tools.txt 86 KB

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