Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mock testing with nested function changes

I am adding testing to a pipeline project, code is already written and in production so it cannot be changed to accommodate the tests.

In simplest terms, if I have a function like so:

def other_foo():
    return 1

def foo():
    res = other_foo()
    return res

In practicality, the other_foo call will return a variety of responses, but for testing, I want to create a fixed response to test foo.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So in my test I want to create a fixed response to other_foo of 2. and my test evaluation to be something like:

def test_foo():
    # some mocking or nesting handle here for other_foo
    res = foo()
    assert res == 2

>Solution :

Use the patch decorator from unitest.mock and patch your module local variable.

from your.module import foo
from unitest.mock import patch

@patch('your.module.other_foo')
def test_foo(mock_other_foo):
    mock_other_foo.return_value = 3
    assert foo() == 3
    mock_other_foo.return_value = 42
    assert foo() == 42

You can find more information here and there.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading