From d6bbea391fd9d0db2d3993aeb77002b080460e9f Mon Sep 17 00:00:00 2001 From: Alberto Bertogli Date: Sat, 13 Jul 2019 14:45:59 +0100 Subject: [PATCH] maillog: Test that we log to the system logger on write errors The maillog package will write to the system logger if it can't write to the mail log. It does this only once to avoid spamming the system logger on misconfigurations. This patch adds a test for this condition. --- internal/maillog/maillog_test.go | 47 ++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/internal/maillog/maillog_test.go b/internal/maillog/maillog_test.go index 2a11603..78d32e1 100644 --- a/internal/maillog/maillog_test.go +++ b/internal/maillog/maillog_test.go @@ -3,10 +3,13 @@ package maillog import ( "bytes" "fmt" + "io" "net" "strings" "testing" "time" + + "blitiri.com.ar/go/log" ) var netAddr = &net.TCPAddr{ @@ -114,3 +117,47 @@ func TestDefault(t *testing.T) { expect(t, buf, "qid from=from all done") buf.Reset() } + +// io.Writer that fails all write operations, for testing. +type failedWriter struct{} + +func (w *failedWriter) Write(p []byte) (int, error) { + return 0, fmt.Errorf("test error") +} + +// nopCloser adds a Close method to an io.Writer, to turn it into a +// io.WriteCloser. This is the equivalent of ioutil.NopCloser but for +// io.Writer. +type nopCloser struct { + io.Writer +} + +func (nopCloser) Close() error { return nil } + +// Test that we complain (only once) when we can't log. +func TestFailedLogger(t *testing.T) { + // Set up a test logger, that will write to a buffer for us to check. + buf := &bytes.Buffer{} + log.Default = log.New(nopCloser{io.Writer(buf)}) + + // Set up a maillog that will use a writer which always fail, to trigger + // the condition. + failedw := &failedWriter{} + l := New(failedw) + + // Log something, which should fail. Then verify that the error message + // appears in the log. + l.printf("123 testing") + s := buf.String() + if !strings.Contains(s, "failed to write to maillog: test error") { + t.Errorf("log did not contain expected message. Log: %#v", s) + } + + // Further attempts should not generate any other errors. + buf.Reset() + l.printf("123 testing") + s = buf.String() + if s != "" { + t.Errorf("expected second attempt to not log, but log had: %#v", s) + } +}