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 60KB

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