tools.txt 68 KB

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