1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
|
"""Nox configuration for SQLAlchemy."""
from __future__ import annotations
import os
from pathlib import Path
import sys
from typing import Dict
from typing import List
from typing import Set
import nox
if sys.version_info > (3, 12):
nox.needs_version = ">=2025.10.16"
nox.options.default_venv_backend = "venv"
if True:
sys.path.insert(0, ".")
from tools.toxnox import apply_pytest_opts
from tools.toxnox import tox_parameters
PYTHON_VERSIONS = [
"3.7",
"3.8",
"3.9",
"3.10",
"3.11",
"3.12",
"3.13",
"3.13t",
"3.14",
"3.14t",
]
DATABASES = ["sqlite", "sqlite_file", "postgresql", "mysql", "oracle", "mssql"]
CEXT = ["_auto", "cext", "nocext"]
GREENLET = ["_greenlet", "nogreenlet"]
BACKENDONLY = ["_all", "backendonly", "memusage"]
# table of ``--dbdriver`` names to use on the pytest command line, which
# match to dialect names
DB_CLI_NAMES = {
"sqlite": {
"nogreenlet": {"sqlite", "pysqlite_numeric"},
"greenlet": {"aiosqlite"},
},
"sqlite_file": {
"nogreenlet": {"sqlite"},
"greenlet": {"aiosqlite"},
},
"postgresql": {
"nogreenlet": {"psycopg2", "pg8000", "psycopg"},
"greenlet": {"asyncpg", "psycopg_async"},
},
"mysql": {
"nogreenlet": {"mysqldb", "pymysql", "mariadbconnector"},
"greenlet": {"asyncmy", "aiomysql"},
},
"oracle": {
"nogreenlet": {"cx_oracle", "oracledb"},
"greenlet": {"oracledb_async"},
},
"mssql": {"nogreenlet": {"pyodbc", "pymssql"}, "greenlet": {"aioodbc"}},
}
def _setup_for_driver(
session: nox.Session,
cmd: List[str],
basename: str,
greenlet: bool = False,
) -> None:
# install driver deps listed out in pyproject.toml
nogreenlet_deps = f"tests-{basename.replace('_', '-')}"
greenlet_deps = f"tests-{basename.replace('_', '-')}-asyncio"
deps = nox.project.dependency_groups(
pyproject,
(greenlet_deps if greenlet else nogreenlet_deps),
)
if deps:
session.install(*deps)
# set up top level ``--db`` sent to pytest command line, which looks
# up a base URL in the [db] section of setup.cfg. Environment variable
# substitution used by CI is also available.
# e.g. TOX_POSTGRESQL, TOX_MYSQL, etc.
dburl_env = f"TOX_{basename.upper()}"
# e.g. --db=postgresql, --db=mysql, etc.
default_dburl = f"--db={basename}"
cmd.extend(os.environ.get(dburl_env, default_dburl).split())
# set up extra drivers using --dbdriver. this first looks in
# an environment variable before making use of the DB_CLI_NAMES
# lookup table
# e.g. EXTRA_PG_DRIVERS, EXTRA_MYSQL_DRIVERS, etc.
if basename == "postgresql":
extra_driver_env = "EXTRA_PG_DRIVERS"
else:
extra_driver_env = f"EXTRA_{basename.upper()}_DRIVERS"
env_dbdrivers = os.environ.get(extra_driver_env, None)
if env_dbdrivers:
cmd.extend(env_dbdrivers.split())
return
# use fixed names in DB_CLI_NAMES
extra_drivers: Dict[str, Set[str]] = DB_CLI_NAMES[basename]
dbdrivers = extra_drivers["nogreenlet"]
if greenlet:
dbdrivers.update(extra_drivers["greenlet"])
# use equals sign so that we avoid
# https://github.com/pytest-dev/pytest/issues/13913
cmd.extend([f"--dbdriver={dbdriver}" for dbdriver in dbdrivers])
pyproject = nox.project.load_toml("pyproject.toml")
nox.options.sessions = ["tests"]
nox.options.tags = ["py"]
@nox.session()
@tox_parameters(
["python", "database", "cext", "greenlet", "backendonly"],
[
PYTHON_VERSIONS,
DATABASES,
CEXT,
GREENLET,
BACKENDONLY,
],
)
def tests(
session: nox.Session,
database: str,
greenlet: str,
backendonly: str,
cext: str,
) -> None:
"""run the main test suite"""
_tests(
session,
database,
greenlet=greenlet == "_greenlet",
backendonly=backendonly == "backendonly",
platform_intensive=backendonly == "memusage",
cext=cext,
)
@nox.session(name="coverage")
@tox_parameters(
["database", "cext", "backendonly"],
[DATABASES, CEXT, ["_all", "backendonly"]],
base_tag="coverage",
)
def coverage(
session: nox.Session, database: str, cext: str, backendonly: str
) -> None:
"""Run tests with coverage."""
_tests(
session,
database,
cext,
timing_intensive=False,
backendonly=backendonly == "backendonly",
coverage=True,
)
@nox.session(name="github-cext-greenlet")
def github_cext_greenlet(session: nox.Session) -> None:
"""run tests for github actions"""
_tests(session, "sqlite", "cext", greenlet=True, timing_intensive=False)
@nox.session(name="github-cext")
def github_cext(session: nox.Session) -> None:
"""run tests for github actions"""
_tests(session, "sqlite", "cext", greenlet=False, timing_intensive=False)
@nox.session(name="github-nocext")
def github_nocext(session: nox.Session) -> None:
"""run tests for github actions"""
_tests(session, "sqlite", "cext", greenlet=False)
def _tests(
session: nox.Session,
database: str,
cext: str = "_auto",
greenlet: bool = True,
backendonly: bool = False,
platform_intensive: bool = False,
timing_intensive: bool = True,
coverage: bool = False,
) -> None:
# ensure external PYTHONPATH not interfering
session.env["PYTHONPATH"] = ""
# PYTHONNOUSERSITE - this *MUST* be set so that the ./lib/ import
# set up explicitly in test/conftest.py is *disabled*, so that
# when SQLAlchemy is built into the .nox area, we use that and not the
# local checkout, at least when usedevelop=False
session.env["PYTHONNOUSERSITE"] = "1"
freethreaded = isinstance(session.python, str) and session.python.endswith(
"t"
)
if freethreaded:
session.env["PYTHON_GIL"] = "0"
# greenlet frequently crashes with freethreading, so omit
# for the near future
greenlet = False
session.env["SQLALCHEMY_WARN_20"] = "1"
if cext == "cext":
session.env["REQUIRE_SQLALCHEMY_CEXT"] = "1"
elif cext == "nocext":
session.env["DISABLE_SQLALCHEMY_CEXT"] = "1"
includes_excludes: dict[str, list[str]] = {"k": [], "m": []}
if coverage:
timing_intensive = False
if platform_intensive:
# platform_intensive refers to test/aaa_profiling/test_memusage.py.
# it's only run exclusively of all other tests. does not include
# greenlet related tests
greenlet = False
# with "-m memory_intensive", only that suite will run, all
# other tests will be deselected by pytest
includes_excludes["m"].append("memory_intensive")
elif backendonly:
# with "-m backendonly", only tests with the backend pytest mark
# (or pytestplugin equivalent, like __backend__) will be selected
# by pytest.
# memory intensive is deselected to prevent these from running
includes_excludes["m"].extend(["backend", "not memory_intensive"])
else:
includes_excludes["m"].append("not memory_intensive")
# the mypy suite is also run exclusively from the test_mypy
# session
includes_excludes["m"].append("not mypy")
if not timing_intensive:
includes_excludes["m"].append("not timing_intensive")
cmd = ["python", "-m", "pytest"]
cmd.extend(os.environ.get("TOX_WORKERS", "-n4").split())
if coverage:
assert not platform_intensive
includes_excludes["k"].append("not aaa_profiling")
session.install("-e", ".")
session.install(*nox.project.dependency_groups(pyproject, "coverage"))
else:
session.install(".")
session.install(*nox.project.dependency_groups(pyproject, "tests"))
if greenlet:
session.install(
*nox.project.dependency_groups(pyproject, "tests_greenlet")
)
else:
# note: if on SQLAlchemy 2.0, for "nogreenlet" need to do an explicit
# uninstall of greenlet since it's included in sqlalchemy dependencies
# in 2.1 it's an optional dependency
session.run("pip", "uninstall", "-y", "greenlet")
_setup_for_driver(session, cmd, database, greenlet=greenlet)
for letter, collection in includes_excludes.items():
if collection:
cmd.extend([f"-{letter}", " and ".join(collection)])
posargs = apply_pytest_opts(
session,
"sqlalchemy",
[
database,
cext,
"_greenlet" if greenlet else "nogreenlet",
"memusage" if platform_intensive else "_nomemusage",
"backendonly" if backendonly else "_notbackendonly",
],
coverage=coverage,
)
if database in ["oracle", "mssql"]:
cmd.extend(["--low-connections"])
if database in ["oracle", "mssql", "sqlite_file"]:
# use equals sign so that we avoid
# https://github.com/pytest-dev/pytest/issues/13913
cmd.extend(["--write-idents=db_idents.txt"])
cmd.extend(posargs)
try:
session.run(*cmd)
finally:
# Run cleanup for oracle/mssql
if database in ["oracle", "mssql", "sqlite_file"] and os.path.exists(
"db_idents.txt"
):
session.run("python", "reap_dbs.py", "db_idents.txt")
os.unlink("db_idents.txt")
@nox.session(name="pep484")
def test_pep484(session: nox.Session) -> None:
"""Run mypy type checking."""
session.install(*nox.project.dependency_groups(pyproject, "mypy"))
session.install("-e", ".")
session.run(
"mypy",
"noxfile.py",
"./lib/sqlalchemy",
)
@nox.session(name="mypy")
def test_mypy(session: nox.Session) -> None:
"""run the typing integration test suite"""
session.install(*nox.project.dependency_groups(pyproject, "mypy"))
session.install("-e", ".")
posargs = apply_pytest_opts(
session,
"sqlalchemy",
["mypy"],
)
cmd = ["pytest", "-m", "mypy"]
session.run(*cmd, *posargs)
@nox.session(name="pep8")
def test_pep8(session: nox.Session) -> None:
"""Run linting and formatting checks."""
for pattern in ["*.so", "*.pyd", "*.dylib"]:
for filepath in Path("lib/sqlalchemy").rglob(pattern):
filepath.unlink()
session.install("-e", ".")
session.install(*nox.project.dependency_groups(pyproject, "lint"))
for cmd in [
"flake8p ./lib/ ./test/ ./examples/ noxfile.py "
"setup.py doc/build/conf.py",
# run "unused argument" lints on asyncio, as we have a lot of
# proxy methods here
"flake8p --ignore='' --select='U100,U101' "
"./lib/sqlalchemy/ext/asyncio "
"./lib/sqlalchemy/orm/scoping.py",
"black --check ./lib/ ./test/ ./examples/ setup.py doc/build/conf.py",
"slotscheck -m sqlalchemy",
"python ./tools/format_docs_code.py --check",
"python ./tools/generate_tuple_map_overloads.py --check",
"python ./tools/generate_proxy_methods.py --check",
"python ./tools/sync_test_files.py --check",
"python ./tools/generate_sql_functions.py --check",
"python ./tools/normalize_file_headers.py --check",
"python ./tools/walk_packages.py",
]:
session.run(*cmd.split())
|