Skip to content

Conversation

@lobsterkatie
Copy link
Member

The Python built-in MagicMock class has assert_called_once_with, assert_any_call, assert_has_calls, etc, but none of those is helpful if what you really want is assert_called_twice_with or assert_called_exactly_three_times_with. This therefore adds a new testing helper, count_matching_calls, which works exactly the same way as the built-in ones, except that you also have to pass it the mock. So, for example, the following sets of assertions are equivalent (yes, I know some of the mock methods don't actually exist - that's the point):

some_mock.assert_called_once_with("dogs", "are", "great", adopt_dont_shop=True)
assert count_matching_calls(some_mock, "dogs", "are", "great", adopt_dont_shop=True) == 1

some_mock.assert_called_twice_with("dogs", "are", "great", adopt_dont_shop=True)
assert count_matching_calls(some_mock, "dogs", "are", "great", adopt_dont_shop=True) == 2

some_mock.assert_called_exactly_three_times_with("dogs", "are", "great", adopt_dont_shop=True)
assert count_matching_calls(some_mock, "dogs", "are", "great", adopt_dont_shop=True) == 3

This will be helpful for testing an upcoming PR involving caching, where for example it will be nice to be able to test that cache.get is called twice while cache.set is only called once (or not at all, if certain criteria aren't met).

@github-actions github-actions bot added the Scope: Backend Automatically applied to PRs that change backend components label Nov 24, 2025
@lobsterkatie lobsterkatie marked this pull request as ready for review November 25, 2025 00:10
Copy link
Contributor

@cvxluo cvxluo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice change

@lobsterkatie lobsterkatie merged commit deb12c6 into master Nov 25, 2025
66 checks passed
@lobsterkatie lobsterkatie deleted the kmclb-add-count-mock-calls-helper branch November 25, 2025 00:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Scope: Backend Automatically applied to PRs that change backend components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants