Python unittest – assert called with is not working

Question:

i do a gitlab api call to a put_request and for my test I want to mock this call and assert if this call was called with the specific input.

The problem is I do two put requests in my question with different input. This causes problems in my test.

Code:

def set_project_settings(project_id: int) -> None:

    gitlabapi.put_request(("projects"), project_id, {"merge_pipelines_enabled": "true"})
    gitlabapi.put_request(("projects"), project_id, {"merge_trains_enabled": "true"})

Test:

    @patch('python_check_gitlab_module.GitlabApi.put_request')
    def test_set_merged_results_pipeline_settings(self, api_mock)-> None:

        project_id = 100
        uut.set_project_settings(project_id)
        api_mock.assert_called_with(
            ("projects"), project_id, {"merge_pipelines_enabled": "true"})
        api_mock.assert_called_with(
            ("projects"), project_id, {"merge_trains_enabled": "true"})

Error:

AssertionError: expected call not found.

FYI: if i do only one put_request in my set_project_settings method and test with
assert_called_once_with then it works.

Asked By: Shalomi90

||

Answers:

From the the docs, assert_called_with only checks the last call. You probably want assert_any_call or similar:

@patch('python_check_gitlab_module.GitlabApi.put_request')
def test_set_merged_results_pipeline_settings(self, api_mock)-> None:

    project_id = 100
    uut.set_project_settings(project_id)
    api_mock.assert_any_call(
        ("projects"), project_id, {"merge_pipelines_enabled": "true"})
    api_mock.assert_any_call(
        ("projects"), project_id, {"merge_trains_enabled": "true"})

Again, the docs are your friend!

Answered By: PirateNinjas