I'm trying to understand the different ways to patch a constant in Python using mock.patch. My goal is to be able to use a variable defined in my Test class as the patching value for my constant.
I've found this question which explains how to patch a constant: How to patch a constant in python And this question which explains how to use self in patch: using self in python @patch decorator
But from this 2nd link, I cannot get the testTwo way (providing the mock as a function parameter) to work
Here is my simplified use case:
mymodule.py
MY_CONSTANT = 5
def get_constant():
return MY_CONSTANT
test_mymodule.py
import unittest
from unittest.mock import patch
import mymodule
class Test(unittest.TestCase):
#This works
@patch("mymodule.MY_CONSTANT", 3)
def test_get_constant_1(self):
self.assertEqual(mymodule.get_constant(), 3)
#This also works
def test_get_constant_2(self):
with patch("mymodule.MY_CONSTANT", 3):
self.assertEqual(mymodule.get_constant(), 3)
#But this doesn't
@patch("mymodule.MY_CONSTANT")
def test_get_constant_3(self, mock_MY_CONSTANT):
mock_MY_CONSTANT.return_value = 3
self.assertEqual(mymodule.get_constant(), 3)
#AssertionError: <MagicMock name='MY_CONSTANT' id='64980808'> != 3
My guess is I shoudln't use return_value, because mock_MY_CONSTANT is not a function. So what attribute am I supposed to use to replace the value returned when the constant is called ?
__eq__()
method fromtest_get_constant_3
. It passes a simple assertEqual test, but when i try to test a function that uses the mocked-constant, the constant appears asMagicMock name='MY_CONSTANT' id='140708674985744'
, rather than the mocked value... Any tips/updates on mocking constants? – Lewis