overview.txt 71 KB

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