tools.txt 86 KB

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