Skip to content

Commit

Permalink
fix monkey key strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
samanhappy committed Aug 12, 2024
1 parent f5dfdb7 commit 7ddaf89
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions monkey/monkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package monkey

Check warning on line 18 in monkey/monkey.go

View workflow job for this annotation

GitHub Actions / Code Lint

should have a package comment

import (
"fmt"
"reflect"

"github.com/agiledragon/gomonkey/v2"
Expand All @@ -27,7 +28,7 @@ var patchesMap = make(map[string]*gomonkey.Patches)

// Patch replaces a function with another
func Patch(target, replacement interface{}) *gomonkey.Patches {
key := reflect.TypeOf(target).String()
key := fmt.Sprintf("%v", target)
existingPatches, ok := patchesMap[key]
if ok {
existingPatches.Reset()
Expand All @@ -39,18 +40,19 @@ func Patch(target, replacement interface{}) *gomonkey.Patches {

// Unpatch unpatch a patch
func Unpatch(target interface{}) bool {
patches, ok := patchesMap[reflect.TypeOf(target).String()]
key := fmt.Sprintf("%v", target)
patches, ok := patchesMap[key]
if !ok {
return false
}
patches.Reset()
delete(patchesMap, reflect.TypeOf(target).String())
delete(patchesMap, key)
return true
}

// PatchInstanceMethod replaces an instance method methodName for the type target with replacement
func PatchInstanceMethod(target reflect.Type, methodName string, replacement interface{}) *gomonkey.Patches {
key := target.String() + methodName
key := fmt.Sprintf("%v:%v", target, methodName)
existingPatches, ok := patchesMap[key]
if ok {
existingPatches.Reset()
Expand All @@ -62,12 +64,13 @@ func PatchInstanceMethod(target reflect.Type, methodName string, replacement int

// UnpatchInstanceMethod unpatch a patch
func UnpatchInstanceMethod(target reflect.Type, methodName string) bool {
patches, ok := patchesMap[target.String()+methodName]
key := fmt.Sprintf("%v:%v", target, methodName)
patches, ok := patchesMap[key]
if !ok {
return false
}
patches.Reset()
delete(patchesMap, target.String()+methodName)
delete(patchesMap, key)
return true
}

Expand Down

0 comments on commit 7ddaf89

Please sign in to comment.