tools.txt 84 KB

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