Django's Test Case Classes Differ by How Much Database and Server They Set Up

In progress Django

Django offers four base classes for tests, each adding infrastructure on top of the previous one: no database, a database reset by transaction rollback, a database reset by truncation so real commits can be tested, and a live HTTP server for browser tests. Picking the lightest class that covers the test keeps the suite fast; picking one too light makes tests fail for reasons unrelated to the code.

The Four Classes

Class Database Isolation between tests Use for
SimpleTestCase blocked: queries raise an error nothing to reset pure logic, forms without models, template filters, URL resolution
TestCase yes each test runs in a transaction rolled back at the end (fast) most model, view and form tests
TransactionTestCase yes tables truncated after each test (slower) code that commits, uses transaction.on_commit(), or tests locking and atomic blocks
LiveServerTestCase yes, as TransactionTestCase as TransactionTestCase a real server in a thread for Selenium or Playwright (self.live_server_url)

TestCase also offers setUpTestData(), which creates data once per class and restores it before each test, much faster than creating it in setUp() for every test.

Unit vs Integration in Django Terms

A unit test checks one piece in isolation and runs fast; an integration test checks pieces together and points less precisely at the cause when it fails. SimpleTestCase tests are unit tests; TestCase tests through the test client (self.client.get("/books/")) are integration tests of URL, view, template and ORM together. Most suites want many of the first and enough of the second to cover each view.

References

Review cards

Flashcard What is the main difference between `SimpleTestCase` and `TestCase`?

SimpleTestCase does not allow database queries, while TestCase does, but runs each test in a transaction that is rolled back at the end.

Flashcard Which test case class should be used for testing code that commits or uses `transaction.on_commit()`?

Use TransactionTestCase for code that commits or uses transaction.on_commit(), as it allows real commits and truncates tables after each test.

Quiz Which of the following is true about `LiveServerTestCase`?
  • It runs tests without a database.
  • It provides a live HTTP server for browser tests.
  • It runs each test in a transaction that is rolled back at the end.
  • It is the fastest test case class.

LiveServerTestCase sets up a live HTTP server for browser tests, making it suitable for Selenium or Playwright tests.