tools.txt 85 KB

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