engines.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. # testing/engines.py
  2. # Copyright (C) 2005-2026 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. import collections
  10. import re
  11. import typing
  12. from typing import Any
  13. from typing import Dict
  14. from typing import Optional
  15. from typing import Union
  16. import warnings
  17. import weakref
  18. from . import config
  19. from .util import decorator
  20. from .util import gc_collect
  21. from .. import event
  22. from .. import pool
  23. from ..util import await_only
  24. from ..util.typing import Literal
  25. if typing.TYPE_CHECKING:
  26. from ..engine import Engine
  27. from ..engine.url import URL
  28. from ..ext.asyncio import AsyncEngine
  29. class ConnectionKiller:
  30. def __init__(self):
  31. self.proxy_refs = weakref.WeakKeyDictionary()
  32. self.testing_engines = collections.defaultdict(set)
  33. self.dbapi_connections = set()
  34. def add_pool(self, pool):
  35. event.listen(pool, "checkout", self._add_conn)
  36. event.listen(pool, "checkin", self._remove_conn)
  37. event.listen(pool, "close", self._remove_conn)
  38. event.listen(pool, "close_detached", self._remove_conn)
  39. # note we are keeping "invalidated" here, as those are still
  40. # opened connections we would like to roll back
  41. def _add_conn(self, dbapi_con, con_record, con_proxy):
  42. self.dbapi_connections.add(dbapi_con)
  43. self.proxy_refs[con_proxy] = True
  44. def _remove_conn(self, dbapi_conn, *arg):
  45. self.dbapi_connections.discard(dbapi_conn)
  46. def add_engine(self, engine, scope):
  47. self.add_pool(engine.pool)
  48. assert scope in ("class", "global", "function", "fixture")
  49. self.testing_engines[scope].add(engine)
  50. def _safe(self, fn):
  51. try:
  52. fn()
  53. except Exception as e:
  54. warnings.warn(
  55. "testing_reaper couldn't rollback/close connection: %s" % e
  56. )
  57. def rollback_all(self):
  58. for rec in list(self.proxy_refs):
  59. if rec is not None and rec.is_valid:
  60. self._safe(rec.rollback)
  61. def checkin_all(self):
  62. # run pool.checkin() for all ConnectionFairy instances we have
  63. # tracked.
  64. for rec in list(self.proxy_refs):
  65. if rec is not None and rec.is_valid:
  66. self.dbapi_connections.discard(rec.dbapi_connection)
  67. self._safe(rec._checkin)
  68. # for fairy refs that were GCed and could not close the connection,
  69. # such as asyncio, roll back those remaining connections
  70. for con in self.dbapi_connections:
  71. self._safe(con.rollback)
  72. self.dbapi_connections.clear()
  73. def close_all(self):
  74. self.checkin_all()
  75. def prepare_for_drop_tables(self, connection):
  76. # don't do aggressive checks for third party test suites
  77. if not config.bootstrapped_as_sqlalchemy:
  78. return
  79. from . import provision
  80. provision.prepare_for_drop_tables(connection.engine.url, connection)
  81. def _drop_testing_engines(self, scope):
  82. eng = self.testing_engines[scope]
  83. for rec in list(eng):
  84. for proxy_ref in list(self.proxy_refs):
  85. if proxy_ref is not None and proxy_ref.is_valid:
  86. if (
  87. proxy_ref._pool is not None
  88. and proxy_ref._pool is rec.pool
  89. ):
  90. self._safe(proxy_ref._checkin)
  91. if hasattr(rec, "sync_engine"):
  92. await_only(rec.dispose())
  93. else:
  94. rec.dispose()
  95. eng.clear()
  96. def _dispose_testing_engines(self, scope):
  97. eng = self.testing_engines[scope]
  98. for rec in list(eng):
  99. if hasattr(rec, "sync_engine"):
  100. await_only(rec.dispose())
  101. else:
  102. rec.dispose()
  103. def after_test(self):
  104. self._drop_testing_engines("function")
  105. def after_test_outside_fixtures(self, test):
  106. # don't do aggressive checks for third party test suites
  107. if not config.bootstrapped_as_sqlalchemy:
  108. return
  109. if test.__class__.__leave_connections_for_teardown__:
  110. return
  111. self.checkin_all()
  112. # on PostgreSQL, this will test for any "idle in transaction"
  113. # connections. useful to identify tests with unusual patterns
  114. # that can't be cleaned up correctly.
  115. from . import provision
  116. with config.db.connect() as conn:
  117. provision.prepare_for_drop_tables(conn.engine.url, conn)
  118. def stop_test_class_inside_fixtures(self):
  119. self.checkin_all()
  120. self._drop_testing_engines("function")
  121. self._drop_testing_engines("class")
  122. def stop_test_class_outside_fixtures(self):
  123. # ensure no refs to checked out connections at all.
  124. if pool.base._strong_ref_connection_records:
  125. gc_collect()
  126. if pool.base._strong_ref_connection_records:
  127. ln = len(pool.base._strong_ref_connection_records)
  128. pool.base._strong_ref_connection_records.clear()
  129. if ln > 2:
  130. # allow two connections to linger, as on loaded down
  131. # CI hardware there seem to be occasional GC lapses that
  132. # are not easily preventable
  133. assert (
  134. False
  135. ), "%d connection recs not cleared after test suite" % (ln)
  136. if config.options and config.options.low_connections:
  137. # for suites running with --low-connections, dispose the "global"
  138. # engines to disconnect everything before making a testing engine
  139. self._dispose_testing_engines("global")
  140. def final_cleanup(self):
  141. self.checkin_all()
  142. for scope in self.testing_engines:
  143. self._drop_testing_engines(scope)
  144. def assert_all_closed(self):
  145. for rec in self.proxy_refs:
  146. if rec.is_valid:
  147. assert False
  148. testing_reaper = ConnectionKiller()
  149. @decorator
  150. def assert_conns_closed(fn, *args, **kw):
  151. try:
  152. fn(*args, **kw)
  153. finally:
  154. testing_reaper.assert_all_closed()
  155. @decorator
  156. def rollback_open_connections(fn, *args, **kw):
  157. """Decorator that rolls back all open connections after fn execution."""
  158. try:
  159. fn(*args, **kw)
  160. finally:
  161. testing_reaper.rollback_all()
  162. @decorator
  163. def close_first(fn, *args, **kw):
  164. """Decorator that closes all connections before fn execution."""
  165. testing_reaper.checkin_all()
  166. fn(*args, **kw)
  167. @decorator
  168. def close_open_connections(fn, *args, **kw):
  169. """Decorator that closes all connections after fn execution."""
  170. try:
  171. fn(*args, **kw)
  172. finally:
  173. testing_reaper.checkin_all()
  174. def all_dialects(exclude=None):
  175. import sqlalchemy.dialects as d
  176. for name in d.__all__:
  177. # TEMPORARY
  178. if exclude and name in exclude:
  179. continue
  180. mod = getattr(d, name, None)
  181. if not mod:
  182. mod = getattr(
  183. __import__("sqlalchemy.dialects.%s" % name).dialects, name
  184. )
  185. yield mod.dialect()
  186. class ReconnectFixture:
  187. def __init__(self, dbapi):
  188. self.dbapi = dbapi
  189. self.connections = []
  190. self.is_stopped = False
  191. def __getattr__(self, key):
  192. return getattr(self.dbapi, key)
  193. def connect(self, *args, **kwargs):
  194. conn = self.dbapi.connect(*args, **kwargs)
  195. if self.is_stopped:
  196. self._safe(conn.close)
  197. curs = conn.cursor() # should fail on Oracle etc.
  198. # should fail for everything that didn't fail
  199. # above, connection is closed
  200. curs.execute("select 1")
  201. assert False, "simulated connect failure didn't work"
  202. else:
  203. self.connections.append(conn)
  204. return conn
  205. def _safe(self, fn):
  206. try:
  207. fn()
  208. except Exception as e:
  209. warnings.warn("ReconnectFixture couldn't close connection: %s" % e)
  210. def shutdown(self, stop=False):
  211. # TODO: this doesn't cover all cases
  212. # as nicely as we'd like, namely MySQLdb.
  213. # would need to implement R. Brewer's
  214. # proxy server idea to get better
  215. # coverage.
  216. self.is_stopped = stop
  217. for c in list(self.connections):
  218. self._safe(c.close)
  219. self.connections = []
  220. def restart(self):
  221. self.is_stopped = False
  222. def reconnecting_engine(url=None, options=None):
  223. url = url or config.db.url
  224. dbapi = config.db.dialect.dbapi
  225. if not options:
  226. options = {}
  227. options["module"] = ReconnectFixture(dbapi)
  228. engine = testing_engine(url, options)
  229. _dispose = engine.dispose
  230. def dispose():
  231. engine.dialect.dbapi.shutdown()
  232. engine.dialect.dbapi.is_stopped = False
  233. _dispose()
  234. engine.test_shutdown = engine.dialect.dbapi.shutdown
  235. engine.test_restart = engine.dialect.dbapi.restart
  236. engine.dispose = dispose
  237. return engine
  238. @typing.overload
  239. def testing_engine(
  240. url: Optional[URL] = ...,
  241. options: Optional[Dict[str, Any]] = ...,
  242. *,
  243. asyncio: Literal[False],
  244. ) -> Engine: ...
  245. @typing.overload
  246. def testing_engine(
  247. url: Optional[URL] = ...,
  248. options: Optional[Dict[str, Any]] = ...,
  249. *,
  250. asyncio: Literal[True],
  251. ) -> AsyncEngine: ...
  252. def testing_engine(
  253. url: Optional[URL] = None,
  254. options: Optional[Dict[str, Any]] = None,
  255. *,
  256. asyncio: bool = False,
  257. ) -> Union[Engine, AsyncEngine]:
  258. if asyncio:
  259. from sqlalchemy.ext.asyncio import (
  260. create_async_engine as create_engine,
  261. )
  262. else:
  263. from sqlalchemy import create_engine
  264. from sqlalchemy.engine.url import make_url
  265. url = make_url(url if url else config.db.url)
  266. if not options:
  267. options = {}
  268. use_options = {}
  269. for opt_dict in (config.db_opts, options):
  270. if not opt_dict:
  271. continue
  272. use_options.update(
  273. {
  274. opt: value
  275. for opt, value in opt_dict.items()
  276. if opt not in ("scope", "use_reaper")
  277. and not opt.startswith("sqlite_")
  278. }
  279. )
  280. engine = create_engine(url, **use_options)
  281. if config.options and config.options.low_connections:
  282. # for suites running with --low-connections, dispose the "global"
  283. # engines to disconnect everything before making a testing engine
  284. testing_reaper._dispose_testing_engines("global")
  285. scope = options.get("scope", "function")
  286. if scope == "global":
  287. if asyncio:
  288. engine.sync_engine._has_events = True
  289. else:
  290. engine._has_events = (
  291. True # enable event blocks, helps with profiling
  292. )
  293. from . import provision
  294. provision.post_configure_testing_engine(engine.url, engine, options, scope)
  295. # post_configure_testing_engine may have modified the options dictionary
  296. # in place; consume additional post arguments afterwards
  297. use_reaper = options.get("use_reaper", True)
  298. if use_reaper:
  299. testing_reaper.add_engine(engine, scope)
  300. if (
  301. isinstance(engine.pool, pool.QueuePool)
  302. and "pool" not in options
  303. and "pool_timeout" not in options
  304. and "max_overflow" not in options
  305. ):
  306. engine.pool._timeout = 0
  307. engine.pool._max_overflow = 0
  308. return engine
  309. def mock_engine(dialect_name=None):
  310. """Provides a mocking engine based on the current testing.db.
  311. This is normally used to test DDL generation flow as emitted
  312. by an Engine.
  313. It should not be used in other cases, as assert_compile() and
  314. assert_sql_execution() are much better choices with fewer
  315. moving parts.
  316. """
  317. from sqlalchemy import create_mock_engine
  318. if not dialect_name:
  319. dialect_name = config.db.name
  320. buffer = []
  321. def executor(sql, *a, **kw):
  322. buffer.append(sql)
  323. def assert_sql(stmts):
  324. recv = [re.sub(r"[\n\t]", "", str(s)) for s in buffer]
  325. assert recv == stmts, recv
  326. def print_sql():
  327. d = engine.dialect
  328. return "\n".join(str(s.compile(dialect=d)) for s in engine.mock)
  329. engine = create_mock_engine(dialect_name + "://", executor)
  330. assert not hasattr(engine, "mock")
  331. engine.mock = buffer
  332. engine.assert_sql = assert_sql
  333. engine.print_sql = print_sql
  334. return engine
  335. class DBAPIProxyCursor:
  336. """Proxy a DBAPI cursor.
  337. Tests can provide subclasses of this to intercept
  338. DBAPI-level cursor operations.
  339. """
  340. def __init__(self, engine, conn, *args, **kwargs):
  341. self.engine = engine
  342. self.connection = conn
  343. self.cursor = conn.cursor(*args, **kwargs)
  344. def execute(self, stmt, parameters=None, **kw):
  345. if parameters:
  346. return self.cursor.execute(stmt, parameters, **kw)
  347. else:
  348. return self.cursor.execute(stmt, **kw)
  349. def executemany(self, stmt, params, **kw):
  350. return self.cursor.executemany(stmt, params, **kw)
  351. def __iter__(self):
  352. return iter(self.cursor)
  353. def __getattr__(self, key):
  354. return getattr(self.cursor, key)
  355. class DBAPIProxyConnection:
  356. """Proxy a DBAPI connection.
  357. Tests can provide subclasses of this to intercept
  358. DBAPI-level connection operations.
  359. """
  360. def __init__(self, engine, conn, cursor_cls):
  361. self.conn = conn
  362. self.engine = engine
  363. self.cursor_cls = cursor_cls
  364. def cursor(self, *args, **kwargs):
  365. return self.cursor_cls(self.engine, self.conn, *args, **kwargs)
  366. def close(self):
  367. self.conn.close()
  368. def __getattr__(self, key):
  369. return getattr(self.conn, key)