testcases.py 66 KB

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