0
0
PyTesttesting~5 mins

Mock return values and side effects in PyTest

Choose your learning style9 modes available
Introduction

We use mock return values and side effects to control what a fake function gives back during tests. This helps us test parts of code without running everything for real.

When a function calls an external service like a website or database and you want to test without using the real service.
When you want to check how your code behaves if a function returns different results.
When you want to simulate errors or special cases from a function to see how your code handles them.
When the real function is slow or changes data and you want fast, safe tests.
When you want to test only one part of your code and ignore others.
Syntax
PyTest
from unittest.mock import Mock

mock_function = Mock()
mock_function.return_value = value

# or for side effects
mock_function.side_effect = function_or_exception_or_list

return_value sets what the mock gives back when called.

side_effect can be a function to run, an error to raise, or a list of values/errors for each call.

Examples
This mock always returns 10 when called.
PyTest
mock = Mock()
mock.return_value = 10
print(mock())  # prints 10
The mock runs the side effect function and returns its result.
PyTest
def side_effect_func():
    return 'hello'

mock = Mock()
mock.side_effect = side_effect_func
print(mock())  # prints 'hello'
The mock returns different values on each call from the list.
PyTest
mock = Mock()
mock.side_effect = [1, 2, 3]
print(mock())  # prints 1
print(mock())  # prints 2
print(mock())  # prints 3
The mock raises an exception when called.
PyTest
mock = Mock()
mock.side_effect = Exception('Error!')
try:
    mock()
except Exception as e:
    print(e)  # prints 'Error!'
Sample Program

This example shows a real function and a mock version. The mock first returns a set value, then raises an error using side_effect.

PyTest
from unittest.mock import Mock

def greet():
    return 'Real Greeting'

mock_greet = Mock()
mock_greet.return_value = 'Mocked Greeting'

print(greet())        # Calls real function
print(mock_greet())   # Calls mock with return_value

# Using side_effect to simulate error
mock_greet.side_effect = Exception('No greeting available')
try:
    print(mock_greet())
except Exception as e:
    print(e)
OutputSuccess
Important Notes

Use mocks to isolate the part of code you want to test.

Remember to reset mocks if you reuse them in multiple tests.

Side effects can simulate complex behaviors like errors or changing return values.

Summary

Mocks let you control what functions return during tests.

Use return_value for simple fixed returns.

Use side_effect to simulate errors or dynamic behavior.