testing.txt 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  1. ===========================
  2. Testing Django applications
  3. ===========================
  4. .. module:: django.test
  5. :synopsis: Testing tools for Django applications.
  6. Automated testing is an extremely useful bug-killing tool for the modern
  7. Web developer. You can use a collection of tests -- a **test suite** -- to
  8. solve, or avoid, a number of problems:
  9. * When you're writing new code, you can use tests to validate your code
  10. works as expected.
  11. * When you're refactoring or modifying old code, you can use tests to
  12. ensure your changes haven't affected your application's behavior
  13. unexpectedly.
  14. Testing a Web application is a complex task, because a Web application is made
  15. of several layers of logic -- from HTTP-level request handling, to form
  16. validation and processing, to template rendering. With Django's test-execution
  17. framework and assorted utilities, you can simulate requests, insert test data,
  18. inspect your application's output and generally verify your code is doing what
  19. it should be doing.
  20. The best part is, it's really easy.
  21. This document is split into two primary sections. First, we explain how to
  22. write tests with Django. Then, we explain how to run them.
  23. Writing tests
  24. =============
  25. There are two primary ways to write tests with Django, corresponding to the
  26. two test frameworks that ship in the Python standard library. The two
  27. frameworks are:
  28. * **Doctests** -- tests that are embedded in your functions' docstrings and
  29. are written in a way that emulates a session of the Python interactive
  30. interpreter. For example::
  31. def my_func(a_list, idx):
  32. """
  33. >>> a = ['larry', 'curly', 'moe']
  34. >>> my_func(a, 0)
  35. 'larry'
  36. >>> my_func(a, 1)
  37. 'curly'
  38. """
  39. return a_list[idx]
  40. * **Unit tests** -- tests that are expressed as methods on a Python class
  41. that subclasses ``unittest.TestCase``. For example::
  42. import unittest
  43. class MyFuncTestCase(unittest.TestCase):
  44. def testBasic(self):
  45. a = ['larry', 'curly', 'moe']
  46. self.assertEqual(my_func(a, 0), 'larry')
  47. self.assertEqual(my_func(a, 1), 'curly')
  48. You can choose the test framework you like, depending on which syntax you
  49. prefer, or you can mix and match, using one framework for some of your code and
  50. the other framework for other code. You can also use any *other* Python test
  51. frameworks, as we'll explain in a bit.
  52. Writing doctests
  53. ----------------
  54. Doctests use Python's standard doctest_ module, which searches your docstrings
  55. for statements that resemble a session of the Python interactive interpreter.
  56. A full explanation of how doctest works is out of the scope of this document;
  57. read Python's official documentation for the details.
  58. .. admonition:: What's a **docstring**?
  59. A good explanation of docstrings (and some guidelines for using them
  60. effectively) can be found in :pep:`257`:
  61. A docstring is a string literal that occurs as the first statement in
  62. a module, function, class, or method definition. Such a docstring
  63. becomes the ``__doc__`` special attribute of that object.
  64. For example, this function has a docstring that describes what it does::
  65. def add_two(num):
  66. "Return the result of adding two to the provided number."
  67. return num + 2
  68. Because tests often make great documentation, putting tests directly in
  69. your docstrings is an effective way to document *and* test your code.
  70. For a given Django application, the test runner looks for doctests in two
  71. places:
  72. * The ``models.py`` file. You can define module-level doctests and/or a
  73. doctest for individual models. It's common practice to put
  74. application-level doctests in the module docstring and model-level
  75. doctests in the model docstrings.
  76. * A file called ``tests.py`` in the application directory -- i.e., the
  77. directory that holds ``models.py``. This file is a hook for any and all
  78. doctests you want to write that aren't necessarily related to models.
  79. Here is an example model doctest::
  80. # models.py
  81. from django.db import models
  82. class Animal(models.Model):
  83. """
  84. An animal that knows how to make noise
  85. # Create some animals
  86. >>> lion = Animal.objects.create(name="lion", sound="roar")
  87. >>> cat = Animal.objects.create(name="cat", sound="meow")
  88. # Make 'em speak
  89. >>> lion.speak()
  90. 'The lion says "roar"'
  91. >>> cat.speak()
  92. 'The cat says "meow"'
  93. """
  94. name = models.CharField(max_length=20)
  95. sound = models.CharField(max_length=20)
  96. def speak(self):
  97. return 'The %s says "%s"' % (self.name, self.sound)
  98. When you :ref:`run your tests <running-tests>`, the test runner will find this
  99. docstring, notice that portions of it look like an interactive Python session,
  100. and execute those lines while checking that the results match.
  101. In the case of model tests, note that the test runner takes care of creating
  102. its own test database. That is, any test that accesses a database -- by
  103. creating and saving model instances, for example -- will not affect your
  104. production database. However, the database is not refreshed between doctests,
  105. so if your doctest requires a certain state you should consider flushing the
  106. database or loading a fixture. (See the section on fixtures, below, for more
  107. on this.) Note that to use this feature, the database user Django is connecting
  108. as must have ``CREATE DATABASE`` rights.
  109. For more details about how doctest works, see the `standard library
  110. documentation for doctest`_.
  111. .. _doctest: http://docs.python.org/library/doctest.html
  112. .. _standard library documentation for doctest: doctest_
  113. Writing unit tests
  114. ------------------
  115. Like doctests, Django's unit tests use a Python standard library
  116. module: unittest_. This module uses a different way of defining tests,
  117. taking a class-based approach.
  118. .. admonition:: unittest2
  119. .. versionchanged:: 1.3
  120. Python 2.7 introduced some major changes to the unittest library,
  121. adding some extremely useful features. To ensure that every Django
  122. project can benefit from these new features, Django ships with a
  123. copy of unittest2_, a copy of the Python 2.7 unittest library,
  124. backported for Python 2.4 compatibility.
  125. To access this library, Django provides the
  126. ``django.utils.unittest`` module alias. If you are using Python
  127. 2.7, or you have installed unittest2 locally, Django will mapt the
  128. alias to the installed version of the unittest library Otherwise,
  129. Django will use it's own bundled version of unittest2.
  130. To use this alias, simply use::
  131. from django.utils import unittest
  132. wherever you would historically used::
  133. import unittest
  134. If you want to continue to use the base unittest libary, you can --
  135. you just won't get any of the nice new unittest2 features.
  136. .. _unittest2: http://pypi.python.org/pypi/unittest2
  137. As with doctests, for a given Django application, the test runner looks for
  138. unit tests in two places:
  139. * The ``models.py`` file. The test runner looks for any subclass of
  140. ``unittest.TestCase`` in this module.
  141. * A file called ``tests.py`` in the application directory -- i.e., the
  142. directory that holds ``models.py``. Again, the test runner looks for any
  143. subclass of ``unittest.TestCase`` in this module.
  144. This example ``unittest.TestCase`` subclass is equivalent to the example given
  145. in the doctest section above::
  146. from django.utils import unittest
  147. from myapp.models import Animal
  148. class AnimalTestCase(unittest.TestCase):
  149. def setUp(self):
  150. self.lion = Animal.objects.create(name="lion", sound="roar")
  151. self.cat = Animal.objects.create(name="cat", sound="meow")
  152. def testSpeaking(self):
  153. self.assertEqual(self.lion.speak(), 'The lion says "roar"')
  154. self.assertEqual(self.cat.speak(), 'The cat says "meow"')
  155. When you :ref:`run your tests <running-tests>`, the default behavior of the
  156. test utility is to find all the test cases (that is, subclasses of
  157. ``unittest.TestCase``) in ``models.py`` and ``tests.py``, automatically build a
  158. test suite out of those test cases, and run that suite.
  159. There is a second way to define the test suite for a module: if you define a
  160. function called ``suite()`` in either ``models.py`` or ``tests.py``, the
  161. Django test runner will use that function to construct the test suite for that
  162. module. This follows the `suggested organization`_ for unit tests. See the
  163. Python documentation for more details on how to construct a complex test
  164. suite.
  165. For more details about ``unittest``, see the `standard library unittest
  166. documentation`_.
  167. .. _unittest: http://docs.python.org/library/unittest.html
  168. .. _standard library unittest documentation: unittest_
  169. .. _suggested organization: http://docs.python.org/library/unittest.html#organizing-tests
  170. Which should I use?
  171. -------------------
  172. Because Django supports both of the standard Python test frameworks, it's up to
  173. you and your tastes to decide which one to use. You can even decide to use
  174. *both*.
  175. For developers new to testing, however, this choice can seem confusing. Here,
  176. then, are a few key differences to help you decide which approach is right for
  177. you:
  178. * If you've been using Python for a while, ``doctest`` will probably feel
  179. more "pythonic". It's designed to make writing tests as easy as possible,
  180. so it requires no overhead of writing classes or methods. You simply put
  181. tests in docstrings. This has the added advantage of serving as
  182. documentation (and correct documentation, at that!).
  183. If you're just getting started with testing, using doctests will probably
  184. get you started faster.
  185. * The ``unittest`` framework will probably feel very familiar to developers
  186. coming from Java. ``unittest`` is inspired by Java's JUnit, so you'll
  187. feel at home with this method if you've used JUnit or any test framework
  188. inspired by JUnit.
  189. * If you need to write a bunch of tests that share similar code, then
  190. you'll appreciate the ``unittest`` framework's organization around
  191. classes and methods. This makes it easy to abstract common tasks into
  192. common methods. The framework also supports explicit setup and/or cleanup
  193. routines, which give you a high level of control over the environment
  194. in which your test cases are run.
  195. * If you're writing tests for Django itself, you should use ``unittest``.
  196. Again, remember that you can use both systems side-by-side (even in the same
  197. app). In the end, most projects will eventually end up using both. Each shines
  198. in different circumstances.
  199. .. _running-tests:
  200. Running tests
  201. =============
  202. Once you've written tests, run them using the :djadmin:`test` subcommand of
  203. your project's ``manage.py`` utility::
  204. $ ./manage.py test
  205. By default, this will run every test in every application in
  206. :setting:`INSTALLED_APPS`. If you only want to run tests for a particular
  207. application, add the application name to the command line. For example, if your
  208. :setting:`INSTALLED_APPS` contains ``'myproject.polls'`` and
  209. ``'myproject.animals'``, you can run the ``myproject.animals`` unit tests alone
  210. with this command::
  211. $ ./manage.py test animals
  212. Note that we used ``animals``, not ``myproject.animals``.
  213. .. versionadded:: 1.0
  214. You can now choose which test to run.
  215. You can be even *more* specific by naming an individual test case. To
  216. run a single test case in an application (for example, the
  217. ``AnimalTestCase`` described in the "Writing unit tests" section), add
  218. the name of the test case to the label on the command line::
  219. $ ./manage.py test animals.AnimalTestCase
  220. And it gets even more granular than that! To run a *single* test
  221. method inside a test case, add the name of the test method to the
  222. label::
  223. $ ./manage.py test animals.AnimalTestCase.testFluffyAnimals
  224. .. versionadded:: 1.2
  225. The ability to select individual doctests was added.
  226. You can use the same rules if you're using doctests. Django will use the
  227. test label as a path to the test method or class that you want to run.
  228. If your ``models.py`` or ``tests.py`` has a function with a doctest, or
  229. class with a class-level doctest, you can invoke that test by appending the
  230. name of the test method or class to the label::
  231. $ ./manage.py test animals.classify
  232. If you want to run the doctest for a specific method in a class, add the
  233. name of the method to the label::
  234. $ ./manage.py test animals.Classifier.run
  235. If you're using a ``__test__`` dictionary to specify doctests for a
  236. module, Django will use the label as a key in the ``__test__`` dictionary
  237. for defined in ``models.py`` and ``tests.py``.
  238. .. versionadded:: 1.2
  239. You can now trigger a graceful exit from a test run by pressing ``Ctrl-C``.
  240. If you press ``Ctrl-C`` while the tests are running, the test runner will
  241. wait for the currently running test to complete and then exit gracefully.
  242. During a graceful exit the test runner will output details of any test
  243. failures, report on how many tests were run and how many errors and failures
  244. were encountered, and destroy any test databases as usual. Thus pressing
  245. ``Ctrl-C`` can be very useful if you forget to pass the :djadminopt:`--failfast`
  246. option, notice that some tests are unexpectedly failing, and want to get details
  247. on the failures without waiting for the full test run to complete.
  248. If you do not want to wait for the currently running test to finish, you
  249. can press ``Ctrl-C`` a second time and the test run will halt immediately,
  250. but not gracefully. No details of the tests run before the interruption will
  251. be reported, and any test databases created by the run will not be destroyed.
  252. .. admonition:: Test with warnings enabled
  253. It's a good idea to run your tests with Python warnings enabled:
  254. ``python -Wall manage.py test``. The ``-Wall`` flag tells Python to
  255. display deprecation warnings. Django, like many other Python libraries,
  256. uses these warnings to flag when features are going away. It also might
  257. flag areas in your code that aren't strictly wrong but could benefit
  258. from a better implementation.
  259. Running tests outside the test runner
  260. -------------------------------------
  261. If you want to run tests outside of ``./manage.py test`` -- for example,
  262. from a shell prompt -- you will need to set up the test
  263. environment first. Django provides a convenience method to do this::
  264. >>> from django.test.utils import setup_test_environment
  265. >>> setup_test_environment()
  266. This convenience method sets up the test database, and puts other
  267. Django features into modes that allow for repeatable testing.
  268. The call to :meth:`~django.test.utils.setup_test_environment` is made
  269. automatically as part of the setup of `./manage.py test`. You only
  270. need to manually invoke this method if you're not using running your
  271. tests via Django's test runner.
  272. The test database
  273. -----------------
  274. Tests that require a database (namely, model tests) will not use your "real"
  275. (production) database. Separate, blank databases are created for the tests.
  276. Regardless of whether the tests pass or fail, the test databases are destroyed
  277. when all the tests have been executed.
  278. By default the test databases get their names by prepending ``test_``
  279. to the value of the :setting:`NAME` settings for the databases
  280. defined in :setting:`DATABASES`. When using the SQLite database engine
  281. the tests will by default use an in-memory database (i.e., the
  282. database will be created in memory, bypassing the filesystem
  283. entirely!). If you want to use a different database name, specify
  284. :setting:`TEST_NAME` in the dictionary for any given database in
  285. :setting:`DATABASES`.
  286. Aside from using a separate database, the test runner will otherwise
  287. use all of the same database settings you have in your settings file:
  288. :setting:`ENGINE`, :setting:`USER`, :setting:`HOST`, etc. The test
  289. database is created by the user specified by ``USER``, so you'll need
  290. to make sure that the given user account has sufficient privileges to
  291. create a new database on the system.
  292. .. versionadded:: 1.0
  293. For fine-grained control over the character encoding of your test
  294. database, use the :setting:`TEST_CHARSET` option. If you're using
  295. MySQL, you can also use the :setting:`TEST_COLLATION` option to
  296. control the particular collation used by the test database. See the
  297. :doc:`settings documentation </ref/settings>` for details of these
  298. advanced settings.
  299. .. _topics-testing-masterslave:
  300. Testing master/slave configurations
  301. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  302. .. versionadded:: 1.2
  303. If you're testing a multiple database configuration with master/slave
  304. replication, this strategy of creating test databases poses a problem.
  305. When the test databases are created, there won't be any replication,
  306. and as a result, data created on the master won't be seen on the
  307. slave.
  308. To compensate for this, Django allows you to define that a database is
  309. a *test mirror*. Consider the following (simplified) example database
  310. configuration::
  311. DATABASES = {
  312. 'default': {
  313. 'ENGINE': 'django.db.backends.mysql',
  314. 'NAME': 'myproject',
  315. 'HOST': 'dbmaster',
  316. # ... plus some other settings
  317. },
  318. 'slave': {
  319. 'ENGINE': 'django.db.backends.mysql',
  320. 'NAME': 'myproject',
  321. 'HOST': 'dbslave',
  322. 'TEST_MIRROR': 'default'
  323. # ... plus some other settings
  324. }
  325. }
  326. In this setup, we have two database servers: ``dbmaster``, described
  327. by the database alias ``default``, and ``dbslave`` described by the
  328. alias ``slave``. As you might expect, ``dbslave`` has been configured
  329. by the database administrator as a read slave of ``dbmaster``, so in
  330. normal activity, any write to ``default`` will appear on ``slave``.
  331. If Django created two independent test databases, this would break any
  332. tests that expected replication to occur. However, the ``slave``
  333. database has been configured as a test mirror (using the
  334. :setting:`TEST_MIRROR` setting), indicating that under testing,
  335. ``slave`` should be treated as a mirror of ``default``.
  336. When the test environment is configured, a test version of ``slave``
  337. will *not* be created. Instead the connection to ``slave``
  338. will be redirected to point at ``default``. As a result, writes to
  339. ``default`` will appear on ``slave`` -- but because they are actually
  340. the same database, not because there is data replication between the
  341. two databases.
  342. Other test conditions
  343. ---------------------
  344. Regardless of the value of the :setting:`DEBUG` setting in your configuration
  345. file, all Django tests run with :setting:`DEBUG`\=False. This is to ensure that
  346. the observed output of your code matches what will be seen in a production
  347. setting.
  348. Understanding the test output
  349. -----------------------------
  350. When you run your tests, you'll see a number of messages as the test runner
  351. prepares itself. You can control the level of detail of these messages with the
  352. ``verbosity`` option on the command line::
  353. Creating test database...
  354. Creating table myapp_animal
  355. Creating table myapp_mineral
  356. Loading 'initial_data' fixtures...
  357. No fixtures found.
  358. This tells you that the test runner is creating a test database, as described
  359. in the previous section.
  360. Once the test database has been created, Django will run your tests.
  361. If everything goes well, you'll see something like this::
  362. ----------------------------------------------------------------------
  363. Ran 22 tests in 0.221s
  364. OK
  365. If there are test failures, however, you'll see full details about which tests
  366. failed::
  367. ======================================================================
  368. FAIL: Doctest: ellington.core.throttle.models
  369. ----------------------------------------------------------------------
  370. Traceback (most recent call last):
  371. File "/dev/django/test/doctest.py", line 2153, in runTest
  372. raise self.failureException(self.format_failure(new.getvalue()))
  373. AssertionError: Failed doctest test for myapp.models
  374. File "/dev/myapp/models.py", line 0, in models
  375. ----------------------------------------------------------------------
  376. File "/dev/myapp/models.py", line 14, in myapp.models
  377. Failed example:
  378. throttle.check("actor A", "action one", limit=2, hours=1)
  379. Expected:
  380. True
  381. Got:
  382. False
  383. ----------------------------------------------------------------------
  384. Ran 2 tests in 0.048s
  385. FAILED (failures=1)
  386. A full explanation of this error output is beyond the scope of this document,
  387. but it's pretty intuitive. You can consult the documentation of Python's
  388. ``unittest`` library for details.
  389. Note that the return code for the test-runner script is the total number of
  390. failed and erroneous tests. If all the tests pass, the return code is 0. This
  391. feature is useful if you're using the test-runner script in a shell script and
  392. need to test for success or failure at that level.
  393. Testing tools
  394. =============
  395. Django provides a small set of tools that come in handy when writing tests.
  396. .. _test-client:
  397. The test client
  398. ---------------
  399. .. module:: django.test.client
  400. :synopsis: Django's test client.
  401. The test client is a Python class that acts as a dummy Web browser, allowing
  402. you to test your views and interact with your Django-powered application
  403. programmatically.
  404. Some of the things you can do with the test client are:
  405. * Simulate GET and POST requests on a URL and observe the response --
  406. everything from low-level HTTP (result headers and status codes) to
  407. page content.
  408. * Test that the correct view is executed for a given URL.
  409. * Test that a given request is rendered by a given Django template, with
  410. a template context that contains certain values.
  411. Note that the test client is not intended to be a replacement for Twill_,
  412. Selenium_, or other "in-browser" frameworks. Django's test client has
  413. a different focus. In short:
  414. * Use Django's test client to establish that the correct view is being
  415. called and that the view is collecting the correct context data.
  416. * Use in-browser frameworks such as Twill and Selenium to test *rendered*
  417. HTML and the *behavior* of Web pages, namely JavaScript functionality.
  418. A comprehensive test suite should use a combination of both test types.
  419. .. _Twill: http://twill.idyll.org/
  420. .. _Selenium: http://seleniumhq.org/
  421. Overview and a quick example
  422. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  423. To use the test client, instantiate ``django.test.client.Client`` and retrieve
  424. Web pages::
  425. >>> from django.test.client import Client
  426. >>> c = Client()
  427. >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
  428. >>> response.status_code
  429. 200
  430. >>> response = c.get('/customer/details/')
  431. >>> response.content
  432. '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...'
  433. As this example suggests, you can instantiate ``Client`` from within a session
  434. of the Python interactive interpreter.
  435. Note a few important things about how the test client works:
  436. * The test client does *not* require the Web server to be running. In fact,
  437. it will run just fine with no Web server running at all! That's because
  438. it avoids the overhead of HTTP and deals directly with the Django
  439. framework. This helps make the unit tests run quickly.
  440. * When retrieving pages, remember to specify the *path* of the URL, not the
  441. whole domain. For example, this is correct::
  442. >>> c.get('/login/')
  443. This is incorrect::
  444. >>> c.get('http://www.example.com/login/')
  445. The test client is not capable of retrieving Web pages that are not
  446. powered by your Django project. If you need to retrieve other Web pages,
  447. use a Python standard library module such as urllib_ or urllib2_.
  448. * To resolve URLs, the test client uses whatever URLconf is pointed-to by
  449. your :setting:`ROOT_URLCONF` setting.
  450. * Although the above example would work in the Python interactive
  451. interpreter, some of the test client's functionality, notably the
  452. template-related functionality, is only available *while tests are
  453. running*.
  454. The reason for this is that Django's test runner performs a bit of black
  455. magic in order to determine which template was loaded by a given view.
  456. This black magic (essentially a patching of Django's template system in
  457. memory) only happens during test running.
  458. * By default, the test client will disable any CSRF checks
  459. performed by your site.
  460. .. versionadded:: 1.2.2
  461. If, for some reason, you *want* the test client to perform CSRF
  462. checks, you can create an instance of the test client that
  463. enforces CSRF checks. To do this, pass in the
  464. ``enforce_csrf_checks`` argument when you construct your
  465. client::
  466. >>> from django.test import Client
  467. >>> csrf_client = Client(enforce_csrf_checks=True)
  468. .. _urllib: http://docs.python.org/library/urllib.html
  469. .. _urllib2: http://docs.python.org/library/urllib2.html
  470. Making requests
  471. ~~~~~~~~~~~~~~~
  472. Use the ``django.test.client.Client`` class to make requests. It requires no
  473. arguments at time of construction:
  474. .. class:: Client()
  475. Once you have a ``Client`` instance, you can call any of the following
  476. methods:
  477. .. method:: Client.get(path, data={}, follow=False, **extra)
  478. Makes a GET request on the provided ``path`` and returns a ``Response``
  479. object, which is documented below.
  480. The key-value pairs in the ``data`` dictionary are used to create a GET
  481. data payload. For example::
  482. >>> c = Client()
  483. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
  484. ...will result in the evaluation of a GET request equivalent to::
  485. /customers/details/?name=fred&age=7
  486. The ``extra`` keyword arguments parameter can be used to specify
  487. headers to be sent in the request. For example::
  488. >>> c = Client()
  489. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
  490. ... HTTP_X_REQUESTED_WITH='XMLHttpRequest')
  491. ...will send the HTTP header ``HTTP_X_REQUESTED_WITH`` to the
  492. details view, which is a good way to test code paths that use the
  493. :meth:`django.http.HttpRequest.is_ajax()` method.
  494. .. versionadded:: 1.1
  495. If you already have the GET arguments in URL-encoded form, you can
  496. use that encoding instead of using the data argument. For example,
  497. the previous GET request could also be posed as::
  498. >>> c = Client()
  499. >>> c.get('/customers/details/?name=fred&age=7')
  500. If you provide a URL with both an encoded GET data and a data argument,
  501. the data argument will take precedence.
  502. If you set ``follow`` to ``True`` the client will follow any redirects
  503. and a ``redirect_chain`` attribute will be set in the response object
  504. containing tuples of the intermediate urls and status codes.
  505. If you had an url ``/redirect_me/`` that redirected to ``/next/``, that
  506. redirected to ``/final/``, this is what you'd see::
  507. >>> response = c.get('/redirect_me/', follow=True)
  508. >>> response.redirect_chain
  509. [(u'http://testserver/next/', 302), (u'http://testserver/final/', 302)]
  510. .. method:: Client.post(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
  511. Makes a POST request on the provided ``path`` and returns a
  512. ``Response`` object, which is documented below.
  513. The key-value pairs in the ``data`` dictionary are used to submit POST
  514. data. For example::
  515. >>> c = Client()
  516. >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
  517. ...will result in the evaluation of a POST request to this URL::
  518. /login/
  519. ...with this POST data::
  520. name=fred&passwd=secret
  521. If you provide ``content_type`` (e.g., ``text/xml`` for an XML
  522. payload), the contents of ``data`` will be sent as-is in the POST
  523. request, using ``content_type`` in the HTTP ``Content-Type`` header.
  524. If you don't provide a value for ``content_type``, the values in
  525. ``data`` will be transmitted with a content type of
  526. ``multipart/form-data``. In this case, the key-value pairs in ``data``
  527. will be encoded as a multipart message and used to create the POST data
  528. payload.
  529. To submit multiple values for a given key -- for example, to specify
  530. the selections for a ``<select multiple>`` -- provide the values as a
  531. list or tuple for the required key. For example, this value of ``data``
  532. would submit three selected values for the field named ``choices``::
  533. {'choices': ('a', 'b', 'd')}
  534. Submitting files is a special case. To POST a file, you need only
  535. provide the file field name as a key, and a file handle to the file you
  536. wish to upload as a value. For example::
  537. >>> c = Client()
  538. >>> f = open('wishlist.doc')
  539. >>> c.post('/customers/wishes/', {'name': 'fred', 'attachment': f})
  540. >>> f.close()
  541. (The name ``attachment`` here is not relevant; use whatever name your
  542. file-processing code expects.)
  543. Note that if you wish to use the same file handle for multiple
  544. ``post()`` calls then you will need to manually reset the file
  545. pointer between posts. The easiest way to do this is to
  546. manually close the file after it has been provided to
  547. ``post()``, as demonstrated above.
  548. You should also ensure that the file is opened in a way that
  549. allows the data to be read. If your file contains binary data
  550. such as an image, this means you will need to open the file in
  551. ``rb`` (read binary) mode.
  552. The ``extra`` argument acts the same as for :meth:`Client.get`.
  553. .. versionchanged:: 1.1
  554. If the URL you request with a POST contains encoded parameters, these
  555. parameters will be made available in the request.GET data. For example,
  556. if you were to make the request::
  557. >>> c.post('/login/?vistor=true', {'name': 'fred', 'passwd': 'secret'})
  558. ... the view handling this request could interrogate request.POST
  559. to retrieve the username and password, and could interrogate request.GET
  560. to determine if the user was a visitor.
  561. If you set ``follow`` to ``True`` the client will follow any redirects
  562. and a ``redirect_chain`` attribute will be set in the response object
  563. containing tuples of the intermediate urls and status codes.
  564. .. method:: Client.head(path, data={}, follow=False, **extra)
  565. .. versionadded:: 1.1
  566. Makes a HEAD request on the provided ``path`` and returns a ``Response``
  567. object. Useful for testing RESTful interfaces. Acts just like
  568. :meth:`Client.get` except it does not return a message body.
  569. If you set ``follow`` to ``True`` the client will follow any redirects
  570. and a ``redirect_chain`` attribute will be set in the response object
  571. containing tuples of the intermediate urls and status codes.
  572. .. method:: Client.options(path, data={}, follow=False, **extra)
  573. .. versionadded:: 1.1
  574. Makes an OPTIONS request on the provided ``path`` and returns a
  575. ``Response`` object. Useful for testing RESTful interfaces.
  576. If you set ``follow`` to ``True`` the client will follow any redirects
  577. and a ``redirect_chain`` attribute will be set in the response object
  578. containing tuples of the intermediate urls and status codes.
  579. The ``extra`` argument acts the same as for :meth:`Client.get`.
  580. .. method:: Client.put(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
  581. .. versionadded:: 1.1
  582. Makes a PUT request on the provided ``path`` and returns a
  583. ``Response`` object. Useful for testing RESTful interfaces. Acts just
  584. like :meth:`Client.post` except with the PUT request method.
  585. If you set ``follow`` to ``True`` the client will follow any redirects
  586. and a ``redirect_chain`` attribute will be set in the response object
  587. containing tuples of the intermediate urls and status codes.
  588. .. method:: Client.delete(path, follow=False, **extra)
  589. .. versionadded:: 1.1
  590. Makes an DELETE request on the provided ``path`` and returns a
  591. ``Response`` object. Useful for testing RESTful interfaces.
  592. If you set ``follow`` to ``True`` the client will follow any redirects
  593. and a ``redirect_chain`` attribute will be set in the response object
  594. containing tuples of the intermediate urls and status codes.
  595. The ``extra`` argument acts the same as for :meth:`Client.get`.
  596. .. method:: Client.login(**credentials)
  597. .. versionadded:: 1.0
  598. If your site uses Django's :doc:`authentication system</topics/auth>`
  599. and you deal with logging in users, you can use the test client's
  600. ``login()`` method to simulate the effect of a user logging into the
  601. site.
  602. After you call this method, the test client will have all the cookies
  603. and session data required to pass any login-based tests that may form
  604. part of a view.
  605. The format of the ``credentials`` argument depends on which
  606. :ref:`authentication backend <authentication-backends>` you're using
  607. (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
  608. setting). If you're using the standard authentication backend provided
  609. by Django (``ModelBackend``), ``credentials`` should be the user's
  610. username and password, provided as keyword arguments::
  611. >>> c = Client()
  612. >>> c.login(username='fred', password='secret')
  613. # Now you can access a view that's only available to logged-in users.
  614. If you're using a different authentication backend, this method may
  615. require different credentials. It requires whichever credentials are
  616. required by your backend's ``authenticate()`` method.
  617. ``login()`` returns ``True`` if it the credentials were accepted and
  618. login was successful.
  619. Finally, you'll need to remember to create user accounts before you can
  620. use this method. As we explained above, the test runner is executed
  621. using a test database, which contains no users by default. As a result,
  622. user accounts that are valid on your production site will not work
  623. under test conditions. You'll need to create users as part of the test
  624. suite -- either manually (using the Django model API) or with a test
  625. fixture. Remember that if you want your test user to have a password,
  626. you can't set the user's password by setting the password attribute
  627. directly -- you must use the
  628. :meth:`~django.contrib.auth.models.User.set_password()` function to
  629. store a correctly hashed password. Alternatively, you can use the
  630. :meth:`~django.contrib.auth.models.UserManager.create_user` helper
  631. method to create a new user with a correctly hashed password.
  632. .. method:: Client.logout()
  633. .. versionadded:: 1.0
  634. If your site uses Django's :doc:`authentication system</topics/auth>`,
  635. the ``logout()`` method can be used to simulate the effect of a user
  636. logging out of your site.
  637. After you call this method, the test client will have all the cookies
  638. and session data cleared to defaults. Subsequent requests will appear
  639. to come from an AnonymousUser.
  640. Testing responses
  641. ~~~~~~~~~~~~~~~~~
  642. The ``get()`` and ``post()`` methods both return a ``Response`` object. This
  643. ``Response`` object is *not* the same as the ``HttpResponse`` object returned
  644. Django views; the test response object has some additional data useful for
  645. test code to verify.
  646. Specifically, a ``Response`` object has the following attributes:
  647. .. class:: Response()
  648. .. attribute:: client
  649. The test client that was used to make the request that resulted in the
  650. response.
  651. .. attribute:: content
  652. The body of the response, as a string. This is the final page content as
  653. rendered by the view, or any error message.
  654. .. attribute:: context
  655. The template ``Context`` instance that was used to render the template that
  656. produced the response content.
  657. If the rendered page used multiple templates, then ``context`` will be a
  658. list of ``Context`` objects, in the order in which they were rendered.
  659. .. versionadded:: 1.1
  660. Regardless of the number of templates used during rendering, you can
  661. retrieve context values using the ``[]`` operator. For example, the
  662. context variable ``name`` could be retrieved using::
  663. >>> response = client.get('/foo/')
  664. >>> response.context['name']
  665. 'Arthur'
  666. .. attribute:: request
  667. The request data that stimulated the response.
  668. .. attribute:: status_code
  669. The HTTP status of the response, as an integer. See RFC2616_ for a full
  670. list of HTTP status codes.
  671. .. versionadded:: 1.3
  672. .. attribute:: templates
  673. A list of ``Template`` instances used to render the final content, in
  674. the order they were rendered. For each template in the list, use
  675. ``template.name`` to get the template's file name, if the template was
  676. loaded from a file. (The name is a string such as
  677. ``'admin/index.html'``.)
  678. You can also use dictionary syntax on the response object to query the value
  679. of any settings in the HTTP headers. For example, you could determine the
  680. content type of a response using ``response['Content-Type']``.
  681. .. _RFC2616: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  682. Exceptions
  683. ~~~~~~~~~~
  684. If you point the test client at a view that raises an exception, that exception
  685. will be visible in the test case. You can then use a standard ``try...except``
  686. block or ``unittest.TestCase.assertRaises()`` to test for exceptions.
  687. The only exceptions that are not visible to the test client are ``Http404``,
  688. ``PermissionDenied`` and ``SystemExit``. Django catches these exceptions
  689. internally and converts them into the appropriate HTTP response codes. In these
  690. cases, you can check ``response.status_code`` in your test.
  691. Persistent state
  692. ~~~~~~~~~~~~~~~~
  693. The test client is stateful. If a response returns a cookie, then that cookie
  694. will be stored in the test client and sent with all subsequent ``get()`` and
  695. ``post()`` requests.
  696. Expiration policies for these cookies are not followed. If you want a cookie
  697. to expire, either delete it manually or create a new ``Client`` instance (which
  698. will effectively delete all cookies).
  699. A test client has two attributes that store persistent state information. You
  700. can access these properties as part of a test condition.
  701. .. attribute:: Client.cookies
  702. A Python ``SimpleCookie`` object, containing the current values of all the
  703. client cookies. See the `Cookie module documentation`_ for more.
  704. .. attribute:: Client.session
  705. A dictionary-like object containing session information. See the
  706. :doc:`session documentation</topics/http/sessions>` for full details.
  707. To modify the session and then save it, it must be stored in a variable
  708. first (because a new ``SessionStore`` is created every time this property
  709. is accessed)::
  710. def test_something(self):
  711. session = self.client.session
  712. session['somekey'] = 'test'
  713. session.save()
  714. .. _Cookie module documentation: http://docs.python.org/library/cookie.html
  715. Example
  716. ~~~~~~~
  717. The following is a simple unit test using the test client::
  718. from django.utils import unittest
  719. from django.test.client import Client
  720. class SimpleTest(unittest.TestCase):
  721. def setUp(self):
  722. # Every test needs a client.
  723. self.client = Client()
  724. def test_details(self):
  725. # Issue a GET request.
  726. response = self.client.get('/customer/details/')
  727. # Check that the response is 200 OK.
  728. self.assertEqual(response.status_code, 200)
  729. # Check that the rendered context contains 5 customers.
  730. self.assertEqual(len(response.context['customers']), 5)
  731. TestCase
  732. --------
  733. .. currentmodule:: django.test
  734. Normal Python unit test classes extend a base class of ``unittest.TestCase``.
  735. Django provides an extension of this base class:
  736. .. class:: TestCase()
  737. This class provides some additional capabilities that can be useful for testing
  738. Web sites.
  739. Converting a normal ``unittest.TestCase`` to a Django ``TestCase`` is easy:
  740. just change the base class of your test from ``unittest.TestCase`` to
  741. ``django.test.TestCase``. All of the standard Python unit test functionality
  742. will continue to be available, but it will be augmented with some useful
  743. additions.
  744. .. versionadded:: 1.1
  745. .. class:: TransactionTestCase()
  746. Django ``TestCase`` classes make use of database transaction facilities, if
  747. available, to speed up the process of resetting the database to a known state
  748. at the beginning of each test. A consequence of this, however, is that the
  749. effects of transaction commit and rollback cannot be tested by a Django
  750. ``TestCase`` class. If your test requires testing of such transactional
  751. behavior, you should use a Django ``TransactionTestCase``.
  752. ``TransactionTestCase`` and ``TestCase`` are identical except for the manner
  753. in which the database is reset to a known state and the ability for test code
  754. to test the effects of commit and rollback. A ``TransactionTestCase`` resets
  755. the database before the test runs by truncating all tables and reloading
  756. initial data. A ``TransactionTestCase`` may call commit and rollback and
  757. observe the effects of these calls on the database.
  758. A ``TestCase``, on the other hand, does not truncate tables and reload initial
  759. data at the beginning of a test. Instead, it encloses the test code in a
  760. database transaction that is rolled back at the end of the test. It also
  761. prevents the code under test from issuing any commit or rollback operations
  762. on the database, to ensure that the rollback at the end of the test restores
  763. the database to its initial state. In order to guarantee that all ``TestCase``
  764. code starts with a clean database, the Django test runner runs all ``TestCase``
  765. tests first, before any other tests (e.g. doctests) that may alter the
  766. database without restoring it to its original state.
  767. When running on a database that does not support rollback (e.g. MySQL with the
  768. MyISAM storage engine), ``TestCase`` falls back to initializing the database
  769. by truncating tables and reloading initial data.
  770. .. note::
  771. The ``TestCase`` use of rollback to un-do the effects of the test code
  772. may reveal previously-undetected errors in test code. For example,
  773. test code that assumes primary keys values will be assigned starting at
  774. one may find that assumption no longer holds true when rollbacks instead
  775. of table truncation are being used to reset the database. Similarly,
  776. the reordering of tests so that all ``TestCase`` classes run first may
  777. reveal unexpected dependencies on test case ordering. In such cases a
  778. quick fix is to switch the ``TestCase`` to a ``TransactionTestCase``.
  779. A better long-term fix, that allows the test to take advantage of the
  780. speed benefit of ``TestCase``, is to fix the underlying test problem.
  781. Default test client
  782. ~~~~~~~~~~~~~~~~~~~
  783. .. versionadded:: 1.0
  784. .. attribute:: TestCase.client
  785. Every test case in a ``django.test.TestCase`` instance has access to an
  786. instance of a Django test client. This client can be accessed as
  787. ``self.client``. This client is recreated for each test, so you don't have to
  788. worry about state (such as cookies) carrying over from one test to another.
  789. This means, instead of instantiating a ``Client`` in each test::
  790. from django.utils import unittest
  791. from django.test.client import Client
  792. class SimpleTest(unittest.TestCase):
  793. def test_details(self):
  794. client = Client()
  795. response = client.get('/customer/details/')
  796. self.assertEqual(response.status_code, 200)
  797. def test_index(self):
  798. client = Client()
  799. response = client.get('/customer/index/')
  800. self.assertEqual(response.status_code, 200)
  801. ...you can just refer to ``self.client``, like so::
  802. from django.test import TestCase
  803. class SimpleTest(TestCase):
  804. def test_details(self):
  805. response = self.client.get('/customer/details/')
  806. self.assertEqual(response.status_code, 200)
  807. def test_index(self):
  808. response = self.client.get('/customer/index/')
  809. self.assertEqual(response.status_code, 200)
  810. Customizing the test client
  811. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  812. .. versionadded:: 1.3
  813. .. attribute:: TestCase.client_class
  814. If you want to use a different Client class (for example, a subclass
  815. with customized behavior), you can use the
  816. :attr:`~TestCase.client_class` class attribute to specify a custom
  817. ``Client`` class in your test case::
  818. from django.test import TestCase
  819. from django.test.client import Client
  820. class MyTestClient(Client):
  821. # .. specialized methods for your environment ..
  822. class MyTest(TestCase):
  823. client_class = MyTestClient
  824. def test_my_stuff(self):
  825. # .. Here self.client is an instance of MyTestClient ..
  826. .. _topics-testing-fixtures:
  827. Fixture loading
  828. ~~~~~~~~~~~~~~~
  829. .. attribute:: TestCase.fixtures
  830. A test case for a database-backed Web site isn't much use if there isn't any
  831. data in the database. To make it easy to put test data into the database,
  832. Django's custom ``TestCase`` class provides a way of loading **fixtures**.
  833. A fixture is a collection of data that Django knows how to import into a
  834. database. For example, if your site has user accounts, you might set up a
  835. fixture of fake user accounts in order to populate your database during tests.
  836. The most straightforward way of creating a fixture is to use the
  837. :djadmin:`manage.py dumpdata <dumpdata>` command. This assumes you
  838. already have some data in your database. See the :djadmin:`dumpdata
  839. documentation<dumpdata>` for more details.
  840. .. note::
  841. If you've ever run :djadmin:`manage.py syncdb<syncdb>`, you've
  842. already used a fixture without even knowing it! When you call
  843. :djadmin:`syncdb` in the database for the first time, Django
  844. installs a fixture called ``initial_data``. This gives you a way
  845. of populating a new database with any initial data, such as a
  846. default set of categories.
  847. Fixtures with other names can always be installed manually using
  848. the :djadmin:`manage.py loaddata<loaddata>` command.
  849. Once you've created a fixture and placed it in a ``fixtures`` directory in one
  850. of your :setting:`INSTALLED_APPS`, you can use it in your unit tests by
  851. specifying a ``fixtures`` class attribute on your :class:`django.test.TestCase`
  852. subclass::
  853. from django.test import TestCase
  854. from myapp.models import Animal
  855. class AnimalTestCase(TestCase):
  856. fixtures = ['mammals.json', 'birds']
  857. def setUp(self):
  858. # Test definitions as before.
  859. call_setup_methods()
  860. def testFluffyAnimals(self):
  861. # A test that uses the fixtures.
  862. call_some_test_code()
  863. Here's specifically what will happen:
  864. * At the start of each test case, before ``setUp()`` is run, Django will
  865. flush the database, returning the database to the state it was in
  866. directly after :djadmin:`syncdb` was called.
  867. * Then, all the named fixtures are installed. In this example, Django will
  868. install any JSON fixture named ``mammals``, followed by any fixture named
  869. ``birds``. See the :djadmin:`loaddata` documentation for more
  870. details on defining and installing fixtures.
  871. This flush/load procedure is repeated for each test in the test case, so you
  872. can be certain that the outcome of a test will not be affected by another test,
  873. or by the order of test execution.
  874. URLconf configuration
  875. ~~~~~~~~~~~~~~~~~~~~~
  876. .. versionadded:: 1.0
  877. .. attribute:: TestCase.urls
  878. If your application provides views, you may want to include tests that use the
  879. test client to exercise those views. However, an end user is free to deploy the
  880. views in your application at any URL of their choosing. This means that your
  881. tests can't rely upon the fact that your views will be available at a
  882. particular URL.
  883. In order to provide a reliable URL space for your test,
  884. ``django.test.TestCase`` provides the ability to customize the URLconf
  885. configuration for the duration of the execution of a test suite. If your
  886. ``TestCase`` instance defines an ``urls`` attribute, the ``TestCase`` will use
  887. the value of that attribute as the ``ROOT_URLCONF`` for the duration of that
  888. test.
  889. For example::
  890. from django.test import TestCase
  891. class TestMyViews(TestCase):
  892. urls = 'myapp.test_urls'
  893. def testIndexPageView(self):
  894. # Here you'd test your view using ``Client``.
  895. call_some_test_code()
  896. This test case will use the contents of ``myapp.test_urls`` as the
  897. URLconf for the duration of the test case.
  898. .. _emptying-test-outbox:
  899. Multi-database support
  900. ~~~~~~~~~~~~~~~~~~~~~~
  901. .. attribute:: TestCase.multi_db
  902. .. versionadded:: 1.2
  903. Django sets up a test database corresponding to every database that is
  904. defined in the :setting:`DATABASES` definition in your settings
  905. file. However, a big part of the time taken to run a Django TestCase
  906. is consumed by the call to ``flush`` that ensures that you have a
  907. clean database at the start of each test run. If you have multiple
  908. databases, multiple flushes are required (one for each database),
  909. which can be a time consuming activity -- especially if your tests
  910. don't need to test multi-database activity.
  911. As an optimization, Django only flushes the ``default`` database at
  912. the start of each test run. If your setup contains multiple databases,
  913. and you have a test that requires every database to be clean, you can
  914. use the ``multi_db`` attribute on the test suite to request a full
  915. flush.
  916. For example::
  917. class TestMyViews(TestCase):
  918. multi_db = True
  919. def testIndexPageView(self):
  920. call_some_test_code()
  921. This test case will flush *all* the test databases before running
  922. ``testIndexPageView``.
  923. Emptying the test outbox
  924. ~~~~~~~~~~~~~~~~~~~~~~~~
  925. .. versionadded:: 1.0
  926. If you use Django's custom ``TestCase`` class, the test runner will clear the
  927. contents of the test e-mail outbox at the start of each test case.
  928. For more detail on e-mail services during tests, see `E-mail services`_.
  929. Assertions
  930. ~~~~~~~~~~
  931. .. versionadded:: 1.0
  932. .. versionchanged:: 1.2
  933. Addded ``msg_prefix`` argument.
  934. As Python's normal ``unittest.TestCase`` class implements assertion methods
  935. such as ``assertTrue`` and ``assertEqual``, Django's custom ``TestCase`` class
  936. provides a number of custom assertion methods that are useful for testing Web
  937. applications:
  938. The failure messages given by the assertion methods can be customized
  939. with the ``msg_prefix`` argument. This string will be prefixed to any
  940. failure message generated by the assertion. This allows you to provide
  941. additional details that may help you to identify the location and
  942. cause of an failure in your test suite.
  943. .. method:: TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='')
  944. Asserts that a ``Response`` instance produced the given ``status_code`` and
  945. that ``text`` appears in the content of the response. If ``count`` is
  946. provided, ``text`` must occur exactly ``count`` times in the response.
  947. .. method:: TestCase.assertNotContains(response, text, status_code=200, msg_prefix='')
  948. Asserts that a ``Response`` instance produced the given ``status_code`` and
  949. that ``text`` does not appears in the content of the response.
  950. .. method:: TestCase.assertFormError(response, form, field, errors, msg_prefix='')
  951. Asserts that a field on a form raises the provided list of errors when
  952. rendered on the form.
  953. ``form`` is the name the ``Form`` instance was given in the template
  954. context.
  955. ``field`` is the name of the field on the form to check. If ``field``
  956. has a value of ``None``, non-field errors (errors you can access via
  957. ``form.non_field_errors()``) will be checked.
  958. ``errors`` is an error string, or a list of error strings, that are
  959. expected as a result of form validation.
  960. .. method:: TestCase.assertTemplateUsed(response, template_name, msg_prefix='')
  961. Asserts that the template with the given name was used in rendering the
  962. response.
  963. The name is a string such as ``'admin/index.html'``.
  964. .. method:: TestCase.assertTemplateNotUsed(response, template_name, msg_prefix='')
  965. Asserts that the template with the given name was *not* used in rendering
  966. the response.
  967. .. method:: TestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='')
  968. Asserts that the response return a ``status_code`` redirect status, it
  969. redirected to ``expected_url`` (including any GET data), and the final
  970. page was received with ``target_status_code``.
  971. .. versionadded:: 1.1
  972. If your request used the ``follow`` argument, the ``expected_url`` and
  973. ``target_status_code`` will be the url and status code for the final
  974. point of the redirect chain.
  975. .. method:: TestCase.assertQuerysetEqual(qs, values, transform=repr)
  976. .. versionadded:: 1.3
  977. Asserts that a queryset ``qs`` returns a particular list of values ``values``.
  978. The comparison of the contents of ``qs`` and ``values`` is performed using
  979. the function ``transform``; by default, this means that the ``repr()`` of
  980. each value is compared. Any other callable can be used if ``repr()`` doesn't
  981. provide a unique or helpful comparison.
  982. The comparison is also ordering dependent. If ``qs`` doesn't provide an
  983. implicit ordering, you will need to apply a ``order_by()`` clause to your
  984. queryset to ensure that the test will pass reliably.
  985. .. _topics-testing-email:
  986. E-mail services
  987. ---------------
  988. .. versionadded:: 1.0
  989. If any of your Django views send e-mail using :doc:`Django's e-mail
  990. functionality </topics/email>`, you probably don't want to send e-mail each time
  991. you run a test using that view. For this reason, Django's test runner
  992. automatically redirects all Django-sent e-mail to a dummy outbox. This lets you
  993. test every aspect of sending e-mail -- from the number of messages sent to the
  994. contents of each message -- without actually sending the messages.
  995. The test runner accomplishes this by transparently replacing the normal
  996. email backend with a testing backend.
  997. (Don't worry -- this has no effect on any other e-mail senders outside of
  998. Django, such as your machine's mail server, if you're running one.)
  999. .. currentmodule:: django.core.mail
  1000. .. data:: django.core.mail.outbox
  1001. During test running, each outgoing e-mail is saved in
  1002. ``django.core.mail.outbox``. This is a simple list of all
  1003. :class:`~django.core.mail.EmailMessage` instances that have been sent.
  1004. The ``outbox`` attribute is a special attribute that is created *only* when
  1005. the ``locmem`` e-mail backend is used. It doesn't normally exist as part of the
  1006. :mod:`django.core.mail` module and you can't import it directly. The code
  1007. below shows how to access this attribute correctly.
  1008. Here's an example test that examines ``django.core.mail.outbox`` for length
  1009. and contents::
  1010. from django.core import mail
  1011. from django.test import TestCase
  1012. class EmailTest(TestCase):
  1013. def test_send_email(self):
  1014. # Send message.
  1015. mail.send_mail('Subject here', 'Here is the message.',
  1016. 'from@example.com', ['to@example.com'],
  1017. fail_silently=False)
  1018. # Test that one message has been sent.
  1019. self.assertEqual(len(mail.outbox), 1)
  1020. # Verify that the subject of the first message is correct.
  1021. self.assertEqual(mail.outbox[0].subject, 'Subject here')
  1022. As noted :ref:`previously <emptying-test-outbox>`, the test outbox is emptied
  1023. at the start of every test in a Django ``TestCase``. To empty the outbox
  1024. manually, assign the empty list to ``mail.outbox``::
  1025. from django.core import mail
  1026. # Empty the test outbox
  1027. mail.outbox = []
  1028. Using different testing frameworks
  1029. ==================================
  1030. Clearly, ``doctest`` and ``unittest`` are not the only Python testing
  1031. frameworks. While Django doesn't provide explicit support for alternative
  1032. frameworks, it does provide a way to invoke tests constructed for an
  1033. alternative framework as if they were normal Django tests.
  1034. When you run ``./manage.py test``, Django looks at the :setting:`TEST_RUNNER`
  1035. setting to determine what to do. By default, :setting:`TEST_RUNNER` points to
  1036. ``'django.test.simple.DjangoTestSuiteRunner'``. This class defines the default Django
  1037. testing behavior. This behavior involves:
  1038. #. Performing global pre-test setup.
  1039. #. Looking for unit tests and doctests in the ``models.py`` and
  1040. ``tests.py`` files in each installed application.
  1041. #. Creating the test databases.
  1042. #. Running ``syncdb`` to install models and initial data into the test
  1043. databases.
  1044. #. Running the unit tests and doctests that are found.
  1045. #. Destroying the test databases.
  1046. #. Performing global post-test teardown.
  1047. If you define your own test runner class and point :setting:`TEST_RUNNER` at
  1048. that class, Django will execute your test runner whenever you run
  1049. ``./manage.py test``. In this way, it is possible to use any test framework
  1050. that can be executed from Python code, or to modify the Django test execution
  1051. process to satisfy whatever testing requirements you may have.
  1052. .. _topics-testing-test_runner:
  1053. Defining a test runner
  1054. ----------------------
  1055. .. versionchanged:: 1.2
  1056. Prior to 1.2, test runners were a single function, not a class.
  1057. .. currentmodule:: django.test.simple
  1058. A test runner is a class defining a ``run_tests()`` method. Django ships
  1059. with a ``DjangoTestSuiteRunner`` class that defines the default Django
  1060. testing behavior. This class defines the ``run_tests()`` entry point,
  1061. plus a selection of other methods that are used to by ``run_tests()`` to
  1062. set up, execute and tear down the test suite.
  1063. .. class:: DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=True, **kwargs)
  1064. ``verbosity`` determines the amount of notification and debug information
  1065. that will be printed to the console; ``0`` is no output, ``1`` is normal
  1066. output, and ``2`` is verbose output.
  1067. If ``interactive`` is ``True``, the test suite has permission to ask the
  1068. user for instructions when the test suite is executed. An example of this
  1069. behavior would be asking for permission to delete an existing test
  1070. database. If ``interactive`` is ``False``, the test suite must be able to
  1071. run without any manual intervention.
  1072. If ``failfast`` is ``True``, the test suite will stop running after the
  1073. first test failure is detected.
  1074. Django will, from time to time, extend the capabilities of
  1075. the test runner by adding new arguments. The ``**kwargs`` declaration
  1076. allows for this expansion. If you subclass ``DjangoTestSuiteRunner`` or
  1077. write your own test runner, ensure accept and handle the ``**kwargs``
  1078. parameter.
  1079. .. method:: DjangoTestSuiteRunner.run_tests(test_labels, extra_tests=None, **kwargs)
  1080. Run the test suite.
  1081. ``test_labels`` is a list of strings describing the tests to be run. A test
  1082. label can take one of three forms:
  1083. * ``app.TestCase.test_method`` -- Run a single test method in a test
  1084. case.
  1085. * ``app.TestCase`` -- Run all the test methods in a test case.
  1086. * ``app`` -- Search for and run all tests in the named application.
  1087. If ``test_labels`` has a value of ``None``, the test runner should run
  1088. search for tests in all the applications in :setting:`INSTALLED_APPS`.
  1089. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  1090. suite that is executed by the test runner. These extra tests are run
  1091. in addition to those discovered in the modules listed in ``test_labels``.
  1092. This method should return the number of tests that failed.
  1093. .. method:: DjangoTestSuiteRunner.setup_test_environment(**kwargs)
  1094. Sets up the test environment ready for testing.
  1095. .. method:: DjangoTestSuiteRunner.build_suite(test_labels, extra_tests=None, **kwargs)
  1096. Constructs a test suite that matches the test labels provided.
  1097. ``test_labels`` is a list of strings describing the tests to be run. A test
  1098. label can take one of three forms:
  1099. * ``app.TestCase.test_method`` -- Run a single test method in a test
  1100. case.
  1101. * ``app.TestCase`` -- Run all the test methods in a test case.
  1102. * ``app`` -- Search for and run all tests in the named application.
  1103. If ``test_labels`` has a value of ``None``, the test runner should run
  1104. search for tests in all the applications in :setting:`INSTALLED_APPS`.
  1105. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  1106. suite that is executed by the test runner. These extra tests are run
  1107. in addition to those discovered in the modules listed in ``test_labels``.
  1108. Returns a ``TestSuite`` instance ready to be run.
  1109. .. method:: DjangoTestSuiteRunner.setup_databases(**kwargs)
  1110. Creates the test databases.
  1111. Returns a data structure that provides enough detail to undo the changes
  1112. that have been made. This data will be provided to the ``teardown_databases()``
  1113. function at the conclusion of testing.
  1114. .. method:: DjangoTestSuiteRunner.run_suite(suite, **kwargs)
  1115. Runs the test suite.
  1116. Returns the result produced by the running the test suite.
  1117. .. method:: DjangoTestSuiteRunner.teardown_databases(old_config, **kwargs)
  1118. Destroys the test databases, restoring pre-test conditions.
  1119. ``old_config`` is a data structure defining the changes in the
  1120. database configuration that need to be reversed. It is the return
  1121. value of the ``setup_databases()`` method.
  1122. .. method:: DjangoTestSuiteRunner.teardown_test_environment(**kwargs)
  1123. Restores the pre-test environment.
  1124. .. method:: DjangoTestSuiteRunner.suite_result(suite, result, **kwargs)
  1125. Computes and returns a return code based on a test suite, and the result
  1126. from that test suite.
  1127. Testing utilities
  1128. -----------------
  1129. .. module:: django.test.utils
  1130. :synopsis: Helpers to write custom test runners.
  1131. To assist in the creation of your own test runner, Django provides a number of
  1132. utility methods in the ``django.test.utils`` module.
  1133. .. function:: setup_test_environment()
  1134. Performs any global pre-test setup, such as the installing the
  1135. instrumentation of the template rendering system and setting up
  1136. the dummy ``SMTPConnection``.
  1137. .. function:: teardown_test_environment()
  1138. Performs any global post-test teardown, such as removing the black
  1139. magic hooks into the template system and restoring normal e-mail
  1140. services.
  1141. The creation module of the database backend (``connection.creation``)
  1142. also provides some utilities that can be useful during testing.
  1143. .. function:: create_test_db(verbosity=1, autoclobber=False)
  1144. Creates a new test database and runs ``syncdb`` against it.
  1145. ``verbosity`` has the same behavior as in ``run_tests()``.
  1146. ``autoclobber`` describes the behavior that will occur if a
  1147. database with the same name as the test database is discovered:
  1148. * If ``autoclobber`` is ``False``, the user will be asked to
  1149. approve destroying the existing database. ``sys.exit`` is
  1150. called if the user does not approve.
  1151. * If autoclobber is ``True``, the database will be destroyed
  1152. without consulting the user.
  1153. Returns the name of the test database that it created.
  1154. ``create_test_db()`` has the side effect of modifying the value of
  1155. :setting:`NAME` in :setting:`DATABASES` to match the name of the test
  1156. database.
  1157. .. versionchanged:: 1.0
  1158. ``create_test_db()`` now returns the name of the test database.
  1159. .. function:: destroy_test_db(old_database_name, verbosity=1)
  1160. Destroys the database whose name is in stored in :setting:`NAME` in the
  1161. :setting:`DATABASES`, and sets :setting:`NAME` to use the
  1162. provided name.
  1163. ``verbosity`` has the same behavior as in ``run_tests()``.