Search code examples
pythonmetaprogramming

Adding module to python at runtime


I have a python script that does this at the begining of the script:

def initialize(module_name):
    return importlib.import_module(module_name) # import module from string

I want to write a test that 'mocks' out the module name like so:

def test():
    # assemble module at run time
    module_obj = {'name': Object, 'another_name': AnotherObject}

    # inject to the "import system"
    inject_mock_module('mymodule', module_obj)

    # assert that the import went correctly
    assert my_module_mock == initialize('mymodule')

How do I do this? First, specifically, how to I create module_obj and how do I define inject_mock_module? This needs to work in both 2.7+ and 3.3+


Solution

  • Use the mock library to mock out the import_module() function. As of Python 3.3, you can import that module as unittest.mock:

    try:
        # Python 3.3+
        from unittest.mock import patch
    except ImportError:
        # External dependency
        from mock import patch
    
    def test():
        module_obj = {'name': Object, 'another_name': AnotherObject}
    
        with patch('importlib.import_module', new=module_obj.get):
            assert initialize('name') is module_obj['name']