Yesterday, I spent some time working on a test that needed to verify the delete method was called a certain number of times for a Django model. In the past we have used the assertNumQueries() method, but it always comes with some flakiness/tediousness (especially if we have to worry about queries made by middleware and/or authentication handlers). When we use this method, we generally run the test once, get the query count and use that as the expected count for future tests. In this case, that number was 33, only 5 of which I cared about for my test. It seemed odd to have an expected query count that wasn’t tied solely to my tests. Thus, I set out to find a way to solely count the number of deletions.
The mock library ended up not working out for me, but I came across a decorator that wraps the method, adding a counter that tracks the number of invocations. The original decorator can be seen at http://code.activestate.com/recipes/577534-counting-decorator/.
Here it is in action.