Fixed #20392 -- Added TestCase.setUpTestData()

Each TestCase is also now wrapped in a class-wide transaction.
This commit is contained in:
Thomas Chaumeny 2014-10-18 23:01:13 +02:00 committed by Tim Graham
parent dee4d23f7e
commit da9fe5c717
7 changed files with 136 additions and 35 deletions

View file

@ -507,6 +507,10 @@ Tests
* The :func:`~django.test.override_settings` decorator can now affect the
master router in :setting:`DATABASE_ROUTERS`.
* Added the ability to setup test data at the class level using
:meth:`TestCase.setUpTestData() <django.test.TestCase.setUpTestData>`. Using
this technique can speed up the tests as compared to using ``setUp()``.
Validators
^^^^^^^^^^
@ -743,6 +747,14 @@ The new package is available `on Github`_ and on PyPI.
.. _on GitHub: https://github.com/django/django-formtools/
Database connection reloading between tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Django previously closed database connections between each test within a
``TestCase``. This is no longer the case as Django now wraps the whole
``TestCase`` within a transaction. If some of your tests relied on the old
behavior, you should have them inherit from ``TransactionTestCase`` instead.
Miscellaneous
~~~~~~~~~~~~~

View file

@ -691,13 +691,45 @@ additions, including:
* Automatic loading of fixtures.
* Wraps each test in a transaction.
* Wraps the tests within two nested ``atomic`` blocks: one for the whole class
and one for each test.
* Creates a TestClient instance.
* Django-specific assertions for testing for things like redirection and form
errors.
.. classmethod:: TestCase.setUpTestData()
.. versionadded:: 1.8
The class-level ``atomic`` block described above allows the creation of
initial data at the class level, once for the whole ``TestCase``. This
technique allows for faster tests as compared to using ``setUp()``.
For example::
from django.test import TestCase
class MyTests(TestCase):
@classmethod
def setUpTestData(cls):
# Set up data for the whole TestCase
cls.foo = Foo.objects.create(bar="Test")
...
def test1(self):
# Some test using self.foo
...
def test2(self):
# Some other test using self.foo
...
Note that if the tests are run on a database with no transaction support
(for instance, MySQL with the MyISAM engine), ``setUpTestData()`` will be
called before each test, negating the speed benefits.
.. warning::
If you want to test some specific database transaction behavior, you should