"Monkey" is a library for monkey-patching functions.
This may be useful to get determined test result with functions that have side effect (like time.Now()
).
Earlier I found library github.com/bouk/monkey with same name and functionality and sometimes used it in tests. But this library was unstable, and currently it's archived. So I decided to create new one with different approach.
Monkey-patching time.Now()
in tests:
package sometest
import (
"testing"
"time"
"github.com/xakep666/monkey"
)
func init() {
monkey.NewPatcher().
Apply(func(patcher *monkey.Patcher) {
monkey.RegisterReplacement(patcher, time.Now, func() time.Time {
return time.Date(1980, 1, 2, 3, 4, 5, 6, time.UTC)
})
}).
MustPatchAndExec()
}
func TestTime(t *testing.T) {
if now := time.Now(); !now.Equal(time.Date(1980, 1, 2, 3, 4, 5, 6, time.UTC)) {
t.Errorf("Time not patched, returned: %s", now)
}
}
More examples can be found here.
To prevent recursive self-(re)start this library adds special environment variable when it starts patched binary.
github.com/bouk/monkey
Unlike mentioned library this performs patching before binary execution. This results in major advantages but has same disadvantages.
Advantages:
unsafe
imported.mprotect
-like system calls. Some systems refused to set writeable and executable flag on pages.Disadvantages:
Here is some points why patch may fail:
//go:noinline
pragma or -gcflags=-l
compiler flag.go test
without -o
go run
go build
with -ldflags=-s