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.

utils.py 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. import collections
  2. import logging
  3. import re
  4. import sys
  5. import time
  6. import warnings
  7. from contextlib import contextmanager
  8. from functools import wraps
  9. from io import StringIO
  10. from itertools import chain
  11. from types import SimpleNamespace
  12. from unittest import TestCase, skipIf, skipUnless
  13. from xml.dom.minidom import Node, parseString
  14. from django.apps import apps
  15. from django.apps.registry import Apps
  16. from django.conf import UserSettingsHolder, settings
  17. from django.core import mail
  18. from django.core.exceptions import ImproperlyConfigured
  19. from django.core.signals import request_started
  20. from django.db import DEFAULT_DB_ALIAS, connections, reset_queries
  21. from django.db.models.options import Options
  22. from django.template import Template
  23. from django.test.signals import setting_changed, template_rendered
  24. from django.urls import get_script_prefix, set_script_prefix
  25. from django.utils.translation import deactivate
  26. try:
  27. import jinja2
  28. except ImportError:
  29. jinja2 = None
  30. __all__ = (
  31. 'Approximate', 'ContextList', 'isolate_lru_cache', 'get_runner',
  32. 'modify_settings', 'override_settings',
  33. 'requires_tz_support',
  34. 'setup_test_environment', 'teardown_test_environment',
  35. )
  36. TZ_SUPPORT = hasattr(time, 'tzset')
  37. class Approximate:
  38. def __init__(self, val, places=7):
  39. self.val = val
  40. self.places = places
  41. def __repr__(self):
  42. return repr(self.val)
  43. def __eq__(self, other):
  44. return self.val == other or round(abs(self.val - other), self.places) == 0
  45. class ContextList(list):
  46. """
  47. A wrapper that provides direct key access to context items contained
  48. in a list of context objects.
  49. """
  50. def __getitem__(self, key):
  51. if isinstance(key, str):
  52. for subcontext in self:
  53. if key in subcontext:
  54. return subcontext[key]
  55. raise KeyError(key)
  56. else:
  57. return super().__getitem__(key)
  58. def get(self, key, default=None):
  59. try:
  60. return self.__getitem__(key)
  61. except KeyError:
  62. return default
  63. def __contains__(self, key):
  64. try:
  65. self[key]
  66. except KeyError:
  67. return False
  68. return True
  69. def keys(self):
  70. """
  71. Flattened keys of subcontexts.
  72. """
  73. return set(chain.from_iterable(d for subcontext in self for d in subcontext))
  74. def instrumented_test_render(self, context):
  75. """
  76. An instrumented Template render method, providing a signal that can be
  77. intercepted by the test Client.
  78. """
  79. template_rendered.send(sender=self, template=self, context=context)
  80. return self.nodelist.render(context)
  81. class _TestState:
  82. pass
  83. def setup_test_environment(debug=None):
  84. """
  85. Perform global pre-test setup, such as installing the instrumented template
  86. renderer and setting the email backend to the locmem email backend.
  87. """
  88. if hasattr(_TestState, 'saved_data'):
  89. # Executing this function twice would overwrite the saved values.
  90. raise RuntimeError(
  91. "setup_test_environment() was already called and can't be called "
  92. "again without first calling teardown_test_environment()."
  93. )
  94. if debug is None:
  95. debug = settings.DEBUG
  96. saved_data = SimpleNamespace()
  97. _TestState.saved_data = saved_data
  98. saved_data.allowed_hosts = settings.ALLOWED_HOSTS
  99. # Add the default host of the test client.
  100. settings.ALLOWED_HOSTS = [*settings.ALLOWED_HOSTS, 'testserver']
  101. saved_data.debug = settings.DEBUG
  102. settings.DEBUG = debug
  103. saved_data.email_backend = settings.EMAIL_BACKEND
  104. settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
  105. saved_data.template_render = Template._render
  106. Template._render = instrumented_test_render
  107. mail.outbox = []
  108. deactivate()
  109. def teardown_test_environment():
  110. """
  111. Perform any global post-test teardown, such as restoring the original
  112. template renderer and restoring the email sending functions.
  113. """
  114. saved_data = _TestState.saved_data
  115. settings.ALLOWED_HOSTS = saved_data.allowed_hosts
  116. settings.DEBUG = saved_data.debug
  117. settings.EMAIL_BACKEND = saved_data.email_backend
  118. Template._render = saved_data.template_render
  119. del _TestState.saved_data
  120. del mail.outbox
  121. def setup_databases(verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, aliases=None, **kwargs):
  122. """Create the test databases."""
  123. test_databases, mirrored_aliases = get_unique_databases_and_mirrors(aliases)
  124. old_names = []
  125. for db_name, aliases in test_databases.values():
  126. first_alias = None
  127. for alias in aliases:
  128. connection = connections[alias]
  129. old_names.append((connection, db_name, first_alias is None))
  130. # Actually create the database for the first connection
  131. if first_alias is None:
  132. first_alias = alias
  133. connection.creation.create_test_db(
  134. verbosity=verbosity,
  135. autoclobber=not interactive,
  136. keepdb=keepdb,
  137. serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
  138. )
  139. if parallel > 1:
  140. for index in range(parallel):
  141. connection.creation.clone_test_db(
  142. suffix=str(index + 1),
  143. verbosity=verbosity,
  144. keepdb=keepdb,
  145. )
  146. # Configure all other connections as mirrors of the first one
  147. else:
  148. connections[alias].creation.set_as_test_mirror(connections[first_alias].settings_dict)
  149. # Configure the test mirrors.
  150. for alias, mirror_alias in mirrored_aliases.items():
  151. connections[alias].creation.set_as_test_mirror(
  152. connections[mirror_alias].settings_dict)
  153. if debug_sql:
  154. for alias in connections:
  155. connections[alias].force_debug_cursor = True
  156. return old_names
  157. def dependency_ordered(test_databases, dependencies):
  158. """
  159. Reorder test_databases into an order that honors the dependencies
  160. described in TEST[DEPENDENCIES].
  161. """
  162. ordered_test_databases = []
  163. resolved_databases = set()
  164. # Maps db signature to dependencies of all its aliases
  165. dependencies_map = {}
  166. # Check that no database depends on its own alias
  167. for sig, (_, aliases) in test_databases:
  168. all_deps = set()
  169. for alias in aliases:
  170. all_deps.update(dependencies.get(alias, []))
  171. if not all_deps.isdisjoint(aliases):
  172. raise ImproperlyConfigured(
  173. "Circular dependency: databases %r depend on each other, "
  174. "but are aliases." % aliases
  175. )
  176. dependencies_map[sig] = all_deps
  177. while test_databases:
  178. changed = False
  179. deferred = []
  180. # Try to find a DB that has all its dependencies met
  181. for signature, (db_name, aliases) in test_databases:
  182. if dependencies_map[signature].issubset(resolved_databases):
  183. resolved_databases.update(aliases)
  184. ordered_test_databases.append((signature, (db_name, aliases)))
  185. changed = True
  186. else:
  187. deferred.append((signature, (db_name, aliases)))
  188. if not changed:
  189. raise ImproperlyConfigured("Circular dependency in TEST[DEPENDENCIES]")
  190. test_databases = deferred
  191. return ordered_test_databases
  192. def get_unique_databases_and_mirrors(aliases=None):
  193. """
  194. Figure out which databases actually need to be created.
  195. Deduplicate entries in DATABASES that correspond the same database or are
  196. configured as test mirrors.
  197. Return two values:
  198. - test_databases: ordered mapping of signatures to (name, list of aliases)
  199. where all aliases share the same underlying database.
  200. - mirrored_aliases: mapping of mirror aliases to original aliases.
  201. """
  202. if aliases is None:
  203. aliases = connections
  204. mirrored_aliases = {}
  205. test_databases = {}
  206. dependencies = {}
  207. default_sig = connections[DEFAULT_DB_ALIAS].creation.test_db_signature()
  208. for alias in connections:
  209. connection = connections[alias]
  210. test_settings = connection.settings_dict['TEST']
  211. if test_settings['MIRROR']:
  212. # If the database is marked as a test mirror, save the alias.
  213. mirrored_aliases[alias] = test_settings['MIRROR']
  214. elif alias in aliases:
  215. # Store a tuple with DB parameters that uniquely identify it.
  216. # If we have two aliases with the same values for that tuple,
  217. # we only need to create the test database once.
  218. item = test_databases.setdefault(
  219. connection.creation.test_db_signature(),
  220. (connection.settings_dict['NAME'], set())
  221. )
  222. item[1].add(alias)
  223. if 'DEPENDENCIES' in test_settings:
  224. dependencies[alias] = test_settings['DEPENDENCIES']
  225. else:
  226. if alias != DEFAULT_DB_ALIAS and connection.creation.test_db_signature() != default_sig:
  227. dependencies[alias] = test_settings.get('DEPENDENCIES', [DEFAULT_DB_ALIAS])
  228. test_databases = dependency_ordered(test_databases.items(), dependencies)
  229. test_databases = collections.OrderedDict(test_databases)
  230. return test_databases, mirrored_aliases
  231. def teardown_databases(old_config, verbosity, parallel=0, keepdb=False):
  232. """Destroy all the non-mirror databases."""
  233. for connection, old_name, destroy in old_config:
  234. if destroy:
  235. if parallel > 1:
  236. for index in range(parallel):
  237. connection.creation.destroy_test_db(
  238. suffix=str(index + 1),
  239. verbosity=verbosity,
  240. keepdb=keepdb,
  241. )
  242. connection.creation.destroy_test_db(old_name, verbosity, keepdb)
  243. def get_runner(settings, test_runner_class=None):
  244. test_runner_class = test_runner_class or settings.TEST_RUNNER
  245. test_path = test_runner_class.split('.')
  246. # Allow for relative paths
  247. if len(test_path) > 1:
  248. test_module_name = '.'.join(test_path[:-1])
  249. else:
  250. test_module_name = '.'
  251. test_module = __import__(test_module_name, {}, {}, test_path[-1])
  252. test_runner = getattr(test_module, test_path[-1])
  253. return test_runner
  254. class TestContextDecorator:
  255. """
  256. A base class that can either be used as a context manager during tests
  257. or as a test function or unittest.TestCase subclass decorator to perform
  258. temporary alterations.
  259. `attr_name`: attribute assigned the return value of enable() if used as
  260. a class decorator.
  261. `kwarg_name`: keyword argument passing the return value of enable() if
  262. used as a function decorator.
  263. """
  264. def __init__(self, attr_name=None, kwarg_name=None):
  265. self.attr_name = attr_name
  266. self.kwarg_name = kwarg_name
  267. def enable(self):
  268. raise NotImplementedError
  269. def disable(self):
  270. raise NotImplementedError
  271. def __enter__(self):
  272. return self.enable()
  273. def __exit__(self, exc_type, exc_value, traceback):
  274. self.disable()
  275. def decorate_class(self, cls):
  276. if issubclass(cls, TestCase):
  277. decorated_setUp = cls.setUp
  278. decorated_tearDown = cls.tearDown
  279. def setUp(inner_self):
  280. context = self.enable()
  281. if self.attr_name:
  282. setattr(inner_self, self.attr_name, context)
  283. try:
  284. decorated_setUp(inner_self)
  285. except Exception:
  286. self.disable()
  287. raise
  288. def tearDown(inner_self):
  289. decorated_tearDown(inner_self)
  290. self.disable()
  291. cls.setUp = setUp
  292. cls.tearDown = tearDown
  293. return cls
  294. raise TypeError('Can only decorate subclasses of unittest.TestCase')
  295. def decorate_callable(self, func):
  296. @wraps(func)
  297. def inner(*args, **kwargs):
  298. with self as context:
  299. if self.kwarg_name:
  300. kwargs[self.kwarg_name] = context
  301. return func(*args, **kwargs)
  302. return inner
  303. def __call__(self, decorated):
  304. if isinstance(decorated, type):
  305. return self.decorate_class(decorated)
  306. elif callable(decorated):
  307. return self.decorate_callable(decorated)
  308. raise TypeError('Cannot decorate object of type %s' % type(decorated))
  309. class override_settings(TestContextDecorator):
  310. """
  311. Act as either a decorator or a context manager. If it's a decorator, take a
  312. function and return a wrapped function. If it's a contextmanager, use it
  313. with the ``with`` statement. In either event, entering/exiting are called
  314. before and after, respectively, the function/block is executed.
  315. """
  316. enable_exception = None
  317. def __init__(self, **kwargs):
  318. self.options = kwargs
  319. super().__init__()
  320. def enable(self):
  321. # Keep this code at the beginning to leave the settings unchanged
  322. # in case it raises an exception because INSTALLED_APPS is invalid.
  323. if 'INSTALLED_APPS' in self.options:
  324. try:
  325. apps.set_installed_apps(self.options['INSTALLED_APPS'])
  326. except Exception:
  327. apps.unset_installed_apps()
  328. raise
  329. override = UserSettingsHolder(settings._wrapped)
  330. for key, new_value in self.options.items():
  331. setattr(override, key, new_value)
  332. self.wrapped = settings._wrapped
  333. settings._wrapped = override
  334. for key, new_value in self.options.items():
  335. try:
  336. setting_changed.send(
  337. sender=settings._wrapped.__class__,
  338. setting=key, value=new_value, enter=True,
  339. )
  340. except Exception as exc:
  341. self.enable_exception = exc
  342. self.disable()
  343. def disable(self):
  344. if 'INSTALLED_APPS' in self.options:
  345. apps.unset_installed_apps()
  346. settings._wrapped = self.wrapped
  347. del self.wrapped
  348. responses = []
  349. for key in self.options:
  350. new_value = getattr(settings, key, None)
  351. responses_for_setting = setting_changed.send_robust(
  352. sender=settings._wrapped.__class__,
  353. setting=key, value=new_value, enter=False,
  354. )
  355. responses.extend(responses_for_setting)
  356. if self.enable_exception is not None:
  357. exc = self.enable_exception
  358. self.enable_exception = None
  359. raise exc
  360. for _, response in responses:
  361. if isinstance(response, Exception):
  362. raise response
  363. def save_options(self, test_func):
  364. if test_func._overridden_settings is None:
  365. test_func._overridden_settings = self.options
  366. else:
  367. # Duplicate dict to prevent subclasses from altering their parent.
  368. test_func._overridden_settings = {
  369. **test_func._overridden_settings,
  370. **self.options,
  371. }
  372. def decorate_class(self, cls):
  373. from django.test import SimpleTestCase
  374. if not issubclass(cls, SimpleTestCase):
  375. raise ValueError(
  376. "Only subclasses of Django SimpleTestCase can be decorated "
  377. "with override_settings")
  378. self.save_options(cls)
  379. return cls
  380. class modify_settings(override_settings):
  381. """
  382. Like override_settings, but makes it possible to append, prepend, or remove
  383. items instead of redefining the entire list.
  384. """
  385. def __init__(self, *args, **kwargs):
  386. if args:
  387. # Hack used when instantiating from SimpleTestCase.setUpClass.
  388. assert not kwargs
  389. self.operations = args[0]
  390. else:
  391. assert not args
  392. self.operations = list(kwargs.items())
  393. super(override_settings, self).__init__()
  394. def save_options(self, test_func):
  395. if test_func._modified_settings is None:
  396. test_func._modified_settings = self.operations
  397. else:
  398. # Duplicate list to prevent subclasses from altering their parent.
  399. test_func._modified_settings = list(
  400. test_func._modified_settings) + self.operations
  401. def enable(self):
  402. self.options = {}
  403. for name, operations in self.operations:
  404. try:
  405. # When called from SimpleTestCase.setUpClass, values may be
  406. # overridden several times; cumulate changes.
  407. value = self.options[name]
  408. except KeyError:
  409. value = list(getattr(settings, name, []))
  410. for action, items in operations.items():
  411. # items my be a single value or an iterable.
  412. if isinstance(items, str):
  413. items = [items]
  414. if action == 'append':
  415. value = value + [item for item in items if item not in value]
  416. elif action == 'prepend':
  417. value = [item for item in items if item not in value] + value
  418. elif action == 'remove':
  419. value = [item for item in value if item not in items]
  420. else:
  421. raise ValueError("Unsupported action: %s" % action)
  422. self.options[name] = value
  423. super().enable()
  424. class override_system_checks(TestContextDecorator):
  425. """
  426. Act as a decorator. Override list of registered system checks.
  427. Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app,
  428. you also need to exclude its system checks.
  429. """
  430. def __init__(self, new_checks, deployment_checks=None):
  431. from django.core.checks.registry import registry
  432. self.registry = registry
  433. self.new_checks = new_checks
  434. self.deployment_checks = deployment_checks
  435. super().__init__()
  436. def enable(self):
  437. self.old_checks = self.registry.registered_checks
  438. self.registry.registered_checks = set()
  439. for check in self.new_checks:
  440. self.registry.register(check, *getattr(check, 'tags', ()))
  441. self.old_deployment_checks = self.registry.deployment_checks
  442. if self.deployment_checks is not None:
  443. self.registry.deployment_checks = set()
  444. for check in self.deployment_checks:
  445. self.registry.register(check, *getattr(check, 'tags', ()), deploy=True)
  446. def disable(self):
  447. self.registry.registered_checks = self.old_checks
  448. self.registry.deployment_checks = self.old_deployment_checks
  449. def compare_xml(want, got):
  450. """
  451. Try to do a 'xml-comparison' of want and got. Plain string comparison
  452. doesn't always work because, for example, attribute ordering should not be
  453. important. Ignore comment nodes and leading and trailing whitespace.
  454. Based on https://github.com/lxml/lxml/blob/master/src/lxml/doctestcompare.py
  455. """
  456. _norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
  457. def norm_whitespace(v):
  458. return _norm_whitespace_re.sub(' ', v)
  459. def child_text(element):
  460. return ''.join(c.data for c in element.childNodes
  461. if c.nodeType == Node.TEXT_NODE)
  462. def children(element):
  463. return [c for c in element.childNodes
  464. if c.nodeType == Node.ELEMENT_NODE]
  465. def norm_child_text(element):
  466. return norm_whitespace(child_text(element))
  467. def attrs_dict(element):
  468. return dict(element.attributes.items())
  469. def check_element(want_element, got_element):
  470. if want_element.tagName != got_element.tagName:
  471. return False
  472. if norm_child_text(want_element) != norm_child_text(got_element):
  473. return False
  474. if attrs_dict(want_element) != attrs_dict(got_element):
  475. return False
  476. want_children = children(want_element)
  477. got_children = children(got_element)
  478. if len(want_children) != len(got_children):
  479. return False
  480. return all(check_element(want, got) for want, got in zip(want_children, got_children))
  481. def first_node(document):
  482. for node in document.childNodes:
  483. if node.nodeType != Node.COMMENT_NODE:
  484. return node
  485. want = want.strip().replace('\\n', '\n')
  486. got = got.strip().replace('\\n', '\n')
  487. # If the string is not a complete xml document, we may need to add a
  488. # root element. This allow us to compare fragments, like "<foo/><bar/>"
  489. if not want.startswith('<?xml'):
  490. wrapper = '<root>%s</root>'
  491. want = wrapper % want
  492. got = wrapper % got
  493. # Parse the want and got strings, and compare the parsings.
  494. want_root = first_node(parseString(want))
  495. got_root = first_node(parseString(got))
  496. return check_element(want_root, got_root)
  497. def str_prefix(s):
  498. return s % {'_': ''}
  499. class CaptureQueriesContext:
  500. """
  501. Context manager that captures queries executed by the specified connection.
  502. """
  503. def __init__(self, connection):
  504. self.connection = connection
  505. def __iter__(self):
  506. return iter(self.captured_queries)
  507. def __getitem__(self, index):
  508. return self.captured_queries[index]
  509. def __len__(self):
  510. return len(self.captured_queries)
  511. @property
  512. def captured_queries(self):
  513. return self.connection.queries[self.initial_queries:self.final_queries]
  514. def __enter__(self):
  515. self.force_debug_cursor = self.connection.force_debug_cursor
  516. self.connection.force_debug_cursor = True
  517. # Run any initialization queries if needed so that they won't be
  518. # included as part of the count.
  519. self.connection.ensure_connection()
  520. self.initial_queries = len(self.connection.queries_log)
  521. self.final_queries = None
  522. request_started.disconnect(reset_queries)
  523. return self
  524. def __exit__(self, exc_type, exc_value, traceback):
  525. self.connection.force_debug_cursor = self.force_debug_cursor
  526. request_started.connect(reset_queries)
  527. if exc_type is not None:
  528. return
  529. self.final_queries = len(self.connection.queries_log)
  530. class ignore_warnings(TestContextDecorator):
  531. def __init__(self, **kwargs):
  532. self.ignore_kwargs = kwargs
  533. if 'message' in self.ignore_kwargs or 'module' in self.ignore_kwargs:
  534. self.filter_func = warnings.filterwarnings
  535. else:
  536. self.filter_func = warnings.simplefilter
  537. super().__init__()
  538. def enable(self):
  539. self.catch_warnings = warnings.catch_warnings()
  540. self.catch_warnings.__enter__()
  541. self.filter_func('ignore', **self.ignore_kwargs)
  542. def disable(self):
  543. self.catch_warnings.__exit__(*sys.exc_info())
  544. @contextmanager
  545. def patch_logger(logger_name, log_level, log_kwargs=False):
  546. """
  547. Context manager that takes a named logger and the logging level
  548. and provides a simple mock-like list of messages received.
  549. Use unittest.assertLogs() if you only need Python 3 support. This
  550. private API will be removed after Python 2 EOL in 2020 (#27753).
  551. """
  552. calls = []
  553. def replacement(msg, *args, **kwargs):
  554. call = msg % args
  555. calls.append((call, kwargs) if log_kwargs else call)
  556. logger = logging.getLogger(logger_name)
  557. orig = getattr(logger, log_level)
  558. setattr(logger, log_level, replacement)
  559. try:
  560. yield calls
  561. finally:
  562. setattr(logger, log_level, orig)
  563. # On OSes that don't provide tzset (Windows), we can't set the timezone
  564. # in which the program runs. As a consequence, we must skip tests that
  565. # don't enforce a specific timezone (with timezone.override or equivalent),
  566. # or attempt to interpret naive datetimes in the default timezone.
  567. requires_tz_support = skipUnless(
  568. TZ_SUPPORT,
  569. "This test relies on the ability to run a program in an arbitrary "
  570. "time zone, but your operating system isn't able to do that."
  571. )
  572. @contextmanager
  573. def extend_sys_path(*paths):
  574. """Context manager to temporarily add paths to sys.path."""
  575. _orig_sys_path = sys.path[:]
  576. sys.path.extend(paths)
  577. try:
  578. yield
  579. finally:
  580. sys.path = _orig_sys_path
  581. @contextmanager
  582. def isolate_lru_cache(lru_cache_object):
  583. """Clear the cache of an LRU cache object on entering and exiting."""
  584. lru_cache_object.cache_clear()
  585. try:
  586. yield
  587. finally:
  588. lru_cache_object.cache_clear()
  589. @contextmanager
  590. def captured_output(stream_name):
  591. """Return a context manager used by captured_stdout/stdin/stderr
  592. that temporarily replaces the sys stream *stream_name* with a StringIO.
  593. Note: This function and the following ``captured_std*`` are copied
  594. from CPython's ``test.support`` module."""
  595. orig_stdout = getattr(sys, stream_name)
  596. setattr(sys, stream_name, StringIO())
  597. try:
  598. yield getattr(sys, stream_name)
  599. finally:
  600. setattr(sys, stream_name, orig_stdout)
  601. def captured_stdout():
  602. """Capture the output of sys.stdout:
  603. with captured_stdout() as stdout:
  604. print("hello")
  605. self.assertEqual(stdout.getvalue(), "hello\n")
  606. """
  607. return captured_output("stdout")
  608. def captured_stderr():
  609. """Capture the output of sys.stderr:
  610. with captured_stderr() as stderr:
  611. print("hello", file=sys.stderr)
  612. self.assertEqual(stderr.getvalue(), "hello\n")
  613. """
  614. return captured_output("stderr")
  615. def captured_stdin():
  616. """Capture the input to sys.stdin:
  617. with captured_stdin() as stdin:
  618. stdin.write('hello\n')
  619. stdin.seek(0)
  620. # call test code that consumes from sys.stdin
  621. captured = input()
  622. self.assertEqual(captured, "hello")
  623. """
  624. return captured_output("stdin")
  625. @contextmanager
  626. def freeze_time(t):
  627. """
  628. Context manager to temporarily freeze time.time(). This temporarily
  629. modifies the time function of the time module. Modules which import the
  630. time function directly (e.g. `from time import time`) won't be affected
  631. This isn't meant as a public API, but helps reduce some repetitive code in
  632. Django's test suite.
  633. """
  634. _real_time = time.time
  635. time.time = lambda: t
  636. try:
  637. yield
  638. finally:
  639. time.time = _real_time
  640. def require_jinja2(test_func):
  641. """
  642. Decorator to enable a Jinja2 template engine in addition to the regular
  643. Django template engine for a test or skip it if Jinja2 isn't available.
  644. """
  645. test_func = skipIf(jinja2 is None, "this test requires jinja2")(test_func)
  646. test_func = override_settings(TEMPLATES=[{
  647. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  648. 'APP_DIRS': True,
  649. }, {
  650. 'BACKEND': 'django.template.backends.jinja2.Jinja2',
  651. 'APP_DIRS': True,
  652. 'OPTIONS': {'keep_trailing_newline': True},
  653. }])(test_func)
  654. return test_func
  655. class override_script_prefix(TestContextDecorator):
  656. """Decorator or context manager to temporary override the script prefix."""
  657. def __init__(self, prefix):
  658. self.prefix = prefix
  659. super().__init__()
  660. def enable(self):
  661. self.old_prefix = get_script_prefix()
  662. set_script_prefix(self.prefix)
  663. def disable(self):
  664. set_script_prefix(self.old_prefix)
  665. class LoggingCaptureMixin:
  666. """
  667. Capture the output from the 'django' logger and store it on the class's
  668. logger_output attribute.
  669. """
  670. def setUp(self):
  671. self.logger = logging.getLogger('django')
  672. self.old_stream = self.logger.handlers[0].stream
  673. self.logger_output = StringIO()
  674. self.logger.handlers[0].stream = self.logger_output
  675. def tearDown(self):
  676. self.logger.handlers[0].stream = self.old_stream
  677. class isolate_apps(TestContextDecorator):
  678. """
  679. Act as either a decorator or a context manager to register models defined
  680. in its wrapped context to an isolated registry.
  681. The list of installed apps the isolated registry should contain must be
  682. passed as arguments.
  683. Two optional keyword arguments can be specified:
  684. `attr_name`: attribute assigned the isolated registry if used as a class
  685. decorator.
  686. `kwarg_name`: keyword argument passing the isolated registry if used as a
  687. function decorator.
  688. """
  689. def __init__(self, *installed_apps, **kwargs):
  690. self.installed_apps = installed_apps
  691. super().__init__(**kwargs)
  692. def enable(self):
  693. self.old_apps = Options.default_apps
  694. apps = Apps(self.installed_apps)
  695. setattr(Options, 'default_apps', apps)
  696. return apps
  697. def disable(self):
  698. setattr(Options, 'default_apps', self.old_apps)
  699. def tag(*tags):
  700. """Decorator to add tags to a test class or method."""
  701. def decorator(obj):
  702. if hasattr(obj, 'tags'):
  703. obj.tags = obj.tags.union(tags)
  704. else:
  705. setattr(obj, 'tags', set(tags))
  706. return obj
  707. return decorator
  708. @contextmanager
  709. def register_lookup(field, *lookups, lookup_name=None):
  710. """
  711. Context manager to temporarily register lookups on a model field using
  712. lookup_name (or the lookup's lookup_name if not provided).
  713. """
  714. try:
  715. for lookup in lookups:
  716. field.register_lookup(lookup, lookup_name)
  717. yield
  718. finally:
  719. for lookup in lookups:
  720. field._unregister_lookup(lookup, lookup_name)