tools.txt 75 KB

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