Skip to content

Repository files navigation

DRF Testing — the three test cases and when each one lies to you

CI

A compact, runnable tour of Django REST Framework testing (lecture_api_testing/): the same tiny API tested with APISimpleTestCase, APITestCase and APITransactionTestCase, through both APIRequestFactory and APIClient — so you can see what each layer actually covers.

What's inside

  • APISimpleTestCase — no database access at all; fastest, for pure logic around serializers/views.
  • APITestCase — database inside a per-test transaction that is rolled back. Fast, isolated — and subtly misleading, see below.
  • APITransactionTestCase — real commits, tables truncated after each test. Slower, but honest about transactional behavior.
  • Request factory vs API client — calling the view function directly vs going through the full URL/middleware stack, side by side.

The gotcha worth remembering

transaction.on_commit() callbacks do not run under APITestCase — the wrapping transaction is rolled back, so the commit never happens and your callback silently never fires. The same code under APITransactionTestCase fires the callback. If commit-time side effects (emails, task queues, cache invalidation) are part of what you're testing, APITestCase will green-light code that behaves differently in production.

Run

pip install -r requirements.txt
python manage.py migrate
python manage.py test

About

DRF testing by example: APITestCase vs APITransactionTestCase, request factory vs client, and the transaction.on_commit gotcha

Topics

Resources

Stars

5 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages