python - 如何用monkeypatch替换常量

标签 python pytest monkeypatching

我想在测试中模拟(覆盖)常量。

  • 常量.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”,但出现了相同的错误。 我怎样才能做到这一点?

最佳答案

您需要在 my_class 上猴子修补LIMIT。为此,请导入 my_class 并确保传递字符串 "LIMIT"名称 my_class 到猴子补丁(上面有后面的内容)。这对我来说是这样的:

import my_class


class TestMyClass:
    def test_get_limit_should_return_value(self, monkeypatch):
        monkeypatch.setattr(my_class, 'LIMIT', 10)
        c = my_class.MyClass()
        assert c.get_limit() == 10

关于python - 如何用monkeypatch替换常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67528328/

相关文章:

python - Python 字典中有一个嵌套列表

python - pytest 在测试方法中插入 caplog fixture

javascript - 如何检查默认的JS对象是否被修改?

python - 使用 scrapy 抓取图像数据

python - 在 Python 中的 scipy/numpy 中计算 2D 矩阵的 z 分数

python - pytest fixture 没有在类里面被调用

python - 如何覆盖在 pytest 4 中调用原始的 pytest fixture

python - Monkey 在 Python 中修补 C 扩展

ruby - 如何为 Timecop 修补 File 和 CoreExtensions

python - 如何去除日期、小时和秒的 Pandas 日期时间