I read a lot of about unittest.mock
but I am unable to transfer this to my own scenario. So I created a minimal working example here.
I simply replace a function before a test and set it back to the original one at the tests end - without using unittest.mock
. The question is how can I replace the function or modify the return-value using unittest.mock
.
Side-queston is if there is a way to reset the mock/patch implicit at the end of the TestCases. Currently it is done explicite in tearDownClass()
. But sometimes I forget things like that.
#!/usr/bin/env python3
class MyData:
me = None
def __init__(self):
MyData.me = self
self.data = self._get_default_data()
def _get_default_data(self):
return "real default data"
if __name__ == '__main__':
MyData()
print(MyData.me.data)
This is the test
import unittest
from mockplay import MyData
def _test_data(self):
return "simulated test data"
class MyTest_Sim(unittest.TestCase):
@classmethod
def setUpClass(cls):
# remember the original method
cls.org_method = MyData._get_default_data
# mock the method
MyData._get_default_data = _test_data
MyData()
@classmethod
def tearDownClass(cls):
# rest the mock/patch to the origiinal
MyData._get_default_data = cls.org_method
def test_data(self):
self.assertEqual(MyData.me.data,
"simulated test data")
Background information:
The real application reads user-related content (e.g. emails) from a JSON file. On the first start, directly after installation, there is no such JSON file. So the application uses an "in-built" default JSON file.
Each test starts with a "fresh" application - without a JSON file on the filesystem. So it uses _get_default_data()
.
To control which data is present in a test I need to mock/patch/replace this method because the default JSON file a) is not suited for all test cases and b) can change during the development of the application.