When writing tests, I often write assertions to test that objects are created or deleted (or not). I wrote a custom assertion to reduce the boilerplate and make the test more readable.
class TestHelpers(TestCase):
@contextmanager
def assert_difference(self, queryset, difference=1, expression="count"):
"""
Test the difference between the return value of a queryset before and after
the yielded block.
Example:
```
with self.assert_difference(User.objects, difference=1):
User.objects.create_user("john", "john@beatles.com", "pwd")
```
"""
func = getattr(queryset, expression)
initial_count = func()
yield
new_count = func()
self.assertEqual(new_count, initial_count + difference)
I’d love to get your feedback if this should be added to the framework.