I have a function similar to foo
and I am trying to test it using following code
from unittest.mock import call, patch
def foo():
x = {}
for i in range(3):
x["val"] = i
print(x)
@patch('builtins.print')
def test_foo(print_mock):
foo()
calls = calls = [call({'val': 0}), call({'val': 1}), call({'val': 2})]
print_mock.assert_has_calls(calls)
test_foo()
But it gives the following error
File "/usr/lib/python3.8/unittest/mock.py", line 950, in assert_has_calls
raise AssertionError(
AssertionError: Calls not found.
Expected: [call({'val': 0}), call({'val': 1}), call({'val': 2})]
Actual: [call({'val': 2}), call({'val': 2}), call({'val': 2})]
I think the issue is that it's taking the last value with which the function was called. Would appreciate a fix or some alternate way to test the foo
function
python documentation has some workaround for this issue
I think you achieved this behavior?
1 from unittest.mock import call, patch
2
3 def foo():
4 x = {}
5 for key, value in zip(range(3), range(3)):
6 x[key] = value
7 print(x)
8
9 @patch("builtins.print")
10 def test_foo(print_mock):
11 foo()
12 calls = [call({0: 0, 1: 1, 2: 2})]
13 print_mock.assert_has_calls(calls)
14
15 test_foo()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.