You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

643 lines
20 KiB

  1. import logging
  2. import re
  3. import sys
  4. import time
  5. import warnings
  6. from contextlib import contextmanager
  7. from functools import wraps
  8. from unittest import skipIf, skipUnless
  9. from xml.dom.minidom import Node, parseString
  10. from django.apps import apps
  11. from django.conf import UserSettingsHolder, settings
  12. from django.core import mail
  13. from django.core.signals import request_started
  14. from django.core.urlresolvers import get_script_prefix, set_script_prefix
  15. from django.db import reset_queries
  16. from django.http import request
  17. from django.template import Template
  18. from django.test.signals import setting_changed, template_rendered
  19. from django.utils import six
  20. from django.utils.decorators import ContextDecorator
  21. from django.utils.encoding import force_str
  22. from django.utils.translation import deactivate
  23. try:
  24. import jinja2
  25. except ImportError:
  26. jinja2 = None
  27. __all__ = (
  28. 'Approximate', 'ContextList', 'isolate_lru_cache', 'get_runner',
  29. 'modify_settings', 'override_settings',
  30. 'requires_tz_support',
  31. 'setup_test_environment', 'teardown_test_environment',
  32. )
  33. TZ_SUPPORT = hasattr(time, 'tzset')
  34. class Approximate(object):
  35. def __init__(self, val, places=7):
  36. self.val = val
  37. self.places = places
  38. def __repr__(self):
  39. return repr(self.val)
  40. def __eq__(self, other):
  41. if self.val == other:
  42. return True
  43. return round(abs(self.val - other), self.places) == 0
  44. class ContextList(list):
  45. """A wrapper that provides direct key access to context items contained
  46. in a list of context objects.
  47. """
  48. def __getitem__(self, key):
  49. if isinstance(key, six.string_types):
  50. for subcontext in self:
  51. if key in subcontext:
  52. return subcontext[key]
  53. raise KeyError(key)
  54. else:
  55. return super(ContextList, self).__getitem__(key)
  56. def __contains__(self, key):
  57. try:
  58. self[key]
  59. except KeyError:
  60. return False
  61. return True
  62. def keys(self):
  63. """
  64. Flattened keys of subcontexts.
  65. """
  66. keys = set()
  67. for subcontext in self:
  68. for dict in subcontext:
  69. keys |= set(dict.keys())
  70. return keys
  71. def instrumented_test_render(self, context):
  72. """
  73. An instrumented Template render method, providing a signal
  74. that can be intercepted by the test system Client
  75. """
  76. template_rendered.send(sender=self, template=self, context=context)
  77. return self.nodelist.render(context)
  78. def setup_test_environment():
  79. """Perform any global pre-test setup. This involves:
  80. - Installing the instrumented test renderer
  81. - Set the email backend to the locmem email backend.
  82. - Setting the active locale to match the LANGUAGE_CODE setting.
  83. """
  84. Template._original_render = Template._render
  85. Template._render = instrumented_test_render
  86. # Storing previous values in the settings module itself is problematic.
  87. # Store them in arbitrary (but related) modules instead. See #20636.
  88. mail._original_email_backend = settings.EMAIL_BACKEND
  89. settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
  90. request._original_allowed_hosts = settings.ALLOWED_HOSTS
  91. settings.ALLOWED_HOSTS = ['*']
  92. mail.outbox = []
  93. deactivate()
  94. def teardown_test_environment():
  95. """Perform any global post-test teardown. This involves:
  96. - Restoring the original test renderer
  97. - Restoring the email sending functions
  98. """
  99. Template._render = Template._original_render
  100. del Template._original_render
  101. settings.EMAIL_BACKEND = mail._original_email_backend
  102. del mail._original_email_backend
  103. settings.ALLOWED_HOSTS = request._original_allowed_hosts
  104. del request._original_allowed_hosts
  105. del mail.outbox
  106. def get_runner(settings, test_runner_class=None):
  107. if not test_runner_class:
  108. test_runner_class = settings.TEST_RUNNER
  109. test_path = test_runner_class.split('.')
  110. # Allow for Python 2.5 relative paths
  111. if len(test_path) > 1:
  112. test_module_name = '.'.join(test_path[:-1])
  113. else:
  114. test_module_name = '.'
  115. test_module = __import__(test_module_name, {}, {}, force_str(test_path[-1]))
  116. test_runner = getattr(test_module, test_path[-1])
  117. return test_runner
  118. class override_settings(object):
  119. """
  120. Acts as either a decorator, or a context manager. If it's a decorator it
  121. takes a function and returns a wrapped function. If it's a contextmanager
  122. it's used with the ``with`` statement. In either event entering/exiting
  123. are called before and after, respectively, the function/block is executed.
  124. """
  125. def __init__(self, **kwargs):
  126. self.options = kwargs
  127. def __enter__(self):
  128. self.enable()
  129. def __exit__(self, exc_type, exc_value, traceback):
  130. self.disable()
  131. def __call__(self, test_func):
  132. from django.test import SimpleTestCase
  133. if isinstance(test_func, type):
  134. if not issubclass(test_func, SimpleTestCase):
  135. raise Exception(
  136. "Only subclasses of Django SimpleTestCase can be decorated "
  137. "with override_settings")
  138. self.save_options(test_func)
  139. return test_func
  140. else:
  141. @wraps(test_func)
  142. def inner(*args, **kwargs):
  143. with self:
  144. return test_func(*args, **kwargs)
  145. return inner
  146. def save_options(self, test_func):
  147. if test_func._overridden_settings is None:
  148. test_func._overridden_settings = self.options
  149. else:
  150. # Duplicate dict to prevent subclasses from altering their parent.
  151. test_func._overridden_settings = dict(
  152. test_func._overridden_settings, **self.options)
  153. def enable(self):
  154. # Keep this code at the beginning to leave the settings unchanged
  155. # in case it raises an exception because INSTALLED_APPS is invalid.
  156. if 'INSTALLED_APPS' in self.options:
  157. try:
  158. apps.set_installed_apps(self.options['INSTALLED_APPS'])
  159. except Exception:
  160. apps.unset_installed_apps()
  161. raise
  162. override = UserSettingsHolder(settings._wrapped)
  163. for key, new_value in self.options.items():
  164. setattr(override, key, new_value)
  165. self.wrapped = settings._wrapped
  166. settings._wrapped = override
  167. for key, new_value in self.options.items():
  168. setting_changed.send(sender=settings._wrapped.__class__,
  169. setting=key, value=new_value, enter=True)
  170. def disable(self):
  171. if 'INSTALLED_APPS' in self.options:
  172. apps.unset_installed_apps()
  173. settings._wrapped = self.wrapped
  174. del self.wrapped
  175. for key in self.options:
  176. new_value = getattr(settings, key, None)
  177. setting_changed.send(sender=settings._wrapped.__class__,
  178. setting=key, value=new_value, enter=False)
  179. class modify_settings(override_settings):
  180. """
  181. Like override_settings, but makes it possible to append, prepend or remove
  182. items instead of redefining the entire list.
  183. """
  184. def __init__(self, *args, **kwargs):
  185. if args:
  186. # Hack used when instantiating from SimpleTestCase.setUpClass.
  187. assert not kwargs
  188. self.operations = args[0]
  189. else:
  190. assert not args
  191. self.operations = list(kwargs.items())
  192. def save_options(self, test_func):
  193. if test_func._modified_settings is None:
  194. test_func._modified_settings = self.operations
  195. else:
  196. # Duplicate list to prevent subclasses from altering their parent.
  197. test_func._modified_settings = list(
  198. test_func._modified_settings) + self.operations
  199. def enable(self):
  200. self.options = {}
  201. for name, operations in self.operations:
  202. try:
  203. # When called from SimpleTestCase.setUpClass, values may be
  204. # overridden several times; cumulate changes.
  205. value = self.options[name]
  206. except KeyError:
  207. value = list(getattr(settings, name, []))
  208. for action, items in operations.items():
  209. # items my be a single value or an iterable.
  210. if isinstance(items, six.string_types):
  211. items = [items]
  212. if action == 'append':
  213. value = value + [item for item in items if item not in value]
  214. elif action == 'prepend':
  215. value = [item for item in items if item not in value] + value
  216. elif action == 'remove':
  217. value = [item for item in value if item not in items]
  218. else:
  219. raise ValueError("Unsupported action: %s" % action)
  220. self.options[name] = value
  221. super(modify_settings, self).enable()
  222. def override_system_checks(new_checks, deployment_checks=None):
  223. """ Acts as a decorator. Overrides list of registered system checks.
  224. Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app,
  225. you also need to exclude its system checks. """
  226. from django.core.checks.registry import registry
  227. def outer(test_func):
  228. @wraps(test_func)
  229. def inner(*args, **kwargs):
  230. old_checks = registry.registered_checks
  231. registry.registered_checks = new_checks
  232. old_deployment_checks = registry.deployment_checks
  233. if deployment_checks is not None:
  234. registry.deployment_checks = deployment_checks
  235. try:
  236. return test_func(*args, **kwargs)
  237. finally:
  238. registry.registered_checks = old_checks
  239. registry.deployment_checks = old_deployment_checks
  240. return inner
  241. return outer
  242. def compare_xml(want, got):
  243. """Tries to do a 'xml-comparison' of want and got. Plain string
  244. comparison doesn't always work because, for example, attribute
  245. ordering should not be important. Comment nodes are not considered in the
  246. comparison.
  247. Based on https://github.com/lxml/lxml/blob/master/src/lxml/doctestcompare.py
  248. """
  249. _norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
  250. def norm_whitespace(v):
  251. return _norm_whitespace_re.sub(' ', v)
  252. def child_text(element):
  253. return ''.join(c.data for c in element.childNodes
  254. if c.nodeType == Node.TEXT_NODE)
  255. def children(element):
  256. return [c for c in element.childNodes
  257. if c.nodeType == Node.ELEMENT_NODE]
  258. def norm_child_text(element):
  259. return norm_whitespace(child_text(element))
  260. def attrs_dict(element):
  261. return dict(element.attributes.items())
  262. def check_element(want_element, got_element):
  263. if want_element.tagName != got_element.tagName:
  264. return False
  265. if norm_child_text(want_element) != norm_child_text(got_element):
  266. return False
  267. if attrs_dict(want_element) != attrs_dict(got_element):
  268. return False
  269. want_children = children(want_element)
  270. got_children = children(got_element)
  271. if len(want_children) != len(got_children):
  272. return False
  273. for want, got in zip(want_children, got_children):
  274. if not check_element(want, got):
  275. return False
  276. return True
  277. def first_node(document):
  278. for node in document.childNodes:
  279. if node.nodeType != Node.COMMENT_NODE:
  280. return node
  281. want, got = strip_quotes(want, got)
  282. want = want.replace('\\n', '\n')
  283. got = got.replace('\\n', '\n')
  284. # If the string is not a complete xml document, we may need to add a
  285. # root element. This allow us to compare fragments, like "<foo/><bar/>"
  286. if not want.startswith('<?xml'):
  287. wrapper = '<root>%s</root>'
  288. want = wrapper % want
  289. got = wrapper % got
  290. # Parse the want and got strings, and compare the parsings.
  291. want_root = first_node(parseString(want))
  292. got_root = first_node(parseString(got))
  293. return check_element(want_root, got_root)
  294. def strip_quotes(want, got):
  295. """
  296. Strip quotes of doctests output values:
  297. >>> strip_quotes("'foo'")
  298. "foo"
  299. >>> strip_quotes('"foo"')
  300. "foo"
  301. """
  302. def is_quoted_string(s):
  303. s = s.strip()
  304. return (len(s) >= 2
  305. and s[0] == s[-1]
  306. and s[0] in ('"', "'"))
  307. def is_quoted_unicode(s):
  308. s = s.strip()
  309. return (len(s) >= 3
  310. and s[0] == 'u'
  311. and s[1] == s[-1]
  312. and s[1] in ('"', "'"))
  313. if is_quoted_string(want) and is_quoted_string(got):
  314. want = want.strip()[1:-1]
  315. got = got.strip()[1:-1]
  316. elif is_quoted_unicode(want) and is_quoted_unicode(got):
  317. want = want.strip()[2:-1]
  318. got = got.strip()[2:-1]
  319. return want, got
  320. def str_prefix(s):
  321. return s % {'_': '' if six.PY3 else 'u'}
  322. class CaptureQueriesContext(object):
  323. """
  324. Context manager that captures queries executed by the specified connection.
  325. """
  326. def __init__(self, connection):
  327. self.connection = connection
  328. def __iter__(self):
  329. return iter(self.captured_queries)
  330. def __getitem__(self, index):
  331. return self.captured_queries[index]
  332. def __len__(self):
  333. return len(self.captured_queries)
  334. @property
  335. def captured_queries(self):
  336. return self.connection.queries[self.initial_queries:self.final_queries]
  337. def __enter__(self):
  338. self.force_debug_cursor = self.connection.force_debug_cursor
  339. self.connection.force_debug_cursor = True
  340. self.initial_queries = len(self.connection.queries_log)
  341. self.final_queries = None
  342. request_started.disconnect(reset_queries)
  343. return self
  344. def __exit__(self, exc_type, exc_value, traceback):
  345. self.connection.force_debug_cursor = self.force_debug_cursor
  346. request_started.connect(reset_queries)
  347. if exc_type is not None:
  348. return
  349. self.final_queries = len(self.connection.queries_log)
  350. class ignore_warnings(object):
  351. def __init__(self, **kwargs):
  352. self.ignore_kwargs = kwargs
  353. if 'message' in self.ignore_kwargs or 'module' in self.ignore_kwargs:
  354. self.filter_func = warnings.filterwarnings
  355. else:
  356. self.filter_func = warnings.simplefilter
  357. def __call__(self, decorated):
  358. if isinstance(decorated, type):
  359. # A class is decorated
  360. saved_setUp = decorated.setUp
  361. saved_tearDown = decorated.tearDown
  362. def setUp(inner_self):
  363. self.catch_warnings = warnings.catch_warnings()
  364. self.catch_warnings.__enter__()
  365. self.filter_func('ignore', **self.ignore_kwargs)
  366. saved_setUp(inner_self)
  367. def tearDown(inner_self):
  368. saved_tearDown(inner_self)
  369. self.catch_warnings.__exit__(*sys.exc_info())
  370. decorated.setUp = setUp
  371. decorated.tearDown = tearDown
  372. return decorated
  373. else:
  374. @wraps(decorated)
  375. def inner(*args, **kwargs):
  376. with warnings.catch_warnings():
  377. self.filter_func('ignore', **self.ignore_kwargs)
  378. return decorated(*args, **kwargs)
  379. return inner
  380. @contextmanager
  381. def patch_logger(logger_name, log_level):
  382. """
  383. Context manager that takes a named logger and the logging level
  384. and provides a simple mock-like list of messages received
  385. """
  386. calls = []
  387. def replacement(msg, *args, **kwargs):
  388. calls.append(msg % args)
  389. logger = logging.getLogger(logger_name)
  390. orig = getattr(logger, log_level)
  391. setattr(logger, log_level, replacement)
  392. try:
  393. yield calls
  394. finally:
  395. setattr(logger, log_level, orig)
  396. # On OSes that don't provide tzset (Windows), we can't set the timezone
  397. # in which the program runs. As a consequence, we must skip tests that
  398. # don't enforce a specific timezone (with timezone.override or equivalent),
  399. # or attempt to interpret naive datetimes in the default timezone.
  400. requires_tz_support = skipUnless(TZ_SUPPORT,
  401. "This test relies on the ability to run a program in an arbitrary "
  402. "time zone, but your operating system isn't able to do that.")
  403. @contextmanager
  404. def extend_sys_path(*paths):
  405. """Context manager to temporarily add paths to sys.path."""
  406. _orig_sys_path = sys.path[:]
  407. sys.path.extend(paths)
  408. try:
  409. yield
  410. finally:
  411. sys.path = _orig_sys_path
  412. @contextmanager
  413. def isolate_lru_cache(lru_cache_object):
  414. """Clear the cache of an LRU cache object on entering and exiting."""
  415. lru_cache_object.cache_clear()
  416. try:
  417. yield
  418. finally:
  419. lru_cache_object.cache_clear()
  420. @contextmanager
  421. def captured_output(stream_name):
  422. """Return a context manager used by captured_stdout/stdin/stderr
  423. that temporarily replaces the sys stream *stream_name* with a StringIO.
  424. Note: This function and the following ``captured_std*`` are copied
  425. from CPython's ``test.support`` module."""
  426. orig_stdout = getattr(sys, stream_name)
  427. setattr(sys, stream_name, six.StringIO())
  428. try:
  429. yield getattr(sys, stream_name)
  430. finally:
  431. setattr(sys, stream_name, orig_stdout)
  432. def captured_stdout():
  433. """Capture the output of sys.stdout:
  434. with captured_stdout() as stdout:
  435. print("hello")
  436. self.assertEqual(stdout.getvalue(), "hello\n")
  437. """
  438. return captured_output("stdout")
  439. def captured_stderr():
  440. """Capture the output of sys.stderr:
  441. with captured_stderr() as stderr:
  442. print("hello", file=sys.stderr)
  443. self.assertEqual(stderr.getvalue(), "hello\n")
  444. """
  445. return captured_output("stderr")
  446. def captured_stdin():
  447. """Capture the input to sys.stdin:
  448. with captured_stdin() as stdin:
  449. stdin.write('hello\n')
  450. stdin.seek(0)
  451. # call test code that consumes from sys.stdin
  452. captured = input()
  453. self.assertEqual(captured, "hello")
  454. """
  455. return captured_output("stdin")
  456. def reset_warning_registry():
  457. """
  458. Clear warning registry for all modules. This is required in some tests
  459. because of a bug in Python that prevents warnings.simplefilter("always")
  460. from always making warnings appear: http://bugs.python.org/issue4180
  461. The bug was fixed in Python 3.4.2.
  462. """
  463. key = "__warningregistry__"
  464. for mod in sys.modules.values():
  465. if hasattr(mod, key):
  466. getattr(mod, key).clear()
  467. @contextmanager
  468. def freeze_time(t):
  469. """
  470. Context manager to temporarily freeze time.time(). This temporarily
  471. modifies the time function of the time module. Modules which import the
  472. time function directly (e.g. `from time import time`) won't be affected
  473. This isn't meant as a public API, but helps reduce some repetitive code in
  474. Django's test suite.
  475. """
  476. _real_time = time.time
  477. time.time = lambda: t
  478. try:
  479. yield
  480. finally:
  481. time.time = _real_time
  482. def require_jinja2(test_func):
  483. """
  484. Decorator to enable a Jinja2 template engine in addition to the regular
  485. Django template engine for a test or skip it if Jinja2 isn't available.
  486. """
  487. test_func = skipIf(jinja2 is None, "this test requires jinja2")(test_func)
  488. test_func = override_settings(TEMPLATES=[{
  489. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  490. 'APP_DIRS': True,
  491. }, {
  492. 'BACKEND': 'django.template.backends.jinja2.Jinja2',
  493. 'APP_DIRS': True,
  494. 'OPTIONS': {'keep_trailing_newline': True},
  495. }])(test_func)
  496. return test_func
  497. class ScriptPrefix(ContextDecorator):
  498. def __enter__(self):
  499. set_script_prefix(self.prefix)
  500. def __exit__(self, exc_type, exc_val, traceback):
  501. set_script_prefix(self.old_prefix)
  502. def __init__(self, prefix):
  503. self.prefix = prefix
  504. self.old_prefix = get_script_prefix()
  505. def override_script_prefix(prefix):
  506. """
  507. Decorator or context manager to temporary override the script prefix.
  508. """
  509. return ScriptPrefix(prefix)
  510. class LoggingCaptureMixin(object):
  511. """
  512. Capture the output from the 'django' logger and store it on the class's
  513. logger_output attribute.
  514. """
  515. def setUp(self):
  516. self.logger = logging.getLogger('django')
  517. self.old_stream = self.logger.handlers[0].stream
  518. self.logger_output = six.StringIO()
  519. self.logger.handlers[0].stream = self.logger_output
  520. def tearDown(self):
  521. self.logger.handlers[0].stream = self.old_stream