PageRenderTime 204ms CodeModel.GetById 120ms app.highlight 9ms RepoModel.GetById 32ms app.codeStats 6ms

/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

Large files files are truncated, but you can click here to view the full 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>` com…

Large files files are truncated, but you can click here to view the full file