tools.txt 71 KB

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