Zaptest ⚡👩🔧
Test helpers to use a github.com/uber-go/zap logger in unit tests.
Package zaptest
implements test helpers that facilitate using a zap.Logger
in standard go unit tests.
This package is useful when running unit tests with components that use the
https://github.com/uber-go/zap logging framework. In unit tests we usually want
to suppress any logging output as long as the tests are not failing or they are
started in a verbose mode.
Installation
$ go get github.com/fgrosse/zaptest
Usage with standard unit tests
You can use zaptest
in standard unit tests. All log output will be sent via
the testing.T
so it will only be shown if the test fails or if the -v
flag
was set.
Note that you can also use zaptest
in benchmarks because testing.B
also
implements the necessary logger interface.
func TestLogger(t *testing.T) {
l := zaptest.Logger(t)
l.Debug("This is a debug message, debug messages will be logged as well")
l.Info("Logs will not be shown during normal test execution")
l.Warn("You can see all log messages of a successful run by passing the -v flag")
l.Error("Additionally the entire log output for a specific unit test will be visible when a test fails")
}
Usage with ginkgo
Package zaptest
is also compatible with the https://github.com/onsi/ginkgo BDD
testing framework. As with the standard unit tests, any log output for a
specific test will only be printed if that test fails or if the test is running
in verbose mode. With ginkgo use ginkgo -v
to enable verbose output (go test -v
does not seem to work).
type TestedType struct {
log *zap.Logger
}
func (tt *TestedType) DoStuff() error {
tt.log.Debug("Doing stuff")
return nil
}
func TestLoggerWriter(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Ginkgo Example Suite")
}
var _ = Describe("TestedType", func() {
It("should do stuff", func() {
tt := &TestedType{log: zaptest.LoggerWriter(GinkgoWriter)}
Expect(tt.DoStuff()).To(Succeed())
})
})
Usage as library
You can also use zaptest
as library since it does not import the testing
package.