testing.txt 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. .. _topics-testing:
  2. ===========================
  3. Testing Django applications
  4. ===========================
  5. .. module:: django.test
  6. :synopsis: Testing tools for Django applications.
  7. Automated testing is an extremely useful bug-killing tool for the modern
  8. Web developer. You can use a collection of tests -- a **test suite** -- to
  9. solve, or avoid, a number of problems:
  10. * When you're writing new code, you can use tests to validate your code
  11. works as expected.
  12. * When you're refactoring or modifying old code, you can use tests to
  13. ensure your changes haven't affected your application's behavior
  14. unexpectedly.
  15. Testing a Web application is a complex task, because a Web application is made
  16. of several layers of logic -- from HTTP-level request handling, to form
  17. validation and processing, to template rendering. With Django's test-execution
  18. framework and assorted utilities, you can simulate requests, insert test data,
  19. inspect your application's output and generally verify your code is doing what
  20. it should be doing.
  21. The best part is, it's really easy.
  22. This document is split into two primary sections. First, we explain how to
  23. write tests with Django. Then, we explain how to run them.
  24. Writing tests
  25. =============
  26. There are two primary ways to write tests with Django, corresponding to the
  27. two test frameworks that ship in the Python standard library. The two
  28. frameworks are:
  29. * **Doctests** -- tests that are embedded in your functions' docstrings and
  30. are written in a way that emulates a session of the Python interactive
  31. interpreter. For example::
  32. def my_func(a_list, idx):
  33. """
  34. >>> a = ['larry', 'curly', 'moe']
  35. >>> my_func(a, 0)
  36. 'larry'
  37. >>> my_func(a, 1)
  38. 'curly'
  39. """
  40. return a_list[idx]
  41. * **Unit tests** -- tests that are expressed as methods on a Python class
  42. that subclasses ``unittest.TestCase``. For example::
  43. import unittest
  44. class MyFuncTestCase(unittest.TestCase):
  45. def testBasic(self):
  46. a = ['larry', 'curly', 'moe']
  47. self.assertEquals(my_func(a, 0), 'larry')
  48. self.assertEquals(my_func(a, 1), 'curly')
  49. You can choose the test framework you like, depending on which syntax you
  50. prefer, or you can mix and match, using one framework for some of your code and
  51. the other framework for other code. You can also use any *other* Python test
  52. frameworks, as we'll explain in a bit.
  53. Writing doctests
  54. ----------------
  55. Doctests use Python's standard doctest_ module, which searches your docstrings
  56. for statements that resemble a session of the Python interactive interpreter.
  57. A full explanation of how doctest works is out of the scope of this document;
  58. read Python's official documentation for the details.
  59. .. admonition:: What's a **docstring**?
  60. A good explanation of docstrings (and some guidelines for using them
  61. effectively) can be found in :pep:`257`:
  62. A docstring is a string literal that occurs as the first statement in
  63. a module, function, class, or method definition. Such a docstring
  64. becomes the ``__doc__`` special attribute of that object.
  65. For example, this function has a docstring that describes what it does::
  66. def add_two(num):
  67. "Return the result of adding two to the provided number."
  68. return num + 2
  69. Because tests often make great documentation, putting tests directly in
  70. your docstrings is an effective way to document *and* test your code.
  71. For a given Django application, the test runner looks for doctests in two
  72. places:
  73. * The ``models.py`` file. You can define module-level doctests and/or a
  74. doctest for individual models. It's common practice to put
  75. application-level doctests in the module docstring and model-level
  76. doctests in the model docstrings.
  77. * A file called ``tests.py`` in the application directory -- i.e., the
  78. directory that holds ``models.py``. This file is a hook for any and all
  79. doctests you want to write that aren't necessarily related to models.
  80. Here is an example model doctest::
  81. # models.py
  82. from django.db import models
  83. class Animal(models.Model):
  84. """
  85. An animal that knows how to make noise
  86. # Create some animals
  87. >>> lion = Animal.objects.create(name="lion", sound="roar")
  88. >>> cat = Animal.objects.create(name="cat", sound="meow")
  89. # Make 'em speak
  90. >>> lion.speak()
  91. 'The lion says "roar"'
  92. >>> cat.speak()
  93. 'The cat says "meow"'
  94. """
  95. name = models.CharField(max_length=20)
  96. sound = models.CharField(max_length=20)
  97. def speak(self):
  98. return 'The %s says "%s"' % (self.name, self.sound)
  99. When you :ref:`run your tests <running-tests>`, the test runner will find this
  100. docstring, notice that portions of it look like an interactive Python session,
  101. and execute those lines while checking that the results match.
  102. In the case of model tests, note that the test runner takes care of creating
  103. its own test database. That is, any test that accesses a database -- by
  104. creating and saving model instances, for example -- will not affect your
  105. production database. Each doctest begins with a "blank slate" -- a fresh
  106. database containing an empty table for each model. (See the section on
  107. fixtures, below, for more on this.) Note that to use this feature, the database
  108. user Django is connecting as must have ``CREATE DATABASE`` rights.
  109. For more details about how doctest works, see the `standard library
  110. documentation for doctest`_.
  111. .. _doctest: http://docs.python.org/lib/module-doctest.html
  112. .. _standard library documentation for doctest: doctest_
  113. Writing unit tests
  114. ------------------
  115. Like doctests, Django's unit tests use a standard library module: unittest_.
  116. This module uses a different way of defining tests, taking a class-based
  117. approach.
  118. As with doctests, for a given Django application, the test runner looks for
  119. unit tests in two places:
  120. * The ``models.py`` file. The test runner looks for any subclass of
  121. ``unittest.TestCase`` in this module.
  122. * A file called ``tests.py`` in the application directory -- i.e., the
  123. directory that holds ``models.py``. Again, the test runner looks for any
  124. subclass of ``unittest.TestCase`` in this module.
  125. This example ``unittest.TestCase`` subclass is equivalent to the example given
  126. in the doctest section above::
  127. import unittest
  128. from myapp.models import Animal
  129. class AnimalTestCase(unittest.TestCase):
  130. def setUp(self):
  131. self.lion = Animal.objects.create(name="lion", sound="roar")
  132. self.cat = Animal.objects.create(name="cat", sound="meow")
  133. def testSpeaking(self):
  134. self.assertEquals(self.lion.speak(), 'The lion says "roar"')
  135. self.assertEquals(self.cat.speak(), 'The cat says "meow"')
  136. When you :ref:`run your tests <running-tests>`, the default behavior of the
  137. test utility is to find all the test cases (that is, subclasses of
  138. ``unittest.TestCase``) in ``models.py`` and ``tests.py``, automatically build a
  139. test suite out of those test cases, and run that suite.
  140. In the Django development version, there is a second way to define the test
  141. suite for a module: if you define a function called ``suite()`` in either
  142. ``models.py`` or ``tests.py``, the Django test runner will use that function
  143. to construct the test suite for that module. This follows the `suggested
  144. organization`_ for unit tests. See the Python documentation for more details on
  145. how to construct a complex test suite.
  146. For more details about ``unittest``, see the `standard library unittest
  147. documentation`_.
  148. .. _unittest: http://docs.python.org/lib/module-unittest.html
  149. .. _standard library unittest documentation: unittest_
  150. .. _suggested organization: http://docs.python.org/lib/organizing-tests.html
  151. Which should I use?
  152. -------------------
  153. Because Django supports both of the standard Python test frameworks, it's up to
  154. you and your tastes to decide which one to use. You can even decide to use
  155. *both*.
  156. For developers new to testing, however, this choice can seem confusing. Here,
  157. then, are a few key differences to help you decide which approach is right for
  158. you:
  159. * If you've been using Python for a while, ``doctest`` will probably feel
  160. more "pythonic". It's designed to make writing tests as easy as possible,
  161. so it requires no overhead of writing classes or methods. You simply put
  162. tests in docstrings. This has the added advantage of serving as
  163. documentation (and correct documentation, at that!).
  164. If you're just getting started with testing, using doctests will probably
  165. get you started faster.
  166. * The ``unittest`` framework will probably feel very familiar to developers
  167. coming from Java. ``unittest`` is inspired by Java's JUnit, so you'll
  168. feel at home with this method if you've used JUnit or any test framework
  169. inspired by JUnit.
  170. * If you need to write a bunch of tests that share similar code, then
  171. you'll appreciate the ``unittest`` framework's organization around
  172. classes and methods. This makes it easy to abstract common tasks into
  173. common methods. The framework also supports explicit setup and/or cleanup
  174. routines, which give you a high level of control over the environment
  175. in which your test cases are run.
  176. Again, remember that you can use both systems side-by-side (even in the same
  177. app). In the end, most projects will eventually end up using both. Each shines
  178. in different circumstances.
  179. .. _running-tests:
  180. Running tests
  181. =============
  182. Once you've written tests, run them using your project's ``manage.py``
  183. utility::
  184. $ ./manage.py test
  185. By default, this will run every test in every application in
  186. :setting:`INSTALLED_APPS`. If you only want to run tests for a particular
  187. application, add the application name to the command line. For example, if your
  188. :setting:`INSTALLED_APPS` contains ``'myproject.polls'`` and
  189. ``'myproject.animals'``, you can run the ``myproject.animals`` unit tests alone
  190. with this command::
  191. $ ./manage.py test animals
  192. Note that we used ``animals``, not ``myproject.animals``.
  193. .. versionadded:: 1.0
  194. You can now choose which test to run.
  195. If you use unit tests, as opposed to
  196. doctests, you can be even *more* specific in choosing which tests to execute.
  197. To run a single test case in an application (for example, the
  198. ``AnimalTestCase`` described in the "Writing unit tests" section), add the
  199. name of the test case to the label on the command line::
  200. $ ./manage.py test animals.AnimalTestCase
  201. And it gets even more granular than that! To run a *single* test method inside
  202. a test case, add the name of the test method to the label::
  203. $ ./manage.py test animals.AnimalTestCase.testFluffyAnimals
  204. The test database
  205. -----------------
  206. Tests that require a database (namely, model tests) will not use your "real"
  207. (production) database. A separate, blank database is created for the tests.
  208. Regardless of whether the tests pass or fail, the test database is destroyed
  209. when all the tests have been executed.
  210. By default this test database gets its name by prepending ``test_`` to the
  211. value of the :setting:`DATABASE_NAME` setting. When using the SQLite database
  212. engine the tests will by default use an in-memory database (i.e., the database
  213. will be created in memory, bypassing the filesystem entirely!). If you want to
  214. use a different database name, specify the :setting:`TEST_DATABASE_NAME`
  215. setting.
  216. Aside from using a separate database, the test runner will otherwise use all of
  217. the same database settings you have in your settings file:
  218. :setting:`DATABASE_ENGINE`, :setting:`DATABASE_USER`, :setting:`DATABASE_HOST`,
  219. etc. The test database is created by the user specified by
  220. :setting:`DATABASE_USER`, so you'll need to make sure that the given user
  221. account has sufficient privileges to create a new database on the system.
  222. .. versionadded:: 1.0
  223. For fine-grained control over the
  224. character encoding of your test database, use the
  225. :setting:`TEST_DATABASE_CHARSET` setting. If you're using MySQL, you can also
  226. use the :setting:`TEST_DATABASE_COLLATION` setting to control the particular
  227. collation used by the test database. See the :ref:`settings documentation
  228. <ref-settings>` for details of these advanced settings.
  229. Other test conditions
  230. ---------------------
  231. Regardless of the value of the :setting:`DEBUG` setting in your configuration
  232. file, all Django tests run with :setting:`DEBUG=False`. This is to ensure that
  233. the observed output of your code matches what will be seen in a production
  234. setting.
  235. Understanding the test output
  236. -----------------------------
  237. When you run your tests, you'll see a number of messages as the test runner
  238. prepares itself. You can control the level of detail of these messages with the
  239. ``verbosity`` option on the command line::
  240. Creating test database...
  241. Creating table myapp_animal
  242. Creating table myapp_mineral
  243. Loading 'initial_data' fixtures...
  244. No fixtures found.
  245. This tells you that the test runner is creating a test database, as described
  246. in the previous section.
  247. Once the test database has been created, Django will run your tests.
  248. If everything goes well, you'll see something like this::
  249. ----------------------------------------------------------------------
  250. Ran 22 tests in 0.221s
  251. OK
  252. If there are test failures, however, you'll see full details about which tests
  253. failed::
  254. ======================================================================
  255. FAIL: Doctest: ellington.core.throttle.models
  256. ----------------------------------------------------------------------
  257. Traceback (most recent call last):
  258. File "/dev/django/test/doctest.py", line 2153, in runTest
  259. raise self.failureException(self.format_failure(new.getvalue()))
  260. AssertionError: Failed doctest test for myapp.models
  261. File "/dev/myapp/models.py", line 0, in models
  262. ----------------------------------------------------------------------
  263. File "/dev/myapp/models.py", line 14, in myapp.models
  264. Failed example:
  265. throttle.check("actor A", "action one", limit=2, hours=1)
  266. Expected:
  267. True
  268. Got:
  269. False
  270. ----------------------------------------------------------------------
  271. Ran 2 tests in 0.048s
  272. FAILED (failures=1)
  273. A full explanation of this error output is beyond the scope of this document,
  274. but it's pretty intuitive. You can consult the documentation of Python's
  275. ``unittest`` library for details.
  276. Note that the return code for the test-runner script is the total number of
  277. failed and erroneous tests. If all the tests pass, the return code is 0. This
  278. feature is useful if you're using the test-runner script in a shell script and
  279. need to test for success or failure at that level.
  280. Testing tools
  281. =============
  282. Django provides a small set of tools that come in handy when writing tests.
  283. The test client
  284. ---------------
  285. .. module:: django.test.client
  286. :synopsis: Django's test client.
  287. The test client is a Python class that acts as a dummy Web browser, allowing
  288. you to test your views and interact with your Django-powered application
  289. programmatically.
  290. Some of the things you can do with the test client are:
  291. * Simulate GET and POST requests on a URL and observe the response --
  292. everything from low-level HTTP (result headers and status codes) to
  293. page content.
  294. * Test that the correct view is executed for a given URL.
  295. * Test that a given request is rendered by a given Django template, with
  296. a template context that contains certain values.
  297. Note that the test client is not intended to be a replacement for Twill_,
  298. Selenium_, or other "in-browser" frameworks. Django's test client has
  299. a different focus. In short:
  300. * Use Django's test client to establish that the correct view is being
  301. called and that the view is collecting the correct context data.
  302. * Use in-browser frameworks such as Twill and Selenium to test *rendered*
  303. HTML and the *behavior* of Web pages, namely JavaScript functionality.
  304. A comprehensive test suite should use a combination of both test types.
  305. .. _Twill: http://twill.idyll.org/
  306. .. _Selenium: http://www.openqa.org/selenium/
  307. Overview and a quick example
  308. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  309. To use the test client, instantiate ``django.test.client.Client`` and retrieve
  310. Web pages::
  311. >>> from django.test.client import Client
  312. >>> c = Client()
  313. >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
  314. >>> response.status_code
  315. 200
  316. >>> response = c.get('/customer/details/')
  317. >>> response.content
  318. '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...'
  319. As this example suggests, you can instantiate ``Client`` from within a session
  320. of the Python interactive interpreter.
  321. Note a few important things about how the test client works:
  322. * The test client does *not* require the Web server to be running. In fact,
  323. it will run just fine with no Web server running at all! That's because
  324. it avoids the overhead of HTTP and deals directly with the Django
  325. framework. This helps make the unit tests run quickly.
  326. * When retrieving pages, remember to specify the *path* of the URL, not the
  327. whole domain. For example, this is correct::
  328. >>> c.get('/login/')
  329. This is incorrect::
  330. >>> c.get('http://www.example.com/login/')
  331. The test client is not capable of retrieving Web pages that are not
  332. powered by your Django project. If you need to retrieve other Web pages,
  333. use a Python standard library module such as urllib_ or urllib2_.
  334. * To resolve URLs, the test client uses whatever URLconf is pointed-to by
  335. your :setting:`ROOT_URLCONF` setting.
  336. * Although the above example would work in the Python interactive
  337. interpreter, some of the test client's functionality, notably the
  338. template-related functionality, is only available *while tests are
  339. running*.
  340. The reason for this is that Django's test runner performs a bit of black
  341. magic in order to determine which template was loaded by a given view.
  342. This black magic (essentially a patching of Django's template system in
  343. memory) only happens during test running.
  344. .. _urllib: http://docs.python.org/lib/module-urllib.html
  345. .. _urllib2: http://docs.python.org/lib/module-urllib2.html
  346. Making requests
  347. ~~~~~~~~~~~~~~~
  348. Use the ``django.test.client.Client`` class to make requests. It requires no
  349. arguments at time of construction:
  350. .. class:: Client()
  351. Once you have a ``Client`` instance, you can call any of the following
  352. methods:
  353. .. method:: Client.get(path, data={})
  354. Makes a GET request on the provided ``path`` and returns a ``Response``
  355. object, which is documented below.
  356. The key-value pairs in the ``data`` dictionary are used to create a GET
  357. data payload. For example::
  358. >>> c = Client()
  359. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
  360. ...will result in the evaluation of a GET request equivalent to::
  361. /customers/details/?name=fred&age=7
  362. .. method:: Client.post(path, data={}, content_type=MULTIPART_CONTENT)
  363. Makes a POST request on the provided ``path`` and returns a
  364. ``Response`` object, which is documented below.
  365. The key-value pairs in the ``data`` dictionary are used to submit POST
  366. data. For example::
  367. >>> c = Client()
  368. >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
  369. ...will result in the evaluation of a POST request to this URL::
  370. /login/
  371. ...with this POST data::
  372. name=fred&passwd=secret
  373. If you provide ``content_type`` (e.g., ``text/xml`` for an XML
  374. payload), the contents of ``data`` will be sent as-is in the POST
  375. request, using ``content_type`` in the HTTP ``Content-Type`` header.
  376. If you don't provide a value for ``content_type``, the values in
  377. ``data`` will be transmitted with a content type of
  378. ``multipart/form-data``. In this case, the key-value pairs in ``data``
  379. will be encoded as a multipart message and used to create the POST data
  380. payload.
  381. To submit multiple values for a given key -- for example, to specify
  382. the selections for a ``<select multiple>`` -- provide the values as a
  383. list or tuple for the required key. For example, this value of ``data``
  384. would submit three selected values for the field named ``choices``::
  385. {'choices': ('a', 'b', 'd')}
  386. Submitting files is a special case. To POST a file, you need only
  387. provide the file field name as a key, and a file handle to the file you
  388. wish to upload as a value. For example::
  389. >>> c = Client()
  390. >>> f = open('wishlist.doc')
  391. >>> c.post('/customers/wishes/', {'name': 'fred', 'attachment': f})
  392. >>> f.close()
  393. (The name ``attachment`` here is not relevant; use whatever name your
  394. file-processing code expects.)
  395. Note that you should manually close the file after it has been provided
  396. to ``post()``.
  397. .. method:: Client.login(**credentials)
  398. .. versionadded:: 1.0
  399. If your site uses Django's :ref:`authentication system<topics-auth>`
  400. and you deal with logging in users, you can use the test client's
  401. ``login()`` method to simulate the effect of a user logging into the
  402. site.
  403. After you call this method, the test client will have all the cookies
  404. and session data required to pass any login-based tests that may form
  405. part of a view.
  406. The format of the ``credentials`` argument depends on which
  407. :ref:`authentication backend <authentication-backends>` you're using
  408. (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
  409. setting). If you're using the standard authentication backend provided
  410. by Django (``ModelBackend``), ``credentials`` should be the user's
  411. username and password, provided as keyword arguments::
  412. >>> c = Client()
  413. >>> c.login(username='fred', password='secret')
  414. # Now you can access a view that's only available to logged-in users.
  415. If you're using a different authentication backend, this method may
  416. require different credentials. It requires whichever credentials are
  417. required by your backend's ``authenticate()`` method.
  418. ``login()`` returns ``True`` if it the credentials were accepted and
  419. login was successful.
  420. Finally, you'll need to remember to create user accounts before you can
  421. use this method. As we explained above, the test runner is executed
  422. using a test database, which contains no users by default. As a result,
  423. user accounts that are valid on your production site will not work
  424. under test conditions. You'll need to create users as part of the test
  425. suite -- either manually (using the Django model API) or with a test
  426. fixture.
  427. .. method:: Client.logout()
  428. .. versionadded:: 1.0
  429. If your site uses Django's :ref:`authentication system<topics-auth>`,
  430. the ``logout()`` method can be used to simulate the effect of a user
  431. logging out of your site.
  432. After you call this method, the test client will have all the cookies
  433. and session data cleared to defaults. Subsequent requests will appear
  434. to come from an AnonymousUser.
  435. Testing responses
  436. ~~~~~~~~~~~~~~~~~
  437. The ``get()`` and ``post()`` methods both return a ``Response`` object. This
  438. ``Response`` object is *not* the same as the ``HttpResponse`` object returned
  439. Django views; the test response object has some additional data useful for
  440. test code to verify.
  441. Specifically, a ``Response`` object has the following attributes:
  442. .. class:: Response()
  443. .. attribute:: client
  444. The test client that was used to make the request that resulted in the
  445. response.
  446. .. attribute:: content
  447. The body of the response, as a string. This is the final page content as
  448. rendered by the view, or any error message.
  449. .. attribute:: context
  450. The template ``Context`` instance that was used to render the template that
  451. produced the response content.
  452. If the rendered page used multiple templates, then ``context`` will be a
  453. list of ``Context`` objects, in the order in which they were rendered.
  454. .. attribute:: request
  455. The request data that stimulated the response.
  456. .. attribute:: status_code
  457. The HTTP status of the response, as an integer. See RFC2616_ for a full
  458. list of HTTP status codes.
  459. .. attribute:: template
  460. The ``Template`` instance that was used to render the final content. Use
  461. ``template.name`` to get the template's file name, if the template was
  462. loaded from a file. (The name is a string such as ``'admin/index.html'``.)
  463. If the rendered page used multiple templates -- e.g., using :ref:`template
  464. inheritance<template-inheritance>` -- then ``template`` will be a list of
  465. ``Template`` instances, in the order in which they were rendered.
  466. You can also use dictionary syntax on the response object to query the value
  467. of any settings in the HTTP headers. For example, you could determine the
  468. content type of a response using ``response['Content-Type']``.
  469. .. _RFC2616: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  470. Exceptions
  471. ~~~~~~~~~~
  472. If you point the test client at a view that raises an exception, that exception
  473. will be visible in the test case. You can then use a standard ``try...catch``
  474. block or ``unittest.TestCase.assertRaises()`` to test for exceptions.
  475. The only exceptions that are not visible to the test client are ``Http404``,
  476. ``PermissionDenied`` and ``SystemExit``. Django catches these exceptions
  477. internally and converts them into the appropriate HTTP response codes. In these
  478. cases, you can check ``response.status_code`` in your test.
  479. Persistent state
  480. ~~~~~~~~~~~~~~~~
  481. The test client is stateful. If a response returns a cookie, then that cookie
  482. will be stored in the test client and sent with all subsequent ``get()`` and
  483. ``post()`` requests.
  484. Expiration policies for these cookies are not followed. If you want a cookie
  485. to expire, either delete it manually or create a new ``Client`` instance (which
  486. will effectively delete all cookies).
  487. A test client has two attributes that store persistent state information. You
  488. can access these properties as part of a test condition.
  489. .. attribute:: Client.cookies
  490. A Python ``SimpleCookie`` object, containing the current values of all the
  491. client cookies. See the `Cookie module documentation`_ for more.
  492. .. attribute:: Client.session
  493. A dictionary-like object containing session information. See the
  494. :ref:`session documentation<topics-http-sessions>` for full details.
  495. .. _Cookie module documentation: http://docs.python.org/lib/module-Cookie.html
  496. Example
  497. ~~~~~~~
  498. The following is a simple unit test using the test client::
  499. import unittest
  500. from django.test.client import Client
  501. class SimpleTest(unittest.TestCase):
  502. def setUp(self):
  503. # Every test needs a client.
  504. self.client = Client()
  505. def test_details(self):
  506. # Issue a GET request.
  507. response = self.client.get('/customer/details/')
  508. # Check that the response is 200 OK.
  509. self.failUnlessEqual(response.status_code, 200)
  510. # Check that the rendered context contains 5 customers.
  511. self.failUnlessEqual(len(response.context['customers']), 5)
  512. TestCase
  513. --------
  514. .. currentmodule:: django.test
  515. Normal Python unit test classes extend a base class of ``unittest.TestCase``.
  516. Django provides an extension of this base class:
  517. .. class:: TestCase()
  518. This class provides some additional capabilities that can be useful for testing
  519. Web sites.
  520. Converting a normal ``unittest.TestCase`` to a Django ``TestCase`` is easy:
  521. just change the base class of your test from ``unittest.TestCase`` to
  522. ``django.test.TestCase``. All of the standard Python unit test functionality
  523. will continue to be available, but it will be augmented with some useful
  524. additions.
  525. Default test client
  526. ~~~~~~~~~~~~~~~~~~~
  527. .. versionadded:: 1.0
  528. .. attribute:: TestCase.client
  529. Every test case in a ``django.test.TestCase`` instance has access to an
  530. instance of a Django test client. This client can be accessed as
  531. ``self.client``. This client is recreated for each test, so you don't have to
  532. worry about state (such as cookies) carrying over from one test to another.
  533. This means, instead of instantiating a ``Client`` in each test::
  534. import unittest
  535. from django.test.client import Client
  536. class SimpleTest(unittest.TestCase):
  537. def test_details(self):
  538. client = Client()
  539. response = client.get('/customer/details/')
  540. self.failUnlessEqual(response.status_code, 200)
  541. def test_index(self):
  542. client = Client()
  543. response = client.get('/customer/index/')
  544. self.failUnlessEqual(response.status_code, 200)
  545. ...you can just refer to ``self.client``, like so::
  546. from django.test import TestCase
  547. class SimpleTest(TestCase):
  548. def test_details(self):
  549. response = self.client.get('/customer/details/')
  550. self.failUnlessEqual(response.status_code, 200)
  551. def test_index(self):
  552. response = self.client.get('/customer/index/')
  553. self.failUnlessEqual(response.status_code, 200)
  554. .. _topics-testing-fixtures:
  555. Fixture loading
  556. ~~~~~~~~~~~~~~~
  557. .. attribute:: TestCase.fixtures
  558. A test case for a database-backed Web site isn't much use if there isn't any
  559. data in the database. To make it easy to put test data into the database,
  560. Django's custom ``TestCase`` class provides a way of loading **fixtures**.
  561. A fixture is a collection of data that Django knows how to import into a
  562. database. For example, if your site has user accounts, you might set up a
  563. fixture of fake user accounts in order to populate your database during tests.
  564. The most straightforward way of creating a fixture is to use the ``manage.py
  565. dumpdata`` command. This assumes you already have some data in your database.
  566. See the :djadmin:`dumpdata documentation<dumpdata>` for more details.
  567. .. note::
  568. If you've ever run ``manage.py syncdb``, you've already used a fixture
  569. without even knowing it! When you call ``syncdb`` in the database for
  570. the first time, Django installs a fixture called ``initial_data``.
  571. This gives you a way of populating a new database with any initial data,
  572. such as a default set of categories.
  573. Fixtures with other names can always be installed manually using the
  574. ``manage.py loaddata`` command.
  575. Once you've created a fixture and placed it somewhere in your Django project,
  576. you can use it in your unit tests by specifying a ``fixtures`` class attribute
  577. on your ``django.test.TestCase`` subclass::
  578. from django.test import TestCase
  579. from myapp.models import Animal
  580. class AnimalTestCase(TestCase):
  581. fixtures = ['mammals.json', 'birds']
  582. def setUp(self):
  583. # Test definitions as before.
  584. def testFluffyAnimals(self):
  585. # A test that uses the fixtures.
  586. Here's specifically what will happen:
  587. * At the start of each test case, before ``setUp()`` is run, Django will
  588. flush the database, returning the database to the state it was in
  589. directly after ``syncdb`` was called.
  590. * Then, all the named fixtures are installed. In this example, Django will
  591. install any JSON fixture named ``mammals``, followed by any fixture named
  592. ``birds``. See the :djadmin:`loaddata documentation<loaddata>` for more
  593. details on defining and installing fixtures.
  594. This flush/load procedure is repeated for each test in the test case, so you
  595. can be certain that the outcome of a test will not be affected by another test,
  596. or by the order of test execution.
  597. URLconf configuration
  598. ~~~~~~~~~~~~~~~~~~~~~
  599. .. versionadded:: 1.0
  600. .. attribute:: TestCase.urls
  601. If your application provides views, you may want to include tests that use the
  602. test client to exercise those views. However, an end user is free to deploy the
  603. views in your application at any URL of their choosing. This means that your
  604. tests can't rely upon the fact that your views will be available at a
  605. particular URL.
  606. In order to provide a reliable URL space for your test,
  607. ``django.test.TestCase`` provides the ability to customize the URLconf
  608. configuration for the duration of the execution of a test suite. If your
  609. ``TestCase`` instance defines an ``urls`` attribute, the ``TestCase`` will use
  610. the value of that attribute as the ``ROOT_URLCONF`` for the duration of that
  611. test.
  612. For example::
  613. from django.test import TestCase
  614. class TestMyViews(TestCase):
  615. urls = 'myapp.test_urls'
  616. def testIndexPageView(self):
  617. # Here you'd test your view using ``Client``.
  618. This test case will use the contents of ``myapp.test_urls`` as the
  619. URLconf for the duration of the test case.
  620. .. _emptying-test-outbox:
  621. Emptying the test outbox
  622. ~~~~~~~~~~~~~~~~~~~~~~~~
  623. .. versionadded:: 1.0
  624. If you use Django's custom ``TestCase`` class, the test runner will clear the
  625. contents of the test e-mail outbox at the start of each test case.
  626. For more detail on e-mail services during tests, see `E-mail services`_.
  627. Assertions
  628. ~~~~~~~~~~
  629. .. versionadded:: 1.0
  630. As Python's normal ``unittest.TestCase`` class implements assertion methods
  631. such as ``assertTrue`` and ``assertEquals``, Django's custom ``TestCase`` class
  632. provides a number of custom assertion methods that are useful for testing Web
  633. applications:
  634. .. method:: TestCase.assertContains(response, text, count=None, status_code=200)
  635. Asserts that a ``Response`` instance produced the given ``status_code`` and
  636. that ``text`` appears in the content of the response. If ``count`` is
  637. provided, ``text`` must occur exactly ``count`` times in the response.
  638. .. method:: TestCase.assertNotContains(response, text, status_code=200)
  639. Asserts that a ``Response`` instance produced the given ``status_code`` and
  640. that ``text`` does not appears in the content of the response.
  641. .. method:: assertFormError(response, form, field, errors)
  642. Asserts that a field on a form raises the provided list of errors when
  643. rendered on the form.
  644. ``form`` is the name the ``Form`` instance was given in the template
  645. context.
  646. ``field`` is the name of the field on the form to check. If ``field``
  647. has a value of ``None``, non-field errors (errors you can access via
  648. ``form.non_field_errors()``) will be checked.
  649. ``errors`` is an error string, or a list of error strings, that are
  650. expected as a result of form validation.
  651. .. method:: assertTemplateUsed(response, template_name)
  652. Asserts that the template with the given name was used in rendering the
  653. response.
  654. The name is a string such as ``'admin/index.html'``.
  655. .. method:: assertTemplateNotUsed(response, template_name)
  656. Asserts that the template with the given name was *not* used in rendering
  657. the response.
  658. .. method:: assertRedirects(response, expected_url, status_code=302, target_status_code=200)
  659. Asserts that the response return a ``status_code`` redirect status, it
  660. redirected to ``expected_url`` (including any GET data), and the subsequent
  661. page was received with ``target_status_code``.
  662. E-mail services
  663. ---------------
  664. .. versionadded:: 1.0
  665. If any of your Django views send e-mail using :ref:`Django's e-mail
  666. functionality <topics-email>`, you probably don't want to send e-mail each time
  667. you run a test using that view. For this reason, Django's test runner
  668. automatically redirects all Django-sent e-mail to a dummy outbox. This lets you
  669. test every aspect of sending e-mail -- from the number of messages sent to the
  670. contents of each message -- without actually sending the messages.
  671. The test runner accomplishes this by transparently replacing the normal
  672. :class:`~django.core.mail.SMTPConnection` class with a different version.
  673. (Don't worry -- this has no effect on any other e-mail senders outside of
  674. Django, such as your machine's mail server, if you're running one.)
  675. .. currentmodule:: django.core.mail
  676. .. data:: django.core.mail.output
  677. During test running, each outgoing e-mail is saved in
  678. ``django.core.mail.outbox``. This is a simple list of all
  679. :class:`<~django.core.mail.EmailMessage>` instances that have been sent.
  680. It does not exist under normal execution conditions, i.e., when you're not
  681. running unit tests. The outbox is created during test setup, along with the
  682. dummy :class:`<~django.core.mail.SMTPConnection>`. When the test framework is
  683. torn down, the standard :class:`<~django.core.mail.SMTPConnection>` class is
  684. restored, and the test outbox is destroyed.
  685. Here's an example test that examines ``django.core.mail.outbox`` for length
  686. and contents::
  687. from django.core import mail
  688. from django.test import TestCase
  689. class EmailTest(TestCase):
  690. def test_send_email(self):
  691. # Send message.
  692. mail.send_mail('Subject here', 'Here is the message.',
  693. 'from@example.com', ['to@example.com'],
  694. fail_silently=False)
  695. # Test that one message has been sent.
  696. self.assertEqual(len(mail.outbox), 1)
  697. # Verify that the subject of the first message is correct.
  698. self.assertEqual(mail.outbox[0].subject, 'Subject here')
  699. As noted :ref:`previously <emptying-test-outbox>`, the test outbox is emptied
  700. at the start of every test in a Django ``TestCase``. To empty the outbox
  701. manually, assign the empty list to ``mail.outbox``::
  702. from django.core import mail
  703. # Empty the test outbox
  704. mail.outbox = []
  705. Using different testing frameworks
  706. ==================================
  707. Clearly, ``doctest`` and ``unittest`` are not the only Python testing
  708. frameworks. While Django doesn't provide explicit support for alternative
  709. frameworks, it does provide a way to invoke tests constructed for an
  710. alternative framework as if they were normal Django tests.
  711. When you run ``./manage.py test``, Django looks at the :setting:`TEST_RUNNER`
  712. setting to determine what to do. By default, :setting:`TEST_RUNNER` points to
  713. ``'django.test.simple.run_tests'``. This method defines the default Django
  714. testing behavior. This behavior involves:
  715. #. Performing global pre-test setup.
  716. #. Creating the test database.
  717. #. Running ``syncdb`` to install models and initial data into the test
  718. database.
  719. #. Looking for unit tests and doctests in the ``models.py`` and
  720. ``tests.py`` files in each installed application.
  721. #. Running the unit tests and doctests that are found.
  722. #. Destroying the test database.
  723. #. Performing global post-test teardown.
  724. If you define your own test runner method and point :setting:`TEST_RUNNER` at
  725. that method, Django will execute your test runner whenever you run
  726. ``./manage.py test``. In this way, it is possible to use any test framework
  727. that can be executed from Python code.
  728. Defining a test runner
  729. ----------------------
  730. .. versionadded:: 1.0
  731. .. currentmodule:: django.test.simple
  732. By convention, a test runner should be called ``run_tests``. The only strict
  733. requirement is that it has the same arguments as the Django test runner:
  734. .. function:: run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[])
  735. ``test_labels`` is a list of strings describing the tests to be run. A test
  736. label can take one of three forms:
  737. * ``app.TestCase.test_method`` -- Run a single test method in a test
  738. case.
  739. * ``app.TestCase`` -- Run all the test methods in a test case.
  740. * ``app`` -- Search for and run all tests in the named application.
  741. If ``test_labels`` has a value of ``None``, the test runner should run
  742. search for tests in all the applications in :setting:`INSTALLED_APPS`.
  743. ``verbosity`` determines the amount of notification and debug information
  744. that will be printed to the console; ``0`` is no output, ``1`` is normal
  745. output, and ``2`` is verbose output.
  746. If ``interactive`` is ``True``, the test suite has permission to ask the
  747. user for instructions when the test suite is executed. An example of this
  748. behavior would be asking for permission to delete an existing test
  749. database. If ``interactive`` is ``False``, the test suite must be able to
  750. run without any manual intervention.
  751. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  752. suite that is executed by the test runner. These extra tests are run
  753. in addition to those discovered in the modules listed in ``module_list``.
  754. This method should return the number of tests that failed.
  755. Testing utilities
  756. -----------------
  757. .. module:: django.test.utils
  758. :synopsis: Helpers to write custom test runners.
  759. To assist in the creation of your own test runner, Django provides a number of
  760. utility methods in the ``django.test.utils`` module.
  761. .. function:: setup_test_environment()
  762. Performs any global pre-test setup, such as the installing the
  763. instrumentation of the template rendering system and setting up the dummy
  764. ``SMTPConnection``.
  765. .. function:: teardown_test_environment()
  766. Performs any global post-test teardown, such as removing the black magic
  767. hooks into the template system and restoring normal e-mail services.
  768. The creation module of the database backend (``connection.creation``) also
  769. provides some utilities that can be useful during testing.
  770. .. function:: create_test_db(verbosity=1, autoclobber=False)
  771. Creates a new test database and runs ``syncdb`` against it.
  772. ``verbosity`` has the same behavior as in ``run_tests()``.
  773. ``autoclobber`` describes the behavior that will occur if a database with
  774. the same name as the test database is discovered:
  775. * If ``autoclobber`` is ``False``, the user will be asked to approve
  776. destroying the existing database. ``sys.exit`` is called if the user
  777. does not approve.
  778. * If autoclobber is ``True``, the database will be destroyed without
  779. consulting the user.
  780. Returns the name of the test database that it created.
  781. ``create_test_db()`` has the side effect of modifying
  782. ``settings.DATABASE_NAME`` to match the name of the test database.
  783. .. versionchanged:: 1.0
  784. ``create_test_db()`` now returns the name of the test database.
  785. .. function:: destroy_test_db(old_database_name, verbosity=1)
  786. Destroys the database whose name is in the :setting:`DATABASE_NAME` setting
  787. and restores the value of :setting:`DATABASE_NAME` to the provided name.
  788. ``verbosity`` has the same behavior as in ``run_tests()``.