如何用monkeypatch替换常量

How to replace constant by monkeypatch

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

LIMIT = 1000
from constants import LIMIT


class MyClass:
    def get_limit(self):
        return LIMIT
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 并确保将 string "LIMIT"name 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