2
0

tools.txt 77 KB

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