首页 > 解决方案 > 属性模拟不返回 Mock.return_value 集

问题描述

在测试文件中,我模拟了这样定义property的类的属性:MyClasspath.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在第三个模块中定义的函数,该函数具有类型的参数MyClassprs调用property其参数的属性。

当我运行上面的测试文件时,回溯会到达prs调用位置MyClass.property并尝试实际执行下载。我原以为MyClass.property会回来"expected_value"。我怎样才能做到这一点?

标签: python-3.xrestmockingpython-unittest

解决方案


推荐阅读