overview.txt 71 KB

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