overview.txt 69 KB

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