Mock an entire module in python

前端 未结 2 1664
庸人自扰
庸人自扰 2020-12-19 01:59

I have an application that imports a module from PyPI. I want to write unittests for that application\'s source code, but I do not want to use the module from PyPI in those

2条回答
  •  -上瘾入骨i
    2020-12-19 02:30

    If you want to dig into the Python import system, I highly recommend David Beazley's talk.

    As for your specific question, here is an example that tests a module when its dependency is missing.

    bar.py - the module you want to test when my_bogus_module is missing

    from my_bogus_module import foo
    
    def bar(x):
        return foo(x) + 1
    

    mock_bogus.py - a file in with your tests that will load a mock module

    from mock import Mock
    import sys
    import types
    
    module_name = 'my_bogus_module'
    bogus_module = types.ModuleType(module_name)
    sys.modules[module_name] = bogus_module
    bogus_module.foo = Mock(name=module_name+'.foo')
    

    test_bar.py - tests bar.py when my_bogus_module is not available

    import unittest
    
    from mock_bogus import bogus_module  # must import before bar module
    from bar import bar
    
    class TestBar(unittest.TestCase):
        def test_bar(self):
            bogus_module.foo.return_value = 99
            x = bar(42)
    
            self.assertEqual(100, x)
    

    You should probably make that a little safer by checking that my_bogus_module isn't actually available when you run your test. You could also look at the pydoc.locate() method that will try to import something, and return None if it fails. It seems to be a public method, but it isn't really documented.

提交回复
热议问题