testing.txt 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344
  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. * **Unit tests** -- tests that are expressed as methods on a Python class
  29. that subclasses :class:`unittest.TestCase` or Django's customized
  30. :class:`TestCase`. For example::
  31. import unittest
  32. class MyFuncTestCase(unittest.TestCase):
  33. def testBasic(self):
  34. a = ['larry', 'curly', 'moe']
  35. self.assertEqual(my_func(a, 0), 'larry')
  36. self.assertEqual(my_func(a, 1), 'curly')
  37. * **Doctests** -- tests that are embedded in your functions' docstrings and
  38. are written in a way that emulates a session of the Python interactive
  39. interpreter. For example::
  40. def my_func(a_list, idx):
  41. """
  42. >>> a = ['larry', 'curly', 'moe']
  43. >>> my_func(a, 0)
  44. 'larry'
  45. >>> my_func(a, 1)
  46. 'curly'
  47. """
  48. return a_list[idx]
  49. We'll discuss choosing the appropriate test framework later, however, most
  50. experienced developers prefer unit tests. You can also use any *other* Python
  51. test framework, as we'll explain in a bit.
  52. Writing unit tests
  53. ------------------
  54. Django's unit tests use a Python standard library module: :mod:`unittest`. This
  55. module defines tests in class-based approach.
  56. .. admonition:: unittest2
  57. Python 2.7 introduced some major changes to the unittest library,
  58. adding some extremely useful features. To ensure that every Django
  59. project can benefit from these new features, Django ships with a
  60. copy of unittest2_, a copy of the Python 2.7 unittest library,
  61. backported for Python 2.5 compatibility.
  62. To access this library, Django provides the
  63. :mod:`django.utils.unittest` module alias. If you are using Python
  64. 2.7, or you have installed unittest2 locally, Django will map the
  65. alias to the installed version of the unittest library. Otherwise,
  66. Django will use its own bundled version of unittest2.
  67. To use this alias, simply use::
  68. from django.utils import unittest
  69. wherever you would have historically used::
  70. import unittest
  71. If you want to continue to use the base unittest library, you can --
  72. you just won't get any of the nice new unittest2 features.
  73. .. _unittest2: http://pypi.python.org/pypi/unittest2
  74. For a given Django application, the test runner looks for unit tests in two
  75. places:
  76. * The ``models.py`` file. The test runner looks for any subclass of
  77. :class:`unittest.TestCase` in this module.
  78. * A file called ``tests.py`` in the application directory -- i.e., the
  79. directory that holds ``models.py``. Again, the test runner looks for any
  80. subclass of :class:`unittest.TestCase` in this module.
  81. Here is an example :class:`unittest.TestCase` subclass::
  82. from django.utils import unittest
  83. from myapp.models import Animal
  84. class AnimalTestCase(unittest.TestCase):
  85. def setUp(self):
  86. self.lion = Animal.objects.create(name="lion", sound="roar")
  87. self.cat = Animal.objects.create(name="cat", sound="meow")
  88. def test_animals_can_speak(self):
  89. """Animals that can speak are correctly identified"""
  90. self.assertEqual(self.lion.speak(), 'The lion says "roar"')
  91. self.assertEqual(self.cat.speak(), 'The cat says "meow"')
  92. When you :ref:`run your tests <running-tests>`, the default behavior of the test
  93. utility is to find all the test cases (that is, subclasses of
  94. :class:`unittest.TestCase`) in ``models.py`` and ``tests.py``, automatically
  95. build a test suite out of those test cases, and run that suite.
  96. There is a second way to define the test suite for a module: if you define a
  97. function called ``suite()`` in either ``models.py`` or ``tests.py``, the
  98. Django test runner will use that function to construct the test suite for that
  99. module. This follows the `suggested organization`_ for unit tests. See the
  100. Python documentation for more details on how to construct a complex test
  101. suite.
  102. For more details about :mod:`unittest`, see the Python documentation.
  103. .. _suggested organization: http://docs.python.org/library/unittest.html#organizing-tests
  104. Writing doctests
  105. ----------------
  106. Doctests use Python's standard :mod:`doctest` module, which searches your
  107. docstrings for statements that resemble a session of the Python interactive
  108. interpreter. A full explanation of how :mod:`doctest` works is out of the scope
  109. of this document; read Python's official documentation for the details.
  110. .. admonition:: What's a **docstring**?
  111. A good explanation of docstrings (and some guidelines for using them
  112. effectively) can be found in :pep:`257`:
  113. A docstring is a string literal that occurs as the first statement in
  114. a module, function, class, or method definition. Such a docstring
  115. becomes the ``__doc__`` special attribute of that object.
  116. For example, this function has a docstring that describes what it does::
  117. def add_two(num):
  118. "Return the result of adding two to the provided number."
  119. return num + 2
  120. Because tests often make great documentation, putting tests directly in
  121. your docstrings is an effective way to document *and* test your code.
  122. As with unit tests, for a given Django application, the test runner looks for
  123. doctests in two places:
  124. * The ``models.py`` file. You can define module-level doctests and/or a
  125. doctest for individual models. It's common practice to put
  126. application-level doctests in the module docstring and model-level
  127. doctests in the model docstrings.
  128. * A file called ``tests.py`` in the application directory -- i.e., the
  129. directory that holds ``models.py``. This file is a hook for any and all
  130. doctests you want to write that aren't necessarily related to models.
  131. This example doctest is equivalent to the example given in the unittest section
  132. above::
  133. # models.py
  134. from django.db import models
  135. class Animal(models.Model):
  136. """
  137. An animal that knows how to make noise
  138. # Create some animals
  139. >>> lion = Animal.objects.create(name="lion", sound="roar")
  140. >>> cat = Animal.objects.create(name="cat", sound="meow")
  141. # Make 'em speak
  142. >>> lion.speak()
  143. 'The lion says "roar"'
  144. >>> cat.speak()
  145. 'The cat says "meow"'
  146. """
  147. name = models.CharField(max_length=20)
  148. sound = models.CharField(max_length=20)
  149. def speak(self):
  150. return 'The %s says "%s"' % (self.name, self.sound)
  151. When you :ref:`run your tests <running-tests>`, the test runner will find this
  152. docstring, notice that portions of it look like an interactive Python session,
  153. and execute those lines while checking that the results match.
  154. In the case of model tests, note that the test runner takes care of creating
  155. its own test database. That is, any test that accesses a database -- by
  156. creating and saving model instances, for example -- will not affect your
  157. production database. However, the database is not refreshed between doctests,
  158. so if your doctest requires a certain state you should consider flushing the
  159. database or loading a fixture. (See the section on fixtures, below, for more
  160. on this.) Note that to use this feature, the database user Django is connecting
  161. as must have ``CREATE DATABASE`` rights.
  162. For more details about :mod:`doctest`, see the Python documentation.
  163. Which should I use?
  164. -------------------
  165. Because Django supports both of the standard Python test frameworks, it's up to
  166. you and your tastes to decide which one to use. You can even decide to use
  167. *both*.
  168. For developers new to testing, however, this choice can seem confusing. Here,
  169. then, are a few key differences to help you decide which approach is right for
  170. you:
  171. * If you've been using Python for a while, :mod:`doctest` will probably feel
  172. more "pythonic". It's designed to make writing tests as easy as possible,
  173. so it requires no overhead of writing classes or methods. You simply put
  174. tests in docstrings. This has the added advantage of serving as
  175. documentation (and correct documentation, at that!). However, while
  176. doctests are good for some simple example code, they are not very good if
  177. you want to produce either high quality, comprehensive tests or high
  178. quality documentation. Test failures are often difficult to debug
  179. as it can be unclear exactly why the test failed. Thus, doctests should
  180. generally be avoided and used primarily for documentation examples only.
  181. * The :mod:`unittest` framework will probably feel very familiar to
  182. developers coming from Java. :mod:`unittest` is inspired by Java's JUnit,
  183. so you'll feel at home with this method if you've used JUnit or any test
  184. framework inspired by JUnit.
  185. * If you need to write a bunch of tests that share similar code, then
  186. you'll appreciate the :mod:`unittest` framework's organization around
  187. classes and methods. This makes it easy to abstract common tasks into
  188. common methods. The framework also supports explicit setup and/or cleanup
  189. routines, which give you a high level of control over the environment
  190. in which your test cases are run.
  191. * If you're writing tests for Django itself, you should use :mod:`unittest`.
  192. .. _running-tests:
  193. Running tests
  194. =============
  195. Once you've written tests, run them using the :djadmin:`test` command of
  196. your project's ``manage.py`` utility::
  197. $ ./manage.py test
  198. By default, this will run every test in every application in
  199. :setting:`INSTALLED_APPS`. If you only want to run tests for a particular
  200. application, add the application name to the command line. For example, if your
  201. :setting:`INSTALLED_APPS` contains ``'myproject.polls'`` and
  202. ``'myproject.animals'``, you can run the ``myproject.animals`` unit tests alone
  203. with this command::
  204. $ ./manage.py test animals
  205. Note that we used ``animals``, not ``myproject.animals``.
  206. You can be even *more* specific by naming an individual test case. To
  207. run a single test case in an application (for example, the
  208. ``AnimalTestCase`` described in the "Writing unit tests" section), add
  209. the name of the test case to the label on the command line::
  210. $ ./manage.py test animals.AnimalTestCase
  211. And it gets even more granular than that! To run a *single* test
  212. method inside a test case, add the name of the test method to the
  213. label::
  214. $ ./manage.py test animals.AnimalTestCase.test_animals_can_speak
  215. You can use the same rules if you're using doctests. Django will use the
  216. test label as a path to the test method or class that you want to run.
  217. If your ``models.py`` or ``tests.py`` has a function with a doctest, or
  218. class with a class-level doctest, you can invoke that test by appending the
  219. name of the test method or class to the label::
  220. $ ./manage.py test animals.classify
  221. If you want to run the doctest for a specific method in a class, add the
  222. name of the method to the label::
  223. $ ./manage.py test animals.Classifier.run
  224. If you're using a ``__test__`` dictionary to specify doctests for a
  225. module, Django will use the label as a key in the ``__test__`` dictionary
  226. for defined in ``models.py`` and ``tests.py``.
  227. If you press ``Ctrl-C`` while the tests are running, the test runner will
  228. wait for the currently running test to complete and then exit gracefully.
  229. During a graceful exit the test runner will output details of any test
  230. failures, report on how many tests were run and how many errors and failures
  231. were encountered, and destroy any test databases as usual. Thus pressing
  232. ``Ctrl-C`` can be very useful if you forget to pass the :djadminopt:`--failfast`
  233. option, notice that some tests are unexpectedly failing, and want to get details
  234. on the failures without waiting for the full test run to complete.
  235. If you do not want to wait for the currently running test to finish, you
  236. can press ``Ctrl-C`` a second time and the test run will halt immediately,
  237. but not gracefully. No details of the tests run before the interruption will
  238. be reported, and any test databases created by the run will not be destroyed.
  239. .. admonition:: Test with warnings enabled
  240. It's a good idea to run your tests with Python warnings enabled:
  241. ``python -Wall manage.py test``. The ``-Wall`` flag tells Python to
  242. display deprecation warnings. Django, like many other Python libraries,
  243. uses these warnings to flag when features are going away. It also might
  244. flag areas in your code that aren't strictly wrong but could benefit
  245. from a better implementation.
  246. Running tests outside the test runner
  247. -------------------------------------
  248. If you want to run tests outside of ``./manage.py test`` -- for example,
  249. from a shell prompt -- you will need to set up the test
  250. environment first. Django provides a convenience method to do this::
  251. >>> from django.test.utils import setup_test_environment
  252. >>> setup_test_environment()
  253. This convenience method sets up the test database, and puts other
  254. Django features into modes that allow for repeatable testing.
  255. The call to :meth:`~django.test.utils.setup_test_environment` is made
  256. automatically as part of the setup of `./manage.py test`. You only
  257. need to manually invoke this method if you're not using running your
  258. tests via Django's test runner.
  259. The test database
  260. -----------------
  261. Tests that require a database (namely, model tests) will not use your "real"
  262. (production) database. Separate, blank databases are created for the tests.
  263. Regardless of whether the tests pass or fail, the test databases are destroyed
  264. when all the tests have been executed.
  265. By default the test databases get their names by prepending ``test_``
  266. to the value of the :setting:`NAME` settings for the databases
  267. defined in :setting:`DATABASES`. When using the SQLite database engine
  268. the tests will by default use an in-memory database (i.e., the
  269. database will be created in memory, bypassing the filesystem
  270. entirely!). If you want to use a different database name, specify
  271. :setting:`TEST_NAME` in the dictionary for any given database in
  272. :setting:`DATABASES`.
  273. Aside from using a separate database, the test runner will otherwise
  274. use all of the same database settings you have in your settings file:
  275. :setting:`ENGINE`, :setting:`USER`, :setting:`HOST`, etc. The test
  276. database is created by the user specified by :setting:`USER`, so you'll need
  277. to make sure that the given user account has sufficient privileges to
  278. create a new database on the system.
  279. For fine-grained control over the character encoding of your test
  280. database, use the :setting:`TEST_CHARSET` option. If you're using
  281. MySQL, you can also use the :setting:`TEST_COLLATION` option to
  282. control the particular collation used by the test database. See the
  283. :doc:`settings documentation </ref/settings>` for details of these
  284. advanced settings.
  285. .. admonition:: Finding data from your production database when running tests?
  286. If your code attempts to access the database when its modules are compiled,
  287. this will occur *before* the test database is set up, with potentially
  288. unexpected results. For example, if you have a database query in
  289. module-level code and a real database exists, production data could pollute
  290. your tests. *It is a bad idea to have such import-time database queries in
  291. your code* anyway - rewrite your code so that it doesn't do this.
  292. .. _topics-testing-masterslave:
  293. Testing master/slave configurations
  294. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  295. If you're testing a multiple database configuration with master/slave
  296. replication, this strategy of creating test databases poses a problem.
  297. When the test databases are created, there won't be any replication,
  298. and as a result, data created on the master won't be seen on the
  299. slave.
  300. To compensate for this, Django allows you to define that a database is
  301. a *test mirror*. Consider the following (simplified) example database
  302. configuration::
  303. DATABASES = {
  304. 'default': {
  305. 'ENGINE': 'django.db.backends.mysql',
  306. 'NAME': 'myproject',
  307. 'HOST': 'dbmaster',
  308. # ... plus some other settings
  309. },
  310. 'slave': {
  311. 'ENGINE': 'django.db.backends.mysql',
  312. 'NAME': 'myproject',
  313. 'HOST': 'dbslave',
  314. 'TEST_MIRROR': 'default'
  315. # ... plus some other settings
  316. }
  317. }
  318. In this setup, we have two database servers: ``dbmaster``, described
  319. by the database alias ``default``, and ``dbslave`` described by the
  320. alias ``slave``. As you might expect, ``dbslave`` has been configured
  321. by the database administrator as a read slave of ``dbmaster``, so in
  322. normal activity, any write to ``default`` will appear on ``slave``.
  323. If Django created two independent test databases, this would break any
  324. tests that expected replication to occur. However, the ``slave``
  325. database has been configured as a test mirror (using the
  326. :setting:`TEST_MIRROR` setting), indicating that under testing,
  327. ``slave`` should be treated as a mirror of ``default``.
  328. When the test environment is configured, a test version of ``slave``
  329. will *not* be created. Instead the connection to ``slave``
  330. will be redirected to point at ``default``. As a result, writes to
  331. ``default`` will appear on ``slave`` -- but because they are actually
  332. the same database, not because there is data replication between the
  333. two databases.
  334. .. _topics-testing-creation-dependencies:
  335. Controlling creation order for test databases
  336. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  337. By default, Django will always create the ``default`` database first.
  338. However, no guarantees are made on the creation order of any other
  339. databases in your test setup.
  340. If your database configuration requires a specific creation order, you
  341. can specify the dependencies that exist using the
  342. :setting:`TEST_DEPENDENCIES` setting. Consider the following
  343. (simplified) example database configuration::
  344. DATABASES = {
  345. 'default': {
  346. # ... db settings
  347. 'TEST_DEPENDENCIES': ['diamonds']
  348. },
  349. 'diamonds': {
  350. # ... db settings
  351. },
  352. 'clubs': {
  353. # ... db settings
  354. 'TEST_DEPENDENCIES': ['diamonds']
  355. },
  356. 'spades': {
  357. # ... db settings
  358. 'TEST_DEPENDENCIES': ['diamonds','hearts']
  359. },
  360. 'hearts': {
  361. # ... db settings
  362. 'TEST_DEPENDENCIES': ['diamonds','clubs']
  363. }
  364. }
  365. Under this configuration, the ``diamonds`` database will be created first,
  366. as it is the only database alias without dependencies. The ``default`` and
  367. ``clubs`` alias will be created next (although the order of creation of this
  368. pair is not guaranteed); then ``hearts``; and finally ``spades``.
  369. If there are any circular dependencies in the
  370. :setting:`TEST_DEPENDENCIES` definition, an ``ImproperlyConfigured``
  371. exception will be raised.
  372. Order in which tests are executed
  373. ---------------------------------
  374. In order to guarantee that all ``TestCase`` code starts with a clean database,
  375. the Django test runner reorders tests in the following way:
  376. * First, all unittests (including :class:`unittest.TestCase`,
  377. :class:`~django.test.SimpleTestCase`, :class:`~django.test.TestCase` and
  378. :class:`~django.test.TransactionTestCase`) are run with no particular ordering
  379. guaranteed nor enforced among them.
  380. * Then any other tests (e.g. doctests) that may alter the database without
  381. restoring it to its original state are run.
  382. .. versionchanged:: 1.5
  383. Before Django 1.5, the only guarantee was that
  384. :class:`~django.test.TestCase` tests were always ran first, before any other
  385. tests.
  386. .. note::
  387. The new ordering of tests may reveal unexpected dependencies on test case
  388. ordering. This is the case with doctests that relied on state left in the
  389. database by a given :class:`~django.test.TransactionTestCase` test, they
  390. must be updated to be able to run independently.
  391. Other test conditions
  392. ---------------------
  393. Regardless of the value of the :setting:`DEBUG` setting in your configuration
  394. file, all Django tests run with :setting:`DEBUG`\=False. This is to ensure that
  395. the observed output of your code matches what will be seen in a production
  396. setting.
  397. Caches are not cleared after each test, and running "manage.py test fooapp" can
  398. insert data from the tests into the cache of a live system if you run your
  399. tests in production because, unlike databases, a separate "test cache" is not
  400. used. This behavior `may change`_ in the future.
  401. .. _may change: https://code.djangoproject.com/ticket/11505
  402. Understanding the test output
  403. -----------------------------
  404. When you run your tests, you'll see a number of messages as the test runner
  405. prepares itself. You can control the level of detail of these messages with the
  406. ``verbosity`` option on the command line::
  407. Creating test database...
  408. Creating table myapp_animal
  409. Creating table myapp_mineral
  410. Loading 'initial_data' fixtures...
  411. No fixtures found.
  412. This tells you that the test runner is creating a test database, as described
  413. in the previous section.
  414. Once the test database has been created, Django will run your tests.
  415. If everything goes well, you'll see something like this::
  416. ----------------------------------------------------------------------
  417. Ran 22 tests in 0.221s
  418. OK
  419. If there are test failures, however, you'll see full details about which tests
  420. failed::
  421. ======================================================================
  422. FAIL: Doctest: ellington.core.throttle.models
  423. ----------------------------------------------------------------------
  424. Traceback (most recent call last):
  425. File "/dev/django/test/doctest.py", line 2153, in runTest
  426. raise self.failureException(self.format_failure(new.getvalue()))
  427. AssertionError: Failed doctest test for myapp.models
  428. File "/dev/myapp/models.py", line 0, in models
  429. ----------------------------------------------------------------------
  430. File "/dev/myapp/models.py", line 14, in myapp.models
  431. Failed example:
  432. throttle.check("actor A", "action one", limit=2, hours=1)
  433. Expected:
  434. True
  435. Got:
  436. False
  437. ----------------------------------------------------------------------
  438. Ran 2 tests in 0.048s
  439. FAILED (failures=1)
  440. A full explanation of this error output is beyond the scope of this document,
  441. but it's pretty intuitive. You can consult the documentation of Python's
  442. :mod:`unittest` library for details.
  443. Note that the return code for the test-runner script is 1 for any number of
  444. failed and erroneous tests. If all the tests pass, the return code is 0. This
  445. feature is useful if you're using the test-runner script in a shell script and
  446. need to test for success or failure at that level.
  447. Speeding up the tests
  448. ---------------------
  449. In recent versions of Django, the default password hasher is rather slow by
  450. design. If during your tests you are authenticating many users, you may want
  451. to use a custom settings file and set the :setting:`PASSWORD_HASHERS` setting
  452. to a faster hashing algorithm::
  453. PASSWORD_HASHERS = (
  454. 'django.contrib.auth.hashers.MD5PasswordHasher',
  455. )
  456. Don't forget to also include in :setting:`PASSWORD_HASHERS` any hashing
  457. algorithm used in fixtures, if any.
  458. .. _topics-testing-code-coverage:
  459. Integration with coverage.py
  460. ----------------------------
  461. Code coverage describes how much source code has been tested. It shows which
  462. parts of your code are being exercised by tests and which are not. It's an
  463. important part of testing applications, so it's strongly recommended to check
  464. the coverage of your tests.
  465. Django can be easily integrated with `coverage.py`_, a tool for measuring code
  466. coverage of Python programs. First, `install coverage.py`_. Next, run the
  467. following from your project folder containing ``manage.py``::
  468. coverage run --source='.' manage.py test myapp
  469. This runs your tests and collects coverage data of the executed files in your
  470. project. You can see a report of this data by typing following command::
  471. coverage report
  472. Note that some Django code was executed while running tests, but it is not
  473. listed here because of the ``source`` flag passed to the previous command.
  474. For more options like annotated HTML listings detailing missed lines, see the
  475. `coverage.py`_ docs.
  476. .. _coverage.py: http://nedbatchelder.com/code/coverage/
  477. .. _install coverage.py: http://pypi.python.org/pypi/coverage
  478. Testing tools
  479. =============
  480. Django provides a small set of tools that come in handy when writing tests.
  481. .. _test-client:
  482. The test client
  483. ---------------
  484. .. module:: django.test.client
  485. :synopsis: Django's test client.
  486. The test client is a Python class that acts as a dummy Web browser, allowing
  487. you to test your views and interact with your Django-powered application
  488. programmatically.
  489. Some of the things you can do with the test client are:
  490. * Simulate GET and POST requests on a URL and observe the response --
  491. everything from low-level HTTP (result headers and status codes) to
  492. page content.
  493. * Test that the correct view is executed for a given URL.
  494. * Test that a given request is rendered by a given Django template, with
  495. a template context that contains certain values.
  496. Note that the test client is not intended to be a replacement for Selenium_ or
  497. other "in-browser" frameworks. Django's test client has a different focus. In
  498. short:
  499. * Use Django's test client to establish that the correct view is being
  500. called and that the view is collecting the correct context data.
  501. * Use in-browser frameworks like Selenium_ to test *rendered* HTML and the
  502. *behavior* of Web pages, namely JavaScript functionality. Django also
  503. provides special support for those frameworks; see the section on
  504. :class:`~django.test.LiveServerTestCase` for more details.
  505. A comprehensive test suite should use a combination of both test types.
  506. Overview and a quick example
  507. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  508. To use the test client, instantiate ``django.test.client.Client`` and retrieve
  509. Web pages::
  510. >>> from django.test.client import Client
  511. >>> c = Client()
  512. >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
  513. >>> response.status_code
  514. 200
  515. >>> response = c.get('/customer/details/')
  516. >>> response.content
  517. '<!DOCTYPE html...'
  518. As this example suggests, you can instantiate ``Client`` from within a session
  519. of the Python interactive interpreter.
  520. Note a few important things about how the test client works:
  521. * The test client does *not* require the Web server to be running. In fact,
  522. it will run just fine with no Web server running at all! That's because
  523. it avoids the overhead of HTTP and deals directly with the Django
  524. framework. This helps make the unit tests run quickly.
  525. * When retrieving pages, remember to specify the *path* of the URL, not the
  526. whole domain. For example, this is correct::
  527. >>> c.get('/login/')
  528. This is incorrect::
  529. >>> c.get('http://www.example.com/login/')
  530. The test client is not capable of retrieving Web pages that are not
  531. powered by your Django project. If you need to retrieve other Web pages,
  532. use a Python standard library module such as :mod:`urllib` or
  533. :mod:`urllib2`.
  534. * To resolve URLs, the test client uses whatever URLconf is pointed-to by
  535. your :setting:`ROOT_URLCONF` setting.
  536. * Although the above example would work in the Python interactive
  537. interpreter, some of the test client's functionality, notably the
  538. template-related functionality, is only available *while tests are
  539. running*.
  540. The reason for this is that Django's test runner performs a bit of black
  541. magic in order to determine which template was loaded by a given view.
  542. This black magic (essentially a patching of Django's template system in
  543. memory) only happens during test running.
  544. * By default, the test client will disable any CSRF checks
  545. performed by your site.
  546. If, for some reason, you *want* the test client to perform CSRF
  547. checks, you can create an instance of the test client that
  548. enforces CSRF checks. To do this, pass in the
  549. ``enforce_csrf_checks`` argument when you construct your
  550. client::
  551. >>> from django.test import Client
  552. >>> csrf_client = Client(enforce_csrf_checks=True)
  553. Making requests
  554. ~~~~~~~~~~~~~~~
  555. Use the ``django.test.client.Client`` class to make requests.
  556. .. class:: Client(enforce_csrf_checks=False, **defaults)
  557. It requires no arguments at time of construction. However, you can use
  558. keywords arguments to specify some default headers. For example, this will
  559. send a ``User-Agent`` HTTP header in each request::
  560. >>> c = Client(HTTP_USER_AGENT='Mozilla/5.0')
  561. The values from the ``extra`` keywords arguments passed to
  562. :meth:`~django.test.client.Client.get()`,
  563. :meth:`~django.test.client.Client.post()`, etc. have precedence over
  564. the defaults passed to the class constructor.
  565. The ``enforce_csrf_checks`` argument can be used to test CSRF
  566. protection (see above).
  567. Once you have a ``Client`` instance, you can call any of the following
  568. methods:
  569. .. method:: Client.get(path, data={}, follow=False, **extra)
  570. Makes a GET request on the provided ``path`` and returns a ``Response``
  571. object, which is documented below.
  572. The key-value pairs in the ``data`` dictionary are used to create a GET
  573. data payload. For example::
  574. >>> c = Client()
  575. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
  576. ...will result in the evaluation of a GET request equivalent to::
  577. /customers/details/?name=fred&age=7
  578. The ``extra`` keyword arguments parameter can be used to specify
  579. headers to be sent in the request. For example::
  580. >>> c = Client()
  581. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
  582. ... HTTP_X_REQUESTED_WITH='XMLHttpRequest')
  583. ...will send the HTTP header ``HTTP_X_REQUESTED_WITH`` to the
  584. details view, which is a good way to test code paths that use the
  585. :meth:`django.http.HttpRequest.is_ajax()` method.
  586. .. admonition:: CGI specification
  587. The headers sent via ``**extra`` should follow CGI_ specification.
  588. For example, emulating a different "Host" header as sent in the
  589. HTTP request from the browser to the server should be passed
  590. as ``HTTP_HOST``.
  591. .. _CGI: http://www.w3.org/CGI/
  592. If you already have the GET arguments in URL-encoded form, you can
  593. use that encoding instead of using the data argument. For example,
  594. the previous GET request could also be posed as::
  595. >>> c = Client()
  596. >>> c.get('/customers/details/?name=fred&age=7')
  597. If you provide a URL with both an encoded GET data and a data argument,
  598. the data argument will take precedence.
  599. If you set ``follow`` to ``True`` the client will follow any redirects
  600. and a ``redirect_chain`` attribute will be set in the response object
  601. containing tuples of the intermediate urls and status codes.
  602. If you had a URL ``/redirect_me/`` that redirected to ``/next/``, that
  603. redirected to ``/final/``, this is what you'd see::
  604. >>> response = c.get('/redirect_me/', follow=True)
  605. >>> response.redirect_chain
  606. [(u'http://testserver/next/', 302), (u'http://testserver/final/', 302)]
  607. .. method:: Client.post(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
  608. Makes a POST request on the provided ``path`` and returns a
  609. ``Response`` object, which is documented below.
  610. The key-value pairs in the ``data`` dictionary are used to submit POST
  611. data. For example::
  612. >>> c = Client()
  613. >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
  614. ...will result in the evaluation of a POST request to this URL::
  615. /login/
  616. ...with this POST data::
  617. name=fred&passwd=secret
  618. If you provide ``content_type`` (e.g. :mimetype:`text/xml` for an XML
  619. payload), the contents of ``data`` will be sent as-is in the POST
  620. request, using ``content_type`` in the HTTP ``Content-Type`` header.
  621. If you don't provide a value for ``content_type``, the values in
  622. ``data`` will be transmitted with a content type of
  623. :mimetype:`multipart/form-data`. In this case, the key-value pairs in
  624. ``data`` will be encoded as a multipart message and used to create the
  625. POST data payload.
  626. To submit multiple values for a given key -- for example, to specify
  627. the selections for a ``<select multiple>`` -- provide the values as a
  628. list or tuple for the required key. For example, this value of ``data``
  629. would submit three selected values for the field named ``choices``::
  630. {'choices': ('a', 'b', 'd')}
  631. Submitting files is a special case. To POST a file, you need only
  632. provide the file field name as a key, and a file handle to the file you
  633. wish to upload as a value. For example::
  634. >>> c = Client()
  635. >>> with open('wishlist.doc') as fp:
  636. ... c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
  637. (The name ``attachment`` here is not relevant; use whatever name your
  638. file-processing code expects.)
  639. Note that if you wish to use the same file handle for multiple
  640. ``post()`` calls then you will need to manually reset the file
  641. pointer between posts. The easiest way to do this is to
  642. manually close the file after it has been provided to
  643. ``post()``, as demonstrated above.
  644. You should also ensure that the file is opened in a way that
  645. allows the data to be read. If your file contains binary data
  646. such as an image, this means you will need to open the file in
  647. ``rb`` (read binary) mode.
  648. The ``extra`` argument acts the same as for :meth:`Client.get`.
  649. If the URL you request with a POST contains encoded parameters, these
  650. parameters will be made available in the request.GET data. For example,
  651. if you were to make the request::
  652. >>> c.post('/login/?visitor=true', {'name': 'fred', 'passwd': 'secret'})
  653. ... the view handling this request could interrogate request.POST
  654. to retrieve the username and password, and could interrogate request.GET
  655. to determine if the user was a visitor.
  656. If you set ``follow`` to ``True`` the client will follow any redirects
  657. and a ``redirect_chain`` attribute will be set in the response object
  658. containing tuples of the intermediate urls and status codes.
  659. .. method:: Client.head(path, data={}, follow=False, **extra)
  660. Makes a HEAD request on the provided ``path`` and returns a
  661. ``Response`` object. This method works just like :meth:`Client.get`,
  662. including the ``follow`` and ``extra`` arguments, except it does not
  663. return a message body.
  664. .. method:: Client.options(path, data='', content_type='application/octet-stream', follow=False, **extra)
  665. Makes an OPTIONS request on the provided ``path`` and returns a
  666. ``Response`` object. Useful for testing RESTful interfaces.
  667. When ``data`` is provided, it is used as the request body, and
  668. a ``Content-Type`` header is set to ``content_type``.
  669. .. versionchanged:: 1.5
  670. :meth:`Client.options` used to process ``data`` like
  671. :meth:`Client.get`.
  672. The ``follow`` and ``extra`` arguments act the same as for
  673. :meth:`Client.get`.
  674. .. method:: Client.put(path, data='', content_type='application/octet-stream', follow=False, **extra)
  675. Makes a PUT request on the provided ``path`` and returns a
  676. ``Response`` object. Useful for testing RESTful interfaces.
  677. When ``data`` is provided, it is used as the request body, and
  678. a ``Content-Type`` header is set to ``content_type``.
  679. .. versionchanged:: 1.5
  680. :meth:`Client.put` used to process ``data`` like
  681. :meth:`Client.post`.
  682. The ``follow`` and ``extra`` arguments act the same as for
  683. :meth:`Client.get`.
  684. .. method:: Client.delete(path, data='', content_type='application/octet-stream', follow=False, **extra)
  685. Makes an DELETE request on the provided ``path`` and returns a
  686. ``Response`` object. Useful for testing RESTful interfaces.
  687. When ``data`` is provided, it is used as the request body, and
  688. a ``Content-Type`` header is set to ``content_type``.
  689. .. versionchanged:: 1.5
  690. :meth:`Client.delete` used to process ``data`` like
  691. :meth:`Client.get`.
  692. The ``follow`` and ``extra`` arguments act the same as for
  693. :meth:`Client.get`.
  694. .. method:: Client.login(**credentials)
  695. If your site uses Django's :doc:`authentication system</topics/auth>`
  696. and you deal with logging in users, you can use the test client's
  697. ``login()`` method to simulate the effect of a user logging into the
  698. site.
  699. After you call this method, the test client will have all the cookies
  700. and session data required to pass any login-based tests that may form
  701. part of a view.
  702. The format of the ``credentials`` argument depends on which
  703. :ref:`authentication backend <authentication-backends>` you're using
  704. (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
  705. setting). If you're using the standard authentication backend provided
  706. by Django (``ModelBackend``), ``credentials`` should be the user's
  707. username and password, provided as keyword arguments::
  708. >>> c = Client()
  709. >>> c.login(username='fred', password='secret')
  710. # Now you can access a view that's only available to logged-in users.
  711. If you're using a different authentication backend, this method may
  712. require different credentials. It requires whichever credentials are
  713. required by your backend's ``authenticate()`` method.
  714. ``login()`` returns ``True`` if it the credentials were accepted and
  715. login was successful.
  716. Finally, you'll need to remember to create user accounts before you can
  717. use this method. As we explained above, the test runner is executed
  718. using a test database, which contains no users by default. As a result,
  719. user accounts that are valid on your production site will not work
  720. under test conditions. You'll need to create users as part of the test
  721. suite -- either manually (using the Django model API) or with a test
  722. fixture. Remember that if you want your test user to have a password,
  723. you can't set the user's password by setting the password attribute
  724. directly -- you must use the
  725. :meth:`~django.contrib.auth.models.User.set_password()` function to
  726. store a correctly hashed password. Alternatively, you can use the
  727. :meth:`~django.contrib.auth.models.UserManager.create_user` helper
  728. method to create a new user with a correctly hashed password.
  729. .. method:: Client.logout()
  730. If your site uses Django's :doc:`authentication system</topics/auth>`,
  731. the ``logout()`` method can be used to simulate the effect of a user
  732. logging out of your site.
  733. After you call this method, the test client will have all the cookies
  734. and session data cleared to defaults. Subsequent requests will appear
  735. to come from an AnonymousUser.
  736. Testing responses
  737. ~~~~~~~~~~~~~~~~~
  738. The ``get()`` and ``post()`` methods both return a ``Response`` object. This
  739. ``Response`` object is *not* the same as the ``HttpResponse`` object returned
  740. Django views; the test response object has some additional data useful for
  741. test code to verify.
  742. Specifically, a ``Response`` object has the following attributes:
  743. .. class:: Response()
  744. .. attribute:: client
  745. The test client that was used to make the request that resulted in the
  746. response.
  747. .. attribute:: content
  748. The body of the response, as a string. This is the final page content as
  749. rendered by the view, or any error message.
  750. .. attribute:: context
  751. The template ``Context`` instance that was used to render the template that
  752. produced the response content.
  753. If the rendered page used multiple templates, then ``context`` will be a
  754. list of ``Context`` objects, in the order in which they were rendered.
  755. Regardless of the number of templates used during rendering, you can
  756. retrieve context values using the ``[]`` operator. For example, the
  757. context variable ``name`` could be retrieved using::
  758. >>> response = client.get('/foo/')
  759. >>> response.context['name']
  760. 'Arthur'
  761. .. attribute:: request
  762. The request data that stimulated the response.
  763. .. attribute:: status_code
  764. The HTTP status of the response, as an integer. See
  765. :rfc:`2616#section-10` for a full list of HTTP status codes.
  766. .. attribute:: templates
  767. A list of ``Template`` instances used to render the final content, in
  768. the order they were rendered. For each template in the list, use
  769. ``template.name`` to get the template's file name, if the template was
  770. loaded from a file. (The name is a string such as
  771. ``'admin/index.html'``.)
  772. You can also use dictionary syntax on the response object to query the value
  773. of any settings in the HTTP headers. For example, you could determine the
  774. content type of a response using ``response['Content-Type']``.
  775. Exceptions
  776. ~~~~~~~~~~
  777. If you point the test client at a view that raises an exception, that exception
  778. will be visible in the test case. You can then use a standard ``try ... except``
  779. block or :meth:`~unittest.TestCase.assertRaises` to test for exceptions.
  780. The only exceptions that are not visible to the test client are ``Http404``,
  781. ``PermissionDenied`` and ``SystemExit``. Django catches these exceptions
  782. internally and converts them into the appropriate HTTP response codes. In these
  783. cases, you can check ``response.status_code`` in your test.
  784. Persistent state
  785. ~~~~~~~~~~~~~~~~
  786. The test client is stateful. If a response returns a cookie, then that cookie
  787. will be stored in the test client and sent with all subsequent ``get()`` and
  788. ``post()`` requests.
  789. Expiration policies for these cookies are not followed. If you want a cookie
  790. to expire, either delete it manually or create a new ``Client`` instance (which
  791. will effectively delete all cookies).
  792. A test client has two attributes that store persistent state information. You
  793. can access these properties as part of a test condition.
  794. .. attribute:: Client.cookies
  795. A Python :class:`~Cookie.SimpleCookie` object, containing the current values
  796. of all the client cookies. See the documentation of the :mod:`Cookie` module
  797. for more.
  798. .. attribute:: Client.session
  799. A dictionary-like object containing session information. See the
  800. :doc:`session documentation</topics/http/sessions>` for full details.
  801. To modify the session and then save it, it must be stored in a variable
  802. first (because a new ``SessionStore`` is created every time this property
  803. is accessed)::
  804. def test_something(self):
  805. session = self.client.session
  806. session['somekey'] = 'test'
  807. session.save()
  808. Example
  809. ~~~~~~~
  810. The following is a simple unit test using the test client::
  811. from django.utils import unittest
  812. from django.test.client import Client
  813. class SimpleTest(unittest.TestCase):
  814. def setUp(self):
  815. # Every test needs a client.
  816. self.client = Client()
  817. def test_details(self):
  818. # Issue a GET request.
  819. response = self.client.get('/customer/details/')
  820. # Check that the response is 200 OK.
  821. self.assertEqual(response.status_code, 200)
  822. # Check that the rendered context contains 5 customers.
  823. self.assertEqual(len(response.context['customers']), 5)
  824. The request factory
  825. -------------------
  826. .. class:: RequestFactory
  827. The :class:`~django.test.client.RequestFactory` shares the same API as
  828. the test client. However, instead of behaving like a browser, the
  829. RequestFactory provides a way to generate a request instance that can
  830. be used as the first argument to any view. This means you can test a
  831. view function the same way as you would test any other function -- as
  832. a black box, with exactly known inputs, testing for specific outputs.
  833. The API for the :class:`~django.test.client.RequestFactory` is a slightly
  834. restricted subset of the test client API:
  835. * It only has access to the HTTP methods :meth:`~Client.get()`,
  836. :meth:`~Client.post()`, :meth:`~Client.put()`,
  837. :meth:`~Client.delete()`, :meth:`~Client.head()` and
  838. :meth:`~Client.options()`.
  839. * These methods accept all the same arguments *except* for
  840. ``follows``. Since this is just a factory for producing
  841. requests, it's up to you to handle the response.
  842. * It does not support middleware. Session and authentication
  843. attributes must be supplied by the test itself if required
  844. for the view to function properly.
  845. Example
  846. ~~~~~~~
  847. The following is a simple unit test using the request factory::
  848. from django.utils import unittest
  849. from django.test.client import RequestFactory
  850. class SimpleTest(unittest.TestCase):
  851. def setUp(self):
  852. # Every test needs access to the request factory.
  853. self.factory = RequestFactory()
  854. def test_details(self):
  855. # Create an instance of a GET request.
  856. request = self.factory.get('/customer/details')
  857. # Test my_view() as if it were deployed at /customer/details
  858. response = my_view(request)
  859. self.assertEqual(response.status_code, 200)
  860. Test cases
  861. ----------
  862. Provided test case classes
  863. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  864. .. currentmodule:: django.test
  865. Normal Python unit test classes extend a base class of
  866. :class:`unittest.TestCase`. Django provides a few extensions of this base class:
  867. .. _testcase_hierarchy_diagram:
  868. .. figure:: _images/django_unittest_classes_hierarchy.*
  869. :alt: Hierarchy of Django unit testing classes (TestCase subclasses)
  870. :width: 508
  871. :height: 391
  872. Regardless of the version of Python you're using, if you've installed
  873. :mod:`unittest2`, :mod:`django.utils.unittest` will point to that library.
  874. TestCase
  875. ^^^^^^^^
  876. .. class:: TestCase()
  877. This class provides some additional capabilities that can be useful for testing
  878. Web sites.
  879. Converting a normal :class:`unittest.TestCase` to a Django :class:`TestCase` is
  880. easy: Just change the base class of your test from `'unittest.TestCase'` to
  881. `'django.test.TestCase'`. All of the standard Python unit test functionality
  882. will continue to be available, but it will be augmented with some useful
  883. additions, including:
  884. * Automatic loading of fixtures.
  885. * Wraps each test in a transaction.
  886. * Creates a TestClient instance.
  887. * Django-specific assertions for testing for things like redirection and form
  888. errors.
  889. .. versionchanged:: 1.5
  890. The order in which tests are run has changed. See `Order in which tests are
  891. executed`_.
  892. ``TestCase`` inherits from :class:`~django.test.TransactionTestCase`.
  893. TransactionTestCase
  894. ^^^^^^^^^^^^^^^^^^^
  895. .. class:: TransactionTestCase()
  896. Django ``TestCase`` classes make use of database transaction facilities, if
  897. available, to speed up the process of resetting the database to a known state
  898. at the beginning of each test. A consequence of this, however, is that the
  899. effects of transaction commit and rollback cannot be tested by a Django
  900. ``TestCase`` class. If your test requires testing of such transactional
  901. behavior, you should use a Django ``TransactionTestCase``.
  902. ``TransactionTestCase`` and ``TestCase`` are identical except for the manner
  903. in which the database is reset to a known state and the ability for test code
  904. to test the effects of commit and rollback:
  905. * A ``TransactionTestCase`` resets the database after the test runs by
  906. truncating all tables. A ``TransactionTestCase`` may call commit and rollback
  907. and observe the effects of these calls on the database.
  908. * A ``TestCase``, on the other hand, does not truncate tables after a test.
  909. Instead, it encloses the test code in a database transaction that is rolled
  910. back at the end of the test. It also prevents the code under test from
  911. issuing any commit or rollback operations on the database, to ensure that the
  912. rollback at the end of the test restores the database to its initial state.
  913. When running on a database that does not support rollback (e.g. MySQL with the
  914. MyISAM storage engine), ``TestCase`` falls back to initializing the database
  915. by truncating tables and reloading initial data.
  916. .. note::
  917. .. versionchanged:: 1.5
  918. Prior to 1.5, ``TransactionTestCase`` flushed the database tables *before*
  919. each test. In Django 1.5, this is instead done *after* the test has been run.
  920. When the flush took place before the test, it was guaranteed that primary
  921. key values started at one in :class:`~django.test.TransactionTestCase`
  922. tests.
  923. Tests should not depend on this behaviour, but for legacy tests that do, the
  924. :attr:`~TransactionTestCase.reset_sequences` attribute can be used until
  925. the test has been properly updated.
  926. .. versionchanged:: 1.5
  927. The order in which tests are run has changed. See `Order in which tests are
  928. executed`_.
  929. ``TransactionTestCase`` inherits from :class:`~django.test.SimpleTestCase`.
  930. .. attribute:: TransactionTestCase.reset_sequences
  931. .. versionadded:: 1.5
  932. Setting ``reset_sequences = True`` on a ``TransactionTestCase`` will make
  933. sure sequences are always reset before the test run::
  934. class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase):
  935. reset_sequences = True
  936. def test_animal_pk(self):
  937. lion = Animal.objects.create(name="lion", sound="roar")
  938. # lion.pk is guaranteed to always be 1
  939. self.assertEqual(lion.pk, 1)
  940. Unless you are explicitly testing primary keys sequence numbers, it is
  941. recommended that you do not hard code primary key values in tests.
  942. Using ``reset_sequences = True`` will slow down the test, since the primary
  943. key reset is an relatively expensive database operation.
  944. SimpleTestCase
  945. ^^^^^^^^^^^^^^
  946. .. class:: SimpleTestCase()
  947. .. versionadded:: 1.4
  948. A very thin subclass of :class:`unittest.TestCase`, it extends it with some
  949. basic functionality like:
  950. * Saving and restoring the Python warning machinery state.
  951. * Checking that a callable :meth:`raises a certain exception <SimpleTestCase.assertRaisesMessage>`.
  952. * :meth:`Testing form field rendering <SimpleTestCase.assertFieldOutput>`.
  953. * Testing server :ref:`HTML responses for the presence/lack of a given fragment <assertions>`.
  954. * The ability to run tests with :ref:`modified settings <overriding-settings>`
  955. If you need any of the other more complex and heavyweight Django-specific
  956. features like:
  957. * Using the :attr:`~TestCase.client` :class:`~django.test.client.Client`.
  958. * Testing or using the ORM.
  959. * Database :attr:`~TestCase.fixtures`.
  960. * Custom test-time :attr:`URL maps <TestCase.urls>`.
  961. * Test :ref:`skipping based on database backend features <skipping-tests>`.
  962. * The remaining specialized :ref:`assert* <assertions>` methods.
  963. then you should use :class:`~django.test.TransactionTestCase` or
  964. :class:`~django.test.TestCase` instead.
  965. ``SimpleTestCase`` inherits from :class:`django.utils.unittest.TestCase`.
  966. Default test client
  967. ~~~~~~~~~~~~~~~~~~~
  968. .. attribute:: TestCase.client
  969. Every test case in a ``django.test.TestCase`` instance has access to an
  970. instance of a Django test client. This client can be accessed as
  971. ``self.client``. This client is recreated for each test, so you don't have to
  972. worry about state (such as cookies) carrying over from one test to another.
  973. This means, instead of instantiating a ``Client`` in each test::
  974. from django.utils import unittest
  975. from django.test.client import Client
  976. class SimpleTest(unittest.TestCase):
  977. def test_details(self):
  978. client = Client()
  979. response = client.get('/customer/details/')
  980. self.assertEqual(response.status_code, 200)
  981. def test_index(self):
  982. client = Client()
  983. response = client.get('/customer/index/')
  984. self.assertEqual(response.status_code, 200)
  985. ...you can just refer to ``self.client``, like so::
  986. from django.test import TestCase
  987. class SimpleTest(TestCase):
  988. def test_details(self):
  989. response = self.client.get('/customer/details/')
  990. self.assertEqual(response.status_code, 200)
  991. def test_index(self):
  992. response = self.client.get('/customer/index/')
  993. self.assertEqual(response.status_code, 200)
  994. Customizing the test client
  995. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  996. .. attribute:: TestCase.client_class
  997. If you want to use a different ``Client`` class (for example, a subclass
  998. with customized behavior), use the :attr:`~TestCase.client_class` class
  999. attribute::
  1000. from django.test import TestCase
  1001. from django.test.client import Client
  1002. class MyTestClient(Client):
  1003. # Specialized methods for your environment...
  1004. class MyTest(TestCase):
  1005. client_class = MyTestClient
  1006. def test_my_stuff(self):
  1007. # Here self.client is an instance of MyTestClient...
  1008. .. _topics-testing-fixtures:
  1009. Fixture loading
  1010. ~~~~~~~~~~~~~~~
  1011. .. attribute:: TestCase.fixtures
  1012. A test case for a database-backed Web site isn't much use if there isn't any
  1013. data in the database. To make it easy to put test data into the database,
  1014. Django's custom ``TestCase`` class provides a way of loading **fixtures**.
  1015. A fixture is a collection of data that Django knows how to import into a
  1016. database. For example, if your site has user accounts, you might set up a
  1017. fixture of fake user accounts in order to populate your database during tests.
  1018. The most straightforward way of creating a fixture is to use the
  1019. :djadmin:`manage.py dumpdata <dumpdata>` command. This assumes you
  1020. already have some data in your database. See the :djadmin:`dumpdata
  1021. documentation<dumpdata>` for more details.
  1022. .. note::
  1023. If you've ever run :djadmin:`manage.py syncdb<syncdb>`, you've
  1024. already used a fixture without even knowing it! When you call
  1025. :djadmin:`syncdb` in the database for the first time, Django
  1026. installs a fixture called ``initial_data``. This gives you a way
  1027. of populating a new database with any initial data, such as a
  1028. default set of categories.
  1029. Fixtures with other names can always be installed manually using
  1030. the :djadmin:`manage.py loaddata<loaddata>` command.
  1031. .. admonition:: Initial SQL data and testing
  1032. Django provides a second way to insert initial data into models --
  1033. the :ref:`custom SQL hook <initial-sql>`. However, this technique
  1034. *cannot* be used to provide initial data for testing purposes.
  1035. Django's test framework flushes the contents of the test database
  1036. after each test; as a result, any data added using the custom SQL
  1037. hook will be lost.
  1038. Once you've created a fixture and placed it in a ``fixtures`` directory in one
  1039. of your :setting:`INSTALLED_APPS`, you can use it in your unit tests by
  1040. specifying a ``fixtures`` class attribute on your :class:`django.test.TestCase`
  1041. subclass::
  1042. from django.test import TestCase
  1043. from myapp.models import Animal
  1044. class AnimalTestCase(TestCase):
  1045. fixtures = ['mammals.json', 'birds']
  1046. def setUp(self):
  1047. # Test definitions as before.
  1048. call_setup_methods()
  1049. def testFluffyAnimals(self):
  1050. # A test that uses the fixtures.
  1051. call_some_test_code()
  1052. Here's specifically what will happen:
  1053. * At the start of each test case, before ``setUp()`` is run, Django will
  1054. flush the database, returning the database to the state it was in
  1055. directly after :djadmin:`syncdb` was called.
  1056. * Then, all the named fixtures are installed. In this example, Django will
  1057. install any JSON fixture named ``mammals``, followed by any fixture named
  1058. ``birds``. See the :djadmin:`loaddata` documentation for more
  1059. details on defining and installing fixtures.
  1060. This flush/load procedure is repeated for each test in the test case, so you
  1061. can be certain that the outcome of a test will not be affected by another test,
  1062. or by the order of test execution.
  1063. URLconf configuration
  1064. ~~~~~~~~~~~~~~~~~~~~~
  1065. .. attribute:: TestCase.urls
  1066. If your application provides views, you may want to include tests that use the
  1067. test client to exercise those views. However, an end user is free to deploy the
  1068. views in your application at any URL of their choosing. This means that your
  1069. tests can't rely upon the fact that your views will be available at a
  1070. particular URL.
  1071. In order to provide a reliable URL space for your test,
  1072. ``django.test.TestCase`` provides the ability to customize the URLconf
  1073. configuration for the duration of the execution of a test suite. If your
  1074. ``TestCase`` instance defines an ``urls`` attribute, the ``TestCase`` will use
  1075. the value of that attribute as the :setting:`ROOT_URLCONF` for the duration
  1076. of that test.
  1077. For example::
  1078. from django.test import TestCase
  1079. class TestMyViews(TestCase):
  1080. urls = 'myapp.test_urls'
  1081. def testIndexPageView(self):
  1082. # Here you'd test your view using ``Client``.
  1083. call_some_test_code()
  1084. This test case will use the contents of ``myapp.test_urls`` as the
  1085. URLconf for the duration of the test case.
  1086. .. _emptying-test-outbox:
  1087. Multi-database support
  1088. ~~~~~~~~~~~~~~~~~~~~~~
  1089. .. attribute:: TestCase.multi_db
  1090. Django sets up a test database corresponding to every database that is
  1091. defined in the :setting:`DATABASES` definition in your settings
  1092. file. However, a big part of the time taken to run a Django TestCase
  1093. is consumed by the call to ``flush`` that ensures that you have a
  1094. clean database at the start of each test run. If you have multiple
  1095. databases, multiple flushes are required (one for each database),
  1096. which can be a time consuming activity -- especially if your tests
  1097. don't need to test multi-database activity.
  1098. As an optimization, Django only flushes the ``default`` database at
  1099. the start of each test run. If your setup contains multiple databases,
  1100. and you have a test that requires every database to be clean, you can
  1101. use the ``multi_db`` attribute on the test suite to request a full
  1102. flush.
  1103. For example::
  1104. class TestMyViews(TestCase):
  1105. multi_db = True
  1106. def testIndexPageView(self):
  1107. call_some_test_code()
  1108. This test case will flush *all* the test databases before running
  1109. ``testIndexPageView``.
  1110. .. _overriding-settings:
  1111. Overriding settings
  1112. ~~~~~~~~~~~~~~~~~~~
  1113. .. method:: TestCase.settings
  1114. .. versionadded:: 1.4
  1115. For testing purposes it's often useful to change a setting temporarily and
  1116. revert to the original value after running the testing code. For this use case
  1117. Django provides a standard Python context manager (see :pep:`343`)
  1118. :meth:`~django.test.TestCase.settings`, which can be used like this::
  1119. from django.test import TestCase
  1120. class LoginTestCase(TestCase):
  1121. def test_login(self):
  1122. # First check for the default behavior
  1123. response = self.client.get('/sekrit/')
  1124. self.assertRedirects(response, '/accounts/login/?next=/sekrit/')
  1125. # Then override the LOGIN_URL setting
  1126. with self.settings(LOGIN_URL='/other/login/'):
  1127. response = self.client.get('/sekrit/')
  1128. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  1129. This example will override the :setting:`LOGIN_URL` setting for the code
  1130. in the ``with`` block and reset its value to the previous state afterwards.
  1131. .. currentmodule:: django.test.utils
  1132. .. function:: override_settings
  1133. In case you want to override a setting for just one test method or even the
  1134. whole :class:`TestCase` class, Django provides the
  1135. :func:`~django.test.utils.override_settings` decorator (see :pep:`318`). It's
  1136. used like this::
  1137. from django.test import TestCase
  1138. from django.test.utils import override_settings
  1139. class LoginTestCase(TestCase):
  1140. @override_settings(LOGIN_URL='/other/login/')
  1141. def test_login(self):
  1142. response = self.client.get('/sekrit/')
  1143. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  1144. The decorator can also be applied to test case classes::
  1145. from django.test import TestCase
  1146. from django.test.utils import override_settings
  1147. @override_settings(LOGIN_URL='/other/login/')
  1148. class LoginTestCase(TestCase):
  1149. def test_login(self):
  1150. response = self.client.get('/sekrit/')
  1151. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  1152. .. note::
  1153. When given a class, the decorator modifies the class directly and
  1154. returns it; it doesn't create and return a modified copy of it. So if
  1155. you try to tweak the above example to assign the return value to a
  1156. different name than ``LoginTestCase``, you may be surprised to find that
  1157. the original ``LoginTestCase`` is still equally affected by the
  1158. decorator.
  1159. When overriding settings, make sure to handle the cases in which your app's
  1160. code uses a cache or similar feature that retains state even if the
  1161. setting is changed. Django provides the
  1162. :data:`django.test.signals.setting_changed` signal that lets you register
  1163. callbacks to clean up and otherwise reset state when settings are changed.
  1164. Django itself uses this signal to reset various data:
  1165. ================================ ========================
  1166. Overriden settings Data reset
  1167. ================================ ========================
  1168. USE_TZ, TIME_ZONE Databases timezone
  1169. TEMPLATE_CONTEXT_PROCESSORS Context processors cache
  1170. TEMPLATE_LOADERS Template loaders cache
  1171. SERIALIZATION_MODULES Serializers cache
  1172. LOCALE_PATHS, LANGUAGE_CODE Default translation and loaded translations
  1173. MEDIA_ROOT, DEFAULT_FILE_STORAGE Default file storage
  1174. ================================ ========================
  1175. Emptying the test outbox
  1176. ~~~~~~~~~~~~~~~~~~~~~~~~
  1177. If you use Django's custom ``TestCase`` class, the test runner will clear the
  1178. contents of the test email outbox at the start of each test case.
  1179. For more detail on email services during tests, see `Email services`_.
  1180. .. _assertions:
  1181. Assertions
  1182. ~~~~~~~~~~
  1183. .. currentmodule:: django.test
  1184. As Python's normal :class:`unittest.TestCase` class implements assertion methods
  1185. such as :meth:`~unittest.TestCase.assertTrue` and
  1186. :meth:`~unittest.TestCase.assertEqual`, Django's custom :class:`TestCase` class
  1187. provides a number of custom assertion methods that are useful for testing Web
  1188. applications:
  1189. The failure messages given by most of these assertion methods can be customized
  1190. with the ``msg_prefix`` argument. This string will be prefixed to any failure
  1191. message generated by the assertion. This allows you to provide additional
  1192. details that may help you to identify the location and cause of an failure in
  1193. your test suite.
  1194. .. method:: SimpleTestCase.assertRaisesMessage(expected_exception, expected_message, callable_obj=None, *args, **kwargs)
  1195. .. versionadded:: 1.4
  1196. Asserts that execution of callable ``callable_obj`` raised the
  1197. ``expected_exception`` exception and that such exception has an
  1198. ``expected_message`` representation. Any other outcome is reported as a
  1199. failure. Similar to unittest's :meth:`~unittest.TestCase.assertRaisesRegexp`
  1200. with the difference that ``expected_message`` isn't a regular expression.
  1201. .. method:: SimpleTestCase.assertFieldOutput(self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value=u'')
  1202. .. versionadded:: 1.4
  1203. Asserts that a form field behaves correctly with various inputs.
  1204. :param fieldclass: the class of the field to be tested.
  1205. :param valid: a dictionary mapping valid inputs to their expected cleaned
  1206. values.
  1207. :param invalid: a dictionary mapping invalid inputs to one or more raised
  1208. error messages.
  1209. :param field_args: the args passed to instantiate the field.
  1210. :param field_kwargs: the kwargs passed to instantiate the field.
  1211. :param empty_value: the expected clean output for inputs in ``EMPTY_VALUES``.
  1212. For example, the following code tests that an ``EmailField`` accepts
  1213. "a@a.com" as a valid email address, but rejects "aaa" with a reasonable
  1214. error message::
  1215. self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': [u'Enter a valid email address.']})
  1216. .. method:: TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False)
  1217. Asserts that a ``Response`` instance produced the given ``status_code`` and
  1218. that ``text`` appears in the content of the response. If ``count`` is
  1219. provided, ``text`` must occur exactly ``count`` times in the response.
  1220. .. versionadded:: 1.4
  1221. Set ``html`` to ``True`` to handle ``text`` as HTML. The comparison with
  1222. the response content will be based on HTML semantics instead of
  1223. character-by-character equality. Whitespace is ignored in most cases,
  1224. attribute ordering is not significant. See
  1225. :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
  1226. .. method:: TestCase.assertNotContains(response, text, status_code=200, msg_prefix='', html=False)
  1227. Asserts that a ``Response`` instance produced the given ``status_code`` and
  1228. that ``text`` does not appears in the content of the response.
  1229. .. versionadded:: 1.4
  1230. Set ``html`` to ``True`` to handle ``text`` as HTML. The comparison with
  1231. the response content will be based on HTML semantics instead of
  1232. character-by-character equality. Whitespace is ignored in most cases,
  1233. attribute ordering is not significant. See
  1234. :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
  1235. .. method:: TestCase.assertFormError(response, form, field, errors, msg_prefix='')
  1236. Asserts that a field on a form raises the provided list of errors when
  1237. rendered on the form.
  1238. ``form`` is the name the ``Form`` instance was given in the template
  1239. context.
  1240. ``field`` is the name of the field on the form to check. If ``field``
  1241. has a value of ``None``, non-field errors (errors you can access via
  1242. ``form.non_field_errors()``) will be checked.
  1243. ``errors`` is an error string, or a list of error strings, that are
  1244. expected as a result of form validation.
  1245. .. method:: TestCase.assertTemplateUsed(response, template_name, msg_prefix='')
  1246. Asserts that the template with the given name was used in rendering the
  1247. response.
  1248. The name is a string such as ``'admin/index.html'``.
  1249. .. versionadded:: 1.4
  1250. You can use this as a context manager, like this::
  1251. with self.assertTemplateUsed('index.html'):
  1252. render_to_string('index.html')
  1253. with self.assertTemplateUsed(template_name='index.html'):
  1254. render_to_string('index.html')
  1255. .. method:: TestCase.assertTemplateNotUsed(response, template_name, msg_prefix='')
  1256. Asserts that the template with the given name was *not* used in rendering
  1257. the response.
  1258. .. versionadded:: 1.4
  1259. You can use this as a context manager in the same way as
  1260. :meth:`~TestCase.assertTemplateUsed`.
  1261. .. method:: TestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='')
  1262. Asserts that the response return a ``status_code`` redirect status, it
  1263. redirected to ``expected_url`` (including any GET data), and the final
  1264. page was received with ``target_status_code``.
  1265. If your request used the ``follow`` argument, the ``expected_url`` and
  1266. ``target_status_code`` will be the url and status code for the final
  1267. point of the redirect chain.
  1268. .. method:: TestCase.assertQuerysetEqual(qs, values, transform=repr, ordered=True)
  1269. Asserts that a queryset ``qs`` returns a particular list of values ``values``.
  1270. The comparison of the contents of ``qs`` and ``values`` is performed using
  1271. the function ``transform``; by default, this means that the ``repr()`` of
  1272. each value is compared. Any other callable can be used if ``repr()`` doesn't
  1273. provide a unique or helpful comparison.
  1274. By default, the comparison is also ordering dependent. If ``qs`` doesn't
  1275. provide an implicit ordering, you can set the ``ordered`` parameter to
  1276. ``False``, which turns the comparison into a Python set comparison.
  1277. .. versionchanged:: 1.4
  1278. The ``ordered`` parameter is new in version 1.4. In earlier versions,
  1279. you would need to ensure the queryset is ordered consistently, possibly
  1280. via an explicit ``order_by()`` call on the queryset prior to
  1281. comparison.
  1282. .. versionchanged:: 1.6
  1283. The method now checks for undefined order and raises ``ValueError``
  1284. if undefined order is spotted. The ordering is seen as undefined if
  1285. the given ``qs`` isn't ordered and the comparison is against more
  1286. than one ordered values.
  1287. .. method:: TestCase.assertNumQueries(num, func, *args, **kwargs)
  1288. Asserts that when ``func`` is called with ``*args`` and ``**kwargs`` that
  1289. ``num`` database queries are executed.
  1290. If a ``"using"`` key is present in ``kwargs`` it is used as the database
  1291. alias for which to check the number of queries. If you wish to call a
  1292. function with a ``using`` parameter you can do it by wrapping the call with
  1293. a ``lambda`` to add an extra parameter::
  1294. self.assertNumQueries(7, lambda: my_function(using=7))
  1295. You can also use this as a context manager::
  1296. with self.assertNumQueries(2):
  1297. Person.objects.create(name="Aaron")
  1298. Person.objects.create(name="Daniel")
  1299. .. method:: SimpleTestCase.assertHTMLEqual(html1, html2, msg=None)
  1300. .. versionadded:: 1.4
  1301. Asserts that the strings ``html1`` and ``html2`` are equal. The comparison
  1302. is based on HTML semantics. The comparison takes following things into
  1303. account:
  1304. * Whitespace before and after HTML tags is ignored.
  1305. * All types of whitespace are considered equivalent.
  1306. * All open tags are closed implicitly, e.g. when a surrounding tag is
  1307. closed or the HTML document ends.
  1308. * Empty tags are equivalent to their self-closing version.
  1309. * The ordering of attributes of an HTML element is not significant.
  1310. * Attributes without an argument are equal to attributes that equal in
  1311. name and value (see the examples).
  1312. The following examples are valid tests and don't raise any
  1313. ``AssertionError``::
  1314. self.assertHTMLEqual('<p>Hello <b>world!</p>',
  1315. '''<p>
  1316. Hello <b>world! <b/>
  1317. </p>''')
  1318. self.assertHTMLEqual(
  1319. '<input type="checkbox" checked="checked" id="id_accept_terms" />',
  1320. '<input id="id_accept_terms" type='checkbox' checked>')
  1321. ``html1`` and ``html2`` must be valid HTML. An ``AssertionError`` will be
  1322. raised if one of them cannot be parsed.
  1323. .. method:: SimpleTestCase.assertHTMLNotEqual(html1, html2, msg=None)
  1324. .. versionadded:: 1.4
  1325. Asserts that the strings ``html1`` and ``html2`` are *not* equal. The
  1326. comparison is based on HTML semantics. See
  1327. :meth:`~SimpleTestCase.assertHTMLEqual` for details.
  1328. ``html1`` and ``html2`` must be valid HTML. An ``AssertionError`` will be
  1329. raised if one of them cannot be parsed.
  1330. .. method:: SimpleTestCase.assertXMLEqual(xml1, xml2, msg=None)
  1331. .. versionadded:: 1.5
  1332. Asserts that the strings ``xml1`` and ``xml2`` are equal. The
  1333. comparison is based on XML semantics. Similarily to
  1334. :meth:`~SimpleTestCase.assertHTMLEqual`, the comparison is
  1335. made on parsed content, hence only semantic differences are considered, not
  1336. syntax differences. When unvalid XML is passed in any parameter, an
  1337. ``AssertionError`` is always raised, even if both string are identical.
  1338. .. method:: SimpleTestCase.assertXMLNotEqual(xml1, xml2, msg=None)
  1339. .. versionadded:: 1.5
  1340. Asserts that the strings ``xml1`` and ``xml2`` are *not* equal. The
  1341. comparison is based on XML semantics. See
  1342. :meth:`~SimpleTestCase.assertXMLEqual` for details.
  1343. .. _topics-testing-email:
  1344. Email services
  1345. --------------
  1346. If any of your Django views send email using :doc:`Django's email
  1347. functionality </topics/email>`, you probably don't want to send email each time
  1348. you run a test using that view. For this reason, Django's test runner
  1349. automatically redirects all Django-sent email to a dummy outbox. This lets you
  1350. test every aspect of sending email -- from the number of messages sent to the
  1351. contents of each message -- without actually sending the messages.
  1352. The test runner accomplishes this by transparently replacing the normal
  1353. email backend with a testing backend.
  1354. (Don't worry -- this has no effect on any other email senders outside of
  1355. Django, such as your machine's mail server, if you're running one.)
  1356. .. currentmodule:: django.core.mail
  1357. .. data:: django.core.mail.outbox
  1358. During test running, each outgoing email is saved in
  1359. ``django.core.mail.outbox``. This is a simple list of all
  1360. :class:`~django.core.mail.EmailMessage` instances that have been sent.
  1361. The ``outbox`` attribute is a special attribute that is created *only* when
  1362. the ``locmem`` email backend is used. It doesn't normally exist as part of the
  1363. :mod:`django.core.mail` module and you can't import it directly. The code
  1364. below shows how to access this attribute correctly.
  1365. Here's an example test that examines ``django.core.mail.outbox`` for length
  1366. and contents::
  1367. from django.core import mail
  1368. from django.test import TestCase
  1369. class EmailTest(TestCase):
  1370. def test_send_email(self):
  1371. # Send message.
  1372. mail.send_mail('Subject here', 'Here is the message.',
  1373. 'from@example.com', ['to@example.com'],
  1374. fail_silently=False)
  1375. # Test that one message has been sent.
  1376. self.assertEqual(len(mail.outbox), 1)
  1377. # Verify that the subject of the first message is correct.
  1378. self.assertEqual(mail.outbox[0].subject, 'Subject here')
  1379. As noted :ref:`previously <emptying-test-outbox>`, the test outbox is emptied
  1380. at the start of every test in a Django ``TestCase``. To empty the outbox
  1381. manually, assign the empty list to ``mail.outbox``::
  1382. from django.core import mail
  1383. # Empty the test outbox
  1384. mail.outbox = []
  1385. .. _skipping-tests:
  1386. Skipping tests
  1387. --------------
  1388. .. currentmodule:: django.test
  1389. The unittest library provides the :func:`@skipIf <unittest.skipIf>` and
  1390. :func:`@skipUnless <unittest.skipUnless>` decorators to allow you to skip tests
  1391. if you know ahead of time that those tests are going to fail under certain
  1392. conditions.
  1393. For example, if your test requires a particular optional library in order to
  1394. succeed, you could decorate the test case with :func:`@skipIf
  1395. <unittest.skipIf>`. Then, the test runner will report that the test wasn't
  1396. executed and why, instead of failing the test or omitting the test altogether.
  1397. To supplement these test skipping behaviors, Django provides two
  1398. additional skip decorators. Instead of testing a generic boolean,
  1399. these decorators check the capabilities of the database, and skip the
  1400. test if the database doesn't support a specific named feature.
  1401. The decorators use a string identifier to describe database features.
  1402. This string corresponds to attributes of the database connection
  1403. features class. See :class:`~django.db.backends.BaseDatabaseFeatures`
  1404. class for a full list of database features that can be used as a basis
  1405. for skipping tests.
  1406. .. function:: skipIfDBFeature(feature_name_string)
  1407. Skip the decorated test if the named database feature is supported.
  1408. For example, the following test will not be executed if the database
  1409. supports transactions (e.g., it would *not* run under PostgreSQL, but
  1410. it would under MySQL with MyISAM tables)::
  1411. class MyTests(TestCase):
  1412. @skipIfDBFeature('supports_transactions')
  1413. def test_transaction_behavior(self):
  1414. # ... conditional test code
  1415. .. function:: skipUnlessDBFeature(feature_name_string)
  1416. Skip the decorated test if the named database feature is *not*
  1417. supported.
  1418. For example, the following test will only be executed if the database
  1419. supports transactions (e.g., it would run under PostgreSQL, but *not*
  1420. under MySQL with MyISAM tables)::
  1421. class MyTests(TestCase):
  1422. @skipUnlessDBFeature('supports_transactions')
  1423. def test_transaction_behavior(self):
  1424. # ... conditional test code
  1425. Live test server
  1426. ----------------
  1427. .. versionadded:: 1.4
  1428. .. currentmodule:: django.test
  1429. .. class:: LiveServerTestCase()
  1430. ``LiveServerTestCase`` does basically the same as
  1431. :class:`~django.test.TransactionTestCase` with one extra feature: it launches a
  1432. live Django server in the background on setup, and shuts it down on teardown.
  1433. This allows the use of automated test clients other than the
  1434. :ref:`Django dummy client <test-client>` such as, for example, the Selenium_
  1435. client, to execute a series of functional tests inside a browser and simulate a
  1436. real user's actions.
  1437. By default the live server's address is `'localhost:8081'` and the full URL
  1438. can be accessed during the tests with ``self.live_server_url``. If you'd like
  1439. to change the default address (in the case, for example, where the 8081 port is
  1440. already taken) then you may pass a different one to the :djadmin:`test` command
  1441. via the :djadminopt:`--liveserver` option, for example:
  1442. .. code-block:: bash
  1443. ./manage.py test --liveserver=localhost:8082
  1444. Another way of changing the default server address is by setting the
  1445. `DJANGO_LIVE_TEST_SERVER_ADDRESS` environment variable somewhere in your
  1446. code (for example, in a :ref:`custom test runner<topics-testing-test_runner>`):
  1447. .. code-block:: python
  1448. import os
  1449. os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8082'
  1450. In the case where the tests are run by multiple processes in parallel (for
  1451. example, in the context of several simultaneous `continuous integration`_
  1452. builds), the processes will compete for the same address, and therefore your
  1453. tests might randomly fail with an "Address already in use" error. To avoid this
  1454. problem, you can pass a comma-separated list of ports or ranges of ports (at
  1455. least as many as the number of potential parallel processes). For example:
  1456. .. code-block:: bash
  1457. ./manage.py test --liveserver=localhost:8082,8090-8100,9000-9200,7041
  1458. Then, during test execution, each new live test server will try every specified
  1459. port until it finds one that is free and takes it.
  1460. .. _continuous integration: http://en.wikipedia.org/wiki/Continuous_integration
  1461. To demonstrate how to use ``LiveServerTestCase``, let's write a simple Selenium
  1462. test. First of all, you need to install the `selenium package`_ into your
  1463. Python path:
  1464. .. code-block:: bash
  1465. pip install selenium
  1466. Then, add a ``LiveServerTestCase``-based test to your app's tests module
  1467. (for example: ``myapp/tests.py``). The code for this test may look as follows:
  1468. .. code-block:: python
  1469. from django.test import LiveServerTestCase
  1470. from selenium.webdriver.firefox.webdriver import WebDriver
  1471. class MySeleniumTests(LiveServerTestCase):
  1472. fixtures = ['user-data.json']
  1473. @classmethod
  1474. def setUpClass(cls):
  1475. cls.selenium = WebDriver()
  1476. super(MySeleniumTests, cls).setUpClass()
  1477. @classmethod
  1478. def tearDownClass(cls):
  1479. cls.selenium.quit()
  1480. super(MySeleniumTests, cls).tearDownClass()
  1481. def test_login(self):
  1482. self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
  1483. username_input = self.selenium.find_element_by_name("username")
  1484. username_input.send_keys('myuser')
  1485. password_input = self.selenium.find_element_by_name("password")
  1486. password_input.send_keys('secret')
  1487. self.selenium.find_element_by_xpath('//input[@value="Log in"]').click()
  1488. Finally, you may run the test as follows:
  1489. .. code-block:: bash
  1490. ./manage.py test myapp.MySeleniumTests.test_login
  1491. This example will automatically open Firefox then go to the login page, enter
  1492. the credentials and press the "Log in" button. Selenium offers other drivers in
  1493. case you do not have Firefox installed or wish to use another browser. The
  1494. example above is just a tiny fraction of what the Selenium client can do; check
  1495. out the `full reference`_ for more details.
  1496. .. _Selenium: http://seleniumhq.org/
  1497. .. _selenium package: http://pypi.python.org/pypi/selenium
  1498. .. _full reference: http://selenium-python.readthedocs.org/en/latest/api.html
  1499. .. _Firefox: http://www.mozilla.com/firefox/
  1500. .. note::
  1501. ``LiveServerTestCase`` makes use of the :doc:`staticfiles contrib app
  1502. </howto/static-files>` so you'll need to have your project configured
  1503. accordingly (in particular by setting :setting:`STATIC_URL`).
  1504. .. note::
  1505. When using an in-memory SQLite database to run the tests, the same database
  1506. connection will be shared by two threads in parallel: the thread in which
  1507. the live server is run and the thread in which the test case is run. It's
  1508. important to prevent simultaneous database queries via this shared
  1509. connection by the two threads, as that may sometimes randomly cause the
  1510. tests to fail. So you need to ensure that the two threads don't access the
  1511. database at the same time. In particular, this means that in some cases
  1512. (for example, just after clicking a link or submitting a form), you might
  1513. need to check that a response is received by Selenium and that the next
  1514. page is loaded before proceeding with further test execution.
  1515. Do this, for example, by making Selenium wait until the `<body>` HTML tag
  1516. is found in the response (requires Selenium > 2.13):
  1517. .. code-block:: python
  1518. def test_login(self):
  1519. from selenium.webdriver.support.wait import WebDriverWait
  1520. timeout = 2
  1521. ...
  1522. self.selenium.find_element_by_xpath('//input[@value="Log in"]').click()
  1523. # Wait until the response is received
  1524. WebDriverWait(self.selenium, timeout).until(
  1525. lambda driver: driver.find_element_by_tag_name('body'))
  1526. The tricky thing here is that there's really no such thing as a "page load,"
  1527. especially in modern Web apps that generate HTML dynamically after the
  1528. server generates the initial document. So, simply checking for the presence
  1529. of `<body>` in the response might not necessarily be appropriate for all
  1530. use cases. Please refer to the `Selenium FAQ`_ and
  1531. `Selenium documentation`_ for more information.
  1532. .. _Selenium FAQ: http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_WebDriver_fails_to_find_elements_/_Does_not_block_on_page_loa
  1533. .. _Selenium documentation: http://seleniumhq.org/docs/04_webdriver_advanced.html#explicit-waits
  1534. Using different testing frameworks
  1535. ==================================
  1536. Clearly, :mod:`doctest` and :mod:`unittest` are not the only Python testing
  1537. frameworks. While Django doesn't provide explicit support for alternative
  1538. frameworks, it does provide a way to invoke tests constructed for an
  1539. alternative framework as if they were normal Django tests.
  1540. When you run ``./manage.py test``, Django looks at the :setting:`TEST_RUNNER`
  1541. setting to determine what to do. By default, :setting:`TEST_RUNNER` points to
  1542. ``'django.test.simple.DjangoTestSuiteRunner'``. This class defines the default Django
  1543. testing behavior. This behavior involves:
  1544. #. Performing global pre-test setup.
  1545. #. Looking for unit tests and doctests in the ``models.py`` and
  1546. ``tests.py`` files in each installed application.
  1547. #. Creating the test databases.
  1548. #. Running ``syncdb`` to install models and initial data into the test
  1549. databases.
  1550. #. Running the unit tests and doctests that are found.
  1551. #. Destroying the test databases.
  1552. #. Performing global post-test teardown.
  1553. If you define your own test runner class and point :setting:`TEST_RUNNER` at
  1554. that class, Django will execute your test runner whenever you run
  1555. ``./manage.py test``. In this way, it is possible to use any test framework
  1556. that can be executed from Python code, or to modify the Django test execution
  1557. process to satisfy whatever testing requirements you may have.
  1558. .. _topics-testing-test_runner:
  1559. Defining a test runner
  1560. ----------------------
  1561. .. currentmodule:: django.test.simple
  1562. A test runner is a class defining a ``run_tests()`` method. Django ships
  1563. with a ``DjangoTestSuiteRunner`` class that defines the default Django
  1564. testing behavior. This class defines the ``run_tests()`` entry point,
  1565. plus a selection of other methods that are used to by ``run_tests()`` to
  1566. set up, execute and tear down the test suite.
  1567. .. class:: DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=True, **kwargs)
  1568. ``verbosity`` determines the amount of notification and debug information
  1569. that will be printed to the console; ``0`` is no output, ``1`` is normal
  1570. output, and ``2`` is verbose output.
  1571. If ``interactive`` is ``True``, the test suite has permission to ask the
  1572. user for instructions when the test suite is executed. An example of this
  1573. behavior would be asking for permission to delete an existing test
  1574. database. If ``interactive`` is ``False``, the test suite must be able to
  1575. run without any manual intervention.
  1576. If ``failfast`` is ``True``, the test suite will stop running after the
  1577. first test failure is detected.
  1578. Django will, from time to time, extend the capabilities of
  1579. the test runner by adding new arguments. The ``**kwargs`` declaration
  1580. allows for this expansion. If you subclass ``DjangoTestSuiteRunner`` or
  1581. write your own test runner, ensure accept and handle the ``**kwargs``
  1582. parameter.
  1583. .. versionadded:: 1.4
  1584. Your test runner may also define additional command-line options.
  1585. If you add an ``option_list`` attribute to a subclassed test runner,
  1586. those options will be added to the list of command-line options that
  1587. the :djadmin:`test` command can use.
  1588. Attributes
  1589. ~~~~~~~~~~
  1590. .. attribute:: DjangoTestSuiteRunner.option_list
  1591. .. versionadded:: 1.4
  1592. This is the tuple of ``optparse`` options which will be fed into the
  1593. management command's ``OptionParser`` for parsing arguments. See the
  1594. documentation for Python's ``optparse`` module for more details.
  1595. Methods
  1596. ~~~~~~~
  1597. .. method:: DjangoTestSuiteRunner.run_tests(test_labels, extra_tests=None, **kwargs)
  1598. Run the test suite.
  1599. ``test_labels`` is a list of strings describing the tests to be run. A test
  1600. label can take one of three forms:
  1601. * ``app.TestCase.test_method`` -- Run a single test method in a test
  1602. case.
  1603. * ``app.TestCase`` -- Run all the test methods in a test case.
  1604. * ``app`` -- Search for and run all tests in the named application.
  1605. If ``test_labels`` has a value of ``None``, the test runner should run
  1606. search for tests in all the applications in :setting:`INSTALLED_APPS`.
  1607. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  1608. suite that is executed by the test runner. These extra tests are run
  1609. in addition to those discovered in the modules listed in ``test_labels``.
  1610. This method should return the number of tests that failed.
  1611. .. method:: DjangoTestSuiteRunner.setup_test_environment(**kwargs)
  1612. Sets up the test environment ready for testing.
  1613. .. method:: DjangoTestSuiteRunner.build_suite(test_labels, extra_tests=None, **kwargs)
  1614. Constructs a test suite that matches the test labels provided.
  1615. ``test_labels`` is a list of strings describing the tests to be run. A test
  1616. label can take one of three forms:
  1617. * ``app.TestCase.test_method`` -- Run a single test method in a test
  1618. case.
  1619. * ``app.TestCase`` -- Run all the test methods in a test case.
  1620. * ``app`` -- Search for and run all tests in the named application.
  1621. If ``test_labels`` has a value of ``None``, the test runner should run
  1622. search for tests in all the applications in :setting:`INSTALLED_APPS`.
  1623. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  1624. suite that is executed by the test runner. These extra tests are run
  1625. in addition to those discovered in the modules listed in ``test_labels``.
  1626. Returns a ``TestSuite`` instance ready to be run.
  1627. .. method:: DjangoTestSuiteRunner.setup_databases(**kwargs)
  1628. Creates the test databases.
  1629. Returns a data structure that provides enough detail to undo the changes
  1630. that have been made. This data will be provided to the ``teardown_databases()``
  1631. function at the conclusion of testing.
  1632. .. method:: DjangoTestSuiteRunner.run_suite(suite, **kwargs)
  1633. Runs the test suite.
  1634. Returns the result produced by the running the test suite.
  1635. .. method:: DjangoTestSuiteRunner.teardown_databases(old_config, **kwargs)
  1636. Destroys the test databases, restoring pre-test conditions.
  1637. ``old_config`` is a data structure defining the changes in the
  1638. database configuration that need to be reversed. It is the return
  1639. value of the ``setup_databases()`` method.
  1640. .. method:: DjangoTestSuiteRunner.teardown_test_environment(**kwargs)
  1641. Restores the pre-test environment.
  1642. .. method:: DjangoTestSuiteRunner.suite_result(suite, result, **kwargs)
  1643. Computes and returns a return code based on a test suite, and the result
  1644. from that test suite.
  1645. Testing utilities
  1646. -----------------
  1647. .. module:: django.test.utils
  1648. :synopsis: Helpers to write custom test runners.
  1649. To assist in the creation of your own test runner, Django provides a number of
  1650. utility methods in the ``django.test.utils`` module.
  1651. .. function:: setup_test_environment()
  1652. Performs any global pre-test setup, such as the installing the
  1653. instrumentation of the template rendering system and setting up
  1654. the dummy email outbox.
  1655. .. function:: teardown_test_environment()
  1656. Performs any global post-test teardown, such as removing the black
  1657. magic hooks into the template system and restoring normal email
  1658. services.
  1659. .. currentmodule:: django.db.connection.creation
  1660. The creation module of the database backend (``connection.creation``)
  1661. also provides some utilities that can be useful during testing.
  1662. .. function:: create_test_db([verbosity=1, autoclobber=False])
  1663. Creates a new test database and runs ``syncdb`` against it.
  1664. ``verbosity`` has the same behavior as in ``run_tests()``.
  1665. ``autoclobber`` describes the behavior that will occur if a
  1666. database with the same name as the test database is discovered:
  1667. * If ``autoclobber`` is ``False``, the user will be asked to
  1668. approve destroying the existing database. ``sys.exit`` is
  1669. called if the user does not approve.
  1670. * If autoclobber is ``True``, the database will be destroyed
  1671. without consulting the user.
  1672. Returns the name of the test database that it created.
  1673. ``create_test_db()`` has the side effect of modifying the value of
  1674. :setting:`NAME` in :setting:`DATABASES` to match the name of the test
  1675. database.
  1676. .. function:: destroy_test_db(old_database_name, [verbosity=1])
  1677. Destroys the database whose name is the value of :setting:`NAME` in
  1678. :setting:`DATABASES`, and sets :setting:`NAME` to the value of
  1679. ``old_database_name``.
  1680. The ``verbosity`` argument has the same behavior as for
  1681. :class:`~django.test.simple.DjangoTestSuiteRunner`.