Monkey fixes function in unit for unit testing

I have the following method in a module that calls another method imported from another module:

def imported_function():
    do_unnecessary_things_for_unittest()

The actual method to be tested imports and uses the above function:

from somewhere import imported_function

def function_to_be_tested():
    imported_function()
    do_something_more()
    return 42

Internal calls and related calculations inside import_function are not important, and they are not what I want to check, so I just want to skip them when checking the actual function_to_be_tested function .

So I tried to defuse a module named somewhere inside the testing method, but no luck.

def test_function_to_be_tested(self):
    import somewhere
    somewhere.__dict__['imported_function'] = lambda : True

The question is, how can I secure the module method during testing so that it is not called during the test phase?

+5
2

, Mock Library

, - :

from somewhere import imported_function

@patch(imported_function)
def test_function_to_be_tested(self, imported_function):
    imported_function.return_value = True
    #Your test

, , .

+13

, :

somewhere.py

def imported_function():
    return False

testme.py

from somewhere import imported_function

def function_to_be_tested():
    return imported_function()

testme.function_to_be_tested() False.


, somewhere testme:

import somewhere
somewhere.__dict__['imported_function'] = lambda : True

import testme
def test_function_to_be_tested():
    print testme.function_to_be_tested()

test_function_to_be_tested()

:

True


testme

import testme

def test_function_to_be_tested():
    print testme.function_to_be_tested()
    import somewhere
    somewhere.__dict__['imported_function'] = lambda : True
    print testme.function_to_be_tested()
    reload(testme)
    print testme.function_to_be_tested()

test_function_to_be_tested()

:

False

True

+8

All Articles