tools.txt 85 KB

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