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

后端 未结 2 558
梦如初夏
梦如初夏 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:51

    I had a similar problem where the helpers library couldn't be loaded as it needed special hardware. Rather than make radical changes to the code that you want to test, an alternative is to insert a "fake" directory into sys.path as suggested by how to add a package to sys path for testing

    import os, sys
    fake_dir = os.path.join(os.path.dirname(__file__), 'fake')
    assert(os.path.exists(fake_dir))
    sys.path.insert(0, fake_dir)
    import foo
    from unittest.mock import sentinel
    def foo_test():
        foo.helpers.helper_func.return_value = sentinel.foobar
        assert foo.foo_func() == sentinel.foobar
    

    where fake is structured as:

    .
    ├── fake/
    │   └── helpers/
    │       └── __init__.py
    ├── foo.py
    └── helpers/
    

    and __init__.py has

    from unittest.mock import Mock
    helper_func = Mock()
    

提交回复
热议问题