testing.txt 69 KB

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