How to patch a module's internal functions with mock?
The answer: Clean up your darned imports
@patch('mymodule.TAX_LOCATION', '')
did indeed patch things appropriately, but since our imports at the time were very haphazard -- sometimes we imported mymodule.build_cart
, sometimes we imported project.mymodule.build_cart
-- instances of the "full" import were not patched at all. Mock couldn't be expected to know about the two separate import paths... without being told explicitly, anyway.
We've since standardized all our imports on the longer path, and things behave much more nicely now.
I'd like to add solution other than accepted one. You can also patch the module before it's been imported in any other modules and remove patch at the end of your test case.
#import some modules that don't use module you are going to patchimport unittestfrom mock import patchimport jsonimport logging...patcher = patch('some.module.path.function', lambda x: x)patcher.start()import some.module.pathclass ViewGetTests(unittest.TestCase): @classmethod def tearDownClass(cls): patcher.stop()