ai_v/venv/Lib/site-packages/sqlalchemy/testing/config.py

435 lines
12 KiB
Python
Raw Normal View History

feat(api): 实现图像生成及后台同步功能 - 新增图像生成接口,支持试用、积分和自定义API Key模式 - 实现生成图片结果异步上传至MinIO存储,带重试机制 - 优化积分预扣除和异常退还逻辑,保障用户积分准确 - 添加获取生成历史记录接口,支持时间范围和分页 - 提供本地字典配置接口,支持模型、比例、提示模板和尺寸 - 实现图片批量上传接口,支持S3兼容对象存储 feat(admin): 增加管理员角色管理与权限分配接口 - 实现角色列表查询、角色创建、更新及删除功能 - 增加权限列表查询接口 - 实现用户角色分配接口,便于统一管理用户权限 - 增加系统字典增删查改接口,支持分类过滤和排序 - 权限控制全面覆盖管理接口,保证安全访问 feat(auth): 完善用户登录注册及权限相关接口与页面 - 实现手机号验证码发送及校验功能,保障注册安全 - 支持手机号注册、登录及退出接口,集成日志记录 - 增加修改密码功能,验证原密码后更新 - 提供动态导航菜单接口,基于权限展示不同菜单 - 实现管理界面路由及日志、角色、字典管理页面访问权限控制 - 添加系统日志查询接口,支持关键词和等级筛选 feat(app): 初始化Flask应用并配置蓝图与数据库 - 创建应用程序工厂,加载配置,初始化数据库和Redis客户端 - 注册认证、API及管理员蓝图,整合路由 - 根路由渲染主页模板 - 应用上下文中自动创建数据库表,保证运行环境准备完毕 feat(database): 提供数据库创建与迁移支持脚本 - 新增数据库创建脚本,支持自动检测是否已存在 - 添加数据库表初始化脚本,支持创建和删除所有表 - 实现RBAC权限初始化,包含基础权限和角色创建 - 新增字段手动修复脚本,添加用户API Key和积分字段 - 强制迁移脚本支持清理连接和修复表结构,初始化默认数据及角色分配 feat(config): 新增系统配置参数 - 配置数据库、Redis、Session和MinIO相关参数 - 添加AI接口地址及试用Key配置 - 集成阿里云短信服务配置及开发模式相关参数 feat(extensions): 初始化数据库、Redis和MinIO客户端 - 创建全局SQLAlchemy数据库实例和Redis客户端 - 配置基于boto3的MinIO兼容S3客户端 chore(logs): 添加示例系统日志文件 - 记录用户请求、验证码发送成功与失败的日志信息
2026-01-12 00:53:31 +08:00
# testing/config.py
# Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
# mypy: ignore-errors
from __future__ import annotations
from argparse import Namespace
import collections
import inspect
import typing
from typing import Any
from typing import Callable
from typing import Iterable
from typing import NoReturn
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union
from . import mock
from . import requirements as _requirements
from .util import fail
from .. import util
# default requirements; this is replaced by plugin_base when pytest
# is run
requirements = _requirements.SuiteRequirements()
db = None
db_url = None
db_opts = None
file_config = None
test_schema = None
test_schema_2 = None
any_async = False
_current = None
ident = "main"
options: Namespace = None # type: ignore
if typing.TYPE_CHECKING:
from .plugin.plugin_base import FixtureFunctions
_fixture_functions: FixtureFunctions
else:
class _NullFixtureFunctions:
def _null_decorator(self):
def go(fn):
return fn
return go
def skip_test_exception(self, *arg, **kw):
return Exception()
@property
def add_to_marker(self):
return mock.Mock()
def mark_base_test_class(self):
return self._null_decorator()
def combinations(self, *arg_sets, **kw):
return self._null_decorator()
def param_ident(self, *parameters):
return self._null_decorator()
def fixture(self, *arg, **kw):
return self._null_decorator()
def get_current_test_name(self):
return None
def async_test(self, fn):
return fn
# default fixture functions; these are replaced by plugin_base when
# pytest runs
_fixture_functions = _NullFixtureFunctions()
_FN = TypeVar("_FN", bound=Callable[..., Any])
def combinations(
*comb: Union[Any, Tuple[Any, ...]],
argnames: Optional[str] = None,
id_: Optional[str] = None,
**kw: str,
) -> Callable[[_FN], _FN]:
r"""Deliver multiple versions of a test based on positional combinations.
This is a facade over pytest.mark.parametrize.
:param \*comb: argument combinations. These are tuples that will be passed
positionally to the decorated function.
:param argnames: optional list of argument names. These are the names
of the arguments in the test function that correspond to the entries
in each argument tuple. pytest.mark.parametrize requires this, however
the combinations function will derive it automatically if not present
by using ``inspect.getfullargspec(fn).args[1:]``. Note this assumes the
first argument is "self" which is discarded.
:param id\_: optional id template. This is a string template that
describes how the "id" for each parameter set should be defined, if any.
The number of characters in the template should match the number of
entries in each argument tuple. Each character describes how the
corresponding entry in the argument tuple should be handled, as far as
whether or not it is included in the arguments passed to the function, as
well as if it is included in the tokens used to create the id of the
parameter set.
If omitted, the argument combinations are passed to parametrize as is. If
passed, each argument combination is turned into a pytest.param() object,
mapping the elements of the argument tuple to produce an id based on a
character value in the same position within the string template using the
following scheme:
.. sourcecode:: text
i - the given argument is a string that is part of the id only, don't
pass it as an argument
n - the given argument should be passed and it should be added to the
id by calling the .__name__ attribute
r - the given argument should be passed and it should be added to the
id by calling repr()
s - the given argument should be passed and it should be added to the
id by calling str()
a - (argument) the given argument should be passed and it should not
be used to generated the id
e.g.::
@testing.combinations(
(operator.eq, "eq"),
(operator.ne, "ne"),
(operator.gt, "gt"),
(operator.lt, "lt"),
id_="na",
)
def test_operator(self, opfunc, name):
pass
The above combination will call ``.__name__`` on the first member of
each tuple and use that as the "id" to pytest.param().
"""
return _fixture_functions.combinations(
*comb, id_=id_, argnames=argnames, **kw
)
def combinations_list(arg_iterable: Iterable[Tuple[Any, ...]], **kw):
"As combination, but takes a single iterable"
return combinations(*arg_iterable, **kw)
class Variation:
__slots__ = ("_name", "_argname")
def __init__(self, case, argname, case_names):
self._name = case
self._argname = argname
for casename in case_names:
setattr(self, casename, casename == case)
if typing.TYPE_CHECKING:
def __getattr__(self, key: str) -> bool: ...
@property
def name(self):
return self._name
def __bool__(self):
return self._name == self._argname
def __nonzero__(self):
return not self.__bool__()
def __str__(self):
return f"{self._argname}={self._name!r}"
def __repr__(self):
return str(self)
def fail(self) -> NoReturn:
fail(f"Unknown {self}")
@classmethod
def idfn(cls, variation):
return variation.name
@classmethod
def generate_cases(cls, argname, cases):
case_names = [
argname if c is True else "not_" + argname if c is False else c
for c in cases
]
typ = type(
argname,
(Variation,),
{
"__slots__": tuple(case_names),
},
)
return [typ(casename, argname, case_names) for casename in case_names]
def variation(argname_or_fn, cases=None):
"""a helper around testing.combinations that provides a single namespace
that can be used as a switch.
e.g.::
@testing.variation("querytyp", ["select", "subquery", "legacy_query"])
@testing.variation("lazy", ["select", "raise", "raise_on_sql"])
def test_thing(self, querytyp, lazy, decl_base):
class Thing(decl_base):
__tablename__ = "thing"
# use name directly
rel = relationship("Rel", lazy=lazy.name)
# use as a switch
if querytyp.select:
stmt = select(Thing)
elif querytyp.subquery:
stmt = select(Thing).subquery()
elif querytyp.legacy_query:
stmt = Session.query(Thing)
else:
querytyp.fail()
The variable provided is a slots object of boolean variables, as well
as the name of the case itself under the attribute ".name"
"""
if inspect.isfunction(argname_or_fn):
argname = argname_or_fn.__name__
cases = argname_or_fn(None)
@variation_fixture(argname, cases)
def go(self, request):
yield request.param
return go
else:
argname = argname_or_fn
cases_plus_limitations = [
(
entry
if (isinstance(entry, tuple) and len(entry) == 2)
else (entry, None)
)
for entry in cases
]
variations = Variation.generate_cases(
argname, [c for c, l in cases_plus_limitations]
)
return combinations(
*[
(
(variation._name, variation, limitation)
if limitation is not None
else (variation._name, variation)
)
for variation, (case, limitation) in zip(
variations, cases_plus_limitations
)
],
id_="ia",
argnames=argname,
)
def variation_fixture(argname, cases, scope="function"):
return fixture(
params=Variation.generate_cases(argname, cases),
ids=Variation.idfn,
scope=scope,
)
def fixture(*arg: Any, **kw: Any) -> Any:
return _fixture_functions.fixture(*arg, **kw)
def get_current_test_name() -> str:
return _fixture_functions.get_current_test_name()
def mark_base_test_class() -> Any:
return _fixture_functions.mark_base_test_class()
class _AddToMarker:
def __getattr__(self, attr: str) -> Any:
return getattr(_fixture_functions.add_to_marker, attr)
add_to_marker = _AddToMarker()
class Config:
def __init__(self, db, db_opts, options, file_config):
self._set_name(db)
self.db = db
self.db_opts = db_opts
self.options = options
self.file_config = file_config
self.test_schema = "test_schema"
self.test_schema_2 = "test_schema_2"
self.is_async = db.dialect.is_async and not util.asbool(
db.url.query.get("async_fallback", False)
)
from . import provision
self.is_default_dialect = provision.is_preferred_driver(self, db)
_stack = collections.deque()
_configs = set()
def __repr__(self):
return (
f"sqlalchemy.testing.config.Config"
f"({self.db.name}+{self.db.driver}, "
f"{self.db.dialect.server_version_info})"
)
def _set_name(self, db):
suffix = "_async" if db.dialect.is_async else ""
if db.dialect.server_version_info:
svi = ".".join(str(tok) for tok in db.dialect.server_version_info)
self.name = "%s+%s%s_[%s]" % (db.name, db.driver, suffix, svi)
else:
self.name = "%s+%s%s" % (db.name, db.driver, suffix)
@classmethod
def register(cls, db, db_opts, options, file_config):
"""add a config as one of the global configs.
If there are no configs set up yet, this config also
gets set as the "_current".
"""
global any_async
cfg = Config(db, db_opts, options, file_config)
# if any backends include an async driver, then ensure
# all setup/teardown and tests are wrapped in the maybe_async()
# decorator that will set up a greenlet context for async drivers.
any_async = any_async or cfg.is_async
cls._configs.add(cfg)
return cfg
@classmethod
def set_as_current(cls, config, namespace):
global db, _current, db_url, test_schema, test_schema_2, db_opts
_current = config
db_url = config.db.url
db_opts = config.db_opts
test_schema = config.test_schema
test_schema_2 = config.test_schema_2
namespace.db = db = config.db
@classmethod
def push_engine(cls, db, namespace):
assert _current, "Can't push without a default Config set up"
cls.push(
Config(
db, _current.db_opts, _current.options, _current.file_config
),
namespace,
)
@classmethod
def push(cls, config, namespace):
cls._stack.append(_current)
cls.set_as_current(config, namespace)
@classmethod
def pop(cls, namespace):
if cls._stack:
# a failed test w/ -x option can call reset() ahead of time
_current = cls._stack[-1]
del cls._stack[-1]
cls.set_as_current(_current, namespace)
@classmethod
def reset(cls, namespace):
if cls._stack:
cls.set_as_current(cls._stack[0], namespace)
cls._stack.clear()
@classmethod
def all_configs(cls):
return cls._configs
@classmethod
def all_dbs(cls):
for cfg in cls.all_configs():
yield cfg.db
def skip_test(self, msg):
skip_test(msg)
def skip_test(msg):
raise _fixture_functions.skip_test_exception(msg)
def async_test(fn):
return _fixture_functions.async_test(fn)