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 57 KiB

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