I would like to mock a certain module in order to test a piece of code that is using the module.
That is to say, I have a module my_module which I'd like to test. my_module imports an external module real_thing and calls real_thing.compute_something():
#my_module
import real_thing
def my_function():
return real_thing.compute_something()
I need to mock real_thing so that in a test it will behave like fake_thing, a module that I've created:
#fake_thing
def compute_something():
return fake_value
The test calls my_module.my_function() which calls real_thing.compute_something():
#test_my_module
import my_module
def test_my_function():
assert_something(my_module.my_function())
What should I add to the test code so that my_function() will call fake_thing.compute_something() within the test instead of real_thing.compute_something()?
I was trying to figure out how to do so with Mock, but I haven't.
import fake_thing as real_thingat the top of your test file?my_module.my_function()andmy_moduledoesn't know it was called from a test.my_moduleimportsreal_thingand thereforereal_thing.compute_something()will be executed, no matter what modules are actually imported in the test module.