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

后端 未结 4 1179
情书的邮戳
情书的邮戳 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: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()
    

提交回复
热议问题