Commit deb12c6
authored
feat(tests): Add helper to count mock calls (#103941)
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).1 parent 8e631f2 commit deb12c6
File tree
2 files changed
+64
-2
lines changed- src/sentry/testutils/pytest
- tests/sentry/testutils/pytest/mocking
2 files changed
+64
-2
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | 3 | | |
4 | | - | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
5 | 7 | | |
6 | 8 | | |
7 | 9 | | |
| |||
122 | 124 | | |
123 | 125 | | |
124 | 126 | | |
| 127 | + | |
| 128 | + | |
| 129 | + | |
| 130 | + | |
| 131 | + | |
| 132 | + | |
| 133 | + | |
| 134 | + | |
| 135 | + | |
| 136 | + | |
| 137 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
| 3 | + | |
3 | 4 | | |
4 | | - | |
| 5 | + | |
5 | 6 | | |
6 | 7 | | |
7 | 8 | | |
| |||
68 | 69 | | |
69 | 70 | | |
70 | 71 | | |
| 72 | + | |
| 73 | + | |
| 74 | + | |
| 75 | + | |
| 76 | + | |
| 77 | + | |
| 78 | + | |
| 79 | + | |
| 80 | + | |
| 81 | + | |
| 82 | + | |
| 83 | + | |
| 84 | + | |
| 85 | + | |
| 86 | + | |
| 87 | + | |
| 88 | + | |
| 89 | + | |
| 90 | + | |
| 91 | + | |
| 92 | + | |
| 93 | + | |
| 94 | + | |
| 95 | + | |
| 96 | + | |
| 97 | + | |
| 98 | + | |
| 99 | + | |
| 100 | + | |
| 101 | + | |
| 102 | + | |
| 103 | + | |
| 104 | + | |
| 105 | + | |
| 106 | + | |
| 107 | + | |
| 108 | + | |
| 109 | + | |
| 110 | + | |
| 111 | + | |
| 112 | + | |
| 113 | + | |
| 114 | + | |
| 115 | + | |
| 116 | + | |
| 117 | + | |
| 118 | + | |
| 119 | + | |
0 commit comments