From d80ef32eb9e669986ed7838296f6373af56c68f0 Mon Sep 17 00:00:00 2001 From: Tim Schilling Date: Fri, 29 May 2026 14:37:29 -0500 Subject: Fixed #37128 -- Doc'd setUpTestData as test speed up. Revises the AnimalTestCase to better show test data isolation and avoid the opportunity to use setUpTestData. --- docs/topics/testing/overview.txt | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/topics/testing/overview.txt b/docs/topics/testing/overview.txt index 8ec1652ba3..39a6843c02 100644 --- a/docs/topics/testing/overview.txt +++ b/docs/topics/testing/overview.txt @@ -30,16 +30,17 @@ transaction to provide isolation:: class AnimalTestCase(TestCase): def setUp(self): - Animal.objects.create(name="lion", sound="roar") Animal.objects.create(name="cat", sound="meow") def test_animals_can_speak(self): """Animals that can speak are correctly identified""" - lion = Animal.objects.get(name="lion") cat = Animal.objects.get(name="cat") - self.assertEqual(lion.speak(), 'The lion says "roar"') self.assertEqual(cat.speak(), 'The cat says "meow"') + cat.sound = "hiss" + cat.save(update_fields=["sound"]) + self.assertEqual(cat.speak(), 'The cat says "hiss"') + When you :ref:`run your tests `, the default behavior of the test utility is to find all the test case classes (that is, subclasses of :class:`unittest.TestCase`) in any file whose name begins with ``test``, @@ -386,3 +387,12 @@ Avoiding disk access for media files The :class:`~django.core.files.storage.InMemoryStorage` is a convenient way to prevent disk access for media files. All data is kept in memory, then it gets discarded after tests run. + +Using ``setUpTestData`` to create test data +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Moving common test data to :meth:`TestCase.setUpTestData` will reduce the +number of times your tests need to create the data. Using +:meth:`TestCase.setUpTestData` to will create test data +once per class. While :meth:`TestCase.setUp() ` will +create the test data once per test. -- cgit v1.3