testcases.py 49 KB

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