overview.txt 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774
  1. ===========================
  2. Testing Django applications
  3. ===========================
  4. .. module:: django.test
  5. :synopsis: Testing tools for Django applications.
  6. .. seealso::
  7. The :doc:`testing tutorial </intro/tutorial05>` and the
  8. :doc:`advanced testing topics </topics/testing/advanced>`.
  9. This document is split into two primary sections. First, we explain how to write
  10. tests with Django. Then, we explain how to run them.
  11. Writing tests
  12. =============
  13. Django's unit tests use a Python standard library module: :mod:`unittest`. This
  14. module defines tests in class-based approach.
  15. .. admonition:: unittest2
  16. Python 2.7 introduced some major changes to the unittest library,
  17. adding some extremely useful features. To ensure that every Django
  18. project can benefit from these new features, Django ships with a
  19. copy of unittest2_, a copy of the Python 2.7 unittest library,
  20. backported for Python 2.5 compatibility.
  21. To access this library, Django provides the
  22. ``django.utils.unittest`` module alias. If you are using Python
  23. 2.7, or you have installed unittest2 locally, Django will map the
  24. alias to the installed version of the unittest library. Otherwise,
  25. Django will use its own bundled version of unittest2.
  26. To use this alias, simply use::
  27. from django.utils import unittest
  28. wherever you would have historically used::
  29. import unittest
  30. If you want to continue to use the base unittest library, you can --
  31. you just won't get any of the nice new unittest2 features.
  32. .. _unittest2: http://pypi.python.org/pypi/unittest2
  33. For a given Django application, the test runner looks for unit tests in two
  34. places:
  35. * The ``models.py`` file. The test runner looks for any subclass of
  36. :class:`unittest.TestCase` in this module.
  37. * A file called ``tests.py`` in the application directory -- i.e., the
  38. directory that holds ``models.py``. Again, the test runner looks for any
  39. subclass of :class:`unittest.TestCase` in this module.
  40. Here is an example :class:`unittest.TestCase` subclass::
  41. from django.utils import unittest
  42. from myapp.models import Animal
  43. class AnimalTestCase(unittest.TestCase):
  44. def setUp(self):
  45. self.lion = Animal(name="lion", sound="roar")
  46. self.cat = Animal(name="cat", sound="meow")
  47. def test_animals_can_speak(self):
  48. """Animals that can speak are correctly identified"""
  49. self.assertEqual(self.lion.speak(), 'The lion says "roar"')
  50. self.assertEqual(self.cat.speak(), 'The cat says "meow"')
  51. When you :ref:`run your tests <running-tests>`, the default behavior of the test
  52. utility is to find all the test cases (that is, subclasses of
  53. :class:`unittest.TestCase`) in ``models.py`` and ``tests.py``, automatically
  54. build a test suite out of those test cases, and run that suite.
  55. There is a second way to define the test suite for a module: if you define a
  56. function called ``suite()`` in either ``models.py`` or ``tests.py``, the
  57. Django test runner will use that function to construct the test suite for that
  58. module. This follows the `suggested organization`_ for unit tests. See the
  59. Python documentation for more details on how to construct a complex test
  60. suite.
  61. For more details about :mod:`unittest`, see the Python documentation.
  62. .. _suggested organization: http://docs.python.org/library/unittest.html#organizing-tests
  63. .. warning::
  64. If your tests rely on database access such as creating or querying models,
  65. be sure to create your test classes as subclasses of
  66. :class:`django.test.TestCase` rather than :class:`unittest.TestCase`.
  67. In the example above, we instantiate some models but do not save them to
  68. the database. Using :class:`unittest.TestCase` avoids the cost of running
  69. each test in a transaction and flushing the database, but for most
  70. applications the scope of tests you will be able to write this way will
  71. be fairly limited, so it's easiest to use :class:`django.test.TestCase`.
  72. .. _running-tests:
  73. Running tests
  74. =============
  75. Once you've written tests, run them using the :djadmin:`test` command of
  76. your project's ``manage.py`` utility::
  77. $ ./manage.py test
  78. By default, this will run every test in every application in
  79. :setting:`INSTALLED_APPS`. If you only want to run tests for a particular
  80. application, add the application name to the command line. For example, if your
  81. :setting:`INSTALLED_APPS` contains ``'myproject.polls'`` and
  82. ``'myproject.animals'``, you can run the ``myproject.animals`` unit tests alone
  83. with this command::
  84. $ ./manage.py test animals
  85. Note that we used ``animals``, not ``myproject.animals``.
  86. You can be even *more* specific by naming an individual test case. To
  87. run a single test case in an application (for example, the
  88. ``AnimalTestCase`` described in the "Writing unit tests" section), add
  89. the name of the test case to the label on the command line::
  90. $ ./manage.py test animals.AnimalTestCase
  91. And it gets even more granular than that! To run a *single* test
  92. method inside a test case, add the name of the test method to the
  93. label::
  94. $ ./manage.py test animals.AnimalTestCase.test_animals_can_speak
  95. You can use the same rules if you're using doctests. Django will use the
  96. test label as a path to the test method or class that you want to run.
  97. If your ``models.py`` or ``tests.py`` has a function with a doctest, or
  98. class with a class-level doctest, you can invoke that test by appending the
  99. name of the test method or class to the label::
  100. $ ./manage.py test animals.classify
  101. If you want to run the doctest for a specific method in a class, add the
  102. name of the method to the label::
  103. $ ./manage.py test animals.Classifier.run
  104. If you're using a ``__test__`` dictionary to specify doctests for a
  105. module, Django will use the label as a key in the ``__test__`` dictionary
  106. for defined in ``models.py`` and ``tests.py``.
  107. If you press ``Ctrl-C`` while the tests are running, the test runner will
  108. wait for the currently running test to complete and then exit gracefully.
  109. During a graceful exit the test runner will output details of any test
  110. failures, report on how many tests were run and how many errors and failures
  111. were encountered, and destroy any test databases as usual. Thus pressing
  112. ``Ctrl-C`` can be very useful if you forget to pass the :djadminopt:`--failfast`
  113. option, notice that some tests are unexpectedly failing, and want to get details
  114. on the failures without waiting for the full test run to complete.
  115. If you do not want to wait for the currently running test to finish, you
  116. can press ``Ctrl-C`` a second time and the test run will halt immediately,
  117. but not gracefully. No details of the tests run before the interruption will
  118. be reported, and any test databases created by the run will not be destroyed.
  119. .. admonition:: Test with warnings enabled
  120. It's a good idea to run your tests with Python warnings enabled:
  121. ``python -Wall manage.py test``. The ``-Wall`` flag tells Python to
  122. display deprecation warnings. Django, like many other Python libraries,
  123. uses these warnings to flag when features are going away. It also might
  124. flag areas in your code that aren't strictly wrong but could benefit
  125. from a better implementation.
  126. .. _the-test-database:
  127. The test database
  128. -----------------
  129. Tests that require a database (namely, model tests) will not use your "real"
  130. (production) database. Separate, blank databases are created for the tests.
  131. Regardless of whether the tests pass or fail, the test databases are destroyed
  132. when all the tests have been executed.
  133. By default the test databases get their names by prepending ``test_``
  134. to the value of the :setting:`NAME` settings for the databases
  135. defined in :setting:`DATABASES`. When using the SQLite database engine
  136. the tests will by default use an in-memory database (i.e., the
  137. database will be created in memory, bypassing the filesystem
  138. entirely!). If you want to use a different database name, specify
  139. :setting:`TEST_NAME` in the dictionary for any given database in
  140. :setting:`DATABASES`.
  141. Aside from using a separate database, the test runner will otherwise
  142. use all of the same database settings you have in your settings file:
  143. :setting:`ENGINE <DATABASE-ENGINE>`, :setting:`USER`, :setting:`HOST`, etc. The
  144. test database is created by the user specified by :setting:`USER`, so you'll
  145. need to make sure that the given user account has sufficient privileges to
  146. create a new database on the system.
  147. For fine-grained control over the character encoding of your test
  148. database, use the :setting:`TEST_CHARSET` option. If you're using
  149. MySQL, you can also use the :setting:`TEST_COLLATION` option to
  150. control the particular collation used by the test database. See the
  151. :doc:`settings documentation </ref/settings>` for details of these
  152. advanced settings.
  153. .. admonition:: Finding data from your production database when running tests?
  154. If your code attempts to access the database when its modules are compiled,
  155. this will occur *before* the test database is set up, with potentially
  156. unexpected results. For example, if you have a database query in
  157. module-level code and a real database exists, production data could pollute
  158. your tests. *It is a bad idea to have such import-time database queries in
  159. your code* anyway - rewrite your code so that it doesn't do this.
  160. .. seealso::
  161. The :ref:`advanced multi-db testing topics <topics-testing-advanced-multidb>`.
  162. Order in which tests are executed
  163. ---------------------------------
  164. In order to guarantee that all ``TestCase`` code starts with a clean database,
  165. the Django test runner reorders tests in the following way:
  166. * First, all unittests (including :class:`unittest.TestCase`,
  167. :class:`~django.test.SimpleTestCase`, :class:`~django.test.TestCase` and
  168. :class:`~django.test.TransactionTestCase`) are run with no particular ordering
  169. guaranteed nor enforced among them.
  170. * Then any other tests (e.g. doctests) that may alter the database without
  171. restoring it to its original state are run.
  172. .. versionchanged:: 1.5
  173. Before Django 1.5, the only guarantee was that
  174. :class:`~django.test.TestCase` tests were always ran first, before any other
  175. tests.
  176. .. note::
  177. The new ordering of tests may reveal unexpected dependencies on test case
  178. ordering. This is the case with doctests that relied on state left in the
  179. database by a given :class:`~django.test.TransactionTestCase` test, they
  180. must be updated to be able to run independently.
  181. Other test conditions
  182. ---------------------
  183. Regardless of the value of the :setting:`DEBUG` setting in your configuration
  184. file, all Django tests run with :setting:`DEBUG`\=False. This is to ensure that
  185. the observed output of your code matches what will be seen in a production
  186. setting.
  187. Caches are not cleared after each test, and running "manage.py test fooapp" can
  188. insert data from the tests into the cache of a live system if you run your
  189. tests in production because, unlike databases, a separate "test cache" is not
  190. used. This behavior `may change`_ in the future.
  191. .. _may change: https://code.djangoproject.com/ticket/11505
  192. Understanding the test output
  193. -----------------------------
  194. When you run your tests, you'll see a number of messages as the test runner
  195. prepares itself. You can control the level of detail of these messages with the
  196. ``verbosity`` option on the command line::
  197. Creating test database...
  198. Creating table myapp_animal
  199. Creating table myapp_mineral
  200. Loading 'initial_data' fixtures...
  201. No fixtures found.
  202. This tells you that the test runner is creating a test database, as described
  203. in the previous section.
  204. Once the test database has been created, Django will run your tests.
  205. If everything goes well, you'll see something like this::
  206. ----------------------------------------------------------------------
  207. Ran 22 tests in 0.221s
  208. OK
  209. If there are test failures, however, you'll see full details about which tests
  210. failed::
  211. ======================================================================
  212. FAIL: Doctest: ellington.core.throttle.models
  213. ----------------------------------------------------------------------
  214. Traceback (most recent call last):
  215. File "/dev/django/test/doctest.py", line 2153, in runTest
  216. raise self.failureException(self.format_failure(new.getvalue()))
  217. AssertionError: Failed doctest test for myapp.models
  218. File "/dev/myapp/models.py", line 0, in models
  219. ----------------------------------------------------------------------
  220. File "/dev/myapp/models.py", line 14, in myapp.models
  221. Failed example:
  222. throttle.check("actor A", "action one", limit=2, hours=1)
  223. Expected:
  224. True
  225. Got:
  226. False
  227. ----------------------------------------------------------------------
  228. Ran 2 tests in 0.048s
  229. FAILED (failures=1)
  230. A full explanation of this error output is beyond the scope of this document,
  231. but it's pretty intuitive. You can consult the documentation of Python's
  232. :mod:`unittest` library for details.
  233. Note that the return code for the test-runner script is 1 for any number of
  234. failed and erroneous tests. If all the tests pass, the return code is 0. This
  235. feature is useful if you're using the test-runner script in a shell script and
  236. need to test for success or failure at that level.
  237. Speeding up the tests
  238. ---------------------
  239. In recent versions of Django, the default password hasher is rather slow by
  240. design. If during your tests you are authenticating many users, you may want
  241. to use a custom settings file and set the :setting:`PASSWORD_HASHERS` setting
  242. to a faster hashing algorithm::
  243. PASSWORD_HASHERS = (
  244. 'django.contrib.auth.hashers.MD5PasswordHasher',
  245. )
  246. Don't forget to also include in :setting:`PASSWORD_HASHERS` any hashing
  247. algorithm used in fixtures, if any.
  248. Testing tools
  249. =============
  250. Django provides a small set of tools that come in handy when writing tests.
  251. .. _test-client:
  252. The test client
  253. ---------------
  254. .. module:: django.test.client
  255. :synopsis: Django's test client.
  256. The test client is a Python class that acts as a dummy Web browser, allowing
  257. you to test your views and interact with your Django-powered application
  258. programmatically.
  259. Some of the things you can do with the test client are:
  260. * Simulate GET and POST requests on a URL and observe the response --
  261. everything from low-level HTTP (result headers and status codes) to
  262. page content.
  263. * Test that the correct view is executed for a given URL.
  264. * Test that a given request is rendered by a given Django template, with
  265. a template context that contains certain values.
  266. Note that the test client is not intended to be a replacement for Selenium_ or
  267. other "in-browser" frameworks. Django's test client has a different focus. In
  268. short:
  269. * Use Django's test client to establish that the correct view is being
  270. called and that the view is collecting the correct context data.
  271. * Use in-browser frameworks like Selenium_ to test *rendered* HTML and the
  272. *behavior* of Web pages, namely JavaScript functionality. Django also
  273. provides special support for those frameworks; see the section on
  274. :class:`~django.test.LiveServerTestCase` for more details.
  275. A comprehensive test suite should use a combination of both test types.
  276. Overview and a quick example
  277. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  278. To use the test client, instantiate ``django.test.client.Client`` and retrieve
  279. Web pages::
  280. >>> from django.test.client import Client
  281. >>> c = Client()
  282. >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
  283. >>> response.status_code
  284. 200
  285. >>> response = c.get('/customer/details/')
  286. >>> response.content
  287. '<!DOCTYPE html...'
  288. As this example suggests, you can instantiate ``Client`` from within a session
  289. of the Python interactive interpreter.
  290. Note a few important things about how the test client works:
  291. * The test client does *not* require the Web server to be running. In fact,
  292. it will run just fine with no Web server running at all! That's because
  293. it avoids the overhead of HTTP and deals directly with the Django
  294. framework. This helps make the unit tests run quickly.
  295. * When retrieving pages, remember to specify the *path* of the URL, not the
  296. whole domain. For example, this is correct::
  297. >>> c.get('/login/')
  298. This is incorrect::
  299. >>> c.get('http://www.example.com/login/')
  300. The test client is not capable of retrieving Web pages that are not
  301. powered by your Django project. If you need to retrieve other Web pages,
  302. use a Python standard library module such as :mod:`urllib` or
  303. :mod:`urllib2`.
  304. * To resolve URLs, the test client uses whatever URLconf is pointed-to by
  305. your :setting:`ROOT_URLCONF` setting.
  306. * Although the above example would work in the Python interactive
  307. interpreter, some of the test client's functionality, notably the
  308. template-related functionality, is only available *while tests are
  309. running*.
  310. The reason for this is that Django's test runner performs a bit of black
  311. magic in order to determine which template was loaded by a given view.
  312. This black magic (essentially a patching of Django's template system in
  313. memory) only happens during test running.
  314. * By default, the test client will disable any CSRF checks
  315. performed by your site.
  316. If, for some reason, you *want* the test client to perform CSRF
  317. checks, you can create an instance of the test client that
  318. enforces CSRF checks. To do this, pass in the
  319. ``enforce_csrf_checks`` argument when you construct your
  320. client::
  321. >>> from django.test import Client
  322. >>> csrf_client = Client(enforce_csrf_checks=True)
  323. Making requests
  324. ~~~~~~~~~~~~~~~
  325. Use the ``django.test.client.Client`` class to make requests.
  326. .. class:: Client(enforce_csrf_checks=False, **defaults)
  327. It requires no arguments at time of construction. However, you can use
  328. keywords arguments to specify some default headers. For example, this will
  329. send a ``User-Agent`` HTTP header in each request::
  330. >>> c = Client(HTTP_USER_AGENT='Mozilla/5.0')
  331. The values from the ``extra`` keywords arguments passed to
  332. :meth:`~django.test.client.Client.get()`,
  333. :meth:`~django.test.client.Client.post()`, etc. have precedence over
  334. the defaults passed to the class constructor.
  335. The ``enforce_csrf_checks`` argument can be used to test CSRF
  336. protection (see above).
  337. Once you have a ``Client`` instance, you can call any of the following
  338. methods:
  339. .. method:: Client.get(path, data={}, follow=False, **extra)
  340. Makes a GET request on the provided ``path`` and returns a ``Response``
  341. object, which is documented below.
  342. The key-value pairs in the ``data`` dictionary are used to create a GET
  343. data payload. For example::
  344. >>> c = Client()
  345. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
  346. ...will result in the evaluation of a GET request equivalent to::
  347. /customers/details/?name=fred&age=7
  348. The ``extra`` keyword arguments parameter can be used to specify
  349. headers to be sent in the request. For example::
  350. >>> c = Client()
  351. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
  352. ... HTTP_X_REQUESTED_WITH='XMLHttpRequest')
  353. ...will send the HTTP header ``HTTP_X_REQUESTED_WITH`` to the
  354. details view, which is a good way to test code paths that use the
  355. :meth:`django.http.HttpRequest.is_ajax()` method.
  356. .. admonition:: CGI specification
  357. The headers sent via ``**extra`` should follow CGI_ specification.
  358. For example, emulating a different "Host" header as sent in the
  359. HTTP request from the browser to the server should be passed
  360. as ``HTTP_HOST``.
  361. .. _CGI: http://www.w3.org/CGI/
  362. If you already have the GET arguments in URL-encoded form, you can
  363. use that encoding instead of using the data argument. For example,
  364. the previous GET request could also be posed as::
  365. >>> c = Client()
  366. >>> c.get('/customers/details/?name=fred&age=7')
  367. If you provide a URL with both an encoded GET data and a data argument,
  368. the data argument will take precedence.
  369. If you set ``follow`` to ``True`` the client will follow any redirects
  370. and a ``redirect_chain`` attribute will be set in the response object
  371. containing tuples of the intermediate urls and status codes.
  372. If you had a URL ``/redirect_me/`` that redirected to ``/next/``, that
  373. redirected to ``/final/``, this is what you'd see::
  374. >>> response = c.get('/redirect_me/', follow=True)
  375. >>> response.redirect_chain
  376. [(u'http://testserver/next/', 302), (u'http://testserver/final/', 302)]
  377. .. method:: Client.post(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
  378. Makes a POST request on the provided ``path`` and returns a
  379. ``Response`` object, which is documented below.
  380. The key-value pairs in the ``data`` dictionary are used to submit POST
  381. data. For example::
  382. >>> c = Client()
  383. >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
  384. ...will result in the evaluation of a POST request to this URL::
  385. /login/
  386. ...with this POST data::
  387. name=fred&passwd=secret
  388. If you provide ``content_type`` (e.g. :mimetype:`text/xml` for an XML
  389. payload), the contents of ``data`` will be sent as-is in the POST
  390. request, using ``content_type`` in the HTTP ``Content-Type`` header.
  391. If you don't provide a value for ``content_type``, the values in
  392. ``data`` will be transmitted with a content type of
  393. :mimetype:`multipart/form-data`. In this case, the key-value pairs in
  394. ``data`` will be encoded as a multipart message and used to create the
  395. POST data payload.
  396. To submit multiple values for a given key -- for example, to specify
  397. the selections for a ``<select multiple>`` -- provide the values as a
  398. list or tuple for the required key. For example, this value of ``data``
  399. would submit three selected values for the field named ``choices``::
  400. {'choices': ('a', 'b', 'd')}
  401. Submitting files is a special case. To POST a file, you need only
  402. provide the file field name as a key, and a file handle to the file you
  403. wish to upload as a value. For example::
  404. >>> c = Client()
  405. >>> with open('wishlist.doc') as fp:
  406. ... c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
  407. (The name ``attachment`` here is not relevant; use whatever name your
  408. file-processing code expects.)
  409. Note that if you wish to use the same file handle for multiple
  410. ``post()`` calls then you will need to manually reset the file
  411. pointer between posts. The easiest way to do this is to
  412. manually close the file after it has been provided to
  413. ``post()``, as demonstrated above.
  414. You should also ensure that the file is opened in a way that
  415. allows the data to be read. If your file contains binary data
  416. such as an image, this means you will need to open the file in
  417. ``rb`` (read binary) mode.
  418. The ``extra`` argument acts the same as for :meth:`Client.get`.
  419. If the URL you request with a POST contains encoded parameters, these
  420. parameters will be made available in the request.GET data. For example,
  421. if you were to make the request::
  422. >>> c.post('/login/?visitor=true', {'name': 'fred', 'passwd': 'secret'})
  423. ... the view handling this request could interrogate request.POST
  424. to retrieve the username and password, and could interrogate request.GET
  425. to determine if the user was a visitor.
  426. If you set ``follow`` to ``True`` the client will follow any redirects
  427. and a ``redirect_chain`` attribute will be set in the response object
  428. containing tuples of the intermediate urls and status codes.
  429. .. method:: Client.head(path, data={}, follow=False, **extra)
  430. Makes a HEAD request on the provided ``path`` and returns a
  431. ``Response`` object. This method works just like :meth:`Client.get`,
  432. including the ``follow`` and ``extra`` arguments, except it does not
  433. return a message body.
  434. .. method:: Client.options(path, data='', content_type='application/octet-stream', follow=False, **extra)
  435. Makes an OPTIONS request on the provided ``path`` and returns a
  436. ``Response`` object. Useful for testing RESTful interfaces.
  437. When ``data`` is provided, it is used as the request body, and
  438. a ``Content-Type`` header is set to ``content_type``.
  439. .. versionchanged:: 1.5
  440. :meth:`Client.options` used to process ``data`` like
  441. :meth:`Client.get`.
  442. The ``follow`` and ``extra`` arguments act the same as for
  443. :meth:`Client.get`.
  444. .. method:: Client.put(path, data='', content_type='application/octet-stream', follow=False, **extra)
  445. Makes a PUT request on the provided ``path`` and returns a
  446. ``Response`` object. Useful for testing RESTful interfaces.
  447. When ``data`` is provided, it is used as the request body, and
  448. a ``Content-Type`` header is set to ``content_type``.
  449. .. versionchanged:: 1.5
  450. :meth:`Client.put` used to process ``data`` like
  451. :meth:`Client.post`.
  452. The ``follow`` and ``extra`` arguments act the same as for
  453. :meth:`Client.get`.
  454. .. method:: Client.patch(path, data='', content_type='application/octet-stream', follow=False, **extra)
  455. Makes a PATCH request on the provided ``path`` and returns a
  456. ``Response`` object. Useful for testing RESTful interfaces.
  457. The ``follow`` and ``extra`` arguments act the same as for
  458. :meth:`Client.get`.
  459. .. method:: Client.delete(path, data='', content_type='application/octet-stream', follow=False, **extra)
  460. Makes an DELETE request on the provided ``path`` and returns a
  461. ``Response`` object. Useful for testing RESTful interfaces.
  462. When ``data`` is provided, it is used as the request body, and
  463. a ``Content-Type`` header is set to ``content_type``.
  464. .. versionchanged:: 1.5
  465. :meth:`Client.delete` used to process ``data`` like
  466. :meth:`Client.get`.
  467. The ``follow`` and ``extra`` arguments act the same as for
  468. :meth:`Client.get`.
  469. .. method:: Client.login(**credentials)
  470. If your site uses Django's :doc:`authentication system</topics/auth/index>`
  471. and you deal with logging in users, you can use the test client's
  472. ``login()`` method to simulate the effect of a user logging into the
  473. site.
  474. After you call this method, the test client will have all the cookies
  475. and session data required to pass any login-based tests that may form
  476. part of a view.
  477. The format of the ``credentials`` argument depends on which
  478. :ref:`authentication backend <authentication-backends>` you're using
  479. (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
  480. setting). If you're using the standard authentication backend provided
  481. by Django (``ModelBackend``), ``credentials`` should be the user's
  482. username and password, provided as keyword arguments::
  483. >>> c = Client()
  484. >>> c.login(username='fred', password='secret')
  485. # Now you can access a view that's only available to logged-in users.
  486. If you're using a different authentication backend, this method may
  487. require different credentials. It requires whichever credentials are
  488. required by your backend's ``authenticate()`` method.
  489. ``login()`` returns ``True`` if it the credentials were accepted and
  490. login was successful.
  491. Finally, you'll need to remember to create user accounts before you can
  492. use this method. As we explained above, the test runner is executed
  493. using a test database, which contains no users by default. As a result,
  494. user accounts that are valid on your production site will not work
  495. under test conditions. You'll need to create users as part of the test
  496. suite -- either manually (using the Django model API) or with a test
  497. fixture. Remember that if you want your test user to have a password,
  498. you can't set the user's password by setting the password attribute
  499. directly -- you must use the
  500. :meth:`~django.contrib.auth.models.User.set_password()` function to
  501. store a correctly hashed password. Alternatively, you can use the
  502. :meth:`~django.contrib.auth.models.UserManager.create_user` helper
  503. method to create a new user with a correctly hashed password.
  504. .. method:: Client.logout()
  505. If your site uses Django's :doc:`authentication system</topics/auth/index>`,
  506. the ``logout()`` method can be used to simulate the effect of a user
  507. logging out of your site.
  508. After you call this method, the test client will have all the cookies
  509. and session data cleared to defaults. Subsequent requests will appear
  510. to come from an AnonymousUser.
  511. Testing responses
  512. ~~~~~~~~~~~~~~~~~
  513. The ``get()`` and ``post()`` methods both return a ``Response`` object. This
  514. ``Response`` object is *not* the same as the ``HttpResponse`` object returned
  515. Django views; the test response object has some additional data useful for
  516. test code to verify.
  517. Specifically, a ``Response`` object has the following attributes:
  518. .. class:: Response()
  519. .. attribute:: client
  520. The test client that was used to make the request that resulted in the
  521. response.
  522. .. attribute:: content
  523. The body of the response, as a string. This is the final page content as
  524. rendered by the view, or any error message.
  525. .. attribute:: context
  526. The template ``Context`` instance that was used to render the template that
  527. produced the response content.
  528. If the rendered page used multiple templates, then ``context`` will be a
  529. list of ``Context`` objects, in the order in which they were rendered.
  530. Regardless of the number of templates used during rendering, you can
  531. retrieve context values using the ``[]`` operator. For example, the
  532. context variable ``name`` could be retrieved using::
  533. >>> response = client.get('/foo/')
  534. >>> response.context['name']
  535. 'Arthur'
  536. .. attribute:: request
  537. The request data that stimulated the response.
  538. .. attribute:: status_code
  539. The HTTP status of the response, as an integer. See
  540. :rfc:`2616#section-10` for a full list of HTTP status codes.
  541. .. attribute:: templates
  542. A list of ``Template`` instances used to render the final content, in
  543. the order they were rendered. For each template in the list, use
  544. ``template.name`` to get the template's file name, if the template was
  545. loaded from a file. (The name is a string such as
  546. ``'admin/index.html'``.)
  547. You can also use dictionary syntax on the response object to query the value
  548. of any settings in the HTTP headers. For example, you could determine the
  549. content type of a response using ``response['Content-Type']``.
  550. Exceptions
  551. ~~~~~~~~~~
  552. If you point the test client at a view that raises an exception, that exception
  553. will be visible in the test case. You can then use a standard ``try ... except``
  554. block or :meth:`~unittest.TestCase.assertRaises` to test for exceptions.
  555. The only exceptions that are not visible to the test client are ``Http404``,
  556. ``PermissionDenied`` and ``SystemExit``. Django catches these exceptions
  557. internally and converts them into the appropriate HTTP response codes. In these
  558. cases, you can check ``response.status_code`` in your test.
  559. Persistent state
  560. ~~~~~~~~~~~~~~~~
  561. The test client is stateful. If a response returns a cookie, then that cookie
  562. will be stored in the test client and sent with all subsequent ``get()`` and
  563. ``post()`` requests.
  564. Expiration policies for these cookies are not followed. If you want a cookie
  565. to expire, either delete it manually or create a new ``Client`` instance (which
  566. will effectively delete all cookies).
  567. A test client has two attributes that store persistent state information. You
  568. can access these properties as part of a test condition.
  569. .. attribute:: Client.cookies
  570. A Python :class:`~Cookie.SimpleCookie` object, containing the current values
  571. of all the client cookies. See the documentation of the :mod:`Cookie` module
  572. for more.
  573. .. attribute:: Client.session
  574. A dictionary-like object containing session information. See the
  575. :doc:`session documentation</topics/http/sessions>` for full details.
  576. To modify the session and then save it, it must be stored in a variable
  577. first (because a new ``SessionStore`` is created every time this property
  578. is accessed)::
  579. def test_something(self):
  580. session = self.client.session
  581. session['somekey'] = 'test'
  582. session.save()
  583. Example
  584. ~~~~~~~
  585. The following is a simple unit test using the test client::
  586. from django.utils import unittest
  587. from django.test.client import Client
  588. class SimpleTest(unittest.TestCase):
  589. def setUp(self):
  590. # Every test needs a client.
  591. self.client = Client()
  592. def test_details(self):
  593. # Issue a GET request.
  594. response = self.client.get('/customer/details/')
  595. # Check that the response is 200 OK.
  596. self.assertEqual(response.status_code, 200)
  597. # Check that the rendered context contains 5 customers.
  598. self.assertEqual(len(response.context['customers']), 5)
  599. .. seealso::
  600. :class:`django.test.client.RequestFactory`
  601. .. _django-testcase-subclasses:
  602. Provided test case classes
  603. --------------------------
  604. .. currentmodule:: django.test
  605. Normal Python unit test classes extend a base class of
  606. :class:`unittest.TestCase`. Django provides a few extensions of this base class:
  607. .. _testcase_hierarchy_diagram:
  608. .. figure:: _images/django_unittest_classes_hierarchy.*
  609. :alt: Hierarchy of Django unit testing classes (TestCase subclasses)
  610. :width: 508
  611. :height: 391
  612. Hierarchy of Django unit testing classes
  613. Regardless of the version of Python you're using, if you've installed
  614. ``unittest2``, ``django.utils.unittest`` will point to that library.
  615. SimpleTestCase
  616. ~~~~~~~~~~~~~~
  617. .. class:: SimpleTestCase()
  618. A very thin subclass of :class:`unittest.TestCase`, it extends it with some
  619. basic functionality like:
  620. * Saving and restoring the Python warning machinery state.
  621. * Checking that a callable :meth:`raises a certain exception <SimpleTestCase.assertRaisesMessage>`.
  622. * :meth:`Testing form field rendering <SimpleTestCase.assertFieldOutput>`.
  623. * Testing server :ref:`HTML responses for the presence/lack of a given fragment <assertions>`.
  624. * The ability to run tests with :ref:`modified settings <overriding-settings>`
  625. If you need any of the other more complex and heavyweight Django-specific
  626. features like:
  627. * Using the :attr:`~TestCase.client` :class:`~django.test.client.Client`.
  628. * Testing or using the ORM.
  629. * Database :attr:`~TestCase.fixtures`.
  630. * Custom test-time :attr:`URL maps <TestCase.urls>`.
  631. * Test :ref:`skipping based on database backend features <skipping-tests>`.
  632. * The remaining specialized :ref:`assert* <assertions>` methods.
  633. then you should use :class:`~django.test.TransactionTestCase` or
  634. :class:`~django.test.TestCase` instead.
  635. ``SimpleTestCase`` inherits from ``django.utils.unittest.TestCase``.
  636. TransactionTestCase
  637. ~~~~~~~~~~~~~~~~~~~
  638. .. class:: TransactionTestCase()
  639. Django ``TestCase`` classes make use of database transaction facilities, if
  640. available, to speed up the process of resetting the database to a known state
  641. at the beginning of each test. A consequence of this, however, is that the
  642. effects of transaction commit and rollback cannot be tested by a Django
  643. ``TestCase`` class. If your test requires testing of such transactional
  644. behavior, you should use a Django ``TransactionTestCase``.
  645. ``TransactionTestCase`` and ``TestCase`` are identical except for the manner
  646. in which the database is reset to a known state and the ability for test code
  647. to test the effects of commit and rollback:
  648. * A ``TransactionTestCase`` resets the database after the test runs by
  649. truncating all tables. A ``TransactionTestCase`` may call commit and rollback
  650. and observe the effects of these calls on the database.
  651. * A ``TestCase``, on the other hand, does not truncate tables after a test.
  652. Instead, it encloses the test code in a database transaction that is rolled
  653. back at the end of the test. It also prevents the code under test from
  654. issuing any commit or rollback operations on the database, to ensure that the
  655. rollback at the end of the test restores the database to its initial state.
  656. When running on a database that does not support rollback (e.g. MySQL with the
  657. MyISAM storage engine), ``TestCase`` falls back to initializing the database
  658. by truncating tables and reloading initial data.
  659. .. note::
  660. .. versionchanged:: 1.5
  661. Prior to 1.5, ``TransactionTestCase`` flushed the database tables *before*
  662. each test. In Django 1.5, this is instead done *after* the test has been run.
  663. When the flush took place before the test, it was guaranteed that primary
  664. key values started at one in :class:`~django.test.TransactionTestCase`
  665. tests.
  666. Tests should not depend on this behaviour, but for legacy tests that do, the
  667. :attr:`~TransactionTestCase.reset_sequences` attribute can be used until
  668. the test has been properly updated.
  669. .. versionchanged:: 1.5
  670. The order in which tests are run has changed. See `Order in which tests are
  671. executed`_.
  672. ``TransactionTestCase`` inherits from :class:`~django.test.SimpleTestCase`.
  673. .. attribute:: TransactionTestCase.reset_sequences
  674. .. versionadded:: 1.5
  675. Setting ``reset_sequences = True`` on a ``TransactionTestCase`` will make
  676. sure sequences are always reset before the test run::
  677. class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase):
  678. reset_sequences = True
  679. def test_animal_pk(self):
  680. lion = Animal.objects.create(name="lion", sound="roar")
  681. # lion.pk is guaranteed to always be 1
  682. self.assertEqual(lion.pk, 1)
  683. Unless you are explicitly testing primary keys sequence numbers, it is
  684. recommended that you do not hard code primary key values in tests.
  685. Using ``reset_sequences = True`` will slow down the test, since the primary
  686. key reset is an relatively expensive database operation.
  687. TestCase
  688. ~~~~~~~~
  689. .. class:: TestCase()
  690. This class provides some additional capabilities that can be useful for testing
  691. Web sites.
  692. Converting a normal :class:`unittest.TestCase` to a Django :class:`TestCase` is
  693. easy: Just change the base class of your test from ``'unittest.TestCase'`` to
  694. ``'django.test.TestCase'``. All of the standard Python unit test functionality
  695. will continue to be available, but it will be augmented with some useful
  696. additions, including:
  697. * Automatic loading of fixtures.
  698. * Wraps each test in a transaction.
  699. * Creates a TestClient instance.
  700. * Django-specific assertions for testing for things like redirection and form
  701. errors.
  702. .. versionchanged:: 1.5
  703. The order in which tests are run has changed. See `Order in which tests are
  704. executed`_.
  705. ``TestCase`` inherits from :class:`~django.test.TransactionTestCase`.
  706. .. _live-test-server:
  707. LiveServerTestCase
  708. ~~~~~~~~~~~~~~~~~~
  709. .. class:: LiveServerTestCase()
  710. ``LiveServerTestCase`` does basically the same as
  711. :class:`~django.test.TransactionTestCase` with one extra feature: it launches a
  712. live Django server in the background on setup, and shuts it down on teardown.
  713. This allows the use of automated test clients other than the
  714. :ref:`Django dummy client <test-client>` such as, for example, the Selenium_
  715. client, to execute a series of functional tests inside a browser and simulate a
  716. real user's actions.
  717. By default the live server's address is ``'localhost:8081'`` and the full URL
  718. can be accessed during the tests with ``self.live_server_url``. If you'd like
  719. to change the default address (in the case, for example, where the 8081 port is
  720. already taken) then you may pass a different one to the :djadmin:`test` command
  721. via the :djadminopt:`--liveserver` option, for example:
  722. .. code-block:: bash
  723. ./manage.py test --liveserver=localhost:8082
  724. Another way of changing the default server address is by setting the
  725. `DJANGO_LIVE_TEST_SERVER_ADDRESS` environment variable somewhere in your
  726. code (for example, in a :ref:`custom test runner<topics-testing-test_runner>`):
  727. .. code-block:: python
  728. import os
  729. os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8082'
  730. In the case where the tests are run by multiple processes in parallel (for
  731. example, in the context of several simultaneous `continuous integration`_
  732. builds), the processes will compete for the same address, and therefore your
  733. tests might randomly fail with an "Address already in use" error. To avoid this
  734. problem, you can pass a comma-separated list of ports or ranges of ports (at
  735. least as many as the number of potential parallel processes). For example:
  736. .. code-block:: bash
  737. ./manage.py test --liveserver=localhost:8082,8090-8100,9000-9200,7041
  738. Then, during test execution, each new live test server will try every specified
  739. port until it finds one that is free and takes it.
  740. .. _continuous integration: http://en.wikipedia.org/wiki/Continuous_integration
  741. To demonstrate how to use ``LiveServerTestCase``, let's write a simple Selenium
  742. test. First of all, you need to install the `selenium package`_ into your
  743. Python path:
  744. .. code-block:: bash
  745. pip install selenium
  746. Then, add a ``LiveServerTestCase``-based test to your app's tests module
  747. (for example: ``myapp/tests.py``). The code for this test may look as follows:
  748. .. code-block:: python
  749. from django.test import LiveServerTestCase
  750. from selenium.webdriver.firefox.webdriver import WebDriver
  751. class MySeleniumTests(LiveServerTestCase):
  752. fixtures = ['user-data.json']
  753. @classmethod
  754. def setUpClass(cls):
  755. cls.selenium = WebDriver()
  756. super(MySeleniumTests, cls).setUpClass()
  757. @classmethod
  758. def tearDownClass(cls):
  759. cls.selenium.quit()
  760. super(MySeleniumTests, cls).tearDownClass()
  761. def test_login(self):
  762. self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
  763. username_input = self.selenium.find_element_by_name("username")
  764. username_input.send_keys('myuser')
  765. password_input = self.selenium.find_element_by_name("password")
  766. password_input.send_keys('secret')
  767. self.selenium.find_element_by_xpath('//input[@value="Log in"]').click()
  768. Finally, you may run the test as follows:
  769. .. code-block:: bash
  770. ./manage.py test myapp.MySeleniumTests.test_login
  771. This example will automatically open Firefox then go to the login page, enter
  772. the credentials and press the "Log in" button. Selenium offers other drivers in
  773. case you do not have Firefox installed or wish to use another browser. The
  774. example above is just a tiny fraction of what the Selenium client can do; check
  775. out the `full reference`_ for more details.
  776. .. _Selenium: http://seleniumhq.org/
  777. .. _selenium package: http://pypi.python.org/pypi/selenium
  778. .. _full reference: http://selenium-python.readthedocs.org/en/latest/api.html
  779. .. _Firefox: http://www.mozilla.com/firefox/
  780. .. note::
  781. ``LiveServerTestCase`` makes use of the :doc:`staticfiles contrib app
  782. </howto/static-files/index>` so you'll need to have your project configured
  783. accordingly (in particular by setting :setting:`STATIC_URL`).
  784. .. note::
  785. When using an in-memory SQLite database to run the tests, the same database
  786. connection will be shared by two threads in parallel: the thread in which
  787. the live server is run and the thread in which the test case is run. It's
  788. important to prevent simultaneous database queries via this shared
  789. connection by the two threads, as that may sometimes randomly cause the
  790. tests to fail. So you need to ensure that the two threads don't access the
  791. database at the same time. In particular, this means that in some cases
  792. (for example, just after clicking a link or submitting a form), you might
  793. need to check that a response is received by Selenium and that the next
  794. page is loaded before proceeding with further test execution.
  795. Do this, for example, by making Selenium wait until the ``<body>`` HTML tag
  796. is found in the response (requires Selenium > 2.13):
  797. .. code-block:: python
  798. def test_login(self):
  799. from selenium.webdriver.support.wait import WebDriverWait
  800. timeout = 2
  801. ...
  802. self.selenium.find_element_by_xpath('//input[@value="Log in"]').click()
  803. # Wait until the response is received
  804. WebDriverWait(self.selenium, timeout).until(
  805. lambda driver: driver.find_element_by_tag_name('body'))
  806. The tricky thing here is that there's really no such thing as a "page load,"
  807. especially in modern Web apps that generate HTML dynamically after the
  808. server generates the initial document. So, simply checking for the presence
  809. of ``<body>`` in the response might not necessarily be appropriate for all
  810. use cases. Please refer to the `Selenium FAQ`_ and
  811. `Selenium documentation`_ for more information.
  812. .. _Selenium FAQ: http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_WebDriver_fails_to_find_elements_/_Does_not_block_on_page_loa
  813. .. _Selenium documentation: http://seleniumhq.org/docs/04_webdriver_advanced.html#explicit-waits
  814. Test cases features
  815. -------------------
  816. Default test client
  817. ~~~~~~~~~~~~~~~~~~~
  818. .. attribute:: TestCase.client
  819. Every test case in a ``django.test.TestCase`` instance has access to an
  820. instance of a Django test client. This client can be accessed as
  821. ``self.client``. This client is recreated for each test, so you don't have to
  822. worry about state (such as cookies) carrying over from one test to another.
  823. This means, instead of instantiating a ``Client`` in each test::
  824. from django.utils import unittest
  825. from django.test.client import Client
  826. class SimpleTest(unittest.TestCase):
  827. def test_details(self):
  828. client = Client()
  829. response = client.get('/customer/details/')
  830. self.assertEqual(response.status_code, 200)
  831. def test_index(self):
  832. client = Client()
  833. response = client.get('/customer/index/')
  834. self.assertEqual(response.status_code, 200)
  835. ...you can just refer to ``self.client``, like so::
  836. from django.test import TestCase
  837. class SimpleTest(TestCase):
  838. def test_details(self):
  839. response = self.client.get('/customer/details/')
  840. self.assertEqual(response.status_code, 200)
  841. def test_index(self):
  842. response = self.client.get('/customer/index/')
  843. self.assertEqual(response.status_code, 200)
  844. Customizing the test client
  845. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  846. .. attribute:: TestCase.client_class
  847. If you want to use a different ``Client`` class (for example, a subclass
  848. with customized behavior), use the :attr:`~TestCase.client_class` class
  849. attribute::
  850. from django.test import TestCase
  851. from django.test.client import Client
  852. class MyTestClient(Client):
  853. # Specialized methods for your environment...
  854. class MyTest(TestCase):
  855. client_class = MyTestClient
  856. def test_my_stuff(self):
  857. # Here self.client is an instance of MyTestClient...
  858. call_some_test_code()
  859. .. _topics-testing-fixtures:
  860. Fixture loading
  861. ~~~~~~~~~~~~~~~
  862. .. attribute:: TestCase.fixtures
  863. A test case for a database-backed Web site isn't much use if there isn't any
  864. data in the database. To make it easy to put test data into the database,
  865. Django's custom ``TestCase`` class provides a way of loading **fixtures**.
  866. A fixture is a collection of data that Django knows how to import into a
  867. database. For example, if your site has user accounts, you might set up a
  868. fixture of fake user accounts in order to populate your database during tests.
  869. The most straightforward way of creating a fixture is to use the
  870. :djadmin:`manage.py dumpdata <dumpdata>` command. This assumes you
  871. already have some data in your database. See the :djadmin:`dumpdata
  872. documentation<dumpdata>` for more details.
  873. .. note::
  874. If you've ever run :djadmin:`manage.py syncdb<syncdb>`, you've
  875. already used a fixture without even knowing it! When you call
  876. :djadmin:`syncdb` in the database for the first time, Django
  877. installs a fixture called ``initial_data``. This gives you a way
  878. of populating a new database with any initial data, such as a
  879. default set of categories.
  880. Fixtures with other names can always be installed manually using
  881. the :djadmin:`manage.py loaddata<loaddata>` command.
  882. .. admonition:: Initial SQL data and testing
  883. Django provides a second way to insert initial data into models --
  884. the :ref:`custom SQL hook <initial-sql>`. However, this technique
  885. *cannot* be used to provide initial data for testing purposes.
  886. Django's test framework flushes the contents of the test database
  887. after each test; as a result, any data added using the custom SQL
  888. hook will be lost.
  889. Once you've created a fixture and placed it in a ``fixtures`` directory in one
  890. of your :setting:`INSTALLED_APPS`, you can use it in your unit tests by
  891. specifying a ``fixtures`` class attribute on your :class:`django.test.TestCase`
  892. subclass::
  893. from django.test import TestCase
  894. from myapp.models import Animal
  895. class AnimalTestCase(TestCase):
  896. fixtures = ['mammals.json', 'birds']
  897. def setUp(self):
  898. # Test definitions as before.
  899. call_setup_methods()
  900. def testFluffyAnimals(self):
  901. # A test that uses the fixtures.
  902. call_some_test_code()
  903. Here's specifically what will happen:
  904. * At the start of each test case, before ``setUp()`` is run, Django will
  905. flush the database, returning the database to the state it was in
  906. directly after :djadmin:`syncdb` was called.
  907. * Then, all the named fixtures are installed. In this example, Django will
  908. install any JSON fixture named ``mammals``, followed by any fixture named
  909. ``birds``. See the :djadmin:`loaddata` documentation for more
  910. details on defining and installing fixtures.
  911. This flush/load procedure is repeated for each test in the test case, so you
  912. can be certain that the outcome of a test will not be affected by another test,
  913. or by the order of test execution.
  914. URLconf configuration
  915. ~~~~~~~~~~~~~~~~~~~~~
  916. .. attribute:: TestCase.urls
  917. If your application provides views, you may want to include tests that use the
  918. test client to exercise those views. However, an end user is free to deploy the
  919. views in your application at any URL of their choosing. This means that your
  920. tests can't rely upon the fact that your views will be available at a
  921. particular URL.
  922. In order to provide a reliable URL space for your test,
  923. ``django.test.TestCase`` provides the ability to customize the URLconf
  924. configuration for the duration of the execution of a test suite. If your
  925. ``TestCase`` instance defines an ``urls`` attribute, the ``TestCase`` will use
  926. the value of that attribute as the :setting:`ROOT_URLCONF` for the duration
  927. of that test.
  928. For example::
  929. from django.test import TestCase
  930. class TestMyViews(TestCase):
  931. urls = 'myapp.test_urls'
  932. def testIndexPageView(self):
  933. # Here you'd test your view using ``Client``.
  934. call_some_test_code()
  935. This test case will use the contents of ``myapp.test_urls`` as the
  936. URLconf for the duration of the test case.
  937. .. _emptying-test-outbox:
  938. Multi-database support
  939. ~~~~~~~~~~~~~~~~~~~~~~
  940. .. attribute:: TestCase.multi_db
  941. Django sets up a test database corresponding to every database that is
  942. defined in the :setting:`DATABASES` definition in your settings
  943. file. However, a big part of the time taken to run a Django TestCase
  944. is consumed by the call to ``flush`` that ensures that you have a
  945. clean database at the start of each test run. If you have multiple
  946. databases, multiple flushes are required (one for each database),
  947. which can be a time consuming activity -- especially if your tests
  948. don't need to test multi-database activity.
  949. As an optimization, Django only flushes the ``default`` database at
  950. the start of each test run. If your setup contains multiple databases,
  951. and you have a test that requires every database to be clean, you can
  952. use the ``multi_db`` attribute on the test suite to request a full
  953. flush.
  954. For example::
  955. class TestMyViews(TestCase):
  956. multi_db = True
  957. def testIndexPageView(self):
  958. call_some_test_code()
  959. This test case will flush *all* the test databases before running
  960. ``testIndexPageView``.
  961. .. _overriding-settings:
  962. Overriding settings
  963. ~~~~~~~~~~~~~~~~~~~
  964. .. method:: TestCase.settings
  965. For testing purposes it's often useful to change a setting temporarily and
  966. revert to the original value after running the testing code. For this use case
  967. Django provides a standard Python context manager (see :pep:`343`)
  968. :meth:`~django.test.TestCase.settings`, which can be used like this::
  969. from django.test import TestCase
  970. class LoginTestCase(TestCase):
  971. def test_login(self):
  972. # First check for the default behavior
  973. response = self.client.get('/sekrit/')
  974. self.assertRedirects(response, '/accounts/login/?next=/sekrit/')
  975. # Then override the LOGIN_URL setting
  976. with self.settings(LOGIN_URL='/other/login/'):
  977. response = self.client.get('/sekrit/')
  978. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  979. This example will override the :setting:`LOGIN_URL` setting for the code
  980. in the ``with`` block and reset its value to the previous state afterwards.
  981. .. currentmodule:: django.test.utils
  982. .. function:: override_settings
  983. In case you want to override a setting for just one test method or even the
  984. whole :class:`~django.test.TestCase` class, Django provides the
  985. :func:`~django.test.utils.override_settings` decorator (see :pep:`318`). It's
  986. used like this::
  987. from django.test import TestCase
  988. from django.test.utils import override_settings
  989. class LoginTestCase(TestCase):
  990. @override_settings(LOGIN_URL='/other/login/')
  991. def test_login(self):
  992. response = self.client.get('/sekrit/')
  993. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  994. The decorator can also be applied to test case classes::
  995. from django.test import TestCase
  996. from django.test.utils import override_settings
  997. @override_settings(LOGIN_URL='/other/login/')
  998. class LoginTestCase(TestCase):
  999. def test_login(self):
  1000. response = self.client.get('/sekrit/')
  1001. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  1002. .. note::
  1003. When given a class, the decorator modifies the class directly and
  1004. returns it; it doesn't create and return a modified copy of it. So if
  1005. you try to tweak the above example to assign the return value to a
  1006. different name than ``LoginTestCase``, you may be surprised to find that
  1007. the original ``LoginTestCase`` is still equally affected by the
  1008. decorator.
  1009. You can also simulate the absence of a setting by deleting it after settings
  1010. have been overriden, like this::
  1011. @override_settings()
  1012. def test_something(self):
  1013. del settings.LOGIN_URL
  1014. ...
  1015. When overriding settings, make sure to handle the cases in which your app's
  1016. code uses a cache or similar feature that retains state even if the
  1017. setting is changed. Django provides the
  1018. :data:`django.test.signals.setting_changed` signal that lets you register
  1019. callbacks to clean up and otherwise reset state when settings are changed.
  1020. Django itself uses this signal to reset various data:
  1021. ================================ ========================
  1022. Overriden settings Data reset
  1023. ================================ ========================
  1024. USE_TZ, TIME_ZONE Databases timezone
  1025. TEMPLATE_CONTEXT_PROCESSORS Context processors cache
  1026. TEMPLATE_LOADERS Template loaders cache
  1027. SERIALIZATION_MODULES Serializers cache
  1028. LOCALE_PATHS, LANGUAGE_CODE Default translation and loaded translations
  1029. MEDIA_ROOT, DEFAULT_FILE_STORAGE Default file storage
  1030. ================================ ========================
  1031. Emptying the test outbox
  1032. ~~~~~~~~~~~~~~~~~~~~~~~~
  1033. If you use Django's custom ``TestCase`` class, the test runner will clear the
  1034. contents of the test email outbox at the start of each test case.
  1035. For more detail on email services during tests, see `Email services`_ below.
  1036. .. _assertions:
  1037. Assertions
  1038. ~~~~~~~~~~
  1039. .. currentmodule:: django.test
  1040. As Python's normal :class:`unittest.TestCase` class implements assertion methods
  1041. such as :meth:`~unittest.TestCase.assertTrue` and
  1042. :meth:`~unittest.TestCase.assertEqual`, Django's custom :class:`TestCase` class
  1043. provides a number of custom assertion methods that are useful for testing Web
  1044. applications:
  1045. The failure messages given by most of these assertion methods can be customized
  1046. with the ``msg_prefix`` argument. This string will be prefixed to any failure
  1047. message generated by the assertion. This allows you to provide additional
  1048. details that may help you to identify the location and cause of an failure in
  1049. your test suite.
  1050. .. method:: SimpleTestCase.assertRaisesMessage(expected_exception, expected_message, callable_obj=None, *args, **kwargs)
  1051. Asserts that execution of callable ``callable_obj`` raised the
  1052. ``expected_exception`` exception and that such exception has an
  1053. ``expected_message`` representation. Any other outcome is reported as a
  1054. failure. Similar to unittest's :meth:`~unittest.TestCase.assertRaisesRegexp`
  1055. with the difference that ``expected_message`` isn't a regular expression.
  1056. .. method:: SimpleTestCase.assertFieldOutput(self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value=u'')
  1057. Asserts that a form field behaves correctly with various inputs.
  1058. :param fieldclass: the class of the field to be tested.
  1059. :param valid: a dictionary mapping valid inputs to their expected cleaned
  1060. values.
  1061. :param invalid: a dictionary mapping invalid inputs to one or more raised
  1062. error messages.
  1063. :param field_args: the args passed to instantiate the field.
  1064. :param field_kwargs: the kwargs passed to instantiate the field.
  1065. :param empty_value: the expected clean output for inputs in ``empty_values``.
  1066. For example, the following code tests that an ``EmailField`` accepts
  1067. "a@a.com" as a valid email address, but rejects "aaa" with a reasonable
  1068. error message::
  1069. self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': [u'Enter a valid email address.']})
  1070. .. method:: TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False)
  1071. Asserts that a ``Response`` instance produced the given ``status_code`` and
  1072. that ``text`` appears in the content of the response. If ``count`` is
  1073. provided, ``text`` must occur exactly ``count`` times in the response.
  1074. Set ``html`` to ``True`` to handle ``text`` as HTML. The comparison with
  1075. the response content will be based on HTML semantics instead of
  1076. character-by-character equality. Whitespace is ignored in most cases,
  1077. attribute ordering is not significant. See
  1078. :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
  1079. .. method:: TestCase.assertNotContains(response, text, status_code=200, msg_prefix='', html=False)
  1080. Asserts that a ``Response`` instance produced the given ``status_code`` and
  1081. that ``text`` does not appears in the content of the response.
  1082. Set ``html`` to ``True`` to handle ``text`` as HTML. The comparison with
  1083. the response content will be based on HTML semantics instead of
  1084. character-by-character equality. Whitespace is ignored in most cases,
  1085. attribute ordering is not significant. See
  1086. :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
  1087. .. method:: TestCase.assertFormError(response, form, field, errors, msg_prefix='')
  1088. Asserts that a field on a form raises the provided list of errors when
  1089. rendered on the form.
  1090. ``form`` is the name the ``Form`` instance was given in the template
  1091. context.
  1092. ``field`` is the name of the field on the form to check. If ``field``
  1093. has a value of ``None``, non-field errors (errors you can access via
  1094. ``form.non_field_errors()``) will be checked.
  1095. ``errors`` is an error string, or a list of error strings, that are
  1096. expected as a result of form validation.
  1097. .. method:: TestCase.assertTemplateUsed(response, template_name, msg_prefix='')
  1098. Asserts that the template with the given name was used in rendering the
  1099. response.
  1100. The name is a string such as ``'admin/index.html'``.
  1101. You can use this as a context manager, like this::
  1102. with self.assertTemplateUsed('index.html'):
  1103. render_to_string('index.html')
  1104. with self.assertTemplateUsed(template_name='index.html'):
  1105. render_to_string('index.html')
  1106. .. method:: TestCase.assertTemplateNotUsed(response, template_name, msg_prefix='')
  1107. Asserts that the template with the given name was *not* used in rendering
  1108. the response.
  1109. You can use this as a context manager in the same way as
  1110. :meth:`~TestCase.assertTemplateUsed`.
  1111. .. method:: TestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='')
  1112. Asserts that the response return a ``status_code`` redirect status, it
  1113. redirected to ``expected_url`` (including any GET data), and the final
  1114. page was received with ``target_status_code``.
  1115. If your request used the ``follow`` argument, the ``expected_url`` and
  1116. ``target_status_code`` will be the url and status code for the final
  1117. point of the redirect chain.
  1118. .. method:: TestCase.assertQuerysetEqual(qs, values, transform=repr, ordered=True)
  1119. Asserts that a queryset ``qs`` returns a particular list of values ``values``.
  1120. The comparison of the contents of ``qs`` and ``values`` is performed using
  1121. the function ``transform``; by default, this means that the ``repr()`` of
  1122. each value is compared. Any other callable can be used if ``repr()`` doesn't
  1123. provide a unique or helpful comparison.
  1124. By default, the comparison is also ordering dependent. If ``qs`` doesn't
  1125. provide an implicit ordering, you can set the ``ordered`` parameter to
  1126. ``False``, which turns the comparison into a Python set comparison.
  1127. .. versionchanged:: 1.6
  1128. The method now checks for undefined order and raises ``ValueError``
  1129. if undefined order is spotted. The ordering is seen as undefined if
  1130. the given ``qs`` isn't ordered and the comparison is against more
  1131. than one ordered values.
  1132. .. method:: TestCase.assertNumQueries(num, func, *args, **kwargs)
  1133. Asserts that when ``func`` is called with ``*args`` and ``**kwargs`` that
  1134. ``num`` database queries are executed.
  1135. If a ``"using"`` key is present in ``kwargs`` it is used as the database
  1136. alias for which to check the number of queries. If you wish to call a
  1137. function with a ``using`` parameter you can do it by wrapping the call with
  1138. a ``lambda`` to add an extra parameter::
  1139. self.assertNumQueries(7, lambda: my_function(using=7))
  1140. You can also use this as a context manager::
  1141. with self.assertNumQueries(2):
  1142. Person.objects.create(name="Aaron")
  1143. Person.objects.create(name="Daniel")
  1144. .. method:: SimpleTestCase.assertHTMLEqual(html1, html2, msg=None)
  1145. Asserts that the strings ``html1`` and ``html2`` are equal. The comparison
  1146. is based on HTML semantics. The comparison takes following things into
  1147. account:
  1148. * Whitespace before and after HTML tags is ignored.
  1149. * All types of whitespace are considered equivalent.
  1150. * All open tags are closed implicitly, e.g. when a surrounding tag is
  1151. closed or the HTML document ends.
  1152. * Empty tags are equivalent to their self-closing version.
  1153. * The ordering of attributes of an HTML element is not significant.
  1154. * Attributes without an argument are equal to attributes that equal in
  1155. name and value (see the examples).
  1156. The following examples are valid tests and don't raise any
  1157. ``AssertionError``::
  1158. self.assertHTMLEqual('<p>Hello <b>world!</p>',
  1159. '''<p>
  1160. Hello <b>world! <b/>
  1161. </p>''')
  1162. self.assertHTMLEqual(
  1163. '<input type="checkbox" checked="checked" id="id_accept_terms" />',
  1164. '<input id="id_accept_terms" type='checkbox' checked>')
  1165. ``html1`` and ``html2`` must be valid HTML. An ``AssertionError`` will be
  1166. raised if one of them cannot be parsed.
  1167. .. method:: SimpleTestCase.assertHTMLNotEqual(html1, html2, msg=None)
  1168. Asserts that the strings ``html1`` and ``html2`` are *not* equal. The
  1169. comparison is based on HTML semantics. See
  1170. :meth:`~SimpleTestCase.assertHTMLEqual` for details.
  1171. ``html1`` and ``html2`` must be valid HTML. An ``AssertionError`` will be
  1172. raised if one of them cannot be parsed.
  1173. .. method:: SimpleTestCase.assertXMLEqual(xml1, xml2, msg=None)
  1174. .. versionadded:: 1.5
  1175. Asserts that the strings ``xml1`` and ``xml2`` are equal. The
  1176. comparison is based on XML semantics. Similarily to
  1177. :meth:`~SimpleTestCase.assertHTMLEqual`, the comparison is
  1178. made on parsed content, hence only semantic differences are considered, not
  1179. syntax differences. When unvalid XML is passed in any parameter, an
  1180. ``AssertionError`` is always raised, even if both string are identical.
  1181. .. method:: SimpleTestCase.assertXMLNotEqual(xml1, xml2, msg=None)
  1182. .. versionadded:: 1.5
  1183. Asserts that the strings ``xml1`` and ``xml2`` are *not* equal. The
  1184. comparison is based on XML semantics. See
  1185. :meth:`~SimpleTestCase.assertXMLEqual` for details.
  1186. .. _topics-testing-email:
  1187. Email services
  1188. --------------
  1189. If any of your Django views send email using :doc:`Django's email
  1190. functionality </topics/email>`, you probably don't want to send email each time
  1191. you run a test using that view. For this reason, Django's test runner
  1192. automatically redirects all Django-sent email to a dummy outbox. This lets you
  1193. test every aspect of sending email -- from the number of messages sent to the
  1194. contents of each message -- without actually sending the messages.
  1195. The test runner accomplishes this by transparently replacing the normal
  1196. email backend with a testing backend.
  1197. (Don't worry -- this has no effect on any other email senders outside of
  1198. Django, such as your machine's mail server, if you're running one.)
  1199. .. currentmodule:: django.core.mail
  1200. .. data:: django.core.mail.outbox
  1201. During test running, each outgoing email is saved in
  1202. ``django.core.mail.outbox``. This is a simple list of all
  1203. :class:`~django.core.mail.EmailMessage` instances that have been sent.
  1204. The ``outbox`` attribute is a special attribute that is created *only* when
  1205. the ``locmem`` email backend is used. It doesn't normally exist as part of the
  1206. :mod:`django.core.mail` module and you can't import it directly. The code
  1207. below shows how to access this attribute correctly.
  1208. Here's an example test that examines ``django.core.mail.outbox`` for length
  1209. and contents::
  1210. from django.core import mail
  1211. from django.test import TestCase
  1212. class EmailTest(TestCase):
  1213. def test_send_email(self):
  1214. # Send message.
  1215. mail.send_mail('Subject here', 'Here is the message.',
  1216. 'from@example.com', ['to@example.com'],
  1217. fail_silently=False)
  1218. # Test that one message has been sent.
  1219. self.assertEqual(len(mail.outbox), 1)
  1220. # Verify that the subject of the first message is correct.
  1221. self.assertEqual(mail.outbox[0].subject, 'Subject here')
  1222. As noted :ref:`previously <emptying-test-outbox>`, the test outbox is emptied
  1223. at the start of every test in a Django ``TestCase``. To empty the outbox
  1224. manually, assign the empty list to ``mail.outbox``::
  1225. from django.core import mail
  1226. # Empty the test outbox
  1227. mail.outbox = []
  1228. .. _skipping-tests:
  1229. Skipping tests
  1230. --------------
  1231. .. currentmodule:: django.test
  1232. The unittest library provides the :func:`@skipIf <unittest.skipIf>` and
  1233. :func:`@skipUnless <unittest.skipUnless>` decorators to allow you to skip tests
  1234. if you know ahead of time that those tests are going to fail under certain
  1235. conditions.
  1236. For example, if your test requires a particular optional library in order to
  1237. succeed, you could decorate the test case with :func:`@skipIf
  1238. <unittest.skipIf>`. Then, the test runner will report that the test wasn't
  1239. executed and why, instead of failing the test or omitting the test altogether.
  1240. To supplement these test skipping behaviors, Django provides two
  1241. additional skip decorators. Instead of testing a generic boolean,
  1242. these decorators check the capabilities of the database, and skip the
  1243. test if the database doesn't support a specific named feature.
  1244. The decorators use a string identifier to describe database features.
  1245. This string corresponds to attributes of the database connection
  1246. features class. See ``django.db.backends.BaseDatabaseFeatures``
  1247. class for a full list of database features that can be used as a basis
  1248. for skipping tests.
  1249. .. function:: skipIfDBFeature(feature_name_string)
  1250. Skip the decorated test if the named database feature is supported.
  1251. For example, the following test will not be executed if the database
  1252. supports transactions (e.g., it would *not* run under PostgreSQL, but
  1253. it would under MySQL with MyISAM tables)::
  1254. class MyTests(TestCase):
  1255. @skipIfDBFeature('supports_transactions')
  1256. def test_transaction_behavior(self):
  1257. # ... conditional test code
  1258. .. function:: skipUnlessDBFeature(feature_name_string)
  1259. Skip the decorated test if the named database feature is *not*
  1260. supported.
  1261. For example, the following test will only be executed if the database
  1262. supports transactions (e.g., it would run under PostgreSQL, but *not*
  1263. under MySQL with MyISAM tables)::
  1264. class MyTests(TestCase):
  1265. @skipUnlessDBFeature('supports_transactions')
  1266. def test_transaction_behavior(self):
  1267. # ... conditional test code