util.py 14 KB

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