testcases.py 67 KB

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