overview.txt 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784
  1. ===========================
  2. Testing Django applications
  3. ===========================
  4. .. module:: django.test
  5. :synopsis: Testing tools for Django applications.
  6. .. seealso::
  7. The :doc:`testing tutorial </intro/tutorial05>` and the
  8. :doc:`advanced testing topics </topics/testing/advanced>`.
  9. This document is split into two primary sections. First, we explain how to write
  10. tests with Django. Then, we explain how to run them.
  11. Writing tests
  12. =============
  13. Django's unit tests use a Python standard library module: :mod:`unittest`. This
  14. module defines tests in class-based approach.
  15. .. admonition:: unittest2
  16. Python 2.7 introduced some major changes to the unittest library,
  17. adding some extremely useful features. To ensure that every Django
  18. project can benefit from these new features, Django ships with a
  19. copy of unittest2_, a copy of the Python 2.7 unittest library,
  20. backported for Python 2.5 compatibility.
  21. To access this library, Django provides the
  22. :mod:`django.utils.unittest` module alias. If you are using Python
  23. 2.7, or you have installed unittest2 locally, Django will map the
  24. alias to the installed version of the unittest library. Otherwise,
  25. Django will use its own bundled version of unittest2.
  26. To use this alias, simply use::
  27. from django.utils import unittest
  28. wherever you would have historically used::
  29. import unittest
  30. If you want to continue to use the base unittest library, you can --
  31. you just won't get any of the nice new unittest2 features.
  32. .. _unittest2: http://pypi.python.org/pypi/unittest2
  33. For a given Django application, the test runner looks for unit tests in two
  34. places:
  35. * The ``models.py`` file. The test runner looks for any subclass of
  36. :class:`unittest.TestCase` in this module.
  37. * A file called ``tests.py`` in the application directory -- i.e., the
  38. directory that holds ``models.py``. Again, the test runner looks for any
  39. subclass of :class:`unittest.TestCase` in this module.
  40. Here is an example :class:`unittest.TestCase` subclass::
  41. from django.utils import unittest
  42. from myapp.models import Animal
  43. class AnimalTestCase(unittest.TestCase):
  44. def setUp(self):
  45. self.lion = Animal(name="lion", sound="roar")
  46. self.cat = Animal(name="cat", sound="meow")
  47. def test_animals_can_speak(self):
  48. """Animals that can speak are correctly identified"""
  49. self.assertEqual(self.lion.speak(), 'The lion says "roar"')
  50. self.assertEqual(self.cat.speak(), 'The cat says "meow"')
  51. When you :ref:`run your tests <running-tests>`, the default behavior of the test
  52. utility is to find all the test cases (that is, subclasses of
  53. :class:`unittest.TestCase`) in ``models.py`` and ``tests.py``, automatically
  54. build a test suite out of those test cases, and run that suite.
  55. There is a second way to define the test suite for a module: if you define a
  56. function called ``suite()`` in either ``models.py`` or ``tests.py``, the
  57. Django test runner will use that function to construct the test suite for that
  58. module. This follows the `suggested organization`_ for unit tests. See the
  59. Python documentation for more details on how to construct a complex test
  60. suite.
  61. For more details about :mod:`unittest`, see the Python documentation.
  62. .. _suggested organization: http://docs.python.org/library/unittest.html#organizing-tests
  63. .. warning::
  64. If your tests rely on database access such as creating or querying models,
  65. be sure to create your test classes as subclasses of
  66. :class:`django.test.TestCase` rather than :class:`unittest.TestCase`.
  67. In the example above, we instantiate some models but do not save them to
  68. the database. Using :class:`unittest.TestCase` avoids the cost of running
  69. each test in a transaction and flushing the database, but for most
  70. applications the scope of tests you will be able to write this way will
  71. be fairly limited, so it's easiest to use :class:`django.test.TestCase`.
  72. .. _running-tests:
  73. Running tests
  74. =============
  75. Once you've written tests, run them using the :djadmin:`test` command of
  76. your project's ``manage.py`` utility::
  77. $ ./manage.py test
  78. By default, this will run every test in every application in
  79. :setting:`INSTALLED_APPS`. If you only want to run tests for a particular
  80. application, add the application name to the command line. For example, if your
  81. :setting:`INSTALLED_APPS` contains ``'myproject.polls'`` and
  82. ``'myproject.animals'``, you can run the ``myproject.animals`` unit tests alone
  83. with this command::
  84. $ ./manage.py test animals
  85. Note that we used ``animals``, not ``myproject.animals``.
  86. You can be even *more* specific by naming an individual test case. To
  87. run a single test case in an application (for example, the
  88. ``AnimalTestCase`` described in the "Writing unit tests" section), add
  89. the name of the test case to the label on the command line::
  90. $ ./manage.py test animals.AnimalTestCase
  91. And it gets even more granular than that! To run a *single* test
  92. method inside a test case, add the name of the test method to the
  93. label::
  94. $ ./manage.py test animals.AnimalTestCase.test_animals_can_speak
  95. You can use the same rules if you're using doctests. Django will use the
  96. test label as a path to the test method or class that you want to run.
  97. If your ``models.py`` or ``tests.py`` has a function with a doctest, or
  98. class with a class-level doctest, you can invoke that test by appending the
  99. name of the test method or class to the label::
  100. $ ./manage.py test animals.classify
  101. If you want to run the doctest for a specific method in a class, add the
  102. name of the method to the label::
  103. $ ./manage.py test animals.Classifier.run
  104. If you're using a ``__test__`` dictionary to specify doctests for a
  105. module, Django will use the label as a key in the ``__test__`` dictionary
  106. for defined in ``models.py`` and ``tests.py``.
  107. If you press ``Ctrl-C`` while the tests are running, the test runner will
  108. wait for the currently running test to complete and then exit gracefully.
  109. During a graceful exit the test runner will output details of any test
  110. failures, report on how many tests were run and how many errors and failures
  111. were encountered, and destroy any test databases as usual. Thus pressing
  112. ``Ctrl-C`` can be very useful if you forget to pass the :djadminopt:`--failfast`
  113. option, notice that some tests are unexpectedly failing, and want to get details
  114. on the failures without waiting for the full test run to complete.
  115. If you do not want to wait for the currently running test to finish, you
  116. can press ``Ctrl-C`` a second time and the test run will halt immediately,
  117. but not gracefully. No details of the tests run before the interruption will
  118. be reported, and any test databases created by the run will not be destroyed.
  119. .. admonition:: Test with warnings enabled
  120. It's a good idea to run your tests with Python warnings enabled:
  121. ``python -Wall manage.py test``. The ``-Wall`` flag tells Python to
  122. display deprecation warnings. Django, like many other Python libraries,
  123. uses these warnings to flag when features are going away. It also might
  124. flag areas in your code that aren't strictly wrong but could benefit
  125. from a better implementation.
  126. .. _the-test-database:
  127. The test database
  128. -----------------
  129. Tests that require a database (namely, model tests) will not use your "real"
  130. (production) database. Separate, blank databases are created for the tests.
  131. Regardless of whether the tests pass or fail, the test databases are destroyed
  132. when all the tests have been executed.
  133. By default the test databases get their names by prepending ``test_``
  134. to the value of the :setting:`NAME` settings for the databases
  135. defined in :setting:`DATABASES`. When using the SQLite database engine
  136. the tests will by default use an in-memory database (i.e., the
  137. database will be created in memory, bypassing the filesystem
  138. entirely!). If you want to use a different database name, specify
  139. :setting:`TEST_NAME` in the dictionary for any given database in
  140. :setting:`DATABASES`.
  141. Aside from using a separate database, the test runner will otherwise
  142. use all of the same database settings you have in your settings file:
  143. :setting:`ENGINE <DATABASE-ENGINE>`, :setting:`USER`, :setting:`HOST`, etc. The
  144. test database is created by the user specified by :setting:`USER`, so you'll
  145. need to make sure that the given user account has sufficient privileges to
  146. create a new database on the system.
  147. For fine-grained control over the character encoding of your test
  148. database, use the :setting:`TEST_CHARSET` option. If you're using
  149. MySQL, you can also use the :setting:`TEST_COLLATION` option to
  150. control the particular collation used by the test database. See the
  151. :doc:`settings documentation </ref/settings>` for details of these
  152. advanced settings.
  153. .. admonition:: Finding data from your production database when running tests?
  154. If your code attempts to access the database when its modules are compiled,
  155. this will occur *before* the test database is set up, with potentially
  156. unexpected results. For example, if you have a database query in
  157. module-level code and a real database exists, production data could pollute
  158. your tests. *It is a bad idea to have such import-time database queries in
  159. your code* anyway - rewrite your code so that it doesn't do this.
  160. .. seealso::
  161. The :ref:`advanced multi-db testing topics <topics-testing-advanced-multidb>`.
  162. Order in which tests are executed
  163. ---------------------------------
  164. In order to guarantee that all ``TestCase`` code starts with a clean database,
  165. the Django test runner reorders tests in the following way:
  166. * First, all unittests (including :class:`unittest.TestCase`,
  167. :class:`~django.test.SimpleTestCase`, :class:`~django.test.TestCase` and
  168. :class:`~django.test.TransactionTestCase`) are run with no particular ordering
  169. guaranteed nor enforced among them.
  170. * Then any other tests (e.g. doctests) that may alter the database without
  171. restoring it to its original state are run.
  172. .. versionchanged:: 1.5
  173. Before Django 1.5, the only guarantee was that
  174. :class:`~django.test.TestCase` tests were always ran first, before any other
  175. tests.
  176. .. note::
  177. The new ordering of tests may reveal unexpected dependencies on test case
  178. ordering. This is the case with doctests that relied on state left in the
  179. database by a given :class:`~django.test.TransactionTestCase` test, they
  180. must be updated to be able to run independently.
  181. Other test conditions
  182. ---------------------
  183. Regardless of the value of the :setting:`DEBUG` setting in your configuration
  184. file, all Django tests run with :setting:`DEBUG`\=False. This is to ensure that
  185. the observed output of your code matches what will be seen in a production
  186. setting.
  187. Caches are not cleared after each test, and running "manage.py test fooapp" can
  188. insert data from the tests into the cache of a live system if you run your
  189. tests in production because, unlike databases, a separate "test cache" is not
  190. used. This behavior `may change`_ in the future.
  191. .. _may change: https://code.djangoproject.com/ticket/11505
  192. Understanding the test output
  193. -----------------------------
  194. When you run your tests, you'll see a number of messages as the test runner
  195. prepares itself. You can control the level of detail of these messages with the
  196. ``verbosity`` option on the command line::
  197. Creating test database...
  198. Creating table myapp_animal
  199. Creating table myapp_mineral
  200. Loading 'initial_data' fixtures...
  201. No fixtures found.
  202. This tells you that the test runner is creating a test database, as described
  203. in the previous section.
  204. Once the test database has been created, Django will run your tests.
  205. If everything goes well, you'll see something like this::
  206. ----------------------------------------------------------------------
  207. Ran 22 tests in 0.221s
  208. OK
  209. If there are test failures, however, you'll see full details about which tests
  210. failed::
  211. ======================================================================
  212. FAIL: Doctest: ellington.core.throttle.models
  213. ----------------------------------------------------------------------
  214. Traceback (most recent call last):
  215. File "/dev/django/test/doctest.py", line 2153, in runTest
  216. raise self.failureException(self.format_failure(new.getvalue()))
  217. AssertionError: Failed doctest test for myapp.models
  218. File "/dev/myapp/models.py", line 0, in models
  219. ----------------------------------------------------------------------
  220. File "/dev/myapp/models.py", line 14, in myapp.models
  221. Failed example:
  222. throttle.check("actor A", "action one", limit=2, hours=1)
  223. Expected:
  224. True
  225. Got:
  226. False
  227. ----------------------------------------------------------------------
  228. Ran 2 tests in 0.048s
  229. FAILED (failures=1)
  230. A full explanation of this error output is beyond the scope of this document,
  231. but it's pretty intuitive. You can consult the documentation of Python's
  232. :mod:`unittest` library for details.
  233. Note that the return code for the test-runner script is 1 for any number of
  234. failed and erroneous tests. If all the tests pass, the return code is 0. This
  235. feature is useful if you're using the test-runner script in a shell script and
  236. need to test for success or failure at that level.
  237. Speeding up the tests
  238. ---------------------
  239. In recent versions of Django, the default password hasher is rather slow by
  240. design. If during your tests you are authenticating many users, you may want
  241. to use a custom settings file and set the :setting:`PASSWORD_HASHERS` setting
  242. to a faster hashing algorithm::
  243. PASSWORD_HASHERS = (
  244. 'django.contrib.auth.hashers.MD5PasswordHasher',
  245. )
  246. Don't forget to also include in :setting:`PASSWORD_HASHERS` any hashing
  247. algorithm used in fixtures, if any.
  248. Testing tools
  249. =============
  250. Django provides a small set of tools that come in handy when writing tests.
  251. .. _test-client:
  252. The test client
  253. ---------------
  254. .. module:: django.test.client
  255. :synopsis: Django's test client.
  256. The test client is a Python class that acts as a dummy Web browser, allowing
  257. you to test your views and interact with your Django-powered application
  258. programmatically.
  259. Some of the things you can do with the test client are:
  260. * Simulate GET and POST requests on a URL and observe the response --
  261. everything from low-level HTTP (result headers and status codes) to
  262. page content.
  263. * Test that the correct view is executed for a given URL.
  264. * Test that a given request is rendered by a given Django template, with
  265. a template context that contains certain values.
  266. Note that the test client is not intended to be a replacement for Selenium_ or
  267. other "in-browser" frameworks. Django's test client has a different focus. In
  268. short:
  269. * Use Django's test client to establish that the correct view is being
  270. called and that the view is collecting the correct context data.
  271. * Use in-browser frameworks like Selenium_ to test *rendered* HTML and the
  272. *behavior* of Web pages, namely JavaScript functionality. Django also
  273. provides special support for those frameworks; see the section on
  274. :class:`~django.test.LiveServerTestCase` for more details.
  275. A comprehensive test suite should use a combination of both test types.
  276. Overview and a quick example
  277. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  278. To use the test client, instantiate ``django.test.client.Client`` and retrieve
  279. Web pages::
  280. >>> from django.test.client import Client
  281. >>> c = Client()
  282. >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
  283. >>> response.status_code
  284. 200
  285. >>> response = c.get('/customer/details/')
  286. >>> response.content
  287. '<!DOCTYPE html...'
  288. As this example suggests, you can instantiate ``Client`` from within a session
  289. of the Python interactive interpreter.
  290. Note a few important things about how the test client works:
  291. * The test client does *not* require the Web server to be running. In fact,
  292. it will run just fine with no Web server running at all! That's because
  293. it avoids the overhead of HTTP and deals directly with the Django
  294. framework. This helps make the unit tests run quickly.
  295. * When retrieving pages, remember to specify the *path* of the URL, not the
  296. whole domain. For example, this is correct::
  297. >>> c.get('/login/')
  298. This is incorrect::
  299. >>> c.get('http://www.example.com/login/')
  300. The test client is not capable of retrieving Web pages that are not
  301. powered by your Django project. If you need to retrieve other Web pages,
  302. use a Python standard library module such as :mod:`urllib` or
  303. :mod:`urllib2`.
  304. * To resolve URLs, the test client uses whatever URLconf is pointed-to by
  305. your :setting:`ROOT_URLCONF` setting.
  306. * Although the above example would work in the Python interactive
  307. interpreter, some of the test client's functionality, notably the
  308. template-related functionality, is only available *while tests are
  309. running*.
  310. The reason for this is that Django's test runner performs a bit of black
  311. magic in order to determine which template was loaded by a given view.
  312. This black magic (essentially a patching of Django's template system in
  313. memory) only happens during test running.
  314. * By default, the test client will disable any CSRF checks
  315. performed by your site.
  316. If, for some reason, you *want* the test client to perform CSRF
  317. checks, you can create an instance of the test client that
  318. enforces CSRF checks. To do this, pass in the
  319. ``enforce_csrf_checks`` argument when you construct your
  320. client::
  321. >>> from django.test import Client
  322. >>> csrf_client = Client(enforce_csrf_checks=True)
  323. Making requests
  324. ~~~~~~~~~~~~~~~
  325. Use the ``django.test.client.Client`` class to make requests.
  326. .. class:: Client(enforce_csrf_checks=False, **defaults)
  327. It requires no arguments at time of construction. However, you can use
  328. keywords arguments to specify some default headers. For example, this will
  329. send a ``User-Agent`` HTTP header in each request::
  330. >>> c = Client(HTTP_USER_AGENT='Mozilla/5.0')
  331. The values from the ``extra`` keywords arguments passed to
  332. :meth:`~django.test.client.Client.get()`,
  333. :meth:`~django.test.client.Client.post()`, etc. have precedence over
  334. the defaults passed to the class constructor.
  335. The ``enforce_csrf_checks`` argument can be used to test CSRF
  336. protection (see above).
  337. Once you have a ``Client`` instance, you can call any of the following
  338. methods:
  339. .. method:: Client.get(path, data={}, follow=False, **extra)
  340. Makes a GET request on the provided ``path`` and returns a ``Response``
  341. object, which is documented below.
  342. The key-value pairs in the ``data`` dictionary are used to create a GET
  343. data payload. For example::
  344. >>> c = Client()
  345. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
  346. ...will result in the evaluation of a GET request equivalent to::
  347. /customers/details/?name=fred&age=7
  348. The ``extra`` keyword arguments parameter can be used to specify
  349. headers to be sent in the request. For example::
  350. >>> c = Client()
  351. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
  352. ... HTTP_X_REQUESTED_WITH='XMLHttpRequest')
  353. ...will send the HTTP header ``HTTP_X_REQUESTED_WITH`` to the
  354. details view, which is a good way to test code paths that use the
  355. :meth:`django.http.HttpRequest.is_ajax()` method.
  356. .. admonition:: CGI specification
  357. The headers sent via ``**extra`` should follow CGI_ specification.
  358. For example, emulating a different "Host" header as sent in the
  359. HTTP request from the browser to the server should be passed
  360. as ``HTTP_HOST``.
  361. .. _CGI: http://www.w3.org/CGI/
  362. If you already have the GET arguments in URL-encoded form, you can
  363. use that encoding instead of using the data argument. For example,
  364. the previous GET request could also be posed as::
  365. >>> c = Client()
  366. >>> c.get('/customers/details/?name=fred&age=7')
  367. If you provide a URL with both an encoded GET data and a data argument,
  368. the data argument will take precedence.
  369. If you set ``follow`` to ``True`` the client will follow any redirects
  370. and a ``redirect_chain`` attribute will be set in the response object
  371. containing tuples of the intermediate urls and status codes.
  372. If you had a URL ``/redirect_me/`` that redirected to ``/next/``, that
  373. redirected to ``/final/``, this is what you'd see::
  374. >>> response = c.get('/redirect_me/', follow=True)
  375. >>> response.redirect_chain
  376. [(u'http://testserver/next/', 302), (u'http://testserver/final/', 302)]
  377. .. method:: Client.post(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
  378. Makes a POST request on the provided ``path`` and returns a
  379. ``Response`` object, which is documented below.
  380. The key-value pairs in the ``data`` dictionary are used to submit POST
  381. data. For example::
  382. >>> c = Client()
  383. >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
  384. ...will result in the evaluation of a POST request to this URL::
  385. /login/
  386. ...with this POST data::
  387. name=fred&passwd=secret
  388. If you provide ``content_type`` (e.g. :mimetype:`text/xml` for an XML
  389. payload), the contents of ``data`` will be sent as-is in the POST
  390. request, using ``content_type`` in the HTTP ``Content-Type`` header.
  391. If you don't provide a value for ``content_type``, the values in
  392. ``data`` will be transmitted with a content type of
  393. :mimetype:`multipart/form-data`. In this case, the key-value pairs in
  394. ``data`` will be encoded as a multipart message and used to create the
  395. POST data payload.
  396. To submit multiple values for a given key -- for example, to specify
  397. the selections for a ``<select multiple>`` -- provide the values as a
  398. list or tuple for the required key. For example, this value of ``data``
  399. would submit three selected values for the field named ``choices``::
  400. {'choices': ('a', 'b', 'd')}
  401. Submitting files is a special case. To POST a file, you need only
  402. provide the file field name as a key, and a file handle to the file you
  403. wish to upload as a value. For example::
  404. >>> c = Client()
  405. >>> with open('wishlist.doc') as fp:
  406. ... c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
  407. (The name ``attachment`` here is not relevant; use whatever name your
  408. file-processing code expects.)
  409. Note that if you wish to use the same file handle for multiple
  410. ``post()`` calls then you will need to manually reset the file
  411. pointer between posts. The easiest way to do this is to
  412. manually close the file after it has been provided to
  413. ``post()``, as demonstrated above.
  414. You should also ensure that the file is opened in a way that
  415. allows the data to be read. If your file contains binary data
  416. such as an image, this means you will need to open the file in
  417. ``rb`` (read binary) mode.
  418. The ``extra`` argument acts the same as for :meth:`Client.get`.
  419. If the URL you request with a POST contains encoded parameters, these
  420. parameters will be made available in the request.GET data. For example,
  421. if you were to make the request::
  422. >>> c.post('/login/?visitor=true', {'name': 'fred', 'passwd': 'secret'})
  423. ... the view handling this request could interrogate request.POST
  424. to retrieve the username and password, and could interrogate request.GET
  425. to determine if the user was a visitor.
  426. If you set ``follow`` to ``True`` the client will follow any redirects
  427. and a ``redirect_chain`` attribute will be set in the response object
  428. containing tuples of the intermediate urls and status codes.
  429. .. method:: Client.head(path, data={}, follow=False, **extra)
  430. Makes a HEAD request on the provided ``path`` and returns a
  431. ``Response`` object. This method works just like :meth:`Client.get`,
  432. including the ``follow`` and ``extra`` arguments, except it does not
  433. return a message body.
  434. .. method:: Client.options(path, data='', content_type='application/octet-stream', follow=False, **extra)
  435. Makes an OPTIONS request on the provided ``path`` and returns a
  436. ``Response`` object. Useful for testing RESTful interfaces.
  437. When ``data`` is provided, it is used as the request body, and
  438. a ``Content-Type`` header is set to ``content_type``.
  439. .. versionchanged:: 1.5
  440. :meth:`Client.options` used to process ``data`` like
  441. :meth:`Client.get`.
  442. The ``follow`` and ``extra`` arguments act the same as for
  443. :meth:`Client.get`.
  444. .. method:: Client.put(path, data='', content_type='application/octet-stream', follow=False, **extra)
  445. Makes a PUT request on the provided ``path`` and returns a
  446. ``Response`` object. Useful for testing RESTful interfaces.
  447. When ``data`` is provided, it is used as the request body, and
  448. a ``Content-Type`` header is set to ``content_type``.
  449. .. versionchanged:: 1.5
  450. :meth:`Client.put` used to process ``data`` like
  451. :meth:`Client.post`.
  452. The ``follow`` and ``extra`` arguments act the same as for
  453. :meth:`Client.get`.
  454. .. method:: Client.delete(path, data='', content_type='application/octet-stream', follow=False, **extra)
  455. Makes an DELETE request on the provided ``path`` and returns a
  456. ``Response`` object. Useful for testing RESTful interfaces.
  457. When ``data`` is provided, it is used as the request body, and
  458. a ``Content-Type`` header is set to ``content_type``.
  459. .. versionchanged:: 1.5
  460. :meth:`Client.delete` used to process ``data`` like
  461. :meth:`Client.get`.
  462. The ``follow`` and ``extra`` arguments act the same as for
  463. :meth:`Client.get`.
  464. .. method:: Client.login(**credentials)
  465. If your site uses Django's :doc:`authentication system</topics/auth/index>`
  466. and you deal with logging in users, you can use the test client's
  467. ``login()`` method to simulate the effect of a user logging into the
  468. site.
  469. After you call this method, the test client will have all the cookies
  470. and session data required to pass any login-based tests that may form
  471. part of a view.
  472. The format of the ``credentials`` argument depends on which
  473. :ref:`authentication backend <authentication-backends>` you're using
  474. (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
  475. setting). If you're using the standard authentication backend provided
  476. by Django (``ModelBackend``), ``credentials`` should be the user's
  477. username and password, provided as keyword arguments::
  478. >>> c = Client()
  479. >>> c.login(username='fred', password='secret')
  480. # Now you can access a view that's only available to logged-in users.
  481. If you're using a different authentication backend, this method may
  482. require different credentials. It requires whichever credentials are
  483. required by your backend's ``authenticate()`` method.
  484. ``login()`` returns ``True`` if it the credentials were accepted and
  485. login was successful.
  486. Finally, you'll need to remember to create user accounts before you can
  487. use this method. As we explained above, the test runner is executed
  488. using a test database, which contains no users by default. As a result,
  489. user accounts that are valid on your production site will not work
  490. under test conditions. You'll need to create users as part of the test
  491. suite -- either manually (using the Django model API) or with a test
  492. fixture. Remember that if you want your test user to have a password,
  493. you can't set the user's password by setting the password attribute
  494. directly -- you must use the
  495. :meth:`~django.contrib.auth.models.User.set_password()` function to
  496. store a correctly hashed password. Alternatively, you can use the
  497. :meth:`~django.contrib.auth.models.UserManager.create_user` helper
  498. method to create a new user with a correctly hashed password.
  499. .. method:: Client.logout()
  500. If your site uses Django's :doc:`authentication system</topics/auth/index>`,
  501. the ``logout()`` method can be used to simulate the effect of a user
  502. logging out of your site.
  503. After you call this method, the test client will have all the cookies
  504. and session data cleared to defaults. Subsequent requests will appear
  505. to come from an AnonymousUser.
  506. Testing responses
  507. ~~~~~~~~~~~~~~~~~
  508. The ``get()`` and ``post()`` methods both return a ``Response`` object. This
  509. ``Response`` object is *not* the same as the ``HttpResponse`` object returned
  510. Django views; the test response object has some additional data useful for
  511. test code to verify.
  512. Specifically, a ``Response`` object has the following attributes:
  513. .. class:: Response()
  514. .. attribute:: client
  515. The test client that was used to make the request that resulted in the
  516. response.
  517. .. attribute:: content
  518. The body of the response, as a string. This is the final page content as
  519. rendered by the view, or any error message.
  520. .. attribute:: context
  521. The template ``Context`` instance that was used to render the template that
  522. produced the response content.
  523. If the rendered page used multiple templates, then ``context`` will be a
  524. list of ``Context`` objects, in the order in which they were rendered.
  525. Regardless of the number of templates used during rendering, you can
  526. retrieve context values using the ``[]`` operator. For example, the
  527. context variable ``name`` could be retrieved using::
  528. >>> response = client.get('/foo/')
  529. >>> response.context['name']
  530. 'Arthur'
  531. .. attribute:: request
  532. The request data that stimulated the response.
  533. .. attribute:: status_code
  534. The HTTP status of the response, as an integer. See
  535. :rfc:`2616#section-10` for a full list of HTTP status codes.
  536. .. attribute:: templates
  537. A list of ``Template`` instances used to render the final content, in
  538. the order they were rendered. For each template in the list, use
  539. ``template.name`` to get the template's file name, if the template was
  540. loaded from a file. (The name is a string such as
  541. ``'admin/index.html'``.)
  542. You can also use dictionary syntax on the response object to query the value
  543. of any settings in the HTTP headers. For example, you could determine the
  544. content type of a response using ``response['Content-Type']``.
  545. Exceptions
  546. ~~~~~~~~~~
  547. If you point the test client at a view that raises an exception, that exception
  548. will be visible in the test case. You can then use a standard ``try ... except``
  549. block or :meth:`~unittest.TestCase.assertRaises` to test for exceptions.
  550. The only exceptions that are not visible to the test client are ``Http404``,
  551. ``PermissionDenied`` and ``SystemExit``. Django catches these exceptions
  552. internally and converts them into the appropriate HTTP response codes. In these
  553. cases, you can check ``response.status_code`` in your test.
  554. Persistent state
  555. ~~~~~~~~~~~~~~~~
  556. The test client is stateful. If a response returns a cookie, then that cookie
  557. will be stored in the test client and sent with all subsequent ``get()`` and
  558. ``post()`` requests.
  559. Expiration policies for these cookies are not followed. If you want a cookie
  560. to expire, either delete it manually or create a new ``Client`` instance (which
  561. will effectively delete all cookies).
  562. A test client has two attributes that store persistent state information. You
  563. can access these properties as part of a test condition.
  564. .. attribute:: Client.cookies
  565. A Python :class:`~Cookie.SimpleCookie` object, containing the current values
  566. of all the client cookies. See the documentation of the :mod:`Cookie` module
  567. for more.
  568. .. attribute:: Client.session
  569. A dictionary-like object containing session information. See the
  570. :doc:`session documentation</topics/http/sessions>` for full details.
  571. To modify the session and then save it, it must be stored in a variable
  572. first (because a new ``SessionStore`` is created every time this property
  573. is accessed)::
  574. def test_something(self):
  575. session = self.client.session
  576. session['somekey'] = 'test'
  577. session.save()
  578. Example
  579. ~~~~~~~
  580. The following is a simple unit test using the test client::
  581. from django.utils import unittest
  582. from django.test.client import Client
  583. class SimpleTest(unittest.TestCase):
  584. def setUp(self):
  585. # Every test needs a client.
  586. self.client = Client()
  587. def test_details(self):
  588. # Issue a GET request.
  589. response = self.client.get('/customer/details/')
  590. # Check that the response is 200 OK.
  591. self.assertEqual(response.status_code, 200)
  592. # Check that the rendered context contains 5 customers.
  593. self.assertEqual(len(response.context['customers']), 5)
  594. .. seealso::
  595. :class:`django.test.client.RequestFactory`
  596. Provided test case classes
  597. --------------------------
  598. .. currentmodule:: django.test
  599. Normal Python unit test classes extend a base class of
  600. :class:`unittest.TestCase`. Django provides a few extensions of this base class:
  601. .. _testcase_hierarchy_diagram:
  602. .. figure:: _images/django_unittest_classes_hierarchy.*
  603. :alt: Hierarchy of Django unit testing classes (TestCase subclasses)
  604. :width: 508
  605. :height: 391
  606. Hierarchy of Django unit testing classes
  607. Regardless of the version of Python you're using, if you've installed
  608. ``unittest2``, :mod:`django.utils.unittest` will point to that library.
  609. SimpleTestCase
  610. ~~~~~~~~~~~~~~
  611. .. class:: SimpleTestCase()
  612. .. versionadded:: 1.4
  613. A very thin subclass of :class:`unittest.TestCase`, it extends it with some
  614. basic functionality like:
  615. * Saving and restoring the Python warning machinery state.
  616. * Checking that a callable :meth:`raises a certain exception <SimpleTestCase.assertRaisesMessage>`.
  617. * :meth:`Testing form field rendering <SimpleTestCase.assertFieldOutput>`.
  618. * Testing server :ref:`HTML responses for the presence/lack of a given fragment <assertions>`.
  619. * The ability to run tests with :ref:`modified settings <overriding-settings>`
  620. If you need any of the other more complex and heavyweight Django-specific
  621. features like:
  622. * Using the :attr:`~TestCase.client` :class:`~django.test.client.Client`.
  623. * Testing or using the ORM.
  624. * Database :attr:`~TestCase.fixtures`.
  625. * Custom test-time :attr:`URL maps <TestCase.urls>`.
  626. * Test :ref:`skipping based on database backend features <skipping-tests>`.
  627. * The remaining specialized :ref:`assert* <assertions>` methods.
  628. then you should use :class:`~django.test.TransactionTestCase` or
  629. :class:`~django.test.TestCase` instead.
  630. ``SimpleTestCase`` inherits from :class:`django.utils.unittest.TestCase`.
  631. TransactionTestCase
  632. ~~~~~~~~~~~~~~~~~~~
  633. .. class:: TransactionTestCase()
  634. Django ``TestCase`` classes make use of database transaction facilities, if
  635. available, to speed up the process of resetting the database to a known state
  636. at the beginning of each test. A consequence of this, however, is that the
  637. effects of transaction commit and rollback cannot be tested by a Django
  638. ``TestCase`` class. If your test requires testing of such transactional
  639. behavior, you should use a Django ``TransactionTestCase``.
  640. ``TransactionTestCase`` and ``TestCase`` are identical except for the manner
  641. in which the database is reset to a known state and the ability for test code
  642. to test the effects of commit and rollback:
  643. * A ``TransactionTestCase`` resets the database after the test runs by
  644. truncating all tables. A ``TransactionTestCase`` may call commit and rollback
  645. and observe the effects of these calls on the database.
  646. * A ``TestCase``, on the other hand, does not truncate tables after a test.
  647. Instead, it encloses the test code in a database transaction that is rolled
  648. back at the end of the test. It also prevents the code under test from
  649. issuing any commit or rollback operations on the database, to ensure that the
  650. rollback at the end of the test restores the database to its initial state.
  651. When running on a database that does not support rollback (e.g. MySQL with the
  652. MyISAM storage engine), ``TestCase`` falls back to initializing the database
  653. by truncating tables and reloading initial data.
  654. .. note::
  655. .. versionchanged:: 1.5
  656. Prior to 1.5, ``TransactionTestCase`` flushed the database tables *before*
  657. each test. In Django 1.5, this is instead done *after* the test has been run.
  658. When the flush took place before the test, it was guaranteed that primary
  659. key values started at one in :class:`~django.test.TransactionTestCase`
  660. tests.
  661. Tests should not depend on this behaviour, but for legacy tests that do, the
  662. :attr:`~TransactionTestCase.reset_sequences` attribute can be used until
  663. the test has been properly updated.
  664. .. versionchanged:: 1.5
  665. The order in which tests are run has changed. See `Order in which tests are
  666. executed`_.
  667. ``TransactionTestCase`` inherits from :class:`~django.test.SimpleTestCase`.
  668. .. attribute:: TransactionTestCase.reset_sequences
  669. .. versionadded:: 1.5
  670. Setting ``reset_sequences = True`` on a ``TransactionTestCase`` will make
  671. sure sequences are always reset before the test run::
  672. class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase):
  673. reset_sequences = True
  674. def test_animal_pk(self):
  675. lion = Animal.objects.create(name="lion", sound="roar")
  676. # lion.pk is guaranteed to always be 1
  677. self.assertEqual(lion.pk, 1)
  678. Unless you are explicitly testing primary keys sequence numbers, it is
  679. recommended that you do not hard code primary key values in tests.
  680. Using ``reset_sequences = True`` will slow down the test, since the primary
  681. key reset is an relatively expensive database operation.
  682. TestCase
  683. ~~~~~~~~
  684. .. class:: TestCase()
  685. This class provides some additional capabilities that can be useful for testing
  686. Web sites.
  687. Converting a normal :class:`unittest.TestCase` to a Django :class:`TestCase` is
  688. easy: Just change the base class of your test from `'unittest.TestCase'` to
  689. `'django.test.TestCase'`. All of the standard Python unit test functionality
  690. will continue to be available, but it will be augmented with some useful
  691. additions, including:
  692. * Automatic loading of fixtures.
  693. * Wraps each test in a transaction.
  694. * Creates a TestClient instance.
  695. * Django-specific assertions for testing for things like redirection and form
  696. errors.
  697. .. versionchanged:: 1.5
  698. The order in which tests are run has changed. See `Order in which tests are
  699. executed`_.
  700. ``TestCase`` inherits from :class:`~django.test.TransactionTestCase`.
  701. .. _live-test-server:
  702. LiveServerTestCase
  703. ~~~~~~~~~~~~~~~~~~
  704. .. versionadded:: 1.4
  705. .. class:: LiveServerTestCase()
  706. ``LiveServerTestCase`` does basically the same as
  707. :class:`~django.test.TransactionTestCase` with one extra feature: it launches a
  708. live Django server in the background on setup, and shuts it down on teardown.
  709. This allows the use of automated test clients other than the
  710. :ref:`Django dummy client <test-client>` such as, for example, the Selenium_
  711. client, to execute a series of functional tests inside a browser and simulate a
  712. real user's actions.
  713. By default the live server's address is `'localhost:8081'` and the full URL
  714. can be accessed during the tests with ``self.live_server_url``. If you'd like
  715. to change the default address (in the case, for example, where the 8081 port is
  716. already taken) then you may pass a different one to the :djadmin:`test` command
  717. via the :djadminopt:`--liveserver` option, for example:
  718. .. code-block:: bash
  719. ./manage.py test --liveserver=localhost:8082
  720. Another way of changing the default server address is by setting the
  721. `DJANGO_LIVE_TEST_SERVER_ADDRESS` environment variable somewhere in your
  722. code (for example, in a :ref:`custom test runner<topics-testing-test_runner>`):
  723. .. code-block:: python
  724. import os
  725. os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8082'
  726. In the case where the tests are run by multiple processes in parallel (for
  727. example, in the context of several simultaneous `continuous integration`_
  728. builds), the processes will compete for the same address, and therefore your
  729. tests might randomly fail with an "Address already in use" error. To avoid this
  730. problem, you can pass a comma-separated list of ports or ranges of ports (at
  731. least as many as the number of potential parallel processes). For example:
  732. .. code-block:: bash
  733. ./manage.py test --liveserver=localhost:8082,8090-8100,9000-9200,7041
  734. Then, during test execution, each new live test server will try every specified
  735. port until it finds one that is free and takes it.
  736. .. _continuous integration: http://en.wikipedia.org/wiki/Continuous_integration
  737. To demonstrate how to use ``LiveServerTestCase``, let's write a simple Selenium
  738. test. First of all, you need to install the `selenium package`_ into your
  739. Python path:
  740. .. code-block:: bash
  741. pip install selenium
  742. Then, add a ``LiveServerTestCase``-based test to your app's tests module
  743. (for example: ``myapp/tests.py``). The code for this test may look as follows:
  744. .. code-block:: python
  745. from django.test import LiveServerTestCase
  746. from selenium.webdriver.firefox.webdriver import WebDriver
  747. class MySeleniumTests(LiveServerTestCase):
  748. fixtures = ['user-data.json']
  749. @classmethod
  750. def setUpClass(cls):
  751. cls.selenium = WebDriver()
  752. super(MySeleniumTests, cls).setUpClass()
  753. @classmethod
  754. def tearDownClass(cls):
  755. cls.selenium.quit()
  756. super(MySeleniumTests, cls).tearDownClass()
  757. def test_login(self):
  758. self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
  759. username_input = self.selenium.find_element_by_name("username")
  760. username_input.send_keys('myuser')
  761. password_input = self.selenium.find_element_by_name("password")
  762. password_input.send_keys('secret')
  763. self.selenium.find_element_by_xpath('//input[@value="Log in"]').click()
  764. Finally, you may run the test as follows:
  765. .. code-block:: bash
  766. ./manage.py test myapp.MySeleniumTests.test_login
  767. This example will automatically open Firefox then go to the login page, enter
  768. the credentials and press the "Log in" button. Selenium offers other drivers in
  769. case you do not have Firefox installed or wish to use another browser. The
  770. example above is just a tiny fraction of what the Selenium client can do; check
  771. out the `full reference`_ for more details.
  772. .. _Selenium: http://seleniumhq.org/
  773. .. _selenium package: http://pypi.python.org/pypi/selenium
  774. .. _full reference: http://selenium-python.readthedocs.org/en/latest/api.html
  775. .. _Firefox: http://www.mozilla.com/firefox/
  776. .. note::
  777. ``LiveServerTestCase`` makes use of the :doc:`staticfiles contrib app
  778. </howto/static-files>` so you'll need to have your project configured
  779. accordingly (in particular by setting :setting:`STATIC_URL`).
  780. .. note::
  781. When using an in-memory SQLite database to run the tests, the same database
  782. connection will be shared by two threads in parallel: the thread in which
  783. the live server is run and the thread in which the test case is run. It's
  784. important to prevent simultaneous database queries via this shared
  785. connection by the two threads, as that may sometimes randomly cause the
  786. tests to fail. So you need to ensure that the two threads don't access the
  787. database at the same time. In particular, this means that in some cases
  788. (for example, just after clicking a link or submitting a form), you might
  789. need to check that a response is received by Selenium and that the next
  790. page is loaded before proceeding with further test execution.
  791. Do this, for example, by making Selenium wait until the `<body>` HTML tag
  792. is found in the response (requires Selenium > 2.13):
  793. .. code-block:: python
  794. def test_login(self):
  795. from selenium.webdriver.support.wait import WebDriverWait
  796. timeout = 2
  797. ...
  798. self.selenium.find_element_by_xpath('//input[@value="Log in"]').click()
  799. # Wait until the response is received
  800. WebDriverWait(self.selenium, timeout).until(
  801. lambda driver: driver.find_element_by_tag_name('body'))
  802. The tricky thing here is that there's really no such thing as a "page load,"
  803. especially in modern Web apps that generate HTML dynamically after the
  804. server generates the initial document. So, simply checking for the presence
  805. of `<body>` in the response might not necessarily be appropriate for all
  806. use cases. Please refer to the `Selenium FAQ`_ and
  807. `Selenium documentation`_ for more information.
  808. .. _Selenium FAQ: http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_WebDriver_fails_to_find_elements_/_Does_not_block_on_page_loa
  809. .. _Selenium documentation: http://seleniumhq.org/docs/04_webdriver_advanced.html#explicit-waits
  810. Test cases features
  811. -------------------
  812. Default test client
  813. ~~~~~~~~~~~~~~~~~~~
  814. .. attribute:: TestCase.client
  815. Every test case in a ``django.test.TestCase`` instance has access to an
  816. instance of a Django test client. This client can be accessed as
  817. ``self.client``. This client is recreated for each test, so you don't have to
  818. worry about state (such as cookies) carrying over from one test to another.
  819. This means, instead of instantiating a ``Client`` in each test::
  820. from django.utils import unittest
  821. from django.test.client import Client
  822. class SimpleTest(unittest.TestCase):
  823. def test_details(self):
  824. client = Client()
  825. response = client.get('/customer/details/')
  826. self.assertEqual(response.status_code, 200)
  827. def test_index(self):
  828. client = Client()
  829. response = client.get('/customer/index/')
  830. self.assertEqual(response.status_code, 200)
  831. ...you can just refer to ``self.client``, like so::
  832. from django.test import TestCase
  833. class SimpleTest(TestCase):
  834. def test_details(self):
  835. response = self.client.get('/customer/details/')
  836. self.assertEqual(response.status_code, 200)
  837. def test_index(self):
  838. response = self.client.get('/customer/index/')
  839. self.assertEqual(response.status_code, 200)
  840. Customizing the test client
  841. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  842. .. attribute:: TestCase.client_class
  843. If you want to use a different ``Client`` class (for example, a subclass
  844. with customized behavior), use the :attr:`~TestCase.client_class` class
  845. attribute::
  846. from django.test import TestCase
  847. from django.test.client import Client
  848. class MyTestClient(Client):
  849. # Specialized methods for your environment...
  850. class MyTest(TestCase):
  851. client_class = MyTestClient
  852. def test_my_stuff(self):
  853. # Here self.client is an instance of MyTestClient...
  854. call_some_test_code()
  855. .. _topics-testing-fixtures:
  856. Fixture loading
  857. ~~~~~~~~~~~~~~~
  858. .. attribute:: TestCase.fixtures
  859. A test case for a database-backed Web site isn't much use if there isn't any
  860. data in the database. To make it easy to put test data into the database,
  861. Django's custom ``TestCase`` class provides a way of loading **fixtures**.
  862. A fixture is a collection of data that Django knows how to import into a
  863. database. For example, if your site has user accounts, you might set up a
  864. fixture of fake user accounts in order to populate your database during tests.
  865. The most straightforward way of creating a fixture is to use the
  866. :djadmin:`manage.py dumpdata <dumpdata>` command. This assumes you
  867. already have some data in your database. See the :djadmin:`dumpdata
  868. documentation<dumpdata>` for more details.
  869. .. note::
  870. If you've ever run :djadmin:`manage.py syncdb<syncdb>`, you've
  871. already used a fixture without even knowing it! When you call
  872. :djadmin:`syncdb` in the database for the first time, Django
  873. installs a fixture called ``initial_data``. This gives you a way
  874. of populating a new database with any initial data, such as a
  875. default set of categories.
  876. Fixtures with other names can always be installed manually using
  877. the :djadmin:`manage.py loaddata<loaddata>` command.
  878. .. admonition:: Initial SQL data and testing
  879. Django provides a second way to insert initial data into models --
  880. the :ref:`custom SQL hook <initial-sql>`. However, this technique
  881. *cannot* be used to provide initial data for testing purposes.
  882. Django's test framework flushes the contents of the test database
  883. after each test; as a result, any data added using the custom SQL
  884. hook will be lost.
  885. Once you've created a fixture and placed it in a ``fixtures`` directory in one
  886. of your :setting:`INSTALLED_APPS`, you can use it in your unit tests by
  887. specifying a ``fixtures`` class attribute on your :class:`django.test.TestCase`
  888. subclass::
  889. from django.test import TestCase
  890. from myapp.models import Animal
  891. class AnimalTestCase(TestCase):
  892. fixtures = ['mammals.json', 'birds']
  893. def setUp(self):
  894. # Test definitions as before.
  895. call_setup_methods()
  896. def testFluffyAnimals(self):
  897. # A test that uses the fixtures.
  898. call_some_test_code()
  899. Here's specifically what will happen:
  900. * At the start of each test case, before ``setUp()`` is run, Django will
  901. flush the database, returning the database to the state it was in
  902. directly after :djadmin:`syncdb` was called.
  903. * Then, all the named fixtures are installed. In this example, Django will
  904. install any JSON fixture named ``mammals``, followed by any fixture named
  905. ``birds``. See the :djadmin:`loaddata` documentation for more
  906. details on defining and installing fixtures.
  907. This flush/load procedure is repeated for each test in the test case, so you
  908. can be certain that the outcome of a test will not be affected by another test,
  909. or by the order of test execution.
  910. URLconf configuration
  911. ~~~~~~~~~~~~~~~~~~~~~
  912. .. attribute:: TestCase.urls
  913. If your application provides views, you may want to include tests that use the
  914. test client to exercise those views. However, an end user is free to deploy the
  915. views in your application at any URL of their choosing. This means that your
  916. tests can't rely upon the fact that your views will be available at a
  917. particular URL.
  918. In order to provide a reliable URL space for your test,
  919. ``django.test.TestCase`` provides the ability to customize the URLconf
  920. configuration for the duration of the execution of a test suite. If your
  921. ``TestCase`` instance defines an ``urls`` attribute, the ``TestCase`` will use
  922. the value of that attribute as the :setting:`ROOT_URLCONF` for the duration
  923. of that test.
  924. For example::
  925. from django.test import TestCase
  926. class TestMyViews(TestCase):
  927. urls = 'myapp.test_urls'
  928. def testIndexPageView(self):
  929. # Here you'd test your view using ``Client``.
  930. call_some_test_code()
  931. This test case will use the contents of ``myapp.test_urls`` as the
  932. URLconf for the duration of the test case.
  933. .. _emptying-test-outbox:
  934. Multi-database support
  935. ~~~~~~~~~~~~~~~~~~~~~~
  936. .. attribute:: TestCase.multi_db
  937. Django sets up a test database corresponding to every database that is
  938. defined in the :setting:`DATABASES` definition in your settings
  939. file. However, a big part of the time taken to run a Django TestCase
  940. is consumed by the call to ``flush`` that ensures that you have a
  941. clean database at the start of each test run. If you have multiple
  942. databases, multiple flushes are required (one for each database),
  943. which can be a time consuming activity -- especially if your tests
  944. don't need to test multi-database activity.
  945. As an optimization, Django only flushes the ``default`` database at
  946. the start of each test run. If your setup contains multiple databases,
  947. and you have a test that requires every database to be clean, you can
  948. use the ``multi_db`` attribute on the test suite to request a full
  949. flush.
  950. For example::
  951. class TestMyViews(TestCase):
  952. multi_db = True
  953. def testIndexPageView(self):
  954. call_some_test_code()
  955. This test case will flush *all* the test databases before running
  956. ``testIndexPageView``.
  957. .. _overriding-settings:
  958. Overriding settings
  959. ~~~~~~~~~~~~~~~~~~~
  960. .. method:: TestCase.settings
  961. .. versionadded:: 1.4
  962. For testing purposes it's often useful to change a setting temporarily and
  963. revert to the original value after running the testing code. For this use case
  964. Django provides a standard Python context manager (see :pep:`343`)
  965. :meth:`~django.test.TestCase.settings`, which can be used like this::
  966. from django.test import TestCase
  967. class LoginTestCase(TestCase):
  968. def test_login(self):
  969. # First check for the default behavior
  970. response = self.client.get('/sekrit/')
  971. self.assertRedirects(response, '/accounts/login/?next=/sekrit/')
  972. # Then override the LOGIN_URL setting
  973. with self.settings(LOGIN_URL='/other/login/'):
  974. response = self.client.get('/sekrit/')
  975. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  976. This example will override the :setting:`LOGIN_URL` setting for the code
  977. in the ``with`` block and reset its value to the previous state afterwards.
  978. .. currentmodule:: django.test.utils
  979. .. function:: override_settings
  980. In case you want to override a setting for just one test method or even the
  981. whole :class:`~django.test.TestCase` class, Django provides the
  982. :func:`~django.test.utils.override_settings` decorator (see :pep:`318`). It's
  983. used like this::
  984. from django.test import TestCase
  985. from django.test.utils import override_settings
  986. class LoginTestCase(TestCase):
  987. @override_settings(LOGIN_URL='/other/login/')
  988. def test_login(self):
  989. response = self.client.get('/sekrit/')
  990. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  991. The decorator can also be applied to test case classes::
  992. from django.test import TestCase
  993. from django.test.utils import override_settings
  994. @override_settings(LOGIN_URL='/other/login/')
  995. class LoginTestCase(TestCase):
  996. def test_login(self):
  997. response = self.client.get('/sekrit/')
  998. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  999. .. note::
  1000. When given a class, the decorator modifies the class directly and
  1001. returns it; it doesn't create and return a modified copy of it. So if
  1002. you try to tweak the above example to assign the return value to a
  1003. different name than ``LoginTestCase``, you may be surprised to find that
  1004. the original ``LoginTestCase`` is still equally affected by the
  1005. decorator.
  1006. When overriding settings, make sure to handle the cases in which your app's
  1007. code uses a cache or similar feature that retains state even if the
  1008. setting is changed. Django provides the
  1009. :data:`django.test.signals.setting_changed` signal that lets you register
  1010. callbacks to clean up and otherwise reset state when settings are changed.
  1011. Django itself uses this signal to reset various data:
  1012. ================================ ========================
  1013. Overriden settings Data reset
  1014. ================================ ========================
  1015. USE_TZ, TIME_ZONE Databases timezone
  1016. TEMPLATE_CONTEXT_PROCESSORS Context processors cache
  1017. TEMPLATE_LOADERS Template loaders cache
  1018. SERIALIZATION_MODULES Serializers cache
  1019. LOCALE_PATHS, LANGUAGE_CODE Default translation and loaded translations
  1020. MEDIA_ROOT, DEFAULT_FILE_STORAGE Default file storage
  1021. ================================ ========================
  1022. Emptying the test outbox
  1023. ~~~~~~~~~~~~~~~~~~~~~~~~
  1024. If you use Django's custom ``TestCase`` class, the test runner will clear the
  1025. contents of the test email outbox at the start of each test case.
  1026. For more detail on email services during tests, see `Email services`_ below.
  1027. .. _assertions:
  1028. Assertions
  1029. ~~~~~~~~~~
  1030. .. currentmodule:: django.test
  1031. As Python's normal :class:`unittest.TestCase` class implements assertion methods
  1032. such as :meth:`~unittest.TestCase.assertTrue` and
  1033. :meth:`~unittest.TestCase.assertEqual`, Django's custom :class:`TestCase` class
  1034. provides a number of custom assertion methods that are useful for testing Web
  1035. applications:
  1036. The failure messages given by most of these assertion methods can be customized
  1037. with the ``msg_prefix`` argument. This string will be prefixed to any failure
  1038. message generated by the assertion. This allows you to provide additional
  1039. details that may help you to identify the location and cause of an failure in
  1040. your test suite.
  1041. .. method:: SimpleTestCase.assertRaisesMessage(expected_exception, expected_message, callable_obj=None, *args, **kwargs)
  1042. .. versionadded:: 1.4
  1043. Asserts that execution of callable ``callable_obj`` raised the
  1044. ``expected_exception`` exception and that such exception has an
  1045. ``expected_message`` representation. Any other outcome is reported as a
  1046. failure. Similar to unittest's :meth:`~unittest.TestCase.assertRaisesRegexp`
  1047. with the difference that ``expected_message`` isn't a regular expression.
  1048. .. method:: SimpleTestCase.assertFieldOutput(self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value=u'')
  1049. .. versionadded:: 1.4
  1050. Asserts that a form field behaves correctly with various inputs.
  1051. :param fieldclass: the class of the field to be tested.
  1052. :param valid: a dictionary mapping valid inputs to their expected cleaned
  1053. values.
  1054. :param invalid: a dictionary mapping invalid inputs to one or more raised
  1055. error messages.
  1056. :param field_args: the args passed to instantiate the field.
  1057. :param field_kwargs: the kwargs passed to instantiate the field.
  1058. :param empty_value: the expected clean output for inputs in ``EMPTY_VALUES``.
  1059. For example, the following code tests that an ``EmailField`` accepts
  1060. "a@a.com" as a valid email address, but rejects "aaa" with a reasonable
  1061. error message::
  1062. self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': [u'Enter a valid email address.']})
  1063. .. method:: TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False)
  1064. Asserts that a ``Response`` instance produced the given ``status_code`` and
  1065. that ``text`` appears in the content of the response. If ``count`` is
  1066. provided, ``text`` must occur exactly ``count`` times in the response.
  1067. .. versionadded:: 1.4
  1068. Set ``html`` to ``True`` to handle ``text`` as HTML. The comparison with
  1069. the response content will be based on HTML semantics instead of
  1070. character-by-character equality. Whitespace is ignored in most cases,
  1071. attribute ordering is not significant. See
  1072. :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
  1073. .. method:: TestCase.assertNotContains(response, text, status_code=200, msg_prefix='', html=False)
  1074. Asserts that a ``Response`` instance produced the given ``status_code`` and
  1075. that ``text`` does not appears in the content of the response.
  1076. .. versionadded:: 1.4
  1077. Set ``html`` to ``True`` to handle ``text`` as HTML. The comparison with
  1078. the response content will be based on HTML semantics instead of
  1079. character-by-character equality. Whitespace is ignored in most cases,
  1080. attribute ordering is not significant. See
  1081. :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
  1082. .. method:: TestCase.assertFormError(response, form, field, errors, msg_prefix='')
  1083. Asserts that a field on a form raises the provided list of errors when
  1084. rendered on the form.
  1085. ``form`` is the name the ``Form`` instance was given in the template
  1086. context.
  1087. ``field`` is the name of the field on the form to check. If ``field``
  1088. has a value of ``None``, non-field errors (errors you can access via
  1089. ``form.non_field_errors()``) will be checked.
  1090. ``errors`` is an error string, or a list of error strings, that are
  1091. expected as a result of form validation.
  1092. .. method:: TestCase.assertTemplateUsed(response, template_name, msg_prefix='')
  1093. Asserts that the template with the given name was used in rendering the
  1094. response.
  1095. The name is a string such as ``'admin/index.html'``.
  1096. .. versionadded:: 1.4
  1097. You can use this as a context manager, like this::
  1098. with self.assertTemplateUsed('index.html'):
  1099. render_to_string('index.html')
  1100. with self.assertTemplateUsed(template_name='index.html'):
  1101. render_to_string('index.html')
  1102. .. method:: TestCase.assertTemplateNotUsed(response, template_name, msg_prefix='')
  1103. Asserts that the template with the given name was *not* used in rendering
  1104. the response.
  1105. .. versionadded:: 1.4
  1106. You can use this as a context manager in the same way as
  1107. :meth:`~TestCase.assertTemplateUsed`.
  1108. .. method:: TestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='')
  1109. Asserts that the response return a ``status_code`` redirect status, it
  1110. redirected to ``expected_url`` (including any GET data), and the final
  1111. page was received with ``target_status_code``.
  1112. If your request used the ``follow`` argument, the ``expected_url`` and
  1113. ``target_status_code`` will be the url and status code for the final
  1114. point of the redirect chain.
  1115. .. method:: TestCase.assertQuerysetEqual(qs, values, transform=repr, ordered=True)
  1116. Asserts that a queryset ``qs`` returns a particular list of values ``values``.
  1117. The comparison of the contents of ``qs`` and ``values`` is performed using
  1118. the function ``transform``; by default, this means that the ``repr()`` of
  1119. each value is compared. Any other callable can be used if ``repr()`` doesn't
  1120. provide a unique or helpful comparison.
  1121. By default, the comparison is also ordering dependent. If ``qs`` doesn't
  1122. provide an implicit ordering, you can set the ``ordered`` parameter to
  1123. ``False``, which turns the comparison into a Python set comparison.
  1124. .. versionchanged:: 1.4
  1125. The ``ordered`` parameter is new in version 1.4. In earlier versions,
  1126. you would need to ensure the queryset is ordered consistently, possibly
  1127. via an explicit ``order_by()`` call on the queryset prior to
  1128. comparison.
  1129. .. versionchanged:: 1.6
  1130. The method now checks for undefined order and raises ``ValueError``
  1131. if undefined order is spotted. The ordering is seen as undefined if
  1132. the given ``qs`` isn't ordered and the comparison is against more
  1133. than one ordered values.
  1134. .. method:: TestCase.assertNumQueries(num, func, *args, **kwargs)
  1135. Asserts that when ``func`` is called with ``*args`` and ``**kwargs`` that
  1136. ``num`` database queries are executed.
  1137. If a ``"using"`` key is present in ``kwargs`` it is used as the database
  1138. alias for which to check the number of queries. If you wish to call a
  1139. function with a ``using`` parameter you can do it by wrapping the call with
  1140. a ``lambda`` to add an extra parameter::
  1141. self.assertNumQueries(7, lambda: my_function(using=7))
  1142. You can also use this as a context manager::
  1143. with self.assertNumQueries(2):
  1144. Person.objects.create(name="Aaron")
  1145. Person.objects.create(name="Daniel")
  1146. .. method:: SimpleTestCase.assertHTMLEqual(html1, html2, msg=None)
  1147. .. versionadded:: 1.4
  1148. Asserts that the strings ``html1`` and ``html2`` are equal. The comparison
  1149. is based on HTML semantics. The comparison takes following things into
  1150. account:
  1151. * Whitespace before and after HTML tags is ignored.
  1152. * All types of whitespace are considered equivalent.
  1153. * All open tags are closed implicitly, e.g. when a surrounding tag is
  1154. closed or the HTML document ends.
  1155. * Empty tags are equivalent to their self-closing version.
  1156. * The ordering of attributes of an HTML element is not significant.
  1157. * Attributes without an argument are equal to attributes that equal in
  1158. name and value (see the examples).
  1159. The following examples are valid tests and don't raise any
  1160. ``AssertionError``::
  1161. self.assertHTMLEqual('<p>Hello <b>world!</p>',
  1162. '''<p>
  1163. Hello <b>world! <b/>
  1164. </p>''')
  1165. self.assertHTMLEqual(
  1166. '<input type="checkbox" checked="checked" id="id_accept_terms" />',
  1167. '<input id="id_accept_terms" type='checkbox' checked>')
  1168. ``html1`` and ``html2`` must be valid HTML. An ``AssertionError`` will be
  1169. raised if one of them cannot be parsed.
  1170. .. method:: SimpleTestCase.assertHTMLNotEqual(html1, html2, msg=None)
  1171. .. versionadded:: 1.4
  1172. Asserts that the strings ``html1`` and ``html2`` are *not* equal. The
  1173. comparison is based on HTML semantics. See
  1174. :meth:`~SimpleTestCase.assertHTMLEqual` for details.
  1175. ``html1`` and ``html2`` must be valid HTML. An ``AssertionError`` will be
  1176. raised if one of them cannot be parsed.
  1177. .. method:: SimpleTestCase.assertXMLEqual(xml1, xml2, msg=None)
  1178. .. versionadded:: 1.5
  1179. Asserts that the strings ``xml1`` and ``xml2`` are equal. The
  1180. comparison is based on XML semantics. Similarily to
  1181. :meth:`~SimpleTestCase.assertHTMLEqual`, the comparison is
  1182. made on parsed content, hence only semantic differences are considered, not
  1183. syntax differences. When unvalid XML is passed in any parameter, an
  1184. ``AssertionError`` is always raised, even if both string are identical.
  1185. .. method:: SimpleTestCase.assertXMLNotEqual(xml1, xml2, msg=None)
  1186. .. versionadded:: 1.5
  1187. Asserts that the strings ``xml1`` and ``xml2`` are *not* equal. The
  1188. comparison is based on XML semantics. See
  1189. :meth:`~SimpleTestCase.assertXMLEqual` for details.
  1190. .. _topics-testing-email:
  1191. Email services
  1192. --------------
  1193. If any of your Django views send email using :doc:`Django's email
  1194. functionality </topics/email>`, you probably don't want to send email each time
  1195. you run a test using that view. For this reason, Django's test runner
  1196. automatically redirects all Django-sent email to a dummy outbox. This lets you
  1197. test every aspect of sending email -- from the number of messages sent to the
  1198. contents of each message -- without actually sending the messages.
  1199. The test runner accomplishes this by transparently replacing the normal
  1200. email backend with a testing backend.
  1201. (Don't worry -- this has no effect on any other email senders outside of
  1202. Django, such as your machine's mail server, if you're running one.)
  1203. .. currentmodule:: django.core.mail
  1204. .. data:: django.core.mail.outbox
  1205. During test running, each outgoing email is saved in
  1206. ``django.core.mail.outbox``. This is a simple list of all
  1207. :class:`~django.core.mail.EmailMessage` instances that have been sent.
  1208. The ``outbox`` attribute is a special attribute that is created *only* when
  1209. the ``locmem`` email backend is used. It doesn't normally exist as part of the
  1210. :mod:`django.core.mail` module and you can't import it directly. The code
  1211. below shows how to access this attribute correctly.
  1212. Here's an example test that examines ``django.core.mail.outbox`` for length
  1213. and contents::
  1214. from django.core import mail
  1215. from django.test import TestCase
  1216. class EmailTest(TestCase):
  1217. def test_send_email(self):
  1218. # Send message.
  1219. mail.send_mail('Subject here', 'Here is the message.',
  1220. 'from@example.com', ['to@example.com'],
  1221. fail_silently=False)
  1222. # Test that one message has been sent.
  1223. self.assertEqual(len(mail.outbox), 1)
  1224. # Verify that the subject of the first message is correct.
  1225. self.assertEqual(mail.outbox[0].subject, 'Subject here')
  1226. As noted :ref:`previously <emptying-test-outbox>`, the test outbox is emptied
  1227. at the start of every test in a Django ``TestCase``. To empty the outbox
  1228. manually, assign the empty list to ``mail.outbox``::
  1229. from django.core import mail
  1230. # Empty the test outbox
  1231. mail.outbox = []
  1232. .. _skipping-tests:
  1233. Skipping tests
  1234. --------------
  1235. .. currentmodule:: django.test
  1236. The unittest library provides the :func:`@skipIf <unittest.skipIf>` and
  1237. :func:`@skipUnless <unittest.skipUnless>` decorators to allow you to skip tests
  1238. if you know ahead of time that those tests are going to fail under certain
  1239. conditions.
  1240. For example, if your test requires a particular optional library in order to
  1241. succeed, you could decorate the test case with :func:`@skipIf
  1242. <unittest.skipIf>`. Then, the test runner will report that the test wasn't
  1243. executed and why, instead of failing the test or omitting the test altogether.
  1244. To supplement these test skipping behaviors, Django provides two
  1245. additional skip decorators. Instead of testing a generic boolean,
  1246. these decorators check the capabilities of the database, and skip the
  1247. test if the database doesn't support a specific named feature.
  1248. The decorators use a string identifier to describe database features.
  1249. This string corresponds to attributes of the database connection
  1250. features class. See :class:`~django.db.backends.BaseDatabaseFeatures`
  1251. class for a full list of database features that can be used as a basis
  1252. for skipping tests.
  1253. .. function:: skipIfDBFeature(feature_name_string)
  1254. Skip the decorated test if the named database feature is supported.
  1255. For example, the following test will not be executed if the database
  1256. supports transactions (e.g., it would *not* run under PostgreSQL, but
  1257. it would under MySQL with MyISAM tables)::
  1258. class MyTests(TestCase):
  1259. @skipIfDBFeature('supports_transactions')
  1260. def test_transaction_behavior(self):
  1261. # ... conditional test code
  1262. .. function:: skipUnlessDBFeature(feature_name_string)
  1263. Skip the decorated test if the named database feature is *not*
  1264. supported.
  1265. For example, the following test will only be executed if the database
  1266. supports transactions (e.g., it would run under PostgreSQL, but *not*
  1267. under MySQL with MyISAM tables)::
  1268. class MyTests(TestCase):
  1269. @skipUnlessDBFeature('supports_transactions')
  1270. def test_transaction_behavior(self):
  1271. # ... conditional test code