I’ve worked with pytest mocker quite a bit, and the key to using it correctly is ensuring you’re patching the right function with the correct path. Here’s a simple example of patching with return_value to override a function’s output:
Patching with a return_value to Simulate a Fixed Result:
You can make a function return a fixed value, regardless of its input:
import pytest
def sum(a, b):
return a + b
def test_sum1(mocker):
mocker.patch(__name__ + ".sum", return_value=9)
assert sum(2, 3) == 9 # This will pass because 'sum' always returns 9 now
Here, pytest mocker ensures sum() always returns 9, making the test predictable.