testing.txt 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971
  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. .. versionchanged:: 1.3
  58. Python 2.7 introduced some major changes to the unittest library,
  59. adding some extremely useful features. To ensure that every Django
  60. project can benefit from these new features, Django ships with a
  61. copy of unittest2_, a copy of the Python 2.7 unittest library,
  62. backported for Python 2.5 compatibility.
  63. To access this library, Django provides the
  64. :mod:`django.utils.unittest` module alias. If you are using Python
  65. 2.7, or you have installed unittest2 locally, Django will map the
  66. alias to the installed version of the unittest library. Otherwise,
  67. Django will use it's own bundled version of unittest2.
  68. To use this alias, simply use::
  69. from django.utils import unittest
  70. wherever you would have historically used::
  71. import unittest
  72. If you want to continue to use the base unittest library, you can --
  73. you just won't get any of the nice new unittest2 features.
  74. .. _unittest2: http://pypi.python.org/pypi/unittest2
  75. For a given Django application, the test runner looks for unit tests in two
  76. places:
  77. * The ``models.py`` file. The test runner looks for any subclass of
  78. :class:`unittest.TestCase` in this module.
  79. * A file called ``tests.py`` in the application directory -- i.e., the
  80. directory that holds ``models.py``. Again, the test runner looks for any
  81. subclass of :class:`unittest.TestCase` in this module.
  82. Here is an example :class:`unittest.TestCase` subclass::
  83. from django.utils import unittest
  84. from myapp.models import Animal
  85. class AnimalTestCase(unittest.TestCase):
  86. def setUp(self):
  87. self.lion = Animal.objects.create(name="lion", sound="roar")
  88. self.cat = Animal.objects.create(name="cat", sound="meow")
  89. def testSpeaking(self):
  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.testFluffyAnimals
  215. .. versionadded:: 1.2
  216. The ability to select individual doctests was added.
  217. You can use the same rules if you're using doctests. Django will use the
  218. test label as a path to the test method or class that you want to run.
  219. If your ``models.py`` or ``tests.py`` has a function with a doctest, or
  220. class with a class-level doctest, you can invoke that test by appending the
  221. name of the test method or class to the label::
  222. $ ./manage.py test animals.classify
  223. If you want to run the doctest for a specific method in a class, add the
  224. name of the method to the label::
  225. $ ./manage.py test animals.Classifier.run
  226. If you're using a ``__test__`` dictionary to specify doctests for a
  227. module, Django will use the label as a key in the ``__test__`` dictionary
  228. for defined in ``models.py`` and ``tests.py``.
  229. .. versionadded:: 1.2
  230. You can now trigger a graceful exit from a test run by pressing ``Ctrl-C``.
  231. If you press ``Ctrl-C`` while the tests are running, the test runner will
  232. wait for the currently running test to complete and then exit gracefully.
  233. During a graceful exit the test runner will output details of any test
  234. failures, report on how many tests were run and how many errors and failures
  235. were encountered, and destroy any test databases as usual. Thus pressing
  236. ``Ctrl-C`` can be very useful if you forget to pass the :djadminopt:`--failfast`
  237. option, notice that some tests are unexpectedly failing, and want to get details
  238. on the failures without waiting for the full test run to complete.
  239. If you do not want to wait for the currently running test to finish, you
  240. can press ``Ctrl-C`` a second time and the test run will halt immediately,
  241. but not gracefully. No details of the tests run before the interruption will
  242. be reported, and any test databases created by the run will not be destroyed.
  243. .. admonition:: Test with warnings enabled
  244. It's a good idea to run your tests with Python warnings enabled:
  245. ``python -Wall manage.py test``. The ``-Wall`` flag tells Python to
  246. display deprecation warnings. Django, like many other Python libraries,
  247. uses these warnings to flag when features are going away. It also might
  248. flag areas in your code that aren't strictly wrong but could benefit
  249. from a better implementation.
  250. Running tests outside the test runner
  251. -------------------------------------
  252. If you want to run tests outside of ``./manage.py test`` -- for example,
  253. from a shell prompt -- you will need to set up the test
  254. environment first. Django provides a convenience method to do this::
  255. >>> from django.test.utils import setup_test_environment
  256. >>> setup_test_environment()
  257. This convenience method sets up the test database, and puts other
  258. Django features into modes that allow for repeatable testing.
  259. The call to :meth:`~django.test.utils.setup_test_environment` is made
  260. automatically as part of the setup of `./manage.py test`. You only
  261. need to manually invoke this method if you're not using running your
  262. tests via Django's test runner.
  263. The test database
  264. -----------------
  265. Tests that require a database (namely, model tests) will not use your "real"
  266. (production) database. Separate, blank databases are created for the tests.
  267. Regardless of whether the tests pass or fail, the test databases are destroyed
  268. when all the tests have been executed.
  269. By default the test databases get their names by prepending ``test_``
  270. to the value of the :setting:`NAME` settings for the databases
  271. defined in :setting:`DATABASES`. When using the SQLite database engine
  272. the tests will by default use an in-memory database (i.e., the
  273. database will be created in memory, bypassing the filesystem
  274. entirely!). If you want to use a different database name, specify
  275. :setting:`TEST_NAME` in the dictionary for any given database in
  276. :setting:`DATABASES`.
  277. Aside from using a separate database, the test runner will otherwise
  278. use all of the same database settings you have in your settings file:
  279. :setting:`ENGINE`, :setting:`USER`, :setting:`HOST`, etc. The test
  280. database is created by the user specified by :setting:`USER`, so you'll need
  281. to make sure that the given user account has sufficient privileges to
  282. create a new database on the system.
  283. For fine-grained control over the character encoding of your test
  284. database, use the :setting:`TEST_CHARSET` option. If you're using
  285. MySQL, you can also use the :setting:`TEST_COLLATION` option to
  286. control the particular collation used by the test database. See the
  287. :doc:`settings documentation </ref/settings>` for details of these
  288. advanced settings.
  289. .. _topics-testing-masterslave:
  290. Testing master/slave configurations
  291. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  292. .. versionadded:: 1.2
  293. If you're testing a multiple database configuration with master/slave
  294. replication, this strategy of creating test databases poses a problem.
  295. When the test databases are created, there won't be any replication,
  296. and as a result, data created on the master won't be seen on the
  297. slave.
  298. To compensate for this, Django allows you to define that a database is
  299. a *test mirror*. Consider the following (simplified) example database
  300. configuration::
  301. DATABASES = {
  302. 'default': {
  303. 'ENGINE': 'django.db.backends.mysql',
  304. 'NAME': 'myproject',
  305. 'HOST': 'dbmaster',
  306. # ... plus some other settings
  307. },
  308. 'slave': {
  309. 'ENGINE': 'django.db.backends.mysql',
  310. 'NAME': 'myproject',
  311. 'HOST': 'dbslave',
  312. 'TEST_MIRROR': 'default'
  313. # ... plus some other settings
  314. }
  315. }
  316. In this setup, we have two database servers: ``dbmaster``, described
  317. by the database alias ``default``, and ``dbslave`` described by the
  318. alias ``slave``. As you might expect, ``dbslave`` has been configured
  319. by the database administrator as a read slave of ``dbmaster``, so in
  320. normal activity, any write to ``default`` will appear on ``slave``.
  321. If Django created two independent test databases, this would break any
  322. tests that expected replication to occur. However, the ``slave``
  323. database has been configured as a test mirror (using the
  324. :setting:`TEST_MIRROR` setting), indicating that under testing,
  325. ``slave`` should be treated as a mirror of ``default``.
  326. When the test environment is configured, a test version of ``slave``
  327. will *not* be created. Instead the connection to ``slave``
  328. will be redirected to point at ``default``. As a result, writes to
  329. ``default`` will appear on ``slave`` -- but because they are actually
  330. the same database, not because there is data replication between the
  331. two databases.
  332. .. _topics-testing-creation-dependencies:
  333. Controlling creation order for test databases
  334. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  335. .. versionadded:: 1.3
  336. By default, Django will always create the ``default`` database first.
  337. However, no guarantees are made on the creation order of any other
  338. databases in your test setup.
  339. If your database configuration requires a specific creation order, you
  340. can specify the dependencies that exist using the
  341. :setting:`TEST_DEPENDENCIES` setting. Consider the following
  342. (simplified) example database configuration::
  343. DATABASES = {
  344. 'default': {
  345. # ... db settings
  346. 'TEST_DEPENDENCIES': ['diamonds']
  347. },
  348. 'diamonds': {
  349. # ... db settings
  350. },
  351. 'clubs': {
  352. # ... db settings
  353. 'TEST_DEPENDENCIES': ['diamonds']
  354. },
  355. 'spades': {
  356. # ... db settings
  357. 'TEST_DEPENDENCIES': ['diamonds','hearts']
  358. },
  359. 'hearts': {
  360. # ... db settings
  361. 'TEST_DEPENDENCIES': ['diamonds','clubs']
  362. }
  363. }
  364. Under this configuration, the ``diamonds`` database will be created first,
  365. as it is the only database alias without dependencies. The ``default`` and
  366. ``clubs`` alias will be created next (although the order of creation of this
  367. pair is not guaranteed); then ``hearts``; and finally ``spades``.
  368. If there are any circular dependencies in the
  369. :setting:`TEST_DEPENDENCIES` definition, an ``ImproperlyConfigured``
  370. exception will be raised.
  371. Other test conditions
  372. ---------------------
  373. Regardless of the value of the :setting:`DEBUG` setting in your configuration
  374. file, all Django tests run with :setting:`DEBUG`\=False. This is to ensure that
  375. the observed output of your code matches what will be seen in a production
  376. setting.
  377. Understanding the test output
  378. -----------------------------
  379. When you run your tests, you'll see a number of messages as the test runner
  380. prepares itself. You can control the level of detail of these messages with the
  381. ``verbosity`` option on the command line::
  382. Creating test database...
  383. Creating table myapp_animal
  384. Creating table myapp_mineral
  385. Loading 'initial_data' fixtures...
  386. No fixtures found.
  387. This tells you that the test runner is creating a test database, as described
  388. in the previous section.
  389. Once the test database has been created, Django will run your tests.
  390. If everything goes well, you'll see something like this::
  391. ----------------------------------------------------------------------
  392. Ran 22 tests in 0.221s
  393. OK
  394. If there are test failures, however, you'll see full details about which tests
  395. failed::
  396. ======================================================================
  397. FAIL: Doctest: ellington.core.throttle.models
  398. ----------------------------------------------------------------------
  399. Traceback (most recent call last):
  400. File "/dev/django/test/doctest.py", line 2153, in runTest
  401. raise self.failureException(self.format_failure(new.getvalue()))
  402. AssertionError: Failed doctest test for myapp.models
  403. File "/dev/myapp/models.py", line 0, in models
  404. ----------------------------------------------------------------------
  405. File "/dev/myapp/models.py", line 14, in myapp.models
  406. Failed example:
  407. throttle.check("actor A", "action one", limit=2, hours=1)
  408. Expected:
  409. True
  410. Got:
  411. False
  412. ----------------------------------------------------------------------
  413. Ran 2 tests in 0.048s
  414. FAILED (failures=1)
  415. A full explanation of this error output is beyond the scope of this document,
  416. but it's pretty intuitive. You can consult the documentation of Python's
  417. :mod:`unittest` library for details.
  418. Note that the return code for the test-runner script is 1 for any number of
  419. failed and erroneous tests. If all the tests pass, the return code is 0. This
  420. feature is useful if you're using the test-runner script in a shell script and
  421. need to test for success or failure at that level.
  422. Testing tools
  423. =============
  424. Django provides a small set of tools that come in handy when writing tests.
  425. .. _test-client:
  426. The test client
  427. ---------------
  428. .. module:: django.test.client
  429. :synopsis: Django's test client.
  430. The test client is a Python class that acts as a dummy Web browser, allowing
  431. you to test your views and interact with your Django-powered application
  432. programmatically.
  433. Some of the things you can do with the test client are:
  434. * Simulate GET and POST requests on a URL and observe the response --
  435. everything from low-level HTTP (result headers and status codes) to
  436. page content.
  437. * Test that the correct view is executed for a given URL.
  438. * Test that a given request is rendered by a given Django template, with
  439. a template context that contains certain values.
  440. Note that the test client is not intended to be a replacement for Twill_,
  441. Selenium_, or other "in-browser" frameworks. Django's test client has
  442. a different focus. In short:
  443. * Use Django's test client to establish that the correct view is being
  444. called and that the view is collecting the correct context data.
  445. * Use in-browser frameworks such as Twill and Selenium to test *rendered*
  446. HTML and the *behavior* of Web pages, namely JavaScript functionality.
  447. A comprehensive test suite should use a combination of both test types.
  448. .. _Twill: http://twill.idyll.org/
  449. .. _Selenium: http://seleniumhq.org/
  450. Overview and a quick example
  451. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  452. To use the test client, instantiate ``django.test.client.Client`` and retrieve
  453. Web pages::
  454. >>> from django.test.client import Client
  455. >>> c = Client()
  456. >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
  457. >>> response.status_code
  458. 200
  459. >>> response = c.get('/customer/details/')
  460. >>> response.content
  461. '<!DOCTYPE html...'
  462. As this example suggests, you can instantiate ``Client`` from within a session
  463. of the Python interactive interpreter.
  464. Note a few important things about how the test client works:
  465. * The test client does *not* require the Web server to be running. In fact,
  466. it will run just fine with no Web server running at all! That's because
  467. it avoids the overhead of HTTP and deals directly with the Django
  468. framework. This helps make the unit tests run quickly.
  469. * When retrieving pages, remember to specify the *path* of the URL, not the
  470. whole domain. For example, this is correct::
  471. >>> c.get('/login/')
  472. This is incorrect::
  473. >>> c.get('http://www.example.com/login/')
  474. The test client is not capable of retrieving Web pages that are not
  475. powered by your Django project. If you need to retrieve other Web pages,
  476. use a Python standard library module such as :mod:`urllib` or
  477. :mod:`urllib2`.
  478. * To resolve URLs, the test client uses whatever URLconf is pointed-to by
  479. your :setting:`ROOT_URLCONF` setting.
  480. * Although the above example would work in the Python interactive
  481. interpreter, some of the test client's functionality, notably the
  482. template-related functionality, is only available *while tests are
  483. running*.
  484. The reason for this is that Django's test runner performs a bit of black
  485. magic in order to determine which template was loaded by a given view.
  486. This black magic (essentially a patching of Django's template system in
  487. memory) only happens during test running.
  488. * By default, the test client will disable any CSRF checks
  489. performed by your site.
  490. .. versionadded:: 1.2.2
  491. If, for some reason, you *want* the test client to perform CSRF
  492. checks, you can create an instance of the test client that
  493. enforces CSRF checks. To do this, pass in the
  494. ``enforce_csrf_checks`` argument when you construct your
  495. client::
  496. >>> from django.test import Client
  497. >>> csrf_client = Client(enforce_csrf_checks=True)
  498. Making requests
  499. ~~~~~~~~~~~~~~~
  500. Use the ``django.test.client.Client`` class to make requests. It requires no
  501. arguments at time of construction:
  502. .. class:: Client()
  503. Once you have a ``Client`` instance, you can call any of the following
  504. methods:
  505. .. method:: Client.get(path, data={}, follow=False, **extra)
  506. Makes a GET request on the provided ``path`` and returns a ``Response``
  507. object, which is documented below.
  508. The key-value pairs in the ``data`` dictionary are used to create a GET
  509. data payload. For example::
  510. >>> c = Client()
  511. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
  512. ...will result in the evaluation of a GET request equivalent to::
  513. /customers/details/?name=fred&age=7
  514. The ``extra`` keyword arguments parameter can be used to specify
  515. headers to be sent in the request. For example::
  516. >>> c = Client()
  517. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
  518. ... HTTP_X_REQUESTED_WITH='XMLHttpRequest')
  519. ...will send the HTTP header ``HTTP_X_REQUESTED_WITH`` to the
  520. details view, which is a good way to test code paths that use the
  521. :meth:`django.http.HttpRequest.is_ajax()` method.
  522. .. admonition:: CGI specification
  523. The headers sent via ``**extra`` should follow CGI_ specification.
  524. For example, emulating a different "Host" header as sent in the
  525. HTTP request from the browser to the server should be passed
  526. as ``HTTP_HOST``.
  527. .. _CGI: http://www.w3.org/CGI/
  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. :mimetype:`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. :mimetype:`multipart/form-data`. In this case, the key-value pairs in
  560. ``data`` will be encoded as a multipart message and used to create the
  561. POST data 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
  695. :rfc:`2616#section-10` for a full 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. Exceptions
  707. ~~~~~~~~~~
  708. If you point the test client at a view that raises an exception, that exception
  709. will be visible in the test case. You can then use a standard ``try ... except``
  710. block or :meth:`~unittest.TestCase.assertRaises` to test for exceptions.
  711. The only exceptions that are not visible to the test client are ``Http404``,
  712. ``PermissionDenied`` and ``SystemExit``. Django catches these exceptions
  713. internally and converts them into the appropriate HTTP response codes. In these
  714. cases, you can check ``response.status_code`` in your test.
  715. Persistent state
  716. ~~~~~~~~~~~~~~~~
  717. The test client is stateful. If a response returns a cookie, then that cookie
  718. will be stored in the test client and sent with all subsequent ``get()`` and
  719. ``post()`` requests.
  720. Expiration policies for these cookies are not followed. If you want a cookie
  721. to expire, either delete it manually or create a new ``Client`` instance (which
  722. will effectively delete all cookies).
  723. A test client has two attributes that store persistent state information. You
  724. can access these properties as part of a test condition.
  725. .. attribute:: Client.cookies
  726. A Python :class:`~Cookie.SimpleCookie` object, containing the current values
  727. of all the client cookies. See the documentation of the :mod:`Cookie` module
  728. 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. Example
  740. ~~~~~~~
  741. The following is a simple unit test using the test client::
  742. from django.utils import unittest
  743. from django.test.client import Client
  744. class SimpleTest(unittest.TestCase):
  745. def setUp(self):
  746. # Every test needs a client.
  747. self.client = Client()
  748. def test_details(self):
  749. # Issue a GET request.
  750. response = self.client.get('/customer/details/')
  751. # Check that the response is 200 OK.
  752. self.assertEqual(response.status_code, 200)
  753. # Check that the rendered context contains 5 customers.
  754. self.assertEqual(len(response.context['customers']), 5)
  755. The request factory
  756. -------------------
  757. .. Class:: RequestFactory
  758. .. versionadded:: 1.3
  759. The :class:`~django.test.client.RequestFactory` shares the same API as
  760. the test client. However, instead of behaving like a browser, the
  761. RequestFactory provides a way to generate a request instance that can
  762. be used as the first argument to any view. This means you can test a
  763. view function the same way as you would test any other function -- as
  764. a black box, with exactly known inputs, testing for specific outputs.
  765. The API for the :class:`~django.test.client.RequestFactory` is a slightly
  766. restricted subset of the test client API:
  767. * It only has access to the HTTP methods :meth:`~Client.get()`,
  768. :meth:`~Client.post()`, :meth:`~Client.put()`,
  769. :meth:`~Client.delete()`, :meth:`~Client.head()` and
  770. :meth:`~Client.options()`.
  771. * These methods accept all the same arguments *except* for
  772. ``follows``. Since this is just a factory for producing
  773. requests, it's up to you to handle the response.
  774. * It does not support middleware. Session and authentication
  775. attributes must be supplied by the test itself if required
  776. for the view to function properly.
  777. Example
  778. ~~~~~~~
  779. The following is a simple unit test using the request factory::
  780. from django.utils import unittest
  781. from django.test.client import RequestFactory
  782. class SimpleTest(unittest.TestCase):
  783. def setUp(self):
  784. # Every test needs access to the request factory.
  785. self.factory = RequestFactory()
  786. def test_details(self):
  787. # Create an instance of a GET request.
  788. request = self.factory.get('/customer/details')
  789. # Test my_view() as if it were deployed at /customer/details
  790. response = my_view(request)
  791. self.assertEqual(response.status_code, 200)
  792. TestCase
  793. --------
  794. .. currentmodule:: django.test
  795. Normal Python unit test classes extend a base class of
  796. :class:`unittest.TestCase`. Django provides a few extensions of this base class:
  797. .. class:: TestCase()
  798. This class provides some additional capabilities that can be useful for testing
  799. Web sites.
  800. Converting a normal :class:`unittest.TestCase` to a Django :class:`TestCase` is
  801. easy: just change the base class of your test from :class:`unittest.TestCase` to
  802. :class:`django.test.TestCase`. All of the standard Python unit test
  803. functionality will continue to be available, but it will be augmented with some
  804. useful additions, including:
  805. * Automatic loading of fixtures.
  806. * Wraps each test in a transaction.
  807. * Creates a TestClient instance.
  808. * Django-specific assertions for testing for things
  809. like redirection and form errors.
  810. ``TestCase`` inherits from :class:`~django.test.TransactionTestCase`.
  811. .. class:: TransactionTestCase()
  812. Django ``TestCase`` classes make use of database transaction facilities, if
  813. available, to speed up the process of resetting the database to a known state
  814. at the beginning of each test. A consequence of this, however, is that the
  815. effects of transaction commit and rollback cannot be tested by a Django
  816. ``TestCase`` class. If your test requires testing of such transactional
  817. behavior, you should use a Django ``TransactionTestCase``.
  818. ``TransactionTestCase`` and ``TestCase`` are identical except for the manner
  819. in which the database is reset to a known state and the ability for test code
  820. to test the effects of commit and rollback. A ``TransactionTestCase`` resets
  821. the database before the test runs by truncating all tables and reloading
  822. initial data. A ``TransactionTestCase`` may call commit and rollback and
  823. observe the effects of these calls on the database.
  824. A ``TestCase``, on the other hand, does not truncate tables and reload initial
  825. data at the beginning of a test. Instead, it encloses the test code in a
  826. database transaction that is rolled back at the end of the test. It also
  827. prevents the code under test from issuing any commit or rollback operations
  828. on the database, to ensure that the rollback at the end of the test restores
  829. the database to its initial state. In order to guarantee that all ``TestCase``
  830. code starts with a clean database, the Django test runner runs all ``TestCase``
  831. tests first, before any other tests (e.g. doctests) that may alter the
  832. database without restoring it to its original state.
  833. When running on a database that does not support rollback (e.g. MySQL with the
  834. MyISAM storage engine), ``TestCase`` falls back to initializing the database
  835. by truncating tables and reloading initial data.
  836. ``TransactionTestCase`` inherits from :class:`~django.test.SimpleTestCase`.
  837. .. note::
  838. The ``TestCase`` use of rollback to un-do the effects of the test code
  839. may reveal previously-undetected errors in test code. For example,
  840. test code that assumes primary keys values will be assigned starting at
  841. one may find that assumption no longer holds true when rollbacks instead
  842. of table truncation are being used to reset the database. Similarly,
  843. the reordering of tests so that all ``TestCase`` classes run first may
  844. reveal unexpected dependencies on test case ordering. In such cases a
  845. quick fix is to switch the ``TestCase`` to a ``TransactionTestCase``.
  846. A better long-term fix, that allows the test to take advantage of the
  847. speed benefit of ``TestCase``, is to fix the underlying test problem.
  848. .. class:: SimpleTestCase()
  849. .. versionadded:: 1.4
  850. A very thin subclass of :class:`unittest.TestCase`, it extends it with some
  851. basic functionality like:
  852. * Saving and restoring the Python warning machinery state.
  853. * Checking that a callable :meth:`raises a certain exeception <TestCase.assertRaisesMessage>`.
  854. * :meth:`Testing form field rendering <assertFieldOutput>`.
  855. If you need any of the other more complex and heavyweight Django-specific
  856. features like:
  857. * The ability to run tests with :ref:`modified settings <overriding-settings>`
  858. * Using the :attr:`~TestCase.client` :class:`~django.test.client.Client`.
  859. * Testing or using the ORM.
  860. * Database :attr:`~TestCase.fixtures`.
  861. * Custom test-time :attr:`URL maps <TestCase.urls>`.
  862. * Test :ref:`skipping based on database backend features <skipping-tests>`.
  863. * Our specialized :ref:`assert* <assertions>` metods.
  864. then you should use :class:`~django.test.TransactionTestCase` or
  865. :class:`~django.test.TestCase` instead.
  866. ``SimpleTestCase`` inherits from :class:`django.utils.unittest.TestCase`.
  867. Default test client
  868. ~~~~~~~~~~~~~~~~~~~
  869. .. attribute:: TestCase.client
  870. Every test case in a ``django.test.TestCase`` instance has access to an
  871. instance of a Django test client. This client can be accessed as
  872. ``self.client``. This client is recreated for each test, so you don't have to
  873. worry about state (such as cookies) carrying over from one test to another.
  874. This means, instead of instantiating a ``Client`` in each test::
  875. from django.utils import unittest
  876. from django.test.client import Client
  877. class SimpleTest(unittest.TestCase):
  878. def test_details(self):
  879. client = Client()
  880. response = client.get('/customer/details/')
  881. self.assertEqual(response.status_code, 200)
  882. def test_index(self):
  883. client = Client()
  884. response = client.get('/customer/index/')
  885. self.assertEqual(response.status_code, 200)
  886. ...you can just refer to ``self.client``, like so::
  887. from django.test import TestCase
  888. class SimpleTest(TestCase):
  889. def test_details(self):
  890. response = self.client.get('/customer/details/')
  891. self.assertEqual(response.status_code, 200)
  892. def test_index(self):
  893. response = self.client.get('/customer/index/')
  894. self.assertEqual(response.status_code, 200)
  895. Customizing the test client
  896. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  897. .. versionadded:: 1.3
  898. .. attribute:: TestCase.client_class
  899. If you want to use a different ``Client`` class (for example, a subclass
  900. with customized behavior), use the :attr:`~TestCase.client_class` class
  901. attribute::
  902. from django.test import TestCase
  903. from django.test.client import Client
  904. class MyTestClient(Client):
  905. # Specialized methods for your environment...
  906. class MyTest(TestCase):
  907. client_class = MyTestClient
  908. def test_my_stuff(self):
  909. # Here self.client is an instance of MyTestClient...
  910. .. _topics-testing-fixtures:
  911. Fixture loading
  912. ~~~~~~~~~~~~~~~
  913. .. attribute:: TestCase.fixtures
  914. A test case for a database-backed Web site isn't much use if there isn't any
  915. data in the database. To make it easy to put test data into the database,
  916. Django's custom ``TestCase`` class provides a way of loading **fixtures**.
  917. A fixture is a collection of data that Django knows how to import into a
  918. database. For example, if your site has user accounts, you might set up a
  919. fixture of fake user accounts in order to populate your database during tests.
  920. The most straightforward way of creating a fixture is to use the
  921. :djadmin:`manage.py dumpdata <dumpdata>` command. This assumes you
  922. already have some data in your database. See the :djadmin:`dumpdata
  923. documentation<dumpdata>` for more details.
  924. .. note::
  925. If you've ever run :djadmin:`manage.py syncdb<syncdb>`, you've
  926. already used a fixture without even knowing it! When you call
  927. :djadmin:`syncdb` in the database for the first time, Django
  928. installs a fixture called ``initial_data``. This gives you a way
  929. of populating a new database with any initial data, such as a
  930. default set of categories.
  931. Fixtures with other names can always be installed manually using
  932. the :djadmin:`manage.py loaddata<loaddata>` command.
  933. .. admonition:: Initial SQL data and testing
  934. Django provides a second way to insert initial data into models --
  935. the :ref:`custom SQL hook <initial-sql>`. However, this technique
  936. *cannot* be used to provide initial data for testing purposes.
  937. Django's test framework flushes the contents of the test database
  938. after each test; as a result, any data added using the custom SQL
  939. hook will be lost.
  940. Once you've created a fixture and placed it in a ``fixtures`` directory in one
  941. of your :setting:`INSTALLED_APPS`, you can use it in your unit tests by
  942. specifying a ``fixtures`` class attribute on your :class:`django.test.TestCase`
  943. subclass::
  944. from django.test import TestCase
  945. from myapp.models import Animal
  946. class AnimalTestCase(TestCase):
  947. fixtures = ['mammals.json', 'birds']
  948. def setUp(self):
  949. # Test definitions as before.
  950. call_setup_methods()
  951. def testFluffyAnimals(self):
  952. # A test that uses the fixtures.
  953. call_some_test_code()
  954. Here's specifically what will happen:
  955. * At the start of each test case, before ``setUp()`` is run, Django will
  956. flush the database, returning the database to the state it was in
  957. directly after :djadmin:`syncdb` was called.
  958. * Then, all the named fixtures are installed. In this example, Django will
  959. install any JSON fixture named ``mammals``, followed by any fixture named
  960. ``birds``. See the :djadmin:`loaddata` documentation for more
  961. details on defining and installing fixtures.
  962. This flush/load procedure is repeated for each test in the test case, so you
  963. can be certain that the outcome of a test will not be affected by another test,
  964. or by the order of test execution.
  965. URLconf configuration
  966. ~~~~~~~~~~~~~~~~~~~~~
  967. .. attribute:: TestCase.urls
  968. If your application provides views, you may want to include tests that use the
  969. test client to exercise those views. However, an end user is free to deploy the
  970. views in your application at any URL of their choosing. This means that your
  971. tests can't rely upon the fact that your views will be available at a
  972. particular URL.
  973. In order to provide a reliable URL space for your test,
  974. ``django.test.TestCase`` provides the ability to customize the URLconf
  975. configuration for the duration of the execution of a test suite. If your
  976. ``TestCase`` instance defines an ``urls`` attribute, the ``TestCase`` will use
  977. the value of that attribute as the :setting:`ROOT_URLCONF` for the duration
  978. of that test.
  979. For example::
  980. from django.test import TestCase
  981. class TestMyViews(TestCase):
  982. urls = 'myapp.test_urls'
  983. def testIndexPageView(self):
  984. # Here you'd test your view using ``Client``.
  985. call_some_test_code()
  986. This test case will use the contents of ``myapp.test_urls`` as the
  987. URLconf for the duration of the test case.
  988. .. _emptying-test-outbox:
  989. Multi-database support
  990. ~~~~~~~~~~~~~~~~~~~~~~
  991. .. attribute:: TestCase.multi_db
  992. .. versionadded:: 1.2
  993. Django sets up a test database corresponding to every database that is
  994. defined in the :setting:`DATABASES` definition in your settings
  995. file. However, a big part of the time taken to run a Django TestCase
  996. is consumed by the call to ``flush`` that ensures that you have a
  997. clean database at the start of each test run. If you have multiple
  998. databases, multiple flushes are required (one for each database),
  999. which can be a time consuming activity -- especially if your tests
  1000. don't need to test multi-database activity.
  1001. As an optimization, Django only flushes the ``default`` database at
  1002. the start of each test run. If your setup contains multiple databases,
  1003. and you have a test that requires every database to be clean, you can
  1004. use the ``multi_db`` attribute on the test suite to request a full
  1005. flush.
  1006. For example::
  1007. class TestMyViews(TestCase):
  1008. multi_db = True
  1009. def testIndexPageView(self):
  1010. call_some_test_code()
  1011. This test case will flush *all* the test databases before running
  1012. ``testIndexPageView``.
  1013. .. _overriding-settings:
  1014. Overriding settings
  1015. ~~~~~~~~~~~~~~~~~~~
  1016. .. method:: TestCase.settings
  1017. .. versionadded:: 1.4
  1018. For testing purposes it's often useful to change a setting temporarily and
  1019. revert to the original value after running the testing code. For this use case
  1020. Django provides a standard Python context manager (see :pep:`343`)
  1021. :meth:`~django.test.TestCase.settings`, which can be used like this::
  1022. from django.test import TestCase
  1023. class LoginTestCase(TestCase):
  1024. def test_login(self):
  1025. # First check for the default behavior
  1026. response = self.client.get('/sekrit/')
  1027. self.assertRedirects(response, '/accounts/login/?next=/sekrit/')
  1028. # Then override the LOGIN_URL setting
  1029. with self.settings(LOGIN_URL='/other/login/'):
  1030. response = self.client.get('/sekrit/')
  1031. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  1032. This example will override the :setting:`LOGIN_URL` setting for the code
  1033. in the ``with`` block and reset its value to the previous state afterwards.
  1034. .. currentmodule:: django.test.utils
  1035. .. function:: override_settings
  1036. In case you want to override a setting for just one test method or even the
  1037. whole :class:`TestCase` class, Django provides the
  1038. :func:`~django.test.utils.override_settings` decorator (see :pep:`318`). It's
  1039. used like this::
  1040. from django.test import TestCase
  1041. from django.test.utils import override_settings
  1042. class LoginTestCase(TestCase):
  1043. @override_settings(LOGIN_URL='/other/login/')
  1044. def test_login(self):
  1045. response = self.client.get('/sekrit/')
  1046. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  1047. The decorator can also be applied to test case classes::
  1048. from django.test import TestCase
  1049. from django.test.utils import override_settings
  1050. class LoginTestCase(TestCase):
  1051. def test_login(self):
  1052. response = self.client.get('/sekrit/')
  1053. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  1054. LoginTestCase = override_settings(LOGIN_URL='/other/login/')(LoginTestCase)
  1055. On Python 2.6 and higher you can also use the well known decorator syntax to
  1056. decorate the class::
  1057. from django.test import TestCase
  1058. from django.test.utils import override_settings
  1059. @override_settings(LOGIN_URL='/other/login/')
  1060. class LoginTestCase(TestCase):
  1061. def test_login(self):
  1062. response = self.client.get('/sekrit/')
  1063. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  1064. .. note::
  1065. When overriding settings make sure to also handle the cases in which
  1066. Django or your app's code uses a cache or similar feature that retains
  1067. state even if the setting is changed. Django provides the
  1068. :data:`django.test.signals.setting_changed` signal to connect cleanup
  1069. and other state-resetting callbacks to.
  1070. Emptying the test outbox
  1071. ~~~~~~~~~~~~~~~~~~~~~~~~
  1072. If you use Django's custom ``TestCase`` class, the test runner will clear the
  1073. contents of the test email outbox at the start of each test case.
  1074. For more detail on email services during tests, see `Email services`_.
  1075. .. _assertions:
  1076. Assertions
  1077. ~~~~~~~~~~
  1078. .. currentmodule:: django.test
  1079. .. versionchanged:: 1.2
  1080. Addded ``msg_prefix`` argument.
  1081. As Python's normal :class:`unittest.TestCase` class implements assertion methods
  1082. such as :meth:`~unittest.TestCase.assertTrue` and
  1083. :meth:`~unittest.TestCase.assertEqual`, Django's custom :class:`TestCase` class
  1084. provides a number of custom assertion methods that are useful for testing Web
  1085. applications:
  1086. The failure messages given by most of these assertion methods can be customized
  1087. with the ``msg_prefix`` argument. This string will be prefixed to any failure
  1088. message generated by the assertion. This allows you to provide additional
  1089. details that may help you to identify the location and cause of an failure in
  1090. your test suite.
  1091. .. method:: TestCase.assertRaisesMessage(expected_exception, expected_message, callable_obj=None, *args, **kwargs)
  1092. Asserts that execution of callable ``callable_obj`` raised the
  1093. ``expected_exception`` exception and that such exception has an
  1094. ``expected_message`` representation. Any other outcome is reported as a
  1095. failure. Similar to unittest's :meth:`~unittest.TestCase.assertRaisesRegexp`
  1096. with the difference that ``expected_message`` isn't a regular expression.
  1097. .. method:: assertFieldOutput(self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value=u'')
  1098. Asserts that a form field behaves correctly with various inputs.
  1099. :param fieldclass: the class of the field to be tested.
  1100. :param valid: a dictionary mapping valid inputs to their expected cleaned
  1101. values.
  1102. :param invalid: a dictionary mapping invalid inputs to one or more raised
  1103. error messages.
  1104. :param field_args: the args passed to instantiate the field.
  1105. :param field_kwargs: the kwargs passed to instantiate the field.
  1106. :param empty_value: the expected clean output for inputs in ``EMPTY_VALUES``.
  1107. For example, the following code tests that an ``EmailField`` accepts
  1108. "a@a.com" as a valid email address, but rejects "aaa" with a reasonable
  1109. error message::
  1110. self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': [u'Enter a valid e-mail address.']})
  1111. .. method:: TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='')
  1112. Asserts that a ``Response`` instance produced the given ``status_code`` and
  1113. that ``text`` appears in the content of the response. If ``count`` is
  1114. provided, ``text`` must occur exactly ``count`` times in the response.
  1115. .. method:: TestCase.assertNotContains(response, text, status_code=200, msg_prefix='')
  1116. Asserts that a ``Response`` instance produced the given ``status_code`` and
  1117. that ``text`` does not appears in the content of the response.
  1118. .. method:: TestCase.assertFormError(response, form, field, errors, msg_prefix='')
  1119. Asserts that a field on a form raises the provided list of errors when
  1120. rendered on the form.
  1121. ``form`` is the name the ``Form`` instance was given in the template
  1122. context.
  1123. ``field`` is the name of the field on the form to check. If ``field``
  1124. has a value of ``None``, non-field errors (errors you can access via
  1125. ``form.non_field_errors()``) will be checked.
  1126. ``errors`` is an error string, or a list of error strings, that are
  1127. expected as a result of form validation.
  1128. .. method:: TestCase.assertTemplateUsed(response, template_name, msg_prefix='')
  1129. Asserts that the template with the given name was used in rendering the
  1130. response.
  1131. The name is a string such as ``'admin/index.html'``.
  1132. .. method:: TestCase.assertTemplateNotUsed(response, template_name, msg_prefix='')
  1133. Asserts that the template with the given name was *not* used in rendering
  1134. the response.
  1135. .. method:: TestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='')
  1136. Asserts that the response return a ``status_code`` redirect status, it
  1137. redirected to ``expected_url`` (including any GET data), and the final
  1138. page was received with ``target_status_code``.
  1139. If your request used the ``follow`` argument, the ``expected_url`` and
  1140. ``target_status_code`` will be the url and status code for the final
  1141. point of the redirect chain.
  1142. .. method:: TestCase.assertQuerysetEqual(qs, values, transform=repr, ordered=True)
  1143. .. versionadded:: 1.3
  1144. Asserts that a queryset ``qs`` returns a particular list of values ``values``.
  1145. The comparison of the contents of ``qs`` and ``values`` is performed using
  1146. the function ``transform``; by default, this means that the ``repr()`` of
  1147. each value is compared. Any other callable can be used if ``repr()`` doesn't
  1148. provide a unique or helpful comparison.
  1149. By default, the comparison is also ordering dependent. If ``qs`` doesn't
  1150. provide an implicit ordering, you can set the ``ordered`` parameter to
  1151. ``False``, which turns the comparison into a Python set comparison.
  1152. .. versionchanged:: 1.4
  1153. The ``ordered`` parameter is new in version 1.4. In earlier versions,
  1154. you would need to ensure the queryset is ordered consistently, possibly
  1155. via an explicit ``order_by()`` call on the queryset prior to
  1156. comparison.
  1157. .. method:: TestCase.assertNumQueries(num, func, *args, **kwargs)
  1158. .. versionadded:: 1.3
  1159. Asserts that when ``func`` is called with ``*args`` and ``**kwargs`` that
  1160. ``num`` database queries are executed.
  1161. If a ``"using"`` key is present in ``kwargs`` it is used as the database
  1162. alias for which to check the number of queries. If you wish to call a
  1163. function with a ``using`` parameter you can do it by wrapping the call with
  1164. a ``lambda`` to add an extra parameter::
  1165. self.assertNumQueries(7, lambda: my_function(using=7))
  1166. If you're using Python 2.5 or greater you can also use this as a context
  1167. manager::
  1168. # This is necessary in Python 2.5 to enable the with statement, in 2.6
  1169. # and up it is no longer necessary.
  1170. from __future__ import with_statement
  1171. with self.assertNumQueries(2):
  1172. Person.objects.create(name="Aaron")
  1173. Person.objects.create(name="Daniel")
  1174. .. _topics-testing-email:
  1175. Email services
  1176. --------------
  1177. If any of your Django views send email using :doc:`Django's email
  1178. functionality </topics/email>`, you probably don't want to send email each time
  1179. you run a test using that view. For this reason, Django's test runner
  1180. automatically redirects all Django-sent email to a dummy outbox. This lets you
  1181. test every aspect of sending email -- from the number of messages sent to the
  1182. contents of each message -- without actually sending the messages.
  1183. The test runner accomplishes this by transparently replacing the normal
  1184. email backend with a testing backend.
  1185. (Don't worry -- this has no effect on any other email senders outside of
  1186. Django, such as your machine's mail server, if you're running one.)
  1187. .. currentmodule:: django.core.mail
  1188. .. data:: django.core.mail.outbox
  1189. During test running, each outgoing email is saved in
  1190. ``django.core.mail.outbox``. This is a simple list of all
  1191. :class:`~django.core.mail.EmailMessage` instances that have been sent.
  1192. The ``outbox`` attribute is a special attribute that is created *only* when
  1193. the ``locmem`` email backend is used. It doesn't normally exist as part of the
  1194. :mod:`django.core.mail` module and you can't import it directly. The code
  1195. below shows how to access this attribute correctly.
  1196. Here's an example test that examines ``django.core.mail.outbox`` for length
  1197. and contents::
  1198. from django.core import mail
  1199. from django.test import TestCase
  1200. class EmailTest(TestCase):
  1201. def test_send_email(self):
  1202. # Send message.
  1203. mail.send_mail('Subject here', 'Here is the message.',
  1204. 'from@example.com', ['to@example.com'],
  1205. fail_silently=False)
  1206. # Test that one message has been sent.
  1207. self.assertEqual(len(mail.outbox), 1)
  1208. # Verify that the subject of the first message is correct.
  1209. self.assertEqual(mail.outbox[0].subject, 'Subject here')
  1210. As noted :ref:`previously <emptying-test-outbox>`, the test outbox is emptied
  1211. at the start of every test in a Django ``TestCase``. To empty the outbox
  1212. manually, assign the empty list to ``mail.outbox``::
  1213. from django.core import mail
  1214. # Empty the test outbox
  1215. mail.outbox = []
  1216. .. _skipping-tests:
  1217. Skipping tests
  1218. --------------
  1219. .. currentmodule:: django.test
  1220. .. versionadded:: 1.3
  1221. The unittest library provides the :func:`@skipIf <unittest.skipIf>` and
  1222. :func:`@skipUnless <unittest.skipUnless>` decorators to allow you to skip tests
  1223. if you know ahead of time that those tests are going to fail under certain
  1224. conditions.
  1225. For example, if your test requires a particular optional library in order to
  1226. succeed, you could decorate the test case with :func:`@skipIf
  1227. <unittest.skipIf>`. Then, the test runner will report that the test wasn't
  1228. executed and why, instead of failing the test or omitting the test altogether.
  1229. To supplement these test skipping behaviors, Django provides two
  1230. additional skip decorators. Instead of testing a generic boolean,
  1231. these decorators check the capabilities of the database, and skip the
  1232. test if the database doesn't support a specific named feature.
  1233. The decorators use a string identifier to describe database features.
  1234. This string corresponds to attributes of the database connection
  1235. features class. See :class:`~django.db.backends.BaseDatabaseFeatures`
  1236. class for a full list of database features that can be used as a basis
  1237. for skipping tests.
  1238. .. function:: skipIfDBFeature(feature_name_string)
  1239. Skip the decorated test if the named database feature is supported.
  1240. For example, the following test will not be executed if the database
  1241. supports transactions (e.g., it would *not* run under PostgreSQL, but
  1242. it would under MySQL with MyISAM tables)::
  1243. class MyTests(TestCase):
  1244. @skipIfDBFeature('supports_transactions')
  1245. def test_transaction_behavior(self):
  1246. # ... conditional test code
  1247. .. function:: skipUnlessDBFeature(feature_name_string)
  1248. Skip the decorated test if the named database feature is *not*
  1249. supported.
  1250. For example, the following test will not be executed if the database
  1251. supports transactions (e.g., it would run under PostgreSQL, but *not*
  1252. under MySQL with MyISAM tables)::
  1253. class MyTests(TestCase):
  1254. @skipUnlessDBFeature('supports_transactions')
  1255. def test_transaction_behavior(self):
  1256. # ... conditional test code
  1257. Using different testing frameworks
  1258. ==================================
  1259. Clearly, :mod:`doctest` and :mod:`unittest` are not the only Python testing
  1260. frameworks. While Django doesn't provide explicit support for alternative
  1261. frameworks, it does provide a way to invoke tests constructed for an
  1262. alternative framework as if they were normal Django tests.
  1263. When you run ``./manage.py test``, Django looks at the :setting:`TEST_RUNNER`
  1264. setting to determine what to do. By default, :setting:`TEST_RUNNER` points to
  1265. ``'django.test.simple.DjangoTestSuiteRunner'``. This class defines the default Django
  1266. testing behavior. This behavior involves:
  1267. #. Performing global pre-test setup.
  1268. #. Looking for unit tests and doctests in the ``models.py`` and
  1269. ``tests.py`` files in each installed application.
  1270. #. Creating the test databases.
  1271. #. Running ``syncdb`` to install models and initial data into the test
  1272. databases.
  1273. #. Running the unit tests and doctests that are found.
  1274. #. Destroying the test databases.
  1275. #. Performing global post-test teardown.
  1276. If you define your own test runner class and point :setting:`TEST_RUNNER` at
  1277. that class, Django will execute your test runner whenever you run
  1278. ``./manage.py test``. In this way, it is possible to use any test framework
  1279. that can be executed from Python code, or to modify the Django test execution
  1280. process to satisfy whatever testing requirements you may have.
  1281. .. _topics-testing-test_runner:
  1282. Defining a test runner
  1283. ----------------------
  1284. .. versionchanged:: 1.2
  1285. Prior to 1.2, test runners were a single function, not a class.
  1286. .. currentmodule:: django.test.simple
  1287. A test runner is a class defining a ``run_tests()`` method. Django ships
  1288. with a ``DjangoTestSuiteRunner`` class that defines the default Django
  1289. testing behavior. This class defines the ``run_tests()`` entry point,
  1290. plus a selection of other methods that are used to by ``run_tests()`` to
  1291. set up, execute and tear down the test suite.
  1292. .. class:: DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=True, **kwargs)
  1293. ``verbosity`` determines the amount of notification and debug information
  1294. that will be printed to the console; ``0`` is no output, ``1`` is normal
  1295. output, and ``2`` is verbose output.
  1296. If ``interactive`` is ``True``, the test suite has permission to ask the
  1297. user for instructions when the test suite is executed. An example of this
  1298. behavior would be asking for permission to delete an existing test
  1299. database. If ``interactive`` is ``False``, the test suite must be able to
  1300. run without any manual intervention.
  1301. If ``failfast`` is ``True``, the test suite will stop running after the
  1302. first test failure is detected.
  1303. Django will, from time to time, extend the capabilities of
  1304. the test runner by adding new arguments. The ``**kwargs`` declaration
  1305. allows for this expansion. If you subclass ``DjangoTestSuiteRunner`` or
  1306. write your own test runner, ensure accept and handle the ``**kwargs``
  1307. parameter.
  1308. .. versionadded:: 1.4
  1309. Your test runner may also define additional command-line options.
  1310. If you add an ``option_list`` attribute to a subclassed test runner,
  1311. those options will be added to the list of command-line options that
  1312. the :djadmin:`test` command can use.
  1313. Attributes
  1314. ~~~~~~~~~~
  1315. .. attribute:: DjangoTestSuiteRunner.option_list
  1316. .. versionadded:: 1.4
  1317. This is the tuple of ``optparse`` options which will be fed into the
  1318. management command's ``OptionParser`` for parsing arguments. See the
  1319. documentation for Python's ``optparse`` module for more details.
  1320. Methods
  1321. ~~~~~~~
  1322. .. method:: DjangoTestSuiteRunner.run_tests(test_labels, extra_tests=None, **kwargs)
  1323. Run the test suite.
  1324. ``test_labels`` is a list of strings describing the tests to be run. A test
  1325. label can take one of three forms:
  1326. * ``app.TestCase.test_method`` -- Run a single test method in a test
  1327. case.
  1328. * ``app.TestCase`` -- Run all the test methods in a test case.
  1329. * ``app`` -- Search for and run all tests in the named application.
  1330. If ``test_labels`` has a value of ``None``, the test runner should run
  1331. search for tests in all the applications in :setting:`INSTALLED_APPS`.
  1332. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  1333. suite that is executed by the test runner. These extra tests are run
  1334. in addition to those discovered in the modules listed in ``test_labels``.
  1335. This method should return the number of tests that failed.
  1336. .. method:: DjangoTestSuiteRunner.setup_test_environment(**kwargs)
  1337. Sets up the test environment ready for testing.
  1338. .. method:: DjangoTestSuiteRunner.build_suite(test_labels, extra_tests=None, **kwargs)
  1339. Constructs a test suite that matches the test labels provided.
  1340. ``test_labels`` is a list of strings describing the tests to be run. A test
  1341. label can take one of three forms:
  1342. * ``app.TestCase.test_method`` -- Run a single test method in a test
  1343. case.
  1344. * ``app.TestCase`` -- Run all the test methods in a test case.
  1345. * ``app`` -- Search for and run all tests in the named application.
  1346. If ``test_labels`` has a value of ``None``, the test runner should run
  1347. search for tests in all the applications in :setting:`INSTALLED_APPS`.
  1348. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  1349. suite that is executed by the test runner. These extra tests are run
  1350. in addition to those discovered in the modules listed in ``test_labels``.
  1351. Returns a ``TestSuite`` instance ready to be run.
  1352. .. method:: DjangoTestSuiteRunner.setup_databases(**kwargs)
  1353. Creates the test databases.
  1354. Returns a data structure that provides enough detail to undo the changes
  1355. that have been made. This data will be provided to the ``teardown_databases()``
  1356. function at the conclusion of testing.
  1357. .. method:: DjangoTestSuiteRunner.run_suite(suite, **kwargs)
  1358. Runs the test suite.
  1359. Returns the result produced by the running the test suite.
  1360. .. method:: DjangoTestSuiteRunner.teardown_databases(old_config, **kwargs)
  1361. Destroys the test databases, restoring pre-test conditions.
  1362. ``old_config`` is a data structure defining the changes in the
  1363. database configuration that need to be reversed. It is the return
  1364. value of the ``setup_databases()`` method.
  1365. .. method:: DjangoTestSuiteRunner.teardown_test_environment(**kwargs)
  1366. Restores the pre-test environment.
  1367. .. method:: DjangoTestSuiteRunner.suite_result(suite, result, **kwargs)
  1368. Computes and returns a return code based on a test suite, and the result
  1369. from that test suite.
  1370. Testing utilities
  1371. -----------------
  1372. .. module:: django.test.utils
  1373. :synopsis: Helpers to write custom test runners.
  1374. To assist in the creation of your own test runner, Django provides a number of
  1375. utility methods in the ``django.test.utils`` module.
  1376. .. function:: setup_test_environment()
  1377. Performs any global pre-test setup, such as the installing the
  1378. instrumentation of the template rendering system and setting up
  1379. the dummy ``SMTPConnection``.
  1380. .. function:: teardown_test_environment()
  1381. Performs any global post-test teardown, such as removing the black
  1382. magic hooks into the template system and restoring normal email
  1383. services.
  1384. .. currentmodule:: django.db.connection.creation
  1385. The creation module of the database backend (``connection.creation``)
  1386. also provides some utilities that can be useful during testing.
  1387. .. function:: create_test_db([verbosity=1, autoclobber=False])
  1388. Creates a new test database and runs ``syncdb`` against it.
  1389. ``verbosity`` has the same behavior as in ``run_tests()``.
  1390. ``autoclobber`` describes the behavior that will occur if a
  1391. database with the same name as the test database is discovered:
  1392. * If ``autoclobber`` is ``False``, the user will be asked to
  1393. approve destroying the existing database. ``sys.exit`` is
  1394. called if the user does not approve.
  1395. * If autoclobber is ``True``, the database will be destroyed
  1396. without consulting the user.
  1397. Returns the name of the test database that it created.
  1398. ``create_test_db()`` has the side effect of modifying the value of
  1399. :setting:`NAME` in :setting:`DATABASES` to match the name of the test
  1400. database.
  1401. .. function:: destroy_test_db(old_database_name, [verbosity=1])
  1402. Destroys the database whose name is the value of :setting:`NAME` in
  1403. :setting:`DATABASES`, and sets :setting:`NAME` to the value of
  1404. ``old_database_name``.
  1405. The ``verbosity`` argument has the same behavior as for
  1406. :class:`~django.test.simple.DjangoTestSuiteRunner`.