Skip to content
This repository has been archived by the owner on Jun 16, 2023. It is now read-only.

adamchainz/django-capture-on-commit-callbacks

Repository files navigation

django-capture-on-commit-callbacks

image

image

image

pre-commit


Unmaintained: I'm no longer maintaining this package because it’s only useful on Django 3.2. If you have any problems, consider copying the source into your project.


Capture and make assertions on transaction.on_commit() callbacks. This allows you to write your tests with the TestCase, rather than needing the slower TransactionTestCase to actually commit the transactions.

This package was made as a first pass for Django PR #12944, which is a solution for Ticket #30457 “on_commit should be triggered in a TestCase”. The PR has been merged to Django and has been released in version 3.2, so this package can now be considered a backport.

Read more in my blog post The Fast Way to Test Django transaction.on_commit() Callbacks.

Installation

Use pip:

Requirements

Python 3.7 to 3.10 supported.

Django 3.2 to 4.0 supported.

Note: This package is not needed on Django 4.0+ and it will error on usage for such versions.


Are your tests slow? Check out my book Speed Up Your Django Tests which covers loads of ways to write faster, more accurate tests.


API

capture_on_commit_callbacks(*, using="default", execute=False)

Acts as a context manager that captures on_commit callbacks for the given database connection. It returns a list that contains, on exit of the context, the captured callback functions. From this list you can make assertions on the callbacks or call them to invoke their side effects, emulating a commit.

All arguments must be passed as keyword arguments.

using is the alias of the database connection to capture callbacks for.

execute specifies whether to call all the callbacks automatically as the context manager exits, if no exception has been raised.

For example, you can test a commit hook that sends an email like so:

The same test can be written a bit more succinctly with execute=True:

TestCaseMixin

A mixin class to be added to your custom TestCase subclass. It adds one method, captureOnCommitCallbacks() that aliases capture_on_commit_callbacks(), to match the camelCase style of unittest assertions.

You can add to your custom TestCase classes like so:

You could then rewrite the above tests with your custom TestCase class like so:

About

Capture and make assertions on transaction.on_commit() callbacks.

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published

Languages