尝试修补成员函数会产生错误属性:'模块'对象没有属性'对象'
我想从ut中断言testrunner.test_run
,其中一些深嵌套的函数stript.run_cmd
用字符串参数“ unique cmd” 。我的设置与以下内容相似:
# Module application/engine/prompt.py
class Prompt:
def run_cmd(self, input):
pass
# Module: application/scheduler/runner.py
class Runner:
def __init__(self):
self.prompt = application.engine.prompt.Prompt()
def run(self):
self.prompt.run_cmd("unique cmd")
# Module tests/application/scheduler/runner_test.py
class TestRunner(unittest.TestCase):
...
def test_run(self):
# calls Runner.run
# Objective assert that Prompt.run is called with the argument "unique cmd"
# Current attempt below:
with mock.patch(application.engine.prompt, "run_cmd") as mock_run_cmd:
pass
不幸的是,我尝试模拟stript.run_cmd
失败的尝试使用错误消息
attributeError:'module'对象没有属性'对象'
I would like to assert from a UT, TestRunner.test_run
that some deeply nested function Prompt.run_cmd
is called with the string argument "unique cmd"
. My setup besically resembles the following:
# Module application/engine/prompt.py
class Prompt:
def run_cmd(self, input):
pass
# Module: application/scheduler/runner.py
class Runner:
def __init__(self):
self.prompt = application.engine.prompt.Prompt()
def run(self):
self.prompt.run_cmd("unique cmd")
# Module tests/application/scheduler/runner_test.py
class TestRunner(unittest.TestCase):
...
def test_run(self):
# calls Runner.run
# Objective assert that Prompt.run is called with the argument "unique cmd"
# Current attempt below:
with mock.patch(application.engine.prompt, "run_cmd") as mock_run_cmd:
pass
Unfortunately my attempts to mock the Prompt.run_cmd
fail with the error message
AttributeError: 'module' object has no attribute 'object'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想修补一个具体实例,则可以使用
mock.patch.Object.Object
和wraps
(例如,请参见此问题。您确实必须使用
mock.patch
。wraps
在这里(至少我不知道一种方法)。然后,您可以通过您自己的实现来修补。
If you wanted to patch a concrete instance, you could easily do this using
mock.patch.object
andwraps
(see for example this question.If you want to patch your function for all instances instead, you indeed have to use
mock.patch
. In this case you could only mock the class itself, as mocking the method would not work (because it is used on instances, not classes), so you cannot usewraps
here (at least I don't know a way to do this).What you could do instead is derive your own class from
Prompt
and overwrite the method to collect the calls yourself. You could then patchPrompt
by your own implementation. Here is a simple example: