overview.txt 72 KB

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