How to patch a module's internal functions with mock?

后端 未结 4 1171
情书的邮戳
情书的邮戳 2021-02-01 05:15

By \"internal function\", I mean a function that is called from within the same module it is defined in.

I am using the mock library, specifically the patch decorators,

相关标签:
4条回答
  • 2021-02-01 05:40

    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.

    0 讨论(0)
  • 2021-02-01 05:40

    I'm pretty sure your problem is that you are importing 'mymodule' inside your test functions, and therefore the patch decorator has no chance of actually patching. Do the import at the top of the module, like any other import.

    0 讨论(0)
  • 2021-02-01 05:42

    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 patch
    import unittest
    from mock import patch
    import json
    import logging
    ...
    
    
    patcher = patch('some.module.path.function', lambda x: x)
    patcher.start()
    
    import some.module.path
    
    class ViewGetTests(unittest.TestCase):
    
      @classmethod
      def tearDownClass(cls):
          patcher.stop()
    
    0 讨论(0)
  • 2021-02-01 05:58

    another option is to explicitly call patch on the function:

    mock.patch('function_name')
    

    and to support both running directly or from py.test etc:

    mock.patch(__name__ + '.' + 'function_name')
    
    0 讨论(0)
提交回复
热议问题