Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace constant by monkeypatch

I want to mock(override) constant in my test.

  • constants.py
LIMIT = 1000
  • my_class.py
from constants import LIMIT


class MyClass:
    def get_limit(self):
        return LIMIT
  • tests/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

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?

like image 227
Kohei Sugimura Avatar asked Feb 20 '26 15:02

Kohei Sugimura


1 Answers

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
like image 76
Mark Avatar answered Feb 23 '26 06:02

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!