testing.txt 49 KB

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