3 ===========================
4 Testing Django applications
5 ===========================
7 .. module:: django.test
8 :synopsis: Testing tools for Django applications.
10 Automated testing is an extremely useful bug-killing tool for the modern
11 Web developer. You can use a collection of tests -- a **test suite** -- to
12 solve, or avoid, a number of problems:
14 * When you're writing new code, you can use tests to validate your code
17 * When you're refactoring or modifying old code, you can use tests to
18 ensure your changes haven't affected your application's behavior
21 Testing a Web application is a complex task, because a Web application is made
22 of several layers of logic -- from HTTP-level request handling, to form
23 validation and processing, to template rendering. With Django's test-execution
24 framework and assorted utilities, you can simulate requests, insert test data,
25 inspect your application's output and generally verify your code is doing what
28 The best part is, it's really easy.
30 This document is split into two primary sections. First, we explain how to
31 write tests with Django. Then, we explain how to run them.
36 There are two primary ways to write tests with Django, corresponding to the
37 two test frameworks that ship in the Python standard library. The two
40 * **Doctests** -- tests that are embedded in your functions' docstrings and
41 are written in a way that emulates a session of the Python interactive
42 interpreter. For example::
44 def my_func(a_list, idx):
46 >>> a = ['larry', 'curly', 'moe']
54 * **Unit tests** -- tests that are expressed as methods on a Python class
55 that subclasses ``unittest.TestCase``. For example::
59 class MyFuncTestCase(unittest.TestCase):
61 a = ['larry', 'curly', 'moe']
62 self.assertEquals(my_func(a, 0), 'larry')
63 self.assertEquals(my_func(a, 1), 'curly')
65 You can choose the test framework you like, depending on which syntax you
66 prefer, or you can mix and match, using one framework for some of your code and
67 the other framework for other code. You can also use any *other* Python test
68 frameworks, as we'll explain in a bit.
73 Doctests use Python's standard doctest_ module, which searches your docstrings
74 for statements that resemble a session of the Python interactive interpreter.
75 A full explanation of how doctest works is out of the scope of this document;
76 read Python's official documentation for the details.
78 .. admonition:: What's a **docstring**?
80 A good explanation of docstrings (and some guidelines for using them
81 effectively) can be found in :pep:`257`:
83 A docstring is a string literal that occurs as the first statement in
84 a module, function, class, or method definition. Such a docstring
85 becomes the ``__doc__`` special attribute of that object.
87 For example, this function has a docstring that describes what it does::
90 "Return the result of adding two to the provided number."
93 Because tests often make great documentation, putting tests directly in
94 your docstrings is an effective way to document *and* test your code.
96 For a given Django application, the test runner looks for doctests in two
99 * The ``models.py`` file. You can define module-level doctests and/or a
100 doctest for individual models. It's common practice to put
101 application-level doctests in the module docstring and model-level
102 doctests in the model docstrings.
104 * A file called ``tests.py`` in the application directory -- i.e., the
105 directory that holds ``models.py``. This file is a hook for any and all
106 doctests you want to write that aren't necessarily related to models.
108 Here is an example model doctest::
112 from django.db import models
114 class Animal(models.Model):
116 An animal that knows how to make noise
118 # Create some animals
119 >>> lion = Animal.objects.create(name="lion", sound="roar")
120 >>> cat = Animal.objects.create(name="cat", sound="meow")
124 'The lion says "roar"'
126 'The cat says "meow"'
128 name = models.CharField(max_length=20)
129 sound = models.CharField(max_length=20)
132 return 'The %s says "%s"' % (self.name, self.sound)
134 When you :ref:`run your tests <running-tests>`, the test runner will find this
135 docstring, notice that portions of it look like an interactive Python session,
136 and execute those lines while checking that the results match.
138 In the case of model tests, note that the test runner takes care of creating
139 its own test database. That is, any test that accesses a database -- by
140 creating and saving model instances, for example -- will not affect your
141 production database. However, the database is not refreshed between doctests,
142 so if your doctest requires a certain state you should consider flushing the
143 database or loading a fixture. (See the section on fixtures, below, for more
144 on this.) Note that to use this feature, the database user Django is connecting
145 as must have ``CREATE DATABASE`` rights.
147 For more details about how doctest works, see the `standard library
148 documentation for doctest`_.
150 .. _doctest: http://docs.python.org/library/doctest.html
151 .. _standard library documentation for doctest: doctest_
156 Like doctests, Django's unit tests use a standard library module: unittest_.
157 This module uses a different way of defining tests, taking a class-based
160 As with doctests, for a given Django application, the test runner looks for
161 unit tests in two places:
163 * The ``models.py`` file. The test runner looks for any subclass of
164 ``unittest.TestCase`` in this module.
166 * A file called ``tests.py`` in the application directory -- i.e., the
167 directory that holds ``models.py``. Again, the test runner looks for any
168 subclass of ``unittest.TestCase`` in this module.
170 This example ``unittest.TestCase`` subclass is equivalent to the example given
171 in the doctest section above::
174 from myapp.models import Animal
176 class AnimalTestCase(unittest.TestCase):
178 self.lion = Animal.objects.create(name="lion", sound="roar")
179 self.cat = Animal.objects.create(name="cat", sound="meow")
181 def testSpeaking(self):
182 self.assertEquals(self.lion.speak(), 'The lion says "roar"')
183 self.assertEquals(self.cat.speak(), 'The cat says "meow"')
185 When you :ref:`run your tests <running-tests>`, the default behavior of the
186 test utility is to find all the test cases (that is, subclasses of
187 ``unittest.TestCase``) in ``models.py`` and ``tests.py``, automatically build a
188 test suite out of those test cases, and run that suite.
190 There is a second way to define the test suite for a module: if you define a
191 function called ``suite()`` in either ``models.py`` or ``tests.py``, the
192 Django test runner will use that function to construct the test suite for that
193 module. This follows the `suggested organization`_ for unit tests. See the
194 Python documentation for more details on how to construct a complex test
197 For more details about ``unittest``, see the `standard library unittest
200 .. _unittest: http://docs.python.org/library/unittest.html
201 .. _standard library unittest documentation: unittest_
202 .. _suggested organization: http://docs.python.org/library/unittest.html#organizing-tests
207 Because Django supports both of the standard Python test frameworks, it's up to
208 you and your tastes to decide which one to use. You can even decide to use
211 For developers new to testing, however, this choice can seem confusing. Here,
212 then, are a few key differences to help you decide which approach is right for
215 * If you've been using Python for a while, ``doctest`` will probably feel
216 more "pythonic". It's designed to make writing tests as easy as possible,
217 so it requires no overhead of writing classes or methods. You simply put
218 tests in docstrings. This has the added advantage of serving as
219 documentation (and correct documentation, at that!).
221 If you're just getting started with testing, using doctests will probably
222 get you started faster.
224 * The ``unittest`` framework will probably feel very familiar to developers
225 coming from Java. ``unittest`` is inspired by Java's JUnit, so you'll
226 feel at home with this method if you've used JUnit or any test framework
229 * If you need to write a bunch of tests that share similar code, then
230 you'll appreciate the ``unittest`` framework's organization around
231 classes and methods. This makes it easy to abstract common tasks into
232 common methods. The framework also supports explicit setup and/or cleanup
233 routines, which give you a high level of control over the environment
234 in which your test cases are run.
236 Again, remember that you can use both systems side-by-side (even in the same
237 app). In the end, most projects will eventually end up using both. Each shines
238 in different circumstances.
245 Once you've written tests, run them using the :djadmin:`test` subcommand of
246 your project's ``manage.py`` utility::
250 By default, this will run every test in every application in
251 :setting:`INSTALLED_APPS`. If you only want to run tests for a particular
252 application, add the application name to the command line. For example, if your
253 :setting:`INSTALLED_APPS` contains ``'myproject.polls'`` and
254 ``'myproject.animals'``, you can run the ``myproject.animals`` unit tests alone
257 $ ./manage.py test animals
259 Note that we used ``animals``, not ``myproject.animals``.
261 .. versionadded:: 1.0
262 You can now choose which test to run.
264 You can be even *more* specific by naming an individual test case. To
265 run a single test case in an application (for example, the
266 ``AnimalTestCase`` described in the "Writing unit tests" section), add
267 the name of the test case to the label on the command line::
269 $ ./manage.py test animals.AnimalTestCase
271 And it gets even more granular than that! To run a *single* test
272 method inside a test case, add the name of the test method to the
275 $ ./manage.py test animals.AnimalTestCase.testFluffyAnimals
277 .. versionadded:: 1.2
278 The ability to select individual doctests was added.
280 You can use the same rules if you're using doctests. Django will use the
281 test label as a path to the test method or class that you want to run.
282 If your ``models.py`` or ``tests.py`` has a function with a doctest, or
283 class with a class-level doctest, you can invoke that test by appending the
284 name of the test method or class to the label::
286 $ ./manage.py test animals.classify
288 If you want to run the doctest for a specific method in a class, add the
289 name of the method to the label::
291 $ ./manage.py test animals.Classifier.run
293 If you're using a ``__test__`` dictionary to specify doctests for a
294 module, Django will use the label as a key in the ``__test__`` dictionary
295 for defined in ``models.py`` and ``tests.py``.
297 .. versionadded:: 1.2
298 You can now trigger a graceful exit from a test run by pressing ``Ctrl-C``.
300 If you press ``Ctrl-C`` while the tests are running, the test runner will
301 wait for the currently running test to complete and then exit gracefully.
302 During a graceful exit the test runner will output details of any test
303 failures, report on how many tests were run and how many errors and failures
304 were encountered, and destroy any test databases as usual. Thus pressing
305 ``Ctrl-C`` can be very useful if you forget to pass the :djadminopt:`--failfast`
306 option, notice that some tests are unexpectedly failing, and want to get details
307 on the failures without waiting for the full test run to complete.
309 If you do not want to wait for the currently running test to finish, you
310 can press ``Ctrl-C`` a second time and the test run will halt immediately,
311 but not gracefully. No details of the tests run before the interruption will
312 be reported, and any test databases created by the run will not be destroyed.
317 Tests that require a database (namely, model tests) will not use your "real"
318 (production) database. Separate, blank databases are created for the tests.
320 Regardless of whether the tests pass or fail, the test databases are destroyed
321 when all the tests have been executed.
323 By default the test databases get their names by prepending ``test_``
324 to the value of the :setting:`NAME` settings for the databases
325 defined in :setting:`DATABASES`. When using the SQLite database engine
326 the tests will by default use an in-memory database (i.e., the
327 database will be created in memory, bypassing the filesystem
328 entirely!). If you want to use a different database name, specify
329 :setting:`TEST_NAME` in the dictionary for any given database in
330 :setting:`DATABASES`.
332 Aside from using a separate database, the test runner will otherwise
333 use all of the same database settings you have in your settings file:
334 :setting:`ENGINE`, :setting:`USER`, :setting:`HOST`, etc. The test
335 database is created by the user specified by ``USER``, so you'll need
336 to make sure that the given user account has sufficient privileges to
337 create a new database on the system.
339 .. versionadded:: 1.0
341 For fine-grained control over the character encoding of your test
342 database, use the :setting:`TEST_CHARSET` option. If you're using
343 MySQL, you can also use the :setting:`TEST_COLLATION` option to
344 control the particular collation used by the test database. See the
345 :ref:`settings documentation <ref-settings>` for details of these
348 .. _topics-testing-masterslave:
350 Testing master/slave configurations
351 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
353 .. versionadded:: 1.2
355 If you're testing a multiple database configuration with master/slave
356 replication, this strategy of creating test databases poses a problem.
357 When the test databases are created, there won't be any replication,
358 and as a result, data created on the master won't be seen on the
361 To compensate for this, Django allows you to define that a database is
362 a *test mirror*. Consider the following (simplified) example database
367 'ENGINE': 'django.db.backends.mysql',
370 # ... plus some other settings
373 'ENGINE': 'django.db.backends.mysql',
376 'TEST_MIRROR': 'default'
377 # ... plus some other settings
381 In this setup, we have two database servers: ``dbmaster``, described
382 by the database alias ``default``, and ``dbslave`` described by the
383 alias ``slave``. As you might expect, ``dbslave`` has been configured
384 by the database administrator as a read slave of ``dbmaster``, so in
385 normal activity, any write to ``default`` will appear on ``slave``.
387 If Django created two independent test databases, this would break any
388 tests that expected replication to occur. However, the ``slave``
389 database has been configured as a test mirror (using the
390 :setting:`TEST_MIRROR` setting), indicating that under testing,
391 ``slave`` should be treated as a mirror of ``default``.
393 When the test environment is configured, a test version of ``slave``
394 will *not* be created. Instead the connection to ``slave``
395 will be redirected to point at ``default``. As a result, writes to
396 ``default`` will appear on ``slave`` -- but because they are actually
397 the same database, not because there is data replication between the
400 Other test conditions
401 ---------------------
403 Regardless of the value of the :setting:`DEBUG` setting in your configuration
404 file, all Django tests run with :setting:`DEBUG=False`. This is to ensure that
405 the observed output of your code matches what will be seen in a production
408 Understanding the test output
409 -----------------------------
411 When you run your tests, you'll see a number of messages as the test runner
412 prepares itself. You can control the level of detail of these messages with the
413 ``verbosity`` option on the command line::
415 Creating test database...
416 Creating table myapp_animal
417 Creating table myapp_mineral
418 Loading 'initial_data' fixtures...
421 This tells you that the test runner is creating a test database, as described
422 in the previous section.
424 Once the test database has been created, Django will run your tests.
425 If everything goes well, you'll see something like this::
427 ----------------------------------------------------------------------
428 Ran 22 tests in 0.221s
432 If there are test failures, however, you'll see full details about which tests
435 ======================================================================
436 FAIL: Doctest: ellington.core.throttle.models
437 ----------------------------------------------------------------------
438 Traceback (most recent call last):
439 File "/dev/django/test/doctest.py", line 2153, in runTest
440 raise self.failureException(self.format_failure(new.getvalue()))
441 AssertionError: Failed doctest test for myapp.models
442 File "/dev/myapp/models.py", line 0, in models
444 ----------------------------------------------------------------------
445 File "/dev/myapp/models.py", line 14, in myapp.models
447 throttle.check("actor A", "action one", limit=2, hours=1)
453 ----------------------------------------------------------------------
454 Ran 2 tests in 0.048s
458 A full explanation of this error output is beyond the scope of this document,
459 but it's pretty intuitive. You can consult the documentation of Python's
460 ``unittest`` library for details.
462 Note that the return code for the test-runner script is the total number of
463 failed and erroneous tests. If all the tests pass, the return code is 0. This
464 feature is useful if you're using the test-runner script in a shell script and
465 need to test for success or failure at that level.
470 Django provides a small set of tools that come in handy when writing tests.
475 .. module:: django.test.client
476 :synopsis: Django's test client.
478 The test client is a Python class that acts as a dummy Web browser, allowing
479 you to test your views and interact with your Django-powered application
482 Some of the things you can do with the test client are:
484 * Simulate GET and POST requests on a URL and observe the response --
485 everything from low-level HTTP (result headers and status codes) to
488 * Test that the correct view is executed for a given URL.
490 * Test that a given request is rendered by a given Django template, with
491 a template context that contains certain values.
493 Note that the test client is not intended to be a replacement for Twill_,
494 Selenium_, or other "in-browser" frameworks. Django's test client has
495 a different focus. In short:
497 * Use Django's test client to establish that the correct view is being
498 called and that the view is collecting the correct context data.
500 * Use in-browser frameworks such as Twill and Selenium to test *rendered*
501 HTML and the *behavior* of Web pages, namely JavaScript functionality.
503 A comprehensive test suite should use a combination of both test types.
505 .. _Twill: http://twill.idyll.org/
506 .. _Selenium: http://seleniumhq.org/
508 Overview and a quick example
509 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
511 To use the test client, instantiate ``django.test.client.Client`` and retrieve
514 >>> from django.test.client import Client
516 >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
517 >>> response.status_code
519 >>> response = c.get('/customer/details/')
521 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...'
523 As this example suggests, you can instantiate ``Client`` from within a session
524 of the Python interactive interpreter.
526 Note a few important things about how the test client works:
528 * The test client does *not* require the Web server to be running. In fact,
529 it will run just fine with no Web server running at all! That's because
530 it avoids the overhead of HTTP and deals directly with the Django
531 framework. This helps make the unit tests run quickly.
533 * When retrieving pages, remember to specify the *path* of the URL, not the
534 whole domain. For example, this is correct::
540 >>> c.get('http://www.example.com/login/')
542 The test client is not capable of retrieving Web pages that are not
543 powered by your Django project. If you need to retrieve other Web pages,
544 use a Python standard library module such as urllib_ or urllib2_.
546 * To resolve URLs, the test client uses whatever URLconf is pointed-to by
547 your :setting:`ROOT_URLCONF` setting.
549 * Although the above example would work in the Python interactive
550 interpreter, some of the test client's functionality, notably the
551 template-related functionality, is only available *while tests are
554 The reason for this is that Django's test runner performs a bit of black
555 magic in order to determine which template was loaded by a given view.
556 This black magic (essentially a patching of Django's template system in
557 memory) only happens during test running.
559 .. _urllib: http://docs.python.org/library/urllib.html
560 .. _urllib2: http://docs.python.org/library/urllib2.html
565 Use the ``django.test.client.Client`` class to make requests. It requires no
566 arguments at time of construction:
570 Once you have a ``Client`` instance, you can call any of the following
573 .. method:: Client.get(path, data={}, follow=False, **extra)
576 Makes a GET request on the provided ``path`` and returns a ``Response``
577 object, which is documented below.
579 The key-value pairs in the ``data`` dictionary are used to create a GET
580 data payload. For example::
583 >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
585 ...will result in the evaluation of a GET request equivalent to::
587 /customers/details/?name=fred&age=7
589 The ``extra`` keyword arguments parameter can be used to specify
590 headers to be sent in the request. For example::
593 >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
594 ... HTTP_X_REQUESTED_WITH='XMLHttpRequest')
596 ...will send the HTTP header ``HTTP_X_REQUESTED_WITH`` to the
597 details view, which is a good way to test code paths that use the
598 :meth:`django.http.HttpRequest.is_ajax()` method.
600 .. versionadded:: 1.1
602 If you already have the GET arguments in URL-encoded form, you can
603 use that encoding instead of using the data argument. For example,
604 the previous GET request could also be posed as::
607 >>> c.get('/customers/details/?name=fred&age=7')
609 If you provide a URL with both an encoded GET data and a data argument,
610 the data argument will take precedence.
612 If you set ``follow`` to ``True`` the client will follow any redirects
613 and a ``redirect_chain`` attribute will be set in the response object
614 containing tuples of the intermediate urls and status codes.
616 If you had an url ``/redirect_me/`` that redirected to ``/next/``, that
617 redirected to ``/final/``, this is what you'd see::
619 >>> response = c.get('/redirect_me/', follow=True)
620 >>> response.redirect_chain
621 [(u'http://testserver/next/', 302), (u'http://testserver/final/', 302)]
623 .. method:: Client.post(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
625 Makes a POST request on the provided ``path`` and returns a
626 ``Response`` object, which is documented below.
628 The key-value pairs in the ``data`` dictionary are used to submit POST
632 >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
634 ...will result in the evaluation of a POST request to this URL::
638 ...with this POST data::
640 name=fred&passwd=secret
642 If you provide ``content_type`` (e.g., ``text/xml`` for an XML
643 payload), the contents of ``data`` will be sent as-is in the POST
644 request, using ``content_type`` in the HTTP ``Content-Type`` header.
646 If you don't provide a value for ``content_type``, the values in
647 ``data`` will be transmitted with a content type of
648 ``multipart/form-data``. In this case, the key-value pairs in ``data``
649 will be encoded as a multipart message and used to create the POST data
652 To submit multiple values for a given key -- for example, to specify
653 the selections for a ``<select multiple>`` -- provide the values as a
654 list or tuple for the required key. For example, this value of ``data``
655 would submit three selected values for the field named ``choices``::
657 {'choices': ('a', 'b', 'd')}
659 Submitting files is a special case. To POST a file, you need only
660 provide the file field name as a key, and a file handle to the file you
661 wish to upload as a value. For example::
664 >>> f = open('wishlist.doc')
665 >>> c.post('/customers/wishes/', {'name': 'fred', 'attachment': f})
668 (The name ``attachment`` here is not relevant; use whatever name your
669 file-processing code expects.)
671 Note that if you wish to use the same file handle for multiple
672 ``post()`` calls then you will need to manually reset the file
673 pointer between posts. The easiest way to do this is to
674 manually close the file after it has been provided to
675 ``post()``, as demonstrated above.
677 You should also ensure that the file is opened in a way that
678 allows the data to be read. If your file contains binary data
679 such as an image, this means you will need to open the file in
680 ``rb`` (read binary) mode.
682 The ``extra`` argument acts the same as for :meth:`Client.get`.
684 .. versionchanged:: 1.1
686 If the URL you request with a POST contains encoded parameters, these
687 parameters will be made available in the request.GET data. For example,
688 if you were to make the request::
690 >>> c.post('/login/?vistor=true', {'name': 'fred', 'passwd': 'secret'})
692 ... the view handling this request could interrogate request.POST
693 to retrieve the username and password, and could interrogate request.GET
694 to determine if the user was a visitor.
696 If you set ``follow`` to ``True`` the client will follow any redirects
697 and a ``redirect_chain`` attribute will be set in the response object
698 containing tuples of the intermediate urls and status codes.
700 .. method:: Client.head(path, data={}, follow=False, **extra)
702 .. versionadded:: 1.1
704 Makes a HEAD request on the provided ``path`` and returns a ``Response``
705 object. Useful for testing RESTful interfaces. Acts just like
706 :meth:`Client.get` except it does not return a message body.
708 If you set ``follow`` to ``True`` the client will follow any redirects
709 and a ``redirect_chain`` attribute will be set in the response object
710 containing tuples of the intermediate urls and status codes.
712 .. method:: Client.options(path, data={}, follow=False, **extra)
714 .. versionadded:: 1.1
716 Makes an OPTIONS request on the provided ``path`` and returns a
717 ``Response`` object. Useful for testing RESTful interfaces.
719 If you set ``follow`` to ``True`` the client will follow any redirects
720 and a ``redirect_chain`` attribute will be set in the response object
721 containing tuples of the intermediate urls and status codes.
723 The ``extra`` argument acts the same as for :meth:`Client.get`.
725 .. method:: Client.put(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
727 .. versionadded:: 1.1
729 Makes a PUT request on the provided ``path`` and returns a
730 ``Response`` object. Useful for testing RESTful interfaces. Acts just
731 like :meth:`Client.post` except with the PUT request method.
733 If you set ``follow`` to ``True`` the client will follow any redirects
734 and a ``redirect_chain`` attribute will be set in the response object
735 containing tuples of the intermediate urls and status codes.
737 .. method:: Client.delete(path, follow=False, **extra)
739 .. versionadded:: 1.1
741 Makes an DELETE request on the provided ``path`` and returns a
742 ``Response`` object. Useful for testing RESTful interfaces.
744 If you set ``follow`` to ``True`` the client will follow any redirects
745 and a ``redirect_chain`` attribute will be set in the response object
746 containing tuples of the intermediate urls and status codes.
748 The ``extra`` argument acts the same as for :meth:`Client.get`.
750 .. method:: Client.login(**credentials)
752 .. versionadded:: 1.0
754 If your site uses Django's :ref:`authentication system<topics-auth>`
755 and you deal with logging in users, you can use the test client's
756 ``login()`` method to simulate the effect of a user logging into the
759 After you call this method, the test client will have all the cookies
760 and session data required to pass any login-based tests that may form
763 The format of the ``credentials`` argument depends on which
764 :ref:`authentication backend <authentication-backends>` you're using
765 (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
766 setting). If you're using the standard authentication backend provided
767 by Django (``ModelBackend``), ``credentials`` should be the user's
768 username and password, provided as keyword arguments::
771 >>> c.login(username='fred', password='secret')
773 # Now you can access a view that's only available to logged-in users.
775 If you're using a different authentication backend, this method may
776 require different credentials. It requires whichever credentials are
777 required by your backend's ``authenticate()`` method.
779 ``login()`` returns ``True`` if it the credentials were accepted and
780 login was successful.
782 Finally, you'll need to remember to create user accounts before you can
783 use this method. As we explained above, the test runner is executed
784 using a test database, which contains no users by default. As a result,
785 user accounts that are valid on your production site will not work
786 under test conditions. You'll need to create users as part of the test
787 suite -- either manually (using the Django model API) or with a test
788 fixture. Remember that if you want your test user to have a password,
789 you can't set the user's password by setting the password attribute
790 directly -- you must use the
791 :meth:`~django.contrib.auth.models.User.set_password()` function to
792 store a correctly hashed password. Alternatively, you can use the
793 :meth:`~django.contrib.auth.models.UserManager.create_user` helper
794 method to create a new user with a correctly hashed password.
796 .. method:: Client.logout()
798 .. versionadded:: 1.0
800 If your site uses Django's :ref:`authentication system<topics-auth>`,
801 the ``logout()`` method can be used to simulate the effect of a user
802 logging out of your site.
804 After you call this method, the test client will have all the cookies
805 and session data cleared to defaults. Subsequent requests will appear
806 to come from an AnonymousUser.
811 The ``get()`` and ``post()`` methods both return a ``Response`` object. This
812 ``Response`` object is *not* the same as the ``HttpResponse`` object returned
813 Django views; the test response object has some additional data useful for
816 Specifically, a ``Response`` object has the following attributes:
818 .. class:: Response()
820 .. attribute:: client
822 The test client that was used to make the request that resulted in the
825 .. attribute:: content
827 The body of the response, as a string. This is the final page content as
828 rendered by the view, or any error message.
830 .. attribute:: context
832 The template ``Context`` instance that was used to render the template that
833 produced the response content.
835 If the rendered page used multiple templates, then ``context`` will be a
836 list of ``Context`` objects, in the order in which they were rendered.
838 .. versionadded:: 1.1
840 Regardless of the number of templates used during rendering, you can
841 retrieve context values using the ``[]`` operator. For example, the
842 context variable ``name`` could be retrieved using::
844 >>> response = client.get('/foo/')
845 >>> response.context['name']
848 .. attribute:: request
850 The request data that stimulated the response.
852 .. attribute:: status_code
854 The HTTP status of the response, as an integer. See RFC2616_ for a full
855 list of HTTP status codes.
857 .. attribute:: template
859 The ``Template`` instance that was used to render the final content. Use
860 ``template.name`` to get the template's file name, if the template was
861 loaded from a file. (The name is a string such as ``'admin/index.html'``.)
863 If the rendered page used multiple templates -- e.g., using :ref:`template
864 inheritance<template-inheritance>` -- then ``template`` will be a list of
865 ``Template`` instances, in the order in which they were rendered.
867 You can also use dictionary syntax on the response object to query the value
868 of any settings in the HTTP headers. For example, you could determine the
869 content type of a response using ``response['Content-Type']``.
871 .. _RFC2616: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
876 If you point the test client at a view that raises an exception, that exception
877 will be visible in the test case. You can then use a standard ``try...except``
878 block or ``unittest.TestCase.assertRaises()`` to test for exceptions.
880 The only exceptions that are not visible to the test client are ``Http404``,
881 ``PermissionDenied`` and ``SystemExit``. Django catches these exceptions
882 internally and converts them into the appropriate HTTP response codes. In these
883 cases, you can check ``response.status_code`` in your test.
888 The test client is stateful. If a response returns a cookie, then that cookie
889 will be stored in the test client and sent with all subsequent ``get()`` and
892 Expiration policies for these cookies are not followed. If you want a cookie
893 to expire, either delete it manually or create a new ``Client`` instance (which
894 will effectively delete all cookies).
896 A test client has two attributes that store persistent state information. You
897 can access these properties as part of a test condition.
899 .. attribute:: Client.cookies
901 A Python ``SimpleCookie`` object, containing the current values of all the
902 client cookies. See the `Cookie module documentation`_ for more.
904 .. attribute:: Client.session
906 A dictionary-like object containing session information. See the
907 :ref:`session documentation<topics-http-sessions>` for full details.
909 .. _Cookie module documentation: http://docs.python.org/library/cookie.html
914 The following is a simple unit test using the test client::
917 from django.test.client import Client
919 class SimpleTest(unittest.TestCase):
921 # Every test needs a client.
922 self.client = Client()
924 def test_details(self):
925 # Issue a GET request.
926 response = self.client.get('/customer/details/')
928 # Check that the response is 200 OK.
929 self.failUnlessEqual(response.status_code, 200)
931 # Check that the rendered context contains 5 customers.
932 self.failUnlessEqual(len(response.context['customers']), 5)
937 .. currentmodule:: django.test
939 Normal Python unit test classes extend a base class of ``unittest.TestCase``.
940 Django provides an extension of this base class:
942 .. class:: TestCase()
944 This class provides some additional capabilities that can be useful for testing
947 Converting a normal ``unittest.TestCase`` to a Django ``TestCase`` is easy:
948 just change the base class of your test from ``unittest.TestCase`` to
949 ``django.test.TestCase``. All of the standard Python unit test functionality
950 will continue to be available, but it will be augmented with some useful
953 .. versionadded:: 1.1
955 .. class:: TransactionTestCase()
957 Django ``TestCase`` classes make use of database transaction facilities, if
958 available, to speed up the process of resetting the database to a known state
959 at the beginning of each test. A consequence of this, however, is that the
960 effects of transaction commit and rollback cannot be tested by a Django
961 ``TestCase`` class. If your test requires testing of such transactional
962 behavior, you should use a Django ``TransactionTestCase``.
964 ``TransactionTestCase`` and ``TestCase`` are identical except for the manner
965 in which the database is reset to a known state and the ability for test code
966 to test the effects of commit and rollback. A ``TransactionTestCase`` resets
967 the database before the test runs by truncating all tables and reloading
968 initial data. A ``TransactionTestCase`` may call commit and rollback and
969 observe the effects of these calls on the database.
971 A ``TestCase``, on the other hand, does not truncate tables and reload initial
972 data at the beginning of a test. Instead, it encloses the test code in a
973 database transaction that is rolled back at the end of the test. It also
974 prevents the code under test from issuing any commit or rollback operations
975 on the database, to ensure that the rollback at the end of the test restores
976 the database to its initial state. In order to guarantee that all ``TestCase``
977 code starts with a clean database, the Django test runner runs all ``TestCase``
978 tests first, before any other tests (e.g. doctests) that may alter the
979 database without restoring it to its original state.
981 When running on a database that does not support rollback (e.g. MySQL with the
982 MyISAM storage engine), ``TestCase`` falls back to initializing the database
983 by truncating tables and reloading initial data.
987 The ``TestCase`` use of rollback to un-do the effects of the test code
988 may reveal previously-undetected errors in test code. For example,
989 test code that assumes primary keys values will be assigned starting at
990 one may find that assumption no longer holds true when rollbacks instead
991 of table truncation are being used to reset the database. Similarly,
992 the reordering of tests so that all ``TestCase`` classes run first may
993 reveal unexpected dependencies on test case ordering. In such cases a
994 quick fix is to switch the ``TestCase`` to a ``TransactionTestCase``.
995 A better long-term fix, that allows the test to take advantage of the
996 speed benefit of ``TestCase``, is to fix the underlying test problem.
1002 .. versionadded:: 1.0
1004 .. attribute:: TestCase.client
1006 Every test case in a ``django.test.TestCase`` instance has access to an
1007 instance of a Django test client. This client can be accessed as
1008 ``self.client``. This client is recreated for each test, so you don't have to
1009 worry about state (such as cookies) carrying over from one test to another.
1011 This means, instead of instantiating a ``Client`` in each test::
1014 from django.test.client import Client
1016 class SimpleTest(unittest.TestCase):
1017 def test_details(self):
1019 response = client.get('/customer/details/')
1020 self.failUnlessEqual(response.status_code, 200)
1022 def test_index(self):
1024 response = client.get('/customer/index/')
1025 self.failUnlessEqual(response.status_code, 200)
1027 ...you can just refer to ``self.client``, like so::
1029 from django.test import TestCase
1031 class SimpleTest(TestCase):
1032 def test_details(self):
1033 response = self.client.get('/customer/details/')
1034 self.failUnlessEqual(response.status_code, 200)
1036 def test_index(self):
1037 response = self.client.get('/customer/index/')
1038 self.failUnlessEqual(response.status_code, 200)
1040 .. _topics-testing-fixtures:
1045 .. attribute:: TestCase.fixtures
1047 A test case for a database-backed Web site isn't much use if there isn't any
1048 data in the database. To make it easy to put test data into the database,
1049 Django's custom ``TestCase`` class provides a way of loading **fixtures**.
1051 A fixture is a collection of data that Django knows how to import into a
1052 database. For example, if your site has user accounts, you might set up a
1053 fixture of fake user accounts in order to populate your database during tests.
1055 The most straightforward way of creating a fixture is to use the ``manage.py
1056 dumpdata`` command. This assumes you already have some data in your database.
1057 See the :djadmin:`dumpdata documentation<dumpdata>` for more details.
1060 If you've ever run ``manage.py syncdb``, you've already used a fixture
1061 without even knowing it! When you call ``syncdb`` in the database for
1062 the first time, Django installs a fixture called ``initial_data``.
1063 This gives you a way of populating a new database with any initial data,
1064 such as a default set of categories.
1066 Fixtures with other names can always be installed manually using the
1067 ``manage.py loaddata`` command.
1069 Once you've created a fixture and placed it in a ``fixtures`` directory in one
1070 of your :setting:`INSTALLED_APPS`, you can use it in your unit tests by
1071 specifying a ``fixtures`` class attribute on your ``django.test.TestCase``
1074 from django.test import TestCase
1075 from myapp.models import Animal
1077 class AnimalTestCase(TestCase):
1078 fixtures = ['mammals.json', 'birds']
1081 # Test definitions as before.
1082 call_setup_methods()
1084 def testFluffyAnimals(self):
1085 # A test that uses the fixtures.
1086 call_some_test_code()
1088 Here's specifically what will happen:
1090 * At the start of each test case, before ``setUp()`` is run, Django will
1091 flush the database, returning the database to the state it was in
1092 directly after :djadmin:`syncdb` was called.
1094 * Then, all the named fixtures are installed. In this example, Django will
1095 install any JSON fixture named ``mammals``, followed by any fixture named
1096 ``birds``. See the :djadmin:`loaddata` documentation for more
1097 details on defining and installing fixtures.
1099 This flush/load procedure is repeated for each test in the test case, so you
1100 can be certain that the outcome of a test will not be affected by another test,
1101 or by the order of test execution.
1103 URLconf configuration
1104 ~~~~~~~~~~~~~~~~~~~~~
1106 .. versionadded:: 1.0
1108 .. attribute:: TestCase.urls
1110 If your application provides views, you may want to include tests that use the
1111 test client to exercise those views. However, an end user is free to deploy the
1112 views in your application at any URL of their choosing. This means that your
1113 tests can't rely upon the fact that your views will be available at a
1116 In order to provide a reliable URL space for your test,
1117 ``django.test.TestCase`` provides the ability to customize the URLconf
1118 configuration for the duration of the execution of a test suite. If your
1119 ``TestCase`` instance defines an ``urls`` attribute, the ``TestCase`` will use
1120 the value of that attribute as the ``ROOT_URLCONF`` for the duration of that
1125 from django.test import TestCase
1127 class TestMyViews(TestCase):
1128 urls = 'myapp.test_urls'
1130 def testIndexPageView(self):
1131 # Here you'd test your view using ``Client``.
1132 call_some_test_code()
1134 This test case will use the contents of ``myapp.test_urls`` as the
1135 URLconf for the duration of the test case.
1137 .. _emptying-test-outbox:
1139 Multi-database support
1140 ~~~~~~~~~~~~~~~~~~~~~~
1142 .. attribute:: TestCase.multi_db
1144 .. versionadded:: 1.2
1146 Django sets up a test database corresponding to every database that is
1147 defined in the :setting:`DATABASES` definition in your settings
1148 file. However, a big part of the time taken to run a Django TestCase
1149 is consumed by the call to ``flush`` that ensures that you have a
1150 clean database at the start of each test run. If you have multiple
1151 databases, multiple flushes are required (one for each database),
1152 which can be a time consuming activity -- especially if your tests
1153 don't need to test multi-database activity.
1155 As an optimization, Django only flushes the ``default`` database at
1156 the start of each test run. If your setup contains multiple databases,
1157 and you have a test that requires every database to be clean, you can
1158 use the ``multi_db`` attribute on the test suite to request a full
1163 class TestMyViews(TestCase):
1166 def testIndexPageView(self):
1167 call_some_test_code()
1169 This test case will flush *all* the test databases before running
1170 ``testIndexPageView``.
1172 Emptying the test outbox
1173 ~~~~~~~~~~~~~~~~~~~~~~~~
1175 .. versionadded:: 1.0
1177 If you use Django's custom ``TestCase`` class, the test runner will clear the
1178 contents of the test e-mail outbox at the start of each test case.
1180 For more detail on e-mail services during tests, see `E-mail services`_.
1185 .. versionadded:: 1.0
1187 .. versionchanged:: 1.2
1188 Addded ``msg_prefix`` argument.
1190 As Python's normal ``unittest.TestCase`` class implements assertion methods
1191 such as ``assertTrue`` and ``assertEquals``, Django's custom ``TestCase`` class
1192 provides a number of custom assertion methods that are useful for testing Web
1195 The failure messages given by the assertion methods can be customized
1196 with the ``msg_prefix`` argument. This string will be prefixed to any
1197 failure message generated by the assertion. This allows you to provide
1198 additional details that may help you to identify the location and
1199 cause of an failure in your test suite.
1201 .. method:: TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='')
1203 Asserts that a ``Response`` instance produced the given ``status_code`` and
1204 that ``text`` appears in the content of the response. If ``count`` is
1205 provided, ``text`` must occur exactly ``count`` times in the response.
1207 .. method:: TestCase.assertNotContains(response, text, status_code=200, msg_prefix='')
1209 Asserts that a ``Response`` instance produced the given ``status_code`` and
1210 that ``text`` does not appears in the content of the response.
1212 .. method:: TestCase.assertFormError(response, form, field, errors, msg_prefix='')
1214 Asserts that a field on a form raises the provided list of errors when
1215 rendered on the form.
1217 ``form`` is the name the ``Form`` instance was given in the template
1220 ``field`` is the name of the field on the form to check. If ``field``
1221 has a value of ``None``, non-field errors (errors you can access via
1222 ``form.non_field_errors()``) will be checked.
1224 ``errors`` is an error string, or a list of error strings, that are
1225 expected as a result of form validation.
1227 .. method:: TestCase.assertTemplateUsed(response, template_name, msg_prefix='')
1229 Asserts that the template with the given name was used in rendering the
1232 The name is a string such as ``'admin/index.html'``.
1234 .. method:: TestCase.assertTemplateNotUsed(response, template_name, msg_prefix='')
1236 Asserts that the template with the given name was *not* used in rendering
1239 .. method:: TestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='')
1241 Asserts that the response return a ``status_code`` redirect status, it
1242 redirected to ``expected_url`` (including any GET data), and the final
1243 page was received with ``target_status_code``.
1245 .. versionadded:: 1.1
1247 If your request used the ``follow`` argument, the ``expected_url`` and
1248 ``target_status_code`` will be the url and status code for the final
1249 point of the redirect chain.
1251 .. _topics-testing-email:
1256 .. versionadded:: 1.0
1258 If any of your Django views send e-mail using :ref:`Django's e-mail
1259 functionality <topics-email>`, you probably don't want to send e-mail each time
1260 you run a test using that view. For this reason, Django's test runner
1261 automatically redirects all Django-sent e-mail to a dummy outbox. This lets you
1262 test every aspect of sending e-mail -- from the number of messages sent to the
1263 contents of each message -- without actually sending the messages.
1265 The test runner accomplishes this by transparently replacing the normal
1266 email backend with a testing backend.
1267 (Don't worry -- this has no effect on any other e-mail senders outside of
1268 Django, such as your machine's mail server, if you're running one.)
1270 .. currentmodule:: django.core.mail
1272 .. data:: django.core.mail.outbox
1274 During test running, each outgoing e-mail is saved in
1275 ``django.core.mail.outbox``. This is a simple list of all
1276 :class:`~django.core.mail.EmailMessage` instances that have been sent.
1277 The ``outbox`` attribute is a special attribute that is created *only* when
1278 the ``locmem`` e-mail backend is used. It doesn't normally exist as part of the
1279 :mod:`django.core.mail` module and you can't import it directly. The code
1280 below shows how to access this attribute correctly.
1282 Here's an example test that examines ``django.core.mail.outbox`` for length
1285 from django.core import mail
1286 from django.test import TestCase
1288 class EmailTest(TestCase):
1289 def test_send_email(self):
1291 mail.send_mail('Subject here', 'Here is the message.',
1292 'from@example.com', ['to@example.com'],
1293 fail_silently=False)
1295 # Test that one message has been sent.
1296 self.assertEquals(len(mail.outbox), 1)
1298 # Verify that the subject of the first message is correct.
1299 self.assertEquals(mail.outbox[0].subject, 'Subject here')
1301 As noted :ref:`previously <emptying-test-outbox>`, the test outbox is emptied
1302 at the start of every test in a Django ``TestCase``. To empty the outbox
1303 manually, assign the empty list to ``mail.outbox``::
1305 from django.core import mail
1307 # Empty the test outbox
1310 Using different testing frameworks
1311 ==================================
1313 Clearly, ``doctest`` and ``unittest`` are not the only Python testing
1314 frameworks. While Django doesn't provide explicit support for alternative
1315 frameworks, it does provide a way to invoke tests constructed for an
1316 alternative framework as if they were normal Django tests.
1318 When you run ``./manage.py test``, Django looks at the :setting:`TEST_RUNNER`
1319 setting to determine what to do. By default, :setting:`TEST_RUNNER` points to
1320 ``'django.test.simple.DjangoTestSuiteRunner'``. This class defines the default Django
1321 testing behavior. This behavior involves:
1323 #. Performing global pre-test setup.
1325 #. Looking for unit tests and doctests in the ``models.py`` and
1326 ``tests.py`` files in each installed application.
1328 #. Creating the test databases.
1330 #. Running ``syncdb`` to install models and initial data into the test
1333 #. Running the unit tests and doctests that are found.
1335 #. Destroying the test databases.
1337 #. Performing global post-test teardown.
1339 If you define your own test runner class and point :setting:`TEST_RUNNER` at
1340 that class, Django will execute your test runner whenever you run
1341 ``./manage.py test``. In this way, it is possible to use any test framework
1342 that can be executed from Python code, or to modify the Django test execution
1343 process to satisfy whatever testing requirements you may have.
1345 .. _topics-testing-test_runner:
1347 Defining a test runner
1348 ----------------------
1350 .. versionchanged:: 1.2
1351 Prior to 1.2, test runners were a single function, not a class.
1353 .. currentmodule:: django.test.simple
1355 A test runner is a class defining a ``run_tests()`` method. Django ships
1356 with a ``DjangoTestSuiteRunner`` class that defines the default Django
1357 testing behavior. This class defines the ``run_tests()`` entry point,
1358 plus a selection of other methods that are used to by ``run_tests()`` to
1359 set up, execute and tear down the test suite.
1361 .. class:: DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=True, **kwargs)
1363 ``verbosity`` determines the amount of notification and debug information
1364 that will be printed to the console; ``0`` is no output, ``1`` is normal
1365 output, and ``2`` is verbose output.
1367 If ``interactive`` is ``True``, the test suite has permission to ask the
1368 user for instructions when the test suite is executed. An example of this
1369 behavior would be asking for permission to delete an existing test
1370 database. If ``interactive`` is ``False``, the test suite must be able to
1371 run without any manual intervention.
1373 If ``failfast`` is ``True``, the test suite will stop running after the
1374 first test failure is detected.
1376 Django will, from time to time, extend the capabilities of
1377 the test runner by adding new arguments. The ``**kwargs`` declaration
1378 allows for this expansion. If you subclass ``DjangoTestSuiteRunner`` or
1379 write your own test runner, ensure accept and handle the ``**kwargs``
1382 .. method:: DjangoTestSuiteRunner.run_tests(test_labels, extra_tests=None, **kwargs)
1386 ``test_labels`` is a list of strings describing the tests to be run. A test
1387 label can take one of three forms:
1389 * ``app.TestCase.test_method`` -- Run a single test method in a test
1391 * ``app.TestCase`` -- Run all the test methods in a test case.
1392 * ``app`` -- Search for and run all tests in the named application.
1394 If ``test_labels`` has a value of ``None``, the test runner should run
1395 search for tests in all the applications in :setting:`INSTALLED_APPS`.
1397 ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
1398 suite that is executed by the test runner. These extra tests are run
1399 in addition to those discovered in the modules listed in ``test_labels``.
1401 This method should return the number of tests that failed.
1403 .. method:: DjangoTestSuiteRunner.setup_test_environment(**kwargs)
1405 Sets up the test environment ready for testing.
1407 .. method:: DjangoTestSuiteRunner.build_suite(test_labels, extra_tests=None, **kwargs)
1409 Constructs a test suite that matches the test labels provided.
1411 ``test_labels`` is a list of strings describing the tests to be run. A test
1412 label can take one of three forms:
1414 * ``app.TestCase.test_method`` -- Run a single test method in a test
1416 * ``app.TestCase`` -- Run all the test methods in a test case.
1417 * ``app`` -- Search for and run all tests in the named application.
1419 If ``test_labels`` has a value of ``None``, the test runner should run
1420 search for tests in all the applications in :setting:`INSTALLED_APPS`.
1422 ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
1423 suite that is executed by the test runner. These extra tests are run
1424 in addition to those discovered in the modules listed in ``test_labels``.
1426 Returns a ``TestSuite`` instance ready to be run.
1428 .. method:: DjangoTestSuiteRunner.setup_databases(**kwargs)
1430 Creates the test databases.
1432 Returns a data structure that provides enough detail to undo the changes
1433 that have been made. This data will be provided to the ``teardown_databases()``
1434 function at the conclusion of testing.
1436 .. method:: DjangoTestSuiteRunner.run_suite(suite, **kwargs)
1438 Runs the test suite.
1440 Returns the result produced by the running the test suite.
1442 .. method:: DjangoTestSuiteRunner.teardown_databases(old_config, **kwargs)
1444 Destroys the test databases, restoring pre-test conditions.
1446 ``old_config`` is a data structure defining the changes in the
1447 database configuration that need to be reversed. It is the return
1448 value of the ``setup_databases()`` method.
1450 .. method:: DjangoTestSuiteRunner.teardown_test_environment(**kwargs)
1452 Restores the pre-test environment.
1454 .. method:: DjangoTestSuiteRunner.suite_result(suite, result, **kwargs)
1456 Computes and returns a return code based on a test suite, and the result
1457 from that test suite.
1463 .. module:: django.test.utils
1464 :synopsis: Helpers to write custom test runners.
1466 To assist in the creation of your own test runner, Django provides a number of
1467 utility methods in the ``django.test.utils`` module.
1469 .. function:: setup_test_environment()
1471 Performs any global pre-test setup, such as the installing the
1472 instrumentation of the template rendering system and setting up
1473 the dummy ``SMTPConnection``.
1475 .. function:: teardown_test_environment()
1477 Performs any global post-test teardown, such as removing the black
1478 magic hooks into the template system and restoring normal e-mail
1481 The creation module of the database backend (``connection.creation``)
1482 also provides some utilities that can be useful during testing.
1484 .. function:: create_test_db(verbosity=1, autoclobber=False)
1486 Creates a new test database and runs ``syncdb`` against it.
1488 ``verbosity`` has the same behavior as in ``run_tests()``.
1490 ``autoclobber`` describes the behavior that will occur if a
1491 database with the same name as the test database is discovered:
1493 * If ``autoclobber`` is ``False``, the user will be asked to
1494 approve destroying the existing database. ``sys.exit`` is
1495 called if the user does not approve.
1497 * If autoclobber is ``True``, the database will be destroyed
1498 without consulting the user.
1500 Returns the name of the test database that it created.
1502 ``create_test_db()`` has the side effect of modifying the value of
1503 :setting:`NAME` in :setting:`DATABASES` to match the name of the test
1506 .. versionchanged:: 1.0
1507 ``create_test_db()`` now returns the name of the test database.
1509 .. function:: destroy_test_db(old_database_name, verbosity=1)
1511 Destroys the database whose name is in stored in :setting:`NAME` in the
1512 :setting:`DATABASES`, and sets :setting:`NAME` to use the
1515 ``verbosity`` has the same behavior as in ``run_tests()``.