monkey

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 5, 2026 License: MIT Imports: 6 Imported by: 0

README

monkey

monkey is a library to make patch for unit tests, this repository modified some from gomonkey.
it can patch exported/unexported methods from exported/unexported structure.

Example

Patch function
patch := func(a ...interface{}) (int, error) {
    return fmt.Print("what?!")
}
pg := monkey.Patch(fmt.Println, patch)
defer pg.Unpatch()

// output: what?!
fmt.Println("hello!")
Patch method
with receiver
var r *bytes.Reader
patch := func(*bytes.Reader, b []byte) (int, error) {
    return 0, nil
}
pg := monkey.PatchMethod(r, "Read", patch)
defer pg.Unpatch()

reader := bytes.NewReader([]byte("hello"))
buf := make([]byte, 1024)

// output: 0 <nil>
fmt.Println(reader.Read(buf))
ignore receiver
var r *bytes.Reader
patch := func(b []byte) (int, error) {
    return 0, nil
}
pg := monkey.PatchMethod(r, "Read", patch)
defer pg.Unpatch()

reader := bytes.NewReader([]byte("hello"))
buf := make([]byte, 1024)

// output: 0 <nil>
fmt.Println(reader.Read(buf))

Original

https://github.com/bouk/monkey
https://github.com/agiledragon/gomonkey

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type PatchGuard

type PatchGuard struct {
	// contains filtered or unexported fields
}

PatchGuard contains original and patch data for unpatch.

func Patch

func Patch(target, patch interface{}) *PatchGuard

Patch is used to patch common function.

Example
patch := func(a ...interface{}) (int, error) {
	return fmt.Print("what?!")
}
pg := Patch(fmt.Println, patch)
defer pg.Unpatch()
Output:

what?!

func PatchMethod

func PatchMethod(target interface{}, method string, patch interface{}) *PatchGuard

PatchMethod is used to patch structure methods, it supports unexported methods and unexported structure exported and unexported methods, usually the unexported structure is from interface.

Example
var r *bytes.Reader
patch := func(b []byte) (int, error) {
	return 0, nil
}
pg := PatchMethod(r, "Read", patch)
defer pg.Unpatch()

reader := bytes.NewReader([]byte("hello"))
buf := make([]byte, 1024)
Output:

0 <nil>

func (*PatchGuard) Restore

func (pg *PatchGuard) Restore()

Restore is used to patch the target again.

func (*PatchGuard) Unpatch

func (pg *PatchGuard) Unpatch()

Unpatch is used to recovery the original about target.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL