tools.txt 79 KB

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