1

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+

1
  • 1
    Are you using Python 2 or 3? Commented Oct 5, 2013 at 18:19

1 Answer 1

3

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']
Sign up to request clarification or add additional context in comments.

2 Comments

Readers, please note that the second argument to patch() used here is "new", not the more usual "return_value".
@Manur: return_value is not a positional argument in mock.patch(). I've made it more explicit by using new as a keyword argument now, but it would be impossible to pass in return_value as a positional argument anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.