testcases.py 62 KB

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