github.com/gbl08ma/monkey@v1.1.0/README.md (about)

     1  # Go monkeypatching :monkey_face: :monkey:
     2  
     3  Actual arbitrary monkeypatching for Go. Yes really.
     4  
     5  Read this blogpost for an explanation on how it works: https://bou.ke/blog/monkey-patching-in-go/
     6  
     7  ## I thought that monkeypatching in Go is impossible?
     8  
     9  It's not possible through regular language constructs, but we can always bend computers to our will! Monkey implements monkeypatching by rewriting the running executable at runtime and inserting a jump to the function you want called instead. **This is as unsafe as it sounds and I don't recommend anyone do it outside of a testing environment.**
    10  
    11  Make sure you read the notes at the bottom of the README if you intend to use this library.
    12  
    13  ## Using monkey
    14  
    15  Monkey's API is very simple and straightfoward. Call `monkey.Patch(<target function>, <replacement function>)` to replace a function. For example:
    16  
    17  ```go
    18  package main
    19  
    20  import (
    21  	"fmt"
    22  	"os"
    23  	"strings"
    24  
    25  	"github.com/gbl08ma/monkey"
    26  )
    27  
    28  func main() {
    29  	monkey.Patch(fmt.Println, func(a ...interface{}) (n int, err error) {
    30  		s := make([]interface{}, len(a))
    31  		for i, v := range a {
    32  			s[i] = strings.Replace(fmt.Sprint(v), "hell", "*bleep*", -1)
    33  		}
    34  		return fmt.Fprintln(os.Stdout, s...)
    35  	})
    36  	fmt.Println("what the hell?") // what the *bleep*?
    37  }
    38  ```
    39  
    40  You can then call `monkey.Unpatch(<target function>)` to unpatch the method again. The replacement function can be any function value, whether it's anonymous, bound or otherwise.
    41  
    42  If you want to patch an instance method you need to use `monkey.PatchInstanceMethod(<type>, <name>, <replacement>)`. You get the type by using `reflect.TypeOf`, and your replacement function simply takes the instance as the first argument. To disable all network connections, you can do as follows for example:
    43  
    44  ```go
    45  package main
    46  
    47  import (
    48  	"fmt"
    49  	"net"
    50  	"net/http"
    51  	"reflect"
    52  
    53  	"github.com/gbl08ma/monkey"
    54  )
    55  
    56  func main() {
    57  	var d *net.Dialer // Has to be a pointer to because `Dial` has a pointer receiver
    58  	monkey.PatchInstanceMethod(reflect.TypeOf(d), "Dial", func(_ *net.Dialer, _, _ string) (net.Conn, error) {
    59  		return nil, fmt.Errorf("no dialing allowed")
    60  	})
    61  	_, err := http.Get("http://google.com")
    62  	fmt.Println(err) // Get http://google.com: no dialing allowed
    63  }
    64  
    65  ```
    66  
    67  Note that patching the method for just one instance is currently not possible, `PatchInstanceMethod` will patch it for all instances. Don't bother trying `monkey.Patch(instance.Method, replacement)`, it won't work. `monkey.UnpatchInstanceMethod(<type>, <name>)` will undo `PatchInstanceMethod`.
    68  
    69  If you want to remove all currently applied monkeypatches simply call `monkey.UnpatchAll`. This could be useful in a test teardown function.
    70  
    71  If you want to call the original function from within the replacement you need to use a `monkey.PatchGuard`. A patchguard allows you to easily remove and restore the patch so you can call the original function. For example:
    72  
    73  ```go
    74  package main
    75  
    76  import (
    77  	"fmt"
    78  	"net/http"
    79  	"reflect"
    80  	"strings"
    81  
    82  	"github.com/gbl08ma/monkey"
    83  )
    84  
    85  func main() {
    86  	var guard *monkey.PatchGuard
    87  	guard = monkey.PatchInstanceMethod(reflect.TypeOf(http.DefaultClient), "Get", func(c *http.Client, url string) (*http.Response, error) {
    88  		guard.Unpatch()
    89  		defer guard.Restore()
    90  
    91  		if !strings.HasPrefix(url, "https://") {
    92  			return nil, fmt.Errorf("only https requests allowed")
    93  		}
    94  
    95  		return c.Get(url)
    96  	})
    97  
    98  	_, err := http.Get("http://google.com")
    99  	fmt.Println(err) // only https requests allowed
   100  	resp, err := http.Get("https://google.com")
   101  	fmt.Println(resp.Status, err) // 200 OK <nil>
   102  }
   103  ```
   104  
   105  ## Notes
   106  
   107  1. Monkey sometimes fails to patch a function if inlining is enabled. Try running your tests with inlining disabled, for example: `go test -gcflags=-l`. The same command line argument can also be used for build.
   108  2. Monkey won't work on some security-oriented operating system that don't allow memory pages to be both write and execute at the same time. With the current approach there's not really a reliable fix for this.
   109  3. Monkey is not threadsafe. Or any kind of safe.
   110  4. I've tested monkey on OSX 10.10.2 and Ubuntu 14.04. It should work on any unix-based x86 or x86-64 system.
   111  
   112  © Bouke van der Bijl