PageRenderTime 3ms CodeModel.GetById 20ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/topics/testing.txt

https://code.google.com/p/mango-py/
Plain Text | 1801 lines | 1291 code | 510 blank | 0 comment | 0 complexity | 168acb74e07b0e612dca55e557f4fece MD5 | raw file
   1===========================
   2Testing Django applications
   3===========================
   4
   5.. module:: django.test
   6   :synopsis: Testing tools for Django applications.
   7
   8Automated testing is an extremely useful bug-killing tool for the modern
   9Web developer. You can use a collection of tests -- a **test suite** -- to
  10solve, or avoid, a number of problems:
  11
  12    * When you're writing new code, you can use tests to validate your code
  13      works as expected.
  14
  15    * When you're refactoring or modifying old code, you can use tests to
  16      ensure your changes haven't affected your application's behavior
  17      unexpectedly.
  18
  19Testing a Web application is a complex task, because a Web application is made
  20of several layers of logic -- from HTTP-level request handling, to form
  21validation and processing, to template rendering. With Django's test-execution
  22framework and assorted utilities, you can simulate requests, insert test data,
  23inspect your application's output and generally verify your code is doing what
  24it should be doing.
  25
  26The best part is, it's really easy.
  27
  28This document is split into two primary sections. First, we explain how to
  29write tests with Django. Then, we explain how to run them.
  30
  31Writing tests
  32=============
  33
  34There are two primary ways to write tests with Django, corresponding to the
  35two test frameworks that ship in the Python standard library. The two
  36frameworks are:
  37
  38    * **Unit tests** -- tests that are expressed as methods on a Python class
  39      that subclasses ``unittest.TestCase`` or Django's customized
  40      :class:`TestCase`. For example::
  41
  42          import unittest
  43
  44          class MyFuncTestCase(unittest.TestCase):
  45              def testBasic(self):
  46                  a = ['larry', 'curly', 'moe']
  47                  self.assertEqual(my_func(a, 0), 'larry')
  48                  self.assertEqual(my_func(a, 1), 'curly')
  49
  50    * **Doctests** -- tests that are embedded in your functions' docstrings and
  51      are written in a way that emulates a session of the Python interactive
  52      interpreter. For example::
  53
  54          def my_func(a_list, idx):
  55              """
  56              >>> a = ['larry', 'curly', 'moe']
  57              >>> my_func(a, 0)
  58              'larry'
  59              >>> my_func(a, 1)
  60              'curly'
  61              """
  62              return a_list[idx]
  63
  64We'll discuss choosing the appropriate test framework later, however, most
  65experienced developers prefer unit tests. You can also use any *other* Python
  66test framework, as we'll explain in a bit.
  67
  68Writing unit tests
  69------------------
  70
  71Django's unit tests use a Python standard library module: unittest_. This
  72module defines tests in class-based approach.
  73
  74.. admonition:: unittest2
  75
  76    .. versionchanged:: 1.3
  77
  78    Python 2.7 introduced some major changes to the unittest library,
  79    adding some extremely useful features. To ensure that every Django
  80    project can benefit from these new features, Django ships with a
  81    copy of unittest2_, a copy of the Python 2.7 unittest library,
  82    backported for Python 2.4 compatibility.
  83
  84    To access this library, Django provides the
  85    ``django.utils.unittest`` module alias. If you are using Python
  86    2.7, or you have installed unittest2 locally, Django will map the
  87    alias to the installed version of the unittest library. Otherwise,
  88    Django will use it's own bundled version of unittest2.
  89
  90    To use this alias, simply use::
  91
  92        from django.utils import unittest
  93
  94    wherever you would have historically used::
  95
  96        import unittest
  97
  98    If you want to continue to use the base unittest library, you can --
  99    you just won't get any of the nice new unittest2 features.
 100
 101.. _unittest2: http://pypi.python.org/pypi/unittest2
 102
 103For a given Django application, the test runner looks for unit tests in two
 104places:
 105
 106    * The ``models.py`` file. The test runner looks for any subclass of
 107      ``unittest.TestCase`` in this module.
 108
 109    * A file called ``tests.py`` in the application directory -- i.e., the
 110      directory that holds ``models.py``. Again, the test runner looks for any
 111      subclass of ``unittest.TestCase`` in this module.
 112
 113Here is an example ``unittest.TestCase`` subclass::
 114
 115    from django.utils import unittest
 116    from myapp.models import Animal
 117
 118    class AnimalTestCase(unittest.TestCase):
 119        def setUp(self):
 120            self.lion = Animal.objects.create(name="lion", sound="roar")
 121            self.cat = Animal.objects.create(name="cat", sound="meow")
 122
 123        def testSpeaking(self):
 124            self.assertEqual(self.lion.speak(), 'The lion says "roar"')
 125            self.assertEqual(self.cat.speak(), 'The cat says "meow"')
 126
 127When you :ref:`run your tests <running-tests>`, the default behavior of the
 128test utility is to find all the test cases (that is, subclasses of
 129``unittest.TestCase``) in ``models.py`` and ``tests.py``, automatically build a
 130test suite out of those test cases, and run that suite.
 131
 132There is a second way to define the test suite for a module: if you define a
 133function called ``suite()`` in either ``models.py`` or ``tests.py``, the
 134Django test runner will use that function to construct the test suite for that
 135module. This follows the `suggested organization`_ for unit tests. See the
 136Python documentation for more details on how to construct a complex test
 137suite.
 138
 139For more details about ``unittest``, see the `standard library unittest
 140documentation`_.
 141
 142.. _unittest: http://docs.python.org/library/unittest.html
 143.. _standard library unittest documentation: unittest_
 144.. _suggested organization: http://docs.python.org/library/unittest.html#organizing-tests
 145
 146Writing doctests
 147----------------
 148
 149Doctests use Python's standard doctest_ module, which searches your docstrings
 150for statements that resemble a session of the Python interactive interpreter.
 151A full explanation of how doctest works is out of the scope of this document;
 152read Python's official documentation for the details.
 153
 154.. admonition:: What's a **docstring**?
 155
 156    A good explanation of docstrings (and some guidelines for using them
 157    effectively) can be found in :pep:`257`:
 158
 159        A docstring is a string literal that occurs as the first statement in
 160        a module, function, class, or method definition.  Such a docstring
 161        becomes the ``__doc__`` special attribute of that object.
 162
 163    For example, this function has a docstring that describes what it does::
 164
 165        def add_two(num):
 166            "Return the result of adding two to the provided number."
 167            return num + 2
 168
 169    Because tests often make great documentation, putting tests directly in
 170    your docstrings is an effective way to document *and* test your code.
 171
 172As with unit tests, for a given Django application, the test runner looks for
 173doctests in two places:
 174
 175    * The ``models.py`` file. You can define module-level doctests and/or a
 176      doctest for individual models. It's common practice to put
 177      application-level doctests in the module docstring and model-level
 178      doctests in the model docstrings.
 179
 180    * A file called ``tests.py`` in the application directory -- i.e., the
 181      directory that holds ``models.py``. This file is a hook for any and all
 182      doctests you want to write that aren't necessarily related to models.
 183
 184This example doctest is equivalent to the example given in the unittest section
 185above::
 186
 187    # models.py
 188
 189    from django.db import models
 190
 191    class Animal(models.Model):
 192        """
 193        An animal that knows how to make noise
 194
 195        # Create some animals
 196        >>> lion = Animal.objects.create(name="lion", sound="roar")
 197        >>> cat = Animal.objects.create(name="cat", sound="meow")
 198
 199        # Make 'em speak
 200        >>> lion.speak()
 201        'The lion says "roar"'
 202        >>> cat.speak()
 203        'The cat says "meow"'
 204        """
 205        name = models.CharField(max_length=20)
 206        sound = models.CharField(max_length=20)
 207
 208        def speak(self):
 209            return 'The %s says "%s"' % (self.name, self.sound)
 210
 211When you :ref:`run your tests <running-tests>`, the test runner will find this
 212docstring, notice that portions of it look like an interactive Python session,
 213and execute those lines while checking that the results match.
 214
 215In the case of model tests, note that the test runner takes care of creating
 216its own test database. That is, any test that accesses a database -- by
 217creating and saving model instances, for example -- will not affect your
 218production database. However, the database is not refreshed between doctests,
 219so if your doctest requires a certain state you should consider flushing the
 220database or loading a fixture. (See the section on fixtures, below, for more
 221on this.) Note that to use this feature, the database user Django is connecting
 222as must have ``CREATE DATABASE`` rights.
 223
 224For more details about how doctest works, see the `standard library
 225documentation for doctest`_.
 226
 227.. _doctest: http://docs.python.org/library/doctest.html
 228.. _standard library documentation for doctest: doctest_
 229
 230
 231Which should I use?
 232-------------------
 233
 234Because Django supports both of the standard Python test frameworks, it's up to
 235you and your tastes to decide which one to use. You can even decide to use
 236*both*.
 237
 238For developers new to testing, however, this choice can seem confusing. Here,
 239then, are a few key differences to help you decide which approach is right for
 240you:
 241
 242    * If you've been using Python for a while, ``doctest`` will probably feel
 243      more "pythonic". It's designed to make writing tests as easy as possible,
 244      so it requires no overhead of writing classes or methods. You simply put
 245      tests in docstrings. This has the added advantage of serving as
 246      documentation (and correct documentation, at that!). However, while
 247      doctests are good for some simple example code, they are not very good if
 248      you want to produce either high quality, comprehensive tests or high
 249      quality documentation. Test failures are often difficult to debug
 250      as it can be unclear exactly why the test failed. Thus, doctests should
 251      generally be avoided and used primarily for documentation examples only.
 252
 253    * The ``unittest`` framework will probably feel very familiar to developers
 254      coming from Java. ``unittest`` is inspired by Java's JUnit, so you'll
 255      feel at home with this method if you've used JUnit or any test framework
 256      inspired by JUnit.
 257
 258    * If you need to write a bunch of tests that share similar code, then
 259      you'll appreciate the ``unittest`` framework's organization around
 260      classes and methods. This makes it easy to abstract common tasks into
 261      common methods. The framework also supports explicit setup and/or cleanup
 262      routines, which give you a high level of control over the environment
 263      in which your test cases are run.
 264
 265    * If you're writing tests for Django itself, you should use ``unittest``.
 266
 267.. _running-tests:
 268
 269Running tests
 270=============
 271
 272Once you've written tests, run them using the :djadmin:`test` command of
 273your project's ``manage.py`` utility::
 274
 275    $ ./manage.py test
 276
 277By default, this will run every test in every application in
 278:setting:`INSTALLED_APPS`. If you only want to run tests for a particular
 279application, add the application name to the command line. For example, if your
 280:setting:`INSTALLED_APPS` contains ``'myproject.polls'`` and
 281``'myproject.animals'``, you can run the ``myproject.animals`` unit tests alone
 282with this command::
 283
 284    $ ./manage.py test animals
 285
 286Note that we used ``animals``, not ``myproject.animals``.
 287
 288You can be even *more* specific by naming an individual test case. To
 289run a single test case in an application (for example, the
 290``AnimalTestCase`` described in the "Writing unit tests" section), add
 291the name of the test case to the label on the command line::
 292
 293    $ ./manage.py test animals.AnimalTestCase
 294
 295And it gets even more granular than that! To run a *single* test
 296method inside a test case, add the name of the test method to the
 297label::
 298
 299    $ ./manage.py test animals.AnimalTestCase.testFluffyAnimals
 300
 301.. versionadded:: 1.2
 302   The ability to select individual doctests was added.
 303
 304You can use the same rules if you're using doctests. Django will use the
 305test label as a path to the test method or class that you want to run.
 306If your ``models.py`` or ``tests.py`` has a function with a doctest, or
 307class with a class-level doctest, you can invoke that test by appending the
 308name of the test method or class to the label::
 309
 310    $ ./manage.py test animals.classify
 311
 312If you want to run the doctest for a specific method in a class, add the
 313name of the method to the label::
 314
 315    $ ./manage.py test animals.Classifier.run
 316
 317If you're using a ``__test__`` dictionary to specify doctests for a
 318module, Django will use the label as a key in the ``__test__`` dictionary
 319for defined in ``models.py`` and ``tests.py``.
 320
 321.. versionadded:: 1.2
 322   You can now trigger a graceful exit from a test run by pressing ``Ctrl-C``.
 323
 324If you press ``Ctrl-C`` while the tests are running, the test runner will
 325wait for the currently running test to complete and then exit gracefully.
 326During a graceful exit the test runner will output details of any test
 327failures, report on how many tests were run and how many errors and failures
 328were encountered, and destroy any test databases as usual. Thus pressing
 329``Ctrl-C`` can be very useful if you forget to pass the :djadminopt:`--failfast`
 330option, notice that some tests are unexpectedly failing, and want to get details
 331on the failures without waiting for the full test run to complete.
 332
 333If you do not want to wait for the currently running test to finish, you
 334can press ``Ctrl-C`` a second time and the test run will halt immediately,
 335but not gracefully. No details of the tests run before the interruption will
 336be reported, and any test databases created by the run will not be destroyed.
 337
 338.. admonition:: Test with warnings enabled
 339
 340    It's a good idea to run your tests with Python warnings enabled:
 341    ``python -Wall manage.py test``. The ``-Wall`` flag tells Python to
 342    display deprecation warnings. Django, like many other Python libraries,
 343    uses these warnings to flag when features are going away. It also might
 344    flag areas in your code that aren't strictly wrong but could benefit
 345    from a better implementation.
 346
 347Running tests outside the test runner
 348-------------------------------------
 349
 350If you want to run tests outside of ``./manage.py test`` -- for example,
 351from a shell prompt -- you will need to set up the test
 352environment first. Django provides a convenience method to do this::
 353
 354    >>> from django.test.utils import setup_test_environment
 355    >>> setup_test_environment()
 356
 357This convenience method sets up the test database, and puts other
 358Django features into modes that allow for repeatable testing.
 359
 360The call to :meth:`~django.test.utils.setup_test_environment` is made
 361automatically as part of the setup of `./manage.py test`. You only
 362need to manually invoke this method if you're not using running your
 363tests via Django's test runner.
 364
 365The test database
 366-----------------
 367
 368Tests that require a database (namely, model tests) will not use your "real"
 369(production) database. Separate, blank databases are created for the tests.
 370
 371Regardless of whether the tests pass or fail, the test databases are destroyed
 372when all the tests have been executed.
 373
 374By default the test databases get their names by prepending ``test_``
 375to the value of the :setting:`NAME` settings for the databases
 376defined in :setting:`DATABASES`. When using the SQLite database engine
 377the tests will by default use an in-memory database (i.e., the
 378database will be created in memory, bypassing the filesystem
 379entirely!). If you want to use a different database name, specify
 380:setting:`TEST_NAME` in the dictionary for any given database in
 381:setting:`DATABASES`.
 382
 383Aside from using a separate database, the test runner will otherwise
 384use all of the same database settings you have in your settings file:
 385:setting:`ENGINE`, :setting:`USER`, :setting:`HOST`, etc. The test
 386database is created by the user specified by :setting:`USER`, so you'll need
 387to make sure that the given user account has sufficient privileges to
 388create a new database on the system.
 389
 390For fine-grained control over the character encoding of your test
 391database, use the :setting:`TEST_CHARSET` option. If you're using
 392MySQL, you can also use the :setting:`TEST_COLLATION` option to
 393control the particular collation used by the test database. See the
 394:doc:`settings documentation </ref/settings>` for details of these
 395advanced settings.
 396
 397.. _topics-testing-masterslave:
 398
 399Testing master/slave configurations
 400~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 401
 402.. versionadded:: 1.2
 403
 404If you're testing a multiple database configuration with master/slave
 405replication, this strategy of creating test databases poses a problem.
 406When the test databases are created, there won't be any replication,
 407and as a result, data created on the master won't be seen on the
 408slave.
 409
 410To compensate for this, Django allows you to define that a database is
 411a *test mirror*. Consider the following (simplified) example database
 412configuration::
 413
 414    DATABASES = {
 415        'default': {
 416            'ENGINE': 'django.db.backends.mysql',
 417            'NAME': 'myproject',
 418            'HOST': 'dbmaster',
 419             # ... plus some other settings
 420        },
 421        'slave': {
 422            'ENGINE': 'django.db.backends.mysql',
 423            'NAME': 'myproject',
 424            'HOST': 'dbslave',
 425            'TEST_MIRROR': 'default'
 426            # ... plus some other settings
 427        }
 428    }
 429
 430In this setup, we have two database servers: ``dbmaster``, described
 431by the database alias ``default``, and ``dbslave`` described by the
 432alias ``slave``. As you might expect, ``dbslave`` has been configured
 433by the database administrator as a read slave of ``dbmaster``, so in
 434normal activity, any write to ``default`` will appear on ``slave``.
 435
 436If Django created two independent test databases, this would break any
 437tests that expected replication to occur. However, the ``slave``
 438database has been configured as a test mirror (using the
 439:setting:`TEST_MIRROR` setting), indicating that under testing,
 440``slave`` should be treated as a mirror of ``default``.
 441
 442When the test environment is configured, a test version of ``slave``
 443will *not* be created. Instead the connection to ``slave``
 444will be redirected to point at ``default``. As a result, writes to
 445``default`` will appear on ``slave`` -- but because they are actually
 446the same database, not because there is data replication between the
 447two databases.
 448
 449.. _topics-testing-creation-dependencies:
 450
 451Controlling creation order for test databases
 452~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 453
 454.. versionadded:: 1.3
 455
 456By default, Django will always create the ``default`` database first.
 457However, no guarantees are made on the creation order of any other
 458databases in your test setup.
 459
 460If your database configuration requires a specific creation order, you
 461can specify the dependencies that exist using the
 462:setting:`TEST_DEPENDENCIES` setting. Consider the following
 463(simplified) example database configuration::
 464
 465    DATABASES = {
 466        'default': {
 467             # ... db settings
 468             'TEST_DEPENDENCIES': ['diamonds']
 469        },
 470        'diamonds': {
 471            # ... db settings
 472        },
 473        'clubs': {
 474            # ... db settings
 475            'TEST_DEPENDENCIES': ['diamonds']
 476        },
 477        'spades': {
 478            # ... db settings
 479            'TEST_DEPENDENCIES': ['diamonds','hearts']
 480        },
 481        'hearts': {
 482            # ... db settings
 483            'TEST_DEPENDENCIES': ['diamonds','clubs']
 484        }
 485    }
 486
 487Under this configuration, the ``diamonds`` database will be created first,
 488as it is the only database alias without dependencies. The ``default`` and
 489``clubs`` alias will be created next (although the order of creation of this
 490pair is not guaranteed); then ``hearts``; and finally ``spades``.
 491
 492If there are any circular dependencies in the
 493:setting:`TEST_DEPENDENCIES` definition, an ``ImproperlyConfigured``
 494exception will be raised.
 495
 496Other test conditions
 497---------------------
 498
 499Regardless of the value of the :setting:`DEBUG` setting in your configuration
 500file, all Django tests run with :setting:`DEBUG`\=False. This is to ensure that
 501the observed output of your code matches what will be seen in a production
 502setting.
 503
 504Understanding the test output
 505-----------------------------
 506
 507When you run your tests, you'll see a number of messages as the test runner
 508prepares itself. You can control the level of detail of these messages with the
 509``verbosity`` option on the command line::
 510
 511    Creating test database...
 512    Creating table myapp_animal
 513    Creating table myapp_mineral
 514    Loading 'initial_data' fixtures...
 515    No fixtures found.
 516
 517This tells you that the test runner is creating a test database, as described
 518in the previous section.
 519
 520Once the test database has been created, Django will run your tests.
 521If everything goes well, you'll see something like this::
 522
 523    ----------------------------------------------------------------------
 524    Ran 22 tests in 0.221s
 525
 526    OK
 527
 528If there are test failures, however, you'll see full details about which tests
 529failed::
 530
 531    ======================================================================
 532    FAIL: Doctest: ellington.core.throttle.models
 533    ----------------------------------------------------------------------
 534    Traceback (most recent call last):
 535      File "/dev/django/test/doctest.py", line 2153, in runTest
 536        raise self.failureException(self.format_failure(new.getvalue()))
 537    AssertionError: Failed doctest test for myapp.models
 538      File "/dev/myapp/models.py", line 0, in models
 539
 540    ----------------------------------------------------------------------
 541    File "/dev/myapp/models.py", line 14, in myapp.models
 542    Failed example:
 543        throttle.check("actor A", "action one", limit=2, hours=1)
 544    Expected:
 545        True
 546    Got:
 547        False
 548
 549    ----------------------------------------------------------------------
 550    Ran 2 tests in 0.048s
 551
 552    FAILED (failures=1)
 553
 554A full explanation of this error output is beyond the scope of this document,
 555but it's pretty intuitive. You can consult the documentation of Python's
 556``unittest`` library for details.
 557
 558Note that the return code for the test-runner script is 1 for any number of
 559failed and erroneous tests. If all the tests pass, the return code is 0. This
 560feature is useful if you're using the test-runner script in a shell script and
 561need to test for success or failure at that level.
 562
 563Testing tools
 564=============
 565
 566Django provides a small set of tools that come in handy when writing tests.
 567
 568.. _test-client:
 569
 570The test client
 571---------------
 572
 573.. module:: django.test.client
 574   :synopsis: Django's test client.
 575
 576The test client is a Python class that acts as a dummy Web browser, allowing
 577you to test your views and interact with your Django-powered application
 578programmatically.
 579
 580Some of the things you can do with the test client are:
 581
 582    * Simulate GET and POST requests on a URL and observe the response --
 583      everything from low-level HTTP (result headers and status codes) to
 584      page content.
 585
 586    * Test that the correct view is executed for a given URL.
 587
 588    * Test that a given request is rendered by a given Django template, with
 589      a template context that contains certain values.
 590
 591Note that the test client is not intended to be a replacement for Twill_,
 592Selenium_, or other "in-browser" frameworks. Django's test client has
 593a different focus. In short:
 594
 595    * Use Django's test client to establish that the correct view is being
 596      called and that the view is collecting the correct context data.
 597
 598    * Use in-browser frameworks such as Twill and Selenium to test *rendered*
 599      HTML and the *behavior* of Web pages, namely JavaScript functionality.
 600
 601A comprehensive test suite should use a combination of both test types.
 602
 603.. _Twill: http://twill.idyll.org/
 604.. _Selenium: http://seleniumhq.org/
 605
 606Overview and a quick example
 607~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 608
 609To use the test client, instantiate ``django.test.client.Client`` and retrieve
 610Web pages::
 611
 612    >>> from django.test.client import Client
 613    >>> c = Client()
 614    >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
 615    >>> response.status_code
 616    200
 617    >>> response = c.get('/customer/details/')
 618    >>> response.content
 619    '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...'
 620
 621As this example suggests, you can instantiate ``Client`` from within a session
 622of the Python interactive interpreter.
 623
 624Note a few important things about how the test client works:
 625
 626    * The test client does *not* require the Web server to be running. In fact,
 627      it will run just fine with no Web server running at all! That's because
 628      it avoids the overhead of HTTP and deals directly with the Django
 629      framework. This helps make the unit tests run quickly.
 630
 631    * When retrieving pages, remember to specify the *path* of the URL, not the
 632      whole domain. For example, this is correct::
 633
 634          >>> c.get('/login/')
 635
 636      This is incorrect::
 637
 638          >>> c.get('http://www.example.com/login/')
 639
 640      The test client is not capable of retrieving Web pages that are not
 641      powered by your Django project. If you need to retrieve other Web pages,
 642      use a Python standard library module such as urllib_ or urllib2_.
 643
 644    * To resolve URLs, the test client uses whatever URLconf is pointed-to by
 645      your :setting:`ROOT_URLCONF` setting.
 646
 647    * Although the above example would work in the Python interactive
 648      interpreter, some of the test client's functionality, notably the
 649      template-related functionality, is only available *while tests are
 650      running*.
 651
 652      The reason for this is that Django's test runner performs a bit of black
 653      magic in order to determine which template was loaded by a given view.
 654      This black magic (essentially a patching of Django's template system in
 655      memory) only happens during test running.
 656
 657    * By default, the test client will disable any CSRF checks
 658      performed by your site.
 659
 660      .. versionadded:: 1.2.2
 661
 662      If, for some reason, you *want* the test client to perform CSRF
 663      checks, you can create an instance of the test client that
 664      enforces CSRF checks. To do this, pass in the
 665      ``enforce_csrf_checks`` argument when you construct your
 666      client::
 667
 668          >>> from django.test import Client
 669          >>> csrf_client = Client(enforce_csrf_checks=True)
 670
 671
 672.. _urllib: http://docs.python.org/library/urllib.html
 673.. _urllib2: http://docs.python.org/library/urllib2.html
 674
 675Making requests
 676~~~~~~~~~~~~~~~
 677
 678Use the ``django.test.client.Client`` class to make requests. It requires no
 679arguments at time of construction:
 680
 681.. class:: Client()
 682
 683    Once you have a ``Client`` instance, you can call any of the following
 684    methods:
 685
 686    .. method:: Client.get(path, data={}, follow=False, **extra)
 687
 688
 689        Makes a GET request on the provided ``path`` and returns a ``Response``
 690        object, which is documented below.
 691
 692        The key-value pairs in the ``data`` dictionary are used to create a GET
 693        data payload. For example::
 694
 695            >>> c = Client()
 696            >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
 697
 698        ...will result in the evaluation of a GET request equivalent to::
 699
 700            /customers/details/?name=fred&age=7
 701
 702        The ``extra`` keyword arguments parameter can be used to specify
 703        headers to be sent in the request. For example::
 704
 705            >>> c = Client()
 706            >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
 707            ...       HTTP_X_REQUESTED_WITH='XMLHttpRequest')
 708
 709        ...will send the HTTP header ``HTTP_X_REQUESTED_WITH`` to the
 710        details view, which is a good way to test code paths that use the
 711        :meth:`django.http.HttpRequest.is_ajax()` method.
 712
 713        .. admonition:: CGI specification
 714
 715            The headers sent via ``**extra`` should follow CGI_ specification.
 716            For example, emulating a different "Host" header as sent in the
 717            HTTP request from the browser to the server should be passed
 718            as ``HTTP_HOST``. 
 719
 720            .. _CGI: http://www.w3.org/CGI/
 721
 722        If you already have the GET arguments in URL-encoded form, you can
 723        use that encoding instead of using the data argument. For example,
 724        the previous GET request could also be posed as::
 725
 726        >>> c = Client()
 727        >>> c.get('/customers/details/?name=fred&age=7')
 728
 729        If you provide a URL with both an encoded GET data and a data argument,
 730        the data argument will take precedence.
 731
 732        If you set ``follow`` to ``True`` the client will follow any redirects
 733        and a ``redirect_chain`` attribute will be set in the response object
 734        containing tuples of the intermediate urls and status codes.
 735
 736        If you had an url ``/redirect_me/`` that redirected to ``/next/``, that
 737        redirected to ``/final/``, this is what you'd see::
 738
 739            >>> response = c.get('/redirect_me/', follow=True)
 740            >>> response.redirect_chain
 741            [(u'http://testserver/next/', 302), (u'http://testserver/final/', 302)]
 742
 743    .. method:: Client.post(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
 744
 745        Makes a POST request on the provided ``path`` and returns a
 746        ``Response`` object, which is documented below.
 747
 748        The key-value pairs in the ``data`` dictionary are used to submit POST
 749        data. For example::
 750
 751            >>> c = Client()
 752            >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
 753
 754        ...will result in the evaluation of a POST request to this URL::
 755
 756            /login/
 757
 758        ...with this POST data::
 759
 760            name=fred&passwd=secret
 761
 762        If you provide ``content_type`` (e.g., ``text/xml`` for an XML
 763        payload), the contents of ``data`` will be sent as-is in the POST
 764        request, using ``content_type`` in the HTTP ``Content-Type`` header.
 765
 766        If you don't provide a value for ``content_type``, the values in
 767        ``data`` will be transmitted with a content type of
 768        ``multipart/form-data``. In this case, the key-value pairs in ``data``
 769        will be encoded as a multipart message and used to create the POST data
 770        payload.
 771
 772        To submit multiple values for a given key -- for example, to specify
 773        the selections for a ``<select multiple>`` -- provide the values as a
 774        list or tuple for the required key. For example, this value of ``data``
 775        would submit three selected values for the field named ``choices``::
 776
 777            {'choices': ('a', 'b', 'd')}
 778
 779        Submitting files is a special case. To POST a file, you need only
 780        provide the file field name as a key, and a file handle to the file you
 781        wish to upload as a value. For example::
 782
 783            >>> c = Client()
 784            >>> f = open('wishlist.doc')
 785            >>> c.post('/customers/wishes/', {'name': 'fred', 'attachment': f})
 786            >>> f.close()
 787
 788        (The name ``attachment`` here is not relevant; use whatever name your
 789        file-processing code expects.)
 790
 791        Note that if you wish to use the same file handle for multiple
 792        ``post()`` calls then you will need to manually reset the file
 793        pointer between posts. The easiest way to do this is to
 794        manually close the file after it has been provided to
 795        ``post()``, as demonstrated above.
 796
 797        You should also ensure that the file is opened in a way that
 798        allows the data to be read. If your file contains binary data
 799        such as an image, this means you will need to open the file in
 800        ``rb`` (read binary) mode.
 801
 802        The ``extra`` argument acts the same as for :meth:`Client.get`.
 803
 804        If the URL you request with a POST contains encoded parameters, these
 805        parameters will be made available in the request.GET data. For example,
 806        if you were to make the request::
 807
 808        >>> c.post('/login/?visitor=true', {'name': 'fred', 'passwd': 'secret'})
 809
 810        ... the view handling this request could interrogate request.POST
 811        to retrieve the username and password, and could interrogate request.GET
 812        to determine if the user was a visitor.
 813
 814        If you set ``follow`` to ``True`` the client will follow any redirects
 815        and a ``redirect_chain`` attribute will be set in the response object
 816        containing tuples of the intermediate urls and status codes.
 817
 818    .. method:: Client.head(path, data={}, follow=False, **extra)
 819
 820        Makes a HEAD request on the provided ``path`` and returns a ``Response``
 821        object. Useful for testing RESTful interfaces. Acts just like
 822        :meth:`Client.get` except it does not return a message body.
 823
 824        If you set ``follow`` to ``True`` the client will follow any redirects
 825        and a ``redirect_chain`` attribute will be set in the response object
 826        containing tuples of the intermediate urls and status codes.
 827
 828    .. method:: Client.options(path, data={}, follow=False, **extra)
 829
 830        Makes an OPTIONS request on the provided ``path`` and returns a
 831        ``Response`` object. Useful for testing RESTful interfaces.
 832
 833        If you set ``follow`` to ``True`` the client will follow any redirects
 834        and a ``redirect_chain`` attribute will be set in the response object
 835        containing tuples of the intermediate urls and status codes.
 836
 837        The ``extra`` argument acts the same as for :meth:`Client.get`.
 838
 839    .. method:: Client.put(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
 840
 841        Makes a PUT request on the provided ``path`` and returns a
 842        ``Response`` object. Useful for testing RESTful interfaces. Acts just
 843        like :meth:`Client.post` except with the PUT request method.
 844
 845        If you set ``follow`` to ``True`` the client will follow any redirects
 846        and a ``redirect_chain`` attribute will be set in the response object
 847        containing tuples of the intermediate urls and status codes.
 848
 849    .. method:: Client.delete(path, follow=False, **extra)
 850
 851        Makes an DELETE request on the provided ``path`` and returns a
 852        ``Response`` object. Useful for testing RESTful interfaces.
 853
 854        If you set ``follow`` to ``True`` the client will follow any redirects
 855        and a ``redirect_chain`` attribute will be set in the response object
 856        containing tuples of the intermediate urls and status codes.
 857
 858        The ``extra`` argument acts the same as for :meth:`Client.get`.
 859
 860    .. method:: Client.login(**credentials)
 861
 862        If your site uses Django's :doc:`authentication system</topics/auth>`
 863        and you deal with logging in users, you can use the test client's
 864        ``login()`` method to simulate the effect of a user logging into the
 865        site.
 866
 867        After you call this method, the test client will have all the cookies
 868        and session data required to pass any login-based tests that may form
 869        part of a view.
 870
 871        The format of the ``credentials`` argument depends on which
 872        :ref:`authentication backend <authentication-backends>` you're using
 873        (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
 874        setting). If you're using the standard authentication backend provided
 875        by Django (``ModelBackend``), ``credentials`` should be the user's
 876        username and password, provided as keyword arguments::
 877
 878            >>> c = Client()
 879            >>> c.login(username='fred', password='secret')
 880
 881            # Now you can access a view that's only available to logged-in users.
 882
 883        If you're using a different authentication backend, this method may
 884        require different credentials. It requires whichever credentials are
 885        required by your backend's ``authenticate()`` method.
 886
 887        ``login()`` returns ``True`` if it the credentials were accepted and
 888        login was successful.
 889
 890        Finally, you'll need to remember to create user accounts before you can
 891        use this method. As we explained above, the test runner is executed
 892        using a test database, which contains no users by default. As a result,
 893        user accounts that are valid on your production site will not work
 894        under test conditions. You'll need to create users as part of the test
 895        suite -- either manually (using the Django model API) or with a test
 896        fixture. Remember that if you want your test user to have a password,
 897        you can't set the user's password by setting the password attribute
 898        directly -- you must use the
 899        :meth:`~django.contrib.auth.models.User.set_password()` function to
 900        store a correctly hashed password. Alternatively, you can use the
 901        :meth:`~django.contrib.auth.models.UserManager.create_user` helper
 902        method to create a new user with a correctly hashed password.
 903
 904    .. method:: Client.logout()
 905
 906        If your site uses Django's :doc:`authentication system</topics/auth>`,
 907        the ``logout()`` method can be used to simulate the effect of a user
 908        logging out of your site.
 909
 910        After you call this method, the test client will have all the cookies
 911        and session data cleared to defaults. Subsequent requests will appear
 912        to come from an AnonymousUser.
 913
 914Testing responses
 915~~~~~~~~~~~~~~~~~
 916
 917The ``get()`` and ``post()`` methods both return a ``Response`` object. This
 918``Response`` object is *not* the same as the ``HttpResponse`` object returned
 919Django views; the test response object has some additional data useful for
 920test code to verify.
 921
 922Specifically, a ``Response`` object has the following attributes:
 923
 924.. class:: Response()
 925
 926    .. attribute:: client
 927
 928        The test client that was used to make the request that resulted in the
 929        response.
 930
 931    .. attribute:: content
 932
 933        The body of the response, as a string. This is the final page content as
 934        rendered by the view, or any error message.
 935
 936    .. attribute:: context
 937
 938        The template ``Context`` instance that was used to render the template that
 939        produced the response content.
 940
 941        If the rendered page used multiple templates, then ``context`` will be a
 942        list of ``Context`` objects, in the order in which they were rendered.
 943
 944        Regardless of the number of templates used during rendering, you can
 945        retrieve context values using the ``[]`` operator. For example, the
 946        context variable ``name`` could be retrieved using::
 947
 948            >>> response = client.get('/foo/')
 949            >>> response.context['name']
 950            'Arthur'
 951
 952    .. attribute:: request
 953
 954        The request data that stimulated the response.
 955
 956    .. attribute:: status_code
 957
 958        The HTTP status of the response, as an integer. See RFC2616_ for a full
 959        list of HTTP status codes.
 960
 961    .. versionadded:: 1.3
 962
 963    .. attribute:: templates
 964
 965        A list of ``Template`` instances used to render the final content, in
 966        the order they were rendered. For each template in the list, use
 967        ``template.name`` to get the template's file name, if the template was
 968        loaded from a file. (The name is a string such as
 969        ``'admin/index.html'``.)
 970
 971You can also use dictionary syntax on the response object to query the value
 972of any settings in the HTTP headers. For example, you could determine the
 973content type of a response using ``response['Content-Type']``.
 974
 975.. _RFC2616: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
 976
 977Exceptions
 978~~~~~~~~~~
 979
 980If you point the test client at a view that raises an exception, that exception
 981will be visible in the test case. You can then use a standard ``try...except``
 982block or ``unittest.TestCase.assertRaises()`` to test for exceptions.
 983
 984The only exceptions that are not visible to the test client are ``Http404``,
 985``PermissionDenied`` and ``SystemExit``. Django catches these exceptions
 986internally and converts them into the appropriate HTTP response codes. In these
 987cases, you can check ``response.status_code`` in your test.
 988
 989Persistent state
 990~~~~~~~~~~~~~~~~
 991
 992The test client is stateful. If a response returns a cookie, then that cookie
 993will be stored in the test client and sent with all subsequent ``get()`` and
 994``post()`` requests.
 995
 996Expiration policies for these cookies are not followed. If you want a cookie
 997to expire, either delete it manually or create a new ``Client`` instance (which
 998will effectively delete all cookies).
 999
1000A test client has two attributes that store persistent state information. You
1001can access these properties as part of a test condition.
1002
1003.. attribute:: Client.cookies
1004
1005    A Python ``SimpleCookie`` object, containing the current values of all the
1006    client cookies. See the `Cookie module documentation`_ for more.
1007
1008.. attribute:: Client.session
1009
1010    A dictionary-like object containing session information. See the
1011    :doc:`session documentation</topics/http/sessions>` for full details.
1012
1013    To modify the session and then save it, it must be stored in a variable
1014    first (because a new ``SessionStore`` is created every time this property
1015    is accessed)::
1016
1017        def test_something(self):
1018            session = self.client.session
1019            session['somekey'] = 'test'
1020            session.save()
1021
1022.. _Cookie module documentation: http://docs.python.org/library/cookie.html
1023
1024Example
1025~~~~~~~
1026
1027The following is a simple unit test using the test client::
1028
1029    from django.utils import unittest
1030    from django.test.client import Client
1031
1032    class SimpleTest(unittest.TestCase):
1033        def setUp(self):
1034            # Every test needs a client.
1035            self.client = Client()
1036
1037        def test_details(self):
1038            # Issue a GET request.
1039            response = self.client.get('/customer/details/')
1040
1041            # Check that the response is 200 OK.
1042            self.assertEqual(response.status_code, 200)
1043
1044            # Check that the rendered context contains 5 customers.
1045            self.assertEqual(len(response.context['customers']), 5)
1046
1047The request factory
1048-------------------
1049
1050.. Class:: RequestFactory
1051
1052.. versionadded:: 1.3
1053
1054The :class:`~django.test.client.RequestFactory` shares the same API as
1055the test client. However, instead of behaving like a browser, the
1056RequestFactory provides a way to generate a request instance that can
1057be used as the first argument to any view. This means you can test a
1058view function the same way as you would test any other function -- as
1059a black box, with exactly known inputs, testing for specific outputs.
1060
1061The API for the :class:`~django.test.client.RequestFactory` is a slightly
1062restricted subset of the test client API:
1063
1064    * It only has access to the HTTP methods :meth:`~Client.get()`,
1065      :meth:`~Client.post()`, :meth:`~Client.put()`,
1066      :meth:`~Client.delete()`, :meth:`~Client.head()` and
1067      :meth:`~Client.options()`.
1068
1069    * These methods accept all the same arguments *except* for
1070      ``follows``. Since this is just a factory for producing
1071      requests, it's up to you to handle the response.
1072
1073    * It does not support middleware. Session and authentication
1074      attributes must be supplied by the test itself if required
1075      for the view to function properly.
1076
1077Example
1078~~~~~~~
1079
1080The following is a simple unit test using the request factory::
1081
1082    from django.utils import unittest
1083    from django.test.client import RequestFactory
1084
1085    class SimpleTest(unittest.TestCase):
1086        def setUp(self):
1087            # Every test needs access to the request factory.
1088            self.factory = RequestFactory()
1089
1090        def test_details(self):
1091            # Create an instance of a GET request.
1092            request = self.factory.get('/customer/details')
1093
1094            # Test my_view() as if it were deployed at /customer/details
1095            response = my_view(request)
1096            self.assertEqual(response.status_code, 200)
1097
1098TestCase
1099--------
1100
1101.. currentmodule:: django.test
1102
1103Normal Python unit test classes extend a base class of ``unittest.TestCase``.
1104Django provides an extension of this base class:
1105
1106.. class:: TestCase()
1107
1108This class provides some additional capabilities that can be useful for testing
1109Web sites.
1110
1111Converting a normal ``unittest.TestCase`` to a Django ``TestCase`` is easy:
1112just change the base class of your test from ``unittest.TestCase`` to
1113``django.test.TestCase``. All of the standard Python unit test functionality
1114will continue to be available, but it will be augmented with some useful
1115additions, including:
1116
1117    * Automatic loading of fixtures.
1118
1119    * Wraps each test in a transaction.
1120
1121    * Creates a TestClient instance.
1122
1123    * Django-specific assertions for testing for things
1124      like redirection and form errors.
1125
1126.. class:: TransactionTestCase()
1127
1128Django ``TestCase`` classes make use of database transaction facilities, if
1129available, to speed up the process of resetting the database to a known state
1130at the beginning of each test. A consequence of this, however, is that the
1131effects of transaction commit and rollback cannot be tested by a Django
1132``TestCase`` class. If your test requires testing of such transactional
1133behavior, you should use a Django ``TransactionTestCase``.
1134
1135``TransactionTestCase`` and ``TestCase`` are identical except for the manner
1136in which the database is reset to a known state and the ability for test code
1137to test the effects of commit and rollback. A ``TransactionTestCase`` resets
1138the database before the test runs by truncating all tables and reloading
1139initial data. A ``TransactionTestCase`` may call commit and rollback and
1140observe the effects of these calls on the database.
1141
1142A ``TestCase``, on the other hand, does not truncate tables and reload initial
1143data at the beginning of a test. Instead, it encloses the test code in a
1144database transaction that is rolled back at the end of the test.  It also
1145prevents the code under test from issuing any commit or rollback operations
1146on the database, to ensure that the rollback at the end of the test restores
1147the database to its initial state. In order to guarantee that all ``TestCase``
1148code starts with a clean database, the Django test runner runs all ``TestCase``
1149tests first, before any other tests (e.g. doctests) that may alter the
1150database without restoring it to its original state.
1151
1152When running on a database that does not support rollback (e.g. MySQL with the
1153MyISAM storage engine), ``TestCase`` falls back to initializing the database
1154by truncating tables and reloading initial data.
1155
1156
1157.. note::
1158    The ``TestCase`` use of rollback to un-do the effects of the test code
1159    may reveal previously-undetected errors in test code.  For example,
1160    test code that assumes primary keys values will be assigned starting at
1161    one may find that assumption no longer holds true when rollbacks instead
1162    of table truncation are being used to reset the database.  Similarly,
1163    the reordering of tests so that all ``TestCase`` classes run first may
1164    reveal unexpected dependencies on test case ordering.  In such cases a
1165    quick fix is to switch the ``TestCase`` to a ``TransactionTestCase``.
1166    A better long-term fix, that allows the test to take advantage of the
1167    speed benefit of ``TestCase``, is to fix the underlying test problem.
1168
1169
1170Default test client
1171~~~~~~~~~~~~~~~~~~~
1172
1173.. attribute:: TestCase.client
1174
1175Every test case in a ``django.test.TestCase`` instance has access to an
1176instance of a Django test client. This client can be accessed as
1177``self.client``. This client is recreated for each test, so you don't have to
1178worry about state (such as cookies) carrying over from one test to another.
1179
1180This means, instead of instantiating a ``Client`` in each test::
1181
1182    from django.utils import unittest
1183    from django.test.client import Client
1184
1185    class SimpleTest(unittest.TestCase):
1186        def test_details(self):
1187            client = Client()
1188            response = client.get('/customer/details/')
1189            self.assertEqual(response.status_code, 200)
1190
1191        def test_index(self):
1192            client = Client()
1193            response = client.get('/customer/index/')
1194            self.assertEqual(response.status_code, 200)
1195
1196...you can just refer to ``self.client``, like so::
1197
1198    from django.test import TestCase
1199
1200    class SimpleTest(TestCase):
1201        def test_details(self):
1202            response = self.client.get('/customer/details/')
1203            self.assertEqual(response.status_code, 200)
1204
1205        def test_index(self):
1206            response = self.client.get('/customer/index/')
1207            self.assertEqual(response.status_code, 200)
1208
1209Customizing the test client
1210~~~~~~~~~~~~~~~~~~~~~~~~~~~
1211
1212.. versionadded:: 1.3
1213
1214.. attribute:: TestCase.client_class
1215
1216If you want to use a different ``Client`` class (for example, a subclass
1217with customized behavior), use the :attr:`~TestCase.client_class` class
1218attribute::
1219
1220    from django.test import TestCase
1221    from django.test.client import Client
1222
1223    class MyTestClient(Client):
1224        # Specialized methods for your environment...
1225
1226    class MyTest(TestCase):
1227        client_class = MyTestClient
1228
1229        def test_my_stuff(self):
1230            # Here self.client is an instance of MyTestClient...
1231
1232.. _topics-testing-fixtures:
1233
1234Fixture loading
1235~~~~~~~~~~~~~~~
1236
1237.. attribute:: TestCase.fixtures
1238
1239A test case for a database-backed Web site isn't much use if there isn't any
1240data in the database. To make it easy to put test data into the database,
1241Django's custom ``TestCase`` class provides a way of loading **fixtures**.
1242
1243A fixture is a collection of data that Django knows how to import into a
1244database. For example, if your site has user accounts, you might set up a
1245fixture of fake user accounts in order to populate your database during tests.
1246
1247The most straightforward way of creating a fixture is to use the
1248:djadmin:`manage.py dumpdata <dumpdata>` command. This assumes you
1249already have some data in your database. See the :djadmin:`dumpdata
1250documentation<dumpdata>` for more details.
1251
1252.. note::
1253    If you've ever run :djadmin:`manage.py syncdb<syncdb>`, you've
1254    already used a fixture without even knowing it! When you call
1255    :djadmin:`syncdb` in the database for the first time, Django
1256    installs a fixture called ``initial_data``. This gives you a way
1257    of populating a new database with any initial data, such as a
1258    default set of categories.
1259
1260    Fixtures with other names can always be installed manually using
1261    the :djadmin:`manage.py loaddata<loaddata>` command.
1262
1263.. admonition:: Initial SQL data and testing
1264
1265    Django provides a second way to insert initial data into models --
1266    the :ref:`custom SQL hook <initial-sql>`. However, this technique
1267    *cannot* be used to provide initial data for testing purposes.
1268    Django's test framework flushes the contents of the test database
1269    after each test; as a result, any data added using the custom SQL
1270    hook will be lost.
1271
1272Once you've created a fixture and placed it in a ``fixtures`` directory in one
1273of your :setting:`INSTALLED_APPS`, you can use it in your unit tests by
1274specifying a ``fixtures`` class attribute on your :class:`django.test.TestCase`
1275subclass::
1276
1277    from django.test import TestCase
1278    from myapp.models import Animal
1279
1280    class AnimalTestCase(TestCase):
1281        fixtures = ['mammals.json', 'birds']
1282
1283        def setUp(self):
1284            # Test definitions as before.
1285            call_setup_methods()
1286
1287        def testFluffyAnimals(self):
1288            # A test that uses the fixtures.
1289            call_some_test_code()
1290
1291Here's specifically what will happen:
1292
1293    * At the start of each test case, before ``setUp()`` is run, Django will
1294      flush the database, returning the database to the state it was in
1295      directly after :djadmin:`syncdb` was called.
1296
1297    * Then, all the named fixtures are installed. In this example, Django will
1298      install any JSON fixture named ``mammals``, followed by any fixture named
1299      ``birds``. See the :djadmin:`loaddata` documentation for more
1300      details on defining and installing fixtures.
1301
1302This flush/load procedure is repeated for each test in the test case, so you
1303can be certain that the outcome of a test will not be affected by another test,
1304or by the order of test execution.
1305
1306URLconf configuration
1307~~~~~~~~~~~~~~~~~~~~~
1308
1309.. attribute:: TestCase.urls
1310
1311If your application provides views, you may want to include tests that use the
1312test client to exercise those views. However, an end user is free to deploy the
1313views in your application at any URL of their choosing. This means that your
1314tests can't rely upon the fact that your views will be available at a
1315particular URL.
1316
1317In order to provide a reliable URL space for your test,
1318``django.test.TestCase`` provides the ability to customize the URLconf
1319configuration for the duration of the execution of a test suite. If your
1320``TestCase`` instance defines an ``urls`` attribute, the ``TestCase`` will use
1321the value of that attribute as the :setting:`ROOT_URLCONF` for the duration
1322of that test.
1323
1324For example::
1325
1326    from django.test import TestCase
1327
1328    class TestMyViews(TestCase):
1329        urls = 'myapp.test_urls'
1330
1331        def testIndexPageView(self):
1332            # Here you'd test your view using ``Client``.
1333            call_some_test_code()
1334
1335This test case will use the contents of ``myapp.test_urls`` as the
1336URLconf for the duration of the test case.
1337
1338.. _emptying-test-outbox:
1339
1340Multi-database support
1341~~~~~~~~~~~~~~~~~~~~~~
1342
1343.. attribute:: TestCase.multi_db
1344
1345.. versionadded:: 1.2
1346
1347Django sets up a test database corresponding to every database that is
1348defined in the :setting:`DATABASES` definition in your settings
1349file. However, a big part of the time taken to run a Django TestCase
1350is consumed by the call to ``flush`` that ensures that you have a
1351clean database at the start of each test run. If you have multiple
1352databases, multiple flushes are required (one for each database),
1353which can be a time consuming activity -- especially if your tests
1354don't need to test multi-database activity.
1355
1356As an optimization, Django only flushes the ``default`` database at
1357the start of each test run. If your setup contains multiple databases,
1358and you have a test that requires every database to be clean, you can
1359use the ``multi_db`` attribute on the test suite to request a full
1360flush.
1361
1362For example::
1363
1364    class TestMyViews(TestCase):
1365        multi_db = True
1366
1367        def testIndexPageView(self):
1368            call_some_test_code()
1369
1370This test case will flush *all* the test databases before running
1371``testIndexPageView``.
1372
1373Emptying the test outbox
1374~~~~~~~~~~~~~~~~~~~~~~~~
1375
1376If you use Django's custom ``TestCase`` class, the test runner will clear the
1377contents of the test e-mail outbox at the start of each test case.
1378
1379For more detail on e-mail services during tests, see `E-mail services`_.
1380
1381Assertions
1382~~~~~~~~~~
1383
1384.. versionchanged:: 1.2
1385    Addded ``msg_prefix`` argument.
1386
1387As Python's normal ``unittest.TestCase`` class implements assertion methods
1388such as ``assertTrue`` and ``assertEqual``, Django's custom ``TestCase`` class
1389provides a number of custom assertion methods that are useful for testing Web
1390applications:
1391
1392The failure messages given by the assertion methods can be customized
1393with the ``msg_prefix`` argument. This string will be prefixed to any
1394failure message generated by the assertion. This allows you to provide
1395additional details that may help you to identify the location and
1396cause of an failure in your test suite.
1397
1398.. method:: TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='')
1399
1400    Asserts that a ``Response`` instance produced the given ``status_code`` and
1401    that ``text`` appears in the content of the response. If ``count`` is
1402    provided, ``text`` must occur exactly ``count`` times in the response.
1403
1404.. method:: TestCase.assertNotContains(response, text, status_code=200, msg_prefix='')
1405
1406    Asserts that a ``Response`` instance produced the given ``status_code`` and
1407    that ``text`` does not appears in the content of the response.
1408
1409.. method:: TestCase.assertFormError(response, form, field, errors, msg_prefix='')
1410
1411    Asserts that a field on a form raises the provided list of errors when
1412    rendered on the form.
1413
1414    ``form`` is the name the ``Form`` instance was given in the template
1415    context.
1416
1417    ``field`` is the name of the field on the form to check. If ``field``
1418    has a value of ``None``, non-field errors (errors you can access via
1419    ``form.non_field_errors()``) will be checked.
1420
1421    ``errors`` is an error string, or a list of error strings, that are
1422    expected as a result of form validation.
1423
1424.. method:: TestCase.assertTemplateUsed(response, template_name, msg_prefix='')
1425
1426    Asserts that the template with the given name was used in rendering the
1427    response.
1428
1429    The name is a string such as ``'admin/index.html'``.
1430
1431.. method:: TestCase.assertTemplateNotUsed(response, template_name, msg_prefix='')
1432
1433    Asserts that the template with the given name was *not* used in rendering
1434    the response.
1435
1436.. method:: TestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='')
1437
1438    Asserts that the response return a ``status_code`` redirect status, it
1439    redirected to ``expected_url`` (including any GET data), and the final
1440    page was received with ``target_status_code``.
1441
1442    If your request used the ``follow`` argument, the ``expected_url`` and
1443    ``target_status_code`` will be the url and status code for the final
1444    point of the redirect chain.
1445
1446.. method:: TestCase.assertQuerysetEqual(qs, values, transform=repr)
1447
1448    .. versionadded:: 1.3
1449
1450    Asserts that a queryset ``qs`` returns a particular list of values ``values``.
1451
1452    The comparison of the contents of ``qs`` and ``values`` is performed using
1453    the function ``transform``; by default, this means that the ``repr()`` of
1454    each value is compared. Any other callable can be used if ``repr()`` doesn't
1455    provide a unique or helpful comparison.
1456
1457    The comparison is also ordering dependent. If ``qs`` doesn't provide an
1458    implicit ordering, you will need to apply a ``order_by()`` clause to your
1459    queryset to ensure that the test will pass reliably.
1460
1461.. method:: TestCase.assertNumQueries(num, func, *args, **kwargs)
1462
1463    .. versionadded:: 1.3
1464
1465    Asserts that when ``func`` is called with ``*args`` and ``**kwargs`` that
1466    ``num`` database queries are executed.
1467
1468    If a ``"using"`` key is present in ``kwargs`` it is used as the database
1469    alias for which to check the number of queries.  If you wish to call a
1470    function with a ``using`` parameter you can do it by wrapping the call with
1471    a ``lambda`` to add an extra parameter::
1472
1473        self.assertNumQueries(7, lambda: my_function(using=7))
1474
1475    If you're using Python 2.5 or greater you can also use this as a context
1476    manager::
1477
1478        # This is necessary in Python 2.5 to enable the with statement, in 2.6
1479        # and up it is no longer necessary.
1480        from __future__ import with_statement
1481
1482        with self.assertNumQueries(2):
1483            Person.objects.create(name="Aaron")
1484            Person.objects.create(name="Daniel")
1485
1486
1487.. _topics-testing-email:
1488
1489E-mail services
1490---------------
1491
1492If any of your Django views send e-mail using :doc:`Django's e-mail
1493functionality </topics/email>`, you probably don't want to send e-mail each time
1494you run a test using that view. For this reason, Django's test runner
1495automatically redirects all Django-sent e-mail to a dummy outbox. This lets you
1496test every aspect of sending e-mail -- from the number of messages sent to the
1497contents of each message -- without actually sending the messages.
1498
1499The test runner accomplishes this by transparently replacing the normal
1500email backend with a testing backend.
1501(Don't worry -- this has no effect on any other e-mail senders outside of
1502Django, such as your machine's mail server, if you're running one.)
1503
1504.. currentmodule:: django.core.mail
1505
1506.. data:: django.core.mail.outbox
1507
1508During test running, each outgoing e-mail is saved in
1509``django.core.mail.outbox``. This is a simple list of all
1510:class:`~django.core.mail.EmailMessage` instances that have been sent.
1511The ``outbox`` attribute is a special attribute that is created *only* when
1512the ``locmem`` e-mail backend is used. It doesn't normally exist as part of the
1513:mod:`django.core.mail` module and you can't import it directly. The code
1514below shows how to access this attribute correctly.
1515
1516Here's an example test that examines ``django.core.mail.outbox`` for length
1517and contents::
1518
1519    from django.core import mail
1520    from django.test import TestCase
1521
1522    class EmailTest(TestCase):
1523        def test_send_email(self):
1524            # Send message.
1525            mail.send_mail('Subject here', 'Here is the message.',
1526                'from@example.com', ['to@example.com'],
1527                fail_silently=False)
1528
1529            # Test that one message has been sent.
1530            self.assertEqual(len(mail.outbox), 1)
1531
1532            # Verify that the subject of the first message is correct.
1533            self.assertEqual(mail.outbox[0].subject, 'Subject here')
1534
1535As noted :ref:`previously <emptying-test-outbox>`, the test outbox is emptied
1536at the start of every test in a Django ``TestCase``. To empty the outbox
1537manually, assign the empty list to ``mail.outbox``::
1538
1539    from django.core import mail
1540
1541    # Empty the test outbox
1542    mail.outbox = []
1543
1544Skipping tests
1545--------------
1546
1547.. versionadded:: 1.3
1548
1549The unittest library provides the ``@skipIf`` and ``@skipUnless``
1550decorators to allow you to skip tests if you know ahead of time that
1551those tests are going to fail under certain conditions.
1552
1553For example, if your test requires a particular optional library in
1554order to succeed, you could decorate the test case with ``@skipIf``.
1555Then, the test runner will report that the test wasn't executed and
1556why, instead of failing the test or omitting the test altogether.
1557
1558To supplement these test skipping behaviors, Django provides two
1559additional skip decorators. Instead of testing a generic boolean,
1560these decorators check the capabilities of the database, and skip the
1561test if the database doesn't support a specific named feature.
1562
1563The decorators use a string identifier to describe database features.
1564This string corresponds to attributes of the database connection
1565features class. See :class:`~django.db.backends.BaseDatabaseFeatures`
1566class for a full list of database features that can be used as a basis
1567for skipping tests.
1568
1569skipIfDBFeature
1570~~~~~~~~~~~~~~~
1571
1572Skip the decorated test if the named database feature is supported.
1573
1574For example, the following test will not be executed if the database
1575supports transactions (e.g., it would *not* run under PostgreSQL, but
1576it would under MySQL with MyISAM tables)::
1577
1578    class MyTests(TestCase):
1579        @skipIfDBFeature('supports_transactions')
1580        def test_transaction_behavior(self):
1581            # ... conditional test code
1582
1583skipUnlessDBFeature
1584~~~~~~~~~~~~~~~~~~~
1585
1586Skip the decorated test if the named database feature is *not*
1587supported.
1588
1589For example, the following test will not be executed if the database
1590supports transactions (e.g., it would run under PostgreSQL, but *not*
1591under MySQL with MyISAM tables)::
1592
1593    class MyTests(TestCase):
1594        @skipUnlessDBFeature('supports_transactions')
1595        def test_transaction_behavior(self):
1596            # ... conditional test code
1597
1598
1599Using different testing frameworks
1600==================================
1601
1602Clearly, ``doctest`` and ``unittest`` are not the only Python testing
1603frameworks. While Django doesn't provide explicit support for alternative
1604frameworks, it does provide a way to invoke tests constructed for an
1605alternative framework as if they were normal Django tests.
1606
1607When you run ``./manage.py test``, Django looks at the :setting:`TEST_RUNNER`
1608setting to determine what to do. By default, :setting:`TEST_RUNNER` points to
1609``'django.test.simple.DjangoTestSuiteRunner'``. This class defines the default Django
1610testing behavior. This behavior involves:
1611
1612    #. Performing global pre-test setup.
1613
1614    #. Looking for unit tests and doctests in the ``models.py`` and
1615       ``tests.py`` files in each installed application.
1616
1617    #. Creating the test databases.
1618
1619    #. Running ``syncdb`` to install models and initial data into the test
1620       databases.
1621
1622    #. Running the unit tests and doctests that are found.
1623
1624    #. Destroying the test databases.
1625
1626    #. Performing global post-test teardown.
1627
1628If you define your own test runner class and point :setting:`TEST_RUNNER` at
1629that class, Django will execute your test runner whenever you run
1630``./manage.py test``. In this way, it is possible to use any test framework
1631that can be executed from Python code, or to modify the Django test execution
1632process to satisfy whatever testing requirements you may have.
1633
1634.. _topics-testing-test_runner:
1635
1636Defining a test runner
1637----------------------
1638
1639.. versionchanged:: 1.2
1640   Prior to 1.2, test runners were a single function, not a class.
1641
1642.. currentmodule:: django.test.simple
1643
1644A test runner is a class defining a ``run_tests()`` method. Django ships
1645with a ``DjangoTestSuiteRunner`` class that defines the default Django
1646testing behavior. This class defines the ``run_tests()`` entry point,
1647plus a selection of other methods that are used to by ``run_tests()`` to
1648set up, execute and tear down the test suite.
1649
1650.. class:: DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=True, **kwargs)
1651
1652    ``verbosity`` determines the amount of notification and debug information
1653    that will be printed to the console; ``0`` is no output, ``1`` is normal
1654    output, and ``2`` is verbose output.
1655
1656    If ``interactive`` is ``True``, the test suite has permission to ask the
1657    user for instructions when the test suite is executed. An example of this
1658    behavior would be asking for permission to delete an existing test
1659    database. If ``interactive`` is ``False``, the test suite must be able to
1660    run without any manual intervention.
1661
1662    If ``failfast`` is ``True``, the test suite will stop running after the
1663    first test failure is detected.
1664
1665    Django will, from time to time, extend the capabilities of
1666    the test runner by adding new arguments. The ``**kwargs`` declaration
1667    allows for this expansion. If you subclass ``DjangoTestSuiteRunner`` or
1668    write your own test runner, ensure accept and handle the ``**kwargs``
1669    parameter.
1670
1671.. method:: DjangoTestSuiteRunner.run_tests(test_labels, extra_tests=None, **kwargs)
1672
1673    Run the test suite.
1674
1675    ``test_labels`` is a list of strings describing the tests to be run. A test
1676    label can take one of three forms:
1677
1678        * ``app.TestCase.test_method`` -- Run a single test method in a test
1679          case.
1680        * ``app.TestCase`` -- Run all the test methods in a test case.
1681        * ``app`` -- Search for and run all tests in the named application.
1682
1683    If ``test_labels`` has a value of ``None``, the test runner should run
1684    search for tests in all the applications in :setting:`INSTALLED_APPS`.
1685
1686    ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
1687    suite that is executed by the test runner. These extra tests are run
1688    in addition to those discovered in the modules listed in ``test_labels``.
1689
1690    This method should return the number of tests that failed.
1691
1692.. method:: DjangoTestSuiteRunner.setup_test_environment(**kwargs)
1693
1694    Sets up the test environment ready for testing.
1695
1696.. method:: DjangoTestSuiteRunner.build_suite(test_labels, extra_tests=None, **kwargs)
1697
1698    Constructs a test suite that matches the test labels provided.
1699
1700    ``test_labels`` is a list of strings describing the tests to be run. A test
1701    label can take one of three forms:
1702
1703        * ``app.TestCase.test_method`` -- Run a single test method in a test
1704          case.
1705        * ``app.TestCase`` -- Run all the test methods in a test case.
1706        * ``app`` -- Search for and run all tests in the named application.
1707
1708    If ``test_labels`` has a value of ``None``, the test runner should run
1709    search for tests in all the applications in :setting:`INSTALLED_APPS`.
1710
1711    ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
1712    suite that is executed by the test runner. These extra tests are run
1713    in addition to those discovered in the modules listed in ``test_labels``.
1714
1715    Returns a ``TestSuite`` instance ready to be run.
1716
1717.. method:: DjangoTestSuiteRunner.setup_databases(**kwargs)
1718
1719    Creates the test databases.
1720
1721    Returns a data structure that provides enough detail to undo the changes
1722    that have been made. This data will be provided to the ``teardown_databases()``
1723    function at the conclusion of testing.
1724
1725.. method:: DjangoTestSuiteRunner.run_suite(suite, **kwargs)
1726
1727    Runs the test suite.
1728
1729    Returns the result produced by the running the test suite.
1730
1731.. method:: DjangoTestSuiteRunner.teardown_databases(old_config, **kwargs)
1732
1733    Destroys the test databases, restoring pre-test conditions.
1734
1735    ``old_config`` is a data structure defining the changes in the
1736    database configuration that need to be reversed. It is the return
1737    value of the ``setup_databases()`` method.
1738
1739.. method:: DjangoTestSuiteRunner.teardown_test_environment(**kwargs)
1740
1741    Restores the pre-test environment.
1742
1743.. method:: DjangoTestSuiteRunner.suite_result(suite, result, **kwargs)
1744
1745    Computes and returns a return code based on a test suite, and the result
1746    from that test suite.
1747
1748
1749Testing utilities
1750-----------------
1751
1752.. module:: django.test.utils
1753   :synopsis: Helpers to write custom test runners.
1754
1755To assist in the creation of your own test runner, Django provides a number of
1756utility methods in the ``django.test.utils`` module.
1757
1758.. function:: setup_test_environment()
1759
1760    Performs any global pre-test setup, such as the installing the
1761    instrumentation of the template rendering system and setting up
1762    the dummy ``SMTPConnection``.
1763
1764.. function:: teardown_test_environment()
1765
1766    Performs any global post-test teardown, such as removing the black
1767    magic hooks into the template system and restoring normal e-mail
1768    services.
1769
1770The creation module of the database backend (``connection.creation``)
1771also provides some utilities that can be useful during testing.
1772
1773.. function:: create_test_db(verbosity=1, autoclobber=False)
1774
1775    Creates a new test database and runs ``syncdb`` against it.
1776
1777    ``verbosity`` has the same behavior as in ``run_tests()``.
1778
1779    ``autoclobber`` describes the behavior that will occur if a
1780    database with the same name as the test database is discovered:
1781
1782        * If ``autoclobber`` is ``False``, the user will be asked to
1783          approve destroying the existing database. ``sys.exit`` is
1784          called if the user does not approve.
1785
1786        * If autoclobber is ``True``, the database will be destroyed
1787          without consulting the user.
1788
1789    Returns the name of the test database that it created.
1790
1791    ``create_test_db()`` has the side effect of modifying the value of
1792    :setting:`NAME` in :setting:`DATABASES` to match the name of the test
1793    database.
1794
1795.. function:: destroy_test_db(old_database_name, verbosity=1)
1796
1797    Destroys the database whose name is in stored in :setting:`NAME` in the
1798    :setting:`DATABASES`, and sets :setting:`NAME` to use the
1799    provided name.
1800
1801    ``verbosity`` has the same behavior as in ``run_tests()``.