Development of an internal social media platform with personalised dashboards for students
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 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  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 = list(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, **kwargs):
  122. """Create the test databases."""
  123. test_databases, mirrored_aliases = get_unique_databases_and_mirrors()
  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():
  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. mirrored_aliases = {}
  203. test_databases = {}
  204. dependencies = {}
  205. default_sig = connections[DEFAULT_DB_ALIAS].creation.test_db_signature()
  206. for alias in connections:
  207. connection = connections[alias]
  208. test_settings = connection.settings_dict['TEST']
  209. if test_settings['MIRROR']:
  210. # If the database is marked as a test mirror, save the alias.
  211. mirrored_aliases[alias] = test_settings['MIRROR']
  212. else:
  213. # Store a tuple with DB parameters that uniquely identify it.
  214. # If we have two aliases with the same values for that tuple,
  215. # we only need to create the test database once.
  216. item = test_databases.setdefault(
  217. connection.creation.test_db_signature(),
  218. (connection.settings_dict['NAME'], set())
  219. )
  220. item[1].add(alias)
  221. if 'DEPENDENCIES' in test_settings:
  222. dependencies[alias] = test_settings['DEPENDENCIES']
  223. else:
  224. if alias != DEFAULT_DB_ALIAS and connection.creation.test_db_signature() != default_sig:
  225. dependencies[alias] = test_settings.get('DEPENDENCIES', [DEFAULT_DB_ALIAS])
  226. test_databases = dependency_ordered(test_databases.items(), dependencies)
  227. test_databases = collections.OrderedDict(test_databases)
  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. test_runner = getattr(test_module, test_path[-1])
  251. return test_runner
  252. class TestContextDecorator:
  253. """
  254. A base class that can either be used as a context manager during tests
  255. or as a test function or unittest.TestCase subclass decorator to perform
  256. temporary alterations.
  257. `attr_name`: attribute assigned the return value of enable() if used as
  258. a class decorator.
  259. `kwarg_name`: keyword argument passing the return value of enable() if
  260. used as a function decorator.
  261. """
  262. def __init__(self, attr_name=None, kwarg_name=None):
  263. self.attr_name = attr_name
  264. self.kwarg_name = kwarg_name
  265. def enable(self):
  266. raise NotImplementedError
  267. def disable(self):
  268. raise NotImplementedError
  269. def __enter__(self):
  270. return self.enable()
  271. def __exit__(self, exc_type, exc_value, traceback):
  272. self.disable()
  273. def decorate_class(self, cls):
  274. if issubclass(cls, TestCase):
  275. decorated_setUp = cls.setUp
  276. decorated_tearDown = cls.tearDown
  277. def setUp(inner_self):
  278. context = self.enable()
  279. if self.attr_name:
  280. setattr(inner_self, self.attr_name, context)
  281. decorated_setUp(inner_self)
  282. def tearDown(inner_self):
  283. decorated_tearDown(inner_self)
  284. self.disable()
  285. cls.setUp = setUp
  286. cls.tearDown = tearDown
  287. return cls
  288. raise TypeError('Can only decorate subclasses of unittest.TestCase')
  289. def decorate_callable(self, func):
  290. @wraps(func)
  291. def inner(*args, **kwargs):
  292. with self as context:
  293. if self.kwarg_name:
  294. kwargs[self.kwarg_name] = context
  295. return func(*args, **kwargs)
  296. return inner
  297. def __call__(self, decorated):
  298. if isinstance(decorated, type):
  299. return self.decorate_class(decorated)
  300. elif callable(decorated):
  301. return self.decorate_callable(decorated)
  302. raise TypeError('Cannot decorate object of type %s' % type(decorated))
  303. class override_settings(TestContextDecorator):
  304. """
  305. Act as either a decorator or a context manager. If it's a decorator, take a
  306. function and return a wrapped function. If it's a contextmanager, use it
  307. with the ``with`` statement. In either event, entering/exiting are called
  308. before and after, respectively, the function/block is executed.
  309. """
  310. def __init__(self, **kwargs):
  311. self.options = kwargs
  312. super().__init__()
  313. def enable(self):
  314. # Keep this code at the beginning to leave the settings unchanged
  315. # in case it raises an exception because INSTALLED_APPS is invalid.
  316. if 'INSTALLED_APPS' in self.options:
  317. try:
  318. apps.set_installed_apps(self.options['INSTALLED_APPS'])
  319. except Exception:
  320. apps.unset_installed_apps()
  321. raise
  322. override = UserSettingsHolder(settings._wrapped)
  323. for key, new_value in self.options.items():
  324. setattr(override, key, new_value)
  325. self.wrapped = settings._wrapped
  326. settings._wrapped = override
  327. for key, new_value in self.options.items():
  328. setting_changed.send(sender=settings._wrapped.__class__,
  329. setting=key, value=new_value, enter=True)
  330. def disable(self):
  331. if 'INSTALLED_APPS' in self.options:
  332. apps.unset_installed_apps()
  333. settings._wrapped = self.wrapped
  334. del self.wrapped
  335. for key in self.options:
  336. new_value = getattr(settings, key, None)
  337. setting_changed.send(sender=settings._wrapped.__class__,
  338. setting=key, value=new_value, enter=False)
  339. def save_options(self, test_func):
  340. if test_func._overridden_settings is None:
  341. test_func._overridden_settings = self.options
  342. else:
  343. # Duplicate dict to prevent subclasses from altering their parent.
  344. test_func._overridden_settings = {
  345. **test_func._overridden_settings,
  346. **self.options,
  347. }
  348. def decorate_class(self, cls):
  349. from django.test import SimpleTestCase
  350. if not issubclass(cls, SimpleTestCase):
  351. raise ValueError(
  352. "Only subclasses of Django SimpleTestCase can be decorated "
  353. "with override_settings")
  354. self.save_options(cls)
  355. return cls
  356. class modify_settings(override_settings):
  357. """
  358. Like override_settings, but makes it possible to append, prepend, or remove
  359. items instead of redefining the entire list.
  360. """
  361. def __init__(self, *args, **kwargs):
  362. if args:
  363. # Hack used when instantiating from SimpleTestCase.setUpClass.
  364. assert not kwargs
  365. self.operations = args[0]
  366. else:
  367. assert not args
  368. self.operations = list(kwargs.items())
  369. super(override_settings, self).__init__()
  370. def save_options(self, test_func):
  371. if test_func._modified_settings is None:
  372. test_func._modified_settings = self.operations
  373. else:
  374. # Duplicate list to prevent subclasses from altering their parent.
  375. test_func._modified_settings = list(
  376. test_func._modified_settings) + self.operations
  377. def enable(self):
  378. self.options = {}
  379. for name, operations in self.operations:
  380. try:
  381. # When called from SimpleTestCase.setUpClass, values may be
  382. # overridden several times; cumulate changes.
  383. value = self.options[name]
  384. except KeyError:
  385. value = list(getattr(settings, name, []))
  386. for action, items in operations.items():
  387. # items my be a single value or an iterable.
  388. if isinstance(items, str):
  389. items = [items]
  390. if action == 'append':
  391. value = value + [item for item in items if item not in value]
  392. elif action == 'prepend':
  393. value = [item for item in items if item not in value] + value
  394. elif action == 'remove':
  395. value = [item for item in value if item not in items]
  396. else:
  397. raise ValueError("Unsupported action: %s" % action)
  398. self.options[name] = value
  399. super().enable()
  400. class override_system_checks(TestContextDecorator):
  401. """
  402. Act as a decorator. Override list of registered system checks.
  403. Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app,
  404. you also need to exclude its system checks.
  405. """
  406. def __init__(self, new_checks, deployment_checks=None):
  407. from django.core.checks.registry import registry
  408. self.registry = registry
  409. self.new_checks = new_checks
  410. self.deployment_checks = deployment_checks
  411. super().__init__()
  412. def enable(self):
  413. self.old_checks = self.registry.registered_checks
  414. self.registry.registered_checks = set()
  415. for check in self.new_checks:
  416. self.registry.register(check, *getattr(check, 'tags', ()))
  417. self.old_deployment_checks = self.registry.deployment_checks
  418. if self.deployment_checks is not None:
  419. self.registry.deployment_checks = set()
  420. for check in self.deployment_checks:
  421. self.registry.register(check, *getattr(check, 'tags', ()), deploy=True)
  422. def disable(self):
  423. self.registry.registered_checks = self.old_checks
  424. self.registry.deployment_checks = self.old_deployment_checks
  425. def compare_xml(want, got):
  426. """
  427. Try to do a 'xml-comparison' of want and got. Plain string comparison
  428. doesn't always work because, for example, attribute ordering should not be
  429. important. Ignore comment nodes and leading and trailing whitespace.
  430. Based on https://github.com/lxml/lxml/blob/master/src/lxml/doctestcompare.py
  431. """
  432. _norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
  433. def norm_whitespace(v):
  434. return _norm_whitespace_re.sub(' ', v)
  435. def child_text(element):
  436. return ''.join(c.data for c in element.childNodes
  437. if c.nodeType == Node.TEXT_NODE)
  438. def children(element):
  439. return [c for c in element.childNodes
  440. if c.nodeType == Node.ELEMENT_NODE]
  441. def norm_child_text(element):
  442. return norm_whitespace(child_text(element))
  443. def attrs_dict(element):
  444. return dict(element.attributes.items())
  445. def check_element(want_element, got_element):
  446. if want_element.tagName != got_element.tagName:
  447. return False
  448. if norm_child_text(want_element) != norm_child_text(got_element):
  449. return False
  450. if attrs_dict(want_element) != attrs_dict(got_element):
  451. return False
  452. want_children = children(want_element)
  453. got_children = children(got_element)
  454. if len(want_children) != len(got_children):
  455. return False
  456. return all(check_element(want, got) for want, got in zip(want_children, got_children))
  457. def first_node(document):
  458. for node in document.childNodes:
  459. if node.nodeType != Node.COMMENT_NODE:
  460. return node
  461. want = want.strip().replace('\\n', '\n')
  462. got = got.strip().replace('\\n', '\n')
  463. # If the string is not a complete xml document, we may need to add a
  464. # root element. This allow us to compare fragments, like "<foo/><bar/>"
  465. if not want.startswith('<?xml'):
  466. wrapper = '<root>%s</root>'
  467. want = wrapper % want
  468. got = wrapper % got
  469. # Parse the want and got strings, and compare the parsings.
  470. want_root = first_node(parseString(want))
  471. got_root = first_node(parseString(got))
  472. return check_element(want_root, got_root)
  473. def str_prefix(s):
  474. return s % {'_': ''}
  475. class CaptureQueriesContext:
  476. """
  477. Context manager that captures queries executed by the specified connection.
  478. """
  479. def __init__(self, connection):
  480. self.connection = connection
  481. def __iter__(self):
  482. return iter(self.captured_queries)
  483. def __getitem__(self, index):
  484. return self.captured_queries[index]
  485. def __len__(self):
  486. return len(self.captured_queries)
  487. @property
  488. def captured_queries(self):
  489. return self.connection.queries[self.initial_queries:self.final_queries]
  490. def __enter__(self):
  491. self.force_debug_cursor = self.connection.force_debug_cursor
  492. self.connection.force_debug_cursor = True
  493. # Run any initialization queries if needed so that they won't be
  494. # included as part of the count.
  495. self.connection.ensure_connection()
  496. self.initial_queries = len(self.connection.queries_log)
  497. self.final_queries = None
  498. request_started.disconnect(reset_queries)
  499. return self
  500. def __exit__(self, exc_type, exc_value, traceback):
  501. self.connection.force_debug_cursor = self.force_debug_cursor
  502. request_started.connect(reset_queries)
  503. if exc_type is not None:
  504. return
  505. self.final_queries = len(self.connection.queries_log)
  506. class ignore_warnings(TestContextDecorator):
  507. def __init__(self, **kwargs):
  508. self.ignore_kwargs = kwargs
  509. if 'message' in self.ignore_kwargs or 'module' in self.ignore_kwargs:
  510. self.filter_func = warnings.filterwarnings
  511. else:
  512. self.filter_func = warnings.simplefilter
  513. super().__init__()
  514. def enable(self):
  515. self.catch_warnings = warnings.catch_warnings()
  516. self.catch_warnings.__enter__()
  517. self.filter_func('ignore', **self.ignore_kwargs)
  518. def disable(self):
  519. self.catch_warnings.__exit__(*sys.exc_info())
  520. @contextmanager
  521. def patch_logger(logger_name, log_level, log_kwargs=False):
  522. """
  523. Context manager that takes a named logger and the logging level
  524. and provides a simple mock-like list of messages received.
  525. Use unitttest.assertLogs() if you only need Python 3 support. This
  526. private API will be removed after Python 2 EOL in 2020 (#27753).
  527. """
  528. calls = []
  529. def replacement(msg, *args, **kwargs):
  530. call = msg % args
  531. calls.append((call, kwargs) if log_kwargs else call)
  532. logger = logging.getLogger(logger_name)
  533. orig = getattr(logger, log_level)
  534. setattr(logger, log_level, replacement)
  535. try:
  536. yield calls
  537. finally:
  538. setattr(logger, log_level, orig)
  539. # On OSes that don't provide tzset (Windows), we can't set the timezone
  540. # in which the program runs. As a consequence, we must skip tests that
  541. # don't enforce a specific timezone (with timezone.override or equivalent),
  542. # or attempt to interpret naive datetimes in the default timezone.
  543. requires_tz_support = skipUnless(
  544. TZ_SUPPORT,
  545. "This test relies on the ability to run a program in an arbitrary "
  546. "time zone, but your operating system isn't able to do that."
  547. )
  548. @contextmanager
  549. def extend_sys_path(*paths):
  550. """Context manager to temporarily add paths to sys.path."""
  551. _orig_sys_path = sys.path[:]
  552. sys.path.extend(paths)
  553. try:
  554. yield
  555. finally:
  556. sys.path = _orig_sys_path
  557. @contextmanager
  558. def isolate_lru_cache(lru_cache_object):
  559. """Clear the cache of an LRU cache object on entering and exiting."""
  560. lru_cache_object.cache_clear()
  561. try:
  562. yield
  563. finally:
  564. lru_cache_object.cache_clear()
  565. @contextmanager
  566. def captured_output(stream_name):
  567. """Return a context manager used by captured_stdout/stdin/stderr
  568. that temporarily replaces the sys stream *stream_name* with a StringIO.
  569. Note: This function and the following ``captured_std*`` are copied
  570. from CPython's ``test.support`` module."""
  571. orig_stdout = getattr(sys, stream_name)
  572. setattr(sys, stream_name, StringIO())
  573. try:
  574. yield getattr(sys, stream_name)
  575. finally:
  576. setattr(sys, stream_name, orig_stdout)
  577. def captured_stdout():
  578. """Capture the output of sys.stdout:
  579. with captured_stdout() as stdout:
  580. print("hello")
  581. self.assertEqual(stdout.getvalue(), "hello\n")
  582. """
  583. return captured_output("stdout")
  584. def captured_stderr():
  585. """Capture the output of sys.stderr:
  586. with captured_stderr() as stderr:
  587. print("hello", file=sys.stderr)
  588. self.assertEqual(stderr.getvalue(), "hello\n")
  589. """
  590. return captured_output("stderr")
  591. def captured_stdin():
  592. """Capture the input to sys.stdin:
  593. with captured_stdin() as stdin:
  594. stdin.write('hello\n')
  595. stdin.seek(0)
  596. # call test code that consumes from sys.stdin
  597. captured = input()
  598. self.assertEqual(captured, "hello")
  599. """
  600. return captured_output("stdin")
  601. @contextmanager
  602. def freeze_time(t):
  603. """
  604. Context manager to temporarily freeze time.time(). This temporarily
  605. modifies the time function of the time module. Modules which import the
  606. time function directly (e.g. `from time import time`) won't be affected
  607. This isn't meant as a public API, but helps reduce some repetitive code in
  608. Django's test suite.
  609. """
  610. _real_time = time.time
  611. time.time = lambda: t
  612. try:
  613. yield
  614. finally:
  615. time.time = _real_time
  616. def require_jinja2(test_func):
  617. """
  618. Decorator to enable a Jinja2 template engine in addition to the regular
  619. Django template engine for a test or skip it if Jinja2 isn't available.
  620. """
  621. test_func = skipIf(jinja2 is None, "this test requires jinja2")(test_func)
  622. test_func = override_settings(TEMPLATES=[{
  623. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  624. 'APP_DIRS': True,
  625. }, {
  626. 'BACKEND': 'django.template.backends.jinja2.Jinja2',
  627. 'APP_DIRS': True,
  628. 'OPTIONS': {'keep_trailing_newline': True},
  629. }])(test_func)
  630. return 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