utils.py 28 KB

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