tools.txt 71 KB

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