Suppose we have a system of modules that exists only at the production stage. At the time of testing, these modules do not exist. But still, I would like to write tests for code that uses these modules. Suppose also that I know how to mock all the necessary objects from these modules. The question is: how is it convenient for me to add module stubs to the current hierarchy?
Here is a small example. The functionality I want to test is placed in a file called actual.py :
actual.py: def coolfunc(): from level1.level2.level3_1 import thing1 from level1.level2.level3_2 import thing2 do_something(thing1) do_something_else(thing2)
In my test suite, I already have everything I need: I have thing1_mock and thing2_mock . I also have a testing function. I need to add level1.level2... to the current module system. Like this:
tests.py import sys import actual class SomeTestCase(TestCase): thing1_mock = mock1() thing2_mock = mock2() def setUp(self): sys.modules['level1'] = what should I do here? @patch('level1.level2.level3_1.thing1', thing1_mock) @patch('level1.level2.level3_1.thing1', thing2_mock) def test_some_case(self): actual.coolfunc()
I know that I can replace sys.modules['level1'] with an object containing another object, and so on. But for me it seems like a lot of code. I suppose it should be much simpler and prettier. I just can't find him.
ikostia
source share