Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

testcases.py 68KB

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