testing.txt 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  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. There is a second way to define the test suite for a module: if you define a
  141. function called ``suite()`` in either ``models.py`` or ``tests.py``, the
  142. Django test runner will use that function to construct the test suite for that
  143. module. This follows the `suggested organization`_ for unit tests. See the
  144. Python documentation for more details on how to construct a complex test
  145. 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. .. versionadded:: development
  363. If you already have the GET arguments in URL-encoded form, you can
  364. use that encoding instead of using the data argument. For example,
  365. the previous GET request could also be posed as::
  366. >>> c = Client()
  367. >>> c.get('/customers/details/?name=fred&age=7')
  368. If you provide URL both an encoded GET data and a data argument,
  369. the data argument will take precedence.
  370. .. method:: Client.post(path, data={}, content_type=MULTIPART_CONTENT)
  371. Makes a POST request on the provided ``path`` and returns a
  372. ``Response`` object, which is documented below.
  373. The key-value pairs in the ``data`` dictionary are used to submit POST
  374. data. For example::
  375. >>> c = Client()
  376. >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
  377. ...will result in the evaluation of a POST request to this URL::
  378. /login/
  379. ...with this POST data::
  380. name=fred&passwd=secret
  381. If you provide ``content_type`` (e.g., ``text/xml`` for an XML
  382. payload), the contents of ``data`` will be sent as-is in the POST
  383. request, using ``content_type`` in the HTTP ``Content-Type`` header.
  384. If you don't provide a value for ``content_type``, the values in
  385. ``data`` will be transmitted with a content type of
  386. ``multipart/form-data``. In this case, the key-value pairs in ``data``
  387. will be encoded as a multipart message and used to create the POST data
  388. payload.
  389. To submit multiple values for a given key -- for example, to specify
  390. the selections for a ``<select multiple>`` -- provide the values as a
  391. list or tuple for the required key. For example, this value of ``data``
  392. would submit three selected values for the field named ``choices``::
  393. {'choices': ('a', 'b', 'd')}
  394. Submitting files is a special case. To POST a file, you need only
  395. provide the file field name as a key, and a file handle to the file you
  396. wish to upload as a value. For example::
  397. >>> c = Client()
  398. >>> f = open('wishlist.doc')
  399. >>> c.post('/customers/wishes/', {'name': 'fred', 'attachment': f})
  400. >>> f.close()
  401. (The name ``attachment`` here is not relevant; use whatever name your
  402. file-processing code expects.)
  403. Note that you should manually close the file after it has been provided
  404. to ``post()``.
  405. .. versionadded:: development
  406. If the URL you request with a POST contains encoded parameters, these
  407. parameters will be made available in the request.GET data. For example,
  408. if you were to make the request::
  409. >>> c.post('/login/?vistor=true', {'name': 'fred', 'passwd': 'secret'})
  410. ... the view handling this request could interrogate request.POST
  411. to retrieve the username and password, and could interrogate request.GET
  412. to determine if the user was a visitor.
  413. .. method:: Client.head(path, data={})
  414. .. versionadded:: development
  415. Makes a HEAD request on the provided ``path`` and returns a ``Response``
  416. object. Useful for testing RESTful interfaces. Acts just like
  417. :meth:`Client.get` except it does not return a message body.
  418. .. method:: Client.options(path, data={})
  419. .. versionadded:: development
  420. Makes an OPTIONS request on the provided ``path`` and returns a
  421. ``Response`` object. Useful for testing RESTful interfaces.
  422. .. method:: Client.put(path, data={}, content_type=MULTIPART_CONTENT)
  423. .. versionadded:: development
  424. Makes an PUT request on the provided ``path`` and returns a
  425. ``Response`` object. Useful for testing RESTful interfaces. Acts just
  426. like :meth:`Client.post` except with the PUT request method.
  427. .. method:: Client.delete(path)
  428. .. versionadded:: development
  429. Makes an DELETE request on the provided ``path`` and returns a
  430. ``Response`` object. Useful for testing RESTful interfaces.
  431. .. method:: Client.login(**credentials)
  432. .. versionadded:: 1.0
  433. If your site uses Django's :ref:`authentication system<topics-auth>`
  434. and you deal with logging in users, you can use the test client's
  435. ``login()`` method to simulate the effect of a user logging into the
  436. site.
  437. After you call this method, the test client will have all the cookies
  438. and session data required to pass any login-based tests that may form
  439. part of a view.
  440. The format of the ``credentials`` argument depends on which
  441. :ref:`authentication backend <authentication-backends>` you're using
  442. (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
  443. setting). If you're using the standard authentication backend provided
  444. by Django (``ModelBackend``), ``credentials`` should be the user's
  445. username and password, provided as keyword arguments::
  446. >>> c = Client()
  447. >>> c.login(username='fred', password='secret')
  448. # Now you can access a view that's only available to logged-in users.
  449. If you're using a different authentication backend, this method may
  450. require different credentials. It requires whichever credentials are
  451. required by your backend's ``authenticate()`` method.
  452. ``login()`` returns ``True`` if it the credentials were accepted and
  453. login was successful.
  454. Finally, you'll need to remember to create user accounts before you can
  455. use this method. As we explained above, the test runner is executed
  456. using a test database, which contains no users by default. As a result,
  457. user accounts that are valid on your production site will not work
  458. under test conditions. You'll need to create users as part of the test
  459. suite -- either manually (using the Django model API) or with a test
  460. fixture.
  461. .. method:: Client.logout()
  462. .. versionadded:: 1.0
  463. If your site uses Django's :ref:`authentication system<topics-auth>`,
  464. the ``logout()`` method can be used to simulate the effect of a user
  465. logging out of your site.
  466. After you call this method, the test client will have all the cookies
  467. and session data cleared to defaults. Subsequent requests will appear
  468. to come from an AnonymousUser.
  469. Testing responses
  470. ~~~~~~~~~~~~~~~~~
  471. The ``get()`` and ``post()`` methods both return a ``Response`` object. This
  472. ``Response`` object is *not* the same as the ``HttpResponse`` object returned
  473. Django views; the test response object has some additional data useful for
  474. test code to verify.
  475. Specifically, a ``Response`` object has the following attributes:
  476. .. class:: Response()
  477. .. attribute:: client
  478. The test client that was used to make the request that resulted in the
  479. response.
  480. .. attribute:: content
  481. The body of the response, as a string. This is the final page content as
  482. rendered by the view, or any error message.
  483. .. attribute:: context
  484. The template ``Context`` instance that was used to render the template that
  485. produced the response content.
  486. If the rendered page used multiple templates, then ``context`` will be a
  487. list of ``Context`` objects, in the order in which they were rendered.
  488. .. attribute:: request
  489. The request data that stimulated the response.
  490. .. attribute:: status_code
  491. The HTTP status of the response, as an integer. See RFC2616_ for a full
  492. list of HTTP status codes.
  493. .. attribute:: template
  494. The ``Template`` instance that was used to render the final content. Use
  495. ``template.name`` to get the template's file name, if the template was
  496. loaded from a file. (The name is a string such as ``'admin/index.html'``.)
  497. If the rendered page used multiple templates -- e.g., using :ref:`template
  498. inheritance<template-inheritance>` -- then ``template`` will be a list of
  499. ``Template`` instances, in the order in which they were rendered.
  500. You can also use dictionary syntax on the response object to query the value
  501. of any settings in the HTTP headers. For example, you could determine the
  502. content type of a response using ``response['Content-Type']``.
  503. .. _RFC2616: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  504. Exceptions
  505. ~~~~~~~~~~
  506. If you point the test client at a view that raises an exception, that exception
  507. will be visible in the test case. You can then use a standard ``try...catch``
  508. block or ``unittest.TestCase.assertRaises()`` to test for exceptions.
  509. The only exceptions that are not visible to the test client are ``Http404``,
  510. ``PermissionDenied`` and ``SystemExit``. Django catches these exceptions
  511. internally and converts them into the appropriate HTTP response codes. In these
  512. cases, you can check ``response.status_code`` in your test.
  513. Persistent state
  514. ~~~~~~~~~~~~~~~~
  515. The test client is stateful. If a response returns a cookie, then that cookie
  516. will be stored in the test client and sent with all subsequent ``get()`` and
  517. ``post()`` requests.
  518. Expiration policies for these cookies are not followed. If you want a cookie
  519. to expire, either delete it manually or create a new ``Client`` instance (which
  520. will effectively delete all cookies).
  521. A test client has two attributes that store persistent state information. You
  522. can access these properties as part of a test condition.
  523. .. attribute:: Client.cookies
  524. A Python ``SimpleCookie`` object, containing the current values of all the
  525. client cookies. See the `Cookie module documentation`_ for more.
  526. .. attribute:: Client.session
  527. A dictionary-like object containing session information. See the
  528. :ref:`session documentation<topics-http-sessions>` for full details.
  529. .. _Cookie module documentation: http://docs.python.org/lib/module-Cookie.html
  530. Example
  531. ~~~~~~~
  532. The following is a simple unit test using the test client::
  533. import unittest
  534. from django.test.client import Client
  535. class SimpleTest(unittest.TestCase):
  536. def setUp(self):
  537. # Every test needs a client.
  538. self.client = Client()
  539. def test_details(self):
  540. # Issue a GET request.
  541. response = self.client.get('/customer/details/')
  542. # Check that the response is 200 OK.
  543. self.failUnlessEqual(response.status_code, 200)
  544. # Check that the rendered context contains 5 customers.
  545. self.failUnlessEqual(len(response.context['customers']), 5)
  546. TestCase
  547. --------
  548. .. currentmodule:: django.test
  549. Normal Python unit test classes extend a base class of ``unittest.TestCase``.
  550. Django provides an extension of this base class:
  551. .. class:: TestCase()
  552. This class provides some additional capabilities that can be useful for testing
  553. Web sites.
  554. Converting a normal ``unittest.TestCase`` to a Django ``TestCase`` is easy:
  555. just change the base class of your test from ``unittest.TestCase`` to
  556. ``django.test.TestCase``. All of the standard Python unit test functionality
  557. will continue to be available, but it will be augmented with some useful
  558. additions.
  559. .. versionadded:: 1.1
  560. .. class:: TransactionTestCase()
  561. Django ``TestCase`` classes make use of database transaction facilities, if
  562. available, to speed up the process of resetting the database to a known state
  563. at the beginning of each test. A consequence of this, however, is that the
  564. effects of transaction commit and rollback cannot be tested by a Django
  565. ``TestCase`` class. If your test requires testing of such transactional
  566. behavior, you should use a Django ``TransactionTestCase``.
  567. ``TransactionTestCase`` and ``TestCase`` are identical except for the manner
  568. in which the database is reset to a known state and the ability for test code
  569. to test the effects of commit and rollback. A ``TranscationTestCase`` resets
  570. the database before the test runs by truncating all tables and reloading
  571. initial data. A ``TransactionTestCase`` may call commit and rollback and
  572. observe the effects of these calls on the database.
  573. A ``TestCase``, on the other hand, does not truncate tables and reload initial
  574. data at the beginning of a test. Instead, it encloses the test code in a
  575. database transaction that is rolled back at the end of the test. It also
  576. prevents the code under test from issuing any commit or rollback operations
  577. on the database, to ensure that the rollback at the end of the test restores
  578. the database to its initial state. In order to guarantee that all ``TestCase``
  579. code starts with a clean database, the Django test runner runs all ``TestCase``
  580. tests first, before any other tests (e.g. doctests) that may alter the
  581. database without restoring it to its original state.
  582. When running on a database that does not support rollback (e.g. MySQL with the
  583. MyISAM storage engine), ``TestCase`` falls back to initializing the database
  584. by truncating tables and reloading initial data.
  585. .. note::
  586. The ``TestCase`` use of rollback to un-do the effects of the test code
  587. may reveal previously-undetected errors in test code. For example,
  588. test code that assumes primary keys values will be assigned starting at
  589. one may find that assumption no longer holds true when rollbacks instead
  590. of table truncation are being used to reset the database. Similarly,
  591. the reordering of tests so that all ``TestCase`` classes run first may
  592. reveal unexpected dependencies on test case ordering. In such cases a
  593. quick fix is to switch the ``TestCase`` to a ``TransactionTestCase``.
  594. A better long-term fix, that allows the test to take advantage of the
  595. speed benefit of ``TestCase``, is to fix the underlying test problem.
  596. Default test client
  597. ~~~~~~~~~~~~~~~~~~~
  598. .. versionadded:: 1.0
  599. .. attribute:: TestCase.client
  600. Every test case in a ``django.test.TestCase`` instance has access to an
  601. instance of a Django test client. This client can be accessed as
  602. ``self.client``. This client is recreated for each test, so you don't have to
  603. worry about state (such as cookies) carrying over from one test to another.
  604. This means, instead of instantiating a ``Client`` in each test::
  605. import unittest
  606. from django.test.client import Client
  607. class SimpleTest(unittest.TestCase):
  608. def test_details(self):
  609. client = Client()
  610. response = client.get('/customer/details/')
  611. self.failUnlessEqual(response.status_code, 200)
  612. def test_index(self):
  613. client = Client()
  614. response = client.get('/customer/index/')
  615. self.failUnlessEqual(response.status_code, 200)
  616. ...you can just refer to ``self.client``, like so::
  617. from django.test import TestCase
  618. class SimpleTest(TestCase):
  619. def test_details(self):
  620. response = self.client.get('/customer/details/')
  621. self.failUnlessEqual(response.status_code, 200)
  622. def test_index(self):
  623. response = self.client.get('/customer/index/')
  624. self.failUnlessEqual(response.status_code, 200)
  625. .. _topics-testing-fixtures:
  626. Fixture loading
  627. ~~~~~~~~~~~~~~~
  628. .. attribute:: TestCase.fixtures
  629. A test case for a database-backed Web site isn't much use if there isn't any
  630. data in the database. To make it easy to put test data into the database,
  631. Django's custom ``TestCase`` class provides a way of loading **fixtures**.
  632. A fixture is a collection of data that Django knows how to import into a
  633. database. For example, if your site has user accounts, you might set up a
  634. fixture of fake user accounts in order to populate your database during tests.
  635. The most straightforward way of creating a fixture is to use the ``manage.py
  636. dumpdata`` command. This assumes you already have some data in your database.
  637. See the :djadmin:`dumpdata documentation<dumpdata>` for more details.
  638. .. note::
  639. If you've ever run ``manage.py syncdb``, you've already used a fixture
  640. without even knowing it! When you call ``syncdb`` in the database for
  641. the first time, Django installs a fixture called ``initial_data``.
  642. This gives you a way of populating a new database with any initial data,
  643. such as a default set of categories.
  644. Fixtures with other names can always be installed manually using the
  645. ``manage.py loaddata`` command.
  646. Once you've created a fixture and placed it somewhere in your Django project,
  647. you can use it in your unit tests by specifying a ``fixtures`` class attribute
  648. on your ``django.test.TestCase`` subclass::
  649. from django.test import TestCase
  650. from myapp.models import Animal
  651. class AnimalTestCase(TestCase):
  652. fixtures = ['mammals.json', 'birds']
  653. def setUp(self):
  654. # Test definitions as before.
  655. def testFluffyAnimals(self):
  656. # A test that uses the fixtures.
  657. Here's specifically what will happen:
  658. * At the start of each test case, before ``setUp()`` is run, Django will
  659. flush the database, returning the database to the state it was in
  660. directly after ``syncdb`` was called.
  661. * Then, all the named fixtures are installed. In this example, Django will
  662. install any JSON fixture named ``mammals``, followed by any fixture named
  663. ``birds``. See the :djadmin:`loaddata documentation<loaddata>` for more
  664. details on defining and installing fixtures.
  665. This flush/load procedure is repeated for each test in the test case, so you
  666. can be certain that the outcome of a test will not be affected by another test,
  667. or by the order of test execution.
  668. URLconf configuration
  669. ~~~~~~~~~~~~~~~~~~~~~
  670. .. versionadded:: 1.0
  671. .. attribute:: TestCase.urls
  672. If your application provides views, you may want to include tests that use the
  673. test client to exercise those views. However, an end user is free to deploy the
  674. views in your application at any URL of their choosing. This means that your
  675. tests can't rely upon the fact that your views will be available at a
  676. particular URL.
  677. In order to provide a reliable URL space for your test,
  678. ``django.test.TestCase`` provides the ability to customize the URLconf
  679. configuration for the duration of the execution of a test suite. If your
  680. ``TestCase`` instance defines an ``urls`` attribute, the ``TestCase`` will use
  681. the value of that attribute as the ``ROOT_URLCONF`` for the duration of that
  682. test.
  683. For example::
  684. from django.test import TestCase
  685. class TestMyViews(TestCase):
  686. urls = 'myapp.test_urls'
  687. def testIndexPageView(self):
  688. # Here you'd test your view using ``Client``.
  689. This test case will use the contents of ``myapp.test_urls`` as the
  690. URLconf for the duration of the test case.
  691. .. _emptying-test-outbox:
  692. Emptying the test outbox
  693. ~~~~~~~~~~~~~~~~~~~~~~~~
  694. .. versionadded:: 1.0
  695. If you use Django's custom ``TestCase`` class, the test runner will clear the
  696. contents of the test e-mail outbox at the start of each test case.
  697. For more detail on e-mail services during tests, see `E-mail services`_.
  698. Assertions
  699. ~~~~~~~~~~
  700. .. versionadded:: 1.0
  701. As Python's normal ``unittest.TestCase`` class implements assertion methods
  702. such as ``assertTrue`` and ``assertEquals``, Django's custom ``TestCase`` class
  703. provides a number of custom assertion methods that are useful for testing Web
  704. applications:
  705. .. method:: TestCase.assertContains(response, text, count=None, status_code=200)
  706. Asserts that a ``Response`` instance produced the given ``status_code`` and
  707. that ``text`` appears in the content of the response. If ``count`` is
  708. provided, ``text`` must occur exactly ``count`` times in the response.
  709. .. method:: TestCase.assertNotContains(response, text, status_code=200)
  710. Asserts that a ``Response`` instance produced the given ``status_code`` and
  711. that ``text`` does not appears in the content of the response.
  712. .. method:: assertFormError(response, form, field, errors)
  713. Asserts that a field on a form raises the provided list of errors when
  714. rendered on the form.
  715. ``form`` is the name the ``Form`` instance was given in the template
  716. context.
  717. ``field`` is the name of the field on the form to check. If ``field``
  718. has a value of ``None``, non-field errors (errors you can access via
  719. ``form.non_field_errors()``) will be checked.
  720. ``errors`` is an error string, or a list of error strings, that are
  721. expected as a result of form validation.
  722. .. method:: assertTemplateUsed(response, template_name)
  723. Asserts that the template with the given name was used in rendering the
  724. response.
  725. The name is a string such as ``'admin/index.html'``.
  726. .. method:: assertTemplateNotUsed(response, template_name)
  727. Asserts that the template with the given name was *not* used in rendering
  728. the response.
  729. .. method:: assertRedirects(response, expected_url, status_code=302, target_status_code=200)
  730. Asserts that the response return a ``status_code`` redirect status, it
  731. redirected to ``expected_url`` (including any GET data), and the subsequent
  732. page was received with ``target_status_code``.
  733. E-mail services
  734. ---------------
  735. .. versionadded:: 1.0
  736. If any of your Django views send e-mail using :ref:`Django's e-mail
  737. functionality <topics-email>`, you probably don't want to send e-mail each time
  738. you run a test using that view. For this reason, Django's test runner
  739. automatically redirects all Django-sent e-mail to a dummy outbox. This lets you
  740. test every aspect of sending e-mail -- from the number of messages sent to the
  741. contents of each message -- without actually sending the messages.
  742. The test runner accomplishes this by transparently replacing the normal
  743. :class:`~django.core.mail.SMTPConnection` class with a different version.
  744. (Don't worry -- this has no effect on any other e-mail senders outside of
  745. Django, such as your machine's mail server, if you're running one.)
  746. .. currentmodule:: django.core.mail
  747. .. data:: django.core.mail.outbox
  748. During test running, each outgoing e-mail is saved in
  749. ``django.core.mail.outbox``. This is a simple list of all
  750. :class:`<~django.core.mail.EmailMessage>` instances that have been sent.
  751. It does not exist under normal execution conditions, i.e., when you're not
  752. running unit tests. The outbox is created during test setup, along with the
  753. dummy :class:`<~django.core.mail.SMTPConnection>`. When the test framework is
  754. torn down, the standard :class:`<~django.core.mail.SMTPConnection>` class is
  755. restored, and the test outbox is destroyed.
  756. The ``outbox`` attribute is a special attribute that is created *only* when
  757. the tests are run. It doesn't normally exist as part of the
  758. :mod:`django.core.mail` module and you can't import it directly. The code
  759. below shows how to access this attribute correctly.
  760. Here's an example test that examines ``django.core.mail.outbox`` for length
  761. and contents::
  762. from django.core import mail
  763. from django.test import TestCase
  764. class EmailTest(TestCase):
  765. def test_send_email(self):
  766. # Send message.
  767. mail.send_mail('Subject here', 'Here is the message.',
  768. 'from@example.com', ['to@example.com'],
  769. fail_silently=False)
  770. # Test that one message has been sent.
  771. self.assertEquals(len(mail.outbox), 1)
  772. # Verify that the subject of the first message is correct.
  773. self.assertEquals(mail.outbox[0].subject, 'Subject here')
  774. As noted :ref:`previously <emptying-test-outbox>`, the test outbox is emptied
  775. at the start of every test in a Django ``TestCase``. To empty the outbox
  776. manually, assign the empty list to ``mail.outbox``::
  777. from django.core import mail
  778. # Empty the test outbox
  779. mail.outbox = []
  780. Using different testing frameworks
  781. ==================================
  782. Clearly, ``doctest`` and ``unittest`` are not the only Python testing
  783. frameworks. While Django doesn't provide explicit support for alternative
  784. frameworks, it does provide a way to invoke tests constructed for an
  785. alternative framework as if they were normal Django tests.
  786. When you run ``./manage.py test``, Django looks at the :setting:`TEST_RUNNER`
  787. setting to determine what to do. By default, :setting:`TEST_RUNNER` points to
  788. ``'django.test.simple.run_tests'``. This method defines the default Django
  789. testing behavior. This behavior involves:
  790. #. Performing global pre-test setup.
  791. #. Creating the test database.
  792. #. Running ``syncdb`` to install models and initial data into the test
  793. database.
  794. #. Looking for unit tests and doctests in the ``models.py`` and
  795. ``tests.py`` files in each installed application.
  796. #. Running the unit tests and doctests that are found.
  797. #. Destroying the test database.
  798. #. Performing global post-test teardown.
  799. If you define your own test runner method and point :setting:`TEST_RUNNER` at
  800. that method, Django will execute your test runner whenever you run
  801. ``./manage.py test``. In this way, it is possible to use any test framework
  802. that can be executed from Python code.
  803. Defining a test runner
  804. ----------------------
  805. .. versionadded:: 1.0
  806. .. currentmodule:: django.test.simple
  807. By convention, a test runner should be called ``run_tests``. The only strict
  808. requirement is that it has the same arguments as the Django test runner:
  809. .. function:: run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[])
  810. ``test_labels`` is a list of strings describing the tests to be run. A test
  811. label can take one of three forms:
  812. * ``app.TestCase.test_method`` -- Run a single test method in a test
  813. case.
  814. * ``app.TestCase`` -- Run all the test methods in a test case.
  815. * ``app`` -- Search for and run all tests in the named application.
  816. If ``test_labels`` has a value of ``None``, the test runner should run
  817. search for tests in all the applications in :setting:`INSTALLED_APPS`.
  818. ``verbosity`` determines the amount of notification and debug information
  819. that will be printed to the console; ``0`` is no output, ``1`` is normal
  820. output, and ``2`` is verbose output.
  821. If ``interactive`` is ``True``, the test suite has permission to ask the
  822. user for instructions when the test suite is executed. An example of this
  823. behavior would be asking for permission to delete an existing test
  824. database. If ``interactive`` is ``False``, the test suite must be able to
  825. run without any manual intervention.
  826. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  827. suite that is executed by the test runner. These extra tests are run
  828. in addition to those discovered in the modules listed in ``module_list``.
  829. This method should return the number of tests that failed.
  830. Testing utilities
  831. -----------------
  832. .. module:: django.test.utils
  833. :synopsis: Helpers to write custom test runners.
  834. To assist in the creation of your own test runner, Django provides a number of
  835. utility methods in the ``django.test.utils`` module.
  836. .. function:: setup_test_environment()
  837. Performs any global pre-test setup, such as the installing the
  838. instrumentation of the template rendering system and setting up the dummy
  839. ``SMTPConnection``.
  840. .. function:: teardown_test_environment()
  841. Performs any global post-test teardown, such as removing the black magic
  842. hooks into the template system and restoring normal e-mail services.
  843. The creation module of the database backend (``connection.creation``) also
  844. provides some utilities that can be useful during testing.
  845. .. function:: create_test_db(verbosity=1, autoclobber=False)
  846. Creates a new test database and runs ``syncdb`` against it.
  847. ``verbosity`` has the same behavior as in ``run_tests()``.
  848. ``autoclobber`` describes the behavior that will occur if a database with
  849. the same name as the test database is discovered:
  850. * If ``autoclobber`` is ``False``, the user will be asked to approve
  851. destroying the existing database. ``sys.exit`` is called if the user
  852. does not approve.
  853. * If autoclobber is ``True``, the database will be destroyed without
  854. consulting the user.
  855. Returns the name of the test database that it created.
  856. ``create_test_db()`` has the side effect of modifying
  857. ``settings.DATABASE_NAME`` to match the name of the test database.
  858. .. versionchanged:: 1.0
  859. ``create_test_db()`` now returns the name of the test database.
  860. .. function:: destroy_test_db(old_database_name, verbosity=1)
  861. Destroys the database whose name is in the :setting:`DATABASE_NAME` setting
  862. and restores the value of :setting:`DATABASE_NAME` to the provided name.
  863. ``verbosity`` has the same behavior as in ``run_tests()``.