【发布时间】:2021-05-14 02:23:40
【问题描述】:
我想在我的测试中模拟(覆盖)常量。
- constants.py
LIMIT = 1000
- my_class.py
from constants import LIMIT
class MyClass:
def get_limit(self):
return LIMIT
- 测试/test_my_class.py
from my_class import MyClass
class TestMyClass:
def test_get_limit_should_return_value(self, monkeypatch):
monkeypatch.setattr('constants', LIMIT, 10)
c = MyClass()
assert c.get_limit() == 10
这个结果如下。
$ pytest
============================= test session starts ==============================
platform linux -- Python 3.8.0, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: /home/sugimurase/src
collected 1 item
tests/test_my_class.py F [100%]
=================================== FAILURES ===================================
________________ TestMyClass.test_get_limit_should_return_value ________________
self = <test_my_class.TestMyClass object at 0x7f83b54c4940>
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7f83b54c4d00>
def test_get_limit_should_return_value(self, monkeypatch):
> monkeypatch.setattr('constants', LIMIT, 100)
E NameError: name 'LIMIT' is not defined
tests/test_my_class.py:6: NameError
=========================== short test summary info ============================
FAILED tests/test_my_class.py::TestMyClass::test_get_limit_should_return_value
============================== 1 failed in 0.08s ===============================
我将 'constants' 替换为 'my_class.constants'、'MyClass',但得到了同样的错误。 我该怎么做?
【问题讨论】:
-
如果你已经在你的测试中导入了
MyClass,那意味着你LIMIT的导入也在那个时候被执行了,所以monkeypatching它不会有帮助。您应该对方法get_limit()本身进行猴子补丁。 -
我没有完全理解常量在哪里激活。你的建议很有帮助。非常感谢。
标签: python pytest monkeypatching