tools.txt 85 KB

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