tools.txt 73 KB

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