From e1e4249e904232e1a3e2f7f22515ec89c67cb02c Mon Sep 17 00:00:00 2001 From: "R.B. Boyer" Date: Fri, 1 Feb 2019 09:21:54 -0600 Subject: [PATCH] testutil: redirect some test agent logs to testing.T.Logf (#5304) When tests fail, only the logs for the failing run are dumped to the console which helps in diagnosis. This is easily added to other test scenarios as they come up. --- agent/consul/server_test.go | 1 + testutil/testlog.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 testutil/testlog.go diff --git a/agent/consul/server_test.go b/agent/consul/server_test.go index de53962707..d89db26193 100644 --- a/agent/consul/server_test.go +++ b/agent/consul/server_test.go @@ -43,6 +43,7 @@ func testServerConfig(t *testing.T) (string, *Config) { config.Bootstrap = true config.Datacenter = "dc1" config.DataDir = dir + config.LogOutput = testutil.TestWriter(t) // bind the rpc server to a random port. config.RPCAdvertise will be // set to the listen address unless it was set in the configuration. diff --git a/testutil/testlog.go b/testutil/testlog.go new file mode 100644 index 0000000000..de603729b1 --- /dev/null +++ b/testutil/testlog.go @@ -0,0 +1,30 @@ +package testutil + +import ( + "io" + "log" + "strings" + "testing" +) + +func TestLogger(t testing.TB) *log.Logger { + return log.New(&testWriter{t}, "test: ", log.LstdFlags) +} + +func TestLoggerWithName(t testing.TB, name string) *log.Logger { + return log.New(&testWriter{t}, "test["+name+"]: ", log.LstdFlags) +} + +func TestWriter(t testing.TB) io.Writer { + return &testWriter{t} +} + +type testWriter struct { + t testing.TB +} + +func (tw *testWriter) Write(p []byte) (n int, err error) { + tw.t.Helper() + tw.t.Log(strings.TrimSpace(string(p))) + return len(p), nil +}