tools.txt 83 KB

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