|
from unittest.mock import call |
|
|
|
import pytest |
|
|
|
import aux_functions |
|
|
|
|
|
def sum_three_numbers(num1, num2, num3): |
|
return num1 + num2 + num3 |
|
|
|
|
|
def test_mock_interception(mocker): |
|
|
|
aux_functions.add_num(1) |
|
mocked = mocker.patch.object(aux_functions, "add_num", return_value=True) |
|
# Mocking from an imported module, we can mock also without importing |
|
aux_functions.add_num(2) |
|
assert mocked.called_once() |
|
aux_functions.add_num(3) |
|
assert mocked.called_twice() |
|
assert aux_functions.add_num(4) == True |
|
|
|
assert aux_functions.num_list == [1] # Only the first one called the function |
|
assert mocked.has_calls(call(2), call(3), call(4)) |
|
assert mocked.has_calls(call(4), call(3), call(2)) |
|
|
|
assert mocked.call_count == 3 |
|
assert mocked.called_with(3) |
|
assert mocked.called_with(4, 3, 2) |
|
|
|
|
|
def test_mock_interception_multiple_parameters(mocker): |
|
# Mocking from a full route module (actually, current one), no need to import sometimes |
|
mocked = mocker.patch("test_mock_with_interception.sum_three_numbers", return_value=0) |
|
sum_three_numbers(1, 2, 3) |
|
sum_three_numbers(4, 5, 6) |
|
|
|
mocked.assert_has_calls([call(1, 2, 3)]) |
|
mocked.assert_has_calls([call(1, 2, 3), call(4, 5, 6)]) |
|
mocked.assert_has_calls([call(4, 5, 6), call(1, 2, 3)], any_order=True) |
|
with pytest.raises(AssertionError): |
|
mocked.assert_has_calls([call(4, 5, 6), call(1, 2, 3)]) |