tools.txt 76 KB

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