Skip to content

Commit

Permalink
feat: restore PatchInstanceMethod (#20)
Browse files Browse the repository at this point in the history
* restore PatchInstanceMethod
* fix global & restore test
* fix test
  • Loading branch information
samanhappy authored May 8, 2024
1 parent eca9cd1 commit d037952
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
14 changes: 14 additions & 0 deletions monkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,20 @@ func Patch(target, replacement interface{}, opts ...Option) *PatchGuard {
return &PatchGuard{t, r, o}
}

// PatchInstanceMethod replaces an instance method methodName for the type target with replacement
// Replacement should expect the receiver (of type target) as the first argument
func PatchInstanceMethod(target reflect.Type, methodName string, replacement interface{}) *PatchGuard {
m, ok := target.MethodByName(methodName)
if !ok {
panic(fmt.Sprintf("unknown method %s", methodName))
}

o := &opt{global: true}
r := reflect.ValueOf(replacement)
patchValue(m.Func, r, o)
return &PatchGuard{m.Func, r, o}
}

// See reflect.Value
type value struct {
_ uintptr
Expand Down
4 changes: 2 additions & 2 deletions monkey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,9 @@ func (f *f) No() bool { return false }
func TestOnInstanceMethod(t *testing.T) {
i := &f{}
assert(t, !i.No())
monkey.Patch((*f).No, func(_ *f) bool { return true })
pg := monkey.PatchInstanceMethod(reflect.TypeOf(i), "No", func(_ *f) bool { return true })
assert(t, i.No())
assert(t, monkey.UnpatchInstanceMethod(reflect.TypeOf(i), "No"))
pg.Unpatch()
assert(t, !i.No())
}

Expand Down

0 comments on commit d037952

Please sign in to comment.