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

单测: 使用xgo替换部分gomonkey进行mock #271

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

xhd2015
Copy link

@xhd2015 xhd2015 commented Apr 3, 2024

在这个PR中,我使用xgo替换了gomonkey。
xgo相对于gomonkey具有如下优点:

  • 不依赖asm, 纯go实现,兼容所有的OS和架构
  • 并发安全,多组用例同时mock,不会相互影响
  • API更加简单,不需要defer patch.Reset()等代码
  • 对于方法,可以直接用c.Method的形式,而不需要通过字符串指定方法名,更加健壮

xgo的项目地址: https://github.com/xhd2015/xgo

使用xgo进行单测的步骤:

  1. 安装
# macOS and Linux (and WSL)
curl -fsSL https://github.com/xhd2015/xgo/raw/master/install.sh | bash

# windows
powershell -c "irm github.com/xhd2015/xgo/raw/master/install.ps1|iex"
  1. 执行test
    注: 由于我只替换了一部分用例,所以这里只运行受影响的那一部分函数。如果仓库作者觉得可行,我可以将它们全部替换掉
xgo test -run 'TestMongoInput_BatchStart|TestMongoInput_GetBatchTableList|TestMongoInput_TableBatchStart' ./input/mongo

测试结果:

$ xgo test -run 'TestMongoInput_BatchStart|TestMongoInput_GetBatchTableList|TestMongoInput_TableBatchStart' 
 ./input/mongo
ok      github.com/brokercap/Bifrost/input/mongo        0.572s

在这个PR中我只对部分函数进行了替换,主要是为了提升单测的可维护性。如果这个PR被认为可接受的话,我可以将所有剩余的mock全部替换为xgo,方便后面进行维护。

@jc3wish
Copy link
Member

jc3wish commented Apr 4, 2024

私有变量或者方法,有办法 mock吗?
假如需要将 集成测试 以及 单测分开 有简单可行的方案吗?
这个必须 安装 xgo 吗 ?不能使用 go test 命令进行运行?

@xhd2015
Copy link
Author

xhd2015 commented Apr 4, 2024

私有变量或者方法,有办法 mock吗? 假如需要将 集成测试 以及 单测分开 有简单可行的方案吗? 这个必须 安装 xgo 吗 ?不能使用 go test 命令进行运行?

你提到的私有变量这个,我正在实现。这个相对来说很简单。
私有方法已经支持了,MockMethodByName

这个需要安装xgo,但是xgo本身是个简单的代码预处理器。最终还是依赖你系统上的go进行编译。在CI环境中跑单测的话,可以使用curl从github下载,github内网应该是很快的。

我不明白你说的集成测试和单测分开是什么意思。是不是指集成测试完全不做mock,单测完全mock?如果是那样的话,我建议集成测试写在一个单独的integration_test目录下,这方面可以参考go编译器的做法。

@xhd2015
Copy link
Author

xhd2015 commented Apr 4, 2024

另外,上面提到xgo的API更加简单,还体现在mock.Patch可以自动识别要mock的是一个函数还是方法,而gomonkey则需要两个API: ApplyFunc, ApplyMethod,并且后者还无法通过常规的方法引用,必须是字符串的形式,因此如果将来改了方法名,编译器识别不出来报错。

@xhd2015
Copy link
Author

xhd2015 commented Apr 4, 2024

上面提到xgo只是一个源码预处理器,这个可以参考我写的原理分析: https://blog.xhd2015.xyz/posts/xgo-monkey-patching-in-go-using-toolexec/

(目前还没有来得及写中文版,可以先将就看着)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants