I want to mock(override) constant in my test.
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
This result is following.
$ 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 ===============================
I replaced 'constants' to 'my_class.constants', 'MyClass', but got same error. How can I do this?
You need to monkey patch LIMIT on my_class. To do this import my_class and make sure you pass the string "LIMIT" and the name my_class to monkey patch (You have that backward above). This passes for me:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With