Last active
October 6, 2017 16:03
-
-
Save clintonb/4539f1350126ac8efe04bfa610dcb716 to your computer and use it in GitHub Desktop.
Example of counting number of invocations for a Django QuerySet method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def counter(fn): | |
""" | |
Adds a call counter to the given function. | |
Source: http://code.activestate.com/recipes/577534-counting-decorator/ | |
""" | |
def _counted(*largs, **kargs): | |
_counted.invocations += 1 | |
fn(*largs, **kargs) | |
_counted.invocations = 0 | |
return _counted | |
class CleanHistoryTests(TestCase): | |
def test_clean_history(self): | |
# Original code is available at https://github.com/edx/ecommerce/blob/12f7f9f/ecommerce/core/management/commands/tests/test_clean_history.py | |
initial_count = 5 | |
OrderFactory.create_batch(initial_count) | |
cutoff_date = now() + datetime.timedelta(days=1) | |
self.assertEqual(Order.history.filter(history_date__lte=cutoff_date).count(), initial_count) | |
QuerySet.delete = counter(QuerySet.delete) | |
call_command('clean_history', '--cutoff_date={}'.format(cutoff_date.strftime('%Y-%m-%d')), batch_size=1) | |
self.assertEqual(QuerySet.delete.invocations, initial_count) | |
self.assertEqual(Order.history.filter(history_date__lte=cutoff_date).count(), 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment