testing.txt 85 KB

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