tools.txt 85 KB

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