tools.txt 71 KB

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