tools.txt 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166
  1. =============
  2. Testing tools
  3. =============
  4. .. currentmodule:: django.test
  5. Django provides a small set of tools that come in handy when writing tests.
  6. .. _test-client:
  7. The test client
  8. ===============
  9. The test client is a Python class that acts as a dummy web browser, allowing
  10. you to test your views and interact with your Django-powered application
  11. programmatically.
  12. Some of the things you can do with the test client are:
  13. * Simulate GET and POST requests on a URL and observe the response --
  14. everything from low-level HTTP (result headers and status codes) to
  15. page content.
  16. * See the chain of redirects (if any) and check the URL and status code at
  17. each step.
  18. * Test that a given request is rendered by a given Django template, with
  19. a template context that contains certain values.
  20. Note that the test client is not intended to be a replacement for Selenium_ or
  21. other "in-browser" frameworks. Django's test client has a different focus. In
  22. short:
  23. * Use Django's test client to establish that the correct template is being
  24. rendered and that the template is passed the correct context data.
  25. * Use :class:`~django.test.RequestFactory` to test view functions directly,
  26. bypassing the routing and middleware layers.
  27. * Use in-browser frameworks like Selenium_ to test *rendered* HTML and the
  28. *behavior* of web pages, namely JavaScript functionality. Django also
  29. provides special support for those frameworks; see the section on
  30. :class:`~django.test.LiveServerTestCase` for more details.
  31. A comprehensive test suite should use a combination of all of these test types.
  32. Overview and a quick example
  33. ----------------------------
  34. To use the test client, instantiate ``django.test.Client`` and retrieve
  35. web pages:
  36. .. code-block:: pycon
  37. >>> from django.test import Client
  38. >>> c = Client()
  39. >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
  40. >>> response.status_code
  41. 200
  42. >>> response = c.get('/customer/details/')
  43. >>> response.content
  44. b'<!DOCTYPE html...'
  45. As this example suggests, you can instantiate ``Client`` from within a session
  46. of the Python interactive interpreter.
  47. Note a few important things about how the test client works:
  48. * The test client does *not* require the web server to be running. In fact,
  49. it will run just fine with no web server running at all! That's because
  50. it avoids the overhead of HTTP and deals directly with the Django
  51. framework. This helps make the unit tests run quickly.
  52. * When retrieving pages, remember to specify the *path* of the URL, not the
  53. whole domain. For example, this is correct:
  54. .. code-block:: pycon
  55. >>> c.get('/login/')
  56. This is incorrect:
  57. .. code-block:: pycon
  58. >>> c.get('https://www.example.com/login/')
  59. The test client is not capable of retrieving web pages that are not
  60. powered by your Django project. If you need to retrieve other web pages,
  61. use a Python standard library module such as :mod:`urllib`.
  62. * To resolve URLs, the test client uses whatever URLconf is pointed-to by
  63. your :setting:`ROOT_URLCONF` setting.
  64. * Although the above example would work in the Python interactive
  65. interpreter, some of the test client's functionality, notably the
  66. template-related functionality, is only available *while tests are
  67. running*.
  68. The reason for this is that Django's test runner performs a bit of black
  69. magic in order to determine which template was loaded by a given view.
  70. This black magic (essentially a patching of Django's template system in
  71. memory) only happens during test running.
  72. * By default, the test client will disable any CSRF checks
  73. performed by your site.
  74. If, for some reason, you *want* the test client to perform CSRF
  75. checks, you can create an instance of the test client that
  76. enforces CSRF checks. To do this, pass in the
  77. ``enforce_csrf_checks`` argument when you construct your
  78. client:
  79. .. code-block:: pycon
  80. >>> from django.test import Client
  81. >>> csrf_client = Client(enforce_csrf_checks=True)
  82. Making requests
  83. ---------------
  84. Use the ``django.test.Client`` class to make requests.
  85. .. class:: Client(enforce_csrf_checks=False, raise_request_exception=True, json_encoder=DjangoJSONEncoder, *, headers=None, **defaults)
  86. A testing HTTP client. Takes several arguments that can customize behavior.
  87. ``headers`` allows you to specify default headers that will be sent with
  88. every request. For example, to set a ``User-Agent`` header::
  89. client = Client(headers={"user-agent": "curl/7.79.1"})
  90. Arbitrary keyword arguments in ``**defaults`` set WSGI
  91. :pep:`environ variables <3333#environ-variables>`. For example, to set the
  92. script name::
  93. client = Client(SCRIPT_NAME="/app/")
  94. .. note::
  95. Keyword arguments starting with a ``HTTP_`` prefix are set as headers,
  96. but the ``headers`` parameter should be preferred for readability.
  97. The values from the ``headers`` and ``extra`` keyword arguments passed to
  98. :meth:`~django.test.Client.get()`,
  99. :meth:`~django.test.Client.post()`, etc. have precedence over
  100. the defaults passed to the class constructor.
  101. The ``enforce_csrf_checks`` argument can be used to test CSRF
  102. protection (see above).
  103. The ``raise_request_exception`` argument allows controlling whether or not
  104. exceptions raised during the request should also be raised in the test.
  105. Defaults to ``True``.
  106. The ``json_encoder`` argument allows setting a custom JSON encoder for
  107. the JSON serialization that's described in :meth:`post`.
  108. Once you have a ``Client`` instance, you can call any of the following
  109. methods:
  110. .. versionchanged:: 4.2
  111. The ``headers`` parameter was added.
  112. .. method:: Client.get(path, data=None, follow=False, secure=False, *, headers=None, **extra)
  113. Makes a GET request on the provided ``path`` and returns a ``Response``
  114. object, which is documented below.
  115. The key-value pairs in the ``data`` dictionary are used to create a GET
  116. data payload. For example:
  117. .. code-block:: pycon
  118. >>> c = Client()
  119. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
  120. ...will result in the evaluation of a GET request equivalent to:
  121. .. code-block:: text
  122. /customers/details/?name=fred&age=7
  123. The ``headers`` parameter can be used to specify headers to be sent in
  124. the request. For example:
  125. .. code-block:: pycon
  126. >>> c = Client()
  127. >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
  128. ... headers={'accept': 'application/json'})
  129. ...will send the HTTP header ``HTTP_ACCEPT`` to the details view, which
  130. is a good way to test code paths that use the
  131. :meth:`django.http.HttpRequest.accepts()` method.
  132. Arbitrary keyword arguments set WSGI
  133. :pep:`environ variables <3333#environ-variables>`. For example, headers
  134. to set the script name:
  135. .. code-block:: pycon
  136. >>> c = Client()
  137. >>> c.get("/", SCRIPT_NAME="/app/")
  138. If you already have the GET arguments in URL-encoded form, you can
  139. use that encoding instead of using the data argument. For example,
  140. the previous GET request could also be posed as:
  141. .. code-block:: pycon
  142. >>> c = Client()
  143. >>> c.get('/customers/details/?name=fred&age=7')
  144. If you provide a URL with both an encoded GET data and a data argument,
  145. the data argument will take precedence.
  146. If you set ``follow`` to ``True`` the client will follow any redirects
  147. and a ``redirect_chain`` attribute will be set in the response object
  148. containing tuples of the intermediate urls and status codes.
  149. If you had a URL ``/redirect_me/`` that redirected to ``/next/``, that
  150. redirected to ``/final/``, this is what you'd see:
  151. .. code-block:: pycon
  152. >>> response = c.get('/redirect_me/', follow=True)
  153. >>> response.redirect_chain
  154. [('http://testserver/next/', 302), ('http://testserver/final/', 302)]
  155. If you set ``secure`` to ``True`` the client will emulate an HTTPS
  156. request.
  157. .. versionchanged:: 4.2
  158. The ``headers`` parameter was added.
  159. .. method:: Client.post(path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, *, headers=None, **extra)
  160. Makes a POST request on the provided ``path`` and returns a
  161. ``Response`` object, which is documented below.
  162. The key-value pairs in the ``data`` dictionary are used to submit POST
  163. data. For example:
  164. .. code-block:: pycon
  165. >>> c = Client()
  166. >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
  167. ...will result in the evaluation of a POST request to this URL:
  168. .. code-block:: text
  169. /login/
  170. ...with this POST data::
  171. name=fred&passwd=secret
  172. If you provide ``content_type`` as :mimetype:`application/json`, the
  173. ``data`` is serialized using :func:`json.dumps` if it's a dict, list,
  174. or tuple. Serialization is performed with
  175. :class:`~django.core.serializers.json.DjangoJSONEncoder` by default,
  176. and can be overridden by providing a ``json_encoder`` argument to
  177. :class:`Client`. This serialization also happens for :meth:`put`,
  178. :meth:`patch`, and :meth:`delete` requests.
  179. If you provide any other ``content_type`` (e.g. :mimetype:`text/xml`
  180. for an XML payload), the contents of ``data`` are sent as-is in the
  181. POST request, using ``content_type`` in the HTTP ``Content-Type``
  182. header.
  183. If you don't provide a value for ``content_type``, the values in
  184. ``data`` will be transmitted with a content type of
  185. :mimetype:`multipart/form-data`. In this case, the key-value pairs in
  186. ``data`` will be encoded as a multipart message and used to create the
  187. POST data payload.
  188. To submit multiple values for a given key -- for example, to specify
  189. the selections for a ``<select multiple>`` -- provide the values as a
  190. list or tuple for the required key. For example, this value of ``data``
  191. would submit three selected values for the field named ``choices``::
  192. {'choices': ['a', 'b', 'd']}
  193. Submitting files is a special case. To POST a file, you need only
  194. provide the file field name as a key, and a file handle to the file you
  195. wish to upload as a value. For example, if your form has fields
  196. ``name`` and ``attachment``, the latter a
  197. :class:`~django.forms.FileField`:
  198. .. code-block:: pycon
  199. >>> c = Client()
  200. >>> with open('wishlist.doc', 'rb') as fp:
  201. ... c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
  202. You may also provide any file-like object (e.g., :class:`~io.StringIO` or
  203. :class:`~io.BytesIO`) as a file handle. If you're uploading to an
  204. :class:`~django.db.models.ImageField`, the object needs a ``name``
  205. attribute that passes the
  206. :data:`~django.core.validators.validate_image_file_extension` validator.
  207. For example:
  208. .. code-block:: pycon
  209. >>> from io import BytesIO
  210. >>> img = BytesIO(
  211. ... b"GIF89a\x01\x00\x01\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00"
  212. ... b"\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x01\x00\x00"
  213. ... )
  214. >>> img.name = "myimage.gif"
  215. Note that if you wish to use the same file handle for multiple
  216. ``post()`` calls then you will need to manually reset the file
  217. pointer between posts. The easiest way to do this is to
  218. manually close the file after it has been provided to
  219. ``post()``, as demonstrated above.
  220. You should also ensure that the file is opened in a way that
  221. allows the data to be read. If your file contains binary data
  222. such as an image, this means you will need to open the file in
  223. ``rb`` (read binary) mode.
  224. The ``headers`` and ``extra`` parameters acts the same as for
  225. :meth:`Client.get`.
  226. If the URL you request with a POST contains encoded parameters, these
  227. parameters will be made available in the request.GET data. For example,
  228. if you were to make the request:
  229. .. code-block:: pycon
  230. >>> c.post('/login/?visitor=true', {'name': 'fred', 'passwd': 'secret'})
  231. ... the view handling this request could interrogate request.POST
  232. to retrieve the username and password, and could interrogate request.GET
  233. to determine if the user was a visitor.
  234. If you set ``follow`` to ``True`` the client will follow any redirects
  235. and a ``redirect_chain`` attribute will be set in the response object
  236. containing tuples of the intermediate urls and status codes.
  237. If you set ``secure`` to ``True`` the client will emulate an HTTPS
  238. request.
  239. .. versionchanged:: 4.2
  240. The ``headers`` parameter was added.
  241. .. method:: Client.head(path, data=None, follow=False, secure=False, *, headers=None, **extra)
  242. Makes a HEAD request on the provided ``path`` and returns a
  243. ``Response`` object. This method works just like :meth:`Client.get`,
  244. including the ``follow``, ``secure``, ``headers``, and ``extra``
  245. parameters, except it does not return a message body.
  246. .. versionchanged:: 4.2
  247. The ``headers`` parameter was added.
  248. .. method:: Client.options(path, data='', content_type='application/octet-stream', follow=False, secure=False, *, headers=None, **extra)
  249. Makes an OPTIONS request on the provided ``path`` and returns a
  250. ``Response`` object. Useful for testing RESTful interfaces.
  251. When ``data`` is provided, it is used as the request body, and
  252. a ``Content-Type`` header is set to ``content_type``.
  253. The ``follow``, ``secure``, ``headers``, and ``extra`` parameters act
  254. the same as for :meth:`Client.get`.
  255. .. versionchanged:: 4.2
  256. The ``headers`` parameter was added.
  257. .. method:: Client.put(path, data='', content_type='application/octet-stream', follow=False, secure=False, *, headers=None, **extra)
  258. Makes a PUT request on the provided ``path`` and returns a
  259. ``Response`` object. Useful for testing RESTful interfaces.
  260. When ``data`` is provided, it is used as the request body, and
  261. a ``Content-Type`` header is set to ``content_type``.
  262. The ``follow``, ``secure``, ``headers``, and ``extra`` parameters act
  263. the same as for :meth:`Client.get`.
  264. .. versionchanged:: 4.2
  265. The ``headers`` parameter was added.
  266. .. method:: Client.patch(path, data='', content_type='application/octet-stream', follow=False, secure=False, *, headers=None, **extra)
  267. Makes a PATCH request on the provided ``path`` and returns a
  268. ``Response`` object. Useful for testing RESTful interfaces.
  269. The ``follow``, ``secure``, ``headers``, and ``extra`` parameters act
  270. the same as for :meth:`Client.get`.
  271. .. versionchanged:: 4.2
  272. The ``headers`` parameter was added.
  273. .. method:: Client.delete(path, data='', content_type='application/octet-stream', follow=False, secure=False, *, headers=None, **extra)
  274. Makes a DELETE request on the provided ``path`` and returns a
  275. ``Response`` object. Useful for testing RESTful interfaces.
  276. When ``data`` is provided, it is used as the request body, and
  277. a ``Content-Type`` header is set to ``content_type``.
  278. The ``follow``, ``secure``, ``headers``, and ``extra`` parameters act
  279. the same as for :meth:`Client.get`.
  280. .. versionchanged:: 4.2
  281. The ``headers`` parameter was added.
  282. .. method:: Client.trace(path, follow=False, secure=False, *, headers=None, **extra)
  283. Makes a TRACE request on the provided ``path`` and returns a
  284. ``Response`` object. Useful for simulating diagnostic probes.
  285. Unlike the other request methods, ``data`` is not provided as a keyword
  286. parameter in order to comply with :rfc:`9110#section-9.3.8`, which
  287. mandates that TRACE requests must not have a body.
  288. The ``follow``, ``secure``, ``headers``, and ``extra`` parameters act
  289. the same as for :meth:`Client.get`.
  290. .. versionchanged:: 4.2
  291. The ``headers`` parameter was added.
  292. .. method:: Client.login(**credentials)
  293. If your site uses Django's :doc:`authentication system</topics/auth/index>`
  294. and you deal with logging in users, you can use the test client's
  295. ``login()`` method to simulate the effect of a user logging into the
  296. site.
  297. After you call this method, the test client will have all the cookies
  298. and session data required to pass any login-based tests that may form
  299. part of a view.
  300. The format of the ``credentials`` argument depends on which
  301. :ref:`authentication backend <authentication-backends>` you're using
  302. (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
  303. setting). If you're using the standard authentication backend provided
  304. by Django (``ModelBackend``), ``credentials`` should be the user's
  305. username and password, provided as keyword arguments:
  306. .. code-block:: pycon
  307. >>> c = Client()
  308. >>> c.login(username='fred', password='secret')
  309. # Now you can access a view that's only available to logged-in users.
  310. If you're using a different authentication backend, this method may
  311. require different credentials. It requires whichever credentials are
  312. required by your backend's ``authenticate()`` method.
  313. ``login()`` returns ``True`` if it the credentials were accepted and
  314. login was successful.
  315. Finally, you'll need to remember to create user accounts before you can
  316. use this method. As we explained above, the test runner is executed
  317. using a test database, which contains no users by default. As a result,
  318. user accounts that are valid on your production site will not work
  319. under test conditions. You'll need to create users as part of the test
  320. suite -- either manually (using the Django model API) or with a test
  321. fixture. Remember that if you want your test user to have a password,
  322. you can't set the user's password by setting the password attribute
  323. directly -- you must use the
  324. :meth:`~django.contrib.auth.models.User.set_password()` function to
  325. store a correctly hashed password. Alternatively, you can use the
  326. :meth:`~django.contrib.auth.models.UserManager.create_user` helper
  327. method to create a new user with a correctly hashed password.
  328. .. method:: Client.force_login(user, backend=None)
  329. If your site uses Django's :doc:`authentication
  330. system</topics/auth/index>`, you can use the ``force_login()`` method
  331. to simulate the effect of a user logging into the site. Use this method
  332. instead of :meth:`login` when a test requires a user be logged in and
  333. the details of how a user logged in aren't important.
  334. Unlike ``login()``, this method skips the authentication and
  335. verification steps: inactive users (:attr:`is_active=False
  336. <django.contrib.auth.models.User.is_active>`) are permitted to login
  337. and the user's credentials don't need to be provided.
  338. The user will have its ``backend`` attribute set to the value of the
  339. ``backend`` argument (which should be a dotted Python path string), or
  340. to ``settings.AUTHENTICATION_BACKENDS[0]`` if a value isn't provided.
  341. The :func:`~django.contrib.auth.authenticate` function called by
  342. :meth:`login` normally annotates the user like this.
  343. This method is faster than ``login()`` since the expensive
  344. password hashing algorithms are bypassed. Also, you can speed up
  345. ``login()`` by :ref:`using a weaker hasher while testing
  346. <speeding-up-tests-auth-hashers>`.
  347. .. method:: Client.logout()
  348. If your site uses Django's :doc:`authentication system</topics/auth/index>`,
  349. the ``logout()`` method can be used to simulate the effect of a user
  350. logging out of your site.
  351. After you call this method, the test client will have all the cookies
  352. and session data cleared to defaults. Subsequent requests will appear
  353. to come from an :class:`~django.contrib.auth.models.AnonymousUser`.
  354. Testing responses
  355. -----------------
  356. The ``get()`` and ``post()`` methods both return a ``Response`` object. This
  357. ``Response`` object is *not* the same as the ``HttpResponse`` object returned
  358. by Django views; the test response object has some additional data useful for
  359. test code to verify.
  360. Specifically, a ``Response`` object has the following attributes:
  361. .. class:: Response()
  362. .. attribute:: client
  363. The test client that was used to make the request that resulted in the
  364. response.
  365. .. attribute:: content
  366. The body of the response, as a bytestring. This is the final page
  367. content as rendered by the view, or any error message.
  368. .. attribute:: context
  369. The template ``Context`` instance that was used to render the template that
  370. produced the response content.
  371. If the rendered page used multiple templates, then ``context`` will be a
  372. list of ``Context`` objects, in the order in which they were rendered.
  373. Regardless of the number of templates used during rendering, you can
  374. retrieve context values using the ``[]`` operator. For example, the
  375. context variable ``name`` could be retrieved using:
  376. .. code-block:: pycon
  377. >>> response = client.get('/foo/')
  378. >>> response.context['name']
  379. 'Arthur'
  380. .. admonition:: Not using Django templates?
  381. This attribute is only populated when using the
  382. :class:`~django.template.backends.django.DjangoTemplates` backend.
  383. If you're using another template engine,
  384. :attr:`~django.template.response.SimpleTemplateResponse.context_data`
  385. may be a suitable alternative on responses with that attribute.
  386. .. attribute:: exc_info
  387. A tuple of three values that provides information about the unhandled
  388. exception, if any, that occurred during the view.
  389. The values are (type, value, traceback), the same as returned by
  390. Python's :func:`sys.exc_info`. Their meanings are:
  391. - *type*: The type of the exception.
  392. - *value*: The exception instance.
  393. - *traceback*: A traceback object which encapsulates the call stack at
  394. the point where the exception originally occurred.
  395. If no exception occurred, then ``exc_info`` will be ``None``.
  396. .. method:: json(**kwargs)
  397. The body of the response, parsed as JSON. Extra keyword arguments are
  398. passed to :func:`json.loads`. For example:
  399. .. code-block:: pycon
  400. >>> response = client.get('/foo/')
  401. >>> response.json()['name']
  402. 'Arthur'
  403. If the ``Content-Type`` header is not ``"application/json"``, then a
  404. :exc:`ValueError` will be raised when trying to parse the response.
  405. .. attribute:: request
  406. The request data that stimulated the response.
  407. .. attribute:: wsgi_request
  408. The ``WSGIRequest`` instance generated by the test handler that
  409. generated the response.
  410. .. attribute:: status_code
  411. The HTTP status of the response, as an integer. For a full list
  412. of defined codes, see the `IANA status code registry`_.
  413. .. _IANA status code registry: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  414. .. attribute:: templates
  415. A list of ``Template`` instances used to render the final content, in
  416. the order they were rendered. For each template in the list, use
  417. ``template.name`` to get the template's file name, if the template was
  418. loaded from a file. (The name is a string such as
  419. ``'admin/index.html'``.)
  420. .. admonition:: Not using Django templates?
  421. This attribute is only populated when using the
  422. :class:`~django.template.backends.django.DjangoTemplates` backend.
  423. If you're using another template engine,
  424. :attr:`~django.template.response.SimpleTemplateResponse.template_name`
  425. may be a suitable alternative if you only need the name of the
  426. template used for rendering.
  427. .. attribute:: resolver_match
  428. An instance of :class:`~django.urls.ResolverMatch` for the response.
  429. You can use the :attr:`~django.urls.ResolverMatch.func` attribute, for
  430. example, to verify the view that served the response::
  431. # my_view here is a function based view.
  432. self.assertEqual(response.resolver_match.func, my_view)
  433. # Class-based views need to compare the view_class, as the
  434. # functions generated by as_view() won't be equal.
  435. self.assertIs(response.resolver_match.func.view_class, MyView)
  436. If the given URL is not found, accessing this attribute will raise a
  437. :exc:`~django.urls.Resolver404` exception.
  438. As with a normal response, you can also access the headers through
  439. :attr:`.HttpResponse.headers`. For example, you could determine the content
  440. type of a response using ``response.headers['Content-Type']``.
  441. Exceptions
  442. ----------
  443. If you point the test client at a view that raises an exception and
  444. ``Client.raise_request_exception`` is ``True``, that exception will be visible
  445. in the test case. You can then use a standard ``try ... except`` block or
  446. :meth:`~unittest.TestCase.assertRaises` to test for exceptions.
  447. The only exceptions that are not visible to the test client are
  448. :class:`~django.http.Http404`,
  449. :class:`~django.core.exceptions.PermissionDenied`, :exc:`SystemExit`, and
  450. :class:`~django.core.exceptions.SuspiciousOperation`. Django catches these
  451. exceptions internally and converts them into the appropriate HTTP response
  452. codes. In these cases, you can check ``response.status_code`` in your test.
  453. If ``Client.raise_request_exception`` is ``False``, the test client will return a
  454. 500 response as would be returned to a browser. The response has the attribute
  455. :attr:`~Response.exc_info` to provide information about the unhandled
  456. exception.
  457. Persistent state
  458. ----------------
  459. The test client is stateful. If a response returns a cookie, then that cookie
  460. will be stored in the test client and sent with all subsequent ``get()`` and
  461. ``post()`` requests.
  462. Expiration policies for these cookies are not followed. If you want a cookie
  463. to expire, either delete it manually or create a new ``Client`` instance (which
  464. will effectively delete all cookies).
  465. A test client has attributes that store persistent state information. You can
  466. access these properties as part of a test condition.
  467. .. attribute:: Client.cookies
  468. A Python :class:`~http.cookies.SimpleCookie` object, containing the current
  469. values of all the client cookies. See the documentation of the
  470. :mod:`http.cookies` module for more.
  471. .. attribute:: Client.session
  472. A dictionary-like object containing session information. See the
  473. :doc:`session documentation</topics/http/sessions>` for full details.
  474. To modify the session and then save it, it must be stored in a variable
  475. first (because a new ``SessionStore`` is created every time this property
  476. is accessed)::
  477. def test_something(self):
  478. session = self.client.session
  479. session['somekey'] = 'test'
  480. session.save()
  481. Setting the language
  482. --------------------
  483. When testing applications that support internationalization and localization,
  484. you might want to set the language for a test client request. The method for
  485. doing so depends on whether or not the
  486. :class:`~django.middleware.locale.LocaleMiddleware` is enabled.
  487. If the middleware is enabled, the language can be set by creating a cookie with
  488. a name of :setting:`LANGUAGE_COOKIE_NAME` and a value of the language code::
  489. from django.conf import settings
  490. def test_language_using_cookie(self):
  491. self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: 'fr'})
  492. response = self.client.get('/')
  493. self.assertEqual(response.content, b"Bienvenue sur mon site.")
  494. or by including the ``Accept-Language`` HTTP header in the request::
  495. def test_language_using_header(self):
  496. response = self.client.get("/", headers={"accept-language": "fr"})
  497. self.assertEqual(response.content, b"Bienvenue sur mon site.")
  498. .. note::
  499. When using these methods, ensure to reset the active language at the end of
  500. each test::
  501. def tearDown(self):
  502. translation.activate(settings.LANGUAGE_CODE)
  503. More details are in :ref:`how-django-discovers-language-preference`.
  504. If the middleware isn't enabled, the active language may be set using
  505. :func:`.translation.override`::
  506. from django.utils import translation
  507. def test_language_using_override(self):
  508. with translation.override('fr'):
  509. response = self.client.get('/')
  510. self.assertEqual(response.content, b"Bienvenue sur mon site.")
  511. More details are in :ref:`explicitly-setting-the-active-language`.
  512. Example
  513. -------
  514. The following is a unit test using the test client::
  515. import unittest
  516. from django.test import Client
  517. class SimpleTest(unittest.TestCase):
  518. def setUp(self):
  519. # Every test needs a client.
  520. self.client = Client()
  521. def test_details(self):
  522. # Issue a GET request.
  523. response = self.client.get('/customer/details/')
  524. # Check that the response is 200 OK.
  525. self.assertEqual(response.status_code, 200)
  526. # Check that the rendered context contains 5 customers.
  527. self.assertEqual(len(response.context['customers']), 5)
  528. .. seealso::
  529. :class:`django.test.RequestFactory`
  530. .. _django-testcase-subclasses:
  531. Provided test case classes
  532. ==========================
  533. Normal Python unit test classes extend a base class of
  534. :class:`unittest.TestCase`. Django provides a few extensions of this base class:
  535. .. _testcase_hierarchy_diagram:
  536. .. figure:: _images/django_unittest_classes_hierarchy.*
  537. :alt: Hierarchy of Django unit testing classes (TestCase subclasses)
  538. :width: 508
  539. :height: 328
  540. Hierarchy of Django unit testing classes
  541. You can convert a normal :class:`unittest.TestCase` to any of the subclasses:
  542. change the base class of your test from ``unittest.TestCase`` to the subclass.
  543. All of the standard Python unit test functionality will be available, and it
  544. will be augmented with some useful additions as described in each section
  545. below.
  546. ``SimpleTestCase``
  547. ------------------
  548. .. class:: SimpleTestCase()
  549. A subclass of :class:`unittest.TestCase` that adds this functionality:
  550. * Some useful assertions like:
  551. * Checking that a callable :meth:`raises a certain exception
  552. <SimpleTestCase.assertRaisesMessage>`.
  553. * Checking that a callable :meth:`triggers a certain warning
  554. <SimpleTestCase.assertWarnsMessage>`.
  555. * Testing form field :meth:`rendering and error treatment
  556. <SimpleTestCase.assertFieldOutput>`.
  557. * Testing :meth:`HTML responses for the presence/lack of a given fragment
  558. <SimpleTestCase.assertContains>`.
  559. * Verifying that a template :meth:`has/hasn't been used to generate a given
  560. response content <SimpleTestCase.assertTemplateUsed>`.
  561. * Verifying that two :meth:`URLs <SimpleTestCase.assertURLEqual>` are equal.
  562. * Verifying an HTTP :meth:`redirect <SimpleTestCase.assertRedirects>` is
  563. performed by the app.
  564. * Robustly testing two :meth:`HTML fragments <SimpleTestCase.assertHTMLEqual>`
  565. for equality/inequality or :meth:`containment <SimpleTestCase.assertInHTML>`.
  566. * Robustly testing two :meth:`XML fragments <SimpleTestCase.assertXMLEqual>`
  567. for equality/inequality.
  568. * Robustly testing two :meth:`JSON fragments <SimpleTestCase.assertJSONEqual>`
  569. for equality.
  570. * The ability to run tests with :ref:`modified settings <overriding-settings>`.
  571. * Using the :attr:`~SimpleTestCase.client` :class:`~django.test.Client`.
  572. If your tests make any database queries, use subclasses
  573. :class:`~django.test.TransactionTestCase` or :class:`~django.test.TestCase`.
  574. .. attribute:: SimpleTestCase.databases
  575. :class:`~SimpleTestCase` disallows database queries by default. This
  576. helps to avoid executing write queries which will affect other tests
  577. since each ``SimpleTestCase`` test isn't run in a transaction. If you
  578. aren't concerned about this problem, you can disable this behavior by
  579. setting the ``databases`` class attribute to ``'__all__'`` on your test
  580. class.
  581. .. warning::
  582. ``SimpleTestCase`` and its subclasses (e.g. ``TestCase``, ...) rely on
  583. ``setUpClass()`` and ``tearDownClass()`` to perform some class-wide
  584. initialization (e.g. overriding settings). If you need to override those
  585. methods, don't forget to call the ``super`` implementation::
  586. class MyTestCase(TestCase):
  587. @classmethod
  588. def setUpClass(cls):
  589. super().setUpClass()
  590. ...
  591. @classmethod
  592. def tearDownClass(cls):
  593. ...
  594. super().tearDownClass()
  595. Be sure to account for Python's behavior if an exception is raised during
  596. ``setUpClass()``. If that happens, neither the tests in the class nor
  597. ``tearDownClass()`` are run. In the case of :class:`django.test.TestCase`,
  598. this will leak the transaction created in ``super()`` which results in
  599. various symptoms including a segmentation fault on some platforms (reported
  600. on macOS). If you want to intentionally raise an exception such as
  601. :exc:`unittest.SkipTest` in ``setUpClass()``, be sure to do it before
  602. calling ``super()`` to avoid this.
  603. ``TransactionTestCase``
  604. -----------------------
  605. .. class:: TransactionTestCase()
  606. ``TransactionTestCase`` inherits from :class:`~django.test.SimpleTestCase` to
  607. add some database-specific features:
  608. * Resetting the database to a known state at the beginning of each test to
  609. ease testing and using the ORM.
  610. * Database :attr:`~TransactionTestCase.fixtures`.
  611. * Test :ref:`skipping based on database backend features <skipping-tests>`.
  612. * The remaining specialized :meth:`assert*
  613. <TransactionTestCase.assertQuerySetEqual>` methods.
  614. Django's :class:`TestCase` class is a more commonly used subclass of
  615. ``TransactionTestCase`` that makes use of database transaction facilities
  616. to speed up the process of resetting the database to a known state at the
  617. beginning of each test. A consequence of this, however, is that some database
  618. behaviors cannot be tested within a Django ``TestCase`` class. For instance,
  619. you cannot test that a block of code is executing within a transaction, as is
  620. required when using
  621. :meth:`~django.db.models.query.QuerySet.select_for_update()`. In those cases,
  622. you should use ``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. This guarantees that the rollback at the end of
  632. the test restores the database to its initial state.
  633. .. warning::
  634. ``TestCase`` running on a database that does not support rollback (e.g. MySQL
  635. with the MyISAM storage engine), and all instances of ``TransactionTestCase``,
  636. will roll back at the end of the test by deleting all data from the test
  637. database.
  638. Apps :ref:`will not see their data reloaded <test-case-serialized-rollback>`;
  639. if you need this functionality (for example, third-party apps should enable
  640. this) you can set ``serialized_rollback = True`` inside the
  641. ``TestCase`` body.
  642. ``TestCase``
  643. ------------
  644. .. class:: TestCase()
  645. This is the most common class to use for writing tests in Django. It inherits
  646. from :class:`TransactionTestCase` (and by extension :class:`SimpleTestCase`).
  647. If your Django application doesn't use a database, use :class:`SimpleTestCase`.
  648. The class:
  649. * Wraps the tests within two nested :func:`~django.db.transaction.atomic`
  650. blocks: one for the whole class and one for each test. Therefore, if you want
  651. to test some specific database transaction behavior, use
  652. :class:`TransactionTestCase`.
  653. * Checks deferrable database constraints at the end of each test.
  654. It also provides an additional method:
  655. .. classmethod:: TestCase.setUpTestData()
  656. The class-level ``atomic`` block described above allows the creation of
  657. initial data at the class level, once for the whole ``TestCase``. This
  658. technique allows for faster tests as compared to using ``setUp()``.
  659. For example::
  660. from django.test import TestCase
  661. class MyTests(TestCase):
  662. @classmethod
  663. def setUpTestData(cls):
  664. # Set up data for the whole TestCase
  665. cls.foo = Foo.objects.create(bar="Test")
  666. ...
  667. def test1(self):
  668. # Some test using self.foo
  669. ...
  670. def test2(self):
  671. # Some other test using self.foo
  672. ...
  673. Note that if the tests are run on a database with no transaction support
  674. (for instance, MySQL with the MyISAM engine), ``setUpTestData()`` will be
  675. called before each test, negating the speed benefits.
  676. Objects assigned to class attributes in ``setUpTestData()`` must support
  677. creating deep copies with :py:func:`copy.deepcopy` in order to isolate them
  678. from alterations performed by each test methods.
  679. .. classmethod:: TestCase.captureOnCommitCallbacks(using=DEFAULT_DB_ALIAS, execute=False)
  680. Returns a context manager that captures :func:`transaction.on_commit()
  681. <django.db.transaction.on_commit>` callbacks for the given database
  682. connection. It returns a list that contains, on exit of the context, the
  683. captured callback functions. From this list you can make assertions on the
  684. callbacks or call them to invoke their side effects, emulating a commit.
  685. ``using`` is the alias of the database connection to capture callbacks for.
  686. If ``execute`` is ``True``, all the callbacks will be called as the context
  687. manager exits, if no exception occurred. This emulates a commit after the
  688. wrapped block of code.
  689. For example::
  690. from django.core import mail
  691. from django.test import TestCase
  692. class ContactTests(TestCase):
  693. def test_post(self):
  694. with self.captureOnCommitCallbacks(execute=True) as callbacks:
  695. response = self.client.post(
  696. '/contact/',
  697. {'message': 'I like your site'},
  698. )
  699. self.assertEqual(response.status_code, 200)
  700. self.assertEqual(len(callbacks), 1)
  701. self.assertEqual(len(mail.outbox), 1)
  702. self.assertEqual(mail.outbox[0].subject, 'Contact Form')
  703. self.assertEqual(mail.outbox[0].body, 'I like your site')
  704. .. _live-test-server:
  705. ``LiveServerTestCase``
  706. ----------------------
  707. .. class:: LiveServerTestCase()
  708. ``LiveServerTestCase`` does basically the same as
  709. :class:`~django.test.TransactionTestCase` with one extra feature: it launches a
  710. live Django server in the background on setup, and shuts it down on teardown.
  711. This allows the use of automated test clients other than the
  712. :ref:`Django dummy client <test-client>` such as, for example, the Selenium_
  713. client, to execute a series of functional tests inside a browser and simulate a
  714. real user's actions.
  715. The live server listens on ``localhost`` and binds to port 0 which uses a free
  716. port assigned by the operating system. The server's URL can be accessed with
  717. ``self.live_server_url`` during the tests.
  718. To demonstrate how to use ``LiveServerTestCase``, let's write a Selenium test.
  719. First of all, you need to install the `selenium package`_ into your Python
  720. path:
  721. .. console::
  722. $ python -m pip install selenium
  723. Then, add a ``LiveServerTestCase``-based test to your app's tests module
  724. (for example: ``myapp/tests.py``). For this example, we'll assume you're using
  725. the :mod:`~django.contrib.staticfiles` app and want to have static files served
  726. during the execution of your tests similar to what we get at development time
  727. with ``DEBUG=True``, i.e. without having to collect them using
  728. :djadmin:`collectstatic`. We'll use
  729. the :class:`~django.contrib.staticfiles.testing.StaticLiveServerTestCase`
  730. subclass which provides that functionality. Replace it with
  731. ``django.test.LiveServerTestCase`` if you don't need that.
  732. The code for this test may look as follows::
  733. from django.contrib.staticfiles.testing import StaticLiveServerTestCase
  734. from selenium.webdriver.common.by import By
  735. from selenium.webdriver.firefox.webdriver import WebDriver
  736. class MySeleniumTests(StaticLiveServerTestCase):
  737. fixtures = ['user-data.json']
  738. @classmethod
  739. def setUpClass(cls):
  740. super().setUpClass()
  741. cls.selenium = WebDriver()
  742. cls.selenium.implicitly_wait(10)
  743. @classmethod
  744. def tearDownClass(cls):
  745. cls.selenium.quit()
  746. super().tearDownClass()
  747. def test_login(self):
  748. self.selenium.get(f'{self.live_server_url}/login/')
  749. username_input = self.selenium.find_element(By.NAME, "username")
  750. username_input.send_keys('myuser')
  751. password_input = self.selenium.find_element(By.NAME, "password")
  752. password_input.send_keys('secret')
  753. self.selenium.find_element(By.XPATH, '//input[@value="Log in"]').click()
  754. Finally, you may run the test as follows:
  755. .. console::
  756. $ ./manage.py test myapp.tests.MySeleniumTests.test_login
  757. This example will automatically open Firefox then go to the login page, enter
  758. the credentials and press the "Log in" button. Selenium offers other drivers in
  759. case you do not have Firefox installed or wish to use another browser. The
  760. example above is just a tiny fraction of what the Selenium client can do; check
  761. out the `full reference`_ for more details.
  762. .. _Selenium: https://www.selenium.dev/
  763. .. _selenium package: https://pypi.org/project/selenium/
  764. .. _full reference: https://selenium-python.readthedocs.io/api.html
  765. .. _Firefox: https://www.mozilla.com/firefox/
  766. .. note::
  767. When using an in-memory SQLite database to run the tests, the same database
  768. connection will be shared by two threads in parallel: the thread in which
  769. the live server is run and the thread in which the test case is run. It's
  770. important to prevent simultaneous database queries via this shared
  771. connection by the two threads, as that may sometimes randomly cause the
  772. tests to fail. So you need to ensure that the two threads don't access the
  773. database at the same time. In particular, this means that in some cases
  774. (for example, just after clicking a link or submitting a form), you might
  775. need to check that a response is received by Selenium and that the next
  776. page is loaded before proceeding with further test execution.
  777. Do this, for example, by making Selenium wait until the ``<body>`` HTML tag
  778. is found in the response (requires Selenium > 2.13)::
  779. def test_login(self):
  780. from selenium.webdriver.support.wait import WebDriverWait
  781. timeout = 2
  782. ...
  783. self.selenium.find_element(By.XPATH, '//input[@value="Log in"]').click()
  784. # Wait until the response is received
  785. WebDriverWait(self.selenium, timeout).until(
  786. lambda driver: driver.find_element(By.TAG_NAME, 'body'))
  787. The tricky thing here is that there's really no such thing as a "page load,"
  788. especially in modern web apps that generate HTML dynamically after the
  789. server generates the initial document. So, checking for the presence of
  790. ``<body>`` in the response might not necessarily be appropriate for all use
  791. cases. Please refer to the `Selenium FAQ`_ and `Selenium documentation`_
  792. for more information.
  793. .. _Selenium FAQ: https://web.archive.org/web/20160129132110/http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_WebDriver_fails_to_find_elements_/_Does_not_block_on_page_loa
  794. .. _Selenium documentation: https://www.selenium.dev/documentation/webdriver/waits/#explicit-wait
  795. Test cases features
  796. ===================
  797. Default test client
  798. -------------------
  799. .. attribute:: SimpleTestCase.client
  800. Every test case in a ``django.test.*TestCase`` instance has access to an
  801. instance of a Django test client. This client can be accessed as
  802. ``self.client``. This client is recreated for each test, so you don't have to
  803. worry about state (such as cookies) carrying over from one test to another.
  804. This means, instead of instantiating a ``Client`` in each test::
  805. import unittest
  806. from django.test import Client
  807. class SimpleTest(unittest.TestCase):
  808. def test_details(self):
  809. client = Client()
  810. response = client.get('/customer/details/')
  811. self.assertEqual(response.status_code, 200)
  812. def test_index(self):
  813. client = Client()
  814. response = client.get('/customer/index/')
  815. self.assertEqual(response.status_code, 200)
  816. ...you can refer to ``self.client``, like so::
  817. from django.test import TestCase
  818. class SimpleTest(TestCase):
  819. def test_details(self):
  820. response = self.client.get('/customer/details/')
  821. self.assertEqual(response.status_code, 200)
  822. def test_index(self):
  823. response = self.client.get('/customer/index/')
  824. self.assertEqual(response.status_code, 200)
  825. Customizing the test client
  826. ---------------------------
  827. .. attribute:: SimpleTestCase.client_class
  828. If you want to use a different ``Client`` class (for example, a subclass
  829. with customized behavior), use the :attr:`~SimpleTestCase.client_class` class
  830. attribute::
  831. from django.test import Client, TestCase
  832. class MyTestClient(Client):
  833. # Specialized methods for your environment
  834. ...
  835. class MyTest(TestCase):
  836. client_class = MyTestClient
  837. def test_my_stuff(self):
  838. # Here self.client is an instance of MyTestClient...
  839. call_some_test_code()
  840. .. _topics-testing-fixtures:
  841. Fixture loading
  842. ---------------
  843. .. attribute:: TransactionTestCase.fixtures
  844. A test case for a database-backed website isn't much use if there isn't any
  845. data in the database. Tests are more readable and it's more maintainable to
  846. create objects using the ORM, for example in :meth:`TestCase.setUpTestData`,
  847. however, you can also use :ref:`fixtures <fixtures-explanation>`.
  848. A fixture is a collection of data that Django knows how to import into a
  849. database. For example, if your site has user accounts, you might set up a
  850. fixture of fake user accounts in order to populate your database during tests.
  851. The most straightforward way of creating a fixture is to use the
  852. :djadmin:`manage.py dumpdata <dumpdata>` command. This assumes you
  853. already have some data in your database. See the :djadmin:`dumpdata
  854. documentation<dumpdata>` for more details.
  855. Once you've created a fixture and placed it in a ``fixtures`` directory in one
  856. of your :setting:`INSTALLED_APPS`, you can use it in your unit tests by
  857. specifying a ``fixtures`` class attribute on your :class:`django.test.TestCase`
  858. subclass::
  859. from django.test import TestCase
  860. from myapp.models import Animal
  861. class AnimalTestCase(TestCase):
  862. fixtures = ['mammals.json', 'birds']
  863. def setUp(self):
  864. # Test definitions as before.
  865. call_setup_methods()
  866. def test_fluffy_animals(self):
  867. # A test that uses the fixtures.
  868. call_some_test_code()
  869. Here's specifically what will happen:
  870. * At the start of each test, before ``setUp()`` is run, Django will flush the
  871. database, returning the database to the state it was in directly after
  872. :djadmin:`migrate` was called.
  873. * Then, all the named fixtures are installed. In this example, Django will
  874. install any JSON fixture named ``mammals``, followed by any fixture named
  875. ``birds``. See the :ref:`fixtures-explanation` topic for more details on
  876. defining and installing fixtures.
  877. For performance reasons, :class:`TestCase` loads fixtures once for the entire
  878. test class, before :meth:`~TestCase.setUpTestData`, instead of before each
  879. test, and it uses transactions to clean the database before each test. In any case,
  880. you can be certain that the outcome of a test will not be affected by another
  881. test or by the order of test execution.
  882. By default, fixtures are only loaded into the ``default`` database. If you are
  883. using multiple databases and set :attr:`TransactionTestCase.databases`,
  884. fixtures will be loaded into all specified databases.
  885. URLconf configuration
  886. ---------------------
  887. If your application provides views, you may want to include tests that use the
  888. test client to exercise those views. However, an end user is free to deploy the
  889. views in your application at any URL of their choosing. This means that your
  890. tests can't rely upon the fact that your views will be available at a
  891. particular URL. Decorate your test class or test method with
  892. ``@override_settings(ROOT_URLCONF=...)`` for URLconf configuration.
  893. .. _testing-multi-db:
  894. Multi-database support
  895. ----------------------
  896. .. attribute:: TransactionTestCase.databases
  897. Django sets up a test database corresponding to every database that is
  898. defined in the :setting:`DATABASES` definition in your settings and referred to
  899. by at least one test through ``databases``.
  900. However, a big part of the time taken to run a Django ``TestCase`` is consumed
  901. by the call to ``flush`` that ensures that you have a clean database at the
  902. start of each test run. If you have multiple databases, multiple flushes are
  903. required (one for each database), which can be a time consuming activity --
  904. especially if your tests don't need to test multi-database activity.
  905. As an optimization, Django only flushes the ``default`` database at
  906. the start of each test run. If your setup contains multiple databases,
  907. and you have a test that requires every database to be clean, you can
  908. use the ``databases`` attribute on the test suite to request extra databases
  909. to be flushed.
  910. For example::
  911. class TestMyViews(TransactionTestCase):
  912. databases = {'default', 'other'}
  913. def test_index_page_view(self):
  914. call_some_test_code()
  915. This test case will flush the ``default`` and ``other`` test databases before
  916. running ``test_index_page_view``. You can also use ``'__all__'`` to specify
  917. that all of the test databases must be flushed.
  918. The ``databases`` flag also controls which databases the
  919. :attr:`TransactionTestCase.fixtures` are loaded into. By default, fixtures are
  920. only loaded into the ``default`` database.
  921. Queries against databases not in ``databases`` will give assertion errors to
  922. prevent state leaking between tests.
  923. .. attribute:: TestCase.databases
  924. By default, only the ``default`` database will be wrapped in a transaction
  925. during a ``TestCase``'s execution and attempts to query other databases will
  926. result in assertion errors to prevent state leaking between tests.
  927. Use the ``databases`` class attribute on the test class to request transaction
  928. wrapping against non-``default`` databases.
  929. For example::
  930. class OtherDBTests(TestCase):
  931. databases = {'other'}
  932. def test_other_db_query(self):
  933. ...
  934. This test will only allow queries against the ``other`` database. Just like for
  935. :attr:`SimpleTestCase.databases` and :attr:`TransactionTestCase.databases`, the
  936. ``'__all__'`` constant can be used to specify that the test should allow
  937. queries to all databases.
  938. .. _overriding-settings:
  939. Overriding settings
  940. -------------------
  941. .. warning::
  942. Use the functions below to temporarily alter the value of settings in tests.
  943. Don't manipulate ``django.conf.settings`` directly as Django won't restore
  944. the original values after such manipulations.
  945. .. method:: SimpleTestCase.settings()
  946. For testing purposes it's often useful to change a setting temporarily and
  947. revert to the original value after running the testing code. For this use case
  948. Django provides a standard Python context manager (see :pep:`343`) called
  949. :meth:`~django.test.SimpleTestCase.settings`, which can be used like this::
  950. from django.test import TestCase
  951. class LoginTestCase(TestCase):
  952. def test_login(self):
  953. # First check for the default behavior
  954. response = self.client.get('/sekrit/')
  955. self.assertRedirects(response, '/accounts/login/?next=/sekrit/')
  956. # Then override the LOGIN_URL setting
  957. with self.settings(LOGIN_URL='/other/login/'):
  958. response = self.client.get('/sekrit/')
  959. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  960. This example will override the :setting:`LOGIN_URL` setting for the code
  961. in the ``with`` block and reset its value to the previous state afterward.
  962. .. method:: SimpleTestCase.modify_settings()
  963. It can prove unwieldy to redefine settings that contain a list of values. In
  964. practice, adding or removing values is often sufficient. Django provides the
  965. :meth:`~django.test.SimpleTestCase.modify_settings` context manager for easier
  966. settings changes::
  967. from django.test import TestCase
  968. class MiddlewareTestCase(TestCase):
  969. def test_cache_middleware(self):
  970. with self.modify_settings(MIDDLEWARE={
  971. 'append': 'django.middleware.cache.FetchFromCacheMiddleware',
  972. 'prepend': 'django.middleware.cache.UpdateCacheMiddleware',
  973. 'remove': [
  974. 'django.contrib.sessions.middleware.SessionMiddleware',
  975. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  976. 'django.contrib.messages.middleware.MessageMiddleware',
  977. ],
  978. }):
  979. response = self.client.get('/')
  980. # ...
  981. For each action, you can supply either a list of values or a string. When the
  982. value already exists in the list, ``append`` and ``prepend`` have no effect;
  983. neither does ``remove`` when the value doesn't exist.
  984. .. function:: override_settings(**kwargs)
  985. In case you want to override a setting for a test method, Django provides the
  986. :func:`~django.test.override_settings` decorator (see :pep:`318`). It's used
  987. like this::
  988. from django.test import TestCase, override_settings
  989. class LoginTestCase(TestCase):
  990. @override_settings(LOGIN_URL='/other/login/')
  991. def test_login(self):
  992. response = self.client.get('/sekrit/')
  993. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  994. The decorator can also be applied to :class:`~django.test.TestCase` classes::
  995. from django.test import TestCase, override_settings
  996. @override_settings(LOGIN_URL='/other/login/')
  997. class LoginTestCase(TestCase):
  998. def test_login(self):
  999. response = self.client.get('/sekrit/')
  1000. self.assertRedirects(response, '/other/login/?next=/sekrit/')
  1001. .. function:: modify_settings(*args, **kwargs)
  1002. Likewise, Django provides the :func:`~django.test.modify_settings`
  1003. decorator::
  1004. from django.test import TestCase, modify_settings
  1005. class MiddlewareTestCase(TestCase):
  1006. @modify_settings(MIDDLEWARE={
  1007. 'append': 'django.middleware.cache.FetchFromCacheMiddleware',
  1008. 'prepend': 'django.middleware.cache.UpdateCacheMiddleware',
  1009. })
  1010. def test_cache_middleware(self):
  1011. response = self.client.get('/')
  1012. # ...
  1013. The decorator can also be applied to test case classes::
  1014. from django.test import TestCase, modify_settings
  1015. @modify_settings(MIDDLEWARE={
  1016. 'append': 'django.middleware.cache.FetchFromCacheMiddleware',
  1017. 'prepend': 'django.middleware.cache.UpdateCacheMiddleware',
  1018. })
  1019. class MiddlewareTestCase(TestCase):
  1020. def test_cache_middleware(self):
  1021. response = self.client.get('/')
  1022. # ...
  1023. .. note::
  1024. When given a class, these decorators modify the class directly and return
  1025. it; they don't create and return a modified copy of it. So if you try to
  1026. tweak the above examples to assign the return value to a different name
  1027. than ``LoginTestCase`` or ``MiddlewareTestCase``, you may be surprised to
  1028. find that the original test case classes are still equally affected by the
  1029. decorator. For a given class, :func:`~django.test.modify_settings` is
  1030. always applied after :func:`~django.test.override_settings`.
  1031. .. warning::
  1032. The settings file contains some settings that are only consulted during
  1033. initialization of Django internals. If you change them with
  1034. ``override_settings``, the setting is changed if you access it via the
  1035. ``django.conf.settings`` module, however, Django's internals access it
  1036. differently. Effectively, using :func:`~django.test.override_settings` or
  1037. :func:`~django.test.modify_settings` with these settings is probably not
  1038. going to do what you expect it to do.
  1039. We do not recommend altering the :setting:`DATABASES` setting. Altering
  1040. the :setting:`CACHES` setting is possible, but a bit tricky if you are
  1041. using internals that make using of caching, like
  1042. :mod:`django.contrib.sessions`. For example, you will have to reinitialize
  1043. the session backend in a test that uses cached sessions and overrides
  1044. :setting:`CACHES`.
  1045. Finally, avoid aliasing your settings as module-level constants as
  1046. ``override_settings()`` won't work on such values since they are
  1047. only evaluated the first time the module is imported.
  1048. You can also simulate the absence of a setting by deleting it after settings
  1049. have been overridden, like this::
  1050. @override_settings()
  1051. def test_something(self):
  1052. del settings.LOGIN_URL
  1053. ...
  1054. When overriding settings, make sure to handle the cases in which your app's
  1055. code uses a cache or similar feature that retains state even if the setting is
  1056. changed. Django provides the :data:`django.test.signals.setting_changed`
  1057. signal that lets you register callbacks to clean up and otherwise reset state
  1058. when settings are changed.
  1059. Django itself uses this signal to reset various data:
  1060. ============================================================================ ========================
  1061. Overridden settings Data reset
  1062. ============================================================================ ========================
  1063. USE_TZ, TIME_ZONE Databases timezone
  1064. TEMPLATES Template engines
  1065. SERIALIZATION_MODULES Serializers cache
  1066. LOCALE_PATHS, LANGUAGE_CODE Default translation and loaded translations
  1067. DEFAULT_FILE_STORAGE, STATICFILES_STORAGE, STATIC_ROOT, STATIC_URL, STORAGES Storages configuration
  1068. ============================================================================ ========================
  1069. Isolating apps
  1070. --------------
  1071. .. function:: utils.isolate_apps(*app_labels, attr_name=None, kwarg_name=None)
  1072. Registers the models defined within a wrapped context into their own
  1073. isolated :attr:`~django.apps.apps` registry. This functionality is useful
  1074. when creating model classes for tests, as the classes will be cleanly
  1075. deleted afterward, and there is no risk of name collisions.
  1076. The app labels which the isolated registry should contain must be passed as
  1077. individual arguments. You can use ``isolate_apps()`` as a decorator or a
  1078. context manager. For example::
  1079. from django.db import models
  1080. from django.test import SimpleTestCase
  1081. from django.test.utils import isolate_apps
  1082. class MyModelTests(SimpleTestCase):
  1083. @isolate_apps("app_label")
  1084. def test_model_definition(self):
  1085. class TestModel(models.Model):
  1086. pass
  1087. ...
  1088. … or::
  1089. with isolate_apps("app_label"):
  1090. class TestModel(models.Model):
  1091. pass
  1092. ...
  1093. The decorator form can also be applied to classes.
  1094. Two optional keyword arguments can be specified:
  1095. * ``attr_name``: attribute assigned the isolated registry if used as a
  1096. class decorator.
  1097. * ``kwarg_name``: keyword argument passing the isolated registry if used as
  1098. a function decorator.
  1099. The temporary ``Apps`` instance used to isolate model registration can be
  1100. retrieved as an attribute when used as a class decorator by using the
  1101. ``attr_name`` parameter::
  1102. @isolate_apps("app_label", attr_name="apps")
  1103. class TestModelDefinition(SimpleTestCase):
  1104. def test_model_definition(self):
  1105. class TestModel(models.Model):
  1106. pass
  1107. self.assertIs(self.apps.get_model("app_label", "TestModel"), TestModel)
  1108. … or alternatively as an argument on the test method when used as a method
  1109. decorator by using the ``kwarg_name`` parameter::
  1110. class TestModelDefinition(SimpleTestCase):
  1111. @isolate_apps("app_label", kwarg_name="apps")
  1112. def test_model_definition(self, apps):
  1113. class TestModel(models.Model):
  1114. pass
  1115. self.assertIs(apps.get_model("app_label", "TestModel"), TestModel)
  1116. .. _emptying-test-outbox:
  1117. Emptying the test outbox
  1118. ------------------------
  1119. If you use any of Django's custom ``TestCase`` classes, the test runner will
  1120. clear the contents of the test email outbox at the start of each test case.
  1121. For more detail on email services during tests, see `Email services`_ below.
  1122. .. _assertions:
  1123. Assertions
  1124. ----------
  1125. As Python's normal :class:`unittest.TestCase` class implements assertion methods
  1126. such as :meth:`~unittest.TestCase.assertTrue` and
  1127. :meth:`~unittest.TestCase.assertEqual`, Django's custom :class:`TestCase` class
  1128. provides a number of custom assertion methods that are useful for testing web
  1129. applications:
  1130. The failure messages given by most of these assertion methods can be customized
  1131. with the ``msg_prefix`` argument. This string will be prefixed to any failure
  1132. message generated by the assertion. This allows you to provide additional
  1133. details that may help you to identify the location and cause of a failure in
  1134. your test suite.
  1135. .. method:: SimpleTestCase.assertRaisesMessage(expected_exception, expected_message, callable, *args, **kwargs)
  1136. SimpleTestCase.assertRaisesMessage(expected_exception, expected_message)
  1137. Asserts that execution of ``callable`` raises ``expected_exception`` and
  1138. that ``expected_message`` is found in the exception's message. Any other
  1139. outcome is reported as a failure. It's a simpler version of
  1140. :meth:`unittest.TestCase.assertRaisesRegex` with the difference that
  1141. ``expected_message`` isn't treated as a regular expression.
  1142. If only the ``expected_exception`` and ``expected_message`` parameters are
  1143. given, returns a context manager so that the code being tested can be
  1144. written inline rather than as a function::
  1145. with self.assertRaisesMessage(ValueError, 'invalid literal for int()'):
  1146. int('a')
  1147. .. method:: SimpleTestCase.assertWarnsMessage(expected_warning, expected_message, callable, *args, **kwargs)
  1148. SimpleTestCase.assertWarnsMessage(expected_warning, expected_message)
  1149. Analogous to :meth:`SimpleTestCase.assertRaisesMessage` but for
  1150. :meth:`~unittest.TestCase.assertWarnsRegex` instead of
  1151. :meth:`~unittest.TestCase.assertRaisesRegex`.
  1152. .. method:: SimpleTestCase.assertFieldOutput(fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value='')
  1153. Asserts that a form field behaves correctly with various inputs.
  1154. :param fieldclass: the class of the field to be tested.
  1155. :param valid: a dictionary mapping valid inputs to their expected cleaned
  1156. values.
  1157. :param invalid: a dictionary mapping invalid inputs to one or more raised
  1158. error messages.
  1159. :param field_args: the args passed to instantiate the field.
  1160. :param field_kwargs: the kwargs passed to instantiate the field.
  1161. :param empty_value: the expected clean output for inputs in ``empty_values``.
  1162. For example, the following code tests that an ``EmailField`` accepts
  1163. ``a@a.com`` as a valid email address, but rejects ``aaa`` with a reasonable
  1164. error message::
  1165. self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': ['Enter a valid email address.']})
  1166. .. method:: SimpleTestCase.assertFormError(form, field, errors, msg_prefix='')
  1167. Asserts that a field on a form raises the provided list of errors.
  1168. ``form`` is a ``Form`` instance. The form must be
  1169. :ref:`bound <ref-forms-api-bound-unbound>` but not necessarily
  1170. validated (``assertFormError()`` will automatically call ``full_clean()``
  1171. on the form).
  1172. ``field`` is the name of the field on the form to check. To check the form's
  1173. :meth:`non-field errors <django.forms.Form.non_field_errors>`, use
  1174. ``field=None``.
  1175. ``errors`` is a list of all the error strings that the field is expected to
  1176. have. You can also pass a single error string if you only expect one error
  1177. which means that ``errors='error message'`` is the same as
  1178. ``errors=['error message']``.
  1179. .. method:: SimpleTestCase.assertFormSetError(formset, form_index, field, errors, msg_prefix='')
  1180. Asserts that the ``formset`` raises the provided list of errors when
  1181. rendered.
  1182. ``formset`` is a ``FormSet`` instance. The formset must be bound but not
  1183. necessarily validated (``assertFormSetError()`` will automatically call the
  1184. ``full_clean()`` on the formset).
  1185. ``form_index`` is the number of the form within the ``FormSet`` (starting
  1186. from 0). Use ``form_index=None`` to check the formset's non-form errors,
  1187. i.e. the errors you get when calling ``formset.non_form_errors()``. In that
  1188. case you must also use ``field=None``.
  1189. ``field`` and ``errors`` have the same meaning as the parameters to
  1190. ``assertFormError()``.
  1191. .. deprecated:: 4.2
  1192. The ``assertFormsetError()`` assertion method is deprecated. Use
  1193. ``assertFormSetError()`` instead.
  1194. .. method:: SimpleTestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False)
  1195. Asserts that a :class:`response <django.http.HttpResponse>` produced the
  1196. given :attr:`~django.http.HttpResponse.status_code` and that ``text``
  1197. appears in its :attr:`~django.http.HttpResponse.content`. If ``count``
  1198. is provided, ``text`` must occur exactly ``count`` times in the response.
  1199. Set ``html`` to ``True`` to handle ``text`` as HTML. The comparison with
  1200. the response content will be based on HTML semantics instead of
  1201. character-by-character equality. Whitespace is ignored in most cases,
  1202. attribute ordering is not significant. See
  1203. :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
  1204. .. method:: SimpleTestCase.assertNotContains(response, text, status_code=200, msg_prefix='', html=False)
  1205. Asserts that a :class:`response <django.http.HttpResponse>` produced the
  1206. given :attr:`~django.http.HttpResponse.status_code` and that ``text`` does
  1207. *not* appear in its :attr:`~django.http.HttpResponse.content`.
  1208. Set ``html`` to ``True`` to handle ``text`` as HTML. The comparison with
  1209. the response content will be based on HTML semantics instead of
  1210. character-by-character equality. Whitespace is ignored in most cases,
  1211. attribute ordering is not significant. See
  1212. :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
  1213. .. method:: SimpleTestCase.assertTemplateUsed(response, template_name, msg_prefix='', count=None)
  1214. Asserts that the template with the given name was used in rendering the
  1215. response.
  1216. ``response`` must be a response instance returned by the
  1217. :class:`test client <django.test.Response>`.
  1218. ``template_name`` should be a string such as ``'admin/index.html'``.
  1219. The ``count`` argument is an integer indicating the number of times the
  1220. template should be rendered. Default is ``None``, meaning that the template
  1221. should be rendered one or more times.
  1222. You can use this as a context manager, like this::
  1223. with self.assertTemplateUsed('index.html'):
  1224. render_to_string('index.html')
  1225. with self.assertTemplateUsed(template_name='index.html'):
  1226. render_to_string('index.html')
  1227. .. method:: SimpleTestCase.assertTemplateNotUsed(response, template_name, msg_prefix='')
  1228. Asserts that the template with the given name was *not* used in rendering
  1229. the response.
  1230. You can use this as a context manager in the same way as
  1231. :meth:`~SimpleTestCase.assertTemplateUsed`.
  1232. .. method:: SimpleTestCase.assertURLEqual(url1, url2, msg_prefix='')
  1233. Asserts that two URLs are the same, ignoring the order of query string
  1234. parameters except for parameters with the same name. For example,
  1235. ``/path/?x=1&y=2`` is equal to ``/path/?y=2&x=1``, but
  1236. ``/path/?a=1&a=2`` isn't equal to ``/path/?a=2&a=1``.
  1237. .. method:: SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='', fetch_redirect_response=True)
  1238. Asserts that the :class:`response <django.http.HttpResponse>` returned a
  1239. :attr:`~django.http.HttpResponse.status_code` redirect status, redirected
  1240. to ``expected_url`` (including any ``GET`` data), and that the final page
  1241. was received with ``target_status_code``.
  1242. If your request used the ``follow`` argument, the ``expected_url`` and
  1243. ``target_status_code`` will be the url and status code for the final
  1244. point of the redirect chain.
  1245. If ``fetch_redirect_response`` is ``False``, the final page won't be
  1246. loaded. Since the test client can't fetch external URLs, this is
  1247. particularly useful if ``expected_url`` isn't part of your Django app.
  1248. Scheme is handled correctly when making comparisons between two URLs. If
  1249. there isn't any scheme specified in the location where we are redirected to,
  1250. the original request's scheme is used. If present, the scheme in
  1251. ``expected_url`` is the one used to make the comparisons to.
  1252. .. method:: SimpleTestCase.assertHTMLEqual(html1, html2, msg=None)
  1253. Asserts that the strings ``html1`` and ``html2`` are equal. The comparison
  1254. is based on HTML semantics. The comparison takes following things into
  1255. account:
  1256. * Whitespace before and after HTML tags is ignored.
  1257. * All types of whitespace are considered equivalent.
  1258. * All open tags are closed implicitly, e.g. when a surrounding tag is
  1259. closed or the HTML document ends.
  1260. * Empty tags are equivalent to their self-closing version.
  1261. * The ordering of attributes of an HTML element is not significant.
  1262. * Boolean attributes (like ``checked``) without an argument are equal to
  1263. attributes that equal in name and value (see the examples).
  1264. * Text, character references, and entity references that refer to the same
  1265. character are equivalent.
  1266. The following examples are valid tests and don't raise any
  1267. ``AssertionError``::
  1268. self.assertHTMLEqual(
  1269. '<p>Hello <b>&#x27;world&#x27;!</p>',
  1270. '''<p>
  1271. Hello <b>&#39;world&#39;! </b>
  1272. </p>'''
  1273. )
  1274. self.assertHTMLEqual(
  1275. '<input type="checkbox" checked="checked" id="id_accept_terms" />',
  1276. '<input id="id_accept_terms" type="checkbox" checked>'
  1277. )
  1278. ``html1`` and ``html2`` must contain HTML. An ``AssertionError`` will be
  1279. raised if one of them cannot be parsed.
  1280. Output in case of error can be customized with the ``msg`` argument.
  1281. .. method:: SimpleTestCase.assertHTMLNotEqual(html1, html2, msg=None)
  1282. Asserts that the strings ``html1`` and ``html2`` are *not* equal. The
  1283. comparison is based on HTML semantics. See
  1284. :meth:`~SimpleTestCase.assertHTMLEqual` for details.
  1285. ``html1`` and ``html2`` must contain HTML. An ``AssertionError`` will be
  1286. raised if one of them cannot be parsed.
  1287. Output in case of error can be customized with the ``msg`` argument.
  1288. .. method:: SimpleTestCase.assertXMLEqual(xml1, xml2, msg=None)
  1289. Asserts that the strings ``xml1`` and ``xml2`` are equal. The
  1290. comparison is based on XML semantics. Similarly to
  1291. :meth:`~SimpleTestCase.assertHTMLEqual`, the comparison is
  1292. made on parsed content, hence only semantic differences are considered, not
  1293. syntax differences. When invalid XML is passed in any parameter, an
  1294. ``AssertionError`` is always raised, even if both strings are identical.
  1295. XML declaration, document type, processing instructions, and comments are
  1296. ignored. Only the root element and its children are compared.
  1297. Output in case of error can be customized with the ``msg`` argument.
  1298. .. method:: SimpleTestCase.assertXMLNotEqual(xml1, xml2, msg=None)
  1299. Asserts that the strings ``xml1`` and ``xml2`` are *not* equal. The
  1300. comparison is based on XML semantics. See
  1301. :meth:`~SimpleTestCase.assertXMLEqual` for details.
  1302. Output in case of error can be customized with the ``msg`` argument.
  1303. .. method:: SimpleTestCase.assertInHTML(needle, haystack, count=None, msg_prefix='')
  1304. Asserts that the HTML fragment ``needle`` is contained in the ``haystack``
  1305. once.
  1306. If the ``count`` integer argument is specified, then additionally the number
  1307. of ``needle`` occurrences will be strictly verified.
  1308. Whitespace in most cases is ignored, and attribute ordering is not
  1309. significant. See :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
  1310. .. method:: SimpleTestCase.assertJSONEqual(raw, expected_data, msg=None)
  1311. Asserts that the JSON fragments ``raw`` and ``expected_data`` are equal.
  1312. Usual JSON non-significant whitespace rules apply as the heavyweight is
  1313. delegated to the :mod:`json` library.
  1314. Output in case of error can be customized with the ``msg`` argument.
  1315. .. method:: SimpleTestCase.assertJSONNotEqual(raw, expected_data, msg=None)
  1316. Asserts that the JSON fragments ``raw`` and ``expected_data`` are *not* equal.
  1317. See :meth:`~SimpleTestCase.assertJSONEqual` for further details.
  1318. Output in case of error can be customized with the ``msg`` argument.
  1319. .. method:: TransactionTestCase.assertQuerySetEqual(qs, values, transform=None, ordered=True, msg=None)
  1320. Asserts that a queryset ``qs`` matches a particular iterable of values
  1321. ``values``.
  1322. If ``transform`` is provided, ``values`` is compared to a list produced by
  1323. applying ``transform`` to each member of ``qs``.
  1324. By default, the comparison is also ordering dependent. If ``qs`` doesn't
  1325. provide an implicit ordering, you can set the ``ordered`` parameter to
  1326. ``False``, which turns the comparison into a ``collections.Counter`` comparison.
  1327. If the order is undefined (if the given ``qs`` isn't ordered and the
  1328. comparison is against more than one ordered value), a ``ValueError`` is
  1329. raised.
  1330. Output in case of error can be customized with the ``msg`` argument.
  1331. .. deprecated:: 4.2
  1332. The ``assertQuerysetEqual()`` assertion method is deprecated. Use
  1333. ``assertQuerySetEqual()`` instead.
  1334. .. method:: TransactionTestCase.assertNumQueries(num, func, *args, **kwargs)
  1335. Asserts that when ``func`` is called with ``*args`` and ``**kwargs`` that
  1336. ``num`` database queries are executed.
  1337. If a ``"using"`` key is present in ``kwargs`` it is used as the database
  1338. alias for which to check the number of queries::
  1339. self.assertNumQueries(7, using='non_default_db')
  1340. If you wish to call a function with a ``using`` parameter you can do it by
  1341. wrapping the call with a ``lambda`` to add an extra parameter::
  1342. self.assertNumQueries(7, lambda: my_function(using=7))
  1343. You can also use this as a context manager::
  1344. with self.assertNumQueries(2):
  1345. Person.objects.create(name="Aaron")
  1346. Person.objects.create(name="Daniel")
  1347. .. _topics-tagging-tests:
  1348. Tagging tests
  1349. -------------
  1350. You can tag your tests so you can easily run a particular subset. For example,
  1351. you might label fast or slow tests::
  1352. from django.test import tag
  1353. class SampleTestCase(TestCase):
  1354. @tag('fast')
  1355. def test_fast(self):
  1356. ...
  1357. @tag('slow')
  1358. def test_slow(self):
  1359. ...
  1360. @tag('slow', 'core')
  1361. def test_slow_but_core(self):
  1362. ...
  1363. You can also tag a test case::
  1364. @tag('slow', 'core')
  1365. class SampleTestCase(TestCase):
  1366. ...
  1367. Subclasses inherit tags from superclasses, and methods inherit tags from their
  1368. class. Given::
  1369. @tag('foo')
  1370. class SampleTestCaseChild(SampleTestCase):
  1371. @tag('bar')
  1372. def test(self):
  1373. ...
  1374. ``SampleTestCaseChild.test`` will be labeled with ``'slow'``, ``'core'``,
  1375. ``'bar'``, and ``'foo'``.
  1376. Then you can choose which tests to run. For example, to run only fast tests:
  1377. .. console::
  1378. $ ./manage.py test --tag=fast
  1379. Or to run fast tests and the core one (even though it's slow):
  1380. .. console::
  1381. $ ./manage.py test --tag=fast --tag=core
  1382. You can also exclude tests by tag. To run core tests if they are not slow:
  1383. .. console::
  1384. $ ./manage.py test --tag=core --exclude-tag=slow
  1385. :option:`test --exclude-tag` has precedence over :option:`test --tag`, so if a
  1386. test has two tags and you select one of them and exclude the other, the test
  1387. won't be run.
  1388. .. _async-tests:
  1389. Testing asynchronous code
  1390. =========================
  1391. If you merely want to test the output of your asynchronous views, the standard
  1392. test client will run them inside their own asynchronous loop without any extra
  1393. work needed on your part.
  1394. However, if you want to write fully-asynchronous tests for a Django project,
  1395. you will need to take several things into account.
  1396. Firstly, your tests must be ``async def`` methods on the test class (in order
  1397. to give them an asynchronous context). Django will automatically detect
  1398. any ``async def`` tests and wrap them so they run in their own event loop.
  1399. If you are testing from an asynchronous function, you must also use the
  1400. asynchronous test client. This is available as ``django.test.AsyncClient``,
  1401. or as ``self.async_client`` on any test.
  1402. .. class:: AsyncClient(enforce_csrf_checks=False, raise_request_exception=True, *, headers=None, **defaults)
  1403. ``AsyncClient`` has the same methods and signatures as the synchronous (normal)
  1404. test client, with two exceptions:
  1405. * In the initialization, arbitrary keyword arguments in ``defaults`` are added
  1406. directly into the ASGI scope.
  1407. * The ``follow`` parameter is not supported.
  1408. * Headers passed as ``extra`` keyword arguments should not have the ``HTTP_``
  1409. prefix required by the synchronous client (see :meth:`Client.get`). For
  1410. example, here is how to set an HTTP ``Accept`` header:
  1411. .. code-block:: pycon
  1412. >>> c = AsyncClient()
  1413. >>> c.get(
  1414. ... '/customers/details/',
  1415. ... {'name': 'fred', 'age': 7},
  1416. ... ACCEPT='application/json'
  1417. ... )
  1418. .. versionchanged:: 4.2
  1419. The ``headers`` parameter was added.
  1420. Using ``AsyncClient`` any method that makes a request must be awaited::
  1421. async def test_my_thing(self):
  1422. response = await self.async_client.get('/some-url/')
  1423. self.assertEqual(response.status_code, 200)
  1424. The asynchronous client can also call synchronous views; it runs through
  1425. Django's :doc:`asynchronous request path </topics/async>`, which supports both.
  1426. Any view called through the ``AsyncClient`` will get an ``ASGIRequest`` object
  1427. for its ``request`` rather than the ``WSGIRequest`` that the normal client
  1428. creates.
  1429. .. warning::
  1430. If you are using test decorators, they must be async-compatible to ensure
  1431. they work correctly. Django's built-in decorators will behave correctly, but
  1432. third-party ones may appear to not execute (they will "wrap" the wrong part
  1433. of the execution flow and not your test).
  1434. If you need to use these decorators, then you should decorate your test
  1435. methods with :func:`~asgiref.sync.async_to_sync` *inside* of them instead::
  1436. from asgiref.sync import async_to_sync
  1437. from django.test import TestCase
  1438. class MyTests(TestCase):
  1439. @mock.patch(...)
  1440. @async_to_sync
  1441. async def test_my_thing(self):
  1442. ...
  1443. .. _topics-testing-email:
  1444. Email services
  1445. ==============
  1446. If any of your Django views send email using :doc:`Django's email
  1447. functionality </topics/email>`, you probably don't want to send email each time
  1448. you run a test using that view. For this reason, Django's test runner
  1449. automatically redirects all Django-sent email to a dummy outbox. This lets you
  1450. test every aspect of sending email -- from the number of messages sent to the
  1451. contents of each message -- without actually sending the messages.
  1452. The test runner accomplishes this by transparently replacing the normal
  1453. email backend with a testing backend.
  1454. (Don't worry -- this has no effect on any other email senders outside of
  1455. Django, such as your machine's mail server, if you're running one.)
  1456. .. currentmodule:: django.core.mail
  1457. .. data:: django.core.mail.outbox
  1458. During test running, each outgoing email is saved in
  1459. ``django.core.mail.outbox``. This is a list of all
  1460. :class:`~django.core.mail.EmailMessage` instances that have been sent. The
  1461. ``outbox`` attribute is a special attribute that is created *only* when the
  1462. ``locmem`` email backend is used. It doesn't normally exist as part of the
  1463. :mod:`django.core.mail` module and you can't import it directly. The code below
  1464. shows how to access this attribute correctly.
  1465. Here's an example test that examines ``django.core.mail.outbox`` for length
  1466. and contents::
  1467. from django.core import mail
  1468. from django.test import TestCase
  1469. class EmailTest(TestCase):
  1470. def test_send_email(self):
  1471. # Send message.
  1472. mail.send_mail(
  1473. 'Subject here', 'Here is the message.',
  1474. 'from@example.com', ['to@example.com'],
  1475. fail_silently=False,
  1476. )
  1477. # Test that one message has been sent.
  1478. self.assertEqual(len(mail.outbox), 1)
  1479. # Verify that the subject of the first message is correct.
  1480. self.assertEqual(mail.outbox[0].subject, 'Subject here')
  1481. As noted :ref:`previously <emptying-test-outbox>`, the test outbox is emptied
  1482. at the start of every test in a Django ``*TestCase``. To empty the outbox
  1483. manually, assign the empty list to ``mail.outbox``::
  1484. from django.core import mail
  1485. # Empty the test outbox
  1486. mail.outbox = []
  1487. .. _topics-testing-management-commands:
  1488. Management Commands
  1489. ===================
  1490. Management commands can be tested with the
  1491. :func:`~django.core.management.call_command` function. The output can be
  1492. redirected into a ``StringIO`` instance::
  1493. from io import StringIO
  1494. from django.core.management import call_command
  1495. from django.test import TestCase
  1496. class ClosepollTest(TestCase):
  1497. def test_command_output(self):
  1498. out = StringIO()
  1499. call_command('closepoll', stdout=out)
  1500. self.assertIn('Expected output', out.getvalue())
  1501. .. _skipping-tests:
  1502. Skipping tests
  1503. ==============
  1504. .. currentmodule:: django.test
  1505. The unittest library provides the :func:`@skipIf <unittest.skipIf>` and
  1506. :func:`@skipUnless <unittest.skipUnless>` decorators to allow you to skip tests
  1507. if you know ahead of time that those tests are going to fail under certain
  1508. conditions.
  1509. For example, if your test requires a particular optional library in order to
  1510. succeed, you could decorate the test case with :func:`@skipIf
  1511. <unittest.skipIf>`. Then, the test runner will report that the test wasn't
  1512. executed and why, instead of failing the test or omitting the test altogether.
  1513. To supplement these test skipping behaviors, Django provides two
  1514. additional skip decorators. Instead of testing a generic boolean,
  1515. these decorators check the capabilities of the database, and skip the
  1516. test if the database doesn't support a specific named feature.
  1517. The decorators use a string identifier to describe database features.
  1518. This string corresponds to attributes of the database connection
  1519. features class. See
  1520. :source:`django.db.backends.base.features.BaseDatabaseFeatures class
  1521. <django/db/backends/base/features.py>` for a full list of database features
  1522. that can be used as a basis for skipping tests.
  1523. .. function:: skipIfDBFeature(*feature_name_strings)
  1524. Skip the decorated test or ``TestCase`` if all of the named database features
  1525. are supported.
  1526. For example, the following test will not be executed if the database
  1527. supports transactions (e.g., it would *not* run under PostgreSQL, but
  1528. it would under MySQL with MyISAM tables)::
  1529. class MyTests(TestCase):
  1530. @skipIfDBFeature('supports_transactions')
  1531. def test_transaction_behavior(self):
  1532. # ... conditional test code
  1533. pass
  1534. .. function:: skipUnlessDBFeature(*feature_name_strings)
  1535. Skip the decorated test or ``TestCase`` if any of the named database features
  1536. are *not* supported.
  1537. For example, the following test will only be executed if the database
  1538. supports transactions (e.g., it would run under PostgreSQL, but *not*
  1539. under MySQL with MyISAM tables)::
  1540. class MyTests(TestCase):
  1541. @skipUnlessDBFeature('supports_transactions')
  1542. def test_transaction_behavior(self):
  1543. # ... conditional test code
  1544. pass