Python: Mock a module without importing it or needing it to exist

后端 未结 2 559
梦如初夏
梦如初夏 2021-02-19 01:28

I am starting to use a python mock library for my testing. I want to mock a module that is imported within the namespace of the module under test without actually importing it o

2条回答
  •  醉话见心
    2021-02-19 01:54

    You're kind of missing the point of what a Mock is. You're supposed to build them when you want an object with a particular interface, regardless of how it's implemented.

    What you're doing is trying to re-implement python's module system, plus it's a pretty horrible abuse of global variables to boot.

    Instead of making foo a module, make a Foo class, and pass in the helpers in the constructor.

    class Foo(object):
        def __init__(self, helpers):
            self.helpers = helpers
    
    # then, instead of import foo:
    foo = Foo(mock_helpers)
    

    Even if the real "helpers" is actually going to be a module, there is no reason you need to be messing with sys.modules and setting it up via import in your tests.

    And if foo has to be a module, that's fine too, but you do it like this:

    # foo.py
    class Foo(object):
        pass # same code as before, plus foo_func
    
    try:
       import whatever
       _singleton = Foo(whatever)
    except ImportError:
       _singleton = Foo(something_else)
    
    def foo_func():
       return _singleton.foo_func()
    

    Large chunks of the standard library work this way. It's pretty much the standard for defining singleton-like modules.

提交回复
热议问题