python - Mock function called on import -
i have module need test calls function on import cannot call function various reasons. mocking function mocking calls import.
for example testing mod1.py looks this:
import os def bar(): return 'foo' def dont_call(): os.listdir("c:\\tmp") dont_call()
and test looks this:
import mock @mock.patch("mod1.dont_call") def test_mod1(mock_dont_call): import mod1 assert mod1.bar()=='foo' if __name__=="__main__": test_mod1()
the problem os.listdir called.
i cannot change mod1 can do?
i using python2.7.
to put in context testing module opens database connection on import not agree can see reasoning behind it. unfortunately cannot access database on qa machine.
if want code 'not' executed on import put them inside following condition:
in mod1.py, following:
if __name__=="__main__": dont_call()
this because, default when import python module, code in gets executed. adding above condition, explicitly stating dont_call() called when file run script , not when imported in other modules.
Comments
Post a Comment