The on_commit function was added in Django 1.9 to be able to initiate an action (for example, a Celery task) after the current transaction has completed.
They mention later in the documents that TransactionTestCase should be used to test functions that rely on this function. However, unlike TestCase (which uses transactions and rolls them back), TransactionTestCase clears the entire database after each test.
Unfortunately, I have a data migration that preloads some useful data into the database, which means that subsequent tests no longer work after the first test clears the database.
In the end, I resorted to a dirty trick, mocking on_commit :
with mock.patch.object(django.db.transaction, 'on_commit', lambda t: t()): test_something()
Is there a better way?
source share