overview.txt 70 KB

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