<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Testing Django applications — Django 1.5.8 documentation</title> <link rel="stylesheet" href="../../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../', VERSION: '1.5.8', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <link rel="top" title="Django 1.5.8 documentation" href="../../index.html" /> <link rel="up" title="Testing in Django" href="index.html" /> <link rel="next" title="Django and doctests" href="doctests.html" /> <link rel="prev" title="Testing in Django" href="index.html" /> <script type="text/javascript" src="../../templatebuiltins.js"></script> <script type="text/javascript"> (function($) { if (!django_template_builtins) { // templatebuiltins.js missing, do nothing. return; } $(document).ready(function() { // Hyperlink Django template tags and filters var base = "../../ref/templates/builtins.html"; if (base == "#") { // Special case for builtins.html itself base = ""; } // Tags are keywords, class '.k' $("div.highlight\\-html\\+django span.k").each(function(i, elem) { var tagname = $(elem).text(); if ($.inArray(tagname, django_template_builtins.ttags) != -1) { var fragment = tagname.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>"); } }); // Filters are functions, class '.nf' $("div.highlight\\-html\\+django span.nf").each(function(i, elem) { var filtername = $(elem).text(); if ($.inArray(filtername, django_template_builtins.tfilters) != -1) { var fragment = filtername.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>"); } }); }); })(jQuery); </script> </head> <body> <div class="document"> <div id="custom-doc" class="yui-t6"> <div id="hd"> <h1><a href="../../index.html">Django 1.5.8 documentation</a></h1> <div id="global-nav"> <a title="Home page" href="../../index.html">Home</a> | <a title="Table of contents" href="../../contents.html">Table of contents</a> | <a title="Global index" href="../../genindex.html">Index</a> | <a title="Module index" href="../../py-modindex.html">Modules</a> </div> <div class="nav"> « <a href="index.html" title="Testing in Django">previous</a> | <a href="../index.html" title="Using Django" accesskey="U">up</a> | <a href="doctests.html" title="Django and doctests">next</a> »</div> </div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> <div class="yui-g" id="topics-testing-overview"> <div class="section" id="s-module-django.test"> <span id="s-testing-django-applications"></span><span id="module-django.test"></span><span id="testing-django-applications"></span><h1>Testing Django applications<a class="headerlink" href="#module-django.test" title="Permalink to this headline">¶</a></h1> <div class="admonition-see-also admonition seealso"> <p class="first admonition-title">See also</p> <p class="last">The <a class="reference internal" href="../../intro/tutorial05.html"><em>testing tutorial</em></a> and the <a class="reference internal" href="advanced.html"><em>advanced testing topics</em></a>.</p> </div> <p>This document is split into two primary sections. First, we explain how to write tests with Django. Then, we explain how to run them.</p> <div class="section" id="s-writing-tests"> <span id="writing-tests"></span><h2>Writing tests<a class="headerlink" href="#writing-tests" title="Permalink to this headline">¶</a></h2> <p>Django’s unit tests use a Python standard library module: <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest" title="(in Python v2.7)"><tt class="xref py py-mod docutils literal"><span class="pre">unittest</span></tt></a>. This module defines tests in class-based approach.</p> <div class="admonition-unittest2 admonition"> <p class="first admonition-title">unittest2</p> <p>Python 2.7 introduced some major changes to the unittest library, adding some extremely useful features. To ensure that every Django project can benefit from these new features, Django ships with a copy of <a class="reference external" href="http://pypi.python.org/pypi/unittest2">unittest2</a>, a copy of the Python 2.7 unittest library, backported for Python 2.5 compatibility.</p> <p>To access this library, Django provides the <tt class="docutils literal"><span class="pre">django.utils.unittest</span></tt> module alias. If you are using Python 2.7, or you have installed unittest2 locally, Django will map the alias to the installed version of the unittest library. Otherwise, Django will use its own bundled version of unittest2.</p> <p>To use this alias, simply use:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">unittest</span> </pre></div> </div> <p>wherever you would have historically used:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">unittest</span> </pre></div> </div> <p class="last">If you want to continue to use the base unittest library, you can – you just won’t get any of the nice new unittest2 features.</p> </div> <p>For a given Django application, the test runner looks for unit tests in two places:</p> <ul class="simple"> <li>The <tt class="docutils literal"><span class="pre">models.py</span></tt> file. The test runner looks for any subclass of <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase" title="(in Python v2.7)"><tt class="xref py py-class docutils literal"><span class="pre">unittest.TestCase</span></tt></a> in this module.</li> <li>A file called <tt class="docutils literal"><span class="pre">tests.py</span></tt> in the application directory – i.e., the directory that holds <tt class="docutils literal"><span class="pre">models.py</span></tt>. Again, the test runner looks for any subclass of <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase" title="(in Python v2.7)"><tt class="xref py py-class docutils literal"><span class="pre">unittest.TestCase</span></tt></a> in this module.</li> </ul> <p>Here is an example which subclasses from <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><tt class="xref py py-class docutils literal"><span class="pre">django.test.TestCase</span></tt></a>, which is a subclass of <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase" title="(in Python v2.7)"><tt class="xref py py-class docutils literal"><span class="pre">unittest.TestCase</span></tt></a> that runs each test inside a transaction to provide isolation:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span> <span class="kn">from</span> <span class="nn">myapp.models</span> <span class="kn">import</span> <span class="n">Animal</span> <span class="k">class</span> <span class="nc">AnimalTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span> <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">Animal</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">"lion"</span><span class="p">,</span> <span class="n">sound</span><span class="o">=</span><span class="s">"roar"</span><span class="p">)</span> <span class="n">Animal</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">"cat"</span><span class="p">,</span> <span class="n">sound</span><span class="o">=</span><span class="s">"meow"</span><span class="p">)</span> <span class="k">def</span> <span class="nf">test_animals_can_speak</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">"""Animals that can speak are correctly identified"""</span> <span class="n">lion</span> <span class="o">=</span> <span class="n">Animal</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">"lion"</span><span class="p">)</span> <span class="n">cat</span> <span class="o">=</span> <span class="n">Animal</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">"cat"</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">lion</span><span class="o">.</span><span class="n">speak</span><span class="p">(),</span> <span class="s">'The lion says "roar"'</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">cat</span><span class="o">.</span><span class="n">speak</span><span class="p">(),</span> <span class="s">'The cat says "meow"'</span><span class="p">)</span> </pre></div> </div> <p>When you <a class="reference internal" href="#running-tests"><em>run your tests</em></a>, the default behavior of the test utility is to find all the test cases (that is, subclasses of <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase" title="(in Python v2.7)"><tt class="xref py py-class docutils literal"><span class="pre">unittest.TestCase</span></tt></a>) in <tt class="docutils literal"><span class="pre">models.py</span></tt> and <tt class="docutils literal"><span class="pre">tests.py</span></tt>, automatically build a test suite out of those test cases, and run that suite.</p> <p>There is a second way to define the test suite for a module: if you define a function called <tt class="docutils literal"><span class="pre">suite()</span></tt> in either <tt class="docutils literal"><span class="pre">models.py</span></tt> or <tt class="docutils literal"><span class="pre">tests.py</span></tt>, the Django test runner will use that function to construct the test suite for that module. This follows the <a class="reference external" href="http://docs.python.org/library/unittest.html#organizing-tests">suggested organization</a> for unit tests. See the Python documentation for more details on how to construct a complex test suite.</p> <p>For more details about <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest" title="(in Python v2.7)"><tt class="xref py py-mod docutils literal"><span class="pre">unittest</span></tt></a>, see the Python documentation.</p> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p>If your tests rely on database access such as creating or querying models, be sure to create your test classes as subclasses of <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><tt class="xref py py-class docutils literal"><span class="pre">django.test.TestCase</span></tt></a> rather than <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase" title="(in Python v2.7)"><tt class="xref py py-class docutils literal"><span class="pre">unittest.TestCase</span></tt></a>.</p> <p class="last">Using <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase" title="(in Python v2.7)"><tt class="xref py py-class docutils literal"><span class="pre">unittest.TestCase</span></tt></a> avoids the cost of running each test in a transaction and flushing the database, but if your tests interact with the database their behavior will vary based on the order that the test runner executes them. This can lead to unit tests that pass when run in isolation but fail when run in a suite.</p> </div> </div> <div class="section" id="s-running-tests"> <span id="s-id1"></span><span id="running-tests"></span><span id="id1"></span><h2>Running tests<a class="headerlink" href="#running-tests" title="Permalink to this headline">¶</a></h2> <p>Once you’ve written tests, run them using the <a class="reference internal" href="../../ref/django-admin.html#django-admin-test"><tt class="xref std std-djadmin docutils literal"><span class="pre">test</span></tt></a> command of your project’s <tt class="docutils literal"><span class="pre">manage.py</span></tt> utility:</p> <div class="highlight-python"><pre>$ ./manage.py test</pre> </div> <p>By default, this will run every test in every application in <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a>. If you only want to run tests for a particular application, add the application name to the command line. For example, if your <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> contains <tt class="docutils literal"><span class="pre">'myproject.polls'</span></tt> and <tt class="docutils literal"><span class="pre">'myproject.animals'</span></tt>, you can run the <tt class="docutils literal"><span class="pre">myproject.animals</span></tt> unit tests alone with this command:</p> <div class="highlight-python"><pre>$ ./manage.py test animals</pre> </div> <p>Note that we used <tt class="docutils literal"><span class="pre">animals</span></tt>, not <tt class="docutils literal"><span class="pre">myproject.animals</span></tt>.</p> <p>You can be even <em>more</em> specific by naming an individual test case. To run a single test case in an application (for example, the <tt class="docutils literal"><span class="pre">AnimalTestCase</span></tt> described in the “Writing unit tests” section), add the name of the test case to the label on the command line:</p> <div class="highlight-python"><pre>$ ./manage.py test animals.AnimalTestCase</pre> </div> <p>And it gets even more granular than that! To run a <em>single</em> test method inside a test case, add the name of the test method to the label:</p> <div class="highlight-python"><pre>$ ./manage.py test animals.AnimalTestCase.test_animals_can_speak</pre> </div> <p>You can use the same rules if you’re using doctests. Django will use the test label as a path to the test method or class that you want to run. If your <tt class="docutils literal"><span class="pre">models.py</span></tt> or <tt class="docutils literal"><span class="pre">tests.py</span></tt> has a function with a doctest, or class with a class-level doctest, you can invoke that test by appending the name of the test method or class to the label:</p> <div class="highlight-python"><pre>$ ./manage.py test animals.classify</pre> </div> <p>If you want to run the doctest for a specific method in a class, add the name of the method to the label:</p> <div class="highlight-python"><pre>$ ./manage.py test animals.Classifier.run</pre> </div> <p>If you’re using a <tt class="docutils literal"><span class="pre">__test__</span></tt> dictionary to specify doctests for a module, Django will use the label as a key in the <tt class="docutils literal"><span class="pre">__test__</span></tt> dictionary for defined in <tt class="docutils literal"><span class="pre">models.py</span></tt> and <tt class="docutils literal"><span class="pre">tests.py</span></tt>.</p> <p>If you press <tt class="docutils literal"><span class="pre">Ctrl-C</span></tt> while the tests are running, the test runner will wait for the currently running test to complete and then exit gracefully. During a graceful exit the test runner will output details of any test failures, report on how many tests were run and how many errors and failures were encountered, and destroy any test databases as usual. Thus pressing <tt class="docutils literal"><span class="pre">Ctrl-C</span></tt> can be very useful if you forget to pass the <a class="reference internal" href="../../ref/django-admin.html#django-admin-option---failfast"><tt class="xref std std-djadminopt docutils literal"><span class="pre">--failfast</span></tt></a> option, notice that some tests are unexpectedly failing, and want to get details on the failures without waiting for the full test run to complete.</p> <p>If you do not want to wait for the currently running test to finish, you can press <tt class="docutils literal"><span class="pre">Ctrl-C</span></tt> a second time and the test run will halt immediately, but not gracefully. No details of the tests run before the interruption will be reported, and any test databases created by the run will not be destroyed.</p> <div class="admonition-test-with-warnings-enabled admonition"> <p class="first admonition-title">Test with warnings enabled</p> <p class="last">It’s a good idea to run your tests with Python warnings enabled: <tt class="docutils literal"><span class="pre">python</span> <span class="pre">-Wall</span> <span class="pre">manage.py</span> <span class="pre">test</span></tt>. The <tt class="docutils literal"><span class="pre">-Wall</span></tt> flag tells Python to display deprecation warnings. Django, like many other Python libraries, uses these warnings to flag when features are going away. It also might flag areas in your code that aren’t strictly wrong but could benefit from a better implementation.</p> </div> <div class="section" id="s-the-test-database"> <span id="s-id2"></span><span id="the-test-database"></span><span id="id2"></span><h3>The test database<a class="headerlink" href="#the-test-database" title="Permalink to this headline">¶</a></h3> <p>Tests that require a database (namely, model tests) will not use your “real” (production) database. Separate, blank databases are created for the tests.</p> <p>Regardless of whether the tests pass or fail, the test databases are destroyed when all the tests have been executed.</p> <p>By default the test databases get their names by prepending <tt class="docutils literal"><span class="pre">test_</span></tt> to the value of the <a class="reference internal" href="../../ref/settings.html#std:setting-NAME"><tt class="xref std std-setting docutils literal"><span class="pre">NAME</span></tt></a> settings for the databases defined in <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASES"><tt class="xref std std-setting docutils literal"><span class="pre">DATABASES</span></tt></a>. When using the SQLite database engine the tests will by default use an in-memory database (i.e., the database will be created in memory, bypassing the filesystem entirely!). If you want to use a different database name, specify <a class="reference internal" href="../../ref/settings.html#std:setting-TEST_NAME"><tt class="xref std std-setting docutils literal"><span class="pre">TEST_NAME</span></tt></a> in the dictionary for any given database in <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASES"><tt class="xref std std-setting docutils literal"><span class="pre">DATABASES</span></tt></a>.</p> <p>Aside from using a separate database, the test runner will otherwise use all of the same database settings you have in your settings file: <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ENGINE"><tt class="xref std std-setting docutils literal"><span class="pre">ENGINE</span></tt></a>, <a class="reference internal" href="../../ref/settings.html#std:setting-USER"><tt class="xref std std-setting docutils literal"><span class="pre">USER</span></tt></a>, <a class="reference internal" href="../../ref/settings.html#std:setting-HOST"><tt class="xref std std-setting docutils literal"><span class="pre">HOST</span></tt></a>, etc. The test database is created by the user specified by <a class="reference internal" href="../../ref/settings.html#std:setting-USER"><tt class="xref std std-setting docutils literal"><span class="pre">USER</span></tt></a>, so you’ll need to make sure that the given user account has sufficient privileges to create a new database on the system.</p> <p>For fine-grained control over the character encoding of your test database, use the <a class="reference internal" href="../../ref/settings.html#std:setting-TEST_CHARSET"><tt class="xref std std-setting docutils literal"><span class="pre">TEST_CHARSET</span></tt></a> option. If you’re using MySQL, you can also use the <a class="reference internal" href="../../ref/settings.html#std:setting-TEST_COLLATION"><tt class="xref std std-setting docutils literal"><span class="pre">TEST_COLLATION</span></tt></a> option to control the particular collation used by the test database. See the <a class="reference internal" href="../../ref/settings.html"><em>settings documentation</em></a> for details of these advanced settings.</p> <div class="admonition-finding-data-from-your-production-database-when-running-tests admonition"> <p class="first admonition-title">Finding data from your production database when running tests?</p> <p class="last">If your code attempts to access the database when its modules are compiled, this will occur <em>before</em> the test database is set up, with potentially unexpected results. For example, if you have a database query in module-level code and a real database exists, production data could pollute your tests. <em>It is a bad idea to have such import-time database queries in your code</em> anyway - rewrite your code so that it doesn’t do this.</p> </div> <div class="admonition-see-also admonition seealso"> <p class="first admonition-title">See also</p> <p class="last">The <a class="reference internal" href="advanced.html#topics-testing-advanced-multidb"><em>advanced multi-db testing topics</em></a>.</p> </div> </div> <div class="section" id="s-order-in-which-tests-are-executed"> <span id="order-in-which-tests-are-executed"></span><h3>Order in which tests are executed<a class="headerlink" href="#order-in-which-tests-are-executed" title="Permalink to this headline">¶</a></h3> <p>In order to guarantee that all <tt class="docutils literal"><span class="pre">TestCase</span></tt> code starts with a clean database, the Django test runner reorders tests in the following way:</p> <ul class="simple"> <li>First, all unittests (including <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase" title="(in Python v2.7)"><tt class="xref py py-class docutils literal"><span class="pre">unittest.TestCase</span></tt></a>, <a class="reference internal" href="#django.test.SimpleTestCase" title="django.test.SimpleTestCase"><tt class="xref py py-class docutils literal"><span class="pre">SimpleTestCase</span></tt></a>, <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><tt class="xref py py-class docutils literal"><span class="pre">TestCase</span></tt></a> and <a class="reference internal" href="#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><tt class="xref py py-class docutils literal"><span class="pre">TransactionTestCase</span></tt></a>) are run with no particular ordering guaranteed nor enforced among them.</li> <li>Then any other tests (e.g. doctests) that may alter the database without restoring it to its original state are run.</li> </ul> <div class="versionchanged"> <span class="title">Changed in Django 1.5:</span> Before Django 1.5, the only guarantee was that <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><tt class="xref py py-class docutils literal"><span class="pre">TestCase</span></tt></a> tests were always ran first, before any other tests.</div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">The new ordering of tests may reveal unexpected dependencies on test case ordering. This is the case with doctests that relied on state left in the database by a given <a class="reference internal" href="#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><tt class="xref py py-class docutils literal"><span class="pre">TransactionTestCase</span></tt></a> test, they must be updated to be able to run independently.</p> </div> </div> <div class="section" id="s-other-test-conditions"> <span id="other-test-conditions"></span><h3>Other test conditions<a class="headerlink" href="#other-test-conditions" title="Permalink to this headline">¶</a></h3> <p>Regardless of the value of the <a class="reference internal" href="../../ref/settings.html#std:setting-DEBUG"><tt class="xref std std-setting docutils literal"><span class="pre">DEBUG</span></tt></a> setting in your configuration file, all Django tests run with <a class="reference internal" href="../../ref/settings.html#std:setting-DEBUG"><tt class="xref std std-setting docutils literal"><span class="pre">DEBUG</span></tt></a>=False. This is to ensure that the observed output of your code matches what will be seen in a production setting.</p> <p>Caches are not cleared after each test, and running “manage.py test fooapp” can insert data from the tests into the cache of a live system if you run your tests in production because, unlike databases, a separate “test cache” is not used. This behavior <a class="reference external" href="https://code.djangoproject.com/ticket/11505">may change</a> in the future.</p> </div> <div class="section" id="s-understanding-the-test-output"> <span id="understanding-the-test-output"></span><h3>Understanding the test output<a class="headerlink" href="#understanding-the-test-output" title="Permalink to this headline">¶</a></h3> <p>When you run your tests, you’ll see a number of messages as the test runner prepares itself. You can control the level of detail of these messages with the <tt class="docutils literal"><span class="pre">verbosity</span></tt> option on the command line:</p> <div class="highlight-python"><pre>Creating test database... Creating table myapp_animal Creating table myapp_mineral Loading 'initial_data' fixtures... No fixtures found.</pre> </div> <p>This tells you that the test runner is creating a test database, as described in the previous section.</p> <p>Once the test database has been created, Django will run your tests. If everything goes well, you’ll see something like this:</p> <div class="highlight-python"><pre>---------------------------------------------------------------------- Ran 22 tests in 0.221s OK</pre> </div> <p>If there are test failures, however, you’ll see full details about which tests failed:</p> <div class="highlight-python"><pre>====================================================================== FAIL: Doctest: ellington.core.throttle.models ---------------------------------------------------------------------- Traceback (most recent call last): File "/dev/django/test/doctest.py", line 2153, in runTest raise self.failureException(self.format_failure(new.getvalue())) AssertionError: Failed doctest test for myapp.models File "/dev/myapp/models.py", line 0, in models ---------------------------------------------------------------------- File "/dev/myapp/models.py", line 14, in myapp.models Failed example: throttle.check("actor A", "action one", limit=2, hours=1) Expected: True Got: False ---------------------------------------------------------------------- Ran 2 tests in 0.048s FAILED (failures=1)</pre> </div> <p>A full explanation of this error output is beyond the scope of this document, but it’s pretty intuitive. You can consult the documentation of Python’s <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest" title="(in Python v2.7)"><tt class="xref py py-mod docutils literal"><span class="pre">unittest</span></tt></a> library for details.</p> <p>Note that the return code for the test-runner script is 1 for any number of failed and erroneous tests. If all the tests pass, the return code is 0. This feature is useful if you’re using the test-runner script in a shell script and need to test for success or failure at that level.</p> </div> <div class="section" id="s-speeding-up-the-tests"> <span id="speeding-up-the-tests"></span><h3>Speeding up the tests<a class="headerlink" href="#speeding-up-the-tests" title="Permalink to this headline">¶</a></h3> <p>In recent versions of Django, the default password hasher is rather slow by design. If during your tests you are authenticating many users, you may want to use a custom settings file and set the <a class="reference internal" href="../../ref/settings.html#std:setting-PASSWORD_HASHERS"><tt class="xref std std-setting docutils literal"><span class="pre">PASSWORD_HASHERS</span></tt></a> setting to a faster hashing algorithm:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">PASSWORD_HASHERS</span> <span class="o">=</span> <span class="p">(</span> <span class="s">'django.contrib.auth.hashers.MD5PasswordHasher'</span><span class="p">,</span> <span class="p">)</span> </pre></div> </div> <p>Don’t forget to also include in <a class="reference internal" href="../../ref/settings.html#std:setting-PASSWORD_HASHERS"><tt class="xref std std-setting docutils literal"><span class="pre">PASSWORD_HASHERS</span></tt></a> any hashing algorithm used in fixtures, if any.</p> </div> </div> <div class="section" id="s-testing-tools"> <span id="testing-tools"></span><h2>Testing tools<a class="headerlink" href="#testing-tools" title="Permalink to this headline">¶</a></h2> <p>Django provides a small set of tools that come in handy when writing tests.</p> <div class="section" id="s-module-django.test.client"> <span id="s-the-test-client"></span><span id="s-test-client"></span><span id="module-django.test.client"></span><span id="the-test-client"></span><span id="test-client"></span><h3>The test client<a class="headerlink" href="#module-django.test.client" title="Permalink to this headline">¶</a></h3> <p>The test client is a Python class that acts as a dummy Web browser, allowing you to test your views and interact with your Django-powered application programmatically.</p> <p>Some of the things you can do with the test client are:</p> <ul class="simple"> <li>Simulate GET and POST requests on a URL and observe the response – everything from low-level HTTP (result headers and status codes) to page content.</li> <li>See the chain of redirects (if any) and check the URL and status code at each step.</li> <li>Test that a given request is rendered by a given Django template, with a template context that contains certain values.</li> </ul> <p>Note that the test client is not intended to be a replacement for <a class="reference external" href="http://seleniumhq.org/">Selenium</a> or other “in-browser” frameworks. Django’s test client has a different focus. In short:</p> <ul class="simple"> <li>Use Django’s test client to establish that the correct template is being rendered and that the template is passed the correct context data.</li> <li>Use in-browser frameworks like <a class="reference external" href="http://seleniumhq.org/">Selenium</a> to test <em>rendered</em> HTML and the <em>behavior</em> of Web pages, namely JavaScript functionality. Django also provides special support for those frameworks; see the section on <a class="reference internal" href="#django.test.LiveServerTestCase" title="django.test.LiveServerTestCase"><tt class="xref py py-class docutils literal"><span class="pre">LiveServerTestCase</span></tt></a> for more details.</li> </ul> <p>A comprehensive test suite should use a combination of both test types.</p> <div class="section" id="s-overview-and-a-quick-example"> <span id="overview-and-a-quick-example"></span><h4>Overview and a quick example<a class="headerlink" href="#overview-and-a-quick-example" title="Permalink to this headline">¶</a></h4> <p>To use the test client, instantiate <tt class="docutils literal"><span class="pre">django.test.client.Client</span></tt> and retrieve Web pages:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">django.test.client</span> <span class="kn">import</span> <span class="n">Client</span> <span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">'/login/'</span><span class="p">,</span> <span class="p">{</span><span class="s">'username'</span><span class="p">:</span> <span class="s">'john'</span><span class="p">,</span> <span class="s">'password'</span><span class="p">:</span> <span class="s">'smith'</span><span class="p">})</span> <span class="gp">>>> </span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span> <span class="go">200</span> <span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customer/details/'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">response</span><span class="o">.</span><span class="n">content</span> <span class="go">'<!DOCTYPE html...'</span> </pre></div> </div> <p>As this example suggests, you can instantiate <tt class="docutils literal"><span class="pre">Client</span></tt> from within a session of the Python interactive interpreter.</p> <p>Note a few important things about how the test client works:</p> <ul> <li><p class="first">The test client does <em>not</em> require the Web server to be running. In fact, it will run just fine with no Web server running at all! That’s because it avoids the overhead of HTTP and deals directly with the Django framework. This helps make the unit tests run quickly.</p> </li> <li><p class="first">When retrieving pages, remember to specify the <em>path</em> of the URL, not the whole domain. For example, this is correct:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/login/'</span><span class="p">)</span> </pre></div> </div> <p>This is incorrect:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'http://www.example.com/login/'</span><span class="p">)</span> </pre></div> </div> <p>The test client is not capable of retrieving Web pages that are not powered by your Django project. If you need to retrieve other Web pages, use a Python standard library module such as <a class="reference external" href="http://docs.python.org/2.7/library/urllib.html#urllib" title="(in Python v2.7)"><tt class="xref py py-mod docutils literal"><span class="pre">urllib</span></tt></a> or <a class="reference external" href="http://docs.python.org/2.7/library/urllib2.html#urllib2" title="(in Python v2.7)"><tt class="xref py py-mod docutils literal"><span class="pre">urllib2</span></tt></a>.</p> </li> <li><p class="first">To resolve URLs, the test client uses whatever URLconf is pointed-to by your <a class="reference internal" href="../../ref/settings.html#std:setting-ROOT_URLCONF"><tt class="xref std std-setting docutils literal"><span class="pre">ROOT_URLCONF</span></tt></a> setting.</p> </li> <li><p class="first">Although the above example would work in the Python interactive interpreter, some of the test client’s functionality, notably the template-related functionality, is only available <em>while tests are running</em>.</p> <p>The reason for this is that Django’s test runner performs a bit of black magic in order to determine which template was loaded by a given view. This black magic (essentially a patching of Django’s template system in memory) only happens during test running.</p> </li> <li><p class="first">By default, the test client will disable any CSRF checks performed by your site.</p> <p>If, for some reason, you <em>want</em> the test client to perform CSRF checks, you can create an instance of the test client that enforces CSRF checks. To do this, pass in the <tt class="docutils literal"><span class="pre">enforce_csrf_checks</span></tt> argument when you construct your client:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">Client</span> <span class="gp">>>> </span><span class="n">csrf_client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">(</span><span class="n">enforce_csrf_checks</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> </pre></div> </div> </li> </ul> </div> <div class="section" id="s-making-requests"> <span id="making-requests"></span><h4>Making requests<a class="headerlink" href="#making-requests" title="Permalink to this headline">¶</a></h4> <p>Use the <tt class="docutils literal"><span class="pre">django.test.client.Client</span></tt> class to make requests.</p> <dl class="class"> <dt id="django.test.client.Client"> <em class="property">class </em><tt class="descname">Client</tt>(<em>enforce_csrf_checks=False</em>, <em>**defaults</em>)<a class="headerlink" href="#django.test.client.Client" title="Permalink to this definition">¶</a></dt> <dd><p>It requires no arguments at time of construction. However, you can use keywords arguments to specify some default headers. For example, this will send a <tt class="docutils literal"><span class="pre">User-Agent</span></tt> HTTP header in each request:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">(</span><span class="n">HTTP_USER_AGENT</span><span class="o">=</span><span class="s">'Mozilla/5.0'</span><span class="p">)</span> </pre></div> </div> <p>The values from the <tt class="docutils literal"><span class="pre">extra</span></tt> keywords arguments passed to <a class="reference internal" href="#django.test.client.Client.get" title="django.test.client.Client.get"><tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt></a>, <a class="reference internal" href="#django.test.client.Client.post" title="django.test.client.Client.post"><tt class="xref py py-meth docutils literal"><span class="pre">post()</span></tt></a>, etc. have precedence over the defaults passed to the class constructor.</p> <p>The <tt class="docutils literal"><span class="pre">enforce_csrf_checks</span></tt> argument can be used to test CSRF protection (see above).</p> <p>Once you have a <tt class="docutils literal"><span class="pre">Client</span></tt> instance, you can call any of the following methods:</p> <dl class="method"> <dt id="django.test.client.Client.get"> <tt class="descname">get</tt>(<em>path</em>, <em>data={}</em>, <em>follow=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.client.Client.get" title="Permalink to this definition">¶</a></dt> <dd><p>Makes a GET request on the provided <tt class="docutils literal"><span class="pre">path</span></tt> and returns a <tt class="docutils literal"><span class="pre">Response</span></tt> object, which is documented below.</p> <p>The key-value pairs in the <tt class="docutils literal"><span class="pre">data</span></tt> dictionary are used to create a GET data payload. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customers/details/'</span><span class="p">,</span> <span class="p">{</span><span class="s">'name'</span><span class="p">:</span> <span class="s">'fred'</span><span class="p">,</span> <span class="s">'age'</span><span class="p">:</span> <span class="mi">7</span><span class="p">})</span> </pre></div> </div> <p>...will result in the evaluation of a GET request equivalent to:</p> <div class="highlight-python"><pre>/customers/details/?name=fred&age=7</pre> </div> <p>The <tt class="docutils literal"><span class="pre">extra</span></tt> keyword arguments parameter can be used to specify headers to be sent in the request. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customers/details/'</span><span class="p">,</span> <span class="p">{</span><span class="s">'name'</span><span class="p">:</span> <span class="s">'fred'</span><span class="p">,</span> <span class="s">'age'</span><span class="p">:</span> <span class="mi">7</span><span class="p">},</span> <span class="gp">... </span> <span class="n">HTTP_X_REQUESTED_WITH</span><span class="o">=</span><span class="s">'XMLHttpRequest'</span><span class="p">)</span> </pre></div> </div> <p>...will send the HTTP header <tt class="docutils literal"><span class="pre">HTTP_X_REQUESTED_WITH</span></tt> to the details view, which is a good way to test code paths that use the <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.is_ajax" title="django.http.HttpRequest.is_ajax"><tt class="xref py py-meth docutils literal"><span class="pre">django.http.HttpRequest.is_ajax()</span></tt></a> method.</p> <div class="admonition-cgi-specification admonition"> <p class="first admonition-title">CGI specification</p> <p class="last">The headers sent via <tt class="docutils literal"><span class="pre">**extra</span></tt> should follow <a class="reference external" href="http://www.w3.org/CGI/">CGI</a> specification. For example, emulating a different “Host” header as sent in the HTTP request from the browser to the server should be passed as <tt class="docutils literal"><span class="pre">HTTP_HOST</span></tt>.</p> </div> <p>If you already have the GET arguments in URL-encoded form, you can use that encoding instead of using the data argument. For example, the previous GET request could also be posed as:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customers/details/?name=fred&age=7'</span><span class="p">)</span> </pre></div> </div> <p>If you provide a URL with both an encoded GET data and a data argument, the data argument will take precedence.</p> <p>If you set <tt class="docutils literal"><span class="pre">follow</span></tt> to <tt class="docutils literal"><span class="pre">True</span></tt> the client will follow any redirects and a <tt class="docutils literal"><span class="pre">redirect_chain</span></tt> attribute will be set in the response object containing tuples of the intermediate urls and status codes.</p> <p>If you had a URL <tt class="docutils literal"><span class="pre">/redirect_me/</span></tt> that redirected to <tt class="docutils literal"><span class="pre">/next/</span></tt>, that redirected to <tt class="docutils literal"><span class="pre">/final/</span></tt>, this is what you’d see:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/redirect_me/'</span><span class="p">,</span> <span class="n">follow</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">response</span><span class="o">.</span><span class="n">redirect_chain</span> <span class="go">[(u'http://testserver/next/', 302), (u'http://testserver/final/', 302)]</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.test.client.Client.post"> <tt class="descname">post</tt>(<em>path</em>, <em>data={}</em>, <em>content_type=MULTIPART_CONTENT</em>, <em>follow=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.client.Client.post" title="Permalink to this definition">¶</a></dt> <dd><p>Makes a POST request on the provided <tt class="docutils literal"><span class="pre">path</span></tt> and returns a <tt class="docutils literal"><span class="pre">Response</span></tt> object, which is documented below.</p> <p>The key-value pairs in the <tt class="docutils literal"><span class="pre">data</span></tt> dictionary are used to submit POST data. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">'/login/'</span><span class="p">,</span> <span class="p">{</span><span class="s">'name'</span><span class="p">:</span> <span class="s">'fred'</span><span class="p">,</span> <span class="s">'passwd'</span><span class="p">:</span> <span class="s">'secret'</span><span class="p">})</span> </pre></div> </div> <p>...will result in the evaluation of a POST request to this URL:</p> <div class="highlight-python"><pre>/login/</pre> </div> <p>...with this POST data:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">name</span><span class="o">=</span><span class="n">fred</span><span class="o">&</span><span class="n">passwd</span><span class="o">=</span><span class="n">secret</span> </pre></div> </div> <p>If you provide <tt class="docutils literal"><span class="pre">content_type</span></tt> (e.g. <em class="mimetype">text/xml</em> for an XML payload), the contents of <tt class="docutils literal"><span class="pre">data</span></tt> will be sent as-is in the POST request, using <tt class="docutils literal"><span class="pre">content_type</span></tt> in the HTTP <tt class="docutils literal"><span class="pre">Content-Type</span></tt> header.</p> <p>If you don’t provide a value for <tt class="docutils literal"><span class="pre">content_type</span></tt>, the values in <tt class="docutils literal"><span class="pre">data</span></tt> will be transmitted with a content type of <em class="mimetype">multipart/form-data</em>. In this case, the key-value pairs in <tt class="docutils literal"><span class="pre">data</span></tt> will be encoded as a multipart message and used to create the POST data payload.</p> <p>To submit multiple values for a given key – for example, to specify the selections for a <tt class="docutils literal"><span class="pre"><select</span> <span class="pre">multiple></span></tt> – provide the values as a list or tuple for the required key. For example, this value of <tt class="docutils literal"><span class="pre">data</span></tt> would submit three selected values for the field named <tt class="docutils literal"><span class="pre">choices</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="p">{</span><span class="s">'choices'</span><span class="p">:</span> <span class="p">(</span><span class="s">'a'</span><span class="p">,</span> <span class="s">'b'</span><span class="p">,</span> <span class="s">'d'</span><span class="p">)}</span> </pre></div> </div> <p>Submitting files is a special case. To POST a file, you need only provide the file field name as a key, and a file handle to the file you wish to upload as a value. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">'wishlist.doc'</span><span class="p">)</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span> <span class="gp">... </span> <span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">'/customers/wishes/'</span><span class="p">,</span> <span class="p">{</span><span class="s">'name'</span><span class="p">:</span> <span class="s">'fred'</span><span class="p">,</span> <span class="s">'attachment'</span><span class="p">:</span> <span class="n">fp</span><span class="p">})</span> </pre></div> </div> <p>(The name <tt class="docutils literal"><span class="pre">attachment</span></tt> here is not relevant; use whatever name your file-processing code expects.)</p> <p>Note that if you wish to use the same file handle for multiple <tt class="docutils literal"><span class="pre">post()</span></tt> calls then you will need to manually reset the file pointer between posts. The easiest way to do this is to manually close the file after it has been provided to <tt class="docutils literal"><span class="pre">post()</span></tt>, as demonstrated above.</p> <p>You should also ensure that the file is opened in a way that allows the data to be read. If your file contains binary data such as an image, this means you will need to open the file in <tt class="docutils literal"><span class="pre">rb</span></tt> (read binary) mode.</p> <p>The <tt class="docutils literal"><span class="pre">extra</span></tt> argument acts the same as for <a class="reference internal" href="#django.test.client.Client.get" title="django.test.client.Client.get"><tt class="xref py py-meth docutils literal"><span class="pre">Client.get()</span></tt></a>.</p> <p>If the URL you request with a POST contains encoded parameters, these parameters will be made available in the request.GET data. For example, if you were to make the request:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">'/login/?visitor=true'</span><span class="p">,</span> <span class="p">{</span><span class="s">'name'</span><span class="p">:</span> <span class="s">'fred'</span><span class="p">,</span> <span class="s">'passwd'</span><span class="p">:</span> <span class="s">'secret'</span><span class="p">})</span> </pre></div> </div> <p>... the view handling this request could interrogate request.POST to retrieve the username and password, and could interrogate request.GET to determine if the user was a visitor.</p> <p>If you set <tt class="docutils literal"><span class="pre">follow</span></tt> to <tt class="docutils literal"><span class="pre">True</span></tt> the client will follow any redirects and a <tt class="docutils literal"><span class="pre">redirect_chain</span></tt> attribute will be set in the response object containing tuples of the intermediate urls and status codes.</p> </dd></dl> <dl class="method"> <dt id="django.test.client.Client.head"> <tt class="descname">head</tt>(<em>path</em>, <em>data={}</em>, <em>follow=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.client.Client.head" title="Permalink to this definition">¶</a></dt> <dd><p>Makes a HEAD request on the provided <tt class="docutils literal"><span class="pre">path</span></tt> and returns a <tt class="docutils literal"><span class="pre">Response</span></tt> object. This method works just like <a class="reference internal" href="#django.test.client.Client.get" title="django.test.client.Client.get"><tt class="xref py py-meth docutils literal"><span class="pre">Client.get()</span></tt></a>, including the <tt class="docutils literal"><span class="pre">follow</span></tt> and <tt class="docutils literal"><span class="pre">extra</span></tt> arguments, except it does not return a message body.</p> </dd></dl> <dl class="method"> <dt id="django.test.client.Client.options"> <tt class="descname">options</tt>(<em>path</em>, <em>data=''</em>, <em>content_type='application/octet-stream'</em>, <em>follow=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.client.Client.options" title="Permalink to this definition">¶</a></dt> <dd><p>Makes an OPTIONS request on the provided <tt class="docutils literal"><span class="pre">path</span></tt> and returns a <tt class="docutils literal"><span class="pre">Response</span></tt> object. Useful for testing RESTful interfaces.</p> <p>When <tt class="docutils literal"><span class="pre">data</span></tt> is provided, it is used as the request body, and a <tt class="docutils literal"><span class="pre">Content-Type</span></tt> header is set to <tt class="docutils literal"><span class="pre">content_type</span></tt>.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.5:</span> <a class="reference internal" href="#django.test.client.Client.options" title="django.test.client.Client.options"><tt class="xref py py-meth docutils literal"><span class="pre">Client.options()</span></tt></a> used to process <tt class="docutils literal"><span class="pre">data</span></tt> like <a class="reference internal" href="#django.test.client.Client.get" title="django.test.client.Client.get"><tt class="xref py py-meth docutils literal"><span class="pre">Client.get()</span></tt></a>.</div> <p>The <tt class="docutils literal"><span class="pre">follow</span></tt> and <tt class="docutils literal"><span class="pre">extra</span></tt> arguments act the same as for <a class="reference internal" href="#django.test.client.Client.get" title="django.test.client.Client.get"><tt class="xref py py-meth docutils literal"><span class="pre">Client.get()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="django.test.client.Client.put"> <tt class="descname">put</tt>(<em>path</em>, <em>data=''</em>, <em>content_type='application/octet-stream'</em>, <em>follow=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.client.Client.put" title="Permalink to this definition">¶</a></dt> <dd><p>Makes a PUT request on the provided <tt class="docutils literal"><span class="pre">path</span></tt> and returns a <tt class="docutils literal"><span class="pre">Response</span></tt> object. Useful for testing RESTful interfaces.</p> <p>When <tt class="docutils literal"><span class="pre">data</span></tt> is provided, it is used as the request body, and a <tt class="docutils literal"><span class="pre">Content-Type</span></tt> header is set to <tt class="docutils literal"><span class="pre">content_type</span></tt>.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.5:</span> <a class="reference internal" href="#django.test.client.Client.put" title="django.test.client.Client.put"><tt class="xref py py-meth docutils literal"><span class="pre">Client.put()</span></tt></a> used to process <tt class="docutils literal"><span class="pre">data</span></tt> like <a class="reference internal" href="#django.test.client.Client.post" title="django.test.client.Client.post"><tt class="xref py py-meth docutils literal"><span class="pre">Client.post()</span></tt></a>.</div> <p>The <tt class="docutils literal"><span class="pre">follow</span></tt> and <tt class="docutils literal"><span class="pre">extra</span></tt> arguments act the same as for <a class="reference internal" href="#django.test.client.Client.get" title="django.test.client.Client.get"><tt class="xref py py-meth docutils literal"><span class="pre">Client.get()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="django.test.client.Client.delete"> <tt class="descname">delete</tt>(<em>path</em>, <em>data=''</em>, <em>content_type='application/octet-stream'</em>, <em>follow=False</em>, <em>**extra</em>)<a class="headerlink" href="#django.test.client.Client.delete" title="Permalink to this definition">¶</a></dt> <dd><p>Makes an DELETE request on the provided <tt class="docutils literal"><span class="pre">path</span></tt> and returns a <tt class="docutils literal"><span class="pre">Response</span></tt> object. Useful for testing RESTful interfaces.</p> <p>When <tt class="docutils literal"><span class="pre">data</span></tt> is provided, it is used as the request body, and a <tt class="docutils literal"><span class="pre">Content-Type</span></tt> header is set to <tt class="docutils literal"><span class="pre">content_type</span></tt>.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.5:</span> <a class="reference internal" href="#django.test.client.Client.delete" title="django.test.client.Client.delete"><tt class="xref py py-meth docutils literal"><span class="pre">Client.delete()</span></tt></a> used to process <tt class="docutils literal"><span class="pre">data</span></tt> like <a class="reference internal" href="#django.test.client.Client.get" title="django.test.client.Client.get"><tt class="xref py py-meth docutils literal"><span class="pre">Client.get()</span></tt></a>.</div> <p>The <tt class="docutils literal"><span class="pre">follow</span></tt> and <tt class="docutils literal"><span class="pre">extra</span></tt> arguments act the same as for <a class="reference internal" href="#django.test.client.Client.get" title="django.test.client.Client.get"><tt class="xref py py-meth docutils literal"><span class="pre">Client.get()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="django.test.client.Client.login"> <tt class="descname">login</tt>(<em>**credentials</em>)<a class="headerlink" href="#django.test.client.Client.login" title="Permalink to this definition">¶</a></dt> <dd><p>If your site uses Django’s <a class="reference internal" href="../auth/index.html"><em>authentication system</em></a> and you deal with logging in users, you can use the test client’s <tt class="docutils literal"><span class="pre">login()</span></tt> method to simulate the effect of a user logging into the site.</p> <p>After you call this method, the test client will have all the cookies and session data required to pass any login-based tests that may form part of a view.</p> <p>The format of the <tt class="docutils literal"><span class="pre">credentials</span></tt> argument depends on which <a class="reference internal" href="../auth/customizing.html#authentication-backends"><em>authentication backend</em></a> you’re using (which is configured by your <a class="reference internal" href="../../ref/settings.html#std:setting-AUTHENTICATION_BACKENDS"><tt class="xref std std-setting docutils literal"><span class="pre">AUTHENTICATION_BACKENDS</span></tt></a> setting). If you’re using the standard authentication backend provided by Django (<tt class="docutils literal"><span class="pre">ModelBackend</span></tt>), <tt class="docutils literal"><span class="pre">credentials</span></tt> should be the user’s username and password, provided as keyword arguments:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">login</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s">'fred'</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">'secret'</span><span class="p">)</span> <span class="go"># Now you can access a view that's only available to logged-in users.</span> </pre></div> </div> <p>If you’re using a different authentication backend, this method may require different credentials. It requires whichever credentials are required by your backend’s <tt class="docutils literal"><span class="pre">authenticate()</span></tt> method.</p> <p><tt class="docutils literal"><span class="pre">login()</span></tt> returns <tt class="docutils literal"><span class="pre">True</span></tt> if it the credentials were accepted and login was successful.</p> <p>Finally, you’ll need to remember to create user accounts before you can use this method. As we explained above, the test runner is executed using a test database, which contains no users by default. As a result, user accounts that are valid on your production site will not work under test conditions. You’ll need to create users as part of the test suite – either manually (using the Django model API) or with a test fixture. Remember that if you want your test user to have a password, you can’t set the user’s password by setting the password attribute directly – you must use the <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.set_password" title="django.contrib.auth.models.User.set_password"><tt class="xref py py-meth docutils literal"><span class="pre">set_password()</span></tt></a> function to store a correctly hashed password. Alternatively, you can use the <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.UserManager.create_user" title="django.contrib.auth.models.UserManager.create_user"><tt class="xref py py-meth docutils literal"><span class="pre">create_user()</span></tt></a> helper method to create a new user with a correctly hashed password.</p> </dd></dl> <dl class="method"> <dt id="django.test.client.Client.logout"> <tt class="descname">logout</tt>()<a class="headerlink" href="#django.test.client.Client.logout" title="Permalink to this definition">¶</a></dt> <dd><p>If your site uses Django’s <a class="reference internal" href="../auth/index.html"><em>authentication system</em></a>, the <tt class="docutils literal"><span class="pre">logout()</span></tt> method can be used to simulate the effect of a user logging out of your site.</p> <p>After you call this method, the test client will have all the cookies and session data cleared to defaults. Subsequent requests will appear to come from an AnonymousUser.</p> </dd></dl> </dd></dl> </div> <div class="section" id="s-testing-responses"> <span id="testing-responses"></span><h4>Testing responses<a class="headerlink" href="#testing-responses" title="Permalink to this headline">¶</a></h4> <p>The <tt class="docutils literal"><span class="pre">get()</span></tt> and <tt class="docutils literal"><span class="pre">post()</span></tt> methods both return a <tt class="docutils literal"><span class="pre">Response</span></tt> object. This <tt class="docutils literal"><span class="pre">Response</span></tt> object is <em>not</em> the same as the <tt class="docutils literal"><span class="pre">HttpResponse</span></tt> object returned Django views; the test response object has some additional data useful for test code to verify.</p> <p>Specifically, a <tt class="docutils literal"><span class="pre">Response</span></tt> object has the following attributes:</p> <dl class="class"> <dt id="django.test.client.Response"> <em class="property">class </em><tt class="descname">Response</tt><a class="headerlink" href="#django.test.client.Response" title="Permalink to this definition">¶</a></dt> <dd><dl class="attribute"> <dt id="django.test.client.Response.client"> <tt class="descname">client</tt><a class="headerlink" href="#django.test.client.Response.client" title="Permalink to this definition">¶</a></dt> <dd><p>The test client that was used to make the request that resulted in the response.</p> </dd></dl> <dl class="attribute"> <dt id="django.test.client.Response.content"> <tt class="descname">content</tt><a class="headerlink" href="#django.test.client.Response.content" title="Permalink to this definition">¶</a></dt> <dd><p>The body of the response, as a string. This is the final page content as rendered by the view, or any error message.</p> </dd></dl> <dl class="attribute"> <dt id="django.test.client.Response.context"> <tt class="descname">context</tt><a class="headerlink" href="#django.test.client.Response.context" title="Permalink to this definition">¶</a></dt> <dd><p>The template <tt class="docutils literal"><span class="pre">Context</span></tt> instance that was used to render the template that produced the response content.</p> <p>If the rendered page used multiple templates, then <tt class="docutils literal"><span class="pre">context</span></tt> will be a list of <tt class="docutils literal"><span class="pre">Context</span></tt> objects, in the order in which they were rendered.</p> <p>Regardless of the number of templates used during rendering, you can retrieve context values using the <tt class="docutils literal"><span class="pre">[]</span></tt> operator. For example, the context variable <tt class="docutils literal"><span class="pre">name</span></tt> could be retrieved using:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/foo/'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">response</span><span class="o">.</span><span class="n">context</span><span class="p">[</span><span class="s">'name'</span><span class="p">]</span> <span class="go">'Arthur'</span> </pre></div> </div> </dd></dl> <dl class="attribute"> <dt id="django.test.client.Response.request"> <tt class="descname">request</tt><a class="headerlink" href="#django.test.client.Response.request" title="Permalink to this definition">¶</a></dt> <dd><p>The request data that stimulated the response.</p> </dd></dl> <dl class="attribute"> <dt id="django.test.client.Response.status_code"> <tt class="descname">status_code</tt><a class="headerlink" href="#django.test.client.Response.status_code" title="Permalink to this definition">¶</a></dt> <dd><p>The HTTP status of the response, as an integer. See <span class="target" id="index-0"></span><a class="rfc reference external" href="http://tools.ietf.org/html/rfc2616.html#section-10"><strong>RFC 2616</strong></a> for a full list of HTTP status codes.</p> </dd></dl> <dl class="attribute"> <dt id="django.test.client.Response.templates"> <tt class="descname">templates</tt><a class="headerlink" href="#django.test.client.Response.templates" title="Permalink to this definition">¶</a></dt> <dd><p>A list of <tt class="docutils literal"><span class="pre">Template</span></tt> instances used to render the final content, in the order they were rendered. For each template in the list, use <tt class="docutils literal"><span class="pre">template.name</span></tt> to get the template’s file name, if the template was loaded from a file. (The name is a string such as <tt class="docutils literal"><span class="pre">'admin/index.html'</span></tt>.)</p> </dd></dl> </dd></dl> <p>You can also use dictionary syntax on the response object to query the value of any settings in the HTTP headers. For example, you could determine the content type of a response using <tt class="docutils literal"><span class="pre">response['Content-Type']</span></tt>.</p> </div> <div class="section" id="s-exceptions"> <span id="exceptions"></span><h4>Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h4> <p>If you point the test client at a view that raises an exception, that exception will be visible in the test case. You can then use a standard <tt class="docutils literal"><span class="pre">try</span> <span class="pre">...</span> <span class="pre">except</span></tt> block or <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase.assertRaises" title="(in Python v2.7)"><tt class="xref py py-meth docutils literal"><span class="pre">assertRaises()</span></tt></a> to test for exceptions.</p> <p>The only exceptions that are not visible to the test client are <tt class="docutils literal"><span class="pre">Http404</span></tt>, <tt class="docutils literal"><span class="pre">PermissionDenied</span></tt> and <tt class="docutils literal"><span class="pre">SystemExit</span></tt>. Django catches these exceptions internally and converts them into the appropriate HTTP response codes. In these cases, you can check <tt class="docutils literal"><span class="pre">response.status_code</span></tt> in your test.</p> </div> <div class="section" id="s-persistent-state"> <span id="persistent-state"></span><h4>Persistent state<a class="headerlink" href="#persistent-state" title="Permalink to this headline">¶</a></h4> <p>The test client is stateful. If a response returns a cookie, then that cookie will be stored in the test client and sent with all subsequent <tt class="docutils literal"><span class="pre">get()</span></tt> and <tt class="docutils literal"><span class="pre">post()</span></tt> requests.</p> <p>Expiration policies for these cookies are not followed. If you want a cookie to expire, either delete it manually or create a new <tt class="docutils literal"><span class="pre">Client</span></tt> instance (which will effectively delete all cookies).</p> <p>A test client has two attributes that store persistent state information. You can access these properties as part of a test condition.</p> <dl class="attribute"> <dt id="django.test.client.Client.cookies"> <tt class="descclassname">Client.</tt><tt class="descname">cookies</tt><a class="headerlink" href="#django.test.client.Client.cookies" title="Permalink to this definition">¶</a></dt> <dd><p>A Python <a class="reference external" href="http://docs.python.org/2.7/library/cookie.html#Cookie.SimpleCookie" title="(in Python v2.7)"><tt class="xref py py-class docutils literal"><span class="pre">SimpleCookie</span></tt></a> object, containing the current values of all the client cookies. See the documentation of the <a class="reference external" href="http://docs.python.org/2.7/library/cookie.html#Cookie" title="(in Python v2.7)"><tt class="xref py py-mod docutils literal"><span class="pre">Cookie</span></tt></a> module for more.</p> </dd></dl> <dl class="attribute"> <dt id="django.test.client.Client.session"> <tt class="descclassname">Client.</tt><tt class="descname">session</tt><a class="headerlink" href="#django.test.client.Client.session" title="Permalink to this definition">¶</a></dt> <dd><p>A dictionary-like object containing session information. See the <a class="reference internal" href="../http/sessions.html"><em>session documentation</em></a> for full details.</p> <p>To modify the session and then save it, it must be stored in a variable first (because a new <tt class="docutils literal"><span class="pre">SessionStore</span></tt> is created every time this property is accessed):</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">test_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">session</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">session</span> <span class="n">session</span><span class="p">[</span><span class="s">'somekey'</span><span class="p">]</span> <span class="o">=</span> <span class="s">'test'</span> <span class="n">session</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> </pre></div> </div> </dd></dl> </div> <div class="section" id="s-example"> <span id="example"></span><h4>Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h4> <p>The following is a simple unit test using the test client:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">unittest</span> <span class="kn">from</span> <span class="nn">django.test.client</span> <span class="kn">import</span> <span class="n">Client</span> <span class="k">class</span> <span class="nc">SimpleTest</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span> <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c"># Every test needs a client.</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span> <span class="k">def</span> <span class="nf">test_details</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c"># Issue a GET request.</span> <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customer/details/'</span><span class="p">)</span> <span class="c"># Check that the response is 200 OK.</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span> <span class="c"># Check that the rendered context contains 5 customers.</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">context</span><span class="p">[</span><span class="s">'customers'</span><span class="p">]),</span> <span class="mi">5</span><span class="p">)</span> </pre></div> </div> <div class="admonition-see-also admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="advanced.html#django.test.client.RequestFactory" title="django.test.client.RequestFactory"><tt class="xref py py-class docutils literal"><span class="pre">django.test.client.RequestFactory</span></tt></a></p> </div> </div> </div> <div class="section" id="s-provided-test-case-classes"> <span id="provided-test-case-classes"></span><h3>Provided test case classes<a class="headerlink" href="#provided-test-case-classes" title="Permalink to this headline">¶</a></h3> <p>Normal Python unit test classes extend a base class of <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase" title="(in Python v2.7)"><tt class="xref py py-class docutils literal"><span class="pre">unittest.TestCase</span></tt></a>. Django provides a few extensions of this base class:</p> <div class="figure" id="testcase-hierarchy-diagram"> <img alt="Hierarchy of Django unit testing classes (TestCase subclasses)" src="../../_images/django_unittest_classes_hierarchy.png" /> <p class="caption">Hierarchy of Django unit testing classes</p> </div> <p>Regardless of the version of Python you’re using, if you’ve installed <tt class="docutils literal"><span class="pre">unittest2</span></tt>, <tt class="docutils literal"><span class="pre">django.utils.unittest</span></tt> will point to that library.</p> <div class="section" id="s-simpletestcase"> <span id="simpletestcase"></span><h4>SimpleTestCase<a class="headerlink" href="#simpletestcase" title="Permalink to this headline">¶</a></h4> <dl class="class"> <dt id="django.test.SimpleTestCase"> <em class="property">class </em><tt class="descname">SimpleTestCase</tt><a class="headerlink" href="#django.test.SimpleTestCase" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <div class="versionadded"> <span class="title">New in Django 1.4.</span> </div> <p>A very thin subclass of <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase" title="(in Python v2.7)"><tt class="xref py py-class docutils literal"><span class="pre">unittest.TestCase</span></tt></a>, it extends it with some basic functionality like:</p> <ul class="simple"> <li>Saving and restoring the Python warning machinery state.</li> <li>Checking that a callable <a class="reference internal" href="#django.test.SimpleTestCase.assertRaisesMessage" title="django.test.SimpleTestCase.assertRaisesMessage"><tt class="xref py py-meth docutils literal"><span class="pre">raises</span> <span class="pre">a</span> <span class="pre">certain</span> <span class="pre">exception</span></tt></a>.</li> <li><a class="reference internal" href="#django.test.SimpleTestCase.assertFieldOutput" title="django.test.SimpleTestCase.assertFieldOutput"><tt class="xref py py-meth docutils literal"><span class="pre">Testing</span> <span class="pre">form</span> <span class="pre">field</span> <span class="pre">rendering</span></tt></a>.</li> <li>Testing server <a class="reference internal" href="#assertions"><em>HTML responses for the presence/lack of a given fragment</em></a>.</li> <li>The ability to run tests with <a class="reference internal" href="#overriding-settings"><em>modified settings</em></a></li> </ul> <p>If you need any of the other more complex and heavyweight Django-specific features like:</p> <ul class="simple"> <li>Using the <a class="reference internal" href="#django.test.TestCase.client" title="django.test.TestCase.client"><tt class="xref py py-attr docutils literal"><span class="pre">client</span></tt></a> <a class="reference internal" href="#django.test.client.Client" title="django.test.client.Client"><tt class="xref py py-class docutils literal"><span class="pre">Client</span></tt></a>.</li> <li>Testing or using the ORM.</li> <li>Database <a class="reference internal" href="#django.test.TestCase.fixtures" title="django.test.TestCase.fixtures"><tt class="xref py py-attr docutils literal"><span class="pre">fixtures</span></tt></a>.</li> <li>Custom test-time <a class="reference internal" href="#django.test.TestCase.urls" title="django.test.TestCase.urls"><tt class="xref py py-attr docutils literal"><span class="pre">URL</span> <span class="pre">maps</span></tt></a>.</li> <li>Test <a class="reference internal" href="#skipping-tests"><em>skipping based on database backend features</em></a>.</li> <li>The remaining specialized <a class="reference internal" href="#assertions"><em>assert*</em></a> methods.</li> </ul> <p>then you should use <a class="reference internal" href="#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><tt class="xref py py-class docutils literal"><span class="pre">TransactionTestCase</span></tt></a> or <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><tt class="xref py py-class docutils literal"><span class="pre">TestCase</span></tt></a> instead.</p> <p><tt class="docutils literal"><span class="pre">SimpleTestCase</span></tt> inherits from <tt class="docutils literal"><span class="pre">django.utils.unittest.TestCase</span></tt>.</p> </div> <div class="section" id="s-transactiontestcase"> <span id="transactiontestcase"></span><h4>TransactionTestCase<a class="headerlink" href="#transactiontestcase" title="Permalink to this headline">¶</a></h4> <dl class="class"> <dt id="django.test.TransactionTestCase"> <em class="property">class </em><tt class="descname">TransactionTestCase</tt><a class="headerlink" href="#django.test.TransactionTestCase" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Django <tt class="docutils literal"><span class="pre">TestCase</span></tt> classes make use of database transaction facilities, if available, to speed up the process of resetting the database to a known state at the beginning of each test. A consequence of this, however, is that the effects of transaction commit and rollback cannot be tested by a Django <tt class="docutils literal"><span class="pre">TestCase</span></tt> class. If your test requires testing of such transactional behavior, you should use a Django <tt class="docutils literal"><span class="pre">TransactionTestCase</span></tt>.</p> <p><tt class="docutils literal"><span class="pre">TransactionTestCase</span></tt> and <tt class="docutils literal"><span class="pre">TestCase</span></tt> are identical except for the manner in which the database is reset to a known state and the ability for test code to test the effects of commit and rollback:</p> <ul> <li><p class="first">A <tt class="docutils literal"><span class="pre">TransactionTestCase</span></tt> resets the database after the test runs by truncating all tables. A <tt class="docutils literal"><span class="pre">TransactionTestCase</span></tt> may call commit and rollback and observe the effects of these calls on the database.</p> </li> <li><p class="first">A <tt class="docutils literal"><span class="pre">TestCase</span></tt>, on the other hand, does not truncate tables after a test. Instead, it encloses the test code in a database transaction that is rolled back at the end of the test. Both explicit commits like <tt class="docutils literal"><span class="pre">transaction.commit()</span></tt> and implicit ones that may be caused by <tt class="docutils literal"><span class="pre">Model.save()</span></tt> are replaced with a <tt class="docutils literal"><span class="pre">nop</span></tt> operation. This guarantees that the rollback at the end of the test restores the database to its initial state.</p> <p>When running on a database that does not support rollback (e.g. MySQL with the MyISAM storage engine), <tt class="docutils literal"><span class="pre">TestCase</span></tt> falls back to initializing the database by truncating tables and reloading initial data.</p> </li> </ul> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">While <tt class="docutils literal"><span class="pre">commit</span></tt> and <tt class="docutils literal"><span class="pre">rollback</span></tt> operations still <em>appear</em> to work when used in <tt class="docutils literal"><span class="pre">TestCase</span></tt>, no actual commit or rollback will be performed by the database. This can cause your tests to pass or fail unexpectedly. Always use <tt class="docutils literal"><span class="pre">TransactionalTestCase</span></tt> when testing transactional behavior.</p> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <div class="versionchanged"> <span class="title">Changed in Django 1.5.</span> </div> <p>Prior to 1.5, <tt class="docutils literal"><span class="pre">TransactionTestCase</span></tt> flushed the database tables <em>before</em> each test. In Django 1.5, this is instead done <em>after</em> the test has been run.</p> <p>When the flush took place before the test, it was guaranteed that primary key values started at one in <a class="reference internal" href="#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><tt class="xref py py-class docutils literal"><span class="pre">TransactionTestCase</span></tt></a> tests.</p> <p class="last">Tests should not depend on this behaviour, but for legacy tests that do, the <a class="reference internal" href="#django.test.TransactionTestCase.reset_sequences" title="django.test.TransactionTestCase.reset_sequences"><tt class="xref py py-attr docutils literal"><span class="pre">reset_sequences</span></tt></a> attribute can be used until the test has been properly updated.</p> </div> <div class="versionchanged"> <span class="title">Changed in Django 1.5:</span> The order in which tests are run has changed. See <a class="reference internal" href="#order-in-which-tests-are-executed">Order in which tests are executed</a>.</div> <p><tt class="docutils literal"><span class="pre">TransactionTestCase</span></tt> inherits from <a class="reference internal" href="#django.test.SimpleTestCase" title="django.test.SimpleTestCase"><tt class="xref py py-class docutils literal"><span class="pre">SimpleTestCase</span></tt></a>.</p> <dl class="attribute"> <dt id="django.test.TransactionTestCase.reset_sequences"> <tt class="descclassname">TransactionTestCase.</tt><tt class="descname">reset_sequences</tt><a class="headerlink" href="#django.test.TransactionTestCase.reset_sequences" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.5.</span> </div> <p>Setting <tt class="docutils literal"><span class="pre">reset_sequences</span> <span class="pre">=</span> <span class="pre">True</span></tt> on a <tt class="docutils literal"><span class="pre">TransactionTestCase</span></tt> will make sure sequences are always reset before the test run:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">TestsThatDependsOnPrimaryKeySequences</span><span class="p">(</span><span class="n">TransactionTestCase</span><span class="p">):</span> <span class="n">reset_sequences</span> <span class="o">=</span> <span class="bp">True</span> <span class="k">def</span> <span class="nf">test_animal_pk</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">lion</span> <span class="o">=</span> <span class="n">Animal</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">"lion"</span><span class="p">,</span> <span class="n">sound</span><span class="o">=</span><span class="s">"roar"</span><span class="p">)</span> <span class="c"># lion.pk is guaranteed to always be 1</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">lion</span><span class="o">.</span><span class="n">pk</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> </pre></div> </div> <p>Unless you are explicitly testing primary keys sequence numbers, it is recommended that you do not hard code primary key values in tests.</p> <p>Using <tt class="docutils literal"><span class="pre">reset_sequences</span> <span class="pre">=</span> <span class="pre">True</span></tt> will slow down the test, since the primary key reset is an relatively expensive database operation.</p> </dd></dl> </div> <div class="section" id="s-testcase"> <span id="testcase"></span><h4>TestCase<a class="headerlink" href="#testcase" title="Permalink to this headline">¶</a></h4> <dl class="class"> <dt id="django.test.TestCase"> <em class="property">class </em><tt class="descname">TestCase</tt><a class="headerlink" href="#django.test.TestCase" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>This class provides some additional capabilities that can be useful for testing Web sites.</p> <p>Converting a normal <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase" title="(in Python v2.7)"><tt class="xref py py-class docutils literal"><span class="pre">unittest.TestCase</span></tt></a> to a Django <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><tt class="xref py py-class docutils literal"><span class="pre">TestCase</span></tt></a> is easy: Just change the base class of your test from <tt class="docutils literal"><span class="pre">'unittest.TestCase'</span></tt> to <tt class="docutils literal"><span class="pre">'django.test.TestCase'</span></tt>. All of the standard Python unit test functionality will continue to be available, but it will be augmented with some useful additions, including:</p> <ul class="simple"> <li>Automatic loading of fixtures.</li> <li>Wraps each test in a transaction.</li> <li>Creates a TestClient instance.</li> <li>Django-specific assertions for testing for things like redirection and form errors.</li> </ul> <div class="versionchanged"> <span class="title">Changed in Django 1.5:</span> The order in which tests are run has changed. See <a class="reference internal" href="#order-in-which-tests-are-executed">Order in which tests are executed</a>.</div> <p><tt class="docutils literal"><span class="pre">TestCase</span></tt> inherits from <a class="reference internal" href="#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><tt class="xref py py-class docutils literal"><span class="pre">TransactionTestCase</span></tt></a>.</p> </div> <div class="section" id="s-liveservertestcase"> <span id="s-live-test-server"></span><span id="liveservertestcase"></span><span id="live-test-server"></span><h4>LiveServerTestCase<a class="headerlink" href="#liveservertestcase" title="Permalink to this headline">¶</a></h4> <div class="versionadded"> <span class="title">New in Django 1.4.</span> </div> <dl class="class"> <dt id="django.test.LiveServerTestCase"> <em class="property">class </em><tt class="descname">LiveServerTestCase</tt><a class="headerlink" href="#django.test.LiveServerTestCase" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p><tt class="docutils literal"><span class="pre">LiveServerTestCase</span></tt> does basically the same as <a class="reference internal" href="#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><tt class="xref py py-class docutils literal"><span class="pre">TransactionTestCase</span></tt></a> with one extra feature: it launches a live Django server in the background on setup, and shuts it down on teardown. This allows the use of automated test clients other than the <a class="reference internal" href="#test-client"><em>Django dummy client</em></a> such as, for example, the <a class="reference external" href="http://seleniumhq.org/">Selenium</a> client, to execute a series of functional tests inside a browser and simulate a real user’s actions.</p> <p>By default the live server’s address is <tt class="docutils literal"><span class="pre">'localhost:8081'</span></tt> and the full URL can be accessed during the tests with <tt class="docutils literal"><span class="pre">self.live_server_url</span></tt>. If you’d like to change the default address (in the case, for example, where the 8081 port is already taken) then you may pass a different one to the <a class="reference internal" href="../../ref/django-admin.html#django-admin-test"><tt class="xref std std-djadmin docutils literal"><span class="pre">test</span></tt></a> command via the <a class="reference internal" href="../../ref/django-admin.html#django-admin-option---liveserver"><tt class="xref std std-djadminopt docutils literal"><span class="pre">--liveserver</span></tt></a> option, for example:</p> <div class="highlight-bash"><div class="highlight"><pre>./manage.py <span class="nb">test</span> --liveserver<span class="o">=</span>localhost:8082 </pre></div> </div> <p>Another way of changing the default server address is by setting the <cite>DJANGO_LIVE_TEST_SERVER_ADDRESS</cite> environment variable somewhere in your code (for example, in a <a class="reference internal" href="advanced.html#topics-testing-test-runner"><em>custom test runner</em></a>):</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">os</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s">'DJANGO_LIVE_TEST_SERVER_ADDRESS'</span><span class="p">]</span> <span class="o">=</span> <span class="s">'localhost:8082'</span> </pre></div> </div> <p>In the case where the tests are run by multiple processes in parallel (for example, in the context of several simultaneous <a class="reference external" href="http://en.wikipedia.org/wiki/Continuous_integration">continuous integration</a> builds), the processes will compete for the same address, and therefore your tests might randomly fail with an “Address already in use” error. To avoid this problem, you can pass a comma-separated list of ports or ranges of ports (at least as many as the number of potential parallel processes). For example:</p> <div class="highlight-bash"><div class="highlight"><pre>./manage.py <span class="nb">test</span> --liveserver<span class="o">=</span>localhost:8082,8090-8100,9000-9200,7041 </pre></div> </div> <p>Then, during test execution, each new live test server will try every specified port until it finds one that is free and takes it.</p> <p>To demonstrate how to use <tt class="docutils literal"><span class="pre">LiveServerTestCase</span></tt>, let’s write a simple Selenium test. First of all, you need to install the <a class="reference external" href="http://pypi.python.org/pypi/selenium">selenium package</a> into your Python path:</p> <div class="highlight-bash"><div class="highlight"><pre>pip install selenium </pre></div> </div> <p>Then, add a <tt class="docutils literal"><span class="pre">LiveServerTestCase</span></tt>-based test to your app’s tests module (for example: <tt class="docutils literal"><span class="pre">myapp/tests.py</span></tt>). The code for this test may look as follows:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">LiveServerTestCase</span> <span class="kn">from</span> <span class="nn">selenium.webdriver.firefox.webdriver</span> <span class="kn">import</span> <span class="n">WebDriver</span> <span class="k">class</span> <span class="nc">MySeleniumTests</span><span class="p">(</span><span class="n">LiveServerTestCase</span><span class="p">):</span> <span class="n">fixtures</span> <span class="o">=</span> <span class="p">[</span><span class="s">'user-data.json'</span><span class="p">]</span> <span class="nd">@classmethod</span> <span class="k">def</span> <span class="nf">setUpClass</span><span class="p">(</span><span class="n">cls</span><span class="p">):</span> <span class="n">cls</span><span class="o">.</span><span class="n">selenium</span> <span class="o">=</span> <span class="n">WebDriver</span><span class="p">()</span> <span class="nb">super</span><span class="p">(</span><span class="n">MySeleniumTests</span><span class="p">,</span> <span class="n">cls</span><span class="p">)</span><span class="o">.</span><span class="n">setUpClass</span><span class="p">()</span> <span class="nd">@classmethod</span> <span class="k">def</span> <span class="nf">tearDownClass</span><span class="p">(</span><span class="n">cls</span><span class="p">):</span> <span class="n">cls</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span> <span class="nb">super</span><span class="p">(</span><span class="n">MySeleniumTests</span><span class="p">,</span> <span class="n">cls</span><span class="p">)</span><span class="o">.</span><span class="n">tearDownClass</span><span class="p">()</span> <span class="k">def</span> <span class="nf">test_login</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'</span><span class="si">%s%s</span><span class="s">'</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">live_server_url</span><span class="p">,</span> <span class="s">'/login/'</span><span class="p">))</span> <span class="n">username_input</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">find_element_by_name</span><span class="p">(</span><span class="s">"username"</span><span class="p">)</span> <span class="n">username_input</span><span class="o">.</span><span class="n">send_keys</span><span class="p">(</span><span class="s">'myuser'</span><span class="p">)</span> <span class="n">password_input</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">find_element_by_name</span><span class="p">(</span><span class="s">"password"</span><span class="p">)</span> <span class="n">password_input</span><span class="o">.</span><span class="n">send_keys</span><span class="p">(</span><span class="s">'secret'</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">find_element_by_xpath</span><span class="p">(</span><span class="s">'//input[@value="Log in"]'</span><span class="p">)</span><span class="o">.</span><span class="n">click</span><span class="p">()</span> </pre></div> </div> <p>Finally, you may run the test as follows:</p> <div class="highlight-bash"><div class="highlight"><pre>./manage.py <span class="nb">test </span>myapp.MySeleniumTests.test_login </pre></div> </div> <p>This example will automatically open Firefox then go to the login page, enter the credentials and press the “Log in” button. Selenium offers other drivers in case you do not have Firefox installed or wish to use another browser. The example above is just a tiny fraction of what the Selenium client can do; check out the <a class="reference external" href="http://selenium-python.readthedocs.org/en/latest/api.html">full reference</a> for more details.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last"><tt class="docutils literal"><span class="pre">LiveServerTestCase</span></tt> makes use of the <a class="reference internal" href="../../howto/static-files/index.html"><em>staticfiles contrib app</em></a> so you’ll need to have your project configured accordingly (in particular by setting <a class="reference internal" href="../../ref/settings.html#std:setting-STATIC_URL"><tt class="xref std std-setting docutils literal"><span class="pre">STATIC_URL</span></tt></a>).</p> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>When using an in-memory SQLite database to run the tests, the same database connection will be shared by two threads in parallel: the thread in which the live server is run and the thread in which the test case is run. It’s important to prevent simultaneous database queries via this shared connection by the two threads, as that may sometimes randomly cause the tests to fail. So you need to ensure that the two threads don’t access the database at the same time. In particular, this means that in some cases (for example, just after clicking a link or submitting a form), you might need to check that a response is received by Selenium and that the next page is loaded before proceeding with further test execution. Do this, for example, by making Selenium wait until the <tt class="docutils literal"><span class="pre"><body></span></tt> HTML tag is found in the response (requires Selenium > 2.13):</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">test_login</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="kn">from</span> <span class="nn">selenium.webdriver.support.wait</span> <span class="kn">import</span> <span class="n">WebDriverWait</span> <span class="n">timeout</span> <span class="o">=</span> <span class="mi">2</span> <span class="o">...</span> <span class="bp">self</span><span class="o">.</span><span class="n">selenium</span><span class="o">.</span><span class="n">find_element_by_xpath</span><span class="p">(</span><span class="s">'//input[@value="Log in"]'</span><span class="p">)</span><span class="o">.</span><span class="n">click</span><span class="p">()</span> <span class="c"># Wait until the response is received</span> <span class="n">WebDriverWait</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">selenium</span><span class="p">,</span> <span class="n">timeout</span><span class="p">)</span><span class="o">.</span><span class="n">until</span><span class="p">(</span> <span class="k">lambda</span> <span class="n">driver</span><span class="p">:</span> <span class="n">driver</span><span class="o">.</span><span class="n">find_element_by_tag_name</span><span class="p">(</span><span class="s">'body'</span><span class="p">))</span> </pre></div> </div> <p class="last">The tricky thing here is that there’s really no such thing as a “page load,” especially in modern Web apps that generate HTML dynamically after the server generates the initial document. So, simply checking for the presence of <tt class="docutils literal"><span class="pre"><body></span></tt> in the response might not necessarily be appropriate for all use cases. Please refer to the <a class="reference external" href="http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_WebDriver_fails_to_find_elements_/_Does_not_block_on_page_loa">Selenium FAQ</a> and <a class="reference external" href="http://seleniumhq.org/docs/04_webdriver_advanced.html#explicit-waits">Selenium documentation</a> for more information.</p> </div> </div> </div> <div class="section" id="s-test-cases-features"> <span id="test-cases-features"></span><h3>Test cases features<a class="headerlink" href="#test-cases-features" title="Permalink to this headline">¶</a></h3> <div class="section" id="s-default-test-client"> <span id="default-test-client"></span><h4>Default test client<a class="headerlink" href="#default-test-client" title="Permalink to this headline">¶</a></h4> <dl class="attribute"> <dt id="django.test.TestCase.client"> <tt class="descclassname">TestCase.</tt><tt class="descname">client</tt><a class="headerlink" href="#django.test.TestCase.client" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Every test case in a <tt class="docutils literal"><span class="pre">django.test.TestCase</span></tt> instance has access to an instance of a Django test client. This client can be accessed as <tt class="docutils literal"><span class="pre">self.client</span></tt>. This client is recreated for each test, so you don’t have to worry about state (such as cookies) carrying over from one test to another.</p> <p>This means, instead of instantiating a <tt class="docutils literal"><span class="pre">Client</span></tt> in each test:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">unittest</span> <span class="kn">from</span> <span class="nn">django.test.client</span> <span class="kn">import</span> <span class="n">Client</span> <span class="k">class</span> <span class="nc">SimpleTest</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span> <span class="k">def</span> <span class="nf">test_details</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span> <span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customer/details/'</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span> <span class="k">def</span> <span class="nf">test_index</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span> <span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customer/index/'</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span> </pre></div> </div> <p>...you can just refer to <tt class="docutils literal"><span class="pre">self.client</span></tt>, like so:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span> <span class="k">class</span> <span class="nc">SimpleTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span> <span class="k">def</span> <span class="nf">test_details</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customer/details/'</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span> <span class="k">def</span> <span class="nf">test_index</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customer/index/'</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span> </pre></div> </div> </div> <div class="section" id="s-customizing-the-test-client"> <span id="customizing-the-test-client"></span><h4>Customizing the test client<a class="headerlink" href="#customizing-the-test-client" title="Permalink to this headline">¶</a></h4> <dl class="attribute"> <dt id="django.test.TestCase.client_class"> <tt class="descclassname">TestCase.</tt><tt class="descname">client_class</tt><a class="headerlink" href="#django.test.TestCase.client_class" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>If you want to use a different <tt class="docutils literal"><span class="pre">Client</span></tt> class (for example, a subclass with customized behavior), use the <a class="reference internal" href="#django.test.TestCase.client_class" title="django.test.TestCase.client_class"><tt class="xref py py-attr docutils literal"><span class="pre">client_class</span></tt></a> class attribute:</p> <div class="highlight-python"><pre>from django.test import TestCase from django.test.client import Client class MyTestClient(Client): # Specialized methods for your environment... class MyTest(TestCase): client_class = MyTestClient def test_my_stuff(self): # Here self.client is an instance of MyTestClient... call_some_test_code()</pre> </div> </div> <div class="section" id="s-fixture-loading"> <span id="s-topics-testing-fixtures"></span><span id="fixture-loading"></span><span id="topics-testing-fixtures"></span><h4>Fixture loading<a class="headerlink" href="#fixture-loading" title="Permalink to this headline">¶</a></h4> <dl class="attribute"> <dt id="django.test.TestCase.fixtures"> <tt class="descclassname">TestCase.</tt><tt class="descname">fixtures</tt><a class="headerlink" href="#django.test.TestCase.fixtures" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>A test case for a database-backed Web site isn’t much use if there isn’t any data in the database. To make it easy to put test data into the database, Django’s custom <tt class="docutils literal"><span class="pre">TestCase</span></tt> class provides a way of loading <strong>fixtures</strong>.</p> <p>A fixture is a collection of data that Django knows how to import into a database. For example, if your site has user accounts, you might set up a fixture of fake user accounts in order to populate your database during tests.</p> <p>The most straightforward way of creating a fixture is to use the <a class="reference internal" href="../../ref/django-admin.html#django-admin-dumpdata"><tt class="xref std std-djadmin docutils literal"><span class="pre">manage.py</span> <span class="pre">dumpdata</span></tt></a> command. This assumes you already have some data in your database. See the <a class="reference internal" href="../../ref/django-admin.html#django-admin-dumpdata"><tt class="xref std std-djadmin docutils literal"><span class="pre">dumpdata</span> <span class="pre">documentation</span></tt></a> for more details.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>If you’ve ever run <a class="reference internal" href="../../ref/django-admin.html#django-admin-syncdb"><tt class="xref std std-djadmin docutils literal"><span class="pre">manage.py</span> <span class="pre">syncdb</span></tt></a>, you’ve already used a fixture without even knowing it! When you call <a class="reference internal" href="../../ref/django-admin.html#django-admin-syncdb"><tt class="xref std std-djadmin docutils literal"><span class="pre">syncdb</span></tt></a> in the database for the first time, Django installs a fixture called <tt class="docutils literal"><span class="pre">initial_data</span></tt>. This gives you a way of populating a new database with any initial data, such as a default set of categories.</p> <p class="last">Fixtures with other names can always be installed manually using the <a class="reference internal" href="../../ref/django-admin.html#django-admin-loaddata"><tt class="xref std std-djadmin docutils literal"><span class="pre">manage.py</span> <span class="pre">loaddata</span></tt></a> command.</p> </div> <div class="admonition-initial-sql-data-and-testing admonition"> <p class="first admonition-title">Initial SQL data and testing</p> <p class="last">Django provides a second way to insert initial data into models – the <a class="reference internal" href="../../howto/initial-data.html#initial-sql"><em>custom SQL hook</em></a>. However, this technique <em>cannot</em> be used to provide initial data for testing purposes. Django’s test framework flushes the contents of the test database after each test; as a result, any data added using the custom SQL hook will be lost.</p> </div> <p>Once you’ve created a fixture and placed it in a <tt class="docutils literal"><span class="pre">fixtures</span></tt> directory in one of your <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a>, you can use it in your unit tests by specifying a <tt class="docutils literal"><span class="pre">fixtures</span></tt> class attribute on your <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><tt class="xref py py-class docutils literal"><span class="pre">django.test.TestCase</span></tt></a> subclass:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span> <span class="kn">from</span> <span class="nn">myapp.models</span> <span class="kn">import</span> <span class="n">Animal</span> <span class="k">class</span> <span class="nc">AnimalTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span> <span class="n">fixtures</span> <span class="o">=</span> <span class="p">[</span><span class="s">'mammals.json'</span><span class="p">,</span> <span class="s">'birds'</span><span class="p">]</span> <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c"># Test definitions as before.</span> <span class="n">call_setup_methods</span><span class="p">()</span> <span class="k">def</span> <span class="nf">testFluffyAnimals</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c"># A test that uses the fixtures.</span> <span class="n">call_some_test_code</span><span class="p">()</span> </pre></div> </div> <p>Here’s specifically what will happen:</p> <ul class="simple"> <li>At the start of each test case, before <tt class="docutils literal"><span class="pre">setUp()</span></tt> is run, Django will flush the database, returning the database to the state it was in directly after <a class="reference internal" href="../../ref/django-admin.html#django-admin-syncdb"><tt class="xref std std-djadmin docutils literal"><span class="pre">syncdb</span></tt></a> was called.</li> <li>Then, all the named fixtures are installed. In this example, Django will install any JSON fixture named <tt class="docutils literal"><span class="pre">mammals</span></tt>, followed by any fixture named <tt class="docutils literal"><span class="pre">birds</span></tt>. See the <a class="reference internal" href="../../ref/django-admin.html#django-admin-loaddata"><tt class="xref std std-djadmin docutils literal"><span class="pre">loaddata</span></tt></a> documentation for more details on defining and installing fixtures.</li> </ul> <p>This flush/load procedure is repeated for each test in the test case, so you can be certain that the outcome of a test will not be affected by another test, or by the order of test execution.</p> <p>By default, fixtures are only loaded into the <tt class="docutils literal"><span class="pre">default</span></tt> database. If you are using multiple databases and set <a class="reference internal" href="#django.test.TestCase.multi_db" title="django.test.TestCase.multi_db"><tt class="xref py py-attr docutils literal"><span class="pre">multi_db=True</span></tt></a>, fixtures will be loaded into all databases.</p> </div> <div class="section" id="s-urlconf-configuration"> <span id="urlconf-configuration"></span><h4>URLconf configuration<a class="headerlink" href="#urlconf-configuration" title="Permalink to this headline">¶</a></h4> <dl class="attribute"> <dt id="django.test.TestCase.urls"> <tt class="descclassname">TestCase.</tt><tt class="descname">urls</tt><a class="headerlink" href="#django.test.TestCase.urls" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>If your application provides views, you may want to include tests that use the test client to exercise those views. However, an end user is free to deploy the views in your application at any URL of their choosing. This means that your tests can’t rely upon the fact that your views will be available at a particular URL.</p> <p>In order to provide a reliable URL space for your test, <tt class="docutils literal"><span class="pre">django.test.TestCase</span></tt> provides the ability to customize the URLconf configuration for the duration of the execution of a test suite. If your <tt class="docutils literal"><span class="pre">TestCase</span></tt> instance defines an <tt class="docutils literal"><span class="pre">urls</span></tt> attribute, the <tt class="docutils literal"><span class="pre">TestCase</span></tt> will use the value of that attribute as the <a class="reference internal" href="../../ref/settings.html#std:setting-ROOT_URLCONF"><tt class="xref std std-setting docutils literal"><span class="pre">ROOT_URLCONF</span></tt></a> for the duration of that test.</p> <p>For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span> <span class="k">class</span> <span class="nc">TestMyViews</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span> <span class="n">urls</span> <span class="o">=</span> <span class="s">'myapp.test_urls'</span> <span class="k">def</span> <span class="nf">testIndexPageView</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c"># Here you'd test your view using ``Client``.</span> <span class="n">call_some_test_code</span><span class="p">()</span> </pre></div> </div> <p>This test case will use the contents of <tt class="docutils literal"><span class="pre">myapp.test_urls</span></tt> as the URLconf for the duration of the test case.</p> </div> <div class="section" id="s-multi-database-support"> <span id="s-emptying-test-outbox"></span><span id="multi-database-support"></span><span id="emptying-test-outbox"></span><h4>Multi-database support<a class="headerlink" href="#multi-database-support" title="Permalink to this headline">¶</a></h4> <dl class="attribute"> <dt id="django.test.TestCase.multi_db"> <tt class="descclassname">TestCase.</tt><tt class="descname">multi_db</tt><a class="headerlink" href="#django.test.TestCase.multi_db" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Django sets up a test database corresponding to every database that is defined in the <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASES"><tt class="xref std std-setting docutils literal"><span class="pre">DATABASES</span></tt></a> definition in your settings file. However, a big part of the time taken to run a Django TestCase is consumed by the call to <tt class="docutils literal"><span class="pre">flush</span></tt> that ensures that you have a clean database at the start of each test run. If you have multiple databases, multiple flushes are required (one for each database), which can be a time consuming activity – especially if your tests don’t need to test multi-database activity.</p> <p>As an optimization, Django only flushes the <tt class="docutils literal"><span class="pre">default</span></tt> database at the start of each test run. If your setup contains multiple databases, and you have a test that requires every database to be clean, you can use the <tt class="docutils literal"><span class="pre">multi_db</span></tt> attribute on the test suite to request a full flush.</p> <p>For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">TestMyViews</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span> <span class="n">multi_db</span> <span class="o">=</span> <span class="bp">True</span> <span class="k">def</span> <span class="nf">testIndexPageView</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">call_some_test_code</span><span class="p">()</span> </pre></div> </div> <p>This test case will flush <em>all</em> the test databases before running <tt class="docutils literal"><span class="pre">testIndexPageView</span></tt>.</p> <p>The <tt class="docutils literal"><span class="pre">multi_db</span></tt> flag also affects into which databases the attr:<cite>TransactionTestCase.fixtures</cite> are loaded. By default (when <tt class="docutils literal"><span class="pre">multi_db=False</span></tt>), fixtures are only loaded into the <tt class="docutils literal"><span class="pre">default</span></tt> database. If <tt class="docutils literal"><span class="pre">multi_db=True</span></tt>, fixtures are loaded into all databases.</p> </div> <div class="section" id="s-overriding-settings"> <span id="s-id3"></span><span id="overriding-settings"></span><span id="id3"></span><h4>Overriding settings<a class="headerlink" href="#overriding-settings" title="Permalink to this headline">¶</a></h4> <dl class="method"> <dt id="django.test.TestCase.settings"> <tt class="descclassname">TestCase.</tt><tt class="descname">settings</tt>()<a class="headerlink" href="#django.test.TestCase.settings" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <div class="versionadded"> <span class="title">New in Django 1.4.</span> </div> <p>For testing purposes it’s often useful to change a setting temporarily and revert to the original value after running the testing code. For this use case Django provides a standard Python context manager (see <span class="target" id="index-1"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a>) <a class="reference internal" href="#django.test.TestCase.settings" title="django.test.TestCase.settings"><tt class="xref py py-meth docutils literal"><span class="pre">settings()</span></tt></a>, which can be used like this:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span> <span class="k">class</span> <span class="nc">LoginTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span> <span class="k">def</span> <span class="nf">test_login</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c"># First check for the default behavior</span> <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/sekrit/'</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRedirects</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="s">'/accounts/login/?next=/sekrit/'</span><span class="p">)</span> <span class="c"># Then override the LOGIN_URL setting</span> <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">settings</span><span class="p">(</span><span class="n">LOGIN_URL</span><span class="o">=</span><span class="s">'/other/login/'</span><span class="p">):</span> <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/sekrit/'</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRedirects</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="s">'/other/login/?next=/sekrit/'</span><span class="p">)</span> </pre></div> </div> <p>This example will override the <a class="reference internal" href="../../ref/settings.html#std:setting-LOGIN_URL"><tt class="xref std std-setting docutils literal"><span class="pre">LOGIN_URL</span></tt></a> setting for the code in the <tt class="docutils literal"><span class="pre">with</span></tt> block and reset its value to the previous state afterwards.</p> <dl class="function"> <dt id="django.test.utils.override_settings"> <tt class="descname">override_settings</tt>()<a class="headerlink" href="#django.test.utils.override_settings" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>In case you want to override a setting for just one test method or even the whole <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><tt class="xref py py-class docutils literal"><span class="pre">TestCase</span></tt></a> class, Django provides the <a class="reference internal" href="#django.test.utils.override_settings" title="django.test.utils.override_settings"><tt class="xref py py-func docutils literal"><span class="pre">override_settings()</span></tt></a> decorator (see <span class="target" id="index-2"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0318"><strong>PEP 318</strong></a>). It’s used like this:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span> <span class="kn">from</span> <span class="nn">django.test.utils</span> <span class="kn">import</span> <span class="n">override_settings</span> <span class="k">class</span> <span class="nc">LoginTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span> <span class="nd">@override_settings</span><span class="p">(</span><span class="n">LOGIN_URL</span><span class="o">=</span><span class="s">'/other/login/'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">test_login</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/sekrit/'</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRedirects</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="s">'/other/login/?next=/sekrit/'</span><span class="p">)</span> </pre></div> </div> <p>The decorator can also be applied to test case classes:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span> <span class="kn">from</span> <span class="nn">django.test.utils</span> <span class="kn">import</span> <span class="n">override_settings</span> <span class="nd">@override_settings</span><span class="p">(</span><span class="n">LOGIN_URL</span><span class="o">=</span><span class="s">'/other/login/'</span><span class="p">)</span> <span class="k">class</span> <span class="nc">LoginTestCase</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span> <span class="k">def</span> <span class="nf">test_login</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/sekrit/'</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRedirects</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="s">'/other/login/?next=/sekrit/'</span><span class="p">)</span> </pre></div> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">When given a class, the decorator modifies the class directly and returns it; it doesn’t create and return a modified copy of it. So if you try to tweak the above example to assign the return value to a different name than <tt class="docutils literal"><span class="pre">LoginTestCase</span></tt>, you may be surprised to find that the original <tt class="docutils literal"><span class="pre">LoginTestCase</span></tt> is still equally affected by the decorator.</p> </div> <p>When overriding settings, make sure to handle the cases in which your app’s code uses a cache or similar feature that retains state even if the setting is changed. Django provides the <a class="reference internal" href="../../ref/signals.html#django.test.signals.setting_changed" title="django.test.signals.setting_changed"><tt class="xref py py-data docutils literal"><span class="pre">django.test.signals.setting_changed</span></tt></a> signal that lets you register callbacks to clean up and otherwise reset state when settings are changed.</p> <p>Django itself uses this signal to reset various data:</p> <table class="docutils"> <colgroup> <col width="43%" /> <col width="57%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Overriden settings</th> <th class="head">Data reset</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td>USE_TZ, TIME_ZONE</td> <td>Databases timezone</td> </tr> <tr class="row-odd"><td>TEMPLATE_CONTEXT_PROCESSORS</td> <td>Context processors cache</td> </tr> <tr class="row-even"><td>TEMPLATE_LOADERS</td> <td>Template loaders cache</td> </tr> <tr class="row-odd"><td>SERIALIZATION_MODULES</td> <td>Serializers cache</td> </tr> <tr class="row-even"><td>LOCALE_PATHS, LANGUAGE_CODE</td> <td>Default translation and loaded translations</td> </tr> <tr class="row-odd"><td>MEDIA_ROOT, DEFAULT_FILE_STORAGE</td> <td>Default file storage</td> </tr> </tbody> </table> </div> <div class="section" id="s-emptying-the-test-outbox"> <span id="emptying-the-test-outbox"></span><h4>Emptying the test outbox<a class="headerlink" href="#emptying-the-test-outbox" title="Permalink to this headline">¶</a></h4> <p>If you use Django’s custom <tt class="docutils literal"><span class="pre">TestCase</span></tt> class, the test runner will clear the contents of the test email outbox at the start of each test case.</p> <p>For more detail on email services during tests, see <a class="reference internal" href="#email-services">Email services</a> below.</p> </div> <div class="section" id="s-assertions"> <span id="s-id4"></span><span id="assertions"></span><span id="id4"></span><h4>Assertions<a class="headerlink" href="#assertions" title="Permalink to this headline">¶</a></h4> <p>As Python’s normal <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase" title="(in Python v2.7)"><tt class="xref py py-class docutils literal"><span class="pre">unittest.TestCase</span></tt></a> class implements assertion methods such as <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase.assertTrue" title="(in Python v2.7)"><tt class="xref py py-meth docutils literal"><span class="pre">assertTrue()</span></tt></a> and <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase.assertEqual" title="(in Python v2.7)"><tt class="xref py py-meth docutils literal"><span class="pre">assertEqual()</span></tt></a>, Django’s custom <a class="reference internal" href="#django.test.TestCase" title="django.test.TestCase"><tt class="xref py py-class docutils literal"><span class="pre">TestCase</span></tt></a> class provides a number of custom assertion methods that are useful for testing Web applications:</p> <p>The failure messages given by most of these assertion methods can be customized with the <tt class="docutils literal"><span class="pre">msg_prefix</span></tt> argument. This string will be prefixed to any failure message generated by the assertion. This allows you to provide additional details that may help you to identify the location and cause of an failure in your test suite.</p> <dl class="method"> <dt id="django.test.SimpleTestCase.assertRaisesMessage"> <tt class="descclassname">SimpleTestCase.</tt><tt class="descname">assertRaisesMessage</tt>(<em>expected_exception</em>, <em>expected_message</em>, <em>callable_obj=None</em>, <em>*args</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertRaisesMessage" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.4.</span> </div> <p>Asserts that execution of callable <tt class="docutils literal"><span class="pre">callable_obj</span></tt> raised the <tt class="docutils literal"><span class="pre">expected_exception</span></tt> exception and that such exception has an <tt class="docutils literal"><span class="pre">expected_message</span></tt> representation. Any other outcome is reported as a failure. Similar to unittest’s <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.TestCase.assertRaisesRegexp" title="(in Python v2.7)"><tt class="xref py py-meth docutils literal"><span class="pre">assertRaisesRegexp()</span></tt></a> with the difference that <tt class="docutils literal"><span class="pre">expected_message</span></tt> isn’t a regular expression.</p> </dd></dl> <dl class="method"> <dt id="django.test.SimpleTestCase.assertFieldOutput"> <tt class="descclassname">SimpleTestCase.</tt><tt class="descname">assertFieldOutput</tt>(<em>fieldclass</em>, <em>valid</em>, <em>invalid</em>, <em>field_args=None</em>, <em>field_kwargs=None</em>, <em>empty_value=u''</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertFieldOutput" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.4.</span> </div> <p>Asserts that a form field behaves correctly with various inputs.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>fieldclass</strong> – the class of the field to be tested.</li> <li><strong>valid</strong> – a dictionary mapping valid inputs to their expected cleaned values.</li> <li><strong>invalid</strong> – a dictionary mapping invalid inputs to one or more raised error messages.</li> <li><strong>field_args</strong> – the args passed to instantiate the field.</li> <li><strong>field_kwargs</strong> – the kwargs passed to instantiate the field.</li> <li><strong>empty_value</strong> – the expected clean output for inputs in <tt class="docutils literal"><span class="pre">EMPTY_VALUES</span></tt>.</li> </ul> </td> </tr> </tbody> </table> <p>For example, the following code tests that an <tt class="docutils literal"><span class="pre">EmailField</span></tt> accepts “<a class="reference external" href="mailto:a%40a.com">a<span>@</span>a<span>.</span>com</a>” as a valid email address, but rejects “aaa” with a reasonable error message:</p> <div class="highlight-python"><div class="highlight"><pre><span class="bp">self</span><span class="o">.</span><span class="n">assertFieldOutput</span><span class="p">(</span><span class="n">EmailField</span><span class="p">,</span> <span class="p">{</span><span class="s">'a@a.com'</span><span class="p">:</span> <span class="s">'a@a.com'</span><span class="p">},</span> <span class="p">{</span><span class="s">'aaa'</span><span class="p">:</span> <span class="p">[</span><span class="s">u'Enter a valid email address.'</span><span class="p">]})</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.test.TestCase.assertContains"> <tt class="descclassname">TestCase.</tt><tt class="descname">assertContains</tt>(<em>response</em>, <em>text</em>, <em>count=None</em>, <em>status_code=200</em>, <em>msg_prefix=''</em>, <em>html=False</em>)<a class="headerlink" href="#django.test.TestCase.assertContains" title="Permalink to this definition">¶</a></dt> <dd><p>Asserts that a <tt class="docutils literal"><span class="pre">Response</span></tt> instance produced the given <tt class="docutils literal"><span class="pre">status_code</span></tt> and that <tt class="docutils literal"><span class="pre">text</span></tt> appears in the content of the response. If <tt class="docutils literal"><span class="pre">count</span></tt> is provided, <tt class="docutils literal"><span class="pre">text</span></tt> must occur exactly <tt class="docutils literal"><span class="pre">count</span></tt> times in the response.</p> <div class="versionadded"> <span class="title">New in Django 1.4.</span> </div> <p>Set <tt class="docutils literal"><span class="pre">html</span></tt> to <tt class="docutils literal"><span class="pre">True</span></tt> to handle <tt class="docutils literal"><span class="pre">text</span></tt> as HTML. The comparison with the response content will be based on HTML semantics instead of character-by-character equality. Whitespace is ignored in most cases, attribute ordering is not significant. See <a class="reference internal" href="#django.test.SimpleTestCase.assertHTMLEqual" title="django.test.SimpleTestCase.assertHTMLEqual"><tt class="xref py py-meth docutils literal"><span class="pre">assertHTMLEqual()</span></tt></a> for more details.</p> </dd></dl> <dl class="method"> <dt id="django.test.TestCase.assertNotContains"> <tt class="descclassname">TestCase.</tt><tt class="descname">assertNotContains</tt>(<em>response</em>, <em>text</em>, <em>status_code=200</em>, <em>msg_prefix=''</em>, <em>html=False</em>)<a class="headerlink" href="#django.test.TestCase.assertNotContains" title="Permalink to this definition">¶</a></dt> <dd><p>Asserts that a <tt class="docutils literal"><span class="pre">Response</span></tt> instance produced the given <tt class="docutils literal"><span class="pre">status_code</span></tt> and that <tt class="docutils literal"><span class="pre">text</span></tt> does not appears in the content of the response.</p> <div class="versionadded"> <span class="title">New in Django 1.4.</span> </div> <p>Set <tt class="docutils literal"><span class="pre">html</span></tt> to <tt class="docutils literal"><span class="pre">True</span></tt> to handle <tt class="docutils literal"><span class="pre">text</span></tt> as HTML. The comparison with the response content will be based on HTML semantics instead of character-by-character equality. Whitespace is ignored in most cases, attribute ordering is not significant. See <a class="reference internal" href="#django.test.SimpleTestCase.assertHTMLEqual" title="django.test.SimpleTestCase.assertHTMLEqual"><tt class="xref py py-meth docutils literal"><span class="pre">assertHTMLEqual()</span></tt></a> for more details.</p> </dd></dl> <dl class="method"> <dt id="django.test.TestCase.assertFormError"> <tt class="descclassname">TestCase.</tt><tt class="descname">assertFormError</tt>(<em>response</em>, <em>form</em>, <em>field</em>, <em>errors</em>, <em>msg_prefix=''</em>)<a class="headerlink" href="#django.test.TestCase.assertFormError" title="Permalink to this definition">¶</a></dt> <dd><p>Asserts that a field on a form raises the provided list of errors when rendered on the form.</p> <p><tt class="docutils literal"><span class="pre">form</span></tt> is the name the <tt class="docutils literal"><span class="pre">Form</span></tt> instance was given in the template context.</p> <p><tt class="docutils literal"><span class="pre">field</span></tt> is the name of the field on the form to check. If <tt class="docutils literal"><span class="pre">field</span></tt> has a value of <tt class="docutils literal"><span class="pre">None</span></tt>, non-field errors (errors you can access via <tt class="docutils literal"><span class="pre">form.non_field_errors()</span></tt>) will be checked.</p> <p><tt class="docutils literal"><span class="pre">errors</span></tt> is an error string, or a list of error strings, that are expected as a result of form validation.</p> </dd></dl> <dl class="method"> <dt id="django.test.TestCase.assertTemplateUsed"> <tt class="descclassname">TestCase.</tt><tt class="descname">assertTemplateUsed</tt>(<em>response</em>, <em>template_name</em>, <em>msg_prefix=''</em>)<a class="headerlink" href="#django.test.TestCase.assertTemplateUsed" title="Permalink to this definition">¶</a></dt> <dd><p>Asserts that the template with the given name was used in rendering the response.</p> <p>The name is a string such as <tt class="docutils literal"><span class="pre">'admin/index.html'</span></tt>.</p> <div class="versionadded"> <span class="title">New in Django 1.4.</span> </div> <p>You can use this as a context manager, like this:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertTemplateUsed</span><span class="p">(</span><span class="s">'index.html'</span><span class="p">):</span> <span class="n">render_to_string</span><span class="p">(</span><span class="s">'index.html'</span><span class="p">)</span> <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertTemplateUsed</span><span class="p">(</span><span class="n">template_name</span><span class="o">=</span><span class="s">'index.html'</span><span class="p">):</span> <span class="n">render_to_string</span><span class="p">(</span><span class="s">'index.html'</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.test.TestCase.assertTemplateNotUsed"> <tt class="descclassname">TestCase.</tt><tt class="descname">assertTemplateNotUsed</tt>(<em>response</em>, <em>template_name</em>, <em>msg_prefix=''</em>)<a class="headerlink" href="#django.test.TestCase.assertTemplateNotUsed" title="Permalink to this definition">¶</a></dt> <dd><p>Asserts that the template with the given name was <em>not</em> used in rendering the response.</p> <div class="versionadded"> <span class="title">New in Django 1.4.</span> </div> <p>You can use this as a context manager in the same way as <a class="reference internal" href="#django.test.TestCase.assertTemplateUsed" title="django.test.TestCase.assertTemplateUsed"><tt class="xref py py-meth docutils literal"><span class="pre">assertTemplateUsed()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="django.test.TestCase.assertRedirects"> <tt class="descclassname">TestCase.</tt><tt class="descname">assertRedirects</tt>(<em>response</em>, <em>expected_url</em>, <em>status_code=302</em>, <em>target_status_code=200</em>, <em>msg_prefix=''</em>)<a class="headerlink" href="#django.test.TestCase.assertRedirects" title="Permalink to this definition">¶</a></dt> <dd><p>Asserts that the response return a <tt class="docutils literal"><span class="pre">status_code</span></tt> redirect status, it redirected to <tt class="docutils literal"><span class="pre">expected_url</span></tt> (including any GET data), and the final page was received with <tt class="docutils literal"><span class="pre">target_status_code</span></tt>.</p> <p>If your request used the <tt class="docutils literal"><span class="pre">follow</span></tt> argument, the <tt class="docutils literal"><span class="pre">expected_url</span></tt> and <tt class="docutils literal"><span class="pre">target_status_code</span></tt> will be the url and status code for the final point of the redirect chain.</p> </dd></dl> <dl class="method"> <dt id="django.test.TestCase.assertQuerysetEqual"> <tt class="descclassname">TestCase.</tt><tt class="descname">assertQuerysetEqual</tt>(<em>qs</em>, <em>values</em>, <em>transform=repr</em>, <em>ordered=True</em>)<a class="headerlink" href="#django.test.TestCase.assertQuerysetEqual" title="Permalink to this definition">¶</a></dt> <dd><p>Asserts that a queryset <tt class="docutils literal"><span class="pre">qs</span></tt> returns a particular list of values <tt class="docutils literal"><span class="pre">values</span></tt>.</p> <p>The comparison of the contents of <tt class="docutils literal"><span class="pre">qs</span></tt> and <tt class="docutils literal"><span class="pre">values</span></tt> is performed using the function <tt class="docutils literal"><span class="pre">transform</span></tt>; by default, this means that the <tt class="docutils literal"><span class="pre">repr()</span></tt> of each value is compared. Any other callable can be used if <tt class="docutils literal"><span class="pre">repr()</span></tt> doesn’t provide a unique or helpful comparison.</p> <p>By default, the comparison is also ordering dependent. If <tt class="docutils literal"><span class="pre">qs</span></tt> doesn’t provide an implicit ordering, you can set the <tt class="docutils literal"><span class="pre">ordered</span></tt> parameter to <tt class="docutils literal"><span class="pre">False</span></tt>, which turns the comparison into a Python set comparison.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.4:</span> The <tt class="docutils literal"><span class="pre">ordered</span></tt> parameter is new in version 1.4. In earlier versions, you would need to ensure the queryset is ordered consistently, possibly via an explicit <tt class="docutils literal"><span class="pre">order_by()</span></tt> call on the queryset prior to comparison.</div> </dd></dl> <dl class="method"> <dt id="django.test.TestCase.assertNumQueries"> <tt class="descclassname">TestCase.</tt><tt class="descname">assertNumQueries</tt>(<em>num</em>, <em>func</em>, <em>*args</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.test.TestCase.assertNumQueries" title="Permalink to this definition">¶</a></dt> <dd><p>Asserts that when <tt class="docutils literal"><span class="pre">func</span></tt> is called with <tt class="docutils literal"><span class="pre">*args</span></tt> and <tt class="docutils literal"><span class="pre">**kwargs</span></tt> that <tt class="docutils literal"><span class="pre">num</span></tt> database queries are executed.</p> <p>If a <tt class="docutils literal"><span class="pre">"using"</span></tt> key is present in <tt class="docutils literal"><span class="pre">kwargs</span></tt> it is used as the database alias for which to check the number of queries. If you wish to call a function with a <tt class="docutils literal"><span class="pre">using</span></tt> parameter you can do it by wrapping the call with a <tt class="docutils literal"><span class="pre">lambda</span></tt> to add an extra parameter:</p> <div class="highlight-python"><div class="highlight"><pre><span class="bp">self</span><span class="o">.</span><span class="n">assertNumQueries</span><span class="p">(</span><span class="mi">7</span><span class="p">,</span> <span class="k">lambda</span><span class="p">:</span> <span class="n">my_function</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="mi">7</span><span class="p">))</span> </pre></div> </div> <p>You can also use this as a context manager:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertNumQueries</span><span class="p">(</span><span class="mi">2</span><span class="p">):</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">"Aaron"</span><span class="p">)</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">"Daniel"</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.test.SimpleTestCase.assertHTMLEqual"> <tt class="descclassname">SimpleTestCase.</tt><tt class="descname">assertHTMLEqual</tt>(<em>html1</em>, <em>html2</em>, <em>msg=None</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertHTMLEqual" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.4.</span> </div> <p>Asserts that the strings <tt class="docutils literal"><span class="pre">html1</span></tt> and <tt class="docutils literal"><span class="pre">html2</span></tt> are equal. The comparison is based on HTML semantics. The comparison takes following things into account:</p> <ul class="simple"> <li>Whitespace before and after HTML tags is ignored.</li> <li>All types of whitespace are considered equivalent.</li> <li>All open tags are closed implicitly, e.g. when a surrounding tag is closed or the HTML document ends.</li> <li>Empty tags are equivalent to their self-closing version.</li> <li>The ordering of attributes of an HTML element is not significant.</li> <li>Attributes without an argument are equal to attributes that equal in name and value (see the examples).</li> </ul> <p>The following examples are valid tests and don’t raise any <tt class="docutils literal"><span class="pre">AssertionError</span></tt>:</p> <div class="highlight-python"><pre>self.assertHTMLEqual('<p>Hello <b>world!</p>', '''<p> Hello <b>world! <b/> </p>''') self.assertHTMLEqual( '<input type="checkbox" checked="checked" id="id_accept_terms" />', '<input id="id_accept_terms" type='checkbox' checked>')</pre> </div> <p><tt class="docutils literal"><span class="pre">html1</span></tt> and <tt class="docutils literal"><span class="pre">html2</span></tt> must be valid HTML. An <tt class="docutils literal"><span class="pre">AssertionError</span></tt> will be raised if one of them cannot be parsed.</p> </dd></dl> <dl class="method"> <dt id="django.test.SimpleTestCase.assertHTMLNotEqual"> <tt class="descclassname">SimpleTestCase.</tt><tt class="descname">assertHTMLNotEqual</tt>(<em>html1</em>, <em>html2</em>, <em>msg=None</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertHTMLNotEqual" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.4.</span> </div> <p>Asserts that the strings <tt class="docutils literal"><span class="pre">html1</span></tt> and <tt class="docutils literal"><span class="pre">html2</span></tt> are <em>not</em> equal. The comparison is based on HTML semantics. See <a class="reference internal" href="#django.test.SimpleTestCase.assertHTMLEqual" title="django.test.SimpleTestCase.assertHTMLEqual"><tt class="xref py py-meth docutils literal"><span class="pre">assertHTMLEqual()</span></tt></a> for details.</p> <p><tt class="docutils literal"><span class="pre">html1</span></tt> and <tt class="docutils literal"><span class="pre">html2</span></tt> must be valid HTML. An <tt class="docutils literal"><span class="pre">AssertionError</span></tt> will be raised if one of them cannot be parsed.</p> </dd></dl> <dl class="method"> <dt id="django.test.SimpleTestCase.assertXMLEqual"> <tt class="descclassname">SimpleTestCase.</tt><tt class="descname">assertXMLEqual</tt>(<em>xml1</em>, <em>xml2</em>, <em>msg=None</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertXMLEqual" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.5.</span> </div> <p>Asserts that the strings <tt class="docutils literal"><span class="pre">xml1</span></tt> and <tt class="docutils literal"><span class="pre">xml2</span></tt> are equal. The comparison is based on XML semantics. Similarily to <a class="reference internal" href="#django.test.SimpleTestCase.assertHTMLEqual" title="django.test.SimpleTestCase.assertHTMLEqual"><tt class="xref py py-meth docutils literal"><span class="pre">assertHTMLEqual()</span></tt></a>, the comparison is made on parsed content, hence only semantic differences are considered, not syntax differences. When unvalid XML is passed in any parameter, an <tt class="docutils literal"><span class="pre">AssertionError</span></tt> is always raised, even if both string are identical.</p> </dd></dl> <dl class="method"> <dt id="django.test.SimpleTestCase.assertXMLNotEqual"> <tt class="descclassname">SimpleTestCase.</tt><tt class="descname">assertXMLNotEqual</tt>(<em>xml1</em>, <em>xml2</em>, <em>msg=None</em>)<a class="headerlink" href="#django.test.SimpleTestCase.assertXMLNotEqual" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.5.</span> </div> <p>Asserts that the strings <tt class="docutils literal"><span class="pre">xml1</span></tt> and <tt class="docutils literal"><span class="pre">xml2</span></tt> are <em>not</em> equal. The comparison is based on XML semantics. See <a class="reference internal" href="#django.test.SimpleTestCase.assertXMLEqual" title="django.test.SimpleTestCase.assertXMLEqual"><tt class="xref py py-meth docutils literal"><span class="pre">assertXMLEqual()</span></tt></a> for details.</p> </dd></dl> </div> </div> <div class="section" id="s-email-services"> <span id="s-topics-testing-email"></span><span id="email-services"></span><span id="topics-testing-email"></span><h3>Email services<a class="headerlink" href="#email-services" title="Permalink to this headline">¶</a></h3> <p>If any of your Django views send email using <a class="reference internal" href="../email.html"><em>Django’s email functionality</em></a>, you probably don’t want to send email each time you run a test using that view. For this reason, Django’s test runner automatically redirects all Django-sent email to a dummy outbox. This lets you test every aspect of sending email – from the number of messages sent to the contents of each message – without actually sending the messages.</p> <p>The test runner accomplishes this by transparently replacing the normal email backend with a testing backend. (Don’t worry – this has no effect on any other email senders outside of Django, such as your machine’s mail server, if you’re running one.)</p> <dl class="data"> <dt id="django.core.mail.django.core.mail.outbox"> <tt class="descclassname">django.core.mail.</tt><tt class="descname">outbox</tt><a class="headerlink" href="#django.core.mail.django.core.mail.outbox" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>During test running, each outgoing email is saved in <tt class="docutils literal"><span class="pre">django.core.mail.outbox</span></tt>. This is a simple list of all <a class="reference internal" href="../email.html#django.core.mail.EmailMessage" title="django.core.mail.EmailMessage"><tt class="xref py py-class docutils literal"><span class="pre">EmailMessage</span></tt></a> instances that have been sent. The <tt class="docutils literal"><span class="pre">outbox</span></tt> attribute is a special attribute that is created <em>only</em> when the <tt class="docutils literal"><span class="pre">locmem</span></tt> email backend is used. It doesn’t normally exist as part of the <a class="reference internal" href="../email.html#module-django.core.mail" title="django.core.mail: Helpers to easily send email."><tt class="xref py py-mod docutils literal"><span class="pre">django.core.mail</span></tt></a> module and you can’t import it directly. The code below shows how to access this attribute correctly.</p> <p>Here’s an example test that examines <tt class="docutils literal"><span class="pre">django.core.mail.outbox</span></tt> for length and contents:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">mail</span> <span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span> <span class="k">class</span> <span class="nc">EmailTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span> <span class="k">def</span> <span class="nf">test_send_email</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c"># Send message.</span> <span class="n">mail</span><span class="o">.</span><span class="n">send_mail</span><span class="p">(</span><span class="s">'Subject here'</span><span class="p">,</span> <span class="s">'Here is the message.'</span><span class="p">,</span> <span class="s">'from@example.com'</span><span class="p">,</span> <span class="p">[</span><span class="s">'to@example.com'</span><span class="p">],</span> <span class="n">fail_silently</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <span class="c"># Test that one message has been sent.</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">mail</span><span class="o">.</span><span class="n">outbox</span><span class="p">),</span> <span class="mi">1</span><span class="p">)</span> <span class="c"># Verify that the subject of the first message is correct.</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">mail</span><span class="o">.</span><span class="n">outbox</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">subject</span><span class="p">,</span> <span class="s">'Subject here'</span><span class="p">)</span> </pre></div> </div> <p>As noted <a class="reference internal" href="#emptying-test-outbox"><em>previously</em></a>, the test outbox is emptied at the start of every test in a Django <tt class="docutils literal"><span class="pre">TestCase</span></tt>. To empty the outbox manually, assign the empty list to <tt class="docutils literal"><span class="pre">mail.outbox</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">mail</span> <span class="c"># Empty the test outbox</span> <span class="n">mail</span><span class="o">.</span><span class="n">outbox</span> <span class="o">=</span> <span class="p">[]</span> </pre></div> </div> </div> <div class="section" id="s-skipping-tests"> <span id="s-id5"></span><span id="skipping-tests"></span><span id="id5"></span><h3>Skipping tests<a class="headerlink" href="#skipping-tests" title="Permalink to this headline">¶</a></h3> <p>The unittest library provides the <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.skipIf" title="(in Python v2.7)"><tt class="xref py py-func docutils literal"><span class="pre">@skipIf</span></tt></a> and <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.skipUnless" title="(in Python v2.7)"><tt class="xref py py-func docutils literal"><span class="pre">@skipUnless</span></tt></a> decorators to allow you to skip tests if you know ahead of time that those tests are going to fail under certain conditions.</p> <p>For example, if your test requires a particular optional library in order to succeed, you could decorate the test case with <a class="reference external" href="http://docs.python.org/2.7/library/unittest.html#unittest.skipIf" title="(in Python v2.7)"><tt class="xref py py-func docutils literal"><span class="pre">@skipIf</span></tt></a>. Then, the test runner will report that the test wasn’t executed and why, instead of failing the test or omitting the test altogether.</p> <p>To supplement these test skipping behaviors, Django provides two additional skip decorators. Instead of testing a generic boolean, these decorators check the capabilities of the database, and skip the test if the database doesn’t support a specific named feature.</p> <p>The decorators use a string identifier to describe database features. This string corresponds to attributes of the database connection features class. See <tt class="docutils literal"><span class="pre">django.db.backends.BaseDatabaseFeatures</span></tt> class for a full list of database features that can be used as a basis for skipping tests.</p> <dl class="function"> <dt id="django.test.skipIfDBFeature"> <tt class="descname">skipIfDBFeature</tt>(<em>feature_name_string</em>)<a class="headerlink" href="#django.test.skipIfDBFeature" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Skip the decorated test if the named database feature is supported.</p> <p>For example, the following test will not be executed if the database supports transactions (e.g., it would <em>not</em> run under PostgreSQL, but it would under MySQL with MyISAM tables):</p> <div class="highlight-python"><pre>class MyTests(TestCase): @skipIfDBFeature('supports_transactions') def test_transaction_behavior(self): # ... conditional test code</pre> </div> <dl class="function"> <dt id="django.test.skipUnlessDBFeature"> <tt class="descname">skipUnlessDBFeature</tt>(<em>feature_name_string</em>)<a class="headerlink" href="#django.test.skipUnlessDBFeature" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Skip the decorated test if the named database feature is <em>not</em> supported.</p> <p>For example, the following test will only be executed if the database supports transactions (e.g., it would run under PostgreSQL, but <em>not</em> under MySQL with MyISAM tables):</p> <div class="highlight-python"><pre>class MyTests(TestCase): @skipUnlessDBFeature('supports_transactions') def test_transaction_behavior(self): # ... conditional test code</pre> </div> </div> </div> </div> </div> </div> </div> <div class="yui-b" id="sidebar"> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h3><a href="../../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">Testing Django applications</a><ul> <li><a class="reference internal" href="#writing-tests">Writing tests</a></li> <li><a class="reference internal" href="#running-tests">Running tests</a><ul> <li><a class="reference internal" href="#the-test-database">The test database</a></li> <li><a class="reference internal" href="#order-in-which-tests-are-executed">Order in which tests are executed</a></li> <li><a class="reference internal" href="#other-test-conditions">Other test conditions</a></li> <li><a class="reference internal" href="#understanding-the-test-output">Understanding the test output</a></li> <li><a class="reference internal" href="#speeding-up-the-tests">Speeding up the tests</a></li> </ul> </li> <li><a class="reference internal" href="#testing-tools">Testing tools</a><ul> <li><a class="reference internal" href="#module-django.test.client">The test client</a><ul> <li><a class="reference internal" href="#overview-and-a-quick-example">Overview and a quick example</a></li> <li><a class="reference internal" href="#making-requests">Making requests</a></li> <li><a class="reference internal" href="#testing-responses">Testing responses</a></li> <li><a class="reference internal" href="#exceptions">Exceptions</a></li> <li><a class="reference internal" href="#persistent-state">Persistent state</a></li> <li><a class="reference internal" href="#example">Example</a></li> </ul> </li> <li><a class="reference internal" href="#provided-test-case-classes">Provided test case classes</a><ul> <li><a class="reference internal" href="#simpletestcase">SimpleTestCase</a></li> <li><a class="reference internal" href="#transactiontestcase">TransactionTestCase</a></li> <li><a class="reference internal" href="#testcase">TestCase</a></li> <li><a class="reference internal" href="#liveservertestcase">LiveServerTestCase</a></li> </ul> </li> <li><a class="reference internal" href="#test-cases-features">Test cases features</a><ul> <li><a class="reference internal" href="#default-test-client">Default test client</a></li> <li><a class="reference internal" href="#customizing-the-test-client">Customizing the test client</a></li> <li><a class="reference internal" href="#fixture-loading">Fixture loading</a></li> <li><a class="reference internal" href="#urlconf-configuration">URLconf configuration</a></li> <li><a class="reference internal" href="#multi-database-support">Multi-database support</a></li> <li><a class="reference internal" href="#overriding-settings">Overriding settings</a></li> <li><a class="reference internal" href="#emptying-the-test-outbox">Emptying the test outbox</a></li> <li><a class="reference internal" href="#assertions">Assertions</a></li> </ul> </li> <li><a class="reference internal" href="#email-services">Email services</a></li> <li><a class="reference internal" href="#skipping-tests">Skipping tests</a></li> </ul> </li> </ul> </li> </ul> <h3>Browse</h3> <ul> <li>Prev: <a href="index.html">Testing in Django</a></li> <li>Next: <a href="doctests.html">Django and doctests</a></li> </ul> <h3>You are here:</h3> <ul> <li> <a href="../../index.html">Django 1.5.8 documentation</a> <ul><li><a href="../index.html">Using Django</a> <ul><li><a href="index.html">Testing in Django</a> <ul><li>Testing Django applications</li></ul> </li></ul></li></ul> </li> </ul> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../../_sources/topics/testing/overview.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <h3>Last update:</h3> <p class="topless">May 15, 2014</p> </div> </div> <div id="ft"> <div class="nav"> « <a href="index.html" title="Testing in Django">previous</a> | <a href="../index.html" title="Using Django" accesskey="U">up</a> | <a href="doctests.html" title="Django and doctests">next</a> »</div> </div> </div> <div class="clearer"></div> </div> </body> </html>