Python: mock function with parameters (pytest + unittest)

Marco Belo
3 min readMar 3, 2020

To follow this tutorial I expect you to know about pytest, fixtures, decorators and python with context/scope, not in deep but had some contact.

This will be a very short tutorial, I will just point some parts that can be tricky at first.

One example of use: mock boto3 returns and avoid making AWS requests just to run your unit tests. (I use a lot to mock Parameter Store)

The files tree:

files tree

The app/program.py uses function_a() from app/function.py and pass forward the function_a() returned value. Function_a() receives 2 params: name and value, both are expected to be string or integer (but they can be anything that python allow in a string), they will be inserted in the f-string assigned to message than printed and returned on message.

function_a(name, value) at app/function.py

Program.py have only start(), that receive 2 params (name, value) and pass to function_a than return function_a returned value.

start(name, value) at app/program.py

To be able to mock something the program needs to know what would be the new return, in my example I choose to use fixtures that allow me to easily reuse the mock at many tests needed. I’m passing 2 params (param1, param2) but it can be as many as you need, remember to return your inner function.

fixture mock_func at test/conftest.py

ATTENTION: now is the tricky part, the mock_patch is where you can get in some trouble, notice that I’m mocking app.program.function_a and not app.function.function_a as you would imagine being the right way.

The unittest.mock is a powerful feature, it allows you to mock anything in python, there is always some way to mock it.

tests with and without mock at tests/test_program.py

Both tests were passing the last time I ran in my machine, you can see that the test with mock have used that returns dictionary from the fixture to select what to return and the test without mock just returned what we expect from the code.

Feel free to clone and use it: github.com/marcobelo/python_mock_example_1

Contact me: linkedin.com/in/marco-belo/

--

--