1

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.

ssloan
  • 2,226
  • 4
  • 26
  • 40
  • 3
    You are replacing the function with your own function, not with a mock, so this is expected. Using `return_value` or `side_effect` should work, though. – MrBean Bremen Oct 05 '22 at 13:44
  • You're right, both of those work. Not sure what I was doing earlier to make them fail! – ssloan Oct 05 '22 at 14:31

0 Answers0