I want to test a Python module, which in turn depends on another Python module, which in turn is badly behaved: it doesn't check for __name__
but always runs some code. This code accesses the file system and hence gets in the way of unit testing.
Here is a simplified version of the problem that just prints something:
test.py:
from unittest import TestCase
import tested
class MyTest(TestCase):
def test_one(self, mocked_dep):
self.assertEqual(1, tested.one())
if __name__ == '__main__':
import unittest
unittest.main()
The code under test, tested.py:
import dep
def one():
return 1
The badly behaved dependency, dep.py:
def do_stuff():
# access file system, open network connection, go to database
print("I got called!")
do_stuff()
When I run this, I see the printed message.
I got called!
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
How can I prevent do_stuff
from running?
I tried mocking it, but by the time my @patch
is evaluated with the import tested
in the beginning of test.py, the module probably has already been loaded and do_stuff
has been called.
I also tried to import tested
after the @patch
inside the test (removing the import tested
on line 3), but that still called do_stuff
and printed its output.
from unittest import TestCase
from mock import patch
class MyTest(TestCase):
@patch("tested.dep.do_stuff") # <-- too late? still prints
def test_one(self, mocked_dep):
import tested # <-- moving the import here did not help either
self.assertEqual(1, tested.one())
I cannot change the behavior of dep.py
as too much other code may depend on it.
How can I prevent do_stuff
from getting called? Or is my only option to mock the functions I don't want do_stuff
to call, in this case print
?