tools.txt 66 KB

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