2
0

tools.txt 85 KB

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