tools.txt 85 KB

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