testing.txt 87 KB

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