tools.txt 69 KB

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