utils.py 31 KB

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