tools.txt 70 KB

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