修补:用另一个方法调用替换方法调用
我使用 Python 的模拟框架进行测试 - 效果很好!
然而,我无法弄清楚的一件事是如何修补一个函数,以便我用另一个函数替换该调用。
示例:
# module_A.py
def original_func(arg_a,arg_b):
# ...
# module_B.py
import module_A
def func_under_test():
# ...
module_A.original_func(a,b)
# Some code that depends on the behavior of the patched function
# ...
# my test code
def alternative_func(arg_a,arg_b):
# do something essential for the test
def the_test():
# patch the original_func with the alternative_func here
func_under_test()
# assertions
通常断言就足够了,但在这种情况下,我需要在调用时立即启动 alternative_func
而不是 original_func
。
另请注意,alternative_func
需要相同的参数。
我确信这非常简单,也许现在已经很晚了,但我只是看不到......
I use Python's mocking framework for tests - It works great!
However, one thing I wasn't able to figure out, is how to patch a function so that I replace the call with another function.
Example:
# module_A.py
def original_func(arg_a,arg_b):
# ...
# module_B.py
import module_A
def func_under_test():
# ...
module_A.original_func(a,b)
# Some code that depends on the behavior of the patched function
# ...
# my test code
def alternative_func(arg_a,arg_b):
# do something essential for the test
def the_test():
# patch the original_func with the alternative_func here
func_under_test()
# assertions
Usually the assertions are enough, but in this case I need the alternative_func
to kick in instead of the original_func
right when it is called.
Also notice that alternative_func
requires the same arguments.
I'm sure it's super easy, and mayb it is the late hour, but I just don't see it...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在顶部的测试
import module_A
中,然后在设置函数中使用:in your test
import module_A
at the top and then in your setup function use:您需要保存原始函数,以便在完成测试函数后可以恢复:
You need to save the original function so you can restore once you're done with the test function:
您可以重新分配原始值以指向新的
然后调用原始值实际上会调用替代值
You can reassign the original to point to the new
Then calling original will actually call alternative