How to test Django on_commit hook without clearing the database?

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?

+5
source share
2 answers

I have two options:

  • as this section says post_migrate released after the flush, so you can preload some useful data
  • You can subclass TransactionTestCase and implement your _fixture_teardown (you can see that the flash is called there at the very end of the method).

I would probably stick to the first if your migration is not too expensive, and the second if it is.

0
source

Just keep using TestCase and a fake commit, which forces pending actions to run_and_clear_commit_hooks. Check out this article:

https://medium.com/gitux/speed-up-django-transaction-hooks-tests-6de4a558ef96

+2
source

Source: https://habr.com/ru/post/1265002/


All Articles