tools.txt 70 KB

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