2
0

testcases.py 48 KB

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