Search code examples
pythonpython-mock

Mock method that is imported into the module under test


Say I want to test this module:

import osutils

def check_ip6(xml):
  ib_output = osutils.call('iconfig ib0')
  # process and validate ib_output (to be unit tested)
  ...

This method is dependent on the environment, because it makes a System call (which expects a specific network interface), so its not callable on a testmachine.

I want to write a Unit test for that method which checks if the processing of ib_output works as expected. Therefore I want to mock osutils.call and let it just return testdata. What is the preferred way to do that? Do I have to do mocking or (monkey) patching?

Example test:

def test_ib6_check():
    from migration import check_ib6
    # how to mock os_utils.call used by the check_ib6-method?
    assert check_ib6(test_xml) == True

Solution

  • One solution would be to do from osutils import call and then when patching things replace yourmodule.call with something else before calling test_ib6_check.