util.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. # testing/util.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: ignore-errors
  8. from __future__ import annotations
  9. from collections import deque
  10. import decimal
  11. import gc
  12. from itertools import chain
  13. import random
  14. import sys
  15. from sys import getsizeof
  16. import types
  17. from . import config
  18. from . import mock
  19. from .. import inspect
  20. from ..engine import Connection
  21. from ..schema import Column
  22. from ..schema import DropConstraint
  23. from ..schema import DropTable
  24. from ..schema import ForeignKeyConstraint
  25. from ..schema import MetaData
  26. from ..schema import Table
  27. from ..sql import schema
  28. from ..sql.sqltypes import Integer
  29. from ..util import decorator
  30. from ..util import defaultdict
  31. from ..util import has_refcount_gc
  32. from ..util import inspect_getfullargspec
  33. if not has_refcount_gc:
  34. def non_refcount_gc_collect(*args):
  35. gc.collect()
  36. gc.collect()
  37. gc_collect = lazy_gc = non_refcount_gc_collect
  38. else:
  39. # assume CPython - straight gc.collect, lazy_gc() is a pass
  40. gc_collect = gc.collect
  41. def lazy_gc():
  42. pass
  43. def picklers():
  44. picklers = set()
  45. import pickle
  46. picklers.add(pickle)
  47. # yes, this thing needs this much testing
  48. for pickle_ in picklers:
  49. for protocol in range(-2, pickle.HIGHEST_PROTOCOL + 1):
  50. yield pickle_.loads, lambda d: pickle_.dumps(d, protocol)
  51. def random_choices(population, k=1):
  52. return random.choices(population, k=k)
  53. def round_decimal(value, prec):
  54. if isinstance(value, float):
  55. return round(value, prec)
  56. # can also use shift() here but that is 2.6 only
  57. return (value * decimal.Decimal("1" + "0" * prec)).to_integral(
  58. decimal.ROUND_FLOOR
  59. ) / pow(10, prec)
  60. class RandomSet(set):
  61. def __iter__(self):
  62. l = list(set.__iter__(self))
  63. random.shuffle(l)
  64. return iter(l)
  65. def pop(self):
  66. index = random.randint(0, len(self) - 1)
  67. item = list(set.__iter__(self))[index]
  68. self.remove(item)
  69. return item
  70. def union(self, other):
  71. return RandomSet(set.union(self, other))
  72. def difference(self, other):
  73. return RandomSet(set.difference(self, other))
  74. def intersection(self, other):
  75. return RandomSet(set.intersection(self, other))
  76. def copy(self):
  77. return RandomSet(self)
  78. def conforms_partial_ordering(tuples, sorted_elements):
  79. """True if the given sorting conforms to the given partial ordering."""
  80. deps = defaultdict(set)
  81. for parent, child in tuples:
  82. deps[parent].add(child)
  83. for i, node in enumerate(sorted_elements):
  84. for n in sorted_elements[i:]:
  85. if node in deps[n]:
  86. return False
  87. else:
  88. return True
  89. def all_partial_orderings(tuples, elements):
  90. edges = defaultdict(set)
  91. for parent, child in tuples:
  92. edges[child].add(parent)
  93. def _all_orderings(elements):
  94. if len(elements) == 1:
  95. yield list(elements)
  96. else:
  97. for elem in elements:
  98. subset = set(elements).difference([elem])
  99. if not subset.intersection(edges[elem]):
  100. for sub_ordering in _all_orderings(subset):
  101. yield [elem] + sub_ordering
  102. return iter(_all_orderings(elements))
  103. def function_named(fn, name):
  104. """Return a function with a given __name__.
  105. Will assign to __name__ and return the original function if possible on
  106. the Python implementation, otherwise a new function will be constructed.
  107. This function should be phased out as much as possible
  108. in favor of @decorator. Tests that "generate" many named tests
  109. should be modernized.
  110. """
  111. try:
  112. fn.__name__ = name
  113. except TypeError:
  114. fn = types.FunctionType(
  115. fn.__code__, fn.__globals__, name, fn.__defaults__, fn.__closure__
  116. )
  117. return fn
  118. def run_as_contextmanager(ctx, fn, *arg, **kw):
  119. """Run the given function under the given contextmanager,
  120. simulating the behavior of 'with' to support older
  121. Python versions.
  122. This is not necessary anymore as we have placed 2.6
  123. as minimum Python version, however some tests are still using
  124. this structure.
  125. """
  126. obj = ctx.__enter__()
  127. try:
  128. result = fn(obj, *arg, **kw)
  129. ctx.__exit__(None, None, None)
  130. return result
  131. except:
  132. exc_info = sys.exc_info()
  133. raise_ = ctx.__exit__(*exc_info)
  134. if not raise_:
  135. raise
  136. else:
  137. return raise_
  138. def rowset(results):
  139. """Converts the results of sql execution into a plain set of column tuples.
  140. Useful for asserting the results of an unordered query.
  141. """
  142. return {tuple(row) for row in results}
  143. def fail(msg):
  144. assert False, msg
  145. @decorator
  146. def provide_metadata(fn, *args, **kw):
  147. """Provide bound MetaData for a single test, dropping afterwards.
  148. Legacy; use the "metadata" pytest fixture.
  149. """
  150. from . import fixtures
  151. metadata = schema.MetaData()
  152. self = args[0]
  153. prev_meta = getattr(self, "metadata", None)
  154. self.metadata = metadata
  155. try:
  156. return fn(*args, **kw)
  157. finally:
  158. # close out some things that get in the way of dropping tables.
  159. # when using the "metadata" fixture, there is a set ordering
  160. # of things that makes sure things are cleaned up in order, however
  161. # the simple "decorator" nature of this legacy function means
  162. # we have to hardcode some of that cleanup ahead of time.
  163. # close ORM sessions
  164. fixtures.close_all_sessions()
  165. # integrate with the "connection" fixture as there are many
  166. # tests where it is used along with provide_metadata
  167. cfc = fixtures.base._connection_fixture_connection
  168. if cfc:
  169. # TODO: this warning can be used to find all the places
  170. # this is used with connection fixture
  171. # warn("mixing legacy provide metadata with connection fixture")
  172. drop_all_tables_from_metadata(metadata, cfc)
  173. # as the provide_metadata fixture is often used with "testing.db",
  174. # when we do the drop we have to commit the transaction so that
  175. # the DB is actually updated as the CREATE would have been
  176. # committed
  177. cfc.get_transaction().commit()
  178. else:
  179. drop_all_tables_from_metadata(metadata, config.db)
  180. self.metadata = prev_meta
  181. def flag_combinations(*combinations):
  182. """A facade around @testing.combinations() oriented towards boolean
  183. keyword-based arguments.
  184. Basically generates a nice looking identifier based on the keywords
  185. and also sets up the argument names.
  186. E.g.::
  187. @testing.flag_combinations(
  188. dict(lazy=False, passive=False),
  189. dict(lazy=True, passive=False),
  190. dict(lazy=False, passive=True),
  191. dict(lazy=False, passive=True, raiseload=True),
  192. )
  193. would result in::
  194. @testing.combinations(
  195. ('', False, False, False),
  196. ('lazy', True, False, False),
  197. ('lazy_passive', True, True, False),
  198. ('lazy_passive', True, True, True),
  199. id_='iaaa',
  200. argnames='lazy,passive,raiseload'
  201. )
  202. """
  203. keys = set()
  204. for d in combinations:
  205. keys.update(d)
  206. keys = sorted(keys)
  207. return config.combinations(
  208. *[
  209. ("_".join(k for k in keys if d.get(k, False)),)
  210. + tuple(d.get(k, False) for k in keys)
  211. for d in combinations
  212. ],
  213. id_="i" + ("a" * len(keys)),
  214. argnames=",".join(keys),
  215. )
  216. def lambda_combinations(lambda_arg_sets, **kw):
  217. args = inspect_getfullargspec(lambda_arg_sets)
  218. arg_sets = lambda_arg_sets(*[mock.Mock() for arg in args[0]])
  219. def create_fixture(pos):
  220. def fixture(**kw):
  221. return lambda_arg_sets(**kw)[pos]
  222. fixture.__name__ = "fixture_%3.3d" % pos
  223. return fixture
  224. return config.combinations(
  225. *[(create_fixture(i),) for i in range(len(arg_sets))], **kw
  226. )
  227. def resolve_lambda(__fn, **kw):
  228. """Given a no-arg lambda and a namespace, return a new lambda that
  229. has all the values filled in.
  230. This is used so that we can have module-level fixtures that
  231. refer to instance-level variables using lambdas.
  232. """
  233. pos_args = inspect_getfullargspec(__fn)[0]
  234. pass_pos_args = {arg: kw.pop(arg) for arg in pos_args}
  235. glb = dict(__fn.__globals__)
  236. glb.update(kw)
  237. new_fn = types.FunctionType(__fn.__code__, glb)
  238. return new_fn(**pass_pos_args)
  239. def metadata_fixture(ddl="function"):
  240. """Provide MetaData for a pytest fixture."""
  241. def decorate(fn):
  242. def run_ddl(self):
  243. metadata = self.metadata = schema.MetaData()
  244. try:
  245. result = fn(self, metadata)
  246. metadata.create_all(config.db)
  247. # TODO:
  248. # somehow get a per-function dml erase fixture here
  249. yield result
  250. finally:
  251. metadata.drop_all(config.db)
  252. return config.fixture(scope=ddl)(run_ddl)
  253. return decorate
  254. def force_drop_names(*names):
  255. """Force the given table names to be dropped after test complete,
  256. isolating for foreign key cycles
  257. """
  258. @decorator
  259. def go(fn, *args, **kw):
  260. try:
  261. return fn(*args, **kw)
  262. finally:
  263. drop_all_tables(config.db, inspect(config.db), include_names=names)
  264. return go
  265. class adict(dict):
  266. """Dict keys available as attributes. Shadows."""
  267. def __getattribute__(self, key):
  268. try:
  269. return self[key]
  270. except KeyError:
  271. return dict.__getattribute__(self, key)
  272. def __call__(self, *keys):
  273. return tuple([self[key] for key in keys])
  274. get_all = __call__
  275. def drop_all_tables_from_metadata(metadata, engine_or_connection):
  276. from . import engines
  277. def go(connection):
  278. engines.testing_reaper.prepare_for_drop_tables(connection)
  279. if not connection.dialect.supports_alter:
  280. from . import assertions
  281. with assertions.expect_warnings(
  282. "Can't sort tables", assert_=False
  283. ):
  284. metadata.drop_all(connection)
  285. else:
  286. metadata.drop_all(connection)
  287. if not isinstance(engine_or_connection, Connection):
  288. with engine_or_connection.begin() as connection:
  289. go(connection)
  290. else:
  291. go(engine_or_connection)
  292. def drop_all_tables(
  293. engine,
  294. inspector,
  295. schema=None,
  296. consider_schemas=(None,),
  297. include_names=None,
  298. ):
  299. if include_names is not None:
  300. include_names = set(include_names)
  301. if schema is not None:
  302. assert consider_schemas == (
  303. None,
  304. ), "consider_schemas and schema are mutually exclusive"
  305. consider_schemas = (schema,)
  306. with engine.begin() as conn:
  307. for table_key, fkcs in reversed(
  308. inspector.sort_tables_on_foreign_key_dependency(
  309. consider_schemas=consider_schemas
  310. )
  311. ):
  312. if table_key:
  313. if (
  314. include_names is not None
  315. and table_key[1] not in include_names
  316. ):
  317. continue
  318. conn.execute(
  319. DropTable(
  320. Table(table_key[1], MetaData(), schema=table_key[0])
  321. )
  322. )
  323. elif fkcs:
  324. if not engine.dialect.supports_alter:
  325. continue
  326. for t_key, fkc in fkcs:
  327. if (
  328. include_names is not None
  329. and t_key[1] not in include_names
  330. ):
  331. continue
  332. tb = Table(
  333. t_key[1],
  334. MetaData(),
  335. Column("x", Integer),
  336. Column("y", Integer),
  337. schema=t_key[0],
  338. )
  339. conn.execute(
  340. DropConstraint(
  341. ForeignKeyConstraint([tb.c.x], [tb.c.y], name=fkc)
  342. )
  343. )
  344. def teardown_events(event_cls):
  345. @decorator
  346. def decorate(fn, *arg, **kw):
  347. try:
  348. return fn(*arg, **kw)
  349. finally:
  350. event_cls._clear()
  351. return decorate
  352. def total_size(o):
  353. """Returns the approximate memory footprint an object and all of its
  354. contents.
  355. source: https://code.activestate.com/recipes/577504/
  356. """
  357. def dict_handler(d):
  358. return chain.from_iterable(d.items())
  359. all_handlers = {
  360. tuple: iter,
  361. list: iter,
  362. deque: iter,
  363. dict: dict_handler,
  364. set: iter,
  365. frozenset: iter,
  366. }
  367. seen = set() # track which object id's have already been seen
  368. default_size = getsizeof(0) # estimate sizeof object without __sizeof__
  369. def sizeof(o):
  370. if id(o) in seen: # do not double count the same object
  371. return 0
  372. seen.add(id(o))
  373. s = getsizeof(o, default_size)
  374. for typ, handler in all_handlers.items():
  375. if isinstance(o, typ):
  376. s += sum(map(sizeof, handler(o)))
  377. break
  378. return s
  379. return sizeof(o)
  380. def count_cache_key_tuples(tup):
  381. """given a cache key tuple, counts how many instances of actual
  382. tuples are found.
  383. used to alert large jumps in cache key complexity.
  384. """
  385. stack = [tup]
  386. sentinel = object()
  387. num_elements = 0
  388. while stack:
  389. elem = stack.pop(0)
  390. if elem is sentinel:
  391. num_elements += 1
  392. elif isinstance(elem, tuple):
  393. if elem:
  394. stack = list(elem) + [sentinel] + stack
  395. return num_elements