Python 3.x 属性模拟不返回Mock.return\u值集
在测试文件中,我模拟类Python 3.x 属性模拟不返回Mock.return\u值集,python-3.x,rest,mocking,python-unittest,Python 3.x,Rest,Mocking,Python Unittest,在测试文件中,我模拟类MyClass的属性property,该类在path.to.my.module中定义,如下所示: # test file import unittest from app.module import run_service class TestMyService(unittest.TestCase): def setUp(self): self.service_url = ... self.query = ... self.head
MyClass
的属性property
,该类在path.to.my.module
中定义,如下所示:
# test file
import unittest
from app.module import run_service
class TestMyService(unittest.TestCase):
def setUp(self):
self.service_url = ...
self.query = ...
self.headers = ....
def test_my_service(self):
proc = Process(target=run_service)
proc.start()
with patch("path.to.my.module.MyClass.property", new_callable=PropertyMock) as attr:
attr.return_value = "expected_value"
res = requests.get(self.service_url, self.query, headers=self.headers)
self.assertEqual(res.status_code, 200)
proc.join()
在实际执行中,property
从外部服务X下载一些东西。服务的GET导入MyClass
,实例化它,并调用第三个模块中定义的函数prs
,该模块的参数类型为MyClass
prs
调用其参数的属性property
当我运行上面的测试文件时,回溯会到达
prs
调用MyClass.property
并尝试实际执行下载。我希望MyClass.property
返回“expected\u value”
。如何实现这一点?我猜您模拟了错误的模块-这取决于MyClass
在使用它的地方是如何导入的。谢谢你的回答。我在所有脚本中都使用了“from module import smthg”。在这种情况下,您必须使用_module.MyClass.property将路径_修补到_。