xakep666 / monkey

Library for monkey-patching functions in Go
MIT License
24 stars 0 forks source link
go monkey-patching

Monkey

Go Reference License: MIT Go Test

"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()).

Why does this library exist?

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.

Usage

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.

How does it work

To prevent recursive self-(re)start this library adds special environment variable when it starts patched binary.

Comparison with github.com/bouk/monkey

Unlike mentioned library this performs patching before binary execution. This results in major advantages but has same disadvantages.

Advantages:

Disadvantages:

Here is some points why patch may fail: