@joe-elmoufak nailed the basics! But sometimes, you need more flexibility than a fixed return value. That’s where side_effect comes in.
Patching with a side_effect to Change Function Behavior Dynamically:
Instead of returning a fixed value, you can provide a custom function to control behavior:
def test_sum2(mocker):
def crazy_sum(a, b):
return b + b # A different behavior, summing only 'b'
mocker.patch(__name__ + ".sum", side_effect=crazy_sum)
assert sum(2, 3) == 6 # This will pass because the new behavior sums 'b + b'
Now, pytest mocker replaces sum() with crazy_sum(), changing the behavior dynamically. Super useful for simulating complex logic!