PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/Lib/site-packages/django/test/testcases.py

http://github.com/JetBrains/intellij-community
Python | 629 lines | 573 code | 7 blank | 49 comment | 12 complexity | ec68817c87f70bbb8b02565907ac5603 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, MPL-2.0-no-copyleft-exception, MIT, EPL-1.0, AGPL-1.0
  1. import re
  2. import sys
  3. from urlparse import urlsplit, urlunsplit
  4. from xml.dom.minidom import parseString, Node
  5. from django.conf import settings
  6. from django.core import mail
  7. from django.core.management import call_command
  8. from django.core.urlresolvers import clear_url_caches
  9. from django.db import transaction, connection, connections, DEFAULT_DB_ALIAS
  10. from django.http import QueryDict
  11. from django.test import _doctest as doctest
  12. from django.test.client import Client
  13. from django.test.utils import get_warnings_state, restore_warnings_state
  14. from django.utils import simplejson, unittest as ut2
  15. from django.utils.encoding import smart_str
  16. from django.utils.functional import wraps
  17. __all__ = ('DocTestRunner', 'OutputChecker', 'TestCase', 'TransactionTestCase',
  18. 'skipIfDBFeature', 'skipUnlessDBFeature')
  19. try:
  20. all
  21. except NameError:
  22. from django.utils.itercompat import all
  23. normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s)
  24. normalize_decimals = lambda s: re.sub(r"Decimal\('(\d+(\.\d*)?)'\)", lambda m: "Decimal(\"%s\")" % m.groups()[0], s)
  25. def to_list(value):
  26. """
  27. Puts value into a list if it's not already one.
  28. Returns an empty list if value is None.
  29. """
  30. if value is None:
  31. value = []
  32. elif not isinstance(value, list):
  33. value = [value]
  34. return value
  35. real_commit = transaction.commit
  36. real_rollback = transaction.rollback
  37. real_enter_transaction_management = transaction.enter_transaction_management
  38. real_leave_transaction_management = transaction.leave_transaction_management
  39. real_managed = transaction.managed
  40. def nop(*args, **kwargs):
  41. return
  42. def disable_transaction_methods():
  43. transaction.commit = nop
  44. transaction.rollback = nop
  45. transaction.enter_transaction_management = nop
  46. transaction.leave_transaction_management = nop
  47. transaction.managed = nop
  48. def restore_transaction_methods():
  49. transaction.commit = real_commit
  50. transaction.rollback = real_rollback
  51. transaction.enter_transaction_management = real_enter_transaction_management
  52. transaction.leave_transaction_management = real_leave_transaction_management
  53. transaction.managed = real_managed
  54. class OutputChecker(doctest.OutputChecker):
  55. def check_output(self, want, got, optionflags):
  56. "The entry method for doctest output checking. Defers to a sequence of child checkers"
  57. checks = (self.check_output_default,
  58. self.check_output_numeric,
  59. self.check_output_xml,
  60. self.check_output_json)
  61. for check in checks:
  62. if check(want, got, optionflags):
  63. return True
  64. return False
  65. def check_output_default(self, want, got, optionflags):
  66. "The default comparator provided by doctest - not perfect, but good for most purposes"
  67. return doctest.OutputChecker.check_output(self, want, got, optionflags)
  68. def check_output_numeric(self, want, got, optionflags):
  69. """Doctest does an exact string comparison of output, which means that
  70. some numerically equivalent values aren't equal. This check normalizes
  71. * long integers (22L) so that they equal normal integers. (22)
  72. * Decimals so that they are comparable, regardless of the change
  73. made to __repr__ in Python 2.6.
  74. """
  75. return doctest.OutputChecker.check_output(self,
  76. normalize_decimals(normalize_long_ints(want)),
  77. normalize_decimals(normalize_long_ints(got)),
  78. optionflags)
  79. def check_output_xml(self, want, got, optionsflags):
  80. """Tries to do a 'xml-comparision' of want and got. Plain string
  81. comparision doesn't always work because, for example, attribute
  82. ordering should not be important.
  83. Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py
  84. """
  85. _norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
  86. def norm_whitespace(v):
  87. return _norm_whitespace_re.sub(' ', v)
  88. def child_text(element):
  89. return ''.join([c.data for c in element.childNodes
  90. if c.nodeType == Node.TEXT_NODE])
  91. def children(element):
  92. return [c for c in element.childNodes
  93. if c.nodeType == Node.ELEMENT_NODE]
  94. def norm_child_text(element):
  95. return norm_whitespace(child_text(element))
  96. def attrs_dict(element):
  97. return dict(element.attributes.items())
  98. def check_element(want_element, got_element):
  99. if want_element.tagName != got_element.tagName:
  100. return False
  101. if norm_child_text(want_element) != norm_child_text(got_element):
  102. return False
  103. if attrs_dict(want_element) != attrs_dict(got_element):
  104. return False
  105. want_children = children(want_element)
  106. got_children = children(got_element)
  107. if len(want_children) != len(got_children):
  108. return False
  109. for want, got in zip(want_children, got_children):
  110. if not check_element(want, got):
  111. return False
  112. return True
  113. want, got = self._strip_quotes(want, got)
  114. want = want.replace('\\n','\n')
  115. got = got.replace('\\n','\n')
  116. # If the string is not a complete xml document, we may need to add a
  117. # root element. This allow us to compare fragments, like "<foo/><bar/>"
  118. if not want.startswith('<?xml'):
  119. wrapper = '<root>%s</root>'
  120. want = wrapper % want
  121. got = wrapper % got
  122. # Parse the want and got strings, and compare the parsings.
  123. try:
  124. want_root = parseString(want).firstChild
  125. got_root = parseString(got).firstChild
  126. except:
  127. return False
  128. return check_element(want_root, got_root)
  129. def check_output_json(self, want, got, optionsflags):
  130. "Tries to compare want and got as if they were JSON-encoded data"
  131. want, got = self._strip_quotes(want, got)
  132. try:
  133. want_json = simplejson.loads(want)
  134. got_json = simplejson.loads(got)
  135. except:
  136. return False
  137. return want_json == got_json
  138. def _strip_quotes(self, want, got):
  139. """
  140. Strip quotes of doctests output values:
  141. >>> o = OutputChecker()
  142. >>> o._strip_quotes("'foo'")
  143. "foo"
  144. >>> o._strip_quotes('"foo"')
  145. "foo"
  146. >>> o._strip_quotes("u'foo'")
  147. "foo"
  148. >>> o._strip_quotes('u"foo"')
  149. "foo"
  150. """
  151. def is_quoted_string(s):
  152. s = s.strip()
  153. return (len(s) >= 2
  154. and s[0] == s[-1]
  155. and s[0] in ('"', "'"))
  156. def is_quoted_unicode(s):
  157. s = s.strip()
  158. return (len(s) >= 3
  159. and s[0] == 'u'
  160. and s[1] == s[-1]
  161. and s[1] in ('"', "'"))
  162. if is_quoted_string(want) and is_quoted_string(got):
  163. want = want.strip()[1:-1]
  164. got = got.strip()[1:-1]
  165. elif is_quoted_unicode(want) and is_quoted_unicode(got):
  166. want = want.strip()[2:-1]
  167. got = got.strip()[2:-1]
  168. return want, got
  169. class DocTestRunner(doctest.DocTestRunner):
  170. def __init__(self, *args, **kwargs):
  171. doctest.DocTestRunner.__init__(self, *args, **kwargs)
  172. self.optionflags = doctest.ELLIPSIS
  173. def report_unexpected_exception(self, out, test, example, exc_info):
  174. doctest.DocTestRunner.report_unexpected_exception(self, out, test,
  175. example, exc_info)
  176. # Rollback, in case of database errors. Otherwise they'd have
  177. # side effects on other tests.
  178. for conn in connections:
  179. transaction.rollback_unless_managed(using=conn)
  180. class _AssertNumQueriesContext(object):
  181. def __init__(self, test_case, num, connection):
  182. self.test_case = test_case
  183. self.num = num
  184. self.connection = connection
  185. def __enter__(self):
  186. self.old_debug_cursor = self.connection.use_debug_cursor
  187. self.connection.use_debug_cursor = True
  188. self.starting_queries = len(self.connection.queries)
  189. return self
  190. def __exit__(self, exc_type, exc_value, traceback):
  191. self.connection.use_debug_cursor = self.old_debug_cursor
  192. if exc_type is not None:
  193. return
  194. final_queries = len(self.connection.queries)
  195. executed = final_queries - self.starting_queries
  196. self.test_case.assertEqual(
  197. executed, self.num, "%d queries executed, %d expected" % (
  198. executed, self.num
  199. )
  200. )
  201. class TransactionTestCase(ut2.TestCase):
  202. # The class we'll use for the test client self.client.
  203. # Can be overridden in derived classes.
  204. client_class = Client
  205. def _pre_setup(self):
  206. """Performs any pre-test setup. This includes:
  207. * Flushing the database.
  208. * If the Test Case class has a 'fixtures' member, installing the
  209. named fixtures.
  210. * If the Test Case class has a 'urls' member, replace the
  211. ROOT_URLCONF with it.
  212. * Clearing the mail test outbox.
  213. """
  214. self._fixture_setup()
  215. self._urlconf_setup()
  216. mail.outbox = []
  217. def _fixture_setup(self):
  218. # If the test case has a multi_db=True flag, flush all databases.
  219. # Otherwise, just flush default.
  220. if getattr(self, 'multi_db', False):
  221. databases = connections
  222. else:
  223. databases = [DEFAULT_DB_ALIAS]
  224. for db in databases:
  225. call_command('flush', verbosity=0, interactive=False, database=db)
  226. if hasattr(self, 'fixtures'):
  227. # We have to use this slightly awkward syntax due to the fact
  228. # that we're using *args and **kwargs together.
  229. call_command('loaddata', *self.fixtures, **{'verbosity': 0, 'database': db})
  230. def _urlconf_setup(self):
  231. if hasattr(self, 'urls'):
  232. self._old_root_urlconf = settings.ROOT_URLCONF
  233. settings.ROOT_URLCONF = self.urls
  234. clear_url_caches()
  235. def __call__(self, result=None):
  236. """
  237. Wrapper around default __call__ method to perform common Django test
  238. set up. This means that user-defined Test Cases aren't required to
  239. include a call to super().setUp().
  240. """
  241. self.client = self.client_class()
  242. try:
  243. self._pre_setup()
  244. except (KeyboardInterrupt, SystemExit):
  245. raise
  246. except Exception:
  247. import sys
  248. result.addError(self, sys.exc_info())
  249. return
  250. super(TransactionTestCase, self).__call__(result)
  251. try:
  252. self._post_teardown()
  253. except (KeyboardInterrupt, SystemExit):
  254. raise
  255. except Exception:
  256. import sys
  257. result.addError(self, sys.exc_info())
  258. return
  259. def _post_teardown(self):
  260. """ Performs any post-test things. This includes:
  261. * Putting back the original ROOT_URLCONF if it was changed.
  262. * Force closing the connection, so that the next test gets
  263. a clean cursor.
  264. """
  265. self._fixture_teardown()
  266. self._urlconf_teardown()
  267. # Some DB cursors include SQL statements as part of cursor
  268. # creation. If you have a test that does rollback, the effect
  269. # of these statements is lost, which can effect the operation
  270. # of tests (e.g., losing a timezone setting causing objects to
  271. # be created with the wrong time).
  272. # To make sure this doesn't happen, get a clean connection at the
  273. # start of every test.
  274. for connection in connections.all():
  275. connection.close()
  276. def _fixture_teardown(self):
  277. pass
  278. def _urlconf_teardown(self):
  279. if hasattr(self, '_old_root_urlconf'):
  280. settings.ROOT_URLCONF = self._old_root_urlconf
  281. clear_url_caches()
  282. def save_warnings_state(self):
  283. """
  284. Saves the state of the warnings module
  285. """
  286. self._warnings_state = get_warnings_state()
  287. def restore_warnings_state(self):
  288. """
  289. Restores the sate of the warnings module to the state
  290. saved by save_warnings_state()
  291. """
  292. restore_warnings_state(self._warnings_state)
  293. def assertRedirects(self, response, expected_url, status_code=302,
  294. target_status_code=200, host=None, msg_prefix=''):
  295. """Asserts that a response redirected to a specific URL, and that the
  296. redirect URL can be loaded.
  297. Note that assertRedirects won't work for external links since it uses
  298. TestClient to do a request.
  299. """
  300. if msg_prefix:
  301. msg_prefix += ": "
  302. if hasattr(response, 'redirect_chain'):
  303. # The request was a followed redirect
  304. self.assertTrue(len(response.redirect_chain) > 0,
  305. msg_prefix + "Response didn't redirect as expected: Response"
  306. " code was %d (expected %d)" %
  307. (response.status_code, status_code))
  308. self.assertEqual(response.redirect_chain[0][1], status_code,
  309. msg_prefix + "Initial response didn't redirect as expected:"
  310. " Response code was %d (expected %d)" %
  311. (response.redirect_chain[0][1], status_code))
  312. url, status_code = response.redirect_chain[-1]
  313. self.assertEqual(response.status_code, target_status_code,
  314. msg_prefix + "Response didn't redirect as expected: Final"
  315. " Response code was %d (expected %d)" %
  316. (response.status_code, target_status_code))
  317. else:
  318. # Not a followed redirect
  319. self.assertEqual(response.status_code, status_code,
  320. msg_prefix + "Response didn't redirect as expected: Response"
  321. " code was %d (expected %d)" %
  322. (response.status_code, status_code))
  323. url = response['Location']
  324. scheme, netloc, path, query, fragment = urlsplit(url)
  325. redirect_response = response.client.get(path, QueryDict(query))
  326. # Get the redirection page, using the same client that was used
  327. # to obtain the original response.
  328. self.assertEqual(redirect_response.status_code, target_status_code,
  329. msg_prefix + "Couldn't retrieve redirection page '%s':"
  330. " response code was %d (expected %d)" %
  331. (path, redirect_response.status_code, target_status_code))
  332. e_scheme, e_netloc, e_path, e_query, e_fragment = urlsplit(expected_url)
  333. if not (e_scheme or e_netloc):
  334. expected_url = urlunsplit(('http', host or 'testserver', e_path,
  335. e_query, e_fragment))
  336. self.assertEqual(url, expected_url,
  337. msg_prefix + "Response redirected to '%s', expected '%s'" %
  338. (url, expected_url))
  339. def assertContains(self, response, text, count=None, status_code=200,
  340. msg_prefix=''):
  341. """
  342. Asserts that a response indicates that some content was retrieved
  343. successfully, (i.e., the HTTP status code was as expected), and that
  344. ``text`` occurs ``count`` times in the content of the response.
  345. If ``count`` is None, the count doesn't matter - the assertion is true
  346. if the text occurs at least once in the response.
  347. """
  348. if msg_prefix:
  349. msg_prefix += ": "
  350. self.assertEqual(response.status_code, status_code,
  351. msg_prefix + "Couldn't retrieve content: Response code was %d"
  352. " (expected %d)" % (response.status_code, status_code))
  353. text = smart_str(text, response._charset)
  354. real_count = response.content.count(text)
  355. if count is not None:
  356. self.assertEqual(real_count, count,
  357. msg_prefix + "Found %d instances of '%s' in response"
  358. " (expected %d)" % (real_count, text, count))
  359. else:
  360. self.assertTrue(real_count != 0,
  361. msg_prefix + "Couldn't find '%s' in response" % text)
  362. def assertNotContains(self, response, text, status_code=200,
  363. msg_prefix=''):
  364. """
  365. Asserts that a response indicates that some content was retrieved
  366. successfully, (i.e., the HTTP status code was as expected), and that
  367. ``text`` doesn't occurs in the content of the response.
  368. """
  369. if msg_prefix:
  370. msg_prefix += ": "
  371. self.assertEqual(response.status_code, status_code,
  372. msg_prefix + "Couldn't retrieve content: Response code was %d"
  373. " (expected %d)" % (response.status_code, status_code))
  374. text = smart_str(text, response._charset)
  375. self.assertEqual(response.content.count(text), 0,
  376. msg_prefix + "Response should not contain '%s'" % text)
  377. def assertFormError(self, response, form, field, errors, msg_prefix=''):
  378. """
  379. Asserts that a form used to render the response has a specific field
  380. error.
  381. """
  382. if msg_prefix:
  383. msg_prefix += ": "
  384. # Put context(s) into a list to simplify processing.
  385. contexts = to_list(response.context)
  386. if not contexts:
  387. self.fail(msg_prefix + "Response did not use any contexts to "
  388. "render the response")
  389. # Put error(s) into a list to simplify processing.
  390. errors = to_list(errors)
  391. # Search all contexts for the error.
  392. found_form = False
  393. for i,context in enumerate(contexts):
  394. if form not in context:
  395. continue
  396. found_form = True
  397. for err in errors:
  398. if field:
  399. if field in context[form].errors:
  400. field_errors = context[form].errors[field]
  401. self.assertTrue(err in field_errors,
  402. msg_prefix + "The field '%s' on form '%s' in"
  403. " context %d does not contain the error '%s'"
  404. " (actual errors: %s)" %
  405. (field, form, i, err, repr(field_errors)))
  406. elif field in context[form].fields:
  407. self.fail(msg_prefix + "The field '%s' on form '%s'"
  408. " in context %d contains no errors" %
  409. (field, form, i))
  410. else:
  411. self.fail(msg_prefix + "The form '%s' in context %d"
  412. " does not contain the field '%s'" %
  413. (form, i, field))
  414. else:
  415. non_field_errors = context[form].non_field_errors()
  416. self.assertTrue(err in non_field_errors,
  417. msg_prefix + "The form '%s' in context %d does not"
  418. " contain the non-field error '%s'"
  419. " (actual errors: %s)" %
  420. (form, i, err, non_field_errors))
  421. if not found_form:
  422. self.fail(msg_prefix + "The form '%s' was not used to render the"
  423. " response" % form)
  424. def assertTemplateUsed(self, response, template_name, msg_prefix=''):
  425. """
  426. Asserts that the template with the provided name was used in rendering
  427. the response.
  428. """
  429. if msg_prefix:
  430. msg_prefix += ": "
  431. template_names = [t.name for t in response.templates]
  432. if not template_names:
  433. self.fail(msg_prefix + "No templates used to render the response")
  434. self.assertTrue(template_name in template_names,
  435. msg_prefix + "Template '%s' was not a template used to render"
  436. " the response. Actual template(s) used: %s" %
  437. (template_name, u', '.join(template_names)))
  438. def assertTemplateNotUsed(self, response, template_name, msg_prefix=''):
  439. """
  440. Asserts that the template with the provided name was NOT used in
  441. rendering the response.
  442. """
  443. if msg_prefix:
  444. msg_prefix += ": "
  445. template_names = [t.name for t in response.templates]
  446. self.assertFalse(template_name in template_names,
  447. msg_prefix + "Template '%s' was used unexpectedly in rendering"
  448. " the response" % template_name)
  449. def assertQuerysetEqual(self, qs, values, transform=repr):
  450. return self.assertEqual(map(transform, qs), values)
  451. def assertNumQueries(self, num, func=None, *args, **kwargs):
  452. using = kwargs.pop("using", DEFAULT_DB_ALIAS)
  453. connection = connections[using]
  454. context = _AssertNumQueriesContext(self, num, connection)
  455. if func is None:
  456. return context
  457. # Basically emulate the `with` statement here.
  458. context.__enter__()
  459. try:
  460. func(*args, **kwargs)
  461. except:
  462. context.__exit__(*sys.exc_info())
  463. raise
  464. else:
  465. context.__exit__(*sys.exc_info())
  466. def connections_support_transactions():
  467. """
  468. Returns True if all connections support transactions. This is messy
  469. because 2.4 doesn't support any or all.
  470. """
  471. return all(conn.features.supports_transactions
  472. for conn in connections.all())
  473. class TestCase(TransactionTestCase):
  474. """
  475. Does basically the same as TransactionTestCase, but surrounds every test
  476. with a transaction, monkey-patches the real transaction management routines to
  477. do nothing, and rollsback the test transaction at the end of the test. You have
  478. to use TransactionTestCase, if you need transaction management inside a test.
  479. """
  480. def _fixture_setup(self):
  481. if not connections_support_transactions():
  482. return super(TestCase, self)._fixture_setup()
  483. # If the test case has a multi_db=True flag, setup all databases.
  484. # Otherwise, just use default.
  485. if getattr(self, 'multi_db', False):
  486. databases = connections
  487. else:
  488. databases = [DEFAULT_DB_ALIAS]
  489. for db in databases:
  490. transaction.enter_transaction_management(using=db)
  491. transaction.managed(True, using=db)
  492. disable_transaction_methods()
  493. from django.contrib.sites.models import Site
  494. Site.objects.clear_cache()
  495. for db in databases:
  496. if hasattr(self, 'fixtures'):
  497. call_command('loaddata', *self.fixtures, **{
  498. 'verbosity': 0,
  499. 'commit': False,
  500. 'database': db
  501. })
  502. def _fixture_teardown(self):
  503. if not connections_support_transactions():
  504. return super(TestCase, self)._fixture_teardown()
  505. # If the test case has a multi_db=True flag, teardown all databases.
  506. # Otherwise, just teardown default.
  507. if getattr(self, 'multi_db', False):
  508. databases = connections
  509. else:
  510. databases = [DEFAULT_DB_ALIAS]
  511. restore_transaction_methods()
  512. for db in databases:
  513. transaction.rollback(using=db)
  514. transaction.leave_transaction_management(using=db)
  515. def _deferredSkip(condition, reason):
  516. def decorator(test_func):
  517. if not (isinstance(test_func, type) and issubclass(test_func, TestCase)):
  518. @wraps(test_func)
  519. def skip_wrapper(*args, **kwargs):
  520. if condition():
  521. raise ut2.SkipTest(reason)
  522. return test_func(*args, **kwargs)
  523. test_item = skip_wrapper
  524. else:
  525. test_item = test_func
  526. test_item.__unittest_skip_why__ = reason
  527. return test_item
  528. return decorator
  529. def skipIfDBFeature(feature):
  530. "Skip a test if a database has the named feature"
  531. return _deferredSkip(lambda: getattr(connection.features, feature),
  532. "Database has feature %s" % feature)
  533. def skipUnlessDBFeature(feature):
  534. "Skip a test unless a database has the named feature"
  535. return _deferredSkip(lambda: not getattr(connection.features, feature),
  536. "Database doesn't support feature %s" % feature)