I am relatively new to python and exploring mocking in unit tests. I have the following method to test, calc_scores
so I want to mock the response to get_score_json
:
def calc_scores(
score_id: str,
):
score_json = get_score_json(score_id)
#Do some calculations...
return {
"total_score": total_score
}
def get_score_json(score_id):
json_obj = call_to_external_service()
return json_obj
And this test, where I want to supply a mock and check it was called in the right way:
def mock_get_score_json(*args, **kwargs):
return {
"scores": [
{"score_1": 123, "score_2":234},
]
}
class Test_Scores:
def test_calc_scores(self):
with mock.patch(
"path.to.calc_scores",
# return_value = mock_get_score_json(),
# new = mock_get_score_json
# side_effect=mock_get_score_json,
new_callable= lambda: mock_get_score_json
) as x:
result = calc_scores(
score_id = 123
)
print(x)
x.assert_called_once()
The test runs and passes, except for the last line where I try assert_called_once()
. This fails with the following error:
AttributeError: 'function' object has no attribute 'assert_called_once'
Where am I going wrong? The commented out lines in the args to mock.patch
are the options I've tried, but none of them work.