Development of an internal social media platform with personalised dashboards for students
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 54KB

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