tools.txt 83 KB

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