How to test Go function containing log.Fatal()
While it's possible to test code that contains log.Fatal, it is not recommended. In particular you cannot test that code in a way that is supported by the -cover
flag on go test
.
Instead it is recommended that you change your code to return an error instead of calling log.Fatal. In a sequential function you can add an additional return value, and in a goroutine you can pass an error on a channel of type chan error
(or some struct type containing a field of type error).
Once that change is made your code will be much easier to read, much easier to test, and it will be more portable (now you can use it in a server program in addition to command line tools).
If you have log.Println
calls I also recommend passing a custom logger as a field on a receiver. That way you can log to the custom logger, which you can set to stderr or stdout for a server, and a noop logger for tests (so you don't get a bunch of unnecessary output in your tests). The log
package supports custom loggers, so there's no need to write your own or import a third party package for this.
If you're using logrus, there's now an option to define your exit function from v1.3.0 introduced in this commit. So your test may look something like:
func Test_X(t *testing.T) {
cases := []struct{
param string
expectFatal bool
}{
{
param: "valid",
expectFatal: false,
},
{
param: "invalid",
expectFatal: true,
},
}
defer func() { log.StandardLogger().ExitFunc = nil }()
var fatal bool
log.StandardLogger().ExitFunc = func(int){ fatal = true }
for _, c := range cases {
fatal = false
X(c.param)
assert.Equal(t, c.expectFatal, fatal)
}
}
This is similar to "How to test os.Exit()
scenarios in Go": you need to implement your own logger, which by default redirect to log.xxx()
, but gives you the opportunity, when testing, to replace a function like log.Fatalf()
with your own (which does not call os.Exit(1)
)
I did the same for testing os.Exit()
calls in exit/exit.go
:
exiter = New(func(int) {})
exiter.Exit(3)
So(exiter.Status(), ShouldEqual, 3)
(here, my "exit" function is an empty one which does nothing)