testcases.py 52 KB

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