overview.txt 71 KB

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