tools.txt 76 KB

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