agiledragon / gomonkey

gomonkey is a library to make monkey patching in unit tests easy
MIT License
1.92k stars 178 forks source link

内联优化导致apply func失效 #157

Open xiaoHoly opened 5 months ago

xiaoHoly commented 5 months ago

需要用户增加go tool env " -gcflags=all=-l"

社区有计划在go monkey包内部解决这个问题吗

xhd2015 commented 3 months ago

xgo从编译器层面解决了这个问题:https://github.com/xhd2015/xgo

nabice commented 2 months ago

@xhd2015 Is there any article introducing the advantages of xgo over gomonkey?

xhd2015 commented 2 months ago

@xhd2015 Is there any article introducing the advantages of xgo over gomonkey?

@nabice Thanks for replying, there are two articles introducing the xgo:

  1. https://blog.xhd2015.xyz/posts/xgo-monkey-patching-in-go-using-toolexec/
  2. https://blog.xhd2015.xyz/posts/xgo-trace_a-powerful-visualization-tool-in-go/

As a brief comparison, here is a glance:

Overview

xgo gomonkey
Concurrent Safety builtin unsafe
API simpler kind of complex
Compatibility OS and Arch agnostic based on ASM, fails on M1 and M2 often

API Comparison

That's just a brief overview. Here is the API comparasion: gomonkey

import "github.com/agiledragon/gomonkey/v2"

func greet(s string) string {
     return "hello "+s
}

func TestGreet(t *testing.T){
     // patch is global, need to clear when current test ends
     gp:=gomonkey.NewPatches()
     defer gp.Reset()

     gp.ApplyFunc(greet, func(s string)string{
           return "huh "+s
     })
    result := greet("world")
    if result!="huh world"{
      t.Fatalf("result: %s", result)
   }
}

xgo

import "github.com/xhd2015/xgo/runtime/mock"

func greet(s string) string {
     return "hello "+s
}

func TestGreet(t *testing.T){
     // patch is local, automatically cleared when current test ends
     mock.Patch(greet, func(s string)string{
           return "huh "+s
     })
     result := greet("world")
     if result!="huh world"{
       t.Fatalf("result: %s", result)
    }
}

Trace

Besides the mock API, xgo has a builtin tool that can show the test execution trace:

xgo test --strace ./
xgo tool trace TestGreet.json

Would result a visual stack trace that helps debugging the tests easier, example from https://github.com/Shibbaz/GOEventBus/pull/11

image