Last active
March 28, 2019 14:04
-
-
Save hectorcanto/ecc42cf5d5ad4ea309f51d21337d537c to your computer and use it in GitHub Desktop.
[Mock examples] Two examples that show how mock intercepts a call and does not let the mocked element execute its code. #python #pytest #mock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
num_list = [] | |
def add_num(num): | |
num_list.append(num) | |
return True |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment