plugin_base.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. # testing/plugin/plugin_base.py
  2. # Copyright (C) 2005-2025 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 abc
  10. from argparse import Namespace
  11. import configparser
  12. import logging
  13. import os
  14. from pathlib import Path
  15. import re
  16. import sys
  17. from typing import Any
  18. from sqlalchemy.testing import asyncio
  19. """Testing extensions.
  20. this module is designed to work as a testing-framework-agnostic library,
  21. created so that multiple test frameworks can be supported at once
  22. (mostly so that we can migrate to new ones). The current target
  23. is pytest.
  24. """
  25. # flag which indicates we are in the SQLAlchemy testing suite,
  26. # and not that of Alembic or a third party dialect.
  27. bootstrapped_as_sqlalchemy = False
  28. log = logging.getLogger("sqlalchemy.testing.plugin_base")
  29. # late imports
  30. fixtures = None
  31. engines = None
  32. exclusions = None
  33. warnings = None
  34. profiling = None
  35. provision = None
  36. assertions = None
  37. requirements = None
  38. config = None
  39. testing = None
  40. util = None
  41. file_config = None
  42. logging = None
  43. include_tags = set()
  44. exclude_tags = set()
  45. options: Namespace = None # type: ignore
  46. def setup_options(make_option):
  47. make_option(
  48. "--log-info",
  49. action="callback",
  50. type=str,
  51. callback=_log,
  52. help="turn on info logging for <LOG> (multiple OK)",
  53. )
  54. make_option(
  55. "--log-debug",
  56. action="callback",
  57. type=str,
  58. callback=_log,
  59. help="turn on debug logging for <LOG> (multiple OK)",
  60. )
  61. make_option(
  62. "--db",
  63. action="append",
  64. type=str,
  65. dest="db",
  66. help="Use prefab database uri. Multiple OK, "
  67. "first one is run by default.",
  68. )
  69. make_option(
  70. "--dbs",
  71. action="callback",
  72. zeroarg_callback=_list_dbs,
  73. help="List available prefab dbs",
  74. )
  75. make_option(
  76. "--dburi",
  77. action="append",
  78. type=str,
  79. dest="dburi",
  80. help="Database uri. Multiple OK, first one is run by default.",
  81. )
  82. make_option(
  83. "--dbdriver",
  84. action="append",
  85. type=str,
  86. dest="dbdriver",
  87. help="Additional database drivers to include in tests. "
  88. "These are linked to the existing database URLs by the "
  89. "provisioning system.",
  90. )
  91. make_option(
  92. "--dropfirst",
  93. action="store_true",
  94. dest="dropfirst",
  95. help="Drop all tables in the target database first",
  96. )
  97. make_option(
  98. "--disable-asyncio",
  99. action="store_true",
  100. help="disable test / fixtures / provisoning running in asyncio",
  101. )
  102. make_option(
  103. "--backend-only",
  104. action="callback",
  105. zeroarg_callback=_set_tag_include("backend"),
  106. help=(
  107. "Run only tests marked with __backend__ or __sparse_backend__; "
  108. "this is now equivalent to the pytest -m backend mark expression"
  109. ),
  110. )
  111. make_option(
  112. "--nomemory",
  113. action="callback",
  114. zeroarg_callback=_set_tag_exclude("memory_intensive"),
  115. help="Don't run memory profiling tests; "
  116. "this is now equivalent to the pytest -m 'not memory_intensive' "
  117. "mark expression",
  118. )
  119. make_option(
  120. "--notimingintensive",
  121. action="callback",
  122. zeroarg_callback=_set_tag_exclude("timing_intensive"),
  123. help="Don't run timing intensive tests; "
  124. "this is now equivalent to the pytest -m 'not timing_intensive' "
  125. "mark expression",
  126. )
  127. make_option(
  128. "--nomypy",
  129. action="callback",
  130. zeroarg_callback=_set_tag_exclude("mypy"),
  131. help="Don't run mypy typing tests; "
  132. "this is now equivalent to the pytest -m 'not mypy' mark expression",
  133. )
  134. make_option(
  135. "--profile-sort",
  136. type=str,
  137. default="cumulative",
  138. dest="profilesort",
  139. help="Type of sort for profiling standard output",
  140. )
  141. make_option(
  142. "--profile-dump",
  143. type=str,
  144. dest="profiledump",
  145. help="Filename where a single profile run will be dumped",
  146. )
  147. make_option(
  148. "--low-connections",
  149. action="store_true",
  150. dest="low_connections",
  151. help="Use a low number of distinct connections - "
  152. "i.e. for Oracle TNS",
  153. )
  154. make_option(
  155. "--write-idents",
  156. type=str,
  157. dest="write_idents",
  158. help="write out generated follower idents to <file>, "
  159. "when -n<num> is used",
  160. )
  161. make_option(
  162. "--requirements",
  163. action="callback",
  164. type=str,
  165. callback=_requirements_opt,
  166. help="requirements class for testing, overrides setup.cfg",
  167. )
  168. make_option(
  169. "--include-tag",
  170. action="callback",
  171. callback=_include_tag,
  172. type=str,
  173. help="Include tests with tag <tag>; "
  174. "legacy, use pytest -m 'tag' instead",
  175. )
  176. make_option(
  177. "--exclude-tag",
  178. action="callback",
  179. callback=_exclude_tag,
  180. type=str,
  181. help="Exclude tests with tag <tag>; "
  182. "legacy, use pytest -m 'not tag' instead",
  183. )
  184. make_option(
  185. "--write-profiles",
  186. action="store_true",
  187. dest="write_profiles",
  188. default=False,
  189. help="Write/update failing profiling data.",
  190. )
  191. make_option(
  192. "--force-write-profiles",
  193. action="store_true",
  194. dest="force_write_profiles",
  195. default=False,
  196. help="Unconditionally write/update profiling data.",
  197. )
  198. make_option(
  199. "--dump-pyannotate",
  200. type=str,
  201. dest="dump_pyannotate",
  202. help="Run pyannotate and dump json info to given file",
  203. )
  204. make_option(
  205. "--mypy-extra-test-path",
  206. type=str,
  207. action="append",
  208. default=[],
  209. dest="mypy_extra_test_paths",
  210. help="Additional test directories to add to the mypy tests. "
  211. "This is used only when running mypy tests. Multiple OK",
  212. )
  213. # db specific options
  214. make_option(
  215. "--postgresql-templatedb",
  216. type=str,
  217. help="name of template database to use for PostgreSQL "
  218. "CREATE DATABASE (defaults to current database)",
  219. )
  220. make_option(
  221. "--oracledb-thick-mode",
  222. action="store_true",
  223. help="enables the 'thick mode' when testing with oracle+oracledb",
  224. )
  225. def configure_follower(follower_ident):
  226. """Configure required state for a follower.
  227. This invokes in the parent process and typically includes
  228. database creation.
  229. """
  230. from sqlalchemy.testing import provision
  231. provision.FOLLOWER_IDENT = follower_ident
  232. def memoize_important_follower_config(dict_):
  233. """Store important configuration we will need to send to a follower.
  234. This invokes in the parent process after normal config is set up.
  235. Hook is currently not used.
  236. """
  237. def restore_important_follower_config(dict_):
  238. """Restore important configuration needed by a follower.
  239. This invokes in the follower process.
  240. Hook is currently not used.
  241. """
  242. def read_config(root_path):
  243. global file_config
  244. file_config = configparser.ConfigParser()
  245. file_config.read(
  246. [str(root_path / "setup.cfg"), str(root_path / "test.cfg")]
  247. )
  248. def pre_begin(opt):
  249. """things to set up early, before coverage might be setup."""
  250. global options
  251. options = opt
  252. for fn in pre_configure:
  253. fn(options, file_config)
  254. def set_coverage_flag(value):
  255. options.has_coverage = value
  256. def post_begin():
  257. """things to set up later, once we know coverage is running."""
  258. # Lazy setup of other options (post coverage)
  259. for fn in post_configure:
  260. fn(options, file_config)
  261. # late imports, has to happen after config.
  262. global util, fixtures, engines, exclusions, assertions, provision
  263. global warnings, profiling, config, testing
  264. from sqlalchemy import testing # noqa
  265. from sqlalchemy.testing import fixtures, engines, exclusions # noqa
  266. from sqlalchemy.testing import assertions, warnings, profiling # noqa
  267. from sqlalchemy.testing import config, provision # noqa
  268. from sqlalchemy import util # noqa
  269. warnings.setup_filters()
  270. def _log(opt_str, value, parser):
  271. global logging
  272. if not logging:
  273. import logging
  274. logging.basicConfig()
  275. if opt_str.endswith("-info"):
  276. logging.getLogger(value).setLevel(logging.INFO)
  277. elif opt_str.endswith("-debug"):
  278. logging.getLogger(value).setLevel(logging.DEBUG)
  279. def _list_dbs(*args):
  280. if file_config is None:
  281. # assume the current working directory is the one containing the
  282. # setup file
  283. read_config(Path.cwd())
  284. print("Available --db options (use --dburi to override)")
  285. for macro in sorted(file_config.options("db")):
  286. print("%20s\t%s" % (macro, file_config.get("db", macro)))
  287. sys.exit(0)
  288. def _requirements_opt(opt_str, value, parser):
  289. _setup_requirements(value)
  290. def _set_tag_include(tag):
  291. def _do_include_tag(opt_str, value, parser):
  292. _include_tag(opt_str, tag, parser)
  293. return _do_include_tag
  294. def _set_tag_exclude(tag):
  295. def _do_exclude_tag(opt_str, value, parser):
  296. _exclude_tag(opt_str, tag, parser)
  297. return _do_exclude_tag
  298. def _exclude_tag(opt_str, value, parser):
  299. exclude_tags.add(value.replace("-", "_"))
  300. def _include_tag(opt_str, value, parser):
  301. include_tags.add(value.replace("-", "_"))
  302. pre_configure = []
  303. post_configure = []
  304. def pre(fn):
  305. pre_configure.append(fn)
  306. return fn
  307. def post(fn):
  308. post_configure.append(fn)
  309. return fn
  310. @pre
  311. def _setup_options(opt, file_config):
  312. global options
  313. options = opt
  314. @pre
  315. def _register_sqlite_numeric_dialect(opt, file_config):
  316. from sqlalchemy.dialects import registry
  317. registry.register(
  318. "sqlite.pysqlite_numeric",
  319. "sqlalchemy.dialects.sqlite.pysqlite",
  320. "_SQLiteDialect_pysqlite_numeric",
  321. )
  322. registry.register(
  323. "sqlite.pysqlite_dollar",
  324. "sqlalchemy.dialects.sqlite.pysqlite",
  325. "_SQLiteDialect_pysqlite_dollar",
  326. )
  327. @post
  328. def __ensure_cext(opt, file_config):
  329. if os.environ.get("REQUIRE_SQLALCHEMY_CEXT", "0") == "1":
  330. from sqlalchemy.util import has_compiled_ext
  331. try:
  332. has_compiled_ext(raise_=True)
  333. except ImportError as err:
  334. raise AssertionError(
  335. "REQUIRE_SQLALCHEMY_CEXT is set but can't import the "
  336. "cython extensions"
  337. ) from err
  338. @post
  339. def _init_symbols(options, file_config):
  340. from sqlalchemy.testing import config
  341. config._fixture_functions = _fixture_fn_class()
  342. @pre
  343. def _set_disable_asyncio(opt, file_config):
  344. if opt.disable_asyncio:
  345. asyncio.ENABLE_ASYNCIO = False
  346. @post
  347. def _engine_uri(options, file_config):
  348. from sqlalchemy import testing
  349. from sqlalchemy.testing import config
  350. from sqlalchemy.testing import provision
  351. from sqlalchemy.engine import url as sa_url
  352. if options.dburi:
  353. db_urls = list(options.dburi)
  354. else:
  355. db_urls = []
  356. extra_drivers = options.dbdriver or []
  357. if options.db:
  358. for db_token in options.db:
  359. for db in re.split(r"[,\s]+", db_token):
  360. if db not in file_config.options("db"):
  361. raise RuntimeError(
  362. "Unknown URI specifier '%s'. "
  363. "Specify --dbs for known uris." % db
  364. )
  365. else:
  366. db_urls.append(file_config.get("db", db))
  367. if not db_urls:
  368. db_urls.append(file_config.get("db", "default"))
  369. config._current = None
  370. if options.write_idents and provision.FOLLOWER_IDENT:
  371. for db_url in [sa_url.make_url(db_url) for db_url in db_urls]:
  372. with open(options.write_idents, "a") as file_:
  373. file_.write(
  374. f"{provision.FOLLOWER_IDENT} "
  375. f"{db_url.render_as_string(hide_password=False)}\n"
  376. )
  377. expanded_urls = list(provision.generate_db_urls(db_urls, extra_drivers))
  378. for db_url in expanded_urls:
  379. log.info("Adding database URL: %s", db_url)
  380. cfg = provision.setup_config(
  381. db_url, options, file_config, provision.FOLLOWER_IDENT
  382. )
  383. if not config._current:
  384. cfg.set_as_current(cfg, testing)
  385. @post
  386. def _requirements(options, file_config):
  387. requirement_cls = file_config.get("sqla_testing", "requirement_cls")
  388. _setup_requirements(requirement_cls)
  389. def _setup_requirements(argument):
  390. from sqlalchemy.testing import config
  391. from sqlalchemy import testing
  392. modname, clsname = argument.split(":")
  393. # importlib.import_module() only introduced in 2.7, a little
  394. # late
  395. mod = __import__(modname)
  396. for component in modname.split(".")[1:]:
  397. mod = getattr(mod, component)
  398. req_cls = getattr(mod, clsname)
  399. config.requirements = testing.requires = req_cls()
  400. config.bootstrapped_as_sqlalchemy = bootstrapped_as_sqlalchemy
  401. @post
  402. def _prep_testing_database(options, file_config):
  403. from sqlalchemy.testing import config
  404. if options.dropfirst:
  405. from sqlalchemy.testing import provision
  406. for cfg in config.Config.all_configs():
  407. provision.drop_all_schema_objects(cfg, cfg.db)
  408. @post
  409. def _post_setup_options(opt, file_config):
  410. from sqlalchemy.testing import config
  411. config.options = options
  412. config.file_config = file_config
  413. @post
  414. def _setup_profiling(options, file_config):
  415. from sqlalchemy.testing import profiling
  416. profiling._profile_stats = profiling.ProfileStatsFile(
  417. file_config.get("sqla_testing", "profile_file"),
  418. sort=options.profilesort,
  419. dump=options.profiledump,
  420. )
  421. def want_class(name, cls):
  422. if not issubclass(cls, fixtures.TestBase):
  423. return False
  424. elif name.startswith("_"):
  425. return False
  426. else:
  427. return True
  428. def want_method(cls, fn):
  429. if not fn.__name__.startswith("test_"):
  430. return False
  431. elif fn.__module__ is None:
  432. return False
  433. else:
  434. return True
  435. def generate_sub_tests(cls, module, markers):
  436. if "backend" in markers or "sparse_backend" in markers:
  437. sparse = "sparse_backend" in markers
  438. for cfg in _possible_configs_for_cls(cls, sparse=sparse):
  439. orig_name = cls.__name__
  440. # we can have special chars in these names except for the
  441. # pytest junit plugin, which is tripped up by the brackets
  442. # and periods, so sanitize
  443. alpha_name = re.sub(r"[_\[\]\.]+", "_", cfg.name)
  444. alpha_name = re.sub(r"_+$", "", alpha_name)
  445. name = "%s_%s" % (cls.__name__, alpha_name)
  446. subcls = type(
  447. name,
  448. (cls,),
  449. {"_sa_orig_cls_name": orig_name, "__only_on_config__": cfg},
  450. )
  451. setattr(module, name, subcls)
  452. yield subcls
  453. else:
  454. yield cls
  455. def start_test_class_outside_fixtures(cls):
  456. _do_skips(cls)
  457. _setup_engine(cls)
  458. def stop_test_class(cls):
  459. # close sessions, immediate connections, etc.
  460. fixtures.stop_test_class_inside_fixtures(cls)
  461. # close outstanding connection pool connections, dispose of
  462. # additional engines
  463. engines.testing_reaper.stop_test_class_inside_fixtures()
  464. def stop_test_class_outside_fixtures(cls):
  465. engines.testing_reaper.stop_test_class_outside_fixtures()
  466. provision.stop_test_class_outside_fixtures(config, config.db, cls)
  467. try:
  468. if not options.low_connections:
  469. assertions.global_cleanup_assertions()
  470. finally:
  471. _restore_engine()
  472. def _restore_engine():
  473. if config._current:
  474. config._current.reset(testing)
  475. def final_process_cleanup():
  476. engines.testing_reaper.final_cleanup()
  477. assertions.global_cleanup_assertions()
  478. _restore_engine()
  479. def _setup_engine(cls):
  480. if getattr(cls, "__engine_options__", None):
  481. opts = dict(cls.__engine_options__)
  482. opts["scope"] = "class"
  483. eng = engines.testing_engine(options=opts)
  484. config._current.push_engine(eng, testing)
  485. def before_test(test, test_module_name, test_class, test_name):
  486. # format looks like:
  487. # "test.aaa_profiling.test_compiler.CompileTest.test_update_whereclause"
  488. name = getattr(test_class, "_sa_orig_cls_name", test_class.__name__)
  489. id_ = "%s.%s.%s" % (test_module_name, name, test_name)
  490. profiling._start_current_test(id_)
  491. def after_test(test):
  492. fixtures.after_test()
  493. engines.testing_reaper.after_test()
  494. def after_test_fixtures(test):
  495. engines.testing_reaper.after_test_outside_fixtures(test)
  496. def _possible_configs_for_cls(cls, reasons=None, sparse=False):
  497. all_configs = set(config.Config.all_configs())
  498. if cls.__unsupported_on__:
  499. spec = exclusions.db_spec(*cls.__unsupported_on__)
  500. for config_obj in list(all_configs):
  501. if spec(config_obj):
  502. all_configs.remove(config_obj)
  503. if getattr(cls, "__only_on__", None):
  504. spec = exclusions.db_spec(*util.to_list(cls.__only_on__))
  505. for config_obj in list(all_configs):
  506. if not spec(config_obj):
  507. all_configs.remove(config_obj)
  508. if getattr(cls, "__only_on_config__", None):
  509. all_configs.intersection_update([cls.__only_on_config__])
  510. if hasattr(cls, "__requires__"):
  511. requirements = config.requirements
  512. for config_obj in list(all_configs):
  513. for requirement in cls.__requires__:
  514. check = getattr(requirements, requirement)
  515. skip_reasons = check.matching_config_reasons(config_obj)
  516. if skip_reasons:
  517. all_configs.remove(config_obj)
  518. if reasons is not None:
  519. reasons.extend(skip_reasons)
  520. break
  521. if hasattr(cls, "__prefer_requires__"):
  522. non_preferred = set()
  523. requirements = config.requirements
  524. for config_obj in list(all_configs):
  525. for requirement in cls.__prefer_requires__:
  526. check = getattr(requirements, requirement)
  527. if not check.enabled_for_config(config_obj):
  528. non_preferred.add(config_obj)
  529. if all_configs.difference(non_preferred):
  530. all_configs.difference_update(non_preferred)
  531. if sparse:
  532. # pick only one config from each base dialect
  533. # sorted so we get the same backend each time selecting the highest
  534. # server version info.
  535. per_dialect = {}
  536. for cfg in reversed(
  537. sorted(
  538. all_configs,
  539. key=lambda cfg: (
  540. cfg.db.name,
  541. cfg.db.driver,
  542. cfg.db.dialect.server_version_info,
  543. ),
  544. )
  545. ):
  546. db = cfg.db.name
  547. if db not in per_dialect:
  548. per_dialect[db] = cfg
  549. return per_dialect.values()
  550. return all_configs
  551. def _do_skips(cls):
  552. reasons = []
  553. all_configs = _possible_configs_for_cls(cls, reasons)
  554. if getattr(cls, "__skip_if__", False):
  555. for c in getattr(cls, "__skip_if__"):
  556. if c():
  557. config.skip_test(
  558. "'%s' skipped by %s" % (cls.__name__, c.__name__)
  559. )
  560. if not all_configs:
  561. msg = "'%s.%s' unsupported on any DB implementation %s%s" % (
  562. cls.__module__,
  563. cls.__name__,
  564. ", ".join(
  565. "'%s(%s)+%s'"
  566. % (
  567. config_obj.db.name,
  568. ".".join(
  569. str(dig)
  570. for dig in exclusions._server_version(config_obj.db)
  571. ),
  572. config_obj.db.driver,
  573. )
  574. for config_obj in config.Config.all_configs()
  575. ),
  576. ", ".join(reasons),
  577. )
  578. config.skip_test(msg)
  579. elif hasattr(cls, "__prefer_backends__"):
  580. non_preferred = set()
  581. spec = exclusions.db_spec(*util.to_list(cls.__prefer_backends__))
  582. for config_obj in all_configs:
  583. if not spec(config_obj):
  584. non_preferred.add(config_obj)
  585. if all_configs.difference(non_preferred):
  586. all_configs.difference_update(non_preferred)
  587. if config._current not in all_configs:
  588. _setup_config(all_configs.pop(), cls)
  589. def _setup_config(config_obj, ctx):
  590. config._current.push(config_obj, testing)
  591. class FixtureFunctions(abc.ABC):
  592. @abc.abstractmethod
  593. def skip_test_exception(self, *arg, **kw):
  594. raise NotImplementedError()
  595. @abc.abstractmethod
  596. def combinations(self, *args, **kw):
  597. raise NotImplementedError()
  598. @abc.abstractmethod
  599. def param_ident(self, *args, **kw):
  600. raise NotImplementedError()
  601. @abc.abstractmethod
  602. def fixture(self, *arg, **kw):
  603. raise NotImplementedError()
  604. def get_current_test_name(self):
  605. raise NotImplementedError()
  606. @abc.abstractmethod
  607. def mark_base_test_class(self) -> Any:
  608. raise NotImplementedError()
  609. @abc.abstractproperty
  610. def add_to_marker(self):
  611. raise NotImplementedError()
  612. _fixture_fn_class = None
  613. def set_fixture_functions(fixture_fn_class):
  614. global _fixture_fn_class
  615. _fixture_fn_class = fixture_fn_class