testcases.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915
  1. import difflib
  2. import inspect
  3. import json
  4. import logging
  5. import posixpath
  6. import sys
  7. import threading
  8. import unittest
  9. import warnings
  10. from collections import Counter
  11. from contextlib import contextmanager
  12. from copy import copy, deepcopy
  13. from difflib import get_close_matches
  14. from functools import wraps
  15. from unittest.suite import _DebugResult
  16. from unittest.util import safe_repr
  17. from urllib.parse import (
  18. parse_qsl,
  19. unquote,
  20. urlencode,
  21. urljoin,
  22. urlparse,
  23. urlsplit,
  24. urlunparse,
  25. )
  26. from urllib.request import url2pathname
  27. from asgiref.sync import async_to_sync, iscoroutinefunction
  28. from django.apps import apps
  29. from django.conf import settings
  30. from django.core import mail
  31. from django.core.exceptions import ImproperlyConfigured, ValidationError
  32. from django.core.files import locks
  33. from django.core.handlers.wsgi import WSGIHandler, get_path_info
  34. from django.core.management import call_command
  35. from django.core.management.color import no_style
  36. from django.core.management.sql import emit_post_migrate_signal
  37. from django.core.servers.basehttp import ThreadedWSGIServer, WSGIRequestHandler
  38. from django.core.signals import setting_changed
  39. from django.db import DEFAULT_DB_ALIAS, connection, connections, transaction
  40. from django.forms.fields import CharField
  41. from django.http import QueryDict
  42. from django.http.request import split_domain_port, validate_host
  43. from django.http.response import HttpResponseBase
  44. from django.test.client import AsyncClient, Client
  45. from django.test.html import HTMLParseError, parse_html
  46. from django.test.signals import template_rendered
  47. from django.test.utils import (
  48. CaptureQueriesContext,
  49. ContextList,
  50. compare_xml,
  51. modify_settings,
  52. override_settings,
  53. )
  54. from django.utils.deprecation import RemovedInDjango50Warning, RemovedInDjango51Warning
  55. from django.utils.functional import classproperty
  56. from django.utils.version import PY310
  57. from django.views.static import serve
  58. logger = logging.getLogger("django.test")
  59. __all__ = (
  60. "TestCase",
  61. "TransactionTestCase",
  62. "SimpleTestCase",
  63. "skipIfDBFeature",
  64. "skipUnlessDBFeature",
  65. )
  66. def to_list(value):
  67. """Put value into a list if it's not already one."""
  68. if not isinstance(value, list):
  69. value = [value]
  70. return value
  71. def assert_and_parse_html(self, html, user_msg, msg):
  72. try:
  73. dom = parse_html(html)
  74. except HTMLParseError as e:
  75. standardMsg = "%s\n%s" % (msg, e)
  76. self.fail(self._formatMessage(user_msg, standardMsg))
  77. return dom
  78. class _AssertNumQueriesContext(CaptureQueriesContext):
  79. def __init__(self, test_case, num, connection):
  80. self.test_case = test_case
  81. self.num = num
  82. super().__init__(connection)
  83. def __exit__(self, exc_type, exc_value, traceback):
  84. super().__exit__(exc_type, exc_value, traceback)
  85. if exc_type is not None:
  86. return
  87. executed = len(self)
  88. self.test_case.assertEqual(
  89. executed,
  90. self.num,
  91. "%d queries executed, %d expected\nCaptured queries were:\n%s"
  92. % (
  93. executed,
  94. self.num,
  95. "\n".join(
  96. "%d. %s" % (i, query["sql"])
  97. for i, query in enumerate(self.captured_queries, start=1)
  98. ),
  99. ),
  100. )
  101. class _AssertTemplateUsedContext:
  102. def __init__(self, test_case, template_name, msg_prefix="", count=None):
  103. self.test_case = test_case
  104. self.template_name = template_name
  105. self.msg_prefix = msg_prefix
  106. self.count = count
  107. self.rendered_templates = []
  108. self.rendered_template_names = []
  109. self.context = ContextList()
  110. def on_template_render(self, sender, signal, template, context, **kwargs):
  111. self.rendered_templates.append(template)
  112. self.rendered_template_names.append(template.name)
  113. self.context.append(copy(context))
  114. def test(self):
  115. self.test_case._assert_template_used(
  116. self.template_name,
  117. self.rendered_template_names,
  118. self.msg_prefix,
  119. self.count,
  120. )
  121. def __enter__(self):
  122. template_rendered.connect(self.on_template_render)
  123. return self
  124. def __exit__(self, exc_type, exc_value, traceback):
  125. template_rendered.disconnect(self.on_template_render)
  126. if exc_type is not None:
  127. return
  128. self.test()
  129. class _AssertTemplateNotUsedContext(_AssertTemplateUsedContext):
  130. def test(self):
  131. self.test_case.assertFalse(
  132. self.template_name in self.rendered_template_names,
  133. f"{self.msg_prefix}Template '{self.template_name}' was used "
  134. f"unexpectedly in rendering the response",
  135. )
  136. class DatabaseOperationForbidden(AssertionError):
  137. pass
  138. class _DatabaseFailure:
  139. def __init__(self, wrapped, message):
  140. self.wrapped = wrapped
  141. self.message = message
  142. def __call__(self):
  143. raise DatabaseOperationForbidden(self.message)
  144. # RemovedInDjango50Warning
  145. class _AssertFormErrorDeprecationHelper:
  146. @staticmethod
  147. def assertFormError(self, response, form, field, errors, msg_prefix=""):
  148. """
  149. Search through all the rendered contexts of the `response` for a form named
  150. `form` then dispatch to the new assertFormError() using that instance.
  151. If multiple contexts contain the form, they're all checked in order and any
  152. failure will abort (this matches the old behavior).
  153. """
  154. warning_msg = (
  155. f"Passing response to assertFormError() is deprecated. Use the form object "
  156. f"directly: assertFormError(response.context[{form!r}], {field!r}, ...)"
  157. )
  158. warnings.warn(warning_msg, RemovedInDjango50Warning, stacklevel=2)
  159. full_msg_prefix = f"{msg_prefix}: " if msg_prefix else ""
  160. contexts = to_list(response.context) if response.context is not None else []
  161. if not contexts:
  162. self.fail(
  163. f"{full_msg_prefix}Response did not use any contexts to render the "
  164. f"response"
  165. )
  166. # Search all contexts for the error.
  167. found_form = False
  168. for i, context in enumerate(contexts):
  169. if form not in context:
  170. continue
  171. found_form = True
  172. self.assertFormError(context[form], field, errors, msg_prefix=msg_prefix)
  173. if not found_form:
  174. self.fail(
  175. f"{full_msg_prefix}The form '{form}' was not used to render the "
  176. f"response"
  177. )
  178. @staticmethod
  179. def assertFormSetError(
  180. self, response, formset, form_index, field, errors, msg_prefix=""
  181. ):
  182. """
  183. Search for a formset named "formset" in the "response" and dispatch to
  184. the new assertFormSetError() using that instance. If the name is found
  185. in multiple contexts they're all checked in order and any failure will
  186. abort the test.
  187. """
  188. warning_msg = (
  189. f"Passing response to assertFormSetError() is deprecated. Use the formset "
  190. f"object directly: assertFormSetError(response.context[{formset!r}], "
  191. f"{form_index!r}, ...)"
  192. )
  193. warnings.warn(warning_msg, RemovedInDjango50Warning, stacklevel=2)
  194. full_msg_prefix = f"{msg_prefix}: " if msg_prefix else ""
  195. contexts = to_list(response.context) if response.context is not None else []
  196. if not contexts:
  197. self.fail(
  198. f"{full_msg_prefix}Response did not use any contexts to render the "
  199. f"response"
  200. )
  201. found_formset = False
  202. for i, context in enumerate(contexts):
  203. if formset not in context or not hasattr(context[formset], "forms"):
  204. continue
  205. found_formset = True
  206. self.assertFormSetError(
  207. context[formset], form_index, field, errors, msg_prefix
  208. )
  209. if not found_formset:
  210. self.fail(
  211. f"{full_msg_prefix}The formset '{formset}' was not used to render the "
  212. f"response"
  213. )
  214. @classmethod
  215. def patch_signature(cls, new_method):
  216. """
  217. Replace the decorated method with a new one that inspects the passed
  218. args/kwargs and dispatch to the old implementation (with deprecation
  219. warning) when it detects the old signature.
  220. """
  221. @wraps(new_method)
  222. def patched_method(self, *args, **kwargs):
  223. old_method = getattr(cls, new_method.__name__)
  224. old_signature = inspect.signature(old_method)
  225. try:
  226. old_bound_args = old_signature.bind(self, *args, **kwargs)
  227. except TypeError:
  228. # If old signature doesn't match then either:
  229. # 1) new signature will match
  230. # 2) or a TypeError will be raised showing the user information
  231. # about the new signature.
  232. return new_method(self, *args, **kwargs)
  233. new_signature = inspect.signature(new_method)
  234. try:
  235. new_bound_args = new_signature.bind(self, *args, **kwargs)
  236. except TypeError:
  237. # Old signature matches but not the new one (because of
  238. # previous try/except).
  239. return old_method(self, *args, **kwargs)
  240. # If both signatures match, decide on which method to call by
  241. # inspecting the first arg (arg[0] = self).
  242. assert old_bound_args.args[1] == new_bound_args.args[1]
  243. if hasattr(
  244. old_bound_args.args[1], "context"
  245. ): # Looks like a response object => old method.
  246. return old_method(self, *args, **kwargs)
  247. elif isinstance(old_bound_args.args[1], HttpResponseBase):
  248. raise ValueError(
  249. f"{old_method.__name__}() is only usable on responses fetched "
  250. f"using the Django test Client."
  251. )
  252. else:
  253. return new_method(self, *args, **kwargs)
  254. return patched_method
  255. class SimpleTestCase(unittest.TestCase):
  256. # The class we'll use for the test client self.client.
  257. # Can be overridden in derived classes.
  258. client_class = Client
  259. async_client_class = AsyncClient
  260. _overridden_settings = None
  261. _modified_settings = None
  262. databases = set()
  263. _disallowed_database_msg = (
  264. "Database %(operation)s to %(alias)r are not allowed in SimpleTestCase "
  265. "subclasses. Either subclass TestCase or TransactionTestCase to ensure "
  266. "proper test isolation or add %(alias)r to %(test)s.databases to silence "
  267. "this failure."
  268. )
  269. _disallowed_connection_methods = [
  270. ("connect", "connections"),
  271. ("temporary_connection", "connections"),
  272. ("cursor", "queries"),
  273. ("chunked_cursor", "queries"),
  274. ]
  275. @classmethod
  276. def setUpClass(cls):
  277. super().setUpClass()
  278. if cls._overridden_settings:
  279. cls._cls_overridden_context = override_settings(**cls._overridden_settings)
  280. cls._cls_overridden_context.enable()
  281. cls.addClassCleanup(cls._cls_overridden_context.disable)
  282. if cls._modified_settings:
  283. cls._cls_modified_context = modify_settings(cls._modified_settings)
  284. cls._cls_modified_context.enable()
  285. cls.addClassCleanup(cls._cls_modified_context.disable)
  286. cls._add_databases_failures()
  287. cls.addClassCleanup(cls._remove_databases_failures)
  288. @classmethod
  289. def _validate_databases(cls):
  290. if cls.databases == "__all__":
  291. return frozenset(connections)
  292. for alias in cls.databases:
  293. if alias not in connections:
  294. message = (
  295. "%s.%s.databases refers to %r which is not defined in "
  296. "settings.DATABASES."
  297. % (
  298. cls.__module__,
  299. cls.__qualname__,
  300. alias,
  301. )
  302. )
  303. close_matches = get_close_matches(alias, list(connections))
  304. if close_matches:
  305. message += " Did you mean %r?" % close_matches[0]
  306. raise ImproperlyConfigured(message)
  307. return frozenset(cls.databases)
  308. @classmethod
  309. def _add_databases_failures(cls):
  310. cls.databases = cls._validate_databases()
  311. for alias in connections:
  312. if alias in cls.databases:
  313. continue
  314. connection = connections[alias]
  315. for name, operation in cls._disallowed_connection_methods:
  316. message = cls._disallowed_database_msg % {
  317. "test": "%s.%s" % (cls.__module__, cls.__qualname__),
  318. "alias": alias,
  319. "operation": operation,
  320. }
  321. method = getattr(connection, name)
  322. setattr(connection, name, _DatabaseFailure(method, message))
  323. @classmethod
  324. def _remove_databases_failures(cls):
  325. for alias in connections:
  326. if alias in cls.databases:
  327. continue
  328. connection = connections[alias]
  329. for name, _ in cls._disallowed_connection_methods:
  330. method = getattr(connection, name)
  331. setattr(connection, name, method.wrapped)
  332. def __call__(self, result=None):
  333. """
  334. Wrapper around default __call__ method to perform common Django test
  335. set up. This means that user-defined Test Cases aren't required to
  336. include a call to super().setUp().
  337. """
  338. self._setup_and_call(result)
  339. def debug(self):
  340. """Perform the same as __call__(), without catching the exception."""
  341. debug_result = _DebugResult()
  342. self._setup_and_call(debug_result, debug=True)
  343. def _setup_and_call(self, result, debug=False):
  344. """
  345. Perform the following in order: pre-setup, run test, post-teardown,
  346. skipping pre/post hooks if test is set to be skipped.
  347. If debug=True, reraise any errors in setup and use super().debug()
  348. instead of __call__() to run the test.
  349. """
  350. testMethod = getattr(self, self._testMethodName)
  351. skipped = getattr(self.__class__, "__unittest_skip__", False) or getattr(
  352. testMethod, "__unittest_skip__", False
  353. )
  354. # Convert async test methods.
  355. if iscoroutinefunction(testMethod):
  356. setattr(self, self._testMethodName, async_to_sync(testMethod))
  357. if not skipped:
  358. try:
  359. self._pre_setup()
  360. except Exception:
  361. if debug:
  362. raise
  363. result.addError(self, sys.exc_info())
  364. return
  365. if debug:
  366. super().debug()
  367. else:
  368. super().__call__(result)
  369. if not skipped:
  370. try:
  371. self._post_teardown()
  372. except Exception:
  373. if debug:
  374. raise
  375. result.addError(self, sys.exc_info())
  376. return
  377. def _pre_setup(self):
  378. """
  379. Perform pre-test setup:
  380. * Create a test client.
  381. * Clear the mail test outbox.
  382. """
  383. self.client = self.client_class()
  384. self.async_client = self.async_client_class()
  385. mail.outbox = []
  386. def _post_teardown(self):
  387. """Perform post-test things."""
  388. pass
  389. def settings(self, **kwargs):
  390. """
  391. A context manager that temporarily sets a setting and reverts to the
  392. original value when exiting the context.
  393. """
  394. return override_settings(**kwargs)
  395. def modify_settings(self, **kwargs):
  396. """
  397. A context manager that temporarily applies changes a list setting and
  398. reverts back to the original value when exiting the context.
  399. """
  400. return modify_settings(**kwargs)
  401. def assertRedirects(
  402. self,
  403. response,
  404. expected_url,
  405. status_code=302,
  406. target_status_code=200,
  407. msg_prefix="",
  408. fetch_redirect_response=True,
  409. ):
  410. """
  411. Assert that a response redirected to a specific URL and that the
  412. redirect URL can be loaded.
  413. Won't work for external links since it uses the test client to do a
  414. request (use fetch_redirect_response=False to check such links without
  415. fetching them).
  416. """
  417. if msg_prefix:
  418. msg_prefix += ": "
  419. if hasattr(response, "redirect_chain"):
  420. # The request was a followed redirect
  421. self.assertTrue(
  422. response.redirect_chain,
  423. msg_prefix
  424. + (
  425. "Response didn't redirect as expected: Response code was %d "
  426. "(expected %d)"
  427. )
  428. % (response.status_code, status_code),
  429. )
  430. self.assertEqual(
  431. response.redirect_chain[0][1],
  432. status_code,
  433. msg_prefix
  434. + (
  435. "Initial response didn't redirect as expected: Response code was "
  436. "%d (expected %d)"
  437. )
  438. % (response.redirect_chain[0][1], status_code),
  439. )
  440. url, status_code = response.redirect_chain[-1]
  441. self.assertEqual(
  442. response.status_code,
  443. target_status_code,
  444. msg_prefix
  445. + (
  446. "Response didn't redirect as expected: Final Response code was %d "
  447. "(expected %d)"
  448. )
  449. % (response.status_code, target_status_code),
  450. )
  451. else:
  452. # Not a followed redirect
  453. self.assertEqual(
  454. response.status_code,
  455. status_code,
  456. msg_prefix
  457. + (
  458. "Response didn't redirect as expected: Response code was %d "
  459. "(expected %d)"
  460. )
  461. % (response.status_code, status_code),
  462. )
  463. url = response.url
  464. scheme, netloc, path, query, fragment = urlsplit(url)
  465. # Prepend the request path to handle relative path redirects.
  466. if not path.startswith("/"):
  467. url = urljoin(response.request["PATH_INFO"], url)
  468. path = urljoin(response.request["PATH_INFO"], path)
  469. if fetch_redirect_response:
  470. # netloc might be empty, or in cases where Django tests the
  471. # HTTP scheme, the convention is for netloc to be 'testserver'.
  472. # Trust both as "internal" URLs here.
  473. domain, port = split_domain_port(netloc)
  474. if domain and not validate_host(domain, settings.ALLOWED_HOSTS):
  475. raise ValueError(
  476. "The test client is unable to fetch remote URLs (got %s). "
  477. "If the host is served by Django, add '%s' to ALLOWED_HOSTS. "
  478. "Otherwise, use "
  479. "assertRedirects(..., fetch_redirect_response=False)."
  480. % (url, domain)
  481. )
  482. # Get the redirection page, using the same client that was used
  483. # to obtain the original response.
  484. extra = response.client.extra or {}
  485. headers = response.client.headers or {}
  486. redirect_response = response.client.get(
  487. path,
  488. QueryDict(query),
  489. secure=(scheme == "https"),
  490. headers=headers,
  491. **extra,
  492. )
  493. self.assertEqual(
  494. redirect_response.status_code,
  495. target_status_code,
  496. msg_prefix
  497. + (
  498. "Couldn't retrieve redirection page '%s': response code was %d "
  499. "(expected %d)"
  500. )
  501. % (path, redirect_response.status_code, target_status_code),
  502. )
  503. self.assertURLEqual(
  504. url,
  505. expected_url,
  506. msg_prefix
  507. + "Response redirected to '%s', expected '%s'" % (url, expected_url),
  508. )
  509. def assertURLEqual(self, url1, url2, msg_prefix=""):
  510. """
  511. Assert that two URLs are the same, ignoring the order of query string
  512. parameters except for parameters with the same name.
  513. For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but
  514. /path/?a=1&a=2 isn't equal to /path/?a=2&a=1.
  515. """
  516. def normalize(url):
  517. """Sort the URL's query string parameters."""
  518. url = str(url) # Coerce reverse_lazy() URLs.
  519. scheme, netloc, path, params, query, fragment = urlparse(url)
  520. query_parts = sorted(parse_qsl(query))
  521. return urlunparse(
  522. (scheme, netloc, path, params, urlencode(query_parts), fragment)
  523. )
  524. self.assertEqual(
  525. normalize(url1),
  526. normalize(url2),
  527. msg_prefix + "Expected '%s' to equal '%s'." % (url1, url2),
  528. )
  529. def _assert_contains(self, response, text, status_code, msg_prefix, html):
  530. # If the response supports deferred rendering and hasn't been rendered
  531. # yet, then ensure that it does get rendered before proceeding further.
  532. if (
  533. hasattr(response, "render")
  534. and callable(response.render)
  535. and not response.is_rendered
  536. ):
  537. response.render()
  538. if msg_prefix:
  539. msg_prefix += ": "
  540. self.assertEqual(
  541. response.status_code,
  542. status_code,
  543. msg_prefix + "Couldn't retrieve content: Response code was %d"
  544. " (expected %d)" % (response.status_code, status_code),
  545. )
  546. if response.streaming:
  547. content = b"".join(response.streaming_content)
  548. else:
  549. content = response.content
  550. if not isinstance(text, bytes) or html:
  551. text = str(text)
  552. content = content.decode(response.charset)
  553. text_repr = "'%s'" % text
  554. else:
  555. text_repr = repr(text)
  556. if html:
  557. content = assert_and_parse_html(
  558. self, content, None, "Response's content is not valid HTML:"
  559. )
  560. text = assert_and_parse_html(
  561. self, text, None, "Second argument is not valid HTML:"
  562. )
  563. real_count = content.count(text)
  564. return (text_repr, real_count, msg_prefix)
  565. def assertContains(
  566. self, response, text, count=None, status_code=200, msg_prefix="", html=False
  567. ):
  568. """
  569. Assert that a response indicates that some content was retrieved
  570. successfully, (i.e., the HTTP status code was as expected) and that
  571. ``text`` occurs ``count`` times in the content of the response.
  572. If ``count`` is None, the count doesn't matter - the assertion is true
  573. if the text occurs at least once in the response.
  574. """
  575. text_repr, real_count, msg_prefix = self._assert_contains(
  576. response, text, status_code, msg_prefix, html
  577. )
  578. if count is not None:
  579. self.assertEqual(
  580. real_count,
  581. count,
  582. msg_prefix
  583. + "Found %d instances of %s in response (expected %d)"
  584. % (real_count, text_repr, count),
  585. )
  586. else:
  587. self.assertTrue(
  588. real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr
  589. )
  590. def assertNotContains(
  591. self, response, text, status_code=200, msg_prefix="", html=False
  592. ):
  593. """
  594. Assert that a response indicates that some content was retrieved
  595. successfully, (i.e., the HTTP status code was as expected) and that
  596. ``text`` doesn't occur in the content of the response.
  597. """
  598. text_repr, real_count, msg_prefix = self._assert_contains(
  599. response, text, status_code, msg_prefix, html
  600. )
  601. self.assertEqual(
  602. real_count, 0, msg_prefix + "Response should not contain %s" % text_repr
  603. )
  604. def _check_test_client_response(self, response, attribute, method_name):
  605. """
  606. Raise a ValueError if the given response doesn't have the required
  607. attribute.
  608. """
  609. if not hasattr(response, attribute):
  610. raise ValueError(
  611. f"{method_name}() is only usable on responses fetched using "
  612. "the Django test Client."
  613. )
  614. def _assert_form_error(self, form, field, errors, msg_prefix, form_repr):
  615. if not form.is_bound:
  616. self.fail(
  617. f"{msg_prefix}The {form_repr} is not bound, it will never have any "
  618. f"errors."
  619. )
  620. if field is not None and field not in form.fields:
  621. self.fail(
  622. f"{msg_prefix}The {form_repr} does not contain the field {field!r}."
  623. )
  624. if field is None:
  625. field_errors = form.non_field_errors()
  626. failure_message = f"The non-field errors of {form_repr} don't match."
  627. else:
  628. field_errors = form.errors.get(field, [])
  629. failure_message = (
  630. f"The errors of field {field!r} on {form_repr} don't match."
  631. )
  632. self.assertEqual(field_errors, errors, msg_prefix + failure_message)
  633. # RemovedInDjango50Warning: When the deprecation ends, remove the
  634. # decorator.
  635. @_AssertFormErrorDeprecationHelper.patch_signature
  636. def assertFormError(self, form, field, errors, msg_prefix=""):
  637. """
  638. Assert that a field named "field" on the given form object has specific
  639. errors.
  640. errors can be either a single error message or a list of errors
  641. messages. Using errors=[] test that the field has no errors.
  642. You can pass field=None to check the form's non-field errors.
  643. """
  644. if errors is None:
  645. warnings.warn(
  646. "Passing errors=None to assertFormError() is deprecated, use "
  647. "errors=[] instead.",
  648. RemovedInDjango50Warning,
  649. stacklevel=2,
  650. )
  651. errors = []
  652. if msg_prefix:
  653. msg_prefix += ": "
  654. errors = to_list(errors)
  655. self._assert_form_error(form, field, errors, msg_prefix, f"form {form!r}")
  656. # RemovedInDjango51Warning.
  657. def assertFormsetError(self, *args, **kw):
  658. warnings.warn(
  659. "assertFormsetError() is deprecated in favor of assertFormSetError().",
  660. category=RemovedInDjango51Warning,
  661. stacklevel=2,
  662. )
  663. return self.assertFormSetError(*args, **kw)
  664. # RemovedInDjango50Warning: When the deprecation ends, remove the
  665. # decorator.
  666. @_AssertFormErrorDeprecationHelper.patch_signature
  667. def assertFormSetError(self, formset, form_index, field, errors, msg_prefix=""):
  668. """
  669. Similar to assertFormError() but for formsets.
  670. Use form_index=None to check the formset's non-form errors (in that
  671. case, you must also use field=None).
  672. Otherwise use an integer to check the formset's n-th form for errors.
  673. Other parameters are the same as assertFormError().
  674. """
  675. if errors is None:
  676. warnings.warn(
  677. "Passing errors=None to assertFormSetError() is deprecated, "
  678. "use errors=[] instead.",
  679. RemovedInDjango50Warning,
  680. stacklevel=2,
  681. )
  682. errors = []
  683. if form_index is None and field is not None:
  684. raise ValueError("You must use field=None with form_index=None.")
  685. if msg_prefix:
  686. msg_prefix += ": "
  687. errors = to_list(errors)
  688. if not formset.is_bound:
  689. self.fail(
  690. f"{msg_prefix}The formset {formset!r} is not bound, it will never have "
  691. f"any errors."
  692. )
  693. if form_index is not None and form_index >= formset.total_form_count():
  694. form_count = formset.total_form_count()
  695. form_or_forms = "forms" if form_count > 1 else "form"
  696. self.fail(
  697. f"{msg_prefix}The formset {formset!r} only has {form_count} "
  698. f"{form_or_forms}."
  699. )
  700. if form_index is not None:
  701. form_repr = f"form {form_index} of formset {formset!r}"
  702. self._assert_form_error(
  703. formset.forms[form_index], field, errors, msg_prefix, form_repr
  704. )
  705. else:
  706. failure_message = f"The non-form errors of formset {formset!r} don't match."
  707. self.assertEqual(
  708. formset.non_form_errors(), errors, msg_prefix + failure_message
  709. )
  710. def _get_template_used(self, response, template_name, msg_prefix, method_name):
  711. if response is None and template_name is None:
  712. raise TypeError("response and/or template_name argument must be provided")
  713. if msg_prefix:
  714. msg_prefix += ": "
  715. if template_name is not None and response is not None:
  716. self._check_test_client_response(response, "templates", method_name)
  717. if not hasattr(response, "templates") or (response is None and template_name):
  718. if response:
  719. template_name = response
  720. response = None
  721. # use this template with context manager
  722. return template_name, None, msg_prefix
  723. template_names = [t.name for t in response.templates if t.name is not None]
  724. return None, template_names, msg_prefix
  725. def _assert_template_used(self, template_name, template_names, msg_prefix, count):
  726. if not template_names:
  727. self.fail(msg_prefix + "No templates used to render the response")
  728. self.assertTrue(
  729. template_name in template_names,
  730. msg_prefix + "Template '%s' was not a template used to render"
  731. " the response. Actual template(s) used: %s"
  732. % (template_name, ", ".join(template_names)),
  733. )
  734. if count is not None:
  735. self.assertEqual(
  736. template_names.count(template_name),
  737. count,
  738. msg_prefix + "Template '%s' was expected to be rendered %d "
  739. "time(s) but was actually rendered %d time(s)."
  740. % (template_name, count, template_names.count(template_name)),
  741. )
  742. def assertTemplateUsed(
  743. self, response=None, template_name=None, msg_prefix="", count=None
  744. ):
  745. """
  746. Assert that the template with the provided name was used in rendering
  747. the response. Also usable as context manager.
  748. """
  749. context_mgr_template, template_names, msg_prefix = self._get_template_used(
  750. response,
  751. template_name,
  752. msg_prefix,
  753. "assertTemplateUsed",
  754. )
  755. if context_mgr_template:
  756. # Use assertTemplateUsed as context manager.
  757. return _AssertTemplateUsedContext(
  758. self, context_mgr_template, msg_prefix, count
  759. )
  760. self._assert_template_used(template_name, template_names, msg_prefix, count)
  761. def assertTemplateNotUsed(self, response=None, template_name=None, msg_prefix=""):
  762. """
  763. Assert that the template with the provided name was NOT used in
  764. rendering the response. Also usable as context manager.
  765. """
  766. context_mgr_template, template_names, msg_prefix = self._get_template_used(
  767. response,
  768. template_name,
  769. msg_prefix,
  770. "assertTemplateNotUsed",
  771. )
  772. if context_mgr_template:
  773. # Use assertTemplateNotUsed as context manager.
  774. return _AssertTemplateNotUsedContext(self, context_mgr_template, msg_prefix)
  775. self.assertFalse(
  776. template_name in template_names,
  777. msg_prefix
  778. + "Template '%s' was used unexpectedly in rendering the response"
  779. % template_name,
  780. )
  781. @contextmanager
  782. def _assert_raises_or_warns_cm(
  783. self, func, cm_attr, expected_exception, expected_message
  784. ):
  785. with func(expected_exception) as cm:
  786. yield cm
  787. self.assertIn(expected_message, str(getattr(cm, cm_attr)))
  788. def _assertFooMessage(
  789. self, func, cm_attr, expected_exception, expected_message, *args, **kwargs
  790. ):
  791. callable_obj = None
  792. if args:
  793. callable_obj, *args = args
  794. cm = self._assert_raises_or_warns_cm(
  795. func, cm_attr, expected_exception, expected_message
  796. )
  797. # Assertion used in context manager fashion.
  798. if callable_obj is None:
  799. return cm
  800. # Assertion was passed a callable.
  801. with cm:
  802. callable_obj(*args, **kwargs)
  803. def assertRaisesMessage(
  804. self, expected_exception, expected_message, *args, **kwargs
  805. ):
  806. """
  807. Assert that expected_message is found in the message of a raised
  808. exception.
  809. Args:
  810. expected_exception: Exception class expected to be raised.
  811. expected_message: expected error message string value.
  812. args: Function to be called and extra positional args.
  813. kwargs: Extra kwargs.
  814. """
  815. return self._assertFooMessage(
  816. self.assertRaises,
  817. "exception",
  818. expected_exception,
  819. expected_message,
  820. *args,
  821. **kwargs,
  822. )
  823. def assertWarnsMessage(self, expected_warning, expected_message, *args, **kwargs):
  824. """
  825. Same as assertRaisesMessage but for assertWarns() instead of
  826. assertRaises().
  827. """
  828. return self._assertFooMessage(
  829. self.assertWarns,
  830. "warning",
  831. expected_warning,
  832. expected_message,
  833. *args,
  834. **kwargs,
  835. )
  836. # A similar method is available in Python 3.10+.
  837. if not PY310:
  838. @contextmanager
  839. def assertNoLogs(self, logger, level=None):
  840. """
  841. Assert no messages are logged on the logger, with at least the
  842. given level.
  843. """
  844. if isinstance(level, int):
  845. level = logging.getLevelName(level)
  846. elif level is None:
  847. level = "INFO"
  848. try:
  849. with self.assertLogs(logger, level) as cm:
  850. yield
  851. except AssertionError as e:
  852. msg = e.args[0]
  853. expected_msg = (
  854. f"no logs of level {level} or higher triggered on {logger}"
  855. )
  856. if msg != expected_msg:
  857. raise e
  858. else:
  859. self.fail(f"Unexpected logs found: {cm.output!r}")
  860. def assertFieldOutput(
  861. self,
  862. fieldclass,
  863. valid,
  864. invalid,
  865. field_args=None,
  866. field_kwargs=None,
  867. empty_value="",
  868. ):
  869. """
  870. Assert that a form field behaves correctly with various inputs.
  871. Args:
  872. fieldclass: the class of the field to be tested.
  873. valid: a dictionary mapping valid inputs to their expected
  874. cleaned values.
  875. invalid: a dictionary mapping invalid inputs to one or more
  876. raised error messages.
  877. field_args: the args passed to instantiate the field
  878. field_kwargs: the kwargs passed to instantiate the field
  879. empty_value: the expected clean output for inputs in empty_values
  880. """
  881. if field_args is None:
  882. field_args = []
  883. if field_kwargs is None:
  884. field_kwargs = {}
  885. required = fieldclass(*field_args, **field_kwargs)
  886. optional = fieldclass(*field_args, **{**field_kwargs, "required": False})
  887. # test valid inputs
  888. for input, output in valid.items():
  889. self.assertEqual(required.clean(input), output)
  890. self.assertEqual(optional.clean(input), output)
  891. # test invalid inputs
  892. for input, errors in invalid.items():
  893. with self.assertRaises(ValidationError) as context_manager:
  894. required.clean(input)
  895. self.assertEqual(context_manager.exception.messages, errors)
  896. with self.assertRaises(ValidationError) as context_manager:
  897. optional.clean(input)
  898. self.assertEqual(context_manager.exception.messages, errors)
  899. # test required inputs
  900. error_required = [required.error_messages["required"]]
  901. for e in required.empty_values:
  902. with self.assertRaises(ValidationError) as context_manager:
  903. required.clean(e)
  904. self.assertEqual(context_manager.exception.messages, error_required)
  905. self.assertEqual(optional.clean(e), empty_value)
  906. # test that max_length and min_length are always accepted
  907. if issubclass(fieldclass, CharField):
  908. field_kwargs.update({"min_length": 2, "max_length": 20})
  909. self.assertIsInstance(fieldclass(*field_args, **field_kwargs), fieldclass)
  910. def assertHTMLEqual(self, html1, html2, msg=None):
  911. """
  912. Assert that two HTML snippets are semantically the same.
  913. Whitespace in most cases is ignored, and attribute ordering is not
  914. significant. The arguments must be valid HTML.
  915. """
  916. dom1 = assert_and_parse_html(
  917. self, html1, msg, "First argument is not valid HTML:"
  918. )
  919. dom2 = assert_and_parse_html(
  920. self, html2, msg, "Second argument is not valid HTML:"
  921. )
  922. if dom1 != dom2:
  923. standardMsg = "%s != %s" % (safe_repr(dom1, True), safe_repr(dom2, True))
  924. diff = "\n" + "\n".join(
  925. difflib.ndiff(
  926. str(dom1).splitlines(),
  927. str(dom2).splitlines(),
  928. )
  929. )
  930. standardMsg = self._truncateMessage(standardMsg, diff)
  931. self.fail(self._formatMessage(msg, standardMsg))
  932. def assertHTMLNotEqual(self, html1, html2, msg=None):
  933. """Assert that two HTML snippets are not semantically equivalent."""
  934. dom1 = assert_and_parse_html(
  935. self, html1, msg, "First argument is not valid HTML:"
  936. )
  937. dom2 = assert_and_parse_html(
  938. self, html2, msg, "Second argument is not valid HTML:"
  939. )
  940. if dom1 == dom2:
  941. standardMsg = "%s == %s" % (safe_repr(dom1, True), safe_repr(dom2, True))
  942. self.fail(self._formatMessage(msg, standardMsg))
  943. def assertInHTML(self, needle, haystack, count=None, msg_prefix=""):
  944. needle = assert_and_parse_html(
  945. self, needle, None, "First argument is not valid HTML:"
  946. )
  947. haystack = assert_and_parse_html(
  948. self, haystack, None, "Second argument is not valid HTML:"
  949. )
  950. real_count = haystack.count(needle)
  951. if count is not None:
  952. self.assertEqual(
  953. real_count,
  954. count,
  955. msg_prefix
  956. + "Found %d instances of '%s' in response (expected %d)"
  957. % (real_count, needle, count),
  958. )
  959. else:
  960. self.assertTrue(
  961. real_count != 0, msg_prefix + "Couldn't find '%s' in response" % needle
  962. )
  963. def assertJSONEqual(self, raw, expected_data, msg=None):
  964. """
  965. Assert that the JSON fragments raw and expected_data are equal.
  966. Usual JSON non-significant whitespace rules apply as the heavyweight
  967. is delegated to the json library.
  968. """
  969. try:
  970. data = json.loads(raw)
  971. except json.JSONDecodeError:
  972. self.fail("First argument is not valid JSON: %r" % raw)
  973. if isinstance(expected_data, str):
  974. try:
  975. expected_data = json.loads(expected_data)
  976. except ValueError:
  977. self.fail("Second argument is not valid JSON: %r" % expected_data)
  978. self.assertEqual(data, expected_data, msg=msg)
  979. def assertJSONNotEqual(self, raw, expected_data, msg=None):
  980. """
  981. Assert that the JSON fragments raw and expected_data are not equal.
  982. Usual JSON non-significant whitespace rules apply as the heavyweight
  983. is delegated to the json library.
  984. """
  985. try:
  986. data = json.loads(raw)
  987. except json.JSONDecodeError:
  988. self.fail("First argument is not valid JSON: %r" % raw)
  989. if isinstance(expected_data, str):
  990. try:
  991. expected_data = json.loads(expected_data)
  992. except json.JSONDecodeError:
  993. self.fail("Second argument is not valid JSON: %r" % expected_data)
  994. self.assertNotEqual(data, expected_data, msg=msg)
  995. def assertXMLEqual(self, xml1, xml2, msg=None):
  996. """
  997. Assert that two XML snippets are semantically the same.
  998. Whitespace in most cases is ignored and attribute ordering is not
  999. significant. The arguments must be valid XML.
  1000. """
  1001. try:
  1002. result = compare_xml(xml1, xml2)
  1003. except Exception as e:
  1004. standardMsg = "First or second argument is not valid XML\n%s" % e
  1005. self.fail(self._formatMessage(msg, standardMsg))
  1006. else:
  1007. if not result:
  1008. standardMsg = "%s != %s" % (
  1009. safe_repr(xml1, True),
  1010. safe_repr(xml2, True),
  1011. )
  1012. diff = "\n" + "\n".join(
  1013. difflib.ndiff(xml1.splitlines(), xml2.splitlines())
  1014. )
  1015. standardMsg = self._truncateMessage(standardMsg, diff)
  1016. self.fail(self._formatMessage(msg, standardMsg))
  1017. def assertXMLNotEqual(self, xml1, xml2, msg=None):
  1018. """
  1019. Assert that two XML snippets are not semantically equivalent.
  1020. Whitespace in most cases is ignored and attribute ordering is not
  1021. significant. The arguments must be valid XML.
  1022. """
  1023. try:
  1024. result = compare_xml(xml1, xml2)
  1025. except Exception as e:
  1026. standardMsg = "First or second argument is not valid XML\n%s" % e
  1027. self.fail(self._formatMessage(msg, standardMsg))
  1028. else:
  1029. if result:
  1030. standardMsg = "%s == %s" % (
  1031. safe_repr(xml1, True),
  1032. safe_repr(xml2, True),
  1033. )
  1034. self.fail(self._formatMessage(msg, standardMsg))
  1035. class TransactionTestCase(SimpleTestCase):
  1036. # Subclasses can ask for resetting of auto increment sequence before each
  1037. # test case
  1038. reset_sequences = False
  1039. # Subclasses can enable only a subset of apps for faster tests
  1040. available_apps = None
  1041. # Subclasses can define fixtures which will be automatically installed.
  1042. fixtures = None
  1043. databases = {DEFAULT_DB_ALIAS}
  1044. _disallowed_database_msg = (
  1045. "Database %(operation)s to %(alias)r are not allowed in this test. "
  1046. "Add %(alias)r to %(test)s.databases to ensure proper test isolation "
  1047. "and silence this failure."
  1048. )
  1049. # If transactions aren't available, Django will serialize the database
  1050. # contents into a fixture during setup and flush and reload them
  1051. # during teardown (as flush does not restore data from migrations).
  1052. # This can be slow; this flag allows enabling on a per-case basis.
  1053. serialized_rollback = False
  1054. def _pre_setup(self):
  1055. """
  1056. Perform pre-test setup:
  1057. * If the class has an 'available_apps' attribute, restrict the app
  1058. registry to these applications, then fire the post_migrate signal --
  1059. it must run with the correct set of applications for the test case.
  1060. * If the class has a 'fixtures' attribute, install those fixtures.
  1061. """
  1062. super()._pre_setup()
  1063. if self.available_apps is not None:
  1064. apps.set_available_apps(self.available_apps)
  1065. setting_changed.send(
  1066. sender=settings._wrapped.__class__,
  1067. setting="INSTALLED_APPS",
  1068. value=self.available_apps,
  1069. enter=True,
  1070. )
  1071. for db_name in self._databases_names(include_mirrors=False):
  1072. emit_post_migrate_signal(verbosity=0, interactive=False, db=db_name)
  1073. try:
  1074. self._fixture_setup()
  1075. except Exception:
  1076. if self.available_apps is not None:
  1077. apps.unset_available_apps()
  1078. setting_changed.send(
  1079. sender=settings._wrapped.__class__,
  1080. setting="INSTALLED_APPS",
  1081. value=settings.INSTALLED_APPS,
  1082. enter=False,
  1083. )
  1084. raise
  1085. # Clear the queries_log so that it's less likely to overflow (a single
  1086. # test probably won't execute 9K queries). If queries_log overflows,
  1087. # then assertNumQueries() doesn't work.
  1088. for db_name in self._databases_names(include_mirrors=False):
  1089. connections[db_name].queries_log.clear()
  1090. @classmethod
  1091. def _databases_names(cls, include_mirrors=True):
  1092. # Only consider allowed database aliases, including mirrors or not.
  1093. return [
  1094. alias
  1095. for alias in connections
  1096. if alias in cls.databases
  1097. and (
  1098. include_mirrors
  1099. or not connections[alias].settings_dict["TEST"]["MIRROR"]
  1100. )
  1101. ]
  1102. def _reset_sequences(self, db_name):
  1103. conn = connections[db_name]
  1104. if conn.features.supports_sequence_reset:
  1105. sql_list = conn.ops.sequence_reset_by_name_sql(
  1106. no_style(), conn.introspection.sequence_list()
  1107. )
  1108. if sql_list:
  1109. with transaction.atomic(using=db_name):
  1110. with conn.cursor() as cursor:
  1111. for sql in sql_list:
  1112. cursor.execute(sql)
  1113. def _fixture_setup(self):
  1114. for db_name in self._databases_names(include_mirrors=False):
  1115. # Reset sequences
  1116. if self.reset_sequences:
  1117. self._reset_sequences(db_name)
  1118. # Provide replica initial data from migrated apps, if needed.
  1119. if self.serialized_rollback and hasattr(
  1120. connections[db_name], "_test_serialized_contents"
  1121. ):
  1122. if self.available_apps is not None:
  1123. apps.unset_available_apps()
  1124. connections[db_name].creation.deserialize_db_from_string(
  1125. connections[db_name]._test_serialized_contents
  1126. )
  1127. if self.available_apps is not None:
  1128. apps.set_available_apps(self.available_apps)
  1129. if self.fixtures:
  1130. # We have to use this slightly awkward syntax due to the fact
  1131. # that we're using *args and **kwargs together.
  1132. call_command(
  1133. "loaddata", *self.fixtures, **{"verbosity": 0, "database": db_name}
  1134. )
  1135. def _should_reload_connections(self):
  1136. return True
  1137. def _post_teardown(self):
  1138. """
  1139. Perform post-test things:
  1140. * Flush the contents of the database to leave a clean slate. If the
  1141. class has an 'available_apps' attribute, don't fire post_migrate.
  1142. * Force-close the connection so the next test gets a clean cursor.
  1143. """
  1144. try:
  1145. self._fixture_teardown()
  1146. super()._post_teardown()
  1147. if self._should_reload_connections():
  1148. # Some DB cursors include SQL statements as part of cursor
  1149. # creation. If you have a test that does a rollback, the effect
  1150. # of these statements is lost, which can affect the operation of
  1151. # tests (e.g., losing a timezone setting causing objects to be
  1152. # created with the wrong time). To make sure this doesn't
  1153. # happen, get a clean connection at the start of every test.
  1154. for conn in connections.all(initialized_only=True):
  1155. conn.close()
  1156. finally:
  1157. if self.available_apps is not None:
  1158. apps.unset_available_apps()
  1159. setting_changed.send(
  1160. sender=settings._wrapped.__class__,
  1161. setting="INSTALLED_APPS",
  1162. value=settings.INSTALLED_APPS,
  1163. enter=False,
  1164. )
  1165. def _fixture_teardown(self):
  1166. # Allow TRUNCATE ... CASCADE and don't emit the post_migrate signal
  1167. # when flushing only a subset of the apps
  1168. for db_name in self._databases_names(include_mirrors=False):
  1169. # Flush the database
  1170. inhibit_post_migrate = (
  1171. self.available_apps is not None
  1172. or ( # Inhibit the post_migrate signal when using serialized
  1173. # rollback to avoid trying to recreate the serialized data.
  1174. self.serialized_rollback
  1175. and hasattr(connections[db_name], "_test_serialized_contents")
  1176. )
  1177. )
  1178. call_command(
  1179. "flush",
  1180. verbosity=0,
  1181. interactive=False,
  1182. database=db_name,
  1183. reset_sequences=False,
  1184. allow_cascade=self.available_apps is not None,
  1185. inhibit_post_migrate=inhibit_post_migrate,
  1186. )
  1187. # RemovedInDjango51Warning.
  1188. def assertQuerysetEqual(self, *args, **kw):
  1189. warnings.warn(
  1190. "assertQuerysetEqual() is deprecated in favor of assertQuerySetEqual().",
  1191. category=RemovedInDjango51Warning,
  1192. stacklevel=2,
  1193. )
  1194. return self.assertQuerySetEqual(*args, **kw)
  1195. def assertQuerySetEqual(self, qs, values, transform=None, ordered=True, msg=None):
  1196. values = list(values)
  1197. items = qs
  1198. if transform is not None:
  1199. items = map(transform, items)
  1200. if not ordered:
  1201. return self.assertDictEqual(Counter(items), Counter(values), msg=msg)
  1202. # For example qs.iterator() could be passed as qs, but it does not
  1203. # have 'ordered' attribute.
  1204. if len(values) > 1 and hasattr(qs, "ordered") and not qs.ordered:
  1205. raise ValueError(
  1206. "Trying to compare non-ordered queryset against more than one "
  1207. "ordered value."
  1208. )
  1209. return self.assertEqual(list(items), values, msg=msg)
  1210. def assertNumQueries(self, num, func=None, *args, using=DEFAULT_DB_ALIAS, **kwargs):
  1211. conn = connections[using]
  1212. context = _AssertNumQueriesContext(self, num, conn)
  1213. if func is None:
  1214. return context
  1215. with context:
  1216. func(*args, **kwargs)
  1217. def connections_support_transactions(aliases=None):
  1218. """
  1219. Return whether or not all (or specified) connections support
  1220. transactions.
  1221. """
  1222. conns = (
  1223. connections.all()
  1224. if aliases is None
  1225. else (connections[alias] for alias in aliases)
  1226. )
  1227. return all(conn.features.supports_transactions for conn in conns)
  1228. class TestData:
  1229. """
  1230. Descriptor to provide TestCase instance isolation for attributes assigned
  1231. during the setUpTestData() phase.
  1232. Allow safe alteration of objects assigned in setUpTestData() by test
  1233. methods by exposing deep copies instead of the original objects.
  1234. Objects are deep copied using a memo kept on the test case instance in
  1235. order to maintain their original relationships.
  1236. """
  1237. memo_attr = "_testdata_memo"
  1238. def __init__(self, name, data):
  1239. self.name = name
  1240. self.data = data
  1241. def get_memo(self, testcase):
  1242. try:
  1243. memo = getattr(testcase, self.memo_attr)
  1244. except AttributeError:
  1245. memo = {}
  1246. setattr(testcase, self.memo_attr, memo)
  1247. return memo
  1248. def __get__(self, instance, owner):
  1249. if instance is None:
  1250. return self.data
  1251. memo = self.get_memo(instance)
  1252. data = deepcopy(self.data, memo)
  1253. setattr(instance, self.name, data)
  1254. return data
  1255. def __repr__(self):
  1256. return "<TestData: name=%r, data=%r>" % (self.name, self.data)
  1257. class TestCase(TransactionTestCase):
  1258. """
  1259. Similar to TransactionTestCase, but use `transaction.atomic()` to achieve
  1260. test isolation.
  1261. In most situations, TestCase should be preferred to TransactionTestCase as
  1262. it allows faster execution. However, there are some situations where using
  1263. TransactionTestCase might be necessary (e.g. testing some transactional
  1264. behavior).
  1265. On database backends with no transaction support, TestCase behaves as
  1266. TransactionTestCase.
  1267. """
  1268. @classmethod
  1269. def _enter_atomics(cls):
  1270. """Open atomic blocks for multiple databases."""
  1271. atomics = {}
  1272. for db_name in cls._databases_names():
  1273. atomic = transaction.atomic(using=db_name)
  1274. atomic._from_testcase = True
  1275. atomic.__enter__()
  1276. atomics[db_name] = atomic
  1277. return atomics
  1278. @classmethod
  1279. def _rollback_atomics(cls, atomics):
  1280. """Rollback atomic blocks opened by the previous method."""
  1281. for db_name in reversed(cls._databases_names()):
  1282. transaction.set_rollback(True, using=db_name)
  1283. atomics[db_name].__exit__(None, None, None)
  1284. @classmethod
  1285. def _databases_support_transactions(cls):
  1286. return connections_support_transactions(cls.databases)
  1287. @classmethod
  1288. def setUpClass(cls):
  1289. super().setUpClass()
  1290. if not cls._databases_support_transactions():
  1291. return
  1292. cls.cls_atomics = cls._enter_atomics()
  1293. if cls.fixtures:
  1294. for db_name in cls._databases_names(include_mirrors=False):
  1295. try:
  1296. call_command(
  1297. "loaddata",
  1298. *cls.fixtures,
  1299. **{"verbosity": 0, "database": db_name},
  1300. )
  1301. except Exception:
  1302. cls._rollback_atomics(cls.cls_atomics)
  1303. raise
  1304. pre_attrs = cls.__dict__.copy()
  1305. try:
  1306. cls.setUpTestData()
  1307. except Exception:
  1308. cls._rollback_atomics(cls.cls_atomics)
  1309. raise
  1310. for name, value in cls.__dict__.items():
  1311. if value is not pre_attrs.get(name):
  1312. setattr(cls, name, TestData(name, value))
  1313. @classmethod
  1314. def tearDownClass(cls):
  1315. if cls._databases_support_transactions():
  1316. cls._rollback_atomics(cls.cls_atomics)
  1317. for conn in connections.all(initialized_only=True):
  1318. conn.close()
  1319. super().tearDownClass()
  1320. @classmethod
  1321. def setUpTestData(cls):
  1322. """Load initial data for the TestCase."""
  1323. pass
  1324. def _should_reload_connections(self):
  1325. if self._databases_support_transactions():
  1326. return False
  1327. return super()._should_reload_connections()
  1328. def _fixture_setup(self):
  1329. if not self._databases_support_transactions():
  1330. # If the backend does not support transactions, we should reload
  1331. # class data before each test
  1332. self.setUpTestData()
  1333. return super()._fixture_setup()
  1334. if self.reset_sequences:
  1335. raise TypeError("reset_sequences cannot be used on TestCase instances")
  1336. self.atomics = self._enter_atomics()
  1337. def _fixture_teardown(self):
  1338. if not self._databases_support_transactions():
  1339. return super()._fixture_teardown()
  1340. try:
  1341. for db_name in reversed(self._databases_names()):
  1342. if self._should_check_constraints(connections[db_name]):
  1343. connections[db_name].check_constraints()
  1344. finally:
  1345. self._rollback_atomics(self.atomics)
  1346. def _should_check_constraints(self, connection):
  1347. return (
  1348. connection.features.can_defer_constraint_checks
  1349. and not connection.needs_rollback
  1350. and connection.is_usable()
  1351. )
  1352. @classmethod
  1353. @contextmanager
  1354. def captureOnCommitCallbacks(cls, *, using=DEFAULT_DB_ALIAS, execute=False):
  1355. """Context manager to capture transaction.on_commit() callbacks."""
  1356. callbacks = []
  1357. start_count = len(connections[using].run_on_commit)
  1358. try:
  1359. yield callbacks
  1360. finally:
  1361. while True:
  1362. callback_count = len(connections[using].run_on_commit)
  1363. for _, callback, robust in connections[using].run_on_commit[
  1364. start_count:
  1365. ]:
  1366. callbacks.append(callback)
  1367. if execute:
  1368. if robust:
  1369. try:
  1370. callback()
  1371. except Exception as e:
  1372. logger.error(
  1373. f"Error calling {callback.__qualname__} in "
  1374. f"on_commit() (%s).",
  1375. e,
  1376. exc_info=True,
  1377. )
  1378. else:
  1379. callback()
  1380. if callback_count == len(connections[using].run_on_commit):
  1381. break
  1382. start_count = callback_count
  1383. class CheckCondition:
  1384. """Descriptor class for deferred condition checking."""
  1385. def __init__(self, *conditions):
  1386. self.conditions = conditions
  1387. def add_condition(self, condition, reason):
  1388. return self.__class__(*self.conditions, (condition, reason))
  1389. def __get__(self, instance, cls=None):
  1390. # Trigger access for all bases.
  1391. if any(getattr(base, "__unittest_skip__", False) for base in cls.__bases__):
  1392. return True
  1393. for condition, reason in self.conditions:
  1394. if condition():
  1395. # Override this descriptor's value and set the skip reason.
  1396. cls.__unittest_skip__ = True
  1397. cls.__unittest_skip_why__ = reason
  1398. return True
  1399. return False
  1400. def _deferredSkip(condition, reason, name):
  1401. def decorator(test_func):
  1402. nonlocal condition
  1403. if not (
  1404. isinstance(test_func, type) and issubclass(test_func, unittest.TestCase)
  1405. ):
  1406. @wraps(test_func)
  1407. def skip_wrapper(*args, **kwargs):
  1408. if (
  1409. args
  1410. and isinstance(args[0], unittest.TestCase)
  1411. and connection.alias not in getattr(args[0], "databases", {})
  1412. ):
  1413. raise ValueError(
  1414. "%s cannot be used on %s as %s doesn't allow queries "
  1415. "against the %r database."
  1416. % (
  1417. name,
  1418. args[0],
  1419. args[0].__class__.__qualname__,
  1420. connection.alias,
  1421. )
  1422. )
  1423. if condition():
  1424. raise unittest.SkipTest(reason)
  1425. return test_func(*args, **kwargs)
  1426. test_item = skip_wrapper
  1427. else:
  1428. # Assume a class is decorated
  1429. test_item = test_func
  1430. databases = getattr(test_item, "databases", None)
  1431. if not databases or connection.alias not in databases:
  1432. # Defer raising to allow importing test class's module.
  1433. def condition():
  1434. raise ValueError(
  1435. "%s cannot be used on %s as it doesn't allow queries "
  1436. "against the '%s' database."
  1437. % (
  1438. name,
  1439. test_item,
  1440. connection.alias,
  1441. )
  1442. )
  1443. # Retrieve the possibly existing value from the class's dict to
  1444. # avoid triggering the descriptor.
  1445. skip = test_func.__dict__.get("__unittest_skip__")
  1446. if isinstance(skip, CheckCondition):
  1447. test_item.__unittest_skip__ = skip.add_condition(condition, reason)
  1448. elif skip is not True:
  1449. test_item.__unittest_skip__ = CheckCondition((condition, reason))
  1450. return test_item
  1451. return decorator
  1452. def skipIfDBFeature(*features):
  1453. """Skip a test if a database has at least one of the named features."""
  1454. return _deferredSkip(
  1455. lambda: any(
  1456. getattr(connection.features, feature, False) for feature in features
  1457. ),
  1458. "Database has feature(s) %s" % ", ".join(features),
  1459. "skipIfDBFeature",
  1460. )
  1461. def skipUnlessDBFeature(*features):
  1462. """Skip a test unless a database has all the named features."""
  1463. return _deferredSkip(
  1464. lambda: not all(
  1465. getattr(connection.features, feature, False) for feature in features
  1466. ),
  1467. "Database doesn't support feature(s): %s" % ", ".join(features),
  1468. "skipUnlessDBFeature",
  1469. )
  1470. def skipUnlessAnyDBFeature(*features):
  1471. """Skip a test unless a database has any of the named features."""
  1472. return _deferredSkip(
  1473. lambda: not any(
  1474. getattr(connection.features, feature, False) for feature in features
  1475. ),
  1476. "Database doesn't support any of the feature(s): %s" % ", ".join(features),
  1477. "skipUnlessAnyDBFeature",
  1478. )
  1479. class QuietWSGIRequestHandler(WSGIRequestHandler):
  1480. """
  1481. A WSGIRequestHandler that doesn't log to standard output any of the
  1482. requests received, so as to not clutter the test result output.
  1483. """
  1484. def log_message(*args):
  1485. pass
  1486. class FSFilesHandler(WSGIHandler):
  1487. """
  1488. WSGI middleware that intercepts calls to a directory, as defined by one of
  1489. the *_ROOT settings, and serves those files, publishing them under *_URL.
  1490. """
  1491. def __init__(self, application):
  1492. self.application = application
  1493. self.base_url = urlparse(self.get_base_url())
  1494. super().__init__()
  1495. def _should_handle(self, path):
  1496. """
  1497. Check if the path should be handled. Ignore the path if:
  1498. * the host is provided as part of the base_url
  1499. * the request's path isn't under the media path (or equal)
  1500. """
  1501. return path.startswith(self.base_url[2]) and not self.base_url[1]
  1502. def file_path(self, url):
  1503. """Return the relative path to the file on disk for the given URL."""
  1504. relative_url = url[len(self.base_url[2]) :]
  1505. return url2pathname(relative_url)
  1506. def get_response(self, request):
  1507. from django.http import Http404
  1508. if self._should_handle(request.path):
  1509. try:
  1510. return self.serve(request)
  1511. except Http404:
  1512. pass
  1513. return super().get_response(request)
  1514. def serve(self, request):
  1515. os_rel_path = self.file_path(request.path)
  1516. os_rel_path = posixpath.normpath(unquote(os_rel_path))
  1517. # Emulate behavior of django.contrib.staticfiles.views.serve() when it
  1518. # invokes staticfiles' finders functionality.
  1519. # TODO: Modify if/when that internal API is refactored
  1520. final_rel_path = os_rel_path.replace("\\", "/").lstrip("/")
  1521. return serve(request, final_rel_path, document_root=self.get_base_dir())
  1522. def __call__(self, environ, start_response):
  1523. if not self._should_handle(get_path_info(environ)):
  1524. return self.application(environ, start_response)
  1525. return super().__call__(environ, start_response)
  1526. class _StaticFilesHandler(FSFilesHandler):
  1527. """
  1528. Handler for serving static files. A private class that is meant to be used
  1529. solely as a convenience by LiveServerThread.
  1530. """
  1531. def get_base_dir(self):
  1532. return settings.STATIC_ROOT
  1533. def get_base_url(self):
  1534. return settings.STATIC_URL
  1535. class _MediaFilesHandler(FSFilesHandler):
  1536. """
  1537. Handler for serving the media files. A private class that is meant to be
  1538. used solely as a convenience by LiveServerThread.
  1539. """
  1540. def get_base_dir(self):
  1541. return settings.MEDIA_ROOT
  1542. def get_base_url(self):
  1543. return settings.MEDIA_URL
  1544. class LiveServerThread(threading.Thread):
  1545. """Thread for running a live HTTP server while the tests are running."""
  1546. server_class = ThreadedWSGIServer
  1547. def __init__(self, host, static_handler, connections_override=None, port=0):
  1548. self.host = host
  1549. self.port = port
  1550. self.is_ready = threading.Event()
  1551. self.error = None
  1552. self.static_handler = static_handler
  1553. self.connections_override = connections_override
  1554. super().__init__()
  1555. def run(self):
  1556. """
  1557. Set up the live server and databases, and then loop over handling
  1558. HTTP requests.
  1559. """
  1560. if self.connections_override:
  1561. # Override this thread's database connections with the ones
  1562. # provided by the main thread.
  1563. for alias, conn in self.connections_override.items():
  1564. connections[alias] = conn
  1565. try:
  1566. # Create the handler for serving static and media files
  1567. handler = self.static_handler(_MediaFilesHandler(WSGIHandler()))
  1568. self.httpd = self._create_server(
  1569. connections_override=self.connections_override,
  1570. )
  1571. # If binding to port zero, assign the port allocated by the OS.
  1572. if self.port == 0:
  1573. self.port = self.httpd.server_address[1]
  1574. self.httpd.set_app(handler)
  1575. self.is_ready.set()
  1576. self.httpd.serve_forever()
  1577. except Exception as e:
  1578. self.error = e
  1579. self.is_ready.set()
  1580. finally:
  1581. connections.close_all()
  1582. def _create_server(self, connections_override=None):
  1583. return self.server_class(
  1584. (self.host, self.port),
  1585. QuietWSGIRequestHandler,
  1586. allow_reuse_address=False,
  1587. connections_override=connections_override,
  1588. )
  1589. def terminate(self):
  1590. if hasattr(self, "httpd"):
  1591. # Stop the WSGI server
  1592. self.httpd.shutdown()
  1593. self.httpd.server_close()
  1594. self.join()
  1595. class LiveServerTestCase(TransactionTestCase):
  1596. """
  1597. Do basically the same as TransactionTestCase but also launch a live HTTP
  1598. server in a separate thread so that the tests may use another testing
  1599. framework, such as Selenium for example, instead of the built-in dummy
  1600. client.
  1601. It inherits from TransactionTestCase instead of TestCase because the
  1602. threads don't share the same transactions (unless if using in-memory sqlite)
  1603. and each thread needs to commit all their transactions so that the other
  1604. thread can see the changes.
  1605. """
  1606. host = "localhost"
  1607. port = 0
  1608. server_thread_class = LiveServerThread
  1609. static_handler = _StaticFilesHandler
  1610. @classproperty
  1611. def live_server_url(cls):
  1612. return "http://%s:%s" % (cls.host, cls.server_thread.port)
  1613. @classproperty
  1614. def allowed_host(cls):
  1615. return cls.host
  1616. @classmethod
  1617. def _make_connections_override(cls):
  1618. connections_override = {}
  1619. for conn in connections.all():
  1620. # If using in-memory sqlite databases, pass the connections to
  1621. # the server thread.
  1622. if conn.vendor == "sqlite" and conn.is_in_memory_db():
  1623. connections_override[conn.alias] = conn
  1624. return connections_override
  1625. @classmethod
  1626. def setUpClass(cls):
  1627. super().setUpClass()
  1628. cls._live_server_modified_settings = modify_settings(
  1629. ALLOWED_HOSTS={"append": cls.allowed_host},
  1630. )
  1631. cls._live_server_modified_settings.enable()
  1632. cls.addClassCleanup(cls._live_server_modified_settings.disable)
  1633. cls._start_server_thread()
  1634. @classmethod
  1635. def _start_server_thread(cls):
  1636. connections_override = cls._make_connections_override()
  1637. for conn in connections_override.values():
  1638. # Explicitly enable thread-shareability for this connection.
  1639. conn.inc_thread_sharing()
  1640. cls.server_thread = cls._create_server_thread(connections_override)
  1641. cls.server_thread.daemon = True
  1642. cls.server_thread.start()
  1643. cls.addClassCleanup(cls._terminate_thread)
  1644. # Wait for the live server to be ready
  1645. cls.server_thread.is_ready.wait()
  1646. if cls.server_thread.error:
  1647. raise cls.server_thread.error
  1648. @classmethod
  1649. def _create_server_thread(cls, connections_override):
  1650. return cls.server_thread_class(
  1651. cls.host,
  1652. cls.static_handler,
  1653. connections_override=connections_override,
  1654. port=cls.port,
  1655. )
  1656. @classmethod
  1657. def _terminate_thread(cls):
  1658. # Terminate the live server's thread.
  1659. cls.server_thread.terminate()
  1660. # Restore shared connections' non-shareability.
  1661. for conn in cls.server_thread.connections_override.values():
  1662. conn.dec_thread_sharing()
  1663. class SerializeMixin:
  1664. """
  1665. Enforce serialization of TestCases that share a common resource.
  1666. Define a common 'lockfile' for each set of TestCases to serialize. This
  1667. file must exist on the filesystem.
  1668. Place it early in the MRO in order to isolate setUpClass()/tearDownClass().
  1669. """
  1670. lockfile = None
  1671. def __init_subclass__(cls, /, **kwargs):
  1672. super().__init_subclass__(**kwargs)
  1673. if cls.lockfile is None:
  1674. raise ValueError(
  1675. "{}.lockfile isn't set. Set it to a unique value "
  1676. "in the base class.".format(cls.__name__)
  1677. )
  1678. @classmethod
  1679. def setUpClass(cls):
  1680. cls._lockfile = open(cls.lockfile)
  1681. cls.addClassCleanup(cls._lockfile.close)
  1682. locks.lock(cls._lockfile, locks.LOCK_EX)
  1683. super().setUpClass()