Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: restore PatchInstanceMethod #20

Merged
merged 4 commits into from
May 8, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
restore PatchInstanceMethod
samanhappy committed May 7, 2024
commit 7b5a6dbcd6a8c283340c07d0bcdac116bb172d42
14 changes: 14 additions & 0 deletions monkey.go
Original file line number Diff line number Diff line change
@@ -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{}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

此处可能有问题。monkey 默认开启协程隔离,原来的 PatchInstanceMethod 函数是全局 patch 吧?需要指定 global 参数。

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

使用 global: true 测试会失败,我不太熟悉之前的代码,这个地方是不是不需要设置?

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

// See reflect.Value
type value struct {
_ uintptr