【问题标题】:How to replace constant by monkeypatch如何用monkeypatch替换常量
【发布时间】: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


【解决方案1】:

您需要在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-06
    • 2021-03-02
    • 2011-07-12
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    相关资源
    最近更新 更多