From ed028895589d4ca3ce333098dc72b9ff6463cee0 Mon Sep 17 00:00:00 2001
From: insistence <3055204202@qq.com>
Date: Sun, 22 Nov 2026 14:33:00 +0800
Subject: [PATCH 1/9] =?UTF-8?q?build!:=20=E5=B0=86=E6=9C=80=E4=BD=8E=20Pyt?=
=?UTF-8?q?hon=20=E7=89=88=E6=9C=AC=E6=8F=90=E5=8D=87=E8=87=B3=203.11?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.github/scripts/ci_plan.py | 2 +-
.github/tests/test_ci_plan.py | 4 +-
.github/workflows/ci-backend.yml | 2 +-
.github/workflows/ci-integration.yml | 2 +-
.github/workflows/ci-native.yml | 2 +-
README.md | 2 +-
ruoyi-fastapi-backend/Dockerfile.my | 2 +-
ruoyi-fastapi-backend/Dockerfile.pg | 2 +-
.../cli/runtime/oidc/service.py | 4 +-
.../cli/runtime/ops/support.py | 8 ++--
.../scaffold/assets/native/Cargo.toml.tmpl | 2 +-
.../assets/native/pyproject.toml.tmpl | 2 +-
.../scaffold/assets/python/__init__.py.tmpl | 4 +-
.../cli/runtime/plugin/scaffold/v2.py | 4 +-
.../cli/runtime/plugin/sdk.py | 2 +-
.../cli/tui/actions/execution.py | 2 +-
ruoyi-fastapi-backend/cli/tui/queries.py | 4 +-
.../common/annotation/cache_annotation.py | 3 +-
.../common/annotation/log_annotation.py | 7 ++-
.../annotation/rate_limit_annotation.py | 3 +-
ruoyi-fastapi-backend/common/enums.py | 4 +-
ruoyi-fastapi-backend/common/types.py | 4 +-
ruoyi-fastapi-backend/common/vo.py | 3 +-
.../config/scheduler/job_execution.py | 2 +-
.../config/scheduler/jobs.py | 4 +-
.../config/scheduler/manager.py | 4 +-
.../config/scheduler/resources.py | 4 +-
ruoyi-fastapi-backend/docs/cli_usage.md | 2 +-
.../docs/plugin_development.md | 12 ++---
.../unified_authentication_developer_guide.md | 2 +-
.../module_admin/service/server_service.py | 4 +-
.../security/backchannel_transport.py | 2 +-
.../module_identity/security/jwt_profile.py | 4 +-
.../service/infrastructure_service.py | 2 +-
.../service/interaction_service.py | 6 +--
.../module_identity/service/key_service.py | 2 +-
.../service/session_service.py | 2 +-
.../plugins/ai/service/ai_chat_service.py | 12 ++---
.../plugins/core/artifacts/store.py | 2 +-
.../plugins/core/deployment/state.py | 4 +-
.../plugins/core/deployment/worker.py | 30 +++++++-----
.../plugins/core/runtime/application.py | 5 +-
.../plugins/core/runtime/asgi.py | 2 +-
.../plugins/core/runtime/connections.py | 2 +-
.../plugins/core/runtime/health.py | 2 +-
.../plugins/core/runtime/hooks.py | 2 +-
.../plugins/core/runtime/job_dispatcher.py | 8 ++--
.../plugins/core/runtime/metrics.py | 2 +-
.../plugins/core/runtime/result.py | 3 +-
.../plugins/core/runtime/startup.py | 2 +-
.../plugins/core/runtime/support/precheck.py | 3 +-
.../plugins/core/runtime/task_cleanup.py | 10 ++--
.../plugins/core/sdk/asgi.py | 2 +-
.../plugins/core/sdk/definition.py | 22 +++++----
.../examples/python/asgi_demo/plugin.yaml | 2 +-
.../examples/python/bundle_demo/plugin.yaml | 2 +-
.../examples/python/task_demo/README.md | 2 +-
.../examples/python/task_demo/plugin.yaml | 2 +-
.../examples/rust/rust_demo/Cargo.toml | 2 +-
.../plugins/examples/rust/rust_demo/README.md | 4 +-
.../examples/rust/rust_demo/plugin.yaml | 2 +-
.../examples/rust/rust_demo/pyproject.toml | 2 +-
ruoyi-fastapi-backend/pyproject.toml | 2 +-
ruoyi-fastapi-backend/ruff.toml | 2 +-
.../scripts/migrate_job_fields.py | 2 +-
.../scripts/migrate_legacy_files.py | 4 +-
.../scripts/plugin_task_integration.py | 4 +-
.../scripts/verify_timezone_database.py | 6 +--
.../tui/adapters/test_app_ops_snapshots.py | 4 +-
.../test_configs_dashboard_snapshots.py | 2 +-
.../tests/common/test_query_time.py | 10 ++--
.../tests/common/test_request_timezone.py | 8 ++--
.../tests/common/test_types.py | 18 ++++---
.../test_current_user_cache_transactions.py | 3 +-
.../tests/config/test_database_registry.py | 2 +-
.../test_scheduler_execution_coordination.py | 39 +++++++--------
.../tests/config/test_scheduler_executor.py | 8 ++--
.../config/test_scheduler_job_persistence.py | 6 +--
.../tests/config/test_scheduler_job_sync.py | 6 +--
.../service/test_common_file_security.py | 6 +--
.../service/test_file_access_log.py | 4 +-
.../module_admin/service/test_file_acl.py | 16 +++----
...test_file_lifecycle_retention_execution.py | 10 ++--
.../service/test_file_reconcile.py | 4 +-
.../service/test_file_reference.py | 14 +++---
.../service/test_notice_service.py | 12 ++---
.../module_generator/dao/test_gen_dao.py | 4 +-
.../test_generated_time_contract.py | 4 +-
.../test_authorization_controller.py | 4 +-
.../test_interaction_controller.py | 4 +-
.../test_oauth_audit_controller.py | 6 +--
.../controllers/test_oidc_key_controller.py | 4 +-
.../dao/test_grant_policy_dao.py | 4 +-
.../module_identity/dao/test_oidc_key_dao.py | 4 +-
.../dao/test_refresh_token_dao.py | 8 ++--
.../models/test_oidc_key_vo.py | 4 +-
.../security/test_jwt_profile.py | 4 +-
.../services/test_audit_service.py | 8 ++--
.../services/test_authorization_service.py | 4 +-
.../services/test_claim_service.py | 6 +--
.../services/test_consent_service.py | 8 ++--
.../test_credential_authentication_service.py | 4 +-
.../test_identity_security_event_service.py | 4 +-
.../services/test_interaction_service.py | 4 +-
.../services/test_introspection_service.py | 8 ++--
.../services/test_key_service.py | 40 ++++++++--------
.../module_identity/services/test_logout.py | 47 +++++--------------
.../services/test_oauth_management_service.py | 22 ++++-----
.../test_oauth_resource_scope_management.py | 6 +--
.../services/test_review_regressions.py | 4 +-
.../services/test_revocation_service.py | 6 +--
.../services/test_sso_session_service.py | 4 +-
.../services/test_token_service.py | 18 +++----
.../controller/test_plugin_controller.py | 4 +-
.../core/deployment/test_convergence.py | 20 ++++----
.../core/deployment/test_release_state.py | 4 +-
.../plugins/core/deployment/test_worker.py | 20 ++++++++
.../core/management/test_plugin_state.py | 14 +++---
.../core/management/test_release_dao.py | 4 +-
.../tests/plugins/core/native/test_wheel.py | 2 +-
.../plugins/core/runtime/test_diagnostics.py | 2 +-
.../core/runtime/test_diagnostics_query.py | 8 ++--
.../core/runtime/test_diagnostics_store.py | 4 +-
.../core/runtime/test_job_dispatcher.py | 8 ++--
.../plugins/core/runtime/test_task_cleanup.py | 12 ++---
.../plugins/core/validation/test_manifest.py | 8 ++--
.../plugins/integration/test_network_smoke.py | 18 +++----
.../tests/scheduler_helpers.py | 4 +-
.../tests/test_audit_time_delegation.py | 8 ++--
.../tests/utils/test_cron_util.py | 10 ++--
.../utils/test_current_user_cache_util.py | 2 +-
.../tests/utils/test_log_sanitize_util.py | 4 +-
.../tests/utils/test_response_timezone.py | 4 +-
.../tests/utils/test_time_util.py | 10 ++--
.../utils/api_annotation_util.py | 3 +-
ruoyi-fastapi-backend/utils/cache_util.py | 2 +-
ruoyi-fastapi-backend/utils/cron_util.py | 4 +-
ruoyi-fastapi-backend/utils/log_util.py | 4 +-
ruoyi-fastapi-backend/utils/time_util.py | 16 +++----
.../utils/transport_crypto_util.py | 4 +-
ruoyi-fastapi-test/README.md | 6 +--
ruoyi-fastapi-test/common/base_page_test.py | 8 ++--
ruoyi-fastapi-test/prepare_e2e_compose.py | 2 +-
ruoyi-fastapi-test/ruff.toml | 2 +-
144 files changed, 458 insertions(+), 455 deletions(-)
diff --git a/.github/scripts/ci_plan.py b/.github/scripts/ci_plan.py
index 09a96e179..5e1022776 100644
--- a/.github/scripts/ci_plan.py
+++ b/.github/scripts/ci_plan.py
@@ -7,7 +7,7 @@
ROOT = Path(__file__).resolve().parents[2]
FRAMEWORKS = ('vue2', 'vue3', 'react')
-PYTHON_VERSIONS = ('3.10', '3.11', '3.12', '3.13', '3.14')
+PYTHON_VERSIONS = ('3.11', '3.12', '3.13', '3.14')
CATEGORIES = ('quality', 'backend', 'frontend', 'integration', 'e2e', 'native')
FRONTEND_FILE_PATH_PARTS = 4
diff --git a/.github/tests/test_ci_plan.py b/.github/tests/test_ci_plan.py
index d27a21432..4f807f9fd 100644
--- a/.github/tests/test_ci_plan.py
+++ b/.github/tests/test_ci_plan.py
@@ -9,7 +9,7 @@
SPEC.loader.exec_module(ci)
FRONTEND_PROJECT_COUNT = 6
STANDARD_E2E_COMBINATION_COUNT = 6
-FULL_E2E_COMBINATION_COUNT = 30
+FULL_E2E_COMBINATION_COUNT = 24
def test_readme_change_only_runs_quality() -> None:
@@ -160,7 +160,7 @@ def test_full_run_preserves_python_database_and_framework_combinations() -> None
plan = ci.build_plan([], full=True)
assert all(plan['required'].values())
assert len(plan['e2e_matrix']['include']) == FULL_E2E_COMBINATION_COUNT
- assert {row['python'] for row in plan['e2e_matrix']['include']} == {'3.10', '3.11', '3.12', '3.13', '3.14'}
+ assert {row['python'] for row in plan['e2e_matrix']['include']} == {'3.11', '3.12', '3.13', '3.14'}
@pytest.mark.parametrize('result', ['failure', 'cancelled', 'skipped', None])
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index e8e45324a..4cbf51dca 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -18,7 +18,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- python: ['3.10', '3.11', '3.12', '3.13', '3.14']
+ python: ['3.11', '3.12', '3.13', '3.14']
defaults:
run:
working-directory: ruoyi-fastapi-backend
diff --git a/.github/workflows/ci-integration.yml b/.github/workflows/ci-integration.yml
index dba1d6e69..00acec1b2 100644
--- a/.github/workflows/ci-integration.yml
+++ b/.github/workflows/ci-integration.yml
@@ -124,7 +124,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- python: ${{ fromJSON(inputs.full && '["3.10","3.11","3.12","3.13","3.14"]' || '["3.12"]') }}
+ python: ${{ fromJSON(inputs.full && '["3.11","3.12","3.13","3.14"]' || '["3.12"]') }}
defaults:
run:
working-directory: ruoyi-fastapi-backend
diff --git a/.github/workflows/ci-native.yml b/.github/workflows/ci-native.yml
index b8eff3d9c..b17dc0ac1 100644
--- a/.github/workflows/ci-native.yml
+++ b/.github/workflows/ci-native.yml
@@ -43,7 +43,7 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
- python: ['3.10', '3.11', '3.12', '3.13', '3.14']
+ python: ['3.11', '3.12', '3.13', '3.14']
defaults:
run:
working-directory: ruoyi-fastapi-backend
diff --git a/README.md b/README.md
index baaed0c41..2a5ba28ff 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,7 @@
-
+
diff --git a/ruoyi-fastapi-backend/Dockerfile.my b/ruoyi-fastapi-backend/Dockerfile.my
index 62973ce19..7dc466053 100644
--- a/ruoyi-fastapi-backend/Dockerfile.my
+++ b/ruoyi-fastapi-backend/Dockerfile.my
@@ -1,4 +1,4 @@
-ARG PYTHON_VERSION=3.10
+ARG PYTHON_VERSION=3.11
FROM python:${PYTHON_VERSION}
ENV TZ=UTC
WORKDIR /app
diff --git a/ruoyi-fastapi-backend/Dockerfile.pg b/ruoyi-fastapi-backend/Dockerfile.pg
index daa2907d9..142bda13c 100644
--- a/ruoyi-fastapi-backend/Dockerfile.pg
+++ b/ruoyi-fastapi-backend/Dockerfile.pg
@@ -1,4 +1,4 @@
-ARG PYTHON_VERSION=3.10
+ARG PYTHON_VERSION=3.11
FROM python:${PYTHON_VERSION}
ENV TZ=UTC
WORKDIR /app
diff --git a/ruoyi-fastapi-backend/cli/runtime/oidc/service.py b/ruoyi-fastapi-backend/cli/runtime/oidc/service.py
index 09bc2cc9e..bb6bd7a99 100644
--- a/ruoyi-fastapi-backend/cli/runtime/oidc/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/oidc/service.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from typing import Any
from cli.exit_codes import RUNTIME_ERROR
@@ -107,7 +107,7 @@ async def bootstrap_signing_key(
kid=kid,
actor=actor,
redis=redis,
- now=datetime.now(timezone.utc),
+ now=datetime.now(UTC),
)
return {
'ok': True,
diff --git a/ruoyi-fastapi-backend/cli/runtime/ops/support.py b/ruoyi-fastapi-backend/cli/runtime/ops/support.py
index 8ba9a17a0..85f4a7429 100644
--- a/ruoyi-fastapi-backend/cli/runtime/ops/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/ops/support.py
@@ -3,7 +3,7 @@
import socket
import time
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from importlib import metadata
from typing import Any
@@ -231,9 +231,9 @@ def build_server_info_fallback(self) -> dict[str, Any]:
'py': {
'name': current_process.name(),
'version': platform.python_version(),
- 'startTime': TimezoneUtil.to_business_time(
- datetime.fromtimestamp(start_time_stamp, tz=timezone.utc)
- ).strftime('%Y-%m-%d %H:%M:%S'),
+ 'startTime': TimezoneUtil.to_business_time(datetime.fromtimestamp(start_time_stamp, tz=UTC)).strftime(
+ '%Y-%m-%d %H:%M:%S'
+ ),
'runTime': f'{days}天{hours}小时{minutes}分钟',
'home': current_process.exe(),
'total': bytes2human(memory_info.available),
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/native/Cargo.toml.tmpl b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/native/Cargo.toml.tmpl
index e415ea432..badac4b7b 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/native/Cargo.toml.tmpl
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/native/Cargo.toml.tmpl
@@ -9,7 +9,7 @@ name = "_native"
crate-type = ["cdylib"]
[dependencies]
-pyo3 = { version = "0.29.2", features = ["abi3-py310"] }
+pyo3 = { version = "0.29.2", features = ["abi3-py311"] }
pyo3-async-runtimes = { version = "0.29.0", features = ["tokio-runtime"] }
[profile.release]
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/native/pyproject.toml.tmpl b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/native/pyproject.toml.tmpl
index 8f6366732..24187fe4c 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/native/pyproject.toml.tmpl
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/native/pyproject.toml.tmpl
@@ -5,7 +5,7 @@ build-backend = "maturin"
[project]
name = "__DISTRIBUTION__"
version = "1.0.0"
-requires-python = ">=3.10"
+requires-python = ">=3.11"
description = "RuoYi native ASGI plugin example"
[tool.maturin]
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/__init__.py.tmpl b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/__init__.py.tmpl
index dc09a9e24..468d8f44d 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/__init__.py.tmpl
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/__init__.py.tmpl
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from fastapi import FastAPI
@@ -48,7 +48,7 @@ async def info(context: PluginRequestContext) -> dict[str, str]:
"pluginId": context.host.plugin_id,
"hostApiVersion": context.host.api_version,
"engine": "python",
- "serverTime": datetime.now(timezone.utc).isoformat(),
+ "serverTime": datetime.now(UTC).isoformat(),
}
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py
index 49a368346..988a794f9 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py
@@ -205,7 +205,7 @@ def _manifest(plugin_id: str, *, native: bool, bundle: bool) -> str:
'backend': backend,
'frontend': frontend,
'permissions': [{'code': f'{plugin_id}:view', 'name': '访问插件'}],
- 'compatibility': {'hostApiVersion': '^1.2.0', 'pythonVersion': '>=3.10'},
+ 'compatibility': {'hostApiVersion': '^1.2.0', 'pythonVersion': '>=3.11'},
},
allow_unicode=True,
sort_keys=False,
@@ -318,7 +318,7 @@ def _readme(plugin_id: str, *, native: bool, bundle: bool, test: bool) -> str:
这是 manifest v2 的 {'Rust native' if native else 'Python'} ASGI 源码工程{',包含独立前端 bundle' if bundle else ''}。
源码位于 `{root}`,创建工程不会安装、启用或导入插件。下面的命令均在宿主后端根目录执行。
-先创建并激活 Python 3.10–3.14 环境;已有宿主环境可直接激活并使用,无需重复创建。
+先创建并激活 Python 3.11–3.14 环境;已有宿主环境可直接激活并使用,无需重复创建。
Windows PowerShell:
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/sdk.py b/ruoyi-fastapi-backend/cli/runtime/plugin/sdk.py
index 7a73a0c91..2c5f7153d 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/sdk.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/sdk.py
@@ -531,7 +531,7 @@ def _apply(
path.unlink(missing_ok=True)
else:
cls._write(path, originals[name])
- except (OSError, ValueError) as rollback_error: # noqa: PERF203 - 单个恢复失败不能跳过其他原文件。
+ except (OSError, ValueError) as rollback_error:
failures.append(f'{name}: {rollback_error}')
if failures:
raise ValueError(f'SDK 更新失败且回滚未完成,请从 {backup} 恢复:{";".join(failures)}') from exc
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/execution.py b/ruoyi-fastapi-backend/cli/tui/actions/execution.py
index 769dded58..d7e9e15bf 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/execution.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/execution.py
@@ -53,7 +53,7 @@ async def execute(self, spec: TuiActionSpec, env: str) -> TuiActionResult:
self._dispatch(spec, env),
timeout=TUI_ACTION_TIMEOUT_SECONDS,
)
- except asyncio.TimeoutError:
+ except TimeoutError:
payload = {
'ok': False,
'message': f'{spec.label}执行超时',
diff --git a/ruoyi-fastapi-backend/cli/tui/queries.py b/ruoyi-fastapi-backend/cli/tui/queries.py
index 94998dd62..8f3f1d5da 100644
--- a/ruoyi-fastapi-backend/cli/tui/queries.py
+++ b/ruoyi-fastapi-backend/cli/tui/queries.py
@@ -78,7 +78,7 @@ async def run_async(
"""
try:
return await asyncio.wait_for(operation(), timeout=self.remote_timeout_seconds)
- except asyncio.TimeoutError:
+ except TimeoutError:
return self.build_timeout_payload(label)
except asyncio.CancelledError:
raise
@@ -117,7 +117,7 @@ async def run_local(
asyncio.shield(future),
timeout=remaining,
)
- except asyncio.TimeoutError:
+ except TimeoutError:
return self.build_timeout_payload(label)
except asyncio.CancelledError:
raise
diff --git a/ruoyi-fastapi-backend/common/annotation/cache_annotation.py b/ruoyi-fastapi-backend/common/annotation/cache_annotation.py
index ba0808175..5f5c63587 100644
--- a/ruoyi-fastapi-backend/common/annotation/cache_annotation.py
+++ b/ruoyi-fastapi-backend/common/annotation/cache_annotation.py
@@ -2,13 +2,12 @@
import json
from collections.abc import Awaitable, Callable, Sequence
from functools import wraps
-from typing import Any, TypeVar
+from typing import Any, ParamSpec, TypeVar
from fastapi import Request
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse, ORJSONResponse, Response, StreamingResponse, UJSONResponse
from redis import asyncio as aioredis
-from typing_extensions import ParamSpec
from common.constant import HttpStatusConstant
from common.context import RequestContext
diff --git a/ruoyi-fastapi-backend/common/annotation/log_annotation.py b/ruoyi-fastapi-backend/common/annotation/log_annotation.py
index a5db0caee..d7cac84bd 100644
--- a/ruoyi-fastapi-backend/common/annotation/log_annotation.py
+++ b/ruoyi-fastapi-backend/common/annotation/log_annotation.py
@@ -4,9 +4,9 @@
from collections.abc import Awaitable, Callable
from copy import deepcopy
from datetime import datetime
-from enum import Enum
+from enum import StrEnum
from functools import wraps
-from typing import Any, Literal, TypeVar
+from typing import Any, Literal, ParamSpec, TypeVar
import httpx
from async_lru import alru_cache
@@ -16,7 +16,6 @@
from pydantic_validation_decorator import FieldValidationError
from starlette.exceptions import HTTPException
from starlette.status import HTTP_200_OK
-from typing_extensions import ParamSpec
from user_agents import parse
from common.context import RequestContext
@@ -46,7 +45,7 @@
R = TypeVar('R')
-class _LogFieldRoot(str, Enum):
+class _LogFieldRoot(StrEnum):
"""
日志字段路径根节点
"""
diff --git a/ruoyi-fastapi-backend/common/annotation/rate_limit_annotation.py b/ruoyi-fastapi-backend/common/annotation/rate_limit_annotation.py
index 1d7e9b81c..b0b9512c6 100644
--- a/ruoyi-fastapi-backend/common/annotation/rate_limit_annotation.py
+++ b/ruoyi-fastapi-backend/common/annotation/rate_limit_annotation.py
@@ -6,11 +6,10 @@
from collections.abc import Awaitable, Callable, Sequence
from dataclasses import dataclass
from functools import wraps
-from typing import Literal, TypeVar
+from typing import Literal, ParamSpec, TypeVar
from fastapi import Request
from redis import asyncio as aioredis
-from typing_extensions import ParamSpec
from common.context import RequestContext
from common.enums import HttpMethod, RedisInitKeyConfig
diff --git a/ruoyi-fastapi-backend/common/enums.py b/ruoyi-fastapi-backend/common/enums.py
index 12b565216..7fe306f88 100644
--- a/ruoyi-fastapi-backend/common/enums.py
+++ b/ruoyi-fastapi-backend/common/enums.py
@@ -1,7 +1,7 @@
-from enum import Enum
+from enum import Enum, StrEnum
-class HttpMethod(str, Enum):
+class HttpMethod(StrEnum):
"""
HTTP请求方法枚举
diff --git a/ruoyi-fastapi-backend/common/types.py b/ruoyi-fastapi-backend/common/types.py
index 5d91ea0ca..fb5bc6b73 100644
--- a/ruoyi-fastapi-backend/common/types.py
+++ b/ruoyi-fastapi-backend/common/types.py
@@ -1,5 +1,5 @@
import re
-from datetime import date, datetime, time, timezone
+from datetime import UTC, date, datetime, time
from typing import Annotated, Any
from pydantic import AfterValidator, AwareDatetime, BeforeValidator, PlainSerializer
@@ -102,5 +102,5 @@ def process_result_value(self, value: datetime | None, dialect: Dialect) -> date
if value is None:
return None
if value.tzinfo is None or value.utcoffset() is None:
- value = value.replace(tzinfo=timezone.utc)
+ value = value.replace(tzinfo=UTC)
return TimezoneUtil.to_utc_milliseconds(value)
diff --git a/ruoyi-fastapi-backend/common/vo.py b/ruoyi-fastapi-backend/common/vo.py
index c5a5bc821..a31dedf68 100644
--- a/ruoyi-fastapi-backend/common/vo.py
+++ b/ruoyi-fastapi-backend/common/vo.py
@@ -1,8 +1,7 @@
-from typing import Any, Generic, TypeVar
+from typing import Any, Generic, Self, TypeVar
from pydantic import BaseModel, ConfigDict, Field, create_model, model_validator
from pydantic.alias_generators import to_camel
-from typing_extensions import Self
from common.constant import HttpStatusConstant
from common.types import ApiUtcDateTime
diff --git a/ruoyi-fastapi-backend/config/scheduler/job_execution.py b/ruoyi-fastapi-backend/config/scheduler/job_execution.py
index 75e18fe41..114804e3d 100644
--- a/ruoyi-fastapi-backend/config/scheduler/job_execution.py
+++ b/ruoyi-fastapi-backend/config/scheduler/job_execution.py
@@ -207,7 +207,7 @@ def finish(
)
)
return
- except DBAPIError as exc: # noqa: PERF203 - 每次重试必须覆盖独立事务的完整生命周期。
+ except DBAPIError as exc:
if attempt + 1 >= cls.FINISH_ATTEMPTS or not cls._retryable_finish_error(exc):
raise
# 旧事务回滚且会话关闭后,再等待并开启新事务。
diff --git a/ruoyi-fastapi-backend/config/scheduler/jobs.py b/ruoyi-fastapi-backend/config/scheduler/jobs.py
index 0990315c9..7ea1951c8 100644
--- a/ruoyi-fastapi-backend/config/scheduler/jobs.py
+++ b/ruoyi-fastapi-backend/config/scheduler/jobs.py
@@ -1,6 +1,6 @@
import json
from collections.abc import Callable
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from typing import Any
from apscheduler.job import Job
@@ -194,7 +194,7 @@ def execute_once(self, job_info: JobModel, *, execution_id: str, dispatch_token:
task_job_group=job_info.job_group,
execution_id=execution_id,
dispatch_token=dispatch_token,
- timezone=timezone.utc,
+ timezone=UTC,
),
misfire_grace_time=None,
coalesce=False,
diff --git a/ruoyi-fastapi-backend/config/scheduler/manager.py b/ruoyi-fastapi-backend/config/scheduler/manager.py
index 60d5e78aa..436ef4f6a 100644
--- a/ruoyi-fastapi-backend/config/scheduler/manager.py
+++ b/ruoyi-fastapi-backend/config/scheduler/manager.py
@@ -2,7 +2,7 @@
import json
import random
import time
-from datetime import timezone
+from datetime import UTC
from typing import Any
from apscheduler.events import EVENT_ALL, SchedulerEvent
@@ -22,7 +22,7 @@
from utils.log_util import logger
from utils.server_util import StartupUtil, WorkerIdUtil
-scheduler = AsyncIOScheduler(timezone=timezone.utc)
+scheduler = AsyncIOScheduler(timezone=UTC)
class SchedulerManager:
diff --git a/ruoyi-fastapi-backend/config/scheduler/resources.py b/ruoyi-fastapi-backend/config/scheduler/resources.py
index 093daacd4..8a97be9ef 100644
--- a/ruoyi-fastapi-backend/config/scheduler/resources.py
+++ b/ruoyi-fastapi-backend/config/scheduler/resources.py
@@ -1,6 +1,6 @@
from collections.abc import Callable
from contextlib import AbstractAsyncContextManager
-from datetime import timezone
+from datetime import UTC
from apscheduler.events import SchedulerEvent
from apscheduler.jobstores.memory import MemoryJobStore
@@ -97,7 +97,7 @@ def configure(self, scheduler: AsyncIOScheduler, on_event: Callable[[SchedulerEv
'default': TimedAsyncIOExecutor(on_rejected=on_event, manage_executions=True),
'processpool': TimedProcessPoolExecutor(5, on_rejected=on_event, manage_executions=True),
}
- scheduler.configure(jobstores=job_stores, executors=executors, job_defaults=job_defaults, timezone=timezone.utc)
+ scheduler.configure(jobstores=job_stores, executors=executors, job_defaults=job_defaults, timezone=UTC)
self._configured = True
@staticmethod
diff --git a/ruoyi-fastapi-backend/docs/cli_usage.md b/ruoyi-fastapi-backend/docs/cli_usage.md
index df9c59fa0..ae996a322 100644
--- a/ruoyi-fastapi-backend/docs/cli_usage.md
+++ b/ruoyi-fastapi-backend/docs/cli_usage.md
@@ -39,7 +39,7 @@ ruoyi --help
### 2.2 安装依赖
-使用 Python 3.10–3.14,先进入后端目录,再创建并激活虚拟环境。以下以标准库 `venv` 为例;已有环境也可直接使用,不要求特定环境名称或安装路径。
+使用 Python 3.11–3.14,先进入后端目录,再创建并激活虚拟环境。以下以标准库 `venv` 为例;已有环境也可直接使用,不要求特定环境名称或安装路径。
Windows PowerShell:
diff --git a/ruoyi-fastapi-backend/docs/plugin_development.md b/ruoyi-fastapi-backend/docs/plugin_development.md
index 5a1be5594..6a650f382 100644
--- a/ruoyi-fastapi-backend/docs/plugin_development.md
+++ b/ruoyi-fastapi-backend/docs/plugin_development.md
@@ -15,7 +15,7 @@
目录插件与签名制品不能同时使用相同插件 ID。两种方式均遵守进程重启边界,不提供原生模块热替换。
-后端命令使用已安装项目依赖的 Python 3.10–3.14 环境;创建与激活步骤见 [CLI 环境准备](cli_usage.md#22-安装依赖)。下文的 `python` 指向已激活环境,命令默认在后端目录执行。通用命令同时适用于 Windows PowerShell、macOS 和 Linux;环境变量等 Shell 语法分别列出。
+后端命令使用已安装项目依赖的 Python 3.11–3.14 环境;创建与激活步骤见 [CLI 环境准备](cli_usage.md#22-安装依赖)。下文的 `python` 指向已激活环境,命令默认在后端目录执行。通用命令同时适用于 Windows PowerShell、macOS 和 Linux;环境变量等 Shell 语法分别列出。
## 1. 基本模型
@@ -516,7 +516,7 @@ dependencies:
| `nodeVersion` | `string \| null` | `null` | Node.js 版本约束。 |
| `databases` | `("mysql" \| "postgresql")[]` | `[]` | 插件支持的数据库类型声明,不能重复。 |
-版本约束可以是版本号,也可以带比较操作符,例如 `>=3.10`、`^20.0.0`。
+版本约束可以是版本号,也可以带比较操作符,例如 `>=3.11`、`^20.0.0`。
`compatibility.frontendVersion` 约束前端工程的发行版本,与脚手架结果、依赖记录和锁文件中的 `frontendFramework` 不同;后者取 `vue2`、`vue3` 等框架标识,不能填入版本约束。
@@ -646,7 +646,7 @@ permissions:
name: 查看报表
compatibility:
hostApiVersion: ^1.2.0
- pythonVersion: '>=3.10'
+ pythonVersion: '>=3.11'
databases: [mysql, postgresql]
```
@@ -971,7 +971,7 @@ Rust 使用 PyO3 暴露 Python 扩展,并通过 maturin 构建 wheel;Windows
原生 wheel 在构建或维护环境中验证并展开到 `backend.native.moduleRoot`,默认 `native/`。宿主检查发行包名称、插件版本、Python 要求、wheel tag、已安装依赖及完整 RECORD SHA256;扩展只能从当前插件目录加载,不能覆盖宿主模块。RECORD 用于检查文件一致性,发布者信任仍需第 15 节的签名流程。
-构建机需安装 Rust、maturin 和目标平台编译工具:Windows 使用 MSVC Build Tools 的 C++ 工具及 Windows SDK,macOS 使用 Xcode Command Line Tools,Linux 使用 GCC 或 Clang 等编译工具。先选择 `rust-asgi` 或 `rust-bundle` 脚手架,再按第 16 节构建。`abi3` 可减少 Python ABI 构建数量,但不能跨操作系统或架构复用制品;按实际目标平台及 Python 3.10–3.14 的测试结果验证兼容性。
+构建机需安装 Rust、maturin 和目标平台编译工具:Windows 使用 MSVC Build Tools 的 C++ 工具及 Windows SDK,macOS 使用 Xcode Command Line Tools,Linux 使用 GCC 或 Clang 等编译工具。先选择 `rust-asgi` 或 `rust-bundle` 脚手架,再按第 16 节构建。`abi3` 可减少 Python ABI 构建数量,但不能跨操作系统或架构复用制品;按实际目标平台及 Python 3.11–3.14 的测试结果验证兼容性。
Rust 通过 `PluginHostContext`、`plugin_endpoint`、`plugin_lifespan` 和版本化服务复用宿主能力,完整实现见 [Rust 示例](../plugins/examples/rust/rust_demo/README.md)。不要覆盖已加载的原生模块或依赖 `reload` 完成更新,发布后必须重启全部相关进程。
@@ -1793,9 +1793,9 @@ pnpm --dir ../ruoyi-fastapi-frontend/vue3/web run test:plugin
### 17.4 CI 覆盖
-统一入口为 [`ci.yml`](../../.github/workflows/ci.yml),完整分类和本地命令见[测试说明](../../ruoyi-fastapi-test/README.md)。[`ci-backend.yml`](../../.github/workflows/ci-backend.yml) 承担 v1/v2 脚手架、SDK 溯源、离线更新及 Windows CLI/路径回归;[`ci-native.yml`](../../.github/workflows/ci-native.yml) 保留 Windows/Linux × Python 3.10–3.14 的真实原生制品测试,Rust fmt/clippy 单独运行一次。
+统一入口为 [`ci.yml`](../../.github/workflows/ci.yml),完整分类和本地命令见[测试说明](../../ruoyi-fastapi-test/README.md)。[`ci-backend.yml`](../../.github/workflows/ci-backend.yml) 承担 v1/v2 脚手架、SDK 溯源、离线更新及 Windows CLI/路径回归;[`ci-native.yml`](../../.github/workflows/ci-native.yml) 保留 Windows/Linux × Python 3.11–3.14 的真实原生制品测试,Rust fmt/clippy 单独运行一次。
-[`ci-integration.yml`](../../.github/workflows/ci-integration.yml) 使用临时 MySQL、PostgreSQL 和 Redis 服务验证多 worker 发布行为,PR 使用 Python 3.12,完整运行覆盖 Python 3.10–3.14。工作流配置不代表已经执行成功;发布前应核对对应提交的实际 CI 结果,并完成目标平台的部署验收。
+[`ci-integration.yml`](../../.github/workflows/ci-integration.yml) 使用临时 MySQL、PostgreSQL 和 Redis 服务验证多 worker 发布行为,PR 使用 Python 3.12,完整运行覆盖 Python 3.11–3.14。工作流配置不代表已经执行成功;发布前应核对对应提交的实际 CI 结果,并完成目标平台的部署验收。
`scripts/plugin_release_integration.py` 还检查双 worker 首次发布、升级和代码回滚后的固定目标收敛,无 worker 时单次断言不收敛,旧目标代际被拒绝、单 worker 故障立即失败,以及报告过期、缺员和遗留陈旧记录下的等待结果。足够的新 worker 全部就绪后,遗留陈旧记录不应造成永久等待;失败结果保留退出码和固定原因供流水线判断。脚本还针对两种数据库启动独立的完整 CLI 进程,验证标准输出可整体解析为一个 JSON 对象,并核对未就绪时退出 `50`、就绪后退出 `0`。
diff --git a/ruoyi-fastapi-backend/docs/unified_authentication_developer_guide.md b/ruoyi-fastapi-backend/docs/unified_authentication_developer_guide.md
index 104ee1c05..40cdbd52c 100644
--- a/ruoyi-fastapi-backend/docs/unified_authentication_developer_guide.md
+++ b/ruoyi-fastapi-backend/docs/unified_authentication_developer_guide.md
@@ -55,7 +55,7 @@ Issuer 必须是无路径前缀、无查询串的固定公开地址。`OIDC_PUBL
## 3. 平台启用与检查
-所有后端命令在 `ruoyi-fastapi-backend` 目录执行,并使用已安装项目依赖的 Python 3.10–3.14 环境。命令适用于 Windows PowerShell、macOS 和 Linux,不依赖特定的环境管理工具、环境名称或安装路径。创建与激活步骤见 [CLI 环境准备](cli_usage.md#22-安装依赖)。下面以 `dev` 环境为例,其他环境替换为对应的 `--env` 和配置文件。
+所有后端命令在 `ruoyi-fastapi-backend` 目录执行,并使用已安装项目依赖的 Python 3.11–3.14 环境。命令适用于 Windows PowerShell、macOS 和 Linux,不依赖特定的环境管理工具、环境名称或安装路径。创建与激活步骤见 [CLI 环境准备](cli_usage.md#22-安装依赖)。下面以 `dev` 环境为例,其他环境替换为对应的 `--env` 和配置文件。
`ruoyi` 命令在三个平台上的参数一致。激活环境后,直接调用解释器统一使用 `python`;在新终端执行命令前也应激活同一环境。
diff --git a/ruoyi-fastapi-backend/module_admin/service/server_service.py b/ruoyi-fastapi-backend/module_admin/service/server_service.py
index 3fbf7d61d..a1e213fde 100644
--- a/ruoyi-fastapi-backend/module_admin/service/server_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/server_service.py
@@ -2,7 +2,7 @@
import platform
import socket
import time
-from datetime import datetime, timezone
+from datetime import UTC, datetime
import anyio
import psutil
@@ -56,7 +56,7 @@ async def get_server_monitor_info() -> ServerMonitorModel:
python_version = platform.python_version()
python_home = current_process.exe()
start_time_stamp = current_process.create_time()
- start_time = datetime.fromtimestamp(start_time_stamp, tz=timezone.utc)
+ start_time = datetime.fromtimestamp(start_time_stamp, tz=UTC)
current_time_stamp = time.time()
difference = current_time_stamp - start_time_stamp
# 将时间差转换为天、小时和分钟数
diff --git a/ruoyi-fastapi-backend/module_identity/security/backchannel_transport.py b/ruoyi-fastapi-backend/module_identity/security/backchannel_transport.py
index 7a4fd2eaf..1865c76b6 100644
--- a/ruoyi-fastapi-backend/module_identity/security/backchannel_transport.py
+++ b/ruoyi-fastapi-backend/module_identity/security/backchannel_transport.py
@@ -61,7 +61,7 @@ async def connect_tcp(self, host: str, port: int, **kwargs: Any) -> httpcore.Asy
for address in sorted(self._addresses):
try:
return await self._backend.connect_tcp(address, port, **kwargs)
- except OSError as exc: # noqa: PERF203
+ except OSError as exc:
last_error = exc
raise last_error or OSError('没有通过安全校验的网络目标')
diff --git a/ruoyi-fastapi-backend/module_identity/security/jwt_profile.py b/ruoyi-fastapi-backend/module_identity/security/jwt_profile.py
index 2cb037def..908c02260 100644
--- a/ruoyi-fastapi-backend/module_identity/security/jwt_profile.py
+++ b/ruoyi-fastapi-backend/module_identity/security/jwt_profile.py
@@ -1,6 +1,6 @@
import math
from collections.abc import Mapping, Sequence
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from typing import Any
import jwt
@@ -378,7 +378,7 @@ def _decode(
if payload.get('iss') != issuer or not _audience_matches(payload.get('aud'), audience):
raise JwtProfileError('JWT 签发者或受众不匹配')
_validate_profile_claims(profile, payload)
- now = datetime.now(timezone.utc).timestamp()
+ now = datetime.now(UTC).timestamp()
_numeric_claims(payload, now=now, skew=clock_skew, verify_exp=not allow_expired_hint)
return dict(payload)
diff --git a/ruoyi-fastapi-backend/module_identity/service/infrastructure_service.py b/ruoyi-fastapi-backend/module_identity/service/infrastructure_service.py
index 02b34d95d..f88f16c97 100644
--- a/ruoyi-fastapi-backend/module_identity/service/infrastructure_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/infrastructure_service.py
@@ -134,7 +134,7 @@ async def commit(self, db: AsyncSession) -> None:
for callback in callbacks:
try:
await callback()
- except Exception as exc: # noqa: PERF203
+ except Exception as exc:
self._callback_errors.append(exc)
callbacks.clear()
diff --git a/ruoyi-fastapi-backend/module_identity/service/interaction_service.py b/ruoyi-fastapi-backend/module_identity/service/interaction_service.py
index e7786d89a..b97e6d8a7 100644
--- a/ruoyi-fastapi-backend/module_identity/service/interaction_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/interaction_service.py
@@ -4,7 +4,7 @@
import secrets
from collections.abc import Awaitable, Callable, Collection, Mapping
from dataclasses import dataclass
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Any
from uuid import uuid4
@@ -179,7 +179,7 @@ async def create(
record.update(
{
'interactionId': interaction_id,
- 'requestedAt': datetime.now(timezone.utc).isoformat(),
+ 'requestedAt': datetime.now(UTC).isoformat(),
'csrfHash': csrf_hash,
'status': initial_status,
'version': 1,
@@ -389,7 +389,7 @@ def _validate_record(cls, record: Mapping[str, Any]) -> None:
parsed = datetime.fromisoformat(requested_at.replace('Z', '+00:00'))
except ValueError as exc:
raise ValueError('认证交互的请求时间 requestedAt 无效') from exc
- if parsed.tzinfo is None or parsed.utcoffset() != timezone.utc.utcoffset(parsed):
+ if parsed.tzinfo is None or parsed.utcoffset() != UTC.utcoffset(parsed):
raise ValueError('认证交互的请求时间 requestedAt 必须使用 UTC')
cls._validate_payload(record)
identity_values = [record.get('userId'), record.get('subjectId'), record.get('authVersion')]
diff --git a/ruoyi-fastapi-backend/module_identity/service/key_service.py b/ruoyi-fastapi-backend/module_identity/service/key_service.py
index c0bb642b3..a2b898d1f 100644
--- a/ruoyi-fastapi-backend/module_identity/service/key_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/key_service.py
@@ -614,7 +614,7 @@ async def activate_due(
):
await db.commit()
activated += 1
- except Exception: # noqa: PERF203
+ except Exception:
await db.rollback()
safe_kid = (
record.kid if isinstance(record.kid, str) and OidcUtil.is_valid_kid(record.kid) else 'invalid'
diff --git a/ruoyi-fastapi-backend/module_identity/service/session_service.py b/ruoyi-fastapi-backend/module_identity/service/session_service.py
index 0398bd7ea..a731ba7e6 100644
--- a/ruoyi-fastapi-backend/module_identity/service/session_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/session_service.py
@@ -1657,7 +1657,7 @@ async def notify() -> None:
audit_writer, 'backchannel_logout_succeeded', uri, client_id, sid
)
return
- except PermanentBackchannelError as exc: # noqa: PERF203
+ except PermanentBackchannelError as exc:
await LogoutService._write_backchannel_audit(
audit_writer,
OidcAuditEvent.BACKCHANNEL_LOGOUT_FAILED,
diff --git a/ruoyi-fastapi-backend/plugins/ai/service/ai_chat_service.py b/ruoyi-fastapi-backend/plugins/ai/service/ai_chat_service.py
index 6735f3393..85a38be61 100644
--- a/ruoyi-fastapi-backend/plugins/ai/service/ai_chat_service.py
+++ b/ruoyi-fastapi-backend/plugins/ai/service/ai_chat_service.py
@@ -2,7 +2,7 @@
import os
import uuid
from collections.abc import AsyncGenerator, AsyncIterator
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from agno.agent import Agent
@@ -446,8 +446,8 @@ async def get_chat_session_list_services(cls, user_id: int) -> list[AiChatSessio
result = []
for s in sessions:
- created_at = datetime.fromtimestamp(s.created_at, tz=timezone.utc) if s.created_at else None
- updated_at = datetime.fromtimestamp(s.updated_at, tz=timezone.utc) if s.updated_at else None
+ created_at = datetime.fromtimestamp(s.created_at, tz=UTC) if s.created_at else None
+ updated_at = datetime.fromtimestamp(s.updated_at, tz=UTC) if s.updated_at else None
title_limit = 20
session_title = s.runs[0].input.input_content[:title_limit] + '...' if s.runs else ''
@@ -540,7 +540,7 @@ async def get_chat_session_detail_services(cls, session_id: str, user_id: int) -
content=m.content,
images=cls._convert_images_to_upload_paths(m.images),
metrics=metrics_model,
- createdAt=datetime.fromtimestamp(m.created_at, tz=timezone.utc) if m.created_at else None,
+ createdAt=datetime.fromtimestamp(m.created_at, tz=UTC) if m.created_at else None,
reasoningContent=m.reasoning_content,
fromHistory=m.from_history,
stopAfterToolCall=m.stop_after_tool_call,
@@ -551,8 +551,8 @@ async def get_chat_session_detail_services(cls, session_id: str, user_id: int) -
sessionId=session.session_id,
sessionTitle=session.runs[0].input.input_content[:20] + '...' if session.runs else '',
userId=session.user_id,
- createdAt=datetime.fromtimestamp(session.created_at, tz=timezone.utc) if session.created_at else None,
- updatedAt=datetime.fromtimestamp(session.updated_at, tz=timezone.utc) if session.updated_at else None,
+ createdAt=datetime.fromtimestamp(session.created_at, tz=UTC) if session.created_at else None,
+ updatedAt=datetime.fromtimestamp(session.updated_at, tz=UTC) if session.updated_at else None,
agentId=session.agent_id,
sessionData=SessionDataModel(
sessionState=session_data.get('session_state'),
diff --git a/ruoyi-fastapi-backend/plugins/core/artifacts/store.py b/ruoyi-fastapi-backend/plugins/core/artifacts/store.py
index b421f6199..d81c676fb 100644
--- a/ruoyi-fastapi-backend/plugins/core/artifacts/store.py
+++ b/ruoyi-fastapi-backend/plugins/core/artifacts/store.py
@@ -313,7 +313,7 @@ def _digest_lock(self, digest: str) -> Iterator[None]:
try:
self._lock_file(descriptor, unlock=False)
acquired = True
- except OSError as exc: # noqa: PERF203 - 操作系统非阻塞锁必须重试
+ except OSError as exc:
if exc.errno not in {errno.EACCES, errno.EAGAIN, errno.EDEADLK}:
raise
if time.monotonic() >= deadline:
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/state.py b/ruoyi-fastapi-backend/plugins/core/deployment/state.py
index 6d2662b55..9d0c3460b 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/state.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/state.py
@@ -1,6 +1,6 @@
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from typing import Any
RUNTIME_PLUGIN_ID = '__runtime__'
@@ -170,7 +170,7 @@ def aggregate_release(
raise ValueError('now必须是带时区的UTC时刻')
if ttl_seconds <= 0:
raise ValueError('心跳TTL必须大于零')
- now = now.astimezone(timezone.utc)
+ now = now.astimezone(UTC)
cutoff = now - timedelta(seconds=ttl_seconds)
plugin_id = _field(release, 'plugin_id', '')
target_digest = _field(release, 'target_digest')
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/worker.py b/ruoyi-fastapi-backend/plugins/core/deployment/worker.py
index 7562b4b01..235d92b62 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/worker.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/worker.py
@@ -2,7 +2,6 @@
import hashlib
import json
import sys
-import time
from contextlib import suppress
from dataclasses import dataclass
from typing import Any
@@ -66,28 +65,33 @@ def __init__(
self.app: Any = None
self.registered = False
- async def start(self, app: Any, builder: Any, lifecycle_lock: Any, *, timeout: float = 60) -> None:
+ async def start(self, app: Any, builder: Any, lifecycle_lock: Any, *, lock_wait_seconds: float = 60) -> None:
"""
在生命周期锁内登记宿主快照,验证目标制品并启动心跳上报。
:param app: 当前宿主应用对象
:param builder: 接收制品发现快照的插件运行时构建器
:param lifecycle_lock: 与插件维护发布共用的生命周期锁
- :param timeout: 等待生命周期锁的最长时间,单位为秒
+ :param lock_wait_seconds: 等待生命周期锁的最长时间,单位为秒
:return: None
:raises TimeoutError: 在等待时限内未能取得维护发布锁
"""
self.config.require_enabled()
self.app = app
- deadline = time.monotonic() + timeout
- while True:
- async with lifecycle_lock.lock(RUNTIME_PLUGIN_ID, 'release_snapshot') as lock:
- if lock.acquired:
- await self._register_snapshot()
- break
- if time.monotonic() >= deadline:
- raise TimeoutError('等待插件维护发布锁超时')
- await asyncio.sleep(min(1, self.config.heartbeat_seconds))
+ lock_deadline = asyncio.timeout(lock_wait_seconds)
+ try:
+ async with lock_deadline:
+ while True:
+ async with lifecycle_lock.lock(RUNTIME_PLUGIN_ID, 'release_snapshot') as lock:
+ if lock.acquired:
+ lock_deadline.reschedule(None)
+ await self._register_snapshot()
+ break
+ await asyncio.sleep(min(1, self.config.heartbeat_seconds))
+ except TimeoutError as exc:
+ if lock_deadline.expired():
+ raise TimeoutError('等待插件维护发布锁超时') from exc
+ raise
# 验签和大文件散列期间也维持宿主存活,维护命令不能越过启动中的进程。
self.task = asyncio.create_task(self._heartbeat(), name=f'plugin-release-{self.worker_id}')
plugins = []
@@ -100,7 +104,7 @@ async def start(self, app: Any, builder: Any, lifecycle_lock: Any, *, timeout: f
raise ValueError('发布目标与制品插件 ID 不一致')
self.versions[target.plugin_id] = artifact.version
plugins.append(self.catalog.discovered(artifact, target.generation))
- except Exception as exc: # noqa: PERF203 - 单个制品损坏不能阻断其他插件。
+ except Exception as exc:
self.errors[target.plugin_id] = str(exc)[:2000]
logger.error(f'插件发布目标验证失败:{target.plugin_id},{exc}')
errors = [
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/application.py b/ruoyi-fastapi-backend/plugins/core/runtime/application.py
index 2a581b5ba..74fb9009f 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/application.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/application.py
@@ -102,7 +102,10 @@ async def startup(
try:
if self.release_worker is not None:
await self.release_worker.start(
- app, self.startup_manager.builder, self.lifecycle_lock, timeout=self.ready_wait_timeout_seconds
+ app,
+ self.startup_manager.builder,
+ self.lifecycle_lock,
+ lock_wait_seconds=self.ready_wait_timeout_seconds,
)
self.startup_generation = self.release_worker.generation(self.resolve_startup_generation())
app.state.plugin_release_worker = self.release_worker
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/asgi.py b/ruoyi-fastapi-backend/plugins/core/runtime/asgi.py
index 3ff931a52..9b98fc019 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/asgi.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/asgi.py
@@ -191,7 +191,7 @@ async def _cancel_task(self) -> None:
"""
if self._task is None:
return
- if await cancel_plugin_tasks({self._task}, timeout=self.cancel_timeout):
+ if await cancel_plugin_tasks({self._task}, grace_seconds=self.cancel_timeout):
logger.warning('插件生命周期未响应取消;保留任务并拒绝重启,等待任务自行退出')
else:
self._task = None
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/connections.py b/ruoyi-fastapi-backend/plugins/core/runtime/connections.py
index a2ce90ca7..44173ca27 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/connections.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/connections.py
@@ -272,7 +272,7 @@ async def _check(self) -> None:
self.stop(ACCESS_REVOKED)
except LookupError:
self.stop(LOGIN_EXPIRED)
- except (TimeoutError, asyncio.TimeoutError):
+ except TimeoutError:
self.stop(CHECK_TIMED_OUT)
except Exception:
self.stop(CHECK_UNAVAILABLE)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/health.py b/ruoyi-fastapi-backend/plugins/core/runtime/health.py
index 507496311..5c13d374f 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/health.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/health.py
@@ -106,7 +106,7 @@ async def check(self, *, app: Any | None = None, query_db: Any | None = None) ->
)
raw_result = await self._invoke_checker_with_timeout(checker_callable, context)
return self._normalize_result(raw_result, checker_path, started_at)
- except asyncio.TimeoutError:
+ except TimeoutError:
return self._build_result(
ok=False,
status='timeout',
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/hooks.py b/ruoyi-fastapi-backend/plugins/core/runtime/hooks.py
index 5cd970113..d814df09c 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/hooks.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/hooks.py
@@ -124,7 +124,7 @@ async def run(
logger.debug('🔄 开始执行插件生命周期钩子')
try:
await self._invoke_hook_with_timeout(hook_callable, context)
- except asyncio.TimeoutError as exc:
+ except TimeoutError as exc:
raise TimeoutError(f'生命周期钩子执行超时:{hook_name},超过 {self.timeout_seconds} 秒') from exc
logger.debug('✅ 插件生命周期钩子执行完成')
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/job_dispatcher.py b/ruoyi-fastapi-backend/plugins/core/runtime/job_dispatcher.py
index 41965167d..6e87ea531 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/job_dispatcher.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/job_dispatcher.py
@@ -96,12 +96,12 @@ def _release_binding(binding: PluginJobBinding) -> None:
del _bindings[plugin_id]
-async def unbind_plugin_jobs(binding: PluginJobBinding, *, timeout: float = CANCEL_TIMEOUT_SECONDS) -> None:
+async def unbind_plugin_jobs(binding: PluginJobBinding, *, grace_seconds: float = CANCEL_TIMEOUT_SECONDS) -> None:
"""
先停止分发,再整批限时取消;未退出时保留绑定并禁止新实例覆盖。
:param binding: 待解除的插件任务绑定
- :param timeout: 整批运行任务的取消等待上限秒数
+ :param grace_seconds: 整批运行任务的取消等待上限秒数
:return: None
"""
if not binding.closing:
@@ -109,7 +109,7 @@ async def unbind_plugin_jobs(binding: PluginJobBinding, *, timeout: float = CANC
for task in binding.tasks:
task.add_done_callback(lambda _: _release_binding(binding))
try:
- pending = await cancel_plugin_tasks(binding.tasks, timeout=timeout)
+ pending = await cancel_plugin_tasks(binding.tasks, grace_seconds=grace_seconds)
if pending:
logger.warning('插件任务取消等待超时:{},尚有 {} 个任务未退出', binding.plugin.manifest.id, len(pending))
finally:
@@ -177,7 +177,7 @@ async def dispatch_plugin_job(plugin_id: str, job_id: str, version: str) -> Any:
raise
except Exception as exc:
error_type = type(exc).__name__
- timed_out = isinstance(exc, (TimeoutError, asyncio.TimeoutError))
+ timed_out = isinstance(exc, TimeoutError)
raise
finally:
if invocation is not None:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/metrics.py b/ruoyi-fastapi-backend/plugins/core/runtime/metrics.py
index 4d6e2484d..6b1634aed 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/metrics.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/metrics.py
@@ -341,7 +341,7 @@ async def observed_send(message: Message) -> None:
raise
except Exception as exc:
error_type = type(exc).__name__
- timed_out = isinstance(exc, (TimeoutError, asyncio.TimeoutError))
+ timed_out = isinstance(exc, TimeoutError)
raise
finally:
closure = scope.get(CONNECTION_OUTCOME_KEY)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/result.py b/ruoyi-fastapi-backend/plugins/core/runtime/result.py
index fa7c5e7df..7fed58831 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/result.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/result.py
@@ -1,7 +1,6 @@
from collections.abc import Mapping
from dataclasses import dataclass
-
-from typing_extensions import Self
+from typing import Self
from i18n.message import I18nMessage
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/startup.py b/ruoyi-fastapi-backend/plugins/core/runtime/startup.py
index abe32ca7d..f29cb77d8 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/startup.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/startup.py
@@ -313,7 +313,7 @@ async def prepare_enabled_plugin_catalogs(self, app: FastAPI, *, startup_write_e
for plugin in registry.list_enabled_plugins():
try:
CatalogRegistry.register_plugin(plugin.plugin_id, plugin.discovered_plugin.backend_path)
- except (OSError, ValueError, KeyError, TypeError) as exc: # noqa: PERF203 - 启动时逐插件隔离失败。
+ except (OSError, ValueError, KeyError, TypeError) as exc:
failures.add(plugin.plugin_id)
logger.error(f'插件词库加载失败:{plugin.plugin_id},{exc}')
if startup_write_enabled:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/precheck.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/precheck.py
index 607bba152..052e9b1d1 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/precheck.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/precheck.py
@@ -1,8 +1,7 @@
from dataclasses import dataclass
-from typing import TypeAlias
+from typing import Self, TypeAlias
from pydantic import Field
-from typing_extensions import Self
from plugins.core.runtime.support.payload.validation import (
DependencyItemPayload,
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/task_cleanup.py b/ruoyi-fastapi-backend/plugins/core/runtime/task_cleanup.py
index d25c9a960..fc49d2b90 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/task_cleanup.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/task_cleanup.py
@@ -32,16 +32,18 @@ def _finish_task(task: asyncio.Task[Any]) -> None:
async def cancel_plugin_tasks(
- tasks: Iterable[asyncio.Task[Any]], *, timeout: float = CANCEL_TIMEOUT_SECONDS
+ tasks: Iterable[asyncio.Task[Any]],
+ *,
+ grace_seconds: float = CANCEL_TIMEOUT_SECONDS,
) -> set[asyncio.Task[Any]]:
"""
并发取消并限时等待;等待者被取消时也保留未退出任务。
:param tasks: 本次需要回收的任务,不取消调用者自身
- :param timeout: 整批任务允许的取消等待秒数
+ :param grace_seconds: 整批任务允许的取消等待秒数
:return: 等待结束后仍未退出的任务
"""
- if not math.isfinite(timeout) or timeout <= 0:
+ if not math.isfinite(grace_seconds) or grace_seconds <= 0:
raise ValueError('任务取消等待时间必须大于零')
selected = set(tasks) - {asyncio.current_task()}
for task in selected:
@@ -49,7 +51,7 @@ async def cancel_plugin_tasks(
task.cancel()
try:
if selected:
- await asyncio.wait(selected, timeout=timeout)
+ await asyncio.wait(selected, timeout=grace_seconds)
finally:
for task in selected:
if task.done():
diff --git a/ruoyi-fastapi-backend/plugins/core/sdk/asgi.py b/ruoyi-fastapi-backend/plugins/core/sdk/asgi.py
index ebe614758..64a6a8db8 100644
--- a/ruoyi-fastapi-backend/plugins/core/sdk/asgi.py
+++ b/ruoyi-fastapi-backend/plugins/core/sdk/asgi.py
@@ -103,7 +103,7 @@ async def endpoint(request: Request) -> Any:
return await await_plugin_callback(callback, context, timeout=timeout)
except PermissionError as exc:
raise HTTPException(status_code=403, detail=str(exc)) from exc
- except asyncio.TimeoutError as exc:
+ except TimeoutError as exc:
raise HTTPException(status_code=504, detail='插件调用超时') from exc
return endpoint
diff --git a/ruoyi-fastapi-backend/plugins/core/sdk/definition.py b/ruoyi-fastapi-backend/plugins/core/sdk/definition.py
index f72f6ed15..161d4c253 100644
--- a/ruoyi-fastapi-backend/plugins/core/sdk/definition.py
+++ b/ruoyi-fastapi-backend/plugins/core/sdk/definition.py
@@ -1,6 +1,6 @@
import asyncio
import inspect
-from collections.abc import Callable, Mapping, Sequence
+from collections.abc import Callable, Coroutine, Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any
@@ -52,14 +52,14 @@ def validate(self, integration: str) -> None:
raise TypeError('register_models 必须可调用')
-async def await_plugin_callback(
+def await_plugin_callback(
callback: Callable[..., Any],
*args: Any,
timeout: float = 30.0,
kwargs: Mapping[str, Any] | None = None,
-) -> Any:
+) -> Coroutine[Any, Any, Any]:
"""
- 等待 Python 或原生 awaitable;同步入口必须立即返回。
+ 返回等待插件回调的协程。开始等待时才调用 Python 或原生入口。
超时只能取消异步等待,不能强制终止阻塞原生函数。平台不在线程池中执行
生命周期写操作,也不将同步返回值视为成功,以免事务结束后继续产生副作用。
@@ -68,9 +68,13 @@ async def await_plugin_callback(
:param args: 传给回调的位置参数
:param timeout: 异步等待超时时间,单位为秒
:param kwargs: 传给回调的关键字参数
- :return: 等待插件回调完成后的返回值
+ :return: 可直接 await 或交给 asyncio.create_task 的协程
"""
- result = callback(*args, **(kwargs or {}))
- if not inspect.isawaitable(result):
- raise TypeError('v2 插件异步回调必须立即返回 awaitable')
- return await asyncio.wait_for(result, timeout=timeout)
+
+ async def invoke() -> Any:
+ result = callback(*args, **(kwargs or {}))
+ if not inspect.isawaitable(result):
+ raise TypeError('v2 插件异步回调必须立即返回 awaitable')
+ return await asyncio.wait_for(result, timeout=timeout)
+
+ return invoke()
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/plugin.yaml b/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/plugin.yaml
index 0a62c690b..c3bc777df 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/plugin.yaml
+++ b/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/plugin.yaml
@@ -19,4 +19,4 @@ permissions:
name: 查看 ASGI 示例
compatibility:
hostApiVersion: ^1.3.0
- pythonVersion: '>=3.10'
+ pythonVersion: '>=3.11'
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/plugin.yaml b/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/plugin.yaml
index 197ae752a..40a4c83cc 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/plugin.yaml
+++ b/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/plugin.yaml
@@ -27,7 +27,7 @@ permissions:
name: 访问独立前端示例
compatibility:
hostApiVersion: ^1.4.0
- pythonVersion: '>=3.10'
+ pythonVersion: '>=3.11'
config:
items:
- key: greeting
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/README.md b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/README.md
index b11382d72..22e1ae7a4 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/README.md
+++ b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/README.md
@@ -2,7 +2,7 @@
`task_demo` 是 manifest v2 的 Python ASGI + 独立 bundle 业务示例,当前版本 `1.1.0`。页面提供新增、编辑、删除、状态筛选和分页;数据保存在宿主默认数据源的 `ruoyi_plugin_task_demo` 表中。它演示插件级共享任务清单:有查看权限的用户看到同一组任务,未实现个人、部门或租户数据隔离。
-源码位于 `plugins/examples/python/task_demo`,示例目录不参与运行时插件扫描。下面的命令均在后端根目录、已激活并安装宿主依赖的 Python 3.10–3.14 环境执行,适用于 Windows PowerShell、macOS 和 Linux;前端构建使用 Node.js 22。
+源码位于 `plugins/examples/python/task_demo`,示例目录不参与运行时插件扫描。下面的命令均在后端根目录、已激活并安装宿主依赖的 Python 3.11–3.14 环境执行,适用于 Windows PowerShell、macOS 和 Linux;前端构建使用 Node.js 22。
## 构建与测试
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/plugin.yaml b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/plugin.yaml
index 5c85237c5..62ddd05a6 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/plugin.yaml
+++ b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/plugin.yaml
@@ -37,7 +37,7 @@ permissions:
name: 编辑任务
compatibility:
hostApiVersion: ^1.4.0
- pythonVersion: '>=3.10'
+ pythonVersion: '>=3.11'
databases:
- mysql
- postgresql
diff --git a/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/Cargo.toml b/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/Cargo.toml
index 1d4326b1f..197e641d7 100644
--- a/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/Cargo.toml
+++ b/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/Cargo.toml
@@ -9,7 +9,7 @@ name = "_native"
crate-type = ["cdylib"]
[dependencies]
-pyo3 = { version = "0.29.2", features = ["abi3-py310"] }
+pyo3 = { version = "0.29.2", features = ["abi3-py311"] }
pyo3-async-runtimes = { version = "0.29.0", features = ["tokio-runtime"] }
[profile.release]
diff --git a/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/README.md b/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/README.md
index 982d58003..b5a51f97e 100644
--- a/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/README.md
+++ b/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/README.md
@@ -35,7 +35,7 @@ target/native-package/
rust_demo-1.0.0.zip
```
-构建器按当前解释器的 wheel tag 优先级选择发行包,校验名称、版本、Python 要求、已安装依赖及完整 RECORD SHA256,再展开至新目录。拒绝目录越界、链接、大小写冲突、未登记文件和超限解压。部署需选择与目标操作系统、架构和 Python 匹配的制品;Windows wheel 不能在 Linux 使用。本例声明 `abi3-py310`,仍需对实际运行平台分别验证。该构建脚本输出的目录 ZIP 不含发布者签名;签名及维护发布由下面的独立 CLI 完成。
+构建器按当前解释器的 wheel tag 优先级选择发行包,校验名称、版本、Python 要求、已安装依赖及完整 RECORD SHA256,再展开至新目录。拒绝目录越界、链接、大小写冲突、未登记文件和超限解压。部署需选择与目标操作系统、架构和 Python 匹配的制品;Windows wheel 不能在 Linux 使用。本例声明 `abi3-py311`,仍需对实际运行平台分别验证。该构建脚本输出的目录 ZIP 不含发布者签名;签名及维护发布由下面的独立 CLI 完成。
## 本地集成验证
@@ -61,7 +61,7 @@ cargo clippy --manifest-path plugins/examples/rust/rust_demo/Cargo.toml --locked
测试直接加载编译后的扩展,覆盖 ASGI、Router、原生 future、Python 协程桥、权限、异常、取消、lifespan 和真实 APScheduler 单次分发。数据库与登录使用替身;测试不会安装、启用插件或写入实际业务数据库。不设置环境变量时,真实原生测试明确跳过。
-仓库的 `.github/workflows/ci-native.yml` 配置 Windows/Linux、Python 3.10、3.11、3.12、3.13、3.14 构建测试矩阵。应以目标平台对应的实际构建与测试结果确认兼容性。
+仓库的 `.github/workflows/ci-native.yml` 配置 Windows/Linux、Python 3.11、3.12、3.13、3.14 构建测试矩阵。应以目标平台对应的实际构建与测试结果确认兼容性。
## 签名制品与维护发布
diff --git a/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/plugin.yaml b/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/plugin.yaml
index 543d6e50b..82843f5cf 100644
--- a/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/plugin.yaml
+++ b/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/plugin.yaml
@@ -32,4 +32,4 @@ permissions:
name: 通过 Rust 示例查看本人资料
compatibility:
hostApiVersion: ^1.3.0
- pythonVersion: '>=3.10'
+ pythonVersion: '>=3.11'
diff --git a/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/pyproject.toml b/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/pyproject.toml
index 0d10f7a18..0b6fa7fe7 100644
--- a/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/pyproject.toml
+++ b/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/pyproject.toml
@@ -5,7 +5,7 @@ build-backend = "maturin"
[project]
name = "ruoyi-plugin-rust-demo"
version = "1.0.0"
-requires-python = ">=3.10"
+requires-python = ">=3.11"
description = "RuoYi native ASGI plugin example"
[tool.maturin]
diff --git a/ruoyi-fastapi-backend/pyproject.toml b/ruoyi-fastapi-backend/pyproject.toml
index cb6b1a493..a195c5c75 100644
--- a/ruoyi-fastapi-backend/pyproject.toml
+++ b/ruoyi-fastapi-backend/pyproject.toml
@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
name = "ruoyi-fastapi-backend-cli"
version = "2.0.0"
description = "RuoYi-FastAPI backend internal CLI entrypoint"
-requires-python = ">=3.10"
+requires-python = ">=3.11"
[project.scripts]
ruoyi = "cli.main:main"
diff --git a/ruoyi-fastapi-backend/ruff.toml b/ruoyi-fastapi-backend/ruff.toml
index 23d788c1e..5d6399b8c 100644
--- a/ruoyi-fastapi-backend/ruff.toml
+++ b/ruoyi-fastapi-backend/ruff.toml
@@ -1,6 +1,6 @@
line-length = 120
show-fixes = true
-target-version = "py310"
+target-version = "py311"
unsafe-fixes = true
[lint]
diff --git a/ruoyi-fastapi-backend/scripts/migrate_job_fields.py b/ruoyi-fastapi-backend/scripts/migrate_job_fields.py
index 9535845e2..74ca349f2 100644
--- a/ruoyi-fastapi-backend/scripts/migrate_job_fields.py
+++ b/ruoyi-fastapi-backend/scripts/migrate_job_fields.py
@@ -302,7 +302,7 @@ def migrate_logs(connection: Connection) -> int:
try:
values[name] = parser(row[f'legacy_{name}'])
json.dumps(values[name], allow_nan=False)
- except (TypeError, ValueError): # noqa: PERF203
+ except (TypeError, ValueError):
# 旧字段原文仍保存在legacy列,不为无效历史参数构造可执行值。
values[name] = None
matched = re.search(r'任务ID: (\d+), 执行ID: ([0-9a-f]{32})(?:,|$)', row['job_message'] or '')
diff --git a/ruoyi-fastapi-backend/scripts/migrate_legacy_files.py b/ruoyi-fastapi-backend/scripts/migrate_legacy_files.py
index af53bdc98..df8dae595 100644
--- a/ruoyi-fastapi-backend/scripts/migrate_legacy_files.py
+++ b/ruoyi-fastapi-backend/scripts/migrate_legacy_files.py
@@ -5,7 +5,7 @@
import stat
import uuid
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from pathlib import Path
import aiofiles
@@ -147,7 +147,7 @@ def collect_legacy_files() -> tuple[list[LegacyFileInfo], int]:
extension=extension,
content_type=content_type,
file_size=signature.file_size,
- file_time=datetime.fromtimestamp(signature.modified_time_ns / 1_000_000_000, tz=timezone.utc),
+ file_time=datetime.fromtimestamp(signature.modified_time_ns / 1_000_000_000, tz=UTC),
signature=signature,
)
)
diff --git a/ruoyi-fastapi-backend/scripts/plugin_task_integration.py b/ruoyi-fastapi-backend/scripts/plugin_task_integration.py
index c5a001efa..aaa97d7fa 100644
--- a/ruoyi-fastapi-backend/scripts/plugin_task_integration.py
+++ b/ruoyi-fastapi-backend/scripts/plugin_task_integration.py
@@ -4,14 +4,14 @@
import shutil
import subprocess
import sys
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from http import HTTPStatus
from pathlib import Path
from typing import Any
TASK_PLUGIN_ID = 'task_demo'
LEGACY_TASK_ID = '0123456789abcdef0123456789abcdef'
-LEGACY_CREATED_AT = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)
+LEGACY_CREATED_AT = datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)
EXPECTED_MIGRATIONS = 2
diff --git a/ruoyi-fastapi-backend/scripts/verify_timezone_database.py b/ruoyi-fastapi-backend/scripts/verify_timezone_database.py
index d3b05fcfd..29e4afcc6 100644
--- a/ruoyi-fastapi-backend/scripts/verify_timezone_database.py
+++ b/ruoyi-fastapi-backend/scripts/verify_timezone_database.py
@@ -4,7 +4,7 @@
import json
import re
import sys
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta, timezone
from pathlib import Path
from uuid import uuid4
@@ -106,7 +106,7 @@ def initialize(source: DataSourceSettings, report: dict) -> DataSourceSettings:
with engine.connect() as connection:
value = connection.execute(text('SELECT create_time FROM sys_dept WHERE dept_id=100')).scalar_one()
if value.tzinfo is None:
- value = value.replace(tzinfo=timezone.utc)
+ value = value.replace(tzinfo=UTC)
assert before <= value <= TimezoneUtil.utc_now() + timedelta(seconds=1), 'Seed time is not UTC'
report['seed_time_utc'] = value.isoformat()
preferences = connection.execute(text('SELECT time_zone FROM sys_user')).scalars().all()
@@ -204,7 +204,7 @@ async def verify_drivers(source: DataSourceSettings, report: dict) -> None:
assert (await connection.execute(text(timezone_query))).scalar_one() in {'UTC', '+00:00'}
actual = (await connection.execute(select(probe.c.instant).order_by(probe.c.id))).scalars().all()
assert actual == [TimezoneUtil.to_utc_milliseconds(value) for value in values]
- assert all(value.tzinfo == timezone.utc for value in actual)
+ assert all(value.tzinfo == UTC for value in actual)
await connection.execute(probe.insert().values(id=ASYNC_PROBE_ID, instant=values[-1]))
await async_engine.dispose()
async with async_engine.connect() as connection:
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_app_ops_snapshots.py b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_app_ops_snapshots.py
index fb20c60fd..6591ba0ed 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_app_ops_snapshots.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_app_ops_snapshots.py
@@ -256,7 +256,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
'message': '核心运行依赖已安装',
'missingRequired': [],
'packages': {
- 'python': {'installed': True, 'version': '3.10.0'},
+ 'python': {'installed': True, 'version': '3.11.0'},
'fastapi': {'installed': True, 'version': '0.111.0'},
'sqlalchemy': {'installed': True, 'version': '2.0.0'},
'redis': {'installed': True, 'version': '5.0.0'},
@@ -277,7 +277,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
},
'cpu': {'cpuNum': 8, 'used': 21.5},
'mem': {'total': '16 GB', 'usage': 48.2},
- 'py': {'version': '3.10.0', 'runTime': '2天4小时', 'used': '256 MB', 'total': '1 GB'},
+ 'py': {'version': '3.11.0', 'runTime': '2天4小时', 'used': '256 MB', 'total': '1 GB'},
'sysFiles': [
{
'dirName': '/',
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_configs_dashboard_snapshots.py b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_configs_dashboard_snapshots.py
index b5e80d1e6..2107191e3 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_configs_dashboard_snapshots.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_configs_dashboard_snapshots.py
@@ -64,7 +64,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
'message': '核心运行依赖已安装',
'missingRequired': [],
'packages': {
- 'python': {'installed': True, 'version': '3.10.0'},
+ 'python': {'installed': True, 'version': '3.11.0'},
'fastapi': {'installed': True, 'version': '0.111.0'},
'sqlalchemy': {'installed': True, 'version': '2.0.0'},
'redis': {'installed': True, 'version': '5.0.0'},
diff --git a/ruoyi-fastapi-backend/tests/common/test_query_time.py b/ruoyi-fastapi-backend/tests/common/test_query_time.py
index 142988313..8d69f6e33 100644
--- a/ruoyi-fastapi-backend/tests/common/test_query_time.py
+++ b/ruoyi-fastapi-backend/tests/common/test_query_time.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from typing import Annotated
import pytest
@@ -48,8 +48,8 @@ def date_query(query: Annotated[ConfigPageQueryModel, Query()]) -> dict:
def test_instant_query_compares_instants_instead_of_offset_strings() -> None:
query = FileInfoQueryModel(beginTime='2026-08-28T10:00:00+08:00', endTime='2026-08-28T03:00:00Z')
assert TimezoneUtil.rfc3339_range_to_utc(query.begin_time, query.end_time) == (
- datetime(2026, 8, 28, 2, tzinfo=timezone.utc),
- datetime(2026, 8, 28, 3, tzinfo=timezone.utc),
+ datetime(2026, 8, 28, 2, tzinfo=UTC),
+ datetime(2026, 8, 28, 3, tzinfo=UTC),
)
with pytest.raises(ValidationError):
FileInfoQueryModel(beginTime='2026-08-28T03:00:00Z', endTime='2026-08-28T10:00:00+08:00')
@@ -59,8 +59,8 @@ def test_instant_query_compares_instants_instead_of_offset_strings() -> None:
@pytest.mark.parametrize(
('boundaries', 'expected_times'),
[
- ({'beginTime': '2026-08-28'}, [datetime(2026, 8, 27, 16, tzinfo=timezone.utc)]),
- ({'endTime': '2026-08-28'}, [datetime(2026, 8, 28, 16, tzinfo=timezone.utc)]),
+ ({'beginTime': '2026-08-28'}, [datetime(2026, 8, 27, 16, tzinfo=UTC)]),
+ ({'endTime': '2026-08-28'}, [datetime(2026, 8, 28, 16, tzinfo=UTC)]),
({}, []),
],
ids=['lower-only', 'upper-only', 'unbounded'],
diff --git a/ruoyi-fastapi-backend/tests/common/test_request_timezone.py b/ruoyi-fastapi-backend/tests/common/test_request_timezone.py
index 2b58ee554..49409c43e 100644
--- a/ruoyi-fastapi-backend/tests/common/test_request_timezone.py
+++ b/ruoyi-fastapi-backend/tests/common/test_request_timezone.py
@@ -1,5 +1,5 @@
import asyncio
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from io import BytesIO
import httpx
@@ -43,9 +43,7 @@ async def date_range(request: Request, preference: str = 'auto') -> dict:
)
bounds = sorted(value for value in params.values() if isinstance(value, datetime))
workbook = load_workbook(
- BytesIO(
- ExcelUtil.export_list2excel([{'at': datetime(2026, 3, 8, 7, 30, tzinfo=timezone.utc)}], {'at': '时间'})
- )
+ BytesIO(ExcelUtil.export_list2excel([{'at': datetime(2026, 3, 8, 7, 30, tzinfo=UTC)}], {'at': '时间'}))
)
key = await ApiCache(namespace='test')._build_cache_key(request)
return {
@@ -120,7 +118,7 @@ def test_background_exports_can_select_business_timezone_explicitly() -> None:
workbook = load_workbook(
BytesIO(
ExcelUtil.export_list2excel(
- [{'at': datetime(2026, 3, 8, 7, 30, tzinfo=timezone.utc)}], {'at': '时间'}, timezone_name='UTC'
+ [{'at': datetime(2026, 3, 8, 7, 30, tzinfo=UTC)}], {'at': '时间'}, timezone_name='UTC'
)
)
)
diff --git a/ruoyi-fastapi-backend/tests/common/test_types.py b/ruoyi-fastapi-backend/tests/common/test_types.py
index c3d2f2344..f6414be8f 100644
--- a/ruoyi-fastapi-backend/tests/common/test_types.py
+++ b/ruoyi-fastapi-backend/tests/common/test_types.py
@@ -1,4 +1,4 @@
-from datetime import date, datetime, time, timedelta, timezone
+from datetime import UTC, date, datetime, time, timedelta, timezone
import pytest
from pydantic import BaseModel, TypeAdapter, ValidationError
@@ -26,8 +26,8 @@ class TestApiUtcDateTime:
def test_aware_inputs_keep_the_same_instant(self, value: object) -> None:
model = TimestampModel(occurred_at=value)
- assert model.occurred_at == datetime(2026, 8, 28, 2, 30, 0, 123000, tzinfo=timezone.utc)
- assert model.occurred_at.tzinfo is timezone.utc
+ assert model.occurred_at == datetime(2026, 8, 28, 2, 30, 0, 123000, tzinfo=UTC)
+ assert model.occurred_at.tzinfo is UTC
assert model.model_dump(mode='json')['occurred_at'] == '2026-08-28T02:30:00.123Z'
assert model.model_dump_json() == '{"occurred_at":"2026-08-28T02:30:00.123Z"}'
@@ -73,7 +73,7 @@ def test_column_uses_the_database_time_representation(self, dialect: Dialect, ex
@pytest.mark.parametrize(
('dialect', 'stored_timezone'),
- [(mysql.dialect(), None), (postgresql.dialect(), timezone.utc), (sqlite.dialect(), None)],
+ [(mysql.dialect(), None), (postgresql.dialect(), UTC), (sqlite.dialect(), None)],
)
def test_database_roundtrip_preserves_utc_and_millisecond_precision(
self, dialect: Dialect, stored_timezone: timezone | None
@@ -85,8 +85,8 @@ def test_database_roundtrip_preserves_utc_and_millisecond_precision(
assert stored == datetime(2026, 8, 28, 2, 30, 0, 123000, tzinfo=stored_timezone)
assert stored.tzinfo is stored_timezone
restored = column_type.process_result_value(stored, dialect)
- assert restored == datetime(2026, 8, 28, 2, 30, 0, 123000, tzinfo=timezone.utc)
- assert restored.tzinfo is timezone.utc
+ assert restored == datetime(2026, 8, 28, 2, 30, 0, 123000, tzinfo=UTC)
+ assert restored.tzinfo is UTC
def test_rejects_naive_values(self) -> None:
with pytest.raises(ValueError, match='只接受携带时区信息'):
@@ -111,7 +111,7 @@ def test_valid_date_keeps_its_calendar_value(self, value: object) -> None:
'2026-02-29',
'20000229',
'2000-02-29T00:00:00Z',
- datetime(2000, 2, 29, tzinfo=timezone.utc),
+ datetime(2000, 2, 29, tzinfo=UTC),
951782400,
],
)
@@ -132,9 +132,7 @@ def test_valid_time_keeps_fractional_seconds(self, value: object) -> None:
assert result.tzinfo is None
assert adapter.dump_json(result) == b'"09:15:00.123456"'
- @pytest.mark.parametrize(
- 'value', ['09:15', '24:00:00', '36:00:00', '09:15:00Z', time(9, tzinfo=timezone.utc), 3600]
- )
+ @pytest.mark.parametrize('value', ['09:15', '24:00:00', '36:00:00', '09:15:00Z', time(9, tzinfo=UTC), 3600])
def test_incomplete_times_offsets_and_durations_are_rejected(self, value: object) -> None:
with pytest.raises(ValidationError, match='一天内时间'):
TypeAdapter(BusinessTime).validate_python(value)
diff --git a/ruoyi-fastapi-backend/tests/config/test_current_user_cache_transactions.py b/ruoyi-fastapi-backend/tests/config/test_current_user_cache_transactions.py
index 33ca18cd6..f9099466d 100644
--- a/ruoyi-fastapi-backend/tests/config/test_current_user_cache_transactions.py
+++ b/ruoyi-fastapi-backend/tests/config/test_current_user_cache_transactions.py
@@ -648,10 +648,9 @@ async def test_listener_failure_does_not_change_committed_database_result(
@pytest.mark.asyncio
-async def test_commit_invalidation_and_cleanup_support_python310(
+async def test_commit_invalidates_cache_and_closes_redis(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
- monkeypatch.delattr(asyncio, 'timeout', raising=False)
redis = SimpleNamespace(aclose=AsyncMock())
create = AsyncMock(return_value=redis)
invalidate = AsyncMock(return_value=True)
diff --git a/ruoyi-fastapi-backend/tests/config/test_database_registry.py b/ruoyi-fastapi-backend/tests/config/test_database_registry.py
index 91c25b408..e8f428d00 100644
--- a/ruoyi-fastapi-backend/tests/config/test_database_registry.py
+++ b/ruoyi-fastapi-backend/tests/config/test_database_registry.py
@@ -1,12 +1,12 @@
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from types import SimpleNamespace
+from typing import Self
from unittest.mock import AsyncMock, MagicMock, call
import pytest
from sqlalchemy import URL
from sqlalchemy.exc import OperationalError
-from typing_extensions import Self
from common.aspect.db_session import DBSessionDependency, get_db_session_provider
from config import database
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py
index 104b8a8ed..25d3f3eda 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py
@@ -47,33 +47,34 @@ async def test_two_processes_atomically_enforce_logical_job_limit(runtime: Runti
assert sorted(row.status for row in rows) == ['rejected', 'running']
-async def wait_for_process_file(path: Path, executor: TimedProcessPoolExecutor, timeout: float = 45) -> dict:
+async def wait_for_process_file(path: Path, executor: TimedProcessPoolExecutor) -> dict:
"""
等待真实进程进入业务函数
:param path: 进程启动标记文件路径
:param executor: 提供超时诊断的真实进程执行器
- :param timeout: 冷启动最长等待秒数,不作为业务执行耗时断言
:return: 进程启动信息
"""
- loop = asyncio.get_running_loop()
- deadline = loop.time() + timeout
+ startup_wait_seconds = 45
last_error = None
- while loop.time() < deadline:
- try:
- return json.loads(await asyncio.to_thread(path.read_text, encoding='utf-8'))
- except (FileNotFoundError, json.JSONDecodeError) as exc:
- last_error = type(exc).__name__
- await asyncio.sleep(0.02)
- processes = getattr(executor._pool, '_processes', None) or {}
- states = [
- {'pid': process.pid, 'alive': process.is_alive(), 'exitcode': process.exitcode}
- for process in processes.values()
- ]
- raise TimeoutError(
- f'process did not enter the task within {timeout}s; marker={path}; '
- f'processes={states}; broken={getattr(executor._pool, "_broken", None)}; last_read={last_error}'
- )
+ try:
+ async with asyncio.timeout(startup_wait_seconds):
+ while True:
+ try:
+ return json.loads(await asyncio.to_thread(path.read_text, encoding='utf-8'))
+ except (FileNotFoundError, json.JSONDecodeError) as exc:
+ last_error = type(exc).__name__
+ await asyncio.sleep(0.02)
+ except TimeoutError as exc:
+ processes = getattr(executor._pool, '_processes', None) or {}
+ states = [
+ {'pid': process.pid, 'alive': process.is_alive(), 'exitcode': process.exitcode}
+ for process in processes.values()
+ ]
+ raise TimeoutError(
+ f'process did not enter the task within {startup_wait_seconds}s; marker={path}; '
+ f'processes={states}; broken={getattr(executor._pool, "_broken", None)}; last_read={last_error}'
+ ) from exc
@pytest.mark.asyncio
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py
index 21b904cdd..aed1eec9c 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py
@@ -3,7 +3,7 @@
import pickle
import threading
from concurrent.futures import ThreadPoolExecutor
-from datetime import timedelta, timezone
+from datetime import UTC, timedelta
from unittest.mock import Mock, patch
import pytest
@@ -108,8 +108,8 @@ def receive(event: TimedJobExecutionEvent) -> None:
assert event.snapshot.invoke_target == job.func_ref
assert scheduler.get_job(job.id) is None
assert event.scheduled_run_time.utcoffset() == timedelta(0)
- assert event.start_time.tzinfo is timezone.utc
- assert event.end_time.tzinfo is timezone.utc
+ assert event.start_time.tzinfo is UTC
+ assert event.end_time.tzinfo is UTC
assert event.start_time >= event.scheduled_run_time
assert event.end_time >= event.start_time
assert event.run_duration_ms >= 0
@@ -184,7 +184,7 @@ async def test_scheduler_emits_one_standard_max_instances_event_and_preserves_re
if kind == 'process'
else TimedAsyncIOExecutor(on_rejected=SchedulerManager.scheduler_event_listener)
)
- scheduler = AsyncIOScheduler(executors={'default': executor}, timezone=timezone.utc)
+ scheduler = AsyncIOScheduler(executors={'default': executor}, timezone=UTC)
events = []
rejected = asyncio.Event()
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_persistence.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_persistence.py
index f6db19839..f230eb4d3 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_persistence.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_persistence.py
@@ -1,5 +1,5 @@
import asyncio
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from pathlib import Path
from unittest.mock import AsyncMock
@@ -67,7 +67,7 @@ async def verify_persistent_scheduler(
def build_scheduler() -> AsyncIOScheduler:
return AsyncIOScheduler(
- timezone=timezone.utc,
+ timezone=UTC,
jobstores={'default': SQLAlchemyJobStore(engine=engine, tablename='apscheduler_timezone_verify')},
executors={'default': TimedAsyncIOExecutor(manage_executions=True)},
)
@@ -107,7 +107,7 @@ def build_scheduler() -> AsyncIOScheduler:
assert SchedulerManager._jobs.is_config_current(restored, updated)
assert old_signature != SchedulerManager._jobs.trigger_signature(restored.trigger)
expected = MyCronTrigger.from_crontab(updated.cron_expression, updated.time_zone)
- start = datetime(2026, 11, 1, tzinfo=timezone.utc)
+ start = datetime(2026, 11, 1, tzinfo=UTC)
assert restored.trigger.get_next_fire_time(None, start) == expected.get_next_fire_time(None, start)
await assert_independent_manual_request(current, updated, sessions)
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py
index 022887ebd..b1fa9bea8 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py
@@ -1,7 +1,7 @@
import asyncio
import json
from collections.abc import AsyncIterator
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from unittest.mock import AsyncMock, patch
import pytest
@@ -17,7 +17,7 @@
@pytest_asyncio.fixture
async def jobs() -> AsyncIterator[SchedulerJobs]:
"""每个用例使用独立的内存调度器和同步缓存。"""
- scheduler = AsyncIOScheduler(timezone=timezone.utc)
+ scheduler = AsyncIOScheduler(timezone=UTC)
scheduler.start(paused=True)
try:
yield SchedulerJobs(scheduler)
@@ -53,7 +53,7 @@ async def test_timezone_only_update_rebuilds_trigger_and_failure_remains_retryab
job_id = str(info.job_id)
jobs.register_job(info)
original = jobs.get_job(job_id)
- changed_at = datetime(2026, 9, 9, tzinfo=timezone.utc)
+ changed_at = datetime(2026, 9, 9, tzinfo=UTC)
changed = info.model_copy(update={'time_zone': 'UTC', 'update_time': changed_at})
with (
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_common_file_security.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_common_file_security.py
index 555cc6af5..9b0e3343d 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_common_file_security.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_common_file_security.py
@@ -2,7 +2,7 @@
import io
import re
from collections.abc import AsyncGenerator
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
@@ -340,7 +340,7 @@ def test_upload_removes_file_when_metadata_write_fails(tmp_path: Path) -> None:
def test_upload_retries_name_collision_without_deleting_existing_file(tmp_path: Path) -> None:
- fixed_time = datetime(2026, 7, 19, 4, 0, 0, tzinfo=timezone.utc)
+ fixed_time = datetime(2026, 7, 19, 4, 0, 0, tzinfo=UTC)
existing_file = tmp_path / 'upload' / '2026' / '07' / '19' / 'report_20260719120000A001.txt'
existing_file.parent.mkdir(parents=True)
existing_file.write_bytes(b'existing-content')
@@ -542,7 +542,7 @@ def test_private_download_rejects_expired_file(tmp_path: Path, admin: bool) -> N
access_type='private',
upload_user_id=10,
owner_user_id=10,
- expire_time=datetime.now(timezone.utc) - timedelta(seconds=1),
+ expire_time=datetime.now(UTC) - timedelta(seconds=1),
storage_key='upload/2026/07/report_20260719120000A001.txt',
original_name='report.txt',
)
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_access_log.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_access_log.py
index 9f9aee6ca..22e9e5176 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_access_log.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_access_log.py
@@ -1,6 +1,6 @@
import asyncio
import json
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
@@ -49,7 +49,7 @@ def make_file_access_log() -> FileAccessLogModel:
userAgent='pytest',
bytesSent=FILE_SIZE,
operationDetail='{"newStatus":"active"}',
- accessTime=datetime(2026, 7, 19, 12, 0, 0, tzinfo=timezone.utc),
+ accessTime=datetime(2026, 7, 19, 12, 0, 0, tzinfo=UTC),
)
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_acl.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_acl.py
index bcfff90cd..f554332a7 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_acl.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_acl.py
@@ -1,5 +1,5 @@
import asyncio
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
@@ -91,7 +91,7 @@ def test_private_file_acl_allows_matching_user_role_or_department(
current_user,
make_file_info(),
FILE_ID,
- datetime.now(timezone.utc),
+ datetime.now(UTC),
)
)
@@ -109,7 +109,7 @@ def test_private_file_acl_does_not_apply_parent_department_without_include_child
current_user,
make_file_info(),
FILE_ID,
- datetime.now(timezone.utc),
+ datetime.now(UTC),
)
)
@@ -261,7 +261,7 @@ def test_private_file_acl_explicit_deny_overrides_uploader_and_allow_rule() -> N
current_user,
make_file_info(upload_user_id=20),
FILE_ID,
- datetime.now(timezone.utc),
+ datetime.now(UTC),
)
)
@@ -278,7 +278,7 @@ def test_private_file_acl_does_not_allow_uploader_when_compatibility_access_is_d
current_user,
make_file_info(upload_user_id=20, uploader_access_enabled='0'),
FILE_ID,
- datetime.now(timezone.utc),
+ datetime.now(UTC),
)
)
@@ -297,7 +297,7 @@ def test_private_file_acl_admin_or_owner_is_not_blocked_by_deny(current_user: Si
current_user,
file_info,
FILE_ID,
- datetime.now(timezone.utc),
+ datetime.now(UTC),
)
)
@@ -318,7 +318,7 @@ def test_save_file_acl_normalizes_department_scope_and_commits() -> None:
'subjectId': 100,
'effect': 'allow',
'includeChildren': True,
- 'expireTime': datetime.now(timezone.utc) + timedelta(days=1),
+ 'expireTime': datetime.now(UTC) + timedelta(days=1),
},
{
'subjectType': 'user',
@@ -453,7 +453,7 @@ def test_save_file_acl_rejects_duplicate_or_expired_entries() -> None:
'subjectType': 'user',
'subjectId': 20,
'effect': 'allow',
- 'expireTime': datetime.now(timezone.utc) - timedelta(seconds=1),
+ 'expireTime': datetime.now(UTC) - timedelta(seconds=1),
}
],
)
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_lifecycle_retention_execution.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_lifecycle_retention_execution.py
index 53a91a43f..e1c341d41 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_lifecycle_retention_execution.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_lifecycle_retention_execution.py
@@ -1,5 +1,5 @@
import asyncio
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
@@ -133,7 +133,7 @@ def test_purge_file_rejects_business_reference(tmp_path: Path) -> None:
def test_retention_scan_creates_expiring_and_expired_notices() -> None:
- current_time = datetime.now(timezone.utc)
+ current_time = datetime.now(UTC)
expired_file = make_file_info(expire_time=current_time - timedelta(days=1))
expiring_file = SimpleNamespace(
**{
@@ -264,7 +264,7 @@ def test_retention_policy_rejects_public_business_file() -> None:
def test_extend_file_retention_updates_terminal_references() -> None:
- current_time = datetime.now(timezone.utc)
+ current_time = datetime.now(UTC)
previous_expire_time = current_time + timedelta(days=1)
new_expire_time = current_time + timedelta(days=31)
file_info = make_file_info(expire_time=previous_expire_time)
@@ -313,7 +313,7 @@ def test_extend_file_retention_updates_terminal_references() -> None:
def test_dispose_expired_file_releases_expired_references() -> None:
- current_time = datetime.now(timezone.utc)
+ current_time = datetime.now(UTC)
expire_time = current_time - timedelta(days=1)
file_info = make_file_info(expire_time=expire_time)
reference = SimpleNamespace(
@@ -361,7 +361,7 @@ def test_dispose_expired_file_releases_expired_references() -> None:
def test_dispose_expired_file_rejects_active_reference() -> None:
- expire_time = datetime.now(timezone.utc) - timedelta(days=1)
+ expire_time = datetime.now(UTC) - timedelta(days=1)
file_info = make_file_info(expire_time=expire_time)
reference = SimpleNamespace(
reference_id=1,
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reconcile.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reconcile.py
index f9f039abb..500570a1b 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reconcile.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reconcile.py
@@ -1,7 +1,7 @@
import asyncio
import hashlib
import os
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
@@ -239,7 +239,7 @@ def test_reconcile_run_page_converts_database_field_names() -> None:
def test_reconcile_issue_page_calculates_actions_from_camel_case_rows() -> None:
current_user = SimpleNamespace(user=SimpleNamespace(admin=True, user_name='admin'))
- current_time = datetime(2026, 7, 26, 12, 0, 0, tzinfo=timezone.utc)
+ current_time = datetime(2026, 7, 26, 12, 0, 0, tzinfo=UTC)
issue_page = PageModel(
rows=[
{
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reference.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reference.py
index 98467fa43..20b774a14 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reference.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reference.py
@@ -1,5 +1,5 @@
import asyncio
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
@@ -49,7 +49,7 @@ def test_get_file_reference_list_includes_legacy_reference() -> None:
def test_get_file_reference_list_converts_orm_reference() -> None:
- create_time = datetime(2026, 7, 26, 10, 0, 0, tzinfo=timezone.utc)
+ create_time = datetime(2026, 7, 26, 10, 0, 0, tzinfo=UTC)
file_info = {
'file_id': FILE_ID,
'business_type': None,
@@ -194,7 +194,7 @@ def test_remove_business_file_references_does_not_lock_files() -> None:
def test_replace_business_file_references_applies_retention_policy() -> None:
query_db = make_query_db()
- create_time = datetime(2026, 7, 23, 10, 0, 0, tzinfo=timezone.utc)
+ create_time = datetime(2026, 7, 23, 10, 0, 0, tzinfo=UTC)
policy = FileRetentionPolicyModel(businessType='notice', retentionDays=30)
with (
patch.object(
@@ -230,8 +230,8 @@ def test_replace_business_file_references_applies_retention_policy() -> None:
def test_replace_business_file_references_preserves_extended_expiration() -> None:
- policy_expire_time = datetime(2026, 8, 22, 10, 0, 0, tzinfo=timezone.utc)
- extended_expire_time = datetime(2027, 7, 23, 10, 0, 0, tzinfo=timezone.utc)
+ policy_expire_time = datetime(2026, 8, 22, 10, 0, 0, tzinfo=UTC)
+ extended_expire_time = datetime(2027, 7, 23, 10, 0, 0, tzinfo=UTC)
old_reference = SysFileReference(
file_id=FILE_ID,
business_type='notice',
@@ -254,8 +254,8 @@ def test_replace_business_file_references_preserves_extended_expiration() -> Non
def test_refresh_file_expire_times_uses_latest_reference_expiration() -> None:
- first_expire_time = datetime(2026, 8, 1, tzinfo=timezone.utc)
- last_expire_time = datetime(2026, 9, 1, tzinfo=timezone.utc)
+ first_expire_time = datetime(2026, 8, 1, tzinfo=UTC)
+ last_expire_time = datetime(2026, 9, 1, tzinfo=UTC)
file_info = SimpleNamespace(
file_id=FILE_ID,
business_type=None,
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_service.py
index 7a4b68e45..0edd7aab2 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_service.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
import pytest
from sqlalchemy import func, select, text
@@ -57,7 +57,7 @@ def _notice(notice_id: int, status: str = '0') -> SysNotice:
notice_content=f'内容{notice_id}'.encode(),
status=status,
create_by='admin',
- create_time=datetime(2026, 3, notice_id, tzinfo=timezone.utc),
+ create_time=datetime(2026, 3, notice_id, tzinfo=UTC),
)
@@ -135,10 +135,10 @@ async def test_get_notice_read_user_list_supports_search_and_pagination() -> Non
)
session.add_all(
[
- SysNoticeRead(notice_id=1, user_id=1, read_time=datetime(2026, 7, 30, 10, 0, tzinfo=timezone.utc)),
- SysNoticeRead(notice_id=1, user_id=2, read_time=datetime(2026, 7, 30, 11, 0, tzinfo=timezone.utc)),
- SysNoticeRead(notice_id=1, user_id=3, read_time=datetime(2026, 7, 30, 12, 0, tzinfo=timezone.utc)),
- SysNoticeRead(notice_id=2, user_id=1, read_time=datetime(2026, 7, 30, 13, 0, tzinfo=timezone.utc)),
+ SysNoticeRead(notice_id=1, user_id=1, read_time=datetime(2026, 7, 30, 10, 0, tzinfo=UTC)),
+ SysNoticeRead(notice_id=1, user_id=2, read_time=datetime(2026, 7, 30, 11, 0, tzinfo=UTC)),
+ SysNoticeRead(notice_id=1, user_id=3, read_time=datetime(2026, 7, 30, 12, 0, tzinfo=UTC)),
+ SysNoticeRead(notice_id=2, user_id=1, read_time=datetime(2026, 7, 30, 13, 0, tzinfo=UTC)),
]
)
await session.commit()
diff --git a/ruoyi-fastapi-backend/tests/module_generator/dao/test_gen_dao.py b/ruoyi-fastapi-backend/tests/module_generator/dao/test_gen_dao.py
index 31438c8f3..7b404012e 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/dao/test_gen_dao.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/dao/test_gen_dao.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -11,7 +11,7 @@
TABLE_ID = 7
COLUMN_ID = 9
-CLIENT_AUDIT_TIME = datetime(2000, 1, 1, tzinfo=timezone.utc)
+CLIENT_AUDIT_TIME = datetime(2000, 1, 1, tzinfo=UTC)
@pytest.mark.asyncio
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py b/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
index c9f5f442d..88c3f3c39 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
@@ -1,7 +1,7 @@
import importlib.util
import json
import sys
-from datetime import date, time, timezone
+from datetime import UTC, date, time
from pathlib import Path
from types import ModuleType, SimpleNamespace
from unittest.mock import patch
@@ -191,7 +191,7 @@ async def test_generated_import_crud_and_query(
assert result.birthday == date(2000, 2, 29)
assert result.opening_time == time(9, 15, 0, 123000)
instant = result.timedetail_list[0].occurred_at if category == 'sub' else result.occurred_at
- assert instant.tzinfo == timezone.utc
+ assert instant.tzinfo == UTC
assert instant.microsecond == (456000 if category == 'sub' else 123000)
serialized = vo.ItemModel.model_validate(result).model_dump(mode='json', by_alias=True)
assert serialized['birthday'] == '2000-02-29'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_authorization_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_authorization_controller.py
index 697369835..896fed4fe 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_authorization_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_authorization_controller.py
@@ -1,6 +1,6 @@
import asyncio
import time
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from typing import Any
@@ -135,7 +135,7 @@ async def test_authorize_max_age_discards_stale_sso(monkeypatch: pytest.MonkeyPa
user_id=2,
subject_id='11111111-1111-4111-8111-111111111111',
auth_version=1,
- auth_time=datetime.now(timezone.utc) - timedelta(seconds=30),
+ auth_time=datetime.now(UTC) - timedelta(seconds=30),
)
async def load_stale(*args: object, **kwargs: object) -> Any:
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_interaction_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_interaction_controller.py
index 05adb4824..7bb7ca3c0 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_interaction_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_interaction_controller.py
@@ -1,6 +1,6 @@
import json
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock
@@ -535,7 +535,7 @@ async def test_consent_commit_then_redis_cas_failure_compensates_persisted_grant
granted_resources=(),
client_policy_version=1,
status='active',
- consented_at=datetime.now(timezone.utc),
+ consented_at=datetime.now(UTC),
expires_at=None,
revoked_at=None,
revoke_reason=None,
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_audit_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_audit_controller.py
index eccf974ff..b07f05e73 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_audit_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_audit_controller.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from http import HTTPStatus
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -72,7 +72,7 @@ async def test_audit_list_uses_real_total_and_safe_projection(monkeypatch: pytes
subject_id='s',
sid='sid',
failure_code='invalid_client',
- create_time=datetime.now(timezone.utc),
+ create_time=datetime.now(UTC),
detail={'access_token': 'redact'},
),
SimpleNamespace(
@@ -86,7 +86,7 @@ async def test_audit_list_uses_real_total_and_safe_projection(monkeypatch: pytes
subject_id='s',
sid='sid',
failure_code=None,
- create_time=datetime.now(timezone.utc),
+ create_time=datetime.now(UTC),
detail={'password': 'redact'},
),
]
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oidc_key_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oidc_key_controller.py
index 7e9d8916f..12093645d 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oidc_key_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oidc_key_controller.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from types import SimpleNamespace
import pytest
@@ -119,7 +119,7 @@ async def list_page(*args: object, **kwargs: object) -> tuple[list[object], int]
monkeypatch.setattr(
OidcRuntimeService,
'inspect_readiness',
- lambda db: _async_readiness(OidcReadiness(False, False, 'disabled', datetime.now(timezone.utc))),
+ lambda db: _async_readiness(OidcReadiness(False, False, 'disabled', datetime.now(UTC))),
)
response = await list_oidc_keys(_Db())
assert b'"enabled":false' in response.body
diff --git a/ruoyi-fastapi-backend/tests/module_identity/dao/test_grant_policy_dao.py b/ruoyi-fastapi-backend/tests/module_identity/dao/test_grant_policy_dao.py
index e84aa47b5..688f987f3 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/dao/test_grant_policy_dao.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/dao/test_grant_policy_dao.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
@@ -14,7 +14,7 @@ async def test_valid_grant_requires_active_unexpired_and_current_client_policy(
data_session: AsyncSession,
) -> None:
"""验证 Grant 过期或 Client 策略版本变化后不再视为有效。"""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
client = SysOAuthClient(
client_pk=4101,
client_id='grant-policy-client',
diff --git a/ruoyi-fastapi-backend/tests/module_identity/dao/test_oidc_key_dao.py b/ruoyi-fastapi-backend/tests/module_identity/dao/test_oidc_key_dao.py
index 30725571e..2693e02d0 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/dao/test_oidc_key_dao.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/dao/test_oidc_key_dao.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from typing import Any
import pytest
@@ -11,7 +11,7 @@
def _key(kid: str, status: str = 'pending') -> SysOidcSigningKey:
"""构造带引用私钥材料的测试密钥。"""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
return SysOidcSigningKey(
kid=kid,
alg='RS256',
diff --git a/ruoyi-fastapi-backend/tests/module_identity/dao/test_refresh_token_dao.py b/ruoyi-fastapi-backend/tests/module_identity/dao/test_refresh_token_dao.py
index f30fafc8e..5a92cdc3c 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/dao/test_refresh_token_dao.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/dao/test_refresh_token_dao.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
@@ -35,7 +35,7 @@ def _token(token_id: str, status: str, now: datetime, idle_expires_at: datetime)
@pytest.mark.asyncio
async def test_refresh_family_lock_rotation_and_reuse_distribution(data_session: AsyncSession) -> None:
"""验证 Family 查询、单 Token 轮换和重放后的状态分布。"""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
data_session.add_all(
[
SysUser(user_id=3001, user_name='refresh', nick_name='Refresh', status='0', del_flag='0'),
@@ -79,7 +79,7 @@ async def test_refresh_family_lock_rotation_and_reuse_distribution(data_session:
family = await OAuthTokenDao.lock_family(data_session, 'family-1')
assert [token.token_id for token in family] == ['token-1', 'token-2']
- injected_now = datetime(2026, 8, 24, 5, 6, 7, tzinfo=timezone.utc)
+ injected_now = datetime(2026, 8, 24, 5, 6, 7, tzinfo=UTC)
assert await OAuthTokenDao.mark_used(data_session, 'token-1', 'token-2', now=injected_now)
assert (await OAuthTokenDao.get_by_token_id(data_session, 'token-1')).last_used_at == injected_now
changed = await OAuthTokenDao.refresh_token_family_reuse(data_session, 'family-1', 'token-1', now=injected_now)
@@ -92,7 +92,7 @@ async def test_refresh_family_lock_rotation_and_reuse_distribution(data_session:
@pytest.mark.asyncio
async def test_refresh_expire_due_handles_idle_and_absolute_expiry(data_session: AsyncSession) -> None:
"""验证闲置和绝对期限任一到期都会使 Active Token 过期。"""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
data_session.add_all(
[
SysUser(user_id=3001, user_name='expire', nick_name='Expire', status='0', del_flag='0'),
diff --git a/ruoyi-fastapi-backend/tests/module_identity/models/test_oidc_key_vo.py b/ruoyi-fastapi-backend/tests/module_identity/models/test_oidc_key_vo.py
index 8611a8e0a..4c57bb003 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/models/test_oidc_key_vo.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/models/test_oidc_key_vo.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
import pytest
from pydantic import ValidationError
@@ -32,5 +32,5 @@ def test_rotation_request_rejects_missing_timezone(value: object) -> None:
def test_rotation_request_normalizes_offset_to_utc() -> None:
model = OidcKeyRotateModel(kid='key-1', publishAt='2026-08-28T10:00:00+08:00')
- assert model.publish_at == datetime(2026, 8, 28, 2, 0, tzinfo=timezone.utc)
+ assert model.publish_at == datetime(2026, 8, 28, 2, 0, tzinfo=UTC)
assert model.model_dump(mode='json', by_alias=True)['publishAt'] == '2026-08-28T02:00:00.000Z'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_jwt_profile.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_jwt_profile.py
index 55fc6de4f..45ec5eb05 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_jwt_profile.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_jwt_profile.py
@@ -1,5 +1,5 @@
import math
-from datetime import datetime, timezone
+from datetime import UTC, datetime
import jwt
import pytest
@@ -24,7 +24,7 @@ def key_pair() -> tuple[object, object]:
def _now() -> int:
- return int(datetime.now(timezone.utc).timestamp())
+ return int(datetime.now(UTC).timestamp())
def test_access_profile_requires_at_jwt_and_checks_audience(key_pair: tuple[object, object]) -> None:
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_audit_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_audit_service.py
index fe6d96710..920cb424c 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_audit_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_audit_service.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from io import BytesIO
from types import SimpleNamespace
@@ -114,7 +114,7 @@ async def test_audit_uses_field_whitelist_and_caller_commit_boundary(audit_sessi
@pytest.mark.asyncio
async def test_audit_retention_moves_old_events_to_archive(audit_session: AsyncSession) -> None:
"""超过在线保留期的审计事件必须转入归档表后再删除。"""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
await AuditService.record(audit_session, 'old_event', 'success', create_time=now - timedelta(days=181))
await AuditService.record(audit_session, 'fresh_event', 'success', create_time=now)
@@ -144,7 +144,7 @@ async def test_audit_admin_reads_project_safe_models_and_export(monkeypatch: pyt
sid='sid-1',
ip_address='127.0.0.1',
failure_code=None,
- create_time=datetime.now(timezone.utc),
+ create_time=datetime.now(UTC),
)
calls: list[dict[str, object]] = []
@@ -189,7 +189,7 @@ async def test_audit_export_serializes_stored_utc_in_request_timezone(
audit_session,
'export_timezone',
'success',
- create_time=datetime(2026, 8, 28, 10, 30, 0, 123000, tzinfo=timezone.utc),
+ create_time=datetime(2026, 8, 28, 10, 30, 0, 123000, tzinfo=UTC),
detail={'private_note': 'not-for-export', 'access_token': 'hidden'},
)
await audit_session.commit()
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_service.py
index 2137004de..710e638df 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_service.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
@@ -292,7 +292,7 @@ async def test_prompt_none_preserves_context_and_requires_valid_grant(data_sessi
assert context.requires_consent is True
assert AuthorizationService.consent_is_satisfied(context, None) is False
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
grant = SysOAuthGrant(
grant_id='authorization-grant',
user_id=7001,
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_claim_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_claim_service.py
index 24745e5c9..4dfa0cef0 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_claim_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_claim_service.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
import pytest
@@ -63,7 +63,7 @@ def test_openid_fails_closed_when_subject_or_sub_policy_is_missing(
def test_updated_at_is_numeric_date_and_roles_are_role_keys() -> None:
"""本地更新时间输出 NumericDate,角色查询语句使用 role_key。"""
- user = {'subject_id': 'stable-sub', 'update_time': datetime(1970, 1, 1, 0, 0, 1, tzinfo=timezone.utc)}
+ user = {'subject_id': 'stable-sub', 'update_time': datetime(1970, 1, 1, 0, 0, 1, tzinfo=UTC)}
claims = ClaimService.build_claims(
user,
{'openid', 'profile', 'roles'},
@@ -75,5 +75,5 @@ def test_updated_at_is_numeric_date_and_roles_are_role_keys() -> None:
['sub', 'updated_at', 'roles'],
roles=['admin_key'],
)
- assert claims['updated_at'] == int(datetime(1970, 1, 1, 0, 0, 1, tzinfo=timezone.utc).timestamp())
+ assert claims['updated_at'] == int(datetime(1970, 1, 1, 0, 0, 1, tzinfo=UTC).timestamp())
assert claims['roles'] == ['admin_key']
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_consent_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_consent_service.py
index eb0adb950..0f8ab3b76 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_consent_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_consent_service.py
@@ -1,5 +1,5 @@
from dataclasses import replace
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
import pytest
from sqlalchemy import select
@@ -99,7 +99,7 @@ def test_denial_is_a_verified_redirect_and_trusted_client_does_not_skip_consent(
def test_prompt_consent_disables_grant_based_skip() -> None:
"""验证 prompt=consent 强制显示同意页,即使已有 Grant 也不能静默跳过。"""
context = _context(prompt='consent')
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
grant = SysOAuthGrant(
grant_id='consent-grant',
user_id=8001,
@@ -181,7 +181,7 @@ async def test_remember_consent_merges_grant_without_commit(data_session: AsyncS
@pytest.mark.asyncio
async def test_compensation_does_not_restore_concurrently_revoked_grant(data_session: AsyncSession) -> None:
"""补偿 CAS 不得覆盖管理员在提交后执行的 Grant 撤销。"""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
user = SysUser(user_id=8002, user_name='race-user', nick_name='Race User', status='0', del_flag='0')
client = SysOAuthClient(
client_pk=8002,
@@ -244,7 +244,7 @@ async def test_compensation_does_not_restore_concurrently_revoked_grant(data_ses
@pytest.mark.asyncio
async def test_compensation_does_not_revoke_concurrently_updated_new_grant(data_session: AsyncSession) -> None:
"""新建 Grant 的撤销补偿不得覆盖另一会话的更新,并记录高风险审计。"""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
user = SysUser(user_id=8003, user_name='new-race-user', nick_name='New Race User', status='0', del_flag='0')
client = SysOAuthClient(
client_pk=8003,
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_credential_authentication_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_credential_authentication_service.py
index 001c4933b..97fde5bc4 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_credential_authentication_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_credential_authentication_service.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
@@ -201,7 +201,7 @@ async def test_oidc_initial_and_expired_password_flags_handle_naive_and_aware_da
@pytest.mark.asyncio
async def test_oidc_expired_aware_password_is_reported_without_datetime_error() -> None:
redis = _Redis({'sys_config:sys.account.passwordValidateDays': '30'})
- old_date = datetime.now(timezone.utc) - timedelta(days=31)
+ old_date = datetime.now(UTC) - timedelta(days=31)
with (
patch.object(OidcConfig, 'oidc_token_hash_pepper', 'p' * 32),
patch(
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_security_event_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_security_event_service.py
index d89964110..12b4c6b62 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_security_event_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_security_event_service.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
import pytest
import pytest_asyncio
@@ -15,7 +15,7 @@
IdentitySecurityEventService,
)
-_NOW = datetime(2026, 8, 24, 8, 0, tzinfo=timezone.utc)
+_NOW = datetime(2026, 8, 24, 8, 0, tzinfo=UTC)
_INITIAL_VERSION = 3
_PASSWORD_REFRESH_COUNT = 2
_CLAIM_USER_ID = 8
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_interaction_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_interaction_service.py
index 349ca3ded..8d6c54e26 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_interaction_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_interaction_service.py
@@ -1,5 +1,5 @@
import json
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from unittest.mock import AsyncMock
import pytest
@@ -214,7 +214,7 @@ async def test_transition_rejects_duplicate_scope_and_incomplete_identity() -> N
def test_max_age_decision_uses_project_local_time() -> None:
"""验证 max_age 使用项目约定的本地无时区时间。"""
- now = datetime(2026, 8, 24, 13, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 8, 24, 13, 0, tzinfo=UTC)
assert OidcUtil.requires_reauthentication(now - timedelta(seconds=10), 5, now) is True
assert OidcUtil.requires_reauthentication(now - timedelta(seconds=2), 5, now) is False
assert OidcUtil.requires_reauthentication(now, 5, now) is False
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_introspection_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_introspection_service.py
index c5fed228c..29092617b 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_introspection_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_introspection_service.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
import pytest
@@ -144,7 +144,7 @@ async def client_lookup(*_args: object, **_kwargs: object) -> SimpleNamespace:
await redis.set('oidc:revoked_jti:jti-1', '1', ex=60)
result = await IntrospectionService.introspect(
- object(), redis, 'signed-access', _principal(), now=datetime.now(timezone.utc)
+ object(), redis, 'signed-access', _principal(), now=datetime.now(UTC)
)
assert result == {'active': False}
@@ -261,7 +261,7 @@ async def test_access_user_state_rejects_each_real_time_failure(
}
assert not await IntrospectionService._access_user_state(
- db, claims, _client(), ['https://api.example'], datetime.now(timezone.utc)
+ db, claims, _client(), ['https://api.example'], datetime.now(UTC)
)
@@ -333,7 +333,7 @@ async def test_refresh_introspection_rechecks_identity_session_grant_and_resourc
client.client_pk = 20
client.client_id = 'business-a'
token = 'rt1.token-0003.' + ('A' * 43)
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
row = SimpleNamespace(
token_id='token-0003',
token_hash='',
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_key_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_key_service.py
index 328ee2d64..6ae13984d 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_key_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_key_service.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -76,7 +76,7 @@ def _record(tmp_path: Path, *, status: str = 'active', matching: bool = True) ->
key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
)
- now = datetime.now(tz=timezone.utc)
+ now = datetime.now(tz=UTC)
return SimpleNamespace(
kid='k1',
alg='RS256',
@@ -229,7 +229,7 @@ async def failed_audit(*args: object, **kwargs: object) -> None:
@pytest.mark.asyncio
async def test_list_due_pending_filters_schedule_and_algorithm(data_session: AsyncSession) -> None:
"""到期查询只返回 RS256、pending 且两个时间点均已到达的密钥。"""
- now = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ now = datetime(2026, 1, 1, tzinfo=UTC)
rows = [
SysOidcSigningKey(
kid='due',
@@ -362,7 +362,7 @@ async def test_management_key_bootstrap_is_available_when_oidc_disabled(data_ses
row = await KeyService.create_pending_key(
data_session,
kid='bootstrap-1',
- publish_at=datetime.now(timezone.utc) + timedelta(minutes=1),
+ publish_at=datetime.now(UTC) + timedelta(minutes=1),
actor='admin',
)
assert row.status == 'pending'
@@ -377,20 +377,20 @@ async def test_pending_key_times_are_stored_and_returned_in_utc(data_session: As
await KeyService.create_pending_key(
data_session,
kid='timezone-normalized',
- publish_at=datetime(2026, 8, 27, 17, 37, 37, tzinfo=timezone.utc),
- activate_at=datetime(2026, 8, 27, 17, 38, 31, tzinfo=timezone.utc),
+ publish_at=datetime(2026, 8, 27, 17, 37, 37, tzinfo=UTC),
+ activate_at=datetime(2026, 8, 27, 17, 38, 31, tzinfo=UTC),
actor='admin',
- now=datetime(2026, 8, 27, 17, 30, tzinfo=timezone.utc),
+ now=datetime(2026, 8, 27, 17, 30, tzinfo=UTC),
)
await data_session.commit()
data_session.expunge_all()
row = (await data_session.execute(select(SysOidcSigningKey))).scalar_one()
- assert row.publish_at == datetime(2026, 8, 27, 17, 37, 37, tzinfo=timezone.utc)
- assert row.signing_start_at == datetime(2026, 8, 27, 17, 38, 31, tzinfo=timezone.utc)
+ assert row.publish_at == datetime(2026, 8, 27, 17, 37, 37, tzinfo=UTC)
+ assert row.signing_start_at == datetime(2026, 8, 27, 17, 38, 31, tzinfo=UTC)
view = OidcKeyManagementService.view(row)
- assert view['publishAt'] == datetime(2026, 8, 27, 17, 37, 37, tzinfo=timezone.utc)
- assert view['signingStartAt'] == datetime(2026, 8, 27, 17, 38, 31, tzinfo=timezone.utc)
+ assert view['publishAt'] == datetime(2026, 8, 27, 17, 37, 37, tzinfo=UTC)
+ assert view['signingStartAt'] == datetime(2026, 8, 27, 17, 38, 31, tzinfo=UTC)
@pytest.mark.asyncio
@@ -399,7 +399,7 @@ async def test_management_bootstrap_is_idempotent_and_activates_first_key(data_s
config = _config()
config.oidc_enabled = False
config.oidc_signing_key_encryption_key = 'e' * 32
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
first, first_created = await OidcKeyManagementService.bootstrap(
data_session,
@@ -457,7 +457,7 @@ async def test_real_session_rotation_persists_state_and_injected_time(
data_session: AsyncSession, tmp_path: Path
) -> None:
"""真实 AsyncSession 轮换后恰有一个 active 且窗口和时间准确。"""
- now = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ now = datetime(2026, 1, 1, tzinfo=UTC)
old = _record(tmp_path)
new = _record(tmp_path)
new.kid = 'new'
@@ -492,7 +492,7 @@ async def test_manual_activation_can_override_future_signing_schedule(
data_session: AsyncSession, tmp_path: Path
) -> None:
"""管理员明确确认后可提前启用已公开的 pending 密钥。"""
- now = datetime.now(tz=timezone.utc)
+ now = datetime.now(tz=UTC)
target = _record(tmp_path, status='pending')
target.publish_at = now - timedelta(minutes=5)
target.signing_start_at = now + timedelta(hours=1)
@@ -510,7 +510,7 @@ async def test_manual_activation_can_override_future_signing_schedule(
@pytest.mark.asyncio
async def test_real_session_rotation_rolls_back_on_key_mismatch(data_session: AsyncSession, tmp_path: Path) -> None:
"""候选私钥失败时真实事务回滚,旧 active 状态保持不变。"""
- now = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ now = datetime(2026, 1, 1, tzinfo=UTC)
old = _record(tmp_path)
new = _record(tmp_path, matching=False)
new.kid = 'new'
@@ -534,7 +534,7 @@ async def test_real_session_rotation_rolls_back_on_key_mismatch(data_session: As
@pytest.mark.asyncio
async def test_jwks_filters_private_jwk_fields(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""JWKS 始终只输出公开字段,即使数据库 JSON 被污染。"""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
record = _record(tmp_path)
record.publish_at = now - timedelta(seconds=1)
record.public_jwk['d'] = 'secret'
@@ -562,7 +562,7 @@ async def published(*args: object, **kwargs: object) -> list[SimpleNamespace]:
@pytest.mark.asyncio
async def test_jwks_excludes_keys_outside_publish_window(monkeypatch: pytest.MonkeyPatch) -> None:
"""JWKS 不发布尚未到 publish_at 或已过 remove_from_jwks_at 的密钥。"""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
base = {
'kty': 'RSA',
'use': 'sig',
@@ -601,7 +601,7 @@ async def published(*args: object, **kwargs: object) -> list[SimpleNamespace]:
@pytest.mark.asyncio
async def test_jwks_rejects_malformed_rsa_jwk(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""非法 RSA n/e 不能污染 JWKS,服务选择 fail-closed。"""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
record = _record(tmp_path)
record.publish_at = now - timedelta(seconds=1)
record.public_jwk['n'] = 'not-a-rsa-modulus'
@@ -620,7 +620,7 @@ async def test_activation_validates_pending_private_key_before_state_change(
) -> None:
"""候选密钥公私钥不匹配时不得调用状态切换。"""
target = _record(tmp_path, status='pending', matching=False)
- target.publish_at = datetime.now(timezone.utc) - timedelta(seconds=1)
+ target.publish_at = datetime.now(UTC) - timedelta(seconds=1)
old = SimpleNamespace(kid='old', status='active')
changed = False
@@ -652,7 +652,7 @@ async def test_activation_retains_old_key_for_max_overlap_window(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""轮换将旧 active 置为 retiring,并覆盖 overlap 与 Token 安全窗口的较大值。"""
- now = datetime.now(tz=timezone.utc)
+ now = datetime.now(tz=UTC)
target = _record(tmp_path, status='pending')
target.publish_at = now - timedelta(seconds=1)
old = SimpleNamespace(kid='old', status='active', remove_from_jwks_at=None)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_logout.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_logout.py
index 824ad11b2..ef0f16abf 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_logout.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_logout.py
@@ -1,8 +1,9 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from types import SimpleNamespace
from typing import Any
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, create_autospec
+import httpcore
import httpx
import jwt
import pytest
@@ -41,7 +42,7 @@
@pytest.fixture
def now() -> datetime:
"""每个用例执行时获取时间,避免等待前序测试期间令牌过期。"""
- return datetime.now(timezone.utc)
+ return datetime.now(UTC)
@pytest.fixture(autouse=True)
@@ -499,37 +500,10 @@ async def audit(event: str, _uri: str, _client_id: str, _sid: str, **kwargs: obj
async def test_pinned_transport_uses_approved_ip_and_preserves_origin_host(monkeypatch: pytest.MonkeyPatch) -> None:
"""Pinned transport 只拨批准 IP,同时保留注册域名的 Host 和 TLS SNI。"""
- class NetworkStream:
- def __init__(self) -> None:
- self.writes: list[bytes] = []
- self.server_hostname: str | None = None
- self.response_sent = False
-
- async def read(self, _max_bytes: int, timeout: float | None = None) -> bytes:
- if self.response_sent:
- return b''
- self.response_sent = True
- return b'HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK'
-
- async def write(self, buffer: bytes, timeout: float | None = None) -> None:
- self.writes.append(buffer)
-
- async def start_tls(
- self,
- ssl_context: object,
- server_hostname: str | None = None,
- timeout: float | None = None,
- ) -> 'NetworkStream':
- self.server_hostname = server_hostname
- return self
-
- async def aclose(self) -> None:
- return None
-
- def get_extra_info(self, _info: str) -> None:
- return None
-
- stream = NetworkStream()
+ stream = create_autospec(httpcore.AsyncNetworkStream, instance=True)
+ stream.read.side_effect = [b'HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK', b'']
+ stream.start_tls.return_value = stream
+ stream.get_extra_info.return_value = None
transport = PinnedHttpxTransport('client.example', {'203.0.113.7'})
backend = transport._pool._network_backend
connect = AsyncMock(return_value=stream)
@@ -540,8 +514,9 @@ def get_extra_info(self, _info: str) -> None:
assert response.content == b'OK'
assert connect.await_args.args[:2] == ('203.0.113.7', 443)
- assert stream.server_hostname == 'client.example'
- assert b'host: client.example\r\n' in b''.join(stream.writes).lower()
+ assert stream.start_tls.await_args.kwargs['server_hostname'] == 'client.example'
+ sent = b''.join(call.args[0] for call in stream.write.await_args_list)
+ assert b'host: client.example\r\n' in sent.lower()
@pytest.mark.asyncio
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_management_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_management_service.py
index 03e4edd81..12aaa5c34 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_management_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_management_service.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
import pytest
import pytest_asyncio
@@ -155,7 +155,7 @@ async def after_commit() -> None:
async def test_create_detail_bindings_secret_and_cors_snapshot(management_session: AsyncSession) -> None:
"""创建应原子写入绑定,创建不自动发放 Secret,轮换时只返回一次明文。"""
await _seed_definitions(management_session)
- now = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ now = datetime(2026, 1, 1, tzinfo=UTC)
detail = await OAuthClientManagementService.create_client(
management_session, _confidential_payload(), actor='admin', now=now
)
@@ -241,10 +241,10 @@ async def test_status_soft_disable_and_secret_revoke_are_safe(management_session
user_id=7,
subject_id='subject-disable',
auth_version=1,
- auth_time=datetime.now(timezone.utc),
- last_seen_at=datetime.now(timezone.utc),
- idle_expires_at=datetime.now(timezone.utc) + timedelta(hours=1),
- absolute_expires_at=datetime.now(timezone.utc) + timedelta(hours=2),
+ auth_time=datetime.now(UTC),
+ last_seen_at=datetime.now(UTC),
+ idle_expires_at=datetime.now(UTC) + timedelta(hours=1),
+ absolute_expires_at=datetime.now(UTC) + timedelta(hours=2),
acr='urn:test',
amr=['pwd'],
status='active',
@@ -264,9 +264,9 @@ async def test_status_soft_disable_and_secret_revoke_are_safe(management_session
scopes=[],
resources=[],
status='active',
- issued_at=datetime.now(timezone.utc),
- idle_expires_at=datetime.now(timezone.utc) + timedelta(hours=1),
- absolute_expires_at=datetime.now(timezone.utc) + timedelta(hours=2),
+ issued_at=datetime.now(UTC),
+ idle_expires_at=datetime.now(UTC) + timedelta(hours=1),
+ absolute_expires_at=datetime.now(UTC) + timedelta(hours=2),
)
)
await management_session.flush()
@@ -350,7 +350,7 @@ async def test_secret_rotation_bounds_old_active_secret(management_session: Asyn
detail = await OAuthClientManagementService.create_client(
management_session, _confidential_payload(), actor='admin'
)
- now = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ now = datetime(2026, 1, 1, tzinfo=UTC)
first = await OAuthClientManagementService.rotate_secret(
management_session, detail.client_id, actor='admin', now=now, retirement_seconds=120
)
@@ -382,7 +382,7 @@ async def test_secret_rotation_respects_original_expiry_and_rejects_a_gap(
) -> None:
"""轮换不延长原过期时间,远期过期会被截断,排期断档则原子拒绝。"""
await _seed_definitions(management_session)
- now = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ now = datetime(2026, 1, 1, tzinfo=UTC)
early_client = await OAuthClientManagementService.create_client(
management_session, _confidential_payload(client_name='原过期较早'), actor='admin'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_resource_scope_management.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_resource_scope_management.py
index 3b5acb8dd..d8a4e73cd 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_resource_scope_management.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_resource_scope_management.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
import pytest
import pytest_asyncio
@@ -85,7 +85,7 @@ def test_management_identifiers_are_safe_path_segments(value: str) -> None:
with pytest.raises(ValueError):
ScopeModel(scope_code=value, scope_name='x', scope_type='identity')
with pytest.raises(ValueError):
- OidcKeyRotateModel(kid=value, publish_at=datetime.now(timezone.utc))
+ OidcKeyRotateModel(kid=value, publish_at=datetime.now(UTC))
def _client_payload(resource_id: str = 'orders-api', scope_code: str | None = None) -> ClientCreateModel:
@@ -126,7 +126,7 @@ async def test_resource_crud_introspection_policy_and_invalidation_snapshot(reso
resource_session,
ResourceUpdateModel.model_validate(update_values),
actor='admin',
- now=datetime(2026, 1, 1, tzinfo=timezone.utc),
+ now=datetime(2026, 1, 1, tzinfo=UTC),
)
assert updated.introspection_client_id == client.client_id
assert updated.allowed_claims == ['sub', 'email']
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_review_regressions.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_review_regressions.py
index f97894faa..915b9dfb7 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_review_regressions.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_review_regressions.py
@@ -1,5 +1,5 @@
import json
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from unittest.mock import AsyncMock
import pytest
@@ -25,7 +25,7 @@
from utils.oidc_util import OidcUtil
from utils.response_util import ResponseUtil
-NOW = datetime(2026, 9, 12, 10, 0, tzinfo=timezone.utc)
+NOW = datetime(2026, 9, 12, 10, 0, tzinfo=UTC)
PEPPER = 'regression-refresh-pepper-' + 'x' * 32
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_revocation_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_revocation_service.py
index 539080a20..355dfd5f0 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_revocation_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_revocation_service.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -159,7 +159,7 @@ async def test_access_revocation_is_written_only_after_commit(monkeypatch: pytes
redis = FakeRedis()
coordinator = AfterCommitCoordinator()
db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
- now = datetime.fromtimestamp(200, timezone.utc)
+ now = datetime.fromtimestamp(200, UTC)
await RevocationService.revoke(
db,
@@ -206,7 +206,7 @@ async def test_public_client_can_revoke_its_own_access_after_commit(monkeypatch:
'signed-public-access',
OAuthClientPrincipal('client-a', 'public', 'none'),
coordinator=coordinator,
- now=datetime.fromtimestamp(200, timezone.utc),
+ now=datetime.fromtimestamp(200, UTC),
)
await coordinator.commit(db)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_sso_session_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_sso_session_service.py
index 0b0f62bdf..fd2ada8ec 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_sso_session_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_sso_session_service.py
@@ -1,7 +1,7 @@
import asyncio
import builtins
import json
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from uuid import UUID, uuid4
import pytest
@@ -20,7 +20,7 @@
from utils.oidc_util import OidcUtil
_PEPPER = 's' * 32
-_NOW = datetime(2026, 1, 1, tzinfo=timezone.utc)
+_NOW = datetime(2026, 1, 1, tzinfo=UTC)
_COOKIE_SECRET_TEXT_LENGTH = 43
_SUBJECT_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_token_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_token_service.py
index 261501417..85d42ae7c 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_token_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_token_service.py
@@ -1,6 +1,6 @@
import asyncio
import base64
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock
@@ -168,7 +168,7 @@ async def session(*args: object, **kwargs: object) -> SimpleNamespace:
subject_id='subject-2001',
auth_version=4,
status='active',
- auth_time=datetime.now(timezone.utc),
+ auth_time=datetime.now(UTC),
acr='urn:test',
amr=['pwd'],
)
@@ -399,7 +399,7 @@ async def test_user_access_and_id_profiles_have_fixed_claims_and_ttl(monkeypatch
client = _client(access_token_ttl_seconds=_ACCESS_TTL)
user = SimpleNamespace(user_id=2001, user_name='user', nick_name='User', status='0', del_flag='0')
subject = SimpleNamespace(subject_id='subject-2001', auth_version=4)
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
session = SimpleNamespace(
sid='sid-2001',
auth_time=now - timedelta(minutes=1),
@@ -570,7 +570,7 @@ async def load(value: object, **kwargs: object) -> object:
return private_key
monkeypatch.setattr('module_identity.service.token_service.KeyService.load_private_key_async', load)
- key, kid = await TokenService._resolve_signer(object(), None, None, datetime.now(timezone.utc))
+ key, kid = await TokenService._resolve_signer(object(), None, None, datetime.now(UTC))
assert key is private_key
assert kid == 'kid-stable'
assert calls == [record]
@@ -594,8 +594,8 @@ async def test_refresh_scope_expansion_is_rejected_before_rotation(monkeypatch:
scopes=['openid'],
resources=[],
grant_id='grant-1',
- idle_expires_at=datetime.now(timezone.utc) + timedelta(hours=1),
- absolute_expires_at=datetime.now(timezone.utc) + timedelta(hours=2),
+ idle_expires_at=datetime.now(UTC) + timedelta(hours=1),
+ absolute_expires_at=datetime.now(UTC) + timedelta(hours=2),
)
monkeypatch.setattr(
'module_identity.service.token_service.OAuthClientDao.get_by_client_id',
@@ -657,8 +657,8 @@ async def test_refresh_concurrent_rotation_has_one_success_and_reuse_revoke(monk
scopes=['openid'],
resources=[],
grant_id='grant-1',
- idle_expires_at=datetime.now(timezone.utc) + timedelta(hours=1),
- absolute_expires_at=datetime.now(timezone.utc) + timedelta(hours=2),
+ idle_expires_at=datetime.now(UTC) + timedelta(hours=1),
+ absolute_expires_at=datetime.now(UTC) + timedelta(hours=2),
)
token = generate_refresh_token()
row.token_hash = token_digest(token, _PEPPER)
@@ -729,7 +729,7 @@ async def reuse(*args: object, **kwargs: object) -> int:
assert sum(isinstance(item, RefreshTokenReuseDetected) for item in results) == 1
assert state['reuse'] == 1
assert isinstance(state['mark_now'], datetime)
- assert state['mark_now'].tzinfo is timezone.utc
+ assert state['mark_now'].tzinfo is UTC
def _async_value(value: object) -> Any:
diff --git a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py
index 747b4394c..7caaddfc9 100644
--- a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py
@@ -1,6 +1,6 @@
import json
from collections.abc import Generator
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from types import SimpleNamespace
import pytest
@@ -482,7 +482,7 @@ async def test_retain_system_plugin_operation_log_commits_session(monkeypatch: p
recorded: dict[str, object] = {}
retention_result = PluginOperationLogRetentionResultModel(
retentionDays=0,
- cutoffTime=datetime(2026, 5, 22, 12, 0, 0, tzinfo=timezone.utc),
+ cutoffTime=datetime(2026, 5, 22, 12, 0, 0, tzinfo=UTC),
matchedCount=2,
deletedCount=0,
dryRun=True,
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py
index 027e97107..11d8fd148 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py
@@ -1,6 +1,6 @@
import asyncio
from copy import deepcopy
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from unittest.mock import AsyncMock
import pytest
@@ -11,7 +11,7 @@
PLUGIN_ID = 'demo'
DIGEST = 'a' * 64
GENERATION = 'b' * 32
-NOW = datetime(2026, 10, 8, tzinfo=timezone.utc)
+NOW = datetime(2026, 10, 8, tzinfo=UTC)
WORKER = 'c' * 32
OTHER = 'd' * 32
EXTRA = 'e' * 32
@@ -285,18 +285,22 @@ async def reader(plugin_id: str) -> dict:
@pytest.mark.asyncio
@pytest.mark.parametrize(
- ('timeout', 'read_timeout', 'reason'), [(0, 10, 'unavailable'), (4, 4, 'timeout'), (20, 10, 'unavailable')]
+ ('total_seconds', 'read_timeout', 'reason'), [(0, 10, 'unavailable'), (4, 4, 'timeout'), (20, 10, 'unavailable')]
)
async def test_read_timeout_is_bounded_and_classified_by_budget_source(
- monkeypatch: pytest.MonkeyPatch, clock: Clock, timeout: float, read_timeout: float, reason: str
+ monkeypatch: pytest.MonkeyPatch,
+ clock: Clock,
+ total_seconds: float,
+ read_timeout: float,
+ reason: str,
) -> None:
- async def time_out(tasks: set, *, timeout: float) -> tuple[set, set]:
+ def time_out(tasks: set, *, timeout: float) -> tuple[set, set]:
assert timeout == read_timeout
clock.now += timeout
return set(), tasks
- monkeypatch.setattr(convergence, 'wait', time_out)
- result = await wait(AsyncMock(return_value=payload()), timeout_seconds=timeout)
+ monkeypatch.setattr(convergence, 'wait', AsyncMock(side_effect=time_out))
+ result = await wait(AsyncMock(return_value=payload()), timeout_seconds=total_seconds)
assert result['reason'] == reason and result['attempts'] == 1
@@ -326,7 +330,7 @@ async def reader(plugin_id: str) -> dict:
@pytest.mark.asyncio
async def test_reader_own_timeout_is_unavailable_even_when_total_budget_limits_read() -> None:
- reader = AsyncMock(side_effect=asyncio.TimeoutError('private-query-timeout'))
+ reader = AsyncMock(side_effect=TimeoutError('private-query-timeout'))
result = await wait(reader, timeout_seconds=0.01)
assert result['reason'] == 'unavailable' and result['ok'] is False
assert 'private-query-timeout' not in str(result)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_release_state.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_release_state.py
index f1532c351..bdefbdf08 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_release_state.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_release_state.py
@@ -1,11 +1,11 @@
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
import pytest
from plugins.core.deployment.state import aggregate_release
-NOW = datetime(2026, 10, 2, tzinfo=timezone.utc)
+NOW = datetime(2026, 10, 2, tzinfo=UTC)
DIGEST = 'a' * 64
GENERATION = 'b' * 32
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_worker.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_worker.py
index a79b4c425..05a800b8b 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_worker.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_worker.py
@@ -171,6 +171,26 @@ async def summary(deployment: SimpleNamespace, plugin_id: str = 'release_demo')
return aggregate_release(release, reports, now=TimezoneUtil.utc_now(), ttl_seconds=6).to_payload()
+@pytest.mark.asyncio
+async def test_lock_deadline_only_limits_acquisition(deployment: SimpleNamespace) -> None:
+ @asynccontextmanager
+ async def busy_lock(_plugin_id: str, _operation: str) -> AsyncIterator[SimpleNamespace]:
+ yield SimpleNamespace(acquired=False)
+
+ worker = PluginReleaseWorker(deployment.config, session_factory=deployment.sessions)
+ builder = PluginRuntimeBuilder(deployment.config.backend_root)
+ app = FastAPI()
+ with pytest.raises(TimeoutError, match='等待插件维护发布锁超时'):
+ await worker.start(app, builder, SimpleNamespace(lock=busy_lock), lock_wait_seconds=0)
+ assert not worker.registered
+
+ try:
+ await worker.start(app, builder, NoopPluginLifecycleLock(), lock_wait_seconds=0)
+ assert worker.registered
+ finally:
+ await worker.stop()
+
+
@pytest.mark.asyncio
async def test_real_entrypoint_ready_reports_and_shutdown(deployment: SimpleNamespace) -> None:
"""验证真实入口激活、就绪上报和关闭后的状态变化。"""
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/management/test_plugin_state.py b/ruoyi-fastapi-backend/tests/plugins/core/management/test_plugin_state.py
index 658686ee1..4f1a60118 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/management/test_plugin_state.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/management/test_plugin_state.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
@@ -2265,7 +2265,7 @@ async def test_plugin_operation_log_export_services_returns_filtered_rows() -> N
continue_on_error=False,
)
# 固定在 UTC 与上海日期不同的时刻,导出筛选使用应用业务日期。
- created_at = datetime(2026, 10, 1, 16, 5, tzinfo=timezone.utc)
+ created_at = datetime(2026, 10, 1, 16, 5, tzinfo=UTC)
await session.execute(update(SysPluginOperationLog).values(create_time=created_at))
await session.commit()
@@ -2315,7 +2315,7 @@ async def test_retain_plugin_operation_log_services_supports_dry_run_and_delete(
dry_run='1',
continue_on_error='1',
status='success',
- create_time=datetime.now(timezone.utc) - timedelta(days=30),
+ create_time=datetime.now(UTC) - timedelta(days=30),
),
SysPluginOperationLog(
operation='install',
@@ -2323,7 +2323,7 @@ async def test_retain_plugin_operation_log_services_supports_dry_run_and_delete(
dry_run='1',
continue_on_error='1',
status='success',
- create_time=datetime.now(timezone.utc),
+ create_time=datetime.now(UTC),
),
]
)
@@ -2340,7 +2340,7 @@ async def test_retain_plugin_operation_log_services_supports_dry_run_and_delete(
await session.commit()
remaining_count = await PluginDao.count_plugin_operation_logs_before(
session,
- datetime.now(timezone.utc) + timedelta(days=1),
+ datetime.now(UTC) + timedelta(days=1),
)
assert dry_run_result.matched_count == 1
@@ -2369,7 +2369,7 @@ async def test_retain_plugin_operation_log_services_accepts_zero_days() -> None:
dry_run='1',
continue_on_error='1',
status='success',
- create_time=datetime.now(timezone.utc) - timedelta(minutes=1),
+ create_time=datetime.now(UTC) - timedelta(minutes=1),
)
)
await session.commit()
@@ -2381,7 +2381,7 @@ async def test_retain_plugin_operation_log_services_accepts_zero_days() -> None:
await session.commit()
remaining_count = await PluginDao.count_plugin_operation_logs_before(
session,
- datetime.now(timezone.utc) + timedelta(days=1),
+ datetime.now(UTC) + timedelta(days=1),
)
assert delete_result.retention_days == 0
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/management/test_release_dao.py b/ruoyi-fastapi-backend/tests/plugins/core/management/test_release_dao.py
index d512ab16e..5b05db9df 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/management/test_release_dao.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/management/test_release_dao.py
@@ -1,6 +1,6 @@
import asyncio
from collections.abc import AsyncIterator
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from pathlib import Path
import pytest
@@ -17,7 +17,7 @@
DIGEST_B = 'b' * 64
WORKER_ID = '1' * 32
EXPECTED_WORKERS = 2
-NOW = datetime(2026, 10, 2, tzinfo=timezone.utc)
+NOW = datetime(2026, 10, 2, tzinfo=UTC)
@pytest_asyncio.fixture
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/native/test_wheel.py b/ruoyi-fastapi-backend/tests/plugins/core/native/test_wheel.py
index 0c540cc0e..2b28ecc92 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/native/test_wheel.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/native/test_wheel.py
@@ -47,7 +47,7 @@ def make_wheel(root: Path, *, extra: dict[str, bytes] | None = None, tag: str |
files = {
f'{MODULE}/__init__.py': b'raise RuntimeError("static validation must not import")',
f'{MODULE}/_native{EXTENSION_SUFFIXES[0]}': b'not-an-executable-test-fixture',
- f'{METADATA}/METADATA': b'Name: ruoyi-plugin-wheel-test\nVersion: 1.0.0\nRequires-Python: >=3.10\n',
+ f'{METADATA}/METADATA': b'Name: ruoyi-plugin-wheel-test\nVersion: 1.0.0\nRequires-Python: >=3.11\n',
f'{METADATA}/WHEEL': f'Wheel-Version: 1.0\nRoot-Is-Purelib: false\nTag: {selected_tag}\n'.encode(),
**(extra or {}),
}
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py
index d294b2598..d98edb383 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py
@@ -263,7 +263,7 @@ async def resistant() -> None:
manager = PluginGatewayASGI(AsyncMock(), PluginLifespanManager(AsyncMock(), managed=False), AsyncMock()).connections
loaded.gateway = SimpleNamespace(connections=manager)
try:
- await cancel_plugin_tasks({task}, timeout=0.01)
+ await cancel_plugin_tasks({task}, grace_seconds=0.01)
await interrupted.wait()
# 模拟同一任务同时由通用回收器与连接回收器保留,诊断只能计算一次。
manager._unfinished.add(task)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_query.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_query.py
index bc1d61336..1b31a763e 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_query.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_query.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -69,7 +69,7 @@ def release(*worker_ids: str, expected: int = 1) -> dict:
'state': 'ready',
'digest': 'f' * 64,
'generation': 'e' * 32,
- 'heartbeatTime': datetime.fromtimestamp(NOW, timezone.utc).isoformat(),
+ 'heartbeatTime': datetime.fromtimestamp(NOW, UTC).isoformat(),
}
for worker_id in worker_ids
for plugin_id in ('__runtime__', 'demo')
@@ -120,7 +120,7 @@ def test_replaced_stale_host_does_not_make_current_coverage_incomplete() -> None
deployment = release(WORKER, OTHER)
for row in deployment['workers']:
if row['workerId'] == OTHER:
- row['heartbeatTime'] = datetime.fromtimestamp(NOW - 61, timezone.utc).isoformat()
+ row['heartbeatTime'] = datetime.fromtimestamp(NOW - 61, UTC).isoformat()
result = query.build_runtime_diagnostics('demo', report(snapshot()), deployment, now=NOW)
assert result['state'] == 'observed' and result['missingWorkers'] == 0
assert result['workers'][1]['actual'] is None
@@ -174,7 +174,7 @@ def test_fresh_runtime_cache_of_stale_host_does_not_fill_expected_capacity() ->
deployment['workerTtlSeconds'] = 15
for row in deployment['workers']:
if row['workerId'] == OTHER:
- row['heartbeatTime'] = datetime.fromtimestamp(NOW - 20, timezone.utc).isoformat()
+ row['heartbeatTime'] = datetime.fromtimestamp(NOW - 20, UTC).isoformat()
result = query.build_runtime_diagnostics(
'demo', report(snapshot(), snapshot(OTHER, collectedAt=NOW - 20)), deployment, now=NOW
)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_store.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_store.py
index a61d0513b..e0c0cfa0a 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_store.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_store.py
@@ -2,7 +2,7 @@
import json
import time
from collections.abc import AsyncIterator
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from fnmatch import fnmatchcase
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -329,7 +329,7 @@ async def test_empty_runtime_uses_release_worker_identity_without_fabricating_mi
'workerId': worker_id,
'pluginId': '__runtime__',
'state': 'ready',
- 'heartbeatTime': datetime.fromtimestamp(now - 1, timezone.utc).isoformat(),
+ 'heartbeatTime': datetime.fromtimestamp(now - 1, UTC).isoformat(),
}
],
}
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_job_dispatcher.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_job_dispatcher.py
index 81c223fcd..8b308b370 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_job_dispatcher.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_job_dispatcher.py
@@ -200,7 +200,7 @@ async def wait(*args: object, **kwargs: object) -> None:
await state.runtime.activate('dispatch_test', FastAPI())
try:
state.service.side_effect = wait
- with pytest.raises(asyncio.TimeoutError):
+ with pytest.raises(TimeoutError):
await dispatch_plugin_job('dispatch_test', 'tick', '1.0.0')
assert closed.is_set()
state.service.side_effect = ValueError('business-error')
@@ -264,7 +264,7 @@ async def resistant(*args: object, **kwargs: object) -> bool:
binding = state.runtime.loaded['dispatch_test'].jobs
task = asyncio.create_task(dispatch_plugin_job('dispatch_test', 'tick', '1.0.0'))
await opened.wait()
- stopping = asyncio.create_task(unbind_plugin_jobs(binding, timeout=0.01))
+ stopping = asyncio.create_task(unbind_plugin_jobs(binding, grace_seconds=0.01))
try:
await asyncio.wait({stopping}, timeout=1)
assert stopping.done() and not task.done()
@@ -284,7 +284,7 @@ async def resistant(*args: object, **kwargs: object) -> bool:
sample = next(item for item in state.runtime.metrics.snapshot().series if item.operation == 'job:tick')
assert (sample.active, sample.succeeded, sample.cancelled) == (0, 0, 1)
replacement = bind_plugin_jobs(state.plugin, binding.host, state.gateway, lambda: True)
- await unbind_plugin_jobs(replacement, timeout=0.01)
+ await unbind_plugin_jobs(replacement, grace_seconds=0.01)
finally:
release.set()
await asyncio.gather(stopping, task, return_exceptions=True)
@@ -307,7 +307,7 @@ async def resistant(*args: object, **kwargs: object) -> bool:
return True
async def bounded_unbind(binding: object) -> None:
- await unbind_plugin_jobs(binding, timeout=0.01)
+ await unbind_plugin_jobs(binding, grace_seconds=0.01)
state.service.side_effect = resistant
monkeypatch.setattr('plugins.core.runtime.explicit.unbind_plugin_jobs', bounded_unbind)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_task_cleanup.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_task_cleanup.py
index d2f9a4b24..bc47e3f56 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_task_cleanup.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_task_cleanup.py
@@ -17,7 +17,7 @@ async def work() -> None:
tasks = {asyncio.create_task(work()) for _ in range(3)}
await asyncio.sleep(0)
- assert await cancel_plugin_tasks(tasks | {asyncio.current_task()}, timeout=0.01) == set()
+ assert await cancel_plugin_tasks(tasks | {asyncio.current_task()}, grace_seconds=0.01) == set()
assert len(stopped) == len(tasks)
assert all(task.cancelled() for task in tasks)
@@ -38,7 +38,7 @@ async def work() -> None:
child = asyncio.create_task(work())
await opened.wait()
- waiter = asyncio.create_task(cancel_plugin_tasks({child}, timeout=0.01 if not cancel_waiter else 1))
+ waiter = asyncio.create_task(cancel_plugin_tasks({child}, grace_seconds=0.01 if not cancel_waiter else 1))
try:
await interrupted.wait()
if cancel_waiter:
@@ -59,12 +59,12 @@ async def work() -> None:
@pytest.mark.asyncio
-@pytest.mark.parametrize('timeout', [0, -1, float('inf'), float('nan')])
-async def test_invalid_timeout_is_rejected_before_any_cancellation(timeout: float) -> None:
+@pytest.mark.parametrize('grace_seconds', [0, -1, float('inf'), float('nan')])
+async def test_invalid_timeout_is_rejected_before_any_cancellation(grace_seconds: float) -> None:
task = asyncio.create_task(asyncio.sleep(10))
try:
with pytest.raises(ValueError, match='大于零'):
- await cancel_plugin_tasks({task}, timeout=timeout)
+ await cancel_plugin_tasks({task}, grace_seconds=grace_seconds)
assert not task.done()
finally:
- await cancel_plugin_tasks({task}, timeout=0.01)
+ await cancel_plugin_tasks({task}, grace_seconds=0.01)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest.py
index 5f3edc588..f78e83d0d 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest.py
@@ -198,7 +198,7 @@ def test_manifest_checker_accepts_satisfied_compatibility(tmp_path: Path) -> Non
'compatibility': {
'backendVersion': '>=1.0.0',
'frontendVersion': '>=1.0.0',
- 'pythonVersion': '>=3.10',
+ 'pythonVersion': '>=3.11',
'nodeVersion': '>=18.0.0',
},
}
@@ -207,7 +207,7 @@ def test_manifest_checker_accepts_satisfied_compatibility(tmp_path: Path) -> Non
result = PluginManifestChecker(
backend_root=backend_root,
frontend_root=frontend_root,
- python_version='3.10.19',
+ python_version='3.11.0',
node_version='20.0.0',
).check(manifest)
@@ -283,7 +283,7 @@ def test_manifest_checker_reports_unsatisfied_compatibility(tmp_path: Path) -> N
'name': '演示插件',
'version': '1.0.0',
'backend': {'module': 'plugins.demo'},
- 'compatibility': {'pythonVersion': '>=99.0.0'},
+ 'compatibility': {'pythonVersion': '>=3.11'},
}
)
@@ -336,7 +336,7 @@ def test_manifest_checker_warns_unknown_compatibility_version(tmp_path: Path) ->
result = PluginManifestChecker(
backend_root=tmp_path / 'missing-backend',
frontend_root=tmp_path / 'missing-frontend',
- python_version='3.10.19',
+ python_version='3.11.0',
node_version='20.0.0',
).check(manifest)
diff --git a/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py b/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py
index 236a0b7c8..cc05ffac4 100644
--- a/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py
+++ b/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py
@@ -7,7 +7,7 @@
import subprocess
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager, suppress
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -44,19 +44,21 @@ def frontend_root() -> Path:
return Path(__file__).resolve().parents[4] / 'ruoyi-fastapi-frontend' / framework / 'web'
-async def wait_until(predicate: Callable[[], bool], timeout: float = 15) -> None:
+async def wait_until(predicate: Callable[[], bool], wait_seconds: float = 15) -> None:
"""
有界等待服务器启动或连接回收,不使用固定长睡眠。
:param predicate: 待满足的状态条件
- :param timeout: 最长等待秒数
+ :param wait_seconds: 最长等待秒数
:return: None
"""
- deadline = asyncio.get_running_loop().time() + timeout
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + wait_seconds
while not predicate():
- if asyncio.get_running_loop().time() >= deadline:
+ remaining = deadline - loop.time()
+ if remaining <= 0:
raise TimeoutError('网络验收等待状态超时')
- await asyncio.sleep(0.05)
+ await asyncio.sleep(min(0.05, remaining))
def certificate_files(directory: Path) -> tuple[Path, Path]:
@@ -68,7 +70,7 @@ def certificate_files(directory: Path) -> tuple[Path, Path]:
"""
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, 'localhost')])
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
certificate = (
x509.CertificateBuilder()
.subject_name(subject)
@@ -221,7 +223,7 @@ async def network_servers(fixture: SimpleNamespace, directory: Path, output: Pat
)
await wait_until(
lambda: ready.exists() or process.returncode is not None,
- timeout=180 if frontend.parent.name == 'vue2' else 60,
+ wait_seconds=180 if frontend.parent.name == 'vue2' else 60,
)
if not ready.exists():
log.flush()
diff --git a/ruoyi-fastapi-backend/tests/scheduler_helpers.py b/ruoyi-fastapi-backend/tests/scheduler_helpers.py
index e49beceab..3c0258be5 100644
--- a/ruoyi-fastapi-backend/tests/scheduler_helpers.py
+++ b/ruoyi-fastapi-backend/tests/scheduler_helpers.py
@@ -4,7 +4,7 @@
import time
from collections.abc import AsyncIterator
from dataclasses import dataclass
-from datetime import timezone
+from datetime import UTC
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -216,7 +216,7 @@ def assign_sqlite_id(_mapper: object, connection: object, target: SysJob) -> Non
async_engine = create_async_engine(f'sqlite+aiosqlite:///{path}')
sessions = async_sessionmaker(async_engine, expire_on_commit=False)
scheduler = AsyncIOScheduler(
- timezone=timezone.utc,
+ timezone=UTC,
executors={
'default': TimedAsyncIOExecutor(manage_executions=True),
},
diff --git a/ruoyi-fastapi-backend/tests/test_audit_time_delegation.py b/ruoyi-fastapi-backend/tests/test_audit_time_delegation.py
index 2ae6798b0..2f0e9919c 100644
--- a/ruoyi-fastapi-backend/tests/test_audit_time_delegation.py
+++ b/ruoyi-fastapi-backend/tests/test_audit_time_delegation.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from plugins.core.management.dao.dao import PluginDao
from plugins.core.management.entity.do.models import SysPluginMigration
@@ -6,7 +6,7 @@
def test_plugin_persistence_payload_ignores_client_audit_times() -> None:
- now = datetime(2026, 8, 21, 12, 0, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 8, 21, 12, 0, 0, tzinfo=UTC)
payload = PluginDao.dump_plugin_persistence_payload(
PluginModel(
pluginId='demo',
@@ -22,12 +22,12 @@ def test_plugin_persistence_payload_ignores_client_audit_times() -> None:
def test_existing_migration_update_uses_onupdate_not_external_time() -> None:
- now = datetime(2026, 8, 21, 12, 0, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 8, 21, 12, 0, 0, tzinfo=UTC)
payload = PluginMigrationModel(
pluginId='demo',
migrationPath='migrations/001.sql',
migrationChecksum='checksum',
- updateTime=datetime(2000, 1, 1, tzinfo=timezone.utc),
+ updateTime=datetime(2000, 1, 1, tzinfo=UTC),
).model_dump(exclude_unset=True)
PluginDao._apply_migration_observability_payload(payload, SysPluginMigration(), now)
diff --git a/ruoyi-fastapi-backend/tests/utils/test_cron_util.py b/ruoyi-fastapi-backend/tests/utils/test_cron_util.py
index 0abf02952..7fcdaad4b 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_cron_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_cron_util.py
@@ -1,5 +1,5 @@
import pickle
-from datetime import datetime, timezone
+from datetime import UTC, datetime
import pytest
@@ -40,7 +40,7 @@ def test_preview_matches_persisted_trigger_across_dst(expression: str, start: st
previous = None
for _ in range(3):
previous = trigger.get_next_fire_time(previous, previous or start_time)
- actual.append(previous.astimezone(timezone.utc))
+ actual.append(previous.astimezone(UTC))
assert preview == actual == [datetime.fromisoformat(value) for value in expected]
@@ -54,14 +54,14 @@ def test_preview_matches_persisted_trigger_across_dst(expression: str, start: st
],
)
def test_quartz_week_and_workday_semantics(expression: str, expected: list[str]) -> None:
- times = CronUtil.next_run_times(expression, 'UTC', datetime(2026, 2, 1, tzinfo=timezone.utc), 2)
+ times = CronUtil.next_run_times(expression, 'UTC', datetime(2026, 2, 1, tzinfo=UTC), 2)
assert [value.date().isoformat() for value in times] == expected
def test_cron_trigger_uses_explicit_business_timezone() -> None:
trigger = MyCronTrigger.from_crontab('0 0 9 * * ?', 'Asia/Shanghai')
- fire_time = trigger.get_next_fire_time(None, datetime(2026, 1, 1, tzinfo=timezone.utc))
+ fire_time = trigger.get_next_fire_time(None, datetime(2026, 1, 1, tzinfo=UTC))
assert trigger.timezone.key == 'Asia/Shanghai'
assert fire_time is not None
- assert fire_time.astimezone(timezone.utc) == datetime(2026, 1, 1, 1, tzinfo=timezone.utc)
+ assert fire_time.astimezone(UTC) == datetime(2026, 1, 1, 1, tzinfo=UTC)
diff --git a/ruoyi-fastapi-backend/tests/utils/test_current_user_cache_util.py b/ruoyi-fastapi-backend/tests/utils/test_current_user_cache_util.py
index 05017cd6e..b31258f08 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_current_user_cache_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_current_user_cache_util.py
@@ -50,7 +50,7 @@ async def cache_redis(redis_socket: IsolatedRedisServer) -> AsyncIterator[Redis]
try:
await asyncio.wait_for(redis.ping(), timeout=0.2)
break
- except (RedisConnectionError, asyncio.TimeoutError):
+ except (TimeoutError, RedisConnectionError):
await asyncio.sleep(0.01)
else:
pytest.fail('隔离Redis测试实例未能启动')
diff --git a/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py b/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py
index 32835e16d..53f9fb248 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py
@@ -1,7 +1,7 @@
import asyncio
import json
from collections.abc import Iterator
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import patch
@@ -399,7 +399,7 @@ def test_log_handles_missing_user_agent_without_error() -> None:
None,
oper_ip='127.0.0.1',
oper_location='内网IP',
- oper_time=datetime(2026, 4, 20, 12, 0, 0, tzinfo=timezone.utc),
+ oper_time=datetime(2026, 4, 20, 12, 0, 0, tzinfo=UTC),
origin_kwargs={},
)
diff --git a/ruoyi-fastapi-backend/tests/utils/test_response_timezone.py b/ruoyi-fastapi-backend/tests/utils/test_response_timezone.py
index 61c2e628a..828b3168a 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_response_timezone.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_response_timezone.py
@@ -1,5 +1,5 @@
import json
-from datetime import datetime, timezone
+from datetime import UTC, datetime
import pytest
@@ -7,7 +7,7 @@
def test_response_util_serializes_nested_datetimes_as_fixed_utc_rfc3339() -> None:
- response = ResponseUtil.success(data={'createdAt': datetime(2026, 8, 28, 10, 30, 0, 123456, tzinfo=timezone.utc)})
+ response = ResponseUtil.success(data={'createdAt': datetime(2026, 8, 28, 10, 30, 0, 123456, tzinfo=UTC)})
payload = json.loads(response.body)
assert payload['data']['createdAt'] == '2026-08-28T10:30:00.123Z'
diff --git a/ruoyi-fastapi-backend/tests/utils/test_time_util.py b/ruoyi-fastapi-backend/tests/utils/test_time_util.py
index d423eaf37..08d2be162 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_time_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_time_util.py
@@ -1,4 +1,4 @@
-from datetime import date, datetime, timezone
+from datetime import UTC, date, datetime
import pytest
@@ -9,7 +9,7 @@
def test_utc_now_returns_aware_utc_datetime() -> None:
now = TimezoneUtil.utc_now()
- assert now.tzinfo is timezone.utc
+ assert now.tzinfo is UTC
assert now.utcoffset().total_seconds() == 0
@@ -21,14 +21,14 @@ def test_naive_datetime_is_rejected() -> None:
def test_datetime_is_normalized_to_utc_and_business_timezone() -> None:
shanghai_time = datetime.fromisoformat('2026-08-28T10:30:00+08:00')
- assert TimezoneUtil.to_utc(shanghai_time) == datetime(2026, 8, 28, 2, 30, tzinfo=timezone.utc)
+ assert TimezoneUtil.to_utc(shanghai_time) == datetime(2026, 8, 28, 2, 30, tzinfo=UTC)
assert TimezoneUtil.to_business_time(TimezoneUtil.to_utc(shanghai_time), 'Asia/Shanghai') == shanghai_time
def test_optional_utc_preserves_none_and_rejects_naive_datetime() -> None:
assert TimezoneUtil.to_optional_utc(None) is None
value = datetime.fromisoformat('2026-08-28T10:30:00+08:00')
- assert TimezoneUtil.to_optional_utc(value) == datetime(2026, 8, 28, 2, 30, tzinfo=timezone.utc)
+ assert TimezoneUtil.to_optional_utc(value) == datetime(2026, 8, 28, 2, 30, tzinfo=UTC)
with pytest.raises(ValueError, match='必须携带时区信息'):
TimezoneUtil.to_optional_utc(datetime(2026, 8, 28, 10, 30))
@@ -36,7 +36,7 @@ def test_optional_utc_preserves_none_and_rejects_naive_datetime() -> None:
def test_to_utc_milliseconds_truncates_sub_millisecond_precision() -> None:
value = datetime.fromisoformat('2026-08-28T10:30:00.123999+08:00')
- assert TimezoneUtil.to_utc_milliseconds(value) == datetime(2026, 8, 28, 2, 30, 0, 123000, tzinfo=timezone.utc)
+ assert TimezoneUtil.to_utc_milliseconds(value) == datetime(2026, 8, 28, 2, 30, 0, 123000, tzinfo=UTC)
@pytest.mark.parametrize(
diff --git a/ruoyi-fastapi-backend/utils/api_annotation_util.py b/ruoyi-fastapi-backend/utils/api_annotation_util.py
index 09c1454d0..27a1433ac 100644
--- a/ruoyi-fastapi-backend/utils/api_annotation_util.py
+++ b/ruoyi-fastapi-backend/utils/api_annotation_util.py
@@ -1,10 +1,9 @@
import inspect
from collections.abc import Awaitable, Callable, Sequence
-from typing import TypeVar
+from typing import ParamSpec, TypeVar
from fastapi import Request
from redis import asyncio as aioredis
-from typing_extensions import ParamSpec
from common.enums import HttpMethod
from utils.log_util import logger
diff --git a/ruoyi-fastapi-backend/utils/cache_util.py b/ruoyi-fastapi-backend/utils/cache_util.py
index c6c5de422..5f7db94d4 100644
--- a/ruoyi-fastapi-backend/utils/cache_util.py
+++ b/ruoyi-fastapi-backend/utils/cache_util.py
@@ -271,7 +271,7 @@ async def _eval(cls, redis: Redis, script: str, key_count: int, *args: object) -
while not settled.done():
try:
await asyncio.shield(settled)
- except asyncio.CancelledError: # noqa: PERF203
+ except asyncio.CancelledError:
cancelled = True
if cancelled:
raise asyncio.CancelledError
diff --git a/ruoyi-fastapi-backend/utils/cron_util.py b/ruoyi-fastapi-backend/utils/cron_util.py
index 450a7ed7b..124cb12de 100644
--- a/ruoyi-fastapi-backend/utils/cron_util.py
+++ b/ruoyi-fastapi-backend/utils/cron_util.py
@@ -1,6 +1,6 @@
import re
from calendar import monthrange
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.cron.expressions import AllExpression
@@ -105,7 +105,7 @@ def get_next_fire_time(self, previous_fire_time: datetime | None, now: datetime)
"""
candidate = super().get_next_fire_time(previous_fire_time, now)
while candidate is not None:
- normalized = candidate.astimezone(timezone.utc).astimezone(self.timezone)
+ normalized = candidate.astimezone(UTC).astimezone(self.timezone)
if candidate.isoformat() == normalized.isoformat() and candidate.fold == 0:
return candidate
candidate = super().get_next_fire_time(candidate, candidate)
diff --git a/ruoyi-fastapi-backend/utils/log_util.py b/ruoyi-fastapi-backend/utils/log_util.py
index 3cd311d31..22fb58142 100644
--- a/ruoyi-fastapi-backend/utils/log_util.py
+++ b/ruoyi-fastapi-backend/utils/log_util.py
@@ -6,7 +6,7 @@
import sys
import traceback
from collections.abc import Mapping, Sequence
-from datetime import timezone
+from datetime import UTC
from typing import Any
from loguru import logger as _logger
@@ -561,7 +561,7 @@ def _patch_record(self, record: dict) -> dict:
:return: 脱敏后的日志记录字典
"""
record['message'] = LogSanitizer.sanitize_text(record['message'])
- record['time'] = record['time'].astimezone(timezone.utc)
+ record['time'] = record['time'].astimezone(UTC)
return record
def _info_file_filter(self, record: dict) -> bool:
diff --git a/ruoyi-fastapi-backend/utils/time_util.py b/ruoyi-fastapi-backend/utils/time_util.py
index 92218897f..6969c0842 100644
--- a/ruoyi-fastapi-backend/utils/time_util.py
+++ b/ruoyi-fastapi-backend/utils/time_util.py
@@ -1,6 +1,6 @@
import re
from dataclasses import dataclass
-from datetime import date, datetime, time, timedelta, timezone
+from datetime import UTC, date, datetime, time, timedelta
from functools import cache
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
@@ -99,7 +99,7 @@ def parse_rfc3339(cls, value: str | datetime) -> datetime:
"""
解析带时区的RFC 3339时刻并归一化为UTC毫秒
- 兼容Python 3.10的ISO格式解析,不接受无时区的日期时间。
+ 接受带 UTC 标记或数字偏移量的日期时间。
:param value: 待校验的输入值
:return: 携带UTC时区的毫秒精度时刻
@@ -108,7 +108,7 @@ def parse_rfc3339(cls, value: str | datetime) -> datetime:
return cls.to_utc_milliseconds(value)
if isinstance(value, str) and cls.RFC3339_PATTERN.fullmatch(value):
try:
- return cls.to_utc_milliseconds(datetime.fromisoformat(value.upper().replace('Z', '+00:00')))
+ return cls.to_utc_milliseconds(datetime.fromisoformat(value.upper()))
except ValueError:
pass
raise ValueError('时刻必须是有效的带offset的RFC 3339字符串或aware datetime')
@@ -132,7 +132,7 @@ def utc_now(cls) -> datetime:
:return: 携带UTC时区的当前时刻
"""
- return datetime.now(timezone.utc)
+ return datetime.now(UTC)
@classmethod
def ensure_aware(cls, value: datetime, *, field_name: str = 'datetime') -> datetime:
@@ -155,7 +155,7 @@ def to_utc(cls, value: datetime) -> datetime:
:param value: 携带时区信息的时刻
:return: 携带UTC时区的时刻
"""
- return cls.ensure_aware(value).astimezone(timezone.utc)
+ return cls.ensure_aware(value).astimezone(UTC)
@classmethod
def to_optional_utc(cls, value: datetime | None) -> datetime | None:
@@ -210,7 +210,7 @@ def local_date_range_to_utc(
business_timezone = cls.get_timezone(timezone_name) if timezone_name else cls.get_app_timezone()
start = datetime.combine(begin_date, time.min, tzinfo=business_timezone)
end = datetime.combine(end_date + timedelta(days=1), time.min, tzinfo=business_timezone)
- return start.astimezone(timezone.utc), end.astimezone(timezone.utc)
+ return start.astimezone(UTC), end.astimezone(UTC)
@classmethod
def local_date_strings_to_utc(
@@ -236,9 +236,9 @@ def local_date_strings_to_utc(
if end == date.max:
raise ValueError('结束日期必须早于9999-12-31')
business_timezone = cls.get_timezone(timezone_name) if timezone_name else cls.get_app_timezone()
- start = datetime.combine(begin, time.min, tzinfo=business_timezone).astimezone(timezone.utc) if begin else None
+ start = datetime.combine(begin, time.min, tzinfo=business_timezone).astimezone(UTC) if begin else None
stop = (
- datetime.combine(end + timedelta(days=1), time.min, tzinfo=business_timezone).astimezone(timezone.utc)
+ datetime.combine(end + timedelta(days=1), time.min, tzinfo=business_timezone).astimezone(UTC)
if end
else None
)
diff --git a/ruoyi-fastapi-backend/utils/transport_crypto_util.py b/ruoyi-fastapi-backend/utils/transport_crypto_util.py
index 755324c04..d17134a36 100644
--- a/ruoyi-fastapi-backend/utils/transport_crypto_util.py
+++ b/ruoyi-fastapi-backend/utils/transport_crypto_util.py
@@ -4,7 +4,7 @@
import time
from collections import Counter, defaultdict, deque
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from threading import Lock
from typing import Any
@@ -1302,4 +1302,4 @@ def _coerce_datetime_for_sort(cls, value: Any) -> datetime:
parsed_datetime = cls._parse_datetime(value)
if parsed_datetime:
return parsed_datetime
- return datetime.min.replace(tzinfo=timezone.utc)
+ return datetime.min.replace(tzinfo=UTC)
diff --git a/ruoyi-fastapi-test/README.md b/ruoyi-fastapi-test/README.md
index 43da32d09..ca8ddcab7 100644
--- a/ruoyi-fastapi-test/README.md
+++ b/ruoyi-fastapi-test/README.md
@@ -9,13 +9,13 @@
| 分类 | 工作流 | 主要检查 |
| --- | --- | --- |
| Quality | [ci-quality.yml](../.github/workflows/ci-quality.yml) | Python/六个前端工程格式、actionlint、选路与失败门禁测试、三框架 × 四份 Compose 配置 |
-| Backend | [ci-backend.yml](../.github/workflows/ci-backend.yml) | Python 3.10–3.14 单元与契约、Windows CLI/路径、三种宿主时区 |
+| Backend | [ci-backend.yml](../.github/workflows/ci-backend.yml) | Python 3.11–3.14 单元与契约、Windows CLI/路径、三种宿主时区 |
| Frontend | [ci-frontend.yml](../.github/workflows/ci-frontend.yml) | Node 22/24 × 六工程单元测试、三时区契约、Web prod/docker、移动端 H5/微信及 H5 登录;React Mobile 的 Android/iOS JS bundle,完整模式增加其他小程序与鸿蒙构建 |
| Integration | [ci-integration.yml](../.github/workflows/ci-integration.yml) | 双数据库时间持久化、插件发布、Vue2/Vue3/React HTTPS 代理与 SSE/WebSocket |
| E2E | [ci-e2e.yml](../.github/workflows/ci-e2e.yml) | 三框架的独立数据库和应用容器、Chromium 登录/权限/29 个菜单页面/时区,以及全部业务操作用例 |
-| Native | [ci-native.yml](../.github/workflows/ci-native.yml) | Rust fmt/clippy、Windows/Linux × Python 3.10–3.14 的真实原生制品 |
+| Native | [ci-native.yml](../.github/workflows/ci-native.yml) | Rust fmt/clippy、Windows/Linux × Python 3.11–3.14 的真实原生制品 |
-PR 按 `.github/scripts/ci_plan.py` 的变更影响规则选择分类与前端工程,框架包含 `vue2`、`vue3`、`react`。单个移动端的改动只运行对应前端工程,不触发 Web E2E 或 Rust Native。共享依赖和 CI 变更触发全部分类;仅文档变更运行 Quality。PR E2E 使用 Python 3.12,受影响的每个 Web 框架分别测试 MySQL 和 PostgreSQL。`master` 推送、每天 UTC 18:21(北京时间次日 02:21)及手动 `full=true` 扩展为五个 Python 版本(3.10–3.14),共 30 个 E2E 组合;插件发布集成测试也覆盖这五个版本,并增加 React Mobile 的支付宝、百度、抖音、QQ、京东、快手、飞书、小红书和鸿蒙构建。手动 `full=false` 运行所有分类的 PR 规模矩阵。
+PR 按 `.github/scripts/ci_plan.py` 的变更影响规则选择分类与前端工程,框架包含 `vue2`、`vue3`、`react`。单个移动端的改动只运行对应前端工程,不触发 Web E2E 或 Rust Native。共享依赖和 CI 变更触发全部分类;仅文档变更运行 Quality。PR E2E 使用 Python 3.12,受影响的每个 Web 框架分别测试 MySQL 和 PostgreSQL。`master` 推送、每天 UTC 18:21(北京时间次日 02:21)及手动 `full=true` 扩展为四个 Python 版本(3.11–3.14),共 24 个 E2E 组合;插件发布集成测试也覆盖这四个版本,并增加 React Mobile 的支付宝、百度、抖音、QQ、京东、快手、飞书、小红书和鸿蒙构建。手动 `full=false` 运行所有分类的 PR 规模矩阵。
Vue2、Vue3、React 执行相同的全部 `e2e` 用例,当前每个框架收集 109 项。覆盖账号资料与锁屏、系统管理 CRUD 与授权、文件上传下载、插件和 OAuth 管理、缓存与服务监控、强退、任务执行及日志、代码生成和表单构建。选择器按实际 Element / Ant Design 组件适配,保留真实 API 响应、保存值与清理断言;React 导出用例校验 JSX 内容。完整模式与 PR 模式使用同一套业务用例。
diff --git a/ruoyi-fastapi-test/common/base_page_test.py b/ruoyi-fastapi-test/common/base_page_test.py
index 3f3d79382..e9631916d 100644
--- a/ruoyi-fastapi-test/common/base_page_test.py
+++ b/ruoyi-fastapi-test/common/base_page_test.py
@@ -32,15 +32,15 @@ async def select_department(self, dialog: Locator, label: str, department: str)
)
await choices.filter(has_text=re.compile(rf'^\s*{re.escape(department)}(?:\s*\(\d+\))?\s*$')).click()
- async def wait_for_page_title(self, title_text: str, timeout: int = 10000) -> None:
+ async def wait_for_page_title(self, title_text: str, timeout_ms: int = 10000) -> None:
"""等待页面标题出现"""
- await self.page.wait_for_selector(f'div:has-text("{title_text}")', timeout=timeout)
+ await self.page.wait_for_selector(f'div:has-text("{title_text}")', timeout=timeout_ms)
page_title = await self.page.inner_text(f'div:has-text("{title_text}")')
assert title_text in page_title
- async def wait_for_selector(self, selector: str, timeout: int = 10000) -> None:
+ async def wait_for_selector(self, selector: str, timeout_ms: int = 10000) -> None:
"""等待选择器出现"""
- await self.page.wait_for_selector(selector, timeout=timeout)
+ await self.page.wait_for_selector(selector, timeout=timeout_ms)
async def query_selector(self, selector: str) -> any:
"""查询选择器元素"""
diff --git a/ruoyi-fastapi-test/prepare_e2e_compose.py b/ruoyi-fastapi-test/prepare_e2e_compose.py
index 1f078a165..09bfa89c6 100644
--- a/ruoyi-fastapi-test/prepare_e2e_compose.py
+++ b/ruoyi-fastapi-test/prepare_e2e_compose.py
@@ -79,7 +79,7 @@ def main() -> None:
parser = argparse.ArgumentParser(description='生成 CI 专用的独立 Compose 项目,不修改开发配置。')
parser.add_argument('--database', choices=['mysql', 'postgresql'], required=True)
parser.add_argument('--framework', choices=['vue2', 'vue3', 'react'], required=True)
- parser.add_argument('--python-version', choices=['3.10', '3.11', '3.12', '3.13', '3.14'], default='3.12')
+ parser.add_argument('--python-version', choices=['3.11', '3.12', '3.13', '3.14'], default='3.12')
parser.add_argument('--project', required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--docker', default='docker')
diff --git a/ruoyi-fastapi-test/ruff.toml b/ruoyi-fastapi-test/ruff.toml
index 23d788c1e..5d6399b8c 100644
--- a/ruoyi-fastapi-test/ruff.toml
+++ b/ruoyi-fastapi-test/ruff.toml
@@ -1,6 +1,6 @@
line-length = 120
show-fixes = true
-target-version = "py310"
+target-version = "py311"
unsafe-fixes = true
[lint]
From decd990e667d04033693c17ecd2bc0b639977c8b Mon Sep 17 00:00:00 2001
From: insistence <3055204202@qq.com>
Date: Sun, 22 Nov 2026 15:59:43 +0800
Subject: [PATCH 2/9] =?UTF-8?q?build:=20=E5=8D=87=E7=BA=A7=E5=90=8E?=
=?UTF-8?q?=E7=AB=AF=E5=8F=8A=E6=8F=92=E4=BB=B6=E4=BE=9D=E8=B5=96=E5=B9=B6?=
=?UTF-8?q?=E6=94=AF=E6=8C=81=20Python=203.15?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.github/requirements.txt | 6 +--
.github/scripts/ci_plan.py | 2 +-
.github/tests/test_ci_plan.py | 4 +-
.github/workflows/ci-backend.yml | 2 +-
.github/workflows/ci-frontend.yml | 2 +-
.github/workflows/ci-integration.yml | 4 +-
.github/workflows/ci-native.yml | 4 +-
.../assets/native/pyproject.toml.tmpl | 2 +-
.../assets/python/build_release.py.tmpl | 15 ++++++-
.../cli/runtime/plugin/scaffold/v2.py | 4 +-
ruoyi-fastapi-backend/common/types.py | 6 +--
ruoyi-fastapi-backend/docs/cli_usage.md | 2 +-
.../docs/plugin_development.md | 8 ++--
.../unified_authentication_developer_guide.md | 2 +-
ruoyi-fastapi-backend/plugins/ai/README.md | 30 ++++++++++++++
ruoyi-fastapi-backend/plugins/ai/plugin.yaml | 18 ++++-----
.../plugins/ai/utils/ai_util.py | 1 -
.../plugins/core/artifacts/schema.py | 6 +--
.../plugins/core/native/wheel.py | 8 ++--
ruoyi-fastapi-backend/plugins/core/utils.py | 11 ++++++
.../examples/python/task_demo/README.md | 2 +-
.../python/task_demo/build_release.py | 15 ++++++-
.../plugins/examples/rust/rust_demo/README.md | 4 +-
.../examples/rust/rust_demo/pyproject.toml | 2 +-
ruoyi-fastapi-backend/pyproject.toml | 3 +-
ruoyi-fastapi-backend/requirements-pg.txt | 24 ++++++------
ruoyi-fastapi-backend/requirements-test.txt | 6 +--
ruoyi-fastapi-backend/requirements.txt | 28 ++++++-------
.../plugins/sample_plugins/test_ai_plugin.py | 39 ++++++++++++++-----
ruoyi-fastapi-test/README.md | 8 ++--
ruoyi-fastapi-test/prepare_e2e_compose.py | 2 +-
ruoyi-fastapi-test/requirements.txt | 8 ++--
32 files changed, 180 insertions(+), 98 deletions(-)
diff --git a/.github/requirements.txt b/.github/requirements.txt
index ce1622982..a712d7a95 100644
--- a/.github/requirements.txt
+++ b/.github/requirements.txt
@@ -1,3 +1,3 @@
-pytest==9.1.1
-PyYAML==6.0.3
-ruff==0.17.1
+pytest==9.2.0
+PyYAML==6.0.4
+ruff==0.17.6
diff --git a/.github/scripts/ci_plan.py b/.github/scripts/ci_plan.py
index 5e1022776..de166ba7a 100644
--- a/.github/scripts/ci_plan.py
+++ b/.github/scripts/ci_plan.py
@@ -7,7 +7,7 @@
ROOT = Path(__file__).resolve().parents[2]
FRAMEWORKS = ('vue2', 'vue3', 'react')
-PYTHON_VERSIONS = ('3.11', '3.12', '3.13', '3.14')
+PYTHON_VERSIONS = ('3.11', '3.12', '3.13', '3.14', '3.15')
CATEGORIES = ('quality', 'backend', 'frontend', 'integration', 'e2e', 'native')
FRONTEND_FILE_PATH_PARTS = 4
diff --git a/.github/tests/test_ci_plan.py b/.github/tests/test_ci_plan.py
index 4f807f9fd..5e0988800 100644
--- a/.github/tests/test_ci_plan.py
+++ b/.github/tests/test_ci_plan.py
@@ -9,7 +9,7 @@
SPEC.loader.exec_module(ci)
FRONTEND_PROJECT_COUNT = 6
STANDARD_E2E_COMBINATION_COUNT = 6
-FULL_E2E_COMBINATION_COUNT = 24
+FULL_E2E_COMBINATION_COUNT = 30
def test_readme_change_only_runs_quality() -> None:
@@ -160,7 +160,7 @@ def test_full_run_preserves_python_database_and_framework_combinations() -> None
plan = ci.build_plan([], full=True)
assert all(plan['required'].values())
assert len(plan['e2e_matrix']['include']) == FULL_E2E_COMBINATION_COUNT
- assert {row['python'] for row in plan['e2e_matrix']['include']} == {'3.11', '3.12', '3.13', '3.14'}
+ assert {row['python'] for row in plan['e2e_matrix']['include']} == {'3.11', '3.12', '3.13', '3.14', '3.15'}
@pytest.mark.parametrize('result', ['failure', 'cancelled', 'skipped', None])
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index 4cbf51dca..b7f41ae3c 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -18,7 +18,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- python: ['3.11', '3.12', '3.13', '3.14']
+ python: ['3.11', '3.12', '3.13', '3.14', '3.15']
defaults:
run:
working-directory: ruoyi-fastapi-backend
diff --git a/.github/workflows/ci-frontend.yml b/.github/workflows/ci-frontend.yml
index 0b1b02237..07b0b6bbe 100644
--- a/.github/workflows/ci-frontend.yml
+++ b/.github/workflows/ci-frontend.yml
@@ -88,7 +88,7 @@ jobs:
- name: Install the Mobile smoke browser
if: matrix.project.target == 'mobile'
run: |
- python -m pip install playwright==1.64.0
+ python -m pip install playwright==1.65.2
python -m playwright install --with-deps chromium
- name: Verify Mobile H5 login and profile
if: matrix.project.target == 'mobile'
diff --git a/.github/workflows/ci-integration.yml b/.github/workflows/ci-integration.yml
index 00acec1b2..e8845b277 100644
--- a/.github/workflows/ci-integration.yml
+++ b/.github/workflows/ci-integration.yml
@@ -124,7 +124,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- python: ${{ fromJSON(inputs.full && '["3.11","3.12","3.13","3.14"]' || '["3.12"]') }}
+ python: ${{ fromJSON(inputs.full && '["3.11","3.12","3.13","3.14","3.15"]' || '["3.12"]') }}
defaults:
run:
working-directory: ruoyi-fastapi-backend
@@ -221,7 +221,7 @@ jobs:
with:
path: ${{ steps.pnpm-store.outputs.path }}
key: ${{ runner.os }}-network-${{ matrix.framework }}-${{ hashFiles(format('ruoyi-fastapi-frontend/{0}/web/pnpm-lock.yaml', matrix.framework)) }}
- - run: python -m pip install -r requirements.txt -r requirements-test.txt playwright==1.64.0
+ - run: python -m pip install -r requirements.txt -r requirements-test.txt playwright==1.65.2
- run: python scripts/compile_i18n.py
- run: python -m playwright install --with-deps chromium
- name: Install Web dependencies
diff --git a/.github/workflows/ci-native.yml b/.github/workflows/ci-native.yml
index b17dc0ac1..a667bec4c 100644
--- a/.github/workflows/ci-native.yml
+++ b/.github/workflows/ci-native.yml
@@ -43,7 +43,7 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
- python: ['3.11', '3.12', '3.13', '3.14']
+ python: ['3.11', '3.12', '3.13', '3.14', '3.15']
defaults:
run:
working-directory: ruoyi-fastapi-backend
@@ -54,7 +54,7 @@ jobs:
python-version: ${{ matrix.python }}
cache: pip
cache-dependency-path: ruoyi-fastapi-backend/requirements*.txt
- - run: python -m pip install -r requirements.txt -r requirements-test.txt 'maturin>=1.15,<2'
+ - run: python -m pip install -r requirements.txt -r requirements-test.txt 'maturin>=1.16.0,<2'
- run: python scripts/compile_i18n.py
- run: rustup toolchain install 1.99.0 --profile minimal
- run: rustup default 1.99.0
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/native/pyproject.toml.tmpl b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/native/pyproject.toml.tmpl
index 24187fe4c..a576387ec 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/native/pyproject.toml.tmpl
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/native/pyproject.toml.tmpl
@@ -1,5 +1,5 @@
[build-system]
-requires = ["maturin>=1.15,<2"]
+requires = ["maturin>=1.16.0,<2"]
build-backend = "maturin"
[project]
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/build_release.py.tmpl b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/build_release.py.tmpl
index cace05ef0..11f082a66 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/build_release.py.tmpl
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/build_release.py.tmpl
@@ -2,10 +2,21 @@ import argparse
import json
import shutil
import stat
+import sys
import unicodedata
-from pathlib import Path, PureWindowsPath
+from pathlib import Path
from typing import Any
+if sys.version_info >= (3, 13):
+ from ntpath import isreserved as is_windows_reserved
+else:
+ from pathlib import PureWindowsPath
+
+ def is_windows_reserved(name: str) -> bool:
+ """按 Windows 规则识别保留路径名。"""
+ return PureWindowsPath(name).is_reserved()
+
+
PLUGIN_ID = '__PLUGIN_ID__'
BUNDLE = __BUNDLE__
SOURCE = Path(__file__).resolve().parent
@@ -91,7 +102,7 @@ def checked_relative_path(value: str) -> tuple[str, ...]:
or part.startswith('.')
or part.endswith((' ', '.'))
or len(part) > MAX_COMPONENT_LENGTH
- or PureWindowsPath(part).is_reserved()
+ or is_windows_reserved(part)
or any(
char in '<>:"\\|?*[]' or ord(char) < FIRST_PRINTABLE_CHARACTER or ord(char) == DELETE_CHARACTER
for char in part
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py
index 988a794f9..225dd6a99 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py
@@ -248,7 +248,7 @@ def _readme(plugin_id: str, *, native: bool, bundle: bool, test: bool) -> str:
else ''
)
native_steps = (
- '需预先安装 Rust 工具链和匹配目标平台的编译工具,以及 `maturin>=1.15,<2`。'
+ '需预先安装 Rust 工具链和匹配目标平台的编译工具,以及 `maturin>=1.16.0,<2`。'
'模板包含 Cargo.lock,构建使用 `--locked`。二进制必须匹配部署系统、架构、Python ABI。\n\n'
if native
else 'Python 交付目录包含业务 Python 源码;签名验证不提供源码保护。\n\n'
@@ -318,7 +318,7 @@ def _readme(plugin_id: str, *, native: bool, bundle: bool, test: bool) -> str:
这是 manifest v2 的 {'Rust native' if native else 'Python'} ASGI 源码工程{',包含独立前端 bundle' if bundle else ''}。
源码位于 `{root}`,创建工程不会安装、启用或导入插件。下面的命令均在宿主后端根目录执行。
-先创建并激活 Python 3.11–3.14 环境;已有宿主环境可直接激活并使用,无需重复创建。
+先创建并激活 Python 3.11–3.15 环境;已有宿主环境可直接激活并使用,无需重复创建。
Windows PowerShell:
diff --git a/ruoyi-fastapi-backend/common/types.py b/ruoyi-fastapi-backend/common/types.py
index fb5bc6b73..ecd6fec33 100644
--- a/ruoyi-fastapi-backend/common/types.py
+++ b/ruoyi-fastapi-backend/common/types.py
@@ -69,10 +69,10 @@ def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
:return: 数据库实际使用的时间类型
"""
if dialect.name == 'postgresql':
- return dialect.type_descriptor(TIMESTAMP(timezone=True, precision=3))
+ return TIMESTAMP(timezone=True, precision=3)
if dialect.name == 'mysql':
- return dialect.type_descriptor(DATETIME(fsp=3))
- return dialect.type_descriptor(DateTime())
+ return DATETIME(fsp=3)
+ return DateTime()
def process_bind_param(self, value: datetime | None, dialect: Dialect) -> datetime | None:
"""
diff --git a/ruoyi-fastapi-backend/docs/cli_usage.md b/ruoyi-fastapi-backend/docs/cli_usage.md
index ae996a322..faff79ff6 100644
--- a/ruoyi-fastapi-backend/docs/cli_usage.md
+++ b/ruoyi-fastapi-backend/docs/cli_usage.md
@@ -39,7 +39,7 @@ ruoyi --help
### 2.2 安装依赖
-使用 Python 3.11–3.14,先进入后端目录,再创建并激活虚拟环境。以下以标准库 `venv` 为例;已有环境也可直接使用,不要求特定环境名称或安装路径。
+使用 Python 3.11–3.15,先进入后端目录,再创建并激活虚拟环境。以下以标准库 `venv` 为例;已有环境也可直接使用,不要求特定环境名称或安装路径。
Windows PowerShell:
diff --git a/ruoyi-fastapi-backend/docs/plugin_development.md b/ruoyi-fastapi-backend/docs/plugin_development.md
index 6a650f382..6c00e4ca7 100644
--- a/ruoyi-fastapi-backend/docs/plugin_development.md
+++ b/ruoyi-fastapi-backend/docs/plugin_development.md
@@ -15,7 +15,7 @@
目录插件与签名制品不能同时使用相同插件 ID。两种方式均遵守进程重启边界,不提供原生模块热替换。
-后端命令使用已安装项目依赖的 Python 3.11–3.14 环境;创建与激活步骤见 [CLI 环境准备](cli_usage.md#22-安装依赖)。下文的 `python` 指向已激活环境,命令默认在后端目录执行。通用命令同时适用于 Windows PowerShell、macOS 和 Linux;环境变量等 Shell 语法分别列出。
+后端命令使用已安装项目依赖的 Python 3.11–3.15 环境;创建与激活步骤见 [CLI 环境准备](cli_usage.md#22-安装依赖)。下文的 `python` 指向已激活环境,命令默认在后端目录执行。通用命令同时适用于 Windows PowerShell、macOS 和 Linux;环境变量等 Shell 语法分别列出。
## 1. 基本模型
@@ -971,7 +971,7 @@ Rust 使用 PyO3 暴露 Python 扩展,并通过 maturin 构建 wheel;Windows
原生 wheel 在构建或维护环境中验证并展开到 `backend.native.moduleRoot`,默认 `native/`。宿主检查发行包名称、插件版本、Python 要求、wheel tag、已安装依赖及完整 RECORD SHA256;扩展只能从当前插件目录加载,不能覆盖宿主模块。RECORD 用于检查文件一致性,发布者信任仍需第 15 节的签名流程。
-构建机需安装 Rust、maturin 和目标平台编译工具:Windows 使用 MSVC Build Tools 的 C++ 工具及 Windows SDK,macOS 使用 Xcode Command Line Tools,Linux 使用 GCC 或 Clang 等编译工具。先选择 `rust-asgi` 或 `rust-bundle` 脚手架,再按第 16 节构建。`abi3` 可减少 Python ABI 构建数量,但不能跨操作系统或架构复用制品;按实际目标平台及 Python 3.11–3.14 的测试结果验证兼容性。
+构建机需安装 Rust、maturin 和目标平台编译工具:Windows 使用 MSVC Build Tools 的 C++ 工具及 Windows SDK,macOS 使用 Xcode Command Line Tools,Linux 使用 GCC 或 Clang 等编译工具。先选择 `rust-asgi` 或 `rust-bundle` 脚手架,再按第 16 节构建。`abi3` 可减少 Python ABI 构建数量,但不能跨操作系统或架构复用制品;按实际目标平台及 Python 3.11–3.15 的测试结果验证兼容性。
Rust 通过 `PluginHostContext`、`plugin_endpoint`、`plugin_lifespan` 和版本化服务复用宿主能力,完整实现见 [Rust 示例](../plugins/examples/rust/rust_demo/README.md)。不要覆盖已加载的原生模块或依赖 `reload` 完成更新,发布后必须重启全部相关进程。
@@ -1793,9 +1793,9 @@ pnpm --dir ../ruoyi-fastapi-frontend/vue3/web run test:plugin
### 17.4 CI 覆盖
-统一入口为 [`ci.yml`](../../.github/workflows/ci.yml),完整分类和本地命令见[测试说明](../../ruoyi-fastapi-test/README.md)。[`ci-backend.yml`](../../.github/workflows/ci-backend.yml) 承担 v1/v2 脚手架、SDK 溯源、离线更新及 Windows CLI/路径回归;[`ci-native.yml`](../../.github/workflows/ci-native.yml) 保留 Windows/Linux × Python 3.11–3.14 的真实原生制品测试,Rust fmt/clippy 单独运行一次。
+统一入口为 [`ci.yml`](../../.github/workflows/ci.yml),完整分类和本地命令见[测试说明](../../ruoyi-fastapi-test/README.md)。[`ci-backend.yml`](../../.github/workflows/ci-backend.yml) 承担 v1/v2 脚手架、SDK 溯源、离线更新及 Windows CLI/路径回归;[`ci-native.yml`](../../.github/workflows/ci-native.yml) 保留 Windows/Linux × Python 3.11–3.15 的真实原生制品测试,Rust fmt/clippy 单独运行一次。
-[`ci-integration.yml`](../../.github/workflows/ci-integration.yml) 使用临时 MySQL、PostgreSQL 和 Redis 服务验证多 worker 发布行为,PR 使用 Python 3.12,完整运行覆盖 Python 3.11–3.14。工作流配置不代表已经执行成功;发布前应核对对应提交的实际 CI 结果,并完成目标平台的部署验收。
+[`ci-integration.yml`](../../.github/workflows/ci-integration.yml) 使用临时 MySQL、PostgreSQL 和 Redis 服务验证多 worker 发布行为,PR 使用 Python 3.12,完整运行覆盖 Python 3.11–3.15。工作流配置不代表已经执行成功;发布前应核对对应提交的实际 CI 结果,并完成目标平台的部署验收。
`scripts/plugin_release_integration.py` 还检查双 worker 首次发布、升级和代码回滚后的固定目标收敛,无 worker 时单次断言不收敛,旧目标代际被拒绝、单 worker 故障立即失败,以及报告过期、缺员和遗留陈旧记录下的等待结果。足够的新 worker 全部就绪后,遗留陈旧记录不应造成永久等待;失败结果保留退出码和固定原因供流水线判断。脚本还针对两种数据库启动独立的完整 CLI 进程,验证标准输出可整体解析为一个 JSON 对象,并核对未就绪时退出 `50`、就绪后退出 `0`。
diff --git a/ruoyi-fastapi-backend/docs/unified_authentication_developer_guide.md b/ruoyi-fastapi-backend/docs/unified_authentication_developer_guide.md
index 40cdbd52c..6bc91ecf1 100644
--- a/ruoyi-fastapi-backend/docs/unified_authentication_developer_guide.md
+++ b/ruoyi-fastapi-backend/docs/unified_authentication_developer_guide.md
@@ -55,7 +55,7 @@ Issuer 必须是无路径前缀、无查询串的固定公开地址。`OIDC_PUBL
## 3. 平台启用与检查
-所有后端命令在 `ruoyi-fastapi-backend` 目录执行,并使用已安装项目依赖的 Python 3.11–3.14 环境。命令适用于 Windows PowerShell、macOS 和 Linux,不依赖特定的环境管理工具、环境名称或安装路径。创建与激活步骤见 [CLI 环境准备](cli_usage.md#22-安装依赖)。下面以 `dev` 环境为例,其他环境替换为对应的 `--env` 和配置文件。
+所有后端命令在 `ruoyi-fastapi-backend` 目录执行,并使用已安装项目依赖的 Python 3.11–3.15 环境。命令适用于 Windows PowerShell、macOS 和 Linux,不依赖特定的环境管理工具、环境名称或安装路径。创建与激活步骤见 [CLI 环境准备](cli_usage.md#22-安装依赖)。下面以 `dev` 环境为例,其他环境替换为对应的 `--env` 和配置文件。
`ruoyi` 命令在三个平台上的参数一致。激活环境后,直接调用解释器统一使用 `python`;在新终端执行命令前也应激活同一环境。
diff --git a/ruoyi-fastapi-backend/plugins/ai/README.md b/ruoyi-fastapi-backend/plugins/ai/README.md
index d33956dcd..11835d62d 100644
--- a/ruoyi-fastapi-backend/plugins/ai/README.md
+++ b/ruoyi-fastapi-backend/plugins/ai/README.md
@@ -131,6 +131,36 @@ ruoyi plugin install-deps ai --env=dev
脚本按插件生命周期执行,支持重复检查和按数据库类型过滤。
+### 从 Agno 2 升级已有数据库
+
+Agno 3 将对话运行记录从 `ai_sessions.runs` 拆分到 `ai_sessions_runs`。已有部署可在停止旧版后端、备份数据库并安装新版插件依赖后,在后端目录使用目标环境的 `APP_ENV` 运行以下 Python 代码。它调用 Agno 的版本化迁移,只处理当前插件已经创建的表,并保留旧会话列。新安装可直接使用新版表结构。
+
+```python
+import asyncio
+
+from agno.db.migrations.manager import MigrationManager
+from plugins.ai.utils.ai_util import AiUtil
+
+
+async def migrate():
+ storage = AiUtil.get_storage_engine()
+ manager = MigrationManager(storage)
+ try:
+ for kind, table in (
+ ('sessions', storage.session_table_name),
+ ('metrics', storage.metrics_table_name),
+ ('evals', storage.eval_table_name),
+ ('knowledge', storage.knowledge_table_name),
+ ):
+ if await storage.table_exists(table):
+ await manager.up(target_version='3.0.0', table_type=kind)
+ finally:
+ await storage.close()
+
+
+asyncio.run(migrate())
+```
+
## 开发注意
- 后端模块路径必须保持为 `plugins.ai`,与插件 ID 对齐。
diff --git a/ruoyi-fastapi-backend/plugins/ai/plugin.yaml b/ruoyi-fastapi-backend/plugins/ai/plugin.yaml
index a883113b8..0e0133c6b 100644
--- a/ruoyi-fastapi-backend/plugins/ai/plugin.yaml
+++ b/ruoyi-fastapi-backend/plugins/ai/plugin.yaml
@@ -92,17 +92,17 @@ permissions:
dependencies:
python:
- - agno==2.8.6
- - anthropic==0.120.2
+ - agno==3.2.1
+ - anthropic==2.12.0
- cerebras-cloud-sdk==1.91.0
- - cohere==7.0.8
- - google-genai==2.16.0
- - groq==1.6.0
- - litellm==1.94.0
+ - cohere==7.3.2
+ - google-genai==3.6.1
+ - groq==1.7.0
+ - litellm==1.110.2
- llama-api-client==0.6.0
- - mistralai==2.10.1
- - ollama==0.6.2
- - openai==2.52.0
+ - mistralai==3.8.0
+ - ollama==0.6.3
+ - openai==3.57.0
- portkey-ai==2.3.4
frontend:
vue2:
diff --git a/ruoyi-fastapi-backend/plugins/ai/utils/ai_util.py b/ruoyi-fastapi-backend/plugins/ai/utils/ai_util.py
index 6a07066a2..416abf748 100644
--- a/ruoyi-fastapi-backend/plugins/ai/utils/ai_util.py
+++ b/ruoyi-fastapi-backend/plugins/ai/utils/ai_util.py
@@ -123,7 +123,6 @@ def get_storage_engine(cls) -> 'AsyncBaseDb':
metrics_table='ai_metrics',
eval_table='ai_eval_runs',
knowledge_table='ai_knowledge',
- culture_table='ai_culture',
traces_table='ai_traces',
spans_table='ai_spans',
versions_table='ai_schema_versions',
diff --git a/ruoyi-fastapi-backend/plugins/core/artifacts/schema.py b/ruoyi-fastapi-backend/plugins/core/artifacts/schema.py
index c1f63ffc9..d0154e982 100644
--- a/ruoyi-fastapi-backend/plugins/core/artifacts/schema.py
+++ b/ruoyi-fastapi-backend/plugins/core/artifacts/schema.py
@@ -3,7 +3,7 @@
import re
import unicodedata
from dataclasses import dataclass
-from pathlib import Path, PurePosixPath, PureWindowsPath
+from pathlib import Path, PurePosixPath
from typing import Any, Literal
from cryptography.hazmat.primitives import serialization
@@ -11,7 +11,7 @@
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from plugins.core.manifest.schema import PluginManifest
-from plugins.core.utils import validate_plugin_id_value
+from plugins.core.utils import is_windows_reserved, validate_plugin_id_value
DIGEST_PATTERN = re.compile(r'^[a-f0-9]{64}$')
KEY_ID_PATTERN = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$')
@@ -65,7 +65,7 @@ def safe_artifact_path(value: str) -> PurePosixPath:
part in {'', '.', '..'}
or len(part) > MAX_COMPONENT_LENGTH
or part.endswith((' ', '.'))
- or PureWindowsPath(part).is_reserved()
+ or is_windows_reserved(part)
or any(
char in '<>:"\\|?*' or ord(char) < FIRST_PRINTABLE_CHARACTER or ord(char) == DELETE_CHARACTER
for char in part
diff --git a/ruoyi-fastapi-backend/plugins/core/native/wheel.py b/ruoyi-fastapi-backend/plugins/core/native/wheel.py
index 54655e07c..9012e479d 100644
--- a/ruoyi-fastapi-backend/plugins/core/native/wheel.py
+++ b/ruoyi-fastapi-backend/plugins/core/native/wheel.py
@@ -7,7 +7,7 @@
import shutil
import stat
from email.parser import Parser
-from pathlib import Path, PurePosixPath, PureWindowsPath
+from pathlib import Path, PurePosixPath
from zipfile import ZipFile, ZipInfo
from packaging.requirements import Requirement
@@ -17,6 +17,7 @@
from packaging.version import Version
from plugins.core.manifest.schema import PluginManifest
+from plugins.core.utils import is_windows_reserved
MAX_WHEEL_FILES = 10000
MAX_WHEEL_BYTES = 512 * 1024 * 1024
@@ -89,10 +90,7 @@ def _safe_member(name: str) -> PurePosixPath:
or path.is_absolute()
or '\\' in name
or ':' in name
- or any(
- part in {'', '.', '..'} or part.endswith((' ', '.')) or PureWindowsPath(part).is_reserved()
- for part in parts
- )
+ or any(part in {'', '.', '..'} or part.endswith((' ', '.')) or is_windows_reserved(part) for part in parts)
):
raise ValueError(f'wheel 中包含不安全路径:{name}')
return path
diff --git a/ruoyi-fastapi-backend/plugins/core/utils.py b/ruoyi-fastapi-backend/plugins/core/utils.py
index e046808b8..50fda132d 100644
--- a/ruoyi-fastapi-backend/plugins/core/utils.py
+++ b/ruoyi-fastapi-backend/plugins/core/utils.py
@@ -1,4 +1,15 @@
import re
+import sys
+
+if sys.version_info >= (3, 13):
+ from ntpath import isreserved as is_windows_reserved
+else:
+ from pathlib import PureWindowsPath
+
+ def is_windows_reserved(name: str) -> bool:
+ """按 Windows 规则识别保留路径名。"""
+ return PureWindowsPath(name).is_reserved()
+
PLUGIN_ID_PATTERN_TEXT = r'[a-z][a-z0-9_]{1,63}'
PLUGIN_ID_PATTERN = re.compile(rf'^{PLUGIN_ID_PATTERN_TEXT}$')
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/README.md b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/README.md
index 22e1ae7a4..f53a3a18a 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/README.md
+++ b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/README.md
@@ -2,7 +2,7 @@
`task_demo` 是 manifest v2 的 Python ASGI + 独立 bundle 业务示例,当前版本 `1.1.0`。页面提供新增、编辑、删除、状态筛选和分页;数据保存在宿主默认数据源的 `ruoyi_plugin_task_demo` 表中。它演示插件级共享任务清单:有查看权限的用户看到同一组任务,未实现个人、部门或租户数据隔离。
-源码位于 `plugins/examples/python/task_demo`,示例目录不参与运行时插件扫描。下面的命令均在后端根目录、已激活并安装宿主依赖的 Python 3.11–3.14 环境执行,适用于 Windows PowerShell、macOS 和 Linux;前端构建使用 Node.js 22。
+源码位于 `plugins/examples/python/task_demo`,示例目录不参与运行时插件扫描。下面的命令均在后端根目录、已激活并安装宿主依赖的 Python 3.11–3.15 环境执行,适用于 Windows PowerShell、macOS 和 Linux;前端构建使用 Node.js 22。
## 构建与测试
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/build_release.py b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/build_release.py
index 4032fd017..1faacc6d9 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/build_release.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/build_release.py
@@ -2,10 +2,21 @@
import json
import shutil
import stat
+import sys
import unicodedata
-from pathlib import Path, PureWindowsPath
+from pathlib import Path
from typing import Any
+if sys.version_info >= (3, 13):
+ from ntpath import isreserved as is_windows_reserved
+else:
+ from pathlib import PureWindowsPath
+
+ def is_windows_reserved(name: str) -> bool:
+ """按 Windows 规则识别保留路径名。"""
+ return PureWindowsPath(name).is_reserved()
+
+
PLUGIN_ID = 'task_demo'
BUNDLE = True
SOURCE = Path(__file__).resolve().parent
@@ -91,7 +102,7 @@ def checked_relative_path(value: str) -> tuple[str, ...]:
or part.startswith('.')
or part.endswith((' ', '.'))
or len(part) > MAX_COMPONENT_LENGTH
- or PureWindowsPath(part).is_reserved()
+ or is_windows_reserved(part)
or any(
char in '<>:"\\|?*[]' or ord(char) < FIRST_PRINTABLE_CHARACTER or ord(char) == DELETE_CHARACTER
for char in part
diff --git a/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/README.md b/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/README.md
index b5a51f97e..690108848 100644
--- a/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/README.md
+++ b/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/README.md
@@ -13,7 +13,7 @@
构建端需要 Rust 及目标平台编译工具:Windows 使用 Rust MSVC 工具链、Visual Studio Build Tools 的 C++ 工具和 Windows SDK;macOS 使用 Xcode Command Line Tools;Linux 使用 GCC 或 Clang 等编译工具。部署端使用构建好的匹配平台制品,无需安装 Rust。
```bash
-python -m pip install 'maturin>=1.15,<2'
+python -m pip install 'maturin>=1.16.0,<2'
rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
rustup default 1.99.0
python scripts/build_native_plugin.py --output target/native-package
@@ -61,7 +61,7 @@ cargo clippy --manifest-path plugins/examples/rust/rust_demo/Cargo.toml --locked
测试直接加载编译后的扩展,覆盖 ASGI、Router、原生 future、Python 协程桥、权限、异常、取消、lifespan 和真实 APScheduler 单次分发。数据库与登录使用替身;测试不会安装、启用插件或写入实际业务数据库。不设置环境变量时,真实原生测试明确跳过。
-仓库的 `.github/workflows/ci-native.yml` 配置 Windows/Linux、Python 3.11、3.12、3.13、3.14 构建测试矩阵。应以目标平台对应的实际构建与测试结果确认兼容性。
+仓库的 `.github/workflows/ci-native.yml` 配置 Windows/Linux、Python 3.11、3.12、3.13、3.14、3.15 构建测试矩阵。应以目标平台对应的实际构建与测试结果确认兼容性。
## 签名制品与维护发布
diff --git a/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/pyproject.toml b/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/pyproject.toml
index 0b6fa7fe7..3544b7ddb 100644
--- a/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/pyproject.toml
+++ b/ruoyi-fastapi-backend/plugins/examples/rust/rust_demo/pyproject.toml
@@ -1,5 +1,5 @@
[build-system]
-requires = ["maturin>=1.15,<2"]
+requires = ["maturin>=1.16.0,<2"]
build-backend = "maturin"
[project]
diff --git a/ruoyi-fastapi-backend/pyproject.toml b/ruoyi-fastapi-backend/pyproject.toml
index a195c5c75..91506d3e6 100644
--- a/ruoyi-fastapi-backend/pyproject.toml
+++ b/ruoyi-fastapi-backend/pyproject.toml
@@ -1,5 +1,5 @@
[build-system]
-requires = ["setuptools"]
+requires = ["setuptools>=84.2.1"]
build-backend = "setuptools.build_meta"
[project]
@@ -13,6 +13,7 @@ ruoyi = "cli.main:main"
[tool.pytest.ini_options]
pythonpath = ["."]
+asyncio_default_fixture_loop_scope = "fixture-scope"
markers = [
"browser: requires a real browser and the frontend network test host",
"native: requires a prebuilt native plugin artifact",
diff --git a/ruoyi-fastapi-backend/requirements-pg.txt b/ruoyi-fastapi-backend/requirements-pg.txt
index e4a2faf86..36c04c2da 100644
--- a/ruoyi-fastapi-backend/requirements-pg.txt
+++ b/ruoyi-fastapi-backend/requirements-pg.txt
@@ -1,27 +1,27 @@
aiofiles==25.1.0
-alembic==1.20.0
+alembic==1.20.1
APScheduler==3.11.3
async-lru==2.4.0
asyncpg==0.32.0
-Babel==2.17.0
+Babel==2.18.0
bcrypt==5.0.0
-fastapi[all]==0.143.3
-loguru==0.7.3
-nh3==0.3.7
+fastapi[all]==0.165.0
+loguru==0.8.0
+nh3==0.3.8
openpyxl==3.1.5
packaging==26.3
-pandas==2.3.3
-Pillow==12.3.0
+pandas==3.1.1
+Pillow==13.0.0
psutil==7.2.2
psycopg2==2.9.13
-pydantic==2.14.1
+pydantic==2.14.4
pydantic-validation-decorator==0.1.5
PyJWT[crypto]==2.15.1
redis==8.1.0
-ruff==0.17.1
-SQLAlchemy[asyncio]==2.0.55
-sqlglot==30.23.0
+ruff==0.17.6
+SQLAlchemy[asyncio]==2.1.9
+sqlglot==30.33.0
textual==8.2.8
-tzdata==2026.5
+tzdata==2026.6
user-agents==2.2.0
.
diff --git a/ruoyi-fastapi-backend/requirements-test.txt b/ruoyi-fastapi-backend/requirements-test.txt
index 0f0e6a6c2..d3abf03dc 100644
--- a/ruoyi-fastapi-backend/requirements-test.txt
+++ b/ruoyi-fastapi-backend/requirements-test.txt
@@ -1,4 +1,4 @@
aiosqlite==0.22.1
-pytest==9.1.1
-pytest-asyncio==1.4.0
-PyYAML==6.0.3
+pytest==9.2.0
+pytest-asyncio==1.5.0
+PyYAML==6.0.4
diff --git a/ruoyi-fastapi-backend/requirements.txt b/ruoyi-fastapi-backend/requirements.txt
index 6acd1b149..73d5ee9c4 100644
--- a/ruoyi-fastapi-backend/requirements.txt
+++ b/ruoyi-fastapi-backend/requirements.txt
@@ -1,27 +1,27 @@
aiofiles==25.1.0
-alembic==1.20.0
+alembic==1.20.1
APScheduler==3.11.3
async-lru==2.4.0
-asyncmy==0.2.16
-Babel==2.17.0
+asyncmy==0.2.18
+Babel==2.18.0
bcrypt==5.0.0
-fastapi[all]==0.143.3
-loguru==0.7.3
-nh3==0.3.7
+fastapi[all]==0.165.0
+loguru==0.8.0
+nh3==0.3.8
openpyxl==3.1.5
packaging==26.3
-pandas==2.3.3
-Pillow==12.3.0
+pandas==3.1.1
+Pillow==13.0.0
psutil==7.2.2
-pydantic==2.14.1
+pydantic==2.14.4
pydantic-validation-decorator==0.1.5
PyJWT[crypto]==2.15.1
-PyMySQL==1.2.3
+PyMySQL==1.2.4
redis==8.1.0
-ruff==0.17.1
-SQLAlchemy[asyncio]==2.0.55
-sqlglot==30.23.0
+ruff==0.17.6
+SQLAlchemy[asyncio]==2.1.9
+sqlglot==30.33.0
textual==8.2.8
-tzdata==2026.5
+tzdata==2026.6
user-agents==2.2.0
.
diff --git a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_plugin.py b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_plugin.py
index 0ea02ab2e..90ae4291a 100644
--- a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_plugin.py
+++ b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_plugin.py
@@ -2,7 +2,10 @@
from pathlib import Path
import pytest
+from sqlalchemy.ext.asyncio import create_async_engine
+from config.database import DataSourceRegistry
+from config.env import DataBaseConfig
from plugins.ai.dao.ai_chat_dao import AiChatConfigDao
from plugins.ai.dao.ai_model_dao import AiModelDao
from plugins.ai.entity.vo.ai_chat_vo import AiChatConfigModel, AiChatRequestModel
@@ -25,17 +28,17 @@
'ai:chat:list',
}
EXPECTED_AI_PYTHON_DEPENDENCIES = [
- 'agno==2.8.6',
- 'anthropic==0.120.2',
+ 'agno==3.2.1',
+ 'anthropic==2.12.0',
'cerebras-cloud-sdk==1.91.0',
- 'cohere==7.0.8',
- 'google-genai==2.16.0',
- 'groq==1.6.0',
- 'litellm==1.94.0',
+ 'cohere==7.3.2',
+ 'google-genai==3.6.1',
+ 'groq==1.7.0',
+ 'litellm==1.110.2',
'llama-api-client==0.6.0',
- 'mistralai==2.10.1',
- 'ollama==0.6.2',
- 'openai==2.52.0',
+ 'mistralai==3.8.0',
+ 'ollama==0.6.3',
+ 'openai==3.57.0',
'portkey-ai==2.3.4',
]
EXPECTED_AI_VUE2_NPM_DEPENDENCIES = [
@@ -251,6 +254,24 @@ def fake_resolve_provider_class(cls: type[AiUtil], provider: str) -> type[FakeMo
)
+@pytest.mark.parametrize(('db_type', 'schema'), [('mysql', 'ai_test'), ('postgresql', 'public')])
+@pytest.mark.asyncio
+async def test_ai_storage_uses_plugin_tables(db_type: str, schema: str, monkeypatch: pytest.MonkeyPatch) -> None:
+ """两个 Agno 存储适配器均能使用宿主引擎和既有的会话表。"""
+ engine = create_async_engine('sqlite+aiosqlite://')
+ monkeypatch.setattr(DataBaseConfig.default_source, 'db_type', db_type)
+ monkeypatch.setattr(DataBaseConfig.default_source, 'db_database', 'ai_test')
+ monkeypatch.setattr(DataSourceRegistry, 'get_async_engine', lambda name: engine)
+ try:
+ storage = AiUtil.get_storage_engine()
+ assert storage.db_engine is engine
+ assert storage.db_schema == schema
+ assert storage.session_table_name == 'ai_sessions'
+ assert storage.runs_table_name == 'ai_sessions_runs'
+ finally:
+ await engine.dispose()
+
+
def test_ai_model_factory_validates_base_url_boundary() -> None:
"""校验 AI 模型工厂限制基础 URL 的信任边界。"""
assert AiUtil._validate_base_url('https://api.example.com/v1') == 'https://api.example.com/v1'
diff --git a/ruoyi-fastapi-test/README.md b/ruoyi-fastapi-test/README.md
index ca8ddcab7..1658973f5 100644
--- a/ruoyi-fastapi-test/README.md
+++ b/ruoyi-fastapi-test/README.md
@@ -9,13 +9,13 @@
| 分类 | 工作流 | 主要检查 |
| --- | --- | --- |
| Quality | [ci-quality.yml](../.github/workflows/ci-quality.yml) | Python/六个前端工程格式、actionlint、选路与失败门禁测试、三框架 × 四份 Compose 配置 |
-| Backend | [ci-backend.yml](../.github/workflows/ci-backend.yml) | Python 3.11–3.14 单元与契约、Windows CLI/路径、三种宿主时区 |
+| Backend | [ci-backend.yml](../.github/workflows/ci-backend.yml) | Python 3.11–3.15 单元与契约、Windows CLI/路径、三种宿主时区 |
| Frontend | [ci-frontend.yml](../.github/workflows/ci-frontend.yml) | Node 22/24 × 六工程单元测试、三时区契约、Web prod/docker、移动端 H5/微信及 H5 登录;React Mobile 的 Android/iOS JS bundle,完整模式增加其他小程序与鸿蒙构建 |
| Integration | [ci-integration.yml](../.github/workflows/ci-integration.yml) | 双数据库时间持久化、插件发布、Vue2/Vue3/React HTTPS 代理与 SSE/WebSocket |
| E2E | [ci-e2e.yml](../.github/workflows/ci-e2e.yml) | 三框架的独立数据库和应用容器、Chromium 登录/权限/29 个菜单页面/时区,以及全部业务操作用例 |
-| Native | [ci-native.yml](../.github/workflows/ci-native.yml) | Rust fmt/clippy、Windows/Linux × Python 3.11–3.14 的真实原生制品 |
+| Native | [ci-native.yml](../.github/workflows/ci-native.yml) | Rust fmt/clippy、Windows/Linux × Python 3.11–3.15 的真实原生制品 |
-PR 按 `.github/scripts/ci_plan.py` 的变更影响规则选择分类与前端工程,框架包含 `vue2`、`vue3`、`react`。单个移动端的改动只运行对应前端工程,不触发 Web E2E 或 Rust Native。共享依赖和 CI 变更触发全部分类;仅文档变更运行 Quality。PR E2E 使用 Python 3.12,受影响的每个 Web 框架分别测试 MySQL 和 PostgreSQL。`master` 推送、每天 UTC 18:21(北京时间次日 02:21)及手动 `full=true` 扩展为四个 Python 版本(3.11–3.14),共 24 个 E2E 组合;插件发布集成测试也覆盖这四个版本,并增加 React Mobile 的支付宝、百度、抖音、QQ、京东、快手、飞书、小红书和鸿蒙构建。手动 `full=false` 运行所有分类的 PR 规模矩阵。
+PR 按 `.github/scripts/ci_plan.py` 的变更影响规则选择分类与前端工程,框架包含 `vue2`、`vue3`、`react`。单个移动端的改动只运行对应前端工程,不触发 Web E2E 或 Rust Native。共享依赖和 CI 变更触发全部分类;仅文档变更运行 Quality。PR E2E 使用 Python 3.12,受影响的每个 Web 框架分别测试 MySQL 和 PostgreSQL。`master` 推送、每天 UTC 18:21(北京时间次日 02:21)及手动 `full=true` 扩展为五个 Python 版本(3.11–3.15),共 30 个 E2E 组合;插件发布集成测试也覆盖这五个版本,并增加 React Mobile 的支付宝、百度、抖音、QQ、京东、快手、飞书、小红书和鸿蒙构建。手动 `full=false` 运行所有分类的 PR 规模矩阵。
Vue2、Vue3、React 执行相同的全部 `e2e` 用例,当前每个框架收集 109 项。覆盖账号资料与锁屏、系统管理 CRUD 与授权、文件上传下载、插件和 OAuth 管理、缓存与服务监控、强退、任务执行及日志、代码生成和表单构建。选择器按实际 Element / Ant Design 组件适配,保留真实 API 响应、保存值与清理断言;React 导出用例校验 JSX 内容。完整模式与 PR 模式使用同一套业务用例。
@@ -54,7 +54,7 @@ pnpm run build:h5
pnpm run build:mp-weixin
# 返回仓库根目录,安装 Chromium 后验证实际 H5 构建
-python -m pip install playwright==1.64.0
+python -m pip install playwright==1.65.2
python -m playwright install chromium
python .github/scripts/mobile_smoke.py --framework vue2
python .github/scripts/mobile_smoke.py --framework vue3
diff --git a/ruoyi-fastapi-test/prepare_e2e_compose.py b/ruoyi-fastapi-test/prepare_e2e_compose.py
index 09bfa89c6..c6467899c 100644
--- a/ruoyi-fastapi-test/prepare_e2e_compose.py
+++ b/ruoyi-fastapi-test/prepare_e2e_compose.py
@@ -79,7 +79,7 @@ def main() -> None:
parser = argparse.ArgumentParser(description='生成 CI 专用的独立 Compose 项目,不修改开发配置。')
parser.add_argument('--database', choices=['mysql', 'postgresql'], required=True)
parser.add_argument('--framework', choices=['vue2', 'vue3', 'react'], required=True)
- parser.add_argument('--python-version', choices=['3.11', '3.12', '3.13', '3.14'], default='3.12')
+ parser.add_argument('--python-version', choices=['3.11', '3.12', '3.13', '3.14', '3.15'], default='3.12')
parser.add_argument('--project', required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--docker', default='docker')
diff --git a/ruoyi-fastapi-test/requirements.txt b/ruoyi-fastapi-test/requirements.txt
index 5f1030aea..7e7d5f95f 100644
--- a/ruoyi-fastapi-test/requirements.txt
+++ b/ruoyi-fastapi-test/requirements.txt
@@ -1,6 +1,6 @@
-playwright==1.64.0
-pytest==9.1.1
-pytest-asyncio==1.4.0
+playwright==1.65.2
+pytest==9.2.0
+pytest-asyncio==1.5.0
pytest-playwright==0.10.0
requests==2.34.2
-ruff==0.17.1
+ruff==0.17.6
From 9f3a0fdf20367ce221d2b84892d7b32ef064a43a Mon Sep 17 00:00:00 2001
From: insistence <3055204202@qq.com>
Date: Mon, 23 Nov 2026 18:43:54 +0800
Subject: [PATCH 3/9] =?UTF-8?q?feat:=20=E7=BB=9F=E4=B8=80=20Python=20?=
=?UTF-8?q?=E4=B8=AD=E6=96=87=20reST=20=E6=96=87=E6=A1=A3=E5=B9=B6?=
=?UTF-8?q?=E6=A0=A1=E9=AA=8C=E6=A8=A1=E5=9E=8B=E5=AD=97=E6=AE=B5=E5=92=8C?=
=?UTF-8?q?=E8=B7=AF=E7=94=B1=E8=AF=B4=E6=98=8E?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.github/requirements.txt | 2 +
.github/scripts/check_compose.py | 8 +-
.github/scripts/check_test_report.py | 7 +-
.github/scripts/ci_plan.py | 3 +-
.../scripts/install_ai_test_dependencies.py | 2 +-
.github/scripts/mobile_smoke.py | 16 +-
.github/tests/test_ci_contracts.py | 6 +-
.github/tests/test_ci_python_matrix.py | 8 +-
.github/workflows/ci-quality.yml | 1 +
.../.x18n/scan_python_domains.py | 9 +-
ruoyi-fastapi-backend/cli/bootstrap.py | 5 +-
.../cli/completion/commands.py | 16 +-
.../cli/completion/controller.py | 18 +-
.../cli/completion/doctor.py | 9 +-
.../cli/completion/installers.py | 27 +-
.../cli/completion/presenter.py | 2 +-
.../cli/completion/providers.py | 82 +-
.../cli/completion/shells.py | 13 +-
ruoyi-fastapi-backend/cli/context.py | 16 +-
ruoyi-fastapi-backend/cli/core/__init__.py | 12 +-
ruoyi-fastapi-backend/cli/core/app_builder.py | 56 +-
.../cli/core/completion_dispatcher.py | 24 +-
.../cli/core/context_factory.py | 41 +-
ruoyi-fastapi-backend/cli/core/execution.py | 8 +-
.../cli/groups/app/command.py | 5 -
.../cli/groups/app/controller.py | 18 +-
.../cli/groups/app/presenter.py | 2 +-
.../cli/groups/cache/command.py | 6 -
.../cli/groups/cache/controller.py | 16 +-
.../cli/groups/cache/presenter.py | 2 +-
.../cli/groups/config/command.py | 5 -
.../cli/groups/config/controller.py | 15 +-
.../cli/groups/config/presenter.py | 2 +-
.../cli/groups/crypto/command.py | 4 -
.../cli/groups/crypto/controller.py | 14 +-
.../cli/groups/crypto/presenter.py | 2 +-
.../cli/groups/db/command.py | 8 -
.../cli/groups/db/controller.py | 18 +-
.../cli/groups/db/presenter.py | 2 +-
.../cli/groups/dev/command.py | 6 +-
.../cli/groups/dev/controller.py | 14 +-
.../cli/groups/dev/presenter.py | 4 +-
.../cli/groups/gen/command.py | 8 -
.../cli/groups/gen/controller.py | 18 +-
.../cli/groups/gen/presenter.py | 2 +-
.../cli/groups/job/command.py | 7 -
.../cli/groups/job/controller.py | 18 +-
.../cli/groups/job/presenter.py | 2 +-
.../cli/groups/oidc/command.py | 3 +-
.../cli/groups/oidc/controller.py | 12 +-
.../cli/groups/ops/command.py | 5 -
.../cli/groups/ops/controller.py | 16 +-
.../cli/groups/ops/presenter.py | 2 +-
.../cli/groups/plugin/artifact_controller.py | 24 +-
.../cli/groups/plugin/commands/artifact.py | 14 -
.../plugin/commands/artifact_maintenance.py | 5 -
.../groups/plugin/commands/configuration.py | 2 -
.../cli/groups/plugin/commands/dependency.py | 7 -
.../cli/groups/plugin/commands/developer.py | 3 -
.../cli/groups/plugin/commands/discovery.py | 7 -
.../cli/groups/plugin/commands/lifecycle.py | 11 -
.../cli/groups/plugin/commands/sdk.py | 4 -
.../cli/groups/plugin/controller.py | 42 +-
.../cli/groups/plugin/options.py | 52 +-
.../cli/groups/plugin/payload.py | 11 +-
.../cli/groups/plugin/presenter.py | 5 +-
ruoyi-fastapi-backend/cli/guards.py | 22 +-
ruoyi-fastapi-backend/cli/main.py | 27 +-
.../cli/metadata/command_specs.py | 16 +-
.../cli/metadata/option_specs.py | 2 +-
.../cli/metadata/risk_specs.py | 8 +-
ruoyi-fastapi-backend/cli/output.py | 55 +-
.../cli/runtime/app/service.py | 7 +-
.../cli/runtime/app/support.py | 5 +-
ruoyi-fastapi-backend/cli/runtime/base.py | 2 +-
.../cli/runtime/cache/service.py | 7 +-
.../cli/runtime/cache/support.py | 12 +-
.../cli/runtime/config/service.py | 7 +-
.../cli/runtime/config/support.py | 4 +-
.../cli/runtime/crypto/service.py | 28 +-
.../cli/runtime/crypto/support.py | 4 +-
.../cli/runtime/db/gateway.py | 4 +-
.../cli/runtime/db/service.py | 13 +-
.../cli/runtime/db/support.py | 8 +-
.../cli/runtime/dev/gateway.py | 9 +-
.../cli/runtime/dev/service.py | 26 +-
.../cli/runtime/dev/support.py | 5 +-
.../cli/runtime/gen/gateway.py | 8 +-
.../cli/runtime/gen/service.py | 7 +-
.../cli/runtime/gen/support.py | 4 +-
.../cli/runtime/job/service.py | 11 +-
.../cli/runtime/job/support.py | 7 +-
.../cli/runtime/oidc/gateway.py | 12 +-
.../cli/runtime/oidc/service.py | 11 +-
.../cli/runtime/ops/gateway.py | 6 +-
.../cli/runtime/ops/service.py | 7 +-
.../cli/runtime/ops/support.py | 13 +-
.../cli/runtime/plugin/gateway.py | 2 +-
.../scaffold/assets/python/__init__.py.tmpl | 1 -
.../assets/python/build_release.py.tmpl | 20 +-
.../scaffold/assets/test_plugin.py.tmpl | 6 +-
.../cli/runtime/plugin/scaffold/backend.py | 4 +-
.../cli/runtime/plugin/scaffold/builder.py | 10 +-
.../cli/runtime/plugin/scaffold/frontend.py | 62 +-
.../runtime/plugin/scaffold/frontend_react.py | 28 +-
.../runtime/plugin/scaffold/frontend_vue2.py | 4 +-
.../cli/runtime/plugin/scaffold/locales.py | 4 +
.../cli/runtime/plugin/scaffold/naming.py | 4 +-
.../cli/runtime/plugin/scaffold/options.py | 21 +-
.../cli/runtime/plugin/scaffold/payload.py | 29 +-
.../cli/runtime/plugin/scaffold/v2.py | 6 +-
.../cli/runtime/plugin/sdk.py | 22 +-
.../cli/runtime/plugin/service.py | 17 +-
.../cli/runtime/plugin/support.py | 92 +-
.../cli/tui/actions/assembly.py | 10 +-
.../cli/tui/actions/builders.py | 22 +-
.../cli/tui/actions/execution.py | 78 +-
.../cli/tui/actions/factories/cache.py | 2 +-
.../cli/tui/actions/factories/gen.py | 2 +-
.../cli/tui/actions/factories/jobs.py | 2 +-
.../cli/tui/actions/factories/static.py | 2 +-
.../cli/tui/actions/models.py | 16 +-
.../cli/tui/actions/presentation.py | 3 +
.../cli/tui/actions/registry.py | 10 +-
.../cli/tui/adapters/__init__.py | 2 +-
ruoyi-fastapi-backend/cli/tui/adapters/app.py | 63 +-
.../cli/tui/adapters/base.py | 14 +-
.../cli/tui/adapters/cache.py | 35 +-
.../cli/tui/adapters/configs.py | 31 +-
.../cli/tui/adapters/crypto.py | 33 +-
.../cli/tui/adapters/database.py | 49 +-
ruoyi-fastapi-backend/cli/tui/adapters/gen.py | 39 +-
.../cli/tui/adapters/health.py | 72 +-
.../cli/tui/adapters/jobs.py | 31 +-
.../cli/tui/adapters/models.py | 42 +-
ruoyi-fastapi-backend/cli/tui/adapters/ops.py | 51 +-
ruoyi-fastapi-backend/cli/tui/app.py | 187 +--
ruoyi-fastapi-backend/cli/tui/capabilities.py | 24 +-
ruoyi-fastapi-backend/cli/tui/commands.py | 24 +-
ruoyi-fastapi-backend/cli/tui/copy/actions.py | 4 +-
.../cli/tui/copy/navigation.py | 6 +-
.../cli/tui/copy/workspace.py | 4 +-
ruoyi-fastapi-backend/cli/tui/diagnostics.py | 65 +-
ruoyi-fastapi-backend/cli/tui/keymaps.py | 2 +-
ruoyi-fastapi-backend/cli/tui/platform.py | 8 +-
ruoyi-fastapi-backend/cli/tui/queries.py | 204 ++-
.../cli/tui/screens/browser.py | 112 +-
.../cli/tui/screens/confirm.py | 44 +-
.../cli/tui/screens/dashboard.py | 23 +-
.../cli/tui/screens/detail.py | 62 +-
.../cli/tui/screens/focus.py | 52 +-
.../cli/tui/screens/interactions.py | 60 +-
.../cli/tui/screens/search.py | 23 +
.../cli/tui/screens/summary.py | 14 +-
ruoyi-fastapi-backend/cli/tui/search.py | 22 +-
.../cli/tui/widgets/status_panel.py | 46 +-
.../cli/tui/widgets/workspace.py | 195 ++-
ruoyi-fastapi-backend/cli/utils.py | 26 +-
.../cli/wizard/aggregators.py | 10 +-
ruoyi-fastapi-backend/cli/wizard/base.py | 60 +-
ruoyi-fastapi-backend/cli/wizard/commands.py | 40 +-
.../cli/wizard/flows/app_run.py | 26 +-
.../cli/wizard/flows/cache_clear.py | 37 +-
.../cli/wizard/flows/db_upgrade.py | 27 +-
.../cli/wizard/flows/gen_export.py | 37 +-
.../cli/wizard/flows/gen_import.py | 27 +-
.../cli/wizard/flows/prod_check.py | 24 +-
.../cli/wizard/presenters.py | 6 +-
.../common/annotation/cache_annotation.py | 93 +-
.../common/annotation/log_annotation.py | 186 ++-
.../common/annotation/pydantic_annotation.py | 22 +-
.../annotation/rate_limit_annotation.py | 127 +-
.../common/aspect/data_scope.py | 21 +-
.../common/aspect/db_session.py | 17 +-
.../common/aspect/interface_auth.py | 32 +-
.../common/aspect/pre_auth.py | 10 +-
ruoyi-fastapi-backend/common/auth_policy.py | 38 +-
ruoyi-fastapi-backend/common/constant.py | 612 ++++----
ruoyi-fastapi-backend/common/context.py | 37 +-
ruoyi-fastapi-backend/common/enums.py | 88 +-
ruoyi-fastapi-backend/common/mixin.py | 50 +-
ruoyi-fastapi-backend/common/router.py | 33 +-
ruoyi-fastapi-backend/common/types.py | 15 +-
ruoyi-fastapi-backend/common/vo.py | 32 +-
ruoyi-fastapi-backend/config/database.py | 170 ++-
ruoyi-fastapi-backend/config/env.py | 495 +++---
ruoyi-fastapi-backend/config/get_redis.py | 18 +-
ruoyi-fastapi-backend/config/lifecycle.py | 3 +-
.../config/scheduler/dispatcher.py | 17 +-
.../config/scheduler/events.py | 33 +-
.../config/scheduler/executors.py | 63 +-
.../config/scheduler/job_adapter.py | 25 +-
.../config/scheduler/job_execution.py | 61 +-
.../config/scheduler/jobs.py | 40 +-
.../config/scheduler/listener.py | 13 +-
.../config/scheduler/manager.py | 137 +-
.../config/scheduler/resources.py | 33 +-
.../config/scheduler/synchronization.py | 14 +-
.../config/scheduler/triggers.py | 18 +-
ruoyi-fastapi-backend/docs/cli_usage.md | 38 +-
ruoyi-fastapi-backend/exceptions/exception.py | 150 +-
ruoyi-fastapi-backend/exceptions/handle.py | 94 +-
ruoyi-fastapi-backend/i18n/__init__.py | 3 +-
ruoyi-fastapi-backend/i18n/catalogs.py | 77 +-
ruoyi-fastapi-backend/i18n/locale.py | 14 +-
ruoyi-fastapi-backend/i18n/message.py | 16 +-
ruoyi-fastapi-backend/i18n/registry.py | 20 +-
ruoyi-fastapi-backend/i18n/translation.py | 11 +-
ruoyi-fastapi-backend/i18n/translator.py | 21 +-
ruoyi-fastapi-backend/i18n/validation.py | 6 +-
.../api_response_header_middleware.py | 12 +-
.../middlewares/context_middleware.py | 12 +-
.../middlewares/cors_middleware.py | 2 +-
.../middlewares/demo_mode_middleware.py | 12 +-
.../middlewares/gzip_middleware.py | 3 +-
ruoyi-fastapi-backend/middlewares/handle.py | 4 +-
.../middlewares/locale_middleware.py | 15 +-
.../middlewares/oidc_cors_middleware.py | 13 +-
.../middlewares/trace_middleware/__init__.py | 3 +-
.../middlewares/trace_middleware/ctx.py | 53 +
.../middlewares/trace_middleware/middle.py | 36 +-
.../middlewares/trace_middleware/span.py | 47 +-
.../transport_crypto_middleware.py | 92 +-
.../controller/login_controller.py | 30 -
.../controller/user_controller.py | 7 +-
.../module_admin/dao/config_dao.py | 20 +-
.../module_admin/dao/dept_dao.py | 41 +-
.../module_admin/dao/dict_dao.py | 46 +-
.../module_admin/dao/file_access_dao.py | 30 +-
.../module_admin/dao/file_business_dao.py | 75 +-
.../module_admin/dao/file_info_dao.py | 97 +-
.../module_admin/dao/job_dao.py | 24 +-
.../module_admin/dao/job_log_dao.py | 16 +-
.../module_admin/dao/job_runtime_dao.py | 43 +-
.../module_admin/dao/log_dao.py | 28 +-
.../module_admin/dao/login_dao.py | 2 +-
.../module_admin/dao/menu_dao.py | 31 +-
.../module_admin/dao/notice_dao.py | 32 +-
.../module_admin/dao/post_dao.py | 24 +-
.../module_admin/dao/role_dao.py | 46 +-
.../module_admin/dao/user_dao.py | 54 +-
.../module_admin/entity/do/config_do.py | 4 +-
.../module_admin/entity/do/dept_do.py | 4 +-
.../module_admin/entity/do/dict_do.py | 8 +-
.../module_admin/entity/do/file_do.py | 32 +-
.../module_admin/entity/do/job_do.py | 8 +-
.../module_admin/entity/do/job_runtime_do.py | 14 +-
.../module_admin/entity/do/log_do.py | 8 +-
.../module_admin/entity/do/menu_do.py | 4 +-
.../module_admin/entity/do/notice_do.py | 8 +-
.../module_admin/entity/do/post_do.py | 4 +-
.../module_admin/entity/do/role_do.py | 12 +-
.../module_admin/entity/do/user_do.py | 12 +-
.../module_admin/entity/vo/cache_vo.py | 8 +-
.../module_admin/entity/vo/common_vo.py | 4 +-
.../module_admin/entity/vo/config_vo.py | 32 +-
.../module_admin/entity/vo/dept_vo.py | 41 +-
.../module_admin/entity/vo/dict_vo.py | 82 +-
.../module_admin/entity/vo/file_vo.py | 128 +-
.../module_admin/entity/vo/job_runtime_vo.py | 20 +-
.../module_admin/entity/vo/job_vo.py | 74 +-
.../module_admin/entity/vo/log_vo.py | 36 +-
.../module_admin/entity/vo/login_vo.py | 26 +
.../module_admin/entity/vo/menu_vo.py | 60 +-
.../module_admin/entity/vo/notice_vo.py | 38 +-
.../module_admin/entity/vo/online_vo.py | 16 +-
.../module_admin/entity/vo/post_vo.py | 32 +-
.../module_admin/entity/vo/role_vo.py | 63 +-
.../module_admin/entity/vo/server_vo.py | 14 +-
.../entity/vo/transport_crypto_vo.py | 20 +-
.../module_admin/entity/vo/user_vo.py | 144 +-
.../module_admin/service/cache_service.py | 18 +-
.../module_admin/service/captcha_service.py | 9 +-
.../module_admin/service/common_service.py | 38 +-
.../module_admin/service/config_service.py | 31 +-
.../module_admin/service/dept_service.py | 45 +-
.../module_admin/service/dict_service.py | 67 +-
.../service/file_access_service.py | 33 +-
.../service/file_business_service.py | 102 +-
.../module_admin/service/file_service.py | 255 +++-
.../module_admin/service/job_log_service.py | 16 +-
.../module_admin/service/job_service.py | 48 +-
.../module_admin/service/log_service.py | 86 +-
.../module_admin/service/login_service.py | 96 +-
.../module_admin/service/menu_service.py | 36 +-
.../module_admin/service/notice_service.py | 32 +-
.../module_admin/service/online_service.py | 9 +-
.../module_admin/service/post_service.py | 26 +-
.../module_admin/service/role_service.py | 50 +-
.../module_admin/service/server_service.py | 13 +-
.../service/transport_crypto_service.py | 10 +-
.../module_admin/service/user_service.py | 85 +-
.../controller/gen_controller.py | 1 +
.../module_generator/dao/gen_dao.py | 69 +-
.../module_generator/entity/do/gen_do.py | 8 +-
.../module_generator/entity/vo/gen_vo.py | 129 +-
.../module_generator/service/gen_service.py | 79 +-
.../templates/python/dao.py.jinja2 | 32 +-
.../templates/python/do.py.jinja2 | 22 +-
.../templates/python/service.py.jinja2 | 31 +-
.../templates/python/vo.py.jinja2 | 54 +-
.../controller/authorization_controller.py | 31 +-
.../controller/discovery_controller.py | 6 +-
.../controller/interaction_controller.py | 18 +-
.../controller/oauth_client_controller.py | 3 +-
.../controller/oauth_resource_controller.py | 3 +-
.../controller/oauth_session_controller.py | 3 +-
.../controller/oidc_key_controller.py | 3 +-
.../controller/token_controller.py | 28 +-
.../dao/identity_subject_dao.py | 29 +-
.../module_identity/dao/identity_user_dao.py | 16 +-
.../dao/oauth_access_policy_dao.py | 29 +-
.../module_identity/dao/oauth_audit_dao.py | 26 +-
.../module_identity/dao/oauth_client_dao.py | 106 +-
.../module_identity/dao/oauth_grant_dao.py | 70 +-
.../module_identity/dao/oauth_resource_dao.py | 72 +-
.../module_identity/dao/oauth_token_dao.py | 43 +-
.../module_identity/dao/oidc_key_dao.py | 46 +-
.../module_identity/dao/sso_session_dao.py | 59 +-
.../module_identity/dependencies.py | 59 +-
.../entity/do/identity_subject_do.py | 6 +-
.../entity/do/oauth_audit_do.py | 20 +-
.../entity/do/oauth_client_do.py | 21 +-
.../entity/do/oauth_grant_do.py | 36 +-
.../entity/do/oauth_resource_do.py | 20 +-
.../module_identity/entity/do/oidc_key_do.py | 6 +-
.../entity/vo/interaction_vo.py | 44 +-
.../entity/vo/oauth_client_vo.py | 33 +-
.../entity/vo/oauth_resource_vo.py | 44 +-
.../entity/vo/oauth_session_vo.py | 49 +-
.../module_identity/entity/vo/oidc_key_vo.py | 15 +-
.../module_identity/entity/vo/protocol_vo.py | 46 +-
.../module_identity/redis_keys.py | 87 +-
.../security/backchannel_transport.py | 74 +-
.../module_identity/security/client_auth.py | 14 +-
.../module_identity/security/jwt_profile.py | 102 +-
.../module_identity/security/opaque_token.py | 38 +-
.../module_identity/security/pkce.py | 19 +-
.../module_identity/security/principal.py | 30 +-
.../module_identity/security/uri_validator.py | 9 +-
.../module_identity/service/audit_service.py | 42 +-
.../service/authorization_service.py | 202 +--
.../service/consent_service.py | 51 +-
.../service/discovery_service.py | 22 +-
.../service/identity_service.py | 157 +-
.../service/infrastructure_service.py | 50 +-
.../service/interaction_service.py | 138 +-
.../module_identity/service/key_service.py | 85 +-
.../service/logout_confirmation_service.py | 16 +-
.../service/oauth_management_service.py | 265 ++--
.../oauth_session_management_service.py | 37 +-
.../service/runtime_service.py | 69 +-
.../service/session_service.py | 283 ++--
.../service/token_protocol_service.py | 115 +-
.../module_identity/service/token_service.py | 178 +--
.../module_plugin/service/plugin_service.py | 3 +-
.../module_task/file_task.py | 9 +-
.../module_task/scheduler_test.py | 10 +-
.../plugins/ai/dao/ai_chat_dao.py | 11 +-
.../plugins/ai/dao/ai_model_dao.py | 16 +-
.../plugins/ai/entity/do/ai_chat_do.py | 4 +-
.../plugins/ai/entity/do/ai_model_do.py | 8 +-
.../plugins/ai/entity/vo/ai_chat_vo.py | 40 +-
.../plugins/ai/entity/vo/ai_model_vo.py | 26 +-
.../plugins/ai/service/ai_chat_service.py | 47 +-
.../plugins/ai/service/ai_model_service.py | 23 +-
.../plugins/ai/utils/ai_util.py | 15 +-
.../plugins/core/artifacts/package.py | 3 -
.../plugins/core/artifacts/schema.py | 65 +-
.../plugins/core/artifacts/store.py | 17 +-
.../plugins/core/capability.py | 14 +
.../plugins/core/deployment/catalog.py | 11 +-
.../plugins/core/deployment/config.py | 29 +-
.../plugins/core/deployment/convergence.py | 10 +-
.../plugins/core/deployment/enablement.py | 4 +-
.../plugins/core/deployment/maintenance.py | 19 +-
.../plugins/core/deployment/service.py | 13 +-
.../plugins/core/deployment/state.py | 16 +
.../plugins/core/deployment/worker.py | 43 +-
.../plugins/core/discovery/registry.py | 7 +
.../plugins/core/discovery/scanner.py | 17 +-
.../plugins/core/environment.py | 8 +-
.../plugins/core/frontend.py | 4 +
.../plugins/core/lifecycle/jobs.py | 25 +-
.../plugins/core/lifecycle/migration.py | 53 +-
.../plugins/core/lifecycle/precheck.py | 6 +-
.../plugins/core/lifecycle/purge.py | 20 +-
.../plugins/core/lifecycle/script.py | 3 +
.../plugins/core/lifecycle/seed.py | 9 +-
.../plugins/core/management/dao/dao.py | 18 +-
.../core/management/dao/release_dao.py | 11 +-
.../management/entity/do/release_models.py | 12 +-
.../plugins/core/management/service/config.py | 8 +-
.../core/management/service/gateway.py | 19 +-
.../plugins/core/management/service/menus.py | 7 +-
.../management/service/router_metadata.py | 4 +-
.../core/management/service/service.py | 15 +-
.../management/service/startup_gateway.py | 11 +-
.../plugins/core/manifest/menu_key.py | 4 +
.../plugins/core/manifest/schema.py | 150 +-
.../plugins/core/manifest/v2.py | 114 +-
.../plugins/core/native/wheel.py | 5 +-
.../plugins/core/runtime/application.py | 30 +-
.../plugins/core/runtime/asgi.py | 60 +-
.../plugins/core/runtime/bootstrap.py | 25 +-
.../plugins/core/runtime/browser_session.py | 26 +-
.../plugins/core/runtime/bundle.py | 11 +-
.../plugins/core/runtime/callable.py | 13 +-
.../plugins/core/runtime/configuration.py | 27 +-
.../plugins/core/runtime/connections.py | 60 +-
.../plugins/core/runtime/diagnostics.py | 85 +-
.../plugins/core/runtime/diagnostics_store.py | 30 +-
.../plugins/core/runtime/entities.py | 11 +-
.../plugins/core/runtime/entrypoint.py | 22 +-
.../plugins/core/runtime/explicit.py | 53 +-
.../plugins/core/runtime/health.py | 30 +-
.../plugins/core/runtime/hooks.py | 34 +-
.../plugins/core/runtime/host_services.py | 10 +-
.../plugins/core/runtime/job_dispatcher.py | 27 +-
.../plugins/core/runtime/metrics.py | 91 +-
.../plugins/core/runtime/metrics_store.py | 26 +-
.../plugins/core/runtime/result.py | 4 +
.../plugins/core/runtime/route_guard.py | 12 +-
.../plugins/core/runtime/service/audit.py | 4 +-
.../plugins/core/runtime/service/batch.py | 9 +-
.../plugins/core/runtime/service/config.py | 3 +
.../plugins/core/runtime/service/context.py | 8 +-
.../core/runtime/service/dependencies.py | 6 +-
.../runtime/service/dependency_container.py | 22 +
.../plugins/core/runtime/service/facade.py | 37 +-
.../plugins/core/runtime/service/gateway.py | 114 +-
.../core/runtime/service/lifecycle/common.py | 6 +-
.../core/runtime/service/lifecycle/enable.py | 35 +-
.../core/runtime/service/lifecycle/install.py | 35 +-
.../runtime/service/lifecycle/operations.py | 11 +-
.../core/runtime/service/lifecycle/purge.py | 26 +-
.../core/runtime/service/lifecycle/runner.py | 15 +
.../core/runtime/service/lifecycle/upgrade.py | 38 +-
.../core/runtime/service/lifecycle_lock.py | 29 +-
.../plugins/core/runtime/service/migration.py | 2 +
.../core/runtime/service/migration_store.py | 15 +-
.../plugins/core/runtime/service/precheck.py | 3 +
.../plugins/core/runtime/service/query.py | 8 +-
.../plugins/core/runtime/service/responses.py | 68 +-
.../plugins/core/runtime/service/tools.py | 3 +
.../plugins/core/runtime/startup.py | 52 +-
.../core/runtime/startup_coordination.py | 3 +
.../plugins/core/runtime/startup_gateway.py | 15 +-
.../core/runtime/support/batch_report.py | 94 +-
.../core/runtime/support/npm_package.py | 2 -
.../core/runtime/support/payload/audit.py | 50 +-
.../core/runtime/support/payload/base.py | 4 +-
.../core/runtime/support/payload/catalog.py | 174 +--
.../core/runtime/support/payload/common.py | 20 +-
.../core/runtime/support/payload/config.py | 120 +-
.../runtime/support/payload/dependencies.py | 38 +-
.../runtime/support/payload/documentation.py | 18 +-
.../core/runtime/support/payload/enable.py | 130 +-
.../core/runtime/support/payload/lifecycle.py | 96 +-
.../core/runtime/support/payload/plan.py | 252 ++--
.../core/runtime/support/payload/purge.py | 24 +-
.../core/runtime/support/payload/runtime.py | 262 ++--
.../runtime/support/payload/validation.py | 223 +--
.../plugins/core/runtime/support/precheck.py | 76 +-
.../plugins/core/runtime/task_cleanup.py | 2 +-
.../plugins/core/sdk/asgi.py | 13 +-
.../plugins/core/sdk/config.py | 10 +-
.../plugins/core/sdk/context.py | 60 +-
.../plugins/core/sdk/definition.py | 17 +-
.../plugins/core/sdk/request.py | 16 +-
ruoyi-fastapi-backend/plugins/core/state.py | 20 +-
ruoyi-fastapi-backend/plugins/core/types.py | 17 +-
ruoyi-fastapi-backend/plugins/core/utils.py | 8 +-
.../plugins/core/validation/dependencies.py | 49 +-
.../core/validation/dependency_policy.py | 74 +-
.../plugins/core/validation/manifest.py | 11 +-
.../plugins/core/validation/menus.py | 20 +-
.../plugins/core/validation/plugin_deps.py | 55 +-
.../core/validation/python_requirements.py | 5 +-
.../plugins/core/validation/result.py | 14 +-
.../plugins/core/validation/structure.py | 17 +-
.../plugins/core/validation/versioning.py | 7 +
.../examples/python/asgi_demo/__init__.py | 8 +-
.../examples/python/bundle_demo/__init__.py | 6 +-
.../examples/python/bundle_demo/events.py | 3 +-
.../examples/python/bundle_demo/files.py | 6 +-
.../examples/python/task_demo/__init__.py | 33 +-
.../python/task_demo/build_release.py | 20 +-
.../examples/python/task_demo/models.py | 33 +-
.../examples/python/task_demo/service.py | 3 +
ruoyi-fastapi-backend/requirements-pg.txt | 2 +
ruoyi-fastapi-backend/requirements.txt | 2 +
ruoyi-fastapi-backend/ruff.toml | 15 +-
.../scripts/build_native_plugin.py | 4 +-
.../scripts/check_docstrings.py | 1326 +++++++++++++++++
ruoyi-fastapi-backend/scripts/compile_i18n.py | 29 +-
.../scripts/migrate_job_fields.py | 47 +-
.../scripts/migrate_legacy_files.py | 36 +-
.../scripts/plugin_release_integration.py | 64 +-
.../scripts/plugin_task_integration.py | 12 +-
.../scripts/verify_timezone_database.py | 25 +-
ruoyi-fastapi-backend/server.py | 24 +-
.../sub_applications/handle.py | 4 +-
.../sub_applications/staticfiles.py | 10 +-
.../tests/cli/completion/test_installers.py | 37 +-
.../tests/cli/completion/test_providers.py | 134 +-
.../tests/cli/core/test_app_bootstrap.py | 37 +
.../tests/cli/core/test_context_factory.py | 7 +
.../tests/cli/core/test_execution_service.py | 24 +-
.../tests/cli/root/conftest.py | 71 +
.../tests/cli/root/test_bootstrap.py | 18 +-
.../tests/cli/root/test_contract_app_ops.py | 26 +
.../tests/cli/root/test_contract_cli.py | 9 +
.../tests/cli/root/test_contract_config.py | 1 +
.../cli/root/test_contract_db_cache_dev.py | 11 +
.../tests/cli/root/test_contract_job_gen.py | 14 +
.../cli/root/test_effective_environment.py | 7 +
.../tests/cli/root/test_guards.py | 18 +-
.../cli/root/test_json_output_suppression.py | 7 +-
.../tests/cli/root/test_main.py | 6 +-
.../tests/cli/root/test_output.py | 60 +-
.../cli/root/test_plugin_artifact_commands.py | 141 +-
.../root/test_plugin_command_controller.py | 189 ++-
.../cli/root/test_plugin_create_templates.py | 41 +-
.../tests/cli/root/test_plugin_diagnostics.py | 2 +
.../root/test_plugin_frontend_environment.py | 7 +-
.../tests/cli/root/test_plugin_lazy_import.py | 8 +-
.../cli/root/test_plugin_release_wait.py | 50 +-
.../cli/root/test_plugin_sdk_commands.py | 29 +-
.../tests/cli/root/test_utils.py | 70 +-
.../tests/cli/runtime/plugin/conftest.py | 88 +-
.../plugin/test_runtime_dependency_lock.py | 6 +-
.../runtime/plugin/test_runtime_scaffold.py | 30 +-
.../plugin/test_runtime_scaffold_v2.py | 127 +-
.../cli/runtime/plugin/test_runtime_sdk.py | 45 +-
.../runtime/plugin/test_runtime_testing.py | 32 +-
.../runtime/plugin/test_scaffold_locales.py | 4 +
.../tests/cli/runtime/test_app_runtime.py | 73 +-
.../tests/cli/runtime/test_base.py | 14 +-
.../tests/cli/runtime/test_cache.py | 62 +-
.../tests/cli/runtime/test_config.py | 107 +-
.../tests/cli/runtime/test_crypto.py | 35 +-
.../tests/cli/runtime/test_db.py | 72 +-
.../tests/cli/runtime/test_dev.py | 89 +-
.../tests/cli/runtime/test_gen.py | 37 +-
.../tests/cli/runtime/test_job.py | 93 +-
.../tests/cli/runtime/test_ops.py | 74 +-
.../cli/tui/actions/test_action_execution.py | 24 +-
.../tests/cli/tui/adapters/conftest.py | 264 +++-
.../tui/adapters/test_app_ops_snapshots.py | 36 +
.../test_cache_db_crypto_snapshots.py | 53 +
.../test_configs_dashboard_snapshots.py | 71 +
.../tui/adapters/test_jobs_gen_snapshots.py | 52 +
.../tests/cli/tui/conftest.py | 12 +
.../tests/cli/tui/test_tui_browser_screen.py | 42 +-
.../tests/cli/tui/test_tui_command_app.py | 195 +++
.../cli/tui/test_tui_dashboard_search.py | 19 +
.../tests/cli/tui/test_tui_detail_screen.py | 44 +-
.../tests/cli/tui/test_tui_platform.py | 2 +
.../tests/cli/tui/test_tui_queries.py | 12 +
.../tests/cli/wizard/conftest.py | 64 +
.../tests/cli/wizard/test_app_run.py | 1 +
.../tests/cli/wizard/test_cache_clear.py | 2 +
.../tests/cli/wizard/test_commands.py | 1 +
.../tests/cli/wizard/test_db_upgrade.py | 2 +
.../tests/cli/wizard/test_gen_export.py | 2 +
.../tests/cli/wizard/test_gen_import.py | 3 +
.../tests/cli/wizard/test_prod_check.py | 9 +
.../tests/common/test_auth_policy.py | 84 +-
.../tests/common/test_data_scope.py | 10 +-
.../tests/common/test_exception_responses.py | 30 +-
.../tests/common/test_pre_auth.py | 389 ++++-
.../tests/common/test_query_time.py | 17 +-
.../tests/common/test_request_timezone.py | 24 +-
.../tests/common/test_router_register.py | 55 +-
.../tests/common/test_types.py | 16 +-
.../tests/config/test_app_settings.py | 2 +
.../test_current_user_cache_resources.py | 36 +-
.../test_current_user_cache_transactions.py | 148 +-
.../test_database_exception_handlers.py | 1 +
.../tests/config/test_database_registry.py | 105 ++
.../tests/config/test_database_settings.py | 16 +
.../tests/config/test_i18n_settings.py | 9 +-
.../tests/config/test_lifecycle.py | 21 +-
.../tests/config/test_oidc_settings.py | 10 +
.../tests/config/test_scheduler_database.py | 4 +
.../test_scheduler_execution_coordination.py | 7 +-
.../config/test_scheduler_execution_retry.py | 57 +-
.../tests/config/test_scheduler_executor.py | 30 +
.../tests/config/test_scheduler_fields.py | 17 +
.../config/test_scheduler_job_persistence.py | 19 +-
.../tests/config/test_scheduler_job_sync.py | 15 +-
.../config/test_scheduler_leader_lease.py | 12 +
.../tests/config/test_scheduler_runtime.py | 27 +-
.../config/test_scheduler_sql_logging.py | 20 +
.../tests/i18n/test_catalog_domains.py | 27 +-
.../tests/i18n/test_core_catalog_modules.py | 8 +-
.../i18n/test_database_initialization.py | 10 +-
.../tests/i18n/test_dict_cache_publication.py | 8 +
.../tests/i18n/test_excel_i18n.py | 5 +
.../tests/i18n/test_locale.py | 34 +-
.../tests/i18n/test_locale_revision.py | 17 +-
.../tests/i18n/test_validation_messages.py | 20 +-
.../middlewares/test_oidc_cors_middleware.py | 62 +-
.../test_transport_crypto_oidc_exclusion.py | 3 +
.../controller/test_dept_controller.py | 3 +
.../controller/test_job_controller.py | 5 +-
.../controller/test_login_logout.py | 34 +
.../controller/test_user_controller.py | 3 +
.../dao/test_user_auth_queries.py | 29 +
.../service/test_cached_session_races.py | 47 +-
.../service/test_common_file_security.py | 60 +
.../test_current_user_cache_integration.py | 113 +-
.../test_current_user_cache_mutations.py | 8 +
.../service/test_current_user_resolution.py | 116 +-
.../module_admin/service/test_dept_service.py | 24 +
.../service/test_file_access_log.py | 43 +-
.../module_admin/service/test_file_acl.py | 49 +
...test_file_lifecycle_retention_execution.py | 25 +
.../service/test_file_management.py | 71 +-
.../service/test_file_reconcile.py | 41 +
.../service/test_file_reference.py | 13 +
.../service/test_file_retention_policy.py | 9 +
.../module_admin/service/test_job_service.py | 21 +-
.../service/test_login_plugin_routes.py | 19 +
.../service/test_login_service.py | 14 +
.../service/test_login_session_renewal.py | 140 +-
.../module_admin/service/test_menu_service.py | 26 +
.../service/test_notice_html_security.py | 13 +-
.../service/test_notice_service.py | 17 +
.../service/test_online_service.py | 1 +
.../module_admin/service/test_user_service.py | 5 +
.../service/test_user_timezone.py | 5 +
.../module_generator/dao/test_gen_dao.py | 7 +
.../module_generator/test_gen_service.py | 10 +
.../module_generator/test_generated_i18n.py | 33 +
.../test_generated_time_contract.py | 102 +-
.../module_generator/test_react_templates.py | 5 +-
.../test_architecture_boundaries.py | 61 +-
.../tests/module_identity/conftest.py | 22 +-
.../module_identity/controllers/conftest.py | 16 +-
.../test_authorization_controller.py | 85 +-
.../controllers/test_client_ip_resolution.py | 30 +
.../controllers/test_discovery_controller.py | 79 +-
.../test_interaction_controller.py | 262 +++-
.../controllers/test_logout_confirmation.py | 40 +
.../test_oauth_audit_controller.py | 23 +-
.../test_oauth_client_controller.py | 103 +-
.../test_oauth_resource_controller.py | 66 +-
.../test_oauth_session_controller.py | 103 +-
.../controllers/test_oidc_key_controller.py | 61 +-
.../controllers/test_token_controller.py | 101 +-
.../controllers/test_userinfo_controller.py | 39 +-
.../module_identity/dao/test_oidc_key_dao.py | 18 +-
.../dao/test_refresh_token_dao.py | 10 +-
.../models/test_oidc_key_vo.py | 3 +
.../models/test_protocol_vo.py | 3 +
.../security/test_client_auth.py | 5 +
.../security/test_identity_dependencies.py | 37 +-
.../security/test_jwt_profile.py | 16 +-
.../test_oauth_rate_limit_metadata.py | 18 +-
.../security/test_oidc_messages.py | 12 +-
.../security/test_opaque_token.py | 2 +
.../module_identity/security/test_pkce.py | 2 +
.../test_protocol_exception_handler.py | 23 +-
.../security/test_redis_keys.py | 4 +
.../services/test_audit_service.py | 35 +-
.../test_authentication_regressions.py | 69 +-
.../test_authorization_code_service.py | 7 +-
.../services/test_authorization_service.py | 20 +-
.../services/test_claim_service.py | 2 +-
.../services/test_consent_service.py | 8 +-
.../test_credential_authentication_service.py | 77 +-
.../test_identity_security_event_service.py | 14 +-
.../services/test_identity_subject_service.py | 12 +-
.../services/test_interaction_service.py | 14 +-
.../services/test_introspection_service.py | 103 +-
.../services/test_key_service.py | 247 ++-
.../module_identity/services/test_logout.py | 219 ++-
.../services/test_oauth_management_service.py | 38 +-
.../test_oauth_resource_scope_management.py | 29 +-
.../services/test_review_completion.py | 42 +-
.../services/test_review_regressions.py | 21 +
.../services/test_revocation_service.py | 36 +-
.../services/test_sso_session_service.py | 139 +-
.../services/test_token_service.py | 72 +-
.../module_identity/support/redis_fakes.py | 83 +-
.../controller/test_plugin_controller.py | 195 ++-
.../test_plugin_diagnostics_controller.py | 2 +
.../test_plugin_release_controller.py | 10 +
.../service/test_plugin_service.py | 11 +-
.../tests/plugins/core/artifacts/conftest.py | 29 +-
.../plugins/core/artifacts/test_package.py | 31 +-
.../plugins/core/artifacts/test_store.py | 60 +-
.../tests/plugins/core/deployment/conftest.py | 38 +-
.../core/deployment/test_convergence.py | 112 +-
.../deployment/test_deployment_catalog.py | 9 +
.../core/deployment/test_enablement.py | 89 +-
.../core/deployment/test_maintenance.py | 98 +-
.../core/deployment/test_release_state.py | 24 +-
.../plugins/core/deployment/test_service.py | 139 +-
.../core/deployment/test_task_delivery.py | 10 +-
.../plugins/core/deployment/test_worker.py | 72 +-
.../plugins/core/discovery/test_registry.py | 19 +-
.../plugins/core/discovery/test_scanner.py | 8 +-
.../plugins/core/lifecycle/test_migration.py | 80 +-
.../tests/plugins/core/lifecycle/test_seed.py | 8 +-
.../core/management/test_artifact_views.py | 33 +-
.../core/management/test_config_manager.py | 7 +-
.../core/management/test_menu_installer.py | 131 +-
.../core/management/test_plugin_state.py | 64 +-
.../core/management/test_release_dao.py | 28 +-
.../tests/plugins/core/native/test_wheel.py | 22 +-
.../tests/plugins/core/runtime/conftest.py | 6 +-
.../plugins/core/runtime/fakes/environment.py | 61 +-
.../plugins/core/runtime/fakes/factory.py | 53 +-
.../plugins/core/runtime/fakes/gateway.py | 281 +++-
.../plugins/core/runtime/fakes/management.py | 217 ++-
.../plugins/core/runtime/fakes/session.py | 51 +-
.../runtime/service/test_artifact_guards.py | 82 +
.../service/test_batch_dependencies.py | 27 +-
.../core/runtime/service/test_catalog.py | 86 +-
.../core/runtime/service/test_check_docs.py | 37 +-
.../service/test_install_config_health.py | 176 ++-
.../runtime/service/test_lifecycle_lock.py | 23 +-
.../runtime/service/test_lifecycle_runner.py | 32 +-
.../service/test_upgrade_enable_purge.py | 103 +-
.../support/test_dependency_payloads.py | 12 +-
.../plugins/core/runtime/test_application.py | 55 +-
.../tests/plugins/core/runtime/test_asgi.py | 108 +-
.../core/runtime/test_browser_session.py | 101 +-
.../tests/plugins/core/runtime/test_bundle.py | 53 +-
.../core/runtime/test_bundle_events.py | 1 -
.../core/runtime/test_bundle_transport.py | 65 +-
.../core/runtime/test_configuration.py | 19 +-
.../core/runtime/test_connection_sessions.py | 36 +-
.../plugins/core/runtime/test_connections.py | 84 +-
.../plugins/core/runtime/test_diagnostics.py | 33 +-
.../core/runtime/test_diagnostics_query.py | 37 +-
.../core/runtime/test_diagnostics_store.py | 82 +-
.../plugins/core/runtime/test_entities.py | 8 +-
.../plugins/core/runtime/test_entrypoint.py | 36 +-
.../plugins/core/runtime/test_explicit.py | 70 +
.../tests/plugins/core/runtime/test_health.py | 15 +-
.../tests/plugins/core/runtime/test_hooks.py | 8 +-
.../runtime/test_host_service_extensions.py | 14 +-
.../core/runtime/test_host_services.py | 21 +
.../core/runtime/test_job_dispatcher.py | 49 +
.../plugins/core/runtime/test_metrics.py | 32 +-
.../core/runtime/test_metrics_store.py | 44 +-
.../core/runtime/test_plugin_bootstrap.py | 7 +-
.../plugins/core/runtime/test_route_guard.py | 17 +-
.../plugins/core/runtime/test_sdk_requests.py | 32 +-
.../core/runtime/test_sdk_transactions.py | 25 +-
.../plugins/core/runtime/test_startup.py | 117 +-
.../plugins/core/runtime/test_task_cleanup.py | 9 +
.../tests/plugins/core/test_capability.py | 7 +-
.../plugins/core/test_frontend_layout.py | 1 -
.../core/validation/test_dependency_policy.py | 23 +-
.../plugins/core/validation/test_manifest.py | 15 +-
.../core/validation/test_manifest_v2.py | 17 +
.../plugins/core/validation/test_menus.py | 16 +-
.../core/validation/test_plugin_deps.py | 20 +-
.../plugins/core/validation/test_structure.py | 17 +-
.../tests/plugins/examples/test_task_demo.py | 122 +-
.../integration/test_harness_safety.py | 74 +-
.../plugins/integration/test_network_smoke.py | 65 +-
.../integration/test_network_smoke_runner.py | 12 +
.../native/test_native_bundle_build.py | 19 +
.../tests/plugins/native/test_rust_demo.py | 52 +
.../tests/plugins/sample_plugins/conftest.py | 6 +-
.../plugins/sample_plugins/test_ai_i18n.py | 8 +
.../plugins/sample_plugins/test_ai_plugin.py | 38 +-
.../test_ai_react_integration.py | 14 +-
ruoyi-fastapi-backend/tests/redis_helpers.py | 30 +-
.../tests/scheduler_helpers.py | 46 +-
.../tests/scripts/test_check_docstrings.py | 537 +++++++
.../tests/scripts/test_migrate_job_fields.py | 14 +
.../scripts/test_migrate_legacy_files.py | 38 +-
.../tests/server/test_oidc_cors_refresh.py | 17 +
.../tests/server/test_oidc_runtime.py | 30 +-
.../tests/server/test_plugin_runtime.py | 20 +-
.../tests/sql/test_plugin_release_schema.py | 2 +
.../tests/sql/test_plugin_schema.py | 7 +-
.../tests/test_api_docs_auth.py | 391 ++++-
.../tests/test_api_docs_switches.py | 2 +
.../tests/test_audit_time_delegation.py | 2 +
.../tests/test_entity_time_columns.py | 8 +
.../utils/test_application_leader_lease.py | 35 +-
.../tests/utils/test_cron_util.py | 3 +
.../utils/test_current_user_cache_util.py | 91 +-
.../tests/utils/test_jwt_util.py | 2 +
.../tests/utils/test_log_sanitize_util.py | 67 +
.../tests/utils/test_oidc_util.py | 20 +
.../tests/utils/test_response_timezone.py | 2 +
.../tests/utils/test_startup_log_filter.py | 9 +-
.../tests/utils/test_template_util.py | 21 +
.../tests/utils/test_time_util.py | 10 +
.../utils/api_annotation_util.py | 13 +-
.../utils/api_response_header_util.py | 7 +-
ruoyi-fastapi-backend/utils/cache_util.py | 31 +-
ruoyi-fastapi-backend/utils/client_ip_util.py | 10 +-
ruoyi-fastapi-backend/utils/common_util.py | 49 +-
ruoyi-fastapi-backend/utils/cron_util.py | 82 +-
ruoyi-fastapi-backend/utils/crypto_util.py | 17 +-
.../utils/dependency_util.py | 10 +-
ruoyi-fastapi-backend/utils/excel_util.py | 12 +-
ruoyi-fastapi-backend/utils/exception_util.py | 4 +-
ruoyi-fastapi-backend/utils/file_util.py | 230 ++-
ruoyi-fastapi-backend/utils/gen_i18n_util.py | 58 +-
ruoyi-fastapi-backend/utils/gen_util.py | 28 +-
ruoyi-fastapi-backend/utils/import_util.py | 8 +-
ruoyi-fastapi-backend/utils/jwt_util.py | 6 +-
ruoyi-fastapi-backend/utils/log_util.py | 113 +-
ruoyi-fastapi-backend/utils/message_util.py | 5 +
ruoyi-fastapi-backend/utils/oidc_util.py | 188 +--
ruoyi-fastapi-backend/utils/openapi_util.py | 38 +-
ruoyi-fastapi-backend/utils/page_util.py | 10 +-
ruoyi-fastapi-backend/utils/pwd_util.py | 8 +-
ruoyi-fastapi-backend/utils/response_util.py | 20 +-
ruoyi-fastapi-backend/utils/security_util.py | 5 +-
ruoyi-fastapi-backend/utils/server_util.py | 125 +-
ruoyi-fastapi-backend/utils/string_util.py | 32 +-
ruoyi-fastapi-backend/utils/template_util.py | 96 +-
ruoyi-fastapi-backend/utils/time_util.py | 69 +-
.../utils/transport_crypto_util.py | 217 +--
ruoyi-fastapi-backend/utils/upload_util.py | 48 +-
.../utils/user_import_util.py | 12 +-
ruoyi-fastapi-test/common/base_page_test.py | 76 +-
ruoyi-fastapi-test/common/browser_harness.py | 111 +-
ruoyi-fastapi-test/common/config.py | 10 +
ruoyi-fastapi-test/common/login_helper.py | 17 +-
ruoyi-fastapi-test/common/page_catalog.py | 17 +-
ruoyi-fastapi-test/common/ui.py | 7 +-
ruoyi-fastapi-test/conftest.py | 22 +-
.../monitor/test_job_management.py | 83 +-
.../monitor/test_transport_crypto.py | 7 +-
ruoyi-fastapi-test/prepare_e2e_compose.py | 11 +-
ruoyi-fastapi-test/ruff.toml | 11 +-
ruoyi-fastapi-test/system/page.py | 243 ++-
.../system/test_dict_management.py | 8 +-
.../system/test_file_management.py | 40 +-
.../system/test_log_management.py | 9 +-
.../system/test_menu_management.py | 9 +-
.../system/test_oauth_management.py | 46 +-
.../system/test_plugin_management.py | 134 +-
.../system/test_role_management.py | 24 +-
.../system/test_user_management.py | 22 +-
ruoyi-fastapi-test/test_account_pages.py | 15 +-
ruoyi-fastapi-test/test_browser_harness.py | 29 +-
ruoyi-fastapi-test/test_code_gen_harness.py | 5 +
ruoyi-fastapi-test/test_login.py | 5 +
ruoyi-fastapi-test/test_pages.py | 8 +-
.../test_plugin_network_harness.py | 6 +
.../test_plugin_response_contract.py | 39 +-
ruoyi-fastapi-test/tool/test_code_gen.py | 31 +-
856 files changed, 24363 insertions(+), 10931 deletions(-)
create mode 100644 ruoyi-fastapi-backend/scripts/check_docstrings.py
create mode 100644 ruoyi-fastapi-backend/tests/scripts/test_check_docstrings.py
diff --git a/.github/requirements.txt b/.github/requirements.txt
index a712d7a95..a032d4c2d 100644
--- a/.github/requirements.txt
+++ b/.github/requirements.txt
@@ -1,3 +1,5 @@
+docutils==0.22.4
pytest==9.2.0
PyYAML==6.0.4
ruff==0.17.6
+Sphinx==9.0.4
diff --git a/.github/scripts/check_compose.py b/.github/scripts/check_compose.py
index 318d93fcf..f59f406b6 100644
--- a/.github/scripts/check_compose.py
+++ b/.github/scripts/check_compose.py
@@ -22,7 +22,7 @@ def validate_configuration(config: dict[str, Any], framework: str, engine: str,
:param framework: 本次选择的框架
:param engine: my 或 pg
:param root: 仓库根目录
- :return: None
+ :raises ValueError: 前端构建目录、Dockerfile、nginx 配置或后端所选框架不匹配
"""
expected = (root / 'ruoyi-fastapi-frontend' / framework / 'web').resolve()
services = config['services']
@@ -44,11 +44,7 @@ def validate_configuration(config: dict[str, Any], framework: str, engine: str,
def main() -> None:
- """
- 使用全部框架解析生产和测试 Compose,无需启动容器。
-
- :return: None
- """
+ """使用全部框架解析生产和测试 Compose,无需启动容器。"""
parser = argparse.ArgumentParser()
parser.add_argument('--docker', default='docker')
args = parser.parse_args()
diff --git a/.github/scripts/check_test_report.py b/.github/scripts/check_test_report.py
index d9a057ea2..9148faf66 100644
--- a/.github/scripts/check_test_report.py
+++ b/.github/scripts/check_test_report.py
@@ -10,6 +10,7 @@ def check_report(path: Path, *, allow_skips: bool = False) -> tuple[int, int]:
:param path: pytest JUnit 报告路径
:param allow_skips: 是否允许普通跨平台回归中的预期跳过
:return: 实际执行及跳过的测试数量
+ :raises ValueError: 没有实际执行用例、存在失败,或跳过了必须执行的用例
"""
root = ET.parse(path).getroot()
cases = root.findall('.//testcase')
@@ -22,11 +23,7 @@ def check_report(path: Path, *, allow_skips: bool = False) -> tuple[int, int]:
def main() -> None:
- """
- 检查报告并将执行数量写入 CI 摘要。
-
- :return: None
- """
+ """检查报告并将执行数量写入 CI 摘要。"""
parser = argparse.ArgumentParser()
parser.add_argument('report', type=Path)
parser.add_argument('--allow-skips', action='store_true')
diff --git a/.github/scripts/ci_plan.py b/.github/scripts/ci_plan.py
index de166ba7a..b738af91d 100644
--- a/.github/scripts/ci_plan.py
+++ b/.github/scripts/ci_plan.py
@@ -198,7 +198,6 @@ def write_outputs(plan: dict[str, Any]) -> None:
输出 GitHub 任务参数及可审阅的执行摘要。
:param plan: 本次运行计划
- :return: None
"""
payload = {
**plan['required'],
@@ -222,7 +221,7 @@ def main() -> None:
"""
执行变更选路或最终结果校验。
- :return: None
+ :raises SystemExit: 变更选路或最终结果校验失败
"""
parser = argparse.ArgumentParser()
parser.add_argument('command', choices=('plan', 'gate'))
diff --git a/.github/scripts/install_ai_test_dependencies.py b/.github/scripts/install_ai_test_dependencies.py
index 6ab49c791..c5065da00 100644
--- a/.github/scripts/install_ai_test_dependencies.py
+++ b/.github/scripts/install_ai_test_dependencies.py
@@ -9,7 +9,7 @@ def main() -> None:
"""
从 AI 插件清单安装测试依赖,避免 CI 维护第二份版本列表。
- :return: None
+ :raises ValueError: AI 插件 Python 依赖清单无效
"""
backend = Path(__file__).resolve().parents[2] / 'ruoyi-fastapi-backend'
manifest = yaml.safe_load((backend / 'plugins/ai/plugin.yaml').read_text(encoding='utf-8'))
diff --git a/.github/scripts/mobile_smoke.py b/.github/scripts/mobile_smoke.py
index 88c3955d0..27b2d60d4 100644
--- a/.github/scripts/mobile_smoke.py
+++ b/.github/scripts/mobile_smoke.py
@@ -48,7 +48,6 @@ async def api(route: Route) -> None:
隔离 API 边界,记录真实构建发出的认证和时区请求。
:param route: 当前浏览器 API 请求
- :return: None
"""
request = route.request
path = urlparse(request.url).path.removeprefix('/dev-api')
@@ -109,7 +108,14 @@ async def api(route: Route) -> None:
async def check_login_styles(framework: str, page: Page, login_button: Locator) -> dict[str, Any]:
- """验证移动端构建确实生成了布局、渐变和图标样式。"""
+ """
+ 验证移动端构建确实生成了布局、渐变和图标样式。
+
+ :param framework: 目标前端框架
+ :param page: 浏览器页面或要查询的页码
+ :param login_button: 提交登录表单的按钮
+ :return: 供调用方使用的 ``styles``
+ """
styles = await login_button.evaluate(
"""element => {
const style = getComputedStyle(element)
@@ -148,7 +154,6 @@ def check_profile_requests(observed: list[dict[str, Any]]) -> None:
验证账号恢复后的认证、时区、语言与初始化请求头。
:param observed: 实际发出的 API 请求记录
- :return: None
"""
profile_requests = [request for request in observed if request['path'] == '/system/user/profile']
assert profile_requests, '个人资料页未发送真实 API 请求'
@@ -165,7 +170,7 @@ async def run_smoke(framework: str, base_url: str, output: Path) -> None:
:param framework: vue2、vue3 或 react
:param base_url: 本次测试的开发服务器或静态文件服务器
:param output: 浏览器报告目录
- :return: None
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
logs: list[str] = []
errors: list[str] = []
@@ -234,7 +239,8 @@ def main() -> None:
"""
验证现有开发服务器或临时 H5 静态服务,结束后关闭自身创建的资源。
- :return: None
+ :raises TimeoutError: H5 服务未能在截止时间前就绪
+ :raises SystemExit: 缺少预先构建的 H5 产物
"""
parser = argparse.ArgumentParser()
parser.add_argument('--framework', choices=('vue2', 'vue3', 'react'), required=True)
diff --git a/.github/tests/test_ci_contracts.py b/.github/tests/test_ci_contracts.py
index 36ec10510..f08a75974 100644
--- a/.github/tests/test_ci_contracts.py
+++ b/.github/tests/test_ci_contracts.py
@@ -29,7 +29,11 @@ def load_script(name: str) -> ModuleType:
@pytest.fixture
def configuration() -> dict[str, Any]:
- """提供前端、nginx 和后端框架一致的 Compose 配置。"""
+ """
+ 提供前端、nginx 和后端框架一致的 Compose 配置。
+
+ :return: 前端、nginx 和后端框架一致的 Compose 配置
+ """
frontend = ROOT / 'ruoyi-fastapi-frontend/vue2/web'
return {
'services': {
diff --git a/.github/tests/test_ci_python_matrix.py b/.github/tests/test_ci_python_matrix.py
index 685925f33..1ba3c1991 100644
--- a/.github/tests/test_ci_python_matrix.py
+++ b/.github/tests/test_ci_python_matrix.py
@@ -13,7 +13,13 @@
def load_module(name: str, path: Path) -> ModuleType:
- """按路径加载 CI 与 E2E 入口,以验证跨工程的版本契约。"""
+ """
+ 按路径加载 CI 与 E2E 入口,以验证跨工程的版本契约。
+
+ :param name: 要读取的本地模块的完整名称
+ :param path: 要读取或处理的路径
+ :return: 提供被测功能的模块
+ """
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
diff --git a/.github/workflows/ci-quality.yml b/.github/workflows/ci-quality.yml
index 5ebbd58aa..2d607529b 100644
--- a/.github/workflows/ci-quality.yml
+++ b/.github/workflows/ci-quality.yml
@@ -23,6 +23,7 @@ jobs:
run: |
ruff check ruoyi-fastapi-backend ruoyi-fastapi-test .github/scripts .github/tests
ruff format --check ruoyi-fastapi-backend ruoyi-fastapi-test .github/scripts .github/tests
+ python ruoyi-fastapi-backend/scripts/check_docstrings.py ruoyi-fastapi-backend ruoyi-fastapi-test .github/scripts .github/tests
- name: Test CI routing, failure gates and deployment contracts
run: python -m pytest .github/tests -q --junitxml=target/ci/quality.xml
- name: Validate every Compose framework selection
diff --git a/ruoyi-fastapi-backend/.x18n/scan_python_domains.py b/ruoyi-fastapi-backend/.x18n/scan_python_domains.py
index 519bd43e1..7aad60097 100644
--- a/ruoyi-fastapi-backend/.x18n/scan_python_domains.py
+++ b/ruoyi-fastapi-backend/.x18n/scan_python_domains.py
@@ -1,7 +1,3 @@
-"""
-使用标准库 AST 为 x18n 扫描消息调用,不导入或执行应用代码
-"""
-
import ast
import json
import sys
@@ -9,10 +5,11 @@
def scan(source: dict) -> dict:
"""
- 提取静态消息标识和显式 domain,位置使用 JavaScript UTF-16 偏移
+ 提取静态消息标识和显式 domain,位置使用 JavaScript UTF-16 偏移。
:param source: 包含源码路径和文本的扫描输入
:return: 源码路径及消息调用信息
+ :raises ValueError: 静态翻译消息的域不是字面字符串或模块常量
"""
text = source['text']
tree = ast.parse(text, filename=source['path'])
@@ -34,7 +31,7 @@ def scan(source: dict) -> dict:
def position(line: int, column: int) -> int:
"""
- 将 Python AST 的 UTF-8 字节位置转换为 JavaScript UTF-16 偏移
+ 将 Python AST 的 UTF-8 字节位置转换为 JavaScript UTF-16 偏移。
:param line: 从 1 开始的源码行号
:param column: 从 0 开始的 UTF-8 字节列偏移
diff --git a/ruoyi-fastapi-backend/cli/bootstrap.py b/ruoyi-fastapi-backend/cli/bootstrap.py
index 8cbc39d60..3fa99be8c 100644
--- a/ruoyi-fastapi-backend/cli/bootstrap.py
+++ b/ruoyi-fastapi-backend/cli/bootstrap.py
@@ -13,6 +13,8 @@ class AppBootstrapService:
该服务负责解析应用原始入口路径、构建启动命令,并使用与当前平台兼容的方式
将 CLI 进程切换为或连接到 FastAPI 应用入口进程。
+
+ :ivar runtime_environment: 运行时环境服务
"""
def __init__(self, *, runtime_environment: RuntimeEnvironmentService | None = None) -> None:
@@ -20,7 +22,6 @@ def __init__(self, *, runtime_environment: RuntimeEnvironmentService | None = No
初始化应用引导服务。
:param runtime_environment: 运行时环境服务
- :return: None
"""
self.runtime_environment = runtime_environment or RUNTIME_ENVIRONMENT
@@ -54,7 +55,7 @@ def exec_app_run_command(self, env: str) -> None:
以应用原始入口进程启动当前 FastAPI 应用。
:param env: 运行环境
- :return: None
+ :raises SystemExit: Windows 子进程退出或被中断时,向调用进程传递退出码
"""
command = self.build_app_run_command(env)
if _IS_WINDOWS:
diff --git a/ruoyi-fastapi-backend/cli/completion/commands.py b/ruoyi-fastapi-backend/cli/completion/commands.py
index 1dce26bcb..8dac2473a 100644
--- a/ruoyi-fastapi-backend/cli/completion/commands.py
+++ b/ruoyi-fastapi-backend/cli/completion/commands.py
@@ -13,8 +13,8 @@ class CompletionCommandRegistration:
"""
completion 子命令注册描述。
- :param name: 子命令名称
- :param help_text: 子命令帮助文本
+ :ivar name: 子命令名称
+ :ivar help_text: 子命令帮助文本
"""
name: str
@@ -26,10 +26,10 @@ class CompletionSubcommandRegistrar:
"""
completion 子命令注册器。
- 该对象负责将 `show/install/doctor` 子命令挂载到 completion 应用,
+ 该对象负责将 ``show/install/doctor`` 子命令挂载到 completion 应用,
将 Typer 命令声明细节从构建器主体中拆出。
- :param completion_provider_gateway: completion 提供器对外网关
+ :ivar completion_provider_gateway: completion 提供器对外网关
"""
completion_provider_gateway: CompletionProviderGateway = field(default_factory=lambda: COMPLETION_PROVIDER_GATEWAY)
@@ -53,7 +53,6 @@ def register(self, app: typer.Typer, *, controller: CompletionCommandController)
:param app: completion 子应用
:param controller: completion 命令控制器
- :return: None
"""
registrations = {registration.name: registration for registration in self.build_registrations()}
@@ -69,7 +68,6 @@ def show(
输出指定 shell 的 completion 脚本。
:param shell: shell 名称
- :return: None
"""
controller.show(shell)
@@ -96,7 +94,6 @@ def install(
:param activate: 是否写入 shell rc 文件激活命令
:param rc_file: 自定义 shell rc 文件路径
:param force: 是否强制覆盖已存在文件
- :return: None
"""
controller.install(
output,
@@ -115,7 +112,6 @@ def doctor(
检查当前 completion 配置状态。
:param output: 输出格式
- :return: None
"""
controller.doctor(output)
@@ -125,10 +121,10 @@ class CompletionCommandBuilder:
"""
completion 子应用构建器。
- 该构建器负责装配 `completion` 子应用,并将控制器实例和子命令注册
+ 该构建器负责装配 ``completion`` 子应用,并将控制器实例和子命令注册
细节收口到类式对象协作中。
- :param completion_subcommand_registrar: completion 子命令注册器
+ :ivar completion_subcommand_registrar: completion 子命令注册器
"""
completion_subcommand_registrar: CompletionSubcommandRegistrar = field(
diff --git a/ruoyi-fastapi-backend/cli/completion/controller.py b/ruoyi-fastapi-backend/cli/completion/controller.py
index 16a7632ef..1fc1f45dc 100644
--- a/ruoyi-fastapi-backend/cli/completion/controller.py
+++ b/ruoyi-fastapi-backend/cli/completion/controller.py
@@ -16,15 +16,15 @@ class CompletionCommandController:
"""
completion 命令控制器。
- 该控制器负责组织 `completion` 命令组的上下文准备、payload 生成、
+ 该控制器负责组织 ``completion`` 命令组的上下文准备、payload 生成、
文本渲染与脚本输出收口。
- :param root_cli: 根 Typer 应用
- :param context_factory: CLI 上下文工厂
- :param execution_service: CLI 执行服务
- :param presenter: completion 命令文本渲染器
- :param installer_service: completion 安装与脚本生成服务
- :param doctor_service: completion 诊断服务
+ :ivar root_cli: 根 Typer 应用
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar presenter: completion 命令文本渲染器
+ :ivar installer_service: completion 安装与脚本生成服务
+ :ivar doctor_service: completion 诊断服务
"""
def __init__(
@@ -46,7 +46,6 @@ def __init__(
:param presenter: completion 命令文本渲染器
:param installer_service: completion 安装与脚本生成服务
:param doctor_service: completion 诊断服务
- :return: None
"""
self.root_cli = root_cli
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
@@ -60,7 +59,6 @@ def show(self, shell: str) -> None:
输出指定 shell 的 completion 脚本。
:param shell: shell 名称
- :return: None
"""
typer.echo(self.installer_service.render_completion_script(self.root_cli, shell), nl=False)
@@ -83,7 +81,6 @@ def install(
:param activate: 是否写入 shell rc 文件激活命令
:param rc_file: 自定义 shell rc 文件路径
:param force: 是否强制覆盖已存在文件
- :return: None
"""
ctx = self.context_factory.build_readonly('dev', output)
payload = self.installer_service.install_completion_script(
@@ -105,7 +102,6 @@ def doctor(self, output: str) -> None:
检查当前 completion 配置状态。
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly('dev', output)
payload = self.doctor_service.build_completion_doctor_payload()
diff --git a/ruoyi-fastapi-backend/cli/completion/doctor.py b/ruoyi-fastapi-backend/cli/completion/doctor.py
index 18c4f23e3..07f179be6 100644
--- a/ruoyi-fastapi-backend/cli/completion/doctor.py
+++ b/ruoyi-fastapi-backend/cli/completion/doctor.py
@@ -19,11 +19,11 @@ class CompletionDoctorService:
completion 诊断服务。
该服务负责汇总活跃 shell、目标脚本路径、rc 文件状态、推荐安装命令
- 与环境候选列表,生成 `completion doctor` 所需的结构化结果。
+ 与环境候选列表,生成 ``completion doctor`` 所需的结构化结果。
- :param installer_service: completion 安装服务
- :param shell_spec_registry: shell 元数据注册表
- :param environment_option_service: 环境选项服务
+ :ivar installer_service: completion 安装服务
+ :ivar shell_spec_registry: shell 元数据注册表
+ :ivar environment_option_service: 环境选项服务
"""
def __init__(
@@ -39,7 +39,6 @@ def __init__(
:param installer_service: completion 安装服务
:param shell_spec_registry: shell 元数据注册表
:param environment_option_service: 环境选项服务
- :return: None
"""
self.installer_service = installer_service or COMPLETION_INSTALLER
self.shell_spec_registry = shell_spec_registry or COMPLETION_SHELL_SPEC_REGISTRY
diff --git a/ruoyi-fastapi-backend/cli/completion/installers.py b/ruoyi-fastapi-backend/cli/completion/installers.py
index 95e488535..d67c1f7bf 100644
--- a/ruoyi-fastapi-backend/cli/completion/installers.py
+++ b/ruoyi-fastapi-backend/cli/completion/installers.py
@@ -20,13 +20,11 @@
class PortableBashComplete(BashComplete):
- """
- 无需探测本机Bash版本的补全脚本生成器
- """
+ """无需探测本机Bash版本的补全脚本生成器。"""
def source(self) -> str:
"""
- 生成可供其他机器使用的Bash补全脚本
+ 生成可供其他机器使用的Bash补全脚本。
旧版Bash差异已由脚本转换器处理;跳过Click版本探测,避免调用Windows WSL启动器。
@@ -60,8 +58,8 @@ def make_bash_completion_script_compatible(script_text: str) -> str:
兼容目标主要包括 macOS 默认 Bash 3.2:
- - `complete -o nosort` 在旧 Bash 上会在 `source` 阶段直接报错
- - `compopt` 在旧 Bash 上可能不存在
+ - ``complete -o nosort`` 在旧 Bash 上会在 ``source`` 阶段直接报错
+ - ``compopt`` 在旧 Bash 上可能不存在
:param script_text: Click 原始 Bash completion 脚本文本
:return: 兼容处理后的脚本文本
@@ -141,10 +139,10 @@ class CompletionShellRuntimePolicy:
"""
completion shell 运行时策略定义。
- :param name: shell 名称
- :param click_completion_class: Click completion 生成器类型
- :param script_transformer: 脚本文本后处理函数
- :param source_command_builder: 激活命令构建函数
+ :ivar name: shell 名称
+ :ivar click_completion_class: Click completion 生成器类型
+ :ivar script_transformer: 脚本文本后处理函数
+ :ivar source_command_builder: 激活命令构建函数
"""
name: str
@@ -158,7 +156,7 @@ class CompletionShellRuntimePolicyRegistry:
"""
completion shell 运行时策略注册表。
- :param policies: 按 shell 名称索引的运行时策略映射
+ :ivar policies: 按 shell 名称索引的运行时策略映射
"""
policies: dict[str, CompletionShellRuntimePolicy]
@@ -210,9 +208,9 @@ class CompletionInstallerService:
该服务负责 shell 元数据解析、脚本生成、目标路径解析、激活命令构建、
rc 文件写入以及安装结果收口。
- :param completion_provider_gateway: completion 提供器对外网关
- :param shell_spec_registry: shell 元数据注册表
- :param shell_runtime_policy_registry: shell 运行时策略注册表
+ :ivar completion_provider_gateway: completion 提供器对外网关
+ :ivar shell_spec_registry: shell 元数据注册表
+ :ivar shell_runtime_policy_registry: shell 运行时策略注册表
"""
def __init__(
@@ -228,7 +226,6 @@ def __init__(
:param completion_provider_gateway: completion 提供器对外网关
:param shell_spec_registry: shell 元数据注册表
:param shell_runtime_policy_registry: shell 运行时策略注册表
- :return: None
"""
self.completion_provider_gateway = completion_provider_gateway or COMPLETION_PROVIDER_GATEWAY
self.shell_spec_registry = shell_spec_registry or COMPLETION_SHELL_SPEC_REGISTRY
diff --git a/ruoyi-fastapi-backend/cli/completion/presenter.py b/ruoyi-fastapi-backend/cli/completion/presenter.py
index f15667f48..b5ea30ef3 100644
--- a/ruoyi-fastapi-backend/cli/completion/presenter.py
+++ b/ruoyi-fastapi-backend/cli/completion/presenter.py
@@ -5,7 +5,7 @@ class CompletionCommandPresenter:
"""
completion 命令文本渲染器。
- 该渲染器负责将 `completion` 命令组产生的结构化 payload 转换为稳定的文本摘要,
+ 该渲染器负责将 ``completion`` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
diff --git a/ruoyi-fastapi-backend/cli/completion/providers.py b/ruoyi-fastapi-backend/cli/completion/providers.py
index c8043e975..2d6912aba 100644
--- a/ruoyi-fastapi-backend/cli/completion/providers.py
+++ b/ruoyi-fastapi-backend/cli/completion/providers.py
@@ -33,7 +33,7 @@ def resolve_completion_env(self, ctx: click.Context | None) -> str:
解析当前 completion 场景使用的环境名称。
:param ctx: Click 上下文
- :return: 环境名称,默认返回 `dev`
+ :return: 环境名称,默认返回 ``dev``
"""
if ctx is not None:
env_value = getattr(ctx, 'params', {}).get('env')
@@ -132,8 +132,8 @@ class DynamicCompletionService:
该服务负责 runtime 模块导入、只读协程执行、标准 payload 提取与
候选过滤,从而避免各补全函数继续复制相同的模板。
- :param context_resolver: completion 上下文解析器
- :param timeout_seconds: 动态补全超时时间
+ :ivar context_resolver: completion 上下文解析器
+ :ivar timeout_seconds: 动态补全超时时间
"""
context_resolver: CompletionContextResolver = field(default_factory=CompletionContextResolver)
@@ -142,10 +142,10 @@ class DynamicCompletionService:
@staticmethod
def _scoped_app_env(env: str) -> Any:
"""
- 为动态补全临时注入 `APP_ENV` 环境变量。
+ 为动态补全临时注入 ``APP_ENV`` 环境变量。
- `config.env` 在导入阶段会优先读取 `APP_ENV`,因此补全场景下
- 直接切换进程环境变量比改写 `sys.argv` 更稳定,也更符合当前
+ ``config.env`` 在导入阶段会优先读取 ``APP_ENV``,因此补全场景下
+ 直接切换进程环境变量比改写 ``sys.argv`` 更稳定,也更符合当前
后端配置模块的解析约束。
:param env: 当前补全环境名称
@@ -153,11 +153,25 @@ def _scoped_app_env(env: str) -> Any:
"""
class _CompletionEnvScope:
+ """
+ 为一次动态补全临时切换应用环境。
+
+ :ivar _original_app_env: 进入补全作用域前的应用环境
+ """
+
def __enter__(self) -> None:
+ """在读取补全候选项之前设置目标环境。"""
self._original_app_env = os.environ.get('APP_ENV')
os.environ['APP_ENV'] = env
def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
+ """
+ 在补全结束时恢复原来的环境配置。
+
+ :param exc_type: 退出上下文时的异常类型
+ :param exc: 捕获到的异常实例
+ :param traceback: 异常的调用栈
+ """
if self._original_app_env is None:
os.environ.pop('APP_ENV', None)
else:
@@ -176,7 +190,7 @@ def load_runtime_module(self, module_name: str) -> Any:
def run_completion_coroutine(self, coroutine: Any, *, env: str) -> Any:
"""
- 在补全场景下执行异步只读查询,并临时注入 `APP_ENV`。
+ 在补全场景下执行异步只读查询,并临时注入 ``APP_ENV``。
:param coroutine: 待执行协程
:param env: 当前补全环境名称
@@ -254,7 +268,7 @@ def extract_completion_list(payload: dict[str, Any], field_name: str) -> list[st
"""
从 CLI 标准结果中提取直接位于顶层字段的字符串列表。
- 该方法用于缓存键名等不走 `items/page.rows` 结构的场景,
+ 该方法用于缓存键名等不走 ``items/page.rows`` 结构的场景,
使这类动态补全也能统一复用 runtime 对象加载与协程执行逻辑。
:param payload: CLI 标准结果字典
@@ -372,10 +386,10 @@ class StaticCompletionProvider:
该对象负责 shell、环境、缓存名称以及 Alembic revision 等静态或
本地推导型补全候选。
- :param context_resolver: completion 上下文解析器
- :param dynamic_service: 动态补全执行服务
- :param shell_spec_registry: shell 元数据注册表
- :param environment_option_service: 环境选项服务
+ :ivar context_resolver: completion 上下文解析器
+ :ivar dynamic_service: 动态补全执行服务
+ :ivar shell_spec_registry: shell 元数据注册表
+ :ivar environment_option_service: 环境选项服务
"""
context_resolver: CompletionContextResolver = field(default_factory=CompletionContextResolver)
@@ -412,7 +426,7 @@ def complete_env_values(
incomplete: str,
) -> list[str]:
"""
- 为 `--env` 选项提供可补全的环境名称。
+ 为 ``--env`` 选项提供可补全的环境名称。
:param ctx: Click 上下文
:param args: 当前命令参数列表
@@ -503,7 +517,7 @@ class PathCompletionProvider:
该对象负责项目相对 SQL 文件路径和输出路径补全。
- :param context_resolver: completion 上下文解析器
+ :ivar context_resolver: completion 上下文解析器
"""
context_resolver: CompletionContextResolver = field(default_factory=CompletionContextResolver)
@@ -515,7 +529,7 @@ def complete_sql_files(
incomplete: str,
) -> list[str]:
"""
- 为 SQL 文件参数提供项目内 `.sql` 文件补全结果。
+ 为 SQL 文件参数提供项目内 ``.sql`` 文件补全结果。
:param ctx: Click 上下文
:param args: 当前命令参数列表
@@ -541,7 +555,7 @@ def complete_output_paths(
incomplete: str,
) -> list[str]:
"""
- 为导出文件参数提供目录和 `.zip` 文件补全结果。
+ 为导出文件参数提供目录和 ``.zip`` 文件补全结果。
:param ctx: Click 上下文
:param args: 当前命令参数列表
@@ -590,19 +604,15 @@ class DomainDynamicCompletionProvider:
该对象负责配置、代码生成、缓存、任务等运行时驱动的只读补全。
- :param context_resolver: completion 上下文解析器
- :param dynamic_service: 动态补全执行服务
+ :ivar context_resolver: completion 上下文解析器
+ :ivar dynamic_service: 动态补全执行服务
"""
context_resolver: CompletionContextResolver = field(default_factory=CompletionContextResolver)
dynamic_service: DynamicCompletionService = field(init=False)
def __post_init__(self) -> None:
- """
- 初始化动态补全执行服务。
-
- :return: None
- """
+ """初始化动态补全执行服务。"""
self.dynamic_service = DynamicCompletionService(context_resolver=self.context_resolver)
def complete_config_keys(
@@ -768,11 +778,11 @@ class CompletionProviderRegistry:
该注册表只负责持有静态补全、路径补全与动态只读补全 provider,
供上层 gateway、安装器与其他协作者按职责选择使用。
- :param context_resolver: completion 上下文解析器
- :param dynamic_service: 动态补全执行服务
- :param static_provider: 静态 completion 提供器
- :param path_provider: 路径 completion 提供器
- :param domain_provider: 业务域动态 completion 提供器
+ :ivar context_resolver: completion 上下文解析器
+ :ivar dynamic_service: 动态补全执行服务
+ :ivar static_provider: 静态 completion 提供器
+ :ivar path_provider: 路径 completion 提供器
+ :ivar domain_provider: 业务域动态 completion 提供器
"""
context_resolver: CompletionContextResolver = field(default_factory=CompletionContextResolver)
@@ -782,11 +792,7 @@ class CompletionProviderRegistry:
domain_provider: DomainDynamicCompletionProvider = field(init=False)
def __post_init__(self) -> None:
- """
- 初始化聚合 provider 依赖。
-
- :return: None
- """
+ """初始化聚合 provider 依赖。"""
self.dynamic_service = DynamicCompletionService(context_resolver=self.context_resolver)
self.static_provider = StaticCompletionProvider(
context_resolver=self.context_resolver,
@@ -803,9 +809,9 @@ class CompletionProviderGateway:
completion 对外网关。
该对象负责对命令声明层、上下文层和 TUI 层暴露统一的 completion 入口,
- 避免 `CompletionProviderRegistry` 本体继续膨胀为大而全的委托门面。
+ 避免 ``CompletionProviderRegistry`` 本体继续膨胀为大而全的委托门面。
- :param provider_registry: completion provider 注册表
+ :ivar provider_registry: completion provider 注册表
"""
provider_registry: CompletionProviderRegistry = field(default_factory=CompletionProviderRegistry)
@@ -833,7 +839,7 @@ def complete_env_values(
incomplete: str,
) -> list[str]:
"""
- 为 `--env` 选项提供可补全的环境名称。
+ 为 ``--env`` 选项提供可补全的环境名称。
:param ctx: Click 上下文
:param args: 当前命令参数列表
@@ -897,7 +903,7 @@ def complete_sql_files(
incomplete: str,
) -> list[str]:
"""
- 为 SQL 文件参数提供项目内 `.sql` 文件补全结果。
+ 为 SQL 文件参数提供项目内 ``.sql`` 文件补全结果。
:param ctx: Click 上下文
:param args: 当前命令参数列表
@@ -913,7 +919,7 @@ def complete_output_paths(
incomplete: str,
) -> list[str]:
"""
- 为导出文件参数提供目录和 `.zip` 文件补全结果。
+ 为导出文件参数提供目录和 ``.zip`` 文件补全结果。
:param ctx: Click 上下文
:param args: 当前命令参数列表
diff --git a/ruoyi-fastapi-backend/cli/completion/shells.py b/ruoyi-fastapi-backend/cli/completion/shells.py
index 01dcb6123..0ce38f0f8 100644
--- a/ruoyi-fastapi-backend/cli/completion/shells.py
+++ b/ruoyi-fastapi-backend/cli/completion/shells.py
@@ -68,9 +68,12 @@ class PowerShellComplete(ShellComplete):
"""
PowerShell shell completion 支持。
- 基于 PowerShell `Register-ArgumentCompleter -Native` 协议,将当前
+ 基于 PowerShell ``Register-ArgumentCompleter -Native`` 协议,将当前
命令行和光标位置传回 Click completion 分发器,再把返回的候选项转换为
- `CompletionResult` 对象。
+ ``CompletionResult`` 对象。
+
+ :cvar name: 用于查找或标识当前对象的名称
+ :cvar source_template: 用于生成目标文件的模板
"""
name = 'powershell'
@@ -104,11 +107,7 @@ def format_completion(self, item: CompletionItem) -> str:
def ensure_custom_completion_classes_registered() -> None:
- """
- 确保自定义 shell completion 类已注册到 Click。
-
- :return: None
- """
+ """确保自定义 shell completion 类已注册到 Click。"""
# Click 8.5 新增同名实现,但其数字索引协议与本项目脚本的文本参数协议不同。
if get_completion_class(PowerShellComplete.name) is not PowerShellComplete:
add_completion_class(PowerShellComplete)
diff --git a/ruoyi-fastapi-backend/cli/context.py b/ruoyi-fastapi-backend/cli/context.py
index 9fa861d42..2749b398f 100644
--- a/ruoyi-fastapi-backend/cli/context.py
+++ b/ruoyi-fastapi-backend/cli/context.py
@@ -11,13 +11,13 @@ class CliContext:
"""
CLI 运行上下文。
- env: 当前加载的配置文件选择名
- app_env: 已加载配置声明的实际应用环境
- output: 结果输出格式
- operator: 操作者标识,后续用于审计
- allow_prod: 是否显式允许生产环境执行危险命令
- yes: 是否跳过二次确认
- dry_run: 是否执行演练模式
+ :ivar env: 当前加载的配置文件选择名
+ :ivar app_env: 已加载配置声明的实际应用环境
+ :ivar output: 结果输出格式
+ :ivar operator: 操作者标识,后续用于审计
+ :ivar allow_prod: 是否显式允许生产环境执行危险命令
+ :ivar yes: 是否跳过二次确认
+ :ivar dry_run: 是否执行演练模式
"""
env: str = 'dev'
@@ -33,7 +33,7 @@ class CliContextBuilder:
"""
CLI 上下文构建器。
- 该对象负责将命令层显式参数收口为统一的 `CliContext` 数据对象,
+ 该对象负责将命令层显式参数收口为统一的 ``CliContext`` 数据对象,
供上下文工厂与测试场景复用。
"""
diff --git a/ruoyi-fastapi-backend/cli/core/__init__.py b/ruoyi-fastapi-backend/cli/core/__init__.py
index 17df42ccb..84c4c3689 100644
--- a/ruoyi-fastapi-backend/cli/core/__init__.py
+++ b/ruoyi-fastapi-backend/cli/core/__init__.py
@@ -15,8 +15,10 @@ class CoreServiceContainer:
该容器负责统一装配输出渲染器、运行期状态、上下文工厂与执行服务,
作为控制器、向导和 TUI 等编排层的默认依赖入口。
- :param output_renderer: 输出渲染器
- :param runtime_state: CLI 运行期状态对象
+ :ivar output_renderer: 输出渲染器
+ :ivar runtime_state: CLI 运行期状态对象
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
"""
output_renderer: OutputRenderer = field(default_factory=OutputRenderer)
@@ -25,11 +27,7 @@ class CoreServiceContainer:
execution_service: CliExecutionService = field(init=False)
def __post_init__(self) -> None:
- """
- 初始化核心服务依赖图。
-
- :return: None
- """
+ """初始化核心服务依赖图。"""
self.context_factory = CliContextFactory(
runtime_state=self.runtime_state,
output_renderer=self.output_renderer,
diff --git a/ruoyi-fastapi-backend/cli/core/app_builder.py b/ruoyi-fastapi-backend/cli/core/app_builder.py
index d03c47794..3a91cbda1 100644
--- a/ruoyi-fastapi-backend/cli/core/app_builder.py
+++ b/ruoyi-fastapi-backend/cli/core/app_builder.py
@@ -16,8 +16,8 @@ class ProjectRuntimeLocator:
"""
CLI 项目运行时定位器。
- 该对象负责判断当前目录是否为后端项目根目录、注入 `sys.path`,
- 并为配置导入阶段提取最小化的 `argv` 参数。
+ 该对象负责判断当前目录是否为后端项目根目录、注入 ``sys.path``,
+ 并为配置导入阶段提取最小化的 ``argv`` 参数。
"""
def is_backend_project_dir(self, project_dir: Path) -> bool:
@@ -31,7 +31,7 @@ def is_backend_project_dir(self, project_dir: Path) -> bool:
def ensure_backend_dir_on_sys_path(self) -> Path:
"""
- 将当前后端项目根目录加入 `sys.path` 首位。
+ 将当前后端项目根目录加入 ``sys.path`` 首位。
:return: 当前后端项目根目录
:raises typer.Exit: 当前目录不是后端项目根目录时退出命令
@@ -53,7 +53,7 @@ def extract_import_argv(self, argv: list[str] | None = None) -> list[str]:
提取供配置模块导入阶段使用的最小参数集。
:param argv: 原始命令行参数列表
- :return: 仅保留程序名和 `--env` 的参数列表
+ :return: 仅保留程序名和 ``--env`` 的参数列表
"""
current_argv = argv or sys.argv
program_name = current_argv[0] if current_argv else 'ruoyi'
@@ -81,7 +81,7 @@ class CliCommandGroupRegistry:
该注册表集中维护根 CLI 需要挂载的业务命令组模块路径,
避免命令组声明散落在应用构建器主体中。
- :param command_modules: 命令组到模块路径的映射
+ :ivar command_modules: 命令组到模块路径的映射
"""
command_modules: dict[str, str]
@@ -92,8 +92,8 @@ class CliExtensionRegistration:
"""
CLI 扩展入口注册描述。
- :param module_path: 扩展模块导入路径
- :param attach: 已加载模块挂载到根 CLI 的函数
+ :ivar module_path: 扩展模块导入路径
+ :ivar attach: 已加载模块挂载到根 CLI 的函数
"""
module_path: str
@@ -108,7 +108,7 @@ class CliExtensionRegistry:
该注册表集中维护 completion、wizard、TUI 等扩展入口的模块路径与
挂载方式,避免这些规则继续散落在注册器主体中。
- :param registrations: 扩展注册描述列表
+ :ivar registrations: 扩展注册描述列表
"""
registrations: tuple[CliExtensionRegistration, ...]
@@ -121,7 +121,8 @@ class CliCommandGroupRegistrar:
该对象负责根据命令组注册表向根 Typer 应用挂载业务命令组。
- :param command_group_registry: CLI 命令组注册表
+ :ivar command_group_registry: CLI 命令组注册表
+ :ivar module_loader: TUI 应用模块加载器
"""
command_group_registry: CliCommandGroupRegistry
@@ -132,7 +133,6 @@ def register(self, cli: typer.Typer) -> None:
向根应用注册业务命令组。
:param cli: 根 Typer 应用
- :return: None
"""
for command_name, module_path in self.command_group_registry.command_modules.items():
command_module = self.module_loader.load(module_path)
@@ -144,7 +144,7 @@ class CliExtensionMountSupport:
CLI 扩展入口挂载支持对象。
该对象负责封装不同扩展模块挂载到根 CLI 的差异,避免扩展注册器本体
- 继续堆积 `if/else` 或硬编码模块处理逻辑。
+ 继续堆积 ``if/else`` 或硬编码模块处理逻辑。
"""
@staticmethod
@@ -154,7 +154,6 @@ def attach_completion(cli: typer.Typer, module: object) -> None:
:param cli: 根 Typer 应用
:param module: 已加载模块
- :return: None
"""
cli.add_typer(module.COMPLETION_COMMAND_BUILDER.build(cli), name='completion')
@@ -165,7 +164,6 @@ def attach_wizard(cli: typer.Typer, module: object) -> None:
:param cli: 根 Typer 应用
:param module: 已加载模块
- :return: None
"""
cli.add_typer(module.WIZARD_COMMAND_BUILDER.build(), name='wizard')
@@ -176,7 +174,6 @@ def attach_tui(cli: typer.Typer, module: object) -> None:
:param cli: 根 Typer 应用
:param module: 已加载模块
- :return: None
"""
module.TUI_COMMAND_REGISTRATION.register(cli)
@@ -188,6 +185,9 @@ class CliExtensionRegistrar:
该对象负责向根 Typer 应用挂载 completion、wizard 与 TUI
等扩展入口。
+
+ :ivar extension_registry: CLI 扩展入口注册表
+ :ivar module_loader: TUI 应用模块加载器
"""
extension_registry: CliExtensionRegistry
@@ -198,7 +198,6 @@ def register(self, cli: typer.Typer) -> None:
向根应用注册扩展入口。
:param cli: 根 Typer 应用
- :return: None
"""
for registration in self.extension_registry.registrations:
extension_module = self.module_loader.load(registration.module_path)
@@ -210,10 +209,10 @@ class CliRootOptionInitializer:
"""
CLI 根级选项初始化器。
- 该对象负责将根级 `--color`、`--icon` 选项映射到共享输出渲染器,
+ 该对象负责将根级 ``--color``、``--icon`` 选项映射到共享输出渲染器,
避免根回调继续内联输出配置逻辑。
- :param output_renderer: 根命令共享的输出渲染器
+ :ivar output_renderer: 根命令共享的输出渲染器
"""
output_renderer: OutputRenderer
@@ -224,7 +223,6 @@ def initialize(self, *, color: str, icon: str) -> None:
:param color: 文本输出颜色模式
:param icon: 文本输出图标模式
- :return: None
"""
self.output_renderer.set_color_mode(color)
self.output_renderer.set_icon_mode(icon)
@@ -235,10 +233,10 @@ class CliRootCallbackRegistrar:
"""
CLI 根回调注册器。
- 该对象负责把根级 `--color`、`--icon` 选项回调挂载到 Typer 根应用,
- 让 `CliApplicationBuilder` 更专注于整体装配流程。
+ 该对象负责把根级 ``--color``、``--icon`` 选项回调挂载到 Typer 根应用,
+ 让 ``CliApplicationBuilder`` 更专注于整体装配流程。
- :param root_option_initializer: 根级选项初始化器
+ :ivar root_option_initializer: 根级选项初始化器
"""
root_option_initializer: CliRootOptionInitializer
@@ -248,7 +246,6 @@ def register(self, cli: typer.Typer) -> None:
向根应用注册回调。
:param cli: 根 Typer 应用
- :return: None
"""
@cli.callback()
@@ -267,7 +264,6 @@ def root_callback(
:param color: 文本输出颜色模式
:param icon: 文本输出图标模式
- :return: None
"""
self.root_option_initializer.initialize(color=color, icon=icon)
@@ -297,9 +293,11 @@ class CliApplicationBuilder:
"""
CLI 根应用构建器。
- :param output_renderer: 根命令共享的输出渲染器
- :param command_group_registrar: CLI 命令组注册器
- :param extension_registrar: CLI 扩展入口注册器
+ :ivar output_renderer: 根命令共享的输出渲染器
+ :ivar command_group_registrar: CLI 命令组注册器
+ :ivar extension_registrar: CLI 扩展入口注册器
+ :ivar root_option_initializer: 根级选项初始化器
+ :ivar root_callback_registrar: CLI 根回调注册器
"""
output_renderer: OutputRenderer
@@ -313,11 +311,7 @@ class CliApplicationBuilder:
root_callback_registrar: CliRootCallbackRegistrar = field(init=False)
def __post_init__(self) -> None:
- """
- 初始化根应用构建器依赖。
-
- :return: None
- """
+ """初始化根应用构建器依赖。"""
self.root_option_initializer = CliRootOptionInitializer(self.output_renderer)
self.root_callback_registrar = CliRootCallbackRegistrar(self.root_option_initializer)
diff --git a/ruoyi-fastapi-backend/cli/core/completion_dispatcher.py b/ruoyi-fastapi-backend/cli/core/completion_dispatcher.py
index 79724f963..741005548 100644
--- a/ruoyi-fastapi-backend/cli/core/completion_dispatcher.py
+++ b/ruoyi-fastapi-backend/cli/core/completion_dispatcher.py
@@ -16,8 +16,8 @@ class CompletionInstructionSupport:
该对象负责管理 completion 环境变量名、受支持 shell 列表,以及
Click / Typer 两种指令格式的判定逻辑。
- :param complete_env_var: completion 环境变量名
- :param supported_shells: 支持的 shell 名称列表
+ :ivar complete_env_var: completion 环境变量名
+ :ivar supported_shells: 支持的 shell 名称列表
"""
complete_env_var: str = '_RUOYI_COMPLETE'
@@ -27,7 +27,7 @@ def is_click_style_instruction(self, instruction: str) -> bool:
"""
判断 completion 指令是否为 Click 原生格式。
- Click 原生格式为 `_`,例如 `bash_complete`。
+ Click 原生格式为 ``_``,例如 ``bash_complete``。
:param instruction: completion 指令文本
:return: 是否为 Click 风格指令
@@ -38,7 +38,7 @@ def is_typer_style_instruction(self, instruction: str) -> bool:
"""
判断 completion 指令是否为 Typer 兼容格式。
- Typer 兼容格式为 `_`,例如 `complete_bash`。
+ Typer 兼容格式为 ``_``,例如 ``complete_bash``。
:param instruction: completion 指令文本
:return: 是否为 Typer 风格指令
@@ -53,7 +53,7 @@ class CompletionInstructionReader:
该对象负责从当前进程环境中读取并规范化 completion 指令。
- :param support: completion 指令解析支持对象
+ :ivar support: completion 指令解析支持对象
"""
support: CompletionInstructionSupport
@@ -75,19 +75,15 @@ class CompletionDispatcher:
该对象负责识别 Click 与 Typer 两种 completion 指令格式,
并在命中时直接执行补全流程后退出当前进程。
- :param support: completion 指令解析支持对象
- :param instruction_reader: completion 指令读取器
+ :ivar support: completion 指令解析支持对象
+ :ivar instruction_reader: completion 指令读取器
"""
support: CompletionInstructionSupport = field(default_factory=CompletionInstructionSupport)
instruction_reader: CompletionInstructionReader = field(init=False)
def __post_init__(self) -> None:
- """
- 初始化 completion 指令读取器。
-
- :return: None
- """
+ """初始化 completion 指令读取器。"""
object.__setattr__(self, 'instruction_reader', CompletionInstructionReader(self.support))
def dispatch(self, cli: typer.Typer) -> None:
@@ -95,10 +91,10 @@ def dispatch(self, cli: typer.Typer) -> None:
处理 shell completion 请求并在命中时直接退出。
这里同时兼容 Click 与 Typer 两种 completion 指令格式,避免
- 生成脚本格式和运行时解析格式不一致时出现 `Shell complete not supported.`。
+ 生成脚本格式和运行时解析格式不一致时出现 ``Shell complete not supported.``。
:param cli: Typer 根应用
- :return: None
+ :raises SystemExit: 补全协议处理结束时将补全器退出码交给命令行
"""
ensure_custom_completion_classes_registered()
instruction = self.instruction_reader.read_instruction()
diff --git a/ruoyi-fastapi-backend/cli/core/context_factory.py b/ruoyi-fastapi-backend/cli/core/context_factory.py
index dc5dbef47..e3210ac1a 100644
--- a/ruoyi-fastapi-backend/cli/core/context_factory.py
+++ b/ruoyi-fastapi-backend/cli/core/context_factory.py
@@ -18,7 +18,8 @@ class CliRuntimeState:
"""
CLI 运行期状态。
- :param logs_suppressed: 当前进程日志是否已切换为静默模式
+ :ivar logs_suppressed: 当前进程日志是否已切换为静默模式
+ :ivar sqlalchemy_logs_suppressed: 是否已关闭命令执行期间的 SQLAlchemy 日志输出
"""
logs_suppressed: bool = False
@@ -33,11 +34,7 @@ def get_logger(self) -> Any:
return import_module('utils.log_util').logger
def suppress_logs(self) -> None:
- """
- 关闭 CLI 进程中的终端日志输出。
-
- :return: None
- """
+ """关闭 CLI 进程中的终端日志输出。"""
if self.logs_suppressed:
return
self.get_logger().remove()
@@ -49,12 +46,10 @@ def suppress_sqlalchemy_logs(self) -> None:
该逻辑同时处理两类来源:
- 1. 将 `config.env.DataBaseConfig.db_sources` 中全部数据源的 `db_echo` 强制关闭,避免后续新建 Engine 时
+ 1. 将 ``config.env.DataBaseConfig.db_sources`` 中全部数据源的 ``db_echo`` 强制关闭,避免后续新建 Engine 时
继续打开 SQLAlchemy echo。
2. 将已知 SQLAlchemy logger 级别提升到 WARNING,避免已有 logger 配置把
- `INFO sqlalchemy.engine.Engine ...` 继续打到标准输出。
-
- :return: None
+ ``INFO sqlalchemy.engine.Engine ...`` 继续打到标准输出。
"""
if self.sqlalchemy_logs_suppressed:
return
@@ -80,17 +75,13 @@ class CliLogPolicy:
该对象负责在上下文构建前应用统一的日志输出策略,
将“是否静默日志”这一策略从上下文工厂主体中拆出。
- :param runtime_state: CLI 运行期状态对象
+ :ivar runtime_state: CLI 运行期状态对象
"""
runtime_state: CliRuntimeState
def prepare_regular_command(self) -> None:
- """
- 为普通 CLI 命令应用默认日志策略。
-
- :return: None
- """
+ """为普通 CLI 命令应用默认日志策略。"""
self.runtime_state.suppress_logs()
self.runtime_state.suppress_sqlalchemy_logs()
@@ -103,9 +94,9 @@ class DangerousCommandContextSupport:
该对象负责危险命令规则查询、保护执行与拒绝结果收口,
让上下文工厂本体只保留装配职责。
- :param dangerous_command_rule_registry: 危险命令规则注册表
- :param dangerous_command_guard_service: 危险命令保护执行服务
- :param output_renderer: 输出渲染器
+ :ivar dangerous_command_rule_registry: 危险命令规则注册表
+ :ivar dangerous_command_guard_service: 危险命令保护执行服务
+ :ivar output_renderer: 输出渲染器
"""
dangerous_command_rule_registry: DangerousCommandRuleRegistry
@@ -132,11 +123,13 @@ class CliContextFactory:
"""
统一构建 CLI 命令上下文。
- :param runtime_state: CLI 运行期状态对象
- :param output_renderer: 输出渲染器
- :param cli_context_builder: CLI 上下文构建器
- :param dangerous_command_rule_registry: 危险命令规则注册表
- :param dangerous_command_guard_service: 危险命令保护执行服务
+ :ivar runtime_state: CLI 运行期状态对象
+ :ivar output_renderer: 输出渲染器
+ :ivar cli_context_builder: CLI 上下文构建器
+ :ivar dangerous_command_rule_registry: 危险命令规则注册表
+ :ivar dangerous_command_guard_service: 危险命令保护执行服务
+ :ivar _log_policy: 配置命令运行期间日志输出的策略
+ :ivar _dangerous_command_support: 处理高风险命令确认流程的支持对象
"""
runtime_state: CliRuntimeState = field(default_factory=CliRuntimeState)
diff --git a/ruoyi-fastapi-backend/cli/core/execution.py b/ruoyi-fastapi-backend/cli/core/execution.py
index 2afd47c84..8b5c9a67e 100644
--- a/ruoyi-fastapi-backend/cli/core/execution.py
+++ b/ruoyi-fastapi-backend/cli/core/execution.py
@@ -13,7 +13,7 @@ class CliExecutionService:
"""
CLI 执行与结果收口服务。
- :param output_renderer: 输出渲染器
+ :ivar output_renderer: 输出渲染器
"""
output_renderer: OutputRenderer = field(default_factory=OutputRenderer)
@@ -40,7 +40,6 @@ def complete_payload(
:param ctx: CLI 上下文
:param payload: 标准结果字典
:param default_exit_code: 默认退出码
- :return: None
"""
self.output_renderer.complete_command(self.build_result(payload, default_exit_code=default_exit_code), ctx)
@@ -54,7 +53,6 @@ def complete_result(
:param ctx: CLI 上下文
:param result: 命令执行结果对象
- :return: None
"""
self.output_renderer.complete_command(result, ctx)
@@ -75,7 +73,6 @@ def complete_payload_with_text(
:param text_builder: 文本结果构建函数
:param default_exit_code: 默认退出码
:param text_condition: 文本模式下是否应用构建函数的判定函数
- :return: None
"""
if ctx.output != 'text':
self.complete_payload(ctx, payload, default_exit_code=default_exit_code)
@@ -106,7 +103,6 @@ def complete_payload_result(
:param text_builder: 文本结果构建函数
:param default_exit_code: 默认退出码
:param text_condition: 文本模式下是否应用构建函数的判定函数
- :return: None
"""
if text_builder is None:
self.complete_payload(ctx, payload, default_exit_code=default_exit_code)
@@ -126,7 +122,7 @@ def build_result(payload: dict[str, Any], *, default_exit_code: int = 0) -> Comm
:param payload: 标准结果字典
:param default_exit_code: 默认退出码;当 payload 未显式提供 exit_code 且
- 该值仍为 0 时,失败结果会统一回退到 `RUNTIME_ERROR`
+ 该值仍为 0 时,失败结果会统一回退到 ``RUNTIME_ERROR``
:return: 命令结果对象
"""
result_payload = dict(payload)
diff --git a/ruoyi-fastapi-backend/cli/groups/app/command.py b/ruoyi-fastapi-backend/cli/groups/app/command.py
index 40bcea43c..0de53c634 100644
--- a/ruoyi-fastapi-backend/cli/groups/app/command.py
+++ b/ruoyi-fastapi-backend/cli/groups/app/command.py
@@ -22,7 +22,6 @@ def run_app(
启动当前 FastAPI 应用。
:param env: 当前命令运行环境
- :return: None
"""
_APP_COMMAND_CONTROLLER.run_app(env)
@@ -37,7 +36,6 @@ def doctor(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_APP_COMMAND_CONTROLLER.doctor(env, output)
@@ -52,7 +50,6 @@ def app_config(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_APP_COMMAND_CONTROLLER.show_config(env, output)
@@ -67,7 +64,6 @@ def app_env(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_APP_COMMAND_CONTROLLER.show_env(env, output)
@@ -90,7 +86,6 @@ def routes(
:param method: 请求方法过滤条件
:param group_by: 路由分组方式
:param include_hidden: 是否包含隐藏路由
- :return: None
"""
_APP_COMMAND_CONTROLLER.show_routes(
env,
diff --git a/ruoyi-fastapi-backend/cli/groups/app/controller.py b/ruoyi-fastapi-backend/cli/groups/app/controller.py
index 7e3df5ae6..84940b75e 100644
--- a/ruoyi-fastapi-backend/cli/groups/app/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/app/controller.py
@@ -23,8 +23,18 @@ class AppCommandController:
"""
应用命令控制器。
- 该控制器负责组织 `app` 命令组的上下文准备、runtime 调用、
+ 该控制器负责组织 ``app`` 命令组的上下文准备、runtime 调用、
payload 构建,以及基于输出格式选择 presenter 或直接返回 JSON。
+
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar presenter: 应用命令文本渲染器
+ :ivar runtime_service: 应用运行时服务
+ :ivar database_runtime: 数据库运行时服务
+ :ivar operations_runtime: 运维运行时服务
+ :ivar crypto_runtime: 传输加密运行时服务
+ :ivar oidc_runtime: OIDC 就绪检查运行时服务
+ :ivar bootstrap_service: 应用引导服务
"""
def __init__(
@@ -52,7 +62,6 @@ def __init__(
:param crypto_runtime: 传输加密运行时服务
:param oidc_runtime: OIDC 就绪检查运行时服务
:param bootstrap_service: 应用引导服务
- :return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
@@ -69,7 +78,6 @@ def run_app(self, env: str) -> None:
启动当前 FastAPI 应用。
:param env: 当前命令运行环境
- :return: None
"""
self.bootstrap_service.exec_app_run_command(env)
@@ -79,7 +87,6 @@ def doctor(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
db_status = self.execution_service.run_async(self.database_runtime.ping_database())
@@ -108,7 +115,6 @@ def show_config(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
self.execution_service.complete_payload_result(
@@ -124,7 +130,6 @@ def show_env(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
self.execution_service.complete_payload_result(
@@ -153,7 +158,6 @@ def show_routes(
:param method: 请求方法过滤条件
:param group_by: 路由分组方式
:param include_hidden: 是否包含隐藏路由
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
routes_payload = self._serialize_routes(
diff --git a/ruoyi-fastapi-backend/cli/groups/app/presenter.py b/ruoyi-fastapi-backend/cli/groups/app/presenter.py
index 8e50e02cf..36e96f4ef 100644
--- a/ruoyi-fastapi-backend/cli/groups/app/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/app/presenter.py
@@ -7,7 +7,7 @@ class AppCommandPresenter:
"""
应用命令文本渲染器。
- 该渲染器负责将 `app` 命令组产生的结构化 payload 转换为稳定的文本摘要,
+ 该渲染器负责将 ``app`` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
diff --git a/ruoyi-fastapi-backend/cli/groups/cache/command.py b/ruoyi-fastapi-backend/cli/groups/cache/command.py
index 6f803dfc0..8dad95cc9 100644
--- a/ruoyi-fastapi-backend/cli/groups/cache/command.py
+++ b/ruoyi-fastapi-backend/cli/groups/cache/command.py
@@ -23,7 +23,6 @@ def stats(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_CACHE_COMMAND_CONTROLLER.stats(env, output)
@@ -44,7 +43,6 @@ def keys(
:param cache_name: 缓存名称
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_CACHE_COMMAND_CONTROLLER.keys(cache_name, env, output)
@@ -71,7 +69,6 @@ def get(
:param cache_key: 缓存键名
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_CACHE_COMMAND_CONTROLLER.get(cache_name, cache_key, env, output)
@@ -103,7 +100,6 @@ def clear(
:param cache_name: 缓存名称前缀
:param cache_key: 缓存键名
:param clear_all: 是否清理全部缓存
- :return: None
"""
_CACHE_COMMAND_CONTROLLER.clear(
env,
@@ -139,7 +135,6 @@ def ttl(
:param cache_key: 缓存键名
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_CACHE_COMMAND_CONTROLLER.ttl(cache_name, cache_key, env, output)
@@ -158,6 +153,5 @@ def warmup(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
_CACHE_COMMAND_CONTROLLER.warmup(env, output, allow_prod, yes)
diff --git a/ruoyi-fastapi-backend/cli/groups/cache/controller.py b/ruoyi-fastapi-backend/cli/groups/cache/controller.py
index 92fd656b6..16e0019ba 100644
--- a/ruoyi-fastapi-backend/cli/groups/cache/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/cache/controller.py
@@ -12,12 +12,13 @@ class CacheCommandController:
"""
缓存命令控制器。
- 该控制器负责组织 `cache` 命令组的上下文准备、runtime 调用、
+ 该控制器负责组织 ``cache`` 命令组的上下文准备、runtime 调用、
payload 注入,以及基于输出格式选择 presenter 或直接返回 JSON。
- :param context_factory: CLI 上下文工厂
- :param execution_service: CLI 执行服务
- :param presenter: 缓存命令文本渲染器
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar presenter: 缓存命令文本渲染器
+ :ivar runtime_service: 缓存运行时服务
"""
def __init__(
@@ -35,7 +36,6 @@ def __init__(
:param execution_service: CLI 执行服务
:param presenter: 缓存命令文本渲染器
:param runtime_service: 缓存运行时服务
- :return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
@@ -48,7 +48,6 @@ def stats(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.get_cache_stats())
@@ -66,7 +65,6 @@ def keys(self, cache_name: str, env: str, output: str) -> None:
:param cache_name: 缓存名称
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.list_cache_keys(cache_name))
@@ -85,7 +83,6 @@ def get(self, cache_name: str, cache_key: str, env: str, output: str) -> None:
:param cache_key: 缓存键名
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.get_cache_value(cache_name, cache_key))
@@ -119,7 +116,6 @@ def clear(
:param cache_name: 缓存名称前缀
:param cache_key: 缓存键名
:param clear_all: 是否清理全部缓存
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -149,7 +145,6 @@ def ttl(self, cache_name: str, cache_key: str, env: str, output: str) -> None:
:param cache_key: 缓存键名
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.get_cache_ttl(cache_name, cache_key))
@@ -168,7 +163,6 @@ def warmup(self, env: str, output: str, allow_prod: bool, yes: bool) -> None:
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
diff --git a/ruoyi-fastapi-backend/cli/groups/cache/presenter.py b/ruoyi-fastapi-backend/cli/groups/cache/presenter.py
index 6b9605253..a6e300ee1 100644
--- a/ruoyi-fastapi-backend/cli/groups/cache/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/cache/presenter.py
@@ -5,7 +5,7 @@ class CacheCommandPresenter:
"""
缓存命令文本渲染器。
- 该渲染器负责将 `cache` 命令组产生的结构化 payload 转换为稳定的文本摘要,
+ 该渲染器负责将 ``cache`` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
diff --git a/ruoyi-fastapi-backend/cli/groups/config/command.py b/ruoyi-fastapi-backend/cli/groups/config/command.py
index ed0b695e3..94cb911be 100644
--- a/ruoyi-fastapi-backend/cli/groups/config/command.py
+++ b/ruoyi-fastapi-backend/cli/groups/config/command.py
@@ -48,7 +48,6 @@ def list_command(
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
- :return: None
"""
_CONFIG_COMMAND_CONTROLLER.list_configs(
env,
@@ -84,7 +83,6 @@ def get_command(
:param env: 当前命令运行环境
:param output: 输出格式
:param source: 配置读取来源
- :return: None
"""
_CONFIG_COMMAND_CONTROLLER.get_config(config_key, env, output, source=source)
@@ -121,7 +119,6 @@ def set_command(
:param name: 参数名称
:param config_type: 参数类型
:param remark: 参数备注
- :return: None
"""
_CONFIG_COMMAND_CONTROLLER.set_config(
config_key,
@@ -151,7 +148,6 @@ def sync_cache(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
_CONFIG_COMMAND_CONTROLLER.sync_cache(env, output, allow_prod, yes)
@@ -168,6 +164,5 @@ def doctor(
:param env: 当前命令运行环境
:param output: 输出格式
:param sample_limit: 问题示例键名输出上限
- :return: None
"""
_CONFIG_COMMAND_CONTROLLER.doctor(env, output, sample_limit=sample_limit)
diff --git a/ruoyi-fastapi-backend/cli/groups/config/controller.py b/ruoyi-fastapi-backend/cli/groups/config/controller.py
index 140489889..0ad56af30 100644
--- a/ruoyi-fastapi-backend/cli/groups/config/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/config/controller.py
@@ -14,12 +14,13 @@ class ConfigCommandController:
"""
参数配置命令控制器。
- 该控制器负责组织 `config` 命令组的上下文准备、runtime 调用、
+ 该控制器负责组织 ``config`` 命令组的上下文准备、runtime 调用、
payload 注入,以及基于输出格式选择 presenter 或直接返回 JSON。
- :param context_factory: CLI 上下文工厂
- :param execution_service: CLI 执行服务
- :param presenter: 参数配置命令文本渲染器
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar presenter: 参数配置命令文本渲染器
+ :ivar runtime_service: 参数配置运行时服务
"""
def __init__(
@@ -37,7 +38,6 @@ def __init__(
:param execution_service: CLI 执行服务
:param presenter: 参数配置命令文本渲染器
:param runtime_service: 参数配置运行时服务
- :return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
@@ -71,7 +71,6 @@ def list_configs(
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(
@@ -109,7 +108,6 @@ def get_config(
:param env: 当前命令运行环境
:param output: 输出格式
:param source: 配置读取来源
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.get_config(config_key, source=source))
@@ -148,7 +146,6 @@ def set_config(
:param name: 参数名称
:param config_type: 参数类型
:param remark: 参数备注
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -185,7 +182,6 @@ def sync_cache(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -212,7 +208,6 @@ def doctor(
:param env: 当前命令运行环境
:param output: 输出格式
:param sample_limit: 问题示例键名输出上限
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.diagnose_config(sample_limit=sample_limit))
diff --git a/ruoyi-fastapi-backend/cli/groups/config/presenter.py b/ruoyi-fastapi-backend/cli/groups/config/presenter.py
index cde9693aa..a1c617c5b 100644
--- a/ruoyi-fastapi-backend/cli/groups/config/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/config/presenter.py
@@ -5,7 +5,7 @@ class ConfigCommandPresenter:
"""
参数配置命令文本渲染器。
- 该渲染器负责将 `config` 命令组产生的结构化 payload 转换为稳定的文本摘要,
+ 该渲染器负责将 ``config`` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
diff --git a/ruoyi-fastapi-backend/cli/groups/crypto/command.py b/ruoyi-fastapi-backend/cli/groups/crypto/command.py
index 391199b8f..8ee5d1916 100644
--- a/ruoyi-fastapi-backend/cli/groups/crypto/command.py
+++ b/ruoyi-fastapi-backend/cli/groups/crypto/command.py
@@ -22,7 +22,6 @@ def validate(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_CRYPTO_COMMAND_CONTROLLER.validate(env, output)
@@ -41,7 +40,6 @@ def keygen(
:param output: 输出格式
:param kid: 生成的密钥版本标识
:param key_size: RSA 密钥长度
- :return: None
"""
_CRYPTO_COMMAND_CONTROLLER.keygen(env, output, kid=kid, key_size=key_size)
@@ -66,7 +64,6 @@ def rotate(
:param dry_run: 是否演练执行
:param next_kid: 轮换后的新密钥版本标识
:param key_size: 新密钥的 RSA 长度
- :return: None
"""
_CRYPTO_COMMAND_CONTROLLER.rotate(
env,
@@ -89,6 +86,5 @@ def export_public(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_CRYPTO_COMMAND_CONTROLLER.export_public(env, output)
diff --git a/ruoyi-fastapi-backend/cli/groups/crypto/controller.py b/ruoyi-fastapi-backend/cli/groups/crypto/controller.py
index 919e4f4ef..fcb2688ab 100644
--- a/ruoyi-fastapi-backend/cli/groups/crypto/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/crypto/controller.py
@@ -12,12 +12,13 @@ class CryptoCommandController:
"""
传输加密命令控制器。
- 该控制器负责组织 `crypto` 命令组的上下文准备、runtime 调用、
+ 该控制器负责组织 ``crypto`` 命令组的上下文准备、runtime 调用、
payload 注入,以及基于输出格式选择 presenter 或直接返回 JSON。
- :param context_factory: CLI 上下文工厂
- :param execution_service: CLI 执行服务
- :param presenter: 传输加密命令文本渲染器
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar presenter: 传输加密命令文本渲染器
+ :ivar runtime_service: 传输加密运行时服务
"""
def __init__(
@@ -35,7 +36,6 @@ def __init__(
:param execution_service: CLI 执行服务
:param presenter: 传输加密命令文本渲染器
:param runtime_service: 传输加密运行时服务
- :return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
@@ -48,7 +48,6 @@ def validate(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
self.execution_service.complete_payload(ctx, self.runtime_service.validate_crypto_config())
@@ -61,7 +60,6 @@ def keygen(self, env: str, output: str, *, kid: str, key_size: int) -> None:
:param output: 输出格式
:param kid: 生成的密钥版本标识
:param key_size: RSA 密钥长度
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.runtime_service.generate_crypto_key_pair(kid, key_size)
@@ -94,7 +92,6 @@ def rotate(
:param dry_run: 是否演练执行
:param next_kid: 轮换后的新密钥版本标识
:param key_size: 新密钥的 RSA 长度
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -112,7 +109,6 @@ def export_public(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.runtime_service.export_public_key()
diff --git a/ruoyi-fastapi-backend/cli/groups/crypto/presenter.py b/ruoyi-fastapi-backend/cli/groups/crypto/presenter.py
index cf5f542be..135b1c9be 100644
--- a/ruoyi-fastapi-backend/cli/groups/crypto/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/crypto/presenter.py
@@ -2,7 +2,7 @@ class CryptoCommandPresenter:
"""
传输加密命令文本渲染器。
- 该渲染器负责将 `crypto` 命令组产生的结构化 payload 转换为稳定的文本摘要,
+ 该渲染器负责将 ``crypto`` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
diff --git a/ruoyi-fastapi-backend/cli/groups/db/command.py b/ruoyi-fastapi-backend/cli/groups/db/command.py
index 80063ded4..4bce33ae3 100644
--- a/ruoyi-fastapi-backend/cli/groups/db/command.py
+++ b/ruoyi-fastapi-backend/cli/groups/db/command.py
@@ -25,7 +25,6 @@ def check(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_DB_COMMAND_CONTROLLER.check(env, output)
@@ -40,7 +39,6 @@ def current(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_DB_COMMAND_CONTROLLER.current(env, output)
@@ -70,7 +68,6 @@ def upgrade(
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:param revision: 目标迁移版本
- :return: None
"""
_DB_COMMAND_CONTROLLER.upgrade(env, output, allow_prod, yes, dry_run, revision=revision)
@@ -91,7 +88,6 @@ def init(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
- :return: None
"""
_DB_COMMAND_CONTROLLER.init(env, output, allow_prod, yes, dry_run)
@@ -121,7 +117,6 @@ def downgrade(
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:param revision: 目标回退版本
- :return: None
"""
_DB_COMMAND_CONTROLLER.downgrade(env, output, allow_prod, yes, dry_run, revision=revision)
@@ -146,7 +141,6 @@ def revision(
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:param autogenerate: 是否自动生成迁移内容
- :return: None
"""
_DB_COMMAND_CONTROLLER.revision(
message,
@@ -169,7 +163,6 @@ def heads(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_DB_COMMAND_CONTROLLER.heads(env, output)
@@ -186,6 +179,5 @@ def history(
:param env: 当前命令运行环境
:param output: 输出格式
:param limit: 输出的最大历史记录数量
- :return: None
"""
_DB_COMMAND_CONTROLLER.history(env, output, limit=limit)
diff --git a/ruoyi-fastapi-backend/cli/groups/db/controller.py b/ruoyi-fastapi-backend/cli/groups/db/controller.py
index 7e4bb3cfd..0a45300d4 100644
--- a/ruoyi-fastapi-backend/cli/groups/db/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/db/controller.py
@@ -12,12 +12,13 @@ class DbCommandController:
"""
数据库命令控制器。
- 该控制器负责组织 `db` 命令组的上下文准备、runtime 调用、
+ 该控制器负责组织 ``db`` 命令组的上下文准备、runtime 调用、
payload 注入,以及基于输出格式选择 presenter 或直接返回 JSON。
- :param context_factory: CLI 上下文工厂
- :param execution_service: CLI 执行服务
- :param presenter: 数据库命令文本渲染器
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar presenter: 数据库命令文本渲染器
+ :ivar runtime_service: 数据库运行时服务
"""
def __init__(
@@ -35,7 +36,6 @@ def __init__(
:param execution_service: CLI 执行服务
:param presenter: 数据库命令文本渲染器
:param runtime_service: 数据库运行时服务
- :return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
@@ -48,7 +48,6 @@ def check(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
self.execution_service.complete_payload(
@@ -61,7 +60,6 @@ def current(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.runtime_service.get_current_revision()
@@ -92,7 +90,6 @@ def upgrade(
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:param revision: 目标迁移版本
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -120,7 +117,6 @@ def init(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -151,7 +147,6 @@ def downgrade(
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:param revision: 目标回退版本
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -184,7 +179,6 @@ def revision(
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
:param autogenerate: 是否自动生成迁移内容
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -205,7 +199,6 @@ def heads(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.runtime_service.get_alembic_heads()
@@ -224,7 +217,6 @@ def history(self, env: str, output: str, *, limit: int) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
:param limit: 输出的最大历史记录数量
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.runtime_service.get_alembic_history(limit=limit)
diff --git a/ruoyi-fastapi-backend/cli/groups/db/presenter.py b/ruoyi-fastapi-backend/cli/groups/db/presenter.py
index 72d04b168..d7bc5db72 100644
--- a/ruoyi-fastapi-backend/cli/groups/db/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/db/presenter.py
@@ -2,7 +2,7 @@ class DbCommandPresenter:
"""
数据库命令文本渲染器。
- 该渲染器负责将 `db` 命令组产生的结构化 payload 转换为稳定的文本摘要,
+ 该渲染器负责将 ``db`` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
diff --git a/ruoyi-fastapi-backend/cli/groups/dev/command.py b/ruoyi-fastapi-backend/cli/groups/dev/command.py
index 0a0f90561..1b3794f1f 100644
--- a/ruoyi-fastapi-backend/cli/groups/dev/command.py
+++ b/ruoyi-fastapi-backend/cli/groups/dev/command.py
@@ -14,7 +14,7 @@
_DEV_COMMAND_CONTROLLER = DevCommandController()
-@app.command('lint', help='执行 Ruff 格式化与静态检查')
+@app.command('lint', help='执行 Ruff 检查、格式化和 reST 文档字符串检查')
def lint(
targets: Annotated[list[str] | None, typer.Argument(help='待检查路径,可传多个')] = None,
env: EnvOption = 'dev',
@@ -24,7 +24,7 @@ def lint(
unsafe_fixes: bool = typer.Option(False, '--unsafe-fixes', help='允许 Ruff 不安全修复'),
) -> None:
"""
- 执行 Ruff 格式化与静态检查。
+ 执行 Ruff 检查、格式化和 reST 文档字符串检查。
:param targets: 待检查路径列表
:param env: 当前命令运行环境
@@ -32,7 +32,6 @@ def lint(
:param check_only: 是否仅检查不写回
:param fix: 是否自动修复可修复问题
:param unsafe_fixes: 是否允许不安全修复
- :return: None
"""
_DEV_COMMAND_CONTROLLER.lint(
targets,
@@ -62,7 +61,6 @@ def test(
:param keyword: pytest 关键字过滤表达式
:param maxfail: 最大失败数
:param quiet: 是否启用简洁输出
- :return: None
"""
_DEV_COMMAND_CONTROLLER.test(
targets,
diff --git a/ruoyi-fastapi-backend/cli/groups/dev/controller.py b/ruoyi-fastapi-backend/cli/groups/dev/controller.py
index ccd86821a..470d12d3a 100644
--- a/ruoyi-fastapi-backend/cli/groups/dev/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/dev/controller.py
@@ -12,12 +12,13 @@ class DevCommandController:
"""
开发命令控制器。
- 该控制器负责组织 `dev` 命令组的上下文准备、runtime 调用、
+ 该控制器负责组织 ``dev`` 命令组的上下文准备、runtime 调用、
payload 注入,以及基于输出格式选择 presenter 或直接返回 JSON。
- :param context_factory: CLI 上下文工厂
- :param execution_service: CLI 执行服务
- :param presenter: 开发命令文本渲染器
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar presenter: 开发命令文本渲染器
+ :ivar runtime_service: 开发运行时服务
"""
def __init__(
@@ -35,7 +36,6 @@ def __init__(
:param execution_service: CLI 执行服务
:param presenter: 开发命令文本渲染器
:param runtime_service: 开发运行时服务
- :return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
@@ -53,7 +53,7 @@ def lint(
unsafe_fixes: bool,
) -> None:
"""
- 执行 Ruff 格式化与静态检查。
+ 执行 Ruff 检查、格式化和 reST 文档字符串检查。
:param targets: 待检查路径列表
:param env: 当前命令运行环境
@@ -61,7 +61,6 @@ def lint(
:param check_only: 是否仅检查不写回
:param fix: 是否自动修复可修复问题
:param unsafe_fixes: 是否允许不安全修复
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.runtime_service.run_lint(targets, check_only=check_only, fix=fix, unsafe_fixes=unsafe_fixes)
@@ -91,7 +90,6 @@ def test(
:param keyword: pytest 关键字过滤表达式
:param maxfail: 最大失败数
:param quiet: 是否启用简洁输出
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.runtime_service.run_tests(targets, keyword=keyword, maxfail=maxfail, quiet=quiet)
diff --git a/ruoyi-fastapi-backend/cli/groups/dev/presenter.py b/ruoyi-fastapi-backend/cli/groups/dev/presenter.py
index b5fc144c2..4a8929bd5 100644
--- a/ruoyi-fastapi-backend/cli/groups/dev/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/dev/presenter.py
@@ -2,7 +2,7 @@ class DevCommandPresenter:
"""
开发命令文本渲染器。
- 该渲染器负责将 `dev` 命令组产生的结构化 payload 转换为稳定的文本摘要,
+ 该渲染器负责将 ``dev`` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
@@ -28,6 +28,8 @@ def build_dev_lint_text(self, payload: dict[str, object]) -> str:
lines.append('targets: none')
lines.extend(self._build_command_result_section('format', payload.get('format')))
lines.extend(self._build_command_result_section('check', payload.get('check')))
+ if 'docstrings' in payload:
+ lines.extend(self._build_command_result_section('docstrings', payload['docstrings']))
return '\n'.join(lines)
def build_dev_test_text(self, payload: dict[str, object]) -> str:
diff --git a/ruoyi-fastapi-backend/cli/groups/gen/command.py b/ruoyi-fastapi-backend/cli/groups/gen/command.py
index e4aac33d3..5eec80f06 100644
--- a/ruoyi-fastapi-backend/cli/groups/gen/command.py
+++ b/ruoyi-fastapi-backend/cli/groups/gen/command.py
@@ -39,7 +39,6 @@ def import_table(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
- :return: None
"""
_GEN_COMMAND_CONTROLLER.import_table(
table_names,
@@ -76,7 +75,6 @@ def list_command(
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
- :return: None
"""
_GEN_COMMAND_CONTROLLER.list_tables(
env,
@@ -114,7 +112,6 @@ def db_list(
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
- :return: None
"""
_GEN_COMMAND_CONTROLLER.list_db_tables(
env,
@@ -139,7 +136,6 @@ def detail(
:param table_id: 业务表 ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_GEN_COMMAND_CONTROLLER.show_detail(table_id, env, output)
@@ -169,7 +165,6 @@ def create_table(
:param dry_run: 是否演练执行
:param sql: 直接传入的 SQL 文本
:param sql_file: SQL 文件路径
- :return: None
"""
_GEN_COMMAND_CONTROLLER.create_table(
env,
@@ -194,7 +189,6 @@ def preview(
:param table_id: 业务表 ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_GEN_COMMAND_CONTROLLER.preview(table_id, env, output)
@@ -232,7 +226,6 @@ def export(
:param dry_run: 是否演练执行
:param mode: 导出模式
:param output_file: zip 导出目标文件路径
- :return: None
"""
_GEN_COMMAND_CONTROLLER.export(
table_names,
@@ -268,6 +261,5 @@ def sync_db(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
_GEN_COMMAND_CONTROLLER.sync_db(table_name, env, output, allow_prod, yes)
diff --git a/ruoyi-fastapi-backend/cli/groups/gen/controller.py b/ruoyi-fastapi-backend/cli/groups/gen/controller.py
index 84fb44692..35d3f7ce1 100644
--- a/ruoyi-fastapi-backend/cli/groups/gen/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/gen/controller.py
@@ -12,12 +12,13 @@ class GenCommandController:
"""
代码生成命令控制器。
- 该控制器负责组织 `gen` 命令组的上下文准备、runtime 调用、
+ 该控制器负责组织 ``gen`` 命令组的上下文准备、runtime 调用、
payload 注入,以及基于输出格式选择 presenter 或直接返回 JSON。
- :param context_factory: CLI 上下文工厂
- :param execution_service: CLI 执行服务
- :param presenter: 代码生成命令文本渲染器
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar presenter: 代码生成命令文本渲染器
+ :ivar runtime_service: 代码生成运行时服务
"""
def __init__(
@@ -35,7 +36,6 @@ def __init__(
:param execution_service: CLI 执行服务
:param presenter: 代码生成命令文本渲染器
:param runtime_service: 代码生成运行时服务
- :return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
@@ -60,7 +60,6 @@ def import_table(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否演练执行
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -95,7 +94,6 @@ def list_tables(
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(
@@ -136,7 +134,6 @@ def list_db_tables(
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(
@@ -163,7 +160,6 @@ def show_detail(self, table_id: int, env: str, output: str) -> None:
:param table_id: 业务表 ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.get_gen_table_detail(table_id))
@@ -196,7 +192,6 @@ def create_table(
:param dry_run: 是否演练执行
:param sql: 直接传入的 SQL 文本
:param sql_file: SQL 文件路径
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -217,7 +212,6 @@ def preview(self, table_id: int, env: str, output: str) -> None:
:param table_id: 业务表 ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.runtime_service.preview_code(table_id))
@@ -252,7 +246,6 @@ def export(
:param dry_run: 是否演练执行
:param mode: 导出模式
:param output_file: zip 导出目标文件路径
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -289,7 +282,6 @@ def sync_db(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
diff --git a/ruoyi-fastapi-backend/cli/groups/gen/presenter.py b/ruoyi-fastapi-backend/cli/groups/gen/presenter.py
index 744d2537d..b47df14b5 100644
--- a/ruoyi-fastapi-backend/cli/groups/gen/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/gen/presenter.py
@@ -5,7 +5,7 @@ class GenCommandPresenter:
"""
代码生成命令文本渲染器。
- 该渲染器负责将 `gen` 命令组产生的结构化 payload 转换为稳定的文本摘要,
+ 该渲染器负责将 ``gen`` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
diff --git a/ruoyi-fastapi-backend/cli/groups/job/command.py b/ruoyi-fastapi-backend/cli/groups/job/command.py
index af62ea75c..05168079d 100644
--- a/ruoyi-fastapi-backend/cli/groups/job/command.py
+++ b/ruoyi-fastapi-backend/cli/groups/job/command.py
@@ -40,7 +40,6 @@ def list_command(
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
- :return: None
"""
_JOB_COMMAND_CONTROLLER.list(
env,
@@ -74,7 +73,6 @@ def run_once(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
_JOB_COMMAND_CONTROLLER.run_once(job_id, env, output, allow_prod, yes)
@@ -95,7 +93,6 @@ def detail(
:param job_id: 任务ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_JOB_COMMAND_CONTROLLER.detail(job_id, env, output)
@@ -131,7 +128,6 @@ def logs(
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
- :return: None
"""
_JOB_COMMAND_CONTROLLER.logs(
env,
@@ -167,7 +163,6 @@ def pause(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
_JOB_COMMAND_CONTROLLER.pause(job_id, env, output, allow_prod, yes)
@@ -192,7 +187,6 @@ def resume(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
_JOB_COMMAND_CONTROLLER.resume(job_id, env, output, allow_prod, yes)
@@ -211,6 +205,5 @@ def sync(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
_JOB_COMMAND_CONTROLLER.sync(env, output, allow_prod, yes)
diff --git a/ruoyi-fastapi-backend/cli/groups/job/controller.py b/ruoyi-fastapi-backend/cli/groups/job/controller.py
index 92bc25223..ef2e1d174 100644
--- a/ruoyi-fastapi-backend/cli/groups/job/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/job/controller.py
@@ -13,12 +13,14 @@ class JobCommandController:
"""
定时任务命令控制器。
- 该控制器负责组织 `job` 命令组的上下文准备、runtime 调用、
+ 该控制器负责组织 ``job`` 命令组的上下文准备、runtime 调用、
payload 注入,以及基于输出格式选择 presenter 或直接返回 JSON。
- :param context_factory: CLI 上下文工厂
- :param execution_service: CLI 执行服务
- :param presenter: 定时任务命令文本渲染器
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar presenter: 定时任务命令文本渲染器
+ :ivar operations_runtime: 运维运行时服务
+ :ivar job_runtime: 定时任务运行时服务
"""
def __init__(
@@ -38,7 +40,6 @@ def __init__(
:param presenter: 定时任务命令文本渲染器
:param operations_runtime: 运维运行时服务
:param job_runtime: 定时任务运行时服务
- :return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
@@ -69,7 +70,6 @@ def list(
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(
@@ -98,7 +98,6 @@ def run_once(self, job_id: int, env: str, output: str, allow_prod: bool, yes: bo
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
ctx = self.context_factory.build_dangerous(env, output, allow_prod, yes, False, command_name='job run-once')
self.execution_service.complete_payload(
@@ -112,7 +111,6 @@ def detail(self, job_id: int, env: str, output: str) -> None:
:param job_id: 任务ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.job_runtime.get_job_detail(job_id))
@@ -150,7 +148,6 @@ def logs(
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(
@@ -181,7 +178,6 @@ def pause(self, job_id: int, env: str, output: str, allow_prod: bool, yes: bool)
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
ctx = self.context_factory.build_dangerous(env, output, allow_prod, yes, False, command_name='job pause')
self.execution_service.complete_payload(
@@ -197,7 +193,6 @@ def resume(self, job_id: int, env: str, output: str, allow_prod: bool, yes: bool
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
ctx = self.context_factory.build_dangerous(env, output, allow_prod, yes, False, command_name='job resume')
self.execution_service.complete_payload(
@@ -212,7 +207,6 @@ def sync(self, env: str, output: str, allow_prod: bool, yes: bool) -> None:
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
ctx = self.context_factory.build_dangerous(env, output, allow_prod, yes, False, command_name='job sync')
self.execution_service.complete_payload(
diff --git a/ruoyi-fastapi-backend/cli/groups/job/presenter.py b/ruoyi-fastapi-backend/cli/groups/job/presenter.py
index 093e78913..426fc2481 100644
--- a/ruoyi-fastapi-backend/cli/groups/job/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/job/presenter.py
@@ -5,7 +5,7 @@ class JobCommandPresenter:
"""
定时任务命令文本渲染器。
- 该渲染器负责将 `job` 命令组产生的结构化 payload 转换为稳定的文本摘要,
+ 该渲染器负责将 ``job`` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
diff --git a/ruoyi-fastapi-backend/cli/groups/oidc/command.py b/ruoyi-fastapi-backend/cli/groups/oidc/command.py
index 99c94fbf7..f60407b11 100644
--- a/ruoyi-fastapi-backend/cli/groups/oidc/command.py
+++ b/ruoyi-fastapi-backend/cli/groups/oidc/command.py
@@ -31,7 +31,7 @@ def bootstrap_key(
actor: Annotated[str, typer.Option('--actor', help='写入审计记录的部署操作者')] = 'system:deployment',
) -> None:
"""
- 初始化首把 OIDC 签名密钥
+ 初始化首把 OIDC 签名密钥。
:param env: 当前命令运行环境
:param output: 输出格式
@@ -40,7 +40,6 @@ def bootstrap_key(
:param dry_run: 是否只执行预演
:param kid: 首把签名密钥标识
:param actor: 部署操作人标识
- :return: None
"""
_OIDC_COMMAND_CONTROLLER.bootstrap_key(
env,
diff --git a/ruoyi-fastapi-backend/cli/groups/oidc/controller.py b/ruoyi-fastapi-backend/cli/groups/oidc/controller.py
index 4cd554767..b3a560aee 100644
--- a/ruoyi-fastapi-backend/cli/groups/oidc/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/oidc/controller.py
@@ -4,10 +4,14 @@
class OidcCommandController:
"""
- OIDC 命令控制器
+ OIDC 命令控制器。
该控制器负责组织 OIDC 命令组的上下文准备、危险操作保护、
runtime 调用和结果输出。
+
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar runtime_service: OIDC CLI 运行时服务
"""
def __init__(
@@ -18,12 +22,11 @@ def __init__(
runtime_service: OidcRuntimeCliService | None = None,
) -> None:
"""
- 初始化 OIDC 命令控制器
+ 初始化 OIDC 命令控制器。
:param context_factory: CLI 上下文工厂
:param execution_service: CLI 执行服务
:param runtime_service: OIDC CLI 运行时服务
- :return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
@@ -41,7 +44,7 @@ def bootstrap_key(
actor: str,
) -> None:
"""
- 执行幂等首把 OIDC 签名密钥初始化
+ 执行幂等首把 OIDC 签名密钥初始化。
:param env: 当前命令运行环境
:param output: 输出格式
@@ -50,7 +53,6 @@ def bootstrap_key(
:param dry_run: 是否只执行预演
:param kid: 首把签名密钥标识
:param actor: 部署操作人标识
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
diff --git a/ruoyi-fastapi-backend/cli/groups/ops/command.py b/ruoyi-fastapi-backend/cli/groups/ops/command.py
index c12530db6..ce6c8500f 100644
--- a/ruoyi-fastapi-backend/cli/groups/ops/command.py
+++ b/ruoyi-fastapi-backend/cli/groups/ops/command.py
@@ -22,7 +22,6 @@ def ping_db(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_OPS_COMMAND_CONTROLLER.ping_db(env, output)
@@ -37,7 +36,6 @@ def ping_redis_command(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_OPS_COMMAND_CONTROLLER.ping_redis(env, output)
@@ -52,7 +50,6 @@ def health(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_OPS_COMMAND_CONTROLLER.health(env, output)
@@ -69,7 +66,6 @@ def deps(
:param env: 当前命令运行环境
:param output: 输出格式
:param include_dev: 是否附带输出开发依赖
- :return: None
"""
_OPS_COMMAND_CONTROLLER.deps(env, output, include_dev=include_dev)
@@ -84,6 +80,5 @@ def server_info(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
_OPS_COMMAND_CONTROLLER.server_info(env, output)
diff --git a/ruoyi-fastapi-backend/cli/groups/ops/controller.py b/ruoyi-fastapi-backend/cli/groups/ops/controller.py
index 346abebac..f5e7f897c 100644
--- a/ruoyi-fastapi-backend/cli/groups/ops/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/ops/controller.py
@@ -14,12 +14,14 @@ class OpsCommandController:
"""
运维命令控制器。
- 该控制器负责组织 `ops` 命令组的上下文准备、runtime 调用、
+ 该控制器负责组织 ``ops`` 命令组的上下文准备、runtime 调用、
payload 注入,以及基于输出格式选择 presenter 或直接返回 JSON。
- :param context_factory: CLI 上下文工厂
- :param execution_service: CLI 执行服务
- :param presenter: 运维命令文本渲染器
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar presenter: 运维命令文本渲染器
+ :ivar database_runtime: 数据库运行时服务
+ :ivar operations_runtime: 运维运行时服务
"""
def __init__(
@@ -39,7 +41,6 @@ def __init__(
:param presenter: 运维命令文本渲染器
:param database_runtime: 数据库运行时服务
:param operations_runtime: 运维运行时服务
- :return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
@@ -53,7 +54,6 @@ def ping_db(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
self.execution_service.complete_payload(
@@ -66,7 +66,6 @@ def ping_redis(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
self.execution_service.complete_payload(
@@ -80,7 +79,6 @@ def health(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
db_status = self.execution_service.run_async(self.database_runtime.ping_database())
@@ -106,7 +104,6 @@ def deps(self, env: str, output: str, *, include_dev: bool) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
:param include_dev: 是否附带输出开发依赖
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.operations_runtime.get_dependency_versions(include_dev=include_dev)
@@ -124,7 +121,6 @@ def server_info(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.operations_runtime.get_server_info())
diff --git a/ruoyi-fastapi-backend/cli/groups/ops/presenter.py b/ruoyi-fastapi-backend/cli/groups/ops/presenter.py
index 31aa1ab79..a271aebd8 100644
--- a/ruoyi-fastapi-backend/cli/groups/ops/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/ops/presenter.py
@@ -5,7 +5,7 @@ class OpsCommandPresenter:
"""
运维命令文本渲染器。
- 该渲染器负责将 `ops` 命令组产生的结构化 payload 转换为稳定的文本摘要,
+ 该渲染器负责将 ``ops`` 命令组产生的结构化 payload 转换为稳定的文本摘要,
同时保持 JSON 输出仍由控制器直接返回,不在此处做契约变形。
"""
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/artifact_controller.py b/ruoyi-fastapi-backend/cli/groups/plugin/artifact_controller.py
index a8d1895f9..b1cb34efd 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/artifact_controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/artifact_controller.py
@@ -21,6 +21,14 @@ class PluginArtifactCommandController:
制品发布命令控制器。
普通插件命令及帮助查询不加载制品部署依赖。
+
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar config_factory: 制品部署配置工厂
+ :ivar catalog_factory: 制品目录服务工厂
+ :ivar service_factory: 维护发布服务工厂
+ :ivar enablement_factory: 制品启停服务工厂
+ :ivar maintenance_factory: 制品清理与签名轮换服务工厂
"""
def __init__(
@@ -44,7 +52,6 @@ def __init__(
:param service_factory: 维护发布服务工厂
:param enablement_factory: 制品启停服务工厂
:param maintenance_factory: 制品清理与签名轮换服务工厂
- :return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
@@ -85,7 +92,7 @@ def maintain_artifacts(
:param allow_prod: 是否允许生产环境变更
:param yes: 是否跳过交互确认
:param dry_run: 是否只生成清理计划
- :return: None
+ :raises ValueError: 未知制品维护命令
"""
methods = {
'inspect': 'inspect',
@@ -189,7 +196,6 @@ def _execute(self, ctx: CliContext, action: Callable[[], dict[str, Any]]) -> Non
:param ctx: CLI 上下文
:param action: 当前命令需要执行的操作
- :return: None
"""
try:
payload = action()
@@ -222,6 +228,7 @@ def _signing_key(source: Path, key_file: Path, password_env: str | None) -> Any:
:param key_file: 插件目录之外的 Ed25519 PKCS8 私钥文件
:param password_env: 保存加密私钥密码的环境变量名称
:return: Ed25519 签名私钥
+ :raises ValueError: 签名私钥必须放在插件源码/预构建目录之外,防止被打入制品;签名私钥文件不存在或过大;签名私钥必须是PKCS8 PEM格式;无法读取PKCS8私钥,请检查密钥格式和密码环境变量;制品签名私钥必须为Ed25519
"""
if key_file.resolve().is_relative_to(source.resolve()):
raise ValueError('签名私钥必须放在插件源码/预构建目录之外,防止被打入制品')
@@ -267,7 +274,6 @@ def build_artifact(
:param key_file: 插件目录之外的 Ed25519 PKCS8 私钥文件
:param key_id: 发布者公钥标识
:param password_env: 保存加密私钥密码的环境变量名称
- :return: None
"""
ctx = self._context(env, output)
@@ -292,7 +298,6 @@ def verify_artifact(self, path: Path, env: str, output: str) -> None:
:param path: 待处理的签名制品文件
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self._context(env, output)
@@ -319,7 +324,6 @@ def import_artifact(self, path: Path, env: str, output: str, *, allow_prod: bool
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演而不写入发布状态
- :return: None
"""
ctx = self._context(
env, output, command_name='plugin artifact import', allow_prod=allow_prod, yes=yes, dry_run=dry_run
@@ -338,7 +342,6 @@ def list_artifacts(self, env: str, output: str, *, plugin_id: str | None = None)
:param env: 当前命令运行环境
:param output: 输出格式
:param plugin_id: 插件 ID
- :return: None
"""
ctx = self._context(env, output)
self._execute(
@@ -356,7 +359,6 @@ def plan_release(self, plugin_id: str, digest: str, env: str, output: str) -> No
:param digest: 已导入制品的 SHA256 摘要
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self._context(env, output)
self._execute(
@@ -389,7 +391,6 @@ def prepare_release(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演而不写入发布状态
- :return: None
"""
ctx = self._context(
env, output, command_name='plugin release prepare', allow_prod=allow_prod, yes=yes, dry_run=dry_run
@@ -428,7 +429,6 @@ def select_release(
:param maintenance: 是否确认已停止全部宿主 worker 并进入维护窗口
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
ctx = self._context(env, output, command_name='plugin release select', allow_prod=allow_prod, yes=yes)
self._execute(
@@ -452,7 +452,6 @@ def release_status(self, env: str, output: str, *, plugin_id: str | None = None)
:param env: 当前命令运行环境
:param output: 输出格式
:param plugin_id: 插件 ID
- :return: None
"""
ctx = self._context(env, output)
self._execute(
@@ -524,7 +523,6 @@ def wait_release(
:param expected_workers: 本次发布要求的宿主 worker 数量
:param timeout_seconds: 轮询超时秒数,为零时只查询一次
:param poll_interval_seconds: 两次查询的间隔秒数
- :return: None
"""
error = self._release_wait_argument_error(
plugin_id, digest, expected_generation, expected_workers, timeout_seconds, poll_interval_seconds
@@ -596,7 +594,6 @@ def rollback_release(
:param maintenance: 是否确认已停止全部宿主 worker 并进入维护窗口
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
ctx = self._context(env, output, command_name='plugin release rollback', allow_prod=allow_prod, yes=yes)
self._execute(
@@ -635,7 +632,6 @@ def set_release_enabled(
:param maintenance: 是否确认已停止全部宿主 worker 并进入维护窗口
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
operation = 'enable' if enabled else 'disable'
ctx = self._context(env, output, command_name=f'plugin release {operation}', allow_prod=allow_prod, yes=yes)
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/commands/artifact.py b/ruoyi-fastapi-backend/cli/groups/plugin/commands/artifact.py
index 36ac147bd..cc2781b30 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/commands/artifact.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/commands/artifact.py
@@ -21,7 +21,6 @@ def register_artifact_commands(app: typer.Typer, get_controller: Callable[[], An
:param app: Typer 命令组
:param get_controller: 制品命令控制器工厂
- :return: None
"""
artifact_app = typer.Typer(help='构建、验证和导入签名插件制品', no_args_is_help=True)
release_app = typer.Typer(help='维护准备、目标选择和worker实际加载状态', no_args_is_help=True)
@@ -50,7 +49,6 @@ def artifact_build(
:param password_env: 保存加密私钥密码的环境变量名称
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().build_artifact(
source, destination, env, output, key_file=key_file, key_id=key_id, password_env=password_env
@@ -68,7 +66,6 @@ def artifact_verify(
:param path: 待处理的签名制品文件
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().verify_artifact(path, env, output)
@@ -90,7 +87,6 @@ def artifact_import(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演而不写入发布状态
- :return: None
"""
get_controller().import_artifact(path, env, output, allow_prod=allow_prod, yes=yes, dry_run=dry_run)
@@ -106,7 +102,6 @@ def artifact_list(
:param plugin_id: 插件 ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().list_artifacts(env, output, plugin_id=plugin_id)
@@ -124,7 +119,6 @@ def release_plan(
:param digest: 已导入制品的 SHA256 摘要
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().plan_release(plugin_id, digest, env, output)
@@ -150,7 +144,6 @@ def release_prepare(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演而不写入发布状态
- :return: None
"""
get_controller().prepare_release(
plugin_id, digest, env, output, maintenance=maintenance, allow_prod=allow_prod, yes=yes, dry_run=dry_run
@@ -180,7 +173,6 @@ def release_select(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
get_controller().select_release(
plugin_id,
@@ -206,7 +198,6 @@ def release_status(
:param plugin_id: 插件 ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().release_status(env, output, plugin_id=plugin_id)
@@ -234,7 +225,6 @@ def release_wait(
:param interval: 查询间隔秒数
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().wait_release(
plugin_id,
@@ -271,7 +261,6 @@ def release_rollback(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
get_controller().rollback_release(
plugin_id,
@@ -291,7 +280,6 @@ def _register_release_enablement(app: typer.Typer, get_controller: Callable[[],
:param app: Typer 命令组
:param get_controller: 制品命令控制器工厂
- :return: None
"""
@app.command('enable', help='维护启用目标制品并更新代际,重启后生效')
@@ -314,7 +302,6 @@ def release_enable(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
get_controller().set_release_enabled(
plugin_id,
@@ -347,7 +334,6 @@ def release_disable(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
get_controller().set_release_enabled(
plugin_id,
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/commands/artifact_maintenance.py b/ruoyi-fastapi-backend/cli/groups/plugin/commands/artifact_maintenance.py
index 33212e86e..4085f1427 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/commands/artifact_maintenance.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/commands/artifact_maintenance.py
@@ -17,7 +17,6 @@ def register_artifact_maintenance_commands(app: typer.Typer, get_controller: Cal
:param app: 制品命令组
:param get_controller: 延迟获取命令控制器的工厂
- :return: None
"""
@app.command('inspect', help='核对存储和索引,列出保护引用、孤儿对象与无效制品')
@@ -34,7 +33,6 @@ def inspect_artifacts(
:param min_age_days: 最短保留天数
:param env: 当前命令环境
:param output: 输出格式
- :return: None
"""
get_controller().maintain_artifacts(
'inspect',
@@ -70,7 +68,6 @@ def prune_artifacts(
:param output: 输出格式
:param allow_prod: 是否允许生产环境变更
:param yes: 是否跳过交互确认
- :return: None
"""
get_controller().maintain_artifacts(
'prune',
@@ -107,7 +104,6 @@ def rotate_signature(
:param output: 输出格式
:param allow_prod: 是否允许生产环境变更
:param yes: 是否跳过交互确认
- :return: None
"""
get_controller().maintain_artifacts(
'rotate-signature',
@@ -138,7 +134,6 @@ def reconcile_artifacts(
:param output: 输出格式
:param allow_prod: 是否允许生产环境变更
:param yes: 是否跳过交互确认
- :return: None
"""
get_controller().maintain_artifacts(
'reconcile',
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/commands/configuration.py b/ruoyi-fastapi-backend/cli/groups/plugin/commands/configuration.py
index 6280a06f1..203102b70 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/commands/configuration.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/commands/configuration.py
@@ -14,7 +14,6 @@ def register_configuration_commands(app: typer.Typer, get_controller: Callable[[
:param app: Typer 命令组
:param get_controller: 插件命令控制器工厂
- :return: None
"""
@app.command('config', help='查看或设置插件配置')
@@ -43,7 +42,6 @@ def config_command(
:param reveal_secret: 是否导出敏感配置明文
:param output_file: 配置导出 JSON 文件路径
:param input_file: 配置导入 JSON 文件路径
- :return: None
"""
get_controller().plugin_config(
plugin_id,
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/commands/dependency.py b/ruoyi-fastapi-backend/cli/groups/plugin/commands/dependency.py
index 174a2430e..e06dc764a 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/commands/dependency.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/commands/dependency.py
@@ -20,7 +20,6 @@ def register_dependency_commands(app: typer.Typer, get_controller: Callable[[],
:param app: Typer 命令组
:param get_controller: 插件命令控制器工厂
- :return: None
"""
@app.command('check-deps', help='检查插件依赖')
@@ -35,7 +34,6 @@ def check_deps_command(
:param plugin_id: 插件ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().check_plugin_dependencies(plugin_id, env, output)
@@ -56,7 +54,6 @@ def precheck_command(
:param plugin_id: 插件ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().precheck_plugin(operation, plugin_id, env, output)
@@ -74,7 +71,6 @@ def plan_command(
:param plugin_ids: 插件ID列表
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().plan_plugins(operation, plugin_ids or [], env, output)
@@ -118,7 +114,6 @@ def install_deps_command( # noqa: PLR0913
:param allowlist: 依赖允许列表路径
:param offline_dir: 离线制品目录
:param require_lockfile: 是否要求锁文件
- :return: None
"""
get_controller().install_plugin_dependencies(
plugin_id,
@@ -162,7 +157,6 @@ def lock_deps_command(
:param output_path: 输出锁文件路径
:param offline_dir: 离线制品目录
:param overwrite: 是否覆盖已有锁文件
- :return: None
"""
get_controller().lock_plugin_dependencies(
plugin_id,
@@ -195,7 +189,6 @@ def allowlist_example_command(
:param dry_run: 是否仅预演
:param output_path: 输出允许列表路径
:param overwrite: 是否覆盖已有允许列表文件
- :return: None
"""
get_controller().generate_plugin_dependency_allowlist_example(
env,
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/commands/developer.py b/ruoyi-fastapi-backend/cli/groups/plugin/commands/developer.py
index 5c4d498b0..fed9c1f97 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/commands/developer.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/commands/developer.py
@@ -14,7 +14,6 @@ def register_developer_commands(app: typer.Typer, get_controller: Callable[[], A
:param app: Typer 命令组
:param get_controller: 插件命令控制器工厂
- :return: None
"""
@app.command('test', help='执行插件测试')
@@ -37,7 +36,6 @@ def test_command(
:param maxfail: 最大失败数
:param quiet: 是否启用简洁输出
:param frontend_build: 是否追加执行前端构建验收
- :return: None
"""
get_controller().test_plugin(
plugin_id,
@@ -95,7 +93,6 @@ def create_command( # noqa: PLR0913
:param no_config: 是否不创建配置项示例
:param no_test: 是否不创建测试样例
:param dry_run: 是否仅预演
- :return: None
"""
get_controller().create_plugin(
plugin_id,
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/commands/discovery.py b/ruoyi-fastapi-backend/cli/groups/plugin/commands/discovery.py
index 1e67e059a..372247e5f 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/commands/discovery.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/commands/discovery.py
@@ -12,7 +12,6 @@ def register_discovery_commands(app: typer.Typer, get_controller: Callable[[], A
:param app: Typer 命令组
:param get_controller: 插件命令控制器工厂
- :return: None
"""
@app.command('list', help='查看本地插件列表')
@@ -25,7 +24,6 @@ def list_command(
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().list_plugins(env, output)
@@ -41,7 +39,6 @@ def info_command(
:param plugin_id: 插件ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().plugin_info(plugin_id, env, output)
@@ -57,7 +54,6 @@ def check_command(
:param plugin_id: 插件ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().check_plugin(plugin_id, env, output)
@@ -73,7 +69,6 @@ def health_command(
:param plugin_id: 插件ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().health_plugin(plugin_id, env, output)
@@ -91,7 +86,6 @@ def diagnose_command(
:param env: 当前命令运行环境
:param output: 输出格式
:param output_file: 诊断包 JSON 导出文件路径
- :return: None
"""
get_controller().diagnose_plugin(plugin_id, env, output, output_file=output_file)
@@ -109,6 +103,5 @@ def docs_command(
:param env: 当前命令运行环境
:param output: 输出格式
:param output_file: Markdown 文档导出文件路径
- :return: None
"""
get_controller().generate_plugin_docs(plugin_id, env, output, output_file=output_file)
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/commands/lifecycle.py b/ruoyi-fastapi-backend/cli/groups/plugin/commands/lifecycle.py
index 176fd7192..422b7ece3 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/commands/lifecycle.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/commands/lifecycle.py
@@ -15,7 +15,6 @@ def register_lifecycle_commands(app: typer.Typer, get_controller: Callable[[], A
:param app: Typer 命令组
:param get_controller: 插件命令控制器工厂
- :return: None
"""
@app.command('batch', help='按拓扑顺序批量执行插件操作')
@@ -40,7 +39,6 @@ def batch_command(
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
:param continue_on_error: 失败后是否继续执行后续插件
- :return: None
"""
get_controller().batch_plugins(
operation,
@@ -71,7 +69,6 @@ def install_command(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
- :return: None
"""
get_controller().install_plugin(
plugin_id,
@@ -100,7 +97,6 @@ def upgrade_command(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
- :return: None
"""
get_controller().upgrade_plugin(
plugin_id,
@@ -129,7 +125,6 @@ def enable_command(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
- :return: None
"""
get_controller().set_plugin_enabled(
plugin_id,
@@ -159,7 +154,6 @@ def disable_command(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
- :return: None
"""
get_controller().set_plugin_enabled(
plugin_id,
@@ -189,7 +183,6 @@ def uninstall_command(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
- :return: None
"""
get_controller().uninstall_plugin(
plugin_id,
@@ -218,7 +211,6 @@ def purge_command(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
- :return: None
"""
get_controller().purge_plugin(
plugin_id,
@@ -243,7 +235,6 @@ def migration_list_command(
:param status: 执行状态
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
get_controller().list_plugin_migrations(plugin_id, status, env, output)
@@ -267,7 +258,6 @@ def mark_success_command(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
get_controller().mark_plugin_migration_success(
plugin_id,
@@ -299,7 +289,6 @@ def mark_failed_command(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
get_controller().mark_plugin_migration_failed(
plugin_id,
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/commands/sdk.py b/ruoyi-fastapi-backend/cli/groups/plugin/commands/sdk.py
index 62f4db83c..b939f3ca9 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/commands/sdk.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/commands/sdk.py
@@ -67,7 +67,6 @@ def _execute_sdk(
:param dry_run: 是否只预演更新
:param force: 是否备份后替换改动过或未跟踪的 SDK
:param frontend_framework: SDK 来源宿主的前端框架标识
- :return: None
"""
try:
frontend_root_resolver = importlib.import_module('plugins.core.frontend').resolve_frontend_root
@@ -100,7 +99,6 @@ def register_sdk_commands(app: typer.Typer) -> None:
注册纯离线 SDK 子命令,帮助查询不加载工程或宿主配置。
:param app: 插件命令组
- :return: None
"""
sdk_app = typer.Typer(help='检查和显式更新独立 bundle 工程中的桥接 SDK', no_args_is_help=True)
app.add_typer(sdk_app, name='sdk')
@@ -119,7 +117,6 @@ def check_sdk(
:param frontend_root: 可选宿主前端工程根目录或包含框架分类的聚合目录
:param output: 输出格式
:param frontend_framework: SDK 来源宿主的前端框架标识
- :return: None
"""
_execute_sdk('check', project, frontend_root, output, frontend_framework=frontend_framework)
@@ -141,7 +138,6 @@ def update_sdk(
:param dry_run: 是否仅预演而不写入文件
:param force: 是否备份后替换改动或未跟踪副本
:param frontend_framework: SDK 来源宿主的前端框架标识
- :return: None
"""
_execute_sdk(
'update',
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/controller.py b/ruoyi-fastapi-backend/cli/groups/plugin/controller.py
index 149933a4e..2e87acbd1 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/controller.py
@@ -31,6 +31,11 @@
class PluginCommandController:
"""
插件命令控制器。
+
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar presenter: 插件命令文本渲染器
+ :ivar _plugin_runtime: 插件运行时服务
"""
def __init__(
@@ -48,7 +53,6 @@ def __init__(
:param execution_service: CLI 执行服务
:param presenter: 插件命令文本渲染器
:param plugin_runtime: 插件运行时服务
- :return: None
"""
self.context_factory = context_factory or DEFAULT_CORE_SERVICES.context_factory
self.execution_service = execution_service or DEFAULT_CORE_SERVICES.execution_service
@@ -81,7 +85,6 @@ def list_plugins(self, env: str, output: str) -> None:
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.core_runtime.list_plugins_with_state())
@@ -109,7 +112,6 @@ def _complete_plugin_payload(
:param text_builder: 文本构造器
:param success_exit_code: 成功退出码
:param failure_exit_code: 失败退出码
- :return: None
"""
payload = PluginCommandPayloadAdapter.adapt(payload)
self.execution_service.complete_payload_with_text(
@@ -152,7 +154,6 @@ def plugin_info(self, plugin_id: str, env: str, output: str) -> None:
:param plugin_id: 插件ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.core_runtime.get_plugin_info_with_state(plugin_id))
@@ -170,7 +171,6 @@ def check_plugin(self, plugin_id: str | None, env: str, output: str) -> None:
:param plugin_id: 插件ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.core_runtime.check_plugin(plugin_id)
@@ -187,7 +187,6 @@ def check_plugin_dependencies(self, plugin_id: str, env: str, output: str) -> No
:param plugin_id: 插件ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.core_runtime.check_plugin_dependencies(plugin_id)
@@ -205,7 +204,6 @@ def precheck_plugin(self, operation: str, plugin_id: str, env: str, output: str)
:param plugin_id: 插件ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.core_runtime.precheck_plugin_operation(plugin_id, operation))
@@ -222,7 +220,6 @@ def health_plugin(self, plugin_id: str, env: str, output: str) -> None:
:param plugin_id: 插件ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.core_runtime.health_plugin(plugin_id))
@@ -240,7 +237,6 @@ def diagnose_plugin(self, plugin_id: str, env: str, output: str, *, output_file:
:param env: 当前命令运行环境
:param output: 输出格式
:param output_file: 诊断包 JSON 导出文件路径
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.plugin_runtime.diagnose_plugin_with_runtime(plugin_id))
@@ -264,7 +260,6 @@ def generate_plugin_docs(self, plugin_id: str, env: str, output: str, *, output_
:param env: 当前命令运行环境
:param output: 输出格式
:param output_file: Markdown 文档导出文件路径
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.core_runtime.generate_plugin_docs(plugin_id)
@@ -302,7 +297,6 @@ def test_plugin(
:param maxfail: 最大失败数
:param quiet: 是否启用简洁输出
:param frontend_build: 是否执行前端构建验收
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.plugin_runtime.test_plugin(
@@ -326,7 +320,6 @@ def plan_plugins(self, operation: str, plugin_ids: list[str], env: str, output:
:param plugin_ids: 插件ID列表
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.core_runtime.plan_plugins(operation, plugin_ids or None)
@@ -359,7 +352,6 @@ def batch_plugins(
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
:param continue_on_error: 失败后是否继续执行后续插件
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -399,7 +391,6 @@ def install_plugin_dependencies(
:param env: 当前命令运行环境
:param output: 输出格式
:param options: 依赖安装命令选项
- :return: None
"""
ctx = self.context_factory.build_regular(
env,
@@ -482,6 +473,12 @@ def _build_dependency_install_output_callback(ctx: object) -> PluginDependencyOu
return None
def output_callback(kind: str, text: str) -> None:
+ """
+ 将依赖安装过程的输出转交给 CLI 展示层。
+
+ :param kind: 当前条目的类别
+ :param text: 待处理的文本
+ """
if text:
typer.echo(text, nl=False, err=kind == 'stderr')
@@ -502,7 +499,6 @@ def lock_plugin_dependencies(
:param env: 当前命令运行环境
:param output: 输出格式
:param options: 依赖锁文件命令选项
- :return: None
"""
ctx = self.context_factory.build_regular(
env,
@@ -538,7 +534,6 @@ def generate_plugin_dependency_allowlist_example(
:param env: 当前命令运行环境
:param output: 输出格式
:param options: 允许列表示例命令选项
- :return: None
"""
ctx = self.context_factory.build_regular(
env,
@@ -636,7 +631,6 @@ def create_plugin(
:param env: 当前命令运行环境
:param output: 输出格式
:param options: 插件创建命令选项
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
if options.backend_only and options.frontend_only:
@@ -690,7 +684,6 @@ def install_plugin(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -727,7 +720,6 @@ def upgrade_plugin(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -766,7 +758,6 @@ def set_plugin_enabled(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
- :return: None
"""
command_name = 'plugin enable' if enabled else 'plugin disable'
ctx = self.context_factory.build_dangerous(
@@ -806,7 +797,6 @@ def uninstall_plugin(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -843,7 +833,6 @@ def purge_plugin(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param dry_run: 是否仅预演
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -869,7 +858,6 @@ def list_plugin_migrations(self, plugin_id: str, status: str | None, env: str, o
:param status: 执行状态
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.core_runtime.list_plugin_migrations(plugin_id, status))
@@ -900,7 +888,6 @@ def mark_plugin_migration_success(
:param note: 人工恢复备注
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -941,7 +928,6 @@ def mark_plugin_migration_failed(
:param note: 人工恢复备注
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -988,7 +974,6 @@ def plugin_config(
:param reveal_secret: 是否导出敏感配置明文
:param output_file: 配置导出 JSON 文件路径
:param input_file: 配置导入 JSON 文件路径
- :return: None
"""
if action == 'get':
self._get_plugin_config(plugin_id, env, output)
@@ -1047,7 +1032,6 @@ def _get_plugin_config(self, plugin_id: str, env: str, output: str) -> None:
:param plugin_id: 插件ID
:param env: 当前命令运行环境
:param output: 输出格式
- :return: None
"""
ctx = self.context_factory.build_readonly(env, output)
payload = self.execution_service.run_async(self.core_runtime.get_plugin_config(plugin_id))
@@ -1078,7 +1062,6 @@ def _export_plugin_config(
:param yes: 是否跳过确认
:param reveal_secret: 是否导出敏感配置明文
:param output_file: 配置导出 JSON 文件路径
- :return: None
"""
ctx = (
self.context_factory.build_dangerous(
@@ -1127,7 +1110,6 @@ def _import_plugin_config(
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
:param input_file: 配置导入 JSON 文件路径
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -1175,7 +1157,6 @@ def _set_plugin_config(
:param output: 输出格式
:param allow_prod: 是否允许生产环境危险命令
:param yes: 是否跳过确认
- :return: None
"""
ctx = self.context_factory.build_dangerous(
env,
@@ -1210,6 +1191,7 @@ def _parse_config_pairs(pairs: list[str]) -> dict[str, str]:
:param pairs: 配置键值参数列表
:return: 配置键值字典
+ :raises ValueError: 配置项未按 key=value 提供
"""
values = {}
for pair in pairs:
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/options.py b/ruoyi-fastapi-backend/cli/groups/plugin/options.py
index acbf71725..3c019ad56 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/options.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/options.py
@@ -9,16 +9,16 @@ class PluginCreateCommandOptions:
"""
插件创建命令选项。
- :param backend_only: 是否只创建后端插件模板
- :param frontend_only: 是否只创建前端插件模板
- :param template: 插件模板名称
- :param frontend_framework: 前端框架标识,auto 表示自动识别;源码模板支持 vue2、vue3、react
- :param no_migration: 是否不创建 migration 示例
- :param no_seed: 是否不创建 seed 示例
- :param no_job: 是否不创建定时任务示例
- :param no_config: 是否不创建配置项示例
- :param no_test: 是否不创建测试样例
- :param dry_run: 是否仅预演
+ :ivar backend_only: 是否只创建后端插件模板
+ :ivar frontend_only: 是否只创建前端插件模板
+ :ivar template: 插件模板名称
+ :ivar frontend_framework: 前端框架标识,auto 表示自动识别;源码模板支持 vue2、vue3、react
+ :ivar no_migration: 是否不创建 migration 示例
+ :ivar no_seed: 是否不创建 seed 示例
+ :ivar no_job: 是否不创建定时任务示例
+ :ivar no_config: 是否不创建配置项示例
+ :ivar no_test: 是否不创建测试样例
+ :ivar dry_run: 是否仅预演
"""
backend_only: bool = False
@@ -38,15 +38,15 @@ class PluginDependencyInstallCommandOptions:
"""
插件依赖安装命令选项。
- :param allow_prod: 是否允许生产环境危险命令
- :param yes: 是否跳过确认
- :param dry_run: 是否仅预演
- :param policy_mode: 临时覆盖策略模式
- :param allow_unlisted: 是否允许未命中 allowlist 的依赖仅告警
- :param lockfile: 锁文件路径
- :param allowlist: 依赖允许列表路径
- :param offline_dir: 离线制品目录
- :param require_lockfile: 是否要求锁文件
+ :ivar allow_prod: 是否允许生产环境危险命令
+ :ivar yes: 是否跳过确认
+ :ivar dry_run: 是否仅预演
+ :ivar policy_mode: 临时覆盖策略模式
+ :ivar allow_unlisted: 是否允许未命中 allowlist 的依赖仅告警
+ :ivar lockfile: 锁文件路径
+ :ivar allowlist: 依赖允许列表路径
+ :ivar offline_dir: 离线制品目录
+ :ivar require_lockfile: 是否要求锁文件
"""
allow_prod: bool = False
@@ -65,10 +65,10 @@ class PluginDependencyLockCommandOptions:
"""
插件依赖锁文件模板命令选项。
- :param output_path: 输出锁文件路径
- :param offline_dir: 离线制品目录
- :param dry_run: 是否仅预演
- :param overwrite: 是否覆盖已有锁文件
+ :ivar output_path: 输出锁文件路径
+ :ivar offline_dir: 离线制品目录
+ :ivar dry_run: 是否仅预演
+ :ivar overwrite: 是否覆盖已有锁文件
"""
output_path: str = ''
@@ -82,9 +82,9 @@ class PluginDependencyAllowlistExampleCommandOptions:
"""
插件依赖允许列表示例命令选项。
- :param output_path: 输出允许列表路径
- :param dry_run: 是否仅预演
- :param overwrite: 是否覆盖已有文件
+ :ivar output_path: 输出允许列表路径
+ :ivar dry_run: 是否仅预演
+ :ivar overwrite: 是否覆盖已有文件
"""
output_path: str = ''
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/payload.py b/ruoyi-fastapi-backend/cli/groups/plugin/payload.py
index 5dd2645a9..03923ba72 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/payload.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/payload.py
@@ -7,7 +7,9 @@ class PluginCommandPayloadAdapter:
插件 CLI 输出负载适配器。
核心运行时 payload 同时服务管理接口和 CLI。CLI 在输出前通过本适配器消除
- `enabled` 的多重语义,不改变管理接口既有契约。
+ ``enabled`` 的多重语义,不改变管理接口既有契约。
+
+ :cvar _LIFECYCLE_OPERATIONS: 由插件生命周期处理器受理的操作名称
"""
_LIFECYCLE_OPERATIONS = {'enable', 'disable', 'uninstall'}
@@ -31,7 +33,6 @@ def _adapt_node(cls, node: object, *, parent_key: str | None = None) -> None:
:param node: 当前负载节点
:param parent_key: 当前节点在父对象中的字段名
- :return: None
"""
if isinstance(node, list):
for item in node:
@@ -59,7 +60,6 @@ def _adapt_database_state(node: dict[str, Any], parent_key: str | None) -> None:
:param node: 当前负载节点
:param parent_key: 当前节点在父对象中的字段名
- :return: None
"""
if parent_key != 'database' or 'enabled' not in node:
return
@@ -72,7 +72,6 @@ def _adapt_lifecycle_target(cls, node: dict[str, Any]) -> None:
将生命周期结果中的目标启停值改为 targetEnabled。
:param node: 当前负载节点
- :return: None
"""
if node.get('operation') == 'purge' and 'enabled' in node:
node.pop('enabled')
@@ -92,7 +91,6 @@ def _adapt_action_state(node: dict[str, Any], parent_key: str | None) -> None:
:param node: 当前负载节点
:param parent_key: 当前节点在父对象中的字段名
- :return: None
"""
is_action = parent_key == 'actions' and 'name' in node
is_purge_plan_item = parent_key == 'items' and 'destructive' in node and 'label' in node
@@ -106,7 +104,6 @@ def _adapt_plan_plugin_state(node: dict[str, Any], parent_key: str | None) -> No
:param node: 当前负载节点
:param parent_key: 当前节点在父对象中的字段名
- :return: None
"""
if parent_key != 'items' or 'pluginId' not in node or 'ready' not in node or 'enabled' not in node:
return
@@ -119,7 +116,6 @@ def _adapt_plugin_runtime_state(node: dict[str, Any]) -> None:
将插件有效启用态改为 runtimeEnabled。
:param node: 当前负载节点
- :return: None
"""
if 'pluginId' not in node or 'status' not in node or 'enabled' not in node or 'dryRun' in node:
return
@@ -136,7 +132,6 @@ def _adapt_manifest_job_state(node: dict[str, Any], parent_key: str | None) -> N
:param node: 当前负载节点
:param parent_key: 当前节点在父对象中的字段名
- :return: None
"""
if parent_key == 'jobs' and 'id' in node and isinstance(node.get('enabled'), bool):
node['defaultEnabled'] = node.pop('enabled')
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/presenter.py b/ruoyi-fastapi-backend/cli/groups/plugin/presenter.py
index 414bf685a..c47363259 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/presenter.py
@@ -2,9 +2,7 @@
class PluginCommandPresenter:
- """
- 插件命令文本渲染器。
- """
+ """插件命令文本渲染器。"""
def build_list_text(self, payload: dict[str, object]) -> str:
"""
@@ -863,7 +861,6 @@ def _append_lifecycle_migration_lines(self, lines: list[str], payload: dict[str,
:param lines: 文本行列表
:param payload: 生命周期负载
- :return: None
"""
migration_recovery = payload.get('migrationRecovery')
if isinstance(migration_recovery, dict):
diff --git a/ruoyi-fastapi-backend/cli/guards.py b/ruoyi-fastapi-backend/cli/guards.py
index 75cc1cbce..a7e91f968 100644
--- a/ruoyi-fastapi-backend/cli/guards.py
+++ b/ruoyi-fastapi-backend/cli/guards.py
@@ -17,9 +17,9 @@ class DangerousCommandRule:
"""
危险命令保护规则。
- :param command_name: 命令唯一标识
- :param risk_level: 风险级别
- :param supports_dry_run: 是否支持演练执行
+ :ivar command_name: 命令唯一标识
+ :ivar risk_level: 风险级别
+ :ivar supports_dry_run: 是否支持演练执行
"""
command_name: str
@@ -35,7 +35,7 @@ class DangerousCommandRuleRegistry:
该注册表负责维护 CLI 内所有危险命令的风险元数据,并提供查询与
强制获取能力,作为上下文工厂、风险元数据与测试的统一入口。
- :param rules: 按命令名索引的危险命令规则表
+ :ivar rules: 按命令名索引的危险命令规则表
"""
rules: dict[str, DangerousCommandRule]
@@ -98,7 +98,7 @@ class DangerousCommandConfirmationService:
该对象负责处理 TTY 检测、确认提示与交互取消异常收口。
- :param result_builder: 危险命令结果构建器
+ :ivar result_builder: 危险命令结果构建器
"""
result_builder: DangerousCommandResultBuilder
@@ -148,9 +148,9 @@ class DangerousCommandGuardService:
该服务负责根据命令规则和 CLI 上下文执行生产环境保护、交互确认
与拒绝结果收口。
- :param rule_registry: 危险命令规则注册表
- :param result_builder: 危险命令结果构建器
- :param confirmation_service: 危险命令确认服务
+ :ivar rule_registry: 危险命令规则注册表
+ :ivar result_builder: 危险命令结果构建器
+ :ivar confirmation_service: 危险命令确认服务
"""
rule_registry: DangerousCommandRuleRegistry
@@ -158,11 +158,7 @@ class DangerousCommandGuardService:
confirmation_service: DangerousCommandConfirmationService = field(init=False)
def __post_init__(self) -> None:
- """
- 初始化危险命令保护服务依赖。
-
- :return: None
- """
+ """初始化危险命令保护服务依赖。"""
self.confirmation_service = DangerousCommandConfirmationService(self.result_builder)
def guard(self, ctx: CliContext, *, rule: DangerousCommandRule) -> CommandResult | None:
diff --git a/ruoyi-fastapi-backend/cli/main.py b/ruoyi-fastapi-backend/cli/main.py
index 6439b9d3f..db7a156b9 100644
--- a/ruoyi-fastapi-backend/cli/main.py
+++ b/ruoyi-fastapi-backend/cli/main.py
@@ -14,11 +14,11 @@ class CliImportArgvScope:
"""
CLI 导入期参数作用域。
- 该对象负责在根应用构建阶段暂时切换 `sys.argv`,只保留导入期
- 需要的最小参数集,避免该过程继续以内联 `try/finally` 形式散落
+ 该对象负责在根应用构建阶段暂时切换 ``sys.argv``,只保留导入期
+ 需要的最小参数集,避免该过程继续以内联 ``try/finally`` 形式散落
在入口运行器中。
- :param project_runtime_locator: CLI 项目运行时定位器
+ :ivar project_runtime_locator: CLI 项目运行时定位器
"""
project_runtime_locator: ProjectRuntimeLocator
@@ -44,12 +44,13 @@ class CliMainRunner:
CLI 根入口运行器。
该运行器负责串联项目目录定位、导入期参数裁剪、根应用构建、
- completion 分发与 Typer 应用启动,避免 `main.py` 继续停留在
+ completion 分发与 Typer 应用启动,避免 ``main.py`` 继续停留在
模块级散乱编排状态。
- :param project_runtime_locator: CLI 项目运行时定位器
- :param completion_dispatcher: shell completion 分发器
- :param application_builder: 根应用构建器
+ :ivar project_runtime_locator: CLI 项目运行时定位器
+ :ivar completion_dispatcher: shell completion 分发器
+ :ivar application_builder: 根应用构建器
+ :ivar import_argv_scope: CLI 导入期参数作用域
"""
project_runtime_locator: ProjectRuntimeLocator
@@ -67,11 +68,7 @@ def build_cli(self) -> object:
return self.import_argv_scope.run(self.application_builder.build)
def run(self) -> None:
- """
- 执行 Typer CLI 根应用。
-
- :return: None
- """
+ """执行 Typer CLI 根应用。"""
cli = self.build_cli()
self.completion_dispatcher.dispatch(cli)
cli(prog_name='ruoyi')
@@ -88,11 +85,7 @@ def run(self) -> None:
def main() -> None:
- """
- 执行 CLI 根入口运行器。
-
- :return: None
- """
+ """执行 CLI 根入口运行器。"""
CLI_MAIN_RUNNER.run()
diff --git a/ruoyi-fastapi-backend/cli/metadata/command_specs.py b/ruoyi-fastapi-backend/cli/metadata/command_specs.py
index 1b5718945..22f127bb1 100644
--- a/ruoyi-fastapi-backend/cli/metadata/command_specs.py
+++ b/ruoyi-fastapi-backend/cli/metadata/command_specs.py
@@ -7,13 +7,13 @@ class CompletionShellSpec:
"""
Shell completion 元数据定义。
- name: shell 名称
- description: shell 描述文本
- generator: 脚本生成方式
- default_target: 默认脚本落盘路径,相对于用户 home 目录
- default_rc_file: 默认 rc 文件路径,相对于用户 home 目录
- auto_discovery: 是否会被 shell 自动发现
- supported: 当前版本是否已支持
+ :ivar name: shell 名称
+ :ivar description: shell 描述文本
+ :ivar generator: 脚本生成方式
+ :ivar default_target: 默认脚本落盘路径,相对于用户 home 目录
+ :ivar default_rc_file: 默认 rc 文件路径,相对于用户 home 目录
+ :ivar auto_discovery: 是否会被 shell 自动发现
+ :ivar supported: 当前版本是否已支持
"""
name: str
@@ -33,7 +33,7 @@ class CompletionShellSpecRegistry:
该注册表集中维护 CLI 当前支持的 shell completion 元数据,
供 installer、doctor 和 provider 等场景统一查询。
- :param specs: 按 shell 名称索引的元数据表
+ :ivar specs: 按 shell 名称索引的元数据表
"""
specs: dict[str, CompletionShellSpec]
diff --git a/ruoyi-fastapi-backend/cli/metadata/option_specs.py b/ruoyi-fastapi-backend/cli/metadata/option_specs.py
index 557e9868c..70356143a 100644
--- a/ruoyi-fastapi-backend/cli/metadata/option_specs.py
+++ b/ruoyi-fastapi-backend/cli/metadata/option_specs.py
@@ -12,7 +12,7 @@ class EnvironmentOptionService:
该服务负责发现当前项目下可用的环境名称集合,供 completion、
wizard 和诊断信息等场景复用。
- :param default_environments: 默认内置环境名称列表
+ :ivar default_environments: 默认内置环境名称列表
"""
default_environments: tuple[str, ...] = DEFAULT_ENVIRONMENTS
diff --git a/ruoyi-fastapi-backend/cli/metadata/risk_specs.py b/ruoyi-fastapi-backend/cli/metadata/risk_specs.py
index d00930415..caa49e0b5 100644
--- a/ruoyi-fastapi-backend/cli/metadata/risk_specs.py
+++ b/ruoyi-fastapi-backend/cli/metadata/risk_specs.py
@@ -11,9 +11,9 @@ class CommandRiskSpec:
"""
CLI 命令风险元数据定义。
- :param command_name: 命令唯一标识
- :param risk_level: 风险级别
- :param supports_dry_run: 是否支持演练执行
+ :ivar command_name: 命令唯一标识
+ :ivar risk_level: 风险级别
+ :ivar supports_dry_run: 是否支持演练执行
"""
command_name: str
@@ -29,7 +29,7 @@ class CommandRiskSpecRegistry:
该注册表负责从危险命令规则注册表派生风险元数据,供 TUI、文档、
诊断提示等只读场景统一查询。
- :param specs: 按命令名索引的风险元数据表
+ :ivar specs: 按命令名索引的风险元数据表
"""
specs: dict[str, CommandRiskSpec]
diff --git a/ruoyi-fastapi-backend/cli/output.py b/ruoyi-fastapi-backend/cli/output.py
index 121ff17d0..e5496ea4f 100644
--- a/ruoyi-fastapi-backend/cli/output.py
+++ b/ruoyi-fastapi-backend/cli/output.py
@@ -15,8 +15,8 @@ class OutputSettings:
"""
输出渲染配置。
- :param color_mode: 颜色模式
- :param icon_mode: 图标模式
+ :ivar color_mode: 颜色模式
+ :ivar icon_mode: 图标模式
"""
color_mode: str = 'always'
@@ -28,10 +28,10 @@ class StatusTokenDefinition:
"""
状态标签定义。
- :param emoji: emoji 模式文案
- :param ascii: ASCII 模式文案
- :param none: 无图标模式文案
- :param color: 默认前景色
+ :ivar emoji: emoji 模式文案
+ :ivar ascii: ASCII 模式文案
+ :ivar none: 无图标模式文案
+ :ivar color: 默认前景色
"""
emoji: str
@@ -45,9 +45,9 @@ class CommandResult:
"""
统一命令执行结果。
- :param data: 命令结果负载
- :param exit_code: 命令退出码
- :param already_printed: 是否已由上层提前输出
+ :ivar data: 命令结果负载
+ :ivar exit_code: 命令退出码
+ :ivar already_printed: 是否已由上层提前输出
"""
data: Any = None
@@ -59,7 +59,9 @@ class OutputStatusStyler:
"""
统一负责状态标签与单行文本样式。
- :param settings: 输出配置
+ :cvar _STATUS_DEFINITIONS: 渲染状态标签使用的定义
+ :cvar _STATUS_FIELD_KIND_MAPPING: 将结果字段映射到状态样式的规则
+ :ivar settings: 输出配置
"""
_STATUS_DEFINITIONS = {
@@ -83,7 +85,6 @@ def __init__(self, settings: OutputSettings) -> None:
初始化状态样式器。
:param settings: 输出配置
- :return: None
"""
self.settings = settings
@@ -310,7 +311,8 @@ class StructuredTextRenderer:
"""
负责结构化数据到文本的转换与装饰。
- :param status_styler: 状态样式器
+ :cvar _SNAKE_CASE_BOUNDARY_PATTERN: 用于拆分下划线风格字段名的正则表达式
+ :ivar status_styler: 状态样式器
"""
_SNAKE_CASE_BOUNDARY_PATTERN = re.compile(r'(? None:
初始化结构化文本渲染器。
:param status_styler: 状态样式器
- :return: None
"""
self.status_styler = status_styler
@@ -390,7 +391,7 @@ def format_scalar(value: Any) -> str:
@classmethod
def format_field_name(cls, key: object) -> str:
"""
- 将字段名标准化为文本输出使用的 `snake_case` 形式。
+ 将字段名标准化为文本输出使用的 ``snake_case`` 形式。
:param key: 原始字段名
:return: 标准化后的字段名
@@ -409,7 +410,6 @@ def append_multiline_text(self, lines: list[str], prefix: str, value: str, inden
:param prefix: 当前字段前缀
:param value: 多行文本内容
:param indent: 子级缩进
- :return: None
"""
lines.append(f'{prefix} |')
lines.extend(f'{indent}{line}' for line in value.splitlines())
@@ -504,8 +504,8 @@ class OutputEmitter:
"""
负责标准输出、标准错误与命令退出收口。
- :param text_renderer: 结构化文本渲染器
- :param status_styler: 状态样式器
+ :ivar text_renderer: 结构化文本渲染器
+ :ivar status_styler: 状态样式器
"""
def __init__(self, text_renderer: StructuredTextRenderer, status_styler: OutputStatusStyler) -> None:
@@ -514,7 +514,6 @@ def __init__(self, text_renderer: StructuredTextRenderer, status_styler: OutputS
:param text_renderer: 结构化文本渲染器
:param status_styler: 状态样式器
- :return: None
"""
self.text_renderer = text_renderer
self.status_styler = status_styler
@@ -525,7 +524,6 @@ def emit_output(self, data: Any, output_format: str) -> None:
:param data: 输出数据
:param output_format: 输出格式
- :return: None
"""
if data is None:
return
@@ -542,7 +540,6 @@ def emit_error(self, message: str, output_format: str, *, exit_code: int) -> Non
:param message: 错误消息
:param output_format: 输出格式
:param exit_code: 退出码
- :return: None
"""
if output_format == 'json':
print(
@@ -558,7 +555,6 @@ def complete_command(self, result: CommandResult, ctx: CliContext) -> None:
:param result: 命令执行结果
:param ctx: CLI 上下文
- :return: None
:raises typer.Exit: 始终通过 Typer 退出并返回对应退出码
"""
if not result.already_printed:
@@ -570,6 +566,10 @@ class OutputRenderer:
"""
CLI 输出渲染门面。
+ :ivar settings: 输出配置
+ :ivar status_styler: 状态样式器
+ :ivar text_renderer: 结构化文本渲染器
+ :ivar emitter: 负责将渲染结果写入目标输出的对象
:param color_mode: 颜色模式
:param icon_mode: 图标模式
"""
@@ -578,9 +578,8 @@ def __init__(self, *, color_mode: str = 'always', icon_mode: str = 'emoji') -> N
"""
初始化输出渲染器。
- :param color_mode: 颜色模式,支持 `auto`、`always`、`never`
- :param icon_mode: 图标模式,支持 `emoji`、`ascii`、`none`
- :return: None
+ :param color_mode: 颜色模式,支持 ``auto``、``always``、``never``
+ :param icon_mode: 图标模式,支持 ``emoji``、``ascii``、``none``
"""
self.settings = OutputSettings(color_mode=color_mode, icon_mode=icon_mode)
self.status_styler = OutputStatusStyler(self.settings)
@@ -610,7 +609,6 @@ def set_color_mode(self, color_mode: str) -> None:
设置颜色模式。
:param color_mode: 颜色模式
- :return: None
"""
self.settings.color_mode = color_mode
@@ -619,7 +617,6 @@ def set_icon_mode(self, icon_mode: str) -> None:
设置图标模式。
:param icon_mode: 图标模式
- :return: None
"""
self.settings.icon_mode = icon_mode
@@ -770,7 +767,7 @@ def format_scalar(value: Any) -> str:
@staticmethod
def format_field_name(key: object) -> str:
"""
- 将字段名标准化为文本输出使用的 `snake_case` 形式。
+ 将字段名标准化为文本输出使用的 ``snake_case`` 形式。
:param key: 原始字段名
:return: 标准化后的字段名
@@ -785,7 +782,6 @@ def append_multiline_text(self, lines: list[str], prefix: str, value: str, inden
:param prefix: 当前字段前缀
:param value: 多行文本内容
:param indent: 子级缩进
- :return: None
"""
self.text_renderer.append_multiline_text(lines, prefix, value, indent)
@@ -836,7 +832,6 @@ def emit_output(self, data: Any, output_format: str) -> None:
:param data: 输出数据
:param output_format: 输出格式
- :return: None
"""
self.emitter.emit_output(data, output_format)
@@ -858,7 +853,6 @@ def emit_error(self, message: str, output_format: str, *, exit_code: int) -> Non
:param message: 错误消息
:param output_format: 输出格式
:param exit_code: 退出码
- :return: None
"""
self.emitter.emit_error(message, output_format, exit_code=exit_code)
@@ -868,6 +862,5 @@ def complete_command(self, result: CommandResult, ctx: CliContext) -> None:
:param result: 命令执行结果
:param ctx: CLI 上下文
- :return: None
"""
self.emitter.complete_command(result, ctx)
diff --git a/ruoyi-fastapi-backend/cli/runtime/app/service.py b/ruoyi-fastapi-backend/cli/runtime/app/service.py
index a26a03fdb..69fd0d2ea 100644
--- a/ruoyi-fastapi-backend/cli/runtime/app/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/app/service.py
@@ -16,9 +16,9 @@ class AppRuntimeService:
该服务作为应用运行时 facade,对外统一暴露应用实例构建、
应用配置快照与环境信息快照入口。
- :param runtime_environment: 运行时环境服务
- :param infrastructure_gateway: 应用基础设施网关
- :param snapshot_support: 应用快照支持对象
+ :ivar runtime_environment: 运行时环境服务
+ :ivar infrastructure_gateway: 应用基础设施网关
+ :ivar snapshot_support: 应用快照支持对象
"""
def __init__(
@@ -34,7 +34,6 @@ def __init__(
:param runtime_environment: 运行时环境服务
:param infrastructure_gateway: 应用基础设施网关
:param snapshot_support: 应用快照支持对象
- :return: None
"""
self.runtime_environment = runtime_environment or RUNTIME_ENVIRONMENT
self.infrastructure_gateway = infrastructure_gateway or AppInfrastructureGateway()
diff --git a/ruoyi-fastapi-backend/cli/runtime/app/support.py b/ruoyi-fastapi-backend/cli/runtime/app/support.py
index 3af2563d4..0b1660e25 100644
--- a/ruoyi-fastapi-backend/cli/runtime/app/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/app/support.py
@@ -15,8 +15,8 @@ class AppSnapshotSupport:
该对象负责应用配置快照和环境快照的构建,
避免主运行时服务继续承载快照字段拼装细节。
- :param infrastructure_gateway: 应用基础设施网关
- :param runtime_environment: 运行时环境服务
+ :ivar infrastructure_gateway: 应用基础设施网关
+ :ivar runtime_environment: 运行时环境服务
"""
def __init__(
@@ -29,7 +29,6 @@ def __init__(
:param infrastructure_gateway: 应用基础设施网关
:param runtime_environment: 运行时环境服务
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway
self.runtime_environment = runtime_environment
diff --git a/ruoyi-fastapi-backend/cli/runtime/base.py b/ruoyi-fastapi-backend/cli/runtime/base.py
index 36610e3a9..5c80deaf8 100644
--- a/ruoyi-fastapi-backend/cli/runtime/base.py
+++ b/ruoyi-fastapi-backend/cli/runtime/base.py
@@ -52,7 +52,7 @@ class RuntimeOperatorService:
CLI 运行时操作者解析服务。
该服务集中提供当前 CLI 进程的操作者名称解析能力,
- 避免各领域运行时对象继续复制相同的 `getpass.getuser()` 回退逻辑。
+ 避免各领域运行时对象继续复制相同的 ``getpass.getuser()`` 回退逻辑。
"""
@staticmethod
diff --git a/ruoyi-fastapi-backend/cli/runtime/cache/service.py b/ruoyi-fastapi-backend/cli/runtime/cache/service.py
index b6a9cf704..68c9c97be 100644
--- a/ruoyi-fastapi-backend/cli/runtime/cache/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/cache/service.py
@@ -13,9 +13,9 @@ class CacheRuntimeService:
该服务作为缓存运行时 facade,对外统一暴露缓存统计、键列表、键值、
TTL 读取,以及缓存清理和预热入口。
- :param infrastructure_gateway: 缓存基础设施网关
- :param domain_support: 缓存领域支持对象
- :param redis_support: 缓存 Redis 访问支持对象
+ :ivar infrastructure_gateway: 缓存基础设施网关
+ :ivar domain_support: 缓存领域支持对象
+ :ivar redis_support: 缓存 Redis 访问支持对象
"""
def __init__(
@@ -31,7 +31,6 @@ def __init__(
:param infrastructure_gateway: 缓存基础设施网关
:param domain_support: 缓存领域支持对象
:param redis_support: 缓存 Redis 访问支持对象
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway or CacheInfrastructureGateway()
self.domain_support = domain_support or CacheDomainSupport(self.infrastructure_gateway)
diff --git a/ruoyi-fastapi-backend/cli/runtime/cache/support.py b/ruoyi-fastapi-backend/cli/runtime/cache/support.py
index 72db4df20..4d01eb8ce 100644
--- a/ruoyi-fastapi-backend/cli/runtime/cache/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/cache/support.py
@@ -13,7 +13,7 @@ class CacheDomainSupport:
该对象负责缓存名称列表构建、键范围解析和 TTL 结果判定等
局部缓存规则,避免主运行时服务继续承载细碎领域判断。
- :param infrastructure_gateway: 缓存基础设施网关
+ :ivar infrastructure_gateway: 缓存基础设施网关
"""
def __init__(self, infrastructure_gateway: CacheInfrastructureGateway) -> None:
@@ -21,7 +21,6 @@ def __init__(self, infrastructure_gateway: CacheInfrastructureGateway) -> None:
初始化缓存领域支持对象。
:param infrastructure_gateway: 缓存基础设施网关
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway
@@ -119,8 +118,8 @@ class CacheRedisSupport:
该对象负责 Redis 连接生命周期、错误结果规整和缓存键模式拼装,
避免主运行时服务继续承载基础设施桥接细节。
- :param infrastructure_gateway: 缓存基础设施网关
- :param domain_support: 缓存领域支持对象
+ :ivar infrastructure_gateway: 缓存基础设施网关
+ :ivar domain_support: 缓存领域支持对象
"""
def __init__(
@@ -133,7 +132,6 @@ def __init__(
:param infrastructure_gateway: 缓存基础设施网关
:param domain_support: 缓存领域支持对象
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway
self.domain_support = domain_support
@@ -143,7 +141,7 @@ async def redis_session(self) -> Any:
"""
创建并托管 Redis 会话。
- :return: `(redis, redis_util)` 元组
+ :yield: ``(redis, redis_util)`` 元组
"""
redis = None
redis_util = self.infrastructure_gateway.get_redis_util()
@@ -192,7 +190,7 @@ def build_clear_target_pattern(
:param cache_name: 缓存名称
:param cache_key: 缓存键名片段
:param clear_all: 是否清理全部缓存
- :return: Redis 键匹配模式;全部清理时返回 `None`
+ :return: Redis 键匹配模式;全部清理时返回 ``None``
"""
if clear_all:
return None
diff --git a/ruoyi-fastapi-backend/cli/runtime/config/service.py b/ruoyi-fastapi-backend/cli/runtime/config/service.py
index af5331a83..699793935 100644
--- a/ruoyi-fastapi-backend/cli/runtime/config/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/config/service.py
@@ -13,8 +13,8 @@ class ConfigRuntimeService:
该服务作为参数配置运行时 facade,对外统一暴露参数配置列表、详情、
写入、缓存刷新与一致性诊断入口。
- :param infrastructure_gateway: 参数配置基础设施网关
- :param domain_support: 参数配置领域支持对象
+ :ivar infrastructure_gateway: 参数配置基础设施网关
+ :ivar domain_support: 参数配置领域支持对象
"""
def __init__(
@@ -28,7 +28,6 @@ def __init__(
:param infrastructure_gateway: 参数配置基础设施网关
:param domain_support: 参数配置领域支持对象
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway or ConfigInfrastructureGateway()
self.domain_support = domain_support or ConfigDomainSupport(self.infrastructure_gateway)
@@ -38,7 +37,7 @@ def build_cli_config_model(config_vo_module: Any, config_record: Any) -> Any | N
"""
将 ORM 配置记录显式转换为 CLI 可用的配置模型。
- `ConfigModel` 当前未统一开启 `populate_by_name`,因此 CLI 侧在处理
+ ``ConfigModel`` 当前未统一开启 ``populate_by_name``,因此 CLI 侧在处理
ORM 蛇形字段对象时,需要主动映射为驼峰 alias 输入,避免详情查询结果
被静默序列化为空。
diff --git a/ruoyi-fastapi-backend/cli/runtime/config/support.py b/ruoyi-fastapi-backend/cli/runtime/config/support.py
index d9ffae7c1..88ef781ec 100644
--- a/ruoyi-fastapi-backend/cli/runtime/config/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/config/support.py
@@ -14,7 +14,8 @@ class ConfigDomainSupport:
该对象负责操作者解析、配置脱敏、序列化、查询模型构建与缺失结果构建,
避免主运行时服务继续承载大量领域规则。
- :param infrastructure_gateway: 参数配置基础设施网关
+ :ivar infrastructure_gateway: 参数配置基础设施网关
+ :ivar operator_service: 运行时操作者解析服务
"""
def __init__(
@@ -27,7 +28,6 @@ def __init__(
:param infrastructure_gateway: 参数配置基础设施网关
:param operator_service: 运行时操作者解析服务
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway
self.operator_service = operator_service
diff --git a/ruoyi-fastapi-backend/cli/runtime/crypto/service.py b/ruoyi-fastapi-backend/cli/runtime/crypto/service.py
index 0760920b3..a85e2aae6 100644
--- a/ruoyi-fastapi-backend/cli/runtime/crypto/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/crypto/service.py
@@ -13,9 +13,9 @@ class CryptoRuntimeService:
该服务作为传输加密运行时 facade,对外统一暴露配置校验、
公钥导出、密钥生成和轮换辅助方案构建入口。
- :param infrastructure_gateway: 传输加密基础设施网关
- :param domain_support: 传输加密领域支持对象
- :param result_support: 传输加密结果支持对象
+ :ivar infrastructure_gateway: 传输加密基础设施网关
+ :ivar domain_support: 传输加密领域支持对象
+ :ivar result_support: 传输加密结果支持对象
"""
def __init__(
@@ -31,7 +31,6 @@ def __init__(
:param infrastructure_gateway: 传输加密基础设施网关
:param domain_support: 传输加密领域支持对象
:param result_support: 传输加密结果支持对象
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway or CryptoInfrastructureGateway()
self.domain_support = domain_support or CryptoDomainSupport(self.infrastructure_gateway)
@@ -47,6 +46,11 @@ def generate_crypto_key_pair(self, kid: str, key_size: int) -> dict[str, Any]:
"""
def _operation() -> dict[str, Any]:
+ """
+ 按指定密钥长度生成传输加密密钥对。
+
+ :return: 包含 ``ok``、``message``、``kid``、``keySize``、``privateKey`` 等字段的数据
+ """
self.domain_support.validate_rsa_key_size(key_size)
private_key_pem, public_key_pem = self.domain_support.generate_rsa_key_pair(key_size)
return {
@@ -70,6 +74,11 @@ def validate_crypto_config(self) -> dict[str, Any]:
transport_key_provider = self.infrastructure_gateway.get_transport_key_provider()
def _operation() -> dict[str, Any]:
+ """
+ 校验运行时传输加密配置并返回检查结果。
+
+ :return: 检查结果
+ """
transport_key_provider.validate_runtime_configuration()
return {'ok': True, 'message': '传输加密配置校验通过'}
@@ -85,6 +94,11 @@ def export_public_key(self) -> dict[str, Any]:
transport_crypto_util = self.infrastructure_gateway.get_transport_crypto_util()
def _operation() -> dict[str, Any]:
+ """
+ 校验当前密钥配置并导出客户端使用的公钥。
+
+ :return: 包含 ``ok``、``publicKey`` 的数据
+ """
transport_key_provider.validate_runtime_configuration()
return {'ok': True, 'publicKey': transport_crypto_util.build_public_key_payload()}
@@ -101,6 +115,12 @@ def build_rotation_payload(self, next_kid: str, key_size: int) -> dict[str, Any]
transport_key_provider = self.infrastructure_gateway.get_transport_key_provider()
def _operation() -> dict[str, Any]:
+ """
+ 根据当前密钥和下一代密钥构建轮换配置。
+
+ :raises ValueError: 新密钥版本不能与当前版本相同
+ :return: 包含 ``ok``、``message``、``currentKid``、``nextKid``、``keySize`` 等字段的数据
+ """
self.domain_support.validate_rsa_key_size(key_size)
transport_key_provider.validate_runtime_configuration()
current_key_pair = transport_key_provider.get_current_key_pair()
diff --git a/ruoyi-fastapi-backend/cli/runtime/crypto/support.py b/ruoyi-fastapi-backend/cli/runtime/crypto/support.py
index 73f2e8104..6ba101e22 100644
--- a/ruoyi-fastapi-backend/cli/runtime/crypto/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/crypto/support.py
@@ -17,7 +17,7 @@ class CryptoDomainSupport:
该对象负责 RSA 密钥规则校验、密钥对生成和历史密钥规整,
避免主运行时服务继续承载局部安全规则和数据拼装细节。
- :param infrastructure_gateway: 传输加密基础设施网关
+ :ivar infrastructure_gateway: 传输加密基础设施网关
"""
def __init__(self, infrastructure_gateway: CryptoInfrastructureGateway) -> None:
@@ -25,7 +25,6 @@ def __init__(self, infrastructure_gateway: CryptoInfrastructureGateway) -> None:
初始化传输加密领域支持对象。
:param infrastructure_gateway: 传输加密基础设施网关
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway
@@ -35,7 +34,6 @@ def validate_rsa_key_size(key_size: int) -> None:
校验 RSA 密钥长度是否合法。
:param key_size: RSA 密钥长度
- :return: None
:raises ValueError: 密钥长度不满足约束时抛出异常
"""
if key_size < MIN_RSA_KEY_SIZE or key_size % RSA_KEY_SIZE_STEP != 0:
diff --git a/ruoyi-fastapi-backend/cli/runtime/db/gateway.py b/ruoyi-fastapi-backend/cli/runtime/db/gateway.py
index 20798e4ff..2e11bed6c 100644
--- a/ruoyi-fastapi-backend/cli/runtime/db/gateway.py
+++ b/ruoyi-fastapi-backend/cli/runtime/db/gateway.py
@@ -31,9 +31,9 @@ def get_sync_db_engine_factory() -> Any:
@staticmethod
def get_sqlalchemy_text() -> Any:
"""
- 获取 SQLAlchemy `text` 构造函数。
+ 获取 SQLAlchemy ``text`` 构造函数。
- :return: SQLAlchemy `text` 函数
+ :return: SQLAlchemy ``text`` 函数
"""
return import_module('sqlalchemy').text
diff --git a/ruoyi-fastapi-backend/cli/runtime/db/service.py b/ruoyi-fastapi-backend/cli/runtime/db/service.py
index 2e015ca18..97032a687 100644
--- a/ruoyi-fastapi-backend/cli/runtime/db/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/db/service.py
@@ -14,10 +14,10 @@ class DatabaseRuntimeService:
该服务作为数据库运行时 facade,对外统一暴露数据库连通性检查、
Alembic 版本读取与迁移命令执行入口。
- :param runtime_environment: 运行时环境服务
- :param infrastructure_gateway: 数据库基础设施网关
- :param revision_support: 数据库迁移版本支持对象
- :param alembic_command_support: 数据库 Alembic 命令支持对象
+ :ivar runtime_environment: 运行时环境服务
+ :ivar infrastructure_gateway: 数据库基础设施网关
+ :ivar revision_support: 数据库迁移版本支持对象
+ :ivar alembic_command_support: 数据库 Alembic 命令支持对象
"""
def __init__(
@@ -35,7 +35,6 @@ def __init__(
:param infrastructure_gateway: 数据库基础设施网关
:param revision_support: 数据库迁移版本支持对象
:param alembic_command_support: 数据库 Alembic 命令支持对象
- :return: None
"""
self.runtime_environment = runtime_environment or RUNTIME_ENVIRONMENT
self.infrastructure_gateway = infrastructure_gateway or DatabaseInfrastructureGateway()
@@ -110,7 +109,7 @@ def upgrade_database(self, revision: str = 'head', *, dry_run: bool = False) ->
"""
执行数据库迁移升级。
- :param revision: 目标迁移版本,默认为 `head`
+ :param revision: 目标迁移版本,默认为 ``head``
:param dry_run: 是否仅演练执行
:return: 数据库迁移执行结果
"""
@@ -141,7 +140,7 @@ def downgrade_database(self, revision: str = '-1', *, dry_run: bool = False) ->
"""
执行数据库回退。
- :param revision: 目标回退版本,默认为 `-1`
+ :param revision: 目标回退版本,默认为 ``-1``
:param dry_run: 是否仅演练执行
:return: 数据库回退结果
"""
diff --git a/ruoyi-fastapi-backend/cli/runtime/db/support.py b/ruoyi-fastapi-backend/cli/runtime/db/support.py
index d95014ea9..f349c7dfb 100644
--- a/ruoyi-fastapi-backend/cli/runtime/db/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/db/support.py
@@ -17,8 +17,8 @@ class DatabaseRevisionSupport:
该对象负责 Alembic script directory 构建、修订版本规整和
版本对象序列化,避免主运行时服务继续承载迁移元数据细节。
- :param infrastructure_gateway: 数据库基础设施网关
- :param runtime_environment: 运行时环境服务
+ :ivar infrastructure_gateway: 数据库基础设施网关
+ :ivar runtime_environment: 运行时环境服务
"""
def __init__(
@@ -31,7 +31,6 @@ def __init__(
:param infrastructure_gateway: 数据库基础设施网关
:param runtime_environment: 运行时环境服务
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway
self.runtime_environment = runtime_environment
@@ -85,7 +84,7 @@ class DatabaseAlembicCommandSupport:
该对象负责 Alembic 命令组装与子进程执行,
避免主运行时服务继续承载命令行桥接细节。
- :param runtime_environment: 运行时环境服务
+ :ivar runtime_environment: 运行时环境服务
"""
def __init__(self, runtime_environment: RuntimeEnvironmentService) -> None:
@@ -93,7 +92,6 @@ def __init__(self, runtime_environment: RuntimeEnvironmentService) -> None:
初始化数据库 Alembic 命令支持对象。
:param runtime_environment: 运行时环境服务
- :return: None
"""
self.runtime_environment = runtime_environment
diff --git a/ruoyi-fastapi-backend/cli/runtime/dev/gateway.py b/ruoyi-fastapi-backend/cli/runtime/dev/gateway.py
index 7ea2c11f9..2289ce831 100644
--- a/ruoyi-fastapi-backend/cli/runtime/dev/gateway.py
+++ b/ruoyi-fastapi-backend/cli/runtime/dev/gateway.py
@@ -1,3 +1,4 @@
+import os
import subprocess
from typing import Any
@@ -10,9 +11,9 @@ class DevelopmentProcessGateway:
开发子进程执行网关。
该对象负责统一执行开发工具子进程命令,
- 避免支持对象直接依赖 `subprocess` 细节。
+ 避免支持对象直接依赖 ``subprocess`` 细节。
- :param runtime_environment: 运行时环境服务
+ :ivar runtime_environment: 运行时环境服务
"""
def __init__(self, runtime_environment: RuntimeEnvironmentService) -> None:
@@ -20,7 +21,6 @@ def __init__(self, runtime_environment: RuntimeEnvironmentService) -> None:
初始化开发子进程执行网关。
:param runtime_environment: 运行时环境服务
- :return: None
"""
self.runtime_environment = runtime_environment
@@ -36,7 +36,8 @@ def run_command(self, command: list[str]) -> dict[str, Any]:
command,
cwd=self.runtime_environment.get_backend_dir(),
capture_output=True,
- text=True,
+ encoding='utf-8',
+ env={**os.environ, 'PYTHONIOENCODING': 'utf-8'},
check=False,
)
except Exception as exc:
diff --git a/ruoyi-fastapi-backend/cli/runtime/dev/service.py b/ruoyi-fastapi-backend/cli/runtime/dev/service.py
index 5812c75f5..17dd03b7e 100644
--- a/ruoyi-fastapi-backend/cli/runtime/dev/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/dev/service.py
@@ -14,10 +14,10 @@ class DevelopmentRuntimeService:
该服务作为开发运行时 facade,对外统一暴露 lint/format 和 pytest
执行入口。
- :param runtime_environment: 运行时环境服务
- :param tooling_support: 开发工具支持对象
- :param command_support: 开发命令构建支持对象
- :param process_gateway: 开发子进程执行网关
+ :ivar runtime_environment: 运行时环境服务
+ :ivar tooling_support: 开发工具支持对象
+ :ivar command_support: 开发命令构建支持对象
+ :ivar process_gateway: 开发子进程执行网关
"""
def __init__(
@@ -35,7 +35,6 @@ def __init__(
:param tooling_support: 开发工具支持对象
:param command_support: 开发命令构建支持对象
:param process_gateway: 开发子进程执行网关
- :return: None
"""
self.runtime_environment = runtime_environment or RUNTIME_ENVIRONMENT
self.tooling_support = tooling_support or DevelopmentToolingSupport()
@@ -55,7 +54,7 @@ def run_lint(
:param targets: 目标路径列表
:param check_only: 是否仅检查不写回
- :param fix: 是否允许 `ruff check --fix`
+ :param fix: 是否允许 ``ruff check --fix``
:param unsafe_fixes: 是否允许不安全修复
:return: lint 执行结果
"""
@@ -88,16 +87,23 @@ def run_lint(
'exit_code': RUNTIME_ERROR,
}
- return {
- 'ok': True,
- 'message': '开发检查已完成',
+ docstrings = self.process_gateway.run_command(
+ [self.runtime_environment.get_python_executable(), 'scripts/check_docstrings.py', *normalized_targets]
+ )
+ payload = {
+ 'ok': docstrings['ok'],
+ 'message': '开发检查已完成' if docstrings['ok'] else '文档规范检查失败',
'targets': normalized_targets,
'checkOnly': check_only,
'fix': fix and not check_only,
'unsafeFixes': unsafe_fixes and fix and not check_only,
'format': format_result,
'check': check_result,
+ 'docstrings': docstrings,
}
+ if not docstrings['ok']:
+ payload['exit_code'] = RUNTIME_ERROR
+ return payload
def run_tests(
self,
@@ -111,7 +117,7 @@ def run_tests(
执行项目测试。
:param targets: 目标测试路径列表
- :param keyword: pytest `-k` 过滤表达式
+ :param keyword: pytest ``-k`` 过滤表达式
:param maxfail: 最大失败数,0 表示不限制
:param quiet: 是否启用简洁输出
:return: 测试执行结果
diff --git a/ruoyi-fastapi-backend/cli/runtime/dev/support.py b/ruoyi-fastapi-backend/cli/runtime/dev/support.py
index 4f37d2b98..ff107d311 100644
--- a/ruoyi-fastapi-backend/cli/runtime/dev/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/dev/support.py
@@ -39,7 +39,7 @@ class DevelopmentCommandSupport:
该对象负责开发工具命令参数拼装,
避免主运行时服务继续承载命令行桥接细节。
- :param runtime_environment: 运行时环境服务
+ :ivar runtime_environment: 运行时环境服务
"""
def __init__(self, runtime_environment: RuntimeEnvironmentService) -> None:
@@ -47,7 +47,6 @@ def __init__(self, runtime_environment: RuntimeEnvironmentService) -> None:
初始化开发命令构建支持对象。
:param runtime_environment: 运行时环境服务
- :return: None
"""
self.runtime_environment = runtime_environment
@@ -102,7 +101,7 @@ def build_pytest_command(
构建 pytest 命令。
:param normalized_targets: 已规整目标列表
- :param keyword: pytest `-k` 表达式
+ :param keyword: pytest ``-k`` 表达式
:param maxfail: 最大失败数
:param quiet: 是否启用简洁输出
:return: pytest 命令参数列表
diff --git a/ruoyi-fastapi-backend/cli/runtime/gen/gateway.py b/ruoyi-fastapi-backend/cli/runtime/gen/gateway.py
index 3bfb95c82..862a49119 100644
--- a/ruoyi-fastapi-backend/cli/runtime/gen/gateway.py
+++ b/ruoyi-fastapi-backend/cli/runtime/gen/gateway.py
@@ -13,18 +13,18 @@ class GenInfrastructureGateway:
@staticmethod
def get_sqlglot_module() -> Any:
"""
- 获取 `sqlglot` 模块。
+ 获取 ``sqlglot`` 模块。
- :return: `sqlglot` 模块
+ :return: ``sqlglot`` 模块
"""
return import_module('sqlglot')
@staticmethod
def get_sqlglot_expressions_module() -> Any:
"""
- 获取 `sqlglot.expressions` 模块。
+ 获取 ``sqlglot.expressions`` 模块。
- :return: `sqlglot.expressions` 模块
+ :return: ``sqlglot.expressions`` 模块
"""
return import_module('sqlglot.expressions')
diff --git a/ruoyi-fastapi-backend/cli/runtime/gen/service.py b/ruoyi-fastapi-backend/cli/runtime/gen/service.py
index e760da91d..f5c31d4f4 100644
--- a/ruoyi-fastapi-backend/cli/runtime/gen/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/gen/service.py
@@ -13,8 +13,8 @@ class GenRuntimeService:
该服务作为代码生成运行时 facade,对外统一暴露业务表、数据库物理表、
建表 SQL、代码预览、导出与数据库同步等入口。
- :param infrastructure_gateway: 代码生成基础设施网关
- :param domain_support: 代码生成领域支持对象
+ :ivar infrastructure_gateway: 代码生成基础设施网关
+ :ivar domain_support: 代码生成领域支持对象
"""
def __init__(
@@ -28,7 +28,6 @@ def __init__(
:param infrastructure_gateway: 代码生成基础设施网关
:param domain_support: 代码生成领域支持对象
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway or GenInfrastructureGateway()
self.domain_support = domain_support or GenDomainSupport(self.infrastructure_gateway)
@@ -305,7 +304,7 @@ async def export_code(
导出代码生成结果。
:param table_names: 业务表名称列表
- :param mode: 导出模式,支持 `zip` 与 `local`
+ :param mode: 导出模式,支持 ``zip`` 与 ``local``
:param output_file: zip 导出目标文件路径
:param dry_run: 是否仅演练执行
:return: 导出结果
diff --git a/ruoyi-fastapi-backend/cli/runtime/gen/support.py b/ruoyi-fastapi-backend/cli/runtime/gen/support.py
index 6f92be72d..a83310249 100644
--- a/ruoyi-fastapi-backend/cli/runtime/gen/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/gen/support.py
@@ -13,7 +13,8 @@ class GenDomainSupport:
该对象负责 CLI 当前用户构建、表名规整、记录序列化、SQL 解析
以及导出路径处理,避免主运行时服务继续承载过多局部规则。
- :param infrastructure_gateway: 代码生成基础设施网关
+ :ivar infrastructure_gateway: 代码生成基础设施网关
+ :ivar operator_service: 运行时操作者解析服务
"""
def __init__(
@@ -26,7 +27,6 @@ def __init__(
:param infrastructure_gateway: 代码生成基础设施网关
:param operator_service: 运行时操作者解析服务
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway
self.operator_service = operator_service
diff --git a/ruoyi-fastapi-backend/cli/runtime/job/service.py b/ruoyi-fastapi-backend/cli/runtime/job/service.py
index 705e46cd8..a49be2612 100644
--- a/ruoyi-fastapi-backend/cli/runtime/job/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/job/service.py
@@ -13,9 +13,9 @@ class JobRuntimeService:
该服务作为定时任务运行时 facade,对外统一暴露任务列表、详情、日志、
执行一次、暂停与恢复入口。
- :param infrastructure_gateway: 定时任务基础设施网关
- :param domain_support: 定时任务领域支持对象
- :param scheduler_support: 定时任务调度上下文支持对象
+ :ivar infrastructure_gateway: 定时任务基础设施网关
+ :ivar domain_support: 定时任务领域支持对象
+ :ivar scheduler_support: 定时任务调度上下文支持对象
"""
def __init__(
@@ -31,7 +31,6 @@ def __init__(
:param infrastructure_gateway: 定时任务基础设施网关
:param domain_support: 定时任务领域支持对象
:param scheduler_support: 定时任务调度上下文支持对象
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway or JobInfrastructureGateway()
self.domain_support = domain_support or JobDomainSupport(self.infrastructure_gateway)
@@ -127,8 +126,8 @@ async def list_job_logs(
:param job_name: 任务名称过滤条件
:param job_group: 任务组过滤条件
:param status: 执行状态过滤条件
- :param begin_date: 开始日期,格式 `YYYY-MM-DD`
- :param end_date: 结束日期,格式 `YYYY-MM-DD`
+ :param begin_date: 开始日期,格式 ``YYYY-MM-DD``
+ :param end_date: 结束日期,格式 ``YYYY-MM-DD``
:param paged: 是否启用分页
:param page_num: 页码
:param page_size: 每页数量
diff --git a/ruoyi-fastapi-backend/cli/runtime/job/support.py b/ruoyi-fastapi-backend/cli/runtime/job/support.py
index 241a493fb..5ac40a0ce 100644
--- a/ruoyi-fastapi-backend/cli/runtime/job/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/job/support.py
@@ -10,7 +10,7 @@ class JobDomainSupport:
该对象负责任务序列化、分页结果规整和任务操作元数据定义,
避免主运行时服务继续承载细碎领域规则。
- :param infrastructure_gateway: 定时任务基础设施网关
+ :ivar infrastructure_gateway: 定时任务基础设施网关
"""
def __init__(self, infrastructure_gateway: JobInfrastructureGateway) -> None:
@@ -18,7 +18,6 @@ def __init__(self, infrastructure_gateway: JobInfrastructureGateway) -> None:
初始化定时任务领域支持对象。
:param infrastructure_gateway: 定时任务基础设施网关
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway
@@ -139,7 +138,7 @@ class JobSchedulerSupport:
该对象负责统一关闭调度器上下文资源,避免调度型操作在 facade 中
持续堆叠资源清理细节。
- :param infrastructure_gateway: 定时任务基础设施网关
+ :ivar infrastructure_gateway: 定时任务基础设施网关
"""
def __init__(self, infrastructure_gateway: JobInfrastructureGateway) -> None:
@@ -147,7 +146,6 @@ def __init__(self, infrastructure_gateway: JobInfrastructureGateway) -> None:
初始化定时任务调度上下文支持对象。
:param infrastructure_gateway: 定时任务基础设施网关
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway
@@ -156,7 +154,6 @@ async def close_scheduler_context(self, redis: Any) -> None:
安全关闭任务调度相关资源。
:param redis: Redis 客户端实例
- :return: None
"""
scheduler_manager = self.infrastructure_gateway.get_scheduler_manager()
try:
diff --git a/ruoyi-fastapi-backend/cli/runtime/oidc/gateway.py b/ruoyi-fastapi-backend/cli/runtime/oidc/gateway.py
index da82c3473..8a0ecf0dd 100644
--- a/ruoyi-fastapi-backend/cli/runtime/oidc/gateway.py
+++ b/ruoyi-fastapi-backend/cli/runtime/oidc/gateway.py
@@ -4,7 +4,7 @@
class OidcInfrastructureGateway:
"""
- OIDC 基础设施网关
+ OIDC 基础设施网关。
该对象负责延迟加载 OIDC CLI 所需的数据库、Redis、运行时检查
与签名密钥管理依赖。
@@ -13,7 +13,7 @@ class OidcInfrastructureGateway:
@staticmethod
def get_data_source_registry() -> Any:
"""
- 获取数据源注册表
+ 获取数据源注册表。
:return: 数据源注册表
"""
@@ -22,7 +22,7 @@ def get_data_source_registry() -> Any:
@staticmethod
def get_oidc_config() -> Any:
"""
- 获取 OIDC 配置对象
+ 获取 OIDC 配置对象。
:return: OIDC 配置对象
"""
@@ -31,7 +31,7 @@ def get_oidc_config() -> Any:
@staticmethod
def get_redis_util() -> Any:
"""
- 获取 Redis 工具类
+ 获取 Redis 工具类。
:return: Redis 工具类
"""
@@ -40,7 +40,7 @@ def get_redis_util() -> Any:
@staticmethod
def get_runtime_service() -> Any:
"""
- 获取 OIDC 运行时服务
+ 获取 OIDC 运行时服务。
:return: OIDC 运行时服务类
"""
@@ -49,7 +49,7 @@ def get_runtime_service() -> Any:
@staticmethod
def get_key_management_service() -> Any:
"""
- 获取 OIDC 签名密钥管理服务
+ 获取 OIDC 签名密钥管理服务。
:return: OIDC 签名密钥管理服务类
"""
diff --git a/ruoyi-fastapi-backend/cli/runtime/oidc/service.py b/ruoyi-fastapi-backend/cli/runtime/oidc/service.py
index bb6bd7a99..87826df58 100644
--- a/ruoyi-fastapi-backend/cli/runtime/oidc/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/oidc/service.py
@@ -8,25 +8,24 @@
class OidcRuntimeCliService:
"""
- OIDC CLI 运行时服务
+ OIDC CLI 运行时服务。
该服务对外统一暴露 OIDC 就绪检查和首把签名密钥初始化入口。
- :param infrastructure_gateway: OIDC 基础设施网关
+ :ivar infrastructure_gateway: OIDC 基础设施网关
"""
def __init__(self, infrastructure_gateway: OidcInfrastructureGateway | None = None) -> None:
"""
- 初始化 OIDC CLI 运行时服务
+ 初始化 OIDC CLI 运行时服务。
:param infrastructure_gateway: OIDC 基础设施网关
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway or OidcInfrastructureGateway()
async def check_readiness(self) -> dict[str, Any]:
"""
- 检查部署配置中的 OIDC 是否已具备签名能力
+ 检查部署配置中的 OIDC 是否已具备签名能力。
:return: OIDC 就绪检查结果
"""
@@ -76,7 +75,7 @@ async def bootstrap_signing_key(
dry_run: bool = False,
) -> dict[str, Any]:
"""
- 幂等创建并激活首把 OIDC 签名密钥
+ 幂等创建并激活首把 OIDC 签名密钥。
:param kid: 首把签名密钥标识
:param actor: 部署操作人标识
diff --git a/ruoyi-fastapi-backend/cli/runtime/ops/gateway.py b/ruoyi-fastapi-backend/cli/runtime/ops/gateway.py
index 40f854911..16b4ebbbc 100644
--- a/ruoyi-fastapi-backend/cli/runtime/ops/gateway.py
+++ b/ruoyi-fastapi-backend/cli/runtime/ops/gateway.py
@@ -49,9 +49,9 @@ def get_server_service() -> Any:
@staticmethod
def get_psutil_module() -> Any:
"""
- 获取 `psutil` 模块。
+ 获取 ``psutil`` 模块。
- :return: `psutil` 模块
+ :return: ``psutil`` 模块
"""
return import_module('psutil')
@@ -60,6 +60,6 @@ def get_bytes2human() -> Any:
"""
获取字节数转可读文本函数。
- :return: `bytes2human` 函数
+ :return: ``bytes2human`` 函数
"""
return import_module('utils.common_util').bytes2human
diff --git a/ruoyi-fastapi-backend/cli/runtime/ops/service.py b/ruoyi-fastapi-backend/cli/runtime/ops/service.py
index d7b0cab6e..cc283c74f 100644
--- a/ruoyi-fastapi-backend/cli/runtime/ops/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/ops/service.py
@@ -17,9 +17,9 @@ class OperationsRuntimeService:
该服务作为运维运行时 facade,对外统一暴露依赖版本检查、Redis 探活、
调度同步以及服务器运行时信息采集入口。
- :param infrastructure_gateway: 运维基础设施网关
- :param dependency_inspector: 运维依赖检查器
- :param server_info_support: 服务器信息支持对象
+ :ivar infrastructure_gateway: 运维基础设施网关
+ :ivar dependency_inspector: 运维依赖检查器
+ :ivar server_info_support: 服务器信息支持对象
"""
def __init__(
@@ -35,7 +35,6 @@ def __init__(
:param infrastructure_gateway: 运维基础设施网关
:param dependency_inspector: 运维依赖检查器
:param server_info_support: 服务器信息支持对象
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway or OperationsInfrastructureGateway()
self.dependency_inspector = dependency_inspector or OperationsDependencyInspector()
diff --git a/ruoyi-fastapi-backend/cli/runtime/ops/support.py b/ruoyi-fastapi-backend/cli/runtime/ops/support.py
index 85f4a7429..cdf28204b 100644
--- a/ruoyi-fastapi-backend/cli/runtime/ops/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/ops/support.py
@@ -18,10 +18,10 @@ class OperationsDependencySpec:
"""
运维依赖检查项定义。
- :param package_name: CLI 展示用包名
- :param distribution: Python 分发名称
- :param required: 是否为必需依赖
- :param version: 显式版本,存在时跳过环境读取
+ :ivar package_name: CLI 展示用包名
+ :ivar distribution: Python 分发名称
+ :ivar required: 是否为必需依赖
+ :ivar version: 显式版本,存在时跳过环境读取
"""
package_name: str
@@ -44,7 +44,7 @@ def read_package_version(distribution_name: str) -> str | None:
读取指定 Python 包的已安装版本号。
:param distribution_name: Python 包分发名称
- :return: 已安装版本号,未安装时返回 `None`
+ :return: 已安装版本号,未安装时返回 ``None``
"""
try:
return metadata.version(distribution_name)
@@ -128,7 +128,7 @@ class OperationsServerInfoSupport:
该对象负责 CLI 兜底服务器信息构建与 IP 解析逻辑,
避免主运行时服务继续承载大量平台采集细节。
- :param infrastructure_gateway: 运维基础设施网关
+ :ivar infrastructure_gateway: 运维基础设施网关
"""
def __init__(self, infrastructure_gateway: OperationsInfrastructureGateway) -> None:
@@ -136,7 +136,6 @@ def __init__(self, infrastructure_gateway: OperationsInfrastructureGateway) -> N
初始化服务器信息支持对象。
:param infrastructure_gateway: 运维基础设施网关
- :return: None
"""
self.infrastructure_gateway = infrastructure_gateway
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/gateway.py b/ruoyi-fastapi-backend/cli/runtime/plugin/gateway.py
index 80b1200da..5b0efb1b9 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/gateway.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/gateway.py
@@ -7,7 +7,7 @@ class PluginRuntimeGateway:
插件 CLI 运行时网关。
该对象负责延迟加载插件核心运行时与管理适配器,避免导入
- `cli.runtime.plugin` 时立即加载 `plugins.core`。
+ ``cli.runtime.plugin`` 时立即加载 ``plugins.core``。
"""
@staticmethod
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/__init__.py.tmpl b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/__init__.py.tmpl
index 468d8f44d..66568c423 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/__init__.py.tmpl
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/__init__.py.tmpl
@@ -27,7 +27,6 @@ async def shutdown(host: PluginHostContext) -> None:
记录插件关闭,可在此释放插件自有资源并保留宿主共享连接池。
:param host: 宿主提供的插件上下文
- :return: None
"""
host.logger.info("__PLUGIN_ID__ stopped")
# 仅释放插件自身创建的资源,不关闭宿主 Redis 或数据库连接池。
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/build_release.py.tmpl b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/build_release.py.tmpl
index 11f082a66..0d6f5a264 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/build_release.py.tmpl
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/python/build_release.py.tmpl
@@ -13,7 +13,12 @@ else:
from pathlib import PureWindowsPath
def is_windows_reserved(name: str) -> bool:
- """按 Windows 规则识别保留路径名。"""
+ """
+ 按 Windows 规则识别保留路径名。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 是否按 Windows 规则识别保留路径名
+ """
return PureWindowsPath(name).is_reserved()
@@ -67,6 +72,7 @@ def checked_file(path: Path) -> Path:
:param path: 待交付的源码文件路径
:return: 通过检查的源码文件路径
+ :raises ValueError: 交付文件越出源码目录或路径包含不允许的链接
"""
for part in (path, *path.parents):
if part == SOURCE:
@@ -88,6 +94,7 @@ def checked_relative_path(value: str) -> tuple[str, ...]:
:param value: 清单或 bundle 中的相对路径
:return: 未经折叠或重写的路径组件
+ :raises ValueError: 交付路径必须为字符串
"""
if not isinstance(value, str):
raise ValueError('交付路径必须为字符串')
@@ -119,7 +126,7 @@ def checked_inventory(names: list[str]) -> None:
拒绝重复文件、文件与目录冲突以及任一级目录的大小写歧义。
:param names: 全部交付文件的相对路径
- :return: None
+ :raises ValueError: 交付清单存在文件与父目录冲突
"""
spellings: dict[str, str] = {}
files: set[str] = set()
@@ -146,6 +153,7 @@ def unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
:param pairs: JSON 对象按原始顺序出现的字段
:return: 不包含重复字段的对象
+ :raises ValueError: 交付清单的 JSON 对象中出现重复字段
"""
result = {}
for key, value in pairs:
@@ -160,6 +168,7 @@ def source_resources() -> list[Path]:
按有大小和数量上限的显式清单读取 Python、SQL 资源,不扫描业务源码。
:return: 已通过路径、类型和链接检查的源码文件列表
+ :raises ValueError: release-files.json 超过 64 KiB 上限;release-files.json 必须包含 schemaVersion: 1 和 files;交付清单 files 必须为包含 1 至 1024 项的列表
"""
path = checked_file(SOURCE / RELEASE_MANIFEST)
with path.open('rb') as source:
@@ -197,6 +206,7 @@ def bundle_resources() -> list[Path]:
收集已构建 bundle,保留原有静态扩展名、隐藏文件和链接限制。
:return: 已通过检查的 web/dist 文件列表
+ :raises ValueError: bundle 入口必须使用准确的 index.html 文件名
"""
dist = SOURCE / 'web' / 'dist'
checked_file(dist / 'index.html')
@@ -215,11 +225,7 @@ def bundle_resources() -> list[Path]:
def main() -> None:
- """
- 按显式文件清单组装新交付目录,不安装依赖、导入插件或生成签名。
-
- :return: None
- """
+ """按显式文件清单组装新交付目录,不安装依赖、导入插件或生成签名。"""
parser = argparse.ArgumentParser(
description='按 release-files.json 组装交付文件;不安装依赖、不导入插件、不生成签名。'
)
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/test_plugin.py.tmpl b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/test_plugin.py.tmpl
index 5a249826b..93de870f4 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/test_plugin.py.tmpl
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/test_plugin.py.tmpl
@@ -27,11 +27,7 @@ pytestmark = pytest.mark.skipif(
@pytest.mark.asyncio
async def test_plugin_contract_and_permission() -> None:
- """
- 验证插件工厂、生命周期、接口权限和健康检查合约。
-
- :return: None
- """
+ """验证插件工厂、生命周期、接口权限和健康检查合约。"""
plugin = PluginScanner(ROOT.parent).load_manifest(ROOT / "plugin.yaml")
host = PluginHostContext(
"__PLUGIN_ID__", ROOT, logger=logging.getLogger("__PLUGIN_ID__")
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/backend.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/backend.py
index f1f1d674d..1e72b8c4f 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/backend.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/backend.py
@@ -3,9 +3,7 @@
class PluginBackendScaffoldTemplateBuilder:
- """
- 后端插件模板内容构建器。
- """
+ """后端插件模板内容构建器。"""
@staticmethod
def build_manifest(plugin_id: str, options: PluginScaffoldOptions) -> str:
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/builder.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/builder.py
index 9e0bc2947..9cac21ba3 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/builder.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/builder.py
@@ -18,6 +18,12 @@ class PluginScaffoldBuilder:
插件模板构建器。
使用 Builder 模式生成后端与前端插件模板文件计划,并在确认无冲突后落地。
+
+ :cvar build_conflict_payload: 构建脚手架文件冲突结果的函数
+ :cvar build_success_payload: 构建脚手架生成成功结果的函数
+ :ivar backend_root: 后端项目根目录
+ :ivar frontend_root: 前端工程根目录或包含框架分类的聚合目录
+ :ivar frontend_framework_resolver: 宿主框架解析函数,保留运行环境中选择的框架
"""
def __init__(
@@ -32,7 +38,6 @@ def __init__(
:param backend_root: 后端项目根目录
:param frontend_root: 前端工程根目录或包含框架分类的聚合目录
:param frontend_framework_resolver: 宿主框架解析函数,保留运行环境中选择的框架
- :return: None
"""
self.backend_root = backend_root
self.frontend_root = select_frontend_root(frontend_root)
@@ -66,6 +71,7 @@ def build_plan(
:param test: 是否创建测试样例
:param frontend_framework: 目标前端框架标识,auto 表示自动识别;源码模板支持 vue2、vue3、react
:return: 插件模板写入计划
+ :raises ValueError: backend 和 frontend 至少需要创建一个
"""
self._validate_plugin_id(plugin_id)
frontend_root = select_frontend_root(self.frontend_root, frontend_framework)
@@ -165,7 +171,6 @@ def _validate_plugin_id(cls, plugin_id: str) -> None:
校验插件模板 ID。
:param plugin_id: 插件ID
- :return: None
"""
validate_plugin_id_value(plugin_id)
@@ -210,7 +215,6 @@ def apply_plan(self, scaffold_plan: dict[str, Any]) -> None:
执行插件模板写入计划。
:param scaffold_plan: 插件模板写入计划
- :return: None
"""
for file_payload in scaffold_plan['files']:
file_path = Path(file_payload['path'])
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/frontend.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/frontend.py
index b3c0e0f33..06987c77b 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/frontend.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/frontend.py
@@ -7,9 +7,7 @@
class PluginVue3FrontendScaffoldTemplateBuilder(PluginFrontendApiScaffoldTemplateBuilder):
- """
- 前端插件模板内容构建器。
- """
+ """前端插件模板内容构建器。"""
@staticmethod
def build_view(plugin_id: str) -> str:
@@ -250,38 +248,81 @@ def build_test(plugin_id: str) -> str:
class PluginFrontendScaffoldTemplateBuilder:
- """
- 根据目标前端框架分派已实现的插件源码模板。
- """
+ """根据目标前端框架分派已实现的插件源码模板。"""
@staticmethod
def build_api(plugin_id: str) -> str:
+ """
+ 生成插件前端的 API 访问模块。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 插件前端的 API 访问模块
+ """
return PluginFrontendApiScaffoldTemplateBuilder.build_api(plugin_id)
@staticmethod
def build_crud_api(plugin_id: str) -> str:
+ """
+ 生成插件前端的增删改查请求函数。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 插件前端的增删改查请求函数
+ """
return PluginFrontendApiScaffoldTemplateBuilder.build_crud_api(plugin_id)
@classmethod
def view_filename(cls, frontend_framework: FrontendFramework = 'vue3') -> str:
- """验证框架并返回该宿主加载的页面文件名。"""
+ """
+ 验证框架并返回该宿主加载的页面文件名。
+
+ :param frontend_framework: 用于生成或构建前端的框架
+ :return: 该宿主加载的页面文件名
+ """
cls._resolve_builder(frontend_framework)
return 'index.jsx' if frontend_framework == 'react' else 'index.vue'
@classmethod
def build_view(cls, plugin_id: str, frontend_framework: FrontendFramework = 'vue3') -> str:
+ """
+ 生成插件前端入口视图。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param frontend_framework: 用于生成或构建前端的框架
+ :return: 插件前端入口视图
+ """
return cls._resolve_builder(frontend_framework).build_view(plugin_id)
@classmethod
def build_crud_view(cls, plugin_id: str, frontend_framework: FrontendFramework = 'vue3') -> str:
+ """
+ 生成插件记录列表及编辑视图。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param frontend_framework: 用于生成或构建前端的框架
+ :return: 插件记录列表及编辑视图
+ """
return cls._resolve_builder(frontend_framework).build_crud_view(plugin_id)
@classmethod
def build_readme(cls, plugin_id: str, frontend_framework: FrontendFramework = 'vue3') -> str:
+ """
+ 生成插件前端的使用说明。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param frontend_framework: 用于生成或构建前端的框架
+ :return: 插件前端的使用说明
+ """
return cls._resolve_builder(frontend_framework).build_readme(plugin_id)
@classmethod
def build_test(cls, plugin_id: str, frontend_framework: FrontendFramework = 'vue3') -> str:
+ """
+ 生成插件前端的测试文件。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param frontend_framework: 用于生成或构建前端的框架
+ :return: 插件前端的测试文件
+ """
return cls._resolve_builder(frontend_framework).build_test(plugin_id)
@staticmethod
@@ -292,6 +333,13 @@ def _resolve_builder(
| type[PluginVue3FrontendScaffoldTemplateBuilder]
| type[PluginReactFrontendScaffoldTemplateBuilder]
):
+ """
+ 按前端框架选择对应的脚手架模板构建器。
+
+ :param frontend_framework: 用于生成或构建前端的框架
+ :return: 适用于目标前端框架的模板构建器类型
+ :raises ValueError: 所选前端框架没有对应的源码模板
+ """
if frontend_framework == 'vue2':
return PluginVue2FrontendScaffoldTemplateBuilder
if frontend_framework == 'vue3':
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/frontend_react.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/frontend_react.py
index f3cb8d8ac..08bc192ff 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/frontend_react.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/frontend_react.py
@@ -6,7 +6,12 @@ class PluginReactFrontendScaffoldTemplateBuilder:
@staticmethod
def build_view(plugin_id: str) -> str:
- """生成与基础 Vue 模板相同的插件信息卡片。"""
+ """
+ 生成与基础 Vue 模板相同的插件信息卡片。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 与基础 Vue 模板相同的插件信息卡片
+ """
class_name = PluginScaffoldNaming.to_class_name(plugin_id)
return f"""import {{ Card }} from 'antd';
import {{ useI18n }} from '../i18n';
@@ -25,7 +30,12 @@ def build_view(plugin_id: str) -> str:
@staticmethod
def build_crud_view(plugin_id: str) -> str:
- """生成筛选、列表和编辑弹窗,复用宿主请求及消息组件。"""
+ """
+ 生成筛选、列表和编辑弹窗,复用宿主请求及消息组件。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 筛选、列表和编辑弹窗
+ """
class_name = PluginScaffoldNaming.to_class_name(plugin_id)
return f"""import {{ useEffect, useState }} from 'react';
import {{ useI18n }} from '../i18n';
@@ -184,7 +194,12 @@ def build_crud_view(plugin_id: str) -> str:
@staticmethod
def build_readme(plugin_id: str) -> str:
- """生成 React 宿主接入和测试说明。"""
+ """
+ 生成 React 宿主接入和测试说明。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: React 宿主接入和测试说明
+ """
return f"""# {plugin_id} React frontend plugin
Generated by `ruoyi plugin create --frontend-framework=react`.
@@ -210,7 +225,12 @@ def build_readme(plugin_id: str) -> str:
@staticmethod
def build_test(plugin_id: str) -> str:
- """生成可由 plugin test 调用的 React 路由解析测试。"""
+ """
+ 生成可由 plugin test 调用的 React 路由解析测试。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 可由 plugin test 调用的 React 路由解析测试
+ """
return f"""import assert from 'node:assert/strict';
import {{ existsSync }} from 'node:fs';
import {{ dirname, resolve }} from 'node:path';
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/frontend_vue2.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/frontend_vue2.py
index 6c427490c..665bfbe8b 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/frontend_vue2.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/frontend_vue2.py
@@ -2,9 +2,7 @@
class PluginVue2FrontendScaffoldTemplateBuilder:
- """
- Vue 2 前端插件模板内容构建器。
- """
+ """Vue 2 前端插件模板内容构建器。"""
@staticmethod
def build_view(plugin_id: str) -> str:
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/locales.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/locales.py
index a4b1a3cd1..82c9b9213 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/locales.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/locales.py
@@ -6,6 +6,8 @@
class PluginLocaleScaffoldBuilder:
"""
生成插件独立词库与宿主注册示例。
+
+ :cvar MESSAGES: 插件模板包含的翻译消息
"""
MESSAGES: ClassVar[dict[str, dict[str, str]]] = {
@@ -68,6 +70,7 @@ def build_files(cls, plugin_id: str, plugin_root: Path, frontend_root: Path) ->
:param plugin_root: 插件输出目录
:param frontend_root: 目标宿主目录
:return: 词库、注册模块和接入说明
+ :raises ValueError: 语言标识不能包含路径分隔符
"""
meta = cls.load_metadata(frontend_root)
codes = list(dict.fromkeys([meta['sourceLocale'], *(entry['code'] for entry in meta['locales'])]))
@@ -175,6 +178,7 @@ def build_bundle_files(cls, root: Path, frontend_root: Path) -> list[tuple[Path,
:param root: 独立前端工程目录
:param frontend_root: 目标宿主目录
:return: 独立 bundle 的国际化文件
+ :raises ValueError: 语言标识不能包含路径分隔符
"""
meta = cls.load_metadata(frontend_root)
messages = {
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/naming.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/naming.py
index ee49ff5ad..519dc8ba5 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/naming.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/naming.py
@@ -1,7 +1,5 @@
class PluginScaffoldNaming:
- """
- 插件模板命名转换工具。
- """
+ """插件模板命名转换工具。"""
@staticmethod
def to_class_name(plugin_id: str) -> str:
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/options.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/options.py
index 0c0837349..7b1b3a5e6 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/options.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/options.py
@@ -6,14 +6,14 @@ class PluginScaffoldOptions:
"""
插件模板生成选项。
- :param backend: 是否生成后端模板
- :param frontend: 是否生成前端模板
- :param migration: 是否生成 migration 示例
- :param seed: 是否生成 seed 示例
- :param job: 是否生成定时任务示例
- :param config: 是否生成配置项示例
- :param test: 是否生成测试样例
- :param crud: 是否生成 CRUD 页面示例
+ :ivar backend: 是否生成后端模板
+ :ivar frontend: 是否生成前端模板
+ :ivar migration: 是否生成 migration 示例
+ :ivar seed: 是否生成 seed 示例
+ :ivar job: 是否生成定时任务示例
+ :ivar config: 是否生成配置项示例
+ :ivar test: 是否生成测试样例
+ :ivar crud: 是否生成 CRUD 页面示例
"""
backend: bool = True
@@ -31,6 +31,10 @@ class PluginScaffoldTemplateResolver:
插件模板预设解析器。
使用 Resolver 模式将模板名称转换为稳定的模板生成选项。
+
+ :cvar V2_TEMPLATES: 第二版插件脚手架支持的模板集合
+ :cvar SUPPORTED_TEMPLATES: 脚手架允许使用的模板
+ :cvar DEFAULT_TEMPLATE: 未显式选择时使用的模板
"""
V2_TEMPLATES = frozenset({'python-asgi', 'python-bundle', 'rust-asgi', 'rust-bundle'})
@@ -44,6 +48,7 @@ def resolve(cls, template: str) -> PluginScaffoldOptions:
:param template: 插件模板名称
:return: 插件模板生成选项
+ :raises ValueError: 插件模板预设不受支持
"""
normalized_template = (template or cls.DEFAULT_TEMPLATE).strip() or cls.DEFAULT_TEMPLATE
if normalized_template in cls.V2_TEMPLATES:
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/payload.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/payload.py
index bfefb3005..e50b38294 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/payload.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/payload.py
@@ -10,6 +10,22 @@
class PluginScaffoldPlanPayload:
"""
插件模板写入计划负载。
+
+ :ivar template: 用于生成文件的模板
+ :ivar backend: 后端部分的配置或处理对象
+ :ivar frontend: 前端部分的配置
+ :ivar migration: 插件的数据迁移配置
+ :ivar seed: 插件的种子数据配置
+ :ivar job: 插件的调度任务配置
+ :ivar config: 当前对象使用的配置
+ :ivar crud: 是否生成增删改查功能
+ :ivar test: 是否生成测试
+ :ivar backend_test: 是否包含后端测试
+ :ivar frontend_test: 是否包含前端测试
+ :ivar frontend_framework: 用于生成或构建前端的框架
+ :ivar target_dirs: 生成操作要写入的目录
+ :ivar files: 此次操作涉及的文件
+ :ivar conflicts: 生成计划与已有文件的冲突
"""
template: str
@@ -57,6 +73,10 @@ def to_payload(self) -> dict[str, Any]:
class PluginScaffoldSuccessPayload:
"""
插件模板创建成功负载。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar scaffold_plan: 插件模板写入计划
+ :ivar dry_run: 是否只预览操作结果
"""
plugin_id: str
@@ -82,6 +102,11 @@ def to_payload(self) -> dict[str, Any]:
class PluginScaffoldConflictPayload:
"""
插件模板目录冲突负载。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar scaffold_plan: 插件模板写入计划
+ :ivar dry_run: 是否只预览操作结果
+ :ivar failure_code: 失败退出码
"""
plugin_id: str
@@ -106,9 +131,7 @@ def to_payload(self) -> dict[str, Any]:
class PluginScaffoldPayloadBuilder:
- """
- 插件模板创建响应负载构建器。
- """
+ """插件模板创建响应负载构建器。"""
@staticmethod
def build_conflict_payload(
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py
index 225dd6a99..a90d94601 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py
@@ -15,6 +15,10 @@
class PluginV2ScaffoldBuilder:
"""
独立 v2 插件源码工程模板构建器。
+
+ :ivar backend_root: 宿主后端项目根目录
+ :ivar frontend_root: 宿主前端项目根目录,用于读取桥接 SDK
+ :ivar frontend_framework_resolver: 宿主框架解析函数,仅 bundle 复制 SDK 时调用
"""
def __init__(
@@ -29,7 +33,6 @@ def __init__(
:param backend_root: 宿主后端项目根目录
:param frontend_root: 宿主前端项目根目录,用于读取桥接 SDK
:param frontend_framework_resolver: 宿主框架解析函数,仅 bundle 复制 SDK 时调用
- :return: None
"""
self.backend_root = backend_root
self.frontend_root = frontend_root
@@ -48,6 +51,7 @@ def build_plan(
:param test: 是否生成本地合约测试
:param frontend_framework: 宿主前端框架选项,v2 模板仅接受 auto
:return: 包含生成文件、目标目录与冲突信息的计划
+ :raises ValueError: v2 ASGI 模板需要后端,不能使用 --frontend-only;bundle 模板不能使用 --backend-only;仅 API 请使用 python-asgi 或 rust-asgi;v2 模板的 --frontend-framework 仅接受 auto;独立 bundle 与宿主前端框架无关
"""
native = template.startswith('rust-')
bundle = template.endswith('-bundle')
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/sdk.py b/ruoyi-fastapi-backend/cli/runtime/plugin/sdk.py
index 2c5f7153d..96384f854 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/sdk.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/sdk.py
@@ -30,7 +30,12 @@
class PluginBridgeSdk:
- """离线检查和更新独立 bundle 工程中的桥接 SDK 副本。"""
+ """
+ 离线检查和更新独立 bundle 工程中的桥接 SDK 副本。
+
+ :ivar frontend_root: 宿主前端工程根目录或包含框架分类的聚合目录
+ :ivar frontend_framework: SDK 来源宿主的框架标识,auto 表示自动识别
+ """
def __init__(self, frontend_root: Path, frontend_framework: str = 'auto') -> None:
"""
@@ -38,7 +43,6 @@ def __init__(self, frontend_root: Path, frontend_framework: str = 'auto') -> Non
:param frontend_root: 宿主前端工程根目录或包含框架分类的聚合目录
:param frontend_framework: SDK 来源宿主的框架标识,auto 表示自动识别
- :return: None
"""
self.frontend_root = select_frontend_root(frontend_root, frontend_framework)
self.frontend_framework = resolve_frontend_framework_request(self.frontend_root, frontend_framework)
@@ -48,6 +52,7 @@ def build_vendor_files(self) -> dict[str, str]:
校验宿主 SDK 并生成使用 UTF-8、LF 和内容摘要的三个副本文件。
:return: 按固定文件名索引的文本,不包含时间戳或本机路径
+ :raises ValueError: 宿主工程缺少所需的桥接 SDK 文件
"""
directory = self._safe_path(self.frontend_root / 'src' / 'utils')
contents: dict[str, str] = {}
@@ -173,6 +178,7 @@ def _safe_path(path: Path) -> Path:
:param path: 待使用的文件或目录路径
:return: 已检查现存路径组件的绝对路径
+ :raises ValueError: SDK 路径包含符号链接或重解析点
"""
absolute = Path(os.path.abspath(path))
for component in reversed((absolute, *absolute.parents)):
@@ -192,6 +198,7 @@ def _project_paths(cls, project: Path) -> tuple[Path, Path]:
:param project: 用户指定的插件工程根目录
:return: 工程根目录及固定的 web/vendor 目录
+ :raises ValueError: 插件工程目录不存在;SDK 命令只支持 manifestVersion: 2 的 bundle 工程;web/vendor 必须是目录
"""
root = cls._safe_path(project)
if not root.is_dir():
@@ -225,6 +232,7 @@ def _metadata(content: str, *, vendor: bool) -> dict[str, Any]:
:param content: 元数据 JSON 文本
:param vendor: 是否要求副本的摘要与来源字段
:return: 通过字段及类型检查的元数据
+ :raises ValueError: 桥接 SDK 元数据字段无效;桥接 SDK 元数据 schemaVersion 无效;桥接 SDK 的 sdkVersion 无效;桥接 SDK 的 bridgeVersion 无效;桥接 SDK 的 capabilities 无效;桥接 SDK 的摘要算法无效;桥接 SDK 文件摘要记录无效
"""
metadata = json.loads(content)
fields = METADATA_FIELDS | ({'hashAlgorithm', 'source', 'files'} if vendor else set())
@@ -268,7 +276,7 @@ def _validate_source(source: Any) -> None:
校验来源记录使用当前项目名和规范的框架工程路径。
:param source: SDK 副本中的来源记录
- :return: None
+ :raises ValueError: 桥接 SDK 的来源记录无效;桥接 SDK 的来源目录无效
"""
if not isinstance(source, dict) or set(source) != {'project', 'directory'} or source['project'] != SDK_PROJECT:
raise ValueError('桥接 SDK 的来源记录无效')
@@ -303,7 +311,7 @@ def _validate_exports(cls, contents: dict[str, str], metadata: dict[str, Any]) -
:param contents: SDK 的 JS 和类型声明文本
:param metadata: 对应的元数据
- :return: None
+ :raises ValueError: 脚本或类型声明导出的版本与 SDK 元数据不符
"""
for name in SDK_FILES:
sdk_versions = re.findall(
@@ -452,7 +460,8 @@ def _lock(cls, root: Path) -> Iterator[None]:
用工程局部独占文件串行更新,不自动抢占可能仍被使用的旧锁。
:param root: 已验证的工程根目录
- :return: 持有更新锁的上下文
+ :yield: 持有更新锁的上下文
+ :raises ValueError: SDK 更新锁已存在,请确认没有并发更新后再处理锁文件
"""
path = cls._safe_path(root / '.plugin-sdk.lock')
try:
@@ -490,7 +499,6 @@ def _write(cls, path: Path, content: bytes) -> None:
:param path: 待替换的 SDK 文件路径
:param content: 要保存的原始字节
- :return: None
"""
cls._safe_path(path)
temporary = path.with_name(f'.{path.name}.{uuid4().hex}.tmp')
@@ -514,6 +522,8 @@ def _apply(
:param originals: 更新前的原始字节快照
:param backup: 可供人工恢复的原文件备份目录
:return: 更新后已核实为 current 的检查结果
+ :raises ValueError: SDK 更新失败且无法完整回滚
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
try:
for name in VENDOR_FILES:
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/service.py b/ruoyi-fastapi-backend/cli/runtime/plugin/service.py
index d2273c207..6c690a4d3 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/service.py
@@ -23,6 +23,13 @@
class CliPluginRuntimeDependencies:
"""
CLI 插件运行时依赖容器。
+
+ :ivar runtime_environment: 插件运行时环境服务
+ :ivar dependency_checker: 插件依赖检查器
+ :ivar management_gateway: 插件管理运行时适配器
+ :ivar model_gateway: 插件管理模型工厂网关
+ :ivar command_gateway: 插件命令执行网关
+ :ivar lifecycle_lock: 插件生命周期操作锁
"""
runtime_environment: object | None = None
@@ -39,6 +46,12 @@ class CliPluginRuntimeService:
该服务负责为 CLI 组装核心插件运行时,并只承载 CLI 专属开发命令能力,
例如插件测试执行、插件模板创建和本地辅助文件生成。
+
+ :ivar success_code: CLI 成功退出码
+ :ivar runtime_error_code: CLI 运行失败退出码
+ :ivar plugin_gateway: 插件 CLI 运行时网关
+ :ivar dependencies: 执行当前步骤所需的依赖
+ :ivar _core_runtime: 提供底层插件操作的运行时
"""
def __init__(
@@ -66,7 +79,6 @@ def __init__(
:param command_gateway: 插件命令执行网关
:param lifecycle_lock: 插件生命周期操作锁
:param plugin_gateway: 插件 CLI 运行时网关
- :return: None
"""
self.success_code = success_code
self.runtime_error_code = runtime_error_code
@@ -374,6 +386,7 @@ def _resolve_backend_output_path(backend_root: Path, output_path: str) -> Path:
:param backend_root: 后端项目根目录
:param output_path: 用户指定输出路径
:return: 规范化后的输出路径
+ :raises ValueError: 输出路径超出后端工程目录
"""
raw_output_path = Path(output_path)
resolved_backend_root = backend_root.resolve(strict=False)
@@ -399,7 +412,7 @@ def test_plugin(
执行插件测试样例。
:param plugin_id: 插件ID
- :param keyword: pytest `-k` 过滤表达式
+ :param keyword: pytest ``-k`` 过滤表达式
:param maxfail: 最大失败数,0 表示不限制
:param quiet: 是否启用简洁输出
:param frontend_build: 是否执行前端构建验收
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/support.py b/ruoyi-fastapi-backend/cli/runtime/plugin/support.py
index 281a8f960..dbd068419 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/support.py
@@ -56,11 +56,11 @@ class PluginTestTarget:
"""
插件测试目标。
- :param kind: 测试目标类型
- :param target_path: 测试目标路径
- :param command: 测试执行命令
- :param workdir: 命令工作目录
- :param timeout: 命令超时时间
+ :ivar kind: 测试目标类型
+ :ivar target_path: 测试目标路径
+ :ivar command: 测试执行命令
+ :ivar workdir: 命令工作目录
+ :ivar timeout: 命令超时时间
"""
kind: str
@@ -74,6 +74,8 @@ class PluginTestTarget:
class PluginTestCommandResultPayload:
"""
插件测试命令执行结果负载。
+
+ :ivar completed: 命令执行结果
"""
completed: Any
@@ -95,6 +97,9 @@ def to_payload(self) -> dict[str, Any]:
class PluginTestResultItemPayload:
"""
插件测试单目标执行结果负载。
+
+ :ivar target: 插件测试目标
+ :ivar completed: 命令执行结果
"""
target: PluginTestTarget
@@ -119,6 +124,9 @@ def to_payload(self) -> dict[str, Any]:
class PluginTestMissingPayload:
"""
插件测试目标缺失负载。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar expected_paths: 约定测试目录列表
"""
plugin_id: str
@@ -142,6 +150,13 @@ def to_payload(self) -> dict[str, Any]:
class PluginTestExecutionPayload:
"""
插件测试执行结果负载。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar keyword: pytest ``-k`` 过滤表达式
+ :ivar maxfail: pytest 达到该失败数量后停止
+ :ivar quiet: 是否使用精简的测试输出
+ :ivar frontend_build: 是否执行前端构建
+ :ivar results: 测试结果项列表
"""
plugin_id: str
@@ -178,6 +193,9 @@ def to_payload(self) -> dict[str, Any]:
class CliPluginRuntimeExceptionPayload:
"""
CLI 插件运行时异常负载。
+
+ :ivar exception_payload: 用于呈现异常的结构化信息
+ :ivar failure_code: 失败退出码
"""
exception_payload: dict[str, Any]
@@ -196,6 +214,10 @@ def to_payload(self) -> dict[str, Any]:
class CliPluginRuntimeExitCodePayload:
"""
CLI 插件运行时退出码负载。
+
+ :ivar payload: 插件测试负载
+ :ivar success_code: 成功退出码
+ :ivar failure_code: 失败退出码
"""
payload: dict[str, Any]
@@ -216,15 +238,15 @@ class PluginDependencyLockfileTemplate:
"""
插件依赖锁文件模板。
- :param plugin_id: 插件ID
- :param plugin_version: 插件版本
- :param generated_at: 生成时间
- :param python: Python 依赖锁定项
- :param npm: npm 依赖锁定项
- :param npm_dev: npmDev 依赖锁定项
- :param artifact_count: 已从离线制品反填的依赖项数量
- :param warnings: 生成过程告警
- :param frontend_framework: 锁定的宿主前端框架,无前端依赖分类时为 None
+ :ivar plugin_id: 插件ID
+ :ivar plugin_version: 插件版本
+ :ivar generated_at: 生成时间
+ :ivar python: Python 依赖锁定项
+ :ivar npm: npm 依赖锁定项
+ :ivar npm_dev: npmDev 依赖锁定项
+ :ivar artifact_count: 已从离线制品反填的依赖项数量
+ :ivar warnings: 生成过程告警
+ :ivar frontend_framework: 锁定的宿主前端框架,无前端依赖分类时为 None
"""
plugin_id: str
@@ -425,10 +447,10 @@ class PluginDependencyOfflineArtifactMatch:
"""
离线制品匹配结果。
- :param path: 制品路径
- :param version: 制品版本
- :param hashes: Python 制品哈希
- :param integrity: npm 制品 SRI
+ :ivar path: 制品路径
+ :ivar version: 制品版本
+ :ivar hashes: Python 制品哈希
+ :ivar integrity: npm 制品 SRI
"""
path: Path
@@ -440,6 +462,8 @@ class PluginDependencyOfflineArtifactMatch:
class PluginDependencyOfflineArtifactResolver:
"""
插件离线依赖制品解析器。
+
+ :ivar offline_dir: 离线制品根目录
"""
def __init__(self, offline_dir: Path | str | None = None) -> None:
@@ -447,7 +471,6 @@ def __init__(self, offline_dir: Path | str | None = None) -> None:
初始化离线依赖制品解析器。
:param offline_dir: 离线制品根目录
- :return: None
"""
self.offline_dir = Path(offline_dir) if offline_dir else None
@@ -688,9 +711,7 @@ def _normalize_npm_artifact_name(name: str) -> str:
class PluginDependencyLockPayloadBuilder:
- """
- 插件依赖锁文件模板 payload 构建器。
- """
+ """插件依赖锁文件模板 payload 构建器。"""
@staticmethod
def build_success_payload(
@@ -711,7 +732,7 @@ def build_success_payload(
:param dry_run: 是否仅预演
:param written: 是否已写入文件
:param overwritten: 是否覆盖了已有文件
- :return: payload
+ :return: 响应数据
"""
return CliPluginRuntimeExitCodePayload(
{
@@ -745,7 +766,7 @@ def build_exists_payload(plugin_id: str, output_path: Path) -> dict[str, object]
:param plugin_id: 插件ID
:param output_path: 输出路径
- :return: payload
+ :return: 响应数据
"""
return CliPluginRuntimeExitCodePayload(
{
@@ -766,7 +787,7 @@ def build_not_found_payload(plugin_id: str) -> dict[str, object]:
构建插件不存在 payload。
:param plugin_id: 插件ID
- :return: payload
+ :return: 响应数据
"""
return CliPluginRuntimeExitCodePayload(
{
@@ -782,9 +803,7 @@ def build_not_found_payload(plugin_id: str) -> dict[str, object]:
class PluginDependencyAllowlistExamplePayloadBuilder:
- """
- 插件依赖允许列表示例 payload 构建器。
- """
+ """插件依赖允许列表示例 payload 构建器。"""
@staticmethod
def build_success_payload(
@@ -803,7 +822,7 @@ def build_success_payload(
:param dry_run: 是否仅预演
:param written: 是否已写入文件
:param overwritten: 是否覆盖了已有文件
- :return: payload
+ :return: 响应数据
"""
return CliPluginRuntimeExitCodePayload(
{
@@ -825,7 +844,7 @@ def build_exists_payload(output_path: Path) -> dict[str, object]:
构建允许列表示例文件已存在 payload。
:param output_path: 输出路径
- :return: payload
+ :return: 响应数据
"""
return CliPluginRuntimeExitCodePayload(
{
@@ -845,6 +864,12 @@ class PluginTestPlanBuilder:
插件 CLI 测试计划构建器。
使用 Builder 模式发现后端 pytest 与前端 node 测试目标,并生成可执行命令。
+
+ :ivar backend_root: 后端项目根目录
+ :ivar frontend_root: 前端项目根目录
+ :ivar python_executable: Python 解释器
+ :ivar node_executable: Node.js 可执行命令
+ :ivar timeout: 命令超时时间
"""
def __init__(
@@ -864,7 +889,6 @@ def __init__(
:param python_executable: Python 解释器
:param node_executable: Node.js 可执行命令
:param timeout: 命令超时时间
- :return: None
"""
self.backend_root = backend_root
self.frontend_root = frontend_root
@@ -885,7 +909,7 @@ def build(
构建插件测试目标列表。
:param plugin_id: 插件ID
- :param keyword: pytest `-k` 过滤表达式
+ :param keyword: pytest ``-k`` 过滤表达式
:param maxfail: pytest 最大失败数
:param quiet: pytest 是否启用简洁输出
:param frontend_build: 是否追加前端构建验收目标
@@ -961,7 +985,7 @@ def _build_backend_command(
构建插件 pytest 命令。
:param target_path: 测试目标路径
- :param keyword: pytest `-k` 过滤表达式
+ :param keyword: pytest ``-k`` 过滤表达式
:param maxfail: 最大失败数
:param quiet: 是否启用简洁输出
:return: pytest 命令参数列表
@@ -1052,7 +1076,7 @@ def build_execution_payload(
构建插件测试执行结果负载。
:param plugin_id: 插件ID
- :param keyword: pytest `-k` 过滤表达式
+ :param keyword: pytest ``-k`` 过滤表达式
:param maxfail: 最大失败数
:param quiet: 是否启用简洁输出
:param frontend_build: 是否执行前端构建验收
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/assembly.py b/ruoyi-fastapi-backend/cli/tui/actions/assembly.py
index ede7331e4..316d1c9cd 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/assembly.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/assembly.py
@@ -16,11 +16,11 @@ class TuiActionRegistryBuilder:
该对象负责装配各领域动作模板工厂,最终输出浏览页和详情页共用的
动作注册表,避免模板常量继续散落在模块底部。
- :param jobs: 任务页动作模板工厂
- :param cache: 缓存页动作模板工厂
- :param gen: 代码生成页动作模板工厂
- :param static: 静态页面动作模板工厂
- :param spec_factory: 动作规格构建器
+ :ivar jobs: 任务页动作模板工厂
+ :ivar cache: 缓存页动作模板工厂
+ :ivar gen: 代码生成页动作模板工厂
+ :ivar static: 静态页面动作模板工厂
+ :ivar spec_factory: 动作规格构建器
"""
jobs: JobActionTemplateFactory
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/builders.py b/ruoyi-fastapi-backend/cli/tui/actions/builders.py
index c56f6f24b..04e859c44 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/builders.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/builders.py
@@ -15,7 +15,7 @@ class TuiActionSpecFactory:
"""
TUI 动作规格构建器。
- 该对象负责统一构建动作预览文本与 `TuiActionSpec`,
+ 该对象负责统一构建动作预览文本与 ``TuiActionSpec``,
避免各动作函数继续手工拼接重复的预览和规格对象。
"""
@@ -113,15 +113,15 @@ class TuiActionTemplate:
该模板将命令参数构建、摘要构建与执行模式收敛为统一对象,
使动作注册层可以直接声明“某个槽位对应哪类动作”。
- :param action_id: 动作唯一标识
- :param label: 动作显示名称
- :param parameter_builder: 进程内动作参数构建器
- :param summary_builder: 预览摘要构建器
- :param action_id_builder: 动态动作标识构建器
- :param label_builder: 动态动作标题构建器
- :param preview_title: 预览标题
- :param consequence_text: 结果影响说明
- :param refresh_view: 执行后是否刷新视图
+ :ivar action_id: 动作唯一标识
+ :ivar label: 动作显示名称
+ :ivar parameter_builder: 进程内动作参数构建器
+ :ivar summary_builder: 预览摘要构建器
+ :ivar action_id_builder: 动态动作标识构建器
+ :ivar label_builder: 动态动作标题构建器
+ :ivar preview_title: 预览标题
+ :ivar consequence_text: 结果影响说明
+ :ivar refresh_view: 执行后是否刷新视图
"""
action_id: str
@@ -175,7 +175,7 @@ class TuiActionTemplateSupport:
该对象集中封装多个动作模板都会复用的记录解析与摘要拼装逻辑,
避免这些基础能力继续散落在模块级函数中。
- :param spec_factory: 动作规格构建器
+ :ivar spec_factory: 动作规格构建器
"""
spec_factory: TuiActionSpecFactory
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/execution.py b/ruoyi-fastapi-backend/cli/tui/actions/execution.py
index d7e9e15bf..ae1aa5595 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/execution.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/execution.py
@@ -28,6 +28,16 @@ class TuiActionExecutionService:
该对象将 TUI 动作直接分发到当前进程的 runtime facade,并统一
施加超时、异常收口和结果文本渲染。动作执行不再启动嵌套 CLI。
+
+ :ivar job_runtime: 定时任务运行时服务
+ :ivar operations_runtime: 运维运行时服务
+ :ivar config_runtime: 参数配置运行时服务
+ :ivar cache_runtime: 缓存运行时服务
+ :ivar gen_runtime: 代码生成运行时服务
+ :ivar database_runtime: 数据库运行时服务
+ :ivar crypto_runtime: 传输加密运行时服务
+ :ivar completion_installer: completion 安装与脚本生成服务
+ :ivar application_builder: 根应用构建器
"""
job_runtime: JobRuntimeService = field(default_factory=lambda: JOB_RUNTIME)
@@ -47,6 +57,7 @@ async def execute(self, spec: TuiActionSpec, env: str) -> TuiActionResult:
:param spec: 动作定义
:param env: 当前运行环境
:return: 动作执行结果
+ :raises asyncio.CancelledError: 异步操作被取消时
"""
try:
payload = await asyncio.wait_for(
@@ -108,7 +119,13 @@ async def _dispatch(self, spec: TuiActionSpec, env: str) -> dict[str, Any]:
return payload
async def _dispatch_job(self, action_id: str, parameters: dict[str, object]) -> dict[str, Any]:
- """执行任务领域动作。"""
+ """
+ 执行任务领域动作。
+
+ :param action_id: 动作唯一标识
+ :param parameters: 分派给目标命令的参数
+ :return: 所选调度任务操作的执行结果
+ """
job_id = int(parameters.get('job_id') or 0)
if action_id == 'job-run-once':
return await self.job_runtime.run_job_once(job_id)
@@ -121,7 +138,13 @@ async def _dispatch_job(self, action_id: str, parameters: dict[str, object]) ->
return self._unsupported_action(action_id)
async def _dispatch_cache(self, action_id: str, parameters: dict[str, object]) -> dict[str, Any]:
- """执行缓存领域动作。"""
+ """
+ 执行缓存领域动作。
+
+ :param action_id: 动作唯一标识
+ :param parameters: 分派给目标命令的参数
+ :return: 缓存预热或清理的执行结果
+ """
if action_id == 'cache-warmup':
return await self.cache_runtime.warmup_cache()
if action_id == 'cache-clear-dry-run':
@@ -132,7 +155,13 @@ async def _dispatch_cache(self, action_id: str, parameters: dict[str, object]) -
return self._unsupported_action(action_id)
async def _dispatch_gen(self, action_id: str, parameters: dict[str, object]) -> dict[str, Any]:
- """执行代码生成领域动作。"""
+ """
+ 执行代码生成领域动作。
+
+ :param action_id: 动作唯一标识
+ :param parameters: 分派给目标命令的参数
+ :return: 生成代码导出预览或表同步的执行结果
+ """
table_name = str(parameters.get('table_name') or '')
if action_id == 'gen-export-dry-run':
return await self.gen_runtime.export_code([table_name], mode='zip', dry_run=True)
@@ -141,7 +170,13 @@ async def _dispatch_gen(self, action_id: str, parameters: dict[str, object]) ->
return self._unsupported_action(action_id)
async def _dispatch_database(self, action_id: str, parameters: dict[str, object]) -> dict[str, Any]:
- """执行数据库领域动作。"""
+ """
+ 执行数据库领域动作。
+
+ :param action_id: 动作唯一标识
+ :param parameters: 分派给目标命令的参数
+ :return: 所选数据库操作的执行结果
+ """
if action_id == 'db-upgrade-dry-run':
return await asyncio.to_thread(
self.database_runtime.upgrade_database,
@@ -153,7 +188,12 @@ async def _dispatch_database(self, action_id: str, parameters: dict[str, object]
return self._unsupported_action(action_id)
async def _dispatch_ops(self, action_id: str) -> dict[str, Any]:
- """执行运维探活动作。"""
+ """
+ 执行运维探活动作。
+
+ :param action_id: 动作唯一标识
+ :return: 目标服务的连接探测结果
+ """
if action_id == 'ops-ping-db':
return await self.database_runtime.ping_database()
if action_id == 'ops-ping-redis':
@@ -161,7 +201,12 @@ async def _dispatch_ops(self, action_id: str) -> dict[str, Any]:
return self._unsupported_action(action_id)
async def _run_precheck(self, label: str) -> dict[str, Any]:
- """并发执行启动前综合检查。"""
+ """
+ 并发执行启动前综合检查。
+
+ :param label: 显示给用户的标签
+ :return: 包含 ``ok``、``message``、``database``、``redis``、``crypto`` 等字段的数据
+ """
database, redis, crypto, config = await asyncio.gather(
self.database_runtime.ping_database(),
self.operations_runtime.ping_redis(),
@@ -180,7 +225,11 @@ async def _run_precheck(self, label: str) -> dict[str, Any]:
}
async def _install_completion(self) -> dict[str, Any]:
- """在当前进程内安装 shell completion。"""
+ """
+ 在当前进程内安装 shell completion。
+
+ :return: 补全脚本的安装结果
+ """
return await asyncio.to_thread(
self.completion_installer.install_completion_script,
self.application_builder.build(),
@@ -189,7 +238,13 @@ async def _install_completion(self) -> dict[str, Any]:
)
async def _dispatch_crypto(self, action_id: str, parameters: dict[str, object]) -> dict[str, Any]:
- """执行传输加密领域动作。"""
+ """
+ 执行传输加密领域动作。
+
+ :param action_id: 动作唯一标识
+ :param parameters: 分派给目标命令的参数
+ :return: 所选密钥操作的执行结果
+ """
timestamp = TimezoneUtil.to_business_time(TimezoneUtil.utc_now()).strftime('%Y%m%d%H%M%S')
key_size = int(parameters.get('key_size') or 2048)
if action_id == 'crypto-keygen':
@@ -208,7 +263,12 @@ async def _dispatch_crypto(self, action_id: str, parameters: dict[str, object])
@staticmethod
def _unsupported_action(action_id: str) -> dict[str, Any]:
- """构建未知动作的失败结果,禁止隐式回退到其他操作。"""
+ """
+ 构建未知动作的失败结果,禁止隐式回退到其他操作。
+
+ :param action_id: 动作唯一标识
+ :return: 未知动作的失败结果
+ """
return {
'ok': False,
'message': f'不支持的 TUI 动作:{action_id}',
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/factories/cache.py b/ruoyi-fastapi-backend/cli/tui/actions/factories/cache.py
index e32b4caaf..097e5ca12 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/factories/cache.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/factories/cache.py
@@ -13,7 +13,7 @@ class CacheActionTemplateFactory:
该对象负责生成缓存浏览页相关动作模板,统一缓存清理预演和预热动作
的参数与预览摘要构建。
- :param support: 动作模板共享构建支持
+ :ivar support: 动作模板共享构建支持
"""
support: TuiActionTemplateSupport
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/factories/gen.py b/ruoyi-fastapi-backend/cli/tui/actions/factories/gen.py
index 140ff56e7..3a0b5e6ff 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/factories/gen.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/factories/gen.py
@@ -13,7 +13,7 @@ class GenActionTemplateFactory:
该对象负责生成代码生成浏览页相关动作模板,统一记录标题提取、
导出预演和表结构同步动作的构建逻辑。
- :param support: 动作模板共享构建支持
+ :ivar support: 动作模板共享构建支持
"""
support: TuiActionTemplateSupport
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/factories/jobs.py b/ruoyi-fastapi-backend/cli/tui/actions/factories/jobs.py
index f375a1248..2b2a994eb 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/factories/jobs.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/factories/jobs.py
@@ -13,7 +13,7 @@ class JobActionTemplateFactory:
该对象负责生成任务浏览页相关动作模板,收口任务 ID 解析、
暂停/恢复切换和摘要拼装逻辑。
- :param support: 动作模板共享构建支持
+ :ivar support: 动作模板共享构建支持
"""
support: TuiActionTemplateSupport
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/factories/static.py b/ruoyi-fastapi-backend/cli/tui/actions/factories/static.py
index b41bdf370..62b5ce87d 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/factories/static.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/factories/static.py
@@ -13,7 +13,7 @@ class StaticActionTemplateFactory:
该对象负责生成不依赖当前记录内容的页面动作模板,统一详情页和
部分浏览页的固定动作定义。
- :param support: 动作模板共享构建支持
+ :ivar support: 动作模板共享构建支持
"""
support: TuiActionTemplateSupport
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/models.py b/ruoyi-fastapi-backend/cli/tui/actions/models.py
index 447a6f990..3a7791fc9 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/models.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/models.py
@@ -15,12 +15,12 @@ class TuiActionSpec:
"""
TUI 低风险动作定义。
- :param action_id: 动作唯一标识
- :param label: 动作显示名称
- :param parameters: 进程内运行时调用参数
- :param preview_title: 预览弹窗标题
- :param preview_lines: 预览摘要文本
- :param refresh_view: 执行完成后是否刷新当前页面
+ :ivar action_id: 动作唯一标识
+ :ivar label: 动作显示名称
+ :ivar parameters: 进程内运行时调用参数
+ :ivar preview_title: 预览弹窗标题
+ :ivar preview_lines: 预览摘要文本
+ :ivar refresh_view: 执行完成后是否刷新当前页面
"""
action_id: str
@@ -36,8 +36,8 @@ class TuiActionResult:
"""
TUI 动作执行结果。
- :param spec: 动作定义
- :param payload: CLI JSON 负载
+ :ivar spec: 动作定义
+ :ivar payload: CLI JSON 负载
"""
spec: TuiActionSpec
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/presentation.py b/ruoyi-fastapi-backend/cli/tui/actions/presentation.py
index e4cd232f4..9063c4b41 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/presentation.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/presentation.py
@@ -16,6 +16,9 @@ class TuiActionPresentationService:
该对象负责动作提示、动作列表和动作结果通知等展示层文本构建,
避免继续保留模块级桥接函数。
+
+ :ivar capability_registry: TUI 页面能力注册表
+ :ivar action_registry: TUI 动作注册表
"""
capability_registry: TuiCapabilityRegistry
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/registry.py b/ruoyi-fastapi-backend/cli/tui/actions/registry.py
index 2f2f396e4..1a35d99ae 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/registry.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/registry.py
@@ -11,10 +11,10 @@ class TuiActionSlotResolver:
TUI 动作槽位解析器。
该对象将一个页面支持的槽位动作集中定义为映射关系,避免继续在
- `resolve_*_action` 中堆叠条件分支。
+ ``resolve_*_action`` 中堆叠条件分支。
- :param slot_templates: 槽位到动作模板的映射
- :param spec_factory: 动作规格构建器
+ :ivar slot_templates: 槽位到动作模板的映射
+ :ivar spec_factory: 动作规格构建器
"""
slot_templates: dict[ActionSlot, TuiActionTemplate]
@@ -49,8 +49,8 @@ class TuiActionRegistry:
该注册表负责集中维护浏览页和详情页的动作解析器,从而将
原本散落的条件分发收敛为可声明的映射关系。
- :param browser_resolvers: 浏览页动作槽位解析器映射
- :param detail_resolvers: 详情页动作槽位解析器映射
+ :ivar browser_resolvers: 浏览页动作槽位解析器映射
+ :ivar detail_resolvers: 详情页动作槽位解析器映射
"""
browser_resolvers: dict[str, TuiActionSlotResolver]
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/__init__.py b/ruoyi-fastapi-backend/cli/tui/adapters/__init__.py
index d671ae6db..b45234a8e 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/__init__.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/__init__.py
@@ -32,7 +32,7 @@ class TuiSnapshotCollectorRegistry:
该对象集中维护页面视图标识与其采集函数之间的映射,
使应用层和测试层可以通过统一入口发现当前可用的采集器。
- :param collectors: 视图到采集函数的映射
+ :ivar collectors: 视图到采集函数的映射
"""
collectors: dict[str, SnapshotCollector]
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/app.py b/ruoyi-fastapi-backend/cli/tui/adapters/app.py
index fa5a02c5b..8a5ecc5e0 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/app.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/app.py
@@ -21,13 +21,13 @@ class AppDetailSourcePayloads:
"""
应用详情页原始数据源快照。
- :param env_payload: `app env` 结果
- :param config_payload: `app config` 结果
- :param doctor_payload: `app doctor` 结果
- :param routes_payload: `app routes` 结果
- :param completion_payload: `completion doctor` 结果
- :param completion_preview_result: `completion show` 命令结果
- :param preview_shell: 当前补全脚本预览 shell
+ :ivar env_payload: ``app env`` 结果
+ :ivar config_payload: ``app config`` 结果
+ :ivar doctor_payload: ``app doctor`` 结果
+ :ivar routes_payload: ``app routes`` 结果
+ :ivar completion_payload: ``completion doctor`` 结果
+ :ivar completion_preview_result: ``completion show`` 命令结果
+ :ivar preview_shell: 当前补全脚本预览 shell
"""
env_payload: dict[str, Any] | None
@@ -44,9 +44,10 @@ class AppDetailSnapshotCollector:
应用详情页数据采集器。
该对象负责拉取应用详情页所需的多路 CLI 原始结果,
- 让 `AppDetailAdapter` 保持详情页编排职责。
+ 让 ``AppDetailAdapter`` 保持详情页编排职责。
- :param section_builder: 应用详情分区构建器
+ :ivar section_builder: 应用详情分区构建器
+ :ivar query_service: TUI 进程内查询服务
"""
def __init__(
@@ -57,8 +58,8 @@ def __init__(
"""
初始化应用详情页数据采集器。
+ :param query_service: TUI 进程内查询服务
:param section_builder: 应用详情分区构建器
- :return: None
"""
self.section_builder = section_builder
self.query_service = query_service or TUI_RUNTIME_QUERIES
@@ -103,7 +104,7 @@ def resolve_completion_preview_shell(payload: dict[str, Any] | None) -> str:
"""
解析补全脚本预览应使用的 shell。
- :param payload: `completion doctor` JSON 负载
+ :param payload: ``completion doctor`` JSON 负载
:return: shell 名称
"""
if not isinstance(payload, dict):
@@ -123,7 +124,7 @@ def build_env_section(payload: dict[str, Any] | None) -> DetailSectionSnapshot:
"""
构建应用环境解析分区。
- :param payload: `app env` JSON 负载
+ :param payload: ``app env`` JSON 负载
:return: 分区快照
"""
runtime = payload.get('runtime') if isinstance(payload, dict) else None
@@ -157,7 +158,7 @@ def build_config_section(payload: dict[str, Any] | None) -> DetailSectionSnapsho
"""
构建应用基础配置分区。
- :param payload: `app config` JSON 负载
+ :param payload: ``app config`` JSON 负载
:return: 分区快照
"""
config = payload.get('config') if isinstance(payload, dict) else None
@@ -192,7 +193,7 @@ def build_dependency_section(payload: dict[str, Any] | None) -> DetailSectionSna
"""
构建应用依赖配置分区。
- :param payload: `app config` JSON 负载
+ :param payload: ``app config`` JSON 负载
:return: 分区快照
"""
config = payload.get('config') if isinstance(payload, dict) else None
@@ -224,7 +225,7 @@ def build_routes_section(self, payload: dict[str, Any] | None) -> DetailSectionS
"""
构建应用路由摘要分区。
- :param payload: `app routes` JSON 负载
+ :param payload: ``app routes`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -290,7 +291,7 @@ def build_completion_section(payload: dict[str, Any] | None) -> DetailSectionSna
"""
构建 shell completion 诊断分区。
- :param payload: `completion doctor` JSON 负载
+ :param payload: ``completion doctor`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -356,7 +357,7 @@ def build_completion_preview_section(
构建补全脚本预览分区。
:param shell: 当前预览 shell
- :param preview_result: `completion show` 调用结果
+ :param preview_result: ``completion show`` 调用结果
:return: 分区快照
"""
stdout = str(getattr(preview_result, 'stdout', '') or '').strip()
@@ -404,7 +405,7 @@ def build_doctor_section(payload: dict[str, Any] | None) -> DetailSectionSnapsho
"""
构建应用启动前检查分区。
- :param payload: `app doctor` JSON 负载
+ :param payload: ``app doctor`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict):
@@ -479,11 +480,11 @@ def build_overview_section(
"""
构建应用页总览判断分区。
- :param env_payload: `app env` JSON 负载
- :param config_payload: `app config` JSON 负载
- :param doctor_payload: `app doctor` JSON 负载
- :param routes_payload: `app routes` JSON 负载
- :param completion_payload: `completion doctor` JSON 负载
+ :param env_payload: ``app env`` JSON 负载
+ :param config_payload: ``app config`` JSON 负载
+ :param doctor_payload: ``app doctor`` JSON 负载
+ :param routes_payload: ``app routes`` JSON 负载
+ :param completion_payload: ``completion doctor`` JSON 负载
:return: 分区快照
"""
env_ok = bool(isinstance(env_payload, dict) and env_payload.get('ok', False))
@@ -556,12 +557,12 @@ def build_sections(
"""
构建应用页全部详情分区。
- :param env_payload: `app env` 结果负载
- :param config_payload: `app config` 结果负载
- :param doctor_payload: `app doctor` 结果负载
- :param routes_payload: `app routes` 结果负载
- :param completion_payload: `completion doctor` 结果负载
- :param completion_preview_result: `completion show` 命令结果
+ :param env_payload: ``app env`` 结果负载
+ :param config_payload: ``app config`` 结果负载
+ :param doctor_payload: ``app doctor`` 结果负载
+ :param routes_payload: ``app routes`` 结果负载
+ :param completion_payload: ``completion doctor`` 结果负载
+ :param completion_preview_result: ``completion show`` 命令结果
:param preview_shell: 当前预览 shell
:return: 详情分区列表
"""
@@ -591,6 +592,9 @@ class AppDetailAdapter(BaseDetailAdapter):
该适配器负责采集应用相关 CLI 结果,并委托分区构建器组装为
TUI 详情页快照。
+
+ :ivar section_builder: 应用详情分区构建器
+ :ivar snapshot_collector: 应用详情页数据采集器
"""
def __init__(
@@ -603,7 +607,6 @@ def __init__(
:param section_builder: 应用详情分区构建器
:param snapshot_collector: 应用详情页数据采集器
- :return: None
"""
super().__init__(
page_title='应用',
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/base.py b/ruoyi-fastapi-backend/cli/tui/adapters/base.py
index 5e3308d6e..ab3b5b616 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/base.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/base.py
@@ -15,9 +15,9 @@ class BaseBrowserAdapter:
"""
TUI 浏览页适配基类。
- :param page_title: 浏览页标题
- :param search_view_key: 搜索上下文对应的页面键
- :param filter_options: 页面支持的筛选项
+ :ivar page_title: 浏览页标题
+ :ivar search_view_key: 搜索上下文对应的页面键
+ :ivar filter_options: 页面支持的筛选项
"""
def __init__(
@@ -33,7 +33,6 @@ def __init__(
:param page_title: 浏览页标题
:param search_view_key: 搜索上下文对应的页面键
:param filter_options: 页面支持的筛选项
- :return: None
"""
self.page_title = page_title
self.search_view_key = search_view_key
@@ -171,9 +170,9 @@ class BaseDetailAdapter:
"""
TUI 详情页适配基类。
- :param page_title: 详情页标题
- :param search_view_key: 搜索上下文对应的页面键
- :param default_suggestions: 默认搜索建议
+ :ivar page_title: 详情页标题
+ :ivar search_view_key: 搜索上下文对应的页面键
+ :ivar default_suggestions: 默认搜索建议
"""
def __init__(
@@ -189,7 +188,6 @@ def __init__(
:param page_title: 详情页标题
:param search_view_key: 搜索上下文对应的页面键
:param default_suggestions: 默认搜索建议
- :return: None
"""
self.page_title = page_title
self.search_view_key = search_view_key
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/cache.py b/ruoyi-fastapi-backend/cli/tui/adapters/cache.py
index 91e980470..0a10bdea3 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/cache.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/cache.py
@@ -27,7 +27,7 @@ def extract_cache_name_rows(payload: dict[str, Any] | None) -> list[dict[str, An
"""
从缓存统计结果中提取缓存名称列表。
- :param payload: `cache stats` JSON 负载
+ :param payload: ``cache stats`` JSON 负载
:return: 缓存名称行列表
"""
if not isinstance(payload, dict):
@@ -52,8 +52,9 @@ class CacheSectionBuilder:
该构建器负责构建缓存浏览页共享分区,以及单个缓存名前缀下的键摘要、
键列表和键详情分区。
- :param page_adapter: 缓存浏览页适配器
- :param row_extractor: 缓存浏览行提取器
+ :ivar page_adapter: 缓存浏览页适配器
+ :ivar row_extractor: 缓存浏览行提取器
+ :ivar query_service: TUI 进程内查询服务
"""
def __init__(
@@ -65,9 +66,9 @@ def __init__(
"""
初始化缓存浏览页分区构建器。
+ :param query_service: TUI 进程内查询服务
:param page_adapter: 缓存浏览页适配器
:param row_extractor: 缓存浏览行提取器
- :return: None
"""
self.page_adapter = page_adapter
self.row_extractor = row_extractor or CacheRowExtractor()
@@ -77,7 +78,7 @@ def build_overview_section(self, payload: dict[str, Any] | None) -> DetailSectio
"""
构建缓存总览共享分区。
- :param payload: `cache stats` JSON 负载
+ :param payload: ``cache stats`` JSON 负载
:return: 分区快照
"""
info = payload.get('info') if isinstance(payload, dict) and isinstance(payload.get('info'), dict) else {}
@@ -105,7 +106,7 @@ def build_overview_judgement_section(
"""
构建缓存页总览判断共享分区。
- :param payload: `cache stats` JSON 负载
+ :param payload: ``cache stats`` JSON 负载
:param filtered_rows: 当前筛选后的缓存名列表
:return: 分区快照
"""
@@ -151,7 +152,7 @@ def build_top_commands_section(self, payload: dict[str, Any] | None) -> DetailSe
"""
构建缓存命令统计共享分区。
- :param payload: `cache stats` JSON 负载
+ :param payload: ``cache stats`` JSON 负载
:return: 分区快照
"""
command_stats = payload.get('commandStats') if isinstance(payload, dict) else None
@@ -195,7 +196,7 @@ def build_keys_summary_section(self, payload: dict[str, Any] | None) -> DetailSe
"""
构建缓存键摘要分区。
- :param payload: `cache keys` JSON 负载
+ :param payload: ``cache keys`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -229,7 +230,7 @@ def build_keys_section(self, payload: dict[str, Any] | None) -> DetailSectionSna
"""
构建缓存键列表分区。
- :param payload: `cache keys` JSON 负载
+ :param payload: ``cache keys`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -258,7 +259,7 @@ def render_ttl_text(self, payload: dict[str, Any] | None) -> str:
"""
渲染缓存 TTL 文本。
- :param payload: `cache ttl` JSON 负载
+ :param payload: ``cache ttl`` JSON 负载
:return: TTL 文本
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -375,7 +376,7 @@ def build_shared_sections(
"""
构建缓存浏览页共享分区。
- :param payload: `cache stats` 结果负载
+ :param payload: ``cache stats`` 结果负载
:param filtered_rows: 当前筛选后的缓存名列表
:return: 共享分区列表
"""
@@ -393,8 +394,8 @@ class CacheRecordBuilder:
该对象负责构建缓存页单条浏览记录与失败兜底记录。
- :param page_adapter: 缓存浏览页适配器
- :param section_builder: 缓存浏览页分区构建器
+ :ivar page_adapter: 缓存浏览页适配器
+ :ivar section_builder: 缓存浏览页分区构建器
"""
def __init__(
@@ -407,7 +408,6 @@ def __init__(
:param page_adapter: 缓存浏览页适配器
:param section_builder: 缓存浏览页分区构建器
- :return: None
"""
self.page_adapter = page_adapter
self.section_builder = section_builder
@@ -459,6 +459,11 @@ class CacheBrowserAdapter(BaseBrowserAdapter):
该适配器负责采集 Redis 统计和缓存名前缀列表,并委托协作对象构建
共享分区、单条记录与键详情分区。
+
+ :ivar row_extractor: 缓存浏览行提取器
+ :ivar query_service: TUI 进程内查询服务
+ :ivar section_builder: 缓存浏览页分区构建器
+ :ivar record_builder: 缓存浏览记录构建器
"""
def __init__(
@@ -471,10 +476,10 @@ def __init__(
"""
初始化缓存浏览页适配器。
+ :param query_service: TUI 进程内查询服务
:param row_extractor: 缓存浏览行提取器
:param section_builder: 缓存浏览页分区构建器
:param record_builder: 缓存浏览记录构建器
- :return: None
"""
super().__init__(
page_title='缓存',
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/configs.py b/ruoyi-fastapi-backend/cli/tui/adapters/configs.py
index ae4782d03..62e2ea778 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/configs.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/configs.py
@@ -49,7 +49,7 @@ def extract_config_issue_keys(payload: dict[str, Any] | None, field_name: str) -
"""
从配置巡检结果中提取指定风险字段对应的配置键集合。
- :param payload: `config doctor` JSON 负载
+ :param payload: ``config doctor`` JSON 负载
:param field_name: 风险字段名
:return: 配置键集合
"""
@@ -62,7 +62,7 @@ def build_config_risk_sets(self, payload: dict[str, Any] | None) -> dict[str, se
"""
构建配置风险分类集合。
- :param payload: `config doctor` JSON 负载
+ :param payload: ``config doctor`` JSON 负载
:return: 按风险分类聚合的配置键集合
"""
return {
@@ -190,8 +190,9 @@ class ConfigSectionBuilder:
该构建器负责构建参数配置页共享分区,以及单个配置项详情分区。
- :param page_adapter: 参数配置浏览页适配器
- :param risk_support: 参数配置风险分类支持对象
+ :ivar page_adapter: 参数配置浏览页适配器
+ :ivar risk_support: 参数配置风险分类支持对象
+ :ivar query_service: TUI 进程内查询服务
"""
def __init__(
@@ -203,9 +204,9 @@ def __init__(
"""
初始化参数配置浏览页分区构建器。
+ :param query_service: TUI 进程内查询服务
:param page_adapter: 参数配置浏览页适配器
:param risk_support: 参数配置风险分类支持对象
- :return: None
"""
self.page_adapter = page_adapter
self.risk_support = risk_support
@@ -215,7 +216,7 @@ def build_config_doctor_section(self, payload: dict[str, Any] | None) -> DetailS
"""
构建参数配置巡检共享分区。
- :param payload: `config doctor` JSON 负载
+ :param payload: ``config doctor`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -243,7 +244,7 @@ def build_config_issue_samples_section(self, payload: dict[str, Any] | None) ->
"""
构建参数配置不一致样本共享分区。
- :param payload: `config doctor` JSON 负载
+ :param payload: ``config doctor`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -419,7 +420,7 @@ def build_config_consistency_section(self, payload: dict[str, Any] | None) -> De
"""
构建单个配置的一致性分区。
- :param payload: `config get` JSON 负载
+ :param payload: ``config get`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -524,8 +525,8 @@ class ConfigRecordBuilder:
该构建器负责构建配置浏览记录与失败兜底记录。
- :param page_adapter: 参数配置浏览页适配器
- :param section_builder: 参数配置浏览页分区构建器
+ :ivar page_adapter: 参数配置浏览页适配器
+ :ivar section_builder: 参数配置浏览页分区构建器
"""
def __init__(
@@ -538,7 +539,6 @@ def __init__(
:param page_adapter: 参数配置浏览页适配器
:param section_builder: 参数配置浏览页分区构建器
- :return: None
"""
self.page_adapter = page_adapter
self.section_builder = section_builder
@@ -608,9 +608,10 @@ class ConfigsBrowserAdapter(BaseBrowserAdapter):
该适配器负责采集配置巡检、配置列表和单项配置详情,并统一完成
风险分类、筛选排序、共享分区构建与浏览记录装配。
- :param risk_support: 参数配置风险分类支持对象
- :param section_builder: 参数配置浏览页分区构建器
- :param record_builder: 参数配置浏览记录构建器
+ :ivar risk_support: 参数配置风险分类支持对象
+ :ivar query_service: TUI 进程内查询服务
+ :ivar section_builder: 参数配置浏览页分区构建器
+ :ivar record_builder: 参数配置浏览记录构建器
"""
def __init__(
@@ -623,10 +624,10 @@ def __init__(
"""
初始化参数配置浏览页适配器。
+ :param query_service: TUI 进程内查询服务
:param risk_support: 参数配置风险分类支持对象
:param section_builder: 参数配置浏览页分区构建器
:param record_builder: 参数配置浏览记录构建器
- :return: None
"""
super().__init__(
page_title='参数配置',
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/crypto.py b/ruoyi-fastapi-backend/cli/tui/adapters/crypto.py
index de8c67602..e4e6bf40d 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/crypto.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/crypto.py
@@ -19,8 +19,8 @@ class CryptoDetailSourcePayloads:
"""
传输加密详情页原始数据源快照。
- :param validate_payload: `crypto validate` 结果
- :param public_payload: `crypto export-public` 结果
+ :ivar validate_payload: ``crypto validate`` 结果
+ :ivar public_payload: ``crypto export-public`` 结果
"""
validate_payload: dict[str, Any] | None
@@ -32,10 +32,17 @@ class CryptoDetailSnapshotCollector:
传输加密详情页数据采集器。
该对象负责拉取传输加密详情页所需的 CLI 原始结果,
- 让 `CryptoDetailAdapter` 保持详情页编排职责。
+ 让 ``CryptoDetailAdapter`` 保持详情页编排职责。
+
+ :ivar query_service: TUI 进程内查询服务
"""
def __init__(self, query_service: TuiRuntimeQueryService | None = None) -> None:
+ """
+ 保存加密详情页使用的运行时查询服务。
+
+ :param query_service: TUI 进程内查询服务
+ """
self.query_service = query_service or TUI_RUNTIME_QUERIES
async def collect(self, env: str) -> CryptoDetailSourcePayloads:
@@ -68,7 +75,7 @@ def build_validate_section(payload: dict[str, Any] | None) -> DetailSectionSnaps
"""
构建传输加密运行校验分区。
- :param payload: `crypto validate` JSON 负载
+ :param payload: ``crypto validate`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict):
@@ -97,7 +104,7 @@ def build_public_identity_section(payload: dict[str, Any] | None) -> DetailSecti
"""
构建公钥身份分区。
- :param payload: `crypto export-public` JSON 负载
+ :param payload: ``crypto export-public`` JSON 负载
:return: 分区快照
"""
public_key_payload = payload.get('publicKey') if isinstance(payload, dict) else None
@@ -124,7 +131,7 @@ def build_supported_kids_section(payload: dict[str, Any] | None) -> DetailSectio
"""
构建兼容版本分区。
- :param payload: `crypto export-public` JSON 负载
+ :param payload: ``crypto export-public`` JSON 负载
:return: 分区快照
"""
public_key_payload = payload.get('publicKey') if isinstance(payload, dict) else None
@@ -155,7 +162,7 @@ def build_public_preview_section(self, payload: dict[str, Any] | None) -> Detail
"""
构建公钥预览分区。
- :param payload: `crypto export-public` JSON 负载
+ :param payload: ``crypto export-public`` JSON 负载
:return: 分区快照
"""
public_key_payload = payload.get('publicKey') if isinstance(payload, dict) else None
@@ -193,8 +200,8 @@ def build_overview_section(
"""
构建加密页总览判断分区。
- :param validate_payload: `crypto validate` JSON 负载
- :param public_payload: `crypto export-public` JSON 负载
+ :param validate_payload: ``crypto validate`` JSON 负载
+ :param public_payload: ``crypto export-public`` JSON 负载
:return: 分区快照
"""
validate_ok = bool(isinstance(validate_payload, dict) and validate_payload.get('ok', False))
@@ -287,8 +294,8 @@ def build_sections(
"""
构建传输加密页全部详情分区。
- :param validate_payload: `crypto validate` 结果负载
- :param public_payload: `crypto export-public` 结果负载
+ :param validate_payload: ``crypto validate`` 结果负载
+ :param public_payload: ``crypto export-public`` 结果负载
:param env: 当前运行环境
:return: 详情分区列表
"""
@@ -310,7 +317,8 @@ class CryptoDetailAdapter(BaseDetailAdapter):
该适配器负责采集传输加密相关 CLI 结果,并组装为 TUI 详情页快照。
页面私有的解析逻辑、分区构建逻辑和快照采集流程统一收口在该类中。
- :param section_builder: 传输加密详情分区构建器
+ :ivar section_builder: 传输加密详情分区构建器
+ :ivar snapshot_collector: 传输加密详情页数据采集器
"""
def __init__(
@@ -323,7 +331,6 @@ def __init__(
:param section_builder: 传输加密详情分区构建器
:param snapshot_collector: 传输加密详情页数据采集器
- :return: None
"""
super().__init__(
page_title='传输加密',
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/database.py b/ruoyi-fastapi-backend/cli/tui/adapters/database.py
index 9a0f4ad6e..081325d5f 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/database.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/database.py
@@ -19,11 +19,11 @@ class DatabaseDetailSourcePayloads:
"""
数据库详情页原始数据源快照。
- :param revision_payload: `db current` 结果
- :param check_payload: `db check` 结果
- :param heads_payload: `db heads` 结果
- :param history_payload: `db history` 结果
- :param config_payload: `app config` 结果
+ :ivar revision_payload: ``db current`` 结果
+ :ivar check_payload: ``db check`` 结果
+ :ivar heads_payload: ``db heads`` 结果
+ :ivar history_payload: ``db history`` 结果
+ :ivar config_payload: ``app config`` 结果
"""
revision_payload: dict[str, Any] | None
@@ -38,7 +38,9 @@ class DatabaseDetailSnapshotCollector:
数据库详情页数据采集器。
该对象负责拉取数据库详情页所需的多路 CLI 原始结果,
- 让 `DatabaseDetailAdapter` 保持详情页编排职责。
+ 让 ``DatabaseDetailAdapter`` 保持详情页编排职责。
+
+ :ivar query_service: TUI 进程内查询服务
"""
def __init__(self, query_service: TuiRuntimeQueryService | None = None) -> None:
@@ -46,7 +48,6 @@ def __init__(self, query_service: TuiRuntimeQueryService | None = None) -> None:
初始化数据库详情页数据采集器。
:param query_service: TUI 进程内查询服务
- :return: None
"""
self.query_service = query_service or TUI_RUNTIME_QUERIES
@@ -86,7 +87,7 @@ def extract_revision_items(payload: dict[str, Any] | None) -> list[dict[str, Any
"""
从 Alembic 结果中提取修订版本列表。
- :param payload: `db heads` 或 `db history` JSON 负载
+ :param payload: ``db heads`` 或 ``db history`` JSON 负载
:return: 修订版本列表
"""
items = payload.get('items') if isinstance(payload, dict) else None
@@ -121,7 +122,7 @@ def build_revision_section(payload: dict[str, Any] | None) -> DetailSectionSnaps
"""
构建数据库迁移状态分区。
- :param payload: `db current` JSON 负载
+ :param payload: ``db current`` JSON 负载
:return: 分区快照
"""
current_revision = payload.get('currentRevision', '-') if isinstance(payload, dict) else '-'
@@ -155,10 +156,10 @@ def build_overview_section(
"""
构建数据库页总览判断分区。
- :param revision_payload: `db current` JSON 负载
- :param check_payload: `db check` JSON 负载
- :param heads_payload: `db heads` JSON 负载
- :param history_payload: `db history` JSON 负载
+ :param revision_payload: ``db current`` JSON 负载
+ :param check_payload: ``db check`` JSON 负载
+ :param heads_payload: ``db heads`` JSON 负载
+ :param history_payload: ``db history`` JSON 负载
:return: 分区快照
"""
revision_ok = bool(isinstance(revision_payload, dict) and revision_payload.get('ok', False))
@@ -200,7 +201,7 @@ def build_profile_section(payload: dict[str, Any] | None) -> DetailSectionSnapsh
"""
构建数据库连接配置分区。
- :param payload: `app config` JSON 负载
+ :param payload: ``app config`` JSON 负载
:return: 分区快照
"""
config = payload.get('config') if isinstance(payload, dict) else None
@@ -228,7 +229,7 @@ def build_check_section(payload: dict[str, Any] | None) -> DetailSectionSnapshot
"""
构建数据库连通性检查分区。
- :param payload: `db check` JSON 负载
+ :param payload: ``db check`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -255,7 +256,7 @@ def build_heads_section(self, payload: dict[str, Any] | None) -> DetailSectionSn
"""
构建 Alembic heads 分区。
- :param payload: `db heads` JSON 负载
+ :param payload: ``db heads`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -292,7 +293,7 @@ def build_history_section(self, payload: dict[str, Any] | None) -> DetailSection
"""
构建 Alembic 历史版本分区。
- :param payload: `db history` JSON 负载
+ :param payload: ``db history`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -372,11 +373,11 @@ def build_sections(
"""
构建数据库页全部详情分区。
- :param revision_payload: `db current` 结果负载
- :param check_payload: `db check` 结果负载
- :param heads_payload: `db heads` 结果负载
- :param history_payload: `db history` 结果负载
- :param config_payload: `app config` 结果负载
+ :param revision_payload: ``db current`` 结果负载
+ :param check_payload: ``db check`` 结果负载
+ :param heads_payload: ``db heads`` 结果负载
+ :param history_payload: ``db history`` 结果负载
+ :param config_payload: ``app config`` 结果负载
:return: 详情分区列表
"""
return [
@@ -398,7 +399,8 @@ class DatabaseDetailAdapter(BaseDetailAdapter):
该适配器负责采集数据库相关 CLI 结果,并组装为 TUI 详情页快照。
页面私有的解析逻辑、分区构建逻辑和快照采集流程统一收口在该类中。
- :param section_builder: 数据库详情分区构建器
+ :ivar section_builder: 数据库详情分区构建器
+ :ivar snapshot_collector: 数据库详情页数据采集器
"""
def __init__(
@@ -411,7 +413,6 @@ def __init__(
:param section_builder: 数据库详情分区构建器
:param snapshot_collector: 数据库详情页数据采集器
- :return: None
"""
super().__init__(
page_title='数据库',
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/gen.py b/ruoyi-fastapi-backend/cli/tui/adapters/gen.py
index 9ee7589a5..c424c637b 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/gen.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/gen.py
@@ -39,8 +39,9 @@ class GenSectionBuilder:
该构建器负责构建代码生成页共享分区,以及单条业务表详情分区。
- :param page_adapter: 代码生成浏览页适配器
- :param rendering: 代码生成浏览页渲染支持对象
+ :ivar page_adapter: 代码生成浏览页适配器
+ :ivar rendering: 代码生成浏览页渲染支持对象
+ :ivar query_service: TUI 进程内查询服务
"""
def __init__(
@@ -52,9 +53,9 @@ def __init__(
"""
初始化代码生成浏览页分区构建器。
+ :param query_service: TUI 进程内查询服务
:param page_adapter: 代码生成浏览页适配器
:param rendering: 代码生成浏览页渲染支持对象
- :return: None
"""
self.page_adapter = page_adapter
self.rendering = rendering
@@ -64,7 +65,7 @@ def build_gen_focus_section(self, payload: dict[str, Any] | None) -> DetailSecti
"""
构建业务表概览分区。
- :param payload: `gen detail` JSON 负载
+ :param payload: ``gen detail`` JSON 负载
:return: 分区快照
"""
detail = payload.get('detail') if isinstance(payload, dict) else None
@@ -89,7 +90,7 @@ def build_gen_generation_section(self, payload: dict[str, Any] | None) -> Detail
"""
构建代码生成配置分区。
- :param payload: `gen detail` JSON 负载
+ :param payload: ``gen detail`` JSON 负载
:return: 分区快照
"""
detail = payload.get('detail') if isinstance(payload, dict) else None
@@ -120,7 +121,7 @@ def build_gen_column_summary_section(self, payload: dict[str, Any] | None) -> De
"""
构建字段概览分区。
- :param payload: `gen detail` JSON 负载
+ :param payload: ``gen detail`` JSON 负载
:return: 分区快照
"""
detail = payload.get('detail') if isinstance(payload, dict) else None
@@ -151,7 +152,7 @@ def build_gen_columns_section(self, payload: dict[str, Any] | None) -> DetailSec
"""
构建业务表字段分区。
- :param payload: `gen detail` JSON 负载
+ :param payload: ``gen detail`` JSON 负载
:return: 分区快照
"""
detail = payload.get('detail') if isinstance(payload, dict) else None
@@ -197,8 +198,8 @@ def build_gen_precheck_section(
"""
构建代码生成前校验分区。
- :param detail_payload: `gen detail` JSON 负载
- :param preview_payload: `gen preview` JSON 负载
+ :param detail_payload: ``gen detail`` JSON 负载
+ :param preview_payload: ``gen preview`` JSON 负载
:return: 分区快照
"""
detail = detail_payload.get('detail') if isinstance(detail_payload, dict) else None
@@ -256,7 +257,7 @@ def build_gen_sync_precheck_section(
构建数据库表结构同步前检查分区。
:param table_name: 业务表名称
- :param payload: `gen db-list --table-name=...` JSON 负载
+ :param payload: ``gen db-list --table-name=...`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -305,7 +306,7 @@ def build_gen_preview_section(self, payload: dict[str, Any] | None) -> DetailSec
"""
构建代码预览分区。
- :param payload: `gen preview` JSON 负载
+ :param payload: ``gen preview`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -352,7 +353,7 @@ def build_gen_export_preview_section(self, payload: dict[str, Any] | None) -> De
"""
构建代码导出预演分区。
- :param payload: `gen export --dry-run` JSON 负载
+ :param payload: ``gen export --dry-run`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -398,7 +399,7 @@ def build_importable_tables_section(self, payload: dict[str, Any] | None) -> Det
"""
构建数据库可导入表共享分区。
- :param payload: `gen db-list` JSON 负载
+ :param payload: ``gen db-list`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict) or not payload.get('ok', False):
@@ -578,8 +579,8 @@ class GenRecordBuilder:
该对象负责构建代码生成页单条业务表浏览记录与失败兜底记录。
- :param page_adapter: 代码生成浏览页适配器
- :param section_builder: 代码生成浏览页分区构建器
+ :ivar page_adapter: 代码生成浏览页适配器
+ :ivar section_builder: 代码生成浏览页分区构建器
"""
def __init__(
@@ -592,7 +593,6 @@ def __init__(
:param page_adapter: 代码生成浏览页适配器
:param section_builder: 代码生成浏览页分区构建器
- :return: None
"""
self.page_adapter = page_adapter
self.section_builder = section_builder
@@ -651,6 +651,11 @@ class GenBrowserAdapter(BaseBrowserAdapter):
该适配器负责采集业务表列表、详情、预览与可导入表清单,并委托
协作对象完成共享分区、详情分区和记录构建。
+
+ :ivar rendering: 代码生成浏览页渲染支持对象
+ :ivar query_service: TUI 进程内查询服务
+ :ivar section_builder: 代码生成浏览页分区构建器
+ :ivar record_builder: 代码生成浏览记录构建器
"""
def __init__(
@@ -663,10 +668,10 @@ def __init__(
"""
初始化代码生成浏览页适配器。
+ :param query_service: TUI 进程内查询服务
:param rendering: 代码生成浏览页渲染支持对象
:param section_builder: 代码生成浏览页分区构建器
:param record_builder: 代码生成浏览记录构建器
- :return: None
"""
super().__init__(
page_title='代码生成',
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/health.py b/ruoyi-fastapi-backend/cli/tui/adapters/health.py
index 687c27fa0..634203a2b 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/health.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/health.py
@@ -19,9 +19,9 @@ class DashboardPanelSnapshot:
"""
TUI 首页单个面板快照。
- :param title: 面板标题
- :param status: 面板状态
- :param lines: 面板正文文本行
+ :ivar title: 面板标题
+ :ivar status: 面板状态
+ :ivar lines: 面板正文文本行
"""
title: str
@@ -34,10 +34,10 @@ class DashboardMetricSnapshot:
"""
TUI 首页单个指标卡快照。
- :param title: 指标标题
- :param value: 指标主值
- :param status: 指标状态
- :param hint: 指标补充说明
+ :ivar title: 指标标题
+ :ivar value: 指标主值
+ :ivar status: 指标状态
+ :ivar hint: 指标补充说明
"""
title: str
@@ -51,8 +51,9 @@ class DashboardSnapshot:
"""
TUI 首页聚合快照。
- :param env: 当前运行环境
- :param panels: 面板列表
+ :ivar env: 当前运行环境
+ :ivar panels: 面板列表
+ :ivar metrics: 当前运行状态的指标
"""
env: str
@@ -65,13 +66,13 @@ class DashboardSourcePayloads:
"""
TUI 首页聚合数据源快照。
- :param app_env_payload: 应用环境结果
- :param app_routes_payload: 应用路由结果
- :param doctor_payload: 应用检查结果
- :param database_payload: 数据库版本结果
- :param cache_payload: 缓存统计结果
- :param deps_payload: 依赖检查结果
- :param server_payload: 服务器摘要结果
+ :ivar app_env_payload: 应用环境结果
+ :ivar app_routes_payload: 应用路由结果
+ :ivar doctor_payload: 应用检查结果
+ :ivar database_payload: 数据库版本结果
+ :ivar cache_payload: 缓存统计结果
+ :ivar deps_payload: 依赖检查结果
+ :ivar server_payload: 服务器摘要结果
"""
app_env_payload: dict[str, Any] | None
@@ -88,10 +89,17 @@ class DashboardSnapshotCollector:
TUI 首页聚合数据采集器。
该对象负责从多路 CLI 命令收集 dashboard 所需原始结果,
- 让 `DashboardAdapter` 保持首页装配职责,而不继续承载所有采集细节。
+ 让 ``DashboardAdapter`` 保持首页装配职责,而不继续承载所有采集细节。
+
+ :ivar query_service: TUI 进程内查询服务
"""
def __init__(self, query_service: TuiRuntimeQueryService | None = None) -> None:
+ """
+ 保存仪表盘使用的运行时查询服务。
+
+ :param query_service: TUI 进程内查询服务
+ """
self.query_service = query_service or TUI_RUNTIME_QUERIES
async def collect(self, env: str) -> DashboardSourcePayloads:
@@ -294,7 +302,7 @@ class DashboardPanelCompressor:
该对象负责将原始多行面板压缩为适合首页展示的统一密度摘要卡。
- :param formatting: 首页仪表盘格式化支持对象
+ :ivar formatting: 首页仪表盘格式化支持对象
"""
def __init__(self, formatting: DashboardFormattingSupport) -> None:
@@ -302,7 +310,6 @@ def __init__(self, formatting: DashboardFormattingSupport) -> None:
初始化首页面板压缩器。
:param formatting: 首页仪表盘格式化支持对象
- :return: None
"""
self.formatting = formatting
@@ -360,7 +367,7 @@ class DashboardPanelBuilder:
该对象负责根据各个 CLI 结果负载构建首页展示面板,并统一风险热区与
建议入口逻辑。
- :param formatting: 首页仪表盘格式化支持对象
+ :ivar formatting: 首页仪表盘格式化支持对象
"""
def __init__(self, formatting: DashboardFormattingSupport) -> None:
@@ -368,7 +375,6 @@ def __init__(self, formatting: DashboardFormattingSupport) -> None:
初始化首页面板构建器。
:param formatting: 首页仪表盘格式化支持对象
- :return: None
"""
self.formatting = formatting
@@ -382,8 +388,8 @@ def build_app_env_panel(
构建应用环境总览面板。
:param env: 当前运行环境
- :param env_payload: `app env` JSON 负载
- :param routes_payload: `app routes` JSON 负载
+ :param env_payload: ``app env`` JSON 负载
+ :param routes_payload: ``app routes`` JSON 负载
:return: 面板快照
"""
runtime = env_payload.get('runtime') if isinstance(env_payload, dict) else None
@@ -420,7 +426,7 @@ def build_health_panel(self, payload: dict[str, Any] | None) -> DashboardPanelSn
"""
构建健康检查面板。
- :param payload: `app doctor` JSON 负载
+ :param payload: ``app doctor`` JSON 负载
:return: 面板快照
"""
if not isinstance(payload, dict):
@@ -602,7 +608,7 @@ def build_database_panel(self, payload: dict[str, Any] | None) -> DashboardPanel
"""
构建数据库状态面板。
- :param payload: `db current` JSON 负载
+ :param payload: ``db current`` JSON 负载
:return: 面板快照
"""
current_revision = payload.get('currentRevision', '-') if isinstance(payload, dict) else '-'
@@ -633,7 +639,7 @@ def build_cache_panel(self, payload: dict[str, Any] | None) -> DashboardPanelSna
"""
构建缓存状态面板。
- :param payload: `cache stats` JSON 负载
+ :param payload: ``cache stats`` JSON 负载
:return: 面板快照
"""
if not isinstance(payload, dict):
@@ -667,7 +673,7 @@ def build_dependency_panel(self, payload: dict[str, Any] | None) -> DashboardPan
"""
构建首页依赖版本摘要面板。
- :param payload: `ops deps` JSON 负载
+ :param payload: ``ops deps`` JSON 负载
:return: 面板快照
"""
if not isinstance(payload, dict):
@@ -706,7 +712,7 @@ def build_server_info_panel(self, payload: dict[str, Any] | None) -> DashboardPa
"""
构建首页服务器概况面板。
- :param payload: `ops server-info` JSON 负载
+ :param payload: ``ops server-info`` JSON 负载
:return: 面板快照
"""
server = payload.get('server') if isinstance(payload, dict) else None
@@ -832,7 +838,7 @@ class DashboardMetricBuilder:
该对象负责根据健康检查、数据库和缓存状态构建首页驾驶舱指标卡。
- :param formatting: 首页仪表盘格式化支持对象
+ :ivar formatting: 首页仪表盘格式化支持对象
"""
def __init__(self, formatting: DashboardFormattingSupport) -> None:
@@ -840,7 +846,6 @@ def __init__(self, formatting: DashboardFormattingSupport) -> None:
初始化首页指标卡构建器。
:param formatting: 首页仪表盘格式化支持对象
- :return: None
"""
self.formatting = formatting
@@ -920,6 +925,12 @@ class DashboardAdapter:
该适配器负责采集应用、健康检查、数据库、缓存与运维只读快照,
并委托面板构建器、指标构建器和压缩器组装首页结果。
+
+ :ivar formatting: 首页仪表盘格式化支持对象
+ :ivar panel_builder: 首页面板构建器
+ :ivar metric_builder: 首页指标卡构建器
+ :ivar panel_compressor: 首页面板压缩器
+ :ivar snapshot_collector: 首页聚合数据采集器
"""
def __init__(
@@ -938,7 +949,6 @@ def __init__(
:param metric_builder: 首页指标卡构建器
:param panel_compressor: 首页面板压缩器
:param snapshot_collector: 首页聚合数据采集器
- :return: None
"""
self.formatting = formatting or DashboardFormattingSupport()
self.panel_builder = panel_builder or DashboardPanelBuilder(self.formatting)
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/jobs.py b/ruoyi-fastapi-backend/cli/tui/adapters/jobs.py
index 6050ee760..5ec74328a 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/jobs.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/jobs.py
@@ -22,7 +22,7 @@ class JobRenderingSupport:
该对象负责状态文本、时间线标记、成功率信号条和失败任务提取等基础
逻辑,供筛选、分区和记录构建复用。
- :param page_adapter: 任务浏览页适配器
+ :ivar page_adapter: 任务浏览页适配器
"""
def __init__(self, page_adapter: BaseBrowserAdapter) -> None:
@@ -30,7 +30,6 @@ def __init__(self, page_adapter: BaseBrowserAdapter) -> None:
初始化任务浏览页渲染支持对象。
:param page_adapter: 任务浏览页适配器
- :return: None
"""
self.page_adapter = page_adapter
@@ -192,8 +191,9 @@ class JobSectionBuilder:
该构建器负责构建任务页共享分区以及单条任务详情分区。
- :param page_adapter: 任务浏览页适配器
- :param rendering: 任务浏览页渲染支持对象
+ :ivar page_adapter: 任务浏览页适配器
+ :ivar rendering: 任务浏览页渲染支持对象
+ :ivar query_service: TUI 进程内查询服务
"""
def __init__(
@@ -205,9 +205,9 @@ def __init__(
"""
初始化任务浏览页分区构建器。
+ :param query_service: TUI 进程内查询服务
:param page_adapter: 任务浏览页适配器
:param rendering: 任务浏览页渲染支持对象
- :return: None
"""
self.page_adapter = page_adapter
self.rendering = rendering
@@ -338,7 +338,7 @@ def build_job_focus_section(self, payload: dict[str, Any] | None) -> DetailSecti
"""
构建任务概览分区。
- :param payload: `job detail` JSON 负载
+ :param payload: ``job detail`` JSON 负载
:return: 分区快照
"""
job = payload.get('job') if isinstance(payload, dict) else None
@@ -365,7 +365,7 @@ def build_job_schedule_section(payload: dict[str, Any] | None) -> DetailSectionS
"""
构建任务调度配置分区。
- :param payload: `job detail` JSON 负载
+ :param payload: ``job detail`` JSON 负载
:return: 分区快照
"""
job = payload.get('job') if isinstance(payload, dict) else None
@@ -393,7 +393,7 @@ def build_job_logs_section(self, payload: dict[str, Any] | None, *, title: str)
"""
构建任务日志分区。
- :param payload: `job logs` JSON 负载
+ :param payload: ``job logs`` JSON 负载
:param title: 分区标题
:return: 分区快照
"""
@@ -523,9 +523,9 @@ class JobRecordBuilder:
该对象负责构建任务页单条浏览记录与失败兜底记录。
- :param page_adapter: 任务浏览页适配器
- :param rendering: 任务浏览页渲染支持对象
- :param section_builder: 任务浏览页分区构建器
+ :ivar page_adapter: 任务浏览页适配器
+ :ivar rendering: 任务浏览页渲染支持对象
+ :ivar section_builder: 任务浏览页分区构建器
"""
def __init__(
@@ -540,7 +540,6 @@ def __init__(
:param page_adapter: 任务浏览页适配器
:param rendering: 任务浏览页渲染支持对象
:param section_builder: 任务浏览页分区构建器
- :return: None
"""
self.page_adapter = page_adapter
self.rendering = rendering
@@ -600,6 +599,12 @@ class JobsBrowserAdapter(BaseBrowserAdapter):
该适配器负责采集任务列表、失败日志和单条任务详情,并委托协作对象
完成过滤、共享分区、详情分区和记录构建。
+
+ :ivar rendering: 任务浏览页渲染支持对象
+ :ivar row_filter: 任务浏览行过滤器
+ :ivar query_service: TUI 进程内查询服务
+ :ivar section_builder: 任务浏览页分区构建器
+ :ivar record_builder: 任务浏览记录构建器
"""
def __init__(
@@ -613,11 +618,11 @@ def __init__(
"""
初始化任务浏览页适配器。
+ :param query_service: TUI 进程内查询服务
:param rendering: 任务浏览页渲染支持对象
:param row_filter: 任务浏览行过滤器
:param section_builder: 任务浏览页分区构建器
:param record_builder: 任务浏览记录构建器
- :return: None
"""
super().__init__(
page_title='任务',
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/models.py b/ruoyi-fastapi-backend/cli/tui/adapters/models.py
index 26d9c333a..1dd99331d 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/models.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/models.py
@@ -11,9 +11,9 @@ class DetailSectionSnapshot:
"""
TUI 详情页单个分区快照。
- :param title: 分区标题
- :param status: 分区状态
- :param lines: 分区正文文本行
+ :ivar title: 分区标题
+ :ivar status: 分区状态
+ :ivar lines: 分区正文文本行
"""
title: str
@@ -26,10 +26,10 @@ class DetailPageSnapshot:
"""
TUI 详情页聚合快照。
- :param title: 页面标题
- :param subtitle: 页面副标题
- :param sections: 页面分区列表
- :param search: 当前页面搜索上下文
+ :ivar title: 页面标题
+ :ivar subtitle: 页面副标题
+ :ivar sections: 页面分区列表
+ :ivar search: 当前页面搜索上下文
"""
title: str
@@ -43,12 +43,14 @@ class BrowserRecordSnapshot:
"""
TUI 浏览页单条记录快照。
- :param key: 记录唯一标识
- :param title: 记录标题
- :param status: 记录状态
- :param summary: 记录摘要
- :param metadata_lines: 记录元信息文本行
- :param detail_sections: 记录联动详情分区列表
+ :ivar key: 记录唯一标识
+ :ivar title: 记录标题
+ :ivar status: 记录状态
+ :ivar summary: 记录摘要
+ :ivar metadata_lines: 记录元信息文本行
+ :ivar detail_sections: 记录联动详情分区列表
+ :ivar detail_loader: 按需加载记录详情的回调
+ :ivar _cached_detail_sections: 已加载的详情分区
"""
key: str
@@ -83,13 +85,13 @@ class BrowserPageSnapshot:
"""
TUI 浏览页聚合快照。
- :param title: 页面标题
- :param subtitle: 页面副标题
- :param records: 可浏览记录列表
- :param shared_sections: 全局共享分区列表
- :param filters: 页面可用筛选项
- :param active_filter_key: 当前激活筛选键
- :param search: 当前页面搜索上下文
+ :ivar title: 页面标题
+ :ivar subtitle: 页面副标题
+ :ivar records: 可浏览记录列表
+ :ivar shared_sections: 全局共享分区列表
+ :ivar filters: 页面可用筛选项
+ :ivar active_filter_key: 当前激活筛选键
+ :ivar search: 当前页面搜索上下文
"""
title: str
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/ops.py b/ruoyi-fastapi-backend/cli/tui/adapters/ops.py
index bfe9068bb..649497e8a 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/ops.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/ops.py
@@ -19,11 +19,11 @@ class OpsDetailSourcePayloads:
"""
运维详情页原始数据源快照。
- :param health_payload: `ops health` 结果
- :param ping_db_payload: `ops ping-db` 结果
- :param ping_redis_payload: `ops ping-redis` 结果
- :param deps_payload: `ops deps` 结果
- :param server_payload: `ops server-info` 结果
+ :ivar health_payload: ``ops health`` 结果
+ :ivar ping_db_payload: ``ops ping-db`` 结果
+ :ivar ping_redis_payload: ``ops ping-redis`` 结果
+ :ivar deps_payload: ``ops deps`` 结果
+ :ivar server_payload: ``ops server-info`` 结果
"""
health_payload: dict[str, Any] | None
@@ -38,10 +38,17 @@ class OpsDetailSnapshotCollector:
运维详情页数据采集器。
该对象负责拉取运维详情页所需的多路 CLI 原始结果,
- 让 `OpsDetailAdapter` 保持详情页编排职责。
+ 让 ``OpsDetailAdapter`` 保持详情页编排职责。
+
+ :ivar query_service: TUI 进程内查询服务
"""
def __init__(self, query_service: TuiRuntimeQueryService | None = None) -> None:
+ """
+ 保存运维详情页使用的运行时查询服务。
+
+ :param query_service: TUI 进程内查询服务
+ """
self.query_service = query_service or TUI_RUNTIME_QUERIES
async def collect(self, env: str) -> OpsDetailSourcePayloads:
@@ -85,7 +92,7 @@ def build_health_section(payload: dict[str, Any] | None) -> DetailSectionSnapsho
"""
构建运维健康检查分区。
- :param payload: `ops health` JSON 负载
+ :param payload: ``ops health`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict):
@@ -116,7 +123,7 @@ def build_ping_db_section(payload: dict[str, Any] | None) -> DetailSectionSnapsh
"""
构建数据库探活结果分区。
- :param payload: `ops ping-db` JSON 负载
+ :param payload: ``ops ping-db`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict):
@@ -142,7 +149,7 @@ def build_ping_redis_section(payload: dict[str, Any] | None) -> DetailSectionSna
"""
构建 Redis 探活结果分区。
- :param payload: `ops ping-redis` JSON 负载
+ :param payload: ``ops ping-redis`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict):
@@ -168,7 +175,7 @@ def build_dependency_section(payload: dict[str, Any] | None) -> DetailSectionSna
"""
构建运维依赖版本分区。
- :param payload: `ops deps` JSON 负载
+ :param payload: ``ops deps`` JSON 负载
:return: 分区快照
"""
if not isinstance(payload, dict):
@@ -207,7 +214,7 @@ def build_server_section(payload: dict[str, Any] | None) -> DetailSectionSnapsho
"""
构建服务器运行概况分区。
- :param payload: `ops server-info` JSON 负载
+ :param payload: ``ops server-info`` JSON 负载
:return: 分区快照
"""
server = payload.get('server') if isinstance(payload, dict) else None
@@ -251,7 +258,7 @@ def build_disk_section(self, payload: dict[str, Any] | None) -> DetailSectionSna
"""
构建服务器磁盘样本分区。
- :param payload: `ops server-info` JSON 负载
+ :param payload: ``ops server-info`` JSON 负载
:return: 分区快照
"""
server = payload.get('server') if isinstance(payload, dict) else None
@@ -322,9 +329,9 @@ def build_overview_section(
"""
构建运维页总览判断分区。
- :param health_payload: `ops health` JSON 负载
- :param deps_payload: `ops deps` JSON 负载
- :param server_payload: `ops server-info` JSON 负载
+ :param health_payload: ``ops health`` JSON 负载
+ :param deps_payload: ``ops deps`` JSON 负载
+ :param server_payload: ``ops server-info`` JSON 负载
:return: 分区快照
"""
health_ok = bool(isinstance(health_payload, dict) and health_payload.get('ok', False))
@@ -382,11 +389,11 @@ def build_sections(
"""
构建运维页全部详情分区。
- :param health_payload: `ops health` 结果负载
- :param ping_db_payload: `ops ping-db` 结果负载
- :param ping_redis_payload: `ops ping-redis` 结果负载
- :param deps_payload: `ops deps` 结果负载
- :param server_payload: `ops server-info` 结果负载
+ :param health_payload: ``ops health`` 结果负载
+ :param ping_db_payload: ``ops ping-db`` 结果负载
+ :param ping_redis_payload: ``ops ping-redis`` 结果负载
+ :param deps_payload: ``ops deps`` 结果负载
+ :param server_payload: ``ops server-info`` 结果负载
:return: 详情分区列表
"""
return [
@@ -407,6 +414,9 @@ class OpsDetailAdapter(BaseDetailAdapter):
该适配器负责采集运维相关 CLI 结果,并委托分区构建器组装为
TUI 详情页快照。
+
+ :ivar section_builder: 运维详情分区构建器
+ :ivar snapshot_collector: 运维详情页数据采集器
"""
def __init__(
@@ -419,7 +429,6 @@ def __init__(
:param section_builder: 运维详情分区构建器
:param snapshot_collector: 运维详情页数据采集器
- :return: None
"""
super().__init__(
page_title='运维',
diff --git a/ruoyi-fastapi-backend/cli/tui/app.py b/ruoyi-fastapi-backend/cli/tui/app.py
index 5544a2f9c..f5ab6fb57 100644
--- a/ruoyi-fastapi-backend/cli/tui/app.py
+++ b/ruoyi-fastapi-backend/cli/tui/app.py
@@ -33,9 +33,9 @@ class TuiViewSpec:
"""
TUI 视图规格定义。
- :param view_key: 视图标识
- :param include_query: 是否注入搜索词
- :param include_filter: 是否注入筛选键
+ :ivar view_key: 视图标识
+ :ivar include_query: 是否注入搜索词
+ :ivar include_filter: 是否注入筛选键
"""
view_key: str
@@ -48,8 +48,8 @@ class TuiViewDefinition:
"""
TUI 视图定义。
- :param view_key: 视图标识
- :param collector: 页面快照采集器
+ :ivar view_key: 视图标识
+ :ivar collector: 页面快照采集器
"""
view_key: str
@@ -62,10 +62,10 @@ class TuiViewRegistry:
TUI 视图注册表。
该对象集中维护视图打开、刷新与顺序导航所需的元数据,
- 避免 `RuoyiTuiApp` 内继续手工维护多份视图映射。
+ 避免 ``RuoyiTuiApp`` 内继续手工维护多份视图映射。
- :param definitions: 视图定义映射
- :param navigation_items: 导航项列表
+ :ivar definitions: 视图定义映射
+ :ivar navigation_items: 导航项列表
"""
definitions: dict[str, TuiViewDefinition]
@@ -300,9 +300,9 @@ class TuiBindingSpec:
"""
TUI 快捷键绑定定义。
- :param key: 快捷键
- :param action: 动作名称
- :param label: 展示标签
+ :ivar key: 快捷键
+ :ivar action: 动作名称
+ :ivar label: 展示标签
"""
key: str
@@ -314,7 +314,7 @@ class TuiBindingBuilder:
"""
TUI 快捷键绑定构建器。
- 该对象负责统一装配应用级固定绑定和视图跳转绑定,避免 `RuoyiTuiApp`
+ 该对象负责统一装配应用级固定绑定和视图跳转绑定,避免 ``RuoyiTuiApp``
继续手工维护重复的绑定元组列表。
"""
@@ -368,7 +368,7 @@ class TuiViewRegistryBuilder:
TUI 视图注册表构建器。
该对象负责根据统一规格构建导航项和快照采集定义,避免模块内
- 继续维护重复的 `lambda collect(...)` 配置块。
+ 继续维护重复的 ``lambda collect(...)`` 配置块。
"""
def build_navigation_items(self) -> list[NavigationItem]:
@@ -396,6 +396,12 @@ def build_collector(self, spec: TuiViewSpec) -> SnapshotCollector:
"""
async def collect(app: 'RuoyiTuiApp') -> PageSnapshot:
+ """
+ 收集当前视图需要的运行时快照。
+
+ :param app: 当前 TUI 应用实例
+ :return: 当前视图需要的运行时快照
+ """
collect_kwargs: dict[str, str] = {}
if spec.include_filter:
collect_kwargs['filter_key'] = app.get_browser_filter(spec.view_key)
@@ -431,11 +437,11 @@ class TuiViewStateStore:
TUI 视图状态存储。
该对象集中维护页面级动作反馈、浏览页筛选键和搜索词,避免
- `RuoyiTuiApp` 本体继续直接操作多份同类字典状态。
+ ``RuoyiTuiApp`` 本体继续直接操作多份同类字典状态。
- :param action_feedback_by_view: 动作反馈映射
- :param browser_filter_by_view: 浏览页筛选映射
- :param browser_query_by_view: 浏览页搜索词映射
+ :ivar action_feedback_by_view: 动作反馈映射
+ :ivar browser_filter_by_view: 浏览页筛选映射
+ :ivar browser_query_by_view: 浏览页搜索词映射
"""
action_feedback_by_view: dict[str, list[str]]
@@ -461,7 +467,6 @@ def remember_action_feedback(self, view_key: str, lines: list[str]) -> None:
:param view_key: 页面视图标识
:param lines: 反馈文本行
- :return: None
"""
self.action_feedback_by_view[view_key] = list(lines)
@@ -480,7 +485,6 @@ def remember_browser_filter(self, view_key: str, filter_key: str) -> None:
:param view_key: 页面视图标识
:param filter_key: 当前筛选键
- :return: None
"""
self.browser_filter_by_view[view_key] = filter_key
@@ -500,7 +504,6 @@ def remember_browser_query(self, view_key: str, query: str) -> None:
:param view_key: 页面视图标识
:param query: 当前搜索词
- :return: None
"""
normalized_query = str(query or '').strip()
if normalized_query:
@@ -528,7 +531,7 @@ class TuiScreenFactory:
"""
TUI 工作台页面工厂。
- 该对象负责把页面快照转换为具体 screen 实例,避免 `RuoyiTuiApp`
+ 该对象负责把页面快照转换为具体 screen 实例,避免 ``RuoyiTuiApp``
同时承担状态协调和 screen 构建职责。
"""
@@ -594,8 +597,8 @@ class TuiScreenNavigator:
该对象负责处理首屏展示与后续切屏差异,让应用壳更专注于状态切换。
- :param app: 当前 TUI 应用实例
- :param initialized: 工作台屏幕是否已初始化
+ :ivar app: 当前 TUI 应用实例
+ :ivar initialized: 工作台屏幕是否已初始化
"""
app: 'RuoyiTuiApp'
@@ -605,12 +608,11 @@ def show(self, screen: BrowserScreen | DashboardScreen | DetailScreen) -> None:
"""
显示工作台页面,并兼容首屏初始化与后续切屏。
- Textual 在默认根屏阶段直接调用 `switch_screen()` 会触发内部回调栈异常,
- 因此首次展示页面需要使用 `push_screen()` 建立活动屏,后续再改用
- `switch_screen()` 做同层页面替换。
+ Textual 在默认根屏阶段直接调用 ``switch_screen()`` 会触发内部回调栈异常,
+ 因此首次展示页面需要使用 ``push_screen()`` 建立活动屏,后续再改用
+ ``switch_screen()`` 做同层页面替换。
:param screen: 待显示的页面对象
- :return: None
"""
if not self.initialized:
self.app.push_screen(screen)
@@ -626,6 +628,10 @@ class TuiSnapshotCache:
缓存按视图、筛选与搜索条件隔离,并通过容量和 TTL 双重限制避免
工作台长时间运行后无界增长。
+
+ :ivar ttl_seconds: 有效期,单位为秒
+ :ivar max_entries: 缓存允许保留的最大条目数
+ :ivar _entries: 已缓存的条目
"""
ttl_seconds: float = TUI_SNAPSHOT_CACHE_TTL_SECONDS
@@ -658,7 +664,6 @@ def put(self, key: str, snapshot: PageSnapshot) -> None:
:param key: 缓存键
:param snapshot: 页面快照
- :return: None
"""
self._entries[key] = (monotonic(), snapshot)
self._entries.move_to_end(key)
@@ -670,7 +675,6 @@ def invalidate(self, key: str) -> None:
删除指定缓存项。
:param key: 缓存键
- :return: None
"""
self._entries.pop(key, None)
@@ -681,11 +685,12 @@ class TuiViewOpeningCoordinator:
TUI 视图打开协调器。
该对象负责串联视图解析、快照采集、screen 构建与切屏展示,
- 让 `RuoyiTuiApp` 更专注于状态暴露与 Textual action 桥接。
+ 让 ``RuoyiTuiApp`` 更专注于状态暴露与 Textual action 桥接。
- :param view_registry: 视图注册表
- :param screen_factory: 工作台页面工厂
- :param navigation_items: 导航项列表
+ :ivar view_registry: 视图注册表
+ :ivar screen_factory: 工作台页面工厂
+ :ivar navigation_items: 导航项列表
+ :ivar snapshot_cache: TUI 页面快照短期缓存
"""
view_registry: TuiViewRegistry
@@ -732,9 +737,11 @@ async def show(
"""
切换并展示指定视图。
+ :param request_id: 请求编号
+ :param force_refresh: 是否绕过已有缓存重新读取
:param app: 当前 TUI 应用实例
:param view_key: 目标视图标识
- :return: None
+ :raises asyncio.CancelledError: 等待视图快照时当前任务被取消
"""
resolved_view_key = self.view_registry.resolve_view_key(view_key)
if app.screen_navigator.initialized:
@@ -776,7 +783,17 @@ class RuoyiTuiApp(App[None]):
"""
RuoYi CLI Textual 应用。
- :param env: 当前运行环境
+ :cvar CSS: 终端界面使用的样式规则
+ :cvar BINDINGS: 终端界面的快捷键和对应动作
+ :ivar env: 当前运行环境
+ :ivar current_view: 当前显示的视图
+ :ivar requested_view: 正在请求切换到的视图
+ :ivar _view_request_id: 用于识别过期加载任务的视图请求编号
+ :ivar _view_task: 正在加载视图的异步任务
+ :ivar view_state_store: 保存各视图状态的对象
+ :ivar screen_factory: 工作台页面工厂
+ :ivar screen_navigator: 负责在终端界面之间导航的对象
+ :ivar view_opening_coordinator: 协调视图异步打开和切换的对象
"""
CSS = _TUI_APP_CSS
@@ -787,7 +804,6 @@ def __init__(self, env: str) -> None:
初始化 TUI 应用实例。
:param env: 当前运行环境
- :return: None
"""
self.env = env
self.current_view = 'dashboard'
@@ -834,8 +850,8 @@ def show_view(self, view_key: str, *, force_refresh: bool = False) -> None:
"""
切换并展示指定视图。
+ :param force_refresh: 是否绕过已有缓存重新读取
:param view_key: 目标视图标识
- :return: None
"""
resolved_view_key = TUI_VIEW_REGISTRY.resolve_view_key(view_key)
self.requested_view = resolved_view_key
@@ -857,7 +873,6 @@ def remember_action_feedback(self, view_key: str, lines: list[str]) -> None:
:param view_key: 页面视图标识
:param lines: 反馈文本行
- :return: None
"""
self.view_state_store.remember_action_feedback(view_key, lines)
@@ -876,7 +891,6 @@ def remember_browser_filter(self, view_key: str, filter_key: str) -> None:
:param view_key: 页面视图标识
:param filter_key: 当前筛选键
- :return: None
"""
self.view_state_store.remember_browser_filter(view_key, filter_key)
@@ -896,7 +910,6 @@ def remember_browser_query(self, view_key: str, query: str) -> None:
:param view_key: 页面视图标识
:param query: 当前搜索词
- :return: None
"""
self.view_state_store.remember_browser_query(view_key, query)
@@ -911,19 +924,11 @@ def get_browser_query(self, view_key: str, default: str = '') -> str:
return self.view_state_store.get_browser_query(view_key, default)
def on_mount(self) -> None:
- """
- 在应用启动时载入首页。
-
- :return: None
- """
+ """在应用启动时载入首页。"""
self.show_view('dashboard')
def on_unmount(self) -> None:
- """
- 应用卸载时取消页面加载任务。
-
- :return: None
- """
+ """应用卸载时取消页面加载任务。"""
if self._view_task is not None and not self._view_task.done():
self._view_task.cancel()
@@ -932,115 +937,62 @@ def open_view(self, view_key: str) -> None:
按视图标识打开对应页面。
:param view_key: 视图标识
- :return: None
"""
self.show_view(view_key)
def action_focus_sidebar(self) -> None:
- """
- 将焦点切换到左侧导航栏。
-
- :return: None
- """
+ """将焦点切换到左侧导航栏。"""
try:
self.screen.query_one(WorkspaceSidebar).focus()
except NoMatches:
return
def action_show_previous_view(self) -> None:
- """
- 切换到前一个工作台视图。
-
- :return: None
- """
+ """切换到前一个工作台视图。"""
self.open_view(TUI_VIEW_REGISTRY.get_relative_view_key(self.requested_view, -1))
def action_show_next_view(self) -> None:
- """
- 切换到后一个工作台视图。
-
- :return: None
- """
+ """切换到后一个工作台视图。"""
self.open_view(TUI_VIEW_REGISTRY.get_relative_view_key(self.requested_view, 1))
def action_refresh_current_view(self) -> None:
- """
- 刷新当前视图数据。
-
- :return: None
- """
+ """刷新当前视图数据。"""
self.show_view(self.current_view, force_refresh=True)
def action_show_dashboard(self) -> None:
- """
- 切换到首页视图。
-
- :return: None
- """
+ """切换到首页视图。"""
self.open_view('dashboard')
def action_show_app(self) -> None:
- """
- 切换到应用详情视图。
-
- :return: None
- """
+ """切换到应用详情视图。"""
self.open_view('app')
def action_show_ops(self) -> None:
- """
- 切换到运维详情视图。
-
- :return: None
- """
+ """切换到运维详情视图。"""
self.open_view('ops')
def action_show_database(self) -> None:
- """
- 切换到数据库详情视图。
-
- :return: None
- """
+ """切换到数据库详情视图。"""
self.open_view('database')
def action_show_cache(self) -> None:
- """
- 切换到缓存浏览视图。
-
- :return: None
- """
+ """切换到缓存浏览视图。"""
self.open_view('cache')
def action_show_jobs(self) -> None:
- """
- 切换到任务浏览视图。
-
- :return: None
- """
+ """切换到任务浏览视图。"""
self.open_view('jobs')
def action_show_gen(self) -> None:
- """
- 切换到代码生成浏览视图。
-
- :return: None
- """
+ """切换到代码生成浏览视图。"""
self.open_view('gen')
def action_show_configs(self) -> None:
- """
- 切换到配置浏览视图。
-
- :return: None
- """
+ """切换到配置浏览视图。"""
self.open_view('configs')
def action_show_crypto(self) -> None:
- """
- 切换到传输加密详情视图。
-
- :return: None
- """
+ """切换到传输加密详情视图。"""
self.open_view('crypto')
@@ -1052,7 +1004,7 @@ class TuiAppRunner:
该对象负责按环境创建并运行 Textual 应用实例,使命令入口不再依赖
模块级启动函数。
- :param app_factory: TUI 应用工厂
+ :ivar app_factory: TUI 应用工厂
"""
app_factory: Callable[[str], RuoyiTuiApp]
@@ -1062,7 +1014,6 @@ def run(self, env: str) -> None:
启动 TUI 应用。
:param env: 当前运行环境
- :return: None
"""
self.app_factory(env).run()
diff --git a/ruoyi-fastapi-backend/cli/tui/capabilities.py b/ruoyi-fastapi-backend/cli/tui/capabilities.py
index 108345826..07cee8067 100644
--- a/ruoyi-fastapi-backend/cli/tui/capabilities.py
+++ b/ruoyi-fastapi-backend/cli/tui/capabilities.py
@@ -12,12 +12,12 @@ class TuiCapability:
"""
TUI 页面能力定义。
- :param kind: 能力类型
- :param slot: 绑定的动作槽位
- :param key: 绑定的快捷键
- :param label: 展示标签
- :param hint_label: 用于顶部提示的简洁标签
- :param scope: 能力所在页面范围
+ :ivar kind: 能力类型
+ :ivar slot: 绑定的动作槽位
+ :ivar key: 绑定的快捷键
+ :ivar label: 展示标签
+ :ivar hint_label: 用于顶部提示的简洁标签
+ :ivar scope: 能力所在页面范围
"""
kind: CapabilityKind
@@ -33,10 +33,10 @@ class TuiCapabilitySpec:
"""
TUI 页面能力规格定义。
- :param capability_key: 能力标识
- :param kind: 能力类型
- :param slot: 绑定动作槽位
- :param key: 绑定快捷键
+ :ivar capability_key: 能力标识
+ :ivar kind: 能力类型
+ :ivar slot: 绑定动作槽位
+ :ivar key: 绑定快捷键
"""
capability_key: str
@@ -91,8 +91,8 @@ class TuiCapabilityRegistry:
该对象集中维护浏览页与详情页的能力描述,避免模块级散落
的字典常量在后续扩展时继续增长。
- :param browser_capabilities: 浏览页能力映射
- :param detail_capabilities: 详情页能力映射
+ :ivar browser_capabilities: 浏览页能力映射
+ :ivar detail_capabilities: 详情页能力映射
"""
browser_capabilities: dict[str, tuple[TuiCapability, ...]]
diff --git a/ruoyi-fastapi-backend/cli/tui/commands.py b/ruoyi-fastapi-backend/cli/tui/commands.py
index 2d3aa1649..fd9eb5871 100644
--- a/ruoyi-fastapi-backend/cli/tui/commands.py
+++ b/ruoyi-fastapi-backend/cli/tui/commands.py
@@ -42,7 +42,7 @@ class TuiAppModuleLoader:
TUI 应用模块加载器。
该对象负责识别缺失的可选依赖,并在命令执行阶段按需导入
- `cli.tui.app` 模块。
+ ``cli.tui.app`` 模块。
"""
def is_missing_dependency_error(self, exc: ModuleNotFoundError) -> bool:
@@ -59,7 +59,7 @@ def load(self) -> ModuleType:
"""
惰性导入 TUI 应用模块。
- :return: `cli.tui.app` 模块对象
+ :return: ``cli.tui.app`` 模块对象
"""
return import_module('cli.tui.app')
@@ -69,10 +69,10 @@ class TuiCommandRegistration:
"""
TUI 命令注册器。
- :param context_factory: CLI 上下文工厂
- :param execution_service: CLI 执行服务
- :param dependency_result_factory: TUI 缺失依赖结果构建器
- :param module_loader: TUI 应用模块加载器
+ :ivar context_factory: CLI 上下文工厂
+ :ivar execution_service: CLI 执行服务
+ :ivar dependency_result_factory: TUI 缺失依赖结果构建器
+ :ivar module_loader: TUI 应用模块加载器
"""
context_factory: CliContextFactory
@@ -82,10 +82,10 @@ class TuiCommandRegistration:
def handle_tui_command(self, env: str) -> None:
"""
- 执行 `ruoyi tui` 命令。
+ 执行 ``ruoyi tui`` 命令。
:param env: 当前命令运行环境
- :return: None
+ :raises ModuleNotFoundError: 加载终端界面时遇到需要向上传播的模块导入错误
"""
ctx = self.context_factory.build_readonly(env, 'text')
try:
@@ -102,9 +102,9 @@ def handle_tui_command(self, env: str) -> None:
def build(self) -> typer.Typer:
"""
- 构建 `tui` 子应用。
+ 构建 ``tui`` 子应用。
- :return: `tui` 子应用
+ :return: ``tui`` 子应用
"""
app = typer.Typer(
help=TUI_COPY.build_tui_command_help(),
@@ -121,7 +121,6 @@ def tui(
进入只读巡检工作台。
:param env: 当前命令运行环境
- :return: None
"""
self.handle_tui_command(env)
@@ -129,10 +128,9 @@ def tui(
def register(self, root_cli: typer.Typer) -> None:
"""
- 向根 Typer 应用注册 `tui` 命令。
+ 向根 Typer 应用注册 ``tui`` 命令。
:param root_cli: 根 Typer 应用
- :return: None
"""
root_cli.add_typer(self.build(), name='tui')
diff --git a/ruoyi-fastapi-backend/cli/tui/copy/actions.py b/ruoyi-fastapi-backend/cli/tui/copy/actions.py
index e2d4762af..f40a6cbde 100644
--- a/ruoyi-fastapi-backend/cli/tui/copy/actions.py
+++ b/ruoyi-fastapi-backend/cli/tui/copy/actions.py
@@ -18,9 +18,7 @@
class TuiActionCopyMixin:
- """
- TUI 动作与能力文案混入。
- """
+ """TUI 动作与能力文案混入。"""
@staticmethod
def build_action_confirm_hint() -> str:
diff --git a/ruoyi-fastapi-backend/cli/tui/copy/navigation.py b/ruoyi-fastapi-backend/cli/tui/copy/navigation.py
index b3d6957d6..2a299b6ac 100644
--- a/ruoyi-fastapi-backend/cli/tui/copy/navigation.py
+++ b/ruoyi-fastapi-backend/cli/tui/copy/navigation.py
@@ -9,9 +9,7 @@
class TuiNavigationCopyMixin:
- """
- TUI 导航与基础标签文案混入。
- """
+ """TUI 导航与基础标签文案混入。"""
@staticmethod
def render_view_label(view_key: str) -> str:
@@ -75,7 +73,7 @@ def render_navigation_description(view_key: str) -> str:
@staticmethod
def build_tui_command_help() -> str:
"""
- 构建 `ruoyi tui` 命令帮助文案。
+ 构建 ``ruoyi tui`` 命令帮助文案。
:return: 命令帮助文案
"""
diff --git a/ruoyi-fastapi-backend/cli/tui/copy/workspace.py b/ruoyi-fastapi-backend/cli/tui/copy/workspace.py
index 129b12bdb..78622a9ae 100644
--- a/ruoyi-fastapi-backend/cli/tui/copy/workspace.py
+++ b/ruoyi-fastapi-backend/cli/tui/copy/workspace.py
@@ -18,9 +18,7 @@
class TuiWorkspaceCopyMixin:
- """
- TUI 工作区与状态文案混入。
- """
+ """TUI 工作区与状态文案混入。"""
@staticmethod
def build_workspace_label(label_key: str) -> str:
diff --git a/ruoyi-fastapi-backend/cli/tui/diagnostics.py b/ruoyi-fastapi-backend/cli/tui/diagnostics.py
index 05f8b3dbe..70cd5c50b 100644
--- a/ruoyi-fastapi-backend/cli/tui/diagnostics.py
+++ b/ruoyi-fastapi-backend/cli/tui/diagnostics.py
@@ -10,8 +10,8 @@ class DiagnosticPagePolicy:
"""
TUI 页面诊断策略定义。
- :param focus_terms: 页面聚焦词
- :param subtitle_builder: 页面摘要构建函数
+ :ivar focus_terms: 页面聚焦词
+ :ivar subtitle_builder: 页面摘要构建函数
"""
focus_terms: tuple[str, ...]
@@ -23,7 +23,7 @@ class DiagnosticPagePolicyRegistry:
"""
TUI 页面诊断策略注册表。
- :param policies: 页面诊断策略映射
+ :ivar policies: 页面诊断策略映射
"""
policies: dict[str, DiagnosticPagePolicy]
@@ -46,7 +46,7 @@ class TuiDiagnosticService:
该服务通过页面级诊断策略注册表管理各页面的聚焦词和 subtitle 规则,
供 adapter、dashboard 等对象复用。
- :param page_policy_registry: 页面诊断策略注册表
+ :ivar page_policy_registry: 页面诊断策略注册表
"""
def __init__(self, page_policy_registry: DiagnosticPagePolicyRegistry) -> None:
@@ -54,7 +54,6 @@ def __init__(self, page_policy_registry: DiagnosticPagePolicyRegistry) -> None:
初始化诊断服务。
:param page_policy_registry: 页面诊断策略注册表
- :return: None
"""
self.page_policy_registry = page_policy_registry
@@ -154,11 +153,11 @@ def _build_app_subtitle(
"""
构建应用页诊断摘要。
- :param env_payload: `app env` 结果
- :param config_payload: `app config` 结果
- :param doctor_payload: `app doctor` 结果
- :param routes_payload: `app routes` 结果
- :param completion_payload: `completion doctor` 结果
+ :param env_payload: ``app env`` 结果
+ :param config_payload: ``app config`` 结果
+ :param doctor_payload: ``app doctor`` 结果
+ :param routes_payload: ``app routes`` 结果
+ :param completion_payload: ``completion doctor`` 结果
:param focus_hint: 聚焦提示
:return: 页面摘要
"""
@@ -193,9 +192,9 @@ def _build_database_subtitle(
"""
构建数据库页诊断摘要。
- :param revision_payload: `db current` 结果
- :param check_payload: `db check` 结果
- :param heads_payload: `db heads` 结果
+ :param revision_payload: ``db current`` 结果
+ :param check_payload: ``db check`` 结果
+ :param heads_payload: ``db heads`` 结果
:param focus_hint: 聚焦提示
:return: 页面摘要
"""
@@ -224,9 +223,9 @@ def _build_ops_subtitle(
"""
构建运维页诊断摘要。
- :param health_payload: `ops health` 结果
- :param deps_payload: `ops deps` 结果
- :param server_payload: `ops server-info` 结果
+ :param health_payload: ``ops health`` 结果
+ :param deps_payload: ``ops deps`` 结果
+ :param server_payload: ``ops server-info`` 结果
:param focus_hint: 聚焦提示
:return: 页面摘要
"""
@@ -252,7 +251,7 @@ def _build_cache_subtitle(
"""
构建缓存页诊断摘要。
- :param stats_payload: `cache stats` 结果
+ :param stats_payload: ``cache stats`` 结果
:param matched_count: 当前筛选后缓存名数量
:param focus_hint: 聚焦提示
:return: 页面摘要
@@ -349,8 +348,8 @@ def _build_crypto_subtitle(
"""
构建加密页诊断摘要。
- :param validate_payload: `crypto validate` 结果
- :param public_payload: `crypto export-public` 结果
+ :param validate_payload: ``crypto validate`` 结果
+ :param public_payload: ``crypto export-public`` 结果
:param focus_hint: 聚焦提示
:return: 页面摘要
"""
@@ -381,11 +380,11 @@ def build_app_diagnostic_subtitle(
"""
构建应用页统一诊断摘要。
- :param env_payload: `app env` 结果
- :param config_payload: `app config` 结果
- :param doctor_payload: `app doctor` 结果
- :param routes_payload: `app routes` 结果
- :param completion_payload: `completion doctor` 结果
+ :param env_payload: ``app env`` 结果
+ :param config_payload: ``app config`` 结果
+ :param doctor_payload: ``app doctor`` 结果
+ :param routes_payload: ``app routes`` 结果
+ :param completion_payload: ``completion doctor`` 结果
:return: 页面摘要
"""
return self.page_policy_registry.get('app').subtitle_builder(
@@ -406,9 +405,9 @@ def build_database_diagnostic_subtitle(
"""
构建数据库页统一诊断摘要。
- :param revision_payload: `db current` 结果
- :param check_payload: `db check` 结果
- :param heads_payload: `db heads` 结果
+ :param revision_payload: ``db current`` 结果
+ :param check_payload: ``db check`` 结果
+ :param heads_payload: ``db heads`` 结果
:return: 页面摘要
"""
return self.page_policy_registry.get('database').subtitle_builder(
@@ -427,9 +426,9 @@ def build_ops_diagnostic_subtitle(
"""
构建运维页统一诊断摘要。
- :param health_payload: `ops health` 结果
- :param deps_payload: `ops deps` 结果
- :param server_payload: `ops server-info` 结果
+ :param health_payload: ``ops health`` 结果
+ :param deps_payload: ``ops deps`` 结果
+ :param server_payload: ``ops server-info`` 结果
:return: 页面摘要
"""
return self.page_policy_registry.get('ops').subtitle_builder(
@@ -447,7 +446,7 @@ def build_cache_diagnostic_subtitle(
"""
构建缓存页统一诊断摘要。
- :param stats_payload: `cache stats` 结果
+ :param stats_payload: ``cache stats`` 结果
:param matched_count: 当前筛选后缓存名数量
:return: 页面摘要
"""
@@ -531,8 +530,8 @@ def build_crypto_diagnostic_subtitle(
"""
构建加密页统一诊断摘要。
- :param validate_payload: `crypto validate` 结果
- :param public_payload: `crypto export-public` 结果
+ :param validate_payload: ``crypto validate`` 结果
+ :param public_payload: ``crypto export-public`` 结果
:return: 页面摘要
"""
return self.page_policy_registry.get('crypto').subtitle_builder(
diff --git a/ruoyi-fastapi-backend/cli/tui/keymaps.py b/ruoyi-fastapi-backend/cli/tui/keymaps.py
index e8392c14e..09f2ed314 100644
--- a/ruoyi-fastapi-backend/cli/tui/keymaps.py
+++ b/ruoyi-fastapi-backend/cli/tui/keymaps.py
@@ -9,7 +9,7 @@ class TuiKeymapRegistry:
该对象集中维护页面切换快捷键和派生提示文案,避免模块级
常量散落并在后续扩展时继续增长。
- :param navigation_shortcuts: 页面导航快捷键映射
+ :ivar navigation_shortcuts: 页面导航快捷键映射
"""
navigation_shortcuts: dict[str, str] = field(default_factory=dict)
diff --git a/ruoyi-fastapi-backend/cli/tui/platform.py b/ruoyi-fastapi-backend/cli/tui/platform.py
index e62065490..60d562c49 100644
--- a/ruoyi-fastapi-backend/cli/tui/platform.py
+++ b/ruoyi-fastapi-backend/cli/tui/platform.py
@@ -10,13 +10,19 @@ class TuiPlatformPolicy:
Windows 终端默认关闭持续动画,避免高频全行重绘与业务查询同时争用
事件循环。可通过 ``RUOYI_TUI_REDUCED_MOTION`` 显式覆盖。
+
+ :ivar reduced_motion: 是否减少界面动画
"""
reduced_motion: bool
@classmethod
def detect(cls) -> 'TuiPlatformPolicy':
- """根据平台与显式环境变量构建渲染策略。"""
+ """
+ 根据平台与显式环境变量构建渲染策略。
+
+ :return: 包含减少动画设置的终端渲染策略
+ """
override = os.environ.get('RUOYI_TUI_REDUCED_MOTION', '').strip().lower()
if override in {'1', 'true', 'yes', 'on'}:
return cls(reduced_motion=True)
diff --git a/ruoyi-fastapi-backend/cli/tui/queries.py b/ruoyi-fastapi-backend/cli/tui/queries.py
index 8f3f1d5da..7e13289b5 100644
--- a/ruoyi-fastapi-backend/cli/tui/queries.py
+++ b/ruoyi-fastapi-backend/cli/tui/queries.py
@@ -31,9 +31,9 @@ class TuiGeneratedOutput:
"""
进程内生成文本结果。
- :param stdout: 生成的标准文本
- :param stderr: 生成失败信息
- :param returncode: 生成结果码
+ :ivar stdout: 生成的标准文本
+ :ivar stderr: 生成失败信息
+ :ivar returncode: 生成结果码
"""
stdout: str
@@ -48,6 +48,11 @@ class TuiQueryExecutor:
该对象统一施加页面查询超时,并将短时间本地同步检查移出 Textual
事件循环。网络查询必须通过 ``run_async`` 执行。
+
+ :ivar remote_timeout_seconds: 远程查询的超时时间(秒)
+ :ivar local_timeout_seconds: 本地查询的超时时间(秒)
+ :ivar local_executor: 执行本地查询的执行器
+ :ivar local_slots: 限制并发本地查询数量的槽位
"""
remote_timeout_seconds: float = TUI_REMOTE_QUERY_TIMEOUT_SECONDS
@@ -75,6 +80,7 @@ async def run_async(
:param operation: 异步查询工厂
:param label: 查询名称
:return: 查询结果或超时负载
+ :raises asyncio.CancelledError: 异步操作被取消时
"""
try:
return await asyncio.wait_for(operation(), timeout=self.remote_timeout_seconds)
@@ -97,6 +103,8 @@ async def run_local(
:param operation: 同步查询函数
:param label: 查询名称
:return: 查询结果或失败负载
+ :raises Exception: 底层操作失败时向调用方传播异常
+ :raises asyncio.CancelledError: 异步操作被取消时
"""
loop = asyncio.get_running_loop()
deadline = loop.time() + self.local_timeout_seconds
@@ -163,6 +171,19 @@ class TuiRuntimeQueryService:
TUI 进程内查询服务。
所有 TUI 页面通过该服务直接调用 runtime,不再启动嵌套 CLI 进程。
+
+ :ivar app_runtime: 应用运行时服务
+ :ivar database_runtime: 数据库运行时服务
+ :ivar operations_runtime: 运维运行时服务
+ :ivar cache_runtime: 缓存运行时服务
+ :ivar job_runtime: 定时任务运行时服务
+ :ivar gen_runtime: 代码生成运行时服务
+ :ivar config_runtime: 参数配置运行时服务
+ :ivar crypto_runtime: 传输加密运行时服务
+ :ivar completion_doctor: completion 诊断服务
+ :ivar completion_installer: completion 安装与脚本生成服务
+ :ivar application_builder: 根应用构建器
+ :ivar executor: TUI 查询执行器
"""
app_runtime: AppRuntimeService = field(default_factory=lambda: APP_RUNTIME)
@@ -179,6 +200,12 @@ class TuiRuntimeQueryService:
executor: TuiQueryExecutor = field(default_factory=TuiQueryExecutor)
async def get_app_env(self, env: str) -> dict[str, Any]:
+ """
+ 为终端界面查询当前应用环境。
+
+ :param env: 当前运行环境
+ :return: 当前应用环境
+ """
result = await self.executor.run_local(
self.app_runtime.get_app_env_snapshot,
label='读取应用环境',
@@ -193,6 +220,12 @@ async def get_app_env(self, env: str) -> dict[str, Any]:
return {'ok': True, 'env': env, 'runtime': result}
async def get_app_config(self, env: str) -> dict[str, Any]:
+ """
+ 为终端界面查询当前应用配置。
+
+ :param env: 当前运行环境
+ :return: 当前应用配置
+ """
result = await self.executor.run_local(
self.app_runtime.get_app_config_snapshot,
label='读取应用配置',
@@ -202,6 +235,12 @@ async def get_app_config(self, env: str) -> dict[str, Any]:
return {'ok': True, 'env': env, 'config': result}
async def get_app_routes(self, env: str) -> dict[str, Any]:
+ """
+ 为终端界面查询已注册的应用路由。
+
+ :param env: 当前运行环境
+ :return: 已注册的应用路由
+ """
result = await self.executor.run_local(
lambda: self.app_runtime.get_app_routes_snapshot(env, group_by='tag'),
label='读取应用路由',
@@ -216,6 +255,12 @@ async def get_app_routes(self, env: str) -> dict[str, Any]:
)
async def get_doctor(self, env: str) -> dict[str, Any]:
+ """
+ 为终端界面查询应用诊断结果。
+
+ :param env: 当前运行环境
+ :return: 随调用传入或返回的结构化数据
+ """
database, redis, crypto = await asyncio.gather(
self.get_database_ping(),
self.get_redis_ping(),
@@ -233,6 +278,11 @@ async def get_doctor(self, env: str) -> dict[str, Any]:
return payload
async def get_completion_doctor(self) -> dict[str, Any]:
+ """
+ 为终端界面查询命令补全环境的诊断结果。
+
+ :return: 命令补全环境的诊断结果
+ """
result = await self.executor.run_local(
self.completion_doctor.build_completion_doctor_payload,
label='读取补全诊断',
@@ -247,7 +297,19 @@ async def get_completion_doctor(self) -> dict[str, Any]:
)
async def get_completion_preview(self, shell: str) -> TuiGeneratedOutput:
+ """
+ 为终端界面查询指定 Shell 的补全脚本预览。
+
+ :param shell: 生成补全命令的目标 shell
+ :return: 指定 Shell 的补全脚本预览
+ """
+
def _render() -> str:
+ """
+ 捕获补全脚本的文本输出供 TUI 预览。
+
+ :return: 补全脚本或诊断命令的输出文本
+ """
return self.completion_installer.render_completion_script(
self.application_builder.build(),
shell,
@@ -263,6 +325,11 @@ def _render() -> str:
return TuiGeneratedOutput(stdout=str(result))
async def get_database_ping(self) -> dict[str, Any]:
+ """
+ 为终端界面查询数据库连接探测结果。
+
+ :return: 数据库连接探测结果
+ """
result = await self.executor.run_async(
self.database_runtime.ping_database,
label='数据库探活',
@@ -270,6 +337,11 @@ async def get_database_ping(self) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_database_current(self) -> dict[str, Any]:
+ """
+ 为终端界面查询数据库当前迁移版本。
+
+ :return: 数据库当前迁移版本
+ """
result = await self.executor.run_async(
self.database_runtime.get_current_revision_async,
label='读取数据库版本',
@@ -277,6 +349,11 @@ async def get_database_current(self) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_database_heads(self) -> dict[str, Any]:
+ """
+ 为终端界面查询迁移脚本的最新版本。
+
+ :return: 迁移脚本的最新版本
+ """
result = await self.executor.run_local(
self.database_runtime.get_alembic_heads,
label='读取 Alembic heads',
@@ -284,6 +361,12 @@ async def get_database_heads(self) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_database_history(self, *, limit: int = 8) -> dict[str, Any]:
+ """
+ 为终端界面查询数据库迁移历史。
+
+ :param limit: 允许读取或返回的最大条目数
+ :return: 数据库迁移历史
+ """
result = await self.executor.run_local(
lambda: self.database_runtime.get_alembic_history(limit=limit),
label='读取 Alembic 历史',
@@ -291,6 +374,11 @@ async def get_database_history(self, *, limit: int = 8) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_redis_ping(self) -> dict[str, Any]:
+ """
+ 为终端界面查询Redis 连接探测结果。
+
+ :return: Redis 连接探测结果
+ """
result = await self.executor.run_async(
self.operations_runtime.ping_redis,
label='Redis 探活',
@@ -298,6 +386,11 @@ async def get_redis_ping(self) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_dependencies(self) -> dict[str, Any]:
+ """
+ 为终端界面查询服务依赖的可用性。
+
+ :return: 服务依赖的可用性
+ """
result = await self.executor.run_local(
self.operations_runtime.get_dependency_versions,
label='读取依赖信息',
@@ -305,6 +398,11 @@ async def get_dependencies(self) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_server_info(self) -> dict[str, Any]:
+ """
+ 为终端界面查询服务器运行信息。
+
+ :return: 服务器运行信息
+ """
result = await self.executor.run_async(
self.operations_runtime.get_server_info,
label='读取服务器信息',
@@ -312,6 +410,11 @@ async def get_server_info(self) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_crypto_validation(self) -> dict[str, Any]:
+ """
+ 为终端界面查询传输加密配置的校验结果。
+
+ :return: 传输加密配置的校验结果
+ """
result = await self.executor.run_local(
self.crypto_runtime.validate_crypto_config,
label='校验传输加密配置',
@@ -319,6 +422,11 @@ async def get_crypto_validation(self) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_crypto_public_key(self) -> dict[str, Any]:
+ """
+ 为终端界面查询当前传输加密公钥。
+
+ :return: 当前传输加密公钥
+ """
result = await self.executor.run_local(
self.crypto_runtime.export_public_key,
label='读取传输加密公钥',
@@ -326,6 +434,11 @@ async def get_crypto_public_key(self) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_cache_stats(self) -> dict[str, Any]:
+ """
+ 为终端界面查询缓存命名空间统计。
+
+ :return: 缓存命名空间统计
+ """
result = await self.executor.run_async(
self.cache_runtime.get_cache_stats,
label='读取缓存统计',
@@ -333,6 +446,12 @@ async def get_cache_stats(self) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_cache_keys(self, cache_name: str) -> dict[str, Any]:
+ """
+ 为终端界面查询指定命名空间中的缓存键。
+
+ :param cache_name: 缓存名称
+ :return: 指定命名空间中的缓存键
+ """
result = await self.executor.run_async(
lambda: self.cache_runtime.list_cache_keys(cache_name),
label='读取缓存键',
@@ -340,6 +459,13 @@ async def get_cache_keys(self, cache_name: str) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_cache_value(self, cache_name: str, cache_key: str) -> dict[str, Any]:
+ """
+ 为终端界面查询指定缓存键的值。
+
+ :param cache_name: 缓存名称
+ :param cache_key: 缓存键名
+ :return: 指定缓存键的值
+ """
result = await self.executor.run_async(
lambda: self.cache_runtime.get_cache_value(cache_name, cache_key),
label='读取缓存值',
@@ -347,6 +473,13 @@ async def get_cache_value(self, cache_name: str, cache_key: str) -> dict[str, An
return result if isinstance(result, dict) else {}
async def get_cache_ttl(self, cache_name: str, cache_key: str) -> dict[str, Any]:
+ """
+ 为终端界面查询指定缓存键的剩余有效期。
+
+ :param cache_name: 缓存名称
+ :param cache_key: 缓存键名
+ :return: 指定缓存键的剩余有效期
+ """
result = await self.executor.run_async(
lambda: self.cache_runtime.get_cache_ttl(cache_name, cache_key),
label='读取缓存 TTL',
@@ -354,6 +487,11 @@ async def get_cache_ttl(self, cache_name: str, cache_key: str) -> dict[str, Any]
return result if isinstance(result, dict) else {}
async def get_jobs(self) -> dict[str, Any]:
+ """
+ 为终端界面查询调度任务列表。
+
+ :return: 调度任务列表
+ """
result = await self.executor.run_async(
lambda: self.job_runtime.list_jobs(paged=True, page_size=8),
label='读取定时任务',
@@ -367,6 +505,14 @@ async def get_job_logs(
status: str | None = None,
page_size: int = 20,
) -> dict[str, Any]:
+ """
+ 为终端界面查询任务执行日志。
+
+ :param job_name: 任务名称过滤条件
+ :param status: 操作或记录所处的状态
+ :param page_size: 每页数量
+ :return: 任务执行日志
+ """
result = await self.executor.run_async(
lambda: self.job_runtime.list_job_logs(
job_name=job_name,
@@ -379,6 +525,12 @@ async def get_job_logs(
return result if isinstance(result, dict) else {}
async def get_job_detail(self, job_id: int) -> dict[str, Any]:
+ """
+ 为终端界面查询指定调度任务的详情。
+
+ :param job_id: 任务ID
+ :return: 指定调度任务的详情
+ """
result = await self.executor.run_async(
lambda: self.job_runtime.get_job_detail(job_id),
label='读取任务详情',
@@ -386,6 +538,11 @@ async def get_job_detail(self, job_id: int) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_gen_tables(self) -> dict[str, Any]:
+ """
+ 为终端界面查询已导入代码生成器的表。
+
+ :return: 已导入代码生成器的表
+ """
result = await self.executor.run_async(
lambda: self.gen_runtime.list_gen_tables(paged=True, page_size=8),
label='读取代码生成业务表',
@@ -393,6 +550,13 @@ async def get_gen_tables(self) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_gen_db_tables(self, *, table_name: str = '', page_size: int = 8) -> dict[str, Any]:
+ """
+ 为终端界面查询可供导入的数据库表。
+
+ :param table_name: 表名称
+ :param page_size: 每页数量
+ :return: 可供导入的数据库表
+ """
result = await self.executor.run_async(
lambda: self.gen_runtime.list_gen_db_tables(
table_name=table_name,
@@ -404,6 +568,12 @@ async def get_gen_db_tables(self, *, table_name: str = '', page_size: int = 8) -
return result if isinstance(result, dict) else {}
async def get_gen_detail(self, table_id: int) -> dict[str, Any]:
+ """
+ 为终端界面查询生成表的详细配置。
+
+ :param table_id: 代码生成表的记录标识
+ :return: 生成表的详细配置
+ """
result = await self.executor.run_async(
lambda: self.gen_runtime.get_gen_table_detail(table_id),
label='读取代码生成详情',
@@ -411,6 +581,12 @@ async def get_gen_detail(self, table_id: int) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_gen_preview(self, table_id: int) -> dict[str, Any]:
+ """
+ 为终端界面查询所选表的代码预览。
+
+ :param table_id: 代码生成表的记录标识
+ :return: 所选表的代码预览
+ """
result = await self.executor.run_async(
lambda: self.gen_runtime.preview_code(table_id),
label='生成代码预览',
@@ -418,6 +594,12 @@ async def get_gen_preview(self, table_id: int) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_gen_export_dry_run(self, table_name: str) -> dict[str, Any]:
+ """
+ 为终端界面查询生成代码导出的预演结果。
+
+ :param table_name: 表名称
+ :return: 生成代码导出的预演结果
+ """
result = await self.executor.run_async(
lambda: self.gen_runtime.export_code([table_name], mode='zip', dry_run=True),
label='代码导出演练',
@@ -425,6 +607,11 @@ async def get_gen_export_dry_run(self, table_name: str) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_configs(self) -> dict[str, Any]:
+ """
+ 为终端界面查询系统参数列表。
+
+ :return: 系统参数列表
+ """
result = await self.executor.run_async(
lambda: self.config_runtime.list_configs(paged=True, page_size=8),
label='读取参数配置',
@@ -432,6 +619,11 @@ async def get_configs(self) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_config_diagnostics(self) -> dict[str, Any]:
+ """
+ 为终端界面查询系统配置的诊断结果。
+
+ :return: 系统配置的诊断结果
+ """
result = await self.executor.run_async(
lambda: self.config_runtime.diagnose_config(sample_limit=5),
label='诊断参数配置',
@@ -439,6 +631,12 @@ async def get_config_diagnostics(self) -> dict[str, Any]:
return result if isinstance(result, dict) else {}
async def get_config_detail(self, config_key: str) -> dict[str, Any]:
+ """
+ 为终端界面查询指定系统参数的详情。
+
+ :param config_key: 用于查找配置项的键
+ :return: 指定系统参数的详情
+ """
result = await self.executor.run_async(
lambda: self.config_runtime.get_config(config_key, source='both'),
label='读取参数配置详情',
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/browser.py b/ruoyi-fastapi-backend/cli/tui/screens/browser.py
index b54d45ed0..84f37f17f 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/browser.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/browser.py
@@ -37,7 +37,7 @@ class BrowserScreenSupport:
浏览页屏幕支持对象。
该对象负责浏览页摘要、搜索词、动作解析、空态/加载态分区构建和
- 焦点顺序编排,使 `BrowserScreen` 本体主要保留 Textual 事件桥接。
+ 焦点顺序编排,使 ``BrowserScreen`` 本体主要保留 Textual 事件桥接。
"""
@staticmethod
@@ -263,11 +263,22 @@ class BrowserScreen(ScreenInteractionActionsMixin, ScreenFocusActionsMixin, Scre
"""
TUI 浏览型页面。
- :param snapshot: 浏览页快照
- :param env: 当前运行环境
- :param active_view: 当前激活视图
- :param navigation_items: 导航项列表
- :param refreshed_at: 本次刷新时间
+ :cvar BINDINGS: 终端界面的快捷键和对应动作
+ :ivar snapshot: 浏览页快照
+ :ivar env: 当前运行环境
+ :ivar active_view: 当前激活视图
+ :ivar navigation_items: 导航项列表
+ :ivar refreshed_at: 本次刷新时间
+ :ivar selected_record_index: 当前选中记录的位置
+ :ivar selected_section_index: 当前选中分区的索引
+ :ivar _is_syncing_sections: 是否正在同步分区选择
+ :ivar _record_detail_request_id: 当前记录详情加载请求的编号
+ :ivar _record_detail_task: 后台加载当前记录详情的任务
+ :ivar _action_task: 当前正在执行的界面操作任务
+ :ivar _last_action_result: 最近一次界面操作的结果
+ :ivar _action_feedback_lines: 最近动作反馈文本
+ :ivar support: 浏览页屏幕支持对象
+ :ivar focus_service: 浏览页焦点服务
"""
BINDINGS = [
@@ -313,7 +324,6 @@ def __init__(
:param action_feedback_lines: 最近动作反馈文本
:param support: 浏览页屏幕支持对象
:param focus_service: 浏览页焦点服务
- :return: None
"""
self.snapshot = snapshot
self.env = env
@@ -349,6 +359,11 @@ def _build_filter_bar_text(self) -> str:
return self.support.build_filter_bar_text(self.snapshot)
def _current_search_query(self) -> str:
+ """
+ 返回当前列表正在使用的搜索条件。
+
+ :return: 当前列表正在使用的搜索条件
+ """
return self.support.current_search_query(self.snapshot)
def _apply_filter_shortcut(self, shortcut: str) -> None:
@@ -356,7 +371,6 @@ def _apply_filter_shortcut(self, shortcut: str) -> None:
按快捷键切换当前浏览页筛选条件。
:param shortcut: 筛选快捷键
- :return: None
"""
if not self.snapshot.filters:
return
@@ -369,11 +383,7 @@ def _apply_filter_shortcut(self, shortcut: str) -> None:
self.app.action_refresh_current_view()
def _open_search(self) -> None:
- """
- 打开当前浏览页搜索输入弹窗。
-
- :return: None
- """
+ """打开当前浏览页搜索输入弹窗。"""
TUI_SCREEN_INTERACTION_SERVICE.open_search_dialog(
self,
self.snapshot.search,
@@ -385,16 +395,11 @@ def _handle_search_submitted(self, query: str | None) -> None:
处理页内搜索输入结果。
:param query: 搜索词
- :return: None
"""
TUI_SCREEN_INTERACTION_SERVICE.remember_query_and_refresh(self, self.active_view, query)
def _clear_search(self) -> None:
- """
- 清空当前浏览页搜索词。
-
- :return: None
- """
+ """清空当前浏览页搜索词。"""
TUI_SCREEN_INTERACTION_SERVICE.clear_query_and_refresh(
self,
self.active_view,
@@ -434,7 +439,6 @@ def _open_action_confirm(self, slot: str) -> None:
打开指定槽位动作的确认弹窗。
:param slot: 动作槽位
- :return: None
"""
self._action_task = TUI_SCREEN_INTERACTION_SERVICE.confirm_and_schedule_action(
self,
@@ -448,10 +452,15 @@ async def _execute_action(self, action: TuiActionSpec) -> None:
执行低风险动作并在结束后通知与刷新页面。
:param action: 动作定义
- :return: None
"""
async def _handle_result(result: TuiActionResult, feedback_lines: list[str]) -> None:
+ """
+ 将操作结果交给当前视图处理。
+
+ :param result: TUI 动作执行结果
+ :param feedback_lines: 最近动作反馈文本
+ """
self._last_action_result = result
self._action_feedback_lines = feedback_lines
await self._render_record_detail()
@@ -499,18 +508,13 @@ def _cancel_task(task: asyncio.Task[None] | None) -> None:
取消指定后台任务。
:param task: 待取消任务
- :return: None
"""
if task is None or task.done():
return
task.cancel()
def _cancel_background_tasks(self) -> None:
- """
- 取消当前屏幕持有的后台任务。
-
- :return: None
- """
+ """取消当前屏幕持有的后台任务。"""
self._record_detail_request_id += 1
self._cancel_task(self._record_detail_task)
self._cancel_task(self._action_task)
@@ -547,11 +551,7 @@ def _get_section_or_fallback(self, record_index: int, section_index: int) -> Det
return self.support.build_empty_section()
async def _render_record_detail(self) -> None:
- """
- 根据当前选中记录刷新右侧详情区域。
-
- :return: None
- """
+ """根据当前选中记录刷新右侧详情区域。"""
record = self._get_record_or_fallback(self.selected_record_index)
sections = self._get_sections_for_record(self.selected_record_index)
selected_section = self._get_section_or_fallback(self.selected_record_index, self.selected_section_index)
@@ -580,7 +580,6 @@ def _sync_detail_pane_state(self, section: DetailSectionSnapshot) -> None:
依据当前分区状态同步右侧详情容器样式。
:param section: 当前分区快照
- :return: None
"""
detail_pane = self.query_one('#browser-detail-pane', Vertical)
detail_pane.remove_class('is-ok', 'is-fail', 'is-warn', 'is-info')
@@ -593,7 +592,6 @@ async def _load_record_detail_async(self, index: int, request_id: int) -> None:
:param index: 记录索引
:param request_id: 当前加载请求编号
- :return: None
"""
record = self._get_record_or_fallback(index)
try:
@@ -612,7 +610,6 @@ def _schedule_record_detail_load(self, index: int) -> None:
为当前选中记录安排一次后台详情加载。
:param index: 记录索引
- :return: None
"""
record = self._get_record_or_fallback(index)
if record.detail_loader is None:
@@ -630,7 +627,6 @@ async def _update_selected_record(self, index: int) -> None:
更新当前选中记录,并同步右侧详情视图。
:param index: 待选中的记录索引
- :return: None
"""
if not self.snapshot.records:
self.selected_record_index = 0
@@ -651,7 +647,6 @@ def _update_selected_section(self, index: int) -> None:
更新当前选中分区,并同步最右侧详情内容。
:param index: 分区索引
- :return: None
"""
if self._is_syncing_sections:
return
@@ -687,52 +682,28 @@ def _update_selected_section(self, index: int) -> None:
self._sync_detail_pane_state(current_section)
def on_mount(self) -> None:
- """
- 浏览页挂载后默认将焦点停留在左侧导航。
-
- :return: None
- """
+ """浏览页挂载后默认将焦点停留在左侧导航。"""
self.call_after_refresh(self.query_one(WorkspaceSidebar).focus)
self._schedule_record_detail_load(self.selected_record_index)
def on_unmount(self) -> None:
- """
- 浏览页卸载时取消尚未完成的后台任务。
-
- :return: None
- """
+ """浏览页卸载时取消尚未完成的后台任务。"""
self._cancel_background_tasks()
def action_apply_filter_1(self) -> None:
- """
- 应用第一个浏览页筛选条件。
-
- :return: None
- """
+ """应用第一个浏览页筛选条件。"""
self._apply_filter_shortcut('1')
def action_apply_filter_2(self) -> None:
- """
- 应用第二个浏览页筛选条件。
-
- :return: None
- """
+ """应用第二个浏览页筛选条件。"""
self._apply_filter_shortcut('2')
def action_apply_filter_3(self) -> None:
- """
- 应用第三个浏览页筛选条件。
-
- :return: None
- """
+ """应用第三个浏览页筛选条件。"""
self._apply_filter_shortcut('3')
def action_apply_filter_4(self) -> None:
- """
- 应用第四个浏览页筛选条件。
-
- :return: None
- """
+ """应用第四个浏览页筛选条件。"""
self._apply_filter_shortcut('4')
def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSidebar.Selected) -> None:
@@ -740,7 +711,6 @@ def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSide
根据侧边栏事件打开对应视图,并避免重复打开当前页面。
:param event: 侧边栏高亮或选中事件
- :return: None
"""
item = getattr(event.item, 'item', None)
if not isinstance(item, NavigationItem):
@@ -757,7 +727,6 @@ def on_sidebar_selected(self, event: WorkspaceSidebar.Selected) -> None:
响应左侧导航选中事件并切换视图。
:param event: 导航选中事件
- :return: None
"""
self._open_sidebar_item(event)
@@ -767,7 +736,6 @@ def on_sidebar_highlighted(self, event: WorkspaceSidebar.Highlighted) -> None:
响应左侧导航高亮变更并立即切换视图。
:param event: 导航高亮事件
- :return: None
"""
self._open_sidebar_item(event)
@@ -775,7 +743,7 @@ def compose(self) -> ComposeResult:
"""
构建浏览页界面结构。
- :return: Textual 组件结果
+ :yield: Textual 组件结果
"""
yield WorkspaceHeader(self.env, self.active_view)
with Horizontal(id='workspace-shell'):
@@ -820,7 +788,6 @@ async def on_record_changed(self, event: RecordNavigator.Changed) -> None:
响应记录导航高亮变更并更新详情内容。
:param event: 记录导航高亮事件
- :return: None
"""
await self._update_selected_record(event.index)
@@ -830,6 +797,5 @@ def on_section_changed(self, event: SectionNavigator.Changed) -> None:
响应记录详情分区高亮变更并更新最右侧详情内容。
:param event: 分区导航高亮事件
- :return: None
"""
self._update_selected_section(event.index)
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/confirm.py b/ruoyi-fastapi-backend/cli/tui/screens/confirm.py
index abdc64c0b..ecb07a42b 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/confirm.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/confirm.py
@@ -12,6 +12,11 @@ class ActionConfirmScreen(ModalScreen[bool]):
"""
通用动作确认弹窗。
+ :cvar CSS: 终端界面使用的样式规则
+ :cvar BINDINGS: 终端界面的快捷键和对应动作
+ :ivar _dialog_title: 确认框的标题
+ :ivar _dialog_lines: 确认框正文显示的各行
+ :ivar _confirm_label: 确认按钮的文字
:param title: 弹窗标题
:param lines: 预览文本行
:param confirm_label: 确认按钮文本
@@ -65,6 +70,13 @@ class ActionConfirmScreen(ModalScreen[bool]):
]
def __init__(self, title: str, lines: list[str], confirm_label: str) -> None:
+ """
+ 设置待确认操作的标题、说明和按钮文字。
+
+ :param title: 弹窗标题
+ :param lines: 预览文本行
+ :param confirm_label: 确认按钮文本
+ """
super().__init__()
self._dialog_title = title
self._dialog_lines = lines
@@ -74,7 +86,7 @@ def compose(self) -> ComposeResult:
"""
构建确认弹窗界面。
- :return: Textual 组件结果
+ :yield: Textual 组件结果
"""
with Vertical(id='action-confirm-dialog'):
yield Static(self._dialog_title, id='action-confirm-title', markup=False)
@@ -85,44 +97,24 @@ def compose(self) -> ComposeResult:
yield Button(self._confirm_label, id='action-confirm-submit', variant='primary')
def on_mount(self) -> None:
- """
- 弹窗挂载后默认聚焦确认按钮。
-
- :return: None
- """
+ """弹窗挂载后默认聚焦确认按钮。"""
self.call_after_refresh(self.query_one('#action-confirm-submit', Button).focus)
def action_cancel(self) -> None:
- """
- 取消并关闭弹窗。
-
- :return: None
- """
+ """取消并关闭弹窗。"""
self.dismiss(False)
def action_submit(self) -> None:
- """
- 通过键盘确认执行当前动作。
-
- :return: None
- """
+ """通过键盘确认执行当前动作。"""
submit_button = self.query_one('#action-confirm-submit', Button)
submit_button.press()
@on(Button.Pressed, '#action-confirm-cancel')
def on_cancel_pressed(self) -> None:
- """
- 响应取消按钮。
-
- :return: None
- """
+ """响应取消按钮。"""
self.dismiss(False)
@on(Button.Pressed, '#action-confirm-submit')
def on_submit_pressed(self) -> None:
- """
- 响应确认按钮。
-
- :return: None
- """
+ """响应确认按钮。"""
self.dismiss(True)
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/dashboard.py b/ruoyi-fastapi-backend/cli/tui/screens/dashboard.py
index a87b8e59c..0a4d931f5 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/dashboard.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/dashboard.py
@@ -28,7 +28,7 @@ class DashboardScreenSupport:
首页屏幕支持对象。
该对象负责首页摘要文本、信号带文本和状态轨迹构建,
- 使 `DashboardScreen` 本体主要保留 Textual 生命周期与界面编排。
+ 使 ``DashboardScreen`` 本体主要保留 Textual 生命周期与界面编排。
"""
@staticmethod
@@ -112,7 +112,14 @@ class DashboardScreen(ScreenFocusActionsMixin, Screen[None]):
"""
TUI 首页巡检屏幕。
- :param snapshot: 首页聚合快照
+ :cvar BINDINGS: 终端界面的快捷键和对应动作
+ :ivar snapshot: 首页聚合快照
+ :ivar env: 当前运行环境
+ :ivar active_view: 当前激活视图
+ :ivar navigation_items: 导航项列表
+ :ivar refreshed_at: 本次刷新时间
+ :ivar support: 首页屏幕支持对象
+ :ivar focus_service: 首页焦点服务
"""
BINDINGS = [
@@ -146,7 +153,6 @@ def __init__(
:param refreshed_at: 本次刷新时间
:param support: 首页屏幕支持对象
:param focus_service: 首页焦点服务
- :return: None
"""
self.snapshot = snapshot
self.env = env
@@ -177,7 +183,7 @@ def compose(self) -> ComposeResult:
"""
构建首页界面结构。
- :return: Textual 组件结果
+ :yield: Textual 组件结果
"""
yield WorkspaceHeader(self.env, self.active_view)
with Horizontal(id='workspace-shell'):
@@ -211,11 +217,7 @@ def compose(self) -> ComposeResult:
yield Footer()
def on_mount(self) -> None:
- """
- 首页挂载后默认将焦点停留在左侧导航。
-
- :return: None
- """
+ """首页挂载后默认将焦点停留在左侧导航。"""
self.call_after_refresh(self.query_one(WorkspaceSidebar).focus)
def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSidebar.Selected) -> None:
@@ -223,7 +225,6 @@ def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSide
根据侧边栏事件打开对应视图,并避免重复打开当前页面。
:param event: 侧边栏高亮或选中事件
- :return: None
"""
item = getattr(event.item, 'item', None)
if not isinstance(item, NavigationItem):
@@ -240,7 +241,6 @@ def on_sidebar_selected(self, event: WorkspaceSidebar.Selected) -> None:
响应左侧导航选中事件并切换视图。
:param event: 导航选中事件
- :return: None
"""
self._open_sidebar_item(event)
@@ -250,6 +250,5 @@ def on_sidebar_highlighted(self, event: WorkspaceSidebar.Highlighted) -> None:
响应左侧导航高亮变更并立即切换视图。
:param event: 导航高亮事件
- :return: None
"""
self._open_sidebar_item(event)
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/detail.py b/ruoyi-fastapi-backend/cli/tui/screens/detail.py
index 9d89ecdaf..f16c7dab5 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/detail.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/detail.py
@@ -34,7 +34,7 @@ class DetailScreenSupport:
详情页屏幕支持对象。
该对象负责详情页摘要、搜索词、动作解析与空态分区构建,
- 使 `DetailScreen` 本体主要保留 Textual 事件桥接。
+ 使 ``DetailScreen`` 本体主要保留 Textual 事件桥接。
"""
@staticmethod
@@ -140,7 +140,18 @@ class DetailScreen(ScreenInteractionActionsMixin, ScreenFocusActionsMixin, Scree
"""
TUI 通用详情屏幕。
- :param snapshot: 页面快照
+ :cvar BINDINGS: 终端界面的快捷键和对应动作
+ :ivar snapshot: 页面快照
+ :ivar env: 当前运行环境
+ :ivar active_view: 当前激活视图
+ :ivar navigation_items: 导航项列表
+ :ivar refreshed_at: 本次刷新时间
+ :ivar selected_section_index: 当前选中分区的索引
+ :ivar _last_action_result: 最近一次界面操作的结果
+ :ivar _action_feedback_lines: 用于显示操作结果的反馈文本
+ :ivar _action_task: 当前正在执行的界面操作任务
+ :ivar support: 详情页屏幕支持对象
+ :ivar focus_service: 详情页焦点服务
"""
BINDINGS = [
@@ -180,7 +191,6 @@ def __init__(
:param refreshed_at: 本次刷新时间
:param support: 详情页屏幕支持对象
:param focus_service: 详情页焦点服务
- :return: None
"""
self.snapshot = snapshot
self.env = env
@@ -201,7 +211,6 @@ def _cancel_task(task: asyncio.Task[None] | None) -> None:
取消指定后台任务。
:param task: 待取消任务
- :return: None
"""
if task is None or task.done():
return
@@ -227,14 +236,15 @@ def _build_summary_text(self) -> str:
return self.support.build_summary_text(self.snapshot, self.active_view)
def _current_search_query(self) -> str:
- return self.support.current_search_query(self.snapshot)
-
- def _open_search(self) -> None:
"""
- 打开当前详情页搜索输入弹窗。
+ 返回当前列表正在使用的搜索条件。
- :return: None
+ :return: 当前列表正在使用的搜索条件
"""
+ return self.support.current_search_query(self.snapshot)
+
+ def _open_search(self) -> None:
+ """打开当前详情页搜索输入弹窗。"""
TUI_SCREEN_INTERACTION_SERVICE.open_search_dialog(
self,
self.snapshot.search,
@@ -246,16 +256,11 @@ def _handle_search_submitted(self, query: str | None) -> None:
处理详情页搜索输入结果。
:param query: 搜索词
- :return: None
"""
TUI_SCREEN_INTERACTION_SERVICE.remember_query_and_refresh(self, self.active_view, query)
def _clear_search(self) -> None:
- """
- 清空当前详情页搜索词。
-
- :return: None
- """
+ """清空当前详情页搜索词。"""
TUI_SCREEN_INTERACTION_SERVICE.clear_query_and_refresh(
self,
self.active_view,
@@ -276,7 +281,6 @@ def _open_action_confirm(self, slot: str) -> None:
打开指定槽位动作的确认弹窗。
:param slot: 动作槽位
- :return: None
"""
self._action_task = TUI_SCREEN_INTERACTION_SERVICE.confirm_and_schedule_action(
self,
@@ -290,10 +294,15 @@ async def _execute_action(self, action: TuiActionSpec) -> None:
执行详情页动作。
:param action: 动作定义
- :return: None
"""
def _handle_result(result: TuiActionResult, feedback_lines: list[str]) -> None:
+ """
+ 将操作结果交给当前视图处理。
+
+ :param result: TUI 动作执行结果
+ :param feedback_lines: 最近动作反馈文本
+ """
self._last_action_result = result
self._action_feedback_lines = feedback_lines
@@ -310,7 +319,6 @@ def _update_selected_section(self, index: int) -> None:
更新当前选中分区,并同步右侧详情视图。
:param index: 待选中的分区索引
- :return: None
"""
if not self.snapshot.sections:
detail_view = self.query_one(SectionDetailView)
@@ -326,7 +334,7 @@ def compose(self) -> ComposeResult:
"""
构建详情页界面结构。
- :return: Textual 组件结果
+ :yield: Textual 组件结果
"""
yield WorkspaceHeader(self.env, self.active_view)
with Horizontal(id='workspace-shell'):
@@ -353,19 +361,11 @@ def compose(self) -> ComposeResult:
yield Footer()
def on_mount(self) -> None:
- """
- 详情页挂载后默认将焦点停留在左侧导航。
-
- :return: None
- """
+ """详情页挂载后默认将焦点停留在左侧导航。"""
self.call_after_refresh(self.query_one(WorkspaceSidebar).focus)
def on_unmount(self) -> None:
- """
- 详情页卸载时取消尚未完成的后台任务。
-
- :return: None
- """
+ """详情页卸载时取消尚未完成的后台任务。"""
self._cancel_task(self._action_task)
def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSidebar.Selected) -> None:
@@ -373,7 +373,6 @@ def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSide
根据侧边栏事件打开对应视图,并避免重复打开当前页面。
:param event: 侧边栏高亮或选中事件
- :return: None
"""
item = getattr(event.item, 'item', None)
if not isinstance(item, NavigationItem):
@@ -390,7 +389,6 @@ def on_sidebar_selected(self, event: WorkspaceSidebar.Selected) -> None:
响应左侧导航选中事件并切换视图。
:param event: 导航选中事件
- :return: None
"""
self._open_sidebar_item(event)
@@ -400,7 +398,6 @@ def on_sidebar_highlighted(self, event: WorkspaceSidebar.Highlighted) -> None:
响应左侧导航高亮变更并立即切换视图。
:param event: 导航高亮事件
- :return: None
"""
self._open_sidebar_item(event)
@@ -410,6 +407,5 @@ def on_section_changed(self, event: SectionNavigator.Changed) -> None:
响应分区导航高亮变更并更新详情内容。
:param event: 分区导航高亮事件
- :return: None
"""
self._update_selected_section(event.index)
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/focus.py b/ruoyi-fastapi-backend/cli/tui/screens/focus.py
index fa3a00e8a..a722418fa 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/focus.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/focus.py
@@ -36,7 +36,6 @@ def move_focus(self, screen: Any, step: int) -> None:
:param screen: 当前屏幕对象
:param step: 焦点移动步长
- :return: None
"""
order = self.get_focus_order(screen)
focused = screen.app.focused
@@ -66,6 +65,8 @@ class ScreenFocusActionsMixin:
该混入负责将焦点服务暴露为屏幕上的左右移动与滚动 action,避免
各个 Screen 类重复编写同形转发方法。
+
+ :ivar focus_service: TUI 屏幕焦点服务基类
"""
focus_service: BaseScreenFocusService
@@ -75,7 +76,6 @@ def _move_focus(self, step: int) -> None:
按给定方向移动当前焦点。
:param step: 焦点移动步长
- :return: None
"""
self.focus_service.move_focus(self, step)
@@ -88,65 +88,33 @@ def _get_scroll_target(self) -> Any:
return self.focus_service.get_scroll_target(self)
def action_scroll_focus_down(self) -> None:
- """
- 向下滚动当前焦点区域。
-
- :return: None
- """
+ """向下滚动当前焦点区域。"""
self._get_scroll_target().scroll_down(animate=False)
def action_scroll_focus_up(self) -> None:
- """
- 向上滚动当前焦点区域。
-
- :return: None
- """
+ """向上滚动当前焦点区域。"""
self._get_scroll_target().scroll_up(animate=False)
def action_scroll_focus_page_down(self) -> None:
- """
- 向下翻动当前焦点区域。
-
- :return: None
- """
+ """向下翻动当前焦点区域。"""
self._get_scroll_target().scroll_page_down(animate=False)
def action_scroll_focus_page_up(self) -> None:
- """
- 向上翻动当前焦点区域。
-
- :return: None
- """
+ """向上翻动当前焦点区域。"""
self._get_scroll_target().scroll_page_up(animate=False)
def action_scroll_focus_home(self) -> None:
- """
- 将当前焦点区域滚动到起始位置。
-
- :return: None
- """
+ """将当前焦点区域滚动到起始位置。"""
self._get_scroll_target().scroll_home(animate=False)
def action_scroll_focus_end(self) -> None:
- """
- 将当前焦点区域滚动到末尾位置。
-
- :return: None
- """
+ """将当前焦点区域滚动到末尾位置。"""
self._get_scroll_target().scroll_end(animate=False)
def action_focus_left(self) -> None:
- """
- 将焦点向左移动一列。
-
- :return: None
- """
+ """将焦点向左移动一列。"""
self._move_focus(-1)
def action_focus_right(self) -> None:
- """
- 将焦点向右移动一列。
-
- :return: None
- """
+ """将焦点向右移动一列。"""
self._move_focus(1)
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/interactions.py b/ruoyi-fastapi-backend/cli/tui/screens/interactions.py
index 99d9e3b9a..f84bdca5a 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/interactions.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/interactions.py
@@ -36,7 +36,6 @@ def open_search_dialog(
:param screen: 当前屏幕对象
:param search_context: 搜索上下文
:param callback: 提交搜索词后的回调
- :return: None
"""
if search_context is None:
return
@@ -58,7 +57,6 @@ def remember_query_and_refresh(screen: Any, active_view: str, query: str | None)
:param screen: 当前屏幕对象
:param active_view: 当前页面视图标识
:param query: 搜索词
- :return: None
"""
if query is None:
return
@@ -74,7 +72,6 @@ def clear_query_and_refresh(self, screen: Any, active_view: str, current_query:
:param screen: 当前屏幕对象
:param active_view: 当前页面视图标识
:param current_query: 当前搜索词
- :return: None
"""
if not current_query:
return
@@ -92,7 +89,6 @@ def open_action_confirm(
:param screen: 当前屏幕对象
:param action: 待执行动作
:param callback: 确认回调
- :return: None
"""
if action is None:
screen.notify(
@@ -147,6 +143,12 @@ def confirm_and_schedule_action(
scheduled_task = existing_task
def _handle_confirmed(confirmed: bool | None, action_spec: TuiActionSpec) -> None:
+ """
+ 用户确认后调度选定的操作。
+
+ :param confirmed: 是否已确认该操作
+ :param action_spec: TUI 低风险动作定义
+ """
nonlocal scheduled_task
if not confirmed:
return
@@ -237,25 +239,16 @@ class ScreenInteractionActionsMixin:
"""
def _open_search(self) -> None:
- """
- 打开当前页面搜索输入弹窗。
-
- :return: None
- """
+ """打开当前页面搜索输入弹窗。"""
def _clear_search(self) -> None:
- """
- 清空当前页面搜索词。
-
- :return: None
- """
+ """清空当前页面搜索词。"""
def _open_action_confirm(self, slot: str) -> None:
"""
打开指定槽位动作的确认弹窗。
:param slot: 动作槽位
- :return: None
"""
def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSidebar.Selected) -> None:
@@ -263,55 +256,30 @@ def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSide
根据侧栏事件打开对应视图。
:param event: 侧栏事件
- :return: None
"""
def action_open_search(self) -> None:
- """
- 打开当前页面搜索输入。
-
- :return: None
- """
+ """打开当前页面搜索输入。"""
self._open_search()
def action_clear_search(self) -> None:
- """
- 清空当前页面搜索词。
-
- :return: None
- """
+ """清空当前页面搜索词。"""
self._clear_search()
def action_trigger_primary_action(self) -> None:
- """
- 触发当前页面主动作。
-
- :return: None
- """
+ """触发当前页面主动作。"""
self._open_action_confirm('primary')
def action_trigger_secondary_action(self) -> None:
- """
- 触发当前页面次动作。
-
- :return: None
- """
+ """触发当前页面次动作。"""
self._open_action_confirm('secondary')
def action_trigger_global_action(self) -> None:
- """
- 触发当前页面全局动作。
-
- :return: None
- """
+ """触发当前页面全局动作。"""
self._open_action_confirm('global')
def action_trigger_utility_action(self) -> None:
- """
- 触发当前页面工具动作。
-
- :return: None
- """
+ """触发当前页面工具动作。"""
self._open_action_confirm('utility')
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/search.py b/ruoyi-fastapi-backend/cli/tui/screens/search.py
index fac67befe..a20f1215e 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/search.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/search.py
@@ -12,6 +12,12 @@ class SearchInputScreen(ModalScreen[str | None]):
"""
通用搜索输入弹窗。
+ :cvar CSS: 终端界面使用的样式规则
+ :cvar BINDINGS: 终端界面的快捷键和对应动作
+ :ivar _title: 输入框的标题
+ :ivar _placeholder: 输入框为空时的提示
+ :ivar _value: 输入框的当前内容
+ :ivar _suggestions: 可供选择的搜索建议
:param title: 弹窗标题
:param placeholder: 输入框提示
:param value: 当前搜索词
@@ -52,6 +58,14 @@ class SearchInputScreen(ModalScreen[str | None]):
]
def __init__(self, title: str, placeholder: str, value: str, suggestions: list[str]) -> None:
+ """
+ 设置搜索初始值、提示文字和候选项。
+
+ :param title: 弹窗标题
+ :param placeholder: 输入框提示
+ :param value: 当前搜索词
+ :param suggestions: 候选建议
+ """
super().__init__()
self._title = title
self._placeholder = placeholder
@@ -59,6 +73,11 @@ def __init__(self, title: str, placeholder: str, value: str, suggestions: list[s
self._suggestions = suggestions
def compose(self) -> ComposeResult:
+ """
+ 构建搜索输入框及操作控件。
+
+ :yield: 按显示顺序排列的界面组件
+ """
with Vertical(id='search-dialog'):
yield Static(self._title, id='search-title', markup=False)
yield Input(value=self._value, placeholder=self._placeholder, id='search-input')
@@ -66,15 +85,19 @@ def compose(self) -> ComposeResult:
yield Static(suggestion_text, id='search-suggestions', markup=False)
def on_mount(self) -> None:
+ """将焦点移到搜索输入框。"""
self.call_after_refresh(self.query_one('#search-input', Input).focus)
def action_cancel(self) -> None:
+ """取消搜索并关闭输入对话框。"""
self.dismiss(None)
def action_submit(self) -> None:
+ """提交当前输入的搜索条件。"""
input_widget = self.query_one('#search-input', Input)
self.dismiss(str(input_widget.value or '').strip())
@on(Input.Submitted, '#search-input')
def on_input_submitted(self) -> None:
+ """在输入框确认时提交搜索。"""
self.action_submit()
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/summary.py b/ruoyi-fastapi-backend/cli/tui/screens/summary.py
index f359cc801..99a3e6fcd 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/summary.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/summary.py
@@ -7,8 +7,10 @@ class StatusCarrier(Protocol):
"""
状态载体协议。
- 该协议用于描述首页面板、详情分区和浏览记录这类具备 `status`
+ 该协议用于描述首页面板、详情分区和浏览记录这类具备 ``status``
属性的摘要统计对象。
+
+ :ivar status: 操作或记录所处的状态
"""
status: str
@@ -19,10 +21,10 @@ class StatusSummary:
"""
状态摘要统计结果。
- :param total_count: 总数量
- :param ok_count: 正常数量
- :param warn_count: 警告数量
- :param fail_count: 失败数量
+ :ivar total_count: 总数量
+ :ivar ok_count: 正常数量
+ :ivar warn_count: 警告数量
+ :ivar fail_count: 失败数量
"""
total_count: int
@@ -35,7 +37,7 @@ class StatusSummaryBuilder:
"""
状态摘要构建器。
- 该对象负责对带 `status` 属性的集合做统一计数,供 dashboard、
+ 该对象负责对带 ``status`` 属性的集合做统一计数,供 dashboard、
detail、browser 三类 screen support 复用。
"""
diff --git a/ruoyi-fastapi-backend/cli/tui/search.py b/ruoyi-fastapi-backend/cli/tui/search.py
index e208dab34..1c09a44d5 100644
--- a/ruoyi-fastapi-backend/cli/tui/search.py
+++ b/ruoyi-fastapi-backend/cli/tui/search.py
@@ -7,9 +7,9 @@ class PageFilterOption:
"""
浏览页筛选项定义。
- :param key: 筛选键
- :param label: 展示名称
- :param shortcut: 快捷键
+ :ivar key: 筛选键
+ :ivar label: 展示名称
+ :ivar shortcut: 快捷键
"""
key: str
@@ -22,9 +22,9 @@ class PageSearchContext:
"""
浏览页搜索上下文定义。
- :param placeholder: 搜索输入提示
- :param query: 当前搜索词
- :param suggestions: 候选建议列表
+ :ivar placeholder: 搜索输入提示
+ :ivar query: 当前搜索词
+ :ivar suggestions: 候选建议列表
"""
placeholder: str
@@ -37,8 +37,8 @@ class SearchSuggestionProviderSpec:
"""
页面搜索建议提供者定义。
- :param placeholder: 搜索输入提示
- :param suggestion_provider: 候选建议提供函数
+ :ivar placeholder: 搜索输入提示
+ :ivar suggestion_provider: 候选建议提供函数
"""
placeholder: str
@@ -67,7 +67,7 @@ class TuiSearchSuggestionProviderRegistry:
该对象负责管理页面搜索提示文案及其候选建议提供函数,避免搜索服务
继续通过字符串反射隐式定位 completion provider。
- :param providers: 页面搜索提供者映射
+ :ivar providers: 页面搜索提供者映射
"""
def __init__(self, providers: dict[str, SearchSuggestionProviderSpec]) -> None:
@@ -75,7 +75,6 @@ def __init__(self, providers: dict[str, SearchSuggestionProviderSpec]) -> None:
初始化搜索建议提供者注册表。
:param providers: 页面搜索提供者映射
- :return: None
"""
self.providers = {self.normalize_view_key(key): value for key, value in providers.items()}
@@ -162,6 +161,8 @@ class TuiSearchService:
TUI 搜索服务。
该对象负责筛选项解析、筛选条文案构建、搜索上下文装配和详情分区过滤。
+
+ :ivar provider_registry: 页面搜索建议提供者注册表
"""
def __init__(self, provider_registry: TuiSearchSuggestionProviderRegistry) -> None:
@@ -169,7 +170,6 @@ def __init__(self, provider_registry: TuiSearchSuggestionProviderRegistry) -> No
初始化 TUI 搜索服务。
:param provider_registry: 页面搜索建议提供者注册表
- :return: None
"""
self.provider_registry = provider_registry
diff --git a/ruoyi-fastapi-backend/cli/tui/widgets/status_panel.py b/ruoyi-fastapi-backend/cli/tui/widgets/status_panel.py
index 94d8eddae..954c2b4e0 100644
--- a/ruoyi-fastapi-backend/cli/tui/widgets/status_panel.py
+++ b/ruoyi-fastapi-backend/cli/tui/widgets/status_panel.py
@@ -10,6 +10,8 @@ class StatusPanelRenderingSupport:
该对象负责状态类名解析、结构化正文渲染和信号带脉冲文本构建,
供状态面板、指标卡与信号带组件复用。
+
+ :cvar PULSE_FRAMES: 绘制脉冲动画的帧序列
"""
PULSE_FRAMES = ['·', '•', '◉', '•']
@@ -36,8 +38,9 @@ def render_structured_body(self, body: str) -> str:
将结构化正文文本渲染为更有层次的终端块内容。
支持以下约定:
- - `## ` 开头:分组标题
- - `> ` 开头:说明或子项
+
+ - ``##`` 后跟空格:分组标题
+ - ``>`` 后跟空格:说明或子项
- 空字符串:保留空行
:param body: 原始正文文本
@@ -88,9 +91,12 @@ class StatusPanel(Static):
"""
TUI 状态面板组件。
- :param title: 面板标题
- :param status: 面板状态
- :param body: 面板正文
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :ivar title: 面板标题
+ :ivar status: 面板状态
+ :ivar body: 面板正文
+ :ivar rendering: 状态面板渲染支持对象
+ :ivar can_focus: 组件是否可以接收键盘焦点
"""
DEFAULT_CSS = """
@@ -144,7 +150,6 @@ def __init__(
:param status: 面板状态
:param body: 面板正文
:param rendering: 状态面板渲染支持对象
- :return: None
"""
self.title = title
self.status = status
@@ -174,10 +179,12 @@ class MetricPanel(Static):
"""
TUI 首页驾驶舱指标卡组件。
- :param title: 指标标题
- :param value: 指标主值
- :param status: 指标状态
- :param hint: 指标补充说明
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :ivar title: 指标标题
+ :ivar value: 指标主值
+ :ivar status: 指标状态
+ :ivar hint: 指标补充说明
+ :ivar rendering: 状态面板渲染支持对象
"""
DEFAULT_CSS = """
@@ -238,7 +245,6 @@ def __init__(
:param hint: 指标补充说明
:param accent: 是否作为主指标高亮展示
:param rendering: 状态面板渲染支持对象
- :return: None
"""
self.title = title
self.value = value
@@ -270,7 +276,10 @@ class SignalRail(Static):
"""
首页信号带组件,用于展示简洁的系统态势条目。
- :param lines: 信号文本行
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :ivar lines: 信号文本行
+ :ivar _pulse_index: 当前脉冲动画帧的位置
+ :ivar rendering: 状态面板渲染支持对象
"""
DEFAULT_CSS = """
@@ -291,7 +300,6 @@ def __init__(self, lines: list[str], rendering: StatusPanelRenderingSupport | No
:param lines: 信号文本行
:param rendering: 状态面板渲染支持对象
- :return: None
"""
self.lines = lines
self._pulse_index = 0
@@ -299,20 +307,12 @@ def __init__(self, lines: list[str], rendering: StatusPanelRenderingSupport | No
super().__init__(self._build_render_text(), markup=False)
def on_mount(self) -> None:
- """
- 挂载后启动轻量脉冲刷新。
-
- :return: None
- """
+ """挂载后启动轻量脉冲刷新。"""
if not TUI_PLATFORM_POLICY.reduced_motion:
self.set_interval(0.8, self._advance_pulse, name='signal rail pulse')
def _advance_pulse(self) -> None:
- """
- 推进信号带脉冲状态。
-
- :return: None
- """
+ """推进信号带脉冲状态。"""
self._pulse_index = (self._pulse_index + 1) % 4
self.update(self._build_render_text())
diff --git a/ruoyi-fastapi-backend/cli/tui/widgets/workspace.py b/ruoyi-fastapi-backend/cli/tui/widgets/workspace.py
index 44bc96753..1a0bc37b7 100644
--- a/ruoyi-fastapi-backend/cli/tui/widgets/workspace.py
+++ b/ruoyi-fastapi-backend/cli/tui/widgets/workspace.py
@@ -94,8 +94,9 @@ def render_structured_lines(self, lines: list[str], empty_text: str) -> str:
将结构化文本行渲染为适合终端展示的块文本。
支持以下轻量约定:
- - `## ` 开头:区块标题
- - `> ` 开头:说明或子项
+
+ - ``##`` 后跟空格:区块标题
+ - ``>`` 后跟空格:说明或子项
- 空字符串:保留空行
:param lines: 原始文本行列表
@@ -139,10 +140,10 @@ class NavigationItem:
"""
工作台导航项定义。
- :param view_key: 视图唯一标识
- :param label: 导航显示名称
- :param shortcut: 快捷键
- :param description: 导航说明
+ :ivar view_key: 视图唯一标识
+ :ivar label: 导航显示名称
+ :ivar shortcut: 快捷键
+ :ivar description: 导航说明
"""
view_key: str
@@ -155,7 +156,8 @@ class NavigationListItem(ListItem):
"""
工作台导航列表项。
- :param item: 导航项定义
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :ivar item: 导航项定义
"""
DEFAULT_CSS = """
@@ -195,8 +197,9 @@ def __init__(self, item: NavigationItem, index: int, *, active: bool = False) ->
"""
初始化导航列表项。
+ :param index: 分区索引
+ :param active: 当前选中的项目
:param item: 导航项定义
- :return: None
"""
self.item = item
super().__init__(
@@ -213,9 +216,11 @@ class WorkspaceSidebar(ListView):
"""
工作台左侧导航组件。
- :param env: 当前运行环境
- :param items: 导航项列表
- :param active_view: 当前激活视图
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :ivar env: 当前运行环境
+ :ivar items: 导航项列表
+ :ivar active_view: 当前激活视图
+ :ivar navigation_ready: 导航组件是否已可接受交互
"""
DEFAULT_CSS = """
@@ -240,7 +245,6 @@ def __init__(self, env: str, items: list[NavigationItem], active_view: str) -> N
:param env: 当前运行环境
:param items: 导航项列表
:param active_view: 当前激活视图
- :return: None
"""
self.env = env
self.items = items
@@ -282,12 +286,15 @@ class WorkspaceHero(Static):
"""
工作台顶部摘要组件。
- :param title: 页面标题
- :param subtitle: 页面副标题
- :param env: 当前运行环境
- :param active_view: 当前激活视图
- :param summary: 状态摘要文本
- :param refreshed_at: 本次刷新时间
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :cvar _BORDER_PHASES: 边框动画各帧使用的阶段序列
+ :cvar _TITLE_GLOW_PALETTE: 标题发光效果使用的颜色
+ :ivar title: 页面标题
+ :ivar subtitle: 页面副标题
+ :ivar env: 当前运行环境
+ :ivar active_view: 当前激活视图
+ :ivar summary: 状态摘要文本
+ :ivar refreshed_at: 本次刷新时间
"""
DEFAULT_CSS = """
@@ -315,12 +322,12 @@ def __init__(
"""
初始化工作台顶部摘要组件。
+ :param env: 当前运行环境
:param title: 页面标题
:param subtitle: 页面副标题
:param active_view: 当前激活视图
:param summary: 状态摘要文本
:param refreshed_at: 本次刷新时间
- :return: None
"""
self.title = title
self.subtitle = subtitle
@@ -331,20 +338,12 @@ def __init__(
super().__init__(self._build_render_text(), id='workspace-hero', markup=False)
def on_mount(self) -> None:
- """
- 在组件挂载后启动低频边框呼吸动效。
-
- :return: None
- """
+ """在组件挂载后启动低频边框呼吸动效。"""
if not TUI_PLATFORM_POLICY.reduced_motion:
self.set_interval(0.9, self._pulse_border, name='pulse workspace hero border')
def _pulse_border(self) -> None:
- """
- 以低频节奏切换 Hero 边框颜色。
-
- :return: None
- """
+ """以低频节奏切换 Hero 边框颜色。"""
phase_index = int(monotonic() * 1.1) % len(self._BORDER_PHASES)
self.styles.border = ('double', self._BORDER_PHASES[phase_index])
@@ -393,8 +392,15 @@ class WorkspaceHeader(Static):
"""
工作台顶部状态栏。
- :param env: 当前运行环境
- :param active_view: 当前激活视图
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :cvar _HEADER_LINE_COUNT: 标题区域占用的行数
+ :cvar _SCANLINE_WIDTH: 扫描高亮区域的宽度
+ :cvar _HEADER_HORIZONTAL_PADDING: 标题两侧保留的空白宽度
+ :cvar _HEADER_FALLBACK_WIDTH: 无法取得布局宽度时使用的默认宽度
+ :cvar _SCANLINE_BASE_STYLE: 扫描线的基础样式
+ :cvar _SCANLINE_GLOW_STYLES: 扫描高亮各阶段的样式
+ :ivar env: 当前运行环境
+ :ivar active_view: 当前激活视图
"""
DEFAULT_CSS = """
@@ -449,18 +455,13 @@ def __init__(self, env: str, active_view: str) -> None:
:param env: 当前运行环境
:param active_view: 当前激活视图
- :return: None
"""
self.env = env
self.active_view = active_view
super().__init__(id='workspace-header', markup=False)
def on_mount(self) -> None:
- """
- 在组件挂载后启动时钟刷新。
-
- :return: None
- """
+ """在组件挂载后启动时钟刷新。"""
if not TUI_PLATFORM_POLICY.reduced_motion:
self.set_interval(0.18, self.refresh, name='update workspace header')
@@ -542,8 +543,11 @@ class SectionListItem(ListItem):
"""
详情页分区导航列表项。
- :param section: 分区快照
- :param index: 分区索引
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :ivar section: 分区快照
+ :ivar index: 分区索引
+ :ivar search_query: 当前搜索词
+ :ivar rendering: 工作台组件渲染支持对象
"""
DEFAULT_CSS = """
@@ -599,10 +603,10 @@ def __init__(
"""
初始化详情页分区导航项。
+ :param query: 搜索词
:param section: 分区快照
:param index: 分区索引
:param rendering: 工作台组件渲染支持对象
- :return: None
"""
self.section = section
self.index = index
@@ -629,7 +633,11 @@ class SectionNavigator(ListView):
"""
详情页分区导航组件。
- :param sections: 分区快照列表
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :ivar sections: 分区快照列表
+ :ivar search_query: 当前搜索词
+ :ivar rendering: 工作台组件渲染支持对象
+ :ivar index: 当前条目在序列中的位置
:param initial_index: 初始高亮索引
"""
@@ -651,9 +659,20 @@ class SectionNavigator(ListView):
class Changed(Message):
"""
分区导航高亮变更消息。
+
+ :ivar navigator: 协调界面和选中项切换的导航器
+ :ivar index: 当前条目在序列中的位置
+ :ivar item: 导航项定义
"""
def __init__(self, navigator: 'SectionNavigator', index: int, item: SectionListItem) -> None:
+ """
+ 保存触发选择变更的控件、索引和所选项。
+
+ :param navigator: 协调界面和选中项切换的导航器
+ :param index: 分区索引
+ :param item: 导航项定义
+ """
super().__init__()
self.navigator = navigator
self.index = index
@@ -661,6 +680,11 @@ def __init__(self, navigator: 'SectionNavigator', index: int, item: SectionListI
@property
def control(self) -> 'SectionNavigator':
+ """
+ 返回发出选择变更消息的导航控件。
+
+ :return: 发出选择变更消息的导航控件
+ """
return self.navigator
def __init__(
@@ -673,10 +697,10 @@ def __init__(
"""
初始化详情页分区导航。
+ :param query: 搜索词
:param sections: 分区快照列表
:param initial_index: 初始高亮索引
:param rendering: 工作台组件渲染支持对象
- :return: None
"""
self.sections = sections
self.search_query = query
@@ -693,7 +717,6 @@ def watch_index(self, old_index: int | None, new_index: int | None) -> None:
:param old_index: 旧索引
:param new_index: 新索引
- :return: None
"""
super().watch_index(old_index, new_index)
if new_index is None or not 0 <= new_index < len(self._nodes):
@@ -708,9 +731,9 @@ async def show_sections(
"""
刷新分区导航内容并恢复高亮位置。
+ :param query: 搜索词
:param sections: 最新分区快照列表
:param initial_index: 目标高亮索引
- :return: None
"""
self.sections = sections
self.search_query = query
@@ -730,7 +753,11 @@ class SectionDetailView(Static):
"""
详情页分区内容展示组件。
- :param section: 当前展示的分区快照
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :ivar section: 当前展示的分区快照
+ :ivar search_query: 当前搜索词
+ :ivar rendering: 工作台组件渲染支持对象
+ :ivar can_focus: 组件是否可以接收键盘焦点
"""
DEFAULT_CSS = """
@@ -780,9 +807,9 @@ def __init__(
"""
初始化详情页分区内容展示组件。
+ :param query: 搜索词
:param section: 当前展示的分区快照
:param rendering: 工作台组件渲染支持对象
- :return: None
"""
self.section = section
self.search_query = query
@@ -795,19 +822,15 @@ def show_section(self, section: DetailSectionSnapshot, query: str = '') -> None:
"""
切换并渲染当前展示的分区内容。
+ :param query: 搜索词
:param section: 待展示的分区快照
- :return: None
"""
self.section = section
self.search_query = query
self._render_section()
def _render_section(self) -> None:
- """
- 渲染当前分区内容。
-
- :return: None
- """
+ """渲染当前分区内容。"""
self.remove_class('is-ok', 'is-fail', 'is-warn', 'is-info')
self.add_class(self.rendering.resolve_status_class(self.section.status))
highlighted_lines = [
@@ -833,8 +856,11 @@ class RecordListItem(ListItem):
"""
浏览页记录导航列表项。
- :param record: 记录快照
- :param index: 记录索引
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :ivar record: 记录快照
+ :ivar index: 记录索引
+ :ivar search_query: 当前搜索词
+ :ivar rendering: 工作台组件渲染支持对象
"""
DEFAULT_CSS = """
@@ -890,10 +916,10 @@ def __init__(
"""
初始化浏览页记录导航项。
+ :param query: 搜索词
:param record: 记录快照
:param index: 记录索引
:param rendering: 工作台组件渲染支持对象
- :return: None
"""
self.record = record
self.index = index
@@ -919,7 +945,10 @@ class RecordNavigator(ListView):
"""
浏览页记录导航组件。
- :param records: 记录快照列表
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :ivar records: 记录快照列表
+ :ivar search_query: 当前搜索词
+ :ivar rendering: 工作台组件渲染支持对象
:param initial_index: 初始高亮索引
"""
@@ -941,9 +970,20 @@ class RecordNavigator(ListView):
class Changed(Message):
"""
记录导航高亮变更消息。
+
+ :ivar navigator: 协调界面和选中项切换的导航器
+ :ivar index: 当前条目在序列中的位置
+ :ivar item: 导航项定义
"""
def __init__(self, navigator: 'RecordNavigator', index: int, item: RecordListItem) -> None:
+ """
+ 保存触发选择变更的控件、索引和所选项。
+
+ :param navigator: 协调界面和选中项切换的导航器
+ :param index: 分区索引
+ :param item: 导航项定义
+ """
super().__init__()
self.navigator = navigator
self.index = index
@@ -951,6 +991,11 @@ def __init__(self, navigator: 'RecordNavigator', index: int, item: RecordListIte
@property
def control(self) -> 'RecordNavigator':
+ """
+ 返回发出选择变更消息的导航控件。
+
+ :return: 发出选择变更消息的导航控件
+ """
return self.navigator
def __init__(
@@ -963,10 +1008,10 @@ def __init__(
"""
初始化浏览页记录导航。
+ :param query: 搜索词
:param records: 记录快照列表
:param initial_index: 初始高亮索引
:param rendering: 工作台组件渲染支持对象
- :return: None
"""
self.records = records
self.search_query = query
@@ -982,7 +1027,6 @@ def watch_index(self, old_index: int | None, new_index: int | None) -> None:
:param old_index: 旧索引
:param new_index: 新索引
- :return: None
"""
super().watch_index(old_index, new_index)
if new_index is None or not 0 <= new_index < len(self._nodes):
@@ -996,8 +1040,12 @@ class RecordDetailView(Static):
"""
浏览页记录详情展示组件。
- :param record: 当前展示的记录快照
- :param shared_sections: 页面共享分区列表
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :ivar record: 当前展示的记录快照
+ :ivar shared_sections: 页面共享分区列表
+ :ivar search_query: 当前搜索词
+ :ivar rendering: 工作台组件渲染支持对象
+ :ivar can_focus: 组件是否可以接收键盘焦点
"""
DEFAULT_CSS = """
@@ -1044,10 +1092,10 @@ def __init__(
"""
初始化浏览页记录详情展示组件。
+ :param query: 搜索词
:param record: 当前展示的记录快照
:param shared_sections: 页面共享分区列表
:param rendering: 工作台组件渲染支持对象
- :return: None
"""
self.record = record
self.shared_sections = shared_sections
@@ -1066,9 +1114,9 @@ def show_record(
"""
切换并渲染当前展示的记录内容。
+ :param query: 搜索词
:param record: 待展示的记录快照
:param shared_sections: 页面共享分区列表
- :return: None
"""
self.record = record
self.shared_sections = shared_sections
@@ -1076,11 +1124,7 @@ def show_record(
self._render_record()
def _render_record(self) -> None:
- """
- 渲染当前记录内容。
-
- :return: None
- """
+ """渲染当前记录内容。"""
self.remove_class('is-ok', 'is-fail', 'is-warn', 'is-info')
self.add_class(self.rendering.resolve_status_class(self.record.status))
lines = [
@@ -1131,7 +1175,13 @@ class RecordSummaryView(Static):
"""
浏览页记录摘要展示组件。
- :param record: 当前展示的记录快照
+ :cvar DEFAULT_CSS: 组件默认使用的 Textual 样式规则
+ :ivar record: 当前展示的记录快照
+ :ivar section: 需要展示的详情分区
+ :ivar action_lines: 动作摘要文本
+ :ivar search_query: 当前搜索词
+ :ivar rendering: 工作台组件渲染支持对象
+ :ivar can_focus: 组件是否可以接收键盘焦点
"""
DEFAULT_CSS = """
@@ -1197,7 +1247,6 @@ def __init__(
:param record: 当前展示的记录快照
:param rendering: 工作台组件渲染支持对象
- :return: None
"""
self.record = record
self.section: DetailSectionSnapshot | None = None
@@ -1218,10 +1267,10 @@ def show_record(
"""
更新当前展示的记录摘要。
+ :param query: 搜索词
:param record: 待展示的记录快照
:param selected_section: 当前联动分区
:param action_lines: 动作摘要文本
- :return: None
"""
self.record = record
self.section = selected_section
@@ -1230,11 +1279,7 @@ def show_record(
self._render_record()
def _render_record(self) -> None:
- """
- 渲染当前记录摘要。
-
- :return: None
- """
+ """渲染当前记录摘要。"""
self.remove_class('is-ok', 'is-fail', 'is-warn', 'is-info')
self.remove_class('section-ok', 'section-fail', 'section-warn', 'section-info')
self.add_class(self.rendering.resolve_status_class(self.record.status))
diff --git a/ruoyi-fastapi-backend/cli/utils.py b/ruoyi-fastapi-backend/cli/utils.py
index a305a9409..83ab3db88 100644
--- a/ruoyi-fastapi-backend/cli/utils.py
+++ b/ruoyi-fastapi-backend/cli/utils.py
@@ -21,6 +21,9 @@ def format_cli_path(path: Path | str) -> str:
Windows 绝对路径保留盘符和原生格式;无盘符路径使用 POSIX 分隔符,
以保证虚拟 Unix 路径和跨平台 payload 的稳定性。
+
+ :param path: 要读取或处理的路径
+ :return: 用于 CLI 展示的文件路径
"""
path_object = Path(path)
return str(path_object) if path_object.drive else path_object.as_posix()
@@ -31,11 +34,11 @@ class NestedCliResult:
"""
内部 CLI 调用结果。
- :param command: 实际执行的命令参数列表
- :param returncode: 子进程退出码
- :param stdout: 标准输出文本
- :param stderr: 标准错误文本
- :param payload: 解析后的 JSON 负载,解析失败时为 None
+ :ivar command: 实际执行的命令参数列表
+ :ivar returncode: 子进程退出码
+ :ivar stdout: 标准输出文本
+ :ivar stderr: 标准错误文本
+ :ivar payload: 解析后的 JSON 负载,解析失败时为 None
"""
command: list[str]
@@ -80,10 +83,10 @@ def truncate_text(value: object, max_length: int) -> str:
@staticmethod
def to_snake_case(value: object) -> str:
"""
- 将字段名标准化为 `snake_case` 形式。
+ 将字段名标准化为 ``snake_case`` 形式。
:param value: 原始字段名
- :return: `snake_case` 字段名
+ :return: ``snake_case`` 字段名
"""
text = '' if value is None else str(value).strip()
if not text:
@@ -115,7 +118,7 @@ def resolve_project_dir(self) -> Path:
解析内部 CLI 子进程应使用的后端项目目录。
优先使用当前工作目录;若当前目录不是后端目录,则回退到当前
- `cli/utils.py` 所在代码树的上一层目录。
+ ``cli/utils.py`` 所在代码树的上一层目录。
:return: 后端项目根目录
"""
@@ -236,9 +239,9 @@ class NestedCliSupport:
该对象统一负责编排项目目录解析、环境注入、标准输出解析以及
实时执行/进程替换执行路径。
- :param project_locator: 项目目录定位器
- :param environment_builder: 子进程环境构建器
- :param payload_parser: 负载解析器
+ :ivar project_locator: 项目目录定位器
+ :ivar environment_builder: 子进程环境构建器
+ :ivar payload_parser: 负载解析器
"""
project_locator: NestedCliProjectLocator = field(default_factory=NestedCliProjectLocator)
@@ -363,7 +366,6 @@ def exec(self, *arguments: str) -> None:
以进程替换方式执行内部 CLI 命令。
:param arguments: CLI 参数列表
- :return: None
"""
project_dir = self.resolve_project_dir()
command = self.build_nested_cli_command(*arguments)
diff --git a/ruoyi-fastapi-backend/cli/wizard/aggregators.py b/ruoyi-fastapi-backend/cli/wizard/aggregators.py
index ade463912..5b49216ff 100644
--- a/ruoyi-fastapi-backend/cli/wizard/aggregators.py
+++ b/ruoyi-fastapi-backend/cli/wizard/aggregators.py
@@ -5,7 +5,7 @@
@dataclass(frozen=True)
class ProdCheckPayloadSupport:
"""
- `wizard prod-check` 结果提取支持对象。
+ ``wizard prod-check`` 结果提取支持对象。
该对象负责从多路只读结果中提取 runtime、doctor、config
片段,避免聚合器本体继续堆叠细碎字段判定逻辑。
@@ -45,7 +45,7 @@ def extract_config_payload(config_payload: dict[str, Any] | None) -> dict[str, A
@dataclass(frozen=True)
class ProdCheckStatusEvaluator:
"""
- `wizard prod-check` 状态评估器。
+ ``wizard prod-check`` 状态评估器。
该对象负责统一计算聚合结果的成功状态和标准消息。
"""
@@ -83,13 +83,13 @@ def build_message() -> str:
@dataclass(frozen=True)
class ProdCheckAggregator:
"""
- `wizard prod-check` 聚合器。
+ ``wizard prod-check`` 聚合器。
该对象负责聚合运行环境、应用检查和配置快照结果,
让 flow 本体只保留交互编排职责。
- :param payload_support: 结果提取支持对象
- :param status_evaluator: 状态评估器
+ :ivar payload_support: 结果提取支持对象
+ :ivar status_evaluator: 状态评估器
"""
payload_support: ProdCheckPayloadSupport = ProdCheckPayloadSupport()
diff --git a/ruoyi-fastapi-backend/cli/wizard/base.py b/ruoyi-fastapi-backend/cli/wizard/base.py
index b699087da..3d39292d7 100644
--- a/ruoyi-fastapi-backend/cli/wizard/base.py
+++ b/ruoyi-fastapi-backend/cli/wizard/base.py
@@ -19,8 +19,8 @@ class WizardInteractionSupport:
"""
向导交互与上下文构建支持对象。
- :param context_factory: CLI 上下文工厂
- :param prompt_service: 向导提示服务
+ :ivar context_factory: CLI 上下文工厂
+ :ivar prompt_service: 向导提示服务
"""
def __init__(
@@ -34,7 +34,6 @@ def __init__(
:param context_factory: CLI 上下文工厂
:param prompt_service: 向导提示服务
- :return: None
"""
self.context_factory = context_factory
self.prompt_service = prompt_service
@@ -85,8 +84,8 @@ class WizardResultSupport:
"""
向导结果收口支持对象。
- :param execution_service: CLI 执行服务
- :param preview_renderer: 向导预览渲染器
+ :ivar execution_service: CLI 执行服务
+ :ivar preview_renderer: 向导预览渲染器
"""
def __init__(
@@ -100,7 +99,6 @@ def __init__(
:param execution_service: CLI 执行服务
:param preview_renderer: 向导预览渲染器
- :return: None
"""
self.execution_service = execution_service
self.preview_renderer = preview_renderer
@@ -111,7 +109,6 @@ def complete_result(self, ctx: CliContext, result: CommandResult) -> None:
:param ctx: CLI 上下文
:param result: 命令结果对象
- :return: None
"""
self.execution_service.complete_result(ctx, result)
@@ -128,7 +125,6 @@ def complete_payload(
:param ctx: CLI 上下文
:param payload: 标准结果负载
:param default_exit_code: 默认退出码
- :return: None
"""
self.execution_service.complete_payload(ctx, payload, default_exit_code=default_exit_code)
@@ -149,7 +145,6 @@ def complete_payload_result(
:param text_builder: 文本结果构建函数
:param default_exit_code: 默认退出码
:param text_condition: 文本模式结果构建判定函数
- :return: None
"""
self.execution_service.complete_payload_result(
ctx,
@@ -181,8 +176,8 @@ class WizardNestedCommandSupport:
"""
向导内部 CLI 调用支持对象。
- :param command_runner: 内部 CLI 子进程调用函数
- :param live_command_runner: 内部 CLI 实时执行函数
+ :ivar command_runner: 内部 CLI 子进程调用函数
+ :ivar live_command_runner: 内部 CLI 实时执行函数
"""
def __init__(
@@ -196,7 +191,6 @@ def __init__(
:param command_runner: 内部 CLI 子进程调用函数
:param live_command_runner: 内部 CLI 实时执行函数
- :return: None
"""
self.command_runner = command_runner
self.live_command_runner = live_command_runner
@@ -242,7 +236,7 @@ class WizardExecutionResultSupport:
该对象负责提取内部 CLI 结果的 payload、退出码与错误文本,并构建
默认失败负载,让模板基类不再直接持有结果翻译细节。
- :param failure_message: 默认失败提示
+ :ivar failure_message: 默认失败提示
"""
def __init__(self, *, failure_message: str) -> None:
@@ -250,7 +244,6 @@ def __init__(self, *, failure_message: str) -> None:
初始化执行结果翻译支持对象。
:param failure_message: 默认失败提示
- :return: None
"""
self.failure_message = failure_message
@@ -316,9 +309,13 @@ class WizardSupportCache:
向导协作者缓存。
该对象负责延迟构建并复用当前 flow 需要的 interaction/result/nested
- support collaborator,让 `BaseCliWizardFlow` 回到模板骨架与桥接层角色。
+ support collaborator,让 ``BaseCliWizardFlow`` 回到模板骨架与桥接层角色。
- :param owner: 当前向导 flow
+ :ivar owner: 当前向导 flow
+ :ivar _interaction_support: 负责处理向导交互的组件
+ :ivar _result_support: 将执行结果转换为向导输出的组件
+ :ivar _nested_command_support: 支持在向导内调用子命令的组件
+ :ivar _execution_result_support: 解析命令退出状态及输出的组件
"""
def __init__(self, owner: 'BaseCliWizardFlow[Any]') -> None:
@@ -326,7 +323,6 @@ def __init__(self, owner: 'BaseCliWizardFlow[Any]') -> None:
初始化向导协作者缓存。
:param owner: 当前向导 flow
- :return: None
"""
self.owner = owner
self._interaction_support: WizardInteractionSupport | None = None
@@ -397,6 +393,10 @@ class BaseNestedCommandWizardFlow(ABC, Generic[SelectionT]):
子类需要提供参数采集、上下文构建、预览摘要、执行参数和
结果收口策略,从而复用向导的通用交互主链路。
+
+ :ivar wizard_name: 向导名称
+ :ivar preview_title: 预览标题
+ :ivar failure_message: 默认失败提示
"""
wizard_name: str
@@ -408,7 +408,6 @@ def run(self, output: OutputOption = 'text') -> None:
执行向导主流程。
:param output: 输出格式
- :return: None
"""
selection = self.collect_selection()
self.prepare_execution_state(selection, output)
@@ -470,7 +469,6 @@ def prepare_execution_state(self, selection: SelectionT, output: OutputOption) -
:param selection: 向导采集结果
:param output: 输出格式
- :return: None
"""
del selection, output
@@ -479,7 +477,7 @@ def handle_execution_result(self, ctx: CliContext, nested_result: Any, output: O
允许子类在默认 payload 收口前接管执行结果。
该钩子适用于需要切换到 live exec、实时终端占用或其他非标准 payload
- 收口路径的少数 flow。返回 `True` 表示结果已处理完成。
+ 收口路径的少数 flow。返回 ``True`` 表示结果已处理完成。
:param ctx: CLI 上下文
:param nested_result: 执行结果
@@ -610,7 +608,6 @@ def complete_result(self, ctx: CliContext, result: CommandResult) -> None:
:param ctx: CLI 上下文
:param result: 命令结果
- :return: None
"""
@abstractmethod
@@ -643,7 +640,6 @@ def complete_payload(
:param ctx: CLI 上下文
:param payload: 结果负载
:param default_exit_code: 默认退出码
- :return: None
"""
def execute(self, selection: SelectionT, output: OutputOption) -> Any:
@@ -673,6 +669,14 @@ class BaseCliWizardFlow(BaseNestedCommandWizardFlow[SelectionT], ABC):
该基类在通用向导主链路之上继续下沉当前项目稳定复用的桥接逻辑,
包括确认交互、上下文构建、命令结果收口与内部 CLI 调用封装。
+
+ :cvar context_factory: CLI 上下文工厂
+ :cvar execution_service: CLI 执行服务
+ :cvar prompt_service: 向导提示服务
+ :cvar preview_renderer: 向导预览渲染器
+ :cvar nested_command_runner: 在向导内运行子命令的回调
+ :cvar nested_live_command_runner: 运行子命令并实时输出进度的回调
+ :ivar _support_cache: 按需复用向导支持组件的缓存
"""
context_factory: ClassVar[CliContextFactory] = DEFAULT_CORE_SERVICES.context_factory
@@ -688,8 +692,6 @@ def __init__(self) -> None:
该基类通过协作者缓存稳定持有交互、结果收口和内部 CLI 调用 support,
避免模板方法执行过程中重复构建同类对象。
-
- :return: None
"""
self._support_cache: WizardSupportCache | None = None
@@ -697,7 +699,7 @@ def get_support_cache(self) -> WizardSupportCache:
"""
返回当前向导使用的协作者缓存。
- 保持惰性创建,以兼容未显式调用基类 `__init__` 的现有 flow。
+ 保持惰性创建,以兼容未显式调用基类 ``__init__`` 的现有 flow。
:return: 协作者缓存
"""
@@ -791,7 +793,6 @@ def complete_result(self, ctx: CliContext, result: CommandResult) -> None:
:param ctx: CLI 上下文
:param result: 命令结果对象
- :return: None
"""
self.get_result_support().complete_result(ctx, result)
@@ -808,7 +809,6 @@ def complete_payload(
:param ctx: CLI 上下文
:param payload: 标准结果负载
:param default_exit_code: 默认退出码
- :return: None
"""
self.get_result_support().complete_payload(ctx, payload, default_exit_code=default_exit_code)
@@ -829,7 +829,6 @@ def complete_payload_result(
:param text_builder: 文本结果构建函数
:param default_exit_code: 默认退出码
:param text_condition: 文本模式结果构建判定函数
- :return: None
"""
self.get_result_support().complete_payload_result(
ctx,
@@ -880,9 +879,9 @@ class BaseLiveExecCliWizardFlow(BaseCliWizardFlow[SelectionT], ABC):
统一封装“确认后切换到实时终端执行路径”的 CLI 向导基类。
该特化基类用于少量不走 JSON payload 收口,而是在确认后直接
- 切换到现有命令实时执行链路的向导场景,例如 `wizard app-run`。
+ 切换到现有命令实时执行链路的向导场景,例如 ``wizard app-run``。
它在保留预览与确认模板骨架的前提下,显式表达“执行阶段即完成收口”,
- 避免子类再通过覆写 `complete_payload()` 或 `handle_execution_result()`
+ 避免子类再通过覆写 ``complete_payload()`` 或 ``handle_execution_result()``
实现规避式短路。
"""
@@ -892,7 +891,6 @@ def execute(self, selection: SelectionT, output: OutputOption) -> None:
:param selection: 向导采集结果
:param output: 输出格式
- :return: None
"""
self.exec_nested_command(*self.build_execute_arguments(selection, output))
diff --git a/ruoyi-fastapi-backend/cli/wizard/commands.py b/ruoyi-fastapi-backend/cli/wizard/commands.py
index 18067accc..33807d8f4 100644
--- a/ruoyi-fastapi-backend/cli/wizard/commands.py
+++ b/ruoyi-fastapi-backend/cli/wizard/commands.py
@@ -14,8 +14,8 @@ class WizardCommandRegistration:
"""
wizard 子命令注册元数据。
- :param name: 子命令名称
- :param help_text: 子命令帮助文案
+ :ivar name: 子命令名称
+ :ivar help_text: 子命令帮助文案
:param registrar: 对应的注册器函数
"""
@@ -28,7 +28,7 @@ class WizardFlowLoader:
wizard flow 惰性加载器。
该对象负责在命令真正执行时导入对应 flow,
- 避免 `wizard` 入口在模块导入阶段提前拉起全部向导依赖。
+ 避免 ``wizard`` 入口在模块导入阶段提前拉起全部向导依赖。
"""
def load_runner(self, module_name: str, function_name: str) -> Callable[..., None]:
@@ -48,7 +48,7 @@ class WizardCommandBuilder:
"""
wizard 子命令构建器。
- :param flow_loader: wizard flow 惰性加载器
+ :ivar flow_loader: wizard flow 惰性加载器
"""
flow_loader: WizardFlowLoader = field(default_factory=WizardFlowLoader)
@@ -72,7 +72,6 @@ def register_commands(self, app: typer.Typer) -> None:
向 Typer 子应用注册全部 wizard 子命令。
:param app: wizard 子应用
- :return: None
"""
for registration, registrar in self.iter_command_registrars():
registrar(app, registration)
@@ -82,7 +81,7 @@ def iter_command_registrars(self) -> tuple[tuple[WizardCommandRegistration, Wiza
返回向导命令注册元数据与显式注册器映射。
该方法将命令声明与注册函数绑定关系显式化,避免继续依赖
- `registrar_name -> getattr(self, ...)` 的字符串分发。
+ ``registrar_name -> getattr(self, ...)`` 的字符串分发。
:return: 注册元数据与注册器映射列表
"""
@@ -115,29 +114,23 @@ def iter_command_registrars(self) -> tuple[tuple[WizardCommandRegistration, Wiza
def _register_app_run_command(self, app: typer.Typer, registration: WizardCommandRegistration) -> None:
"""
- 注册 `app-run` 子命令。
+ 注册 ``app-run`` 子命令。
:param app: wizard 子应用
:param registration: 子命令注册元数据
- :return: None
"""
@app.command(registration.name, help=registration.help_text)
def app_run() -> None:
- """
- 通过交互方式启动应用。
-
- :return: None
- """
+ """通过交互方式启动应用。"""
self.flow_loader.load_runner('cli.wizard.flows.app_run', 'run_app_run_wizard')()
def _register_db_upgrade_command(self, app: typer.Typer, registration: WizardCommandRegistration) -> None:
"""
- 注册 `db-upgrade` 子命令。
+ 注册 ``db-upgrade`` 子命令。
:param app: wizard 子应用
:param registration: 子命令注册元数据
- :return: None
"""
@app.command(registration.name, help=registration.help_text)
@@ -156,7 +149,6 @@ def db_upgrade(
:param default_env: 向导默认环境
:param default_revision: 向导默认目标 revision
:param default_dry_run: 向导默认 dry-run 选项
- :return: None
"""
self.flow_loader.load_runner('cli.wizard.flows.db_upgrade', 'run_db_upgrade_wizard')(
output,
@@ -167,11 +159,10 @@ def db_upgrade(
def _register_cache_clear_command(self, app: typer.Typer, registration: WizardCommandRegistration) -> None:
"""
- 注册 `cache-clear` 子命令。
+ 注册 ``cache-clear`` 子命令。
:param app: wizard 子应用
:param registration: 子命令注册元数据
- :return: None
"""
@app.command(registration.name, help=registration.help_text)
@@ -194,7 +185,6 @@ def cache_clear(
:param default_cache_name: 向导默认缓存名称前缀
:param default_cache_key: 向导默认缓存键关键字
:param default_dry_run: 向导默认 dry-run 选项
- :return: None
"""
self.flow_loader.load_runner('cli.wizard.flows.cache_clear', 'run_cache_clear_wizard')(
output,
@@ -207,11 +197,10 @@ def cache_clear(
def _register_gen_export_command(self, app: typer.Typer, registration: WizardCommandRegistration) -> None:
"""
- 注册 `gen-export` 子命令。
+ 注册 ``gen-export`` 子命令。
:param app: wizard 子应用
:param registration: 子命令注册元数据
- :return: None
"""
@app.command(registration.name, help=registration.help_text)
@@ -234,7 +223,6 @@ def gen_export(
:param default_mode: 向导默认导出模式
:param default_output_file: 向导默认导出目标文件路径
:param default_dry_run: 向导默认 dry-run 选项
- :return: None
"""
self.flow_loader.load_runner('cli.wizard.flows.gen_export', 'run_gen_export_wizard')(
output,
@@ -247,11 +235,10 @@ def gen_export(
def _register_gen_import_command(self, app: typer.Typer, registration: WizardCommandRegistration) -> None:
"""
- 注册 `gen-import` 子命令。
+ 注册 ``gen-import`` 子命令。
:param app: wizard 子应用
:param registration: 子命令注册元数据
- :return: None
"""
@app.command(registration.name, help=registration.help_text)
@@ -270,7 +257,6 @@ def gen_import(
:param default_env: 向导默认环境
:param default_table_names: 向导默认物理表名称列表
:param default_dry_run: 向导默认 dry-run 选项
- :return: None
"""
self.flow_loader.load_runner('cli.wizard.flows.gen_import', 'run_gen_import_wizard')(
output,
@@ -281,11 +267,10 @@ def gen_import(
def _register_prod_check_command(self, app: typer.Typer, registration: WizardCommandRegistration) -> None:
"""
- 注册 `prod-check` 子命令。
+ 注册 ``prod-check`` 子命令。
:param app: wizard 子应用
:param registration: 子命令注册元数据
- :return: None
"""
@app.command(registration.name, help=registration.help_text)
@@ -304,7 +289,6 @@ def prod_check(
:param output: 输出格式
:param default_env: 向导默认环境
:param default_include_config: 向导默认是否附带配置快照
- :return: None
"""
self.flow_loader.load_runner('cli.wizard.flows.prod_check', 'run_prod_check_wizard')(
output,
diff --git a/ruoyi-fastapi-backend/cli/wizard/flows/app_run.py b/ruoyi-fastapi-backend/cli/wizard/flows/app_run.py
index 1e392653f..600c8bf76 100644
--- a/ruoyi-fastapi-backend/cli/wizard/flows/app_run.py
+++ b/ruoyi-fastapi-backend/cli/wizard/flows/app_run.py
@@ -8,10 +8,10 @@
@dataclass(frozen=True)
class AppRunWizardSelection:
"""
- `wizard app-run` 向导采集结果。
+ ``wizard app-run`` 向导采集结果。
- :param env: 运行环境
- :param run_doctor: 启动前是否先执行应用检查
+ :ivar env: 运行环境
+ :ivar run_doctor: 启动前是否先执行应用检查
"""
env: str
@@ -20,9 +20,12 @@ class AppRunWizardSelection:
class AppRunWizardFlow(BaseLiveExecCliWizardFlow[AppRunWizardSelection]):
"""
- `wizard app-run` 向导流程。
+ ``wizard app-run`` 向导流程。
- :param doctor_payload: 启动前检查结果缓存
+ :cvar wizard_name: 向导名称
+ :cvar preview_title: 预览标题
+ :cvar failure_message: 流程失败时显示的提示
+ :ivar doctor_payload: 启动前检查结果缓存
"""
wizard_name = 'wizard app-run'
@@ -117,11 +120,7 @@ def build_execute_arguments(self, selection: AppRunWizardSelection, output: str)
return ['app', 'run', f'--env={selection.env}']
def __init__(self) -> None:
- """
- 初始化应用启动向导流程。
-
- :return: None
- """
+ """初始化应用启动向导流程。"""
super().__init__()
self.doctor_payload: dict[str, Any] | None = None
@@ -131,7 +130,6 @@ def prepare_execution_state(self, selection: AppRunWizardSelection, output: str)
:param selection: 向导采集结果
:param output: 输出格式
- :return: None
"""
del output
self.doctor_payload = None
@@ -144,9 +142,5 @@ def prepare_execution_state(self, selection: AppRunWizardSelection, output: str)
def run_app_run_wizard() -> None:
- """
- 执行 `wizard app-run` 向导。
-
- :return: None
- """
+ """执行 ``wizard app-run`` 向导。"""
AppRunWizardFlow().run('text')
diff --git a/ruoyi-fastapi-backend/cli/wizard/flows/cache_clear.py b/ruoyi-fastapi-backend/cli/wizard/flows/cache_clear.py
index 4d4226647..2db7c93f1 100644
--- a/ruoyi-fastapi-backend/cli/wizard/flows/cache_clear.py
+++ b/ruoyi-fastapi-backend/cli/wizard/flows/cache_clear.py
@@ -7,14 +7,14 @@
@dataclass(frozen=True)
class CacheClearWizardSelection:
"""
- `wizard cache-clear` 向导采集结果。
-
- :param env: 运行环境
- :param mode: 清理模式
- :param cache_name: 缓存名称前缀
- :param cache_key: 缓存键名关键字
- :param dry_run: 是否演练执行
- :param allow_prod: 是否允许生产环境执行
+ ``wizard cache-clear`` 向导采集结果。
+
+ :ivar env: 运行环境
+ :ivar mode: 清理模式
+ :ivar cache_name: 缓存名称前缀
+ :ivar cache_key: 缓存键名关键字
+ :ivar dry_run: 是否演练执行
+ :ivar allow_prod: 是否允许生产环境执行
"""
env: str
@@ -27,13 +27,16 @@ class CacheClearWizardSelection:
class CacheClearWizardFlow(BaseCliWizardFlow[CacheClearWizardSelection]):
"""
- `wizard cache-clear` 向导流程。
-
- :param default_env: 默认环境
- :param default_mode: 默认清理模式
- :param default_cache_name: 默认缓存名称前缀
- :param default_cache_key: 默认缓存键名关键字
- :param default_dry_run: 默认是否先执行 dry-run
+ ``wizard cache-clear`` 向导流程。
+
+ :cvar wizard_name: 向导名称
+ :cvar preview_title: 预览标题
+ :cvar failure_message: 流程失败时显示的提示
+ :ivar default_env: 默认环境
+ :ivar default_mode: 默认清理模式
+ :ivar default_cache_name: 默认缓存名称前缀
+ :ivar default_cache_key: 默认缓存键名关键字
+ :ivar default_dry_run: 默认是否先执行 dry-run
"""
wizard_name = 'wizard cache-clear'
@@ -57,7 +60,6 @@ def __init__(
:param default_cache_name: 默认缓存名称前缀
:param default_cache_key: 默认缓存键名关键字
:param default_dry_run: 默认是否先执行 dry-run
- :return: None
"""
self.default_env = default_env
self.default_mode = default_mode
@@ -194,7 +196,7 @@ def run_cache_clear_wizard(
default_dry_run: bool = True,
) -> None:
"""
- 执行 `wizard cache-clear` 向导。
+ 执行 ``wizard cache-clear`` 向导。
:param output: 输出格式
:param default_env: 默认环境
@@ -202,7 +204,6 @@ def run_cache_clear_wizard(
:param default_cache_name: 默认缓存名称前缀
:param default_cache_key: 默认缓存键关键字
:param default_dry_run: 默认是否执行 dry-run
- :return: None
"""
CacheClearWizardFlow(
default_env=default_env,
diff --git a/ruoyi-fastapi-backend/cli/wizard/flows/db_upgrade.py b/ruoyi-fastapi-backend/cli/wizard/flows/db_upgrade.py
index 1d75ff2af..7008d87fd 100644
--- a/ruoyi-fastapi-backend/cli/wizard/flows/db_upgrade.py
+++ b/ruoyi-fastapi-backend/cli/wizard/flows/db_upgrade.py
@@ -7,12 +7,12 @@
@dataclass(frozen=True)
class DbUpgradeWizardSelection:
"""
- `wizard db-upgrade` 向导采集结果。
+ ``wizard db-upgrade`` 向导采集结果。
- :param env: 运行环境
- :param revision: 目标迁移版本
- :param dry_run: 是否演练执行
- :param allow_prod: 是否允许生产环境执行
+ :ivar env: 运行环境
+ :ivar revision: 目标迁移版本
+ :ivar dry_run: 是否演练执行
+ :ivar allow_prod: 是否允许生产环境执行
"""
env: str
@@ -23,11 +23,14 @@ class DbUpgradeWizardSelection:
class DbUpgradeWizardFlow(BaseCliWizardFlow[DbUpgradeWizardSelection]):
"""
- `wizard db-upgrade` 向导流程。
-
- :param default_env: 默认环境
- :param default_revision: 默认目标 revision
- :param default_dry_run: 默认是否先执行 dry-run
+ ``wizard db-upgrade`` 向导流程。
+
+ :cvar wizard_name: 向导名称
+ :cvar preview_title: 预览标题
+ :cvar failure_message: 流程失败时显示的提示
+ :ivar default_env: 默认环境
+ :ivar default_revision: 默认目标 revision
+ :ivar default_dry_run: 默认是否先执行 dry-run
"""
wizard_name = 'wizard db-upgrade'
@@ -47,7 +50,6 @@ def __init__(
:param default_env: 默认环境
:param default_revision: 默认目标 revision
:param default_dry_run: 默认是否先执行 dry-run
- :return: None
"""
self.default_env = default_env
self.default_revision = default_revision
@@ -154,13 +156,12 @@ def run_db_upgrade_wizard(
default_dry_run: bool = True,
) -> None:
"""
- 执行 `wizard db-upgrade` 向导。
+ 执行 ``wizard db-upgrade`` 向导。
:param output: 输出格式
:param default_env: 默认环境
:param default_revision: 默认目标 revision
:param default_dry_run: 默认是否先 dry-run
- :return: None
"""
DbUpgradeWizardFlow(
default_env=default_env,
diff --git a/ruoyi-fastapi-backend/cli/wizard/flows/gen_export.py b/ruoyi-fastapi-backend/cli/wizard/flows/gen_export.py
index 96632b6d9..7a774d531 100644
--- a/ruoyi-fastapi-backend/cli/wizard/flows/gen_export.py
+++ b/ruoyi-fastapi-backend/cli/wizard/flows/gen_export.py
@@ -9,14 +9,14 @@
@dataclass(frozen=True)
class GenExportWizardSelection:
"""
- `wizard gen-export` 向导采集结果。
-
- :param env: 运行环境
- :param table_names: 业务表名称列表
- :param mode: 导出模式
- :param output_file: zip 导出目标文件路径
- :param dry_run: 是否演练执行
- :param allow_prod: 是否允许生产环境执行
+ ``wizard gen-export`` 向导采集结果。
+
+ :ivar env: 运行环境
+ :ivar table_names: 业务表名称列表
+ :ivar mode: 导出模式
+ :ivar output_file: zip 导出目标文件路径
+ :ivar dry_run: 是否演练执行
+ :ivar allow_prod: 是否允许生产环境执行
"""
env: str
@@ -29,13 +29,16 @@ class GenExportWizardSelection:
class GenExportWizardFlow(BaseCliWizardFlow[GenExportWizardSelection]):
"""
- `wizard gen-export` 向导流程。
-
- :param default_env: 默认环境
- :param default_table_names: 默认业务表名称列表文本
- :param default_mode: 默认导出模式
- :param default_output_file: 默认 zip 导出目标文件路径
- :param default_dry_run: 默认是否先执行 dry-run
+ ``wizard gen-export`` 向导流程。
+
+ :cvar wizard_name: 向导名称
+ :cvar preview_title: 预览标题
+ :cvar failure_message: 流程失败时显示的提示
+ :ivar default_env: 默认环境
+ :ivar default_table_names: 默认业务表名称列表文本
+ :ivar default_mode: 默认导出模式
+ :ivar default_output_file: 默认 zip 导出目标文件路径
+ :ivar default_dry_run: 默认是否先执行 dry-run
"""
wizard_name = 'wizard gen-export'
@@ -59,7 +62,6 @@ def __init__(
:param default_mode: 默认导出模式
:param default_output_file: 默认 zip 导出目标文件路径
:param default_dry_run: 默认是否先执行 dry-run
- :return: None
"""
self.default_env = default_env
self.default_table_names = default_table_names
@@ -220,7 +222,7 @@ def run_gen_export_wizard(
default_dry_run: bool = True,
) -> None:
"""
- 执行 `wizard gen-export` 向导。
+ 执行 ``wizard gen-export`` 向导。
:param output: 输出格式
:param default_env: 默认环境
@@ -228,7 +230,6 @@ def run_gen_export_wizard(
:param default_mode: 默认导出模式
:param default_output_file: 默认 zip 导出目标文件路径
:param default_dry_run: 默认是否先 dry-run
- :return: None
"""
GenExportWizardFlow(
default_env=default_env,
diff --git a/ruoyi-fastapi-backend/cli/wizard/flows/gen_import.py b/ruoyi-fastapi-backend/cli/wizard/flows/gen_import.py
index e3363b700..e167d0b70 100644
--- a/ruoyi-fastapi-backend/cli/wizard/flows/gen_import.py
+++ b/ruoyi-fastapi-backend/cli/wizard/flows/gen_import.py
@@ -9,12 +9,12 @@
@dataclass(frozen=True)
class GenImportWizardSelection:
"""
- `wizard gen-import` 向导采集结果。
+ ``wizard gen-import`` 向导采集结果。
- :param env: 运行环境
- :param table_names: 待导入物理表名称列表
- :param dry_run: 是否演练执行
- :param allow_prod: 是否允许生产环境执行
+ :ivar env: 运行环境
+ :ivar table_names: 待导入物理表名称列表
+ :ivar dry_run: 是否演练执行
+ :ivar allow_prod: 是否允许生产环境执行
"""
env: str
@@ -25,11 +25,14 @@ class GenImportWizardSelection:
class GenImportWizardFlow(BaseCliWizardFlow[GenImportWizardSelection]):
"""
- `wizard gen-import` 向导流程。
-
- :param default_env: 默认环境
- :param default_table_names: 默认物理表名称列表文本
- :param default_dry_run: 默认是否先执行 dry-run
+ ``wizard gen-import`` 向导流程。
+
+ :cvar wizard_name: 向导名称
+ :cvar preview_title: 预览标题
+ :cvar failure_message: 流程失败时显示的提示
+ :ivar default_env: 默认环境
+ :ivar default_table_names: 默认物理表名称列表文本
+ :ivar default_dry_run: 默认是否先执行 dry-run
"""
wizard_name = 'wizard gen-import'
@@ -49,7 +52,6 @@ def __init__(
:param default_env: 默认环境
:param default_table_names: 默认物理表名称列表文本
:param default_dry_run: 默认是否先执行 dry-run
- :return: None
"""
self.default_env = default_env
self.default_table_names = default_table_names
@@ -193,13 +195,12 @@ def run_gen_import_wizard(
default_dry_run: bool = True,
) -> None:
"""
- 执行 `wizard gen-import` 向导。
+ 执行 ``wizard gen-import`` 向导。
:param output: 输出格式
:param default_env: 默认环境
:param default_table_names: 默认物理表名称列表文本
:param default_dry_run: 默认是否先 dry-run
- :return: None
"""
GenImportWizardFlow(
default_env=default_env,
diff --git a/ruoyi-fastapi-backend/cli/wizard/flows/prod_check.py b/ruoyi-fastapi-backend/cli/wizard/flows/prod_check.py
index 9bed6b75a..81067ffc2 100644
--- a/ruoyi-fastapi-backend/cli/wizard/flows/prod_check.py
+++ b/ruoyi-fastapi-backend/cli/wizard/flows/prod_check.py
@@ -10,10 +10,10 @@
@dataclass(frozen=True)
class ProdCheckWizardSelection:
"""
- `wizard prod-check` 向导采集结果。
+ ``wizard prod-check`` 向导采集结果。
- :param env: 运行环境
- :param include_config: 是否附带配置快照
+ :ivar env: 运行环境
+ :ivar include_config: 是否附带配置快照
"""
env: str
@@ -22,10 +22,15 @@ class ProdCheckWizardSelection:
class ProdCheckWizardFlow(BaseCliWizardFlow[ProdCheckWizardSelection]):
"""
- `wizard prod-check` 向导流程。
-
- :param default_env: 默认环境
- :param default_include_config: 默认是否附带配置快照
+ ``wizard prod-check`` 向导流程。
+
+ :cvar wizard_name: 向导名称
+ :cvar preview_title: 预览标题
+ :cvar failure_message: 流程失败时显示的提示
+ :ivar default_env: 默认环境
+ :ivar default_include_config: 默认是否附带配置快照
+ :ivar aggregator: 汇总各项检查结果的对象
+ :ivar presenter: 将检查结果转换为界面输出的对象
"""
wizard_name = 'wizard prod-check'
@@ -43,7 +48,6 @@ def __init__(
:param default_env: 默认环境
:param default_include_config: 默认是否附带配置快照
- :return: None
"""
super().__init__()
self.default_env = default_env
@@ -175,7 +179,6 @@ def complete_payload(
:param ctx: CLI 上下文
:param payload: 聚合结果负载
:param default_exit_code: 默认退出码
- :return: None
"""
self.complete_payload_result(
ctx,
@@ -211,12 +214,11 @@ def run_prod_check_wizard(
default_include_config: bool = True,
) -> None:
"""
- 执行 `wizard prod-check` 向导。
+ 执行 ``wizard prod-check`` 向导。
:param output: 输出格式
:param default_env: 默认环境
:param default_include_config: 默认是否附带配置快照
- :return: None
"""
ProdCheckWizardFlow(
default_env=default_env,
diff --git a/ruoyi-fastapi-backend/cli/wizard/presenters.py b/ruoyi-fastapi-backend/cli/wizard/presenters.py
index a0eea0b4d..133d35658 100644
--- a/ruoyi-fastapi-backend/cli/wizard/presenters.py
+++ b/ruoyi-fastapi-backend/cli/wizard/presenters.py
@@ -5,7 +5,7 @@
@dataclass(frozen=True)
class ProdCheckRenderingSupport:
"""
- `wizard prod-check` 文本渲染支持对象。
+ ``wizard prod-check`` 文本渲染支持对象。
该对象负责构建 runtime、doctor、config 分区文本行,
避免 presenter 本体继续维护全部分区细节。
@@ -61,12 +61,12 @@ def build_config_lines(config: dict[str, Any]) -> list[str]:
@dataclass(frozen=True)
class ProdCheckPresenter:
"""
- `wizard prod-check` 结果展示器。
+ ``wizard prod-check`` 结果展示器。
该对象负责将聚合结果转换为文本摘要,
避免在 flow 内继续维护文本渲染细节。
- :param rendering_support: 文本渲染支持对象
+ :ivar rendering_support: 文本渲染支持对象
"""
rendering_support: ProdCheckRenderingSupport = ProdCheckRenderingSupport()
diff --git a/ruoyi-fastapi-backend/common/annotation/cache_annotation.py b/ruoyi-fastapi-backend/common/annotation/cache_annotation.py
index 5f5c63587..f42d197d2 100644
--- a/ruoyi-fastapi-backend/common/annotation/cache_annotation.py
+++ b/ruoyi-fastapi-backend/common/annotation/cache_annotation.py
@@ -24,14 +24,12 @@
class ApiCacheManager:
- """
- 接口缓存键与命名空间管理工具类
- """
+ """接口缓存键与命名空间管理工具类。"""
@classmethod
async def clear_namespace(cls, redis: aioredis.Redis, namespace: str) -> int:
"""
- 清理指定命名空间下的接口缓存
+ 清理指定命名空间下的接口缓存。
:param redis: Redis连接对象
:param namespace: 缓存命名空间
@@ -42,7 +40,7 @@ async def clear_namespace(cls, redis: aioredis.Redis, namespace: str) -> int:
@classmethod
async def clear_all(cls, redis: aioredis.Redis) -> int:
"""
- 清理所有接口缓存
+ 清理所有接口缓存。
:param redis: Redis连接对象
:return: 删除的缓存数量
@@ -52,7 +50,7 @@ async def clear_all(cls, redis: aioredis.Redis) -> int:
@classmethod
async def clear_namespaces(cls, redis: aioredis.Redis, namespaces: list[str] | tuple[str, ...] | set[str]) -> int:
"""
- 批量清理多个命名空间下的接口缓存
+ 批量清理多个命名空间下的接口缓存。
:param redis: Redis连接对象
:param namespaces: 需要清理的缓存命名空间列表
@@ -67,7 +65,7 @@ async def clear_namespaces(cls, redis: aioredis.Redis, namespaces: list[str] | t
@classmethod
async def clear_namespace_prefix(cls, redis: aioredis.Redis, namespace_prefix: str) -> int:
"""
- 按命名空间前缀清理接口缓存
+ 按命名空间前缀清理接口缓存。
:param redis: Redis连接对象
:param namespace_prefix: 缓存命名空间前缀
@@ -82,7 +80,7 @@ async def clear_namespace_prefixes(
namespace_prefixes: list[str] | tuple[str, ...] | set[str],
) -> int:
"""
- 批量按命名空间前缀清理接口缓存
+ 批量按命名空间前缀清理接口缓存。
:param redis: Redis连接对象
:param namespace_prefixes: 需要清理的缓存命名空间前缀列表
@@ -97,7 +95,7 @@ async def clear_namespace_prefixes(
@classmethod
def build_namespace_pattern(cls, namespace: str) -> str:
"""
- 生成命名空间扫描表达式
+ 生成命名空间扫描表达式。
:param namespace: 缓存命名空间
:return: 缓存键扫描匹配模式
@@ -107,7 +105,7 @@ def build_namespace_pattern(cls, namespace: str) -> str:
@classmethod
def build_namespace_prefix_pattern(cls, namespace_prefix: str) -> str:
"""
- 生成命名空间前缀扫描表达式
+ 生成命名空间前缀扫描表达式。
:param namespace_prefix: 缓存命名空间前缀
:return: 缓存键扫描匹配模式
@@ -117,7 +115,7 @@ def build_namespace_prefix_pattern(cls, namespace_prefix: str) -> str:
@classmethod
async def _clear_by_pattern(cls, redis: aioredis.Redis, pattern: str) -> int:
"""
- 根据扫描表达式清理匹配的接口缓存
+ 根据扫描表达式清理匹配的接口缓存。
:param redis: Redis连接对象
:param pattern: 缓存键扫描匹配模式
@@ -131,13 +129,11 @@ async def _clear_by_pattern(cls, redis: aioredis.Redis, pattern: str) -> int:
class _ApiCacheSupport:
- """
- 接口缓存装饰器共用工具基类
- """
+ """接口缓存装饰器共用工具基类。"""
def _load_json_content(self, response_body: str) -> Any | None:
"""
- 解析JSON响应体内容
+ 解析JSON响应体内容。
:param response_body: JSON字符串响应体
:return: 解析后的Python对象,解析失败时返回None
@@ -149,7 +145,7 @@ def _load_json_content(self, response_body: str) -> Any | None:
def _extract_json_response_content(self, result: Any) -> Any | None:
"""
- 提取响应中的JSON内容
+ 提取响应中的JSON内容。
:param result: 原始接口返回结果
:return: 解析后的JSON内容,无法提取时返回None
@@ -167,7 +163,7 @@ def _extract_json_response_content(self, result: Any) -> Any | None:
def _match_response_codes(self, response_content: Any, response_codes: set[int]) -> bool:
"""
- 判断响应内容中的业务响应码是否匹配
+ 判断响应内容中的业务响应码是否匹配。
:param response_content: JSON响应内容
:param response_codes: 允许的业务响应码集合
@@ -184,7 +180,7 @@ def _match_response_codes(self, response_content: Any, response_codes: set[int])
def _get_matched_response_content(self, result: Any, response_codes: set[int]) -> Any | None:
"""
- 提取并校验满足业务响应码要求的JSON响应内容
+ 提取并校验满足业务响应码要求的JSON响应内容。
:param result: 原始接口返回结果
:param response_codes: 允许的业务响应码集合
@@ -199,7 +195,13 @@ def _get_matched_response_content(self, result: Any, response_codes: set[int]) -
class ApiCache(_ApiCacheSupport):
"""
- 接口缓存装饰器,仅用于幂等且返回JSON的接口
+ 接口缓存装饰器,仅用于幂等且返回JSON的接口。
+
+ :ivar namespace: 缓存命名空间,用于区分不同接口类型
+ :ivar expire_seconds: 缓存过期时间,单位秒
+ :ivar vary_by_user: 是否按当前登录用户隔离缓存
+ :ivar methods: 允许启用缓存的HttpMethod枚举列表,为None时默认仅缓存GET请求
+ :ivar cache_response_codes: 允许缓存的业务响应码,为None时默认仅缓存成功响应
"""
def __init__(
@@ -211,7 +213,7 @@ def __init__(
cache_response_codes: set[int] | None = None,
) -> None:
"""
- 初始化接口缓存装饰器
+ 初始化接口缓存装饰器。
:param namespace: 缓存命名空间,用于区分不同接口类型
:param expire_seconds: 缓存过期时间,单位秒
@@ -229,7 +231,7 @@ def __init__(
def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]:
"""
- 为目标异步接口函数增加接口缓存能力
+ 为目标异步接口函数增加接口缓存能力。
:param func: 需要被缓存的异步接口函数
:return: 包装后的异步接口函数
@@ -237,6 +239,13 @@ def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]
@wraps(func)
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ """
+ 读取匹配请求的接口缓存,并在缓存未命中时执行接口。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 匹配请求的接口缓存
+ """
request, redis = ApiAnnotationUtil.resolve_request_redis(
func, '当前应用未初始化Redis连接,跳过接口缓存', *args, **kwargs
)
@@ -263,7 +272,7 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
def _is_request_method_allowed(self, request: Request) -> bool:
"""
- 判断当前请求方法是否允许启用接口缓存
+ 判断当前请求方法是否允许启用接口缓存。
:param request: 当前请求对象
:return: 是否允许缓存
@@ -272,7 +281,7 @@ def _is_request_method_allowed(self, request: Request) -> bool:
async def _build_cache_key(self, request: Request, *, catalog_fingerprint: str | None = None) -> str:
"""
- 根据当前请求生成稳定缓存键
+ 根据当前请求生成稳定缓存键。
:param request: 当前请求对象
:param catalog_fingerprint: 本次请求使用的词库版本指纹,未提供时读取当前指纹
@@ -306,7 +315,7 @@ async def _build_cache_key(self, request: Request, *, catalog_fingerprint: str |
def _get_user_scope(self, request: Request) -> str:
"""
- 获取用户隔离维度
+ 获取用户隔离维度。
优先使用当前登录用户ID,未登录时回退到Authorization摘要。
@@ -322,7 +331,7 @@ def _get_user_scope(self, request: Request) -> str:
def _serialize_response(self, result: Any) -> str | None:
"""
- 将响应对象序列化为可存入缓存的字符串
+ 将响应对象序列化为可存入缓存的字符串。
:param result: 原始接口返回结果
:return: 序列化后的缓存内容,不可缓存时返回None
@@ -335,7 +344,7 @@ def _serialize_response(self, result: Any) -> str | None:
def _extract_response_payload(self, result: Any) -> dict[str, Any] | None:
"""
- 提取可缓存的响应载荷
+ 提取可缓存的响应载荷。
:param result: 原始接口返回结果
:return: 可缓存的响应载荷,不可缓存时返回None
@@ -375,7 +384,7 @@ def _extract_response_payload(self, result: Any) -> dict[str, Any] | None:
def _build_cached_response(self, cached_response: str) -> JSONResponse:
"""
- 根据缓存内容重建JSON响应对象
+ 根据缓存内容重建JSON响应对象。
:param cached_response: 缓存中读取到的响应字符串
:return: 重建后的JSON响应对象
@@ -394,12 +403,11 @@ def _build_cached_response(self, cached_response: str) -> JSONResponse:
async def _cache_response(self, redis: aioredis.Redis, cache_key: str, result: Any) -> None:
"""
- 将接口响应写入接口缓存
+ 将接口响应写入接口缓存。
:param redis: Redis连接对象
:param cache_key: 接口缓存键
:param result: 原始接口返回结果
- :return: None
"""
serialized_response = self._serialize_response(result)
if serialized_response is None:
@@ -410,7 +418,7 @@ async def _cache_response(self, redis: aioredis.Redis, cache_key: str, result: A
def _filter_response_headers(self, headers: dict[str, str]) -> dict[str, str]:
"""
- 过滤不适合直接回放的响应头
+ 过滤不适合直接回放的响应头。
:param headers: 原始响应头
:return: 过滤后的响应头
@@ -420,7 +428,7 @@ def _filter_response_headers(self, headers: dict[str, str]) -> dict[str, str]:
def _refresh_response_time(self, response_content: Any) -> Any:
"""
- 刷新项目统一响应体中的time字段
+ 刷新项目统一响应体中的time字段。
:param response_content: JSON响应内容
:return: 刷新time后的响应内容
@@ -438,7 +446,11 @@ def _refresh_response_time(self, response_content: Any) -> Any:
class ApiCacheEvict(_ApiCacheSupport):
"""
- 接口缓存失效装饰器,用于在写操作成功后统一清理相关缓存
+ 接口缓存失效装饰器,用于在写操作成功后统一清理相关缓存。
+
+ :ivar namespaces: 需要失效的缓存命名空间列表
+ :ivar namespace_prefixes: 需要失效的缓存命名空间前缀列表
+ :ivar evict_response_codes: 允许触发失效的业务响应码,默认为仅成功响应触发
"""
def __init__(
@@ -448,11 +460,12 @@ def __init__(
evict_response_codes: set[int] | None = None,
) -> None:
"""
- 初始化接口缓存失效装饰器
+ 初始化接口缓存失效装饰器。
:param namespaces: 需要失效的缓存命名空间列表
:param namespace_prefixes: 需要失效的缓存命名空间前缀列表
:param evict_response_codes: 允许触发失效的业务响应码,默认为仅成功响应触发
+ :raises ValueError: ApiCacheEvict至少需要指定namespaces或namespace_prefixes
"""
self.namespaces = tuple(dict.fromkeys(namespaces or ()))
self.namespace_prefixes = tuple(dict.fromkeys(namespace_prefixes or ()))
@@ -465,7 +478,7 @@ def __init__(
def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]:
"""
- 为目标异步接口函数增加缓存失效能力
+ 为目标异步接口函数增加缓存失效能力。
:param func: 需要在成功后触发缓存失效的异步接口函数
:return: 包装后的异步接口函数
@@ -473,6 +486,13 @@ def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]
@wraps(func)
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ """
+ 在接口成功执行后失效相关缓存。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 执行当前操作得到的结果
+ """
result = await func(*args, **kwargs)
_, redis = ApiAnnotationUtil.resolve_request_redis(
func, '当前应用未初始化Redis连接,跳过接口缓存失效', *args, **kwargs
@@ -489,10 +509,9 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
async def _evict_cache(self, redis: aioredis.Redis) -> None:
"""
- 根据配置统一执行接口缓存失效
+ 根据配置统一执行接口缓存失效。
:param redis: Redis连接对象
- :return: None
"""
if self.namespaces:
await ApiCacheManager.clear_namespaces(redis, self.namespaces)
@@ -502,7 +521,7 @@ async def _evict_cache(self, redis: aioredis.Redis) -> None:
def _should_evict(self, result: Any) -> bool:
"""
- 判断当前响应是否应触发缓存失效
+ 判断当前响应是否应触发缓存失效。
:param result: 原始接口返回结果
:return: 是否触发缓存失效
diff --git a/ruoyi-fastapi-backend/common/annotation/log_annotation.py b/ruoyi-fastapi-backend/common/annotation/log_annotation.py
index d7cac84bd..fb465e25a 100644
--- a/ruoyi-fastapi-backend/common/annotation/log_annotation.py
+++ b/ruoyi-fastapi-backend/common/annotation/log_annotation.py
@@ -46,13 +46,11 @@
class _LogFieldRoot(StrEnum):
- """
- 日志字段路径根节点
- """
+ """日志字段路径根节点。"""
def field(self, *parts: str) -> str:
"""
- 生成 include 字段路径
+ 生成 include 字段路径。
:param parts: 后续字段路径片段
:return: 完整字段路径
@@ -62,7 +60,14 @@ def field(self, *parts: str) -> str:
class RequestLogFieldRoot(_LogFieldRoot):
"""
- 请求日志字段路径支持的根节点
+ 请求日志字段路径支持的根节点。
+
+ :cvar PATH_PARAMS: 请求路径中的参数
+ :cvar QUERY_PARAMS: URL 查询参数
+ :cvar JSON_BODY: 解析后的 JSON 请求体
+ :cvar FORM_DATA: 请求表单数据
+ :cvar FILES: 随请求上传的文件
+ :cvar RAW_BODY: 未解析的请求体
"""
PATH_PARAMS = 'path_params'
@@ -75,7 +80,14 @@ class RequestLogFieldRoot(_LogFieldRoot):
class ResponseLogFieldRoot(_LogFieldRoot):
"""
- 响应日志字段路径推荐的根节点
+ 响应日志字段路径推荐的根节点。
+
+ :cvar CODE: 业务响应的状态码
+ :cvar MSG: 业务响应的消息文本
+ :cvar DATA: 业务响应的数据字段
+ :cvar ROWS: 分页响应的记录集合
+ :cvar SUCCESS: 业务响应的成功标志
+ :cvar TIME: 业务响应的时间字段
"""
CODE = 'code'
@@ -88,7 +100,7 @@ class ResponseLogFieldRoot(_LogFieldRoot):
class Log:
"""
- 日志装饰器
+ 日志装饰器。
支持的日志模式:
- `full`: 记录脱敏后的完整载荷
@@ -98,25 +110,42 @@ class Log:
- `exclude`: 记录完整载荷后排除少数字段,适合中敏感接口
模式建议:
- - 普通后台管理接口可使用`full`
- - 包含大量字段但只关心结构时使用`summary`
- - 包含密钥、密码、提示词、配置项等高敏感字段时优先使用`include`
- - 字段较多但只需排除极少数字段时可使用`exclude`
- - 完全无需保留请求体或响应体时使用`none`
+ - 普通后台管理接口可使用 ``full``
+ - 包含大量字段但只关心结构时使用 ``summary``
+ - 包含密钥、密码、提示词、配置项等高敏感字段时优先使用 ``include``
+ - 字段较多但只需排除极少数字段时可使用 ``exclude``
+ - 完全无需保留请求体或响应体时使用 ``none``
include / exclude 模式字段路径规则:
- - 使用`.`分隔路径,如`json_body.modelCode`、`data.userId`
- - 请求日志推荐根节点:`path_params`、`query_params`、`json_body`、`form_data`、`files`、`raw_body`
- - 响应日志推荐根节点:`code`、`msg`、`data`、`rows`、`success`、`time`
+ - 使用 ``.`` 分隔路径,如 ``json_body.modelCode``、``data.userId``
+ - 请求日志推荐根节点:``path_params``、``query_params``、``json_body``、``form_data``、``files``、``raw_body``
+ - 响应日志推荐根节点:``code``、``msg``、``data``、``rows``、``success``、``time``
- 字段名优先按原样精确匹配,若未命中会自动尝试 snake_case、camelCase、kebab-case 归一化匹配
- - 数组使用数字下标,如`rows.0.userName`
+ - 数组使用数字下标,如 ``rows.0.userName``
- 当前不支持通配符
- - 推荐优先使用`RequestLogFieldRoot.JSON_BODY.field(...)`和`ResponseLogFieldRoot.DATA.field(...)`构造字段路径
+ - 推荐优先使用 ``RequestLogFieldRoot.JSON_BODY.field(...)`` 和 ``ResponseLogFieldRoot.DATA.field(...)`` 构造字段路径
示例:
- - `request_include_fields=(RequestLogFieldRoot.JSON_BODY.field('model_code'),)`
- - `response_include_fields=(ResponseLogFieldRoot.DATA.field('userName'),)`
- - `request_exclude_fields=('json_body.api_key',)`
+ - ``request_include_fields=(RequestLogFieldRoot.JSON_BODY.field('model_code'),)``
+ - ``response_include_fields=(ResponseLogFieldRoot.DATA.field('userName'),)``
+ - ``request_exclude_fields=('json_body.api_key',)``
+
+ :cvar _REQUEST_INCLUDE_ROOTS: 允许在请求日志白名单中使用的根字段
+ :cvar _RESPONSE_INCLUDE_ROOTS: 允许在响应日志白名单中使用的根字段
+ :cvar _MISSING: 标识字段不存在的哨兵对象
+ :cvar _AMBIGUOUS: 标识字段匹配到多个候选项的哨兵对象
+ :ivar title: 当前日志装饰器装饰的模块标题
+ :ivar business_type: 业务类型(OTHER其它 INSERT新增 UPDATE修改 DELETE删除 GRANT授权 EXPORT导出 IMPORT导入 FORCE强退 GENCODE生成代码 CLEAN清空数据)
+ :ivar log_type: 日志类型;``login`` 表示登录日志,仅落登录信息,``operation`` 表示操作日志,会落请求/响应摘要与操作人信息
+ :ivar request_log_mode: 请求日志记录模式;``full`` 记录脱敏后的完整请求,``none`` 不记录请求体,``summary`` 记录请求摘要,``include`` 仅记录request_include_fields指定的字段,``exclude`` 记录完整请求后排除request_exclude_fields指定的字段
+ :ivar response_log_mode: 响应日志记录模式;``full`` 记录脱敏后的完整响应,``none`` 不记录响应体,``summary`` 记录响应摘要,``include`` 仅记录response_include_fields指定的字段,``exclude`` 记录完整响应后排除response_exclude_fields指定的字段
+ :ivar request_include_fields: 请求日志白名单字段路径,仅在request_log_mode='include'时生效;推荐从path_params/query_params/json_body/form_data/files/raw_body开始,字段名支持 snake_case 与 camelCase 自动兼容
+ :ivar response_include_fields: 响应日志白名单字段路径,仅在response_log_mode='include'时生效;推荐从code/msg/data/rows/success/time开始,字段名支持 snake_case 与 camelCase 自动兼容
+ :ivar request_exclude_fields: 请求日志排除字段路径,仅在request_log_mode='exclude'时生效;推荐从path_params/query_params/json_body/form_data/files/raw_body开始,字段名支持 snake_case 与 camelCase 自动兼容
+ :ivar response_exclude_fields: 响应日志排除字段路径,仅在response_log_mode='exclude'时生效;推荐从code/msg/data/rows/success/time开始,字段名支持 snake_case 与 camelCase 自动兼容
+ :ivar _oper_param_len: 操作日志允许保存的请求参数长度
+ :ivar _json_result_len: 操作日志允许保存的响应文本长度
+ :ivar _warned_field_path_warnings: 已发出警告的字段路径
"""
_REQUEST_INCLUDE_ROOTS = tuple(item.value for item in RequestLogFieldRoot)
@@ -137,18 +166,17 @@ def __init__(
response_exclude_fields: tuple[str, ...] | None = None,
) -> None:
"""
- 日志装饰器
+ 日志装饰器。
:param title: 当前日志装饰器装饰的模块标题
:param business_type: 业务类型(OTHER其它 INSERT新增 UPDATE修改 DELETE删除 GRANT授权 EXPORT导出 IMPORT导入 FORCE强退 GENCODE生成代码 CLEAN清空数据)
- :param log_type: 日志类型;`login`表示登录日志,仅落登录信息,`operation`表示操作日志,会落请求/响应摘要与操作人信息
- :param request_log_mode: 请求日志记录模式;`full`记录脱敏后的完整请求,`none`不记录请求体,`summary`记录请求摘要,`include`仅记录request_include_fields指定的字段,`exclude`记录完整请求后排除request_exclude_fields指定的字段
- :param response_log_mode: 响应日志记录模式;`full`记录脱敏后的完整响应,`none`不记录响应体,`summary`记录响应摘要,`include`仅记录response_include_fields指定的字段,`exclude`记录完整响应后排除response_exclude_fields指定的字段
+ :param log_type: 日志类型;``login`` 表示登录日志,仅落登录信息,``operation`` 表示操作日志,会落请求/响应摘要与操作人信息
+ :param request_log_mode: 请求日志记录模式;``full`` 记录脱敏后的完整请求,``none`` 不记录请求体,``summary`` 记录请求摘要,``include`` 仅记录request_include_fields指定的字段,``exclude`` 记录完整请求后排除request_exclude_fields指定的字段
+ :param response_log_mode: 响应日志记录模式;``full`` 记录脱敏后的完整响应,``none`` 不记录响应体,``summary`` 记录响应摘要,``include`` 仅记录response_include_fields指定的字段,``exclude`` 记录完整响应后排除response_exclude_fields指定的字段
:param request_include_fields: 请求日志白名单字段路径,仅在request_log_mode='include'时生效;推荐从path_params/query_params/json_body/form_data/files/raw_body开始,字段名支持 snake_case 与 camelCase 自动兼容
:param response_include_fields: 响应日志白名单字段路径,仅在response_log_mode='include'时生效;推荐从code/msg/data/rows/success/time开始,字段名支持 snake_case 与 camelCase 自动兼容
:param request_exclude_fields: 请求日志排除字段路径,仅在request_log_mode='exclude'时生效;推荐从path_params/query_params/json_body/form_data/files/raw_body开始,字段名支持 snake_case 与 camelCase 自动兼容
:param response_exclude_fields: 响应日志排除字段路径,仅在response_log_mode='exclude'时生效;推荐从code/msg/data/rows/success/time开始,字段名支持 snake_case 与 camelCase 自动兼容
- :return:
"""
self.title = title
self.business_type = business_type.value
@@ -166,8 +194,23 @@ def __init__(
self._warn_invalid_field_path_config()
def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]:
+ """
+ 为接口添加操作日志或登录日志记录。
+
+ :param func: 装饰器包装的可调用对象
+ :return: 供调用方使用的 ``wrapper``
+ """
+
@wraps(func)
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ """
+ 执行接口并根据日志策略记录请求、响应及耗时。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises Exception: 被装饰操作抛出异常,记录操作日志后将其重新抛出
+ :return: 执行当前操作得到的结果
+ """
start_time = time.perf_counter()
# 获取当前被装饰函数所在路径
func_path = self._get_decorator_func_path(func)
@@ -247,9 +290,7 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
# 根据日志类型向对应的日志表插入数据
if self.log_type == 'login':
# 登录请求来自于api文档时不记录登录日志,其余情况则记录
- if request_from_swagger or request_from_redoc:
- pass
- else:
+ if not (request_from_swagger or request_from_redoc):
user = kwargs.get('form_data')
login_log.update(
{
@@ -263,7 +304,6 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
await LogQueueService.enqueue_login_log(request, LogininforModel(**login_log), func_path)
else:
current_user = RequestContext.get_current_user()
- oper_name = current_user.user.user_name
dept_name = current_user.user.dept.dept_name if current_user.user.dept else None
operation_log = OperLogModel(
title=self.title,
@@ -271,7 +311,7 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
method=func_path,
requestMethod=request_method,
operatorType=operator_type,
- operName=oper_name,
+ operName=current_user.user.user_name,
deptName=dept_name,
operUrl=oper_url,
operIp=oper_ip,
@@ -296,7 +336,7 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
def _get_decorator_func_path(self, func: Callable) -> str:
"""
- 获取被装饰函数所在路径
+ 获取被装饰函数所在路径。
:param func: 被装饰函数
:return: 被装饰函数所在路径
@@ -313,7 +353,7 @@ def _get_decorator_func_path(self, func: Callable) -> str:
@staticmethod
def _limit_log_text(log_text: str, max_length: int, overflow_text: str) -> str:
"""
- 限制日志文本长度,避免超过日志表字段长度
+ 限制日志文本长度,避免超过日志表字段长度。
:param log_text: 原始日志文本
:param max_length: 最大长度
@@ -324,7 +364,7 @@ def _limit_log_text(log_text: str, max_length: int, overflow_text: str) -> str:
def _get_oper_type(self, user_agent: Any) -> int:
"""
- 获取操作类型
+ 获取操作类型。
:param user_agent: 用户代理字符串
:return: 操作类型
@@ -340,7 +380,7 @@ def _get_oper_type(self, user_agent: Any) -> int:
async def _get_oper_location(self, oper_ip: str) -> str:
"""
- 获取请求IP归属区域
+ 获取请求IP归属区域。
:param oper_ip: 请求IP
:return: 请求IP归属区域
@@ -353,7 +393,7 @@ async def _get_oper_location(self, oper_ip: str) -> str:
async def _get_request_params(self, request: Request) -> dict[str, Any]:
"""
- 获取请求参数
+ 获取请求参数。
:param request: Request对象
:return: 结构化请求参数
@@ -384,7 +424,7 @@ async def _get_request_params(self, request: Request) -> dict[str, Any]:
async def _get_json_request_params(self, request: Request, content_type: str) -> dict[str, Any]:
"""
- 获取 JSON 请求参数,解析失败时自动降级为原始文本
+ 获取 JSON 请求参数,解析失败时自动降级为原始文本。
:param request: Request对象
:param content_type: 请求头中的 content-type
@@ -408,7 +448,7 @@ async def _get_json_request_params(self, request: Request, content_type: str) ->
async def _get_form_request_params(self, request: Request, content_type: str) -> dict[str, Any]:
"""
- 获取表单请求参数
+ 获取表单请求参数。
:param request: Request对象
:param content_type: 请求头中的 content-type
@@ -443,7 +483,7 @@ async def _get_form_request_params(self, request: Request, content_type: str) ->
async def _get_raw_request_params(self, request: Request) -> dict[str, Any]:
"""
- 获取原始文本请求参数
+ 获取原始文本请求参数。
:param request: Request对象
:return: 原始文本请求参数
@@ -456,7 +496,7 @@ async def _get_raw_request_params(self, request: Request) -> dict[str, Any]:
@staticmethod
def _decode_request_body(body: bytes) -> str:
"""
- 安全解码请求体,避免日志采集影响主流程
+ 安全解码请求体,避免日志采集影响主流程。
:param body: 原始请求体字节
:return: 解码后的请求体文本
@@ -472,7 +512,7 @@ def _build_log_text(
payload_kind: Literal['request', 'response'],
) -> str:
"""
- 根据日志策略构建日志文本
+ 根据日志策略构建日志文本。
:param payload: 已完成脱敏的日志载荷
:param mode: 日志记录模式
@@ -495,7 +535,7 @@ def _build_log_text(
def _build_summary_payload(self, payload: Any, payload_kind: Literal['request', 'response']) -> dict[str, Any]:
"""
- 构建摘要日志载荷
+ 构建摘要日志载荷。
:param payload: 原始载荷
:param payload_kind: 载荷类型
@@ -538,7 +578,7 @@ def _extract_include_fields(
payload_kind: Literal['request', 'response'],
) -> dict[str, Any]:
"""
- 提取白名单字段日志载荷
+ 提取白名单字段日志载荷。
:param payload: 原始载荷
:param include_fields: 白名单字段路径
@@ -564,7 +604,7 @@ def _exclude_fields(
payload_kind: Literal['request', 'response'],
) -> Any:
"""
- 排除指定字段后返回日志载荷
+ 排除指定字段后返回日志载荷。
:param payload: 原始载荷
:param exclude_fields: 排除字段路径
@@ -587,13 +627,12 @@ def _warn_missing_field_path(
strategy: Literal['include', 'exclude'],
) -> None:
"""
- 记录未命中的字段路径告警,同一路径仅提示一次
+ 记录未命中的字段路径告警,同一路径仅提示一次。
:param payload: 原始载荷
:param field_path: 字段路径
:param payload_kind: 载荷类型
:param strategy: 当前字段路径策略
- :return: None
"""
warning_key = f'{strategy}:{payload_kind}:{field_path}'
if warning_key in self._warned_field_path_warnings:
@@ -614,7 +653,7 @@ def _warn_missing_field_path(
def _describe_missing_field_path(self, payload: Any, field_path: str) -> str:
"""
- 描述字段路径未命中的原因
+ 描述字段路径未命中的原因。
:param payload: 原始载荷
:param field_path: 字段路径
@@ -654,11 +693,7 @@ def _describe_missing_field_path(self, payload: Any, field_path: str) -> str:
return ''
def _warn_invalid_field_path_config(self) -> None:
- """
- 记录字段路径配置告警,帮助开发者发现路径误配
-
- :return: None
- """
+ """记录字段路径配置告警,帮助开发者发现路径误配。"""
warnings = [
*self._collect_field_path_warnings(
mode=self.request_log_mode,
@@ -678,9 +713,9 @@ def _warn_invalid_field_path_config(self) -> None:
def _validate_request_field_paths_strict(self) -> None:
"""
- 严格校验请求日志字段路径根节点
+ 严格校验请求日志字段路径根节点。
- :return: None
+ :raises ValueError: 请求日志字段路径使用不支持的根节点
"""
field_paths = ()
if self.request_log_mode == 'include':
@@ -705,7 +740,7 @@ def _collect_field_path_warnings(
payload_kind: Literal['request', 'response'],
) -> list[str]:
"""
- 收集字段路径配置告警信息
+ 收集字段路径配置告警信息。
:param mode: 日志记录模式
:param include_fields: 白名单字段路径列表
@@ -746,7 +781,7 @@ def _validate_field_path(
strategy: Literal['include', 'exclude'],
) -> str | None:
"""
- 校验单个字段路径
+ 校验单个字段路径。
:param field_path: 字段路径
:param payload_kind: 载荷类型
@@ -771,7 +806,7 @@ def _validate_field_path(
def _get_field_value_by_path(self, payload: Any, field_path: str) -> Any:
"""
- 通过字段路径获取字段值
+ 通过字段路径获取字段值。
:param payload: 原始载荷
:param field_path: 字段路径
@@ -795,7 +830,7 @@ def _get_field_value_by_path(self, payload: Any, field_path: str) -> Any:
def _get_mapping_value_by_part(self, payload: dict[str, Any], part: str) -> Any:
"""
- 从字典中按字段片段获取值,支持 snake_case / camelCase / kebab-case 自动兼容
+ 从字典中按字段片段获取值,支持 snake_case / camelCase / kebab-case 自动兼容。
:param payload: 当前字典载荷
:param part: 当前路径片段
@@ -814,7 +849,7 @@ def _get_mapping_value_by_part(self, payload: dict[str, Any], part: str) -> Any:
@staticmethod
def _sort_field_paths_for_exclude(field_paths: tuple[str, ...]) -> list[str]:
"""
- 对 exclude 字段路径排序,优先处理更深层路径和更大的列表下标,避免列表删除时发生索引位移
+ 对 exclude 字段路径排序,优先处理更深层路径和更大的列表下标,避免列表删除时发生索引位移。
:param field_paths: 原始字段路径
:return: 排序后的字段路径列表
@@ -824,7 +859,7 @@ def _sort_field_paths_for_exclude(field_paths: tuple[str, ...]) -> list[str]:
@staticmethod
def _build_exclude_sort_key(field_path: str) -> tuple[int, tuple[tuple[int, int | str], ...]]:
"""
- 构建 exclude 字段路径排序键
+ 构建 exclude 字段路径排序键。
:param field_path: 字段路径
:return: 排序键
@@ -837,7 +872,7 @@ def _build_exclude_sort_key(field_path: str) -> tuple[int, tuple[tuple[int, int
def _remove_field_by_path(self, payload: Any, field_path: str) -> bool:
"""
- 按路径移除字段
+ 按路径移除字段。
:param payload: 原始载荷
:param field_path: 字段路径
@@ -878,7 +913,7 @@ def _remove_field_by_path(self, payload: Any, field_path: str) -> bool:
def _resolve_mapping_key_by_part(self, payload: dict[str, Any], part: str) -> str | object:
"""
- 解析字段片段在字典中的真实键名
+ 解析字段片段在字典中的真实键名。
:param payload: 当前字典载荷
:param part: 当前路径片段
@@ -899,7 +934,7 @@ def _resolve_include_root(
root: RequestLogFieldRoot | ResponseLogFieldRoot | str, candidates: tuple[str, ...]
) -> str | None:
"""
- 解析 include 根节点到标准写法
+ 解析 include 根节点到标准写法。
:param root: 原始根节点
:param candidates: 候选根节点
@@ -914,7 +949,7 @@ def _resolve_include_root(
@staticmethod
def _normalize_include_key(field_name: str) -> str:
"""
- 标准化 include 字段名
+ 标准化 include 字段名。
:param field_name: 原始字段名
:return: 标准化后的字段名
@@ -924,7 +959,7 @@ def _normalize_include_key(field_name: str) -> str:
@staticmethod
def _get_mapping_keys(payload: Any) -> list[str]:
"""
- 获取字典载荷的键列表
+ 获取字典载荷的键列表。
:param payload: 原始载荷
:return: 键列表
@@ -937,7 +972,7 @@ def _get_login_log(
self, user_agent: Any, oper_ip: str, oper_location: str, oper_time: datetime, origin_kwargs: dict
) -> dict:
"""
- 获取登录日志信息
+ 获取登录日志信息。
:param user_agent: 用户代理字符串
:param oper_ip: 操作ip
@@ -968,18 +1003,17 @@ def _get_login_log(
def _set_login_data(self, login_log: dict, origin_kwargs: dict) -> None:
"""
- 设置登录日志数据
+ 设置登录日志数据。
:param login_log: 登录日志信息
:param origin_kwargs: 原始函数参数
- :return: None
"""
if 'form_data' in origin_kwargs:
origin_kwargs['form_data'].login_info = login_log
def _get_status_and_error_msg(self, result_dict: dict) -> tuple[int, str]:
"""
- 获取操作状态和错误信息
+ 获取操作状态和错误信息。
:param result_dict: 操作结果字典
:return: 操作状态和错误信息元组
@@ -996,7 +1030,7 @@ def _get_status_and_error_msg(self, result_dict: dict) -> tuple[int, str]:
@staticmethod
def _get_result_message(result_dict: dict[str, Any]) -> Any:
"""
- 获取响应结果中的消息字段,兼容 msg / message 两种写法
+ 获取响应结果中的消息字段,兼容 msg / message 两种写法。
:param result_dict: 操作结果字典
:return: 消息内容
@@ -1005,7 +1039,7 @@ def _get_result_message(result_dict: dict[str, Any]) -> Any:
def _is_request_from_swagger_or_redoc(self, request: Request) -> tuple[bool, bool]:
"""
- 判断请求是否来自swagger或redoc
+ 判断请求是否来自swagger或redoc。
:param request: Request对象
:return: 是否来自swagger请求和是否来自redoc请求元组
@@ -1021,7 +1055,7 @@ def _is_request_from_swagger_or_redoc(self, request: Request) -> tuple[bool, boo
def _get_result_dict(self, result: Any, request_from_swagger: bool, request_from_redoc: bool) -> dict:
"""
- 获取操作结果字典
+ 获取操作结果字典。
:param result: 操作结果
:param request_from_swagger: 是否来自swagger请求
@@ -1043,7 +1077,7 @@ def _get_result_dict(self, result: Any, request_from_swagger: bool, request_from
@alru_cache()
async def get_ip_location(oper_ip: str) -> str:
"""
- 查询ip归属区域
+ 查询ip归属区域。
:param oper_ip: 需要查询的ip
:return: ip归属区域
@@ -1067,10 +1101,10 @@ async def get_ip_location(oper_ip: str) -> str:
def get_function_parameters_name_by_type(func: Callable, param_type: Any) -> list:
"""
- 获取函数指定类型的参数名称
+ 获取函数指定类型的参数名称。
:param func: 函数
- :param arg_type: 参数类型
+ :param param_type: 参数类型
:return: 函数指定类型的参数名称
"""
# 获取函数的参数信息
@@ -1095,8 +1129,10 @@ def get_function_parameters_name_by_type(func: Callable, param_type: Any) -> lis
def get_function_parameters_value_by_name(func: Callable, name: str, *args, **kwargs) -> Any:
"""
- 获取函数指定参数的值
+ 获取函数指定参数的值。
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
:param func: 函数
:param name: 参数名
:return: 参数值
diff --git a/ruoyi-fastapi-backend/common/annotation/pydantic_annotation.py b/ruoyi-fastapi-backend/common/annotation/pydantic_annotation.py
index 9dde679c3..1d4c14014 100644
--- a/ruoyi-fastapi-backend/common/annotation/pydantic_annotation.py
+++ b/ruoyi-fastapi-backend/common/annotation/pydantic_annotation.py
@@ -12,7 +12,10 @@
def as_query(cls: type[BaseModelVar]) -> type[BaseModelVar]:
"""
- pydantic模型查询参数装饰器,将pydantic模型用于接收查询参数
+ pydantic模型查询参数装饰器,将pydantic模型用于接收查询参数。
+
+ :param cls: 将查询参数转换到的模型类
+ :return: 将查询参数转换到的模型类
"""
new_parameters = []
@@ -39,6 +42,12 @@ def as_query(cls: type[BaseModelVar]) -> type[BaseModelVar]:
)
async def as_query_func(**data) -> type[BaseModelVar]:
+ """
+ 用解析出的查询参数构建模型实例。
+
+ :param data: 调用方按名称传入的附加选项
+ :return: 由查询参数创建的模型实例
+ """
return cls(**data)
sig = inspect.signature(as_query_func)
@@ -50,7 +59,10 @@ async def as_query_func(**data) -> type[BaseModelVar]:
def as_form(cls: type[BaseModelVar]) -> type[BaseModelVar]:
"""
- pydantic模型表单参数装饰器,将pydantic模型用于接收表单参数
+ pydantic模型表单参数装饰器,将pydantic模型用于接收表单参数。
+
+ :param cls: 将表单字段转换到的模型类
+ :return: 将表单字段转换到的模型类
"""
new_parameters = []
@@ -77,6 +89,12 @@ def as_form(cls: type[BaseModelVar]) -> type[BaseModelVar]:
)
async def as_form_func(**data) -> type[BaseModelVar]:
+ """
+ 用解析出的表单字段构建模型实例。
+
+ :param data: 调用方按名称传入的附加选项
+ :return: 由表单字段创建的模型实例
+ """
return cls(**data)
sig = inspect.signature(as_form_func)
diff --git a/ruoyi-fastapi-backend/common/annotation/rate_limit_annotation.py b/ruoyi-fastapi-backend/common/annotation/rate_limit_annotation.py
index b0b9512c6..69d41bdc1 100644
--- a/ruoyi-fastapi-backend/common/annotation/rate_limit_annotation.py
+++ b/ruoyi-fastapi-backend/common/annotation/rate_limit_annotation.py
@@ -31,7 +31,16 @@
@dataclass(frozen=True)
class ApiRateLimitPresetConfig:
"""
- 接口限流预设配置
+ 接口限流预设配置。
+
+ :ivar name: 用于查找或标识当前对象的名称
+ :ivar limit: 窗口内允许的最大请求次数,可覆盖预设
+ :ivar window_seconds: 限流窗口时长,单位秒,可覆盖预设
+ :ivar scope: 限流作用域,ip: 按客户端IP限流,客户端IP由可信代理配置控制提取,user: 仅按当前登录用户限流,未登录请求跳过限流,user_or_ip: 已登录按用户限流,未登录按客户端IP限流,可覆盖预设
+ :ivar algorithm: 限流算法,fixed_window: 固定窗口,sliding_window: 滑动窗口,可覆盖预设
+ :ivar fail_strategy: 限流组件异常时的故障策略,open: 放行,closed: 直接拦截,local_fallback: 使用进程内内存做应急兜底限流,仅保证单进程内生效,可覆盖预设
+ :ivar methods: 需要限流的HttpMethod枚举列表,为None时默认限制所有方法,可覆盖预设
+ :ivar message: 触发限流后的提示信息,可覆盖预设
"""
name: str
@@ -47,7 +56,9 @@ class ApiRateLimitPresetConfig:
@dataclass(frozen=True)
class ApiRateLimitBypassConfig:
"""
- 接口限流角色豁免配置
+ 接口限流角色豁免配置。
+
+ :ivar roles: 应用规则的角色集合
"""
roles: tuple[str, ...]
@@ -55,24 +66,24 @@ class ApiRateLimitBypassConfig:
class ApiRateLimitPreset:
"""
- 接口限流预设
-
- ANON_AUTH_LOGIN: 匿名登录类接口限流预设
- ANON_AUTH_REGISTER: 匿名注册类接口限流预设
- ANON_AUTH_CAPTCHA: 匿名验证码类接口限流预设
- ANON_PUBLIC_METADATA: 匿名公开元数据接口限流预设
- COMMON_UPLOAD: 通用上传接口限流预设
- USER_INTERACTIVE_HIGH_FREQ: 用户高频交互接口限流预设
- USER_RESOURCE_EXECUTION: 用户执行类接口限流预设
- USER_COMMON_MUTATION: 用户普通写操作接口限流预设
- USER_SECURITY_MUTATION: 用户安全敏感操作接口限流预设
- USER_DESTRUCTIVE_MUTATION: 用户破坏性操作接口限流预设
- USER_RESOURCE_EXPORT: 用户导出类接口限流预设
- USER_RESOURCE_IMPORT: 用户导入类接口限流预设
- USER_RESOURCE_UPLOAD: 用户上传类接口限流预设
- USER_RESOURCE_GENERATE: 用户生成类接口限流预设
- USER_RESOURCE_DOWNLOAD: 用户下载类接口限流预设
- USER_RESOURCE_SYNC: 用户同步类接口限流预设
+ 接口限流预设。
+
+ :cvar ANON_AUTH_LOGIN: 匿名登录类接口限流预设
+ :cvar ANON_AUTH_REGISTER: 匿名注册类接口限流预设
+ :cvar ANON_AUTH_CAPTCHA: 匿名验证码类接口限流预设
+ :cvar ANON_PUBLIC_METADATA: 匿名公开元数据接口限流预设
+ :cvar COMMON_UPLOAD: 通用上传接口限流预设
+ :cvar USER_INTERACTIVE_HIGH_FREQ: 用户高频交互接口限流预设
+ :cvar USER_RESOURCE_EXECUTION: 用户执行类接口限流预设
+ :cvar USER_COMMON_MUTATION: 用户普通写操作接口限流预设
+ :cvar USER_SECURITY_MUTATION: 用户安全敏感操作接口限流预设
+ :cvar USER_DESTRUCTIVE_MUTATION: 用户破坏性操作接口限流预设
+ :cvar USER_RESOURCE_EXPORT: 用户导出类接口限流预设
+ :cvar USER_RESOURCE_IMPORT: 用户导入类接口限流预设
+ :cvar USER_RESOURCE_UPLOAD: 用户上传类接口限流预设
+ :cvar USER_RESOURCE_GENERATE: 用户生成类接口限流预设
+ :cvar USER_RESOURCE_DOWNLOAD: 用户下载类接口限流预设
+ :cvar USER_RESOURCE_SYNC: 用户同步类接口限流预设
"""
ANON_AUTH_LOGIN = ApiRateLimitPresetConfig(
@@ -182,12 +193,29 @@ class ApiRateLimit:
"""
接口限流装饰器,支持Redis固定窗口、滑动窗口及本地应急兜底。
- `local_fallback` 仅作为Redis异常场景下的进程内应急保护,能提供单进程内的
+ ``local_fallback`` 仅作为Redis异常场景下的进程内应急保护,能提供单进程内的
基础限流能力,但不保证多 worker / 多实例部署下的全局一致性。
- `ip` 维度限流通过 `ClientIPUtil` 提取客户端地址,仅当请求来源命中
- `APP_TRUSTED_PROXY_IPS` 且 `APP_TRUSTED_PROXY_HOPS` 大于0时,才会解析
- `X-Forwarded-For` / `X-Real-IP` 请求头;否则回退到直接连接来源地址。
+ ``ip`` 维度限流通过 ``ClientIPUtil`` 提取客户端地址,仅当请求来源命中
+ ``APP_TRUSTED_PROXY_IPS`` 且 ``APP_TRUSTED_PROXY_HOPS`` 大于0时,才会解析
+ ``X-Forwarded-For`` / ``X-Real-IP`` 请求头;否则回退到直接连接来源地址。
+
+ :cvar _SUPPORTED_SCOPES: 允许配置的限流作用域
+ :cvar _SUPPORTED_ALGORITHMS: 可供选择的限流算法
+ :cvar _SUPPORTED_FAIL_STRATEGIES: 限流后端异常时支持的处理策略
+ :cvar _FIXED_WINDOW_LUA_SCRIPT: 在 Redis 中更新固定窗口计数器的 Lua 脚本
+ :cvar _SLIDING_WINDOW_LUA_SCRIPT: 在 Redis 中维护滑动窗口的 Lua 脚本
+ :cvar _LOCAL_FALLBACK_STORE: 限流后端不可用时使用的进程内存储
+ :ivar namespace: 限流命名空间,用于区分不同接口
+ :ivar preset_name: 当前使用的限流预设名称
+ :ivar limit: 窗口内允许的最大请求次数,可覆盖预设
+ :ivar window_seconds: 限流窗口时长,单位秒,可覆盖预设
+ :ivar scope: 限流作用域,ip: 按客户端IP限流,客户端IP由可信代理配置控制提取,user: 仅按当前登录用户限流,未登录请求跳过限流,user_or_ip: 已登录按用户限流,未登录按客户端IP限流,可覆盖预设
+ :ivar algorithm: 限流算法,fixed_window: 固定窗口,sliding_window: 滑动窗口,可覆盖预设
+ :ivar fail_strategy: 限流组件异常时的故障策略,open: 放行,closed: 直接拦截,local_fallback: 使用进程内内存做应急兜底限流,仅保证单进程内生效,可覆盖预设
+ :ivar bypass_roles: 原始角色标识列表
+ :ivar methods: 需要限流的HttpMethod枚举列表,为None时默认限制所有方法,可覆盖预设
+ :ivar message: 触发限流后的提示信息,可覆盖预设
"""
_SUPPORTED_SCOPES: tuple[RateLimitScope, ...] = ('ip', 'user', 'user_or_ip')
@@ -259,7 +287,7 @@ def __init__(
preset: ApiRateLimitPresetConfig | None = None,
) -> None:
"""
- 初始化接口限流装饰器
+ 初始化接口限流装饰器。
:param namespace: 限流命名空间,用于区分不同接口
:param limit: 窗口内允许的最大请求次数,可覆盖预设
@@ -271,6 +299,7 @@ def __init__(
:param methods: 需要限流的HttpMethod枚举列表,为None时默认限制所有方法,可覆盖预设
:param message: 触发限流后的提示信息,可覆盖预设
:param preset: 限流预设配置
+ :raises ValueError: ApiRateLimit的namespace不能为空;ApiRateLimit的limit必须大于0;ApiRateLimit的window_seconds必须大于0;ApiRateLimit在scope=ip时不支持角色豁免配置
"""
resolved_limit = limit if limit is not None else preset.limit if preset else None
resolved_window_seconds = (
@@ -313,7 +342,7 @@ def __init__(
def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]:
"""
- 为目标异步接口函数增加接口限流能力
+ 为目标异步接口函数增加接口限流能力。
:param func: 需要限流的异步接口函数
:return: 包装后的异步接口函数
@@ -321,6 +350,13 @@ def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]
@wraps(func)
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ """
+ 校验请求的限流条件后执行被装饰的接口。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 通过限流检查后原端点返回的响应
+ """
request = ApiAnnotationUtil.get_request(func, *args, **kwargs)
if request is None:
return await func(*args, **kwargs)
@@ -364,7 +400,7 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
def _is_request_method_allowed(self, request: Request) -> bool:
"""
- 判断当前请求方法是否启用限流
+ 判断当前请求方法是否启用限流。
:param request: 当前请求对象
:return: 是否启用限流
@@ -373,10 +409,11 @@ def _is_request_method_allowed(self, request: Request) -> bool:
def _normalize_bypass_roles(self, bypass_roles: Sequence[str] | None) -> tuple[str, ...]:
"""
- 标准化角色豁免配置
+ 标准化角色豁免配置。
:param bypass_roles: 原始角色标识列表
:return: 去重后的角色标识元组
+ :raises ValueError: ApiRateLimit的bypass_roles不能包含空角色标识
"""
if not bypass_roles:
return ()
@@ -393,7 +430,7 @@ def _normalize_bypass_roles(self, bypass_roles: Sequence[str] | None) -> tuple[s
def _match_bypass_role(self) -> str | None:
"""
- 判断当前登录用户是否命中角色豁免
+ 判断当前登录用户是否命中角色豁免。
:return: 命中的角色标识,未命中时返回None
"""
@@ -413,7 +450,7 @@ def _match_bypass_role(self) -> str | None:
async def _acquire_rate_limit(self, redis: aioredis.Redis, request: Request) -> dict[str, int | bool] | None:
"""
- 获取当前请求的限流计数结果
+ 获取当前请求的限流计数结果。
:param redis: Redis连接对象
:param request: 当前请求对象
@@ -455,8 +492,9 @@ def _build_rate_limit_key(
self, request: Request, current_time_ms: int, include_window_bucket: bool = True
) -> str | None:
"""
- 构建当前请求的限流键
+ 构建当前请求的限流键。
+ :param include_window_bucket: 是否将固定限流窗口编号写入缓存键
:param request: 当前请求对象
:param current_time_ms: 当前时间戳,单位毫秒
:return: 限流键,当前请求不适用限流时返回None
@@ -491,7 +529,7 @@ def _resolve_failed_rate_limit(
self, request: Request, reason: str, error_message: str
) -> dict[str, int | bool] | None:
"""
- 处理Redis不可用或执行异常时的限流故障策略
+ 处理Redis不可用或执行异常时的限流故障策略。
:param request: 当前请求对象
:param reason: 降级原因
@@ -508,7 +546,7 @@ def _resolve_failed_rate_limit(
def _acquire_local_fallback_rate_limit(self, request: Request) -> dict[str, int | bool] | None:
"""
- 使用进程内内存进行应急兜底限流,仅在Redis异常时启用
+ 使用进程内内存进行应急兜底限流,仅在Redis异常时启用。
该兜底能力仅在当前进程内生效,不保证多 worker / 多实例场景下的
全局一致限流,更适合作为短时故障期间的降级保护。
@@ -556,7 +594,7 @@ def _acquire_local_fallback_rate_limit(self, request: Request) -> dict[str, int
def _build_closed_rate_limit_result(self) -> dict[str, int | bool]:
"""
- 构建故障关闭策略下的拦截结果
+ 构建故障关闭策略下的拦截结果。
:return: 限流结果
"""
@@ -573,7 +611,7 @@ def _build_closed_rate_limit_result(self) -> dict[str, int | bool]:
def _get_route_path(self, request: Request) -> str:
"""
- 获取当前请求的路由模板路径
+ 获取当前请求的路由模板路径。
:param request: 当前请求对象
:return: 路由模板路径
@@ -584,7 +622,7 @@ def _get_route_path(self, request: Request) -> str:
def _get_scope_value(self, request: Request) -> str | None:
"""
- 获取当前请求的限流作用域值
+ 获取当前请求的限流作用域值。
:param request: 当前请求对象
:return: 作用域值,当前请求不适用限流时返回None
@@ -603,7 +641,7 @@ def _get_scope_value(self, request: Request) -> str | None:
def _get_current_user_id(self) -> int | None:
"""
- 获取当前登录用户ID
+ 获取当前登录用户ID。
:return: 用户ID,未登录时返回None
"""
@@ -612,7 +650,7 @@ def _get_current_user_id(self) -> int | None:
def _get_current_user(self) -> CurrentUserModel | None:
"""
- 获取当前登录用户
+ 获取当前登录用户。
:return: 当前登录用户,未登录时返回None
"""
@@ -623,7 +661,7 @@ def _get_current_user(self) -> CurrentUserModel | None:
def _get_client_ip(self, request: Request) -> str:
"""
- 获取客户端IP地址
+ 获取客户端IP地址。
:param request: 当前请求对象
:return: 客户端IP地址
@@ -632,7 +670,7 @@ def _get_client_ip(self, request: Request) -> str:
def _build_rate_limit_headers(self, rate_limit_result: dict[str, int | bool]) -> dict[str, str]:
"""
- 构建限流响应头
+ 构建限流响应头。
:param rate_limit_result: 限流结果
:return: 限流响应头
@@ -649,11 +687,10 @@ def _build_rate_limit_headers(self, rate_limit_result: dict[str, int | bool]) ->
def _log_rate_limit_hit(self, request: Request, rate_limit_result: dict[str, int | bool]) -> None:
"""
- 记录限流命中日志
+ 记录限流命中日志。
:param request: 当前请求对象
:param rate_limit_result: 限流结果
- :return: None
"""
logger.warning(
'接口限流命中: namespace={} preset={} algorithm={} fail_strategy={} method={} path={} scope={} scope_value={} current={} limit={} retry_after={}s',
@@ -672,12 +709,11 @@ def _log_rate_limit_hit(self, request: Request, rate_limit_result: dict[str, int
def _log_rate_limit_degrade(self, request: Request, reason: str, error_message: str) -> None:
"""
- 记录限流组件异常时的降级日志
+ 记录限流组件异常时的降级日志。
:param request: 当前请求对象
:param reason: 降级原因
:param error_message: 错误详情
- :return: None
"""
log_message = (
'接口限流降级: namespace={} preset={} algorithm={} fail_strategy={} '
@@ -702,11 +738,10 @@ def _log_rate_limit_degrade(self, request: Request, reason: str, error_message:
def _log_rate_limit_bypass(self, request: Request, bypass_role: str) -> None:
"""
- 记录角色豁免限流日志
+ 记录角色豁免限流日志。
:param request: 当前请求对象
:param bypass_role: 命中的角色标识
- :return: None
"""
logger.info(
'接口限流绕过: namespace={} preset={} method={} path={} scope={} bypass_role={}',
diff --git a/ruoyi-fastapi-backend/common/aspect/data_scope.py b/ruoyi-fastapi-backend/common/aspect/data_scope.py
index 0d3384101..907a80829 100644
--- a/ruoyi-fastapi-backend/common/aspect/data_scope.py
+++ b/ruoyi-fastapi-backend/common/aspect/data_scope.py
@@ -10,7 +10,16 @@
class GetDataScope:
"""
- 获取当前用户数据权限对应的查询sql语句
+ 获取当前用户数据权限对应的查询sql语句。
+
+ :cvar DATA_SCOPE_ALL: 可以访问所有部门数据的数据权限标识
+ :cvar DATA_SCOPE_CUSTOM: 使用角色自定义部门范围的数据权限标识
+ :cvar DATA_SCOPE_DEPT: 仅可访问本部门数据的权限标识
+ :cvar DATA_SCOPE_DEPT_AND_CHILD: 可访问本部门及下级部门数据的权限标识
+ :cvar DATA_SCOPE_SELF: 仅可访问本人数据的权限标识
+ :ivar query_alias: 所要查询表对应的sqlalchemy模型类,不可为空
+ :ivar user_alias: 用户id字段别名,默认为'user_id'
+ :ivar dept_alias: 部门id字段别名,默认为'dept_id'
"""
DATA_SCOPE_ALL = '1'
@@ -26,7 +35,7 @@ def __init__(
dept_alias: str | None = 'dept_id',
) -> None:
"""
- 获取当前用户数据权限对应的查询sql语句
+ 获取当前用户数据权限对应的查询sql语句。
:param query_alias: 所要查询表对应的sqlalchemy模型类,不可为空
:param user_alias: 用户id字段别名,默认为'user_id'
@@ -37,6 +46,12 @@ def __init__(
self.dept_alias = dept_alias
def __call__(self, request: Request) -> ColumnElement:
+ """
+ 根据当前用户和角色构建数据范围查询条件。
+
+ :param request: 当前 HTTP 请求
+ :return: 限制当前用户可见数据的 SQL 条件
+ """
DependencyUtil.check_exclude_routes(request, err_msg='当前路由不在认证规则内,不可使用GetDataScope依赖项')
current_user = RequestContext.get_current_user()
if current_user.user.admin:
@@ -103,7 +118,7 @@ def DataScopeDependency( # noqa: N802
dept_alias: str | None = 'dept_id',
) -> params.Depends:
"""
- 当前用户数据权限依赖
+ 当前用户数据权限依赖。
:param query_alias: 所要查询表对应的sqlalchemy模型类,不可为空
:param user_alias: 用户id字段别名,默认为'user_id'
diff --git a/ruoyi-fastapi-backend/common/aspect/db_session.py b/ruoyi-fastapi-backend/common/aspect/db_session.py
index 526777bdd..4b27b73fb 100644
--- a/ruoyi-fastapi-backend/common/aspect/db_session.py
+++ b/ruoyi-fastapi-backend/common/aspect/db_session.py
@@ -9,17 +9,24 @@
class DBSessionProvider:
"""
- 数据库会话依赖提供者
+ 数据库会话依赖提供者。
+
+ :ivar source_name: 数据源名称
"""
def __init__(self, source_name: str | None = None) -> None:
+ """
+ 绑定请求会话使用的数据源名称。
+
+ :param source_name: 数据源名称
+ """
self.source_name = source_name
async def __call__(self) -> AsyncIterator[AsyncSession]:
"""
- 创建指定数据源的数据库会话
+ 创建指定数据源的数据库会话。
- :return: 异步数据库会话
+ :yield: 异步数据库会话
"""
async with DataSourceRegistry.session(self.source_name) as session:
yield session
@@ -28,7 +35,7 @@ async def __call__(self) -> AsyncIterator[AsyncSession]:
@cache
def get_db_session_provider(source_name: str | None) -> DBSessionProvider:
"""
- 获取指定数据源的数据库会话依赖提供者
+ 获取指定数据源的数据库会话依赖提供者。
:param source_name: 数据源名称
:return: 数据库会话依赖提供者
@@ -38,7 +45,7 @@ def get_db_session_provider(source_name: str | None) -> DBSessionProvider:
def DBSessionDependency(source_name: str | None = None) -> params.Depends: # noqa: N802
"""
- 数据库会话依赖
+ 数据库会话依赖。
:param source_name: 数据源名称,为空时使用默认数据源
:return: 数据库会话依赖
diff --git a/ruoyi-fastapi-backend/common/aspect/interface_auth.py b/ruoyi-fastapi-backend/common/aspect/interface_auth.py
index fcaf2e1b5..1082e92ca 100644
--- a/ruoyi-fastapi-backend/common/aspect/interface_auth.py
+++ b/ruoyi-fastapi-backend/common/aspect/interface_auth.py
@@ -7,12 +7,15 @@
class CheckUserInterfaceAuth:
"""
- 校验当前用户是否具有相应的接口权限
+ 校验当前用户是否具有相应的接口权限。
+
+ :ivar perm: 权限标识
+ :ivar is_strict: 当传入的权限标识是list类型时,是否开启严格模式,开启表示会校验列表中的每一个权限标识,所有的校验结果都需要为True才会通过
"""
def __init__(self, perm: str | list, is_strict: bool = False) -> None:
"""
- 校验当前用户是否具有相应的接口权限
+ 校验当前用户是否具有相应的接口权限。
:param perm: 权限标识
:param is_strict: 当传入的权限标识是list类型时,是否开启严格模式,开启表示会校验列表中的每一个权限标识,所有的校验结果都需要为True才会通过
@@ -21,6 +24,13 @@ def __init__(self, perm: str | list, is_strict: bool = False) -> None:
self.is_strict = is_strict
def __call__(self, request: Request) -> bool:
+ """
+ 校验当前用户能否使用请求接口所需的权限。
+
+ :param request: 当前 HTTP 请求
+ :return: 是否校验当前用户能否使用请求接口所需的权限
+ :raises PermissionException: 该用户无此接口权限
+ """
DependencyUtil.check_exclude_routes(
request, err_msg='当前路由不在认证规则内,不可使用CheckUserInterfaceAuth依赖项'
)
@@ -41,12 +51,15 @@ def __call__(self, request: Request) -> bool:
class CheckRoleInterfaceAuth:
"""
- 根据角色校验当前用户是否具有相应的接口权限
+ 根据角色校验当前用户是否具有相应的接口权限。
+
+ :ivar role_key: 角色标识
+ :ivar is_strict: 当传入的角色标识是list类型时,是否开启严格模式,开启表示会校验列表中的每一个角色标识,所有的校验结果都需要为True才会通过
"""
def __init__(self, role_key: str | list, is_strict: bool = False) -> None:
"""
- 根据角色校验当前用户是否具有相应的接口权限
+ 根据角色校验当前用户是否具有相应的接口权限。
:param role_key: 角色标识
:param is_strict: 当传入的角色标识是list类型时,是否开启严格模式,开启表示会校验列表中的每一个角色标识,所有的校验结果都需要为True才会通过
@@ -55,6 +68,13 @@ def __init__(self, role_key: str | list, is_strict: bool = False) -> None:
self.is_strict = is_strict
def __call__(self, request: Request) -> bool:
+ """
+ 校验当前用户角色是否满足接口要求。
+
+ :param request: 当前 HTTP 请求
+ :return: 是否校验当前用户角色是否满足接口要求
+ :raises PermissionException: 该用户无此接口权限
+ """
DependencyUtil.check_exclude_routes(
request, err_msg='当前路由不在认证规则内,不可使用CheckRoleInterfaceAuth依赖项'
)
@@ -74,7 +94,7 @@ def __call__(self, request: Request) -> bool:
def UserInterfaceAuthDependency(perm: str | list, is_strict: bool = False) -> params.Depends: # noqa: N802
"""
- 根据权限标识校验当前用户接口权限依赖
+ 根据权限标识校验当前用户接口权限依赖。
:param perm: 权限标识
:param is_strict: 当传入的权限标识是list类型时,是否开启严格模式,开启表示会校验列表中的每一个权限标识,所有的校验结果都需要为True才会通过
@@ -85,7 +105,7 @@ def UserInterfaceAuthDependency(perm: str | list, is_strict: bool = False) -> pa
def RoleInterfaceAuthDependency(role_key: str | list, is_strict: bool = False) -> params.Depends: # noqa: N802
"""
- 根据角色校验当前用户接口权限依赖
+ 根据角色校验当前用户接口权限依赖。
:param role_key: 角色标识
:param is_strict: 当传入的角色标识是list类型时,是否开启严格模式,开启表示会校验列表中的每一个角色标识,所有的校验结果都需要为True才会通过
diff --git a/ruoyi-fastapi-backend/common/aspect/pre_auth.py b/ruoyi-fastapi-backend/common/aspect/pre_auth.py
index ead8c696a..0f471dc3b 100644
--- a/ruoyi-fastapi-backend/common/aspect/pre_auth.py
+++ b/ruoyi-fastapi-backend/common/aspect/pre_auth.py
@@ -8,9 +8,7 @@
class PreAuth(AuthRule):
- """
- 登录认证前置校验依赖类
- """
+ """登录认证前置校验依赖类。"""
async def __call__(
self,
@@ -18,7 +16,7 @@ async def __call__(
current_user: CurrentUserModel | None = Depends(LoginService.get_current_user),
) -> CurrentUserModel | None:
"""
- 保存前置认证规则和登录用户上下文
+ 保存前置认证规则和登录用户上下文。
:param request: 当前请求对象
:param current_user: 登录认证依赖返回的当前用户
@@ -36,7 +34,7 @@ async def __call__(
def PreAuthDependency(exclude_routes: list[ExcludeRoute] | None = None) -> params.Depends: # noqa: N802
"""
- 登录认证前置校验依赖
+ 登录认证前置校验依赖。
:param exclude_routes: 需要排除的路由列表,格式为:
[{'path': '/path1', 'methods': ['GET', 'POST']}, {'path': '/path2/{param}', 'methods': ['GET']}]
@@ -48,7 +46,7 @@ def PreAuthDependency(exclude_routes: list[ExcludeRoute] | None = None) -> param
def CurrentUserDependency() -> params.Depends: # noqa: N802
"""
- 当前登录用户信息依赖
+ 当前登录用户信息依赖。
:return: 当前登录用户信息依赖
"""
diff --git a/ruoyi-fastapi-backend/common/auth_policy.py b/ruoyi-fastapi-backend/common/auth_policy.py
index 9d2baa930..925089f17 100644
--- a/ruoyi-fastapi-backend/common/auth_policy.py
+++ b/ruoyi-fastapi-backend/common/auth_policy.py
@@ -12,11 +12,11 @@
# 定义排除路由的字典结构
class ExcludeRoute(TypedDict, total=False):
"""
- 排除路由的字典结构
+ 排除路由的字典结构。
- :param path: 路由路径(必填)
- :param methods: HTTP方法列表,空列表表示所有方法(可选,默认为[])
- :param ignore_paths: 需要忽略的特定路径列表,即使匹配通配符也不排除(可选,默认为[])
+ :ivar path: 路由路径(必填)
+ :ivar methods: HTTP方法列表,空列表表示所有方法(可选,默认为[])
+ :ivar ignore_paths: 需要忽略的特定路径列表,即使匹配通配符也不排除(可选,默认为[])
"""
path: str
@@ -26,12 +26,15 @@ class ExcludeRoute(TypedDict, total=False):
class AuthRule:
"""
- 登录认证排除规则
+ 登录认证排除规则。
+
+ :ivar exclude_routes: 需要排除的路由列表,格式为:
+ :ivar exclude_patterns: 编译后的排除路由模式列表
"""
def __init__(self, exclude_routes: list[ExcludeRoute] | None = None) -> None:
"""
- 初始化登录认证排除规则
+ 初始化登录认证排除规则。
:param exclude_routes: 需要排除的路由列表,格式为:
[{'path': '/path1', 'methods': ['GET', 'POST']}, {'path': '/path2/{param}', 'methods': ['GET']}]
@@ -60,7 +63,7 @@ def __init__(self, exclude_routes: list[ExcludeRoute] | None = None) -> None:
def _compile_path_pattern(self, path: str) -> re.Pattern:
"""
- 将FastAPI路径转换为正则表达式模式
+ 将FastAPI路径转换为正则表达式模式。
:param path: FastAPI路径(如 /configKey/{config_key})
:return: 编译后的正则表达式模式
@@ -73,7 +76,7 @@ def _compile_path_pattern(self, path: str) -> re.Pattern:
def is_excluded(self, request: Request) -> bool:
"""
- 判断当前请求是否排除登录认证
+ 判断当前请求是否排除登录认证。
:param request: 当前请求对象
:return: 是否排除认证
@@ -84,7 +87,7 @@ def is_excluded(self, request: Request) -> bool:
def is_excluded_path(self, path: str, method: str) -> bool:
"""
- 判断应用内路径和请求方法是否排除登录认证
+ 判断应用内路径和请求方法是否排除登录认证。
:param path: 应用内请求路径
:param method: 请求方法
@@ -108,9 +111,7 @@ def is_excluded_path(self, path: str, method: str) -> bool:
class AuthPolicy:
- """
- 登录认证依赖判定
- """
+ """登录认证依赖判定。"""
@classmethod
def iter_auth_dependencies(
@@ -120,16 +121,23 @@ def iter_auth_dependencies(
overrides: dict[Callable, Callable] | None = None,
) -> Iterator[AuthRule | None]:
"""
- 遍历实际生效的登录认证声明
+ 遍历实际生效的登录认证声明。
:param dependant: 路由依赖
:param auth_dependencies: 需要识别的认证入口和令牌依赖
:param overrides: 应用覆盖的依赖
- :return: 前置认证规则对象,显式登录认证返回None
+ :yield: 前置认证规则对象,显式登录认证返回None
"""
overrides = overrides or {}
def visit(dependency: Dependant, rule: AuthRule | None = None) -> Iterator[AuthRule | None]:
+ """
+ 遍历路由依赖树并应用认证依赖覆盖。
+
+ :param dependency: 当前需要展开的依赖
+ :param rule: 当前正在检查的规则
+ :yield: 依赖树中匹配的认证规则
+ """
if dependency.call in overrides:
# 按替换函数的实际声明判断,普通依赖覆盖不会使公开接口变为必需登录。
dependency = get_dependant(
@@ -157,7 +165,7 @@ def get_auth_mode(
cls, request: Request, auth_dependencies: tuple[Callable, ...]
) -> Literal['pre_auth', 'current_user', 'excluded']:
"""
- 根据路由的依赖声明确定登录认证方式
+ 根据路由的依赖声明确定登录认证方式。
:param request: 当前请求对象
:param auth_dependencies: 需要识别的认证入口和令牌依赖
diff --git a/ruoyi-fastapi-backend/common/constant.py b/ruoyi-fastapi-backend/common/constant.py
index 1c6c8bf56..f6731a67a 100644
--- a/ruoyi-fastapi-backend/common/constant.py
+++ b/ruoyi-fastapi-backend/common/constant.py
@@ -1,20 +1,20 @@
class CommonConstant:
"""
- 常用常量
-
- PASSWORD_ERROR_COUNT: 密码错误次数
- WWW: www主域
- HTTP: http请求
- HTTPS: https请求
- LOOKUP_RMI: RMI远程方法调用
- LOOKUP_LDAP: LDAP远程方法调用
- LOOKUP_LDAPS: LDAPS远程方法调用
- YES: 是否为系统默认(是)
- NO: 是否为系统默认(否)
- DEPT_NORMAL: 部门正常状态
- DEPT_DISABLE: 部门停用状态
- UNIQUE: 校验是否唯一的返回标识(是)
- NOT_UNIQUE: 校验是否唯一的返回标识(否)
+ 常用常量。
+
+ :cvar PASSWORD_ERROR_COUNT: 密码错误次数
+ :cvar WWW: www主域
+ :cvar HTTP: http请求
+ :cvar HTTPS: https请求
+ :cvar LOOKUP_RMI: RMI远程方法调用
+ :cvar LOOKUP_LDAP: LDAP远程方法调用
+ :cvar LOOKUP_LDAPS: LDAPS远程方法调用
+ :cvar YES: 是否为系统默认(是)
+ :cvar NO: 是否为系统默认(否)
+ :cvar DEPT_NORMAL: 部门正常状态
+ :cvar DEPT_DISABLE: 部门停用状态
+ :cvar UNIQUE: 校验是否唯一的返回标识(是)
+ :cvar NOT_UNIQUE: 校验是否唯一的返回标识(否)
"""
PASSWORD_ERROR_COUNT = 5
@@ -34,26 +34,26 @@ class CommonConstant:
class HttpStatusConstant:
"""
- 返回状态码
-
- SUCCESS: 操作成功
- CREATED: 对象创建成功
- ACCEPTED: 请求已经被接受
- NO_CONTENT: 操作已经执行成功,但是没有返回数据
- MOVED_PERM: 资源已被移除
- SEE_OTHER: 重定向
- NOT_MODIFIED: 资源没有被修改
- BAD_REQUEST: 参数列表错误(缺少,格式不匹配)
- UNAUTHORIZED: 未授权
- FORBIDDEN: 访问受限,授权过期
- NOT_FOUND: 资源,服务未找到
- BAD_METHOD: 不允许的http方法
- CONFLICT: 资源冲突,或者资源被锁
- UNSUPPORTED_TYPE: 不支持的数据,媒体类型
- TOO_MANY_REQUESTS: 请求过于频繁
- ERROR: 系统内部错误
- NOT_IMPLEMENTED: 接口未实现
- WARN: 系统警告消息
+ 返回状态码。
+
+ :cvar SUCCESS: 操作成功
+ :cvar CREATED: 对象创建成功
+ :cvar ACCEPTED: 请求已经被接受
+ :cvar NO_CONTENT: 操作已经执行成功,但是没有返回数据
+ :cvar MOVED_PERM: 资源已被移除
+ :cvar SEE_OTHER: 重定向
+ :cvar NOT_MODIFIED: 资源没有被修改
+ :cvar BAD_REQUEST: 参数列表错误(缺少,格式不匹配)
+ :cvar UNAUTHORIZED: 未授权
+ :cvar FORBIDDEN: 访问受限,授权过期
+ :cvar NOT_FOUND: 资源,服务未找到
+ :cvar BAD_METHOD: 不允许的http方法
+ :cvar CONFLICT: 资源冲突,或者资源被锁
+ :cvar UNSUPPORTED_TYPE: 不支持的数据,媒体类型
+ :cvar TOO_MANY_REQUESTS: 请求过于频繁
+ :cvar ERROR: 系统内部错误
+ :cvar NOT_IMPLEMENTED: 接口未实现
+ :cvar WARN: 系统警告消息
"""
SUCCESS = 200
@@ -78,10 +78,10 @@ class HttpStatusConstant:
class JobConstant:
"""
- 定时任务常量
+ 定时任务常量。
- JOB_ERROR_LIST: 定时任务禁止调用模块及违规字符串列表
- JOB_WHITE_LIST: 定时任务允许调用模块列表
+ :cvar JOB_ERROR_LIST: 定时任务禁止调用模块及违规字符串列表
+ :cvar JOB_WHITE_LIST: 定时任务允许调用模块列表
"""
JOB_ERROR_LIST = [
@@ -134,18 +134,18 @@ class JobConstant:
class LockConstant:
"""
- 分布式锁常量
-
- APP_STARTUP_LOCK_KEY: 应用启动分布式锁键
- LOCK_EXPIRE_SECONDS: 通用分布式锁过期时间(秒)
- LOCK_RENEWAL_INTERVAL: 分布式锁续期间隔(秒)
- PLUGIN_STARTUP_READY_KEY: 插件启动就绪状态键
- PLUGIN_STARTUP_READY_EXPIRE_SECONDS: 插件启动就绪状态过期时间(秒)
- PLUGIN_STARTUP_FAILED_EXPIRE_SECONDS: 插件启动失败状态过期时间(秒)
- PLUGIN_STARTUP_READY_WAIT_TIMEOUT_SECONDS: 等待插件启动就绪的超时时间(秒)
- PLUGIN_STARTUP_READY_WAIT_INTERVAL_SECONDS: 等待插件启动就绪的轮询间隔(秒)
- PLUGIN_LIFECYCLE_LOCK_PREFIX: 插件生命周期锁键前缀
- PLUGIN_LIFECYCLE_LOCK_EXPIRE_SECONDS: 插件生命周期锁过期时间(秒)
+ 分布式锁常量。
+
+ :cvar APP_STARTUP_LOCK_KEY: 应用启动分布式锁键
+ :cvar LOCK_EXPIRE_SECONDS: 通用分布式锁过期时间(秒)
+ :cvar LOCK_RENEWAL_INTERVAL: 分布式锁续期间隔(秒)
+ :cvar PLUGIN_STARTUP_READY_KEY: 插件启动就绪状态键
+ :cvar PLUGIN_STARTUP_READY_EXPIRE_SECONDS: 插件启动就绪状态过期时间(秒)
+ :cvar PLUGIN_STARTUP_FAILED_EXPIRE_SECONDS: 插件启动失败状态过期时间(秒)
+ :cvar PLUGIN_STARTUP_READY_WAIT_TIMEOUT_SECONDS: 等待插件启动就绪的超时时间(秒)
+ :cvar PLUGIN_STARTUP_READY_WAIT_INTERVAL_SECONDS: 等待插件启动就绪的轮询间隔(秒)
+ :cvar PLUGIN_LIFECYCLE_LOCK_PREFIX: 插件生命周期锁键前缀
+ :cvar PLUGIN_LIFECYCLE_LOCK_EXPIRE_SECONDS: 插件生命周期锁过期时间(秒)
"""
APP_STARTUP_LOCK_KEY = 'app:startup:lock'
@@ -167,20 +167,20 @@ class OidcConstant:
OIDC 状态与现有 ``access_token:*`` Legacy 会话严格隔离;Redis 具体键由
``module_identity.redis_keys.OidcRedisKey`` 生成,这里只保存稳定的命名空间。
- REDIS_PREFIX: OIDC Redis 键前缀
- INTERACTION_NAMESPACE: 认证交互状态命名空间
- AUTHORIZATION_CODE_NAMESPACE: 授权码命名空间
- SSO_SESSION_NAMESPACE: 单点登录会话命名空间
- USER_SESSIONS_NAMESPACE: 用户会话集合命名空间
- SSO_COOKIE_NAMESPACE: 单点登录 Cookie 命名空间
- REVOKED_JTI_NAMESPACE: 已撤销令牌 JTI 命名空间
- RATE_LIMIT_NAMESPACE: OIDC 限流命名空间
- EVENT_NAMESPACE: OIDC 审计事件命名空间
- CACHE_NAMESPACE: OIDC 缓存命名空间
- AUTHORIZE_RATE_LIMIT: 授权端点限流命名空间
- LOGIN_RATE_LIMIT: 登录端点限流命名空间
- TOKEN_RATE_LIMIT: 令牌端点限流命名空间
- INTROSPECT_RATE_LIMIT: 令牌自省端点限流命名空间
+ :cvar REDIS_PREFIX: OIDC Redis 键前缀
+ :cvar INTERACTION_NAMESPACE: 认证交互状态命名空间
+ :cvar AUTHORIZATION_CODE_NAMESPACE: 授权码命名空间
+ :cvar SSO_SESSION_NAMESPACE: 单点登录会话命名空间
+ :cvar USER_SESSIONS_NAMESPACE: 用户会话集合命名空间
+ :cvar SSO_COOKIE_NAMESPACE: 单点登录 Cookie 命名空间
+ :cvar REVOKED_JTI_NAMESPACE: 已撤销令牌 JTI 命名空间
+ :cvar RATE_LIMIT_NAMESPACE: OIDC 限流命名空间
+ :cvar EVENT_NAMESPACE: OIDC 审计事件命名空间
+ :cvar CACHE_NAMESPACE: OIDC 缓存命名空间
+ :cvar AUTHORIZE_RATE_LIMIT: 授权端点限流命名空间
+ :cvar LOGIN_RATE_LIMIT: 登录端点限流命名空间
+ :cvar TOKEN_RATE_LIMIT: 令牌端点限流命名空间
+ :cvar INTROSPECT_RATE_LIMIT: 令牌自省端点限流命名空间
"""
REDIS_PREFIX = 'oidc'
@@ -206,34 +206,34 @@ class OidcAuditEvent:
事件值用于审计持久化和风险检索,禁止写入 Token、Secret 或 Cookie 明文。
- AUTHORIZE_REQUESTED: 收到授权请求
- AUTHORIZE_SUCCEEDED: 授权请求成功
- AUTHORIZE_DENIED: 授权请求被拒绝
- LOGIN_SUCCEEDED: 登录成功
- LOGIN_FAILED: 登录失败
- CONSENT_GRANTED: 用户授予同意
- CONSENT_REVOKED: 用户撤销同意
- AUTHORIZATION_CODE_REUSED: 授权码重复使用
- TOKEN_ISSUED: 令牌签发成功
- TOKEN_FAILED: 令牌处理失败
- REFRESH_ROTATED: 刷新令牌轮换成功
- REFRESH_REUSE_DETECTED: 检测到刷新令牌重复使用
- TOKEN_REVOKED: 令牌已撤销
- SESSION_REVOKED: 会话已撤销
- CLIENT_ACCESS_BLOCKED: 用户应用访问已禁止
- CLIENT_ACCESS_ALLOWED: 用户应用访问已允许
- GRANT_REVOKED: 授权授予已撤销
- RESOURCE_POLICY_CHANGED: 资源策略已变更
- SCOPE_POLICY_CHANGED: Scope 策略已变更
- CLIENT_CREATED: OAuth 客户端已创建
- CLIENT_DISABLED: OAuth 客户端已停用
- CLIENT_SECRET_ROTATED: OAuth 客户端密钥已轮换
- SIGNING_KEY_ROTATED: OIDC 签名密钥已轮换
- BACKCHANNEL_LOGOUT_SUCCEEDED: Back-Channel Logout 成功
- BACKCHANNEL_LOGOUT_FAILED: Back-Channel Logout 失败
- IDENTITY_SUBJECT_MISSING: 身份 Subject 缺失
- SECURITY_VERSION_CHANGED: 安全版本已变更
- INVALID_CLIENT: 无效客户端请求
+ :cvar AUTHORIZE_REQUESTED: 收到授权请求
+ :cvar AUTHORIZE_SUCCEEDED: 授权请求成功
+ :cvar AUTHORIZE_DENIED: 授权请求被拒绝
+ :cvar LOGIN_SUCCEEDED: 登录成功
+ :cvar LOGIN_FAILED: 登录失败
+ :cvar CONSENT_GRANTED: 用户授予同意
+ :cvar CONSENT_REVOKED: 用户撤销同意
+ :cvar AUTHORIZATION_CODE_REUSED: 授权码重复使用
+ :cvar TOKEN_ISSUED: 令牌签发成功
+ :cvar TOKEN_FAILED: 令牌处理失败
+ :cvar REFRESH_ROTATED: 刷新令牌轮换成功
+ :cvar REFRESH_REUSE_DETECTED: 检测到刷新令牌重复使用
+ :cvar TOKEN_REVOKED: 令牌已撤销
+ :cvar SESSION_REVOKED: 会话已撤销
+ :cvar CLIENT_ACCESS_BLOCKED: 用户应用访问已禁止
+ :cvar CLIENT_ACCESS_ALLOWED: 用户应用访问已允许
+ :cvar GRANT_REVOKED: 授权授予已撤销
+ :cvar RESOURCE_POLICY_CHANGED: 资源策略已变更
+ :cvar SCOPE_POLICY_CHANGED: Scope 策略已变更
+ :cvar CLIENT_CREATED: OAuth 客户端已创建
+ :cvar CLIENT_DISABLED: OAuth 客户端已停用
+ :cvar CLIENT_SECRET_ROTATED: OAuth 客户端密钥已轮换
+ :cvar SIGNING_KEY_ROTATED: OIDC 签名密钥已轮换
+ :cvar BACKCHANNEL_LOGOUT_SUCCEEDED: Back-Channel Logout 成功
+ :cvar BACKCHANNEL_LOGOUT_FAILED: Back-Channel Logout 失败
+ :cvar IDENTITY_SUBJECT_MISSING: 身份 Subject 缺失
+ :cvar SECURITY_VERSION_CHANGED: 安全版本已变更
+ :cvar INVALID_CLIENT: 无效客户端请求
"""
AUTHORIZE_REQUESTED = 'authorize_requested'
@@ -270,8 +270,8 @@ class PluginRuntimeConstant:
"""
插件运行时常量。
- PLUGIN_HOOK_TIMEOUT_SECONDS: 插件钩子执行超时时间(秒)
- PLUGIN_HEALTH_TIMEOUT_SECONDS: 插件健康检查超时时间(秒)
+ :cvar PLUGIN_HOOK_TIMEOUT_SECONDS: 插件钩子执行超时时间(秒)
+ :cvar PLUGIN_HEALTH_TIMEOUT_SECONDS: 插件健康检查超时时间(秒)
"""
PLUGIN_HOOK_TIMEOUT_SECONDS = 30
@@ -280,146 +280,146 @@ class PluginRuntimeConstant:
class ApiNamespace:
"""
- 接口注解通用命名空间常量
+ 接口注解通用命名空间常量。
- 这一组常量统一提供给 `ApiCache`、`ApiCacheEvict`、`ApiRateLimit`
+ 这一组常量统一提供给 ``ApiCache``、``ApiCacheEvict``、``ApiRateLimit``
等接口注解使用,用同一套“模块:功能”命名规则收敛缓存和限流场景。
- LOGIN: 登录接口命名空间
- LOGIN_UNLOCK_SCREEN: 锁屏解锁接口命名空间
- REGISTER: 注册接口命名空间
- LOGIN_USER_INFO: 登录用户信息接口命名空间
- LOGIN_USER_ROUTERS: 登录用户路由接口命名空间
- CAPTCHA_IMAGE: 图片验证码接口命名空间
- COMMON_UPLOAD: 通用上传接口命名空间
- COMMON_PRIVATE_UPLOAD: 通用私有文件上传接口命名空间
- COMMON_FILE_DOWNLOAD: 通用文件下载接口命名空间
- TRANSPORT_CRYPTO_PUBLIC_KEY: 传输层加密公钥接口命名空间
- TRANSPORT_CRYPTO_FRONTEND_CONFIG: 传输层加密前端配置接口命名空间
-
- OIDC_AUTHORIZE: OIDC 授权接口命名空间
- OIDC_LOGIN: OIDC 登录接口命名空间
- OIDC_TOKEN: OIDC 令牌接口命名空间
- OIDC_USERINFO: OIDC 用户信息接口命名空间
- OIDC_INTROSPECT: OIDC 令牌自省接口命名空间
- OIDC_REVOKE: OIDC 令牌撤销接口命名空间
- OIDC_LOGOUT: OIDC 登出接口命名空间
- OIDC_INTERACTION: OIDC 认证交互接口命名空间
- OIDC_INTERACTION_LOGIN: OIDC 认证交互登录接口命名空间
- OIDC_INTERACTION_CONSENT: OIDC 认证交互同意接口命名空间
-
- SYSTEM_OAUTH_CLIENT_CREATE: OAuth 客户端创建接口命名空间
- SYSTEM_OAUTH_CLIENT_DISABLE: OAuth 客户端停用接口命名空间
- SYSTEM_OAUTH_CLIENT_STATUS: OAuth 客户端状态接口命名空间
- SYSTEM_OAUTH_CLIENT_UPDATE: OAuth 客户端更新接口命名空间
- SYSTEM_OAUTH_CLIENT_SECRET_ROTATE: OAuth 客户端密钥轮换接口命名空间
- SYSTEM_OAUTH_CLIENT_SECRET_REVOKE: OAuth 客户端密钥撤销接口命名空间
- SYSTEM_OAUTH_CLIENT_URI_ADD: OAuth 客户端回调地址新增接口命名空间
- SYSTEM_OAUTH_CLIENT_URI_REMOVE: OAuth 客户端回调地址移除接口命名空间
- SYSTEM_OAUTH_RESOURCE_CREATE: OAuth 资源创建接口命名空间
- SYSTEM_OAUTH_RESOURCE_UPDATE: OAuth 资源更新接口命名空间
- SYSTEM_OAUTH_RESOURCE_DISABLE: OAuth 资源停用接口命名空间
- SYSTEM_OAUTH_RESOURCE_STATUS: OAuth 资源状态接口命名空间
- SYSTEM_OAUTH_SCOPE_CREATE: OAuth Scope 创建接口命名空间
- SYSTEM_OAUTH_SCOPE_UPDATE: OAuth Scope 更新接口命名空间
- SYSTEM_OAUTH_SCOPE_DISABLE: OAuth Scope 停用接口命名空间
- SYSTEM_OAUTH_SCOPE_STATUS: OAuth Scope 状态接口命名空间
- SYSTEM_OAUTH_SESSION_REVOKE: OAuth 会话撤销接口命名空间
- SYSTEM_OAUTH_SESSION_USER_REVOKE: OAuth 用户会话批量撤销接口命名空间
- SYSTEM_OAUTH_GRANT_ACCESS: 用户应用访问控制
- SYSTEM_OAUTH_GRANT_REVOKE: OAuth 授权授予撤销接口命名空间
- SYSTEM_OAUTH_KEY_ROTATE: OAuth 签名密钥轮换接口命名空间
- SYSTEM_OAUTH_KEY_ACTIVATE: OAuth 签名密钥激活接口命名空间
- SYSTEM_OAUTH_KEY_RETIRE: OAuth 签名密钥退役接口命名空间
- SYSTEM_OAUTH_KEY_DELETE: OAuth 签名密钥删除接口命名空间
- MONITOR_OAUTH_AUDIT_EXPORT: OAuth 审计日志导出接口命名空间
- MONITOR_OAUTH_AUDIT_CLEANUP: OAuth 审计日志清理接口命名空间
-
- MONITOR_SERVER_INFO: 服务监控信息接口命名空间
- MONITOR_CACHE_CLEAR_NAME: 缓存名称清理接口命名空间
- MONITOR_CACHE_CLEAR_KEY: 缓存键清理接口命名空间
- MONITOR_CACHE_CLEAR_ALL: 缓存全量清理接口命名空间
- MONITOR_ONLINE_FORCE_LOGOUT: 在线用户强退接口命名空间
- MONITOR_OPERLOG_CLEAN: 操作日志清空接口命名空间
- MONITOR_OPERLOG_DELETE: 操作日志删除接口命名空间
- MONITOR_OPERLOG_EXPORT: 操作日志导出接口命名空间
- MONITOR_LOGININFO_CLEAN: 登录日志清空接口命名空间
- MONITOR_LOGININFO_DELETE: 登录日志删除接口命名空间
- MONITOR_LOGININFO_UNLOCK: 账户解锁接口命名空间
- MONITOR_LOGININFO_EXPORT: 登录日志导出接口命名空间
- MONITOR_JOB_LIST: 定时任务分页列表接口命名空间
- MONITOR_JOB_DETAIL: 定时任务详情接口命名空间
- MONITOR_JOB_RUN: 定时任务执行接口命名空间
- MONITOR_JOB_DELETE: 定时任务删除接口命名空间
- MONITOR_JOB_EXPORT: 定时任务导出接口命名空间
- MONITOR_JOB_LOG_CLEAN: 定时任务日志清空接口命名空间
- MONITOR_JOB_LOG_DELETE: 定时任务日志删除接口命名空间
- MONITOR_JOB_LOG_EXPORT: 定时任务日志导出接口命名空间
-
- SYSTEM_DEPT_EDIT_TREE: 部门编辑树接口命名空间
- SYSTEM_DEPT_LIST: 部门列表接口命名空间
- SYSTEM_DEPT_DETAIL: 部门详情接口命名空间
- SYSTEM_CONFIG_LIST: 参数配置列表接口命名空间
- SYSTEM_CONFIG_DETAIL: 参数配置详情接口命名空间
- SYSTEM_CONFIG_REFRESH_CACHE: 参数缓存刷新接口命名空间
- SYSTEM_CONFIG_EXPORT: 参数导出接口命名空间
- SYSTEM_DICT_TYPE_LIST: 字典类型列表接口命名空间
- SYSTEM_DICT_TYPE_OPTIONS: 字典类型选项接口命名空间
- SYSTEM_DICT_TYPE_DETAIL: 字典类型详情接口命名空间
- SYSTEM_DICT_REFRESH_CACHE: 字典缓存刷新接口命名空间
- SYSTEM_DICT_TYPE_EXPORT: 字典类型导出接口命名空间
- SYSTEM_DICT_DATA_LIST: 字典数据列表接口命名空间
- SYSTEM_DICT_DATA_DETAIL: 字典数据详情接口命名空间
- SYSTEM_DICT_DATA_EXPORT: 字典数据导出接口命名空间
- SYSTEM_MENU_TREE: 菜单树接口命名空间
- SYSTEM_MENU_ROLE_TREE: 角色菜单树接口命名空间
- SYSTEM_MENU_LIST: 菜单分页列表接口命名空间
- SYSTEM_MENU_DETAIL: 菜单详情接口命名空间
- SYSTEM_NOTICE_LIST: 通知公告列表接口命名空间
- SYSTEM_NOTICE_DETAIL: 通知公告详情接口命名空间
- SYSTEM_FILE_DOWNLOAD: 文件管理下载接口命名空间
- SYSTEM_FILE_DELETE: 文件管理删除接口命名空间
- SYSTEM_FILE_ACL: 文件访问控制接口命名空间
- SYSTEM_FILE_RETENTION_POLICY: 文件业务保留策略接口命名空间
- SYSTEM_FILE_RECONCILE: 文件存储对账接口命名空间
- SYSTEM_FILE_TRANSFER: 文件管理转移接口命名空间
- SYSTEM_FILE_RESTORE: 文件管理恢复接口命名空间
- SYSTEM_POST_LIST: 岗位列表接口命名空间
- SYSTEM_POST_DETAIL: 岗位详情接口命名空间
- SYSTEM_POST_EXPORT: 岗位导出接口命名空间
- SYSTEM_ROLE_DEPT_TREE: 角色部门树接口命名空间
- SYSTEM_ROLE_LIST: 角色列表接口命名空间
- SYSTEM_ROLE_DETAIL: 角色详情接口命名空间
- SYSTEM_ROLE_ALLOCATED_USER_LIST: 已分配用户角色列表接口命名空间
- SYSTEM_ROLE_UNALLOCATED_USER_LIST: 未分配用户角色列表接口命名空间
- SYSTEM_ROLE_EXPORT: 角色导出接口命名空间
- SYSTEM_ROLE_AUTH_USER_SELECT_ALL: 角色批量分配用户接口命名空间
- SYSTEM_ROLE_AUTH_USER_CANCEL: 角色取消分配用户接口命名空间
- SYSTEM_ROLE_AUTH_USER_CANCEL_ALL: 角色批量取消分配用户接口命名空间
- SYSTEM_USER_DEPT_TREE: 用户部门树接口命名空间
- SYSTEM_USER_LIST: 用户列表接口命名空间
- SYSTEM_USER_PROFILE: 用户个人信息接口命名空间
- SYSTEM_USER_DETAIL: 用户详情接口命名空间
- SYSTEM_USER_PROFILE_AVATAR: 用户头像上传接口命名空间
- SYSTEM_USER_IMPORT: 用户导入接口命名空间
- SYSTEM_USER_EXPORT: 用户导出接口命名空间
-
- AI_MODEL_LIST: AI模型列表接口命名空间
- AI_MODEL_ALL: AI模型全量列表接口命名空间
- AI_MODEL_DETAIL: AI模型详情接口命名空间
- AI_CHAT_CONFIG: AI对话配置接口命名空间
- AI_CHAT_SEND: AI对话发送接口命名空间
- AI_CHAT_CANCEL: AI对话取消接口命名空间
-
- TOOL_GEN_LIST: 代码生成列表接口命名空间
- TOOL_GEN_DB_LIST: 代码生成数据源列表接口命名空间
- TOOL_GEN_DETAIL: 代码生成详情接口命名空间
- TOOL_GEN_PREVIEW: 代码生成预览接口命名空间
- TOOL_GEN_IMPORT_TABLE: 代码生成导入表接口命名空间
- TOOL_GEN_CREATE_TABLE: 代码生成建表接口命名空间
- TOOL_GEN_BATCH_GEN_CODE: 代码生成批量下载接口命名空间
- TOOL_GEN_GEN_CODE_LOCAL: 代码生成到本地接口命名空间
- TOOL_GEN_SYNC_DB: 代码生成同步库结构接口命名空间
+ :cvar LOGIN: 登录接口命名空间
+ :cvar LOGIN_UNLOCK_SCREEN: 锁屏解锁接口命名空间
+ :cvar REGISTER: 注册接口命名空间
+ :cvar LOGIN_USER_INFO: 登录用户信息接口命名空间
+ :cvar LOGIN_USER_ROUTERS: 登录用户路由接口命名空间
+ :cvar CAPTCHA_IMAGE: 图片验证码接口命名空间
+ :cvar COMMON_UPLOAD: 通用上传接口命名空间
+ :cvar COMMON_PRIVATE_UPLOAD: 通用私有文件上传接口命名空间
+ :cvar COMMON_FILE_DOWNLOAD: 通用文件下载接口命名空间
+ :cvar TRANSPORT_CRYPTO_PUBLIC_KEY: 传输层加密公钥接口命名空间
+ :cvar TRANSPORT_CRYPTO_FRONTEND_CONFIG: 传输层加密前端配置接口命名空间
+
+ :cvar OIDC_AUTHORIZE: OIDC 授权接口命名空间
+ :cvar OIDC_LOGIN: OIDC 登录接口命名空间
+ :cvar OIDC_TOKEN: OIDC 令牌接口命名空间
+ :cvar OIDC_USERINFO: OIDC 用户信息接口命名空间
+ :cvar OIDC_INTROSPECT: OIDC 令牌自省接口命名空间
+ :cvar OIDC_REVOKE: OIDC 令牌撤销接口命名空间
+ :cvar OIDC_LOGOUT: OIDC 登出接口命名空间
+ :cvar OIDC_INTERACTION: OIDC 认证交互接口命名空间
+ :cvar OIDC_INTERACTION_LOGIN: OIDC 认证交互登录接口命名空间
+ :cvar OIDC_INTERACTION_CONSENT: OIDC 认证交互同意接口命名空间
+
+ :cvar SYSTEM_OAUTH_CLIENT_CREATE: OAuth 客户端创建接口命名空间
+ :cvar SYSTEM_OAUTH_CLIENT_DISABLE: OAuth 客户端停用接口命名空间
+ :cvar SYSTEM_OAUTH_CLIENT_STATUS: OAuth 客户端状态接口命名空间
+ :cvar SYSTEM_OAUTH_CLIENT_UPDATE: OAuth 客户端更新接口命名空间
+ :cvar SYSTEM_OAUTH_CLIENT_SECRET_ROTATE: OAuth 客户端密钥轮换接口命名空间
+ :cvar SYSTEM_OAUTH_CLIENT_SECRET_REVOKE: OAuth 客户端密钥撤销接口命名空间
+ :cvar SYSTEM_OAUTH_CLIENT_URI_ADD: OAuth 客户端回调地址新增接口命名空间
+ :cvar SYSTEM_OAUTH_CLIENT_URI_REMOVE: OAuth 客户端回调地址移除接口命名空间
+ :cvar SYSTEM_OAUTH_RESOURCE_CREATE: OAuth 资源创建接口命名空间
+ :cvar SYSTEM_OAUTH_RESOURCE_UPDATE: OAuth 资源更新接口命名空间
+ :cvar SYSTEM_OAUTH_RESOURCE_DISABLE: OAuth 资源停用接口命名空间
+ :cvar SYSTEM_OAUTH_RESOURCE_STATUS: OAuth 资源状态接口命名空间
+ :cvar SYSTEM_OAUTH_SCOPE_CREATE: OAuth Scope 创建接口命名空间
+ :cvar SYSTEM_OAUTH_SCOPE_UPDATE: OAuth Scope 更新接口命名空间
+ :cvar SYSTEM_OAUTH_SCOPE_DISABLE: OAuth Scope 停用接口命名空间
+ :cvar SYSTEM_OAUTH_SCOPE_STATUS: OAuth Scope 状态接口命名空间
+ :cvar SYSTEM_OAUTH_SESSION_REVOKE: OAuth 会话撤销接口命名空间
+ :cvar SYSTEM_OAUTH_SESSION_USER_REVOKE: OAuth 用户会话批量撤销接口命名空间
+ :cvar SYSTEM_OAUTH_GRANT_ACCESS: 用户应用访问控制
+ :cvar SYSTEM_OAUTH_GRANT_REVOKE: OAuth 授权授予撤销接口命名空间
+ :cvar SYSTEM_OAUTH_KEY_ROTATE: OAuth 签名密钥轮换接口命名空间
+ :cvar SYSTEM_OAUTH_KEY_ACTIVATE: OAuth 签名密钥激活接口命名空间
+ :cvar SYSTEM_OAUTH_KEY_RETIRE: OAuth 签名密钥退役接口命名空间
+ :cvar SYSTEM_OAUTH_KEY_DELETE: OAuth 签名密钥删除接口命名空间
+ :cvar MONITOR_OAUTH_AUDIT_EXPORT: OAuth 审计日志导出接口命名空间
+ :cvar MONITOR_OAUTH_AUDIT_CLEANUP: OAuth 审计日志清理接口命名空间
+
+ :cvar MONITOR_SERVER_INFO: 服务监控信息接口命名空间
+ :cvar MONITOR_CACHE_CLEAR_NAME: 缓存名称清理接口命名空间
+ :cvar MONITOR_CACHE_CLEAR_KEY: 缓存键清理接口命名空间
+ :cvar MONITOR_CACHE_CLEAR_ALL: 缓存全量清理接口命名空间
+ :cvar MONITOR_ONLINE_FORCE_LOGOUT: 在线用户强退接口命名空间
+ :cvar MONITOR_OPERLOG_CLEAN: 操作日志清空接口命名空间
+ :cvar MONITOR_OPERLOG_DELETE: 操作日志删除接口命名空间
+ :cvar MONITOR_OPERLOG_EXPORT: 操作日志导出接口命名空间
+ :cvar MONITOR_LOGININFO_CLEAN: 登录日志清空接口命名空间
+ :cvar MONITOR_LOGININFO_DELETE: 登录日志删除接口命名空间
+ :cvar MONITOR_LOGININFO_UNLOCK: 账户解锁接口命名空间
+ :cvar MONITOR_LOGININFO_EXPORT: 登录日志导出接口命名空间
+ :cvar MONITOR_JOB_LIST: 定时任务分页列表接口命名空间
+ :cvar MONITOR_JOB_DETAIL: 定时任务详情接口命名空间
+ :cvar MONITOR_JOB_RUN: 定时任务执行接口命名空间
+ :cvar MONITOR_JOB_DELETE: 定时任务删除接口命名空间
+ :cvar MONITOR_JOB_EXPORT: 定时任务导出接口命名空间
+ :cvar MONITOR_JOB_LOG_CLEAN: 定时任务日志清空接口命名空间
+ :cvar MONITOR_JOB_LOG_DELETE: 定时任务日志删除接口命名空间
+ :cvar MONITOR_JOB_LOG_EXPORT: 定时任务日志导出接口命名空间
+
+ :cvar SYSTEM_DEPT_EDIT_TREE: 部门编辑树接口命名空间
+ :cvar SYSTEM_DEPT_LIST: 部门列表接口命名空间
+ :cvar SYSTEM_DEPT_DETAIL: 部门详情接口命名空间
+ :cvar SYSTEM_CONFIG_LIST: 参数配置列表接口命名空间
+ :cvar SYSTEM_CONFIG_DETAIL: 参数配置详情接口命名空间
+ :cvar SYSTEM_CONFIG_REFRESH_CACHE: 参数缓存刷新接口命名空间
+ :cvar SYSTEM_CONFIG_EXPORT: 参数导出接口命名空间
+ :cvar SYSTEM_DICT_TYPE_LIST: 字典类型列表接口命名空间
+ :cvar SYSTEM_DICT_TYPE_OPTIONS: 字典类型选项接口命名空间
+ :cvar SYSTEM_DICT_TYPE_DETAIL: 字典类型详情接口命名空间
+ :cvar SYSTEM_DICT_REFRESH_CACHE: 字典缓存刷新接口命名空间
+ :cvar SYSTEM_DICT_TYPE_EXPORT: 字典类型导出接口命名空间
+ :cvar SYSTEM_DICT_DATA_LIST: 字典数据列表接口命名空间
+ :cvar SYSTEM_DICT_DATA_DETAIL: 字典数据详情接口命名空间
+ :cvar SYSTEM_DICT_DATA_EXPORT: 字典数据导出接口命名空间
+ :cvar SYSTEM_MENU_TREE: 菜单树接口命名空间
+ :cvar SYSTEM_MENU_ROLE_TREE: 角色菜单树接口命名空间
+ :cvar SYSTEM_MENU_LIST: 菜单分页列表接口命名空间
+ :cvar SYSTEM_MENU_DETAIL: 菜单详情接口命名空间
+ :cvar SYSTEM_NOTICE_LIST: 通知公告列表接口命名空间
+ :cvar SYSTEM_NOTICE_DETAIL: 通知公告详情接口命名空间
+ :cvar SYSTEM_FILE_DOWNLOAD: 文件管理下载接口命名空间
+ :cvar SYSTEM_FILE_DELETE: 文件管理删除接口命名空间
+ :cvar SYSTEM_FILE_ACL: 文件访问控制接口命名空间
+ :cvar SYSTEM_FILE_RETENTION_POLICY: 文件业务保留策略接口命名空间
+ :cvar SYSTEM_FILE_RECONCILE: 文件存储对账接口命名空间
+ :cvar SYSTEM_FILE_TRANSFER: 文件管理转移接口命名空间
+ :cvar SYSTEM_FILE_RESTORE: 文件管理恢复接口命名空间
+ :cvar SYSTEM_POST_LIST: 岗位列表接口命名空间
+ :cvar SYSTEM_POST_DETAIL: 岗位详情接口命名空间
+ :cvar SYSTEM_POST_EXPORT: 岗位导出接口命名空间
+ :cvar SYSTEM_ROLE_DEPT_TREE: 角色部门树接口命名空间
+ :cvar SYSTEM_ROLE_LIST: 角色列表接口命名空间
+ :cvar SYSTEM_ROLE_DETAIL: 角色详情接口命名空间
+ :cvar SYSTEM_ROLE_ALLOCATED_USER_LIST: 已分配用户角色列表接口命名空间
+ :cvar SYSTEM_ROLE_UNALLOCATED_USER_LIST: 未分配用户角色列表接口命名空间
+ :cvar SYSTEM_ROLE_EXPORT: 角色导出接口命名空间
+ :cvar SYSTEM_ROLE_AUTH_USER_SELECT_ALL: 角色批量分配用户接口命名空间
+ :cvar SYSTEM_ROLE_AUTH_USER_CANCEL: 角色取消分配用户接口命名空间
+ :cvar SYSTEM_ROLE_AUTH_USER_CANCEL_ALL: 角色批量取消分配用户接口命名空间
+ :cvar SYSTEM_USER_DEPT_TREE: 用户部门树接口命名空间
+ :cvar SYSTEM_USER_LIST: 用户列表接口命名空间
+ :cvar SYSTEM_USER_PROFILE: 用户个人信息接口命名空间
+ :cvar SYSTEM_USER_DETAIL: 用户详情接口命名空间
+ :cvar SYSTEM_USER_PROFILE_AVATAR: 用户头像上传接口命名空间
+ :cvar SYSTEM_USER_IMPORT: 用户导入接口命名空间
+ :cvar SYSTEM_USER_EXPORT: 用户导出接口命名空间
+
+ :cvar AI_MODEL_LIST: AI模型列表接口命名空间
+ :cvar AI_MODEL_ALL: AI模型全量列表接口命名空间
+ :cvar AI_MODEL_DETAIL: AI模型详情接口命名空间
+ :cvar AI_CHAT_CONFIG: AI对话配置接口命名空间
+ :cvar AI_CHAT_SEND: AI对话发送接口命名空间
+ :cvar AI_CHAT_CANCEL: AI对话取消接口命名空间
+
+ :cvar TOOL_GEN_LIST: 代码生成列表接口命名空间
+ :cvar TOOL_GEN_DB_LIST: 代码生成数据源列表接口命名空间
+ :cvar TOOL_GEN_DETAIL: 代码生成详情接口命名空间
+ :cvar TOOL_GEN_PREVIEW: 代码生成预览接口命名空间
+ :cvar TOOL_GEN_IMPORT_TABLE: 代码生成导入表接口命名空间
+ :cvar TOOL_GEN_CREATE_TABLE: 代码生成建表接口命名空间
+ :cvar TOOL_GEN_BATCH_GEN_CODE: 代码生成批量下载接口命名空间
+ :cvar TOOL_GEN_GEN_CODE_LOCAL: 代码生成到本地接口命名空间
+ :cvar TOOL_GEN_SYNC_DB: 代码生成同步库结构接口命名空间
"""
LOGIN = 'login'
@@ -570,31 +570,31 @@ class ApiNamespace:
class ApiGroup:
"""
- 接口命名空间分组常量
-
- 当前主要用于 `ApiCacheEvict` 批量清理关联命名空间,分组成员均来自
- `ApiNamespace`,按业务写操作影响范围收敛管理。
-
- PERMISSION_MUTATION: 权限与菜单视图关联命名空间分组
- DATA_SCOPE_MUTATION: 数据范围相关视图关联命名空间分组
- MENU_MUTATION: 菜单写操作关联命名空间分组
- JOB_MUTATION: 定时任务写操作关联命名空间分组
- POST_MUTATION: 岗位写操作关联命名空间分组
- NOTICE_MUTATION: 通知公告写操作关联命名空间分组
- ROLE_ENTITY_MUTATION: 角色实体信息变更关联命名空间分组
- ROLE_PERMISSION_MUTATION: 角色权限变更关联命名空间分组
- ROLE_MUTATION: 角色通用写操作关联命名空间组合分组
- USER_ENTITY_MUTATION: 用户实体信息变更关联命名空间分组
- USER_PERMISSION_MUTATION: 用户权限变更关联命名空间分组
- USER_INFO_MUTATION: 用户资料与安全相关写操作关联命名空间分组
- LOGIN_SUCCESS_MUTATION: 登录成功后关联命名空间分组
- LOGOUT_MUTATION: 登出后关联命名空间分组
- CONFIG_MUTATION: 参数配置写操作关联命名空间分组
- DICT_TYPE_MUTATION: 字典类型写操作关联命名空间分组
- DICT_DATA_MUTATION: 字典数据写操作关联命名空间分组
- AI_MODEL_MUTATION: AI模型写操作关联命名空间分组
- AI_CHAT_CONFIG_MUTATION: AI对话配置写操作关联命名空间分组
- GEN_MUTATION: 代码生成写操作关联命名空间分组
+ 接口命名空间分组常量。
+
+ 当前主要用于 ``ApiCacheEvict`` 批量清理关联命名空间,分组成员均来自
+ ``ApiNamespace``,按业务写操作影响范围收敛管理。
+
+ :cvar PERMISSION_MUTATION: 权限与菜单视图关联命名空间分组
+ :cvar DATA_SCOPE_MUTATION: 数据范围相关视图关联命名空间分组
+ :cvar MENU_MUTATION: 菜单写操作关联命名空间分组
+ :cvar JOB_MUTATION: 定时任务写操作关联命名空间分组
+ :cvar POST_MUTATION: 岗位写操作关联命名空间分组
+ :cvar NOTICE_MUTATION: 通知公告写操作关联命名空间分组
+ :cvar ROLE_ENTITY_MUTATION: 角色实体信息变更关联命名空间分组
+ :cvar ROLE_PERMISSION_MUTATION: 角色权限变更关联命名空间分组
+ :cvar ROLE_MUTATION: 角色通用写操作关联命名空间组合分组
+ :cvar USER_ENTITY_MUTATION: 用户实体信息变更关联命名空间分组
+ :cvar USER_PERMISSION_MUTATION: 用户权限变更关联命名空间分组
+ :cvar USER_INFO_MUTATION: 用户资料与安全相关写操作关联命名空间分组
+ :cvar LOGIN_SUCCESS_MUTATION: 登录成功后关联命名空间分组
+ :cvar LOGOUT_MUTATION: 登出后关联命名空间分组
+ :cvar CONFIG_MUTATION: 参数配置写操作关联命名空间分组
+ :cvar DICT_TYPE_MUTATION: 字典类型写操作关联命名空间分组
+ :cvar DICT_DATA_MUTATION: 字典数据写操作关联命名空间分组
+ :cvar AI_MODEL_MUTATION: AI模型写操作关联命名空间分组
+ :cvar AI_CHAT_CONFIG_MUTATION: AI对话配置写操作关联命名空间分组
+ :cvar GEN_MUTATION: 代码生成写操作关联命名空间分组
"""
PERMISSION_MUTATION = (
@@ -736,17 +736,17 @@ class ApiGroup:
class MenuConstant:
"""
- 菜单常量
-
- ROOT_ID: 根菜单ID
- TYPE_DIR: 菜单类型(目录)
- TYPE_MENU: 菜单类型(菜单)
- TYPE_BUTTON: 菜单类型(按钮)
- YES_FRAME: 是否菜单外链(是)
- NO_FRAME: 是否菜单外链(否)
- LAYOUT: Layout组件标识
- PARENT_VIEW: ParentView组件标识
- INNER_LINK: InnerLink组件标识
+ 菜单常量。
+
+ :cvar ROOT_ID: 根菜单ID
+ :cvar TYPE_DIR: 菜单类型(目录)
+ :cvar TYPE_MENU: 菜单类型(菜单)
+ :cvar TYPE_BUTTON: 菜单类型(按钮)
+ :cvar YES_FRAME: 是否菜单外链(是)
+ :cvar NO_FRAME: 是否菜单外链(否)
+ :cvar LAYOUT: Layout组件标识
+ :cvar PARENT_VIEW: ParentView组件标识
+ :cvar INNER_LINK: InnerLink组件标识
"""
ROOT_ID = 0
@@ -762,45 +762,45 @@ class MenuConstant:
class GenConstant:
"""
- 代码生成常量
-
- TPL_CRUD: 单表(增删改查
- TPL_TREE: 树表(增删改查)
- TPL_SUB: 主子表(增删改查)
- TREE_CODE: 树编码字段
- TREE_PARENT_CODE: 树父编码字段
- TREE_NAME: 树名称字段
- PARENT_MENU_ID: 上级菜单ID字段
- PARENT_MENU_NAME: 上级菜单名称字段
- GEN_VIEW: 生成详情页开关
- COLUMNTYPE_STR: 数据库字符串类型
- COLUMNTYPE_TEXT: 数据库文本类型
- COLUMNTYPE_TIME: 数据库时间类型
- COLUMNTYPE_GEOMETRY: 数据库字空间类型
- COLUMNTYPE_NUMBER: 数据库数字类型
- COLUMNNAME_NOT_EDIT: 页面不需要编辑字段
- COLUMNNAME_NOT_LIST: 页面不需要显示的列表字段
- COLUMNNAME_NOT_QUERY: 页面不需要查询字段
- BASE_ENTITY: Entity基类字段
- TREE_ENTITY: Tree基类字段
- HTML_INPUT: 文本框
- HTML_TEXTAREA: 文本域
- HTML_SELECT: 下拉框
- HTML_RADIO: 单选框
- HTML_CHECKBOX: 复选框
- HTML_DATETIME: 日期控件
- HTML_IMAGE_UPLOAD: 图片上传控件
- HTML_FILE_UPLOAD: 文件上传控件
- HTML_EDITOR: 富文本控件
- TYPE_DECIMAL: 高精度计算类型
- TYPE_DATE: 时间类型
- QUERY_LIKE: 模糊查询
- QUERY_EQ: 相等查询
- REQUIRE: 需要
- COLUMNNAME_NOT_ADD_SHOW: 页面新增时不显示字段
- COLUMNNAME_NOT_EDIT_SHOW: 页面编辑时不显示字段
- DB_TO_SQLALCHEMY_TYPE_MAPPING: 数据库类型与sqlalchemy类型映射
- DB_TO_PYTHON_TYPE_MAPPING: 数据库类型与python类型映射
+ 代码生成常量。
+
+ :cvar TPL_CRUD: 单表(增删改查
+ :cvar TPL_TREE: 树表(增删改查)
+ :cvar TPL_SUB: 主子表(增删改查)
+ :cvar TREE_CODE: 树编码字段
+ :cvar TREE_PARENT_CODE: 树父编码字段
+ :cvar TREE_NAME: 树名称字段
+ :cvar PARENT_MENU_ID: 上级菜单ID字段
+ :cvar PARENT_MENU_NAME: 上级菜单名称字段
+ :cvar GEN_VIEW: 生成详情页开关
+ :cvar COLUMNTYPE_STR: 数据库字符串类型
+ :cvar COLUMNTYPE_TEXT: 数据库文本类型
+ :cvar COLUMNTYPE_TIME: 数据库时间类型
+ :cvar COLUMNTYPE_GEOMETRY: 数据库字空间类型
+ :cvar COLUMNTYPE_NUMBER: 数据库数字类型
+ :cvar COLUMNNAME_NOT_EDIT: 页面不需要编辑字段
+ :cvar COLUMNNAME_NOT_LIST: 页面不需要显示的列表字段
+ :cvar COLUMNNAME_NOT_QUERY: 页面不需要查询字段
+ :cvar BASE_ENTITY: Entity基类字段
+ :cvar TREE_ENTITY: Tree基类字段
+ :cvar HTML_INPUT: 文本框
+ :cvar HTML_TEXTAREA: 文本域
+ :cvar HTML_SELECT: 下拉框
+ :cvar HTML_RADIO: 单选框
+ :cvar HTML_CHECKBOX: 复选框
+ :cvar HTML_DATETIME: 日期控件
+ :cvar HTML_IMAGE_UPLOAD: 图片上传控件
+ :cvar HTML_FILE_UPLOAD: 文件上传控件
+ :cvar HTML_EDITOR: 富文本控件
+ :cvar TYPE_DECIMAL: 高精度计算类型
+ :cvar TYPE_DATE: 时间类型
+ :cvar QUERY_LIKE: 模糊查询
+ :cvar QUERY_EQ: 相等查询
+ :cvar REQUIRE: 需要
+ :cvar COLUMNNAME_NOT_ADD_SHOW: 页面新增时不显示字段
+ :cvar COLUMNNAME_NOT_EDIT_SHOW: 页面编辑时不显示字段
+ :cvar DB_TO_SQLALCHEMY_TYPE_MAPPING: 数据库类型与sqlalchemy类型映射
+ :cvar DB_TO_PYTHON_TYPE_MAPPING: 数据库类型与python类型映射
"""
TPL_CRUD = 'crud'
diff --git a/ruoyi-fastapi-backend/common/context.py b/ruoyi-fastapi-backend/common/context.py
index 71883fd9e..755e532ea 100644
--- a/ruoyi-fastapi-backend/common/context.py
+++ b/ruoyi-fastapi-backend/common/context.py
@@ -13,7 +13,9 @@
@dataclass(frozen=True)
class LocaleContext:
"""
- 当前请求的有效语言
+ 当前请求的有效语言。
+
+ :ivar locale: 当前使用的语言区域标识
"""
locale: str = I18nConfig.i18n_default_locale
@@ -32,9 +34,7 @@ class LocaleContext:
class RequestContext:
- """
- 请求上下文管理类,用于设置和清理上下文变量
- """
+ """请求上下文管理类,用于设置和清理上下文变量。"""
@staticmethod
def set_current_exclude_patterns(
@@ -43,7 +43,7 @@ def set_current_exclude_patterns(
],
) -> Token:
"""
- 设置当前请求的编译后的排除路由模式列表
+ 设置当前请求的编译后的排除路由模式列表。
:param exclude_patterns: 编译后的排除路由模式列表
:return: 上下文变量令牌,用于重置
@@ -55,7 +55,7 @@ def get_current_exclude_patterns() -> list[
dict[str, str | list[Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']] | re.Pattern]
]:
"""
- 获取当前请求的编译后的排除路由模式列表
+ 获取当前请求的编译后的排除路由模式列表。
:return: 编译后的排除路由模式列表
"""
@@ -67,7 +67,7 @@ def get_current_exclude_patterns() -> list[
@staticmethod
def set_current_user(user: 'CurrentUserModel') -> Token:
"""
- 设置当前用户信息
+ 设置当前用户信息。
:param user: 用户信息
:return: 上下文变量令牌,用于重置
@@ -77,9 +77,10 @@ def set_current_user(user: 'CurrentUserModel') -> Token:
@staticmethod
def get_current_user() -> 'CurrentUserModel':
"""
- 获取当前用户信息
+ 获取当前用户信息。
:return: 用户信息
+ :raises LoginException: 当前用户信息为空,请检查是否已登录
"""
_current_user = current_user.get()
if _current_user is None:
@@ -91,7 +92,7 @@ def get_current_user() -> 'CurrentUserModel':
@staticmethod
def reset_current_exclude_patterns(token: Token) -> None:
"""
- 重置当前请求的编译后的排除路由模式列表
+ 重置当前请求的编译后的排除路由模式列表。
:param token: 设置编译后的排除路由模式列表时返回的令牌
"""
@@ -100,7 +101,7 @@ def reset_current_exclude_patterns(token: Token) -> None:
@staticmethod
def reset_current_user(token: Token) -> None:
"""
- 重置当前用户信息
+ 重置当前用户信息。
:param token: 设置用户信息时返回的令牌
"""
@@ -109,7 +110,7 @@ def reset_current_user(token: Token) -> None:
@staticmethod
def set_current_timezone(timezone_name: str | None) -> Token:
"""
- 保存中间件已校验的请求时区
+ 保存中间件已校验的请求时区。
:param timezone_name: IANA时区名称,未上报时为None
:return: 用于恢复上下文的令牌
@@ -119,7 +120,7 @@ def set_current_timezone(timezone_name: str | None) -> Token:
@staticmethod
def reset_current_timezone(token: Token) -> None:
"""
- 恢复请求进入前的时区,避免并发请求之间串用
+ 恢复请求进入前的时区,避免并发请求之间串用。
:param token: 设置请求时区时返回的令牌
"""
@@ -128,7 +129,7 @@ def reset_current_timezone(token: Token) -> None:
@staticmethod
def get_current_timezone() -> str | None:
"""
- 优先使用页面实际展示的时区,未上报时回退到账号偏好
+ 优先使用页面实际展示的时区,未上报时回退到账号偏好。
:return: 当前请求的IANA时区名称,未指定时为None
"""
@@ -141,7 +142,7 @@ def get_current_timezone() -> str | None:
@staticmethod
def set_current_locale(context: LocaleContext) -> Token[LocaleContext | None]:
"""
- 保存中间件已协商的请求语言上下文
+ 保存中间件已协商的请求语言上下文。
:param context: 当前请求的有效语言
:return: 用于恢复上下文的令牌
@@ -151,7 +152,7 @@ def set_current_locale(context: LocaleContext) -> Token[LocaleContext | None]:
@staticmethod
def get_current_locale() -> LocaleContext:
"""
- 获取当前请求的语言上下文,未设置时使用默认语言
+ 获取当前请求的语言上下文,未设置时使用默认语言。
:return: 当前请求的语言上下文
"""
@@ -163,7 +164,7 @@ def get_current_locale() -> LocaleContext:
@staticmethod
def reset_current_locale(token: Token[LocaleContext | None]) -> None:
"""
- 恢复进入当前作用域前的语言上下文
+ 恢复进入当前作用域前的语言上下文。
:param token: 设置语言上下文时返回的令牌
"""
@@ -171,9 +172,7 @@ def reset_current_locale(token: Token[LocaleContext | None]) -> None:
@staticmethod
def clear_all() -> None:
- """
- 清除所有上下文变量
- """
+ """清除所有上下文变量。"""
current_exclude_patterns.set(None)
current_user.set(None)
current_timezone.set(None)
diff --git a/ruoyi-fastapi-backend/common/enums.py b/ruoyi-fastapi-backend/common/enums.py
index 7fe306f88..7a13194e4 100644
--- a/ruoyi-fastapi-backend/common/enums.py
+++ b/ruoyi-fastapi-backend/common/enums.py
@@ -3,17 +3,17 @@
class HttpMethod(StrEnum):
"""
- HTTP请求方法枚举
-
- GET: 获取资源
- POST: 创建资源
- PUT: 整体更新资源
- DELETE: 删除资源
- PATCH: 局部更新资源
- HEAD: 获取响应头
- OPTIONS: 获取允许的方法信息
- TRACE: 回显诊断请求
- CONNECT: 建立隧道连接
+ HTTP请求方法枚举。
+
+ :cvar GET: 获取资源
+ :cvar POST: 创建资源
+ :cvar PUT: 整体更新资源
+ :cvar DELETE: 删除资源
+ :cvar PATCH: 局部更新资源
+ :cvar HEAD: 获取响应头
+ :cvar OPTIONS: 获取允许的方法信息
+ :cvar TRACE: 回显诊断请求
+ :cvar CONNECT: 建立隧道连接
"""
GET = 'GET'
@@ -29,18 +29,18 @@ class HttpMethod(StrEnum):
class BusinessType(Enum):
"""
- 业务操作类型
-
- OTHER: 其它
- INSERT: 新增
- UPDATE: 修改
- DELETE: 删除
- GRANT: 授权
- EXPORT: 导出
- IMPORT: 导入
- FORCE: 强退
- GENCODE: 生成代码
- CLEAN: 清空数据
+ 业务操作类型。
+
+ :cvar OTHER: 其它
+ :cvar INSERT: 新增
+ :cvar UPDATE: 修改
+ :cvar DELETE: 删除
+ :cvar GRANT: 授权
+ :cvar EXPORT: 导出
+ :cvar IMPORT: 导入
+ :cvar FORCE: 强退
+ :cvar GENCODE: 生成代码
+ :cvar CLEAN: 清空数据
"""
OTHER = 0
@@ -57,10 +57,26 @@ class BusinessType(Enum):
class PasswordCharacterType(Enum):
"""
- 密码字符范围类型
+ 密码字符范围类型。
+
+ :cvar DEFAULT: 密码不能包含非法字符:< > " ' / |
+ :cvar NUMBER: 密码只能为数字(0-9)
+ :cvar LETTER: 密码只能为英文字母(a-z、A-Z)
+ :cvar LETTER_NUMBER: 密码必须同时包含字母和数字
+ :cvar LETTER_NUMBER_SPECIAL: 密码必须同时包含字母、数字和特殊字符(~!@#$%^&*()-=_+)
+ :ivar code: 密码字符范围配置值
+ :ivar pattern: 用于验证输入的正则表达式
+ :ivar message: 与当前结果一起返回的说明
"""
def __init__(self, code: str, pattern: str, message: str) -> None:
+ """
+ 保存密码字符类别的编码、匹配表达式和提示。
+
+ :param code: 密码字符范围配置值
+ :param pattern: 用于验证输入的正则表达式
+ :param message: 与当前结果一起返回的说明
+ """
self.code = code
self.pattern = pattern
self.message = message
@@ -68,7 +84,7 @@ def __init__(self, code: str, pattern: str, message: str) -> None:
@classmethod
def from_code(cls, code: str | bytes | None) -> 'PasswordCharacterType':
"""
- 根据配置值获取密码字符范围类型
+ 根据配置值获取密码字符范围类型。
:param code: 密码字符范围配置值
:return: 密码字符范围类型
@@ -91,15 +107,35 @@ def from_code(cls, code: str | bytes | None) -> 'PasswordCharacterType':
class RedisInitKeyConfig(Enum):
"""
- 系统内置Redis键名
+ 系统内置Redis键名。
+
+ :cvar ACCESS_TOKEN: 登录令牌信息
+ :cvar SYS_DICT: 数据字典
+ :cvar SYS_CONFIG: 配置信息
+ :cvar API_CACHE: 接口响应缓存
+ :cvar API_RATE_LIMIT: 接口限流
+ :cvar CAPTCHA_CODES: 图片验证码
+ :cvar ACCOUNT_LOCK: 用户锁定
+ :cvar PASSWORD_ERROR_COUNT: 密码错误次数
+ :cvar SMS_CODE: 短信验证码
"""
@property
def key(self) -> str | None:
+ """
+ 返回初始化配置对应的 Redis 键。
+
+ :return: 初始化配置对应的 Redis 键
+ """
return self.value.get('key')
@property
def remark(self) -> str | None:
+ """
+ 返回 Redis 初始化配置的用途说明。
+
+ :return: Redis 初始化配置的用途说明
+ """
return self.value.get('remark')
ACCESS_TOKEN = {'key': 'access_token', 'remark': '登录令牌信息'}
diff --git a/ruoyi-fastapi-backend/common/mixin.py b/ruoyi-fastapi-backend/common/mixin.py
index 125bc18d8..50abc8314 100644
--- a/ruoyi-fastapi-backend/common/mixin.py
+++ b/ruoyi-fastapi-backend/common/mixin.py
@@ -11,7 +11,10 @@
class CreateTimeMixin:
"""
- 创建时间字段Mixin
+ 创建时间字段Mixin。
+
+ :cvar __create_time_nullable__: 创建时间列是否允许空值
+ :cvar __create_time_comment__: 创建时间列的数据库注释
"""
__create_time_nullable__ = True
@@ -19,6 +22,11 @@ class CreateTimeMixin:
@declared_attr
def create_time(cls) -> Mapped[datetime]: # noqa: N805
+ """
+ 声明记录创建时间的 ORM 字段。
+
+ :return: ``Column`` 实例
+ """
return Column(
DbUtcDateTime(),
nullable=cls.__create_time_nullable__,
@@ -29,7 +37,11 @@ def create_time(cls) -> Mapped[datetime]: # noqa: N805
class UpdateTimeMixin:
"""
- 更新时间字段Mixin
+ 更新时间字段Mixin。
+
+ :cvar __update_time_nullable__: 更新时间列是否允许空值
+ :cvar __update_time_insert_default__: 新增记录时是否填充默认更新时间
+ :cvar __update_time_comment__: 更新时间列的数据库注释
"""
__update_time_nullable__ = True
@@ -38,6 +50,11 @@ class UpdateTimeMixin:
@declared_attr
def update_time(cls) -> Mapped[datetime]: # noqa: N805
+ """
+ 声明记录更新时间的 ORM 字段。
+
+ :return: ``Column`` 实例
+ """
return Column(
DbUtcDateTime(),
nullable=cls.__update_time_nullable__,
@@ -48,21 +65,17 @@ def update_time(cls) -> Mapped[datetime]: # noqa: N805
class AuditTimeMixin(CreateTimeMixin, UpdateTimeMixin):
- """
- 创建时间和更新时间字段Mixin
- """
+ """创建时间和更新时间字段Mixin。"""
class DateRangeQueryMixin:
- """
- 业务日期范围查询校验混入类
- """
+ """业务日期范围查询校验混入类。"""
@field_validator('begin_time', 'end_time', mode='before', check_fields=False)
@classmethod
def validate_date_boundary(cls, value: Any) -> str | None:
"""
- 校验日期查询边界并保留纯日期字符串协议
+ 校验日期查询边界并保留纯日期字符串协议。
:param value: 待校验的输入值
:return: YYYY-MM-DD字符串,空值返回None
@@ -74,9 +87,10 @@ def validate_date_boundary(cls, value: Any) -> str | None:
@model_validator(mode='after')
def validate_date_range(self) -> 'DateRangeQueryMixin':
"""
- 校验业务日期范围顺序和结束日期上限
+ 校验业务日期范围顺序和结束日期上限。
:return: 校验通过的查询模型
+ :raises ValueError: 结束日期不能早于开始日期;结束日期必须早于9999-12-31
"""
begin, end = self.begin_time, self.end_time
if begin and end and end < begin:
@@ -87,15 +101,13 @@ def validate_date_range(self) -> 'DateRangeQueryMixin':
class InstantRangeQueryMixin:
- """
- RFC 3339时刻范围查询校验混入类
- """
+ """RFC 3339时刻范围查询校验混入类。"""
@field_validator('begin_time', 'end_time', mode='before', check_fields=False)
@classmethod
def validate_instant_boundary(cls, value: Any) -> str | None:
"""
- 校验精确时刻查询边界并归一化为UTC
+ 校验精确时刻查询边界并归一化为UTC。
:param value: 待校验的输入值
:return: 携带UTC偏移的毫秒精度字符串,空值返回None
@@ -107,9 +119,10 @@ def validate_instant_boundary(cls, value: Any) -> str | None:
@model_validator(mode='after')
def validate_instant_range(self) -> 'InstantRangeQueryMixin':
"""
- 按真实时刻校验查询范围顺序
+ 按真实时刻校验查询范围顺序。
:return: 校验通过的查询模型
+ :raises ValueError: 结束时间不能早于开始时间
"""
begin, end = self.begin_time, self.end_time
if begin and end and TimezoneUtil.parse_rfc3339(end) < TimezoneUtil.parse_rfc3339(begin):
@@ -119,7 +132,9 @@ def validate_instant_range(self) -> 'InstantRangeQueryMixin':
class GeneratedTimeRangeQueryMixin:
"""
- 代码生成器命名时间范围校验混入类
+ 代码生成器命名时间范围校验混入类。
+
+ :cvar time_range_fields: 参与区间查询的字段及其时间语义
"""
time_range_fields: ClassVar[dict[str, str]] = {}
@@ -127,9 +142,10 @@ class GeneratedTimeRangeQueryMixin:
@model_validator(mode='after')
def validate_generated_time_ranges(self) -> 'GeneratedTimeRangeQueryMixin':
"""
- 校验生成模型中的命名时间范围
+ 校验生成模型中的命名时间范围。
:return: 校验通过的查询模型
+ :raises ValueError: 结束值早于开始值,或结束日期无法转换为开区间上界
"""
for name, kind in self.time_range_fields.items():
begin, end = getattr(self, f'begin_{name}'), getattr(self, f'end_{name}')
diff --git a/ruoyi-fastapi-backend/common/router.py b/ruoyi-fastapi-backend/common/router.py
index 77f707897..a4a4fbcae 100644
--- a/ruoyi-fastapi-backend/common/router.py
+++ b/ruoyi-fastapi-backend/common/router.py
@@ -287,12 +287,15 @@ def __init__( # noqa: PLR0913
class RouterRegister:
"""
- 路由注册器,用于自动注册所有controller目录下的路由
+ 路由注册器,用于自动注册所有controller目录下的路由。
+
+ :ivar app: FastAPI对象
+ :ivar project_root: 测试项目根目录
"""
def __init__(self, app: FastAPI) -> None:
"""
- 初始化路由注册器
+ 初始化路由注册器。
:param app: FastAPI对象
"""
@@ -303,7 +306,7 @@ def __init__(self, app: FastAPI) -> None:
def _find_controller_files(self) -> list[str]:
"""
- 查找所有controller目录下的py文件
+ 查找所有controller目录下的py文件。
:return: py文件路径列表
"""
@@ -312,7 +315,7 @@ def _find_controller_files(self) -> list[str]:
def _import_module_and_get_routers(self, controller_files: list[str]) -> list[tuple[str, APIRouter]]:
"""
- 导入模块并获取路由实例
+ 导入模块并获取路由实例。
:param controller_files: controller目录下的py文件路径列表
:return: 路由实例列表
@@ -338,7 +341,7 @@ def _import_module_and_get_routers(self, controller_files: list[str]) -> list[tu
def _sort_routers(self, routers: list[tuple[str, APIRouter]]) -> list[tuple[str, APIRouter]]:
"""
- 按规则排序路由
+ 按规则排序路由。
:param routers: 路由实例列表
:return: 排序后的路由实例列表
@@ -346,6 +349,12 @@ def _sort_routers(self, routers: list[tuple[str, APIRouter]]) -> list[tuple[str,
# 按规则排序路由
def sort_key(item: tuple[str, APIRouter]) -> tuple[Literal[0], int, str] | tuple[Literal[1], str]:
+ """
+ 返回路由自动注册时使用的排序键。
+
+ :param item: 当前要处理的条目
+ :return: 路由自动注册时使用的排序键
+ """
attr_name, router = item
# APIRouterPro实例按order_num排序,序号越小越靠前
if isinstance(router, APIRouterPro):
@@ -361,21 +370,16 @@ def _register_routers_to_app(
dependencies: Sequence[params.Depends] | None = None,
) -> None:
"""
- 将路由注册到FastAPI应用
+ 将路由注册到FastAPI应用。
:param routers: 排序后的路由实例列表
:param dependencies: 注册时附加到路由上的依赖项
- :return: None
"""
for _attr_name, router in routers:
self.app.include_router(router=router, dependencies=dependencies)
def register_routers(self) -> None:
- """
- 自动注册所有controller目录下的路由
-
- :return: None
- """
+ """自动注册所有controller目录下的路由。"""
# 查找所有controller目录下的py文件
controller_files = self._find_controller_files()
self._register_controller_files(controller_files)
@@ -390,7 +394,6 @@ def _register_controller_files(
:param controller_files: controller文件路径列表
:param dependencies: 注册时附加到路由上的依赖项
- :return: None
"""
# 导入模块并获取路由实例
routers = self._import_module_and_get_routers(controller_files)
@@ -402,10 +405,9 @@ def _register_controller_files(
def auto_register_routers(app: FastAPI) -> None:
"""
- 自动注册所有controller目录下的路由
+ 自动注册所有controller目录下的路由。
:param app: FastAPI对象
- :return: None
"""
# 使用路由注册器进行注册
router_register = RouterRegister(app)
@@ -423,7 +425,6 @@ def auto_register_controller_files(
:param app: FastAPI对象
:param controller_files: controller文件路径列表
:param dependencies: 注册时附加到路由上的依赖项
- :return: None
"""
router_register = RouterRegister(app)
router_register._register_controller_files(list(controller_files), dependencies)
diff --git a/ruoyi-fastapi-backend/common/types.py b/ruoyi-fastapi-backend/common/types.py
index ecd6fec33..abc2b81d2 100644
--- a/ruoyi-fastapi-backend/common/types.py
+++ b/ruoyi-fastapi-backend/common/types.py
@@ -14,7 +14,7 @@
def validate_aware_datetime_input(value: Any) -> datetime:
"""
- 校验API输入的真实时刻
+ 校验API输入的真实时刻。
:param value: 待校验的输入值
:return: 携带UTC时区的毫秒精度时刻
@@ -32,12 +32,13 @@ def validate_aware_datetime_input(value: Any) -> datetime:
def validate_business_time_input(value: Any) -> time:
"""
- 校验不含日期和时区的一天内时间
+ 校验不含日期和时区的一天内时间。
仅接受time对象或HH:mm:ss格式字符串,可含小数秒,不接受时间戳或持续时长。
:param value: 待校验的输入值
:return: 一天内的时间对象
+ :raises ValueError: 一天内时间必须为 HH:mm:ss,可含小数秒,不能带时区
"""
if isinstance(value, str) and re.fullmatch(r'(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,6})?', value):
value = time.fromisoformat(value)
@@ -56,6 +57,9 @@ class DbUtcDateTime(TypeDecorator[datetime]):
PostgreSQL使用带时区时间戳;MySQL和SQLite在驱动边界保存naive UTC,
应用层始终只接收和返回aware UTC datetime。
+
+ :cvar impl: 向 SQLAlchemy 声明的底层字段类型
+ :cvar cache_ok: 是否允许 SQLAlchemy 缓存包含此类型的 SQL
"""
impl = DateTime
@@ -63,7 +67,7 @@ class DbUtcDateTime(TypeDecorator[datetime]):
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
"""
- 获取当前数据库对应的毫秒精度时间类型
+ 获取当前数据库对应的毫秒精度时间类型。
:param dialect: SQLAlchemy数据库方言
:return: 数据库实际使用的时间类型
@@ -76,11 +80,12 @@ def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
def process_bind_param(self, value: datetime | None, dialect: Dialect) -> datetime | None:
"""
- 在写入边界统一UTC时区和毫秒精度
+ 在写入边界统一UTC时区和毫秒精度。
:param value: 待写入时刻
:param dialect: SQLAlchemy数据库方言
:return: 符合驱动要求的UTC时刻,空值返回None
+ :raises ValueError: DbUtcDateTime只接受携带时区信息的datetime
"""
if value is None:
return None
@@ -93,7 +98,7 @@ def process_bind_param(self, value: datetime | None, dialect: Dialect) -> dateti
def process_result_value(self, value: datetime | None, dialect: Dialect) -> datetime | None:
"""
- 将数据库读出的时间恢复为带时区UTC时刻
+ 将数据库读出的时间恢复为带时区UTC时刻。
:param value: 驱动返回的时间值
:param dialect: SQLAlchemy数据库方言
diff --git a/ruoyi-fastapi-backend/common/vo.py b/ruoyi-fastapi-backend/common/vo.py
index a31dedf68..c580b87bb 100644
--- a/ruoyi-fastapi-backend/common/vo.py
+++ b/ruoyi-fastapi-backend/common/vo.py
@@ -12,9 +12,7 @@
class CrudResponseModel(BaseModel):
- """
- 操作响应模型
- """
+ """操作响应模型。"""
is_success: bool = Field(description='操作是否成功')
message: str = Field(description='响应信息')
@@ -28,7 +26,7 @@ class CrudResponseModel(BaseModel):
@model_validator(mode='after')
def preserve_message_metadata(self) -> Self:
"""
- 通过现有消息字段保留词库域和复数消息元数据
+ 通过现有消息字段保留词库域和复数消息元数据。
:return: 保留消息元数据的操作响应模型
"""
@@ -45,9 +43,7 @@ def preserve_message_metadata(self) -> Self:
class ResponseBaseModel(BaseModel):
- """
- 响应模型
- """
+ """响应模型。"""
code: int = Field(default=HttpStatusConstant.SUCCESS, description='响应码')
msg: str = Field(default='操作成功', description='响应信息')
@@ -61,15 +57,17 @@ class ResponseBaseModel(BaseModel):
class DynamicResponseModel(ResponseBaseModel, Generic[T]):
- """
- 动态响应模型
- """
+ """动态响应模型。"""
model_config = ConfigDict(alias_generator=to_camel)
def __class_getitem__(cls, item: Any) -> Any | Self:
"""
- 当使用 DynamicResponseModel[Item] 语法时,动态创建一个包含所有字段的新模型
+ 当使用 DynamicResponseModel[Item] 语法时,动态创建一个包含所有字段的新模型。
+
+ :param item: 当前要处理的条目
+ :return: 绑定给定数据类型的响应模型
+ :raises TypeError: 泛型参数不是 Pydantic 模型
"""
# 检查是否已经为该类型创建了模型
if not hasattr(cls, '_cached_models'):
@@ -107,9 +105,7 @@ def __class_getitem__(cls, item: Any) -> Any | Self:
class PageModel(BaseModel, Generic[T]):
- """
- 分页模型
- """
+ """分页模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -121,14 +117,10 @@ class PageModel(BaseModel, Generic[T]):
class PageResponseModel(PageModel, ResponseBaseModel, Generic[T]):
- """
- 分页响应模型
- """
+ """分页响应模型。"""
class DataResponseModel(ResponseBaseModel, Generic[T]):
- """
- 数据响应模型
- """
+ """数据响应模型。"""
data: T = Field(description='响应数据')
diff --git a/ruoyi-fastapi-backend/config/database.py b/ruoyi-fastapi-backend/config/database.py
index 2023a74db..cca47e400 100644
--- a/ruoyi-fastapi-backend/config/database.py
+++ b/ruoyi-fastapi-backend/config/database.py
@@ -48,13 +48,11 @@
class _QuietSqlLogFilter(logging.Filter):
- """
- 按连接日志标记过滤内部SQL,保留警告和错误
- """
+ """按连接日志标记过滤内部SQL,保留警告和错误。"""
def filter(self, record: logging.LogRecord) -> bool:
"""
- 判断是否保留当前SQLAlchemy日志
+ 判断是否保留当前SQLAlchemy日志。
:param record: 待输出的日志记录
:return: 是否保留日志
@@ -71,7 +69,7 @@ def filter(self, record: logging.LogRecord) -> bool:
def quiet_sql_engine(engine: _DatabaseEngine) -> _DatabaseEngine:
"""
- 创建复用原连接池、只过滤自身常规SQL日志的引擎视图
+ 创建复用原连接池、只过滤自身常规SQL日志的引擎视图。
:param engine: 注册中心管理的同步或异步引擎
:return: 带有内部SQL日志标记的引擎视图,由原引擎统一管理连接池
@@ -87,7 +85,7 @@ def quiet_sql_engine(engine: _DatabaseEngine) -> _DatabaseEngine:
def _error_details(exc: BaseException) -> tuple[str, int | None]:
"""
- 提取不含连接凭据和SQL参数的安全错误摘要
+ 提取不含连接凭据和SQL参数的安全错误摘要。
:param exc: 原始异常或数据源异常
:return: 异常类型和数字错误码
@@ -101,7 +99,7 @@ def _error_details(exc: BaseException) -> tuple[str, int | None]:
def _error_log_suffix(error_type: str, error_code: int | None) -> str:
"""
- 构建数据源错误日志摘要
+ 构建数据源错误日志摘要。
:param error_type: 异常类型
:param error_code: 数字错误码
@@ -114,7 +112,13 @@ def _error_log_suffix(error_type: str, error_code: int | None) -> str:
@dataclass(frozen=True, slots=True)
class DatabaseDriverAdapter:
"""
- 数据库驱动适配器
+ 数据库驱动适配器。
+
+ :ivar db_type: 数据库类型
+ :ivar async_driver: 异步数据库连接使用的驱动
+ :ivar sync_driver: 同步数据库连接使用的驱动
+ :ivar async_connect_timeout_key: 异步驱动接受的连接超时选项
+ :ivar sync_connect_timeout_key: 同步驱动接受的连接超时选项
"""
db_type: str
@@ -125,7 +129,7 @@ class DatabaseDriverAdapter:
def build_url(self, config: DataSourceSettings, *, sync: bool) -> URL:
"""
- 根据数据源配置构建SQLAlchemy数据库连接URL
+ 根据数据源配置构建SQLAlchemy数据库连接URL。
:param config: 数据源配置
:param sync: 是否构建同步数据库连接URL
@@ -142,7 +146,7 @@ def build_url(self, config: DataSourceSettings, *, sync: bool) -> URL:
def build_connect_args(self, config: DataSourceSettings, *, sync: bool) -> dict[str, Any]:
"""
- 构建数据库驱动连接参数
+ 构建数据库驱动连接参数。
:param config: 数据源配置
:param sync: 是否构建同步数据库连接参数
@@ -183,7 +187,7 @@ def build_connect_args(self, config: DataSourceSettings, *, sync: bool) -> dict[
def _secret_value(value: SecretStr | str) -> str:
"""
- 获取密码配置的原始值
+ 获取密码配置的原始值。
:param value: 密码配置
:return: 密码原始值
@@ -193,7 +197,7 @@ def _secret_value(value: SecretStr | str) -> str:
def _database_source(config: DataBaseSettings | DataSourceSettings) -> DataSourceSettings:
"""
- 获取指定配置对应的数据源配置
+ 获取指定配置对应的数据源配置。
:param config: 数据库集合配置或单个数据源配置
:return: 单个数据源配置
@@ -203,10 +207,11 @@ def _database_source(config: DataBaseSettings | DataSourceSettings) -> DataSourc
def _driver_adapter(config: DataSourceSettings) -> DatabaseDriverAdapter:
"""
- 获取数据库驱动适配器
+ 获取数据库驱动适配器。
:param config: 数据源配置
:return: 数据库驱动适配器
+ :raises ValueError: 没有支持当前数据库类型的驱动适配器
"""
adapter = _DATABASE_DRIVER_ADAPTERS.get(config.db_type)
if adapter is None:
@@ -216,7 +221,7 @@ def _driver_adapter(config: DataSourceSettings) -> DatabaseDriverAdapter:
def _build_url(config: DataSourceSettings, *, sync: bool) -> URL:
"""
- 使用对应的数据库驱动适配器构建连接URL
+ 使用对应的数据库驱动适配器构建连接URL。
:param config: 数据源配置
:param sync: 是否构建同步数据库连接URL
@@ -227,7 +232,7 @@ def _build_url(config: DataSourceSettings, *, sync: bool) -> URL:
def build_async_sqlalchemy_database_url(config: DataBaseSettings | DataSourceSettings | None = None) -> URL:
"""
- 构建异步SQLAlchemy数据库连接URL
+ 构建异步SQLAlchemy数据库连接URL。
:param config: 数据库集合配置或单个数据源配置
:return: 异步SQLAlchemy数据库连接URL
@@ -237,7 +242,7 @@ def build_async_sqlalchemy_database_url(config: DataBaseSettings | DataSourceSet
def build_sync_sqlalchemy_database_url(config: DataBaseSettings | DataSourceSettings | None = None) -> URL:
"""
- 构建同步SQLAlchemy数据库连接URL
+ 构建同步SQLAlchemy数据库连接URL。
:param config: 数据库集合配置或单个数据源配置
:return: 同步SQLAlchemy数据库连接URL
@@ -247,7 +252,7 @@ def build_sync_sqlalchemy_database_url(config: DataBaseSettings | DataSourceSett
def _engine_options(config: DataSourceSettings, echo: bool | None = None) -> dict[str, Any]:
"""
- 构建数据库引擎连接池参数
+ 构建数据库引擎连接池参数。
:param config: 数据源配置
:param echo: 是否输出SQLAlchemy SQL日志
@@ -268,7 +273,7 @@ def create_async_db_engine(
echo: bool | None = None, config: DataBaseSettings | DataSourceSettings | None = None
) -> AsyncEngine:
"""
- 创建异步SQLAlchemy Engine
+ 创建异步SQLAlchemy Engine。
:param echo: 是否输出SQLAlchemy SQL日志
:param config: 数据库集合配置或单个数据源配置
@@ -287,7 +292,7 @@ def create_sync_db_engine(
echo: bool | None = None, config: DataBaseSettings | DataSourceSettings | None = None
) -> Engine:
"""
- 创建同步SQLAlchemy Engine
+ 创建同步SQLAlchemy Engine。
:param echo: 是否输出SQLAlchemy SQL日志
:param config: 数据库集合配置或单个数据源配置
@@ -304,7 +309,14 @@ def create_sync_db_engine(
class CurrentUserCacheSession(Session):
"""
- 登记当前用户资料和权限变更,在事务提交后使缓存失效
+ 登记当前用户资料和权限变更,在事务提交后使缓存失效。
+
+ :cvar _USER_TABLES: 变更后需要刷新特定用户缓存的数据表
+ :cvar _SHARED_TABLES: 变更后需要刷新共享权限缓存的数据表
+ :cvar _CHANGE_KEY: 会话中用于跟踪待失效数据的键
+ :cvar _REDIS_KEY: 会话中保存 Redis 客户端的键
+ :cvar _INVALIDATE_TIMEOUT_SECONDS: 缓存失效操作的超时时间(秒)
+ :cvar _CLOSE_TIMEOUT_SECONDS: 等待关闭的超时时间(秒)
"""
_USER_TABLES = frozenset({'sys_user', 'sys_user_role', 'sys_user_post'})
@@ -317,7 +329,7 @@ class CurrentUserCacheSession(Session):
@staticmethod
def _table_names(table: Any) -> set[str]:
"""
- 解析别名和多表更新目标中的原始表名
+ 解析别名和多表更新目标中的原始表名。
:param table: SQLAlchemy写入目标
:return: 原始表名集合
@@ -332,7 +344,7 @@ def _table_names(table: Any) -> set[str]:
@staticmethod
def _has_unscoped_write(statement: Any) -> bool:
"""
- 识别原生SQL和包装语句中无法精确定位用户的写入
+ 识别原生SQL和包装语句中无法精确定位用户的写入。
:param statement: SQLAlchemy执行语句
:return: 是否需要全局失效
@@ -354,10 +366,9 @@ def _has_unscoped_write(statement: Any) -> bool:
def _record_cache_change(self, user_ids: set[int] | None) -> None:
"""
- 按当前事务登记变更,None表示共享权限或无法确定用户范围
+ 按当前事务登记变更,None表示共享权限或无法确定用户范围。
:param user_ids: 需要失效的用户ID集合
- :return: None
"""
transaction = self.get_nested_transaction() or self.get_transaction()
if transaction is None:
@@ -371,7 +382,7 @@ def _record_cache_change(self, user_ids: set[int] | None) -> None:
@classmethod
def _where_user_ids(cls, clause: Any, table_name: str, parameters: Any) -> set[int] | None:
"""
- 仅识别明确的用户ID等值条件,复杂条件保守失效全部快照
+ 仅识别明确的用户ID等值条件,复杂条件保守失效全部快照。
:param clause: 更新或删除语句的条件
:param table_name: 目标表名
@@ -410,10 +421,9 @@ def _where_user_ids(cls, clause: Any, table_name: str, parameters: Any) -> set[i
async def _invalidate_cache(self, user_ids: set[int] | None) -> None:
"""
- 提交完成后轮换缓存版本,Redis异常由短时硬过期兜底
+ 提交完成后轮换缓存版本,Redis异常由短时硬过期兜底。
:param user_ids: 需要失效的用户ID集合,None表示全部用户
- :return: None
"""
from config.get_redis import RedisUtil # noqa: PLC0415
from utils.cache_util import CurrentUserCacheUtil # noqa: PLC0415
@@ -446,7 +456,7 @@ async def _invalidate_cache(self, user_ids: set[int] | None) -> None:
@event.listens_for(CurrentUserCacheSession, 'do_orm_execute', retval=True)
def _track_current_user_statement(state: ORMExecuteState) -> Any:
"""
- 登记成功执行的用户及权限写入,覆盖ORM批量操作和Core语句
+ 登记成功执行的用户及权限写入,覆盖ORM批量操作和Core语句。
:param state: 当前SQL执行状态
:return: 原语句执行结果
@@ -517,12 +527,11 @@ def _track_current_user_statement(state: ORMExecuteState) -> Any:
@event.listens_for(CurrentUserCacheSession, 'before_flush')
def _track_current_user_flush(session: CurrentUserCacheSession, _context: Any, _instances: Any) -> None:
"""
- 登记ORM对象变更,覆盖直接修改用户和权限模型的入口
+ 登记ORM对象变更,覆盖直接修改用户和权限模型的入口。
:param session: 当前数据库会话
:param _context: 刷新上下文
:param _instances: 刷新对象
- :return: None
"""
if not AppConfig.app_current_user_cache_enabled:
return
@@ -545,10 +554,9 @@ def _track_current_user_flush(session: CurrentUserCacheSession, _context: Any, _
@event.listens_for(CurrentUserCacheSession, 'after_commit')
def _invalidate_current_user_cache(session: CurrentUserCacheSession) -> None:
"""
- 保存点提交只合并记录,最外层提交后才执行缓存失效
+ 保存点提交只合并记录,最外层提交后才执行缓存失效。
:param session: 当前数据库会话
- :return: None
"""
try:
transaction = session.get_nested_transaction() or session.get_transaction()
@@ -575,11 +583,10 @@ def _invalidate_current_user_cache(session: CurrentUserCacheSession) -> None:
@event.listens_for(CurrentUserCacheSession, 'after_transaction_end')
def _discard_current_user_changes(session: CurrentUserCacheSession, transaction: SessionTransaction) -> None:
"""
- 清理已结束事务的记录,回滚和关闭会话不影响Redis缓存
+ 清理已结束事务的记录,回滚和关闭会话不影响Redis缓存。
:param session: 当前数据库会话
:param transaction: 已结束的事务
- :return: None
"""
changes = session.info.get(session._CHANGE_KEY)
if changes is not None:
@@ -590,7 +597,7 @@ def _discard_current_user_changes(session: CurrentUserCacheSession, transaction:
def create_async_session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
"""
- 创建异步Session工厂
+ 创建异步Session工厂。
:param engine: 异步SQLAlchemy Engine
:return: 异步Session工厂
@@ -606,7 +613,7 @@ def create_async_session_factory(engine: AsyncEngine) -> async_sessionmaker[Asyn
def create_sync_session_factory(engine: Engine) -> sessionmaker:
"""
- 创建同步Session工厂
+ 创建同步Session工厂。
:param engine: 同步SQLAlchemy Engine
:return: 同步Session工厂
@@ -617,7 +624,18 @@ def create_sync_session_factory(engine: Engine) -> sessionmaker:
@dataclass(slots=True)
class DataSourceRuntime:
"""
- 数据源运行时状态
+ 数据源运行时状态。
+
+ :ivar name: 数据源名称
+ :ivar config: 单个数据源配置
+ :ivar async_engine: 用于异步数据库操作的 SQLAlchemy 引擎
+ :ivar async_session_factory: 创建异步数据库会话的工厂
+ :ivar sync_engine: 用于同步数据库操作的 SQLAlchemy 引擎
+ :ivar available: 数据源当前是否可用
+ :ivar last_health_check_at: 上一次健康检查的时间
+ :ivar next_retry_at: 下次允许重试连接的时间
+ :ivar session_timezone: 为数据库会话设置的时区
+ :ivar health_lock: 避免并发执行数据源健康检查的锁
"""
name: str
@@ -634,10 +652,22 @@ class DataSourceRuntime:
class _DataSourceRegistry:
"""
- 数据源注册中心
+ 数据源注册中心。
+
+ :ivar settings: 当前操作采用的配置
+ :ivar _runtimes: 按名称索引的数据源运行时
+ :ivar _initialized: 是否已完成初始化
+ :ivar _log_enabled: 是否开启数据源日志
+ :ivar _configs: 按名称保存的数据源配置
+ :ivar _cache_redis: 与数据源共享的 Redis 客户端
"""
def __init__(self, settings: DataBaseSettings | None = None) -> None:
+ """
+ 根据数据源配置初始化运行时连接注册表。
+
+ :param settings: 当前操作采用的配置
+ """
self.settings = settings or DataBaseConfig
self._runtimes: dict[str, DataSourceRuntime] = {}
self._initialized = False
@@ -647,19 +677,19 @@ def __init__(self, settings: DataBaseSettings | None = None) -> None:
def set_cache_redis(self, redis: Any | None) -> None:
"""
- 绑定应用生命周期管理的Redis,数据库会话只借用连接池
+ 绑定应用生命周期管理的Redis,数据库会话只借用连接池。
:param redis: 应用Redis客户端,None表示解除绑定
- :return: None
"""
self._cache_redis = redis
def _resolve_name(self, name: str | None = None) -> str:
"""
- 解析并校验数据源名称
+ 解析并校验数据源名称。
:param name: 数据源名称
:return: 已配置的数据源名称
+ :raises DataSourceNotFoundException: 指定的数据源没有注册
"""
source_name = name or self.settings.db_default_source
if source_name not in self._configs:
@@ -668,7 +698,7 @@ def _resolve_name(self, name: str | None = None) -> str:
def _runtime(self, name: str | None = None) -> DataSourceRuntime:
"""
- 获取或创建数据源运行时状态
+ 获取或创建数据源运行时状态。
:param name: 数据源名称
:return: 数据源运行时状态
@@ -683,10 +713,9 @@ def _runtime(self, name: str | None = None) -> DataSourceRuntime:
@staticmethod
def _mark_unavailable(runtime: DataSourceRuntime) -> None:
"""
- 标记数据源不可用并设置下次重试时间
+ 标记数据源不可用并设置下次重试时间。
:param runtime: 数据源运行时状态
- :return: None
"""
now = TimezoneUtil.utc_now()
runtime.available = False
@@ -700,17 +729,24 @@ def _data_source_error(
runtime: DataSourceRuntime,
exc: BaseException,
) -> DataSourceException:
- """将底层异常转换为不泄露连接信息的数据源异常。"""
+ """
+ 将底层异常转换为不泄露连接信息的数据源异常。
+
+ :param exception_type: 异常的类型
+ :param runtime: 数据源运行时状态
+ :param exc: 捕获到的异常实例
+ :return: 带安全诊断信息的数据源异常实例
+ """
error_type, error_code = _error_details(exc)
return exception_type(runtime.name, error_type=error_type, error_code=error_code)
@classmethod
def _ensure_async_resources(cls, runtime: DataSourceRuntime) -> None:
"""
- 确保数据源异步引擎和Session工厂已创建
+ 确保数据源异步引擎和Session工厂已创建。
:param runtime: 数据源运行时状态
- :return: None
+ :raises DataSourceInitializationException: 异步引擎或会话工厂初始化失败
"""
if runtime.async_engine is not None and runtime.async_session_factory is not None:
return
@@ -725,10 +761,10 @@ def _ensure_async_resources(cls, runtime: DataSourceRuntime) -> None:
async def initialize(self, log_enabled: bool = True) -> None:
"""
- 初始化并检查所有数据源的连接状态
+ 初始化并检查所有数据源的连接状态。
:param log_enabled: 是否输出数据源启动日志
- :return: None
+ :raises DataSourceInitializationException: 必需数据源初始化失败
"""
self._log_enabled = log_enabled
if self._initialized:
@@ -782,7 +818,7 @@ async def initialize(self, log_enabled: bool = True) -> None:
def get_async_engine(self, name: str | None = None) -> AsyncEngine:
"""
- 获取数据源异步引擎
+ 获取数据源异步引擎。
:param name: 数据源名称
:return: 异步SQLAlchemy Engine
@@ -794,10 +830,11 @@ def get_async_engine(self, name: str | None = None) -> AsyncEngine:
def get_sync_engine(self, name: str | None = None) -> Engine:
"""
- 获取数据源同步引擎
+ 获取数据源同步引擎。
:param name: 数据源名称
:return: 同步SQLAlchemy Engine
+ :raises DataSourceInitializationException: 同步引擎初始化失败
"""
runtime = self._runtime(name)
if runtime.sync_engine is None:
@@ -809,10 +846,9 @@ def get_sync_engine(self, name: str | None = None) -> Engine:
async def _check_health(self, name: str) -> None:
"""
- 检查指定数据源的连接状态
+ 检查指定数据源的连接状态。
:param name: 数据源名称
- :return: None
"""
runtime = self._runtime(name)
async with runtime.health_lock:
@@ -820,10 +856,10 @@ async def _check_health(self, name: str) -> None:
async def _check_health_locked(self, runtime: DataSourceRuntime) -> None:
"""
- 在持有健康检查锁时检查数据源连接状态
+ 在持有健康检查锁时检查数据源连接状态。
:param runtime: 数据源运行时状态
- :return: None
+ :raises DataSourceUnavailableException: 数据源未通过连接健康检查
"""
try:
self._ensure_async_resources(runtime)
@@ -844,10 +880,10 @@ async def _check_health_locked(self, runtime: DataSourceRuntime) -> None:
async def _ensure_available(self, runtime: DataSourceRuntime) -> None:
"""
- 确保指定数据源当前可用
+ 确保指定数据源当前可用。
:param runtime: 数据源运行时状态
- :return: None
+ :raises DataSourceUnavailableException: 数据源尚处在故障冷却期
"""
async with runtime.health_lock:
if runtime.available:
@@ -864,10 +900,11 @@ async def _ensure_available(self, runtime: DataSourceRuntime) -> None:
@asynccontextmanager
async def connection(self, name: str | None = None) -> AsyncGenerator[AsyncConnection, None]:
"""
- 创建指定数据源的异步数据库连接事务
+ 创建指定数据源的异步数据库连接事务。
:param name: 数据源名称
- :return: 异步数据库连接
+ :yield: 异步数据库连接
+ :raises DBAPIError: 数据库操作失败且连接未被标记失效
"""
runtime = self._runtime(name)
await self._ensure_available(runtime)
@@ -884,11 +921,12 @@ async def connection(self, name: str | None = None) -> AsyncGenerator[AsyncConne
@asynccontextmanager
async def session(self, name: str | None = None, *, log_sql: bool = True) -> AsyncGenerator[AsyncSession, None]:
"""
- 创建指定数据源的异步数据库会话
+ 创建指定数据源的异步数据库会话。
:param name: 数据源名称
:param log_sql: 是否保留数据源原有的SQL日志设置,False时只过滤此会话的常规SQL日志
- :return: 异步数据库会话
+ :yield: 异步数据库会话
+ :raises DBAPIError: 会话中的数据库操作失败且连接未被标记失效
"""
runtime = self._runtime(name)
await self._ensure_available(runtime)
@@ -911,9 +949,9 @@ async def session(self, name: str | None = None, *, log_sql: bool = True) -> Asy
async def dispose_all(self) -> None:
"""
- 释放所有数据源的同步和异步引擎
+ 释放所有数据源的同步和异步引擎。
- :return: None
+ :raises BaseException: 释放引擎时有清理操作失败
"""
runtimes = tuple(self._runtimes.values())
self._cache_redis = None
@@ -953,13 +991,13 @@ async def dispose_all(self) -> None:
class Base(AsyncAttrs, DeclarativeBase):
- pass
+ """默认数据源的 SQLAlchemy 声明式模型基类。"""
@cache
def get_data_source_base(source_name: str) -> type[DeclarativeBase]:
"""
- 获取指定数据源独立且可复用的ORM元数据基类
+ 获取指定数据源独立且可复用的ORM元数据基类。
:param source_name: 数据源名称
:return: ORM元数据基类
@@ -967,7 +1005,7 @@ def get_data_source_base(source_name: str) -> type[DeclarativeBase]:
DataBaseConfig.get_source(source_name)
class NamedDataSourceBase(AsyncAttrs, DeclarativeBase):
- pass
+ """绑定指定数据源元数据的声明式模型基类。"""
NamedDataSourceBase.__name__ = f'{source_name.title().replace("_", "").replace("-", "")}DataSourceBase'
return NamedDataSourceBase
diff --git a/ruoyi-fastapi-backend/config/env.py b/ruoyi-fastapi-backend/config/env.py
index 756805692..ba9e5173f 100644
--- a/ruoyi-fastapi-backend/config/env.py
+++ b/ruoyi-fastapi-backend/config/env.py
@@ -17,30 +17,28 @@
class AppSettings(BaseSettings):
- """
- 应用配置
- """
-
- app_env: str = 'dev'
- app_name: str = 'RuoYi-FastAPI'
- app_root_path: str = '/dev-api'
- app_host: str = '0.0.0.0'
- app_port: int = 9099
- app_version: str = '2.0.0'
- app_release_id: str = ''
- app_reload: bool = True
- app_workers: int = 1
- app_ip_location_query: bool = True
- app_same_time_login: bool = True
- app_current_user_cache_enabled: bool = True
- app_current_user_cache_ttl_seconds: int = Field(default=5, ge=1, le=60)
- app_demo_mode: bool = False
- app_disable_swagger: bool = False
- app_disable_redoc: bool = False
- app_trusted_proxy_ips: str = '127.0.0.1,::1'
- app_trusted_proxy_hops: int = 1
- app_default_enabled_plugins: str = 'ai'
- app_timezone: str = 'Asia/Shanghai'
+ """应用配置。"""
+
+ app_env: str = Field(default='dev', description='应用运行环境')
+ app_name: str = Field(default='RuoYi-FastAPI', description='应用名称')
+ app_root_path: str = Field(default='/dev-api', description='部署在反向代理后的应用路径前缀')
+ app_host: str = Field(default='0.0.0.0', description='应用监听地址')
+ app_port: int = Field(default=9099, description='应用监听端口')
+ app_version: str = Field(default='2.0.0', description='应用版本号')
+ app_release_id: str = Field(default='', description='当前部署的发布标识')
+ app_reload: bool = Field(default=True, description='是否在源码变更后自动重启')
+ app_workers: int = Field(default=1, description='应用工作进程数')
+ app_ip_location_query: bool = Field(default=True, description='是否查询客户端 IP 的地理位置')
+ app_same_time_login: bool = Field(default=True, description='是否允许同一账号同时登录')
+ app_current_user_cache_enabled: bool = Field(default=True, description='是否缓存当前用户的资料和权限')
+ app_current_user_cache_ttl_seconds: int = Field(default=5, ge=1, le=60, description='当前用户缓存的有效期(秒)')
+ app_demo_mode: bool = Field(default=False, description='是否启用演示模式')
+ app_disable_swagger: bool = Field(default=False, description='是否关闭 Swagger UI')
+ app_disable_redoc: bool = Field(default=False, description='是否关闭 ReDoc 接口文档')
+ app_trusted_proxy_ips: str = Field(default='127.0.0.1,::1', description='可转发客户端地址的受信任代理 IP')
+ app_trusted_proxy_hops: int = Field(default=1, description='解析客户端地址时信任的代理跳数')
+ app_default_enabled_plugins: str = Field(default='ai', description='默认启用的插件标识')
+ app_timezone: str = Field(default='Asia/Shanghai', description='业务日期和时间使用的 IANA 时区')
@field_validator('app_timezone')
@classmethod
@@ -50,6 +48,7 @@ def validate_app_timezone(cls, value: str) -> str:
:param value: IANA时区名称
:return: 去除首尾空格后的IANA时区名称
+ :raises ValueError: 应用时区不是有效的 IANA 名称
"""
try:
return TimezoneUtil.validate_timezone_name(value)
@@ -58,23 +57,21 @@ def validate_app_timezone(cls, value: str) -> str:
class I18nSettings(BaseSettings):
- """
- 国际化配置
- """
+ """国际化配置。"""
SOURCE_LOCALE: ClassVar[str] = 'zh-CN'
- i18n_default_locale: str = Field(default=SOURCE_LOCALE, min_length=1, max_length=63)
+ i18n_default_locale: str = Field(
+ default=SOURCE_LOCALE, min_length=1, max_length=63, description='未指定语言时使用的语言标记'
+ )
class JwtSettings(BaseSettings):
- """
- Jwt配置
- """
+ """Jwt配置。"""
- jwt_secret_key: str = Field(default_factory=lambda: secrets.token_hex(32))
- jwt_algorithm: str = 'HS256'
- jwt_expire_minutes: int = 1440
- jwt_redis_expire_minutes: int = Field(default=30, gt=0)
+ jwt_secret_key: str = Field(default_factory=lambda: secrets.token_hex(32), description='签发和校验 JWT 的密钥')
+ jwt_algorithm: str = Field(default='HS256', description='JWT 签名算法')
+ jwt_expire_minutes: int = Field(default=1440, description='JWT 的有效期(分钟)')
+ jwt_redis_expire_minutes: int = Field(default=30, gt=0, description='Redis 登录会话的有效期(分钟)')
@field_validator('jwt_secret_key', mode='before')
@classmethod
@@ -91,32 +88,30 @@ def generate_empty_secret_key(cls, value: object) -> object:
class DataSourceSettings(BaseModel):
- """
- 单个数据源配置
- """
+ """单个数据源配置。"""
model_config = ConfigDict(hide_input_in_errors=True)
- db_type: Literal['mysql', 'postgresql']
- db_host: str = Field(min_length=1)
- db_port: int = Field(ge=1, le=65535)
- db_username: str = Field(min_length=1)
- db_password: SecretStr
- db_database: str = Field(min_length=1)
-
- db_echo: bool = True
- db_connect_timeout: int = Field(default=10, gt=0)
- db_max_overflow: int = Field(default=10, ge=0)
- db_pool_size: int = Field(default=20, ge=1)
- db_pool_recycle: int = Field(default=3600, ge=-1)
- db_pool_timeout: int = Field(default=30, gt=0)
- db_required: bool = True
-
- @computed_field
+ db_type: Literal['mysql', 'postgresql'] = Field(description='数据库类型')
+ db_host: str = Field(min_length=1, description='数据库服务器地址')
+ db_port: int = Field(ge=1, le=65535, description='数据库监听端口')
+ db_username: str = Field(min_length=1, description='数据库连接用户名')
+ db_password: SecretStr = Field(description='数据库连接密码')
+ db_database: str = Field(min_length=1, description='数据库名称')
+
+ db_echo: bool = Field(default=True, description='是否输出 SQLAlchemy 执行的 SQL')
+ db_connect_timeout: int = Field(default=10, gt=0, description='建立数据库连接的超时时间(秒)')
+ db_max_overflow: int = Field(default=10, ge=0, description='连接池可临时增加的最大连接数')
+ db_pool_size: int = Field(default=20, ge=1, description='连接池保留的连接数')
+ db_pool_recycle: int = Field(default=3600, ge=-1, description='回收数据库连接的时限(秒),负一表示禁用')
+ db_pool_timeout: int = Field(default=30, gt=0, description='等待连接池分配连接的超时时间(秒)')
+ db_required: bool = Field(default=True, description='应用启动时是否要求该数据源可用')
+
+ @computed_field(description='SQLGlot 解析该数据源 SQL 时使用的方言')
@property
def sqlglot_parse_dialect(self) -> str:
"""
- 获取SQLGlot解析方言
+ 获取SQLGlot解析方言。
:return: SQLGlot解析方言
"""
@@ -129,23 +124,24 @@ def sqlglot_parse_dialect(self) -> str:
class DataBaseSettings(BaseSettings):
- """
- 数据库集合配置
- """
+ """数据库集合配置。"""
model_config = SettingsConfigDict(hide_input_in_errors=True)
- db_default_source: str = 'primary'
- db_sources: Annotated[dict[str, DataSourceSettings], NoDecode] = Field(default_factory=dict)
+ db_default_source: str = Field(default='primary', description='默认数据源名称')
+ db_sources: Annotated[dict[str, DataSourceSettings], NoDecode] = Field(
+ default_factory=dict, description='按名称索引的数据源配置'
+ )
@field_validator('db_sources', mode='before')
@classmethod
def parse_sources_json(cls, value: object) -> object:
"""
- 解析显式传入的数据源JSON字符串
+ 解析显式传入的数据源JSON字符串。
:param value: 数据源配置原始值
:return: 解析后的数据源配置
+ :raises ValueError: DB_SOURCES JSON 格式错误
"""
if not isinstance(value, str):
return value
@@ -157,9 +153,10 @@ def parse_sources_json(cls, value: object) -> object:
@model_validator(mode='after')
def validate_sources(self) -> 'DataBaseSettings':
"""
- 校验数据源集合和默认数据源配置
+ 校验数据源集合和默认数据源配置。
:return: 数据库集合配置
+ :raises ValueError: DB_SOURCES 不能为空
"""
if not self.db_sources:
raise ValueError('DB_SOURCES 不能为空')
@@ -172,10 +169,11 @@ def validate_sources(self) -> 'DataBaseSettings':
def get_source(self, name: str | None = None) -> DataSourceSettings:
"""
- 获取指定数据源配置
+ 获取指定数据源配置。
:param name: 数据源名称
:return: 数据源配置
+ :raises DataSourceNotFoundException: 指定的数据源没有配置
"""
source_name = name or self.db_default_source
try:
@@ -186,7 +184,7 @@ def get_source(self, name: str | None = None) -> DataSourceSettings:
@property
def default_source(self) -> DataSourceSettings:
"""
- 获取默认数据源配置
+ 获取默认数据源配置。
:return: 默认数据源配置
"""
@@ -194,134 +192,159 @@ def default_source(self) -> DataSourceSettings:
class RedisSettings(BaseSettings):
- """
- Redis配置
- """
+ """Redis配置。"""
- redis_host: str = '127.0.0.1'
- redis_port: int = 6379
- redis_username: str = ''
- redis_password: str = ''
- redis_database: int = 2
+ redis_host: str = Field(default='127.0.0.1', description='Redis 服务器地址')
+ redis_port: int = Field(default=6379, description='Redis 监听端口')
+ redis_username: str = Field(default='', description='Redis 认证用户名')
+ redis_password: str = Field(default='', description='Redis 认证密码')
+ redis_database: int = Field(default=2, description='Redis 数据库编号')
class LogSettings(BaseSettings):
- """
- 日志与队列配置
- """
-
- log_mask_enabled: bool = True
- log_mask_placeholder: str = '******'
- log_mask_fields: str = (
- 'password,old_password,new_password,confirm_password,api_key,token,access_token,refresh_token,'
- 'authorization,client_secret,secret,secret_key,private_key,private_key_pem,credential,credentials,'
- 'sms_code,captcha_code,system_prompt'
+ """日志与队列配置。"""
+
+ log_mask_enabled: bool = Field(default=True, description='是否对日志中的敏感值脱敏')
+ log_mask_placeholder: str = Field(default='******', description='替换敏感日志值的占位符')
+ log_mask_fields: str = Field(
+ default=(
+ 'password,old_password,new_password,confirm_password,api_key,token,access_token,refresh_token,'
+ 'authorization,client_secret,secret,secret_key,private_key,private_key_pem,credential,credentials,'
+ 'sms_code,captcha_code,system_prompt'
+ ),
+ description='需要完全遮盖的日志字段',
)
- log_partial_mask_fields: str = 'phonenumber,phone,mobile,email'
- log_config_secret_patterns: str = 'password,token,secret,key,private,credential,access,jwt,captcha,sms'
- log_stream_key: str = 'log:stream'
- log_stream_group: str = 'log_aggregator'
- log_stream_consumer_prefix: str = 'worker'
- log_stream_batch_size: int = 100
- log_stream_block_ms: int = 2000
- log_stream_maxlen: int = 100000
- log_stream_claim_idle_ms: int = 60000
- log_stream_claim_interval_ms: int = 5000
- log_stream_claim_batch_size: int = 100
- log_stream_dedup_ttl: int = 3600
- log_stream_dedup_prefix: str = 'log:dedup'
-
- loguru_json: bool = False
- loguru_level: str = 'INFO'
- loguru_stdout: bool = True
- log_file_enabled: bool = True
- log_file_base_dir: str = 'logs'
- loguru_rotation: str = '50MB'
- loguru_retention: str = '30 days'
- loguru_compression: str = 'zip'
- log_instance_id: str = 'prod'
- log_service_name: str = 'ruoyi-fastapi-backend'
- log_worker_id: str = 'auto'
+ log_partial_mask_fields: str = Field(
+ default='phonenumber,phone,mobile,email', description='仅遮盖部分内容的日志字段'
+ )
+ log_config_secret_patterns: str = Field(
+ default='password,token,secret,key,private,credential,access,jwt,captcha,sms',
+ description='用来识别敏感配置键的名称模式',
+ )
+ log_stream_key: str = Field(default='log:stream', description='存放待处理日志的 Redis Stream 键')
+ log_stream_group: str = Field(default='log_aggregator', description='消费日志的 Redis 消费组名称')
+ log_stream_consumer_prefix: str = Field(default='worker', description='日志消费者名称的前缀')
+ log_stream_batch_size: int = Field(default=100, description='每批读取的最大日志条数')
+ log_stream_block_ms: int = Field(default=2000, description='等待新日志的阻塞时间(毫秒)')
+ log_stream_maxlen: int = Field(default=100000, description='日志流保留的最大条目数')
+ log_stream_claim_idle_ms: int = Field(default=60000, description='待确认日志可被其他消费者认领前的空闲时长(毫秒)')
+ log_stream_claim_interval_ms: int = Field(default=5000, description='两次认领未确认日志的间隔(毫秒)')
+ log_stream_claim_batch_size: int = Field(default=100, description='每次认领未确认日志的最大条数')
+ log_stream_dedup_ttl: int = Field(default=3600, description='日志去重标记的有效期(秒)')
+ log_stream_dedup_prefix: str = Field(default='log:dedup', description='Redis 日志去重键的前缀')
+
+ loguru_json: bool = Field(default=False, description='是否以 JSON 输出日志')
+ loguru_level: str = Field(default='INFO', description='输出日志的最低级别')
+ loguru_stdout: bool = Field(default=True, description='是否将日志写入标准输出')
+ log_file_enabled: bool = Field(default=True, description='是否写入日志文件')
+ log_file_base_dir: str = Field(default='logs', description='日志文件的根目录')
+ loguru_rotation: str = Field(default='50MB', description='日志文件轮转条件')
+ loguru_retention: str = Field(default='30 days', description='已轮转日志的保留期限')
+ loguru_compression: str = Field(default='zip', description='归档日志文件的压缩格式')
+ log_instance_id: str = Field(default='prod', description='写入日志的应用实例标识')
+ log_service_name: str = Field(default='ruoyi-fastapi-backend', description='写入日志的服务名称')
+ log_worker_id: str = Field(default='auto', description='写入日志的工作进程标识')
class TransportCryptoSettings(BaseSettings):
- """
- 传输层加解密配置
- """
+ """传输层加解密配置。"""
- transport_crypto_enabled: bool = True
- transport_crypto_mode: Literal['off', 'optional', 'required'] = 'optional'
- transport_crypto_algorithm: str = 'RSA_OAEP_AES_256_GCM'
- transport_crypto_kid: str = 'default'
- transport_crypto_public_key: str = ''
- transport_crypto_private_key: str = ''
- transport_crypto_legacy_key_pairs: str = '[]'
- transport_crypto_rsa_key_size: int = 2048
- transport_crypto_public_key_ttl_seconds: int = 3600
- transport_crypto_frontend_config_ttl_seconds: int = 300
- transport_crypto_max_get_url_length: int = 4096
- transport_crypto_clock_skew_seconds: int = 120
- transport_crypto_replay_ttl_seconds: int = 300
- transport_crypto_enabled_paths: str = ''
- transport_crypto_required_paths: str = ''
- transport_crypto_exclude_paths: str = (
- '/openapi.json,/docs,/docs/oauth2-redirect,/redoc,'
- '/transport/crypto/frontend-config,/transport/crypto/public-key,/common/download,/common/download/resource,'
- '/common/files,/system/file/download,'
- '/.well-known/openid-configuration,/.well-known/oauth-authorization-server,'
- '/oauth2/authorize,/oauth2/token,/oauth2/userinfo,/oauth2/jwks,'
- '/oauth2/revoke,/oauth2/introspect,/oauth2/logout'
+ transport_crypto_enabled: bool = Field(default=True, description='是否启用请求和响应的传输加密')
+ transport_crypto_mode: Literal['off', 'optional', 'required'] = Field(
+ default='optional', description='接口传输加密模式'
+ )
+ transport_crypto_algorithm: str = Field(default='RSA_OAEP_AES_256_GCM', description='传输加密协议使用的算法')
+ transport_crypto_kid: str = Field(default='default', description='当前传输密钥的标识')
+ transport_crypto_public_key: str = Field(default='', description='用于传输加密的公钥')
+ transport_crypto_private_key: str = Field(default='', description='用于传输解密的私钥')
+ transport_crypto_legacy_key_pairs: str = Field(default='[]', description='轮换后仍可用于解密的旧密钥对')
+ transport_crypto_rsa_key_size: int = Field(default=2048, description='传输加密 RSA 密钥的位数')
+ transport_crypto_public_key_ttl_seconds: int = Field(default=3600, description='传输公钥的缓存时长(秒)')
+ transport_crypto_frontend_config_ttl_seconds: int = Field(
+ default=300, description='前端缓存传输加密配置的时长(秒)'
+ )
+ transport_crypto_max_get_url_length: int = Field(default=4096, description='加密 GET 请求允许的最大 URL 长度')
+ transport_crypto_clock_skew_seconds: int = Field(
+ default=120, description='校验加密请求时间戳时允许的时钟偏差(秒)'
+ )
+ transport_crypto_replay_ttl_seconds: int = Field(default=300, description='加密请求防重放标记的有效期(秒)')
+ transport_crypto_enabled_paths: str = Field(default='', description='启用传输加密的接口路径')
+ transport_crypto_required_paths: str = Field(default='', description='必须使用传输加密的接口路径')
+ transport_crypto_exclude_paths: str = Field(
+ default=(
+ '/openapi.json,/docs,/docs/oauth2-redirect,/redoc,'
+ '/transport/crypto/frontend-config,/transport/crypto/public-key,/common/download,/common/download/resource,'
+ '/common/files,/system/file/download,'
+ '/.well-known/openid-configuration,/.well-known/oauth-authorization-server,'
+ '/oauth2/authorize,/oauth2/token,/oauth2/userinfo,/oauth2/jwks,'
+ '/oauth2/revoke,/oauth2/introspect,/oauth2/logout'
+ ),
+ description='跳过传输加密的接口路径',
)
class OidcSettings(BaseSettings):
"""
- OIDC/OAuth2 认证中心配置
+ OIDC/OAuth2 认证中心配置。
OIDC 默认关闭,关闭时只保留可安全解析的默认值,不要求发行者、签名密钥
或不透明令牌 Pepper,从而保证现有 Legacy JWT 启动路径完全不变。
"""
- oidc_enabled: bool = False
- oidc_issuer: str = 'https://auth.example.com'
- oidc_public_base_url: str = 'https://auth.example.com'
-
- oidc_require_pkce: bool = True
- oidc_pkce_methods: str = 'S256'
- oidc_allowed_clock_skew_seconds: int = Field(default=60, ge=0)
- oidc_authorization_code_ttl_seconds: int = Field(default=90, gt=0)
- oidc_interaction_ttl_seconds: int = Field(default=300, gt=0)
- oidc_id_token_ttl_seconds: int = Field(default=300, gt=0)
- oidc_access_token_ttl_seconds: int = Field(default=600, gt=0)
- oidc_max_access_token_ttl_seconds: int = Field(default=1800, gt=0)
- oidc_refresh_token_idle_seconds: int = Field(default=604800, gt=0)
- oidc_refresh_token_absolute_seconds: int = Field(default=2592000, gt=0)
-
- oidc_sso_idle_seconds: int = Field(default=1800, gt=0)
- oidc_sso_absolute_seconds: int = Field(default=28800, gt=0)
- oidc_sso_remember_absolute_seconds: int = Field(default=604800, gt=0)
- oidc_sso_cookie_name: str = '__Host-ruoyi-sso'
- oidc_sso_cookie_secure: bool = True
- oidc_sso_cookie_samesite: Literal['lax', 'strict', 'none'] = 'lax'
- oidc_sso_cookie_domain: str | None = None
-
- oidc_signing_algorithm: Literal['RS256'] = 'RS256'
- oidc_signing_key_source: Literal['file', 'kms', 'hsm'] = 'file'
- oidc_signing_private_key_path: str = ''
- oidc_signing_key_encryption_key: str = ''
- oidc_active_kid: str = ''
- oidc_key_rotation_overlap_seconds: int = Field(default=86400, gt=0)
-
- oidc_token_hash_pepper: str = ''
-
- oidc_cors_allowed_origins: str = ''
- oidc_interaction_login_url: str = 'https://auth.example.com/auth-center/login'
- oidc_interaction_consent_url: str = 'https://auth.example.com/auth-center/consent'
- oidc_interaction_error_url: str = 'https://auth.example.com/auth-center/error'
-
- oidc_audit_retention_days: int = Field(default=180, gt=0)
- oidc_backchannel_logout_timeout_seconds: int = Field(default=5, gt=0)
- oidc_legacy_auth_isolation_enabled: bool = True
+ oidc_enabled: bool = Field(default=False, description='是否启用 OIDC 身份提供方')
+ oidc_issuer: str = Field(default='https://auth.example.com', description='OIDC 令牌的签发者标识')
+ oidc_public_base_url: str = Field(default='https://auth.example.com', description='对外发布 OIDC 端点的基础地址')
+
+ oidc_require_pkce: bool = Field(default=True, description='是否要求授权码流程使用 PKCE')
+ oidc_pkce_methods: str = Field(default='S256', description='允许的 PKCE 挑战方法')
+ oidc_allowed_clock_skew_seconds: int = Field(default=60, ge=0, description='OIDC 令牌校验允许的时钟偏差(秒)')
+ oidc_authorization_code_ttl_seconds: int = Field(default=90, gt=0, description='授权码有效期(秒)')
+ oidc_interaction_ttl_seconds: int = Field(default=300, gt=0, description='登录和授权交互的有效期(秒)')
+ oidc_id_token_ttl_seconds: int = Field(default=300, gt=0, description='身份令牌有效期(秒)')
+ oidc_access_token_ttl_seconds: int = Field(default=600, gt=0, description='访问令牌的默认有效期(秒)')
+ oidc_max_access_token_ttl_seconds: int = Field(default=1800, gt=0, description='访问令牌允许的最长有效期(秒)')
+ oidc_refresh_token_idle_seconds: int = Field(default=604800, gt=0, description='刷新令牌允许空闲的最长时间(秒)')
+ oidc_refresh_token_absolute_seconds: int = Field(
+ default=2592000, gt=0, description='刷新令牌从签发起的最长有效期(秒)'
+ )
+
+ oidc_sso_idle_seconds: int = Field(default=1800, gt=0, description='单点登录会话允许空闲的最长时间(秒)')
+ oidc_sso_absolute_seconds: int = Field(default=28800, gt=0, description='普通单点登录会话的最长有效期(秒)')
+ oidc_sso_remember_absolute_seconds: int = Field(
+ default=604800, gt=0, description='选择记住登录后会话的最长有效期(秒)'
+ )
+ oidc_sso_cookie_name: str = Field(default='__Host-ruoyi-sso', description='单点登录 Cookie 名称')
+ oidc_sso_cookie_secure: bool = Field(default=True, description='是否仅通过 HTTPS 发送单点登录 Cookie')
+ oidc_sso_cookie_samesite: Literal['lax', 'strict', 'none'] = Field(
+ default='lax', description='单点登录 Cookie 的跨站发送策略'
+ )
+ oidc_sso_cookie_domain: str | None = Field(default=None, description='单点登录 Cookie 的作用域名')
+
+ oidc_signing_algorithm: Literal['RS256'] = Field(default='RS256', description='OIDC 令牌的签名算法')
+ oidc_signing_key_source: Literal['file', 'kms', 'hsm'] = Field(default='file', description='OIDC 签名密钥的来源')
+ oidc_signing_private_key_path: str = Field(default='', description='OIDC 签名私钥文件路径')
+ oidc_signing_key_encryption_key: str = Field(default='', description='加密存储 OIDC 签名私钥的密钥')
+ oidc_active_kid: str = Field(default='', description='当前用于签发令牌的密钥标识')
+ oidc_key_rotation_overlap_seconds: int = Field(
+ default=86400, gt=0, description='密钥轮换时新旧密钥并存的时长(秒)'
+ )
+
+ oidc_token_hash_pepper: str = Field(default='', description='计算 OIDC 令牌摘要时使用的独立密钥')
+
+ oidc_cors_allowed_origins: str = Field(default='', description='允许跨域访问 OIDC 端点的来源')
+ oidc_interaction_login_url: str = Field(
+ default='https://auth.example.com/auth-center/login', description='OIDC 交互登录页面地址'
+ )
+ oidc_interaction_consent_url: str = Field(
+ default='https://auth.example.com/auth-center/consent', description='OIDC 授权确认页面地址'
+ )
+ oidc_interaction_error_url: str = Field(
+ default='https://auth.example.com/auth-center/error', description='OIDC 交互错误页面地址'
+ )
+
+ oidc_audit_retention_days: int = Field(default=180, gt=0, description='OIDC 审计记录保留天数')
+ oidc_backchannel_logout_timeout_seconds: int = Field(default=5, gt=0, description='后通道注销请求的超时时间(秒)')
+ oidc_legacy_auth_isolation_enabled: bool = Field(default=True, description='是否隔离 OIDC 与旧版登录认证')
OIDC_PEPPER_MIN_BYTES: ClassVar[int] = 32
@staticmethod
@@ -527,33 +550,35 @@ def validate_oidc_configuration(self) -> 'OidcSettings':
class PluginDependencyPolicySettings(BaseSettings):
- """
- 插件依赖安装策略配置
- """
+ """插件依赖安装策略配置。"""
- plugin_dependency_policy_mode: str = 'dev=explicit,test=plan_only,stage=locked,prod=plan_only'
- plugin_dependency_allow_prod_install: bool = False
- plugin_dependency_require_yes: bool = True
- plugin_dependency_require_allowlist: bool | None = None
- plugin_dependency_require_lockfile: bool | None = None
- plugin_dependency_lockfile: str = ''
- plugin_dependency_allowlist: str = ''
- plugin_dependency_offline_dir: str = ''
- plugin_dependency_pip_index_url: str = ''
- plugin_dependency_npm_registry: str = ''
- plugin_dependency_install_timeout: int = 600
+ plugin_dependency_policy_mode: str = Field(
+ default='dev=explicit,test=plan_only,stage=locked,prod=plan_only', description='插件依赖安装的策略模式'
+ )
+ plugin_dependency_allow_prod_install: bool = Field(default=False, description='是否允许在生产环境安装插件依赖')
+ plugin_dependency_require_yes: bool = Field(default=True, description='安装插件依赖前是否要求显式确认')
+ plugin_dependency_require_allowlist: bool | None = Field(default=None, description='是否要求依赖出现在允许清单中')
+ plugin_dependency_require_lockfile: bool | None = Field(default=None, description='安装插件依赖时是否要求锁文件')
+ plugin_dependency_lockfile: str = Field(default='', description='插件依赖锁文件路径')
+ plugin_dependency_allowlist: str = Field(default='', description='允许安装的插件依赖清单')
+ plugin_dependency_offline_dir: str = Field(default='', description='存放离线依赖包的目录')
+ plugin_dependency_pip_index_url: str = Field(default='', description='安装 Python 依赖时使用的软件包索引地址')
+ plugin_dependency_npm_registry: str = Field(default='', description='安装前端依赖时使用的 npm 仓库地址')
+ plugin_dependency_install_timeout: int = Field(default=600, description='插件依赖安装的超时时间(秒)')
class PluginArtifactSettings(BaseSettings):
- """
- 签名插件制品与维护发布配置;默认关闭以兼容目录插件部署。
- """
+ """签名插件制品与维护发布配置;默认关闭以兼容目录插件部署。"""
- plugin_artifact_enabled: bool = False
- plugin_artifact_store: str = 'vf_admin/plugin_artifacts'
- plugin_artifact_trust_file: str = ''
- plugin_artifact_heartbeat_seconds: int = Field(default=15, ge=1, le=60)
- plugin_artifact_worker_ttl_seconds: int = Field(default=60, ge=3, le=600)
+ plugin_artifact_enabled: bool = Field(default=False, description='是否启用插件制品交付')
+ plugin_artifact_store: str = Field(default='vf_admin/plugin_artifacts', description='插件制品的存储目录')
+ plugin_artifact_trust_file: str = Field(default='', description='声明受信任制品签发者的配置文件路径')
+ plugin_artifact_heartbeat_seconds: int = Field(
+ default=15, ge=1, le=60, description='插件制品工作进程发送心跳的间隔(秒)'
+ )
+ plugin_artifact_worker_ttl_seconds: int = Field(
+ default=60, ge=3, le=600, description='插件制品工作进程心跳记录的有效期(秒)'
+ )
@model_validator(mode='after')
def validate_artifact_settings(self) -> 'PluginArtifactSettings':
@@ -561,6 +586,7 @@ def validate_artifact_settings(self) -> 'PluginArtifactSettings':
拒绝缺少信任根的启用配置和无法容纳正常心跳的超时。
:return: 通过信任根及维护心跳配置校验的制品设置
+ :raises ValueError: 启用签名插件制品时必须配置 PLUGIN_ARTIFACT_TRUST_FILE;PLUGIN_ARTIFACT_STORE 不能为空;插件 worker 超时必须至少为心跳间隔的三倍
"""
if self.plugin_artifact_enabled and not self.plugin_artifact_trust_file.strip():
raise ValueError('启用签名插件制品时必须配置 PLUGIN_ARTIFACT_TRUST_FILE')
@@ -573,7 +599,14 @@ def validate_artifact_settings(self) -> 'PluginArtifactSettings':
class GenSettings:
"""
- 代码生成配置
+ 代码生成配置。
+
+ :cvar author: 生成代码使用的作者名称
+ :cvar package_name: 包名
+ :cvar auto_remove_pre: 生成模型名称时是否去除表名前缀
+ :cvar table_prefix: 生成代码时识别的数据库表前缀
+ :cvar allow_overwrite: 是否允许覆盖已有生成文件
+ :cvar GEN_PATH: 保存生成代码的目录
"""
author = 'insistence'
@@ -585,13 +618,24 @@ class GenSettings:
GEN_PATH = 'vf_admin/gen_path'
def __init__(self) -> None:
+ """确保代码生成目录存在。"""
if not os.path.exists(self.GEN_PATH):
os.makedirs(self.GEN_PATH)
class UploadSettings:
"""
- 上传配置
+ 上传配置。
+
+ :cvar UPLOAD_PREFIX: 公开上传文件使用的访问路径前缀
+ :cvar UPLOAD_PATH: 公开上传文件的存放目录
+ :cvar PRIVATE_UPLOAD_PATH: 私有上传文件的存放目录
+ :cvar FILE_TRASH_PATH: 文件移入回收站后的存放目录
+ :cvar FILE_RECONCILE_QUARANTINE_PATH: 对账发现异常文件时使用的隔离目录
+ :cvar UPLOAD_MACHINE: 生成上传文件标识所使用的机器代号
+ :cvar DEFAULT_ALLOWED_EXTENSION: 默认允许上传的文件扩展名
+ :cvar DOWNLOAD_PATH: 存放待下载文件的目录
+ :cvar MAX_FILE_SIZE: 允许上传的最大字节数
"""
UPLOAD_PREFIX = '/profile'
@@ -607,7 +651,7 @@ class UploadSettings:
'jpg',
'jpeg',
'png',
- # word excel powerpoint
+ # Word、Excel 和 PowerPoint 文档
'doc',
'docx',
'xls',
@@ -626,13 +670,14 @@ class UploadSettings:
'mp4',
'avi',
'rmvb',
- # pdf
+ # PDF 文档
'pdf',
]
DOWNLOAD_PATH = 'vf_admin/download_path'
MAX_FILE_SIZE = 100 * 1024 * 1024
def __init__(self) -> None:
+ """准备上传、私有文件、回收站和对账隔离目录。"""
if not os.path.exists(self.UPLOAD_PATH):
os.makedirs(self.UPLOAD_PATH)
if not os.path.exists(self.PRIVATE_UPLOAD_PATH):
@@ -647,7 +692,10 @@ def __init__(self) -> None:
class CachePathConfig:
"""
- 缓存目录配置
+ 缓存目录配置。
+
+ :cvar PATH: 缓存目录的绝对路径
+ :cvar PATHSTR: 缓存目录的相对名称
"""
PATH = os.path.join(os.path.abspath(os.getcwd()), 'caches')
@@ -656,55 +704,72 @@ class CachePathConfig:
class GetConfig:
"""
- 获取配置
+ 获取配置。
+
+ :ivar run_env: 从命令行或环境配置选中的运行环境
"""
def __init__(self) -> None:
+ """从命令行参数确定当前运行环境。"""
self.run_env = self.parse_cli_args()
def get_app_config(self) -> AppSettings:
"""
- 获取应用配置
+ 获取应用配置。
+
+ :return: 应用配置
"""
# 实例化应用配置模型
return AppSettings()
def get_i18n_config(self) -> I18nSettings:
"""
- 获取国际化配置
+ 获取国际化配置。
+
+ :return: 国际化配置
"""
return I18nSettings()
def get_jwt_config(self) -> JwtSettings:
"""
- 获取Jwt配置
+ 获取Jwt配置。
+
+ :return: Jwt配置
"""
# 实例化Jwt配置模型
return JwtSettings()
def get_database_config(self) -> DataBaseSettings:
"""
- 获取数据库配置
+ 获取数据库配置。
+
+ :return: 数据库配置
"""
# 实例化数据库配置模型
return DataBaseSettings()
def get_redis_config(self) -> RedisSettings:
"""
- 获取Redis配置
+ 获取Redis配置。
+
+ :return: Redis配置
"""
# 实例化Redis配置模型
return RedisSettings()
def get_log_config(self) -> LogSettings:
"""
- 获取日志配置
+ 获取日志配置。
+
+ :return: 日志配置
"""
return LogSettings()
def get_transport_crypto_config(self) -> TransportCryptoSettings:
"""
- 获取传输层加解密配置
+ 获取传输层加解密配置。
+
+ :return: 传输层加解密配置
"""
return TransportCryptoSettings()
@@ -713,25 +778,33 @@ def get_oidc_config(self) -> OidcSettings:
获取统一认证中心配置。
OIDC 配置由模型自身执行启动级校验;关闭时不会校验密钥和 Pepper。
+
+ :return: 统一认证中心配置
"""
return OidcSettings()
def get_plugin_dependency_policy_config(self) -> PluginDependencyPolicySettings:
"""
- 获取插件依赖安装策略配置
+ 获取插件依赖安装策略配置。
+
+ :return: 插件依赖安装策略配置
"""
return PluginDependencyPolicySettings()
def get_gen_config(self) -> GenSettings:
"""
- 获取代码生成配置
+ 获取代码生成配置。
+
+ :return: 代码生成配置
"""
# 实例化代码生成配置
return GenSettings()
def get_upload_config(self) -> UploadSettings:
"""
- 获取上传配置
+ 获取上传配置。
+
+ :return: 上传配置
"""
# 实例上传配置
return UploadSettings()
diff --git a/ruoyi-fastapi-backend/config/get_redis.py b/ruoyi-fastapi-backend/config/get_redis.py
index 2b424613f..5c94cd84a 100644
--- a/ruoyi-fastapi-backend/config/get_redis.py
+++ b/ruoyi-fastapi-backend/config/get_redis.py
@@ -11,14 +11,12 @@
class RedisUtil:
- """
- Redis相关方法
- """
+ """Redis相关方法。"""
@classmethod
async def create_redis_pool(cls, log_enabled: bool = True, log_start_enabled: bool | None = None) -> aioredis.Redis:
"""
- 应用启动时初始化redis连接
+ 应用启动时初始化redis连接。
:param log_enabled: 是否输出日志
:param log_start_enabled: 是否输出开始连接日志
@@ -48,13 +46,12 @@ async def check_redis_connection(
log_error_enabled: bool | None = None,
) -> None:
"""
- 检查redis连接状态
+ 检查redis连接状态。
:param redis: redis对象
:param log_enabled: 是否输出成功日志
:param log_start_enabled: 是否输出开始连接日志
:param log_error_enabled: 是否输出错误日志,未指定时沿用log_enabled
- :return: None
"""
if log_start_enabled is None:
log_start_enabled = log_enabled
@@ -82,10 +79,9 @@ async def check_redis_connection(
@classmethod
async def close_redis_pool(cls, app: FastAPI) -> None:
"""
- 应用关闭时关闭redis连接
+ 应用关闭时关闭redis连接。
:param app: fastapi对象
- :return:
"""
await app.state.redis.close()
logger.debug('✅️ 关闭redis连接成功')
@@ -93,10 +89,9 @@ async def close_redis_pool(cls, app: FastAPI) -> None:
@classmethod
async def init_sys_dict(cls, redis: FastAPI) -> None:
"""
- 应用启动时缓存字典表
+ 应用启动时缓存字典表。
:param redis: redis对象
- :return:
"""
async with DataSourceRegistry.session() as session:
await DictDataService.init_cache_sys_dict_services(session, redis)
@@ -104,10 +99,9 @@ async def init_sys_dict(cls, redis: FastAPI) -> None:
@classmethod
async def init_sys_config(cls, redis: aioredis.Redis) -> None:
"""
- 应用启动时缓存参数配置表
+ 应用启动时缓存参数配置表。
:param redis: redis对象
- :return:
"""
async with DataSourceRegistry.session() as session:
await ConfigService.init_cache_sys_config_services(session, redis)
diff --git a/ruoyi-fastapi-backend/config/lifecycle.py b/ruoyi-fastapi-backend/config/lifecycle.py
index cc18c361c..83f095ede 100644
--- a/ruoyi-fastapi-backend/config/lifecycle.py
+++ b/ruoyi-fastapi-backend/config/lifecycle.py
@@ -10,11 +10,10 @@ async def init_create_table(
log_success_enabled: bool = True,
) -> None:
"""
- 在默认数据源中初始化平台数据库元数据
+ 在默认数据源中初始化平台数据库元数据。
:param stage: 建表阶段
:param log_success_enabled: 是否输出阶段成功摘要
- :return: None
"""
if log_success_enabled:
message = '🔎 初始化平台数据库元数据...' if stage == 'platform' else '🔎 同步插件实体表...'
diff --git a/ruoyi-fastapi-backend/config/scheduler/dispatcher.py b/ruoyi-fastapi-backend/config/scheduler/dispatcher.py
index 5ab46bf74..a85c348b8 100644
--- a/ruoyi-fastapi-backend/config/scheduler/dispatcher.py
+++ b/ruoyi-fastapi-backend/config/scheduler/dispatcher.py
@@ -16,17 +16,22 @@
class SchedulerDispatcher:
"""
- 持久化执行请求领取、派发和下次调度时刻观测
+ 持久化执行请求领取、派发和下次调度时刻观测。
+
+ :ivar jobs: 本地任务管理器
+ :ivar resources: 调度数据库资源
+ :ivar synchronizer: 已应用配置管理器
+ :ivar lock: 用于串行访问共享资源的锁
+ :ivar _observed_at: 最近一次观测到调度状态的时刻
"""
def __init__(self, jobs: SchedulerJobs, resources: SchedulerResources, synchronizer: SchedulerSynchronizer) -> None:
"""
- 初始化请求派发所需的任务、数据库和配置同步对象
+ 初始化请求派发所需的任务、数据库和配置同步对象。
:param jobs: 本地任务管理器
:param resources: 调度数据库资源
:param synchronizer: 已应用配置管理器
- :return: None
"""
self.jobs = jobs
self.resources = resources
@@ -36,10 +41,9 @@ def __init__(self, jobs: SchedulerJobs, resources: SchedulerResources, synchroni
async def refresh_observations(self, *, is_leader: Callable[[], bool]) -> None:
"""
- 定期保存Leader观测的下次调度时刻,供其他worker读取
+ 定期保存Leader观测的下次调度时刻,供其他worker读取。
:param is_leader: 检查当前进程是否仍持有Leader租约
- :return: None
"""
now = time.monotonic()
interval_seconds = 5
@@ -67,10 +71,9 @@ async def refresh_observations(self, *, is_leader: Callable[[], bool]) -> None:
async def dispatch_pending(self, *, is_leader: Callable[[], bool]) -> None:
"""
- 分批领取待执行请求,派发只在领取事务提交后进行
+ 分批领取待执行请求,派发只在领取事务提交后进行。
:param is_leader: 检查当前进程是否仍持有Leader租约
- :return: None
"""
if not is_leader() or self.lock.locked():
return
diff --git a/ruoyi-fastapi-backend/config/scheduler/events.py b/ruoyi-fastapi-backend/config/scheduler/events.py
index 2eda2cd06..34cbded22 100644
--- a/ruoyi-fastapi-backend/config/scheduler/events.py
+++ b/ruoyi-fastapi-backend/config/scheduler/events.py
@@ -14,7 +14,21 @@
@dataclass(frozen=True)
class JobSnapshot:
"""
- 任务提交时的不可变配置快照
+ 任务提交时的不可变配置快照。
+
+ :ivar name: 用于查找或标识当前对象的名称
+ :ivar jobstore: 保存该任务的调度存储名称
+ :ivar executor: 负责运行任务的执行器
+ :ivar invoke_target: 调用目标字符串
+ :ivar args: 传给被调用对象的位置参数
+ :ivar kwargs: 传给被调用对象的关键字参数
+ :ivar trigger: 计算任务下次执行时间的触发器
+ :ivar time_zone: 任务IANA时区名称
+ :ivar job_group: 任务组过滤条件
+ :ivar job_id: 任务ID
+ :ivar execution_id: 执行ID
+ :ivar dispatch_token: 本次派发的领取凭据
+ :ivar managed: 是否启用持久化执行管理
"""
name: str
@@ -34,7 +48,7 @@ class JobSnapshot:
@classmethod
def from_job(cls, job: Job, *, managed: bool = False) -> 'JobSnapshot':
"""
- 从调度器任务提取执行日志所需的配置
+ 从调度器任务提取执行日志所需的配置。
:param job: 调度器任务对象
:param managed: 是否启用持久化执行管理
@@ -58,7 +72,7 @@ def from_job(cls, job: Job, *, managed: bool = False) -> 'JobSnapshot':
def execution_snapshot(self) -> dict[str, Any]:
"""
- 生成跨进程执行记录需要的可序列化配置快照
+ 生成跨进程执行记录需要的可序列化配置快照。
:return: 可序列化的任务配置快照
"""
@@ -77,19 +91,26 @@ def execution_snapshot(self) -> dict[str, Any]:
class TimedJobExecutionEvent(JobExecutionEvent):
"""
- 包含任务快照、真实起止时刻和耗时的执行事件
+ 包含任务快照、真实起止时刻和耗时的执行事件。
+
+ :ivar snapshot: 提交任务时的配置快照
+ :ivar execution_id: 执行ID
+ :ivar execution_key: 关联一次调度执行的唯一键
+ :ivar start_time: 查询开始时间
+ :ivar end_time: 查询结束时间
+ :ivar run_duration_ms: 实际执行耗时(毫秒)
+ :ivar execution_status: 调度执行的状态
"""
def __init__(self, code: int, job: Job, run_time: datetime, snapshot: JobSnapshot, **kwargs) -> None:
"""
- 初始化任务执行事件
+ 初始化任务执行事件。
:param code: APScheduler事件类型
:param job: 调度器任务对象
:param run_time: 本次计划执行时刻
:param snapshot: 提交任务时的配置快照
:param kwargs: 传递给标准执行事件的附加参数
- :return: None
"""
super().__init__(code, job.id, snapshot.jobstore, run_time, **kwargs)
self.snapshot = snapshot
diff --git a/ruoyi-fastapi-backend/config/scheduler/executors.py b/ruoyi-fastapi-backend/config/scheduler/executors.py
index 8a8b4b13c..eeef4cbf6 100644
--- a/ruoyi-fastapi-backend/config/scheduler/executors.py
+++ b/ruoyi-fastapi-backend/config/scheduler/executors.py
@@ -23,7 +23,7 @@
def _missed_event(job: Job, run_time: datetime, snapshot: JobSnapshot) -> TimedJobExecutionEvent | None:
"""
- 判断本次计划是否已超过允许的延迟执行时限
+ 判断本次计划是否已超过允许的延迟执行时限。
:param job: 调度器任务对象
:param run_time: 本次计划执行时刻
@@ -48,7 +48,7 @@ def _execution(
event: TimedJobExecutionEvent | None = None,
) -> Iterator[TimedJobExecutionEvent]:
"""
- 在实际调用边界记录任务起止时刻和单调耗时
+ 在实际调用边界记录任务起止时刻和单调耗时。
保留APScheduler对BaseException的捕获行为,异常通过执行事件回传。
@@ -58,7 +58,7 @@ def _execution(
:param events: 接收执行事件的结果列表
:param logger_name: 调度器日志名称
:param event: 已创建的执行事件,未指定时自动创建
- :return: 供调用方写入任务返回值的执行事件
+ :yield: 供调用方写入任务返回值的执行事件
"""
logger = logging.getLogger(logger_name)
event = event or TimedJobExecutionEvent(EVENT_JOB_EXECUTED, job, run_time, snapshot)
@@ -88,7 +88,7 @@ def _execution(
def _claim_execution(event: TimedJobExecutionEvent) -> str | None:
"""
- 在实际调用前检查持久化并发约束,失败时生成未执行事件
+ 在实际调用前检查持久化并发约束,失败时生成未执行事件。
:param event: 任务执行事件
:return: 执行占用凭据,未获得占用时返回None
@@ -117,11 +117,10 @@ def _claim_execution(event: TimedJobExecutionEvent) -> str | None:
def _finish_execution(event: TimedJobExecutionEvent, token: str) -> None:
"""
- 保存已执行任务的终态,存储故障保留未确认占用供恢复流程处理
+ 保存已执行任务的终态,存储故障保留未确认占用供恢复流程处理。
:param event: 任务执行事件
:param token: 当前执行占用凭据
- :return: None
"""
try:
JobExecutionStore.finish(
@@ -139,10 +138,9 @@ def _finish_execution(event: TimedJobExecutionEvent, token: str) -> None:
def _record_unstarted_execution(event: TimedJobExecutionEvent) -> None:
"""
- 保存过期和执行器拒绝记录,不覆盖已经开始的执行
+ 保存过期和执行器拒绝记录,不覆盖已经开始的执行。
:param event: 任务执行事件
- :return: None
"""
if not event.snapshot.managed:
return
@@ -164,7 +162,7 @@ def run_timed_job(
job: Job, run_times: list[datetime], snapshot: JobSnapshot, logger_name: str
) -> list[TimedJobExecutionEvent]:
"""
- 执行同步任务并收集带测时信息的事件
+ 执行同步任务并收集带测时信息的事件。
:param job: 调度器任务对象
:param run_times: 本次提交需要处理的计划执行时刻列表
@@ -201,7 +199,7 @@ async def run_timed_coroutine_job(
job: Job, run_times: list[datetime], snapshot: JobSnapshot, logger_name: str
) -> list[TimedJobExecutionEvent]:
"""
- 执行异步任务并收集带测时信息的事件
+ 执行异步任务并收集带测时信息的事件。
:param job: 调度器任务对象
:param run_times: 本次提交需要处理的计划执行时刻列表
@@ -236,7 +234,10 @@ async def run_timed_coroutine_job(
class JobSubmission:
"""
- 任务提交和并发拒绝事件处理
+ 任务提交和并发拒绝事件处理。
+
+ :ivar _on_rejected: 并发拒绝事件回调
+ :ivar manage_executions: 是否启用持久化执行管理
"""
def __init__(
@@ -245,11 +246,10 @@ def __init__(
manage_executions: bool = False,
) -> None:
"""
- 初始化提交配置和拒绝事件回调
+ 初始化提交配置和拒绝事件回调。
:param on_rejected: 并发拒绝事件回调
:param manage_executions: 是否启用持久化执行管理
- :return: None
"""
self._on_rejected = on_rejected
self.manage_executions = manage_executions
@@ -262,13 +262,13 @@ def submit_job(
job_logger: logging.Logger,
) -> None:
"""
- 调用执行器提交任务,达到并发上限时记录未执行事件
+ 调用执行器提交任务,达到并发上限时记录未执行事件。
:param submit: 执行器的原始提交方法
:param job: 调度器任务对象
:param run_times: 本次提交的计划执行时刻
:param job_logger: 执行器日志对象
- :return: None
+ :raises MaxInstancesReachedError: 任务已达到同时执行的实例数上限
"""
try:
submit(job, run_times)
@@ -289,7 +289,9 @@ def submit_job(
class TimedAsyncIOExecutor(AsyncIOExecutor):
"""
- 记录真实执行耗时的异步及线程执行器
+ 记录真实执行耗时的异步及线程执行器。
+
+ :ivar _submission: 关联调度提交与执行结果的状态
"""
def __init__(
@@ -300,43 +302,39 @@ def __init__(
**kwargs,
) -> None:
"""
- 初始化执行器和任务提交处理对象
+ 初始化执行器和任务提交处理对象。
:param args: 执行器的位置参数
:param on_rejected: 并发拒绝事件回调
:param manage_executions: 是否启用持久化执行管理
:param kwargs: 执行器的关键字参数
- :return: None
"""
super().__init__(*args, **kwargs)
self._submission = JobSubmission(on_rejected, manage_executions)
def submit_job(self, job: Job, run_times: list[datetime]) -> None:
"""
- 通过提交处理对象执行原始提交并记录并发拒绝事件
+ 通过提交处理对象执行原始提交并记录并发拒绝事件。
:param job: 调度器任务对象
:param run_times: 本次提交的计划执行时刻
- :return: None
"""
self._submission.submit_job(super().submit_job, job, run_times, self._logger)
def _do_submit_job(self, job: Job, run_times: list[datetime]) -> None:
"""
- 提交携带配置快照的任务并注册完成回调
+ 提交携带配置快照的任务并注册完成回调。
:param job: 调度器任务对象
:param run_times: 本次提交需要处理的计划执行时刻列表
- :return: None
"""
snapshot = JobSnapshot.from_job(job, managed=self._submission.manage_executions)
def callback(future: Future) -> None:
"""
- 将任务执行结果交回APScheduler处理
+ 将任务执行结果交回APScheduler处理。
:param future: 任务执行产生的Future对象
- :return: None
"""
self._pending_futures.discard(future)
try:
@@ -356,7 +354,10 @@ def callback(future: Future) -> None:
class TimedProcessPoolExecutor(ProcessPoolExecutor):
"""
- 记录真实执行耗时的进程池执行器
+ 记录真实执行耗时的进程池执行器。
+
+ :ivar _submission: 关联调度提交与执行结果的状态
+ :ivar _pool: 复用底层资源的池
"""
def __init__(
@@ -367,43 +368,39 @@ def __init__(
**kwargs,
) -> None:
"""
- 初始化执行器和任务提交处理对象
+ 初始化执行器和任务提交处理对象。
:param args: 执行器的位置参数
:param on_rejected: 并发拒绝事件回调
:param manage_executions: 是否启用持久化执行管理
:param kwargs: 执行器的关键字参数
- :return: None
"""
super().__init__(*args, **kwargs)
self._submission = JobSubmission(on_rejected, manage_executions)
def submit_job(self, job: Job, run_times: list[datetime]) -> None:
"""
- 通过提交处理对象执行原始提交并记录并发拒绝事件
+ 通过提交处理对象执行原始提交并记录并发拒绝事件。
:param job: 调度器任务对象
:param run_times: 本次提交的计划执行时刻
- :return: None
"""
self._submission.submit_job(super().submit_job, job, run_times, self._logger)
def _do_submit_job(self, job: Job, run_times: list[datetime]) -> None:
"""
- 提交携带配置快照的任务并注册完成回调
+ 提交携带配置快照的任务并注册完成回调。
:param job: 调度器任务对象
:param run_times: 本次提交需要处理的计划执行时刻列表
- :return: None
"""
snapshot = JobSnapshot.from_job(job, managed=self._submission.manage_executions)
def callback(future: Future) -> None:
"""
- 将任务执行结果交回APScheduler处理
+ 将任务执行结果交回APScheduler处理。
:param future: 任务执行产生的Future对象
- :return: None
"""
exc = future.exception()
if exc:
diff --git a/ruoyi-fastapi-backend/config/scheduler/job_adapter.py b/ruoyi-fastapi-backend/config/scheduler/job_adapter.py
index 525b66ea6..2cf060366 100644
--- a/ruoyi-fastapi-backend/config/scheduler/job_adapter.py
+++ b/ruoyi-fastapi-backend/config/scheduler/job_adapter.py
@@ -16,7 +16,11 @@
class JobAdapter:
"""
- 统一任务默认值、参数解析和调度配置校验
+ 统一任务默认值、参数解析和调度配置校验。
+
+ :cvar JOB_STORES: 支持的任务持久化存储
+ :cvar EXECUTORS: 支持的任务执行器
+ :cvar CONFIG_FIELDS: 可写入调度任务配置的字段
"""
JOB_STORES = frozenset({'default', 'sqlalchemy', 'redis'})
@@ -40,7 +44,7 @@ class JobAdapter:
@staticmethod
def from_record(record: Any) -> JobModel:
"""
- 读取已保存配置,不在读取阶段阻断无效配置的诊断和停用
+ 读取已保存配置,不在读取阶段阻断无效配置的诊断和停用。
:param record: 数据库记录或任务对象
:return: 任务对象信息
@@ -54,7 +58,7 @@ def from_record(record: Any) -> JobModel:
@staticmethod
def normalize(job: JobModel) -> JobModel:
"""
- 补齐保存和注册共用的默认值,保留显式填写的配置
+ 补齐保存和注册共用的默认值,保留显式填写的配置。
:param job: 任务对象信息
:return: 补齐默认值后的任务对象
@@ -73,10 +77,11 @@ def normalize(job: JobModel) -> JobModel:
@staticmethod
def parse_args(value: list[Any]) -> list[Any]:
"""
- 校验位置参数为JSON数组,保留数组内的值类型
+ 校验位置参数为JSON数组,保留数组内的值类型。
:param value: 待解析的位置参数
:return: 位置参数列表
+ :raises ValueError: 位置参数必须是 JSON 数组
"""
if not isinstance(value, list):
raise ValueError('位置参数必须是 JSON 数组')
@@ -85,10 +90,11 @@ def parse_args(value: list[Any]) -> list[Any]:
@staticmethod
def import_function(target: str) -> Callable[..., Any]:
"""
- 导入任务函数,明确拒绝不存在和不可调用的目标
+ 导入任务函数,明确拒绝不存在和不可调用的目标。
:param target: 调用目标字符串
:return: 任务函数
+ :raises ValueError: 任务目标无法导入或不可调用
"""
try:
module_name, name = target.rsplit('.', 1)
@@ -102,10 +108,10 @@ def import_function(target: str) -> Callable[..., Any]:
@staticmethod
def validate_allowed_target(target: str | None) -> None:
"""
- 校验管理接口允许保存的调用模块,按完整模块前缀匹配
+ 校验管理接口允许保存的调用模块,按完整模块前缀匹配。
:param target: 调用目标字符串
- :return: None
+ :raises ValueError: 调用目标不能为空;调用目标包含禁止使用的模块或协议;调用目标字符串不在白名单内
"""
if not target:
raise ValueError('调用目标不能为空')
@@ -128,11 +134,12 @@ def validate_allowed_target(target: str | None) -> None:
@classmethod
def prepare(cls, job: JobModel, *, function: Callable[..., Any] | None = None) -> dict[str, Any]:
"""
- 校验完整配置并构造注册参数,不写数据库或改变调度器
+ 校验完整配置并构造注册参数,不写数据库或改变调度器。
:param job: 任务对象信息
:param function: 已导入的任务函数,未指定时根据调用目标导入
:return: 调度器任务注册参数
+ :raises ValueError: 任务名称不能为空;业务分组不能为空;调用目标不能为空;调用目标不可调用
"""
job = JobModel.model_validate(cls.normalize(job).model_dump(by_alias=True))
if not job.job_name or not job.job_name.strip():
@@ -189,7 +196,7 @@ def prepare(cls, job: JobModel, *, function: Callable[..., Any] | None = None) -
@classmethod
def config_hash(cls, job: JobModel | None) -> str:
"""
- 计算调度配置摘要,供版本跟踪和插件变更校准使用
+ 计算调度配置摘要,供版本跟踪和插件变更校准使用。
:param job: 任务对象信息
:return: 任务配置摘要
diff --git a/ruoyi-fastapi-backend/config/scheduler/job_execution.py b/ruoyi-fastapi-backend/config/scheduler/job_execution.py
index 114804e3d..a12ff55c4 100644
--- a/ruoyi-fastapi-backend/config/scheduler/job_execution.py
+++ b/ruoyi-fastapi-backend/config/scheduler/job_execution.py
@@ -22,7 +22,12 @@
@dataclass(frozen=True)
class ExecutionClaim:
"""
- 实际执行前获得的占用凭据或明确的未执行原因
+ 实际执行前获得的占用凭据或明确的未执行原因。
+
+ :ivar accepted: 当前执行请求是否成功认领
+ :ivar token: 当前执行占用凭据
+ :ivar status: 执行状态
+ :ivar message: 执行结果或未执行原因
"""
accepted: bool
@@ -33,7 +38,11 @@ class ExecutionClaim:
class JobExecutionStore:
"""
- 使用独立短事务保存占用、续租和最终执行结果
+ 使用独立短事务保存占用、续租和最终执行结果。
+
+ :cvar LEASE_SECONDS: 工作租约保持有效的秒数
+ :cvar HEARTBEAT_SECONDS: 两次续租心跳之间的秒数
+ :cvar FINISH_ATTEMPTS: 提交任务终态时允许的最大尝试次数
"""
LEASE_SECONDS = 30
@@ -43,7 +52,7 @@ class JobExecutionStore:
@staticmethod
def session() -> Session:
"""
- 按当前进程的数据源配置创建独立同步会话
+ 按当前进程的数据源配置创建独立同步会话。
:return: 同步数据库会话
"""
@@ -61,7 +70,7 @@ def claim(
dispatch_token: str | None = None,
) -> ExecutionClaim:
"""
- 串行检查同一任务的并发占用,再原子标记本次执行开始
+ 串行检查同一任务的并发占用,再原子标记本次执行开始。
:param execution_id: 执行ID
:param job_id: 任务ID
@@ -128,12 +137,11 @@ def claim(
@staticmethod
def _stop(execution: SysJobExecution, status: str, message: str) -> None:
"""
- 保存未执行的终态,不伪造实际执行开始时间和耗时
+ 保存未执行的终态,不伪造实际执行开始时间和耗时。
:param execution: 执行记录对象
:param status: 执行状态
:param message: 执行结果或未执行原因
- :return: None
"""
execution.status = status
execution.message = message
@@ -144,7 +152,7 @@ def _stop(execution: SysJobExecution, status: str, message: str) -> None:
@classmethod
def renew(cls, execution_id: str, token: str) -> bool:
"""
- 仅允许当前占用者续租;迟到的旧执行不能更新其他请求
+ 仅允许当前占用者续租;迟到的旧执行不能更新其他请求。
:param execution_id: 执行ID
:param token: 当前执行占用凭据
@@ -175,7 +183,7 @@ def finish(
run_duration_ms: int,
) -> None:
"""
- 按占用凭据保存真实执行结果;结果未知的原执行仍可补交最终结果
+ 按占用凭据保存真实执行结果;结果未知的原执行仍可补交最终结果。
:param execution_id: 执行ID
:param token: 当前执行占用凭据
@@ -184,7 +192,7 @@ def finish(
:param start_time: 实际执行开始时刻
:param end_time: 实际执行结束时刻
:param run_duration_ms: 实际执行耗时(毫秒)
- :return: None
+ :raises DBAPIError: 写入任务结果遇到不可重试的错误或已耗尽重试次数
"""
for attempt in range(cls.FINISH_ATTEMPTS):
try:
@@ -216,7 +224,7 @@ def finish(
@staticmethod
def _retryable_finish_error(error: DBAPIError) -> bool:
"""
- 只重试数据库明确回滚的死锁或序列化冲突,连接中断等不明结果继续向上报告
+ 只重试数据库明确回滚的死锁或序列化冲突,连接中断等不明结果继续向上报告。
:param error: SQLAlchemy 包装的数据库异常
:return: 是否可以重试终态更新事务
@@ -240,7 +248,7 @@ def record_unstarted(
dispatch_token: str | None = None,
) -> None:
"""
- 记录过期或执行器拒绝,已有执行记录保持原状态以避免覆盖结果
+ 记录过期或执行器拒绝,已有执行记录保持原状态以避免覆盖结果。
:param execution_id: 执行ID
:param job_id: 任务ID
@@ -249,7 +257,6 @@ def record_unstarted(
:param status: 执行状态
:param message: 执行结果或未执行原因
:param dispatch_token: 本次派发的领取凭据
- :return: None
"""
with cls.session() as db, db.begin():
locked = db.execute(
@@ -280,16 +287,20 @@ def record_unstarted(
class ExecutionHeartbeat:
"""
- 在同步、异步和进程池任务运行期间独立续租,退出时停止续租
+ 在同步、异步和进程池任务运行期间独立续租,退出时停止续租。
+
+ :ivar execution_id: 执行ID
+ :ivar token: 当前执行占用凭据
+ :ivar _stop: 通知心跳循环退出的信号
+ :ivar _thread: 执行周期性心跳的后台线程
"""
def __init__(self, execution_id: str, token: str) -> None:
"""
- 保存执行凭据,线程只在任务真正开始后创建
+ 保存执行凭据,线程只在任务真正开始后创建。
:param execution_id: 执行ID
:param token: 当前执行占用凭据
- :return: None
"""
self.execution_id = execution_id
self.token = token
@@ -297,34 +308,22 @@ def __init__(self, execution_id: str, token: str) -> None:
self._thread = threading.Thread(target=self._renew, name=f'job-lease-{execution_id[:8]}', daemon=True)
def start(self) -> None:
- """
- 启动占用续租
-
- :return: None
- """
+ """启动占用续租。"""
self._thread.start()
def stop(self) -> None:
- """
- 通知续租线程退出,避免任务完成后继续持有占用
-
- :return: None
- """
+ """通知续租线程退出,避免任务完成后继续持有占用。"""
self._stop.set()
def _renew(self) -> None:
- """
- 周期续租;连接故障交由过期状态处理,不自动重放业务调用
-
- :return: None
- """
+ """周期续租;连接故障交由过期状态处理,不自动重放业务调用。"""
while not self._stop.wait(JobExecutionStore.HEARTBEAT_SECONDS):
if not self._renew_once():
return
def _renew_once(self) -> bool:
"""
- 尝试续租一次,暂时断连后允许下一轮恢复连接
+ 尝试续租一次,暂时断连后允许下一轮恢复连接。
:return: 是否继续续租
"""
diff --git a/ruoyi-fastapi-backend/config/scheduler/jobs.py b/ruoyi-fastapi-backend/config/scheduler/jobs.py
index 7ea1951c8..689a858ca 100644
--- a/ruoyi-fastapi-backend/config/scheduler/jobs.py
+++ b/ruoyi-fastapi-backend/config/scheduler/jobs.py
@@ -18,15 +18,17 @@
class SchedulerJobs:
"""
- 任务注册、配置比较和本地调度进度管理
+ 任务注册、配置比较和本地调度进度管理。
+
+ :ivar scheduler: 当前进程的调度器
+ :ivar update_time_cache: 按任务标识保存的最近更新时间
"""
def __init__(self, scheduler: AsyncIOScheduler) -> None:
"""
- 绑定当前进程的调度器并初始化任务更新时间缓存
+ 绑定当前进程的调度器并初始化任务更新时间缓存。
:param scheduler: 当前进程的调度器
- :return: None
"""
self.scheduler = scheduler
self.update_time_cache: dict[str, datetime | None] = {}
@@ -54,7 +56,7 @@ def dump_args(args: tuple[Any, ...] | list[Any] | None) -> str:
@classmethod
def import_function(cls, func_path: str) -> Callable[..., Any]:
"""
- 动态导入函数
+ 动态导入函数。
:param func_path: 函数字符串,如module_task.scheduler_test.job
:return: 导入的函数对象
@@ -64,7 +66,7 @@ def import_function(cls, func_path: str) -> Callable[..., Any]:
@classmethod
def prepare_job(cls, job_info: JobModel) -> dict[str, Any]:
"""
- 构建调度器任务参数
+ 构建调度器任务参数。
:param job_info: 任务对象信息
:return: 调度器任务参数
@@ -74,7 +76,7 @@ def prepare_job(cls, job_info: JobModel) -> dict[str, Any]:
@classmethod
def trigger_signature(cls, trigger: Any) -> tuple[Any, ...]:
"""
- 提取用于比较触发器配置的完整签名
+ 提取用于比较触发器配置的完整签名。
:param trigger: 待比较的触发器对象
:return: 包含时区、起止边界和子触发器信息的签名
@@ -98,7 +100,7 @@ def trigger_signature(cls, trigger: Any) -> tuple[Any, ...]:
@classmethod
def is_config_current(cls, scheduler_job: Job, job_info: JobModel) -> bool:
"""
- 判断任务配置是否一致
+ 判断任务配置是否一致。
:param scheduler_job: 调度器任务对象
:param job_info: 数据库任务对象
@@ -136,7 +138,7 @@ def is_config_current(cls, scheduler_job: Job, job_info: JobModel) -> bool:
def register_job(self, job_info: JobModel) -> bool:
"""
- 注册或更新调度任务,保留未发生变化的调度进度
+ 注册或更新调度任务,保留未发生变化的调度进度。
:param job_info: 任务对象信息
:return: 是否成功注册任务
@@ -157,7 +159,7 @@ def register_job(self, job_info: JobModel) -> bool:
def get_job(self, job_id: str | int) -> Job | None:
"""
- 根据任务id获取任务对象
+ 根据任务id获取任务对象。
:param job_id: 任务id
:return: 任务对象
@@ -168,22 +170,20 @@ def get_job(self, job_id: str | int) -> Job | None:
def add_job(self, job_info: JobModel) -> None:
"""
- 根据输入的任务对象信息添加任务
+ 根据输入的任务对象信息添加任务。
:param job_info: 任务对象信息
- :return: None
"""
self.scheduler.add_job(**self.prepare_job(job_info))
self.record_update_time(str(job_info.job_id), job_info.update_time)
def execute_once(self, job_info: JobModel, *, execution_id: str, dispatch_token: str) -> None:
"""
- 将已持久化并领取的手动请求注册为独立单次任务
+ 将已持久化并领取的手动请求注册为独立单次任务。
:param job_info: 任务对象信息
:param execution_id: 已持久化的执行请求 ID
:param dispatch_token: 本次派发持有的领取凭据
- :return: None
"""
options = self.prepare_job(job_info)
options.update(
@@ -204,10 +204,9 @@ def execute_once(self, job_info: JobModel, *, execution_id: str, dispatch_token:
def remove_job(self, job_id: str | int) -> None:
"""
- 根据任务id移除任务
+ 根据任务id移除任务。
:param job_id: 任务id
- :return: None
"""
job_id = str(job_id)
query_job = self.get_job(job_id=job_id)
@@ -219,13 +218,12 @@ def update_job(
self, job_id: str, job_info: JobModel | None, scheduler_job: Job | None, job_update_time: datetime | None
) -> None:
"""
- 同步更新任务配置
+ 同步更新任务配置。
:param job_id: 任务ID
:param job_info: 数据库任务对象
:param scheduler_job: 调度器任务对象
:param job_update_time: 任务更新时间
- :return: None
"""
if not job_info or not scheduler_job:
return
@@ -239,7 +237,7 @@ def update_job(
def has_update_time(self, job_id: str, job_update_time: datetime | None) -> bool:
"""
- 判断是否跳过同步更新
+ 判断是否跳过同步更新。
:param job_id: 任务ID
:param job_update_time: 任务更新时间
@@ -249,19 +247,17 @@ def has_update_time(self, job_id: str, job_update_time: datetime | None) -> bool
def record_update_time(self, job_id: str, job_update_time: datetime | None) -> None:
"""
- 刷新任务更新时间缓存
+ 刷新任务更新时间缓存。
:param job_id: 任务ID
:param job_update_time: 任务更新时间
- :return: None
"""
self.update_time_cache[job_id] = job_update_time
def forget_update_time(self, job_id: str) -> None:
"""
- 移除任务更新时间缓存
+ 移除任务更新时间缓存。
:param job_id: 任务ID
- :return: None
"""
self.update_time_cache.pop(job_id, None)
diff --git a/ruoyi-fastapi-backend/config/scheduler/listener.py b/ruoyi-fastapi-backend/config/scheduler/listener.py
index 430939c89..b4d3011e2 100644
--- a/ruoyi-fastapi-backend/config/scheduler/listener.py
+++ b/ruoyi-fastapi-backend/config/scheduler/listener.py
@@ -12,24 +12,24 @@
class SchedulerJobListener:
"""
- 调度事件转换和任务执行日志持久化
+ 调度事件转换和任务执行日志持久化。
+
+ :ivar resources: 调度数据库资源
"""
def __init__(self, resources: SchedulerResources) -> None:
"""
- 绑定执行日志使用的独立数据库会话资源
+ 绑定执行日志使用的独立数据库会话资源。
:param resources: 调度数据库资源
- :return: None
"""
self.resources = resources
def handle_event(self, event: SchedulerEvent) -> None:
"""
- 调度器事件监听器,记录任务执行日志
+ 调度器事件监听器,记录任务执行日志。
:param event: APScheduler分发的任务执行事件
- :return: None
"""
if not isinstance(event, TimedJobExecutionEvent) or (
str(event.job_id).startswith('_') and not str(event.job_id).startswith('_manual:')
@@ -72,10 +72,9 @@ def handle_event(self, event: SchedulerEvent) -> None:
def persist_log(self, job_log: JobLogModel) -> None:
"""
- 使用独立同步会话保存任务执行日志
+ 使用独立同步会话保存任务执行日志。
:param job_log: 待保存的任务执行日志
- :return: None
"""
session = self.resources.log_session_factory()()
try:
diff --git a/ruoyi-fastapi-backend/config/scheduler/manager.py b/ruoyi-fastapi-backend/config/scheduler/manager.py
index 436ef4f6a..30d5c56f0 100644
--- a/ruoyi-fastapi-backend/config/scheduler/manager.py
+++ b/ruoyi-fastapi-backend/config/scheduler/manager.py
@@ -27,7 +27,34 @@
class SchedulerManager:
"""
- 定时任务统一入口,负责生命周期、Leader控制和跨进程同步通知
+ 定时任务统一入口,负责生命周期、Leader控制和跨进程同步通知。
+
+ :cvar _scheduler: 管理定时任务的调度器实例
+ :cvar _is_leader: 当前进程是否持有调度器主锁
+ :cvar _worker_id: 当前工作进程的标识
+ :cvar _application_lock_owner_token: 用于验证应用锁所有权的令牌
+ :cvar _application_lock_renewal_task: 周期性续租应用主锁的后台任务
+ :cvar _redis: 回调签名接收的 Redis 客户端
+ :cvar _sync_channel: 传递调度同步通知的 Redis 频道
+ :cvar _sync_listener_task: 接收同步通知的后台任务
+ :cvar _lock_lost_task: 丢失主锁后处理调度切换的任务
+ :cvar _sync_task: 应用待处理同步变更的任务
+ :cvar _sync_pending: 是否已有同步请求排队
+ :cvar _sync_full_pending: 是否等待执行一次全量同步
+ :cvar _sync_pending_ids: 待同步的任务标识集合
+ :cvar _sync_lock: 串行处理调度同步请求的锁
+ :cvar _last_sync_at: 最近一次同步任务的时间
+ :cvar _sync_debounce_seconds: 合并同步请求的等待时间(秒)
+ :cvar _sync_min_interval_seconds: 两次同步的最小间隔(秒)
+ :cvar _reacquire_task: 尝试重新取得主锁的任务
+ :cvar _reacquire_interval_seconds: 重新获取租约的间隔(秒)
+ :cvar _reacquire_jitter_seconds: 重新获取租约时的随机抖动范围(秒)
+ :cvar _is_closing: 是否正在关闭当前资源
+ :cvar _resources: 调度器启动时创建的共享资源
+ :cvar _jobs: 当前管理的任务集合
+ :cvar _synchronizer: 在数据库与调度器间同步任务的组件
+ :cvar _dispatcher: 分派调度操作的组件
+ :cvar _listener: 监听调度事件的组件
"""
_scheduler: AsyncIOScheduler = scheduler
@@ -61,7 +88,7 @@ class SchedulerManager:
@classmethod
def _should_enable_scheduler_sync(cls) -> bool:
"""
- 判断是否需要启用多 worker 的任务状态同步机制
+ 判断是否需要启用多 worker 的任务状态同步机制。
:return: 是否开启定时同步与监听
"""
@@ -70,10 +97,9 @@ def _should_enable_scheduler_sync(cls) -> bool:
@classmethod
async def init_system_scheduler(cls, redis: aioredis.Redis) -> None:
"""
- 应用启动时初始化定时任务(使用分布式锁确保只有一个worker启动scheduler)
+ 应用启动时初始化定时任务(使用分布式锁确保只有一个worker启动scheduler)。
:param redis: Redis连接对象
- :return: None
"""
cls._redis = redis
cls._is_closing = False
@@ -137,11 +163,7 @@ def start_application_lock_renewal(cls, redis: aioredis.Redis) -> asyncio.Task:
@classmethod
async def stop_application_lock_renewal(cls) -> None:
- """
- 停止当前进程的Application leader租约续期任务。
-
- :return: None
- """
+ """停止当前进程的Application leader租约续期任务。"""
renewal_task = cls._application_lock_renewal_task
cls._application_lock_renewal_task = None
if not renewal_task or renewal_task.done():
@@ -155,10 +177,9 @@ async def stop_application_lock_renewal(cls) -> None:
@classmethod
async def _start_scheduler_as_leader(cls, redis: aioredis.Redis) -> None:
"""
- 以 Leader 身份启动 Scheduler(内部方法,调用前需确保已持有锁)
+ 以 Leader 身份启动 Scheduler(内部方法,调用前需确保已持有锁)。
:param redis: Redis连接对象
- :return: None
"""
cls._is_leader = True
logger.info(f'🎯 Worker {cls._worker_id} 持有 Application 锁,开始启动定时任务...')
@@ -207,7 +228,7 @@ async def _activate_scheduler_as_leader(cls, redis: aioredis.Redis) -> None:
Application leader身份。
:param redis: Redis连接对象
- :return: None
+ :raises Exception: 底层操作失败时向调用方传播异常
"""
cls.start_application_lock_renewal(redis)
try:
@@ -227,11 +248,7 @@ async def _activate_scheduler_as_leader(cls, redis: aioredis.Redis) -> None:
@classmethod
def on_lock_lost(cls) -> None:
- """
- 锁丢失处理入口
-
- :return: None
- """
+ """锁丢失处理入口。"""
if not cls._is_leader:
return
cls._is_leader = False
@@ -242,11 +259,7 @@ def on_lock_lost(cls) -> None:
@classmethod
async def _handle_lock_lost(cls) -> None:
- """
- 处理锁丢失后的资源释放
-
- :return: None
- """
+ """处理锁丢失后的资源释放。"""
if cls._sync_listener_task:
cls._sync_listener_task.cancel()
try:
@@ -269,11 +282,7 @@ async def _handle_lock_lost(cls) -> None:
@classmethod
def _ensure_reacquire_task(cls) -> None:
- """
- 启动锁重新竞争任务
-
- :return: None
- """
+ """启动锁重新竞争任务。"""
if cls._is_closing or not cls._redis:
return
if cls._reacquire_task and not cls._reacquire_task.done():
@@ -283,7 +292,7 @@ def _ensure_reacquire_task(cls) -> None:
@classmethod
def _get_reacquire_delay(cls) -> float:
"""
- 获取带随机抖动的锁重新竞争间隔
+ 获取带随机抖动的锁重新竞争间隔。
:return: 重新竞争等待秒数
"""
@@ -292,9 +301,9 @@ def _get_reacquire_delay(cls) -> float:
@classmethod
async def _run_reacquire_loop(cls) -> None:
"""
- 循环尝试重新获取锁并恢复调度器
+ 循环尝试重新获取锁并恢复调度器。
- :return: None
+ :raises asyncio.CancelledError: 异步操作被取消时
"""
try:
while not cls._is_leader and not cls._is_closing:
@@ -327,11 +336,7 @@ async def _run_reacquire_loop(cls) -> None:
@classmethod
async def close_system_scheduler(cls) -> None:
- """
- 应用关闭时关闭定时任务
-
- :return: None
- """
+ """应用关闭时关闭定时任务。"""
cls._is_closing = True
await cls.stop_application_lock_renewal()
if cls._sync_listener_task:
@@ -390,7 +395,7 @@ async def request_scheduler_sync(
immediate: bool = False,
) -> dict[str, Any]:
"""
- 请求调度器同步任务状态
+ 请求调度器同步任务状态。
:param job_ids: 指定受影响任务,None 表示完整校准
:param immediate: Leader 是否在返回前完成本地同步
@@ -425,11 +430,7 @@ async def request_scheduler_sync(
@classmethod
def _ensure_sync_task(cls) -> None:
- """
- 启动同步调度任务
-
- :return: None
- """
+ """启动同步调度任务。"""
if cls._sync_task and not cls._sync_task.done():
return
cls._sync_task = asyncio.create_task(cls._run_sync_loop())
@@ -437,9 +438,9 @@ def _ensure_sync_task(cls) -> None:
@classmethod
async def _run_sync_loop(cls) -> None:
"""
- 执行同步调度循环
+ 执行同步调度循环。
- :return: None
+ :raises asyncio.CancelledError: 异步操作被取消时
"""
try:
while True:
@@ -454,11 +455,7 @@ async def _run_sync_loop(cls) -> None:
@classmethod
async def _sync_with_throttle(cls) -> None:
- """
- 按节流规则执行同步
-
- :return: None
- """
+ """按节流规则执行同步。"""
async with cls._sync_lock:
if not cls._is_leader:
return
@@ -478,10 +475,10 @@ async def _sync_with_throttle(cls) -> None:
@classmethod
async def _listen_sync_channel(cls, redis: aioredis.Redis) -> None:
"""
- 监听同步请求通道
+ 监听同步请求通道。
:param redis: Redis连接对象
- :return: None
+ :raises asyncio.CancelledError: 异步操作被取消时
"""
while True:
pubsub = redis.pubsub()
@@ -510,10 +507,9 @@ async def _listen_sync_channel(cls, redis: aioredis.Redis) -> None:
@classmethod
async def _handle_sync_notification(cls, data: str | bytes) -> None:
"""
- 解析唤醒通知;实际配置和执行请求均重新从数据库读取
+ 解析唤醒通知;实际配置和执行请求均重新从数据库读取。
:param data: 同步通知数据
- :return: None
"""
try:
payload = json.loads(data)
@@ -530,11 +526,7 @@ async def _handle_sync_notification(cls, data: str | bytes) -> None:
@classmethod
async def request_execution_dispatch(cls) -> None:
- """
- 唤醒 Leader 处理持久化执行请求,通知失败由周期派发恢复
-
- :return: None
- """
+ """唤醒 Leader 处理持久化执行请求,通知失败由周期派发恢复。"""
try:
if cls._is_leader:
await cls._drain_execution_requests()
@@ -545,11 +537,7 @@ async def request_execution_dispatch(cls) -> None:
@classmethod
def _configure_scheduler(cls) -> None:
- """
- 配置当前调度器的任务存储、执行器和事件回调
-
- :return: None
- """
+ """配置当前调度器的任务存储、执行器和事件回调。"""
cls._resources.configure(cls._scheduler, cls.scheduler_event_listener)
@classmethod
@@ -557,7 +545,7 @@ async def _sync_jobs_from_database(
cls, job_ids: set[int] | None = None, *, raise_errors: bool = False
) -> dict[str, Any]:
"""
- 调用配置同步功能类校准数据库任务
+ 调用配置同步功能类校准数据库任务。
:param job_ids: 指定任务ID,None表示完整校准
:param raise_errors: 是否向调用方抛出完整扫描异常
@@ -569,27 +557,22 @@ async def _sync_jobs_from_database(
@classmethod
async def _drain_execution_requests(cls) -> None:
- """
- 调用执行派发功能类处理已持久化的执行请求
-
- :return: None
- """
+ """调用执行派发功能类处理已持久化的执行请求。"""
await cls._dispatcher.dispatch_pending(is_leader=cls.is_application_leader)
@classmethod
def scheduler_event_listener(cls, event: SchedulerEvent) -> None:
"""
- 调用日志功能类记录任务执行事件
+ 调用日志功能类记录任务执行事件。
:param event: 调度器产生的执行事件
- :return: None
"""
cls._listener.handle_event(event)
@staticmethod
def _prepare_scheduler_job_add(job_info: JobModel) -> dict[str, Any]:
"""
- 校验任务配置并构造注册参数
+ 校验任务配置并构造注册参数。
:param job_info: 任务配置
:return: 调度器任务注册参数
@@ -599,7 +582,7 @@ def _prepare_scheduler_job_add(job_info: JobModel) -> dict[str, Any]:
@classmethod
def get_scheduler_job(cls, job_id: str | int) -> Job | None:
"""
- 获取当前进程的调度任务
+ 获取当前进程的调度任务。
:param job_id: 任务ID
:return: 调度任务,不存在时返回None
@@ -609,10 +592,9 @@ def get_scheduler_job(cls, job_id: str | int) -> Job | None:
@classmethod
def add_scheduler_job(cls, job_info: JobModel) -> None:
"""
- 在Leader进程中注册任务
+ 在Leader进程中注册任务。
:param job_info: 任务配置
- :return: None
"""
if cls._is_leader:
cls._jobs.add_job(job_info)
@@ -620,10 +602,9 @@ def add_scheduler_job(cls, job_info: JobModel) -> None:
@classmethod
def remove_scheduler_job(cls, job_id: str | int) -> None:
"""
- 在Leader进程中移除任务
+ 在Leader进程中移除任务。
:param job_id: 任务ID
- :return: None
"""
if cls._is_leader:
cls._jobs.remove_job(job_id)
@@ -631,12 +612,12 @@ def remove_scheduler_job(cls, job_id: str | int) -> None:
@classmethod
def execute_scheduler_job_once(cls, job_info: JobModel, *, execution_id: str, dispatch_token: str) -> None:
"""
- 在Leader进程中注册已领取的单次执行请求
+ 在Leader进程中注册已领取的单次执行请求。
:param job_info: 任务配置
:param execution_id: 已持久化的执行请求ID
:param dispatch_token: 本次派发的领取凭据
- :return: None
+ :raises RuntimeError: 仅 Leader 可以派发已领取的执行请求
"""
if not cls._is_leader:
raise RuntimeError('仅 Leader 可以派发已领取的执行请求')
diff --git a/ruoyi-fastapi-backend/config/scheduler/resources.py b/ruoyi-fastapi-backend/config/scheduler/resources.py
index 8a97be9ef..79d21b3f1 100644
--- a/ruoyi-fastapi-backend/config/scheduler/resources.py
+++ b/ruoyi-fastapi-backend/config/scheduler/resources.py
@@ -27,15 +27,17 @@
class SchedulerResources:
"""
- 调度器存储、执行器和数据库资源管理
+ 调度器存储、执行器和数据库资源管理。
+
+ :ivar _jobstore_engine: 用于持久化任务的数据库引擎
+ :ivar _listener_engine: 监听器访问数据库时使用的引擎
+ :ivar _session_local: 创建本地数据库会话的工厂
+ :ivar _configured: 是否已完成资源配置
+ :ivar _disposed: 是否已释放底层资源
"""
def __init__(self) -> None:
- """
- 初始化当前进程的调度资源引用,数据库引擎按需创建
-
- :return: None
- """
+ """初始化当前进程的调度资源引用,数据库引擎按需创建。"""
self._jobstore_engine: Engine | None = None
self._listener_engine: Engine | None = None
self._session_local: sessionmaker[Session] | None = None
@@ -44,7 +46,7 @@ def __init__(self) -> None:
def jobstore_engine(self) -> Engine:
"""
- 懒加载获取 jobstore 使用的同步 Engine
+ 懒加载获取 jobstore 使用的同步 Engine。
:return: 同步 Engine
"""
@@ -55,7 +57,7 @@ def jobstore_engine(self) -> Engine:
def listener_engine(self) -> Engine:
"""
- 懒加载获取 listener 使用的同步 Engine
+ 懒加载获取 listener 使用的同步 Engine。
:return: 同步 Engine
"""
@@ -65,9 +67,9 @@ def listener_engine(self) -> Engine:
def log_session_factory(self) -> sessionmaker[Session]:
"""
- 懒加载获取同步 SessionLocal
+ 懒加载获取同步 SessionLocal。
- :return: SessionLocal
+ :return: 用于创建数据库会话的工厂
"""
if self._session_local is None:
self._session_local = sessionmaker(
@@ -79,11 +81,10 @@ def log_session_factory(self) -> sessionmaker[Session]:
def configure(self, scheduler: AsyncIOScheduler, on_event: Callable[[SchedulerEvent], None]) -> None:
"""
- 配置 scheduler(懒加载 jobstore)
+ 配置 scheduler(懒加载 jobstore)。
:param scheduler: 当前进程的调度器
:param on_event: 任务执行事件回调
- :return: None
"""
if self._configured:
return
@@ -103,7 +104,7 @@ def configure(self, scheduler: AsyncIOScheduler, on_event: Callable[[SchedulerEv
@staticmethod
def session() -> AbstractAsyncContextManager[AsyncSession]:
"""
- 获取内部调度使用的异步 Session,过滤轮询和事务的常规SQL日志
+ 获取内部调度使用的异步 Session,过滤轮询和事务的常规SQL日志。
:return: 异步 Session
"""
@@ -111,11 +112,7 @@ def session() -> AbstractAsyncContextManager[AsyncSession]:
return DataSourceRegistry.session(DataBaseConfig.db_default_source, log_sql=False)
def dispose(self) -> None:
- """
- 释放 Scheduler 使用的同步 Engine
-
- :return: None
- """
+ """释放 Scheduler 使用的同步 Engine。"""
if self._disposed:
return
self._configured = False
diff --git a/ruoyi-fastapi-backend/config/scheduler/synchronization.py b/ruoyi-fastapi-backend/config/scheduler/synchronization.py
index d58dd07f0..5c4084cf3 100644
--- a/ruoyi-fastapi-backend/config/scheduler/synchronization.py
+++ b/ruoyi-fastapi-backend/config/scheduler/synchronization.py
@@ -12,16 +12,19 @@
class SchedulerSynchronizer:
"""
- 数据库任务配置校准和已应用版本管理
+ 数据库任务配置校准和已应用版本管理。
+
+ :ivar jobs: 本地任务管理器
+ :ivar resources: 调度数据库资源
+ :ivar applied_jobs: 当前已同步到调度器的任务
"""
def __init__(self, jobs: SchedulerJobs, resources: SchedulerResources) -> None:
"""
- 初始化配置同步所需的任务管理器和数据库资源
+ 初始化配置同步所需的任务管理器和数据库资源。
:param jobs: 本地任务管理器
:param resources: 调度数据库资源
- :return: None
"""
self.jobs = jobs
self.resources = resources
@@ -41,6 +44,7 @@ async def sync_jobs(
:param is_leader: 检查当前进程是否仍持有Leader租约
:param raise_errors: 完整扫描失败时是否阻止调度器启动
:return: 每个任务的应用结果及总体同步状态
+ :raises Exception: 同步任务失败且调用方要求传播错误
"""
if not is_leader():
return self.result(
@@ -95,7 +99,7 @@ async def sync_jobs(
async def sync_job(self, job_id: int, *, is_leader: Callable[[], bool]) -> dict[str, Any]:
"""
- 锁定并应用一个任务的最新配置,独立保存成功或失败状态
+ 锁定并应用一个任务的最新配置,独立保存成功或失败状态。
:param job_id: 任务ID
:param is_leader: 检查当前进程是否仍持有Leader租约
@@ -148,7 +152,7 @@ async def sync_job(self, job_id: int, *, is_leader: Callable[[], bool]) -> dict[
@staticmethod
def result(jobs: list[dict[str, Any]], *, default: str = 'applied') -> dict[str, Any]:
"""
- 汇总逐任务结果,失败和待同步状态不会被当成全部生效
+ 汇总逐任务结果,失败和待同步状态不会被当成全部生效。
:param jobs: 各任务的同步结果
:param default: 没有任务结果时使用的同步状态
diff --git a/ruoyi-fastapi-backend/config/scheduler/triggers.py b/ruoyi-fastapi-backend/config/scheduler/triggers.py
index b91abea7e..57be7d94f 100644
--- a/ruoyi-fastapi-backend/config/scheduler/triggers.py
+++ b/ruoyi-fastapi-backend/config/scheduler/triggers.py
@@ -5,7 +5,13 @@
class TaskDateTrigger(DateTrigger):
"""
- 携带任务原始时区的单次触发器
+ 携带任务原始时区的单次触发器。
+
+ :ivar task_timezone: 任务原始IANA时区名称
+ :ivar task_job_id: 关联的逻辑任务ID
+ :ivar task_job_group: 业务分组快照
+ :ivar execution_id: 执行ID
+ :ivar dispatch_token: 本次派发的领取凭据
"""
def __init__(
@@ -19,7 +25,7 @@ def __init__(
**kwargs,
) -> None:
"""
- 初始化保留任务时区的单次触发器
+ 初始化保留任务时区的单次触发器。
:param task_timezone: 任务原始IANA时区名称
:param task_job_id: 关联的逻辑任务ID
@@ -27,7 +33,6 @@ def __init__(
:param execution_id: 执行ID
:param dispatch_token: 本次派发的领取凭据
:param kwargs: 传递给DateTrigger的执行时刻及其他配置
- :return: None
"""
super().__init__(**kwargs)
self.task_timezone = task_timezone
@@ -38,7 +43,7 @@ def __init__(
def __getstate__(self) -> dict[str, Any]:
"""
- 序列化单次触发器及任务时区
+ 序列化单次触发器及任务时区。
:return: 可供持久化任务仓库存储的触发器状态
"""
@@ -53,10 +58,9 @@ def __getstate__(self) -> dict[str, Any]:
def __setstate__(self, state: dict[str, Any]) -> None:
"""
- 从持久化状态恢复触发器和任务时区
+ 从持久化状态恢复触发器和任务时区。
:param state: 已序列化的触发器状态
- :return: None
"""
super().__setstate__(state)
self.task_timezone = state['task_timezone']
@@ -68,7 +72,7 @@ def __setstate__(self, state: dict[str, Any]) -> None:
def trigger_timezone(trigger: Any) -> str | None:
"""
- 读取触发器携带的任务时区
+ 读取触发器携带的任务时区。
:param trigger: Cron、单次或组合触发器
:return: 任务时区名称,未携带时区时返回None
diff --git a/ruoyi-fastapi-backend/docs/cli_usage.md b/ruoyi-fastapi-backend/docs/cli_usage.md
index faff79ff6..928e93660 100644
--- a/ruoyi-fastapi-backend/docs/cli_usage.md
+++ b/ruoyi-fastapi-backend/docs/cli_usage.md
@@ -543,11 +543,47 @@ ruoyi dev test tests --output=json
说明:
-- `dev lint` 默认顺序是先执行 `ruff format`,再执行 `ruff check`
+- `dev lint` 依次运行 Ruff 格式化、静态检查和项目文档规范检查。CLI 和 CI 共用 `scripts/check_docstrings.py` 校验 reST 文档、模型字段和 HTTP 路由说明。在后端目录执行 `python scripts/check_docstrings.py .` 可单独运行这项检查。
- `--check-only` 会改成只检查,不写回
- `--fix` 会执行 `ruff check --fix`
- `dev test` 通过当前环境的 `python -m pytest` 执行测试
+#### Python 文档字符串
+
+Python 文件顶部禁止说明性 `#` 注释和模块 docstring。首行 shebang 和 Python 识别的编码声明可以保留。类、方法和函数实现使用 Sphinx/reStructuredText docstring,包括私有成员、嵌套定义和异步函数。使用 `@overload` 的函数在具体实现上统一写文档。[Ruff 重载文档规则](https://docs.astral.sh/ruff/rules/overload-with-docstring/)
+
+摘要、说明段落、接口字段的描述和普通 `#` 注释使用中文,可以混用英文术语和标识符。类型表达式、代码示例和工具指令保留原样。单行 docstring 的摘要与引号同一行。所有多行 docstring 的起始三引号独占首行,摘要从第二行开始,以句末标点结束。正文或字段与摘要之间空一行。项目通过 Ruff 的 D213 检查多行摘要的位置。[Ruff D213](https://docs.astral.sh/ruff/rules/multi-line-summary-second-line/)
+
+函数在 `:param 名称:` 中逐项说明显式参数的用途,包括仅限位置、仅限关键字和可变参数,省略绑定方法的隐式首参。普通类用 `:ivar 名称:` 说明实例属性,用 `:cvar 名称:` 说明类属性。同名属性和构造参数分别写在类和 `__init__` 的文档中。带有自身 docstring 的 `@property` 在访问器上说明即可。类型注解和 `:type:`、`:vartype:` 字段可补充类型信息。字段续行要缩进。[Sphinx Python 域](https://www.sphinx-doc.org/en/master/usage/domains/python.html#info-field-lists)
+
+- 有返回值的函数用 `:return:` 说明调用方获得什么。无返回值的函数可省略该字段。
+- 同步和异步生成器用项目约定的 reST 字段 `:yield:` 说明每次产生什么。同步生成器若还有最终返回值,另写 `:return:`。
+- 对当前函数显式抛出并传给调用方的异常,用 `:raises 异常类型:` 说明触发条件。检查器区分本地捕获和重新抛出,按词法作用域独立检查嵌套函数。
+
+- 每次注册 FastAPI HTTP 路径操作都必须显式提供含中文的 `summary` 和 `description`。摘要写接口做什么,描述补充输入、效果或返回内容。此规则适用于 HTTP 装饰器、`api_route` 和 `add_api_route`,包括 `include_in_schema=False` 的接口。同一函数注册到多条路径时逐条检查。路由函数可省略 docstring 和参数说明。WebSocket 和 Starlette 原生 `route`、`add_route` 使用框架各自的注册参数。[FastAPI 路径操作配置](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#summary-and-description)
+- pytest 收集的测试函数和测试方法只写测试意图,出现参数、类型、返回值、生成值或异常等接口字段会报错。夹具和测试辅助函数遵循普通函数规则。
+- Pydantic 模型(含派生模型和配置模型)的字段必须提供含中文的 `description`,例如 `name: str = Field(description='用户名称')`。也可通过 `Annotated` 声明。计算字段在装饰器上填写说明,例如 `@computed_field(description='记录总数')`。私有属性、`ClassVar` 和 `model_config` 免检。
+- SQLAlchemy 映射列必须提供含中文的 `comment`,例如 `id: Mapped[int] = mapped_column(primary_key=True, comment='用户标识')`。同样检查 `Table` 中显式声明的 `Column` 和混入类声明的列。`relationship` 等关系属性免写列说明。
+- 两类模型及其普通方法仍需中文 reST 文档。字段说明写在模型声明处,派生类直接继承的字段沿用基类的说明,类文档无需重复写 `:ivar:`。
+- 检查器会拒绝缺失的说明、空白或纯英文的字符串字面量,也会解析同一作用域中的字符串常量。通过运行时表达式提供的说明,以模型最终的字段元数据为准。
+- `alembic/env.py` 和 `common/router.py` 中的 `APIRouterPro` 保留原有文档。同一文件中的 `RouterRegister` 遵循普通类规则。
+
+```python
+def positive_count(value: int) -> int:
+ """
+ 校验数量为正整数。
+
+ :param value: 待校验的数量
+ :return: 已校验的数量
+ :raises ValueError: 数量小于 1
+ """
+ if value < 1:
+ raise ValueError('数量必须大于零')
+ return value
+```
+
+行内代码使用双反引号,对 Python 对象的引用可使用 `:py:class:` 等角色。代码示例使用 `::` 或 `.. code-block:: python` 引出缩进的代码块。运行 `ruoyi dev lint 路径 --check-only` 可查看 Ruff 排版检查、Sphinx/reST 解析诊断及 API 字段风格违规的源码位置。检查使用 Sphinx 内置角色和指令,代码块内可以展示其他文档格式。[Sphinx reST 入门](https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html)
+
### 5.10 `completion`
用于生成、安装和诊断 shell completion。
diff --git a/ruoyi-fastapi-backend/exceptions/exception.py b/ruoyi-fastapi-backend/exceptions/exception.py
index d4d093ab1..3a211a2c3 100644
--- a/ruoyi-fastapi-backend/exceptions/exception.py
+++ b/ruoyi-fastapi-backend/exceptions/exception.py
@@ -4,7 +4,12 @@
class LoginException(Exception):
"""
- 自定义登录异常LoginException
+ 自定义登录异常LoginException。
+
+ :ivar data: 随异常返回的业务数据
+ :ivar message: 异常消息原文
+ :ivar msg_key: 响应阶段使用的消息标识
+ :ivar msg_params: 可在响应中公开的插值参数
"""
def __init__(
@@ -19,7 +24,7 @@ def __init__(
plural_key: str | None = None,
) -> None:
"""
- 保存登录校验失败时的消息原文和翻译参数
+ 保存登录校验失败时的消息原文和翻译参数。
:param data: 随异常返回的业务数据
:param message: 异常消息原文
@@ -46,7 +51,12 @@ def __init__(
class AuthException(Exception):
"""
- 自定义令牌异常AuthException
+ 自定义令牌异常AuthException。
+
+ :ivar data: 随异常返回的业务数据
+ :ivar message: 异常消息原文
+ :ivar msg_key: 响应阶段使用的消息标识
+ :ivar msg_params: 可在响应中公开的插值参数
"""
def __init__(
@@ -61,7 +71,7 @@ def __init__(
plural_key: str | None = None,
) -> None:
"""
- 保存令牌认证失败时的消息原文和翻译参数
+ 保存令牌认证失败时的消息原文和翻译参数。
:param data: 随异常返回的业务数据
:param message: 异常消息原文
@@ -92,6 +102,17 @@ class OAuthProtocolException(Exception):
异常 message 和字符串表示使用中文,error_description 保持 OAuth 要求的 ASCII 格式。
统一异常处理器仅返回标准协议字段和经过验证的重定向状态,不回传内部诊断详情。
+
+ :cvar _DEFAULT_BAD_REQUEST_STATUS: 无其他协议状态时返回的 HTTP 错误码
+ :ivar error: 发生错误时返回的错误信息
+ :ivar error_description: 返回给调用方的错误说明
+ :ivar message: 异常消息原文
+ :ivar status_code: 响应使用的 HTTP 状态码
+ :ivar redirect_uri: 已注册的授权回调地址
+ :ivar state: 当前流程的状态
+ :ivar redirect_uri_verified: 重定向地址是否已通过客户端注册信息校验
+ :ivar issuer: 签发令牌的身份提供方标识
+ :ivar headers: 响应或请求携带的 HTTP 头
"""
_DEFAULT_BAD_REQUEST_STATUS = 400
@@ -108,6 +129,18 @@ def __init__(
issuer: str | None = None,
headers: dict[str, str] | None = None,
) -> None:
+ """
+ 保存 OAuth 错误码、协议描述及本地化消息。
+
+ :param error: 发生错误时返回的错误信息
+ :param error_description: 返回给调用方的错误说明
+ :param status_code: 响应使用的 HTTP 状态码
+ :param redirect_uri: 已注册的授权回调地址
+ :param state: 当前流程的状态
+ :param redirect_uri_verified: 重定向地址是否已通过客户端注册信息校验
+ :param issuer: 签发令牌的身份提供方标识
+ :param headers: 响应或请求携带的 HTTP 头
+ """
self.error = error
self.error_description = OidcUtil.protocol_error_description(error, error_description)
self.message = OidcUtil.localized_oauth_message(error, error_description)
@@ -160,6 +193,14 @@ class OidcInteractionException(Exception):
交互异常不默认跳转到外部地址;只有 Interaction 已绑定并验证了 Client
Redirect URI 时,调用方才可将其转换为 ``OAuthProtocolException``。
+
+ :ivar interaction_id: 认证交互标识
+ :ivar message: 异常消息原文
+ :ivar error: 发生错误时返回的错误信息
+ :ivar status_code: 响应使用的 HTTP 状态码
+ :ivar redirect_uri: 已注册的授权回调地址
+ :ivar state: 当前流程的状态
+ :ivar redirect_uri_verified: 重定向地址是否已通过客户端注册信息校验
"""
def __init__(
@@ -173,6 +214,17 @@ def __init__(
state: str | None = None,
redirect_uri_verified: bool = False,
) -> None:
+ """
+ 保存交互错误及继续处理所需的重定向状态。
+
+ :param interaction_id: 认证交互标识
+ :param message: 异常消息原文
+ :param error: 发生错误时返回的错误信息
+ :param status_code: 响应使用的 HTTP 状态码
+ :param redirect_uri: 已注册的授权回调地址
+ :param state: 当前流程的状态
+ :param redirect_uri_verified: 重定向地址是否已通过客户端注册信息校验
+ """
self.interaction_id = interaction_id
self.message = message or '认证交互无效或已过期'
self.error = error
@@ -209,7 +261,12 @@ def as_protocol_exception(self) -> OAuthProtocolException:
class PermissionException(Exception):
"""
- 自定义权限异常PermissionException
+ 自定义权限异常PermissionException。
+
+ :ivar data: 随异常返回的业务数据
+ :ivar message: 异常消息原文
+ :ivar msg_key: 响应阶段使用的消息标识
+ :ivar msg_params: 可在响应中公开的插值参数
"""
def __init__(
@@ -224,7 +281,7 @@ def __init__(
plural_key: str | None = None,
) -> None:
"""
- 保存权限校验失败时的消息原文和翻译参数
+ 保存权限校验失败时的消息原文和翻译参数。
:param data: 随异常返回的业务数据
:param message: 异常消息原文
@@ -251,7 +308,12 @@ def __init__(
class ServiceException(Exception):
"""
- 自定义服务异常ServiceException
+ 自定义服务异常ServiceException。
+
+ :ivar data: 随异常返回的业务数据
+ :ivar message: 异常消息原文
+ :ivar msg_key: 响应阶段使用的消息标识
+ :ivar msg_params: 可在响应中公开的插值参数
"""
def __init__(
@@ -266,7 +328,7 @@ def __init__(
plural_key: str | None = None,
) -> None:
"""
- 保存业务处理失败时的消息原文和翻译参数
+ 保存业务处理失败时的消息原文和翻译参数。
:param data: 随异常返回的业务数据
:param message: 异常消息原文
@@ -293,7 +355,12 @@ def __init__(
class ServiceWarning(Exception):
"""
- 自定义服务警告ServiceWarning
+ 自定义服务警告ServiceWarning。
+
+ :ivar data: 随异常返回的业务数据
+ :ivar message: 异常消息原文
+ :ivar msg_key: 响应阶段使用的消息标识
+ :ivar msg_params: 可在响应中公开的插值参数
"""
def __init__(
@@ -308,7 +375,7 @@ def __init__(
plural_key: str | None = None,
) -> None:
"""
- 保存需要提示用户的业务情况时的消息原文和翻译参数
+ 保存需要提示用户的业务情况时的消息原文和翻译参数。
:param data: 随异常返回的业务数据
:param message: 异常消息原文
@@ -335,16 +402,28 @@ def __init__(
class FileRangeNotSatisfiableException(Exception):
"""
- 文件Range范围不可满足异常
+ 文件Range范围不可满足异常。
+
+ :ivar file_size: 文件大小
"""
def __init__(self, file_size: int) -> None:
+ """
+ 记录无法满足范围请求的文件大小。
+
+ :param file_size: 文件大小
+ """
self.file_size = file_size
class ModelValidatorException(Exception):
"""
- 自定义模型校验异常ModelValidatorException
+ 自定义模型校验异常ModelValidatorException。
+
+ :ivar data: 随异常返回的业务数据
+ :ivar message: 异常消息原文
+ :ivar msg_key: 响应阶段使用的消息标识
+ :ivar msg_params: 可在响应中公开的插值参数
"""
def __init__(
@@ -359,7 +438,7 @@ def __init__(
plural_key: str | None = None,
) -> None:
"""
- 保存模型校验失败时的消息原文和翻译参数
+ 保存模型校验失败时的消息原文和翻译参数。
:param data: 随异常返回的业务数据
:param message: 异常消息原文
@@ -386,9 +465,13 @@ def __init__(
class DataSourceException(ServiceException):
"""
- 自定义数据源异常DataSourceException
+ 自定义数据源异常DataSourceException。
对外异常信息仅包含数据源名称,内部诊断字段仅保留异常类型和数字错误码。
+
+ :ivar source_name: 数据源名称
+ :ivar error_type: 用于区分失败原因的类型
+ :ivar error_code: 数字错误码
"""
def __init__(
@@ -399,6 +482,14 @@ def __init__(
error_type: str | None = None,
error_code: int | None = None,
) -> None:
+ """
+ 保存发生异常的数据源名称及错误详情。
+
+ :param source_name: 数据源名称
+ :param message: 异常消息原文
+ :param error_type: 用于区分失败原因的类型
+ :param error_code: 数字错误码
+ """
self.source_name = source_name
self.error_type = error_type
self.error_code = error_code
@@ -406,18 +497,19 @@ def __init__(
class DataSourceNotFoundException(DataSourceException):
- """
- 自定义数据源未配置异常DataSourceNotFoundException
- """
+ """自定义数据源未配置异常DataSourceNotFoundException。"""
def __init__(self, source_name: str) -> None:
+ """
+ 记录缺少配置的数据源名称。
+
+ :param source_name: 数据源名称
+ """
super().__init__(source_name, message=f'数据源未配置:{source_name}')
class DataSourceUnavailableException(DataSourceException):
- """
- 自定义数据源不可用异常DataSourceUnavailableException
- """
+ """自定义数据源不可用异常DataSourceUnavailableException。"""
def __init__(
self,
@@ -426,6 +518,13 @@ def __init__(
error_type: str | None = None,
error_code: int | None = None,
) -> None:
+ """
+ 记录不可用的数据源及其错误类型。
+
+ :param source_name: 数据源名称
+ :param error_type: 用于区分失败原因的类型
+ :param error_code: 数字错误码
+ """
super().__init__(
source_name,
message=f'数据源暂不可用:{source_name}',
@@ -435,9 +534,7 @@ def __init__(
class DataSourceInitializationException(DataSourceException):
- """
- 自定义数据源初始化异常DataSourceInitializationException
- """
+ """自定义数据源初始化异常DataSourceInitializationException。"""
def __init__(
self,
@@ -446,6 +543,13 @@ def __init__(
error_type: str | None = None,
error_code: int | None = None,
) -> None:
+ """
+ 记录初始化失败的数据源及其错误类型。
+
+ :param source_name: 数据源名称
+ :param error_type: 用于区分失败原因的类型
+ :param error_code: 数字错误码
+ """
super().__init__(
source_name,
message=f'数据源初始化失败:{source_name}',
diff --git a/ruoyi-fastapi-backend/exceptions/handle.py b/ruoyi-fastapi-backend/exceptions/handle.py
index fcb334736..d247913bb 100644
--- a/ruoyi-fastapi-backend/exceptions/handle.py
+++ b/ruoyi-fastapi-backend/exceptions/handle.py
@@ -33,17 +33,33 @@
def handle_exception(app: FastAPI) -> None:
"""
- 全局异常处理
+ 全局异常处理。
+
+ :param app: 正在配置或处理请求的 ASGI 应用
"""
# 自定义token检验异常
@app.exception_handler(AuthException)
async def auth_exception_handler(request: Request, exc: AuthException) -> Response:
+ """
+ 将身份认证异常转换为对应的 HTTP 响应。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: 认证失败时的 HTTP 响应
+ """
return ResponseUtil.unauthorized(data=exc.data, msg=exc.message, msg_key=exc.msg_key, msg_params=exc.msg_params)
# 自定义OAuth协议异常
@app.exception_handler(OAuthProtocolException)
async def oauth_protocol_exception_handler(request: Request, exc: OAuthProtocolException) -> Response:
+ """
+ 将OAuth 协议错误转换为对应的 HTTP 响应。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: OAuth 协议错误响应或安全重定向
+ """
if exc.can_redirect:
return _build_oauth_redirect(exc)
headers = {**exc.headers, 'Cache-Control': 'no-store', 'Pragma': 'no-cache'}
@@ -58,6 +74,13 @@ async def oauth_protocol_exception_handler(request: Request, exc: OAuthProtocolE
# 自定义OIDC认证交互异常
@app.exception_handler(OidcInteractionException)
async def oidc_interaction_exception_handler(request: Request, exc: OidcInteractionException) -> Response:
+ """
+ 将OIDC 交互异常转换为对应的 HTTP 响应。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: OIDC 交互失败的 HTTP 响应
+ """
safe_message = {
'invalid_request': I18nMessage('认证交互请求无效', msg_key='identity.interaction.invalidRequest'),
'interaction_required': I18nMessage('认证交互已过期或不可用', msg_key='identity.interaction.unavailable'),
@@ -75,34 +98,76 @@ async def oidc_interaction_exception_handler(request: Request, exc: OidcInteract
# 自定义登录检验异常
@app.exception_handler(LoginException)
async def login_exception_handler(request: Request, exc: LoginException) -> Response:
+ """
+ 将登录异常转换为对应的 HTTP 响应。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: 登录失败的 HTTP 响应
+ """
return ResponseUtil.failure(data=exc.data, msg=exc.message, msg_key=exc.msg_key, msg_params=exc.msg_params)
# 自定义模型检验异常
@app.exception_handler(ModelValidatorException)
async def model_validator_exception_handler(request: Request, exc: ModelValidatorException) -> Response:
+ """
+ 将模型校验异常转换为对应的 HTTP 响应。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: 包含模型校验错误的响应
+ """
logger.warning(exc.message)
return ResponseUtil.failure(data=exc.data, msg=exc.message, msg_key=exc.msg_key, msg_params=exc.msg_params)
# 自定义字段检验异常
@app.exception_handler(FieldValidationError)
async def field_validation_error_handler(request: Request, exc: FieldValidationError) -> Response:
+ """
+ 将字段校验失败转换为接口错误响应。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: 包含字段错误信息的响应
+ """
logger.warning(exc.message)
return ResponseUtil.failure(msg=exc.message)
# 自定义权限检验异常
@app.exception_handler(PermissionException)
async def permission_exception_handler(request: Request, exc: PermissionException) -> Response:
+ """
+ 将权限异常转换为对应的 HTTP 响应。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: 权限不足的响应
+ """
return ResponseUtil.forbidden(data=exc.data, msg=exc.message, msg_key=exc.msg_key, msg_params=exc.msg_params)
# 自定义服务异常
@app.exception_handler(ServiceException)
async def service_exception_handler(request: Request, exc: ServiceException) -> Response:
+ """
+ 将业务异常转换为对应的 HTTP 响应。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: 包含业务错误详情的响应
+ """
logger.error(exc.message)
return ResponseUtil.error(data=exc.data, msg=exc.message, msg_key=exc.msg_key, msg_params=exc.msg_params)
# 自定义服务警告
@app.exception_handler(ServiceWarning)
async def service_warning_handler(request: Request, exc: ServiceWarning) -> Response:
+ """
+ 返回业务提示及其关联数据。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: 业务提示及其关联数据
+ """
logger.warning(exc.message)
return ResponseUtil.failure(data=exc.data, msg=exc.message, msg_key=exc.msg_key, msg_params=exc.msg_params)
@@ -112,6 +177,13 @@ async def file_range_not_satisfiable_exception_handler(
request: Request,
exc: FileRangeNotSatisfiableException,
) -> Response:
+ """
+ 将无效的文件范围请求转换为对应的 HTTP 响应。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: ``Response`` 实例
+ """
return Response(
status_code=416,
headers={
@@ -124,7 +196,11 @@ async def file_range_not_satisfiable_exception_handler(
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> Response:
"""
- 按请求语言本地化参数校验消息,保留字段位置和错误类型
+ 按请求语言本地化参数校验消息,保留字段位置和错误类型。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: ``JSONResponse`` 实例
"""
details = [ValidationMessageUtil.localize(error) for error in exc.errors()]
return JSONResponse(status_code=422, content={'detail': details})
@@ -132,6 +208,13 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
# 处理其他http请求异常
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException) -> Response:
+ """
+ 将HTTP 异常转换为对应的 HTTP 响应。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: ``JSONResponse`` 实例
+ """
fields = I18nUtil.message_fields(exc.detail) if isinstance(exc.detail, I18nMessage) else {'msg': exc.detail}
return JSONResponse(
content=jsonable_encoder({'code': exc.status_code, **fields}),
@@ -142,6 +225,13 @@ async def http_exception_handler(request: Request, exc: HTTPException) -> Respon
# 处理其他异常
@app.exception_handler(Exception)
async def exception_handler(request: Request, exc: Exception) -> Response:
+ """
+ 将未处理异常转换为对应的 HTTP 响应。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: 当前调用产生的响应
+ """
context = getattr(request.state, 'locale_context', LocaleContext())
token = RequestContext.set_current_locale(context)
try:
diff --git a/ruoyi-fastapi-backend/i18n/__init__.py b/ruoyi-fastapi-backend/i18n/__init__.py
index 45425b2ed..7da16abbe 100644
--- a/ruoyi-fastapi-backend/i18n/__init__.py
+++ b/ruoyi-fastapi-backend/i18n/__init__.py
@@ -9,10 +9,11 @@
def __getattr__(name: str) -> Any:
"""
- 按需加载翻译入口,避免配置加载时提前初始化翻译模块
+ 按需加载翻译入口,避免配置加载时提前初始化翻译模块。
:param name: 请求的模块属性名
:return: 翻译入口函数
+ :raises AttributeError: 请求的名称不是支持的翻译入口
"""
if name == 't':
return import_module('i18n.translator').t
diff --git a/ruoyi-fastapi-backend/i18n/catalogs.py b/ruoyi-fastapi-backend/i18n/catalogs.py
index 8ac0b72c4..ac1127631 100644
--- a/ruoyi-fastapi-backend/i18n/catalogs.py
+++ b/ruoyi-fastapi-backend/i18n/catalogs.py
@@ -15,13 +15,13 @@
@dataclass(frozen=True)
class CatalogSpec:
"""
- 已注册词库的资源目录和回退配置
+ 已注册词库的资源目录和回退配置。
- :param domain: 核心或插件独占的 gettext 域名
- :param root: 已校验的词库根目录
- :param default_locale: 请求语言无法匹配时使用的默认语言
- :param fallbacks: 各已发布语言及其回退语言列表
- :param policy: 计算发布指纹时使用的额外配置
+ :ivar domain: 核心或插件独占的 gettext 域名
+ :ivar root: 已校验的词库根目录
+ :ivar default_locale: 请求语言无法匹配时使用的默认语言
+ :ivar fallbacks: 各已发布语言及其回退语言列表
+ :ivar policy: 计算发布指纹时使用的额外配置
"""
domain: str
@@ -33,7 +33,7 @@ class CatalogSpec:
@property
def locales(self) -> tuple[str, ...]:
"""
- 获取当前词库域已交付的语言
+ 获取当前词库域已交付的语言。
:return: 已交付的语言标识
"""
@@ -41,11 +41,12 @@ def locales(self) -> tuple[str, ...]:
def path(self, code: str, suffix: str) -> Path:
"""
- 从受信配置构造资源路径,拒绝越界符号链接
+ 从受信配置构造资源路径,拒绝越界符号链接。
:param code: 已注册的语言标识
:param suffix: 词库文件扩展名,仅支持 .po 和 .mo
:return: 校验后的词库资源路径
+ :raises ValueError: 语言或文件后缀未注册,或路径越出词库根目录
"""
if code not in self.locales or suffix not in ('.po', '.mo'):
raise ValueError('Unregistered catalog resource')
@@ -56,7 +57,7 @@ def path(self, code: str, suffix: str) -> Path:
def chain(self, locale: str) -> tuple[str, ...]:
"""
- 按当前词库域解析语言回退链,插件词库不回退到核心域
+ 按当前词库域解析语言回退链,插件词库不回退到核心域。
:param locale: 请求的语言标识
:return: 按优先级排列的语言回退链
@@ -65,6 +66,13 @@ def chain(self, locale: str) -> tuple[str, ...]:
fallbacks = dict(self.fallbacks)
def visit(code: str, stack: tuple[str, ...] = ()) -> None:
+ """
+ 递归展开消息目录的回退链并避免循环。
+
+ :param code: 已注册的语言标识
+ :param stack: 当前递归路径上已访问的节点
+ :raises ValueError: 回退链含有循环或引用未登记的语言
+ """
if code in stack or code not in fallbacks:
raise ValueError('Invalid domain locale fallback')
if code not in result:
@@ -82,11 +90,11 @@ def visit(code: str, stack: tuple[str, ...] = ()) -> None:
@dataclass(frozen=True)
class CatalogSnapshot:
"""
- 同一发布版本的词库配置、译文和指纹
+ 同一发布版本的词库配置、译文和指纹。
- :param spec: 加载本版本时使用的配置
- :param translations: 按语言保存的 gettext 词库实例
- :param fingerprint: 根据配置和编译产物内容计算的发布指纹
+ :ivar spec: 加载本版本时使用的配置
+ :ivar translations: 按语言保存的 gettext 词库实例
+ :ivar fingerprint: 根据配置和编译产物内容计算的发布指纹
"""
spec: CatalogSpec
@@ -96,7 +104,11 @@ class CatalogSnapshot:
class CatalogRegistry:
"""
- 进程内受信词库注册表,在启动或生命周期操作中计算内容指纹
+ 进程内受信词库注册表,在启动或生命周期操作中计算内容指纹。
+
+ :cvar _snapshots: 已加载的消息目录快照
+ :cvar _fingerprint: 检测消息目录变更的指纹
+ :cvar _lock: 协调并发访问共享状态的锁
"""
_snapshots: dict[str, CatalogSnapshot] = {}
@@ -106,7 +118,7 @@ class CatalogRegistry:
@staticmethod
def core_spec() -> CatalogSpec:
"""
- 使用项目固定目录和后端语言配置构造核心词库配置
+ 使用项目固定目录和后端语言配置构造核心词库配置。
:return: 核心词库配置
"""
@@ -125,10 +137,11 @@ def core_spec() -> CatalogSpec:
@staticmethod
def plugin_domain(plugin_id: str) -> str:
"""
- 校验插件标识并生成独立的插件词库域
+ 校验插件标识并生成独立的插件词库域。
:param plugin_id: 插件标识
:return: plugin. 格式的词库域
+ :raises ValueError: 插件标识不能作为词库所有者
"""
if not isinstance(plugin_id, str) or not re.fullmatch(r'[a-z][a-z0-9_-]{0,63}', plugin_id):
raise ValueError('Invalid plugin catalog owner')
@@ -137,11 +150,12 @@ def plugin_domain(plugin_id: str) -> str:
@classmethod
def plugin_spec(cls, plugin_id: str, plugin_root: Path) -> CatalogSpec | None:
"""
- 读取已验证插件目录中的 i18n/locale-meta.json 声明
+ 读取已验证插件目录中的 i18n/locale-meta.json 声明。
:param plugin_id: 插件标识
:param plugin_root: 已验证的插件根目录
:return: 插件词库配置,未提供词库资源时返回 None
+ :raises ValueError: 插件词库路径越界,或声明的语言为空、重复或不规范
"""
domain = cls.plugin_domain(plugin_id)
trusted_root = Path(plugin_root).resolve()
@@ -167,7 +181,7 @@ def plugin_spec(cls, plugin_id: str, plugin_root: Path) -> CatalogSpec | None:
@staticmethod
def load(spec: CatalogSpec) -> CatalogSnapshot:
"""
- 校验并加载 MO 资源,不使用 gettext 的全局路径缓存
+ 校验并加载 MO 资源,不使用 gettext 的全局路径缓存。
:param spec: 受信词库配置
:return: 已加载的词库快照
@@ -187,10 +201,11 @@ def load(spec: CatalogSpec) -> CatalogSnapshot:
@staticmethod
def parse(payload: bytes) -> gettext.GNUTranslations:
"""
- 解析 MO 资源,将二进制或复数规则异常统一转换为词库错误
+ 解析 MO 资源,将二进制或复数规则异常统一转换为词库错误。
:param payload: MO 资源内容
:return: gettext 翻译对象
+ :raises ValueError: 编译后的 gettext 词库或复数规则损坏
"""
try:
return gettext.GNUTranslations(io.BytesIO(payload))
@@ -200,10 +215,9 @@ def parse(payload: bytes) -> gettext.GNUTranslations:
@classmethod
def install(cls, snapshot: CatalogSnapshot) -> None:
"""
- 提交已验证的快照,整体替换当前词库域
+ 提交已验证的快照,整体替换当前词库域。
:param snapshot: 已验证的词库快照
- :return: None
"""
with cls._lock:
cls._snapshots = {**cls._snapshots, snapshot.spec.domain: snapshot}
@@ -212,18 +226,17 @@ def install(cls, snapshot: CatalogSnapshot) -> None:
@classmethod
def register_plugin(cls, plugin_id: str, plugin_root: Path) -> None:
"""
- 加载插件发布资源,无声明时清除上一版本遗留的词库域
+ 加载插件发布资源,无声明时清除上一版本遗留的词库域。
:param plugin_id: 插件标识
:param plugin_root: 已验证的插件根目录
- :return: None
"""
cls.commit_plugin(plugin_id, cls.prepare_plugin(plugin_id, plugin_root))
@classmethod
def prepare_plugin(cls, plugin_id: str, plugin_root: Path) -> CatalogSnapshot | None:
"""
- 在安装写入前验证新资源,保留当前已激活版本
+ 在安装写入前验证新资源,保留当前已激活版本。
:param plugin_id: 插件标识
:param plugin_root: 已验证的插件根目录
@@ -235,12 +248,12 @@ def prepare_plugin(cls, plugin_id: str, plugin_root: Path) -> CatalogSnapshot |
@classmethod
def commit_plugin(cls, plugin_id: str, snapshot: CatalogSnapshot | None, *, enabled: bool = True) -> None:
"""
- 生命周期持久化成功后提交资源,禁用或无资源时清除旧词库域
+ 生命周期持久化成功后提交资源,禁用或无资源时清除旧词库域。
:param plugin_id: 插件标识
:param snapshot: 待提交的词库快照
:param enabled: 插件是否启用
- :return: None
+ :raises ValueError: 词库快照声明的域不属于当前插件
"""
if snapshot is None or not enabled:
cls.unregister_plugin(plugin_id)
@@ -252,10 +265,9 @@ def commit_plugin(cls, plugin_id: str, snapshot: CatalogSnapshot | None, *, enab
@classmethod
def unregister_plugin(cls, plugin_id: str) -> None:
"""
- 移除当前插件的词库资源并清除发布指纹缓存
+ 移除当前插件的词库资源并清除发布指纹缓存。
:param plugin_id: 插件标识
- :return: None
"""
domain = cls.plugin_domain(plugin_id)
with cls._lock:
@@ -265,10 +277,9 @@ def unregister_plugin(cls, plugin_id: str) -> None:
@classmethod
def refresh(cls, domain: str | None = None) -> None:
"""
- 重新加载发布产物,失败时保留旧快照和指纹
+ 重新加载发布产物,失败时保留旧快照和指纹。
:param domain: 需要刷新的词库域,未指定时刷新全部已注册域
- :return: None
"""
with cls._lock:
specs = {key: snapshot.spec for key, snapshot in cls._snapshots.items()}
@@ -282,7 +293,7 @@ def refresh(cls, domain: str | None = None) -> None:
@classmethod
def snapshot(cls, domain: str = 'core') -> CatalogSnapshot:
"""
- 获取已注册词库域的快照
+ 获取已注册词库域的快照。
:param domain: 已注册的词库域
:return: 当前词库快照
@@ -295,7 +306,7 @@ def snapshot(cls, domain: str = 'core') -> CatalogSnapshot:
@classmethod
def specs(cls) -> tuple[CatalogSpec, ...]:
"""
- 获取核心域和已注册插件域的词库配置
+ 获取核心域和已注册插件域的词库配置。
:return: 供编译工具使用的词库配置
"""
@@ -305,7 +316,7 @@ def specs(cls) -> tuple[CatalogSpec, ...]:
@classmethod
def fingerprint(cls) -> str:
"""
- 从内存获取词库内容和域配置的发布指纹
+ 从内存获取词库内容和域配置的发布指纹。
:return: 用于响应缓存隔离的词库指纹
"""
diff --git a/ruoyi-fastapi-backend/i18n/locale.py b/ruoyi-fastapi-backend/i18n/locale.py
index 6be053e78..c8ceca64c 100644
--- a/ruoyi-fastapi-backend/i18n/locale.py
+++ b/ruoyi-fastapi-backend/i18n/locale.py
@@ -22,14 +22,12 @@
class LocaleUtil:
- """
- 请求语言协商与响应头工具类
- """
+ """请求语言协商与响应头工具类。"""
@staticmethod
def negotiate_language(header: str) -> str:
"""
- 根据请求头权重协商有效语言
+ 根据请求头权重协商有效语言。
:param header: Accept-Language 请求头原始值
:return: 匹配到的已注册语言,无法匹配时返回默认语言
@@ -68,7 +66,7 @@ def negotiate_language(header: str) -> str:
@staticmethod
def _match_range(language: str, enabled: tuple[str, ...], *, excluded: bool) -> tuple[tuple[str, ...], int]:
"""
- 匹配 Accept-Language 中的单个语言范围
+ 匹配 Accept-Language 中的单个语言范围。
:param language: 请求头中的语言标签或通配符
:param enabled: 按注册顺序排列的已启用语言
@@ -92,7 +90,7 @@ def _match_range(language: str, enabled: tuple[str, ...], *, excluded: bool) ->
@staticmethod
def _report_limit(reason: str, total: int) -> None:
"""
- 在累计次数为 2 的整数次幂时记录摘要,限制重复告警的频率
+ 在累计次数为 2 的整数次幂时记录摘要,限制重复告警的频率。
:param reason: 超限类别,对应请求头长度或语言范围数量
:param total: 当前进程中该类别累计超限的次数
@@ -103,7 +101,7 @@ def _report_limit(reason: str, total: int) -> None:
@classmethod
def context_from_headers(cls, headers: Mapping[str, str]) -> LocaleContext:
"""
- 根据 Accept-Language 请求头构造语言上下文
+ 根据 Accept-Language 请求头构造语言上下文。
:param headers: 支持按小写名称读取的请求头集合
:return: 当前请求的语言上下文
@@ -113,7 +111,7 @@ def context_from_headers(cls, headers: Mapping[str, str]) -> LocaleContext:
@staticmethod
def add_locale_headers(headers: MutableHeaders, context: LocaleContext) -> None:
"""
- 追加语言响应头并保留原有 Vary 配置
+ 追加语言响应头并保留原有 Vary 配置。
:param headers: 可修改的响应头集合
:param context: 当前请求的语言上下文
diff --git a/ruoyi-fastapi-backend/i18n/message.py b/ruoyi-fastapi-backend/i18n/message.py
index 275898046..58bd6ba87 100644
--- a/ruoyi-fastapi-backend/i18n/message.py
+++ b/ruoyi-fastapi-backend/i18n/message.py
@@ -1,10 +1,10 @@
def validate_plural(count: int | None, plural_key: str | None) -> None:
"""
- 校验复数数量与消息标识成对提供,且数量为非负整数
+ 校验复数数量与消息标识成对提供,且数量为非负整数。
:param count: 复数消息数量
:param plural_key: 复数消息标识
- :return: None
+ :raises ValueError: 复数键与计数没有配对,或计数不是非负整数
"""
if (count is None) != (plural_key is None):
raise ValueError('count and plural_key must be provided together')
@@ -14,7 +14,13 @@ def validate_plural(count: int | None, plural_key: str | None) -> None:
class I18nMessage(str):
"""
- 保存原文和消息标识,在响应阶段按请求语言翻译
+ 保存原文和消息标识,在响应阶段按请求语言翻译。
+
+ :ivar msg_key: 完整消息标识
+ :ivar msg_params: 消息插值参数
+ :ivar domain: 已注册的词库域
+ :ivar count: 本次处理或预期的数量
+ :ivar plural_key: 复数消息标识
"""
msg_key: str
@@ -34,7 +40,7 @@ def __new__(
plural_key: str | None = None,
) -> 'I18nMessage':
"""
- 构造带国际化元数据的原文,不在模块加载时读取语言上下文
+ 构造带国际化元数据的原文,不在模块加载时读取语言上下文。
:param message: 写入日志或异常的消息原文
:param msg_key: 完整消息标识
@@ -55,7 +61,7 @@ def __new__(
def __getnewargs_ex__(self) -> tuple[tuple[str], dict]:
"""
- 复制或序列化时保留消息元数据
+ 复制或序列化时保留消息元数据。
:return: 重建消息所需的构造参数
"""
diff --git a/ruoyi-fastapi-backend/i18n/registry.py b/ruoyi-fastapi-backend/i18n/registry.py
index 92ab46729..0d302742b 100644
--- a/ruoyi-fastapi-backend/i18n/registry.py
+++ b/ruoyi-fastapi-backend/i18n/registry.py
@@ -25,14 +25,12 @@
class LocaleRegistry:
- """
- 语言注册与规范化工具类
- """
+ """语言注册与规范化工具类。"""
@staticmethod
def enabled_locales() -> tuple[str, ...]:
"""
- 获取协商和编译时使用的已启用语言
+ 获取协商和编译时使用的已启用语言。
:return: 按注册顺序排列的语言标签
:raises ValueError: 默认语言或基准语言未注册或已停用
@@ -47,11 +45,12 @@ def enabled_locales() -> tuple[str, ...]:
@staticmethod
def normalize_locale(value: str, *, preference: bool = False) -> str:
"""
- 校验并规范化语言标识
+ 校验并规范化语言标识。
:param value: 原始语言标识,兼容下划线分隔形式
:param preference: 是否允许表示跟随设备的 auto 偏好
:return: 规范化后的语言标识或 auto
+ :raises ValueError: 语言标记无效或包含重复扩展
"""
if not isinstance(value, str) or not value or len(value) > MAX_LOCALE_LENGTH:
raise ValueError('Invalid locale')
@@ -84,7 +83,7 @@ def normalize_locale(value: str, *, preference: bool = False) -> str:
@classmethod
def match_locale(cls, value: str) -> str | None:
"""
- 按语言标识或显式别名匹配已注册语言
+ 按语言标识或显式别名匹配已注册语言。
:param value: 待匹配的语言标识
:return: 已注册的语言标识,无法匹配时返回 None
@@ -105,7 +104,7 @@ def match_locale(cls, value: str) -> str | None:
@staticmethod
def fallback_chain(code: str) -> tuple[str, ...]:
"""
- 生成去重后的语言回退链并校验循环配置
+ 生成去重后的语言回退链并校验循环配置。
:param code: 已注册的语言标识
:return: 包含基准语言的回退链
@@ -113,6 +112,13 @@ def fallback_chain(code: str) -> tuple[str, ...]:
result = []
def visit(item: str, stack: tuple[str, ...] = ()) -> None:
+ """
+ 遍历已启用语言的回退配置并去重。
+
+ :param item: 当前要处理的条目
+ :param stack: 当前递归路径上已访问的节点
+ :raises ValueError: 语言回退链含有未知语言或循环
+ """
if item in stack or item not in LOCALES:
raise ValueError('Invalid locale fallback configuration')
if item not in result and LOCALES[item].get('enabled', True):
diff --git a/ruoyi-fastapi-backend/i18n/translation.py b/ruoyi-fastapi-backend/i18n/translation.py
index 43ace3e19..4a4cc14bb 100644
--- a/ruoyi-fastapi-backend/i18n/translation.py
+++ b/ruoyi-fastapi-backend/i18n/translation.py
@@ -6,18 +6,17 @@
class TranslationUtil:
- """
- 菜单和字典译文工具类
- """
+ """菜单和字典译文工具类。"""
@staticmethod
def validate(value: Any, max_length: int) -> dict[str, str | None]:
"""
- 校验译文补丁,允许保存尚未启用的语言
+ 校验译文补丁,允许保存尚未启用的语言。
:param value: 语言标识到译文的映射,空值表示没有译文补丁
:param max_length: 单个译文的最大长度
:return: 规范化语言标识后的译文补丁
+ :raises ValueError: 译文结构、目标语言或文本内容不符合翻译要求
"""
if value is None:
return {}
@@ -42,7 +41,7 @@ def validate(value: Any, max_length: int) -> dict[str, str | None]:
@staticmethod
def merge(current: dict[str, str] | None, patch: dict[str, str | None]) -> dict[str, str]:
"""
- 合并语言补丁,空映射保留已有译文,单项空值删除对应语言
+ 合并语言补丁,空映射保留已有译文,单项空值删除对应语言。
:param current: 数据库中的最新译文
:param patch: 本次提交的语言补丁
@@ -59,7 +58,7 @@ def merge(current: dict[str, str] | None, patch: dict[str, str | None]) -> dict[
@staticmethod
def resolve(original: str, translations: dict[str, str] | None, *, locale: str | None = None) -> str:
"""
- 按当前请求语言和回退链解析数据库译文
+ 按当前请求语言和回退链解析数据库译文。
:param original: 基准语言名称
:param translations: 数据库译文
diff --git a/ruoyi-fastapi-backend/i18n/translator.py b/ruoyi-fastapi-backend/i18n/translator.py
index d5335df19..5d27853eb 100644
--- a/ruoyi-fastapi-backend/i18n/translator.py
+++ b/ruoyi-fastapi-backend/i18n/translator.py
@@ -12,14 +12,12 @@
class I18nUtil:
- """
- 词库加载、消息翻译与响应字段工具类
- """
+ """词库加载、消息翻译与响应字段工具类。"""
@staticmethod
def _load_catalog(code: str, domain: str = 'core') -> gettext.GNUTranslations:
"""
- 加载并缓存编译后的语言资源
+ 加载并缓存编译后的语言资源。
:param code: 已注册的语言标识,不接受请求路径
:param domain: 由调用方指定的可信 gettext 域名
@@ -29,18 +27,15 @@ def _load_catalog(code: str, domain: str = 'core') -> gettext.GNUTranslations:
@classmethod
def validate_catalogs(cls) -> None:
- """
- 校验全部已注册语言的编译产物是否可加载
- """
+ """校验全部已注册语言的编译产物是否可加载。"""
CatalogRegistry.refresh()
@staticmethod
def refresh_catalogs(domain: str | None = None) -> None:
"""
- 在受信发布操作后刷新词库对象和响应缓存指纹
+ 在受信发布操作后刷新词库对象和响应缓存指纹。
:param domain: 需要刷新的词库域,未指定时刷新全部已注册域
- :return: None
"""
CatalogRegistry.refresh(domain)
@@ -56,7 +51,7 @@ def _translate_catalog_message(
plural_key: str | None = None,
) -> str | None:
"""
- 尝试从单个语言资源中取词并插值
+ 尝试从单个语言资源中取词并插值。
:param code: 已注册的语言标识
:param msg_key: 语义消息标识
@@ -94,7 +89,7 @@ def translate(
plural_key: str | None = None,
) -> str:
"""
- 按指定语言及回退链翻译消息
+ 按指定语言及回退链翻译消息。
:param msg_key: 语义消息标识
:param params: 消息插值参数
@@ -139,7 +134,7 @@ def message_fields(
plural_key: str | None = None,
) -> dict:
"""
- 根据请求语言和消息标识生成响应消息字段
+ 根据请求语言和消息标识生成响应消息字段。
:param msg: 调用方指定的消息,可携带翻译元数据
:param msg_key: 显式语义消息标识,优先于消息自带的标识
@@ -194,7 +189,7 @@ def t(
plural_key: str | None = None,
) -> str:
"""
- 即时翻译文本,默认读取调用时的请求语言
+ 即时翻译文本,默认读取调用时的请求语言。
接口响应应传递 msg_key 和 msg_params,由响应工具保留消息标识和插值参数。
后台任务等脱离请求的场景应显式传入语言快照。
diff --git a/ruoyi-fastapi-backend/i18n/validation.py b/ruoyi-fastapi-backend/i18n/validation.py
index c8194d220..7d1d76efd 100644
--- a/ruoyi-fastapi-backend/i18n/validation.py
+++ b/ruoyi-fastapi-backend/i18n/validation.py
@@ -44,14 +44,12 @@
class ValidationMessageUtil:
- """
- 原生 422 校验错误翻译工具,保留字段定位和公开约束
- """
+ """原生 422 校验错误翻译工具,保留字段定位和公开约束。"""
@staticmethod
def localize(error: dict[str, Any]) -> dict[str, Any]:
"""
- 翻译支持的校验错误,未知类型使用通用提示并保留字段路径
+ 翻译支持的校验错误,未知类型使用通用提示并保留字段路径。
:param error: 原生校验错误信息
:return: 包含译文和消息元数据的校验错误
diff --git a/ruoyi-fastapi-backend/middlewares/api_response_header_middleware.py b/ruoyi-fastapi-backend/middlewares/api_response_header_middleware.py
index 5393eaf71..1113ba25a 100644
--- a/ruoyi-fastapi-backend/middlewares/api_response_header_middleware.py
+++ b/ruoyi-fastapi-backend/middlewares/api_response_header_middleware.py
@@ -4,13 +4,15 @@
class ApiResponseHeaderMiddleware(BaseHTTPMiddleware):
- """
- 接口响应头追加中间件
- """
+ """接口响应头追加中间件。"""
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
"""
- 在响应返回前统一追加接口响应头
+ 在响应返回前统一追加接口响应头。
+
+ :param request: 当前 HTTP 请求
+ :param call_next: 调用下一层请求处理器的异步回调
+ :return: 当前调用产生的响应
"""
response = await call_next(request)
api_response_headers = getattr(request.state, 'api_response_headers', None)
@@ -21,7 +23,7 @@ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -
def add_api_response_header_middleware(app: FastAPI) -> None:
"""
- 添加接口响应头追加中间件
+ 添加接口响应头追加中间件。
:param app: FastAPI对象
"""
diff --git a/ruoyi-fastapi-backend/middlewares/context_middleware.py b/ruoyi-fastapi-backend/middlewares/context_middleware.py
index ca29556d7..4484b5eb4 100644
--- a/ruoyi-fastapi-backend/middlewares/context_middleware.py
+++ b/ruoyi-fastapi-backend/middlewares/context_middleware.py
@@ -7,13 +7,15 @@
class ContextCleanupMiddleware(BaseHTTPMiddleware):
- """
- 上下文清理中间件
- """
+ """上下文清理中间件。"""
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
"""
- 在每个请求处理完成后清理上下文信息
+ 在每个请求处理完成后清理上下文信息。
+
+ :param request: 当前 HTTP 请求
+ :param call_next: 调用下一层请求处理器的异步回调
+ :return: 下游处理结果或请求上下文错误响应
"""
timezone_name = request.headers.get('X-Timezone')
try:
@@ -37,7 +39,7 @@ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -
def add_context_cleanup_middleware(app: FastAPI) -> None:
"""
- 添加上下文清理中间件
+ 添加上下文清理中间件。
:param app: FastAPI对象
"""
diff --git a/ruoyi-fastapi-backend/middlewares/cors_middleware.py b/ruoyi-fastapi-backend/middlewares/cors_middleware.py
index ef938072f..76f7792b0 100644
--- a/ruoyi-fastapi-backend/middlewares/cors_middleware.py
+++ b/ruoyi-fastapi-backend/middlewares/cors_middleware.py
@@ -4,7 +4,7 @@
def add_cors_middleware(app: FastAPI) -> None:
"""
- 添加跨域中间件
+ 添加跨域中间件。
:param app: FastAPI对象
"""
diff --git a/ruoyi-fastapi-backend/middlewares/demo_mode_middleware.py b/ruoyi-fastapi-backend/middlewares/demo_mode_middleware.py
index d35562546..661192e2a 100644
--- a/ruoyi-fastapi-backend/middlewares/demo_mode_middleware.py
+++ b/ruoyi-fastapi-backend/middlewares/demo_mode_middleware.py
@@ -8,13 +8,15 @@
class DemoModeMiddleware(BaseHTTPMiddleware):
- """
- 演示模式中间件
- """
+ """演示模式中间件。"""
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
"""
- 演示模式下拦截指定请求
+ 演示模式下拦截指定请求。
+
+ :param request: 当前 HTTP 请求
+ :param call_next: 调用下一层请求处理器的异步回调
+ :return: 演示限制提示或下游响应
"""
url_path = str(request.url)
method = request.method.lower()
@@ -58,7 +60,7 @@ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -
def add_demo_mode_middleware(app: FastAPI) -> None:
"""
- 添加演示模式中间件
+ 添加演示模式中间件。
:param app: FastAPI对象
"""
diff --git a/ruoyi-fastapi-backend/middlewares/gzip_middleware.py b/ruoyi-fastapi-backend/middlewares/gzip_middleware.py
index 867b7864a..ed72f3f26 100644
--- a/ruoyi-fastapi-backend/middlewares/gzip_middleware.py
+++ b/ruoyi-fastapi-backend/middlewares/gzip_middleware.py
@@ -4,9 +4,8 @@
def add_gzip_middleware(app: FastAPI) -> None:
"""
- 添加gzip压缩中间件
+ 添加gzip压缩中间件。
:param app: FastAPI对象
- :return:
"""
app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=9)
diff --git a/ruoyi-fastapi-backend/middlewares/handle.py b/ruoyi-fastapi-backend/middlewares/handle.py
index f0f7c48a7..20adfd29a 100644
--- a/ruoyi-fastapi-backend/middlewares/handle.py
+++ b/ruoyi-fastapi-backend/middlewares/handle.py
@@ -14,7 +14,9 @@
def handle_middleware(app: FastAPI) -> None:
"""
- 全局中间件处理
+ 全局中间件处理。
+
+ :param app: 正在配置或处理请求的 ASGI 应用
"""
# 加载上下文清理中间件
add_context_cleanup_middleware(app)
diff --git a/ruoyi-fastapi-backend/middlewares/locale_middleware.py b/ruoyi-fastapi-backend/middlewares/locale_middleware.py
index eca6a503a..85f6bdc2b 100644
--- a/ruoyi-fastapi-backend/middlewares/locale_middleware.py
+++ b/ruoyi-fastapi-backend/middlewares/locale_middleware.py
@@ -8,12 +8,14 @@
class LocaleMiddleware:
"""
- 请求语言中间件,注册在传输加密中间件外层
+ 请求语言中间件,注册在传输加密中间件外层。
+
+ :ivar app: 由本中间件包装的 ASGI 应用
"""
def __init__(self, app: ASGIApp) -> None:
"""
- 初始化请求语言中间件
+ 初始化请求语言中间件。
:param app: 由本中间件包装的 ASGI 应用
"""
@@ -21,7 +23,7 @@ def __init__(self, app: ASGIApp) -> None:
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
"""
- 协商请求语言并在请求结束或取消时恢复上下文
+ 协商请求语言并在请求结束或取消时恢复上下文。
:param scope: ASGI 请求作用域
:param receive: ASGI 接收函数
@@ -35,6 +37,11 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
token = RequestContext.set_current_locale(context)
async def send_localized(message: Message) -> None:
+ """
+ 将协商后的语言信息写入响应头并发送消息。
+
+ :param message: 与当前结果一起返回的说明
+ """
if message['type'] == 'http.response.start':
LocaleUtil.add_locale_headers(MutableHeaders(scope=message), context)
await send(message)
@@ -47,7 +54,7 @@ async def send_localized(message: Message) -> None:
def add_locale_middleware(app: FastAPI) -> None:
"""
- 添加请求语言中间件
+ 添加请求语言中间件。
:param app: FastAPI 应用
"""
diff --git a/ruoyi-fastapi-backend/middlewares/oidc_cors_middleware.py b/ruoyi-fastapi-backend/middlewares/oidc_cors_middleware.py
index 0c0824c94..33d7d4ecd 100644
--- a/ruoyi-fastapi-backend/middlewares/oidc_cors_middleware.py
+++ b/ruoyi-fastapi-backend/middlewares/oidc_cors_middleware.py
@@ -12,6 +12,12 @@
class OidcCorsMiddleware:
"""
为 OIDC 协议和认证交互接口提供独立的 CORS 边界。
+
+ :cvar _OIDC_PREFIXES: 适用 OIDC 跨域策略的路径前缀
+ :cvar _INTERACTION_PREFIX: 用户交互端点的路径前缀
+ :cvar _NO_CORS_PATHS: 不接受跨域访问的端点路径
+ :cvar _PUBLIC_METADATA_PATHS: 公开协议元数据端点的路径
+ :ivar app: FastAPI 对象
"""
_OIDC_PREFIXES = ('/oauth2/', '/.well-known/')
@@ -24,6 +30,11 @@ class OidcCorsMiddleware:
)
def __init__(self, app: ASGIApp) -> None:
+ """
+ 绑定接收 OIDC 跨域请求的下游应用。
+
+ :param app: FastAPI 对象
+ """
self.app = app
@classmethod
@@ -158,7 +169,6 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
:param scope: 当前 ASGI 请求作用域
:param receive: 接收 ASGI 消息的可调用对象
:param send: 发送 ASGI 消息的可调用对象
- :return: None
"""
# 注册层已经按 OIDC_ENABLED 控制是否挂载;这里保留运行时保护,
# 避免测试或动态配置场景下开关关闭后仍处理协议请求。
@@ -225,7 +235,6 @@ async def send_wrapper(message: Message) -> None:
在下游响应开始消息中应用 OIDC CORS 策略。
:param message: 下游 ASGI 消息
- :return: None
"""
if message.get('type') != 'http.response.start':
await send(message)
diff --git a/ruoyi-fastapi-backend/middlewares/trace_middleware/__init__.py b/ruoyi-fastapi-backend/middlewares/trace_middleware/__init__.py
index c2ea30267..20a4aeed4 100644
--- a/ruoyi-fastapi-backend/middlewares/trace_middleware/__init__.py
+++ b/ruoyi-fastapi-backend/middlewares/trace_middleware/__init__.py
@@ -10,9 +10,8 @@
def add_trace_middleware(app: FastAPI) -> None:
"""
- 添加trace中间件
+ 添加trace中间件。
:param app: FastAPI对象
- :return:
"""
app.add_middleware(TraceASGIMiddleware)
diff --git a/ruoyi-fastapi-backend/middlewares/trace_middleware/ctx.py b/ruoyi-fastapi-backend/middlewares/trace_middleware/ctx.py
index f5461d11b..6cd414cb7 100644
--- a/ruoyi-fastapi-backend/middlewares/trace_middleware/ctx.py
+++ b/ruoyi-fastapi-backend/middlewares/trace_middleware/ctx.py
@@ -9,54 +9,107 @@
class TraceCtx:
+ """保存当前请求的链路跟踪上下文。"""
+
@staticmethod
def set_trace_id() -> str:
+ """
+ 设置当前请求的链路标识。
+
+ :return: 供调用方使用的 ``_id``
+ """
_id = uuid4().hex
CTX_TRACE_ID.set(_id)
return _id
@staticmethod
def get_trace_id() -> str:
+ """
+ 读取当前请求的链路标识。
+
+ :return: 当前请求的链路标识
+ """
return CTX_TRACE_ID.get()
@staticmethod
def set_request_id() -> str:
+ """
+ 设置当前请求的请求标识。
+
+ :return: 供调用方使用的 ``_id``
+ """
_id = uuid4().hex
CTX_REQUEST_ID.set(_id)
return _id
@staticmethod
def get_request_id() -> str:
+ """
+ 读取当前请求的请求标识。
+
+ :return: 当前请求的请求标识
+ """
return CTX_REQUEST_ID.get()
@staticmethod
def set_span_id() -> str:
+ """
+ 设置当前请求的跨度标识。
+
+ :return: 供调用方使用的 ``_id``
+ """
_id = uuid4().hex
CTX_SPAN_ID.set(_id)
return _id
@staticmethod
def get_span_id() -> str:
+ """
+ 读取当前请求的跨度标识。
+
+ :return: 当前请求的跨度标识
+ """
return CTX_SPAN_ID.get()
@staticmethod
def set_request_path(path: str) -> None:
+ """
+ 设置当前请求的路径。
+
+ :param path: 要读取或处理的路径
+ """
CTX_REQUEST_PATH.set(path)
@staticmethod
def get_request_path() -> str:
+ """
+ 读取当前请求的路径。
+
+ :return: 当前请求的路径
+ """
return CTX_REQUEST_PATH.get()
@staticmethod
def set_request_method(method: str) -> None:
+ """
+ 设置当前请求的HTTP 方法。
+
+ :param method: 当前请求的 HTTP 方法
+ """
CTX_REQUEST_METHOD.set(method)
@staticmethod
def get_request_method() -> str:
+ """
+ 读取当前请求的HTTP 方法。
+
+ :return: 当前请求的HTTP 方法
+ """
return CTX_REQUEST_METHOD.get()
@staticmethod
def clear() -> None:
+ """清除当前请求的链路标识和请求信息。"""
CTX_TRACE_ID.set('')
CTX_REQUEST_ID.set('')
CTX_SPAN_ID.set('')
diff --git a/ruoyi-fastapi-backend/middlewares/trace_middleware/middle.py b/ruoyi-fastapi-backend/middlewares/trace_middleware/middle.py
index 57a9a2802..57b73ba92 100644
--- a/ruoyi-fastapi-backend/middlewares/trace_middleware/middle.py
+++ b/ruoyi-fastapi-backend/middlewares/trace_middleware/middle.py
@@ -8,20 +8,42 @@
class TraceASGIMiddleware:
"""
- fastapi-example:
+ FastAPI 中间件用法示例。
+
+ ::
+
app = FastAPI()
app.add_middleware(TraceASGIMiddleware)
+
+ :ivar app: 正在配置或处理请求的 ASGI 应用
"""
def __init__(self, app: ASGIApp) -> None:
+ """
+ 绑定需要跟踪请求的 ASGI 应用。
+
+ :param app: 正在配置或处理请求的 ASGI 应用
+ """
self.app = app
@staticmethod
async def my_receive(receive: Receive, span: Span) -> Receive:
+ """
+ 在接收请求体前启动跟踪并包装接收回调。
+
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param span: HTTP 请求和响应的处理顺序如下
+ :return: 供调用方使用的 ``my_receive``
+ """
await span.request_before()
@wraps(receive)
async def my_receive() -> Message:
+ """
+ 接收一条 ASGI 消息并交给当前跟踪跨度记录。
+
+ :return: 与当前结果一起返回的说明
+ """
message = await receive()
await span.request_after(message)
return message
@@ -29,6 +51,13 @@ async def my_receive() -> Message:
return my_receive
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 为 HTTP 请求建立跟踪跨度并包装消息收发。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
if scope['type'] != 'http':
await self.app(scope, receive, send)
return
@@ -37,6 +66,11 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
handle_outgoing_receive = await self.my_receive(receive, span)
async def handle_outgoing_request(message: 'Message') -> None:
+ """
+ 跟踪即将发送的 ASGI 响应消息。
+
+ :param message: 与当前结果一起返回的说明
+ """
await span.response(message)
await send(message)
diff --git a/ruoyi-fastapi-backend/middlewares/trace_middleware/span.py b/ruoyi-fastapi-backend/middlewares/trace_middleware/span.py
index ba6600077..c5db2465d 100644
--- a/ruoyi-fastapi-backend/middlewares/trace_middleware/span.py
+++ b/ruoyi-fastapi-backend/middlewares/trace_middleware/span.py
@@ -8,17 +8,25 @@
class Span:
"""
- 整个http生命周期:
+ HTTP 请求和响应的处理顺序如下。
+
+ ::
+
request(before) --> request(after) --> response(before) --> response(after)
+
+ :ivar scope: 当前操作使用的作用域
"""
def __init__(self, scope: Scope) -> None:
+ """
+ 保存当前请求的 ASGI 作用域。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ """
self.scope = scope
async def request_before(self) -> None:
- """
- request_before: 处理header信息等, 如记录请求体信息
- """
+ """request_before: 处理header信息等, 如记录请求体信息。"""
TraceCtx.set_trace_id()
TraceCtx.set_request_id()
TraceCtx.set_span_id()
@@ -26,21 +34,28 @@ async def request_before(self) -> None:
TraceCtx.set_request_method(self.scope.get('method', ''))
async def request_after(self, message: Message) -> Message:
- """
- request_after: 处理请求bytes, 如记录请求参数
+ r"""
+ request_after: 处理请求bytes, 如记录请求参数。
+
+ ASGI 请求消息示例::
- example:
- message: {'type': 'http.request', 'body': b'{\r\n "name": "\xe8\x8b\x8f\xe8\x8b\x8f\xe8\x8b\x8f"\r\n}', 'more_body': False}
+ message: {
+ 'type': 'http.request',
+ 'body': b'{\r\n "name": "\xe8\x8b\x8f\xe8\x8b\x8f\xe8\x8b\x8f"\r\n}',
+ 'more_body': False,
+ }
+
+ :param message: 与当前结果一起返回的说明
+ :return: 与当前结果一起返回的说明
"""
return message
async def response(self, message: Message) -> Message:
"""
- if message['type'] == "http.response.start": -----> request-before
- pass
- if message['type'] == "http.response.body": -----> request-after
- message.get('body', b'')
- pass
+ 在响应开始时写入请求、追踪和跨度标识。
+
+ :param message: 与当前结果一起返回的说明
+ :return: 与当前结果一起返回的说明
"""
if message['type'] == 'http.response.start':
message['headers'].append((b'request-id', TraceCtx.get_request_id().encode()))
@@ -51,4 +66,10 @@ async def response(self, message: Message) -> Message:
@asynccontextmanager
async def get_current_span(scope: Scope) -> AsyncGenerator[Span, None]:
+ """
+ 为当前 ASGI 作用域提供跟踪跨度。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :yield: ``Span`` 实例
+ """
yield Span(scope)
diff --git a/ruoyi-fastapi-backend/middlewares/transport_crypto_middleware.py b/ruoyi-fastapi-backend/middlewares/transport_crypto_middleware.py
index 16e42b764..4bfaa5355 100644
--- a/ruoyi-fastapi-backend/middlewares/transport_crypto_middleware.py
+++ b/ruoyi-fastapi-backend/middlewares/transport_crypto_middleware.py
@@ -21,7 +21,18 @@
class TransportCryptoMiddleware:
"""
- 传输层请求解密与响应加密中间件
+ 传输层请求解密与响应加密中间件。
+
+ :cvar _STANDARD_OIDC_PATHS: 使用标准 OIDC 传输协议的端点路径
+ :cvar _ENCRYPT_REQUEST_HEADER: 标识请求加密方式的 HTTP 头
+ :cvar _ENCRYPT_RESPONSE_HEADER: 标识响应加密方式的 HTTP 头
+ :cvar _ENCRYPT_ALG_HEADER: 声明加密算法的 HTTP 头
+ :cvar _ENCRYPT_KID_HEADER: 声明加密密钥标识的 HTTP 头
+ :cvar _MONITOR_REQUEST_MODE_HEADER: 记录请求加密模式的监控头
+ :cvar _MONITOR_RESPONSE_MODE_HEADER: 记录响应加密模式的监控头
+ :cvar _MONITOR_STATUS_HEADER: 记录加密处理状态的监控头
+ :cvar _MONITOR_KID_HEADER: 记录密钥标识的监控头
+ :ivar app: FastAPI/Starlette应用对象
"""
# 标准 OAuth/OIDC 客户端无法理解项目自定义传输信封,协议路径始终旁路,
@@ -49,21 +60,19 @@ class TransportCryptoMiddleware:
def __init__(self, app: ASGIApp) -> None:
"""
- 初始化传输层加解密中间件
+ 初始化传输层加解密中间件。
:param app: FastAPI/Starlette应用对象
- :return: None
"""
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
"""
- 拦截HTTP请求,按配置执行请求解密与响应加密
+ 拦截HTTP请求,按配置执行请求解密与响应加密。
:param scope: 当前ASGI请求作用域
:param receive: ASGI receive函数
:param send: ASGI send函数
- :return: None
"""
if scope['type'] != 'http' or not TransportCryptoConfig.transport_crypto_enabled:
await self.app(scope, receive, send)
@@ -156,6 +165,11 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
return
async def send_wrapper(message: Message) -> None:
+ """
+ 在发送 HTTP 响应时应用传输加密策略。
+
+ :param message: 原始异常信息
+ """
await response_encryptor(message)
response_encryptor = self._build_response_encryptor(
@@ -174,13 +188,14 @@ async def _decrypt_request(
body: bytes,
) -> tuple[Scope, bytes, dict[str, str | bytes | bool]]:
"""
- 解密请求并回写解密后的headers、query和body
+ 解密请求并回写解密后的headers、query和body。
:param scope: 当前ASGI请求作用域
:param request: FastAPI请求对象
:param headers: 当前请求头对象
:param body: 原始请求体字节串
:return: 解密后的scope、请求体与加密上下文
+ :raises ValueError: 未找到可解密的请求载荷;请求中存在不一致的密钥版本;请求中存在不一致的会话密钥;加密请求缺少可用的密钥上下文
"""
new_scope = dict(scope)
new_scope['state'] = dict(scope.get('state', {}))
@@ -232,7 +247,7 @@ async def _decrypt_envelope(
envelope: dict[str, str],
) -> DecryptedTransportEnvelope:
"""
- 解密单个请求信封并执行时间窗、防重放校验
+ 解密单个请求信封并执行时间窗、防重放校验。
:param request: 当前请求对象
:param scope: 当前ASGI请求作用域
@@ -250,7 +265,7 @@ async def _decrypt_envelope(
def _extract_query_envelope(self, scope: Scope) -> dict[str, str] | None:
"""
- 从查询参数中提取加密信封
+ 从查询参数中提取加密信封。
:param scope: 当前ASGI请求作用域
:return: 查询参数中的信封字典,不存在时返回None
@@ -263,11 +278,12 @@ def _extract_query_envelope(self, scope: Scope) -> dict[str, str] | None:
def _extract_body_envelope(self, content_type: str, body: bytes) -> dict[str, str] | None:
"""
- 根据内容类型从请求体中提取加密信封
+ 根据内容类型从请求体中提取加密信封。
:param content_type: 当前请求内容类型
:param body: 原始请求体字节串
:return: 请求体中的信封字典,不存在时返回None
+ :raises ValueError: 加密请求体格式不合法
"""
if not body or 'multipart/form-data' in content_type:
return None
@@ -303,8 +319,9 @@ def _build_response_encryptor(
crypto_context: dict[str, str | bytes | bool],
) -> Callable[[Message], Awaitable[None]]:
"""
- 构建响应加密发送器,仅对JSON响应执行加密
+ 构建响应加密发送器,仅对JSON响应执行加密。
+ :param app: FastAPI/Starlette应用对象
:param scope: 当前ASGI请求作用域
:param send: ASGI send函数
:param crypto_context: 当前请求加密上下文
@@ -315,6 +332,11 @@ def _build_response_encryptor(
should_buffer_json = False
async def _encrypt_response(message: Message) -> None:
+ """
+ 按协商的密钥和算法加密响应内容。
+
+ :param message: 原始异常信息
+ """
nonlocal response_start_message, should_buffer_json
if message['type'] == 'http.response.start':
@@ -402,8 +424,9 @@ def _build_passthrough_response_observer(
kid: str | None = None,
) -> Callable[[Message], Awaitable[None]]:
"""
- 构建明文响应观察器,为响应追加监控诊断头
+ 构建明文响应观察器,为响应追加监控诊断头。
+ :param app: FastAPI/Starlette应用对象
:param send: ASGI send函数
:param request_mode: 请求传输模式
:param crypto_status: 当前传输层处理状态
@@ -413,6 +436,11 @@ def _build_passthrough_response_observer(
has_recorded_response = False
async def _observe_response(message: Message) -> None:
+ """
+ 记录直通响应的传输状态。
+
+ :param message: 原始异常信息
+ """
nonlocal has_recorded_response
if message['type'] == 'http.response.start':
@@ -441,7 +469,7 @@ async def _observe_response(message: Message) -> None:
def _build_crypto_context(self, decrypted_payload: DecryptedTransportEnvelope) -> dict[str, str | bytes | bool]:
"""
- 从解密结果构建请求生命周期内的加密上下文
+ 从解密结果构建请求生命周期内的加密上下文。
:param decrypted_payload: 解密后的请求信封对象
:return: 请求加密上下文字典
@@ -459,7 +487,7 @@ def _build_error_crypto_context(
body: bytes,
) -> dict[str, str | bytes | bool] | None:
"""
- 尝试在解密失败场景下提取AES会话密钥,以便返回加密错误响应
+ 尝试在解密失败场景下提取AES会话密钥,以便返回加密错误响应。
:param scope: 当前ASGI请求作用域
:param headers: 当前请求头对象
@@ -488,7 +516,7 @@ def _build_error_crypto_context(
def _extract_request_kid(self, scope: Scope, headers: Headers, body: bytes) -> str | None:
"""
- 尝试从原始请求信封中提取密钥版本
+ 尝试从原始请求信封中提取密钥版本。
:param scope: 当前ASGI请求作用域
:param headers: 当前请求头对象
@@ -509,10 +537,11 @@ def _extract_request_kid(self, scope: Scope, headers: Headers, body: bytes) -> s
@staticmethod
def _loads_json_mapping(payload: str) -> dict:
"""
- 将JSON字符串解析为字典,并限制结果必须为JSON对象
+ 将JSON字符串解析为字典,并限制结果必须为JSON对象。
:param payload: JSON字符串
:return: 解析后的字典对象
+ :raises ValueError: 解密后的请求载荷必须为JSON对象
"""
json_payload = json.loads(payload)
if not isinstance(json_payload, dict):
@@ -522,7 +551,7 @@ def _loads_json_mapping(payload: str) -> dict:
@staticmethod
async def _read_body(receive: Receive) -> bytes:
"""
- 从ASGI receive中读取完整请求体
+ 从ASGI receive中读取完整请求体。
:param receive: ASGI receive函数
:return: 完整请求体字节串
@@ -540,7 +569,7 @@ async def _read_body(receive: Receive) -> bytes:
@staticmethod
def _build_receive(body: bytes) -> Receive:
"""
- 根据指定请求体重建一次性可消费的ASGI receive函数
+ 根据指定请求体重建一次性可消费的ASGI receive函数。
:param body: 需要回放的请求体字节串
:return: 重建后的ASGI receive函数
@@ -548,6 +577,11 @@ def _build_receive(body: bytes) -> Receive:
has_been_called = False
async def _receive() -> Message:
+ """
+ 将缓冲的请求体交还给下游 ASGI 应用。
+
+ :return: 带有已缓冲请求体的 ASGI 消息
+ """
nonlocal has_been_called
if has_been_called:
return {'type': 'http.request', 'body': b'', 'more_body': False}
@@ -559,7 +593,7 @@ async def _receive() -> Message:
@staticmethod
def _replace_header(headers: list[tuple[bytes, bytes]], key: bytes, value: bytes) -> list[tuple[bytes, bytes]]:
"""
- 替换或新增指定响应头
+ 替换或新增指定响应头。
:param headers: 原始请求/响应头列表
:param key: 头名称
@@ -576,7 +610,7 @@ def _replace_header(headers: list[tuple[bytes, bytes]], key: bytes, value: bytes
@staticmethod
def _remove_header(headers: list[tuple[bytes, bytes]], key: bytes) -> list[tuple[bytes, bytes]]:
"""
- 删除指定请求头
+ 删除指定请求头。
:param headers: 原始请求头列表
:param key: 头名称
@@ -590,7 +624,7 @@ def _remove_header(headers: list[tuple[bytes, bytes]], key: bytes) -> list[tuple
@staticmethod
def _normalize_path(path: str) -> str:
"""
- 标准化请求路径,剥离应用根路径前缀
+ 标准化请求路径,剥离应用根路径前缀。
:param path: 原始请求路径
:return: 标准化后的业务路径
@@ -608,7 +642,7 @@ def _merge_response_headers(
extra_headers: dict[str, str],
) -> list[tuple[bytes, bytes]]:
"""
- 将字符串响应头批量写回到原始headers列表
+ 将字符串响应头批量写回到原始headers列表。
:param headers: 原始请求/响应头列表
:param extra_headers: 需要追加的响应头
@@ -630,7 +664,7 @@ def _build_monitor_headers(
kid: str | None = None,
) -> dict[str, str]:
"""
- 构建传输层加解密监控响应头
+ 构建传输层加解密监控响应头。
:param request_mode: 请求传输模式
:param response_mode: 响应传输模式
@@ -658,7 +692,7 @@ async def _send_error_response(
headers: dict[str, str] | None = None,
) -> None:
"""
- 发送错误响应,在存在AES会话密钥时优先返回加密错误响应
+ 发送错误响应,在存在AES会话密钥时优先返回加密错误响应。
:param scope: 当前ASGI请求作用域
:param receive: ASGI receive函数
@@ -666,7 +700,6 @@ async def _send_error_response(
:param msg_key: 错误消息的语义标识
:param crypto_context: 可选的请求加密上下文
:param headers: 需要追加的诊断响应头
- :return: None
"""
response_content = {
'code': HttpStatusConstant.BAD_REQUEST,
@@ -694,7 +727,7 @@ async def _send_error_response(
@staticmethod
def _classify_failure_reason(message: str) -> str:
"""
- 根据异常信息归类传输层失败原因
+ 根据异常信息归类传输层失败原因。
:param message: 原始异常信息
:return: 失败原因分类编码
@@ -741,7 +774,7 @@ def _is_bundle_ui_navigation(scope: Scope, path: str) -> bool:
@classmethod
def _is_excluded_path(cls, path: str) -> bool:
"""
- 判断当前路径是否在传输加密排除列表内
+ 判断当前路径是否在传输加密排除列表内。
:param path: 当前请求路径
:return: 是否命中排除列表
@@ -757,7 +790,7 @@ def _is_excluded_path(cls, path: str) -> bool:
@classmethod
def _is_required_path(cls, path: str) -> bool:
"""
- 判断当前路径是否在强制加密列表内
+ 判断当前路径是否在强制加密列表内。
:param path: 当前请求路径
:return: 是否命中强制加密列表
@@ -774,7 +807,7 @@ def _is_required_path(cls, path: str) -> bool:
@classmethod
def _is_enabled_path(cls, path: str) -> bool:
"""
- 判断当前路径是否在启用传输加密的列表内
+ 判断当前路径是否在启用传输加密的列表内。
:param path: 当前请求路径
:return: 当前路径是否启用传输加密
@@ -791,9 +824,8 @@ def _is_enabled_path(cls, path: str) -> bool:
def add_transport_crypto_middleware(app: ASGIApp) -> None:
"""
- 添加传输层加解密中间件
+ 添加传输层加解密中间件。
:param app: FastAPI/Starlette应用对象
- :return: None
"""
app.add_middleware(TransportCryptoMiddleware)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/login_controller.py b/ruoyi-fastapi-backend/module_admin/controller/login_controller.py
index 1af7eb2fe..6072ea0f1 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/login_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/login_controller.py
@@ -168,36 +168,6 @@ async def register_user(
return ResponseUtil.success(data=user_register_result, msg=user_register_result.message)
-# @login_controller.post("/getSmsCode", response_model=SmsCode)
-# async def get_sms_code(request: Request, user: ResetUserModel, query_db: AsyncSession = DBSessionDependency()):
-# try:
-# sms_result = await LoginService.get_sms_code_services(request, query_db, user)
-# if sms_result.is_success:
-# logger.info('获取成功')
-# return ResponseUtil.success(data=sms_result)
-# else:
-# logger.warning(sms_result.message)
-# return ResponseUtil.failure(msg=sms_result.message)
-# except Exception as e:
-# logger.exception(e)
-# return ResponseUtil.error(msg=str(e))
-#
-#
-# @login_controller.post("/forgetPwd", response_model=CrudResponseModel)
-# async def forget_user_pwd(request: Request, forget_user: ResetUserModel, query_db: AsyncSession = DBSessionDependency()):
-# try:
-# forget_user_result = await LoginService.forget_user_services(request, query_db, forget_user)
-# if forget_user_result.is_success:
-# logger.info(forget_user_result.message)
-# return ResponseUtil.success(data=forget_user_result, msg=forget_user_result.message)
-# else:
-# logger.warning(forget_user_result.message)
-# return ResponseUtil.failure(msg=forget_user_result.message)
-# except Exception as e:
-# logger.exception(e)
-# return ResponseUtil.error(msg=str(e))
-
-
@login_controller.post(
'/logout',
summary='退出登录接口',
diff --git a/ruoyi-fastapi-backend/module_admin/controller/user_controller.py b/ruoyi-fastapi-backend/module_admin/controller/user_controller.py
index 0505a632b..e43c362fa 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/user_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/user_controller.py
@@ -422,7 +422,12 @@ async def get_system_user_timezones(request: Request) -> Response:
return ResponseUtil.success(data=sorted(available_timezones() - {'localtime'}))
-@user_controller.put('/profile/locale', summary='修改当前用户语言偏好', response_model=ResponseBaseModel)
+@user_controller.put(
+ '/profile/locale',
+ summary='修改当前用户语言偏好',
+ description='保存当前账号的界面语言,可选择受支持的语言或使用 auto 跟随设备设置。',
+ response_model=ResponseBaseModel,
+)
@ApiCacheEvict(namespaces=ApiGroup.USER_INFO_MUTATION)
@Log(title='语言设置', business_type=BusinessType.UPDATE)
async def change_system_user_locale(
diff --git a/ruoyi-fastapi-backend/module_admin/dao/config_dao.py b/ruoyi-fastapi-backend/module_admin/dao/config_dao.py
index c12fbaa76..4cabfc661 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/config_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/config_dao.py
@@ -11,14 +11,12 @@
class ConfigDao:
- """
- 参数配置管理模块数据库操作层
- """
+ """参数配置管理模块数据库操作层。"""
@classmethod
async def get_config_detail_by_id(cls, db: AsyncSession, config_id: int) -> SysConfig | None:
"""
- 根据参数配置id获取参数配置详细信息
+ 根据参数配置id获取参数配置详细信息。
:param db: orm对象
:param config_id: 参数配置id
@@ -31,7 +29,7 @@ async def get_config_detail_by_id(cls, db: AsyncSession, config_id: int) -> SysC
@classmethod
async def get_config_detail_by_info(cls, db: AsyncSession, config: ConfigModel) -> SysConfig | None:
"""
- 根据参数配置参数获取参数配置信息
+ 根据参数配置参数获取参数配置信息。
:param db: orm对象
:param config: 参数配置参数对象
@@ -57,7 +55,7 @@ async def get_config_list(
cls, db: AsyncSession, query_object: ConfigPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取参数配置列表信息
+ 根据查询参数获取参数配置列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -88,11 +86,11 @@ async def get_config_list(
@classmethod
async def add_config_dao(cls, db: AsyncSession, config: ConfigModel) -> SysConfig:
"""
- 新增参数配置数据库操作
+ 新增参数配置数据库操作。
:param db: orm对象
:param config: 参数配置对象
- :return:
+ :return: 新增的参数配置记录
"""
db_config = SysConfig(**config.model_dump(exclude={'create_time', 'update_time'}))
db.add(db_config)
@@ -103,11 +101,10 @@ async def add_config_dao(cls, db: AsyncSession, config: ConfigModel) -> SysConfi
@classmethod
async def edit_config_dao(cls, db: AsyncSession, config: dict) -> None:
"""
- 编辑参数配置数据库操作
+ 编辑参数配置数据库操作。
:param db: orm对象
:param config: 需要更新的参数配置字典
- :return:
"""
await db.execute(
update(SysConfig),
@@ -117,10 +114,9 @@ async def edit_config_dao(cls, db: AsyncSession, config: dict) -> None:
@classmethod
async def delete_config_dao(cls, db: AsyncSession, config: ConfigModel) -> None:
"""
- 删除参数配置数据库操作
+ 删除参数配置数据库操作。
:param db: orm对象
:param config: 参数配置对象
- :return:
"""
await db.execute(delete(SysConfig).where(SysConfig.config_id.in_([config.config_id])))
diff --git a/ruoyi-fastapi-backend/module_admin/dao/dept_dao.py b/ruoyi-fastapi-backend/module_admin/dao/dept_dao.py
index b70695107..9b7e1e7a6 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/dept_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/dept_dao.py
@@ -10,14 +10,12 @@
class DeptDao:
- """
- 部门管理模块数据库操作层
- """
+ """部门管理模块数据库操作层。"""
@classmethod
async def get_dept_by_id(cls, db: AsyncSession, dept_id: int) -> SysDept | None:
"""
- 根据部门id获取在用部门信息
+ 根据部门id获取在用部门信息。
:param db: orm对象
:param dept_id: 部门id
@@ -30,7 +28,7 @@ async def get_dept_by_id(cls, db: AsyncSession, dept_id: int) -> SysDept | None:
@classmethod
async def get_dept_detail_by_id(cls, db: AsyncSession, dept_id: int) -> SysDept | None:
"""
- 根据部门id获取部门详细信息
+ 根据部门id获取部门详细信息。
:param db: orm对象
:param dept_id: 部门id
@@ -47,7 +45,7 @@ async def get_dept_detail_by_id(cls, db: AsyncSession, dept_id: int) -> SysDept
@classmethod
async def get_dept_detail_by_info(cls, db: AsyncSession, dept: DeptModel) -> SysDept | None:
"""
- 根据部门参数获取部门信息
+ 根据部门参数获取部门信息。
:param db: orm对象
:param dept: 部门参数对象
@@ -74,7 +72,7 @@ async def get_dept_info_for_edit_option(
cls, db: AsyncSession, dept_info: DeptModel, data_scope_sql: ColumnElement
) -> Sequence[SysDept]:
"""
- 获取部门编辑对应的在用部门列表信息
+ 获取部门编辑对应的在用部门列表信息。
:param db: orm对象
:param dept_info: 部门对象
@@ -107,7 +105,7 @@ async def get_dept_info_for_edit_option(
@classmethod
async def get_children_dept_dao(cls, db: AsyncSession, dept_id: int) -> Sequence[SysDept]:
"""
- 根据部门id查询当前部门的子部门列表信息
+ 根据部门id查询当前部门的子部门列表信息。
:param db: orm对象
:param dept_id: 部门id
@@ -124,7 +122,7 @@ async def get_dept_list_for_tree(
cls, db: AsyncSession, dept_info: DeptModel, data_scope_sql: ColumnElement
) -> Sequence[SysDept]:
"""
- 获取所有在用部门列表信息
+ 获取所有在用部门列表信息。
:param db: orm对象
:param dept_info: 部门对象
@@ -156,7 +154,7 @@ async def get_dept_list(
cls, db: AsyncSession, page_object: DeptModel, data_scope_sql: ColumnElement
) -> Sequence[SysDept]:
"""
- 根据查询参数获取部门列表信息
+ 根据查询参数获取部门列表信息。
:param db: orm对象
:param page_object: 不分页查询参数对象
@@ -187,7 +185,7 @@ async def get_dept_list(
@classmethod
async def add_dept_dao(cls, db: AsyncSession, dept: DeptModel) -> SysDept:
"""
- 新增部门数据库操作
+ 新增部门数据库操作。
:param db: orm对象
:param dept: 部门对象
@@ -202,11 +200,10 @@ async def add_dept_dao(cls, db: AsyncSession, dept: DeptModel) -> SysDept:
@classmethod
async def edit_dept_dao(cls, db: AsyncSession, dept: dict) -> None:
"""
- 编辑部门数据库操作
+ 编辑部门数据库操作。
:param db: orm对象
:param dept: 需要更新的部门字典
- :return: 编辑校验结果
"""
await db.execute(
update(SysDept),
@@ -216,11 +213,10 @@ async def edit_dept_dao(cls, db: AsyncSession, dept: dict) -> None:
@classmethod
async def update_dept_children_dao(cls, db: AsyncSession, update_dept: list) -> None:
"""
- 更新子部门信息
+ 更新子部门信息。
:param db: orm对象
:param update_dept: 需要更新的部门列表
- :return:
"""
await db.execute(
update(SysDept)
@@ -238,11 +234,10 @@ async def update_dept_children_dao(cls, db: AsyncSession, update_dept: list) ->
@classmethod
async def update_dept_sort_dao(cls, db: AsyncSession, dept_sort_list: list[dict[str, int]]) -> None:
"""
- 批量更新部门显示顺序
+ 批量更新部门显示顺序。
:param db: orm对象
:param dept_sort_list: 部门id与显示顺序列表
- :return:
"""
await db.execute(
update(SysDept.__table__)
@@ -254,22 +249,20 @@ async def update_dept_sort_dao(cls, db: AsyncSession, dept_sort_list: list[dict[
@classmethod
async def update_dept_status_normal_dao(cls, db: AsyncSession, dept_id_list: list) -> None:
"""
- 批量更新部门状态为正常
+ 批量更新部门状态为正常。
:param db: orm对象
:param dept_id_list: 部门id列表
- :return:
"""
await db.execute(update(SysDept).where(SysDept.dept_id.in_(dept_id_list)).values(status='0'))
@classmethod
async def delete_dept_dao(cls, db: AsyncSession, dept: DeptModel) -> None:
"""
- 删除部门数据库操作
+ 删除部门数据库操作。
:param db: orm对象
:param dept: 部门对象
- :return:
"""
await db.execute(
update(SysDept).where(SysDept.dept_id == dept.dept_id).values(del_flag='2', update_by=dept.update_by)
@@ -278,7 +271,7 @@ async def delete_dept_dao(cls, db: AsyncSession, dept: DeptModel) -> None:
@classmethod
async def count_normal_children_dept_dao(cls, db: AsyncSession, dept_id: int) -> int | None:
"""
- 根据部门id查询查询所有子部门(正常状态)的数量
+ 根据部门id查询查询所有子部门(正常状态)的数量。
:param db: orm对象
:param dept_id: 部门id
@@ -297,7 +290,7 @@ async def count_normal_children_dept_dao(cls, db: AsyncSession, dept_id: int) ->
@classmethod
async def count_children_dept_dao(cls, db: AsyncSession, dept_id: int) -> int | None:
"""
- 根据部门id查询查询所有子部门(所有状态)的数量
+ 根据部门id查询查询所有子部门(所有状态)的数量。
:param db: orm对象
:param dept_id: 部门id
@@ -317,7 +310,7 @@ async def count_children_dept_dao(cls, db: AsyncSession, dept_id: int) -> int |
@classmethod
async def count_dept_user_dao(cls, db: AsyncSession, dept_id: int) -> int | None:
"""
- 根据部门id查询查询部门下的用户数量
+ 根据部门id查询查询部门下的用户数量。
:param db: orm对象
:param dept_id: 部门id
diff --git a/ruoyi-fastapi-backend/module_admin/dao/dict_dao.py b/ruoyi-fastapi-backend/module_admin/dao/dict_dao.py
index 4e89cc9d4..e896e0fd0 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/dict_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/dict_dao.py
@@ -13,14 +13,12 @@
class DictTypeDao:
- """
- 字典类型管理模块数据库操作层
- """
+ """字典类型管理模块数据库操作层。"""
@classmethod
async def get_dict_type_detail_by_id(cls, db: AsyncSession, dict_id: int) -> SysDictType | None:
"""
- 根据字典类型id获取字典类型详细信息
+ 根据字典类型id获取字典类型详细信息。
:param db: orm对象
:param dict_id: 字典类型id
@@ -33,7 +31,7 @@ async def get_dict_type_detail_by_id(cls, db: AsyncSession, dict_id: int) -> Sys
@classmethod
async def get_dict_type_detail_by_info(cls, db: AsyncSession, dict_type: DictTypeModel) -> SysDictType | None:
"""
- 根据字典类型参数获取字典类型信息
+ 根据字典类型参数获取字典类型信息。
:param db: orm对象
:param dict_type: 字典类型参数对象
@@ -57,7 +55,7 @@ async def get_dict_type_detail_by_info(cls, db: AsyncSession, dict_type: DictTyp
@classmethod
async def get_all_dict_type(cls, db: AsyncSession) -> list[Any]:
"""
- 获取所有的字典类型信息
+ 获取所有的字典类型信息。
:param db: orm对象
:return: 字典类型信息列表对象
@@ -71,7 +69,7 @@ async def get_dict_type_list(
cls, db: AsyncSession, query_object: DictTypePageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取字典类型列表信息
+ 根据查询参数获取字典类型列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -102,11 +100,11 @@ async def get_dict_type_list(
@classmethod
async def add_dict_type_dao(cls, db: AsyncSession, dict_type: DictTypeModel) -> SysDictType:
"""
- 新增字典类型数据库操作
+ 新增字典类型数据库操作。
:param db: orm对象
:param dict_type: 字典类型对象
- :return:
+ :return: 新增的字典类型记录
"""
db_dict_type = SysDictType(**dict_type.model_dump(exclude={'create_time', 'update_time'}))
db_dict_type.dict_name_i18n = TranslationUtil.merge(None, dict_type.dict_name_i18n)
@@ -118,11 +116,10 @@ async def add_dict_type_dao(cls, db: AsyncSession, dict_type: DictTypeModel) ->
@classmethod
async def edit_dict_type_dao(cls, db: AsyncSession, dict_type: dict) -> None:
"""
- 编辑字典类型数据库操作
+ 编辑字典类型数据库操作。
:param db: orm对象
:param dict_type: 需要更新的字典类型字典
- :return:
"""
if 'dict_name_i18n' in dict_type:
current = await db.scalar(
@@ -137,24 +134,21 @@ async def edit_dict_type_dao(cls, db: AsyncSession, dict_type: dict) -> None:
@classmethod
async def delete_dict_type_dao(cls, db: AsyncSession, dict_type: DictTypeModel) -> None:
"""
- 删除字典类型数据库操作
+ 删除字典类型数据库操作。
:param db: orm对象
:param dict_type: 字典类型对象
- :return:
"""
await db.execute(delete(SysDictType).where(SysDictType.dict_id.in_([dict_type.dict_id])))
class DictDataDao:
- """
- 字典数据管理模块数据库操作层
- """
+ """字典数据管理模块数据库操作层。"""
@classmethod
async def get_dict_data_detail_by_id(cls, db: AsyncSession, dict_code: int) -> SysDictData | None:
"""
- 根据字典数据id获取字典数据详细信息
+ 根据字典数据id获取字典数据详细信息。
:param db: orm对象
:param dict_code: 字典数据id
@@ -169,7 +163,7 @@ async def get_dict_data_detail_by_id(cls, db: AsyncSession, dict_code: int) -> S
@classmethod
async def get_dict_data_detail_by_info(cls, db: AsyncSession, dict_data: DictDataModel) -> SysDictData | None:
"""
- 根据字典数据参数获取字典数据信息
+ 根据字典数据参数获取字典数据信息。
:param db: orm对象
:param dict_data: 字典数据参数对象
@@ -196,7 +190,7 @@ async def get_dict_data_list(
cls, db: AsyncSession, query_object: DictDataPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取字典数据列表信息
+ 根据查询参数获取字典数据列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -222,7 +216,7 @@ async def get_dict_data_list(
@classmethod
async def query_dict_data_list(cls, db: AsyncSession, dict_type: str) -> Sequence[SysDictData | None]:
"""
- 查询启用字典类型及其启用的数据项
+ 查询启用字典类型及其启用的数据项。
:param db: orm对象
:param dict_type: 字典类型
@@ -252,11 +246,11 @@ async def query_dict_data_list(cls, db: AsyncSession, dict_type: str) -> Sequenc
@classmethod
async def add_dict_data_dao(cls, db: AsyncSession, dict_data: DictDataModel) -> SysDictData:
"""
- 新增字典数据数据库操作
+ 新增字典数据数据库操作。
:param db: orm对象
:param dict_data: 字典数据对象
- :return:
+ :return: 新增的字典数据记录
"""
db_data_type = SysDictData(**dict_data.model_dump(exclude={'create_time', 'update_time'}))
db_data_type.dict_label_i18n = TranslationUtil.merge(None, dict_data.dict_label_i18n)
@@ -268,11 +262,10 @@ async def add_dict_data_dao(cls, db: AsyncSession, dict_data: DictDataModel) ->
@classmethod
async def edit_dict_data_dao(cls, db: AsyncSession, dict_data: dict) -> None:
"""
- 编辑字典数据数据库操作
+ 编辑字典数据数据库操作。
:param db: orm对象
:param dict_data: 需要更新的字典数据字典
- :return:
"""
if 'dict_label_i18n' in dict_data:
current = await db.scalar(
@@ -289,18 +282,17 @@ async def edit_dict_data_dao(cls, db: AsyncSession, dict_data: dict) -> None:
@classmethod
async def delete_dict_data_dao(cls, db: AsyncSession, dict_data: DictDataModel) -> None:
"""
- 删除字典数据数据库操作
+ 删除字典数据数据库操作。
:param db: orm对象
:param dict_data: 字典数据对象
- :return:
"""
await db.execute(delete(SysDictData).where(SysDictData.dict_code.in_([dict_data.dict_code])))
@classmethod
async def count_dict_data_dao(cls, db: AsyncSession, dict_type: str) -> int | None:
"""
- 根据字典类型查询字典类型关联的字典数据数量
+ 根据字典类型查询字典类型关联的字典数据数量。
:param db: orm对象
:param dict_type: 字典类型
diff --git a/ruoyi-fastapi-backend/module_admin/dao/file_access_dao.py b/ruoyi-fastapi-backend/module_admin/dao/file_access_dao.py
index 5431c706b..32eb7d7a2 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/file_access_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/file_access_dao.py
@@ -18,9 +18,7 @@
class FileAclDao:
- """
- 文件访问控制数据操作层
- """
+ """文件访问控制数据操作层。"""
@classmethod
async def get_effective_file_acl_list(
@@ -30,7 +28,7 @@ async def get_effective_file_acl_list(
current_time: datetime,
) -> list[SysFileAcl]:
"""
- 获取文件有效访问控制列表
+ 获取文件有效访问控制列表。
:param db: orm对象
:param file_id: 文件ID
@@ -55,7 +53,7 @@ async def get_effective_file_acl_list(
@classmethod
async def get_file_acl_list(cls, db: AsyncSession, file_id: str) -> list[SysFileAcl]:
"""
- 获取文件访问控制列表
+ 获取文件访问控制列表。
:param db: orm对象
:param file_id: 文件ID
@@ -76,7 +74,7 @@ async def get_file_acl_list(cls, db: AsyncSession, file_id: str) -> list[SysFile
@classmethod
async def get_acl_dept_list(cls, db: AsyncSession, dept_data_scope_sql: ColumnElement) -> list[SysDept]:
"""
- 获取文件授权可选部门列表
+ 获取文件授权可选部门列表。
:param db: orm对象
:param dept_data_scope_sql: 部门数据权限对应的查询sql语句
@@ -97,12 +95,11 @@ async def get_acl_dept_list(cls, db: AsyncSession, dept_data_scope_sql: ColumnEl
@classmethod
async def replace_file_acl_list(cls, db: AsyncSession, file_id: str, file_acl_list: list[SysFileAcl]) -> None:
"""
- 替换文件访问控制列表
+ 替换文件访问控制列表。
:param db: orm对象
:param file_id: 文件ID
:param file_acl_list: 文件访问控制列表
- :return: None
"""
await db.execute(delete(SysFileAcl).where(SysFileAcl.file_id == file_id))
if file_acl_list:
@@ -117,12 +114,11 @@ async def replace_file_acl_lists(
file_acl_list: list[SysFileAcl],
) -> None:
"""
- 批量替换文件访问控制列表
+ 批量替换文件访问控制列表。
:param db: orm对象
:param file_ids: 文件ID列表
:param file_acl_list: 文件访问控制列表
- :return: None
"""
await db.execute(delete(SysFileAcl).where(SysFileAcl.file_id.in_(file_ids)))
if file_acl_list:
@@ -138,7 +134,7 @@ async def get_acl_subject_name_map(
dept_data_scope_sql: ColumnElement,
) -> dict[tuple[str, int], str]:
"""
- 获取访问控制主体名称映射
+ 获取访问控制主体名称映射。
:param db: orm对象
:param subject_ids: 按主体类型分组的主体ID
@@ -205,7 +201,7 @@ async def search_acl_subjects(
dept_data_scope_sql: ColumnElement,
) -> list[dict[str, Any]]:
"""
- 查询访问控制主体选项
+ 查询访问控制主体选项。
:param db: orm对象
:param subject_type: 主体类型
@@ -265,7 +261,7 @@ async def _filter_role_rows_by_data_scope(
user_data_scope_sql: ColumnElement,
) -> list[Any]:
"""
- 过滤包含数据权限范围外成员的角色
+ 过滤包含数据权限范围外成员的角色。
:param db: orm对象
:param role_rows: 候选角色列表
@@ -313,14 +309,12 @@ async def _filter_role_rows_by_data_scope(
class FileAccessLogDao:
- """
- 文件访问审计数据操作层
- """
+ """文件访问审计数据操作层。"""
@classmethod
async def add_file_access_log_dao(cls, db: AsyncSession, file_access_log: FileAccessLogModel) -> SysFileAccessLog:
"""
- 新增文件访问审计记录
+ 新增文件访问审计记录。
:param db: orm对象
:param file_access_log: 文件访问审计对象
@@ -340,7 +334,7 @@ async def get_file_access_log_list(
is_page: bool = False,
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取文件访问审计列表
+ 根据查询参数获取文件访问审计列表。
:param db: orm对象
:param file_id: 文件ID
diff --git a/ruoyi-fastapi-backend/module_admin/dao/file_business_dao.py b/ruoyi-fastapi-backend/module_admin/dao/file_business_dao.py
index c8c744641..1232badd2 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/file_business_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/file_business_dao.py
@@ -19,14 +19,12 @@
class FileReferenceDao:
- """
- 文件业务引用数据操作层
- """
+ """文件业务引用数据操作层。"""
@classmethod
async def get_file_reference_list(cls, db: AsyncSession, file_id: str) -> list[SysFileReference]:
"""
- 获取文件业务引用列表
+ 获取文件业务引用列表。
:param db: orm对象
:param file_id: 文件ID
@@ -51,7 +49,7 @@ async def get_file_reference_list(cls, db: AsyncSession, file_id: str) -> list[S
@classmethod
async def get_file_reference_list_for_update(cls, db: AsyncSession, file_id: str) -> list[SysFileReference]:
"""
- 锁定文件业务引用列表
+ 锁定文件业务引用列表。
:param db: orm对象
:param file_id: 文件ID
@@ -73,18 +71,17 @@ async def get_file_reference_list_for_update(cls, db: AsyncSession, file_id: str
@classmethod
async def delete_file_references(cls, db: AsyncSession, file_id: str) -> None:
"""
- 删除文件的全部业务引用
+ 删除文件的全部业务引用。
:param db: orm对象
:param file_id: 文件ID
- :return: None
"""
await db.execute(delete(SysFileReference).where(SysFileReference.file_id == file_id))
@classmethod
async def get_file_reference_count_map(cls, db: AsyncSession, file_ids: list[str]) -> dict[str, int]:
"""
- 获取文件业务引用数量映射
+ 获取文件业务引用数量映射。
:param db: orm对象
:param file_ids: 文件ID列表
@@ -117,13 +114,12 @@ async def replace_business_file_references(
file_reference_list: list[SysFileReference],
) -> None:
"""
- 替换业务对象的文件引用
+ 替换业务对象的文件引用。
:param db: orm对象
:param business_type: 业务类型
:param business_id: 业务ID
:param file_reference_list: 文件业务引用列表
- :return: None
"""
old_reference_list = list(
(
@@ -180,7 +176,12 @@ def _preserve_later_retention_expire_times(
old_reference_list: list[SysFileReference],
new_reference_list: list[SysFileReference],
) -> None:
- """保留同一业务引用已经延长的更晚到期时间。"""
+ """
+ 保留同一业务引用已经延长的更晚到期时间。
+
+ :param old_reference_list: 更新前的文件引用集合
+ :param new_reference_list: 更新后的文件引用集合
+ """
old_reference_map = {reference.file_id: reference for reference in old_reference_list}
for reference in new_reference_list:
old_reference = old_reference_map.get(reference.file_id)
@@ -199,7 +200,13 @@ async def _refresh_file_expire_times(
file_ids: list[str],
file_info_map: dict[str, SysFileInfo],
) -> None:
- """根据业务引用重新计算文件过期时间。"""
+ """
+ 根据业务引用重新计算文件过期时间。
+
+ :param db: 当前操作使用的数据库会话
+ :param file_ids: 文件ID列表
+ :param file_info_map: 按文件标识索引的元数据
+ """
if not file_ids:
return
rows = (
@@ -232,14 +239,12 @@ async def _refresh_file_expire_times(
class FileRetentionPolicyDao:
- """
- 文件业务保留策略数据操作层
- """
+ """文件业务保留策略数据操作层。"""
@classmethod
async def get_file_retention_policy_list(cls, db: AsyncSession) -> list[SysFileRetentionPolicy]:
"""
- 获取文件业务保留策略列表
+ 获取文件业务保留策略列表。
:param db: orm对象
:return: 文件业务保留策略列表
@@ -258,7 +263,7 @@ async def get_file_retention_policy_by_business_type(
enabled_only: bool = False,
) -> SysFileRetentionPolicy | None:
"""
- 根据业务类型获取文件业务保留策略
+ 根据业务类型获取文件业务保留策略。
:param db: orm对象
:param business_type: 业务类型
@@ -285,11 +290,10 @@ async def add_file_retention_policy(
policy: SysFileRetentionPolicy,
) -> None:
"""
- 新增文件业务保留策略
+ 新增文件业务保留策略。
:param db: orm对象
:param policy: 文件业务保留策略
- :return: None
"""
db.add(policy)
await db.flush()
@@ -302,12 +306,11 @@ async def edit_file_retention_policy(
policy: dict,
) -> None:
"""
- 修改文件业务保留策略
+ 修改文件业务保留策略。
:param db: orm对象
:param business_type: 业务类型
:param policy: 文件业务保留策略
- :return: None
"""
await db.execute(
update(SysFileRetentionPolicy)
@@ -318,19 +321,16 @@ async def edit_file_retention_policy(
@classmethod
async def delete_file_retention_policy(cls, db: AsyncSession, business_type: str) -> None:
"""
- 删除文件业务保留策略
+ 删除文件业务保留策略。
:param db: orm对象
:param business_type: 业务类型
- :return: None
"""
await db.execute(delete(SysFileRetentionPolicy).where(SysFileRetentionPolicy.business_type == business_type))
class FileRetentionNoticeDao:
- """
- 文件保留期限提醒数据操作层
- """
+ """文件保留期限提醒数据操作层。"""
@classmethod
async def get_missing_notice_candidates(
@@ -343,7 +343,7 @@ async def get_missing_notice_candidates(
file_data_scope_sql: ColumnElement | bool = True,
) -> list[SysFileInfo]:
"""
- 获取尚未生成当前到期提醒的文件
+ 获取尚未生成当前到期提醒的文件。
:param db: orm对象
:param notice_type: 提醒类型
@@ -398,11 +398,10 @@ async def add_file_retention_notices(
notice_list: list[SysFileRetentionNotice],
) -> None:
"""
- 批量新增文件保留期限提醒
+ 批量新增文件保留期限提醒。
:param db: orm对象
:param notice_list: 提醒对象列表
- :return: None
"""
if notice_list:
db.add_all(notice_list)
@@ -411,11 +410,10 @@ async def add_file_retention_notices(
@classmethod
async def invalidate_expiring_notices(cls, db: AsyncSession, file_ids: list[str]) -> None:
"""
- 将已经到期文件的即将到期提醒标记为失效
+ 将已经到期文件的即将到期提醒标记为失效。
:param db: orm对象
:param file_ids: 文件ID列表
- :return: None
"""
if not file_ids:
return
@@ -437,12 +435,11 @@ async def invalidate_changed_expire_time_notices(
expire_time: datetime | None,
) -> None:
"""
- 将与文件当前到期时间不一致的未读提醒标记为失效
+ 将与文件当前到期时间不一致的未读提醒标记为失效。
:param db: orm对象
:param file_id: 文件ID
:param expire_time: 文件当前到期时间
- :return: None
"""
expire_condition = (
True
@@ -471,7 +468,7 @@ async def get_file_retention_notice_list(
is_page: bool = False,
) -> PageModel | list[dict[str, Any]]:
"""
- 获取文件保留期限提醒列表
+ 获取文件保留期限提醒列表。
:param db: orm对象
:param query_object: 查询参数
@@ -541,7 +538,7 @@ async def get_file_retention_notice_context_for_update(
file_data_scope_sql: ColumnElement,
) -> tuple[SysFileRetentionNotice, SysFileInfo] | None:
"""
- 锁定数据权限范围内的有效提醒和文件
+ 锁定数据权限范围内的有效提醒和文件。
:param db: orm对象
:param notice_id: 提醒ID
@@ -574,7 +571,7 @@ async def get_notice_ids_in_data_scope_for_update(
file_data_scope_sql: ColumnElement,
) -> list[int]:
"""
- 锁定数据权限范围内的有效提醒
+ 锁定数据权限范围内的有效提醒。
:param db: orm对象
:param notice_ids: 提醒ID列表
@@ -612,13 +609,12 @@ async def mark_file_retention_notices_read(
read_time: datetime,
) -> None:
"""
- 标记文件保留期限提醒为已读
+ 标记文件保留期限提醒为已读。
:param db: orm对象
:param notice_ids: 提醒ID列表
:param read_by: 读取者
:param read_time: 读取时间
- :return: None
"""
await db.execute(
update(SysFileRetentionNotice)
@@ -632,11 +628,10 @@ async def mark_file_retention_notices_read(
@classmethod
async def invalidate_file_retention_notices(cls, db: AsyncSession, file_id: str) -> None:
"""
- 将文件当前有效的保留期限提醒标记为失效
+ 将文件当前有效的保留期限提醒标记为失效。
:param db: orm对象
:param file_id: 文件ID
- :return: None
"""
await db.execute(
update(SysFileRetentionNotice)
diff --git a/ruoyi-fastapi-backend/module_admin/dao/file_info_dao.py b/ruoyi-fastapi-backend/module_admin/dao/file_info_dao.py
index f505e6537..ead1999c5 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/file_info_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/file_info_dao.py
@@ -28,7 +28,10 @@
class FileInfoDao:
"""
- 文件信息数据操作层
+ 文件信息数据操作层。
+
+ :cvar FILE_EXPIRING_DAYS: 查询即将到期文件时向前看的天数
+ :cvar ACL_EXPIRING_DAYS: 查询即将到期授权时向前看的天数
"""
FILE_EXPIRING_DAYS = 7
@@ -37,7 +40,7 @@ class FileInfoDao:
@classmethod
async def add_file_info_dao(cls, db: AsyncSession, file_info: FileInfoModel) -> SysFileInfo:
"""
- 新增文件信息
+ 新增文件信息。
:param db: orm对象
:param file_info: 文件信息对象
@@ -56,7 +59,7 @@ async def get_file_info_by_id(
file_data_scope_sql: ColumnElement | None = None,
) -> SysFileInfo | None:
"""
- 根据文件ID获取有效文件信息
+ 根据文件ID获取有效文件信息。
:param db: orm对象
:param file_id: 文件ID
@@ -81,12 +84,11 @@ async def get_file_info_by_id(
@classmethod
async def release_stale_runs(cls, db: AsyncSession, stale_before: datetime, current_time: datetime) -> None:
"""
- 释放超时未完成的对账任务锁
+ 释放超时未完成的对账任务锁。
:param db: orm对象
:param stale_before: 超时边界
:param current_time: 当前时间
- :return: None
"""
await db.execute(
update(SysFileReconcileRun)
@@ -105,11 +107,10 @@ async def release_stale_runs(cls, db: AsyncSession, stale_before: datetime, curr
@classmethod
async def add_reconcile_run(cls, db: AsyncSession, reconcile_run: SysFileReconcileRun) -> None:
"""
- 新增文件存储对账任务
+ 新增文件存储对账任务。
:param db: orm对象
:param reconcile_run: 对账任务
- :return: None
"""
db.add(reconcile_run)
await db.flush()
@@ -117,7 +118,7 @@ async def add_reconcile_run(cls, db: AsyncSession, reconcile_run: SysFileReconci
@classmethod
async def get_reconcile_run_by_id(cls, db: AsyncSession, run_id: str) -> SysFileReconcileRun | None:
"""
- 根据任务ID获取文件存储对账任务
+ 根据任务ID获取文件存储对账任务。
:param db: orm对象
:param run_id: 任务ID
@@ -132,7 +133,7 @@ async def get_reconcile_run_by_id(cls, db: AsyncSession, run_id: str) -> SysFile
@classmethod
async def has_running_reconcile_run(cls, db: AsyncSession) -> bool:
"""
- 判断是否存在运行中的文件存储对账任务
+ 判断是否存在运行中的文件存储对账任务。
:param db: orm对象
:return: 是否正在运行
@@ -147,7 +148,7 @@ async def get_reconcile_run_list(
is_page: bool = True,
) -> PageModel | list[dict[str, Any]]:
"""
- 获取文件存储对账任务列表
+ 获取文件存储对账任务列表。
:param db: orm对象
:param query_object: 查询参数
@@ -181,7 +182,7 @@ async def get_reconcile_run_list(
@classmethod
async def get_all_local_file_infos(cls, db: AsyncSession) -> list[dict[str, Any]]:
"""
- 获取全部本地文件存储信息
+ 获取全部本地文件存储信息。
:param db: orm对象
:return: 文件存储信息列表
@@ -216,7 +217,7 @@ async def upsert_reconcile_issues(
current_time: datetime,
) -> int:
"""
- 新增或更新文件存储对账异常
+ 新增或更新文件存储对账异常。
:param db: orm对象
:param run_id: 任务ID
@@ -283,7 +284,7 @@ async def resolve_disappeared_issues(
current_time: datetime,
) -> int:
"""
- 自动关闭本次扫描未再次出现的异常
+ 自动关闭本次扫描未再次出现的异常。
:param db: orm对象
:param run_id: 任务ID
@@ -322,9 +323,18 @@ async def finish_reconcile_run(
error_message: str = '',
) -> None:
"""
- 完成文件存储对账任务
+ 完成文件存储对账任务。
- :return: None
+ :param db: 当前操作使用的数据库会话
+ :param run_id: 任务ID
+ :param status: 操作或记录所处的状态
+ :param finished_time: 操作完成时间
+ :param scanned_file_count: 已检查的文件记录数量
+ :param scanned_storage_count: 已扫描的存储对象数量
+ :param issue_count: 检出的异常总数
+ :param new_issue_count: 本次新增的异常数
+ :param resolved_issue_count: 本次已解决的异常数
+ :param error_message: 记录到结果或审计日志中的错误详情
"""
await db.execute(
update(SysFileReconcileRun)
@@ -350,7 +360,7 @@ async def get_reconcile_issue_list(
is_page: bool = True,
) -> PageModel | list[dict[str, Any]]:
"""
- 获取文件存储对账异常列表
+ 获取文件存储对账异常列表。
:param db: orm对象
:param query_object: 查询参数
@@ -399,7 +409,7 @@ async def get_reconcile_issue_for_update(
issue_id: int,
) -> SysFileReconcileIssue | None:
"""
- 锁定文件存储对账异常
+ 锁定文件存储对账异常。
:param db: orm对象
:param issue_id: 异常ID
@@ -422,7 +432,7 @@ async def get_file_info_for_reconcile(
file_id: str,
) -> SysFileInfo | None:
"""
- 锁定对账异常关联的文件信息
+ 锁定对账异常关联的文件信息。
:param db: orm对象
:param file_id: 文件ID
@@ -444,9 +454,13 @@ async def resolve_file_integrity_issues(
reason: str,
) -> None:
"""
- 关闭文件大小和摘要不一致异常
+ 关闭文件大小和摘要不一致异常。
- :return: None
+ :param db: 当前操作使用的数据库会话
+ :param file_id: 文件ID
+ :param current_time: 当前时间
+ :param handled_by: 处理该问题的用户标识
+ :param reason: 作出该决定或状态变化的原因
"""
await db.execute(
update(SysFileReconcileIssue)
@@ -467,7 +481,7 @@ async def resolve_file_integrity_issues(
@classmethod
async def get_reconcile_stats(cls, db: AsyncSession) -> dict[str, Any]:
"""
- 获取文件存储对账统计
+ 获取文件存储对账统计。
:param db: orm对象
:return: 对账统计
@@ -535,7 +549,7 @@ async def get_file_info_detail_by_id(
file_data_scope_sql: ColumnElement | None = None,
) -> SysFileInfo | None:
"""
- 根据文件ID获取文件详细信息
+ 根据文件ID获取文件详细信息。
:param db: orm对象
:param file_id: 文件ID
@@ -563,7 +577,7 @@ async def get_file_info_by_id_for_update(
file_data_scope_sql: ColumnElement | None = None,
) -> SysFileInfo | None:
"""
- 根据文件ID锁定有效文件信息
+ 根据文件ID锁定有效文件信息。
:param db: orm对象
:param file_id: 文件ID
@@ -595,7 +609,7 @@ async def get_file_infos_by_ids_for_update(
file_data_scope_sql: ColumnElement | None = None,
) -> list[SysFileInfo]:
"""
- 根据文件ID列表锁定有效文件信息
+ 根据文件ID列表锁定有效文件信息。
:param db: orm对象
:param file_ids: 文件ID列表
@@ -628,7 +642,7 @@ async def get_deleted_file_infos_by_ids_for_update(
file_data_scope_sql: ColumnElement | None = None,
) -> list[SysFileInfo]:
"""
- 根据文件ID列表锁定已删除文件信息
+ 根据文件ID列表锁定已删除文件信息。
:param db: orm对象
:param file_ids: 文件ID列表
@@ -661,7 +675,7 @@ async def get_purgeable_file_infos_by_ids_for_update(
file_data_scope_sql: ColumnElement | None = None,
) -> list[SysFileInfo]:
"""
- 根据文件ID列表锁定可永久清理的文件信息
+ 根据文件ID列表锁定可永久清理的文件信息。
:param db: orm对象
:param file_ids: 文件ID列表
@@ -694,7 +708,7 @@ async def get_recycle_bin_purge_candidates(
batch_size: int,
) -> list[SysFileInfo]:
"""
- 获取自动清理的回收站文件
+ 获取自动清理的回收站文件。
:param db: orm对象
:param deleted_before: 最晚删除时间
@@ -738,7 +752,7 @@ async def get_file_info_list(
is_page: bool = False,
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取文件信息列表
+ 根据查询参数获取文件信息列表。
:param db: orm对象
:param query_object: 文件信息查询参数
@@ -787,7 +801,7 @@ async def get_file_management_detail_by_id(
file_data_scope_sql: ColumnElement,
) -> dict[str, Any] | None:
"""
- 获取包含管理展示字段的文件详情
+ 获取包含管理展示字段的文件详情。
:param db: orm对象
:param file_id: 文件ID
@@ -837,7 +851,7 @@ async def get_file_stats(
file_data_scope_sql: ColumnElement,
) -> FileStatsModel:
"""
- 获取文件管理统计信息
+ 获取文件管理统计信息。
:param db: orm对象
:param query_object: 文件信息查询参数
@@ -932,7 +946,7 @@ def _get_file_info_query_conditions(
current_time: datetime,
) -> list[ColumnElement | bool]:
"""
- 构建文件管理查询条件
+ 构建文件管理查询条件。
:param query_object: 文件信息查询参数
:param current_time: 当前时间
@@ -975,13 +989,12 @@ async def soft_delete_file_infos(
update_time: datetime,
) -> None:
"""
- 逻辑删除文件信息
+ 逻辑删除文件信息。
:param db: orm对象
:param file_ids: 文件ID列表
:param update_by: 更新者
:param update_time: 更新时间
- :return: None
"""
await db.execute(
update(SysFileInfo)
@@ -1004,13 +1017,12 @@ async def restore_file_infos(
update_time: datetime,
) -> None:
"""
- 恢复文件信息
+ 恢复文件信息。
:param db: orm对象
:param file_ids: 文件ID列表
:param update_by: 更新者
:param update_time: 更新时间
- :return: None
"""
await db.execute(
update(SysFileInfo)
@@ -1033,13 +1045,12 @@ async def mark_file_infos_purging(
update_time: datetime,
) -> None:
"""
- 标记文件正在执行永久清理
+ 标记文件正在执行永久清理。
:param db: orm对象
:param file_ids: 文件ID列表
:param update_by: 更新者
:param update_time: 更新时间
- :return: None
"""
await db.execute(
update(SysFileInfo)
@@ -1058,11 +1069,10 @@ async def mark_file_infos_purging(
@classmethod
async def purge_file_infos(cls, db: AsyncSession, file_ids: list[str]) -> None:
"""
- 永久删除文件元数据及关联管理数据
+ 永久删除文件元数据及关联管理数据。
:param db: orm对象
:param file_ids: 文件ID列表
- :return: None
"""
await db.execute(delete(SysFileAcl).where(SysFileAcl.file_id.in_(file_ids)))
await db.execute(delete(SysFileReference).where(SysFileReference.file_id.in_(file_ids)))
@@ -1083,7 +1093,7 @@ async def get_transfer_user_by_id(
user_data_scope_sql: ColumnElement,
) -> SysUser | None:
"""
- 获取数据权限范围内的文件转移目标用户
+ 获取数据权限范围内的文件转移目标用户。
:param db: orm对象
:param user_id: 用户ID
@@ -1115,7 +1125,7 @@ async def get_transfer_dept_by_id(
dept_data_scope_sql: ColumnElement,
) -> SysDept | None:
"""
- 获取数据权限范围内的文件转移目标部门
+ 获取数据权限范围内的文件转移目标部门。
:param db: orm对象
:param dept_id: 部门ID
@@ -1151,7 +1161,7 @@ async def transfer_file_infos(
update_time: datetime,
) -> None:
"""
- 批量转移文件所有者和所属部门
+ 批量转移文件所有者和所属部门。
:param db: orm对象
:param file_ids: 文件ID列表
@@ -1160,7 +1170,6 @@ async def transfer_file_infos(
:param retain_uploader_access: 是否保留上传人访问权限
:param update_by: 更新者
:param update_time: 更新时间
- :return: None
"""
await db.execute(
update(SysFileInfo)
@@ -1184,7 +1193,7 @@ async def get_file_info_by_storage_key(
storage_type: str = 'local',
) -> SysFileInfo | None:
"""
- 根据存储相对路径获取文件信息
+ 根据存储相对路径获取文件信息。
:param db: orm对象
:param storage_key: 存储相对路径
diff --git a/ruoyi-fastapi-backend/module_admin/dao/job_dao.py b/ruoyi-fastapi-backend/module_admin/dao/job_dao.py
index 77261f8bd..47484b748 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/job_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/job_dao.py
@@ -11,14 +11,12 @@
class JobDao:
- """
- 定时任务管理模块数据库操作层
- """
+ """定时任务管理模块数据库操作层。"""
@classmethod
async def get_job_detail_by_id(cls, db: AsyncSession, job_id: int) -> SysJob | None:
"""
- 根据定时任务id获取定时任务详细信息
+ 根据定时任务id获取定时任务详细信息。
:param db: orm对象
:param job_id: 定时任务id
@@ -31,7 +29,7 @@ async def get_job_detail_by_id(cls, db: AsyncSession, job_id: int) -> SysJob | N
@classmethod
async def get_job_detail_by_info(cls, db: AsyncSession, job: JobModel) -> SysJob | None:
"""
- 根据定时任务参数获取定时任务信息
+ 根据定时任务参数获取定时任务信息。
:param db: orm对象
:param job: 定时任务参数对象
@@ -57,7 +55,7 @@ async def get_job_list(
cls, db: AsyncSession, query_object: JobPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取定时任务列表信息
+ 根据查询参数获取定时任务列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -82,7 +80,7 @@ async def get_job_list(
@classmethod
async def get_job_list_for_scheduler(cls, db: AsyncSession) -> Sequence[SysJob]:
"""
- 获取定时任务列表信息
+ 获取定时任务列表信息。
:param db: orm对象
:return: 定时任务列表信息对象
@@ -94,7 +92,7 @@ async def get_job_list_for_scheduler(cls, db: AsyncSession) -> Sequence[SysJob]:
@classmethod
async def get_all_job_list_for_scheduler(cls, db: AsyncSession) -> Sequence[SysJob]:
"""
- 获取全部定时任务列表信息
+ 获取全部定时任务列表信息。
:param db: orm对象
:return: 定时任务列表信息对象
@@ -106,11 +104,11 @@ async def get_all_job_list_for_scheduler(cls, db: AsyncSession) -> Sequence[SysJ
@classmethod
async def add_job_dao(cls, db: AsyncSession, job: JobModel) -> SysJob:
"""
- 新增定时任务数据库操作
+ 新增定时任务数据库操作。
:param db: orm对象
:param job: 定时任务对象
- :return:
+ :return: 新增的定时任务记录
"""
db_job = SysJob(
**job.model_dump(
@@ -136,12 +134,11 @@ async def add_job_dao(cls, db: AsyncSession, job: JobModel) -> SysJob:
@classmethod
async def edit_job_dao(cls, db: AsyncSession, job: dict, old_job: JobModel) -> None:
"""
- 编辑定时任务数据库操作
+ 编辑定时任务数据库操作。
:param db: orm对象
:param job: 需要更新的定时任务字典
:param old_job: 原定时任务对象
- :return:
"""
await db.execute(
update(SysJob)
@@ -154,10 +151,9 @@ async def edit_job_dao(cls, db: AsyncSession, job: dict, old_job: JobModel) -> N
@classmethod
async def delete_job_dao(cls, db: AsyncSession, job: JobModel) -> None:
"""
- 删除定时任务数据库操作
+ 删除定时任务数据库操作。
:param db: orm对象
:param job: 定时任务对象
- :return:
"""
await db.execute(delete(SysJob).where(SysJob.job_id.in_([job.job_id])))
diff --git a/ruoyi-fastapi-backend/module_admin/dao/job_log_dao.py b/ruoyi-fastapi-backend/module_admin/dao/job_log_dao.py
index 4120258da..ccc71ff95 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/job_log_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/job_log_dao.py
@@ -12,16 +12,14 @@
class JobLogDao:
- """
- 定时任务日志管理模块数据库操作层
- """
+ """定时任务日志管理模块数据库操作层。"""
@classmethod
async def get_job_log_list(
cls, db: AsyncSession, query_object: JobLogPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取定时任务日志列表信息
+ 根据查询参数获取定时任务日志列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -53,11 +51,11 @@ async def get_job_log_list(
@classmethod
def add_job_log_dao(cls, db: Session, job_log: JobLogModel) -> SysJobLog:
"""
- 新增定时任务日志数据库操作
+ 新增定时任务日志数据库操作。
:param db: orm对象
:param job_log: 定时任务日志对象
- :return:
+ :return: 新增的任务日志记录
"""
db_job_log = SysJobLog(**job_log.model_dump())
db.add(db_job_log)
@@ -68,20 +66,18 @@ def add_job_log_dao(cls, db: Session, job_log: JobLogModel) -> SysJobLog:
@classmethod
async def delete_job_log_dao(cls, db: AsyncSession, job_log: JobLogModel) -> None:
"""
- 删除定时任务日志数据库操作
+ 删除定时任务日志数据库操作。
:param db: orm对象
:param job_log: 定时任务日志对象
- :return:
"""
await db.execute(delete(SysJobLog).where(SysJobLog.job_log_id.in_([job_log.job_log_id])))
@classmethod
async def clear_job_log_dao(cls, db: AsyncSession) -> None:
"""
- 清除定时任务日志数据库操作
+ 清除定时任务日志数据库操作。
:param db: orm对象
- :return:
"""
await db.execute(delete(SysJobLog))
diff --git a/ruoyi-fastapi-backend/module_admin/dao/job_runtime_dao.py b/ruoyi-fastapi-backend/module_admin/dao/job_runtime_dao.py
index a8105e8bf..e7428329e 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/job_runtime_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/job_runtime_dao.py
@@ -20,7 +20,9 @@
class JobRuntimeDao:
"""
- 在业务事务内维护版本、删除记录和手动执行请求
+ 在业务事务内维护版本、删除记录和手动执行请求。
+
+ :cvar LEASE_SECONDS: 工作租约保持有效的秒数
"""
LEASE_SECONDS = 30
@@ -28,11 +30,11 @@ class JobRuntimeDao:
@staticmethod
async def ensure_state(db: AsyncSession, job_id: int) -> None:
"""
- 原子建立状态行,避免两个事务首次接触同一任务时重复插入
+ 原子建立状态行,避免两个事务首次接触同一任务时重复插入。
:param db: orm对象
:param job_id: 任务ID
- :return: None
+ :raises ValueError: 数据库方言不支持任务状态初始化
"""
values = {
'job_id': job_id,
@@ -56,7 +58,7 @@ async def ensure_state(db: AsyncSession, job_id: int) -> None:
@classmethod
async def lock_job(cls, db: AsyncSession, job_id: int) -> tuple[SysJob | None, SysJobSync | None]:
"""
- 按同步状态、任务记录的固定顺序加锁,并为已有任务建立初始状态
+ 按同步状态、任务记录的固定顺序加锁,并为已有任务建立初始状态。
:param db: orm对象
:param job_id: 任务ID
@@ -73,7 +75,7 @@ async def lock_job(cls, db: AsyncSession, job_id: int) -> tuple[SysJob | None, S
@classmethod
async def record_configuration(cls, db: AsyncSession, job_id: int, job: JobModel | None) -> SysJobSync:
"""
- 在业务提交前记录最新配置版本,任务删除后仍保留同步状态
+ 在业务提交前记录最新配置版本,任务删除后仍保留同步状态。
:param db: orm对象
:param job_id: 任务ID
@@ -109,7 +111,7 @@ async def record_configuration(cls, db: AsyncSession, job_id: int, job: JobModel
@staticmethod
def state_result(state: SysJobSync) -> dict[str, Any]:
"""
- 构造可供接口返回的同步状态,避免暴露 ORM 对象
+ 构造可供接口返回的同步状态,避免暴露 ORM 对象。
:param state: 任务同步状态对象
:return: 任务同步状态字典
@@ -129,7 +131,7 @@ def state_result(state: SysJobSync) -> dict[str, Any]:
@classmethod
async def get_states(cls, db: AsyncSession, job_ids: list[int]) -> dict[int, dict[str, Any]]:
"""
- 批量读取任务同步状态,供列表和变更响应使用
+ 批量读取任务同步状态,供列表和变更响应使用。
:param db: orm对象
:param job_ids: 任务ID集合
@@ -151,7 +153,7 @@ async def get_states(cls, db: AsyncSession, job_ids: list[int]) -> dict[int, dic
@classmethod
async def all_sync_ids(cls, db: AsyncSession) -> set[int]:
"""
- 收集任务与删除记录,支持完整校准和删除同步重试
+ 收集任务与删除记录,支持完整校准和删除同步重试。
:param db: orm对象
:return: 需要校准的任务ID集合
@@ -165,7 +167,7 @@ async def all_sync_ids(cls, db: AsyncSession) -> set[int]:
@staticmethod
async def pending_sync_ids(db: AsyncSession) -> set[int]:
"""
- 读取需要重试的同步状态,包括已经删除的任务
+ 读取需要重试的同步状态,包括已经删除的任务。
:param db: orm对象
:return: 待同步任务ID集合
@@ -177,11 +179,10 @@ async def pending_sync_ids(db: AsyncSession) -> set[int]:
@staticmethod
async def cancel_unstarted(db: AsyncSession, job_ids: list[int]) -> None:
"""
- 删除任务时取消未开始的手动请求,保留运行中的执行记录
+ 删除任务时取消未开始的手动请求,保留运行中的执行记录。
:param db: orm对象
:param job_ids: 任务ID集合
- :return: None
"""
await db.execute(
update(SysJobExecution)
@@ -198,7 +199,7 @@ async def cancel_unstarted(db: AsyncSession, job_ids: list[int]) -> None:
@classmethod
async def create_request(cls, db: AsyncSession, job: JobModel, requested_by: str | None) -> SysJobExecution:
"""
- 在事务内保存手动请求及配置快照,派发必须发生在提交之后
+ 在事务内保存手动请求及配置快照,派发必须发生在提交之后。
:param db: orm对象
:param job: 任务对象信息
@@ -220,7 +221,7 @@ async def create_request(cls, db: AsyncSession, job: JobModel, requested_by: str
@staticmethod
async def get_execution(db: AsyncSession, execution_id: str) -> SysJobExecution | None:
"""
- 按执行 ID 查询手动或定时执行结果
+ 按执行 ID 查询手动或定时执行结果。
:param db: orm对象
:param execution_id: 执行ID
@@ -231,7 +232,7 @@ async def get_execution(db: AsyncSession, execution_id: str) -> SysJobExecution
@staticmethod
async def execution_page(db: AsyncSession, query: JobExecutionQueryModel) -> PageModel:
"""
- 分页查询执行状态,排除配置参数和内部占用凭据
+ 分页查询执行状态,排除配置参数和内部占用凭据。
:param db: orm对象
:param query: 查询参数对象
@@ -268,7 +269,7 @@ async def execution_page(db: AsyncSession, query: JobExecutionQueryModel) -> Pag
@staticmethod
async def sync_page(db: AsyncSession, query: JobSyncQueryModel) -> PageModel:
"""
- 分页查询同步状态,删除任务后仍能查看结果和发起重试
+ 分页查询同步状态,删除任务后仍能查看结果和发起重试。
:param db: orm对象
:param query: 查询参数对象
@@ -300,7 +301,7 @@ async def sync_page(db: AsyncSession, query: JobSyncQueryModel) -> PageModel:
@staticmethod
def execution_result(execution: SysJobExecution) -> dict[str, Any]:
"""
- 返回执行状态和必要的时间信息,不返回调用参数快照
+ 返回执行状态和必要的时间信息,不返回调用参数快照。
:param execution: 执行记录对象
:return: 执行状态及时间信息
@@ -323,10 +324,9 @@ def execution_result(execution: SysJobExecution) -> dict[str, Any]:
@staticmethod
async def recover_expired(db: AsyncSession) -> None:
"""
- 重试尚未开始的过期派发;已开始的过期执行标记未知,禁止自动重放
+ 重试尚未开始的过期派发;已开始的过期执行标记未知,禁止自动重放。
:param db: orm对象
- :return: None
"""
now = TimezoneUtil.utc_now()
await db.execute(
@@ -343,7 +343,7 @@ async def recover_expired(db: AsyncSession) -> None:
@staticmethod
async def pending_ids(db: AsyncSession, limit: int = 50) -> list[tuple[str, int]]:
"""
- 按提交顺序读取一批待派发执行,不持有跨任务的行锁
+ 按提交顺序读取一批待派发执行,不持有跨任务的行锁。
:param db: orm对象
:param limit: 本次读取的最大请求数
@@ -362,7 +362,7 @@ async def pending_ids(db: AsyncSession, limit: int = 50) -> list[tuple[str, int]
@classmethod
async def claim_request(cls, db: AsyncSession, execution_id: str, job_id: int) -> SysJobExecution | None:
"""
- 原子领取尚未开始的手动请求,并绑定本次派发凭据
+ 原子领取尚未开始的手动请求,并绑定本次派发凭据。
:param db: orm对象
:param execution_id: 执行ID
@@ -391,13 +391,12 @@ async def claim_request(cls, db: AsyncSession, execution_id: str, job_id: int) -
@staticmethod
async def fail_dispatch(db: AsyncSession, execution_id: str, token: str, message: str) -> None:
"""
- 记录确定未成功注册的派发失败,保留错误供用户查询
+ 记录确定未成功注册的派发失败,保留错误供用户查询。
:param db: orm对象
:param execution_id: 执行ID
:param token: 当前执行占用凭据
:param message: 执行结果或未执行原因
- :return: None
"""
await db.execute(
update(SysJobExecution)
diff --git a/ruoyi-fastapi-backend/module_admin/dao/log_dao.py b/ruoyi-fastapi-backend/module_admin/dao/log_dao.py
index 853df9b35..2c7a20441 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/log_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/log_dao.py
@@ -12,16 +12,14 @@
class OperationLogDao:
- """
- 操作日志管理模块数据库操作层
- """
+ """操作日志管理模块数据库操作层。"""
@classmethod
async def get_operation_log_list(
cls, db: AsyncSession, query_object: OperLogPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取操作日志列表信息
+ 根据查询参数获取操作日志列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -61,7 +59,7 @@ async def get_operation_log_list(
@classmethod
async def add_operation_log_dao(cls, db: AsyncSession, operation_log: OperLogModel) -> SysOperLog:
"""
- 新增操作日志数据库操作
+ 新增操作日志数据库操作。
:param db: orm对象
:param operation_log: 操作日志对象
@@ -76,36 +74,32 @@ async def add_operation_log_dao(cls, db: AsyncSession, operation_log: OperLogMod
@classmethod
async def delete_operation_log_dao(cls, db: AsyncSession, operation_log: OperLogModel) -> None:
"""
- 删除操作日志数据库操作
+ 删除操作日志数据库操作。
:param db: orm对象
:param operation_log: 操作日志对象
- :return:
"""
await db.execute(delete(SysOperLog).where(SysOperLog.oper_id.in_([operation_log.oper_id])))
@classmethod
async def clear_operation_log_dao(cls, db: AsyncSession) -> None:
"""
- 清除操作日志数据库操作
+ 清除操作日志数据库操作。
:param db: orm对象
- :return:
"""
await db.execute(delete(SysOperLog))
class LoginLogDao:
- """
- 登录日志管理模块数据库操作层
- """
+ """登录日志管理模块数据库操作层。"""
@classmethod
async def get_login_log_list(
cls, db: AsyncSession, query_object: LoginLogPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取登录日志列表信息
+ 根据查询参数获取登录日志列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -146,7 +140,7 @@ async def get_login_log_list(
@classmethod
async def add_login_log_dao(cls, db: AsyncSession, login_log: LogininforModel) -> SysLogininfor:
"""
- 新增登录日志数据库操作
+ 新增登录日志数据库操作。
:param db: orm对象
:param login_log: 登录日志对象
@@ -161,20 +155,18 @@ async def add_login_log_dao(cls, db: AsyncSession, login_log: LogininforModel) -
@classmethod
async def delete_login_log_dao(cls, db: AsyncSession, login_log: LogininforModel) -> None:
"""
- 删除登录日志数据库操作
+ 删除登录日志数据库操作。
:param db: orm对象
:param login_log: 登录日志对象
- :return:
"""
await db.execute(delete(SysLogininfor).where(SysLogininfor.info_id.in_([login_log.info_id])))
@classmethod
async def clear_login_log_dao(cls, db: AsyncSession) -> None:
"""
- 清除登录日志数据库操作
+ 清除登录日志数据库操作。
:param db: orm对象
- :return:
"""
await db.execute(delete(SysLogininfor))
diff --git a/ruoyi-fastapi-backend/module_admin/dao/login_dao.py b/ruoyi-fastapi-backend/module_admin/dao/login_dao.py
index fe68bc29f..70417beab 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/login_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/login_dao.py
@@ -7,7 +7,7 @@
async def login_by_account(db: AsyncSession, user_name: str) -> Row[tuple[SysUser, SysDept]] | None:
"""
- 根据用户名查询用户信息
+ 根据用户名查询用户信息。
:param db: orm对象
:param user_name: 用户名
diff --git a/ruoyi-fastapi-backend/module_admin/dao/menu_dao.py b/ruoyi-fastapi-backend/module_admin/dao/menu_dao.py
index db2fc9d6e..9e8c9d564 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/menu_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/menu_dao.py
@@ -12,14 +12,12 @@
class MenuDao:
- """
- 菜单管理模块数据库操作层
- """
+ """菜单管理模块数据库操作层。"""
@classmethod
async def get_menu_detail_by_id(cls, db: AsyncSession, menu_id: int) -> SysMenu | None:
"""
- 根据菜单id获取菜单详细信息
+ 根据菜单id获取菜单详细信息。
:param db: orm对象
:param menu_id: 菜单id
@@ -32,7 +30,7 @@ async def get_menu_detail_by_id(cls, db: AsyncSession, menu_id: int) -> SysMenu
@classmethod
async def get_menu_detail_by_info(cls, db: AsyncSession, menu: MenuModel) -> SysMenu | None:
"""
- 根据菜单参数获取菜单信息
+ 根据菜单参数获取菜单信息。
:param db: orm对象
:param menu: 菜单参数对象
@@ -57,7 +55,7 @@ async def get_menu_detail_by_info(cls, db: AsyncSession, menu: MenuModel) -> Sys
@classmethod
async def get_menus_by_path_or_route_name(cls, db: AsyncSession, path: str, route_name: str) -> Sequence[SysMenu]:
"""
- 根据路由地址或路由名称获取目录和菜单列表
+ 根据路由地址或路由名称获取目录和菜单列表。
:param db: orm对象
:param path: 路由地址
@@ -86,7 +84,7 @@ async def get_menus_by_path_or_route_name(cls, db: AsyncSession, path: str, rout
@classmethod
async def get_menu_list_for_tree(cls, db: AsyncSession, user_id: int, role: list) -> Sequence[SysMenu]:
"""
- 根据角色信息获取所有在用菜单列表信息
+ 根据角色信息获取所有在用菜单列表信息。
:param db: orm对象
:param user_id: 用户id
@@ -132,7 +130,7 @@ async def get_menu_list(
cls, db: AsyncSession, page_object: MenuQueryModel, user_id: int, role: list
) -> Sequence[SysMenu]:
"""
- 根据查询参数获取菜单列表信息
+ 根据查询参数获取菜单列表信息。
:param db: orm对象
:param page_object: 不分页查询参数对象
@@ -194,11 +192,11 @@ async def get_menu_list(
@classmethod
async def add_menu_dao(cls, db: AsyncSession, menu: MenuModel) -> SysMenu:
"""
- 新增菜单数据库操作
+ 新增菜单数据库操作。
:param db: orm对象
:param menu: 菜单对象
- :return:
+ :return: 新增的菜单记录
"""
db_menu = SysMenu(**menu.model_dump(exclude={'create_time', 'update_time'}))
db_menu.menu_name_i18n = TranslationUtil.merge(None, menu.menu_name_i18n)
@@ -210,11 +208,10 @@ async def add_menu_dao(cls, db: AsyncSession, menu: MenuModel) -> SysMenu:
@classmethod
async def edit_menu_dao(cls, db: AsyncSession, menu: dict) -> None:
"""
- 编辑菜单数据库操作
+ 编辑菜单数据库操作。
:param db: orm对象
:param menu: 需要更新的菜单字典
- :return:
"""
if 'menu_name_i18n' in menu:
current = await db.scalar(
@@ -229,11 +226,10 @@ async def edit_menu_dao(cls, db: AsyncSession, menu: dict) -> None:
@classmethod
async def update_menu_sort_dao(cls, db: AsyncSession, menu_sort_list: list[dict[str, int]]) -> None:
"""
- 批量更新菜单显示顺序
+ 批量更新菜单显示顺序。
:param db: orm对象
:param menu_sort_list: 菜单ID与显示顺序列表
- :return:
"""
await db.execute(
update(SysMenu.__table__)
@@ -245,18 +241,17 @@ async def update_menu_sort_dao(cls, db: AsyncSession, menu_sort_list: list[dict[
@classmethod
async def delete_menu_dao(cls, db: AsyncSession, menu: MenuModel) -> None:
"""
- 删除菜单数据库操作
+ 删除菜单数据库操作。
:param db: orm对象
:param menu: 菜单对象
- :return:
"""
await db.execute(delete(SysMenu).where(SysMenu.menu_id.in_([menu.menu_id])))
@classmethod
async def has_child_by_menu_id_dao(cls, db: AsyncSession, menu_id: int) -> int | None:
"""
- 根据菜单id查询菜单关联子菜单的数量
+ 根据菜单id查询菜单关联子菜单的数量。
:param db: orm对象
:param menu_id: 菜单id
@@ -271,7 +266,7 @@ async def has_child_by_menu_id_dao(cls, db: AsyncSession, menu_id: int) -> int |
@classmethod
async def check_menu_exist_role_dao(cls, db: AsyncSession, menu_id: int) -> int | None:
"""
- 根据菜单id查询菜单关联角色数量
+ 根据菜单id查询菜单关联角色数量。
:param db: orm对象
:param menu_id: 菜单id
diff --git a/ruoyi-fastapi-backend/module_admin/dao/notice_dao.py b/ruoyi-fastapi-backend/module_admin/dao/notice_dao.py
index db31bf895..e1088b5a0 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/notice_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/notice_dao.py
@@ -16,14 +16,12 @@
class NoticeDao:
- """
- 通知公告管理模块数据库操作层
- """
+ """通知公告管理模块数据库操作层。"""
@classmethod
async def get_notice_detail_by_id(cls, db: AsyncSession, notice_id: int) -> SysNotice | None:
"""
- 根据通知公告id获取通知公告详细信息
+ 根据通知公告id获取通知公告详细信息。
:param db: orm对象
:param notice_id: 通知公告id
@@ -36,7 +34,7 @@ async def get_notice_detail_by_id(cls, db: AsyncSession, notice_id: int) -> SysN
@classmethod
async def get_notice_detail_by_info(cls, db: AsyncSession, notice: NoticeModel) -> SysNotice | None:
"""
- 根据通知公告参数获取通知公告信息
+ 根据通知公告参数获取通知公告信息。
:param db: orm对象
:param notice: 通知公告参数对象
@@ -63,7 +61,7 @@ async def get_notice_list(
cls, db: AsyncSession, query_object: NoticePageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取通知公告列表信息
+ 根据查询参数获取通知公告列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -94,7 +92,7 @@ async def get_notice_list(
@classmethod
async def get_notice_list_with_read_status(cls, db: AsyncSession, user_id: int, limit: int) -> list[dict[str, Any]]:
"""
- 查询带当前用户已读状态的正常公告列表
+ 查询带当前用户已读状态的正常公告列表。
:param db: orm对象
:param user_id: 用户ID
@@ -126,7 +124,7 @@ async def get_notice_list_with_read_status(cls, db: AsyncSession, user_id: int,
@classmethod
async def get_unread_count(cls, db: AsyncSession, user_id: int) -> int:
"""
- 查询当前用户未读的正常公告数量
+ 查询当前用户未读的正常公告数量。
:param db: orm对象
:param user_id: 用户ID
@@ -148,7 +146,7 @@ async def get_notice_read_user_list(
cls, db: AsyncSession, query_object: NoticeReadUserPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 查询已阅读指定公告的用户列表
+ 查询已阅读指定公告的用户列表。
:param db: orm对象
:param query_object: 查询参数对象
@@ -184,12 +182,11 @@ async def get_notice_read_user_list(
@classmethod
async def add_notice_reads(cls, db: AsyncSession, user_id: int, notice_ids: list[int]) -> None:
"""
- 幂等新增公告已读记录
+ 幂等新增公告已读记录。
:param db: orm对象
:param user_id: 用户ID
:param notice_ids: 公告ID列表
- :return:
"""
unique_notice_ids = list(dict.fromkeys(notice_ids))
if not unique_notice_ids:
@@ -239,11 +236,10 @@ async def add_notice_reads(cls, db: AsyncSession, user_id: int, notice_ids: list
@classmethod
async def delete_notice_reads(cls, db: AsyncSession, notice_ids: list[int]) -> None:
"""
- 根据公告ID列表删除已读记录
+ 根据公告ID列表删除已读记录。
:param db: orm对象
:param notice_ids: 公告ID列表
- :return:
"""
if notice_ids:
await db.execute(delete(SysNoticeRead).where(SysNoticeRead.notice_id.in_(notice_ids)))
@@ -251,11 +247,11 @@ async def delete_notice_reads(cls, db: AsyncSession, notice_ids: list[int]) -> N
@classmethod
async def add_notice_dao(cls, db: AsyncSession, notice: NoticeModel) -> SysNotice:
"""
- 新增通知公告数据库操作
+ 新增通知公告数据库操作。
:param db: orm对象
:param notice: 通知公告对象
- :return:
+ :return: 新增的通知公告记录
"""
db_notice = SysNotice(**notice.model_dump(exclude={'create_time', 'update_time'}))
db.add(db_notice)
@@ -266,11 +262,10 @@ async def add_notice_dao(cls, db: AsyncSession, notice: NoticeModel) -> SysNotic
@classmethod
async def edit_notice_dao(cls, db: AsyncSession, notice: dict) -> None:
"""
- 编辑通知公告数据库操作
+ 编辑通知公告数据库操作。
:param db: orm对象
:param notice: 需要更新的通知公告字典
- :return:
"""
await db.execute(
update(SysNotice),
@@ -280,10 +275,9 @@ async def edit_notice_dao(cls, db: AsyncSession, notice: dict) -> None:
@classmethod
async def delete_notice_dao(cls, db: AsyncSession, notice: NoticeModel) -> None:
"""
- 删除通知公告数据库操作
+ 删除通知公告数据库操作。
:param db: orm对象
:param notice: 通知公告对象
- :return:
"""
await db.execute(delete(SysNotice).where(SysNotice.notice_id.in_([notice.notice_id])))
diff --git a/ruoyi-fastapi-backend/module_admin/dao/post_dao.py b/ruoyi-fastapi-backend/module_admin/dao/post_dao.py
index 644ab21ec..df9aa933c 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/post_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/post_dao.py
@@ -11,14 +11,12 @@
class PostDao:
- """
- 岗位管理模块数据库操作层
- """
+ """岗位管理模块数据库操作层。"""
@classmethod
async def get_post_by_id(cls, db: AsyncSession, post_id: int) -> SysPost | None:
"""
- 根据岗位id获取在用岗位详细信息
+ 根据岗位id获取在用岗位详细信息。
:param db: orm对象
:param post_id: 岗位id
@@ -35,7 +33,7 @@ async def get_post_by_id(cls, db: AsyncSession, post_id: int) -> SysPost | None:
@classmethod
async def get_post_detail_by_id(cls, db: AsyncSession, post_id: int) -> SysPost | None:
"""
- 根据岗位id获取岗位详细信息
+ 根据岗位id获取岗位详细信息。
:param db: orm对象
:param post_id: 岗位id
@@ -48,7 +46,7 @@ async def get_post_detail_by_id(cls, db: AsyncSession, post_id: int) -> SysPost
@classmethod
async def get_post_detail_by_info(cls, db: AsyncSession, post: PostModel) -> SysPost | None:
"""
- 根据岗位参数获取岗位信息
+ 根据岗位参数获取岗位信息。
:param db: orm对象
:param post: 岗位参数对象
@@ -75,7 +73,7 @@ async def get_post_list(
cls, db: AsyncSession, query_object: PostPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取岗位列表信息
+ 根据查询参数获取岗位列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -101,11 +99,11 @@ async def get_post_list(
@classmethod
async def add_post_dao(cls, db: AsyncSession, post: PostModel) -> SysPost:
"""
- 新增岗位数据库操作
+ 新增岗位数据库操作。
:param db: orm对象
:param post: 岗位对象
- :return:
+ :return: 新增的岗位记录
"""
db_post = SysPost(**post.model_dump(exclude={'create_time', 'update_time'}))
db.add(db_post)
@@ -116,11 +114,10 @@ async def add_post_dao(cls, db: AsyncSession, post: PostModel) -> SysPost:
@classmethod
async def edit_post_dao(cls, db: AsyncSession, post: dict) -> None:
"""
- 编辑岗位数据库操作
+ 编辑岗位数据库操作。
:param db: orm对象
:param post: 需要更新的岗位字典
- :return:
"""
await db.execute(
update(SysPost),
@@ -130,18 +127,17 @@ async def edit_post_dao(cls, db: AsyncSession, post: dict) -> None:
@classmethod
async def delete_post_dao(cls, db: AsyncSession, post: PostModel) -> None:
"""
- 删除岗位数据库操作
+ 删除岗位数据库操作。
:param db: orm对象
:param post: 岗位对象
- :return:
"""
await db.execute(delete(SysPost).where(SysPost.post_id.in_([post.post_id])))
@classmethod
async def count_user_post_dao(cls, db: AsyncSession, post_id: int) -> int | None:
"""
- 根据岗位id查询岗位关联的用户数量
+ 根据岗位id查询岗位关联的用户数量。
:param db: orm对象
:param post_id: 岗位id
diff --git a/ruoyi-fastapi-backend/module_admin/dao/role_dao.py b/ruoyi-fastapi-backend/module_admin/dao/role_dao.py
index b71256f28..a311a5308 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/role_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/role_dao.py
@@ -15,14 +15,12 @@
class RoleDao:
- """
- 角色管理模块数据库操作层
- """
+ """角色管理模块数据库操作层。"""
@classmethod
async def get_role_by_name(cls, db: AsyncSession, role_name: str) -> SysRole | None:
"""
- 根据角色名获取在用角色信息
+ 根据角色名获取在用角色信息。
:param db: orm对象
:param role_name: 角色名
@@ -46,7 +44,7 @@ async def get_role_by_name(cls, db: AsyncSession, role_name: str) -> SysRole | N
@classmethod
async def get_role_by_info(cls, db: AsyncSession, role: RoleModel) -> SysRole | None:
"""
- 根据角色参数获取角色信息
+ 根据角色参数获取角色信息。
:param db: orm对象
:param role: 角色参数
@@ -74,7 +72,7 @@ async def get_role_by_info(cls, db: AsyncSession, role: RoleModel) -> SysRole |
@classmethod
async def get_role_by_id(cls, db: AsyncSession, role_id: int) -> SysRole | None:
"""
- 根据角色id获取在用角色信息
+ 根据角色id获取在用角色信息。
:param db: orm对象
:param role_id: 角色id
@@ -95,7 +93,7 @@ async def get_role_by_id(cls, db: AsyncSession, role_id: int) -> SysRole | None:
@classmethod
async def get_role_detail_by_id(cls, db: AsyncSession, role_id: int) -> SysRole | None:
"""
- 根据role_id获取角色详细信息
+ 根据role_id获取角色详细信息。
:param db: orm对象
:param role_id: 角色id
@@ -112,7 +110,7 @@ async def get_role_detail_by_id(cls, db: AsyncSession, role_id: int) -> SysRole
@classmethod
async def get_role_select_option_dao(cls, db: AsyncSession) -> Sequence[SysRole]:
"""
- 获取编辑页面对应的在用角色列表信息
+ 获取编辑页面对应的在用角色列表信息。
:param db: orm对象
:return: 角色列表信息
@@ -134,7 +132,7 @@ async def get_role_list(
cls, db: AsyncSession, query_object: RolePageQueryModel, data_scope_sql: ColumnElement, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取角色列表信息
+ 根据查询参数获取角色列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -172,11 +170,11 @@ async def get_role_list(
@classmethod
async def add_role_dao(cls, db: AsyncSession, role: RoleModel) -> SysRole:
"""
- 新增角色数据库操作
+ 新增角色数据库操作。
:param db: orm对象
:param role: 角色对象
- :return:
+ :return: 新增的角色记录
"""
db_role = SysRole(**role.model_dump(exclude={'admin', 'create_time', 'update_time'}))
db.add(db_role)
@@ -187,11 +185,10 @@ async def add_role_dao(cls, db: AsyncSession, role: RoleModel) -> SysRole:
@classmethod
async def edit_role_dao(cls, db: AsyncSession, role: dict) -> None:
"""
- 编辑角色数据库操作
+ 编辑角色数据库操作。
:param db: orm对象
:param role: 需要更新的角色字典
- :return:
"""
await db.execute(
update(SysRole),
@@ -201,11 +198,10 @@ async def edit_role_dao(cls, db: AsyncSession, role: dict) -> None:
@classmethod
async def delete_role_dao(cls, db: AsyncSession, role: RoleModel) -> None:
"""
- 删除角色数据库操作
+ 删除角色数据库操作。
:param db: orm对象
:param role: 角色对象
- :return:
"""
await db.execute(
update(SysRole).where(SysRole.role_id == role.role_id).values(del_flag='2', update_by=role.update_by)
@@ -214,7 +210,7 @@ async def delete_role_dao(cls, db: AsyncSession, role: RoleModel) -> None:
@classmethod
async def get_role_menu_dao(cls, db: AsyncSession, role: RoleModel) -> Sequence[SysMenu]:
"""
- 根据角色id获取角色菜单关联列表信息
+ 根据角色id获取角色菜单关联列表信息。
:param db: orm对象
:param role: 角色对象
@@ -250,7 +246,7 @@ async def get_role_menu_dao(cls, db: AsyncSession, role: RoleModel) -> Sequence[
@classmethod
async def list_role_menu_ids(cls, db: AsyncSession, role_id: int) -> Sequence[int]:
"""
- 查询角色完整菜单关联编号
+ 查询角色完整菜单关联编号。
:param db: 异步数据库会话
:param role_id: 角色编号
@@ -262,11 +258,10 @@ async def list_role_menu_ids(cls, db: AsyncSession, role_id: int) -> Sequence[in
@classmethod
async def add_role_menu_dao(cls, db: AsyncSession, role_menu: RoleMenuModel) -> None:
"""
- 新增角色菜单关联信息数据库操作
+ 新增角色菜单关联信息数据库操作。
:param db: orm对象
:param role_menu: 用户角色菜单关联对象
- :return:
"""
db_role_menu = SysRoleMenu(**role_menu.model_dump())
db.add(db_role_menu)
@@ -274,18 +269,17 @@ async def add_role_menu_dao(cls, db: AsyncSession, role_menu: RoleMenuModel) ->
@classmethod
async def delete_role_menu_dao(cls, db: AsyncSession, role_menu: RoleMenuModel) -> None:
"""
- 删除角色菜单关联信息数据库操作
+ 删除角色菜单关联信息数据库操作。
:param db: orm对象
:param role_menu: 角色菜单关联对象
- :return:
"""
await db.execute(delete(SysRoleMenu).where(SysRoleMenu.role_id.in_([role_menu.role_id])))
@classmethod
async def get_role_dept_dao(cls, db: AsyncSession, role: RoleModel) -> Sequence[SysDept]:
"""
- 根据角色id获取角色部门关联列表信息
+ 根据角色id获取角色部门关联列表信息。
:param db: orm对象
:param role: 角色对象
@@ -321,11 +315,10 @@ async def get_role_dept_dao(cls, db: AsyncSession, role: RoleModel) -> Sequence[
@classmethod
async def add_role_dept_dao(cls, db: AsyncSession, role_dept: RoleDeptModel) -> None:
"""
- 新增角色部门关联信息数据库操作
+ 新增角色部门关联信息数据库操作。
:param db: orm对象
:param role_dept: 用户角色部门关联对象
- :return:
"""
db_role_dept = SysRoleDept(**role_dept.dict())
db.add(db_role_dept)
@@ -333,18 +326,17 @@ async def add_role_dept_dao(cls, db: AsyncSession, role_dept: RoleDeptModel) ->
@classmethod
async def delete_role_dept_dao(cls, db: AsyncSession, role_dept: RoleDeptModel) -> None:
"""
- 删除角色部门关联信息数据库操作
+ 删除角色部门关联信息数据库操作。
:param db: orm对象
:param role_dept: 角色部门关联对象
- :return:
"""
await db.execute(delete(SysRoleDept).where(SysRoleDept.role_id.in_([role_dept.role_id])))
@classmethod
async def count_user_role_dao(cls, db: AsyncSession, role_id: int) -> int | None:
"""
- 根据角色id查询角色关联用户数量
+ 根据角色id查询角色关联用户数量。
:param db: orm对象
:param role_id: 角色id
diff --git a/ruoyi-fastapi-backend/module_admin/dao/user_dao.py b/ruoyi-fastapi-backend/module_admin/dao/user_dao.py
index 7864cf259..e9fb55071 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/user_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/user_dao.py
@@ -25,14 +25,12 @@
class UserDao:
- """
- 用户管理模块数据库操作层
- """
+ """用户管理模块数据库操作层。"""
@classmethod
async def get_user_by_name(cls, db: AsyncSession, user_name: str) -> SysUser | None:
"""
- 根据用户名获取用户信息
+ 根据用户名获取用户信息。
:param db: orm对象
:param user_name: 用户名
@@ -56,7 +54,7 @@ async def get_user_by_name(cls, db: AsyncSession, user_name: str) -> SysUser | N
@classmethod
async def get_role_ids(cls, db: AsyncSession, user_id: int) -> set[int]:
"""
- 查询用户当前关联的角色ID
+ 查询用户当前关联的角色ID。
:param db: orm对象
:param user_id: 用户id
@@ -68,7 +66,7 @@ async def get_role_ids(cls, db: AsyncSession, user_id: int) -> set[int]:
@classmethod
async def get_user_by_info(cls, db: AsyncSession, user: UserModel) -> SysUser | None:
"""
- 根据用户参数获取用户信息
+ 根据用户参数获取用户信息。
:param db: orm对象
:param user: 用户参数
@@ -97,7 +95,7 @@ async def get_user_by_info(cls, db: AsyncSession, user: UserModel) -> SysUser |
@classmethod
async def get_user_by_id(cls, db: AsyncSession, user_id: int, *, for_auth: bool = False) -> dict[str, Any]:
"""
- 根据user_id获取用户信息
+ 根据user_id获取用户信息。
:param db: orm对象
:param user_id: 用户id
@@ -194,7 +192,7 @@ async def get_user_by_id(cls, db: AsyncSession, user_id: int, *, for_auth: bool
@classmethod
async def get_user_detail_by_id(cls, db: AsyncSession, user_id: int) -> dict[str, Any]:
"""
- 根据user_id获取用户详细信息
+ 根据user_id获取用户详细信息。
:param db: orm对象
:param user_id: 用户id
@@ -287,7 +285,7 @@ async def get_user_list(
cls, db: AsyncSession, query_object: UserPageQueryModel, data_scope_sql: ColumnElement, is_page: bool = False
) -> PageModel | list[list[dict[str, Any]]]:
"""
- 根据查询参数获取用户列表信息
+ 根据查询参数获取用户列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -338,7 +336,7 @@ async def get_user_list(
@classmethod
async def add_user_dao(cls, db: AsyncSession, user: UserModel) -> SysUser:
"""
- 新增用户数据库操作
+ 新增用户数据库操作。
:param db: orm对象
:param user: 用户对象
@@ -353,11 +351,12 @@ async def add_user_dao(cls, db: AsyncSession, user: UserModel) -> SysUser:
@classmethod
async def edit_user_dao(cls, db: AsyncSession, user: dict) -> dict[str, str] | None:
"""
- 编辑用户数据库操作
+ 编辑用户数据库操作。
:param db: orm对象
:param user: 需要更新的用户字典
:return: 写入语言偏好时返回该事务的偏好和版本,其他修改返回 None
+ :raises ServiceException: 用户不存在
"""
values = {
key: value for key, value in user.items() if key not in {'create_time', 'update_time', 'locale_revision'}
@@ -382,11 +381,10 @@ async def edit_user_dao(cls, db: AsyncSession, user: dict) -> dict[str, str] | N
@classmethod
async def delete_user_dao(cls, db: AsyncSession, user: UserModel) -> None:
"""
- 删除用户数据库操作
+ 删除用户数据库操作。
:param db: orm对象
:param user: 用户对象
- :return:
"""
await db.execute(
update(SysUser).where(SysUser.user_id == user.user_id).values(del_flag='2', update_by=user.update_by)
@@ -397,7 +395,7 @@ async def get_user_role_allocated_list_by_user_id(
cls, db: AsyncSession, query_object: UserRoleQueryModel
) -> Sequence[SysRole]:
"""
- 根据用户id获取用户已分配的角色列表信息数据库操作
+ 根据用户id获取用户已分配的角色列表信息数据库操作。
:param db: orm对象
:param query_object: 用户角色查询对象
@@ -434,7 +432,7 @@ async def get_user_role_allocated_list_by_role_id(
is_page: bool = False,
) -> PageModel | list[dict[str, Any]]:
"""
- 根据角色id获取已分配的用户列表信息
+ 根据角色id获取已分配的用户列表信息。
:param db: orm对象
:param query_object: 用户角色查询对象
@@ -471,7 +469,7 @@ async def get_user_role_unallocated_list_by_role_id(
is_page: bool = False,
) -> PageModel | list[dict[str, Any]]:
"""
- 根据角色id获取未分配的用户列表信息
+ 根据角色id获取未分配的用户列表信息。
:param db: orm对象
:param query_object: 用户角色查询对象
@@ -510,11 +508,10 @@ async def get_user_role_unallocated_list_by_role_id(
@classmethod
async def add_user_role_dao(cls, db: AsyncSession, user_role: UserRoleModel) -> None:
"""
- 新增用户角色关联信息数据库操作
+ 新增用户角色关联信息数据库操作。
:param db: orm对象
:param user_role: 用户角色关联对象
- :return:
"""
db_user_role = SysUserRole(**user_role.model_dump())
db.add(db_user_role)
@@ -522,22 +519,20 @@ async def add_user_role_dao(cls, db: AsyncSession, user_role: UserRoleModel) ->
@classmethod
async def delete_user_role_dao(cls, db: AsyncSession, user_role: UserRoleModel) -> None:
"""
- 删除用户角色关联信息数据库操作
+ 删除用户角色关联信息数据库操作。
:param db: orm对象
:param user_role: 用户角色关联对象
- :return:
"""
await db.execute(delete(SysUserRole).where(SysUserRole.user_id.in_([user_role.user_id])))
@classmethod
async def delete_user_role_by_user_and_role_dao(cls, db: AsyncSession, user_role: UserRoleModel) -> None:
"""
- 根据用户id及角色id删除用户角色关联信息数据库操作
+ 根据用户id及角色id删除用户角色关联信息数据库操作。
:param db: orm对象
:param user_role: 用户角色关联对象
- :return:
"""
await db.execute(
delete(SysUserRole).where(
@@ -549,7 +544,7 @@ async def delete_user_role_by_user_and_role_dao(cls, db: AsyncSession, user_role
@classmethod
async def get_user_role_detail(cls, db: AsyncSession, user_role: UserRoleModel) -> SysUserRole | None:
"""
- 根据用户角色关联获取用户角色关联详细信息
+ 根据用户角色关联获取用户角色关联详细信息。
:param db: orm对象
:param user_role: 用户角色关联对象
@@ -572,11 +567,10 @@ async def get_user_role_detail(cls, db: AsyncSession, user_role: UserRoleModel)
@classmethod
async def add_user_post_dao(cls, db: AsyncSession, user_post: UserPostModel) -> None:
"""
- 新增用户岗位关联信息数据库操作
+ 新增用户岗位关联信息数据库操作。
:param db: orm对象
:param user_post: 用户岗位关联对象
- :return:
"""
db_user_post = SysUserPost(**user_post.model_dump())
db.add(db_user_post)
@@ -584,16 +578,22 @@ async def add_user_post_dao(cls, db: AsyncSession, user_post: UserPostModel) ->
@classmethod
async def delete_user_post_dao(cls, db: AsyncSession, user_post: UserPostModel) -> None:
"""
- 删除用户岗位关联信息数据库操作
+ 删除用户岗位关联信息数据库操作。
:param db: orm对象
:param user_post: 用户岗位关联对象
- :return:
"""
await db.execute(delete(SysUserPost).where(SysUserPost.user_id.in_([user_post.user_id])))
@classmethod
async def get_user_dept_info(cls, db: AsyncSession, dept_id: int) -> SysDept | None:
+ """
+ 查询用户关联的部门信息。
+
+ :param db: 当前操作使用的数据库会话
+ :param dept_id: 部门id
+ :return: 用户关联的部门信息
+ """
dept_basic_info = (
(
await db.execute(
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/config_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/config_do.py
index d657074c7..c5f21e58f 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/config_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/config_do.py
@@ -7,9 +7,7 @@
class SysConfig(AuditTimeMixin, Base):
- """
- 参数配置表
- """
+ """参数配置表。"""
__tablename__ = 'sys_config'
__table_args__ = {'comment': '参数配置表'}
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/dept_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/dept_do.py
index 0a90e7461..81d28d205 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/dept_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/dept_do.py
@@ -7,9 +7,7 @@
class SysDept(AuditTimeMixin, Base):
- """
- 部门表
- """
+ """部门表。"""
__tablename__ = 'sys_dept'
__table_args__ = {'comment': '部门表'}
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/dict_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/dict_do.py
index 5cc1995c0..7d0f35f3e 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/dict_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/dict_do.py
@@ -8,9 +8,7 @@
class SysDictType(AuditTimeMixin, Base):
- """
- 字典类型表
- """
+ """字典类型表。"""
__tablename__ = 'sys_dict_type'
__table_args__ = {'comment': '字典类型表'}
@@ -31,9 +29,7 @@ class SysDictType(AuditTimeMixin, Base):
class SysDictData(AuditTimeMixin, Base):
- """
- 字典数据表
- """
+ """字典数据表。"""
__tablename__ = 'sys_dict_data'
__table_args__ = {'comment': '字典数据表'}
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/file_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/file_do.py
index 6fe41b0e1..efded5bca 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/file_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/file_do.py
@@ -7,9 +7,7 @@
class SysFileInfo(AuditTimeMixin, Base):
- """
- 文件信息表
- """
+ """文件信息表。"""
__tablename__ = 'sys_file_info'
__create_time_nullable__ = False
@@ -59,9 +57,7 @@ class SysFileInfo(AuditTimeMixin, Base):
class SysFileReference(CreateTimeMixin, Base):
- """
- 文件业务引用表
- """
+ """文件业务引用表。"""
__tablename__ = 'sys_file_reference'
__create_time_nullable__ = False
@@ -87,9 +83,7 @@ class SysFileReference(CreateTimeMixin, Base):
class SysFileRetentionPolicy(AuditTimeMixin, Base):
- """
- 文件业务保留策略表
- """
+ """文件业务保留策略表。"""
__tablename__ = 'sys_file_retention_policy'
__create_time_nullable__ = False
@@ -105,9 +99,7 @@ class SysFileRetentionPolicy(AuditTimeMixin, Base):
class SysFileRetentionNotice(CreateTimeMixin, Base):
- """
- 文件保留期限提醒表
- """
+ """文件保留期限提醒表。"""
__tablename__ = 'sys_file_retention_notice'
__create_time_nullable__ = False
@@ -133,9 +125,7 @@ class SysFileRetentionNotice(CreateTimeMixin, Base):
class SysFileAcl(CreateTimeMixin, Base):
- """
- 文件访问控制表
- """
+ """文件访问控制表。"""
__tablename__ = 'sys_file_acl'
__create_time_nullable__ = False
@@ -165,9 +155,7 @@ class SysFileAcl(CreateTimeMixin, Base):
class SysFileAccessLog(Base):
- """
- 文件访问审计表
- """
+ """文件访问审计表。"""
__tablename__ = 'sys_file_access_log'
__table_args__ = (
@@ -193,9 +181,7 @@ class SysFileAccessLog(Base):
class SysFileReconcileRun(Base):
- """
- 文件存储对账任务表
- """
+ """文件存储对账任务表。"""
__tablename__ = 'sys_file_reconcile_run'
__table_args__ = (
@@ -221,9 +207,7 @@ class SysFileReconcileRun(Base):
class SysFileReconcileIssue(Base):
- """
- 文件存储对账异常表
- """
+ """文件存储对账异常表。"""
__tablename__ = 'sys_file_reconcile_issue'
__table_args__ = (
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/job_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/job_do.py
index fc9beb53d..9cd62f838 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/job_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/job_do.py
@@ -17,9 +17,7 @@
class SysJob(AuditTimeMixin, Base):
- """
- 定时任务调度表
- """
+ """定时任务调度表。"""
__tablename__ = 'sys_job'
__table_args__ = (
@@ -51,9 +49,7 @@ class SysJob(AuditTimeMixin, Base):
class SysJobLog(CreateTimeMixin, Base):
- """
- 定时任务调度日志表
- """
+ """定时任务调度日志表。"""
__tablename__ = 'sys_job_log'
__table_args__ = (
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/job_runtime_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/job_runtime_do.py
index 501c5530d..7e6ee4b2b 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/job_runtime_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/job_runtime_do.py
@@ -6,9 +6,7 @@
class SysJobSync(AuditTimeMixin, Base):
- """
- 任务配置版本和应用状态,删除任务后保留删除同步记录
- """
+ """任务配置版本和应用状态,删除任务后保留删除同步记录。"""
__tablename__ = 'sys_job_sync'
__table_args__ = (
@@ -21,7 +19,9 @@ class SysJobSync(AuditTimeMixin, Base):
applied_version = Column(BigInteger, nullable=False, default=0, comment='已应用版本')
config_hash = Column(String(64), nullable=False, comment='最新配置摘要')
deleted = Column(Boolean, nullable=False, default=False, comment='任务是否已删除')
- sync_status = Column(String(16), nullable=False, default='pending', comment='pending/applied/failed')
+ sync_status = Column(
+ String(16), nullable=False, default='pending', comment='应用状态(pending、applied 或 failed)'
+ )
sync_error = Column(String(2000), nullable=True, comment='最近同步错误')
applied_time = Column(DbUtcDateTime(), nullable=True, comment='最近应用时刻')
next_run_time = Column(DbUtcDateTime(), nullable=True, comment='最近观测的实际下次调度时刻')
@@ -29,9 +29,7 @@ class SysJobSync(AuditTimeMixin, Base):
class SysJobExecution(AuditTimeMixin, Base):
- """
- 手动执行请求及定时执行记录,运行记录同时承担跨进程并发占用
- """
+ """手动执行请求及定时执行记录,运行记录同时承担跨进程并发占用。"""
__tablename__ = 'sys_job_execution'
__table_args__ = (
@@ -42,7 +40,7 @@ class SysJobExecution(AuditTimeMixin, Base):
execution_id = Column(String(32), primary_key=True, comment='执行ID')
job_id = Column(BigInteger, nullable=False, comment='逻辑任务ID')
- source = Column(String(10), nullable=False, comment='manual/cron')
+ source = Column(String(10), nullable=False, comment='触发方式(手动或定时)')
status = Column(String(16), nullable=False, default='pending', comment='执行状态')
job_snapshot = Column(JSON, nullable=False, comment='提交时任务配置快照')
owner_token = Column(String(64), nullable=True, comment='派发或执行占用凭据')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/log_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/log_do.py
index bd2a9afab..b02d81c0f 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/log_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/log_do.py
@@ -6,9 +6,7 @@
class SysLogininfor(Base):
- """
- 系统访问记录
- """
+ """系统访问记录。"""
__tablename__ = 'sys_logininfor'
__table_args__ = {'comment': '系统访问记录'}
@@ -28,9 +26,7 @@ class SysLogininfor(Base):
class SysOperLog(Base):
- """
- 操作日志记录
- """
+ """操作日志记录。"""
__tablename__ = 'sys_oper_log'
__table_args__ = {'comment': '操作日志记录'}
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/menu_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/menu_do.py
index facdf030f..5731ee151 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/menu_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/menu_do.py
@@ -8,9 +8,7 @@
class SysMenu(AuditTimeMixin, Base):
- """
- 菜单权限表
- """
+ """菜单权限表。"""
__tablename__ = 'sys_menu'
__table_args__ = {'comment': '菜单权限表'}
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/notice_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/notice_do.py
index bec2589d1..e02524fa8 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/notice_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/notice_do.py
@@ -10,9 +10,7 @@
class SysNotice(AuditTimeMixin, Base):
- """
- 通知公告表
- """
+ """通知公告表。"""
__tablename__ = 'sys_notice'
__table_args__ = {'comment': '通知公告表'}
@@ -38,9 +36,7 @@ class SysNotice(AuditTimeMixin, Base):
class SysNoticeRead(Base):
- """
- 公告已读记录表
- """
+ """公告已读记录表。"""
__tablename__ = 'sys_notice_read'
__table_args__ = (
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/post_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/post_do.py
index 6791533ed..22f0fa36a 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/post_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/post_do.py
@@ -7,9 +7,7 @@
class SysPost(AuditTimeMixin, Base):
- """
- 岗位信息表
- """
+ """岗位信息表。"""
__tablename__ = 'sys_post'
__table_args__ = {'comment': '岗位信息表'}
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/role_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/role_do.py
index f1353c73d..6a4bacca1 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/role_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/role_do.py
@@ -8,9 +8,7 @@
class SysRole(AuditTimeMixin, Base):
- """
- 角色信息表
- """
+ """角色信息表。"""
__tablename__ = 'sys_role'
__table_args__ = {'comment': '角色信息表'}
@@ -50,9 +48,7 @@ class SysRole(AuditTimeMixin, Base):
class SysRoleDept(Base):
- """
- 角色和部门关联表
- """
+ """角色和部门关联表。"""
__tablename__ = 'sys_role_dept'
__table_args__ = {'comment': '角色和部门关联表'}
@@ -62,9 +58,7 @@ class SysRoleDept(Base):
class SysRoleMenu(Base):
- """
- 角色和菜单关联表
- """
+ """角色和菜单关联表。"""
__tablename__ = 'sys_role_menu'
__table_args__ = {'comment': '角色和菜单关联表'}
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/user_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/user_do.py
index 2e803c76e..16d29cd9d 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/user_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/user_do.py
@@ -8,9 +8,7 @@
class SysUser(AuditTimeMixin, Base):
- """
- 用户信息表
- """
+ """用户信息表。"""
__tablename__ = 'sys_user'
__table_args__ = {'comment': '用户信息表'}
@@ -49,9 +47,7 @@ class SysUser(AuditTimeMixin, Base):
class SysUserRole(Base):
- """
- 用户和角色关联表
- """
+ """用户和角色关联表。"""
__tablename__ = 'sys_user_role'
__table_args__ = {'comment': '用户和角色关联表'}
@@ -61,9 +57,7 @@ class SysUserRole(Base):
class SysUserPost(Base):
- """
- 用户与岗位关联表
- """
+ """用户与岗位关联表。"""
__tablename__ = 'sys_user_post'
__table_args__ = {'comment': '用户与岗位关联表'}
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/cache_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/cache_vo.py
index 079f93c1d..e95174a8e 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/cache_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/cache_vo.py
@@ -5,9 +5,7 @@
class CacheMonitorModel(BaseModel):
- """
- 缓存监控信息对应pydantic模型
- """
+ """缓存监控信息对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -17,9 +15,7 @@ class CacheMonitorModel(BaseModel):
class CacheInfoModel(BaseModel):
- """
- 缓存监控对象对应pydantic模型
- """
+ """缓存监控对象对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/common_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/common_vo.py
index 94afbc61c..9be1c02be 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/common_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/common_vo.py
@@ -5,9 +5,7 @@
class UploadResponseModel(BaseModel):
- """
- 上传响应模型
- """
+ """上传响应模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/config_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/config_vo.py
index b609f8a04..597421b48 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/config_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/config_vo.py
@@ -10,9 +10,7 @@
class ConfigModel(BaseModel):
- """
- 参数配置表对应pydantic模型
- """
+ """参数配置表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -35,6 +33,11 @@ class ConfigModel(BaseModel):
message=I18nMessage('参数名称长度不能超过100个字符', msg_key='validation.configNameLength'),
)
def get_config_key(self) -> str | None:
+ """
+ 校验并返回参数键名。
+
+ :return: 参数键名
+ """
return self.config_key
@NotBlank(field_name='config_name', message=I18nMessage('参数键名不能为空', msg_key='validation.configKeyRequired'))
@@ -45,6 +48,11 @@ def get_config_key(self) -> str | None:
message=I18nMessage('参数键名长度不能超过100个字符', msg_key='validation.configKeyLength'),
)
def get_config_name(self) -> str | None:
+ """
+ 校验并返回参数名称。
+
+ :return: 参数名称
+ """
return self.config_name
@NotBlank(
@@ -57,36 +65,36 @@ def get_config_name(self) -> str | None:
message=I18nMessage('参数键值长度不能超过500个字符', msg_key='validation.configValueLength'),
)
def get_config_value(self) -> str | None:
+ """
+ 校验并返回参数键值。
+
+ :return: 参数键值
+ """
return self.config_value
def validate_fields(self) -> None:
+ """校验参数键名、参数名称、参数键值。"""
self.get_config_key()
self.get_config_name()
self.get_config_value()
class ConfigQueryModel(DateRangeQueryMixin, ConfigModel):
- """
- 参数配置管理不分页查询模型
- """
+ """参数配置管理不分页查询模型。"""
begin_time: str | None = Field(default=None, description='开始时间')
end_time: str | None = Field(default=None, description='结束时间')
class ConfigPageQueryModel(ConfigQueryModel):
- """
- 参数配置管理分页查询模型
- """
+ """参数配置管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class DeleteConfigModel(BaseModel):
- """
- 删除参数配置模型
- """
+ """删除参数配置模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/dept_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/dept_vo.py
index cffd7c118..742063b81 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/dept_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/dept_vo.py
@@ -10,9 +10,7 @@
class DeptModel(BaseModel):
- """
- 部门表对应pydantic模型
- """
+ """部门表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -39,10 +37,20 @@ class DeptModel(BaseModel):
message=I18nMessage('部门名称长度不能超过30个字符', msg_key='validation.deptNameLength'),
)
def get_dept_name(self) -> str | None:
+ """
+ 校验并返回部门名称。
+
+ :return: 部门名称
+ """
return self.dept_name
@NotBlank(field_name='order_num', message=I18nMessage('显示顺序不能为空', msg_key='validation.orderRequired'))
def get_order_num(self) -> int | None:
+ """
+ 校验并返回显示顺序。
+
+ :return: 显示顺序
+ """
return self.order_num
@Size(
@@ -52,6 +60,11 @@ def get_order_num(self) -> int | None:
message=I18nMessage('联系电话长度不能超过11个字符', msg_key='validation.contactPhoneLength'),
)
def get_phone(self) -> str | None:
+ """
+ 校验并返回联系电话。
+
+ :return: 联系电话
+ """
return self.phone
@Network(
@@ -66,9 +79,15 @@ def get_phone(self) -> str | None:
message=I18nMessage('邮箱长度不能超过50个字符', msg_key='validation.emailLength'),
)
def get_email(self) -> str | None:
+ """
+ 校验并返回邮箱。
+
+ :return: 邮箱
+ """
return self.email
def validate_fields(self) -> None:
+ """校验部门名称、显示顺序、联系电话、邮箱。"""
self.get_dept_name()
self.get_order_num()
self.get_phone()
@@ -76,18 +95,14 @@ def validate_fields(self) -> None:
class DeptQueryModel(DateRangeQueryMixin, DeptModel):
- """
- 部门管理不分页查询模型
- """
+ """部门管理不分页查询模型。"""
begin_time: str | None = Field(default=None, description='开始时间')
end_time: str | None = Field(default=None, description='结束时间')
class DeptTreeModel(BaseModel):
- """
- 部门树模型
- """
+ """部门树模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -98,9 +113,7 @@ class DeptTreeModel(BaseModel):
class DeleteDeptModel(BaseModel):
- """
- 删除部门模型
- """
+ """删除部门模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -110,9 +123,7 @@ class DeleteDeptModel(BaseModel):
class DeptSortModel(BaseModel):
- """
- 部门排序批量保存模型
- """
+ """部门排序批量保存模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/dict_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/dict_vo.py
index 507ffcb1e..3eea7101e 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/dict_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/dict_vo.py
@@ -11,9 +11,7 @@
class DictTypeBaseModel(BaseModel):
- """
- 字典类型表对应pydantic模型
- """
+ """字典类型表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -35,6 +33,11 @@ class DictTypeBaseModel(BaseModel):
message=I18nMessage('字典类型名称长度不能超过100个字符', msg_key='validation.dictNameLength'),
)
def get_dict_name(self) -> str | None:
+ """
+ 校验并返回字典名称。
+
+ :return: 字典名称
+ """
return self.dict_name
@NotBlank(field_name='dict_type', message=I18nMessage('字典类型不能为空', msg_key='validation.dictTypeRequired'))
@@ -52,17 +55,21 @@ def get_dict_name(self) -> str | None:
),
)
def get_dict_type(self) -> str | None:
+ """
+ 校验并返回字典类型。
+
+ :return: 字典类型
+ """
return self.dict_type
def validate_fields(self) -> None:
+ """校验字典名称、字典类型。"""
self.get_dict_name()
self.get_dict_type()
class DictTypeModel(DictTypeBaseModel):
- """
- 包含多语言译文的字典类型模型
- """
+ """包含多语言译文的字典类型模型。"""
dict_name_i18n: dict[str, str | None] = Field(default_factory=dict, alias='dictNameI18n', description='多语言译文')
@@ -70,15 +77,16 @@ class DictTypeModel(DictTypeBaseModel):
@classmethod
def validate_dict_name_i18n(cls, value: object) -> dict[str, str | None]:
"""
- 校验多语言译文
+ 校验多语言译文。
+
+ :param value: 待处理的输入值
+ :return: 通过校验的字典名称译文
"""
return TranslationUtil.validate(value, 100)
class DictDataBaseModel(BaseModel):
- """
- 字典数据表对应pydantic模型
- """
+ """字典数据表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -105,6 +113,11 @@ class DictDataBaseModel(BaseModel):
message=I18nMessage('字典标签长度不能超过100个字符', msg_key='validation.dictLabelLength'),
)
def get_dict_label(self) -> str | None:
+ """
+ 校验并返回字典标签。
+
+ :return: 字典标签
+ """
return self.dict_label
@NotBlank(field_name='dict_value', message=I18nMessage('字典键值不能为空', msg_key='validation.dictValueRequired'))
@@ -115,6 +128,11 @@ def get_dict_label(self) -> str | None:
message=I18nMessage('字典键值长度不能超过100个字符', msg_key='validation.dictValueLength'),
)
def get_dict_value(self) -> str | None:
+ """
+ 校验并返回字典键值。
+
+ :return: 字典键值
+ """
return self.dict_value
@NotBlank(field_name='dict_type', message=I18nMessage('字典类型不能为空', msg_key='validation.dictTypeRequired'))
@@ -125,6 +143,11 @@ def get_dict_value(self) -> str | None:
message=I18nMessage('字典类型长度不能超过100个字符', msg_key='validation.dictTypeLength'),
)
def get_dict_type(self) -> str | None:
+ """
+ 校验并返回字典类型。
+
+ :return: 字典类型
+ """
return self.dict_type
@Size(
@@ -134,9 +157,15 @@ def get_dict_type(self) -> str | None:
message=I18nMessage('样式属性长度不能超过100个字符', msg_key='validation.cssClassLength'),
)
def get_css_class(self) -> str | None:
+ """
+ 校验并返回样式属性(其他样式扩展)。
+
+ :return: 样式属性(其他样式扩展)
+ """
return self.css_class
def validate_fields(self) -> None:
+ """校验字典标签、字典键值、字典类型、样式属性(其他样式扩展)。"""
self.get_dict_label()
self.get_dict_value()
self.get_dict_type()
@@ -144,9 +173,7 @@ def validate_fields(self) -> None:
class DictDataModel(DictDataBaseModel):
- """
- 包含多语言译文的字典数据模型
- """
+ """包含多语言译文的字典数据模型。"""
dict_label_i18n: dict[str, str | None] = Field(
default_factory=dict, alias='dictLabelI18n', description='多语言译文'
@@ -156,33 +183,30 @@ class DictDataModel(DictDataBaseModel):
@classmethod
def validate_dict_label_i18n(cls, value: object) -> dict[str, str | None]:
"""
- 校验多语言译文
+ 校验多语言译文。
+
+ :param value: 待处理的输入值
+ :return: 通过校验的字典标签译文
"""
return TranslationUtil.validate(value, 100)
class DictTypeQueryModel(DateRangeQueryMixin, DictTypeBaseModel):
- """
- 字典类型管理不分页查询模型
- """
+ """字典类型管理不分页查询模型。"""
begin_time: str | None = Field(default=None, description='开始时间')
end_time: str | None = Field(default=None, description='结束时间')
class DictTypePageQueryModel(DictTypeQueryModel):
- """
- 字典类型管理分页查询模型
- """
+ """字典类型管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class DeleteDictTypeModel(BaseModel):
- """
- 删除字典类型模型
- """
+ """删除字典类型模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -190,27 +214,21 @@ class DeleteDictTypeModel(BaseModel):
class DictDataQueryModel(DateRangeQueryMixin, DictDataBaseModel):
- """
- 字典数据管理不分页查询模型
- """
+ """字典数据管理不分页查询模型。"""
begin_time: str | None = Field(default=None, description='开始时间')
end_time: str | None = Field(default=None, description='结束时间')
class DictDataPageQueryModel(DictDataQueryModel):
- """
- 字典数据管理分页查询模型
- """
+ """字典数据管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class DeleteDictDataModel(BaseModel):
- """
- 删除字典数据模型
- """
+ """删除字典数据模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/file_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/file_vo.py
index d1dc6978a..f1e933390 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/file_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/file_vo.py
@@ -21,9 +21,7 @@
class FileInfoModel(BaseModel):
- """
- 文件信息表对应pydantic模型
- """
+ """文件信息表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -55,9 +53,7 @@ class FileInfoModel(BaseModel):
class FileInfoDisplayModel(FileInfoModel):
- """
- 文件信息展示模型
- """
+ """文件信息展示模型。"""
owner_name: str | None = Field(default=None, description='所有者用户名称')
dept_name: str | None = Field(default=None, description='所属部门名称')
@@ -70,9 +66,7 @@ class FileInfoDisplayModel(FileInfoModel):
class FileReferenceModel(BaseModel):
- """
- 文件业务引用表对应pydantic模型
- """
+ """文件业务引用表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -88,9 +82,7 @@ class FileReferenceModel(BaseModel):
class FileRetentionPolicyModel(BaseModel):
- """
- 文件业务保留策略模型
- """
+ """文件业务保留策略模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True, str_strip_whitespace=True)
@@ -105,9 +97,7 @@ class FileRetentionPolicyModel(BaseModel):
class FileRetentionNoticeModel(BaseModel):
- """
- 文件保留期限提醒展示模型
- """
+ """文件保留期限提醒展示模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -127,9 +117,7 @@ class FileRetentionNoticeModel(BaseModel):
class FileRetentionNoticeQueryModel(BaseModel):
- """
- 文件保留期限提醒不分页查询模型
- """
+ """文件保留期限提醒不分页查询模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -139,18 +127,14 @@ class FileRetentionNoticeQueryModel(BaseModel):
class FileRetentionNoticePageQueryModel(FileRetentionNoticeQueryModel):
- """
- 文件保留期限提醒分页查询模型
- """
+ """文件保留期限提醒分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class FileRetentionScanModel(BaseModel):
- """
- 文件保留期限提醒扫描结果模型
- """
+ """文件保留期限提醒扫描结果模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -159,9 +143,7 @@ class FileRetentionScanModel(BaseModel):
class ExtendFileRetentionModel(BaseModel):
- """
- 延长文件保留期限模型
- """
+ """延长文件保留期限模型。"""
model_config = ConfigDict(alias_generator=to_camel, str_strip_whitespace=True)
@@ -170,9 +152,7 @@ class ExtendFileRetentionModel(BaseModel):
class DisposeExpiredFileModel(BaseModel):
- """
- 到期文件处置模型
- """
+ """到期文件处置模型。"""
model_config = ConfigDict(alias_generator=to_camel, str_strip_whitespace=True)
@@ -180,9 +160,7 @@ class DisposeExpiredFileModel(BaseModel):
class FileAccessLogModel(BaseModel):
- """
- 文件访问审计表对应pydantic模型
- """
+ """文件访问审计表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -214,9 +192,7 @@ class FileAccessLogModel(BaseModel):
class FileAclModel(BaseModel):
- """
- 文件访问控制表对应pydantic模型
- """
+ """文件访问控制表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -234,9 +210,7 @@ class FileAclModel(BaseModel):
class FileAclItemModel(BaseModel):
- """
- 文件访问控制配置项模型
- """
+ """文件访问控制配置项模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -248,9 +222,7 @@ class FileAclItemModel(BaseModel):
class FileAclBuiltinPermissionModel(BaseModel):
- """
- 文件内置访问权限展示模型
- """
+ """文件内置访问权限展示模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -264,9 +236,7 @@ class FileAclBuiltinPermissionModel(BaseModel):
class FileAclListModel(BaseModel):
- """
- 文件访问控制列表模型
- """
+ """文件访问控制列表模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -278,9 +248,7 @@ class FileAclListModel(BaseModel):
class SaveFileAclModel(BaseModel):
- """
- 保存文件访问控制模型
- """
+ """保存文件访问控制模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -289,9 +257,7 @@ class SaveFileAclModel(BaseModel):
class BatchSaveFileAclModel(BaseModel):
- """
- 批量保存文件访问控制模型
- """
+ """批量保存文件访问控制模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -300,9 +266,7 @@ class BatchSaveFileAclModel(BaseModel):
class FileAclSubjectOptionModel(BaseModel):
- """
- 文件访问控制主体选项模型
- """
+ """文件访问控制主体选项模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -312,9 +276,7 @@ class FileAclSubjectOptionModel(BaseModel):
class FileInfoQueryModel(InstantRangeQueryMixin, BaseModel):
- """
- 文件信息管理不分页查询模型
- """
+ """文件信息管理不分页查询模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -332,18 +294,14 @@ class FileInfoQueryModel(InstantRangeQueryMixin, BaseModel):
class FileInfoPageQueryModel(FileInfoQueryModel):
- """
- 文件信息管理分页查询模型
- """
+ """文件信息管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class FileStatsModel(BaseModel):
- """
- 文件管理统计模型
- """
+ """文件管理统计模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -359,9 +317,7 @@ class FileStatsModel(BaseModel):
class FileAccessLogQueryModel(InstantRangeQueryMixin, BaseModel):
- """
- 文件访问审计不分页查询模型
- """
+ """文件访问审计不分页查询模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -387,18 +343,14 @@ class FileAccessLogQueryModel(InstantRangeQueryMixin, BaseModel):
class FileAccessLogPageQueryModel(FileAccessLogQueryModel):
- """
- 文件访问审计分页查询模型
- """
+ """文件访问审计分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class DeleteFileModel(BaseModel):
- """
- 删除文件模型
- """
+ """删除文件模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -406,9 +358,7 @@ class DeleteFileModel(BaseModel):
class TransferFileModel(BaseModel):
- """
- 转移文件模型
- """
+ """转移文件模型。"""
model_config = ConfigDict(alias_generator=to_camel, str_strip_whitespace=True)
@@ -419,9 +369,7 @@ class TransferFileModel(BaseModel):
class FileReconcileRunModel(BaseModel):
- """
- 文件存储对账任务展示模型
- """
+ """文件存储对账任务展示模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -441,9 +389,7 @@ class FileReconcileRunModel(BaseModel):
class FileReconcileRunPageQueryModel(BaseModel):
- """
- 文件存储对账任务分页查询模型
- """
+ """文件存储对账任务分页查询模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -454,9 +400,7 @@ class FileReconcileRunPageQueryModel(BaseModel):
class FileReconcileIssueModel(BaseModel):
- """
- 文件存储对账异常展示模型
- """
+ """文件存储对账异常展示模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -502,9 +446,7 @@ class FileReconcileIssueModel(BaseModel):
class FileReconcileIssuePageQueryModel(BaseModel):
- """
- 文件存储对账异常分页查询模型
- """
+ """文件存储对账异常分页查询模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -517,9 +459,7 @@ class FileReconcileIssuePageQueryModel(BaseModel):
class FileReconcileStartModel(BaseModel):
- """
- 启动文件存储对账模型
- """
+ """启动文件存储对账模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -527,9 +467,7 @@ class FileReconcileStartModel(BaseModel):
class FileReconcileHandleModel(BaseModel):
- """
- 文件存储对账异常处理模型
- """
+ """文件存储对账异常处理模型。"""
model_config = ConfigDict(alias_generator=to_camel, str_strip_whitespace=True)
@@ -539,9 +477,7 @@ class FileReconcileHandleModel(BaseModel):
class FileReconcileStatsModel(BaseModel):
- """
- 文件存储对账统计模型
- """
+ """文件存储对账统计模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/job_runtime_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/job_runtime_vo.py
index 5b1727589..12e940a6a 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/job_runtime_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/job_runtime_vo.py
@@ -7,9 +7,7 @@
class JobExecutionModel(BaseModel):
- """
- 可供管理界面查询的执行状态,不包含执行占用凭据
- """
+ """可供管理界面查询的执行状态,不包含执行占用凭据。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -30,9 +28,7 @@ class JobExecutionModel(BaseModel):
class JobExecutionQueryModel(BaseModel):
- """
- 执行记录分页查询条件
- """
+ """执行记录分页查询条件。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -47,9 +43,7 @@ class JobExecutionQueryModel(BaseModel):
class JobSyncModel(BaseModel):
- """
- 单任务配置版本和实际应用状态
- """
+ """单任务配置版本和实际应用状态。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -68,9 +62,7 @@ class JobSyncModel(BaseModel):
class JobSyncQueryModel(BaseModel):
- """
- 包含删除记录的同步状态分页查询条件
- """
+ """包含删除记录的同步状态分页查询条件。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -83,9 +75,7 @@ class JobSyncQueryModel(BaseModel):
class JobMutationResult(BaseModel):
- """
- 业务修改已保存与调度配置已生效分开表达的响应数据
- """
+ """业务修改已保存与调度配置已生效分开表达的响应数据。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/job_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/job_vo.py
index a96ec4d04..0f3bf482b 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/job_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/job_vo.py
@@ -13,9 +13,7 @@
class JobModel(BaseModel):
- """
- 定时任务调度表对应pydantic模型
- """
+ """定时任务调度表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -69,10 +67,11 @@ class JobModel(BaseModel):
@classmethod
def reject_legacy_policy(cls, value: Any) -> Any:
"""
- 拒绝已替换的策略字段,避免旧调用方的配置被静默忽略
+ 拒绝已替换的策略字段,避免旧调用方的配置被静默忽略。
:param value: 接口传入的任务数据
:return: 使用当前字段的任务数据
+ :raises ValueError: 请使用 misfireGraceTime、coalesce 和 maxInstances 配置执行策略
"""
if isinstance(value, dict) and {'misfirePolicy', 'misfire_policy', 'concurrent'} & value.keys():
raise ValueError('请使用 misfireGraceTime、coalesce 和 maxInstances 配置执行策略')
@@ -82,7 +81,7 @@ def reject_legacy_policy(cls, value: Any) -> Any:
@classmethod
def validate_time_zone(cls, value: str) -> str:
"""
- 校验任务IANA时区名称
+ 校验任务IANA时区名称。
:param value: 任务时区名称
:return: 去除首尾空白后的有效时区名称
@@ -93,7 +92,7 @@ def validate_time_zone(cls, value: str) -> str:
@classmethod
def validate_cron_expression(cls, value: str | None) -> str | None:
"""
- 校验Quartz表达式语法
+ 校验Quartz表达式语法。
:param value: 待校验的Cron表达式
:return: 去除首尾空白后的表达式,未填写时保留None
@@ -114,6 +113,11 @@ def validate_cron_expression(cls, value: str | None) -> str | None:
message=I18nMessage('调用目标字符串长度不能超过500个字符', msg_key='validation.invokeTargetLength'),
)
def get_invoke_target(self) -> str | None:
+ """
+ 校验并返回调用目标字符串。
+
+ :return: 调用目标字符串
+ """
return self.invoke_target
@NotBlank(
@@ -126,17 +130,21 @@ def get_invoke_target(self) -> str | None:
message=I18nMessage('Cron执行表达式不能超过255个字符', msg_key='validation.cronLength'),
)
def get_cron_expression(self) -> str | None:
+ """
+ 校验并返回cron执行表达式。
+
+ :return: cron执行表达式
+ """
return self.cron_expression
def validate_fields(self) -> None:
+ """校验调用目标字符串、cron执行表达式。"""
self.get_invoke_target()
self.get_cron_expression()
class JobPreviewRequest(BaseModel):
- """
- Cron执行时刻预览请求模型
- """
+ """Cron执行时刻预览请求模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -149,7 +157,7 @@ class JobPreviewRequest(BaseModel):
@classmethod
def validate_time_zone(cls, value: str) -> str:
"""
- 校验任务IANA时区名称
+ 校验任务IANA时区名称。
:param value: 任务时区名称
:return: 去除首尾空白后的有效时区名称
@@ -160,7 +168,7 @@ def validate_time_zone(cls, value: str) -> str:
@classmethod
def validate_cron_expression(cls, value: str) -> str:
"""
- 校验Quartz表达式语法
+ 校验Quartz表达式语法。
:param value: 待校验的Cron表达式
:return: 去除首尾空白后的表达式
@@ -170,9 +178,7 @@ def validate_cron_expression(cls, value: str) -> str:
class JobPreviewResult(BaseModel):
- """
- Cron执行时刻预览结果模型
- """
+ """Cron执行时刻预览结果模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -182,9 +188,7 @@ class JobPreviewResult(BaseModel):
class JobLogModel(BaseModel):
- """
- 定时任务调度日志表对应pydantic模型
- """
+ """定时任务调度日志表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -211,9 +215,7 @@ class JobLogModel(BaseModel):
class JobQueryModel(DateRangeQueryMixin, BaseModel):
- """
- 定时任务管理不分页查询模型
- """
+ """定时任务管理不分页查询模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -225,27 +227,21 @@ class JobQueryModel(DateRangeQueryMixin, BaseModel):
class JobPageQueryModel(JobQueryModel):
- """
- 定时任务管理分页查询模型
- """
+ """定时任务管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class EditJobModel(JobModel):
- """
- 编辑定时任务模型
- """
+ """编辑定时任务模型。"""
job_id: int = Field(gt=0, description='任务ID')
type: str | None = Field(default=None, description='操作类型')
class JobRunModel(BaseModel):
- """
- 手动执行请求,仅按稳定任务ID读取已保存配置
- """
+ """手动执行请求,仅按稳定任务ID读取已保存配置。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -253,17 +249,13 @@ class JobRunModel(BaseModel):
class ChangeJobStatusModel(JobRunModel):
- """
- 修改任务状态请求
- """
+ """修改任务状态请求。"""
status: Literal['0', '1'] = Field(description='状态(0正常 1暂停)')
class DeleteJobModel(BaseModel):
- """
- 删除定时任务模型
- """
+ """删除定时任务模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -271,9 +263,7 @@ class DeleteJobModel(BaseModel):
class JobLogQueryModel(DateRangeQueryMixin, BaseModel):
- """
- 定时任务日志不分页查询模型
- """
+ """定时任务日志不分页查询模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -287,18 +277,14 @@ class JobLogQueryModel(DateRangeQueryMixin, BaseModel):
class JobLogPageQueryModel(JobLogQueryModel):
- """
- 定时任务日志管理分页查询模型
- """
+ """定时任务日志管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class DeleteJobLogModel(BaseModel):
- """
- 删除定时任务日志模型
- """
+ """删除定时任务日志模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/log_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/log_vo.py
index 081ae7638..3f3834d2c 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/log_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/log_vo.py
@@ -8,9 +8,7 @@
class OperLogModel(BaseModel):
- """
- 操作日志表对应pydantic模型
- """
+ """操作日志表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -38,9 +36,7 @@ class OperLogModel(BaseModel):
class LogininforModel(BaseModel):
- """
- 登录日志表对应pydantic模型
- """
+ """登录日志表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -56,9 +52,7 @@ class LogininforModel(BaseModel):
class OperLogQueryModel(DateRangeQueryMixin, OperLogModel):
- """
- 操作日志管理不分页查询模型
- """
+ """操作日志管理不分页查询模型。"""
order_by_column: str | None = Field(default=None, description='排序的字段名称')
is_asc: Literal['ascending', 'descending'] | None = Field(
@@ -69,18 +63,14 @@ class OperLogQueryModel(DateRangeQueryMixin, OperLogModel):
class OperLogPageQueryModel(OperLogQueryModel):
- """
- 操作日志管理分页查询模型
- """
+ """操作日志管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class DeleteOperLogModel(BaseModel):
- """
- 删除操作日志模型
- """
+ """删除操作日志模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -88,9 +78,7 @@ class DeleteOperLogModel(BaseModel):
class LoginLogQueryModel(DateRangeQueryMixin, LogininforModel):
- """
- 登录日志管理不分页查询模型
- """
+ """登录日志管理不分页查询模型。"""
order_by_column: str | None = Field(default=None, description='排序的字段名称')
is_asc: Literal['ascending', 'descending'] | None = Field(
@@ -101,18 +89,14 @@ class LoginLogQueryModel(DateRangeQueryMixin, LogininforModel):
class LoginLogPageQueryModel(LoginLogQueryModel):
- """
- 登录日志管理分页查询模型
- """
+ """登录日志管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class DeleteLoginLogModel(BaseModel):
- """
- 删除登录日志模型
- """
+ """删除登录日志模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -120,9 +104,7 @@ class DeleteLoginLogModel(BaseModel):
class UnlockUser(BaseModel):
- """
- 解锁用户模型
- """
+ """解锁用户模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/login_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/login_vo.py
index d8dc8260d..a438a9474 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/login_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/login_vo.py
@@ -8,6 +8,8 @@
class UserLogin(BaseModel):
+ """用户登录所需的凭据和验证信息。"""
+
model_config = ConfigDict(alias_generator=to_camel)
user_name: str = Field(description='用户名称')
@@ -19,12 +21,16 @@ class UserLogin(BaseModel):
class UnlockScreenModel(BaseModel):
+ """用于验证锁屏解锁请求的凭据。"""
+
model_config = ConfigDict(alias_generator=to_camel)
password: str | None = Field(default=None, description='用户密码')
class UserRegister(BaseModel):
+ """注册新用户时提交的账户资料。"""
+
model_config = ConfigDict(alias_generator=to_camel)
username: str = Field(description='用户名称')
@@ -35,6 +41,12 @@ class UserRegister(BaseModel):
@model_validator(mode='after')
def check_password(self) -> 'UserRegister':
+ """
+ 校验密码中是否包含禁止使用的字符。
+
+ :return: 当前实例
+ :raises ModelValidatorException: 密码中含有禁止使用的字符
+ """
pattern = r"""^[^<>"'|\\]+$"""
if self.password is None or re.match(pattern, self.password):
return self
@@ -42,17 +54,23 @@ def check_password(self) -> 'UserRegister':
class Token(BaseModel):
+ """OAuth 登录令牌响应。"""
+
access_token: str = Field(description='token信息')
token_type: str = Field(description='token类型')
class LoginToken(BaseModel):
+ """用户登录成功后签发的令牌。"""
+
model_config = ConfigDict(alias_generator=to_camel)
token: str = Field(description='token信息')
class CaptchaCode(BaseModel):
+ """图形验证码响应。"""
+
model_config = ConfigDict(alias_generator=to_camel)
captcha_enabled: bool = Field(description='是否启用验证码')
@@ -62,6 +80,8 @@ class CaptchaCode(BaseModel):
class SmsCode(BaseModel):
+ """短信验证码及其发送结果。"""
+
is_success: bool | None = Field(default=None, description='操作是否成功')
sms_code: str = Field(description='短信验证码')
session_id: str = Field(description='会话编号')
@@ -69,10 +89,14 @@ class SmsCode(BaseModel):
class MenuTreeModel(MenuModel):
+ """表示菜单树中的可选节点。"""
+
children: list['MenuTreeModel'] | None | None = Field(default=None, description='子菜单')
class MetaModel(BaseModel):
+ """描述前端路由的展示及缓存选项。"""
+
model_config = ConfigDict(alias_generator=to_camel)
title: str | None = Field(default=None, description='设置路由在侧边栏和面包屑中展示的名字')
@@ -84,6 +108,8 @@ class MetaModel(BaseModel):
class RouterModel(BaseModel):
+ """描述用户可访问的前端路由及其子路由。"""
+
model_config = ConfigDict(alias_generator=to_camel)
name: str | None = Field(default=None, description='路由名称')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/menu_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/menu_vo.py
index 6298058fd..3ca762a1e 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/menu_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/menu_vo.py
@@ -11,9 +11,7 @@
class MenuBaseModel(BaseModel):
- """
- 菜单表对应pydantic模型
- """
+ """菜单表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -46,10 +44,20 @@ class MenuBaseModel(BaseModel):
message=I18nMessage('菜单名称长度不能超过50个字符', msg_key='validation.menuNameLength'),
)
def get_menu_name(self) -> str | None:
+ """
+ 校验并返回菜单名称。
+
+ :return: 菜单名称
+ """
return self.menu_name
@NotBlank(field_name='order_num', message=I18nMessage('显示顺序不能为空', msg_key='validation.orderRequired'))
def get_order_num(self) -> int | None:
+ """
+ 校验并返回显示顺序。
+
+ :return: 显示顺序
+ """
return self.order_num
@Size(
@@ -59,6 +67,11 @@ def get_order_num(self) -> int | None:
message=I18nMessage('路由地址长度不能超过200个字符', msg_key='validation.routePathLength'),
)
def get_path(self) -> str | None:
+ """
+ 校验并返回路由地址。
+
+ :return: 路由地址
+ """
return self.path
@Size(
@@ -68,10 +81,20 @@ def get_path(self) -> str | None:
message=I18nMessage('组件路径长度不能超过255个字符', msg_key='validation.componentPathLength'),
)
def get_component(self) -> str | None:
+ """
+ 校验并返回组件路径。
+
+ :return: 组件路径
+ """
return self.component
@NotBlank(field_name='menu_type', message=I18nMessage('菜单类型不能为空', msg_key='validation.menuTypeRequired'))
def get_menu_type(self) -> Literal['M', 'C', 'F'] | None:
+ """
+ 校验并返回菜单类型(M目录 C菜单 F按钮)。
+
+ :return: 菜单类型(M目录 C菜单 F按钮)
+ """
return self.menu_type
@Size(
@@ -81,9 +104,15 @@ def get_menu_type(self) -> Literal['M', 'C', 'F'] | None:
message=I18nMessage('权限标识长度不能超过100个字符', msg_key='validation.permissionLength'),
)
def get_perms(self) -> str | None:
+ """
+ 校验并返回权限标识。
+
+ :return: 权限标识
+ """
return self.perms
def validate_fields(self) -> None:
+ """校验代码生成所需的表名、模型命名、包名和作者等字段。"""
self.get_menu_name()
self.get_order_num()
self.get_path()
@@ -93,9 +122,7 @@ def validate_fields(self) -> None:
class MenuModel(MenuBaseModel):
- """
- 包含多语言译文的菜单模型
- """
+ """包含多语言译文的菜单模型。"""
menu_name_i18n: dict[str, str | None] = Field(default_factory=dict, alias='menuNameI18n', description='多语言译文')
@@ -103,24 +130,23 @@ class MenuModel(MenuBaseModel):
@classmethod
def validate_menu_name_i18n(cls, value: object) -> dict[str, str | None]:
"""
- 校验多语言译文
+ 校验多语言译文。
+
+ :param value: 待处理的输入值
+ :return: 通过校验的菜单名称译文
"""
return TranslationUtil.validate(value, 50)
class MenuQueryModel(DateRangeQueryMixin, MenuBaseModel):
- """
- 菜单管理不分页查询模型
- """
+ """菜单管理不分页查询模型。"""
begin_time: str | None = Field(default=None, description='开始时间')
end_time: str | None = Field(default=None, description='结束时间')
class MenuTreeModel(BaseModel):
- """
- 菜单树模型
- """
+ """菜单树模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -132,9 +158,7 @@ class MenuTreeModel(BaseModel):
class DeleteMenuModel(BaseModel):
- """
- 删除菜单模型
- """
+ """删除菜单模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -142,9 +166,7 @@ class DeleteMenuModel(BaseModel):
class MenuSortModel(BaseModel):
- """
- 菜单排序批量保存模型
- """
+ """菜单排序批量保存模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/notice_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/notice_vo.py
index 331daefe3..5f9525808 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/notice_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/notice_vo.py
@@ -11,9 +11,7 @@
class NoticeModel(BaseModel):
- """
- 通知公告表对应pydantic模型
- """
+ """通知公告表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -54,34 +52,34 @@ def sanitize_content(cls, value: bytes | None) -> bytes | None:
message=I18nMessage('公告标题不能超过50个字符', msg_key='validation.noticeTitleLength'),
)
def get_notice_title(self) -> str | None:
+ """
+ 校验并返回公告标题。
+
+ :return: 公告标题
+ """
return self.notice_title
def validate_fields(self) -> None:
+ """校验公告标题。"""
self.get_notice_title()
class NoticeQueryModel(DateRangeQueryMixin, NoticeModel):
- """
- 通知公告管理不分页查询模型
- """
+ """通知公告管理不分页查询模型。"""
begin_time: str | None = Field(default=None, description='开始时间')
end_time: str | None = Field(default=None, description='结束时间')
class NoticePageQueryModel(NoticeQueryModel):
- """
- 通知公告管理分页查询模型
- """
+ """通知公告管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class NoticeReadUserModel(BaseModel):
- """
- 公告已读用户模型
- """
+ """公告已读用户模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -94,9 +92,7 @@ class NoticeReadUserModel(BaseModel):
class NoticeReadUserPageQueryModel(BaseModel):
- """
- 公告已读用户分页查询模型
- """
+ """公告已读用户分页查询模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -107,9 +103,7 @@ class NoticeReadUserPageQueryModel(BaseModel):
class DeleteNoticeModel(BaseModel):
- """
- 删除通知公告模型
- """
+ """删除通知公告模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -117,9 +111,7 @@ class DeleteNoticeModel(BaseModel):
class NoticeTopModel(BaseModel):
- """
- 首页顶部通知公告模型
- """
+ """首页顶部通知公告模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -133,9 +125,7 @@ class NoticeTopModel(BaseModel):
class NoticeTopResponseModel(BaseModel):
- """
- 首页顶部通知公告响应模型
- """
+ """首页顶部通知公告响应模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/online_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/online_vo.py
index 47f784613..8d18fce49 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/online_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/online_vo.py
@@ -6,9 +6,7 @@
class OnlineModel(BaseModel):
- """
- 在线用户对应pydantic模型
- """
+ """在线用户对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -23,18 +21,14 @@ class OnlineModel(BaseModel):
class OnlineQueryModel(DateRangeQueryMixin, OnlineModel):
- """
- 岗位管理不分页查询模型
- """
+ """岗位管理不分页查询模型。"""
begin_time: str | None = Field(default=None, description='开始时间')
end_time: str | None = Field(default=None, description='结束时间')
class OnlinePageResponseModel(BaseModel):
- """
- 在线用户分页响应模型
- """
+ """在线用户分页响应模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -43,9 +37,7 @@ class OnlinePageResponseModel(BaseModel):
class DeleteOnlineModel(BaseModel):
- """
- 强退在线用户模型
- """
+ """强退在线用户模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/post_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/post_vo.py
index f9aee5b93..37b4f51e0 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/post_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/post_vo.py
@@ -10,9 +10,7 @@
class PostModel(BaseModel):
- """
- 岗位信息表对应pydantic模型
- """
+ """岗位信息表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -35,6 +33,11 @@ class PostModel(BaseModel):
message=I18nMessage('岗位编码长度不能超过64个字符', msg_key='validation.postCodeLength'),
)
def get_post_code(self) -> str | None:
+ """
+ 校验并返回岗位编码。
+
+ :return: 岗位编码
+ """
return self.post_code
@NotBlank(field_name='post_name', message=I18nMessage('岗位名称不能为空', msg_key='validation.postNameRequired'))
@@ -45,40 +48,45 @@ def get_post_code(self) -> str | None:
message=I18nMessage('岗位名称长度不能超过50个字符', msg_key='validation.postNameLength'),
)
def get_post_name(self) -> str | None:
+ """
+ 校验并返回岗位名称。
+
+ :return: 岗位名称
+ """
return self.post_name
@NotBlank(field_name='post_sort', message=I18nMessage('显示顺序不能为空', msg_key='validation.orderRequired'))
def get_post_sort(self) -> int | None:
+ """
+ 校验并返回显示顺序。
+
+ :return: 显示顺序
+ """
return self.post_sort
def validate_fields(self) -> None:
+ """校验岗位编码、岗位名称、显示顺序。"""
self.get_post_code()
self.get_post_name()
self.get_post_sort()
class PostQueryModel(DateRangeQueryMixin, PostModel):
- """
- 岗位管理不分页查询模型
- """
+ """岗位管理不分页查询模型。"""
begin_time: str | None = Field(default=None, description='开始时间')
end_time: str | None = Field(default=None, description='结束时间')
class PostPageQueryModel(PostQueryModel):
- """
- 岗位管理分页查询模型
- """
+ """岗位管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class DeletePostModel(BaseModel):
- """
- 删除岗位模型
- """
+ """删除岗位模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/role_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/role_vo.py
index 9af499715..3da6d77fe 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/role_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/role_vo.py
@@ -10,9 +10,7 @@
class RoleModel(BaseModel):
- """
- 角色表对应pydantic模型
- """
+ """角色表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -38,6 +36,12 @@ class RoleModel(BaseModel):
@field_validator('menu_check_strictly', 'dept_check_strictly')
@classmethod
def check_filed_mapping(cls, v: int | bool) -> int | bool:
+ """
+ 将角色标志值转换为模型接受的表示。
+
+ :param v: 待校验的字段映射
+ :return: 待校验的字段映射
+ """
if v == 1:
v = True
elif v == 0:
@@ -50,6 +54,11 @@ def check_filed_mapping(cls, v: int | bool) -> int | bool:
@model_validator(mode='after')
def check_admin(self) -> 'RoleModel':
+ """
+ 根据角色编号标记管理员角色。
+
+ :return: 当前实例
+ """
if self.role_id == 1:
self.admin = True
else:
@@ -64,6 +73,11 @@ def check_admin(self) -> 'RoleModel':
message=I18nMessage('角色名称长度不能超过30个字符', msg_key='validation.roleNameLength'),
)
def get_role_name(self) -> str | None:
+ """
+ 校验并返回角色名称。
+
+ :return: 角色名称
+ """
return self.role_name
@NotBlank(field_name='role_key', message=I18nMessage('权限字符不能为空', msg_key='validation.roleKeyRequired'))
@@ -74,22 +88,31 @@ def get_role_name(self) -> str | None:
message=I18nMessage('权限字符长度不能超过100个字符', msg_key='validation.roleKeyLength'),
)
def get_role_key(self) -> str | None:
+ """
+ 校验并返回角色权限字符串。
+
+ :return: 角色权限字符串
+ """
return self.role_key
@NotBlank(field_name='role_sort', message=I18nMessage('显示顺序不能为空', msg_key='validation.orderRequired'))
def get_role_sort(self) -> int | None:
+ """
+ 校验并返回显示顺序。
+
+ :return: 显示顺序
+ """
return self.role_sort
def validate_fields(self) -> None:
+ """校验角色名称、角色权限字符串、显示顺序。"""
self.get_role_name()
self.get_role_key()
self.get_role_sort()
class RoleMenuModel(BaseModel):
- """
- 角色和菜单关联表对应pydantic模型
- """
+ """角色和菜单关联表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -98,9 +121,7 @@ class RoleMenuModel(BaseModel):
class RoleDeptModel(BaseModel):
- """
- 角色和部门关联表对应pydantic模型
- """
+ """角色和部门关联表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -109,27 +130,21 @@ class RoleDeptModel(BaseModel):
class RoleQueryModel(DateRangeQueryMixin, RoleModel):
- """
- 角色管理不分页查询模型
- """
+ """角色管理不分页查询模型。"""
begin_time: str | None = Field(default=None, description='开始时间')
end_time: str | None = Field(default=None, description='结束时间')
class RolePageQueryModel(RoleQueryModel):
- """
- 角色管理分页查询模型
- """
+ """角色管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class RoleMenuQueryModel(BaseModel):
- """
- 角色菜单查询模型
- """
+ """角色菜单查询模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -138,9 +153,7 @@ class RoleMenuQueryModel(BaseModel):
class RoleDeptQueryModel(BaseModel):
- """
- 角色部门查询模型
- """
+ """角色部门查询模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -149,9 +162,7 @@ class RoleDeptQueryModel(BaseModel):
class AddRoleModel(RoleModel):
- """
- 新增角色模型
- """
+ """新增角色模型。"""
dept_ids: list = Field(default=[], description='部门ID信息')
menu_ids: list = Field(default=[], description='菜单ID信息')
@@ -159,9 +170,7 @@ class AddRoleModel(RoleModel):
class DeleteRoleModel(BaseModel):
- """
- 删除角色模型
- """
+ """删除角色模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/server_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/server_vo.py
index 78ecb139c..325d36934 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/server_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/server_vo.py
@@ -5,6 +5,8 @@
class CpuInfo(BaseModel):
+ """描述处理器的核心数量和使用情况。"""
+
model_config = ConfigDict(alias_generator=to_camel)
cpu_num: int | None = Field(default=None, description='核心数')
@@ -14,6 +16,8 @@ class CpuInfo(BaseModel):
class MemoryInfo(BaseModel):
+ """描述服务器内存的容量和占用情况。"""
+
model_config = ConfigDict(alias_generator=to_camel)
total: str | None = Field(default=None, description='内存总量')
@@ -23,6 +27,8 @@ class MemoryInfo(BaseModel):
class SysInfo(BaseModel):
+ """描述服务器主机及操作系统信息。"""
+
model_config = ConfigDict(alias_generator=to_camel)
computer_ip: str | None = Field(default=None, description='服务器IP')
@@ -33,6 +39,8 @@ class SysInfo(BaseModel):
class PyInfo(MemoryInfo):
+ """描述 Python 运行环境及进程信息。"""
+
model_config = ConfigDict(alias_generator=to_camel)
name: str | None = Field(default=None, description='Python名称')
@@ -43,6 +51,8 @@ class PyInfo(MemoryInfo):
class SysFiles(BaseModel):
+ """描述文件系统挂载点及磁盘空间用量。"""
+
model_config = ConfigDict(alias_generator=to_camel)
dir_name: str | None = Field(default=None, description='盘符路径')
@@ -55,9 +65,7 @@ class SysFiles(BaseModel):
class ServerMonitorModel(BaseModel):
- """
- 服务监控对应pydantic模型
- """
+ """服务监控对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/transport_crypto_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/transport_crypto_vo.py
index 8f3affd82..2071c400e 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/transport_crypto_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/transport_crypto_vo.py
@@ -5,9 +5,7 @@
class TransportCryptoFrontendConfigModel(BaseModel):
- """
- 传输层加解密前端运行配置模型
- """
+ """传输层加解密前端运行配置模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -26,9 +24,7 @@ class TransportCryptoFrontendConfigModel(BaseModel):
class TransportCryptoPublicKeyModel(BaseModel):
- """
- 传输层加解密公钥下发模型
- """
+ """传输层加解密公钥下发模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -41,9 +37,7 @@ class TransportCryptoPublicKeyModel(BaseModel):
class TransportCryptoKidStatModel(BaseModel):
- """
- 传输层加解密按密钥版本统计模型
- """
+ """传输层加解密按密钥版本统计模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -55,9 +49,7 @@ class TransportCryptoKidStatModel(BaseModel):
class TransportCryptoFailureRecordModel(BaseModel):
- """
- 传输层加解密最近失败记录模型
- """
+ """传输层加解密最近失败记录模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -69,9 +61,7 @@ class TransportCryptoFailureRecordModel(BaseModel):
class TransportCryptoMonitorModel(BaseModel):
- """
- 传输层加解密监控模型
- """
+ """传输层加解密监控模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/user_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/user_vo.py
index 8821b252f..101590489 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/user_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/user_vo.py
@@ -17,17 +17,13 @@
class TokenData(BaseModel):
- """
- token解析结果
- """
+ """token解析结果。"""
user_id: int | None = Field(default=None, description='用户ID')
class UserModel(BaseModel):
- """
- 用户表对应pydantic模型
- """
+ """用户表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -59,7 +55,7 @@ class UserModel(BaseModel):
@field_serializer('locale_revision')
def serialize_locale_revision(self, value: int) -> str:
"""
- 将语言偏好版本输出为字符串,保留 BIGINT 精度
+ 将语言偏好版本输出为字符串,保留 BIGINT 精度。
:param value: 账号语言偏好版本
:return: 十进制版本字符串
@@ -70,7 +66,7 @@ def serialize_locale_revision(self, value: int) -> str:
@classmethod
def validate_user_locale(cls, value: str) -> str:
"""
- 校验并规范化账号语言偏好
+ 校验并规范化账号语言偏好。
:param value: auto或语言标识
:return: 规范化后的语言偏好
@@ -81,7 +77,7 @@ def validate_user_locale(cls, value: str) -> str:
@classmethod
def validate_time_zone(cls, value: str) -> str:
"""
- 校验账号显示时区偏好
+ 校验账号显示时区偏好。
:param value: auto或IANA时区名称
:return: 校验后的时区偏好
@@ -90,6 +86,12 @@ def validate_time_zone(cls, value: str) -> str:
@model_validator(mode='after')
def check_password(self) -> 'UserModel':
+ """
+ 校验密码中是否包含禁止使用的字符。
+
+ :return: 当前实例
+ :raises ModelValidatorException: 密码中含有禁止使用的字符
+ """
pattern = r"""^[^<>"'|\\]+$"""
if self.password is None or re.match(pattern, self.password):
return self
@@ -97,6 +99,11 @@ def check_password(self) -> 'UserModel':
@model_validator(mode='after')
def check_admin(self) -> 'UserModel':
+ """
+ 根据用户编号标记管理员用户。
+
+ :return: 当前实例
+ """
if self.user_id == 1:
self.admin = True
else:
@@ -112,6 +119,11 @@ def check_admin(self) -> 'UserModel':
message=I18nMessage('用户账号长度不能超过30个字符', msg_key='validation.userNameLength'),
)
def get_user_name(self) -> str | None:
+ """
+ 校验并返回用户账号。
+
+ :return: 用户账号
+ """
return self.user_name
@Xss(field_name='nick_name', message=I18nMessage('用户昵称不能包含脚本字符', msg_key='validation.nickNameScript'))
@@ -122,6 +134,11 @@ def get_user_name(self) -> str | None:
message=I18nMessage('用户昵称长度不能超过30个字符', msg_key='validation.nickNameLength'),
)
def get_nick_name(self) -> str | None:
+ """
+ 校验并返回用户昵称。
+
+ :return: 用户昵称
+ """
return self.nick_name
@Network(
@@ -136,6 +153,11 @@ def get_nick_name(self) -> str | None:
message=I18nMessage('邮箱长度不能超过50个字符', msg_key='validation.emailLength'),
)
def get_email(self) -> str | None:
+ """
+ 校验并返回用户邮箱。
+
+ :return: 用户邮箱
+ """
return self.email
@Size(
@@ -145,9 +167,15 @@ def get_email(self) -> str | None:
message=I18nMessage('手机号码长度不能超过11个字符', msg_key='validation.mobileLength'),
)
def get_phonenumber(self) -> str | None:
+ """
+ 校验并返回手机号码。
+
+ :return: 手机号码
+ """
return self.phonenumber
def validate_fields(self) -> None:
+ """校验用户账号、用户昵称、用户邮箱、手机号码。"""
self.get_user_name()
self.get_nick_name()
self.get_email()
@@ -155,17 +183,13 @@ def validate_fields(self) -> None:
class UserRowModel(UserModel):
- """
- 用户列表行数据模型
- """
+ """用户列表行数据模型。"""
dept: DeptModel | None = Field(default=None, description='部门信息')
class UserRoleModel(BaseModel):
- """
- 用户和角色关联表对应pydantic模型
- """
+ """用户和角色关联表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -174,9 +198,7 @@ class UserRoleModel(BaseModel):
class UserPostModel(BaseModel):
- """
- 用户与岗位关联表对应pydantic模型
- """
+ """用户与岗位关联表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -185,6 +207,8 @@ class UserPostModel(BaseModel):
class UserInfoModel(UserModel):
+ """用户个人资料及其部门、角色信息。"""
+
post_ids: str | None | None = Field(default=None, description='岗位ID信息')
role_ids: str | None | None = Field(default=None, description='角色ID信息')
dept: DeptModel | None | None = Field(default=None, description='部门信息')
@@ -192,9 +216,7 @@ class UserInfoModel(UserModel):
class UpdateUserProfileModel(BaseModel):
- """
- 修改用户个人资料模型
- """
+ """修改用户个人资料模型。"""
model_config = ConfigDict(alias_generator=to_camel, extra='forbid')
@@ -205,9 +227,7 @@ class UpdateUserProfileModel(BaseModel):
class UserTimezoneModel(BaseModel):
- """
- 当前用户的显示时区偏好模型
- """
+ """当前用户的显示时区偏好模型。"""
model_config = ConfigDict(alias_generator=to_camel, extra='forbid')
@@ -217,7 +237,7 @@ class UserTimezoneModel(BaseModel):
@classmethod
def validate_time_zone(cls, value: str) -> str:
"""
- 校验并规范化时区偏好
+ 校验并规范化时区偏好。
:param value: auto或IANA时区名称
:return: 校验后的时区偏好
@@ -226,9 +246,7 @@ def validate_time_zone(cls, value: str) -> str:
class UserLocaleModel(BaseModel):
- """
- 当前用户的语言偏好模型
- """
+ """当前用户的语言偏好模型。"""
model_config = ConfigDict(extra='forbid')
locale: str = Field(max_length=63, description='语言偏好(auto跟随设备或语言标识)')
@@ -237,7 +255,7 @@ class UserLocaleModel(BaseModel):
@classmethod
def validate_locale(cls, value: str) -> str:
"""
- 校验并规范化语言偏好设置
+ 校验并规范化语言偏好设置。
:param value: auto或语言标识
:return: 规范化后的语言偏好
@@ -246,6 +264,8 @@ def validate_locale(cls, value: str) -> str:
class CurrentUserModel(BaseModel):
+ """当前已认证用户及其权限信息。"""
+
model_config = ConfigDict(alias_generator=to_camel)
permissions: list = Field(description='权限信息')
@@ -258,9 +278,7 @@ class CurrentUserModel(BaseModel):
class UserDetailModel(BaseModel):
- """
- 获取用户详情信息响应模型
- """
+ """获取用户详情信息响应模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -272,9 +290,7 @@ class UserDetailModel(BaseModel):
class UserProfileModel(BaseModel):
- """
- 获取个人信息响应模型
- """
+ """获取个人信息响应模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -284,9 +300,7 @@ class UserProfileModel(BaseModel):
class AvatarModel(BaseModel):
- """
- 上传头像响应模型
- """
+ """上传头像响应模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -294,27 +308,21 @@ class AvatarModel(BaseModel):
class UserQueryModel(DateRangeQueryMixin, UserModel):
- """
- 用户管理不分页查询模型
- """
+ """用户管理不分页查询模型。"""
begin_time: str | None = Field(default=None, description='开始时间')
end_time: str | None = Field(default=None, description='结束时间')
class UserPageQueryModel(UserQueryModel):
- """
- 用户管理分页查询模型
- """
+ """用户管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class AddUserModel(UserModel):
- """
- 新增用户模型
- """
+ """新增用户模型。"""
role_ids: list | None = Field(default=[], description='角色ID信息')
post_ids: list | None = Field(default=[], description='岗位ID信息')
@@ -322,17 +330,13 @@ class AddUserModel(UserModel):
class EditUserModel(AddUserModel):
- """
- 编辑用户模型
- """
+ """编辑用户模型。"""
role: list | None = Field(default=[], description='角色信息')
class ResetPasswordModel(BaseModel):
- """
- 重置密码模型
- """
+ """重置密码模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -341,6 +345,12 @@ class ResetPasswordModel(BaseModel):
@model_validator(mode='after')
def check_new_password(self) -> 'ResetPasswordModel':
+ """
+ 校验重置密码是否包含禁止使用的字符。
+
+ :return: 当前实例
+ :raises ModelValidatorException: 密码中含有禁止使用的字符
+ """
pattern = r"""^[^<>"'|\\]+$"""
if self.new_password is None or re.match(pattern, self.new_password):
return self
@@ -348,9 +358,7 @@ def check_new_password(self) -> 'ResetPasswordModel':
class ResetUserModel(UserModel):
- """
- 重置用户密码模型
- """
+ """重置用户密码模型。"""
old_password: str | None = Field(default=None, description='旧密码')
sms_code: str | None = Field(default=None, description='验证码')
@@ -358,9 +366,7 @@ class ResetUserModel(UserModel):
class DeleteUserModel(BaseModel):
- """
- 删除用户模型
- """
+ """删除用户模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -370,34 +376,26 @@ class DeleteUserModel(BaseModel):
class UserRoleQueryModel(UserModel):
- """
- 用户角色关联管理不分页查询模型
- """
+ """用户角色关联管理不分页查询模型。"""
role_id: int | None = Field(default=None, description='角色ID')
class UserRolePageQueryModel(UserRoleQueryModel):
- """
- 用户角色关联管理分页查询模型
- """
+ """用户角色关联管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class SelectedRoleModel(RoleModel):
- """
- 是否选择角色模型
- """
+ """是否选择角色模型。"""
flag: bool | None = Field(default=False, description='选择标识')
class UserRoleResponseModel(BaseModel):
- """
- 用户角色关联管理列表返回模型
- """
+ """用户角色关联管理列表返回模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -406,9 +404,7 @@ class UserRoleResponseModel(BaseModel):
class CrudUserRoleModel(BaseModel):
- """
- 新增、删除用户关联角色及角色关联用户模型
- """
+ """新增、删除用户关联角色及角色关联用户模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_admin/service/cache_service.py b/ruoyi-fastapi-backend/module_admin/service/cache_service.py
index f94b52f18..0d8a85653 100644
--- a/ruoyi-fastapi-backend/module_admin/service/cache_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/cache_service.py
@@ -7,14 +7,12 @@
class CacheService:
- """
- 缓存监控模块服务层
- """
+ """缓存监控模块服务层。"""
@classmethod
async def get_cache_monitor_statistical_info_services(cls, request: Request) -> CacheMonitorModel:
"""
- 获取缓存监控信息service
+ 获取缓存监控信息service。
:param request: Request对象
:return: 缓存监控信息
@@ -32,7 +30,7 @@ async def get_cache_monitor_statistical_info_services(cls, request: Request) ->
@classmethod
async def get_cache_monitor_cache_name_services(cls) -> list[CacheInfoModel]:
"""
- 获取缓存名称列表信息service
+ 获取缓存名称列表信息service。
:return: 缓存名称列表信息
"""
@@ -51,7 +49,7 @@ async def get_cache_monitor_cache_name_services(cls) -> list[CacheInfoModel]:
@classmethod
async def get_cache_monitor_cache_key_services(cls, request: Request, cache_name: str) -> list[str]:
"""
- 获取缓存键名列表信息service
+ 获取缓存键名列表信息service。
:param request: Request对象
:param cache_name: 缓存名称
@@ -67,7 +65,7 @@ async def get_cache_monitor_cache_value_services(
cls, request: Request, cache_name: str, cache_key: str
) -> CacheInfoModel:
"""
- 获取缓存内容信息service
+ 获取缓存内容信息service。
:param request: Request对象
:param cache_name: 缓存名称
@@ -81,7 +79,7 @@ async def get_cache_monitor_cache_value_services(
@classmethod
async def clear_cache_monitor_cache_name_services(cls, request: Request, cache_name: str) -> CrudResponseModel:
"""
- 清除缓存名称对应所有键值service
+ 清除缓存名称对应所有键值service。
:param request: Request对象
:param cache_name: 缓存名称
@@ -101,7 +99,7 @@ async def clear_cache_monitor_cache_name_services(cls, request: Request, cache_n
@classmethod
async def clear_cache_monitor_cache_key_services(cls, request: Request, cache_key: str) -> CrudResponseModel:
"""
- 清除缓存名称对应所有键值service
+ 清除缓存名称对应所有键值service。
:param request: Request对象
:param cache_key: 缓存键名
@@ -121,7 +119,7 @@ async def clear_cache_monitor_cache_key_services(cls, request: Request, cache_ke
@classmethod
async def clear_cache_monitor_all_services(cls, request: Request) -> CrudResponseModel:
"""
- 清除所有缓存service
+ 清除所有缓存service。
:param request: Request对象
:return: 操作缓存响应信息
diff --git a/ruoyi-fastapi-backend/module_admin/service/captcha_service.py b/ruoyi-fastapi-backend/module_admin/service/captcha_service.py
index 7a8126997..3d2160d34 100644
--- a/ruoyi-fastapi-backend/module_admin/service/captcha_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/captcha_service.py
@@ -7,12 +7,15 @@
class CaptchaService:
- """
- 验证码模块服务层
- """
+ """验证码模块服务层。"""
@classmethod
async def create_captcha_image_service(cls) -> list[str, int]:
+ """
+ 创建登录使用的图形验证码。
+
+ :return: 登录使用的图形验证码
+ """
# 创建空白图像
image = Image.new('RGB', (160, 60), color='#EAEAEA')
diff --git a/ruoyi-fastapi-backend/module_admin/service/common_service.py b/ruoyi-fastapi-backend/module_admin/service/common_service.py
index a3c5b201d..9d01aa88f 100644
--- a/ruoyi-fastapi-backend/module_admin/service/common_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/common_service.py
@@ -27,9 +27,7 @@
class CommonService:
- """
- 通用模块服务层
- """
+ """通用模块服务层。"""
@classmethod
async def upload_service(
@@ -41,7 +39,7 @@ async def upload_service(
access_type: Literal['public', 'private'] = 'public',
) -> CrudResponseModel:
"""
- 通用上传service
+ 通用上传service。
:param request: Request对象
:param query_db: orm对象
@@ -49,6 +47,8 @@ async def upload_service(
:param file: 上传文件对象
:param access_type: 文件访问类型
:return: 上传结果
+ :raises ServiceException: 文件访问类型不合法;文件类型不合法;文件名生成冲突,请重新上传;无法获取当前用户信息
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
if access_type not in {'public', 'private'}:
raise ServiceException(message='文件访问类型不合法', msg_key='file.invalidAccessType')
@@ -158,11 +158,12 @@ async def upload_service(
@classmethod
async def _write_uploaded_file(cls, file: UploadFile, filepath: Path) -> tuple[int, str]:
"""
- 将上传文件写入目标路径并计算摘要
+ 将上传文件写入目标路径并计算摘要。
:param file: 上传文件对象
:param filepath: 文件目标路径
:return: 文件大小和SHA-256
+ :raises Exception: 底层操作失败时向调用方传播异常
"""
total_size = 0
file_hasher = hashlib.sha256()
@@ -198,7 +199,7 @@ async def download_managed_file_services(
range_header: str | None = None,
) -> FileDownloadResult:
"""
- 下载已登记文件service
+ 下载已登记文件service。
:param request: Request对象
:param query_db: orm对象
@@ -208,6 +209,8 @@ async def download_managed_file_services(
:param file_data_scope_sql: 文件数据权限对应的查询sql语句
:param range_header: Range请求头
:return: 文件下载结果
+ :raises ServiceException: 文件不存在或无权访问
+ :raises FileRangeNotSatisfiableException: 事务失败并回滚后重新抛出原异常
"""
file_info = await FileInfoDao.get_file_info_by_id(query_db, file_id, file_data_scope_sql)
user = current_user.user
@@ -315,7 +318,7 @@ async def _has_private_file_download_permission(
current_time: datetime,
) -> bool:
"""
- 校验私有文件下载权限
+ 校验私有文件下载权限。
:param query_db: orm对象
:param current_user: 当前用户对象
@@ -359,7 +362,7 @@ async def _has_private_file_download_permission(
@staticmethod
def _get_current_user_role_ids(user: object) -> set[int]:
"""
- 获取当前用户角色ID集合
+ 获取当前用户角色ID集合。
:param user: 当前用户对象
:return: 角色ID集合
@@ -377,7 +380,7 @@ def _get_current_user_role_ids(user: object) -> set[int]:
@staticmethod
def _get_current_user_dept_ids(user: object) -> tuple[int | None, set[int]]:
"""
- 获取当前用户部门及祖级部门ID
+ 获取当前用户部门及祖级部门ID。
:param user: 当前用户对象
:return: 当前部门ID和祖级部门ID集合
@@ -398,14 +401,16 @@ async def _generate_audited_file(
byte_range: FileByteRange,
) -> AsyncGenerator[bytes, None]:
"""
- 生成带有完成审计的文件流
+ 生成带有完成审计的文件流。
:param request: Request对象
:param current_user: 当前用户对象
:param file_id: 文件ID
:param filepath: 文件路径
:param byte_range: 文件字节范围
- :yield: 文件二进制数据
+ :yield: 逐块产生文件二进制数据并记录下载审计的异步迭代器
+ :raises asyncio.CancelledError: 异步操作被取消时
+ :raises Exception: 底层操作失败时向调用方传播异常
"""
bytes_sent = 0
audit_result: Literal['completed', 'failed'] = 'failed'
@@ -454,7 +459,7 @@ async def _enqueue_file_access_log(
operation_detail: dict[str, object] | None = None,
) -> None:
"""
- 将文件访问审计写入日志队列
+ 将文件访问审计写入日志队列。
:param request: Request对象
:param current_user: 当前用户对象
@@ -464,7 +469,6 @@ async def _enqueue_file_access_log(
:param bytes_sent: 已发送字节数
:param error_message: 失败原因
:param operation_detail: 操作详情
- :return: None
"""
await FileAuditService.enqueue_file_audit(
request,
@@ -480,7 +484,7 @@ async def _enqueue_file_access_log(
@staticmethod
def _build_download_operation_detail(byte_range: FileByteRange) -> dict[str, object] | None:
"""
- 构造分段下载审计详情
+ 构造分段下载审计详情。
:param byte_range: 文件字节范围
:return: 分段下载审计详情
@@ -502,13 +506,14 @@ async def download_services(
range_header: str | None = None,
) -> FileDownloadResult:
"""
- 下载下载目录文件service
+ 下载下载目录文件service。
:param background_tasks: 后台任务对象
:param file_name: 下载的文件名称
:param delete: 是否在下载完成后删除文件
:param range_header: Range请求头
:return: 文件下载结果
+ :raises ServiceException: 文件名称不合法或文件不存在
"""
try:
filepath = FilePathUtil.resolve_file_within_root(UploadConfig.DOWNLOAD_PATH, file_name)
@@ -536,11 +541,12 @@ async def download_resource_services(
range_header: str | None = None,
) -> FileDownloadResult:
"""
- 下载上传目录文件service
+ 下载上传目录文件service。
:param resource: 下载的文件名称
:param range_header: Range请求头
:return: 文件下载结果
+ :raises ServiceException: 资源路径不合法;资源路径不合法或文件不存在;资源文件名称不合法
"""
resource_prefix = f'{UploadConfig.UPLOAD_PREFIX.rstrip("/")}/'
if not resource.startswith(resource_prefix):
diff --git a/ruoyi-fastapi-backend/module_admin/service/config_service.py b/ruoyi-fastapi-backend/module_admin/service/config_service.py
index 583d12c01..45d90e6ce 100644
--- a/ruoyi-fastapi-backend/module_admin/service/config_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/config_service.py
@@ -16,16 +16,14 @@
class ConfigService:
- """
- 参数配置管理模块服务层
- """
+ """参数配置管理模块服务层。"""
@classmethod
async def get_config_list_services(
cls, query_db: AsyncSession, query_object: ConfigPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 获取参数配置列表信息service
+ 获取参数配置列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -39,11 +37,10 @@ async def get_config_list_services(
@classmethod
async def init_cache_sys_config_services(cls, query_db: AsyncSession, redis: aioredis.Redis) -> None:
"""
- 应用初始化:获取所有参数配置对应的键值对信息并缓存service
+ 应用初始化:获取所有参数配置对应的键值对信息并缓存service。
:param query_db: orm对象
:param redis: redis对象
- :return:
"""
# 获取以sys_config:开头的键列表
keys = await redis.keys(f'{RedisInitKeyConfig.SYS_CONFIG.key}:*')
@@ -60,7 +57,7 @@ async def init_cache_sys_config_services(cls, query_db: AsyncSession, redis: aio
@classmethod
async def query_config_list_from_cache_services(cls, redis: aioredis.Redis, config_key: str) -> Any:
"""
- 从缓存获取参数键名对应值service
+ 从缓存获取参数键名对应值service。
:param redis: redis对象
:param config_key: 参数键名
@@ -73,7 +70,7 @@ async def query_config_list_from_cache_services(cls, redis: aioredis.Redis, conf
@classmethod
async def check_config_key_unique_services(cls, query_db: AsyncSession, page_object: ConfigModel) -> bool:
"""
- 校验参数键名是否唯一service
+ 校验参数键名是否唯一service。
:param query_db: orm对象
:param page_object: 参数配置对象
@@ -90,12 +87,14 @@ async def add_config_services(
cls, request: Request, query_db: AsyncSession, page_object: ConfigModel
) -> CrudResponseModel:
"""
- 新增参数配置信息service
+ 新增参数配置信息service。
:param request: Request对象
:param query_db: orm对象
:param page_object: 新增参数配置对象
:return: 新增参数配置校验结果
+ :raises ServiceException: 参数键名已被使用
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
if not await cls.check_config_key_unique_services(query_db, page_object):
raise ServiceException(
@@ -119,12 +118,14 @@ async def edit_config_services(
cls, request: Request, query_db: AsyncSession, page_object: ConfigModel
) -> CrudResponseModel:
"""
- 编辑参数配置信息service
+ 编辑参数配置信息service。
:param request: Request对象
:param query_db: orm对象
:param page_object: 编辑参数配置对象
:return: 编辑参数配置校验结果
+ :raises ServiceException: 参数配置不存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
edit_config = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'update_time'})
config_info = await cls.config_detail_services(query_db, page_object.config_id)
@@ -157,12 +158,14 @@ async def delete_config_services(
cls, request: Request, query_db: AsyncSession, page_object: DeleteConfigModel
) -> CrudResponseModel:
"""
- 删除参数配置信息service
+ 删除参数配置信息service。
:param request: Request对象
:param query_db: orm对象
:param page_object: 删除参数配置对象
:return: 删除参数配置校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入参数配置id为空
"""
if page_object.config_ids:
config_id_list = page_object.config_ids.split(',')
@@ -191,7 +194,7 @@ async def delete_config_services(
@classmethod
async def config_detail_services(cls, query_db: AsyncSession, config_id: int) -> ConfigModel:
"""
- 获取参数配置详细信息service
+ 获取参数配置详细信息service。
:param query_db: orm对象
:param config_id: 参数配置id
@@ -205,7 +208,7 @@ async def config_detail_services(cls, query_db: AsyncSession, config_id: int) ->
@staticmethod
async def export_config_list_services(config_list: list) -> bytes:
"""
- 导出参数配置信息service
+ 导出参数配置信息service。
:param config_list: 参数配置信息列表
:return: 参数配置信息对应excel的二进制数据
@@ -236,7 +239,7 @@ async def export_config_list_services(config_list: list) -> bytes:
@classmethod
async def refresh_sys_config_services(cls, request: Request, query_db: AsyncSession) -> CrudResponseModel:
"""
- 刷新字典缓存信息service
+ 刷新字典缓存信息service。
:param request: Request对象
:param query_db: orm对象
diff --git a/ruoyi-fastapi-backend/module_admin/service/dept_service.py b/ruoyi-fastapi-backend/module_admin/service/dept_service.py
index 00eaa2dfb..b6e0e66e8 100644
--- a/ruoyi-fastapi-backend/module_admin/service/dept_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/dept_service.py
@@ -14,16 +14,14 @@
class DeptService:
- """
- 部门管理模块服务层
- """
+ """部门管理模块服务层。"""
@classmethod
async def get_dept_tree_services(
cls, query_db: AsyncSession, page_object: DeptModel, data_scope_sql: ColumnElement
) -> list[dict[str, Any]]:
"""
- 获取部门树信息service
+ 获取部门树信息service。
:param query_db: orm对象
:param page_object: 查询参数对象
@@ -41,7 +39,7 @@ async def get_dept_for_edit_option_services(
cls, query_db: AsyncSession, page_object: DeptModel, data_scope_sql: ColumnElement
) -> list[dict[str, Any]]:
"""
- 获取部门编辑部门树信息service
+ 获取部门编辑部门树信息service。
:param query_db: orm对象
:param page_object: 查询参数对象
@@ -57,7 +55,7 @@ async def get_dept_list_services(
cls, query_db: AsyncSession, page_object: DeptModel, data_scope_sql: ColumnElement
) -> list[dict[str, Any]]:
"""
- 获取部门列表信息service
+ 获取部门列表信息service。
:param query_db: orm对象
:param page_object: 分页查询参数对象
@@ -73,12 +71,13 @@ async def check_dept_data_scope_services(
cls, query_db: AsyncSession, dept_id: int, data_scope_sql: ColumnElement
) -> CrudResponseModel:
"""
- 校验部门是否有数据权限service
+ 校验部门是否有数据权限service。
:param query_db: orm对象
:param dept_id: 部门id
:param data_scope_sql: 数据权限对应的查询sql语句
:return: 校验结果
+ :raises ServiceException: 没有权限访问部门数据
"""
depts = await DeptDao.get_dept_list(query_db, DeptModel(deptId=dept_id), data_scope_sql)
if depts:
@@ -88,7 +87,7 @@ async def check_dept_data_scope_services(
@classmethod
async def check_dept_name_unique_services(cls, query_db: AsyncSession, page_object: DeptModel) -> bool:
"""
- 校验部门名称是否唯一service
+ 校验部门名称是否唯一service。
:param query_db: orm对象
:param page_object: 部门对象
@@ -105,11 +104,13 @@ async def check_dept_name_unique_services(cls, query_db: AsyncSession, page_obje
@classmethod
async def add_dept_services(cls, query_db: AsyncSession, page_object: DeptModel) -> CrudResponseModel:
"""
- 新增部门信息service
+ 新增部门信息service。
:param query_db: orm对象
:param page_object: 新增部门对象
:return: 新增部门校验结果
+ :raises ServiceException: 上级部门不存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
if not await cls.check_dept_name_unique_services(query_db, page_object):
raise ServiceException(
@@ -138,11 +139,13 @@ async def add_dept_services(cls, query_db: AsyncSession, page_object: DeptModel)
@classmethod
async def edit_dept_services(cls, query_db: AsyncSession, page_object: DeptModel) -> CrudResponseModel:
"""
- 编辑部门信息service
+ 编辑部门信息service。
:param query_db: orm对象
:param page_object: 编辑部门对象
:return: 编辑部门校验结果
+ :raises ServiceException: 部门不存在;上级部门不存在;上级部门不能是当前部门的子部门
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
old_dept = await DeptDao.get_dept_detail_by_id(query_db, page_object.dept_id)
if not old_dept:
@@ -206,12 +209,13 @@ async def update_dept_sort_services(
data_scope_sql: ColumnElement | None = None,
) -> CrudResponseModel:
"""
- 批量保存部门显示顺序
+ 批量保存部门显示顺序。
:param query_db: orm对象
:param page_object: 部门排序参数
:param data_scope_sql: 数据权限对应的查询sql语句
:return: 保存结果
+ :raises ServiceException: 事务失败并回滚后重新抛出原异常;保存排序异常,请联系管理员
"""
dept_sort_list = cls.parse_dept_sort_items(page_object)
try:
@@ -231,10 +235,11 @@ async def update_dept_sort_services(
@classmethod
def parse_dept_sort_items(cls, page_object: DeptSortModel) -> list[dict[str, int]]:
"""
- 解析并校验部门排序参数
+ 解析并校验部门排序参数。
:param page_object: 部门排序参数
:return: 部门id与显示顺序列表
+ :raises ServiceException: 部门排序参数不正确
"""
dept_id_values = [value.strip() for value in page_object.dept_ids.split(',') if value.strip()]
order_num_values = [value.strip() for value in page_object.order_nums.split(',') if value.strip()]
@@ -258,11 +263,13 @@ def parse_dept_sort_items(cls, page_object: DeptSortModel) -> list[dict[str, int
@classmethod
async def delete_dept_services(cls, query_db: AsyncSession, page_object: DeleteDeptModel) -> CrudResponseModel:
"""
- 删除部门信息service
+ 删除部门信息service。
:param query_db: orm对象
:param page_object: 删除部门对象
:return: 删除部门校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入部门id为空
"""
if page_object.dept_ids:
dept_id_list = page_object.dept_ids.split(',')
@@ -285,7 +292,7 @@ async def delete_dept_services(cls, query_db: AsyncSession, page_object: DeleteD
@classmethod
async def dept_detail_services(cls, query_db: AsyncSession, dept_id: int) -> DeptModel:
"""
- 获取部门详细信息service
+ 获取部门详细信息service。
:param query_db: orm对象
:param dept_id: 部门id
@@ -299,7 +306,7 @@ async def dept_detail_services(cls, query_db: AsyncSession, dept_id: int) -> Dep
@classmethod
def list_to_tree(cls, permission_list: Sequence[SysDept]) -> list[DeptTreeModel]:
"""
- 工具方法:根据部门列表信息生成树形嵌套数据
+ 工具方法:根据部门列表信息生成树形嵌套数据。
:param permission_list: 部门列表信息
:return: 部门树形嵌套数据
@@ -330,7 +337,7 @@ def list_to_tree(cls, permission_list: Sequence[SysDept]) -> list[DeptTreeModel]
@classmethod
async def replace_first(cls, original_str: str, old_str: str, new_str: str) -> str:
"""
- 工具方法:替换字符串
+ 工具方法:替换字符串。
:param original_str: 需要替换的原始字符串
:param old_str: 用于匹配的字符串
@@ -344,11 +351,10 @@ async def replace_first(cls, original_str: str, old_str: str, new_str: str) -> s
@classmethod
async def update_parent_dept_status_normal(cls, query_db: AsyncSession, dept: DeptModel) -> None:
"""
- 更新父部门状态为正常
+ 更新父部门状态为正常。
:param query_db: orm对象
:param dept: 部门对象
- :return:
"""
dept_id_list = dept.ancestors.split(',')
await DeptDao.update_dept_status_normal_dao(query_db, list(map(int, dept_id_list)))
@@ -358,13 +364,12 @@ async def update_dept_children(
cls, query_db: AsyncSession, dept_id: int, new_ancestors: str, old_ancestors: str
) -> None:
"""
- 更新子部门信息
+ 更新子部门信息。
:param query_db: orm对象
:param dept_id: 部门id
:param new_ancestors: 新的祖先
:param old_ancestors: 旧的祖先
- :return:
"""
children = await DeptDao.get_children_dept_dao(query_db, dept_id)
update_children = []
diff --git a/ruoyi-fastapi-backend/module_admin/service/dict_service.py b/ruoyi-fastapi-backend/module_admin/service/dict_service.py
index fabbb5c8e..609b953f5 100644
--- a/ruoyi-fastapi-backend/module_admin/service/dict_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/dict_service.py
@@ -28,16 +28,14 @@
class DictTypeService:
- """
- 字典类型管理模块服务层
- """
+ """字典类型管理模块服务层。"""
@classmethod
async def get_dict_type_list_services(
cls, query_db: AsyncSession, query_object: DictTypePageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 获取字典类型列表信息service
+ 获取字典类型列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -55,7 +53,7 @@ async def get_dict_type_list_services(
@classmethod
async def check_dict_type_unique_services(cls, query_db: AsyncSession, page_object: DictTypeModel) -> bool:
"""
- 校验字典类型称是否唯一service
+ 校验字典类型称是否唯一service。
:param query_db: orm对象
:param page_object: 字典类型对象
@@ -74,12 +72,14 @@ async def add_dict_type_services(
cls, request: Request, query_db: AsyncSession, page_object: DictTypeModel
) -> CrudResponseModel:
"""
- 新增字典类型信息service
+ 新增字典类型信息service。
:param request: Request对象
:param query_db: orm对象
:param page_object: 新增岗位对象
:return: 新增字典类型校验结果
+ :raises ServiceException: 字典类型已存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
if not await cls.check_dict_type_unique_services(query_db, page_object):
raise ServiceException(
@@ -103,12 +103,14 @@ async def edit_dict_type_services(
cls, request: Request, query_db: AsyncSession, page_object: DictTypeModel
) -> CrudResponseModel:
"""
- 编辑字典类型信息service
+ 编辑字典类型信息service。
:param request: Request对象
:param query_db: orm对象
:param page_object: 编辑字典类型对象
:return: 编辑字典类型校验结果
+ :raises ServiceException: 字典类型不存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
edit_dict_type = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'update_time'})
dict_type_info = await cls.dict_type_detail_services(query_db, page_object.dict_id)
@@ -148,12 +150,14 @@ async def delete_dict_type_services(
cls, request: Request, query_db: AsyncSession, page_object: DeleteDictTypeModel
) -> CrudResponseModel:
"""
- 删除字典类型信息service
+ 删除字典类型信息service。
:param request: Request对象
:param query_db: orm对象
:param page_object: 删除字典类型对象
:return: 删除字典类型校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入字典类型id为空
"""
if page_object.dict_ids:
dict_id_list = page_object.dict_ids.split(',')
@@ -181,7 +185,7 @@ async def delete_dict_type_services(
@classmethod
async def dict_type_detail_services(cls, query_db: AsyncSession, dict_id: int) -> DictTypeModel:
"""
- 获取字典类型详细信息service
+ 获取字典类型详细信息service。
:param query_db: orm对象
:param dict_id: 字典类型id
@@ -195,7 +199,7 @@ async def dict_type_detail_services(cls, query_db: AsyncSession, dict_id: int) -
@staticmethod
async def export_dict_type_list_services(dict_type_list: list) -> bytes:
"""
- 导出字典类型信息service
+ 导出字典类型信息service。
:param dict_type_list: 字典信息列表
:return: 字典信息对应excel的二进制数据
@@ -226,7 +230,7 @@ async def export_dict_type_list_services(dict_type_list: list) -> bytes:
@classmethod
async def refresh_sys_dict_services(cls, request: Request, query_db: AsyncSession) -> CrudResponseModel:
"""
- 刷新字典缓存信息service
+ 刷新字典缓存信息service。
:param request: Request对象
:param query_db: orm对象
@@ -239,16 +243,14 @@ async def refresh_sys_dict_services(cls, request: Request, query_db: AsyncSessio
class DictDataService:
- """
- 字典数据管理模块服务层
- """
+ """字典数据管理模块服务层。"""
@classmethod
async def get_dict_data_list_services(
cls, query_db: AsyncSession, query_object: DictDataPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 获取字典数据列表信息service
+ 获取字典数据列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -268,7 +270,7 @@ async def query_dict_data_list_services(
cls, query_db: AsyncSession, dict_type: str
) -> Sequence[SysDictData | None]:
"""
- 获取字典数据列表信息service
+ 获取字典数据列表信息service。
:param query_db: orm对象
:param dict_type: 字典类型
@@ -281,11 +283,10 @@ async def query_dict_data_list_services(
@classmethod
async def init_cache_sys_dict_services(cls, query_db: AsyncSession, redis: aioredis.Redis) -> None:
"""
- 应用初始化:获取所有字典类型对应的字典数据信息并缓存service
+ 应用初始化:获取所有字典类型对应的字典数据信息并缓存service。
:param query_db: orm对象
:param redis: redis对象
- :return:
"""
prefix = f'{RedisInitKeyConfig.SYS_DICT.key}:'
keys = await redis.keys(f'{prefix}*')
@@ -297,15 +298,21 @@ async def init_cache_sys_dict_services(cls, query_db: AsyncSession, redis: aiore
@staticmethod
async def publish_dict_cache(query_db: AsyncSession, redis: aioredis.Redis, *dict_types: str) -> None:
"""
- 将指定字典类型的最新数据写入缓存
+ 将指定字典类型的最新数据写入缓存。
:param query_db: orm对象
:param redis: redis对象
:param dict_types: 待刷新缓存的字典类型
- :return:
"""
async def publish_snapshot(pipe: aioredis.client.Pipeline, *, dict_type: str, cache_key: str) -> None:
+ """
+ 发布提交后的字典缓存快照。
+
+ :param pipe: 用于批量提交 Redis 操作的管道
+ :param dict_type: 字典类型
+ :param cache_key: 缓存键名
+ """
# WATCH 冲突后 Redis 会再次调用此函数,每次都要打开新会话读取最新已提交的数据。
async with AsyncSession(bind=query_db.bind) as snapshot_db:
rows = await DictDataDao.query_dict_data_list(snapshot_db, dict_type)
@@ -327,7 +334,7 @@ async def query_dict_data_list_from_cache_services(
cls, redis: aioredis.Redis, dict_type: str
) -> list[dict[str, Any]]:
"""
- 从缓存获取字典数据列表信息service
+ 从缓存获取字典数据列表信息service。
:param redis: redis对象
:param dict_type: 字典类型
@@ -339,7 +346,7 @@ async def query_dict_data_list_from_cache_services(
@classmethod
async def check_dict_data_unique_services(cls, query_db: AsyncSession, page_object: DictDataModel) -> bool:
"""
- 校验字典数据是否唯一service
+ 校验字典数据是否唯一service。
:param query_db: orm对象
:param page_object: 字典数据对象
@@ -356,12 +363,14 @@ async def add_dict_data_services(
cls, request: Request, query_db: AsyncSession, page_object: DictDataModel
) -> CrudResponseModel:
"""
- 新增字典数据信息service
+ 新增字典数据信息service。
:param request: Request对象
:param query_db: orm对象
:param page_object: 新增岗位对象
:return: 新增字典数据校验结果
+ :raises ServiceException: 同一字典类型下已存在对应数据
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
if not await cls.check_dict_data_unique_services(query_db, page_object):
raise ServiceException(
@@ -383,12 +392,14 @@ async def edit_dict_data_services(
cls, request: Request, query_db: AsyncSession, page_object: DictDataModel
) -> CrudResponseModel:
"""
- 编辑字典数据信息service
+ 编辑字典数据信息service。
:param request: Request对象
:param query_db: orm对象
:param page_object: 编辑字典数据对象
:return: 编辑字典数据校验结果
+ :raises ServiceException: 字典数据不存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
edit_data_type = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'update_time'})
dict_data_info = await cls.dict_data_detail_services(query_db, page_object.dict_code)
@@ -417,12 +428,14 @@ async def delete_dict_data_services(
cls, request: Request, query_db: AsyncSession, page_object: DeleteDictDataModel
) -> CrudResponseModel:
"""
- 删除字典数据信息service
+ 删除字典数据信息service。
:param request: Request对象
:param query_db: orm对象
:param page_object: 删除字典数据对象
:return: 删除字典数据校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入字典数据id为空
"""
if page_object.dict_codes:
dict_code_list = page_object.dict_codes.split(',')
@@ -444,7 +457,7 @@ async def delete_dict_data_services(
@classmethod
async def dict_data_detail_services(cls, query_db: AsyncSession, dict_code: int) -> DictDataModel:
"""
- 获取字典数据详细信息service
+ 获取字典数据详细信息service。
:param query_db: orm对象
:param dict_code: 字典数据id
@@ -458,7 +471,7 @@ async def dict_data_detail_services(cls, query_db: AsyncSession, dict_code: int)
@staticmethod
async def export_dict_data_list_services(dict_data_list: list) -> bytes:
"""
- 导出字典数据信息service
+ 导出字典数据信息service。
:param dict_data_list: 字典数据信息列表
:return: 字典数据信息对应excel的二进制数据
diff --git a/ruoyi-fastapi-backend/module_admin/service/file_access_service.py b/ruoyi-fastapi-backend/module_admin/service/file_access_service.py
index fb610e5af..1608a9ee1 100644
--- a/ruoyi-fastapi-backend/module_admin/service/file_access_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/file_access_service.py
@@ -31,6 +31,8 @@
class FileAclService:
+ """管理文件访问控制项并校验文件访问权限。"""
+
@classmethod
async def get_file_acl_list_services(
cls,
@@ -41,7 +43,7 @@ async def get_file_acl_list_services(
dept_data_scope_sql: ColumnElement,
) -> FileAclListModel:
"""
- 获取文件访问控制列表service
+ 获取文件访问控制列表service。
:param query_db: orm对象
:param file_id: 文件ID
@@ -49,6 +51,7 @@ async def get_file_acl_list_services(
:param user_data_scope_sql: 用户数据权限对应的查询sql语句
:param dept_data_scope_sql: 部门数据权限对应的查询sql语句
:return: 文件访问控制列表及版本
+ :raises ServiceException: 文件信息不存在或超出数据权限
"""
file_info = await FileInfoDao.get_file_info_detail_by_id(query_db, file_id, file_data_scope_sql)
if file_info is None:
@@ -95,7 +98,7 @@ def _build_builtin_permissions(
subject_name_map: dict[tuple[str, int], str],
) -> list[FileAclBuiltinPermissionModel]:
"""
- 构建文件内置访问权限
+ 构建文件内置访问权限。
:param file_info: 文件信息
:param subject_name_map: 主体名称映射
@@ -169,7 +172,7 @@ async def search_file_acl_subjects_services(
dept_data_scope_sql: ColumnElement,
) -> list[FileAclSubjectOptionModel]:
"""
- 查询文件访问控制主体选项service
+ 查询文件访问控制主体选项service。
:param query_db: orm对象
:param subject_type: 主体类型
@@ -196,7 +199,7 @@ async def get_file_acl_dept_tree_services(
dept_data_scope_sql: ColumnElement,
) -> list[DeptTreeModel]:
"""
- 获取文件授权部门树service
+ 获取文件授权部门树service。
:param query_db: orm对象
:param dept_data_scope_sql: 部门数据权限对应的查询sql语句
@@ -218,7 +221,7 @@ async def save_file_acl_services(
request: Request | None = None,
) -> CrudResponseModel:
"""
- 保存文件访问控制service
+ 保存文件访问控制service。
:param query_db: orm对象
:param current_user: 当前用户对象
@@ -229,6 +232,8 @@ async def save_file_acl_services(
:param dept_data_scope_sql: 部门数据权限对应的查询sql语句
:param request: Request对象
:return: 保存结果
+ :raises ServiceException: 文件信息不存在、已删除或超出数据权限;公开文件不支持配置访问权限;无法获取当前用户信息;文件权限已被其他用户修改,请刷新后重试;同一授权主体不能重复配置;授权过期时间必须晚于当前时间;部分授权主体不存在、已停用或超出数据权限
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
file_info = await FileInfoDao.get_file_info_by_id_for_update(query_db, file_id, file_data_scope_sql)
if file_info is None:
@@ -340,7 +345,7 @@ async def batch_save_file_acl_services(
request: Request | None = None,
) -> CrudResponseModel:
"""
- 批量保存文件访问控制service
+ 批量保存文件访问控制service。
:param query_db: orm对象
:param current_user: 当前用户对象
@@ -350,6 +355,8 @@ async def batch_save_file_acl_services(
:param dept_data_scope_sql: 部门数据权限对应的查询sql语句
:param request: Request对象
:return: 保存结果
+ :raises ServiceException: 无法获取当前用户信息;部分文件不存在、已删除或超出数据权限;批量授权仅支持受保护文件;同一授权主体不能重复配置;授权过期时间必须晚于当前时间;部分授权主体不存在、已停用或超出数据权限
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
file_ids = FileUtil.parse_file_ids(batch_save_file_acl.file_ids)
user = current_user.user
@@ -454,7 +461,7 @@ async def batch_save_file_acl_services(
@staticmethod
def _group_acl_subject_ids(file_acl_list: list[SysFileAcl]) -> dict[str, set[int]]:
"""
- 按类型分组文件访问控制主体ID
+ 按类型分组文件访问控制主体ID。
:param file_acl_list: 文件访问控制列表
:return: 主体ID分组
@@ -467,9 +474,7 @@ def _group_acl_subject_ids(file_acl_list: list[SysFileAcl]) -> dict[str, set[int
class FileAuditService:
- """
- 文件审计服务层
- """
+ """文件审计服务层。"""
@classmethod
async def enqueue_file_audit(
@@ -495,7 +500,7 @@ async def enqueue_file_audit(
operation_detail: dict[str, Any] | None = None,
) -> None:
"""
- 将文件审计事件写入日志队列
+ 将文件审计事件写入日志队列。
:param request: Request对象
:param current_user: 当前用户对象
@@ -505,7 +510,6 @@ async def enqueue_file_audit(
:param bytes_sent: 已发送字节数
:param error_message: 失败原因
:param operation_detail: 操作详情
- :return: None
"""
if request is None:
return
@@ -545,7 +549,7 @@ async def add_system_file_audit(
operation_detail: dict[str, Any] | None = None,
) -> None:
"""
- 在后台任务事务内写入文件审计记录
+ 在后台任务事务内写入文件审计记录。
:param query_db: orm对象
:param file_id: 文件ID
@@ -553,7 +557,6 @@ async def add_system_file_audit(
:param result: 操作结果
:param error_message: 失败原因
:param operation_detail: 操作详情
- :return: None
"""
file_access_log = FileAccessLogModel(
fileId=file_id,
@@ -569,7 +572,7 @@ async def add_system_file_audit(
@staticmethod
def _serialize_operation_detail(operation_detail: dict[str, Any] | None) -> str:
"""
- 序列化文件操作详情
+ 序列化文件操作详情。
:param operation_detail: 操作详情
:return: 序列化后的操作详情
diff --git a/ruoyi-fastapi-backend/module_admin/service/file_business_service.py b/ruoyi-fastapi-backend/module_admin/service/file_business_service.py
index c524f9e54..0c01b24bb 100644
--- a/ruoyi-fastapi-backend/module_admin/service/file_business_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/file_business_service.py
@@ -31,7 +31,9 @@
class FileReferenceService:
"""
- 文件业务引用服务层
+ 文件业务引用服务层。
+
+ :cvar MAX_REFERENCE_FILES: 一次操作可关联的最大文件数
"""
MAX_REFERENCE_FILES = 100
@@ -44,12 +46,13 @@ async def get_file_reference_list_services(
file_data_scope_sql: ColumnElement,
) -> list[FileReferenceModel]:
"""
- 获取文件业务引用列表service
+ 获取文件业务引用列表service。
:param query_db: orm对象
:param file_id: 文件ID
:param file_data_scope_sql: 文件数据权限对应的查询sql语句
:return: 文件业务引用列表
+ :raises ServiceException: 文件信息不存在或超出数据权限
"""
file_info = await FileInfoDao.get_file_management_detail_by_id(query_db, file_id, file_data_scope_sql)
if file_info is None:
@@ -83,7 +86,7 @@ async def replace_business_file_references_services(
business_name: str | None = None,
) -> None:
"""
- 在调用方业务事务内全量替换文件引用service
+ 在调用方业务事务内全量替换文件引用service。
:param query_db: orm对象
:param business_type: 业务类型
@@ -92,7 +95,7 @@ async def replace_business_file_references_services(
:param create_by: 创建者
:param file_data_scope_sql: 文件数据权限对应的查询sql语句
:param business_name: 业务名称
- :return: None
+ :raises ServiceException: 部分引用文件不存在或已失效;配置保留策略的业务只能引用受保护文件
"""
normalized_business_type = cls._normalize_text(business_type, '业务类型', 50, required=True)
normalized_business_id = cls._normalize_text(business_id, '业务ID', 64, required=True)
@@ -151,12 +154,11 @@ async def remove_business_file_references_services(
business_id: str,
) -> None:
"""
- 在调用方业务事务内解除业务对象的全部文件引用service
+ 在调用方业务事务内解除业务对象的全部文件引用service。
:param query_db: orm对象
:param business_type: 业务类型
:param business_id: 业务ID
- :return: None
"""
await cls.replace_business_file_references_services(
query_db,
@@ -174,7 +176,7 @@ async def get_file_reference_count_map_services(
file_infos: list[SysFileInfo] | list[dict],
) -> dict[str, int]:
"""
- 获取包含兼容字段的文件业务引用数量映射service
+ 获取包含兼容字段的文件业务引用数量映射service。
:param query_db: orm对象
:param file_infos: 文件信息列表
@@ -192,7 +194,13 @@ async def get_file_reference_count_map_services(
@classmethod
def _normalize_file_ids(cls, file_ids: list[str]) -> list[str]:
- """校验并标准化文件ID列表。"""
+ """
+ 校验并标准化文件ID列表。
+
+ :param file_ids: 文件ID列表
+ :raises ServiceException: 文件ID格式错误
+ :return: 按输入顺序去重后的有效文件标识
+ """
if len(file_ids) > cls.MAX_REFERENCE_FILES:
raise ServiceException(
message=f'单个业务对象最多引用{cls.MAX_REFERENCE_FILES}个文件',
@@ -207,7 +215,16 @@ def _normalize_file_ids(cls, file_ids: list[str]) -> list[str]:
@staticmethod
def _normalize_text(value: str | None, field_name: str, max_length: int, required: bool = False) -> str | None:
- """校验并标准化业务引用文本字段。"""
+ """
+ 校验并标准化业务引用文本字段。
+
+ :param value: 待处理的输入值
+ :param field_name: 需要读取或校验的字段名
+ :param max_length: 字段允许的最大长度
+ :param required: 是否必须提供该字段
+ :raises ServiceException: 必填文本为空或文本格式不符合要求
+ :return: 供调用方使用的 ``normalized_value``
+ """
normalized_value = value.strip() if value else None
if required and not normalized_value:
raise ServiceException(
@@ -225,16 +242,21 @@ def _normalize_text(value: str | None, field_name: str, max_length: int, require
@staticmethod
def _get_value(item: SysFileInfo | dict, snake_name: str, camel_name: str) -> Any:
- """兼容读取ORM对象和查询字典。"""
+ """
+ 兼容读取ORM对象和查询字典。
+
+ :param item: 当前要处理的条目
+ :param snake_name: 字段的下划线形式
+ :param camel_name: 字段的驼峰形式
+ :return: 从记录读取的字段值
+ """
if isinstance(item, dict):
return item.get(snake_name) if snake_name in item else item.get(camel_name)
return getattr(item, snake_name)
class FileRetentionPolicyService:
- """
- 文件业务保留策略服务层
- """
+ """文件业务保留策略服务层。"""
@classmethod
async def get_file_retention_policy_list_services(
@@ -242,7 +264,7 @@ async def get_file_retention_policy_list_services(
query_db: AsyncSession,
) -> list[FileRetentionPolicyModel]:
"""
- 获取文件业务保留策略列表service
+ 获取文件业务保留策略列表service。
:param query_db: orm对象
:return: 文件业务保留策略列表
@@ -257,7 +279,7 @@ async def get_enabled_file_retention_policy_services(
business_type: str,
) -> FileRetentionPolicyModel | None:
"""
- 获取已启用的文件业务保留策略service
+ 获取已启用的文件业务保留策略service。
:param query_db: orm对象
:param business_type: 业务类型
@@ -278,12 +300,14 @@ async def add_file_retention_policy_services(
operator_name: str,
) -> CrudResponseModel:
"""
- 新增文件业务保留策略service
+ 新增文件业务保留策略service。
:param query_db: orm对象
:param policy: 文件业务保留策略
:param operator_name: 操作人名称
:return: 操作结果
+ :raises ServiceException: 该业务类型已有保留策略
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
cls._validate_business_type(policy.business_type)
exists_policy = await FileRetentionPolicyDao.get_file_retention_policy_by_business_type(
@@ -324,12 +348,14 @@ async def edit_file_retention_policy_services(
operator_name: str,
) -> CrudResponseModel:
"""
- 修改文件业务保留策略service
+ 修改文件业务保留策略service。
:param query_db: orm对象
:param policy: 文件业务保留策略
:param operator_name: 操作人名称
:return: 操作结果
+ :raises ServiceException: 文件业务保留策略不存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
cls._validate_business_type(policy.business_type)
exists_policy = await FileRetentionPolicyDao.get_file_retention_policy_by_business_type(
@@ -367,11 +393,13 @@ async def delete_file_retention_policy_services(
business_type: str,
) -> CrudResponseModel:
"""
- 删除文件业务保留策略service
+ 删除文件业务保留策略service。
:param query_db: orm对象
:param business_type: 业务类型
:return: 操作结果
+ :raises ServiceException: 文件业务保留策略不存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
normalized_business_type = business_type.strip()
cls._validate_business_type(normalized_business_type)
@@ -391,14 +419,23 @@ async def delete_file_retention_policy_services(
@staticmethod
def _validate_business_type(business_type: str) -> None:
- """校验业务类型。"""
+ """
+ 校验业务类型。
+
+ :param business_type: 业务类型
+ :raises ServiceException: 业务类型格式错误
+ """
if not business_type.isprintable():
raise ServiceException(message='业务类型格式错误', msg_key='file.business.invalidType')
class FileRetentionNoticeService:
"""
- 文件保留期限提醒服务层
+ 文件保留期限提醒服务层。
+
+ :cvar DEFAULT_REMIND_DAYS: 到期前默认提前提醒的天数
+ :cvar MAX_REMIND_DAYS: 允许提前提醒的最大天数
+ :cvar MAX_BATCH_SIZE: 单批处理的最大记录数
"""
DEFAULT_REMIND_DAYS = 7
@@ -414,13 +451,14 @@ async def scan_file_retention_notices_services(
file_data_scope_sql: ColumnElement | None = None,
) -> FileRetentionScanModel:
"""
- 扫描并生成文件保留期限提醒service
+ 扫描并生成文件保留期限提醒service。
:param query_db: orm对象
:param remind_days: 提前提醒天数
:param batch_size: 单类提醒单批处理数量
:param file_data_scope_sql: 文件数据权限对应的查询sql语句
:return: 扫描结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
cls._validate_scan_parameters(remind_days, batch_size)
current_time = TimezoneUtil.utc_now()
@@ -480,7 +518,7 @@ async def get_file_retention_notice_list_services(
is_page: bool = True,
) -> PageModel | list[dict]:
"""
- 获取文件保留期限提醒列表service
+ 获取文件保留期限提醒列表service。
:param query_db: orm对象
:param query_object: 查询参数
@@ -504,13 +542,15 @@ async def mark_file_retention_notices_read_services(
file_data_scope_sql: ColumnElement,
) -> CrudResponseModel:
"""
- 标记文件保留期限提醒为已读service
+ 标记文件保留期限提醒为已读service。
:param query_db: orm对象
:param notice_ids: 提醒ID字符串
:param read_by: 读取者
:param file_data_scope_sql: 文件数据权限对应的查询sql语句
:return: 操作结果
+ :raises ServiceException: 部分提醒不存在、已失效或超出数据权限
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
parsed_notice_ids = cls._parse_notice_ids(notice_ids)
scoped_notice_ids = await FileRetentionNoticeDao.get_notice_ids_in_data_scope_for_update(
@@ -538,7 +578,13 @@ async def mark_file_retention_notices_read_services(
@classmethod
def _validate_scan_parameters(cls, remind_days: int, batch_size: int) -> None:
- """校验提醒扫描参数。"""
+ """
+ 校验提醒扫描参数。
+
+ :param remind_days: 提前提醒天数
+ :param batch_size: 单类提醒单批处理数量
+ :raises ServiceException: 提前提醒天数或批次大小超出允许范围
+ """
if remind_days < 1 or remind_days > cls.MAX_REMIND_DAYS:
raise ServiceException(
message=f'提前提醒天数必须在1到{cls.MAX_REMIND_DAYS}之间',
@@ -554,7 +600,13 @@ def _validate_scan_parameters(cls, remind_days: int, batch_size: int) -> None:
@staticmethod
def _parse_notice_ids(notice_ids: str) -> list[int]:
- """解析并校验提醒ID。"""
+ """
+ 解析并校验提醒ID。
+
+ :param notice_ids: 提醒ID字符串
+ :raises ServiceException: 提醒ID格式不正确
+ :return: 供调用方使用的 ``parsed_notice_ids``
+ """
try:
parsed_notice_ids = list(dict.fromkeys(int(item.strip()) for item in notice_ids.split(',') if item.strip()))
except (AttributeError, ValueError) as exc:
diff --git a/ruoyi-fastapi-backend/module_admin/service/file_service.py b/ruoyi-fastapi-backend/module_admin/service/file_service.py
index 37f8b24af..67e850d7b 100644
--- a/ruoyi-fastapi-backend/module_admin/service/file_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/file_service.py
@@ -47,7 +47,13 @@
@dataclass(frozen=True)
class FileAuditSnapshot:
- """文件审计快照。"""
+ """
+ 文件审计快照。
+
+ :ivar file_id: 文件ID
+ :ivar original_name: 原始文件名
+ :ivar access_type: 文件访问类型
+ """
file_id: str
original_name: str
@@ -55,9 +61,7 @@ class FileAuditSnapshot:
class FileRetentionDispositionService:
- """
- 文件到期处置服务层
- """
+ """文件到期处置服务层。"""
@classmethod
async def extend_file_retention_services(
@@ -70,7 +74,7 @@ async def extend_file_retention_services(
request: Request | None = None,
) -> CrudResponseModel:
"""
- 延长文件保留期限service
+ 延长文件保留期限service。
:param query_db: orm对象
:param current_user: 当前用户对象
@@ -79,6 +83,8 @@ async def extend_file_retention_services(
:param file_data_scope_sql: 文件数据权限对应的查询sql语句
:param request: Request对象
:return: 延期结果
+ :raises ServiceException: 无法获取当前用户信息;提醒不存在、已失效或超出数据权限;文件未配置保留期限;新的到期时间必须晚于当前时间和原到期时间;文件不存在可延期的限时业务引用,请先重新关联业务;文件存在永久业务引用,不能通过到期提醒延期;文件到期时间与业务引用不一致,请先检查业务引用
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
user = current_user.user
if user is None or not user.user_name:
@@ -214,7 +220,7 @@ async def dispose_expired_file_services(
request: Request | None = None,
) -> CrudResponseModel:
"""
- 将到期文件移入回收站service
+ 将到期文件移入回收站service。
:param query_db: orm对象
:param current_user: 当前用户对象
@@ -223,6 +229,8 @@ async def dispose_expired_file_services(
:param file_data_scope_sql: 文件数据权限对应的查询sql语句
:param request: Request对象
:return: 处置结果
+ :raises ServiceException: 无法获取当前用户信息;提醒不存在、已失效或超出数据权限;文件尚未到期,不能执行到期处置;文件存在永久或尚未到期的业务引用,不能执行到期处置;到期文件移入回收区失败
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
user = current_user.user
if user is None or not user.user_name:
@@ -358,7 +366,20 @@ async def _enqueue_retention_audit(
reference_count: int | None = None,
error_message: str = '',
) -> None:
- """写入文件到期处置审计。"""
+ """
+ 写入文件到期处置审计。
+
+ :param request: 当前 HTTP 请求
+ :param current_user: 当前登录用户及其权限信息
+ :param file_snapshot: 用于比较文件状态的快照
+ :param action: 当前要记录或执行的动作
+ :param result: 执行当前操作得到的结果
+ :param reason: 作出该决定或状态变化的原因
+ :param previous_expire_time: 修改前的到期时间
+ :param new_expire_time: 更新后的到期时间
+ :param reference_count: 文件被引用的次数
+ :param error_message: 记录到结果或审计日志中的错误详情
+ """
operation_detail = {
'originalName': file_snapshot.original_name,
'accessType': file_snapshot.access_type,
@@ -381,7 +402,12 @@ async def _enqueue_retention_audit(
@staticmethod
def _build_reference_snapshots(reference_list: list[SysFileReference]) -> list[dict[str, Any]]:
- """构建释放业务引用的审计快照。"""
+ """
+ 构建释放业务引用的审计快照。
+
+ :param reference_list: 引用该文件的业务记录
+ :return: 释放业务引用的审计快照
+ """
return [
{
'referenceId': reference.reference_id,
@@ -395,6 +421,13 @@ def _build_reference_snapshots(reference_list: list[SysFileReference]) -> list[d
class FileLifecycleService:
+ """
+ 管理文件删除、回收和恢复。
+
+ :cvar MAX_PURGE_RETENTION_DAYS: 清理策略允许配置的最长保留天数
+ :cvar MAX_PURGE_BATCH_SIZE: 一批允许清理的最大文件数
+ """
+
MAX_PURGE_RETENTION_DAYS = 36500
MAX_PURGE_BATCH_SIZE = 1000
@@ -408,7 +441,7 @@ async def delete_file_services(
request: Request | None = None,
) -> CrudResponseModel:
"""
- 删除文件service
+ 删除文件service。
:param query_db: orm对象
:param current_user: 当前用户对象
@@ -416,6 +449,8 @@ async def delete_file_services(
:param file_data_scope_sql: 文件数据权限对应的查询sql语句
:param request: Request对象
:return: 删除结果
+ :raises ServiceException: 无法获取当前用户信息;部分文件不存在、已删除或超出数据权限;文件移入回收区失败
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
file_ids = FileUtil.parse_file_ids(delete_file.file_ids)
user = current_user.user
@@ -522,7 +557,7 @@ async def purge_file_services(
request: Request | None = None,
) -> CrudResponseModel:
"""
- 永久清理回收站文件service
+ 永久清理回收站文件service。
:param query_db: orm对象
:param current_user: 当前用户对象
@@ -530,6 +565,8 @@ async def purge_file_services(
:param file_data_scope_sql: 文件数据权限对应的查询sql语句
:param request: Request对象
:return: 永久清理结果
+ :raises ServiceException: 无法获取当前用户信息;部分文件不存在、未进入回收站或超出数据权限;部分文件仍被业务引用,不能永久清理;回收区文件校验失败,未执行永久清理;永久清理物理文件失败,文件已保留为清理中状态,可重试
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
parsed_file_ids = FileUtil.parse_file_ids(file_ids)
user = current_user.user
@@ -636,12 +673,16 @@ async def purge_recycle_bin_services(
batch_size: int = 100,
) -> int:
"""
- 按回收站保留天数自动永久清理文件service
+ 按回收站保留天数自动永久清理文件service。
:param query_db: orm对象
:param retention_days: 回收站保留天数
:param batch_size: 单批处理数量
:return: 永久清理文件数量
+ :raises ServiceException: 自动清理候选文件仍存在业务引用
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises OSError: 事务失败并回滚后重新抛出原异常
+ :raises ValueError: 事务失败并回滚后重新抛出原异常
"""
cls._validate_purge_parameters(retention_days, batch_size)
deleted_before = TimezoneUtil.utc_now() - timedelta(days=retention_days)
@@ -719,7 +760,7 @@ async def restore_file_services(
request: Request | None = None,
) -> CrudResponseModel:
"""
- 恢复文件service
+ 恢复文件service。
:param query_db: orm对象
:param current_user: 当前用户对象
@@ -727,6 +768,8 @@ async def restore_file_services(
:param file_data_scope_sql: 文件数据权限对应的查询sql语句
:param request: Request对象
:return: 恢复结果
+ :raises ServiceException: 无法获取当前用户信息;部分文件不存在、未删除或超出数据权限;文件从回收区恢复失败
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
parsed_file_ids = FileUtil.parse_file_ids(file_ids)
user = current_user.user
@@ -838,7 +881,7 @@ async def restore_file_services(
@staticmethod
def _build_file_audit_snapshots(file_infos: list[SysFileInfo]) -> list[FileAuditSnapshot]:
"""
- 在事务结束前固化文件审计字段
+ 在事务结束前固化文件审计字段。
:param file_infos: 文件信息列表
:return: 文件审计快照列表
@@ -861,7 +904,15 @@ async def _enqueue_purge_audits(
result: str,
error_message: str = '',
) -> None:
- """批量写入永久清理审计。"""
+ """
+ 批量写入永久清理审计。
+
+ :param request: 当前 HTTP 请求
+ :param current_user: 当前登录用户及其权限信息
+ :param file_audit_snapshots: 用于生成审计记录的文件快照
+ :param result: 执行当前操作得到的结果
+ :param error_message: 记录到结果或审计日志中的错误详情
+ """
for file_audit_snapshot in file_audit_snapshots:
await FileAuditService.enqueue_file_audit(
request,
@@ -879,7 +930,13 @@ async def _enqueue_purge_audits(
@classmethod
def _validate_purge_parameters(cls, retention_days: int, batch_size: int) -> None:
- """校验自动清理参数。"""
+ """
+ 校验自动清理参数。
+
+ :param retention_days: 回收站保留天数
+ :param batch_size: 单批处理数量
+ :raises ServiceException: 回收站保留天数或清理批次大小超出允许范围
+ """
if retention_days < 1 or retention_days > cls.MAX_PURGE_RETENTION_DAYS:
raise ServiceException(
message=f'回收站保留天数必须在1到{cls.MAX_PURGE_RETENTION_DAYS}之间',
@@ -895,6 +952,8 @@ def _validate_purge_parameters(cls, retention_days: int, batch_size: int) -> Non
class FileQueryService:
+ """查询文件列表、详情及管理统计。"""
+
@classmethod
async def get_file_list_services(
cls,
@@ -904,7 +963,7 @@ async def get_file_list_services(
is_page: bool = True,
) -> PageModel | list[dict[str, Any]]:
"""
- 获取文件信息列表service
+ 获取文件信息列表service。
:param query_db: orm对象
:param query_object: 文件信息查询参数
@@ -927,7 +986,7 @@ async def get_file_stats_services(
file_data_scope_sql: ColumnElement,
) -> FileStatsModel:
"""
- 获取文件管理统计信息service
+ 获取文件管理统计信息service。
:param query_db: orm对象
:param query_object: 文件信息查询参数
@@ -944,12 +1003,13 @@ async def file_detail_services(
file_data_scope_sql: ColumnElement,
) -> FileInfoDisplayModel:
"""
- 获取文件详细信息service
+ 获取文件详细信息service。
:param query_db: orm对象
:param file_id: 文件ID
:param file_data_scope_sql: 文件数据权限对应的查询sql语句
:return: 文件详细信息
+ :raises ServiceException: 文件信息不存在或超出数据权限
"""
file_info = await FileInfoDao.get_file_management_detail_by_id(query_db, file_id, file_data_scope_sql)
if file_info is None:
@@ -969,7 +1029,7 @@ async def get_file_access_log_list_services(
is_page: bool = True,
) -> PageModel | list[dict[str, Any]]:
"""
- 获取文件访问审计列表service
+ 获取文件访问审计列表service。
:param query_db: orm对象
:param file_id: 文件ID
@@ -977,6 +1037,7 @@ async def get_file_access_log_list_services(
:param file_data_scope_sql: 文件数据权限对应的查询sql语句
:param is_page: 是否开启分页
:return: 文件访问审计列表
+ :raises ServiceException: 文件信息不存在或超出数据权限
"""
if await FileInfoDao.get_file_info_detail_by_id(query_db, file_id, file_data_scope_sql) is None:
raise ServiceException(message='文件信息不存在或超出数据权限', msg_key='file.notFoundOrForbidden')
@@ -985,11 +1046,10 @@ async def get_file_access_log_list_services(
@staticmethod
def _enrich_file_reference_counts(file_rows: list[dict[str, Any]], reference_count_map: dict[str, int]) -> None:
"""
- 补充文件业务引用数量
+ 补充文件业务引用数量。
:param file_rows: 文件信息列表
:param reference_count_map: 文件ID和业务引用数量映射
- :return: None
"""
for file_row in file_rows:
file_id = str(file_row.get('file_id') or file_row.get('fileId'))
@@ -997,6 +1057,8 @@ def _enrich_file_reference_counts(file_rows: list[dict[str, Any]], reference_cou
class FileTransferService:
+ """处理文件所有权的转移。"""
+
@classmethod
async def transfer_file_services(
cls,
@@ -1010,7 +1072,7 @@ async def transfer_file_services(
request: Request | None = None,
) -> CrudResponseModel:
"""
- 批量转移文件service
+ 批量转移文件service。
:param query_db: orm对象
:param current_user: 当前用户对象
@@ -1021,6 +1083,8 @@ async def transfer_file_services(
:param dept_data_scope_sql: 部门数据权限对应的查询sql语句
:param request: Request对象
:return: 转移结果
+ :raises ServiceException: 无法获取当前用户信息;目标用户或部门不存在、已停用或超出数据权限;目标用户不属于所选部门;部分文件不存在、已删除或超出数据权限
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
parsed_file_ids = FileUtil.parse_file_ids(file_ids)
user = current_user.user
@@ -1118,7 +1182,11 @@ async def transfer_file_services(
class FileReconcileService:
"""
- 文件存储对账服务
+ 文件存储对账服务。
+
+ :cvar RUN_LOCK_NAME: 对账任务使用的互斥锁名称
+ :cvar RUN_STALE_HOURS: 将未完成任务判为失效前等待的小时数
+ :cvar ISSUE_ACTIONS: 各类对账异常支持的处理操作
"""
RUN_LOCK_NAME = 'storage_reconcile'
@@ -1143,13 +1211,15 @@ async def start_reconcile_run_services(
current_user: CurrentUserModel | None = None,
) -> FileReconcileRunModel:
"""
- 创建文件存储对账任务
+ 创建文件存储对账任务。
:param query_db: orm对象
:param check_hash: 是否校验文件摘要
:param trigger_type: 触发类型
:param current_user: 当前用户对象
:return: 对账任务
+ :raises ServiceException: 对账任务触发类型不正确;已有文件存储对账任务正在运行
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
if trigger_type not in {'manual', 'scheduled'}:
raise ServiceException(message='对账任务触发类型不正确', msg_key='file.reconciliation.invalidTrigger')
@@ -1189,10 +1259,9 @@ async def start_reconcile_run_services(
@classmethod
async def execute_reconcile_run_services(cls, run_id: str) -> None:
"""
- 在独立会话中执行文件存储对账任务
+ 在独立会话中执行文件存储对账任务。
:param run_id: 任务ID
- :return: None
"""
try:
async with DataSourceRegistry.session() as query_db:
@@ -1253,10 +1322,9 @@ async def execute_reconcile_run_services(cls, run_id: str) -> None:
@classmethod
async def run_scheduled_reconcile_services(cls, check_hash: bool = False) -> None:
"""
- 执行定时文件存储对账
+ 执行定时文件存储对账。
:param check_hash: 是否校验文件摘要
- :return: None
"""
async with DataSourceRegistry.session() as query_db:
try:
@@ -1279,7 +1347,13 @@ async def get_reconcile_run_list_services(
is_page: bool = True,
) -> PageModel | list[FileReconcileRunModel]:
"""
- 获取文件存储对账任务列表
+ 获取文件存储对账任务列表。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param current_user: 当前登录用户及其权限信息
+ :param query_object: 文件存储对账任务分页查询模型
+ :param is_page: 是否开启分页
+ :return: 文件存储对账任务列表
"""
cls._require_admin(current_user)
run_list = await FileInfoDao.get_reconcile_run_list(query_db, query_object, is_page)
@@ -1305,7 +1379,13 @@ async def get_reconcile_issue_list_services(
is_page: bool = True,
) -> PageModel | list[FileReconcileIssueModel]:
"""
- 获取文件存储对账异常列表
+ 获取文件存储对账异常列表。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param current_user: 当前登录用户及其权限信息
+ :param query_object: 文件存储对账异常分页查询模型
+ :param is_page: 是否开启分页
+ :return: 文件存储对账异常列表
"""
cls._require_admin(current_user)
issue_list = await FileInfoDao.get_reconcile_issue_list(query_db, query_object, is_page)
@@ -1335,7 +1415,11 @@ async def get_reconcile_stats_services(
current_user: CurrentUserModel,
) -> FileReconcileStatsModel:
"""
- 获取文件存储对账统计
+ 获取文件存储对账统计。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param current_user: 当前登录用户及其权限信息
+ :return: 文件存储对账统计
"""
cls._require_admin(current_user)
stats = await FileInfoDao.get_reconcile_stats(query_db)
@@ -1355,7 +1439,7 @@ async def handle_reconcile_issue_services(
request: Request | None = None,
) -> CrudResponseModel:
"""
- 处理文件存储对账异常
+ 处理文件存储对账异常。
:param query_db: orm对象
:param current_user: 当前用户对象
@@ -1363,6 +1447,8 @@ async def handle_reconcile_issue_services(
:param handle: 处理参数
:param request: Request对象
:return: 处理结果
+ :raises ServiceException: 文件存储对账任务运行中,请等待扫描完成后再处理异常;文件存储对账异常不存在;当前异常状态不支持该处理动作;事务失败并回滚后重新抛出原异常
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
cls._require_admin(current_user)
if await FileInfoDao.has_running_reconcile_run(query_db):
@@ -1444,7 +1530,16 @@ async def _apply_reconcile_action(
current_user: CurrentUserModel,
current_time: datetime,
) -> tuple[str | None, tuple[str, str, str, str] | None]:
- """执行已通过状态校验的对账处理动作。"""
+ """
+ 执行已通过状态校验的对账处理动作。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param issue: 文件存储对账异常表
+ :param handle: 处理参数
+ :param current_user: 当前登录用户及其权限信息
+ :param current_time: 当前时间
+ :return: 依次为 ``file_id``、``performed_move`` 的元组
+ """
user = cls._require_admin(current_user)
performed_move: tuple[str, str, str, str] | None = None
file_id = issue.file_id
@@ -1486,6 +1581,12 @@ async def _move_issue_file(
cls,
issue: SysFileReconcileIssue,
) -> tuple[str, str, str, str]:
+ """
+ 将对账问题涉及的文件移到选定位置。
+
+ :param issue: 文件存储对账异常表
+ :return: 回滚时需要撤销的文件移动记录
+ """
move = cls._get_issue_move_locations(issue)
await asyncio.to_thread(FileReconcileUtil.move_regular_file, *move)
return move
@@ -1495,6 +1596,12 @@ async def _quarantine_issue_file(
cls,
issue: SysFileReconcileIssue,
) -> tuple[str, str, str, str]:
+ """
+ 将有问题的文件移入对账隔离区。
+
+ :param issue: 文件存储对账异常表
+ :return: 回滚时需要撤销的文件移动记录
+ """
source_root, source_key = cls._require_location(issue.actual_root, issue.actual_key)
quarantine_key = f'{issue.issue_id}/{source_root}/{source_key}'
move = (source_root, source_key, 'quarantine', quarantine_key)
@@ -1507,6 +1614,13 @@ async def _restore_quarantine_file(
cls,
issue: SysFileReconcileIssue,
) -> tuple[str, str, str, str]:
+ """
+ 从隔离区恢复文件。
+
+ :param issue: 文件存储对账异常表
+ :raises ServiceException: 隔离区文件路径不存在
+ :return: 回滚时需要撤销的文件移动记录
+ """
if not issue.quarantine_key:
raise ServiceException(message='隔离区文件路径不存在', msg_key='file.reconciliation.quarantineMissing')
target_root, target_key = cls._require_location(issue.actual_root, issue.actual_key)
@@ -1517,6 +1631,12 @@ async def _restore_quarantine_file(
@staticmethod
async def _delete_quarantine_file(issue: SysFileReconcileIssue) -> None:
+ """
+ 删除隔离区中的文件。
+
+ :param issue: 文件存储对账异常表
+ :raises ServiceException: 隔离区文件路径不存在
+ """
if not issue.quarantine_key:
raise ServiceException(message='隔离区文件路径不存在', msg_key='file.reconciliation.quarantineMissing')
await asyncio.to_thread(FileReconcileUtil.delete_quarantine_file, issue.quarantine_key)
@@ -1531,6 +1651,17 @@ async def _accept_current_file(
reason: str,
current_time: datetime,
) -> str:
+ """
+ 将当前文件状态确认为对账结果。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param issue: 文件存储对账异常表
+ :param handled_by: 处理该问题的用户标识
+ :param reason: 作出该决定或状态变化的原因
+ :param current_time: 当前时间
+ :raises ServiceException: 异常未关联文件信息;异常关联的文件信息不存在
+ :return: 供调用方使用的 ``issue.file_id``
+ """
if not issue.file_id:
raise ServiceException(message='异常未关联文件信息', msg_key='file.reconciliation.noFileReference')
file_info = await FileInfoDao.get_file_info_for_reconcile(query_db, issue.file_id)
@@ -1567,6 +1698,17 @@ async def _register_orphan_file(
current_user: CurrentUserModel,
current_time: datetime,
) -> str:
+ """
+ 为没有登记的磁盘文件创建记录。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param issue: 文件存储对账异常表
+ :param handle: 处理参数
+ :param current_user: 当前登录用户及其权限信息
+ :param current_time: 当前时间
+ :raises ServiceException: 仅公开或受保护存储区的孤立文件可以登记;该物理文件已登记到文件信息表;孤立文件扩展名不在允许范围内;原始文件名扩展名必须与物理文件一致
+ :return: 供调用方使用的 ``file_id``
+ """
user = cls._require_admin(current_user)
access_type, storage_key = cls._require_location(issue.actual_root, issue.actual_key)
if issue.issue_type != 'orphan_file' or access_type not in {'public', 'private'}:
@@ -1627,6 +1769,12 @@ def _get_available_actions(
cls,
issue: SysFileReconcileIssue | FileReconcileIssueModel,
) -> list[FileReconcileAction]:
+ """
+ 返回当前对账问题允许执行的处理操作。
+
+ :param issue: 待处理的文件对账异常记录
+ :return: 当前对账问题允许执行的处理操作
+ """
if issue.quarantine_key or issue.status == 'quarantined':
return ['restore_quarantine', 'delete_quarantine']
if issue.status == 'ignored':
@@ -1644,12 +1792,26 @@ def _get_issue_move_locations(
cls,
issue: SysFileReconcileIssue,
) -> tuple[str, str, str, str]:
+ """
+ 确定处理对账问题时使用的源位置和目标位置。
+
+ :param issue: 文件存储对账异常表
+ :return: 依次为 ``source_root``、``source_key``、``target_root``、``target_key`` 的元组
+ """
source_root, source_key = cls._require_location(issue.actual_root, issue.actual_key)
target_root, target_key = cls._require_location(issue.expected_root, issue.expected_key)
return source_root, source_key, target_root, target_key
@staticmethod
def _require_location(root_name: str | None, relative_key: str | None) -> tuple[str, str]:
+ """
+ 校验对账操作所需的文件位置。
+
+ :param root_name: 存储区域
+ :param relative_key: 相对路径
+ :raises ServiceException: 异常记录缺少可处理的存储位置;异常记录的存储区域不合法
+ :return: 依次为 ``root_name``、``relative_key`` 的元组
+ """
if not root_name or not relative_key:
raise ServiceException(
message='异常记录缺少可处理的存储位置', msg_key='file.reconciliation.locationMissing'
@@ -1666,6 +1828,15 @@ def _mark_issue_handled(
handled_by: str,
handled_time: datetime,
) -> None:
+ """
+ 保存对账问题的处理结果。
+
+ :param issue: 文件存储对账异常表
+ :param status: 操作或记录所处的状态
+ :param handle: 处理参数
+ :param handled_by: 处理该问题的用户标识
+ :param handled_time: 问题处理时间
+ """
issue.status = status
issue.handle_action = handle.action
issue.handle_reason = handle.reason
@@ -1674,6 +1845,11 @@ def _mark_issue_handled(
@classmethod
async def _rollback_file_move(cls, move: tuple[str, str, str, str]) -> None:
+ """
+ 撤销未能完成的对账文件移动。
+
+ :param move: 回滚时需要撤销的文件移动记录
+ """
source_root, source_key, target_root, target_key = move
try:
await asyncio.to_thread(
@@ -1688,6 +1864,12 @@ async def _rollback_file_move(cls, move: tuple[str, str, str, str]) -> None:
@staticmethod
def _build_run_data(reconcile_run: SysFileReconcileRun) -> dict[str, Any]:
+ """
+ 组装文件对账批次的结果数据。
+
+ :param reconcile_run: 对账任务
+ :return: 文件对账批次的结果数据
+ """
return {
'run_id': reconcile_run.run_id,
'trigger_type': reconcile_run.trigger_type,
@@ -1706,6 +1888,13 @@ def _build_run_data(reconcile_run: SysFileReconcileRun) -> dict[str, Any]:
@staticmethod
def _require_admin(current_user: CurrentUserModel | None) -> Any:
+ """
+ 校验当前用户具有文件对账管理权限。
+
+ :param current_user: 当前登录用户及其权限信息
+ :raises ServiceException: 仅系统管理员可以使用文件存储对账功能
+ :return: 当前操作对应的用户
+ """
user = current_user.user if current_user else None
if user is None or not user.admin or not user.user_name:
raise ServiceException(
diff --git a/ruoyi-fastapi-backend/module_admin/service/job_log_service.py b/ruoyi-fastapi-backend/module_admin/service/job_log_service.py
index 92f3fa962..8056bf86b 100644
--- a/ruoyi-fastapi-backend/module_admin/service/job_log_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/job_log_service.py
@@ -15,16 +15,14 @@
class JobLogService:
- """
- 定时任务日志管理模块服务层
- """
+ """定时任务日志管理模块服务层。"""
@classmethod
async def get_job_log_list_services(
cls, query_db: AsyncSession, query_object: JobLogPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 获取定时任务日志列表信息service
+ 获取定时任务日志列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -38,7 +36,7 @@ async def get_job_log_list_services(
@classmethod
def add_job_log_services(cls, query_db: Session, page_object: JobLogModel) -> CrudResponseModel:
"""
- 新增定时任务日志信息service
+ 新增定时任务日志信息service。
:param query_db: orm对象
:param page_object: 新增定时任务日志对象
@@ -57,11 +55,12 @@ def add_job_log_services(cls, query_db: Session, page_object: JobLogModel) -> Cr
@classmethod
async def delete_job_log_services(cls, query_db: AsyncSession, page_object: DeleteJobLogModel) -> CrudResponseModel:
"""
- 删除定时任务日志信息service
+ 删除定时任务日志信息service。
:param query_db: orm对象
:param page_object: 删除定时任务日志对象
:return: 删除定时任务日志校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
if page_object.job_log_ids:
job_log_id_list = page_object.job_log_ids.split(',')
@@ -80,10 +79,11 @@ async def delete_job_log_services(cls, query_db: AsyncSession, page_object: Dele
@classmethod
async def clear_job_log_services(cls, query_db: AsyncSession) -> CrudResponseModel:
"""
- 清除定时任务日志信息service
+ 清除定时任务日志信息service。
:param query_db: orm对象
:return: 清除定时任务日志校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
try:
await JobLogDao.clear_job_log_dao(query_db)
@@ -98,7 +98,7 @@ async def clear_job_log_services(cls, query_db: AsyncSession) -> CrudResponseMod
@staticmethod
async def export_job_log_list_services(request: Request, job_log_list: list) -> bytes:
"""
- 导出定时任务日志信息service
+ 导出定时任务日志信息service。
:param request: Request对象
:param job_log_list: 定时任务日志信息列表
diff --git a/ruoyi-fastapi-backend/module_admin/service/job_service.py b/ruoyi-fastapi-backend/module_admin/service/job_service.py
index 9b923f957..d58c660be 100644
--- a/ruoyi-fastapi-backend/module_admin/service/job_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/job_service.py
@@ -25,7 +25,9 @@
class JobService:
"""
- 定时任务管理模块服务层
+ 定时任务管理模块服务层。
+
+ :cvar RUNTIME_FIELDS: 来自调度运行时的字段集合
"""
RUNTIME_FIELDS = {
@@ -42,11 +44,12 @@ class JobService:
@staticmethod
def _validate_job(job: JobModel, *, check_target_permission: bool = True) -> JobModel:
"""
- 在业务事务提交前完成与调度注册相同的配置校验
+ 在业务事务提交前完成与调度注册相同的配置校验。
:param job: 任务对象信息
:param check_target_permission: 是否校验管理接口的调用目标白名单
:return: 校验后的任务对象
+ :raises ServiceException: 任务配置未通过调度器的注册校验
"""
job = JobAdapter.normalize(job)
try:
@@ -62,7 +65,7 @@ def _validate_job(job: JobModel, *, check_target_permission: bool = True) -> Job
@classmethod
async def _after_commit(cls, states: list[dict[str, Any]], action: str) -> CrudResponseModel:
"""
- 反馈已提交修改的同步结果,后续同步失败不伪装成事务回滚
+ 反馈已提交修改的同步结果,后续同步失败不伪装成事务回滚。
:param states: 已提交的任务同步状态
:param action: 任务操作类型
@@ -92,7 +95,7 @@ async def get_job_list_services(
cls, query_db: AsyncSession, query_object: JobPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 获取定时任务列表信息service
+ 获取定时任务列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -112,7 +115,7 @@ async def get_job_list_services(
@staticmethod
def _get_observed_next_run_time(row: dict[str, Any]) -> datetime | None:
"""
- 只展示已生效且近期被Leader观测到的实际调度时刻
+ 只展示已生效且近期被Leader观测到的实际调度时刻。
:param row: 包含任务状态与调度观测数据的字典
:return: 实际下次调度时刻,停用、同步未完成或观测过期时返回None
@@ -127,7 +130,7 @@ def _get_observed_next_run_time(row: dict[str, Any]) -> datetime | None:
@staticmethod
def _get_next_valid_time(cron_expression: str | None, time_zone: str | None) -> datetime | None:
"""
- 根据任务时区计算Cron理论预览,不代表调度器已安排执行
+ 根据任务时区计算Cron理论预览,不代表调度器已安排执行。
:param cron_expression: 任务Cron表达式
:param time_zone: 任务IANA时区名称
@@ -144,7 +147,7 @@ def _get_next_valid_time(cron_expression: str | None, time_zone: str | None) ->
@classmethod
async def check_job_unique_services(cls, query_db: AsyncSession, page_object: JobModel) -> bool:
"""
- 校验定时任务是否存在service
+ 校验定时任务是否存在service。
:param query_db: orm对象
:param page_object: 定时任务对象
@@ -159,11 +162,13 @@ async def check_job_unique_services(cls, query_db: AsyncSession, page_object: Jo
@classmethod
async def add_job_services(cls, query_db: AsyncSession, page_object: JobModel) -> CrudResponseModel:
"""
- 新增定时任务信息service
+ 新增定时任务信息service。
:param query_db: orm对象
:param page_object: 新增定时任务对象
:return: 新增定时任务校验结果
+ :raises ServiceException: 同一任务组内已有同名任务
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
page_object = cls._validate_job(page_object.model_copy(update={'job_id': None}))
if not await cls.check_job_unique_services(query_db, page_object):
@@ -186,7 +191,7 @@ async def add_job_services(cls, query_db: AsyncSession, page_object: JobModel) -
@classmethod
def _deal_edit_job(cls, page_object: EditJobModel, edit_job: dict[str, Any]) -> None:
"""
- 处理编辑定时任务字典
+ 处理编辑定时任务字典。
:param page_object: 编辑定时任务对象
:param edit_job: 编辑定时任务字典
@@ -200,11 +205,12 @@ def _deal_edit_job(cls, page_object: EditJobModel, edit_job: dict[str, Any]) ->
@classmethod
async def edit_job_services(cls, query_db: AsyncSession, page_object: EditJobModel) -> CrudResponseModel:
"""
- 编辑定时任务信息service
+ 编辑定时任务信息service。
:param query_db: orm对象
:param page_object: 编辑定时任务对象
:return: 编辑定时任务校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
edit_job = page_object.model_dump(
exclude_unset=True,
@@ -244,12 +250,13 @@ async def execute_job_once_services(
requested_by: str | None = None,
) -> CrudResponseModel:
"""
- 执行一次定时任务service
+ 执行一次定时任务service。
:param query_db: orm对象
:param page_object: 定时任务对象
:param requested_by: 手动执行提交者
:return: 执行一次定时任务结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
try:
db_job, _state = await JobRuntimeDao.lock_job(query_db, page_object.job_id)
@@ -270,11 +277,13 @@ async def execute_job_once_services(
@classmethod
async def delete_job_services(cls, query_db: AsyncSession, page_object: DeleteJobModel) -> CrudResponseModel:
"""
- 删除定时任务信息service
+ 删除定时任务信息service。
:param query_db: orm对象
:param page_object: 删除定时任务对象
:return: 删除定时任务校验结果
+ :raises ServiceException: 任务ID必须为正整数;传入定时任务id为空
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
if page_object.job_ids:
try:
@@ -301,11 +310,12 @@ async def delete_job_services(cls, query_db: AsyncSession, page_object: DeleteJo
@classmethod
async def job_detail_services(cls, query_db: AsyncSession, job_id: int) -> JobModel:
"""
- 获取定时任务详细信息service
+ 获取定时任务详细信息service。
:param query_db: orm对象
:param job_id: 定时任务id
:return: 定时任务id对应的信息
+ :raises ServiceException: 定时任务不存在
"""
job = await JobDao.get_job_detail_by_id(query_db, job_id=job_id)
if job is None:
@@ -330,11 +340,12 @@ async def job_detail_services(cls, query_db: AsyncSession, job_id: int) -> JobMo
@classmethod
async def execution_detail_services(cls, query_db: AsyncSession, execution_id: str) -> dict[str, Any]:
"""
- 查询执行结果,任务删除后仍可按执行 ID 追踪
+ 查询执行结果,任务删除后仍可按执行 ID 追踪。
:param query_db: orm对象
:param execution_id: 执行ID
:return: 执行状态及时间信息
+ :raises ServiceException: 执行记录不存在
"""
execution = await JobRuntimeDao.get_execution(query_db, execution_id)
if execution is None:
@@ -344,7 +355,7 @@ async def execution_detail_services(cls, query_db: AsyncSession, execution_id: s
@staticmethod
async def execution_list_services(query_db: AsyncSession, query: JobExecutionQueryModel) -> PageModel:
"""
- 查询任务执行记录及未执行原因
+ 查询任务执行记录及未执行原因。
:param query_db: orm对象
:param query: 查询参数对象
@@ -355,7 +366,7 @@ async def execution_list_services(query_db: AsyncSession, query: JobExecutionQue
@staticmethod
async def sync_list_services(query_db: AsyncSession, query: JobSyncQueryModel) -> PageModel:
"""
- 查询配置和删除操作的调度应用状态
+ 查询配置和删除操作的调度应用状态。
:param query_db: orm对象
:param query: 查询参数对象
@@ -366,11 +377,12 @@ async def sync_list_services(query_db: AsyncSession, query: JobSyncQueryModel) -
@classmethod
async def retry_sync_services(cls, query_db: AsyncSession, job_id: int) -> CrudResponseModel:
"""
- 重试指定任务的最新配置或删除记录,不重复保存业务修改
+ 重试指定任务的最新配置或删除记录,不重复保存业务修改。
:param query_db: orm对象
:param job_id: 任务ID
:return: 调度同步结果
+ :raises ServiceException: 调度同步记录不存在
"""
states = await JobRuntimeDao.get_states(query_db, [job_id])
if job_id not in states:
@@ -380,7 +392,7 @@ async def retry_sync_services(cls, query_db: AsyncSession, job_id: int) -> CrudR
@staticmethod
async def export_job_list_services(request: Request, job_list: list) -> bytes:
"""
- 导出定时任务信息service
+ 导出定时任务信息service。
:param request: Request对象
:param job_list: 定时任务信息列表
diff --git a/ruoyi-fastapi-backend/module_admin/service/log_service.py b/ruoyi-fastapi-backend/module_admin/service/log_service.py
index f741286ec..32b12f516 100644
--- a/ruoyi-fastapi-backend/module_admin/service/log_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/log_service.py
@@ -34,16 +34,14 @@
class OperationLogService:
- """
- 操作日志管理模块服务层
- """
+ """操作日志管理模块服务层。"""
@classmethod
async def get_operation_log_list_services(
cls, query_db: AsyncSession, query_object: OperLogPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 获取操作日志列表信息service
+ 获取操作日志列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -57,11 +55,12 @@ async def get_operation_log_list_services(
@classmethod
async def add_operation_log_services(cls, query_db: AsyncSession, page_object: OperLogModel) -> CrudResponseModel:
"""
- 新增操作日志service
+ 新增操作日志service。
:param query_db: orm对象
:param page_object: 新增操作日志对象
:return: 新增操作日志校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
try:
await OperationLogDao.add_operation_log_dao(query_db, page_object)
@@ -76,11 +75,13 @@ async def delete_operation_log_services(
cls, query_db: AsyncSession, page_object: DeleteOperLogModel
) -> CrudResponseModel:
"""
- 删除操作日志信息service
+ 删除操作日志信息service。
:param query_db: orm对象
:param page_object: 删除操作日志对象
:return: 删除操作日志校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入操作日志id为空
"""
if page_object.oper_ids:
oper_id_list = page_object.oper_ids.split(',')
@@ -98,10 +99,11 @@ async def delete_operation_log_services(
@classmethod
async def clear_operation_log_services(cls, query_db: AsyncSession) -> CrudResponseModel:
"""
- 清除操作日志信息service
+ 清除操作日志信息service。
:param query_db: orm对象
:return: 清除操作日志校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
try:
await OperationLogDao.clear_operation_log_dao(query_db)
@@ -114,7 +116,7 @@ async def clear_operation_log_services(cls, query_db: AsyncSession) -> CrudRespo
@classmethod
async def export_operation_log_list_services(cls, request: Request, operation_log_list: list) -> bytes:
"""
- 导出操作日志信息service
+ 导出操作日志信息service。
:param request: Request对象
:param operation_log_list: 操作日志信息列表
@@ -165,16 +167,14 @@ async def export_operation_log_list_services(cls, request: Request, operation_lo
class LoginLogService:
- """
- 登录日志管理模块服务层
- """
+ """登录日志管理模块服务层。"""
@classmethod
async def get_login_log_list_services(
cls, query_db: AsyncSession, query_object: LoginLogPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 获取登录日志列表信息service
+ 获取登录日志列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -188,11 +188,12 @@ async def get_login_log_list_services(
@classmethod
async def add_login_log_services(cls, query_db: AsyncSession, page_object: LogininforModel) -> CrudResponseModel:
"""
- 新增登录日志service
+ 新增登录日志service。
:param query_db: orm对象
:param page_object: 新增登录日志对象
:return: 新增登录日志校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
try:
await LoginLogDao.add_login_log_dao(query_db, page_object)
@@ -207,11 +208,13 @@ async def delete_login_log_services(
cls, query_db: AsyncSession, page_object: DeleteLoginLogModel
) -> CrudResponseModel:
"""
- 删除操作日志信息service
+ 删除操作日志信息service。
:param query_db: orm对象
:param page_object: 删除操作日志对象
:return: 删除操作日志校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入登录日志id为空
"""
if page_object.info_ids:
info_id_list = page_object.info_ids.split(',')
@@ -229,10 +232,11 @@ async def delete_login_log_services(
@classmethod
async def clear_login_log_services(cls, query_db: AsyncSession) -> CrudResponseModel:
"""
- 清除操作日志信息service
+ 清除操作日志信息service。
:param query_db: orm对象
:return: 清除操作日志校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
try:
await LoginLogDao.clear_login_log_dao(query_db)
@@ -244,6 +248,14 @@ async def clear_login_log_services(cls, query_db: AsyncSession) -> CrudResponseM
@classmethod
async def unlock_user_services(cls, request: Request, unlock_user: UnlockUser) -> CrudResponseModel:
+ """
+ 解除用户因登录失败触发的锁定。
+
+ :param request: 当前 HTTP 请求
+ :param unlock_user: 解锁用户模型
+ :return: ``CrudResponseModel`` 实例
+ :raises ServiceException: 该用户未锁定
+ """
locked_user = await request.app.state.redis.get(f'account_lock:{unlock_user.user_name}')
if locked_user:
await request.app.state.redis.delete(f'account_lock:{unlock_user.user_name}')
@@ -253,7 +265,7 @@ async def unlock_user_services(cls, request: Request, unlock_user: UnlockUser) -
@staticmethod
async def export_login_log_list_services(login_log_list: list) -> bytes:
"""
- 导出登录日志信息service
+ 导出登录日志信息service。
:param login_log_list: 登录日志信息列表
:return: 登录日志信息对应excel的二进制数据
@@ -282,14 +294,12 @@ async def export_login_log_list_services(login_log_list: list) -> bytes:
class LogQueueService:
- """
- 日志队列服务
- """
+ """日志队列服务。"""
@classmethod
def _build_event_id(cls, request_id: str, log_type: str, source: str) -> str:
"""
- 生成日志事件唯一标识
+ 生成日志事件唯一标识。
:param request_id: 请求唯一标识
:param log_type: 日志类型
@@ -304,13 +314,12 @@ def _build_event_id(cls, request_id: str, log_type: str, source: str) -> str:
@classmethod
async def _xadd_event(cls, redis: aioredis.Redis, event_type: str, payload: dict, source: str) -> None:
"""
- 写入日志事件到Redis Streams
+ 写入日志事件到Redis Streams。
:param redis: Redis连接对象
:param event_type: 事件类型
:param payload: 事件负载
:param source: 日志来源
- :return: None
"""
request_id = TraceCtx.get_request_id()
trace_id = TraceCtx.get_trace_id()
@@ -333,12 +342,11 @@ async def _xadd_event(cls, redis: aioredis.Redis, event_type: str, payload: dict
@classmethod
async def enqueue_login_log(cls, request: Request, login_log: LogininforModel, source: str) -> None:
"""
- 登录日志入队
+ 登录日志入队。
:param request: Request对象
:param login_log: 登录日志模型
:param source: 日志来源
- :return: None
"""
payload = LogSanitizer.sanitize_data(login_log.model_dump(mode='json', by_alias=True, exclude_none=True))
await cls._xadd_event(request.app.state.redis, 'login', payload, source)
@@ -346,12 +354,11 @@ async def enqueue_login_log(cls, request: Request, login_log: LogininforModel, s
@classmethod
async def enqueue_operation_log(cls, request: Request, operation_log: OperLogModel, source: str) -> None:
"""
- 操作日志入队
+ 操作日志入队。
:param request: Request对象
:param operation_log: 操作日志模型
:param source: 日志来源
- :return: None
"""
payload = LogSanitizer.sanitize_data(operation_log.model_dump(mode='json', by_alias=True, exclude_none=True))
await cls._xadd_event(request.app.state.redis, 'operation', payload, source)
@@ -359,29 +366,26 @@ async def enqueue_operation_log(cls, request: Request, operation_log: OperLogMod
@classmethod
async def enqueue_file_access_log(cls, request: Request, file_access_log: FileAccessLogModel, source: str) -> None:
"""
- 文件访问审计日志入队
+ 文件访问审计日志入队。
:param request: Request对象
:param file_access_log: 文件访问审计日志模型
:param source: 日志来源
- :return: None
"""
payload = LogSanitizer.sanitize_data(file_access_log.model_dump(mode='json', by_alias=True, exclude_none=True))
await cls._xadd_event(request.app.state.redis, 'file_access', payload, source)
class LogAggregatorService:
- """
- 日志聚合消费服务
- """
+ """日志聚合消费服务。"""
@classmethod
async def _ensure_group(cls, redis: aioredis.Redis) -> None:
"""
- 初始化消费组
+ 初始化消费组。
:param redis: Redis连接对象
- :return: None
+ :raises Exception: 创建 Redis 消费组失败且原因不是消费组已存在
"""
try:
await redis.xgroup_create(
@@ -397,7 +401,7 @@ async def _ensure_group(cls, redis: aioredis.Redis) -> None:
@classmethod
async def _acquire_dedup(cls, redis: aioredis.Redis, event_id: str) -> bool:
"""
- 获取去重锁
+ 获取去重锁。
:param redis: Redis连接对象
:param event_id: 事件唯一标识
@@ -411,11 +415,10 @@ async def _acquire_dedup(cls, redis: aioredis.Redis, event_id: str) -> bool:
@classmethod
async def _release_dedup(cls, redis: aioredis.Redis, event_id: str) -> None:
"""
- 释放去重锁
+ 释放去重锁。
:param redis: Redis连接对象
:param event_id: 事件唯一标识
- :return: None
"""
if not event_id:
return
@@ -424,11 +427,10 @@ async def _release_dedup(cls, redis: aioredis.Redis, event_id: str) -> None:
@classmethod
async def _claim_pending(cls, redis: aioredis.Redis, consumer_name: str) -> None:
"""
- 认领并处理超时未确认的消息
+ 认领并处理超时未确认的消息。
:param redis: Redis连接对象
:param consumer_name: 消费者名称
- :return: None
"""
if LogConfig.log_stream_claim_idle_ms <= 0:
return
@@ -454,10 +456,10 @@ async def _claim_pending(cls, redis: aioredis.Redis, consumer_name: str) -> None
@classmethod
async def consume_stream(cls, redis: aioredis.Redis) -> None:
"""
- 消费日志队列
+ 消费日志队列。
:param redis: Redis连接对象
- :return: None
+ :raises asyncio.CancelledError: 异步操作被取消时
"""
await cls._ensure_group(redis)
consumer_name = f'{LogConfig.log_stream_consumer_prefix}-{os.getpid()}-{uuid.uuid4().hex[:6]}'
@@ -488,12 +490,12 @@ async def consume_stream(cls, redis: aioredis.Redis) -> None:
@classmethod
async def _process_messages(cls, redis: aioredis.Redis, stream_name: str, messages: list[tuple[str, dict]]) -> None:
"""
- 处理消息并落库
+ 处理消息并落库。
:param redis: Redis连接对象
:param stream_name: Stream名称
:param messages: 消息列表
- :return: None
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
if not messages:
return
diff --git a/ruoyi-fastapi-backend/module_admin/service/login_service.py b/ruoyi-fastapi-backend/module_admin/service/login_service.py
index c673f0fce..d8001419c 100644
--- a/ruoyi-fastapi-backend/module_admin/service/login_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/login_service.py
@@ -51,16 +51,16 @@
class PreAuthOAuth2PasswordBearer(OAuth2PasswordBearer):
- """
- 支持公开路由排除的登录令牌依赖
- """
+ """支持公开路由排除的登录令牌依赖。"""
async def __call__(self, request: Request) -> str | None:
"""
- 根据路由认证要求读取登录令牌
+ 根据路由认证要求读取登录令牌。
:param request: 当前请求对象
:return: 登录令牌,公开路由返回None
+ :raises AuthException: 用户未登录,请先完成登录;用户token已失效,请重新登录
+ :raises HTTPException: 当前路由要求认证且请求未提供有效凭据
"""
mode = AuthPolicy.get_auth_mode(request, (LoginService.get_current_user, oauth2_scheme))
if mode == 'excluded':
@@ -94,7 +94,12 @@ async def __call__(self, request: Request) -> str | None:
class CustomOAuth2PasswordRequestForm(OAuth2PasswordRequestForm):
"""
- 自定义OAuth2PasswordRequestForm类,增加验证码、会话编号及语言偏好参数
+ 自定义OAuth2PasswordRequestForm类,增加验证码、会话编号及语言偏好参数。
+
+ :ivar code: 与当前结果对应的编码
+ :ivar uuid: 验证码请求的唯一标识
+ :ivar login_info: 登录信息,前端无需传递
+ :ivar locale: 当前使用的语言区域标识
"""
def __init__(
@@ -112,6 +117,20 @@ def __init__(
default=None, max_length=63, description='登录页显式选择的语言偏好'
),
) -> None:
+ """
+ 解析密码授权表单以及验证码和登录扩展字段。
+
+ :param grant_type: 产生该 Access Token 的 OAuth Grant Type 字符串
+ :param username: 登录账号名称
+ :param password: 用户密码
+ :param scope: 当前操作使用的作用域
+ :param client_id: 客户端标识
+ :param client_secret: 仅在创建或轮换时返回的客户端密钥明文
+ :param code: 与当前结果对应的编码
+ :param uuid: 验证码请求的唯一标识
+ :param login_info: 登录信息,前端无需传递
+ :param locale: 当前使用的语言区域标识
+ """
super().__init__(
grant_type=grant_type,
username=username,
@@ -127,21 +146,20 @@ def __init__(
class LoginService:
- """
- 登录模块服务层
- """
+ """登录模块服务层。"""
@classmethod
async def authenticate_user(
cls, request: Request, query_db: AsyncSession, login_user: UserLogin
) -> Row[tuple[SysUser, SysDept]]:
"""
- 根据用户名密码校验用户登录
+ 根据用户名密码校验用户登录。
:param request: Request对象
:param query_db: orm对象
:param login_user: 登录用户对象
:return: 校验结果
+ :raises LoginException: 凭据校验失败,向登录入口返回对应的业务异常
"""
referer = request.headers.get('referer')
request_from_docs = bool(referer and referer.endswith(('docs', 'redoc')))
@@ -162,12 +180,13 @@ async def unlock_screen_services(
cls, query_db: AsyncSession, current_user: CurrentUserModel, password: str | None
) -> bool:
"""
- 校验当前登录用户的密码并解锁屏幕
+ 校验当前登录用户的密码并解锁屏幕。
:param query_db: orm对象
:param current_user: 当前登录用户
:param password: 用户密码
:return: 解锁结果
+ :raises ServiceException: 密码不能为空;服务器超时,请重新登录;密码错误,请重新输入
"""
if not password:
raise ServiceException(message='密码不能为空', msg_key='auth.passwordRequired')
@@ -182,11 +201,11 @@ async def unlock_screen_services(
@classmethod
async def create_access_token(cls, data: dict, expires_delta: timedelta | None = None) -> str:
"""
- 根据登录信息创建当前用户token
+ 根据登录信息创建当前用户token。
:param data: 登录信息
:param expires_delta: token有效期
- :return: token
+ :return: 签发的令牌
"""
to_encode = data.copy()
expire = (
@@ -203,13 +222,13 @@ async def get_current_user(
query_db: AsyncSession = DBSessionDependency(),
) -> CurrentUserModel | None:
"""
- 根据token获取当前用户信息
+ 根据token获取当前用户信息。
:param request: Request对象
:param token: 用户token
:param query_db: orm对象
:return: 当前用户信息对象,公开路由返回None
- :raise: 令牌异常AuthException
+ :raises AuthException: 用户未登录或令牌无效
"""
if token is None:
if AuthPolicy.get_auth_mode(request, (cls.get_current_user, oauth2_scheme)) == 'excluded':
@@ -243,6 +262,7 @@ async def _resolve_current_user(
:param query_db: 用于查询用户及权限的数据库会话
:param refresh_session: 是否续期宿主主登录会话
:return: 通过宿主身份及权限校验的当前用户
+ :raises AuthException: 用户token不合法;用户token已失效,请重新登录
"""
try:
if token.startswith('Bearer '):
@@ -296,7 +316,7 @@ async def _resolve_current_user(
@classmethod
async def _get_current_user_snapshot(cls, redis: Redis, query_db: AsyncSession, user_id: int) -> CurrentUserModel:
"""
- 获取当前用户快照,已有事务继续使用调用方的查询语义
+ 获取当前用户快照,已有事务继续使用调用方的查询语义。
:param redis: Redis连接对象
:param query_db: orm对象
@@ -338,11 +358,12 @@ async def _get_current_user_snapshot(cls, redis: Redis, query_db: AsyncSession,
@classmethod
async def _get_current_user_from_db(cls, query_db: AsyncSession, user_id: int) -> CurrentUserModel:
"""
- 查询当前用户资料和权限
+ 查询当前用户资料和权限。
:param query_db: orm对象
:param user_id: 用户id
:return: 当前用户信息对象
+ :raises AuthException: 用户token不合法
"""
query_user = await UserDao.get_user_by_id(query_db, user_id=user_id, for_auth=True)
basic_info = query_user.get('user_basic_info')
@@ -371,7 +392,7 @@ async def _get_current_user_from_db(cls, query_db: AsyncSession, user_id: int) -
@classmethod
async def get_sys_account_chrtype(cls, request: Request) -> str:
"""
- 获取用户密码字符范围配置
+ 获取用户密码字符范围配置。
:param request: Request对象
:return: 密码字符范围配置
@@ -383,7 +404,7 @@ async def get_sys_account_chrtype(cls, request: Request) -> str:
@classmethod
async def __init_password_is_modify(cls, request: Request, pwd_update_date: datetime) -> bool:
"""
- 判断当前用户是否初始密码登录
+ 判断当前用户是否初始密码登录。
:param request: Request对象
:param pwd_update_date: 密码最后更新时间
@@ -397,7 +418,7 @@ async def __init_password_is_modify(cls, request: Request, pwd_update_date: date
@classmethod
async def __password_is_expired(cls, request: Request, pwd_update_date: datetime) -> bool:
"""
- 判断当前用户密码是否过期
+ 判断当前用户密码是否过期。
:param request: Request对象
:param pwd_update_date: 密码最后更新时间
@@ -417,7 +438,7 @@ async def __password_is_expired(cls, request: Request, pwd_update_date: datetime
@classmethod
async def get_current_user_routers(cls, user_id: int, query_db: AsyncSession) -> list[dict[str, Any]]:
"""
- 根据用户id获取当前用户路由信息
+ 根据用户id获取当前用户路由信息。
:param user_id: 用户id
:param query_db: orm对象
@@ -440,7 +461,7 @@ async def get_current_user_routers(cls, user_id: int, query_db: AsyncSession) ->
@classmethod
def __generate_menus(cls, pid: int, permission_list: list[SysMenu]) -> list[MenuTreeModel]:
"""
- 工具方法:根据菜单信息生成菜单信息树形嵌套数据
+ 工具方法:根据菜单信息生成菜单信息树形嵌套数据。
:param pid: 菜单id
:param permission_list: 菜单列表信息
@@ -464,7 +485,7 @@ def __generate_user_router_menu(
plugin_menu_ids: dict[int, str] | None = None,
) -> list[RouterModel]:
"""
- 工具方法:根据菜单树信息生成路由信息树形嵌套数据
+ 工具方法:根据菜单树信息生成路由信息树形嵌套数据。
:param permission_list: 菜单树列表信息
:param plugin_menu_ids: 当前用户页面菜单的可信插件归属
@@ -546,12 +567,13 @@ async def register_user_services(
cls, request: Request, query_db: AsyncSession, user_register: UserRegister
) -> CrudResponseModel:
"""
- 用户注册services
+ 用户注册services。
:param request: Request对象
:param query_db: orm对象
:param user_register: 注册用户对象
:return: 注册结果
+ :raises ServiceException: 验证码已失效;验证码错误;注册程序已关闭,禁止注册;两次输入的密码不一致
"""
register_enabled = (
await request.app.state.redis.get(f'{RedisInitKeyConfig.SYS_CONFIG.key}:sys.account.registerUser') == 'true'
@@ -587,7 +609,7 @@ async def register_user_services(
@classmethod
async def get_sms_code_services(cls, request: Request, query_db: AsyncSession, user: ResetUserModel) -> SmsCode:
"""
- 获取短信验证码service
+ 获取短信验证码service。
:param request: Request对象
:param query_db: orm对象
@@ -616,7 +638,7 @@ async def forget_user_services(
cls, request: Request, query_db: AsyncSession, forget_user: ResetUserModel
) -> CrudResponseModel:
"""
- 用户忘记密码services
+ 用户忘记密码services。
:param request: Request对象
:param query_db: orm对象
@@ -645,7 +667,7 @@ async def forget_user_services(
@classmethod
async def logout_services(cls, request: Request, token_id: str, token: str) -> bool:
"""
- 退出登录services
+ 退出登录services。
:param request: Request对象
:param token_id: 令牌编号
@@ -661,14 +683,12 @@ async def logout_services(cls, request: Request, token_id: str, token: str) -> b
class RouterUtil:
- """
- 路由处理工具类
- """
+ """路由处理工具类。"""
@classmethod
def get_router_name(cls, menu: MenuTreeModel) -> str:
"""
- 获取路由名称
+ 获取路由名称。
:param menu: 菜单数对象
:return: 路由名称
@@ -682,7 +702,7 @@ def get_router_name(cls, menu: MenuTreeModel) -> str:
@classmethod
def get_route_name(cls, name: str, path: str) -> str:
"""
- 获取路由名称,如没有配置路由名称则取路由地址
+ 获取路由名称,如没有配置路由名称则取路由地址。
:param name: 路由名称
:param path: 路由地址
@@ -694,7 +714,7 @@ def get_route_name(cls, name: str, path: str) -> str:
@classmethod
def get_router_path(cls, menu: MenuTreeModel) -> str | None:
"""
- 获取路由地址
+ 获取路由地址。
:param menu: 菜单数对象
:return: 路由地址
@@ -718,7 +738,7 @@ def get_router_path(cls, menu: MenuTreeModel) -> str | None:
@classmethod
def get_component(cls, menu: MenuTreeModel) -> str:
"""
- 获取组件信息
+ 获取组件信息。
:param menu: 菜单数对象
:return: 组件信息
@@ -739,7 +759,7 @@ def get_component(cls, menu: MenuTreeModel) -> str:
@classmethod
def is_menu_frame(cls, menu: MenuTreeModel) -> bool:
"""
- 判断是否为菜单内部跳转
+ 判断是否为菜单内部跳转。
:param menu: 菜单数对象
:return: 是否为菜单内部跳转
@@ -753,7 +773,7 @@ def is_menu_frame(cls, menu: MenuTreeModel) -> bool:
@classmethod
def is_inner_link(cls, menu: MenuTreeModel) -> bool:
"""
- 判断是否为内链组件
+ 判断是否为内链组件。
:param menu: 菜单数对象
:return: 是否为内链组件
@@ -763,7 +783,7 @@ def is_inner_link(cls, menu: MenuTreeModel) -> bool:
@classmethod
def is_parent_view(cls, menu: MenuTreeModel) -> bool:
"""
- 判断是否为parent_view组件
+ 判断是否为parent_view组件。
:param menu: 菜单数对象
:return: 是否为parent_view组件
@@ -773,7 +793,7 @@ def is_parent_view(cls, menu: MenuTreeModel) -> bool:
@classmethod
def is_http(cls, link: str) -> bool:
"""
- 判断是否为http(s)://开头
+ 判断是否为http(s)://开头。
:param link: 链接
:return: 是否为http(s)://开头
@@ -783,7 +803,7 @@ def is_http(cls, link: str) -> bool:
@classmethod
def inner_link_replace_each(cls, path: str) -> str:
"""
- 内链域名特殊字符替换
+ 内链域名特殊字符替换。
:param path: 内链域名
:return: 替换后的内链域名
diff --git a/ruoyi-fastapi-backend/module_admin/service/menu_service.py b/ruoyi-fastapi-backend/module_admin/service/menu_service.py
index 4dfc499e8..67a5a0550 100644
--- a/ruoyi-fastapi-backend/module_admin/service/menu_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/menu_service.py
@@ -18,16 +18,14 @@
class MenuService:
- """
- 菜单管理模块服务层
- """
+ """菜单管理模块服务层。"""
@classmethod
async def get_menu_tree_services(
cls, query_db: AsyncSession, current_user: CurrentUserModel | None = None
) -> list[dict[str, Any]]:
"""
- 获取菜单树信息service
+ 获取菜单树信息service。
:param query_db: orm对象
:param current_user: 当前用户对象
@@ -46,7 +44,7 @@ async def get_role_menu_tree_services(
cls, query_db: AsyncSession, role_id: int, current_user: CurrentUserModel | None = None
) -> RoleMenuQueryModel:
"""
- 根据角色id获取菜单树信息service
+ 根据角色id获取菜单树信息service。
:param query_db: orm对象
:param role_id: 角色id
@@ -69,7 +67,7 @@ async def get_menu_list_services(
cls, query_db: AsyncSession, page_object: MenuQueryModel, current_user: CurrentUserModel | None = None
) -> list[dict[str, Any]]:
"""
- 获取菜单列表信息service
+ 获取菜单列表信息service。
:param query_db: orm对象
:param page_object: 分页查询参数对象
@@ -87,7 +85,7 @@ async def get_menu_list_services(
@classmethod
async def check_menu_name_unique_services(cls, query_db: AsyncSession, page_object: MenuModel) -> bool:
"""
- 校验菜单名称是否唯一service
+ 校验菜单名称是否唯一service。
:param query_db: orm对象
:param page_object: 菜单对象
@@ -102,7 +100,7 @@ async def check_menu_name_unique_services(cls, query_db: AsyncSession, page_obje
@classmethod
async def check_route_config_unique_services(cls, query_db: AsyncSession, page_object: MenuModel) -> bool:
"""
- 校验路由名称和地址是否唯一service
+ 校验路由名称和地址是否唯一service。
:param query_db: orm对象
:param page_object: 菜单对象
@@ -139,11 +137,13 @@ async def check_route_config_unique_services(cls, query_db: AsyncSession, page_o
@classmethod
async def add_menu_services(cls, query_db: AsyncSession, page_object: MenuModel) -> CrudResponseModel:
"""
- 新增菜单信息service
+ 新增菜单信息service。
:param query_db: orm对象
:param page_object: 新增菜单对象
:return: 新增菜单校验结果
+ :raises ServiceException: 菜单名称或路由地址冲突,或外链缺少有效协议
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
if not await cls.check_menu_name_unique_services(query_db, page_object):
raise ServiceException(
@@ -174,11 +174,13 @@ async def add_menu_services(cls, query_db: AsyncSession, page_object: MenuModel)
@classmethod
async def edit_menu_services(cls, query_db: AsyncSession, page_object: MenuModel) -> CrudResponseModel:
"""
- 编辑菜单信息service
+ 编辑菜单信息service。
:param query_db: orm对象
:param page_object: 编辑菜单对象
:return: 编辑菜单校验结果
+ :raises ServiceException: 上级菜单存在循环关系;上级菜单不存在;菜单不存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
menu_info = await cls.menu_detail_services(query_db, page_object.menu_id)
if menu_info.menu_id:
@@ -237,11 +239,12 @@ async def update_menu_sort_services(
page_object: MenuSortModel,
) -> CrudResponseModel:
"""
- 批量保存菜单显示顺序
+ 批量保存菜单显示顺序。
:param query_db: orm对象
:param page_object: 菜单排序参数
:return: 保存结果
+ :raises ServiceException: 保存排序异常,请联系管理员
"""
menu_sort_list = cls.parse_menu_sort_items(page_object)
try:
@@ -255,10 +258,11 @@ async def update_menu_sort_services(
@classmethod
def parse_menu_sort_items(cls, page_object: MenuSortModel) -> list[dict[str, int]]:
"""
- 解析并校验菜单排序参数
+ 解析并校验菜单排序参数。
:param page_object: 菜单排序参数
:return: 菜单ID与显示顺序列表
+ :raises ServiceException: 菜单排序参数不正确
"""
menu_id_values = [value.strip() for value in page_object.menu_ids.split(',') if value.strip()]
order_num_values = [value.strip() for value in page_object.order_nums.split(',') if value.strip()]
@@ -282,11 +286,13 @@ def parse_menu_sort_items(cls, page_object: MenuSortModel) -> list[dict[str, int
@classmethod
async def delete_menu_services(cls, query_db: AsyncSession, page_object: DeleteMenuModel) -> CrudResponseModel:
"""
- 删除菜单信息service
+ 删除菜单信息service。
:param query_db: orm对象
:param page_object: 删除菜单对象
:return: 删除菜单校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入菜单id为空
"""
if page_object.menu_ids:
menu_id_list = page_object.menu_ids.split(',')
@@ -308,7 +314,7 @@ async def delete_menu_services(cls, query_db: AsyncSession, page_object: DeleteM
@classmethod
async def menu_detail_services(cls, query_db: AsyncSession, menu_id: int) -> MenuModel:
"""
- 获取菜单详细信息service
+ 获取菜单详细信息service。
:param query_db: orm对象
:param menu_id: 菜单id
@@ -322,7 +328,7 @@ async def menu_detail_services(cls, query_db: AsyncSession, menu_id: int) -> Men
@classmethod
def list_to_tree(cls, permission_list: Sequence[SysMenu]) -> list[MenuTreeModel]:
"""
- 工具方法:根据菜单列表信息生成树形嵌套数据
+ 工具方法:根据菜单列表信息生成树形嵌套数据。
:param permission_list: 菜单列表信息
:return: 菜单树形嵌套数据
diff --git a/ruoyi-fastapi-backend/module_admin/service/notice_service.py b/ruoyi-fastapi-backend/module_admin/service/notice_service.py
index f8894c288..85152a31d 100644
--- a/ruoyi-fastapi-backend/module_admin/service/notice_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/notice_service.py
@@ -20,7 +20,9 @@
class NoticeService:
"""
- 通知公告管理模块服务层
+ 通知公告管理模块服务层。
+
+ :cvar TOP_NOTICE_LIMIT: 首页最多展示的公告条数
"""
TOP_NOTICE_LIMIT = 5
@@ -30,7 +32,7 @@ async def get_notice_list_services(
cls, query_db: AsyncSession, query_object: NoticePageQueryModel, is_page: bool = True
) -> PageModel | list[dict[str, Any]]:
"""
- 获取通知公告列表信息service
+ 获取通知公告列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -48,7 +50,7 @@ async def get_notice_list_services(
@classmethod
async def get_notice_top_services(cls, query_db: AsyncSession, user_id: int) -> NoticeTopResponseModel:
"""
- 获取首页顶部通知公告及当前用户已读状态
+ 获取首页顶部通知公告及当前用户已读状态。
:param query_db: orm对象
:param user_id: 用户ID
@@ -65,7 +67,7 @@ async def get_notice_read_user_list_services(
cls, query_db: AsyncSession, query_object: NoticeReadUserPageQueryModel, is_page: bool = True
) -> PageModel | list[dict[str, Any]]:
"""
- 获取公告已读用户列表
+ 获取公告已读用户列表。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -79,12 +81,13 @@ async def mark_notice_read_services(
cls, query_db: AsyncSession, user_id: int, notice_ids: list[int]
) -> CrudResponseModel:
"""
- 标记通知公告已读
+ 标记通知公告已读。
:param query_db: orm对象
:param user_id: 用户ID
:param notice_ids: 公告ID列表
:return: 操作结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
try:
await NoticeDao.add_notice_reads(query_db, user_id, notice_ids)
@@ -97,10 +100,11 @@ async def mark_notice_read_services(
@classmethod
def parse_notice_ids(cls, notice_ids: str) -> list[int]:
"""
- 解析逗号分隔的公告ID
+ 解析逗号分隔的公告ID。
:param notice_ids: 逗号分隔的公告ID
:return: 去重后的公告ID列表
+ :raises ServiceException: 公告ID格式不正确
"""
try:
return list(
@@ -112,7 +116,7 @@ def parse_notice_ids(cls, notice_ids: str) -> list[int]:
@classmethod
async def check_notice_unique_services(cls, query_db: AsyncSession, page_object: NoticeModel) -> bool:
"""
- 校验通知公告是否存在service
+ 校验通知公告是否存在service。
:param query_db: orm对象
:param page_object: 通知公告对象
@@ -127,11 +131,13 @@ async def check_notice_unique_services(cls, query_db: AsyncSession, page_object:
@classmethod
async def add_notice_services(cls, query_db: AsyncSession, page_object: NoticeModel) -> CrudResponseModel:
"""
- 新增通知公告信息service
+ 新增通知公告信息service。
:param query_db: orm对象
:param page_object: 新增通知公告对象
:return: 新增通知公告校验结果
+ :raises ServiceException: 同名通知公告已存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
if not await cls.check_notice_unique_services(query_db, page_object):
raise ServiceException(
@@ -150,11 +156,13 @@ async def add_notice_services(cls, query_db: AsyncSession, page_object: NoticeMo
@classmethod
async def edit_notice_services(cls, query_db: AsyncSession, page_object: NoticeModel) -> CrudResponseModel:
"""
- 编辑通知公告信息service
+ 编辑通知公告信息service。
:param query_db: orm对象
:param page_object: 编辑通知公告对象
:return: 编辑通知公告校验结果
+ :raises ServiceException: 通知公告不存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
edit_notice = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'update_time'})
notice_info = await cls.notice_detail_services(query_db, page_object.notice_id)
@@ -178,11 +186,13 @@ async def edit_notice_services(cls, query_db: AsyncSession, page_object: NoticeM
@classmethod
async def delete_notice_services(cls, query_db: AsyncSession, page_object: DeleteNoticeModel) -> CrudResponseModel:
"""
- 删除通知公告信息service
+ 删除通知公告信息service。
:param query_db: orm对象
:param page_object: 删除通知公告对象
:return: 删除通知公告校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入通知公告id为空
"""
if page_object.notice_ids:
notice_id_list = cls.parse_notice_ids(page_object.notice_ids)
@@ -201,7 +211,7 @@ async def delete_notice_services(cls, query_db: AsyncSession, page_object: Delet
@classmethod
async def notice_detail_services(cls, query_db: AsyncSession, notice_id: int) -> NoticeModel:
"""
- 获取通知公告详细信息service
+ 获取通知公告详细信息service。
:param query_db: orm对象
:param notice_id: 通知公告id
diff --git a/ruoyi-fastapi-backend/module_admin/service/online_service.py b/ruoyi-fastapi-backend/module_admin/service/online_service.py
index 72d05d074..3710e0dac 100644
--- a/ruoyi-fastapi-backend/module_admin/service/online_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/online_service.py
@@ -12,14 +12,12 @@
class OnlineService:
- """
- 在线用户管理模块服务层
- """
+ """在线用户管理模块服务层。"""
@classmethod
async def get_online_list_services(cls, request: Request, query_object: OnlineQueryModel) -> list[dict[str, Any]]:
"""
- 获取在线用户表信息service
+ 获取在线用户表信息service。
:param request: Request对象
:param query_object: 查询参数对象
@@ -68,11 +66,12 @@ async def get_online_list_services(cls, request: Request, query_object: OnlineQu
@classmethod
async def delete_online_services(cls, request: Request, page_object: DeleteOnlineModel) -> CrudResponseModel:
"""
- 强退在线用户信息service
+ 强退在线用户信息service。
:param request: Request对象
:param page_object: 强退在线用户对象
:return: 强退在线用户校验结果
+ :raises ServiceException: 传入session_id为空
"""
if page_object.token_ids:
token_id_list = page_object.token_ids.split(',')
diff --git a/ruoyi-fastapi-backend/module_admin/service/post_service.py b/ruoyi-fastapi-backend/module_admin/service/post_service.py
index 5aeabb768..81f7f14e7 100644
--- a/ruoyi-fastapi-backend/module_admin/service/post_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/post_service.py
@@ -13,16 +13,14 @@
class PostService:
- """
- 岗位管理模块服务层
- """
+ """岗位管理模块服务层。"""
@classmethod
async def get_post_list_services(
cls, query_db: AsyncSession, query_object: PostPageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 获取岗位列表信息service
+ 获取岗位列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -36,7 +34,7 @@ async def get_post_list_services(
@classmethod
async def check_post_name_unique_services(cls, query_db: AsyncSession, page_object: PostModel) -> bool:
"""
- 检查岗位名称是否唯一service
+ 检查岗位名称是否唯一service。
:param query_db: orm对象
:param page_object: 岗位对象
@@ -51,7 +49,7 @@ async def check_post_name_unique_services(cls, query_db: AsyncSession, page_obje
@classmethod
async def check_post_code_unique_services(cls, query_db: AsyncSession, page_object: PostModel) -> bool:
"""
- 检查岗位编码是否唯一service
+ 检查岗位编码是否唯一service。
:param query_db: orm对象
:param page_object: 岗位对象
@@ -66,11 +64,13 @@ async def check_post_code_unique_services(cls, query_db: AsyncSession, page_obje
@classmethod
async def add_post_services(cls, query_db: AsyncSession, page_object: PostModel) -> CrudResponseModel:
"""
- 新增岗位信息service
+ 新增岗位信息service。
:param query_db: orm对象
:param page_object: 新增岗位对象
:return: 新增岗位校验结果
+ :raises ServiceException: 岗位名称或编码已存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
if not await cls.check_post_name_unique_services(query_db, page_object):
raise ServiceException(
@@ -95,11 +95,13 @@ async def add_post_services(cls, query_db: AsyncSession, page_object: PostModel)
@classmethod
async def edit_post_services(cls, query_db: AsyncSession, page_object: PostModel) -> CrudResponseModel:
"""
- 编辑岗位信息service
+ 编辑岗位信息service。
:param query_db: orm对象
:param page_object: 编辑岗位对象
:return: 编辑岗位校验结果
+ :raises ServiceException: 岗位不存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
edit_post = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'update_time'})
post_info = await cls.post_detail_services(query_db, page_object.post_id)
@@ -129,11 +131,13 @@ async def edit_post_services(cls, query_db: AsyncSession, page_object: PostModel
@classmethod
async def delete_post_services(cls, query_db: AsyncSession, page_object: DeletePostModel) -> CrudResponseModel:
"""
- 删除岗位信息service
+ 删除岗位信息service。
:param query_db: orm对象
:param page_object: 删除岗位对象
:return: 删除岗位校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入岗位id为空
"""
if page_object.post_ids:
post_id_list = page_object.post_ids.split(',')
@@ -158,7 +162,7 @@ async def delete_post_services(cls, query_db: AsyncSession, page_object: DeleteP
@classmethod
async def post_detail_services(cls, query_db: AsyncSession, post_id: int) -> PostModel:
"""
- 获取岗位详细信息service
+ 获取岗位详细信息service。
:param query_db: orm对象
:param post_id: 岗位id
@@ -172,7 +176,7 @@ async def post_detail_services(cls, query_db: AsyncSession, post_id: int) -> Pos
@staticmethod
async def export_post_list_services(post_list: list) -> bytes:
"""
- 导出岗位信息service
+ 导出岗位信息service。
:param post_list: 岗位信息列表
:return: 岗位信息对应excel的二进制数据
diff --git a/ruoyi-fastapi-backend/module_admin/service/role_service.py b/ruoyi-fastapi-backend/module_admin/service/role_service.py
index 8da62eff0..a0b86b7d5 100644
--- a/ruoyi-fastapi-backend/module_admin/service/role_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/role_service.py
@@ -25,14 +25,12 @@
class RoleService:
- """
- 角色管理模块服务层
- """
+ """角色管理模块服务层。"""
@classmethod
async def get_role_select_option_services(cls, query_db: AsyncSession) -> list[dict[str, Any]]:
"""
- 获取角色列表不分页信息service
+ 获取角色列表不分页信息service。
:param query_db: orm对象
:return: 角色列表不分页信息对象
@@ -44,7 +42,7 @@ async def get_role_select_option_services(cls, query_db: AsyncSession) -> list[d
@classmethod
async def get_role_dept_tree_services(cls, query_db: AsyncSession, role_id: int) -> RoleDeptQueryModel:
"""
- 根据角色id获取部门树信息service
+ 根据角色id获取部门树信息service。
:param query_db: orm对象
:param role_id: 角色id
@@ -66,7 +64,7 @@ async def get_role_list_services(
is_page: bool = False,
) -> PageModel | list[dict[str, Any]]:
"""
- 获取角色列表信息service
+ 获取角色列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -81,10 +79,11 @@ async def get_role_list_services(
@classmethod
async def check_role_allowed_services(cls, check_role: RoleModel) -> CrudResponseModel:
"""
- 校验角色是否允许操作service
+ 校验角色是否允许操作service。
:param check_role: 角色信息
:return: 校验结果
+ :raises ServiceException: 不允许操作超级管理员角色
"""
if check_role.admin:
raise ServiceException(message='不允许操作超级管理员角色', msg_key='role.superAdminProtected')
@@ -95,12 +94,12 @@ async def check_role_data_scope_services(
cls, query_db: AsyncSession, role_ids: str, data_scope_sql: ColumnElement
) -> None:
"""
- 校验角色是否有数据权限service
+ 校验角色是否有数据权限service。
:param query_db: orm对象
:param role_ids: 角色id
:param data_scope_sql: 数据权限对应的查询sql语句
- :return: 校验结果
+ :raises ServiceException: 没有权限访问角色数据
"""
role_id_list = role_ids.split(',') if role_ids else []
if role_id_list:
@@ -115,7 +114,7 @@ async def check_role_data_scope_services(
@classmethod
async def check_role_name_unique_services(cls, query_db: AsyncSession, page_object: RoleModel) -> bool:
"""
- 校验角色名称是否唯一service
+ 校验角色名称是否唯一service。
:param query_db: orm对象
:param page_object: 角色对象
@@ -130,7 +129,7 @@ async def check_role_name_unique_services(cls, query_db: AsyncSession, page_obje
@classmethod
async def check_role_key_unique_services(cls, query_db: AsyncSession, page_object: RoleModel) -> bool:
"""
- 校验角色权限字符是否唯一service
+ 校验角色权限字符是否唯一service。
:param query_db: orm对象
:param page_object: 角色对象
@@ -145,11 +144,13 @@ async def check_role_key_unique_services(cls, query_db: AsyncSession, page_objec
@classmethod
async def add_role_services(cls, query_db: AsyncSession, page_object: AddRoleModel) -> CrudResponseModel:
"""
- 新增角色信息service
+ 新增角色信息service。
:param query_db: orm对象
:param page_object: 新增角色对象
:return: 新增角色校验结果
+ :raises ServiceException: 角色名称或权限标识已存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
add_role = RoleModel(**page_object.model_dump(by_alias=True, exclude={'create_time', 'update_time'}))
if not await cls.check_role_name_unique_services(query_db, page_object):
@@ -183,7 +184,7 @@ async def _role_menu_changed(
role_info: RoleModel,
) -> bool:
"""
- 比较角色保存前后的菜单授权集合
+ 比较角色保存前后的菜单授权集合。
:param query_db: 角色变更使用的异步数据库会话
:param page_object: 本次角色编辑请求
@@ -203,12 +204,11 @@ async def _handle_edit_identity_event(
role_info: RoleModel,
) -> None:
"""
- 在角色安全属性变化时同步失效统一认证身份状态
+ 在角色安全属性变化时同步失效统一认证身份状态。
:param query_db: orm对象
:param page_object: 编辑角色对象
:param role_info: 当前角色信息
- :return: None
"""
if page_object.type == 'status':
if page_object.status == '1' and role_info.status != '1':
@@ -233,11 +233,13 @@ async def _handle_edit_identity_event(
@classmethod
async def edit_role_services(cls, query_db: AsyncSession, page_object: AddRoleModel) -> CrudResponseModel:
"""
- 编辑角色信息service
+ 编辑角色信息service。
:param query_db: orm对象
:param page_object: 编辑角色对象
:return: 编辑角色校验结果
+ :raises ServiceException: 角色不存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
edit_role = page_object.model_dump(
exclude_unset=True,
@@ -283,11 +285,13 @@ async def edit_role_services(cls, query_db: AsyncSession, page_object: AddRoleMo
@classmethod
async def role_datascope_services(cls, query_db: AsyncSession, page_object: AddRoleModel) -> CrudResponseModel:
"""
- 分配角色数据权限service
+ 分配角色数据权限service。
:param query_db: orm对象
:param page_object: 角色数据权限对象
:return: 分配角色数据权限结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 角色不存在
"""
edit_role = page_object.model_dump(
exclude_unset=True,
@@ -314,11 +318,13 @@ async def role_datascope_services(cls, query_db: AsyncSession, page_object: AddR
@classmethod
async def delete_role_services(cls, query_db: AsyncSession, page_object: DeleteRoleModel) -> CrudResponseModel:
"""
- 删除角色信息service
+ 删除角色信息service。
:param query_db: orm对象
:param page_object: 删除角色对象
:return: 删除角色校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入角色id为空
"""
if page_object.role_ids:
role_id_list = page_object.role_ids.split(',')
@@ -356,7 +362,7 @@ async def delete_role_services(cls, query_db: AsyncSession, page_object: DeleteR
@classmethod
async def role_detail_services(cls, query_db: AsyncSession, role_id: int) -> RoleModel:
"""
- 获取角色详细信息service
+ 获取角色详细信息service。
:param query_db: orm对象
:param role_id: 角色id
@@ -370,7 +376,7 @@ async def role_detail_services(cls, query_db: AsyncSession, role_id: int) -> Rol
@staticmethod
async def export_role_list_services(role_list: list) -> bytes:
"""
- 导出角色列表信息service
+ 导出角色列表信息service。
:param role_list: 角色信息列表
:return: 角色列表信息对象
@@ -407,7 +413,7 @@ async def get_role_user_allocated_list_services(
is_page: bool = False,
) -> PageModel:
"""
- 根据角色id获取已分配用户列表
+ 根据角色id获取已分配用户列表。
:param query_db: orm对象
:param page_object: 用户关联角色对象
@@ -436,7 +442,7 @@ async def get_role_user_unallocated_list_services(
is_page: bool = False,
) -> PageModel:
"""
- 根据角色id获取未分配用户列表
+ 根据角色id获取未分配用户列表。
:param query_db: orm对象
:param page_object: 用户关联角色对象
diff --git a/ruoyi-fastapi-backend/module_admin/service/server_service.py b/ruoyi-fastapi-backend/module_admin/service/server_service.py
index a1e213fde..c2e1577e9 100644
--- a/ruoyi-fastapi-backend/module_admin/service/server_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/server_service.py
@@ -13,12 +13,15 @@
class ServerService:
- """
- 服务监控模块服务层
- """
+ """服务监控模块服务层。"""
@staticmethod
async def get_server_monitor_info() -> ServerMonitorModel:
+ """
+ 汇总服务器的处理器、内存、运行环境和磁盘信息。
+
+ :return: 执行当前操作得到的结果
+ """
# CPU信息
# 获取CPU总核心数
cpu_num = psutil.cpu_count(logical=True)
@@ -90,7 +93,7 @@ async def get_server_monitor_info() -> ServerMonitorModel:
@classmethod
def _get_disk_info(cls) -> list[SysFiles]:
"""
- 获取可访问的磁盘信息
+ 获取可访问的磁盘信息。
:return: 磁盘信息列表
"""
@@ -120,7 +123,7 @@ def _get_disk_info(cls) -> list[SysFiles]:
@staticmethod
def _read_disk_info(device: str, mountpoint: str, filesystem: str) -> SysFiles | None:
"""
- 读取指定磁盘的容量信息
+ 读取指定磁盘的容量信息。
:param device: 磁盘设备名称
:param mountpoint: 磁盘挂载路径
diff --git a/ruoyi-fastapi-backend/module_admin/service/transport_crypto_service.py b/ruoyi-fastapi-backend/module_admin/service/transport_crypto_service.py
index f581314e4..1d579068f 100644
--- a/ruoyi-fastapi-backend/module_admin/service/transport_crypto_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/transport_crypto_service.py
@@ -9,14 +9,12 @@
class TransportCryptoService:
- """
- 传输加密模块服务层
- """
+ """传输加密模块服务层。"""
@classmethod
async def get_transport_frontend_config_services(cls) -> TransportCryptoFrontendConfigModel:
"""
- 获取前端传输加密运行配置service
+ 获取前端传输加密运行配置service。
:return: 前端传输加密运行配置
"""
@@ -25,7 +23,7 @@ async def get_transport_frontend_config_services(cls) -> TransportCryptoFrontend
@classmethod
async def get_transport_public_key_services(cls) -> TransportCryptoPublicKeyModel:
"""
- 获取传输加密公钥service
+ 获取传输加密公钥service。
:return: 传输加密公钥信息
"""
@@ -34,7 +32,7 @@ async def get_transport_public_key_services(cls) -> TransportCryptoPublicKeyMode
@classmethod
async def get_transport_crypto_monitor_info_services(cls, request: Request) -> TransportCryptoMonitorModel:
"""
- 获取传输加密监控信息service
+ 获取传输加密监控信息service。
:param request: Request对象
:return: 传输加密监控信息
diff --git a/ruoyi-fastapi-backend/module_admin/service/user_service.py b/ruoyi-fastapi-backend/module_admin/service/user_service.py
index a879264e2..6ba240e53 100644
--- a/ruoyi-fastapi-backend/module_admin/service/user_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/user_service.py
@@ -50,7 +50,10 @@
class UserService:
"""
- 用户管理模块服务层
+ 用户管理模块服务层。
+
+ :cvar PASSWORD_MIN_LENGTH: 密码允许的最小长度
+ :cvar PASSWORD_MAX_LENGTH: 密码允许的最大长度
"""
PASSWORD_MIN_LENGTH = 6
@@ -59,7 +62,7 @@ class UserService:
@staticmethod
async def _current_role_ids(query_db: AsyncSession, user_id: int) -> set[int]:
"""
- 读取用户当前角色ID,用于避免无变化时递增身份版本
+ 读取用户当前角色ID,用于避免无变化时递增身份版本。
:param query_db: orm对象
:param user_id: 用户id
@@ -72,12 +75,11 @@ async def _handle_role_assignment_changes(
query_db: AsyncSession, user_ids: list[int], actor: str | None = None
) -> None:
"""
- 仅在角色关联实际变化时批量触发身份安全事件
+ 仅在角色关联实际变化时批量触发身份安全事件。
:param query_db: orm对象
:param user_ids: 角色关联发生变化的用户ID列表
:param actor: 实际执行角色分配的操作者
- :return: None
"""
if user_ids:
await IdentitySecurityEventService.handle_users_event(
@@ -100,7 +102,7 @@ async def validate_password_services(
:param redis: redis对象
:param password: 明文密码
:param pwd_chrtype: 指定密码字符范围,未指定时读取系统配置
- :return: None
+ :raises ServiceException: 密码不能为空;密码长度必须介于 6 和 20 之间
"""
if pwd_chrtype is None:
pwd_chrtype = await ConfigService.query_config_list_from_cache_services(redis, 'sys.account.chrtype')
@@ -127,7 +129,7 @@ async def get_user_list_services(
is_page: bool = False,
) -> PageModel[UserRowModel] | list[dict[str, Any]]:
"""
- 获取用户列表信息service
+ 获取用户列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -153,10 +155,11 @@ async def get_user_list_services(
@classmethod
async def check_user_allowed_services(cls, check_user: UserModel) -> CrudResponseModel:
"""
- 校验用户是否允许操作service
+ 校验用户是否允许操作service。
:param check_user: 用户信息
:return: 校验结果
+ :raises ServiceException: 不允许操作超级管理员用户
"""
if check_user.admin:
raise ServiceException(message='不允许操作超级管理员用户', msg_key='user.superAdminProtected')
@@ -167,12 +170,13 @@ async def check_user_data_scope_services(
cls, query_db: AsyncSession, user_id: int, data_scope_sql: ColumnElement
) -> CrudResponseModel:
"""
- 校验用户数据权限service
+ 校验用户数据权限service。
:param query_db: orm对象
:param user_id: 用户id
:param data_scope_sql: 数据权限对应的查询sql语句
:return: 校验结果
+ :raises ServiceException: 没有权限访问用户数据
"""
users = await UserDao.get_user_list(query_db, UserPageQueryModel(userId=user_id), data_scope_sql, is_page=False)
if users:
@@ -182,7 +186,7 @@ async def check_user_data_scope_services(
@classmethod
async def check_user_name_unique_services(cls, query_db: AsyncSession, page_object: UserModel) -> bool:
"""
- 校验用户名是否唯一service
+ 校验用户名是否唯一service。
:param query_db: orm对象
:param page_object: 用户对象
@@ -197,7 +201,7 @@ async def check_user_name_unique_services(cls, query_db: AsyncSession, page_obje
@classmethod
async def check_phonenumber_unique_services(cls, query_db: AsyncSession, page_object: UserModel) -> bool:
"""
- 校验用户手机号是否唯一service
+ 校验用户手机号是否唯一service。
:param query_db: orm对象
:param page_object: 用户对象
@@ -212,7 +216,7 @@ async def check_phonenumber_unique_services(cls, query_db: AsyncSession, page_ob
@classmethod
async def check_email_unique_services(cls, query_db: AsyncSession, page_object: UserModel) -> bool:
"""
- 校验用户邮箱是否唯一service
+ 校验用户邮箱是否唯一service。
:param query_db: orm对象
:param page_object: 用户对象
@@ -227,11 +231,13 @@ async def check_email_unique_services(cls, query_db: AsyncSession, page_object:
@classmethod
async def add_user_services(cls, query_db: AsyncSession, page_object: AddUserModel) -> CrudResponseModel:
"""
- 新增用户信息service
+ 新增用户信息service。
:param query_db: orm对象
:param page_object: 新增用户对象
:return: 新增用户校验结果
+ :raises ServiceException: 登录账号、手机号或邮箱已被使用
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
add_user = UserModel(**page_object.model_dump(by_alias=True, exclude={'create_time', 'update_time'}))
if not await cls.check_user_name_unique_services(query_db, page_object):
@@ -275,11 +281,10 @@ async def add_user_services(cls, query_db: AsyncSession, page_object: AddUserMod
@classmethod
def _deal_edit_user(cls, page_object: EditUserModel, edit_user: dict[str, Any]) -> None:
"""
- 处理编辑用户字典
+ 处理编辑用户字典。
:param page_object: 编辑用户对象
:param edit_user: 编辑用户字典
- :return: None
"""
if page_object.type not in ['status', 'avatar', 'pwd']:
del edit_user['role_ids']
@@ -296,12 +301,12 @@ async def _handle_edit_identity_security_event(
current_user: UserInfoModel,
) -> None:
"""
- 将用户编辑类型映射为同事务OIDC安全事件
+ 将用户编辑类型映射为同事务OIDC安全事件。
:param query_db: orm对象
:param page_object: 编辑用户对象
:param current_user: 编辑前的用户信息
- :return: None
+ :raises ServiceException: 用户不存在
"""
user_id = page_object.user_id
if user_id is None:
@@ -343,11 +348,13 @@ async def _handle_edit_identity_security_event(
@classmethod
async def edit_user_services(cls, query_db: AsyncSession, page_object: EditUserModel) -> CrudResponseModel:
"""
- 编辑用户信息service
+ 编辑用户信息service。
:param query_db: orm对象
:param page_object: 编辑用户对象
:return: 编辑用户校验结果
+ :raises ServiceException: 用户不存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
edit_user = page_object.model_dump(
exclude_unset=True,
@@ -402,11 +409,13 @@ async def edit_user_services(cls, query_db: AsyncSession, page_object: EditUserM
@classmethod
async def delete_user_services(cls, query_db: AsyncSession, page_object: DeleteUserModel) -> CrudResponseModel:
"""
- 删除用户信息service
+ 删除用户信息service。
:param query_db: orm对象
:param page_object: 删除用户对象
:return: 删除用户校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入用户id为空
"""
if page_object.user_ids:
user_id_list = page_object.user_ids.split(',')
@@ -437,7 +446,7 @@ async def delete_user_services(cls, query_db: AsyncSession, page_object: DeleteU
@classmethod
async def user_detail_services(cls, query_db: AsyncSession, user_id: int | str) -> UserDetailModel:
"""
- 获取用户详细信息service
+ 获取用户详细信息service。
:param query_db: orm对象
:param user_id: 用户id
@@ -473,13 +482,14 @@ async def update_user_locale_services(
cls, query_db: AsyncSession, user_id: int, user_name: str, locale: str
) -> CrudResponseModel:
"""
- 更新当前账号的语言偏好
+ 更新当前账号的语言偏好。
:param query_db: 数据库会话
:param user_id: 当前登录用户ID
:param user_name: 当前登录用户账号
:param locale: auto或规范化语言标识
:return: 语言偏好更新结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
preference = LocaleRegistry.normalize_locale(locale, preference=True)
try:
@@ -499,13 +509,14 @@ async def update_user_timezone_services(
cls, query_db: AsyncSession, user_id: int, user_name: str, time_zone: str
) -> CrudResponseModel:
"""
- 更新当前账号的显示时区
+ 更新当前账号的显示时区。
:param query_db: 数据库会话
:param user_id: 当前登录用户ID
:param user_name: 当前登录用户账号
:param time_zone: auto或IANA时区名称
:return: 时区更新结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
preference = TimezoneUtil.validate_timezone_preference(time_zone)
try:
@@ -519,7 +530,7 @@ async def update_user_timezone_services(
@classmethod
async def user_profile_services(cls, query_db: AsyncSession, user_id: int) -> UserProfileModel:
"""
- 获取用户个人详细信息service
+ 获取用户个人详细信息service。
:param query_db: orm对象
:param user_id: 用户id
@@ -546,11 +557,13 @@ async def user_profile_services(cls, query_db: AsyncSession, user_id: int) -> Us
@classmethod
async def reset_user_services(cls, query_db: AsyncSession, page_object: ResetUserModel) -> CrudResponseModel:
"""
- 重置用户密码service
+ 重置用户密码service。
:param query_db: orm对象
:param page_object: 重置用户对象
:return: 重置用户校验结果
+ :raises ServiceException: 修改密码失败,旧密码错误;新密码不能与旧密码相同
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
reset_user = page_object.model_dump(
exclude_unset=True,
@@ -584,20 +597,18 @@ async def reset_user_services(cls, query_db: AsyncSession, page_object: ResetUse
@classmethod
def _set_row_sex_value(cls, row: pd.Series) -> None:
"""
- 设置行性别值
+ 设置行性别值。
:param row: 行数据
- :return: None
"""
row['sex'] = UserImportUtil.normalize_value('sex', row['sex'])
@classmethod
def _set_row_status_value(cls, row: pd.Series) -> None:
"""
- 设置行状态值
+ 设置行状态值。
:param row: 行数据
- :return: None
"""
row['status'] = UserImportUtil.normalize_value('status', row['status'])
@@ -613,7 +624,7 @@ async def batch_import_user_services(
dept_data_scope_sql: ColumnElement,
) -> CrudResponseModel:
"""
- 批量导入用户service
+ 批量导入用户service。
:param request: Request对象
:param query_db: orm对象
@@ -623,6 +634,8 @@ async def batch_import_user_services(
:param user_data_scope_sql: 用户数据权限sql
:param dept_data_scope_sql: 部门数据权限sql
:return: 批量导入用户结果
+ :raises ServiceException: 导入文件为空
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
contents = await file.read()
await file.close()
@@ -728,7 +741,7 @@ async def batch_import_user_services(
@staticmethod
async def get_user_import_template_services() -> bytes:
"""
- 获取用户导入模板service
+ 获取用户导入模板service。
:return: 用户导入模板excel的二进制数据
"""
@@ -769,7 +782,7 @@ async def get_user_import_template_services() -> bytes:
@staticmethod
async def export_user_list_services(user_list: list) -> bytes:
"""
- 导出用户信息service
+ 导出用户信息service。
:param user_list: 用户信息列表
:return: 用户信息对应excel的二进制数据
@@ -812,7 +825,7 @@ async def get_user_role_allocated_list_services(
cls, query_db: AsyncSession, page_object: UserRoleQueryModel
) -> UserRoleResponseModel:
"""
- 根据用户id获取已分配角色列表
+ 根据用户id获取已分配角色列表。
:param query_db: orm对象
:param page_object: 用户关联角色对象
@@ -844,12 +857,14 @@ async def add_user_role_services(
cls, query_db: AsyncSession, page_object: CrudUserRoleModel, actor: str | None = None
) -> CrudResponseModel:
"""
- 新增用户关联角色信息service
+ 新增用户关联角色信息service。
:param query_db: orm对象
:param page_object: 新增用户关联角色对象
:param actor: 实际执行角色分配的操作者
:return: 新增用户关联角色校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 不满足新增条件
"""
if page_object.user_id and page_object.role_ids:
role_id_list = page_object.role_ids.split(',')
@@ -915,12 +930,14 @@ async def delete_user_role_services(
cls, query_db: AsyncSession, page_object: CrudUserRoleModel, actor: str | None = None
) -> CrudResponseModel:
"""
- 删除用户关联角色信息service
+ 删除用户关联角色信息service。
:param query_db: orm对象
:param page_object: 删除用户关联角色对象
:param actor: 实际执行取消分配的操作者
:return: 删除用户关联角色校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 不满足删除条件;传入用户角色关联信息为空
"""
if (page_object.user_id and page_object.role_id) or (page_object.user_ids and page_object.role_id):
if page_object.user_id and page_object.role_id:
@@ -972,7 +989,7 @@ async def delete_user_role_services(
@classmethod
async def detail_user_role_services(cls, query_db: AsyncSession, page_object: UserRoleModel) -> SysUserRole | None:
"""
- 获取用户关联角色详细信息service
+ 获取用户关联角色详细信息service。
:param query_db: orm对象
:param page_object: 用户关联角色对象
diff --git a/ruoyi-fastapi-backend/module_generator/controller/gen_controller.py b/ruoyi-fastapi-backend/module_generator/controller/gen_controller.py
index 08a40806d..c83f66c65 100644
--- a/ruoyi-fastapi-backend/module_generator/controller/gen_controller.py
+++ b/ruoyi-fastapi-backend/module_generator/controller/gen_controller.py
@@ -37,6 +37,7 @@
@gen_controller.get(
'/dataSources',
summary='获取代码生成数据源选项接口',
+ description='列出可用于代码生成的数据源名称、数据库类型,并标明默认数据源。',
response_model=DataResponseModel[list[GenDataSourceModel]],
dependencies=[UserInterfaceAuthDependency('tool:gen:list')],
)
diff --git a/ruoyi-fastapi-backend/module_generator/dao/gen_dao.py b/ruoyi-fastapi-backend/module_generator/dao/gen_dao.py
index e26ae0471..68d84e166 100644
--- a/ruoyi-fastapi-backend/module_generator/dao/gen_dao.py
+++ b/ruoyi-fastapi-backend/module_generator/dao/gen_dao.py
@@ -25,8 +25,17 @@
@dataclass(frozen=True, slots=True)
class DatabaseMetadataAdapter:
- """元数据时间单独定义:MySQL 的目录时间按连接会话时区返回(连接工厂固定 UTC);
+ """
+ 定义数据库元数据查询和时间字段。
+
+ MySQL 的目录时间按连接会话时区返回(连接工厂固定 UTC)。
PostgreSQL 不提供表创建时间,list_table 返回 NULL,不能用查询时刻冒充。
+
+ :ivar table_list_query: 枚举数据库表时执行的查询
+ :ivar tables_by_name_query: 按名称筛选数据库表的查询
+ :ivar columns_query: 读取数据库列定义的查询
+ :ivar created_after_filter: 按创建时间下界筛选的条件
+ :ivar created_before_filter: 按创建时间上界筛选的条件
"""
table_list_query: str
@@ -125,10 +134,11 @@ class DatabaseMetadataAdapter:
def _get_database_metadata_adapter(db_type: str) -> DatabaseMetadataAdapter:
"""
- 根据数据库类型获取元数据查询适配器
+ 根据数据库类型获取元数据查询适配器。
:param db_type: 数据库类型
:return: 元数据查询适配器
+ :raises ValueError: 当前数据库类型没有元数据查询适配器
"""
try:
return _METADATA_ADAPTERS[db_type]
@@ -137,14 +147,12 @@ def _get_database_metadata_adapter(db_type: str) -> DatabaseMetadataAdapter:
class GenTableDao:
- """
- 代码生成业务表模块数据库操作层
- """
+ """代码生成业务表模块数据库操作层。"""
@classmethod
async def get_gen_table_by_id(cls, db: AsyncSession, table_id: int) -> GenTable | None:
"""
- 根据业务表id获取需要生成的业务表信息
+ 根据业务表id获取需要生成的业务表信息。
:param db: orm对象
:param table_id: 业务表id
@@ -165,7 +173,7 @@ async def get_gen_table_by_id(cls, db: AsyncSession, table_id: int) -> GenTable
@classmethod
async def get_gen_table_by_name(cls, db: AsyncSession, table_name: str, source_name: str) -> GenTable | None:
"""
- 根据业务表名称获取需要生成的业务表信息
+ 根据业务表名称获取需要生成的业务表信息。
:param db: orm对象
:param table_name: 业务表名称
@@ -192,7 +200,7 @@ async def get_gen_table_by_name(cls, db: AsyncSession, table_name: str, source_n
@classmethod
async def get_gen_table_all(cls, db: AsyncSession, source_name: str | None = None) -> Sequence[GenTable]:
"""
- 获取所有业务表信息
+ 获取所有业务表信息。
:param db: orm对象
:param source_name: 数据源名称
@@ -210,12 +218,11 @@ async def create_table_by_sql_dao(
cls, db: AsyncSession, sql_statements: list[Expression], *, source_config: DataSourceSettings
) -> None:
"""
- 根据sql语句创建表结构
+ 根据sql语句创建表结构。
:param db: orm对象
:param sql_statements: sql语句的ast列表
:param source_config: 目标数据源配置
- :return:
"""
for sql_statement in sql_statements:
sql = sql_statement.sql(dialect=source_config.sqlglot_parse_dialect)
@@ -226,7 +233,7 @@ async def get_gen_table_list(
cls, db: AsyncSession, query_object: GenTablePageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取代码生成业务表列表信息
+ 根据查询参数获取代码生成业务表列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -259,7 +266,7 @@ async def get_gen_table_list(
@classmethod
async def get_gen_table_names(cls, db: AsyncSession, source_name: str | None = None) -> set[str]:
"""
- 获取控制库中指定数据源已导入的业务表名称
+ 获取控制库中指定数据源已导入的业务表名称。
:param db: orm对象
:param source_name: 数据源名称
@@ -281,7 +288,7 @@ async def get_gen_db_table_list(
source_config: DataSourceSettings | None = None,
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取数据库列表信息
+ 根据查询参数获取数据库列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -289,6 +296,7 @@ async def get_gen_db_table_list(
:param excluded_table_names: 需要排除的已导入表名称集合
:param source_config: 目标数据源配置
:return: 数据库列表信息对象
+ :raises ServiceWarning: PostgreSQL 系统目录不记录建表时间,请清除建表日期筛选
"""
source_config = source_config or DataBaseConfig.default_source
metadata = _get_database_metadata_adapter(source_config.db_type)
@@ -335,7 +343,7 @@ async def get_gen_db_table_list_by_names(
cls, db: AsyncSession, table_names: list[str], source_config: DataSourceSettings | None = None
) -> Sequence[Row]:
"""
- 根据业务表名称组获取数据库列表信息
+ 根据业务表名称组获取数据库列表信息。
:param db: orm对象
:param table_names: 业务表名称组
@@ -352,11 +360,11 @@ async def get_gen_db_table_list_by_names(
@classmethod
async def add_gen_table_dao(cls, db: AsyncSession, gen_table: GenTableModel) -> GenTable:
"""
- 新增业务表数据库操作
+ 新增业务表数据库操作。
:param db: orm对象
:param gen_table: 业务表对象
- :return:
+ :return: 新增的生成表记录
"""
db_gen_table = GenTable(
**GenTableBaseModel(
@@ -371,11 +379,10 @@ async def add_gen_table_dao(cls, db: AsyncSession, gen_table: GenTableModel) ->
@classmethod
async def edit_gen_table_dao(cls, db: AsyncSession, gen_table: dict) -> None:
"""
- 编辑业务表数据库操作
+ 编辑业务表数据库操作。
:param db: orm对象
:param gen_table: 需要更新的业务表字典
- :return:
"""
await db.execute(
update(GenTable),
@@ -385,24 +392,21 @@ async def edit_gen_table_dao(cls, db: AsyncSession, gen_table: dict) -> None:
@classmethod
async def delete_gen_table_dao(cls, db: AsyncSession, gen_table: GenTableModel) -> None:
"""
- 删除业务表数据库操作
+ 删除业务表数据库操作。
:param db: orm对象
:param gen_table: 业务表对象
- :return:
"""
await db.execute(delete(GenTable).where(GenTable.table_id.in_([gen_table.table_id])))
class GenTableColumnDao:
- """
- 代码生成业务表字段模块数据库操作层
- """
+ """代码生成业务表字段模块数据库操作层。"""
@classmethod
async def get_gen_table_column_list_by_table_id(cls, db: AsyncSession, table_id: int) -> GenTableColumn:
"""
- 根据业务表id获取需要生成的业务表字段列表信息
+ 根据业务表id获取需要生成的业务表字段列表信息。
:param db: orm对象
:param table_id: 业务表id
@@ -425,7 +429,7 @@ async def get_gen_db_table_columns_by_name(
cls, db: AsyncSession, table_name: str, source_config: DataSourceSettings | None = None
) -> Sequence[Row]:
"""
- 根据业务表名称获取业务表字段列表信息
+ 根据业务表名称获取业务表字段列表信息。
:param db: orm对象
:param table_name: 业务表名称
@@ -442,11 +446,11 @@ async def get_gen_db_table_columns_by_name(
@classmethod
async def add_gen_table_column_dao(cls, db: AsyncSession, gen_table_column: GenTableColumnModel) -> GenTableColumn:
"""
- 新增业务表字段数据库操作
+ 新增业务表字段数据库操作。
:param db: orm对象
:param gen_table_column: 岗位对象
- :return:
+ :return: 新增的生成表列记录
"""
db_gen_table_column = GenTableColumn(
**GenTableColumnBaseModel(
@@ -461,11 +465,10 @@ async def add_gen_table_column_dao(cls, db: AsyncSession, gen_table_column: GenT
@classmethod
async def edit_gen_table_column_dao(cls, db: AsyncSession, gen_table_column: dict) -> None:
"""
- 编辑业务表字段数据库操作
+ 编辑业务表字段数据库操作。
:param db: orm对象
:param gen_table_column: 需要更新的业务表字段字典
- :return:
"""
await db.execute(
update(GenTableColumn),
@@ -477,11 +480,10 @@ async def delete_gen_table_column_by_table_id_dao(
cls, db: AsyncSession, gen_table_column: GenTableColumnModel
) -> None:
"""
- 通过业务表id删除业务表字段数据库操作
+ 通过业务表id删除业务表字段数据库操作。
:param db: orm对象
:param gen_table_column: 业务表字段对象
- :return:
"""
await db.execute(delete(GenTableColumn).where(GenTableColumn.table_id.in_([gen_table_column.table_id])))
@@ -490,10 +492,9 @@ async def delete_gen_table_column_by_column_id_dao(
cls, db: AsyncSession, gen_table_column: GenTableColumnModel
) -> None:
"""
- 通过业务字段id删除业务表字段数据库操作
+ 通过业务字段id删除业务表字段数据库操作。
:param db: orm对象
- :param post: 业务表字段对象
- :return:
+ :param gen_table_column: 业务表字段对象
"""
await db.execute(delete(GenTableColumn).where(GenTableColumn.column_id.in_([gen_table_column.column_id])))
diff --git a/ruoyi-fastapi-backend/module_generator/entity/do/gen_do.py b/ruoyi-fastapi-backend/module_generator/entity/do/gen_do.py
index 5b16e000a..e3386038d 100644
--- a/ruoyi-fastapi-backend/module_generator/entity/do/gen_do.py
+++ b/ruoyi-fastapi-backend/module_generator/entity/do/gen_do.py
@@ -8,9 +8,7 @@
class GenTable(AuditTimeMixin, Base):
- """
- 代码生成业务表
- """
+ """代码生成业务表。"""
__tablename__ = 'gen_table'
__table_args__ = {'comment': '代码生成业务表'}
@@ -65,9 +63,7 @@ class GenTable(AuditTimeMixin, Base):
class GenTableColumn(AuditTimeMixin, Base):
- """
- 代码生成业务表字段
- """
+ """代码生成业务表字段。"""
__tablename__ = 'gen_table_column'
__table_args__ = {'comment': '代码生成业务表字段'}
diff --git a/ruoyi-fastapi-backend/module_generator/entity/vo/gen_vo.py b/ruoyi-fastapi-backend/module_generator/entity/vo/gen_vo.py
index eb81bd434..b4e71b93c 100644
--- a/ruoyi-fastapi-backend/module_generator/entity/vo/gen_vo.py
+++ b/ruoyi-fastapi-backend/module_generator/entity/vo/gen_vo.py
@@ -12,9 +12,7 @@
class GenTableBaseModel(BaseModel):
- """
- 代码生成业务表对应pydantic模型
- """
+ """代码生成业务表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -44,51 +42,92 @@ class GenTableBaseModel(BaseModel):
@NotBlank(field_name='table_name', message=I18nMessage('表名称不能为空', msg_key='validation.tableNameRequired'))
def get_table_name(self) -> str | None:
+ """
+ 校验并返回表名称。
+
+ :return: 表名称
+ """
return self.table_name
@NotBlank(
field_name='table_comment', message=I18nMessage('表描述不能为空', msg_key='validation.tableCommentRequired')
)
def get_table_comment(self) -> str | None:
+ """
+ 校验并返回表描述。
+
+ :return: 表描述
+ """
return self.table_comment
@NotBlank(
field_name='class_name', message=I18nMessage('实体类名称不能为空', msg_key='validation.classNameRequired')
)
def get_class_name(self) -> str | None:
+ """
+ 校验并返回实体类名称。
+
+ :return: 实体类名称
+ """
return self.class_name
@NotBlank(
field_name='package_name', message=I18nMessage('生成包路径不能为空', msg_key='validation.packageNameRequired')
)
def get_package_name(self) -> str | None:
+ """
+ 校验并返回生成包路径。
+
+ :return: 生成包路径
+ """
return self.package_name
@NotBlank(
field_name='module_name', message=I18nMessage('生成模块名不能为空', msg_key='validation.moduleNameRequired')
)
def get_module_name(self) -> str | None:
+ """
+ 校验并返回生成模块名。
+
+ :return: 生成模块名
+ """
return self.module_name
@NotBlank(
field_name='business_name', message=I18nMessage('生成业务名不能为空', msg_key='validation.businessNameRequired')
)
def get_business_name(self) -> str | None:
+ """
+ 校验并返回生成业务名。
+
+ :return: 生成业务名
+ """
return self.business_name
@NotBlank(
field_name='function_name', message=I18nMessage('生成功能名不能为空', msg_key='validation.functionNameRequired')
)
def get_function_name(self) -> str | None:
+ """
+ 校验并返回生成功能名。
+
+ :return: 生成功能名
+ """
return self.function_name
@NotBlank(
field_name='function_author', message=I18nMessage('生成功能作者不能为空', msg_key='validation.authorRequired')
)
def get_function_author(self) -> str | None:
+ """
+ 校验并返回生成功能作者。
+
+ :return: 生成功能作者
+ """
return self.function_author
def validate_fields(self) -> None:
+ """校验代码生成所需的表名、模型命名、包名和作者等字段。"""
self.get_table_name()
self.get_table_comment()
self.get_class_name()
@@ -100,17 +139,13 @@ def validate_fields(self) -> None:
class GenTableRowModel(GenTableBaseModel):
- """
- 代码生成业务表行数据模型
- """
+ """代码生成业务表行数据模型。"""
columns: list['GenTableColumnBaseModel'] | None = Field(default=None, description='表列信息')
class GenTableDbRowModel(BaseModel):
- """
- 代码生成业务表数据库行数据模型
- """
+ """代码生成业务表数据库行数据模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -121,21 +156,17 @@ class GenTableDbRowModel(BaseModel):
class GenDataSourceModel(BaseModel):
- """
- 代码生成数据源选项模型
- """
+ """代码生成数据源选项模型。"""
model_config = ConfigDict(alias_generator=to_camel)
- name: str
+ name: str = Field(description='数据源名称')
db_type: str = Field(description='数据库类型')
- is_default: bool = False
+ is_default: bool = Field(default=False, description='是否为默认数据源')
class GenTableModel(GenTableBaseModel):
- """
- 代码生成业务表模型
- """
+ """代码生成业务表模型。"""
pk_column: Optional['GenTableColumnModel'] = Field(default=None, description='主键信息')
sub_table: Optional['GenTableModel'] = Field(default=None, description='子表信息')
@@ -152,6 +183,11 @@ class GenTableModel(GenTableBaseModel):
@model_validator(mode='after')
def check_some_is(self) -> 'GenTableModel':
+ """
+ 按模板类别补全生成表的主子表和树表标志。
+
+ :return: 当前实例
+ """
self.sub = bool(self.tpl_category and self.tpl_category == GenConstant.TPL_SUB)
self.tree = bool(self.tpl_category and self.tpl_category == GenConstant.TPL_TREE)
self.crud = bool(self.tpl_category and self.tpl_category == GenConstant.TPL_CRUD)
@@ -159,17 +195,13 @@ def check_some_is(self) -> 'GenTableModel':
class EditGenTableModel(GenTableModel):
- """
- 修改代码生成业务表模型
- """
+ """修改代码生成业务表模型。"""
params: Optional['GenTableParamsModel'] = Field(default=None, description='业务表参数')
class GenTableParamsModel(BaseModel):
- """
- 代码生成业务表参数模型
- """
+ """代码生成业务表参数模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -188,27 +220,21 @@ class GenTableParamsModel(BaseModel):
class GenTableQueryModel(DateRangeQueryMixin, GenTableBaseModel):
- """
- 代码生成业务表不分页查询模型
- """
+ """代码生成业务表不分页查询模型。"""
begin_time: str | None = Field(default=None, description='开始时间')
end_time: str | None = Field(default=None, description='结束时间')
class GenTablePageQueryModel(GenTableQueryModel):
- """
- 代码生成业务表分页查询模型
- """
+ """代码生成业务表分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class GenTableDetailModel(BaseModel):
- """
- 代码生成业务表详情模型
- """
+ """代码生成业务表详情模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -218,9 +244,7 @@ class GenTableDetailModel(BaseModel):
class DeleteGenTableModel(BaseModel):
- """
- 删除代码生成业务表模型
- """
+ """删除代码生成业务表模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -228,9 +252,7 @@ class DeleteGenTableModel(BaseModel):
class GenTableColumnBaseModel(BaseModel):
- """
- 代码生成业务表字段对应pydantic模型
- """
+ """代码生成业务表字段对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -264,16 +286,20 @@ class GenTableColumnBaseModel(BaseModel):
field_name='python_field', message=I18nMessage('Python属性不能为空', msg_key='validation.pythonFieldRequired')
)
def get_python_field(self) -> str | None:
+ """
+ 校验并返回PYTHON字段名。
+
+ :return: PYTHON字段名
+ """
return self.python_field
def validate_fields(self) -> None:
+ """校验PYTHON字段名。"""
self.get_python_field()
class GenTableColumnModel(GenTableColumnBaseModel):
- """
- 代码生成业务表字段模型
- """
+ """代码生成业务表字段模型。"""
cap_python_field: str | None = Field(default=None, description='字段大写形式')
pk: bool | None = Field(default=None, description='是否主键')
@@ -286,11 +312,16 @@ class GenTableColumnModel(GenTableColumnBaseModel):
query: bool | None = Field(default=None, description='是否查询字段')
super_column: bool | None = Field(default=None, description='是否为基类字段')
usable_column: bool | None = Field(default=None, description='是否为基类字段白名单')
- time_kind: str | None = Field(default=None, exclude=True)
- vo_type: str | None = Field(default=None, exclude=True)
+ time_kind: str | None = Field(default=None, exclude=True, description='列表示的时间语义')
+ vo_type: str | None = Field(default=None, exclude=True, description='生成的 Pydantic 模型使用的字段类型')
@model_validator(mode='after')
def check_some_is(self) -> 'GenTableModel':
+ """
+ 根据数据库列配置计算生成模板使用的字段标志。
+
+ :return: 当前实例
+ """
self.cap_python_field = self.python_field[0].upper() + self.python_field[1:] if self.python_field else None
self.pk = self.is_pk and self.is_pk == '1'
self.increment = bool(self.is_increment and self.is_increment == '1')
@@ -310,27 +341,21 @@ def check_some_is(self) -> 'GenTableModel':
class GenTableColumnQueryModel(DateRangeQueryMixin, GenTableColumnBaseModel):
- """
- 代码生成业务表字段不分页查询模型
- """
+ """代码生成业务表字段不分页查询模型。"""
begin_time: str | None = Field(default=None, description='开始时间')
end_time: str | None = Field(default=None, description='结束时间')
class GenTableColumnPageQueryModel(GenTableColumnQueryModel):
- """
- 代码生成业务表字段分页查询模型
- """
+ """代码生成业务表字段分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class DeleteGenTableColumnModel(BaseModel):
- """
- 删除代码生成业务表字段模型
- """
+ """删除代码生成业务表字段模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/module_generator/service/gen_service.py b/ruoyi-fastapi-backend/module_generator/service/gen_service.py
index 8eee539df..615749f2a 100644
--- a/ruoyi-fastapi-backend/module_generator/service/gen_service.py
+++ b/ruoyi-fastapi-backend/module_generator/service/gen_service.py
@@ -32,14 +32,12 @@
class GenTableService:
- """
- 代码生成业务表服务层
- """
+ """代码生成业务表服务层。"""
@classmethod
def get_data_source_list_services(cls) -> list[GenDataSourceModel]:
"""
- 获取代码生成可用的数据源列表
+ 获取代码生成可用的数据源列表。
:return: 数据源选项列表
"""
@@ -52,7 +50,7 @@ def get_data_source_list_services(cls) -> list[GenDataSourceModel]:
@staticmethod
def _source_name(source_name: str | None) -> str:
"""
- 获取代码生成操作使用的数据源名称
+ 获取代码生成操作使用的数据源名称。
:param source_name: 数据源名称
:return: 指定的数据源名称或默认数据源名称
@@ -64,7 +62,7 @@ async def get_gen_table_list_services(
cls, query_db: AsyncSession, query_object: GenTablePageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 获取代码生成业务表列表信息service
+ 获取代码生成业务表列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -83,7 +81,7 @@ async def get_gen_db_table_list_services(
is_page: bool = False,
) -> PageModel | list[dict[str, Any]]:
"""
- 获取数据库列表信息service
+ 获取数据库列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -108,7 +106,7 @@ async def get_gen_db_table_list_by_name_services(
cls, query_db: AsyncSession, table_names: list[str], source_name: str | None = None
) -> list[GenTableModel]:
"""
- 根据表名称组获取数据库列表信息service
+ 根据表名称组获取数据库列表信息service。
:param query_db: orm对象
:param table_names: 表名称组
@@ -133,12 +131,13 @@ async def import_gen_table_services(
current_user: CurrentUserModel,
) -> CrudResponseModel:
"""
- 导入表结构service
+ 导入表结构service。
:param query_db: orm对象
:param gen_table_list: 导入表列表
:param current_user: 当前用户信息对象
:return: 导入结果
+ :raises ServiceException: 导入表结构失败
"""
source_name = cls._source_name(gen_table_list[0].data_source_name if gen_table_list else None)
source_config = DataBaseConfig.get_source(source_name)
@@ -169,11 +168,13 @@ async def import_gen_table_services(
@classmethod
async def edit_gen_table_services(cls, query_db: AsyncSession, page_object: EditGenTableModel) -> CrudResponseModel:
"""
- 编辑业务表信息service
+ 编辑业务表信息service。
:param query_db: orm对象
:param page_object: 编辑业务表对象
:return: 编辑业务表校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 业务表不存在
"""
edit_gen_table = page_object.model_dump(
exclude_unset=True,
@@ -211,11 +212,13 @@ async def delete_gen_table_services(
cls, query_db: AsyncSession, page_object: DeleteGenTableModel
) -> CrudResponseModel:
"""
- 删除业务表信息service
+ 删除业务表信息service。
:param query_db: orm对象
:param page_object: 删除业务表对象
:return: 删除业务表校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入业务表id为空
"""
if page_object.table_ids:
table_id_list = page_object.table_ids.split(',')
@@ -236,7 +239,7 @@ async def delete_gen_table_services(
@classmethod
async def get_gen_table_by_id_services(cls, query_db: AsyncSession, table_id: int) -> GenTableModel:
"""
- 获取需要生成的业务表详细信息service
+ 获取需要生成的业务表详细信息service。
:param query_db: orm对象
:param table_id: 需要生成的业务表id
@@ -252,7 +255,7 @@ async def get_gen_table_all_services(
cls, query_db: AsyncSession, source_name: str | None = None
) -> list[GenTableModel]:
"""
- 获取所有业务表信息service
+ 获取所有业务表信息service。
:param query_db: orm对象
:param source_name: 数据源名称
@@ -268,13 +271,14 @@ async def create_table_services(
cls, query_db: AsyncSession, sql: str, current_user: CurrentUserModel, source_name: str | None = None
) -> CrudResponseModel:
"""
- 创建表结构service
+ 创建表结构service。
:param query_db: orm对象
:param sql: 建表语句
:param current_user: 当前用户信息对象
:param source_name: 数据源名称
:return: 创建表结构结果
+ :raises ServiceException: 建表语句不合法
"""
source_name = cls._source_name(source_name)
target_config = DataBaseConfig.get_source(source_name)
@@ -301,7 +305,7 @@ async def create_table_services(
@classmethod
def __is_valid_create_table(cls, sql_statements: list[Expression]) -> bool:
"""
- 校验sql语句是否为合法的建表语句
+ 校验sql语句是否为合法的建表语句。
:param sql_statements: sql语句的ast列表
:return: 校验结果
@@ -319,7 +323,7 @@ def __is_valid_create_table(cls, sql_statements: list[Expression]) -> bool:
@classmethod
def __get_table_names(cls, sql_statements: list[Expression]) -> list[str]:
"""
- 获取sql语句中所有的建表表名
+ 获取sql语句中所有的建表表名。
:param sql_statements: sql语句的ast列表
:return: 建表表名列表
@@ -333,7 +337,7 @@ def __get_table_names(cls, sql_statements: list[Expression]) -> list[str]:
@classmethod
async def preview_code_services(cls, query_db: AsyncSession, table_id: int) -> dict[str, str]:
"""
- 预览代码service
+ 预览代码service。
:param query_db: orm对象
:param table_id: 业务表id
@@ -359,12 +363,14 @@ async def generate_code_services(
cls, query_db: AsyncSession, table_name: str, source_name: str | None = None
) -> CrudResponseModel:
"""
- 生成代码至指定路径service
+ 生成代码至指定路径service。
:param query_db: orm对象
:param table_name: 业务表名称
:param source_name: 数据源名称
:return: 生成代码结果
+ :raises ServiceWarning: 代码生成过程中需要向调用方传递业务提示
+ :raises ServiceException: 渲染业务表模板失败
"""
source_name = cls._source_name(source_name)
env = TemplateInitializer.init_jinja2()
@@ -401,12 +407,13 @@ async def batch_gen_code_services(
cls, query_db: AsyncSession, table_names: list[str], source_name: str | None = None
) -> bytes:
"""
- 批量生成代码service
+ 批量生成代码service。
:param query_db: orm对象
:param table_names: 业务表名称组
:param source_name: 数据源名称
:return: 下载代码结果
+ :raises ServiceException: 业务表不存在或不属于本次指定的数据源
"""
source_name = cls._source_name(source_name)
configured_table_names = await GenTableDao.get_gen_table_names(query_db, source_name)
@@ -442,7 +449,7 @@ async def batch_gen_code_services(
@classmethod
def __render_files(cls, env: Any, render_info: list) -> dict[str, str]:
"""
- 渲染源码后收集模板登记的独立语言资源
+ 渲染源码后收集模板登记的独立语言资源。
:param env: 模板环境
:param render_info: 模板、输出路径、上下文和业务表
@@ -460,11 +467,12 @@ def __render_files(cls, env: Any, render_info: list) -> dict[str, str]:
@staticmethod
def __get_output_path(output_root: Path, relative_path: str) -> Path:
"""
- 校验已有符号链接和生成文件始终位于独立生成目录内
+ 校验已有符号链接和生成文件始终位于独立生成目录内。
:param output_root: 独立生成目录
:param relative_path: 生成文件的相对路径
:return: 已校验的输出路径
+ :raises ServiceWarning: 请选择独立生成目录,不能直接覆盖应用源码目录
"""
resolved = (output_root / relative_path).resolve()
if not resolved.is_relative_to(output_root.resolve()):
@@ -477,10 +485,11 @@ def __get_output_path(output_root: Path, relative_path: str) -> Path:
@staticmethod
def __get_output_root(gen_table: GenTableModel) -> Path:
"""
- 保持生成路径为独立生成包根,拒绝直接覆盖已知应用源码
+ 保持生成路径为独立生成包根,拒绝直接覆盖已知应用源码。
:param gen_table: 生成配置
:return: 独立生成目录
+ :raises ServiceWarning: 请选择独立生成目录,不能直接覆盖应用源码目录
"""
root = (
Path(os.getcwd(), GenConfig.GEN_PATH) if gen_table.gen_path in (None, '', '/') else Path(gen_table.gen_path)
@@ -502,12 +511,13 @@ async def __get_gen_render_info(
cls, query_db: AsyncSession, table_name: str, source_name: str | None = None
) -> list:
"""
- 获取生成代码渲染模板相关信息
+ 获取生成代码渲染模板相关信息。
:param query_db: orm对象
:param table_name: 业务表名称
:param source_name: 数据源名称
:return: 生成代码渲染模板相关信息
+ :raises ServiceException: 目标表不存在或不属于选中的数据源
"""
gen_table_info = await GenTableDao.get_gen_table_by_name(query_db, table_name, source_name)
if gen_table_info is None:
@@ -528,7 +538,7 @@ async def __get_gen_render_info(
@classmethod
def __get_gen_path(cls, gen_table: GenTableModel, template: str) -> str:
"""
- 根据GenTableModel对象和模板名称生成路径
+ 根据GenTableModel对象和模板名称生成路径。
:param gen_table: GenTableModel对象
:param template: 模板名称
@@ -545,12 +555,14 @@ async def sync_db_services(
cls, query_db: AsyncSession, table_name: str, source_name: str | None = None
) -> CrudResponseModel:
"""
- 同步数据库service
+ 同步数据库service。
:param query_db: orm对象
:param table_name: 业务表名称
:param source_name: 数据源名称
:return: 同步数据库结果
+ :raises ServiceException: 同步数据失败,原表结构不存在
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
source_name = cls._source_name(source_name)
gen_table = await GenTableDao.get_gen_table_by_name(query_db, table_name, source_name)
@@ -601,11 +613,10 @@ async def sync_db_services(
@classmethod
async def set_sub_table(cls, query_db: AsyncSession, gen_table: GenTableModel) -> None:
"""
- 设置主子表信息
+ 设置主子表信息。
:param query_db: orm对象
:param gen_table: 业务表信息
- :return:
"""
if gen_table.sub_table_name:
sub_table = await GenTableDao.get_gen_table_by_name(
@@ -618,10 +629,9 @@ async def set_sub_table(cls, query_db: AsyncSession, gen_table: GenTableModel) -
@classmethod
async def set_pk_column(cls, gen_table: GenTableModel) -> None:
"""
- 设置主键列信息
+ 设置主键列信息。
:param gen_table: 业务表信息
- :return:
"""
for column in gen_table.columns:
if column.pk:
@@ -640,7 +650,7 @@ async def set_pk_column(cls, gen_table: GenTableModel) -> None:
@classmethod
async def set_table_from_options(cls, gen_table: GenTableModel) -> GenTableModel:
"""
- 设置代码生成其他选项值
+ 设置代码生成其他选项值。
:param gen_table: 生成对象
:return: 设置后的生成对象
@@ -659,9 +669,10 @@ async def set_table_from_options(cls, gen_table: GenTableModel) -> GenTableModel
@classmethod
async def validate_edit(cls, edit_gen_table: EditGenTableModel) -> None:
"""
- 编辑保存参数校验
+ 编辑保存参数校验。
:param edit_gen_table: 编辑业务表对象
+ :raises ServiceException: 树编码字段不能为空;树父编码字段不能为空;树名称字段不能为空;关联子表的表名不能为空;子表关联的外键名不能为空
"""
if edit_gen_table.tpl_category == GenConstant.TPL_TREE:
params_obj = edit_gen_table.params.model_dump(by_alias=True)
@@ -682,16 +693,14 @@ async def validate_edit(cls, edit_gen_table: EditGenTableModel) -> None:
class GenTableColumnService:
- """
- 代码生成业务表字段服务层
- """
+ """代码生成业务表字段服务层。"""
@classmethod
async def get_gen_table_column_list_by_table_id_services(
cls, query_db: AsyncSession, table_id: int
) -> list[GenTableColumnModel]:
"""
- 获取业务表字段列表信息service
+ 获取业务表字段列表信息service。
:param query_db: orm对象
:param table_id: 业务表格id
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/dao.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/dao.py.jinja2
index 4fec4b567..8f8c926b4 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/dao.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/dao.py.jinja2
@@ -64,17 +64,15 @@ from utils.time_util import TimezoneUtil
class {{ BusinessName }}Dao:
- """
- {{ functionName }}模块数据库操作层
- """
+ """{{ functionName }}模块数据库操作层。"""
@classmethod
async def get_{{ businessName }}_detail_by_id(cls, db: AsyncSession, {{ pk_field }}: int) -> {{ ClassName }} | None:
"""
- 根据{{ pk_field_comment }}获取{{ functionName }}详细信息
+ 根据{{ pk_field_comment }}获取{{ functionName }}详细信息。
:param db: orm对象
- :param {{ pk_field }}: {{ pk_field_comment }}
+ :param {{ pk_field }}: 待查询的主键({{ pk_field_comment }})
:return: {{ functionName }}信息对象
"""
{{ businessName }}_info = (
@@ -100,7 +98,7 @@ class {{ BusinessName }}Dao:
@classmethod
async def get_{{ businessName }}_detail_by_info(cls, db: AsyncSession, {{ businessName }}: {{ BusinessName }}Model) -> {{ ClassName }} | None:
"""
- 根据{{ functionName }}参数获取{{ functionName }}信息
+ 根据{{ functionName }}参数获取{{ functionName }}信息。
:param db: orm对象
:param {{ businessName }}: {{ functionName }}参数对象
@@ -129,7 +127,7 @@ class {{ BusinessName }}Dao:
cls, db: AsyncSession, query_object: {{ BusinessName }}PageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取{{ functionName }}列表信息
+ 根据查询参数获取{{ functionName }}列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -191,11 +189,11 @@ class {{ BusinessName }}Dao:
@classmethod
async def add_{{ businessName }}_dao(cls, db: AsyncSession, {{ businessName }}: {{ BusinessName }}Model) -> {{ ClassName }}:
"""
- 新增{{ functionName }}数据库操作
+ 新增{{ functionName }}数据库操作。
:param db: orm对象
:param {{ businessName }}: {{ functionName }}对象
- :return:
+ :return: 新增的{{ functionName }}记录
"""
db_{{ businessName }} = {{ ClassName }}(**{{ businessName }}.model_dump(exclude={% raw %}{{% endraw %}{% for field in add_exclude_fields.fields %}'{{ field }}'{% if not loop.last %}, {% endif %}{% endfor %}{% raw %}}{% endraw %}))
db.add(db_{{ businessName }})
@@ -206,11 +204,10 @@ class {{ BusinessName }}Dao:
@classmethod
async def edit_{{ businessName }}_dao(cls, db: AsyncSession, {{ businessName }}: dict) -> None:
"""
- 编辑{{ functionName }}数据库操作
+ 编辑{{ functionName }}数据库操作。
:param db: orm对象
:param {{ businessName }}: 需要更新的{{ functionName }}字典
- :return:
"""
safe_{{ businessName }} = {
key: value
@@ -221,11 +218,10 @@ class {{ BusinessName }}Dao:
@classmethod
async def delete_{{ businessName }}_dao(cls, db: AsyncSession, {{ businessName }}: {{ BusinessName }}Model) -> None:
"""
- 删除{{ functionName }}数据库操作
+ 删除{{ functionName }}数据库操作。
:param db: orm对象
:param {{ businessName }}: {{ functionName }}对象
- :return:
"""
await db.execute(delete({{ ClassName }}).where({{ ClassName }}.{{ pk_field }}.in_([{{ businessName }}.{{ pk_field }}])))
@@ -233,11 +229,11 @@ class {{ BusinessName }}Dao:
@classmethod
async def add_{{ subTable.business_name }}_dao(cls, db: AsyncSession, {{ subTable.business_name }}: {{ subTable.business_name | capitalize }}Model) -> {{ subClassName }}:
"""
- 新增{{ subTable.function_name }}数据库操作
+ 新增{{ subTable.function_name }}数据库操作。
:param db: orm对象
:param {{ subTable.business_name }}: {{ subTable.function_name }}对象
- :return:
+ :return: 新增的{{ subTable.function_name }}记录
"""
db_{{ subTable.business_name }} = {{ subClassName }}(**{{ subTable.business_name }}.model_dump(exclude={% raw %}{{% endraw %}{% for field in sub_edit_audit_fields.fields %}'{{ field }}'{% if not loop.last %}, {% endif %}{% endfor %}{% raw %}}{% endraw %}))
db.add(db_{{ subTable.business_name }})
@@ -248,11 +244,10 @@ class {{ BusinessName }}Dao:
@classmethod
async def edit_{{ subTable.business_name }}_dao(cls, db: AsyncSession, {{ subTable.business_name }}: dict) -> None:
"""
- 编辑{{ subTable.function_name }}数据库操作
+ 编辑{{ subTable.function_name }}数据库操作。
:param db: orm对象
:param {{ subTable.business_name }}: 需要更新的{{ subTable.function_name }}字典
- :return:
"""
safe_{{ subTable.business_name }} = {
key: value
@@ -263,11 +258,10 @@ class {{ BusinessName }}Dao:
@classmethod
async def delete_{{ subTable.business_name }}_dao(cls, db: AsyncSession, {{ subTable.business_name }}: {{ subTable.business_name | capitalize }}Model) -> None:
"""
- 删除{{ subTable.function_name }}数据库操作
+ 删除{{ subTable.function_name }}数据库操作。
:param db: orm对象
:param {{ subTable.business_name }}: {{ subTable.function_name }}对象
- :return:
"""
await db.execute(delete({{ subClassName }}).where({{ subClassName }}.{{ subTable.pk_column.python_field | camel_to_snake }}.in_([{{ subTable.business_name }}.{{ subTable.pk_column.python_field | camel_to_snake }}])))
{% endif %}
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/do.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/do.py.jinja2
index 78cd1bb99..8747af194 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/do.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/do.py.jinja2
@@ -54,28 +54,26 @@ DataSourceBase = get_data_source_base('{{ dataSourceName }}')
class {{ ClassName }}({% if main_time.create and main_time.update %}AuditTimeMixin, {% elif main_time.create %}CreateTimeMixin, {% elif main_time.update %}UpdateTimeMixin, {% endif %}{% if dataSourceName == defaultDataSourceName %}Base{% else %}DataSourceBase{% endif %}):
- """
- {{ functionName }}表
- """
+ """{{ functionName }}表。"""
__tablename__ = '{{ tableName }}'
- __table_args__ = {'comment': '{{ tableComment }}'}
+ __table_args__ = {'comment': {{ (tableComment or '') | python_literal }}}
{% if main_time.create and (main_time.create.required or main_time.create.pk) %}
__create_time_nullable__ = False
{% endif %}
{% if main_time.create and main_time.create.column_comment != '创建时间' %}
- __create_time_comment__ = '{{ main_time.create.column_comment }}'
+ __create_time_comment__ = {{ main_time.create.column_comment | model_field_label | python_literal }}
{% endif %}
{% if main_time.update and (main_time.update.required or main_time.update.pk) %}
__update_time_nullable__ = False
{% endif %}
{% if main_time.update and main_time.update.column_comment != '更新时间' %}
- __update_time_comment__ = '{{ main_time.update.column_comment }}'
+ __update_time_comment__ = {{ main_time.update.column_comment | model_field_label | python_literal }}
{% endif %}
{% for column in columns %}
{% if not (column.column_name in ["create_time", "update_time"] and column.time_kind == "instant") %}
- {{ column.column_name }} = Column({% if column.time_kind == "instant" %}DbUtcDateTime(){% else %}{{ column.column_type | get_sqlalchemy_type(dataSourceName) }}{% endif %}, {% if column.pk %}primary_key=True, {% endif %}{% if column.increment %}autoincrement=True, {% endif %}{% if column.required or column.pk %}nullable=False{% else %}nullable=True{% endif %}, comment='{{ column.column_comment }}')
+ {{ column.column_name }} = Column({% if column.time_kind == "instant" %}DbUtcDateTime(){% else %}{{ column.column_type | get_sqlalchemy_type(dataSourceName) }}{% endif %}, {% if column.pk %}primary_key=True, {% endif %}{% if column.increment %}autoincrement=True, {% endif %}{% if column.required or column.pk %}nullable=False{% else %}nullable=True{% endif %}, comment={{ column.column_comment | model_field_label | python_literal }})
{% endif %}
{% endfor %}
@@ -86,27 +84,25 @@ class {{ ClassName }}({% if main_time.create and main_time.update %}AuditTimeMix
{% if table.sub %}
class {{ subClassName }}({% if sub_time.create and sub_time.update %}AuditTimeMixin, {% elif sub_time.create %}CreateTimeMixin, {% elif sub_time.update %}UpdateTimeMixin, {% endif %}{% if dataSourceName == defaultDataSourceName %}Base{% else %}DataSourceBase{% endif %}):
- """
- {{ subTable.function_name }}表
- """
+ """{{ subTable.function_name }}表。"""
__tablename__ = '{{ subTableName }}'
{% if sub_time.create and (sub_time.create.required or sub_time.create.pk) %}
__create_time_nullable__ = False
{% endif %}
{% if sub_time.create and sub_time.create.column_comment != '创建时间' %}
- __create_time_comment__ = '{{ sub_time.create.column_comment }}'
+ __create_time_comment__ = {{ sub_time.create.column_comment | model_field_label | python_literal }}
{% endif %}
{% if sub_time.update and (sub_time.update.required or sub_time.update.pk) %}
__update_time_nullable__ = False
{% endif %}
{% if sub_time.update and sub_time.update.column_comment != '更新时间' %}
- __update_time_comment__ = '{{ sub_time.update.column_comment }}'
+ __update_time_comment__ = {{ sub_time.update.column_comment | model_field_label | python_literal }}
{% endif %}
{% for column in subTable.columns %}
{% if not (column.column_name in ["create_time", "update_time"] and column.time_kind == "instant") %}
- {{ column.column_name }} = Column({% if column.time_kind == "instant" %}DbUtcDateTime(){% else %}{{ column.column_type | get_sqlalchemy_type(dataSourceName) }}{% endif %}, {% if column.column_name == subTableFkName %}ForeignKey('{{ tableName }}.{{ pkColumn.column_name }}'), {% endif %}{% if column.pk %}primary_key=True, {% endif %}{% if column.increment %}autoincrement=True, {% endif %}{% if column.required or column.pk %}nullable=False{% else %}nullable=True{% endif %}, comment='{{ column.column_comment }}')
+ {{ column.column_name }} = Column({% if column.time_kind == "instant" %}DbUtcDateTime(){% else %}{{ column.column_type | get_sqlalchemy_type(dataSourceName) }}{% endif %}, {% if column.column_name == subTableFkName %}ForeignKey('{{ tableName }}.{{ pkColumn.column_name }}'), {% endif %}{% if column.pk %}primary_key=True, {% endif %}{% if column.increment %}autoincrement=True, {% endif %}{% if column.required or column.pk %}nullable=False{% else %}nullable=True{% endif %}, comment={{ column.column_comment | model_field_label | python_literal }})
{% endif %}
{% endfor %}
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2
index 3f510a44c..230ade6d6 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2
@@ -27,16 +27,14 @@ from utils.excel_util import ExcelUtil
class {{ BusinessName }}Service:
- """
- {{ functionName }}模块服务层
- """
+ """{{ functionName }}模块服务层。"""
@classmethod
async def get_{{ businessName }}_list_services(
cls, query_db: AsyncSession, query_object: {{ BusinessName }}PageQueryModel, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 获取{{ functionName }}列表信息service
+ 获取{{ functionName }}列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -54,7 +52,7 @@ class {{ BusinessName }}Service:
@classmethod
async def check_{{ column.python_field | camel_to_snake }}_unique_services(cls, query_db: AsyncSession, page_object: {{ BusinessName }}Model) -> bool:
"""
- 检查{{ comment }}是否唯一service
+ 检查{{ comment }}是否唯一service。
:param query_db: orm对象
:param page_object: {{ functionName }}对象
@@ -72,11 +70,15 @@ class {{ BusinessName }}Service:
@classmethod
async def add_{{ businessName }}_services(cls, query_db: AsyncSession, page_object: {{ BusinessName }}Model) -> CrudResponseModel:
"""
- 新增{{ functionName }}信息service
+ 新增{{ functionName }}信息service。
:param query_db: orm对象
:param page_object: 新增{{ functionName }}对象
:return: 新增{{ functionName }}校验结果
+ {% if columns | selectattr('unique') | list %}
+ :raises ServiceException: 唯一字段与已有记录重复
+ {% endif %}
+ :raises Exception: 写入失败,事务回滚后重新抛出原异常
"""
{% for column in columns %}
{% set parentheseIndex = column.column_comment.find("(") %}
@@ -108,11 +110,13 @@ class {{ BusinessName }}Service:
@classmethod
async def edit_{{ businessName }}_services(cls, query_db: AsyncSession, page_object: {{ BusinessName }}Model) -> CrudResponseModel:
"""
- 编辑{{ functionName }}信息service
+ 编辑{{ functionName }}信息service。
:param query_db: orm对象
:param page_object: 编辑{{ functionName }}对象
:return: 编辑{{ functionName }}校验结果
+ :raises ServiceException: 目标记录不存在或唯一字段冲突
+ :raises Exception: 更新失败,事务回滚后重新抛出原异常
"""
edit_{{ businessName }} = page_object.model_dump(exclude_unset=True, exclude={% raw %}{{% endraw %}{% if table.sub %}'{{ subclassName }}_list', {% endif %}{% for column in columns %}{% if not column.edit and not column.pk and column.column_name not in column_not_edit_show %}'{{ column.python_field | camel_to_snake }}'{% if not loop.last %}, {% endif %}{% endif %}{% endfor %}{% raw %}}{% endraw %})
{{ businessName }}_info = await cls.{{ businessName }}_detail_services(query_db, page_object.{{ pk_field }})
@@ -151,11 +155,13 @@ class {{ BusinessName }}Service:
@classmethod
async def delete_{{ businessName }}_services(cls, query_db: AsyncSession, page_object: Delete{{ BusinessName }}Model) -> CrudResponseModel:
"""
- 删除{{ functionName }}信息service
+ 删除{{ functionName }}信息service。
:param query_db: orm对象
:param page_object: 删除{{ functionName }}对象
:return: 删除{{ functionName }}校验结果
+ :raises ServiceException: 缺少待删除记录的主键
+ :raises Exception: 删除失败,事务回滚后重新抛出原异常
"""
if page_object.{{ pk_field }}s:
{{ pk_field }}_list = page_object.{{ pk_field }}s.split(',')
@@ -181,10 +187,10 @@ class {{ BusinessName }}Service:
@classmethod
async def {{ businessName }}_detail_services(cls, query_db: AsyncSession, {{ pk_field }}: int) -> {{ BusinessName }}Model:
"""
- 获取{{ functionName }}详细信息service
+ 获取{{ functionName }}详细信息service。
:param query_db: orm对象
- :param {{ pk_field }}: {{ pk_field_comment }}
+ :param {{ pk_field }}: 待查询的主键({{ pk_field_comment }})
:return: {{ pk_field_comment }}对应的信息
"""
{{ businessName }} = await {{ BusinessName }}Dao.get_{{ businessName }}_detail_by_id(query_db, {{ pk_field }}={{ pk_field }})
@@ -195,8 +201,11 @@ class {{ BusinessName }}Service:
@staticmethod
async def export_{{ businessName }}_list_services({% if dicts %}request: Request, {% endif %}{{ businessName }}_list: list) -> bytes:
"""
- 导出{{ functionName }}信息service
+ 导出{{ functionName }}信息service。
+ {% if dicts %}
+ :param request: 读取字典标签时使用的当前 HTTP 请求
+ {% endif %}
:param {{ businessName }}_list: {{ functionName }}信息列表
:return: {{ functionName }}信息对应excel的二进制数据
"""
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/vo.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/vo.py.jinja2
index 696d13255..092332a03 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/vo.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/vo.py.jinja2
@@ -49,14 +49,12 @@ from common.mixin import GeneratedTimeRangeQueryMixin
{% if table.sub %}
class {{ BusinessName }}BaseModel(BaseModel):
- """
- {{ functionName }}表对应pydantic模型
- """
+ """{{ functionName }}表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
{% for column in columns %}
- {{ column.column_name }}: {{ column.vo_type }} | None = Field(default=None, description={{ column.column_comment | tojson }})
+ {{ column.column_name }}: {{ column.vo_type }} | None = Field(default=None, description={{ column.column_comment | model_field_label | tojson }})
{% endfor %}
{% for column in columns %}
@@ -71,6 +69,11 @@ class {{ BusinessName }}BaseModel(BaseModel):
),
)
def get_{{ column.column_name }}(self) -> {{ column.vo_type }} | None:
+ """
+ 校验必填字段。
+
+ :return: 当前记录的 {{ column.column_name }} 字段值
+ """
return self.{{ column.column_name }}
{% if not loop.last %}{{ "\n" }}{% endif %}
{% endif %}
@@ -78,6 +81,7 @@ class {{ BusinessName }}BaseModel(BaseModel):
{% if vo_field_required.has_required %}
def validate_fields(self) -> None:
+ """校验模型的必填字段。"""
{% for column in columns %}
{% if column.required %}
self.get_{{ column.column_name }}()
@@ -88,14 +92,12 @@ class {{ BusinessName }}BaseModel(BaseModel):
{% endif %}
class {{ BusinessName }}Model({% if table.sub %}{{ BusinessName }}BaseModel{% else %}BaseModel{% endif %}):
- """
- {{ functionName }}表对应pydantic模型
- """
+ """{{ functionName }}表对应pydantic模型。"""
{% if not table.sub %}
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
{% for column in columns %}
- {{ column.column_name }}: {{ column.vo_type }} | None = Field(default=None, description={{ column.column_comment | tojson }})
+ {{ column.column_name }}: {{ column.vo_type }} | None = Field(default=None, description={{ column.column_comment | model_field_label | tojson }})
{% endfor %}
{% endif %}
{% if table.sub %}
@@ -115,6 +117,11 @@ class {{ BusinessName }}Model({% if table.sub %}{{ BusinessName }}BaseModel{% el
),
)
def get_{{ column.column_name }}(self) -> {{ column.vo_type }} | None:
+ """
+ 校验必填字段。
+
+ :return: 当前记录的 {{ column.column_name }} 字段值
+ """
return self.{{ column.column_name }}
{% if not loop.last %}{{ "\n" }}{% endif %}
{% endif %}
@@ -122,6 +129,7 @@ class {{ BusinessName }}Model({% if table.sub %}{{ BusinessName }}BaseModel{% el
{% if vo_field_required.has_required %}
def validate_fields(self) -> None:
+ """校验模型的必填字段。"""
{% for column in columns %}
{% if column.required %}
self.get_{{ column.column_name }}()
@@ -133,14 +141,12 @@ class {{ BusinessName }}Model({% if table.sub %}{{ BusinessName }}BaseModel{% el
{% if table.sub %}
class {{ subTable.business_name | capitalize }}Model(BaseModel):
- """
- {{ subTable.function_name }}表对应pydantic模型
- """
+ """{{ subTable.function_name }}表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
{% for sub_column in subTable.columns %}
- {{ sub_column.column_name }}: {{ sub_column.vo_type }} | None = Field(default=None, description='{{ sub_column.column_comment}}')
+ {{ sub_column.column_name }}: {{ sub_column.vo_type }} | None = Field(default=None, description={{ sub_column.column_comment | model_field_label | tojson }})
{% endfor %}
{% for sub_column in subTable.columns %}
@@ -155,6 +161,11 @@ class {{ subTable.business_name | capitalize }}Model(BaseModel):
),
)
def get_{{ sub_column.column_name }}(self) -> {{ sub_column.vo_type }} | None:
+ """
+ 校验子表的必填字段。
+
+ :return: 子表记录的 {{ sub_column.column_name }} 字段值
+ """
return self.{{ sub_column.column_name }}
{% if not loop.last %}{{ "\n" }}{% endif %}
{% endif %}
@@ -162,6 +173,7 @@ class {{ subTable.business_name | capitalize }}Model(BaseModel):
{% if sub_vo_field_required.has_required %}
def validate_fields(self) -> None:
+ """校验模型的必填字段。"""
{% for sub_column in subTable.columns %}
{% if sub_column.required %}
self.get_{{ sub_column.column_name }}()
@@ -172,9 +184,7 @@ class {{ subTable.business_name | capitalize }}Model(BaseModel):
class {{ BusinessName }}QueryModel({% if vo_field_daterange.has_daterange %}GeneratedTimeRangeQueryMixin, {% endif %}{% if table.sub %}{{ BusinessName }}BaseModel{% else %}{{ BusinessName }}Model{% endif %}):
- """
- {{ functionName }}不分页查询模型
- """
+ """{{ functionName }}不分页查询模型。"""
{% if vo_field_daterange.has_daterange %}
time_range_fields: ClassVar[dict[str, str]] = {
{% for column in columns %}
@@ -186,8 +196,8 @@ class {{ BusinessName }}QueryModel({% if vo_field_daterange.has_daterange %}Gene
{% for column in columns %}
{% if column.time_kind and column.query_type == "BETWEEN" %}
- begin_{{ column.column_name }}: {% if column.time_kind == 'time' %}BusinessTime{% else %}BusinessDate{% endif %} | None = Field(default=None, description='开始{{ column.column_comment }}')
- end_{{ column.column_name }}: {% if column.time_kind == 'time' %}BusinessTime{% else %}BusinessDate{% endif %} | None = Field(default=None, description='结束{{ column.column_comment }}')
+ begin_{{ column.column_name }}: {% if column.time_kind == 'time' %}BusinessTime{% else %}BusinessDate{% endif %} | None = Field(default=None, description={{ ('开始' ~ column.column_comment) | tojson }})
+ end_{{ column.column_name }}: {% if column.time_kind == 'time' %}BusinessTime{% else %}BusinessDate{% endif %} | None = Field(default=None, description={{ ('结束' ~ column.column_comment) | tojson }})
{% endif %}
{% endfor %}
{% else %}
@@ -196,19 +206,15 @@ class {{ BusinessName }}QueryModel({% if vo_field_daterange.has_daterange %}Gene
class {{ BusinessName }}PageQueryModel({{ BusinessName }}QueryModel):
- """
- {{ functionName }}分页查询模型
- """
+ """{{ functionName }}分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class Delete{{ BusinessName }}Model(BaseModel):
- """
- 删除{{ functionName }}模型
- """
+ """删除{{ functionName }}模型。"""
model_config = ConfigDict(alias_generator=to_camel)
- {{ pk_field }}s: str = Field(description='需要删除的{{ pk_field_comment }}')
+ {{ pk_field }}s: str = Field(description={{ ('需要删除的' ~ pk_field_comment) | tojson }})
diff --git a/ruoyi-fastapi-backend/module_identity/controller/authorization_controller.py b/ruoyi-fastapi-backend/module_identity/controller/authorization_controller.py
index f86803dab..deb195b20 100644
--- a/ruoyi-fastapi-backend/module_identity/controller/authorization_controller.py
+++ b/ruoyi-fastapi-backend/module_identity/controller/authorization_controller.py
@@ -50,13 +50,12 @@
def _read_authorization_query(request: Request) -> dict[str, str]:
"""
- 读取并拒绝重复授权 Query 参数
+ 读取并拒绝重复授权 Query 参数。
:param request: 当前 HTTP 请求
:return: 唯一 Query 参数映射
:raises OAuthProtocolException: Query 参数重复时抛出
"""
-
values: dict[str, str] = {}
# 拒绝重复授权参数
for key, value in request.query_params.multi_items():
@@ -68,13 +67,12 @@ def _read_authorization_query(request: Request) -> dict[str, str]:
def _authorization_redis(request: Request) -> Redis:
"""
- 读取应用生命周期创建的 Redis 客户端
+ 读取应用生命周期创建的 Redis 客户端。
:param request: 当前 HTTP 请求
:return: Redis 客户端
:raises OAuthProtocolException: Redis 客户端不可用时抛出
"""
-
redis = getattr(request.app.state, 'redis', None)
if redis is None:
raise OAuthProtocolException('server_error', 'Authorization service is unavailable', 503)
@@ -83,11 +81,10 @@ def _authorization_redis(request: Request) -> Redis:
async def _enforce_authorization_rate_limit(request: Request, redis: Redis) -> None:
"""
- 按 HMAC-IP 固定窗口执行授权请求限流
+ 按 HMAC-IP 固定窗口执行授权请求限流。
:param request: 当前 HTTP 请求
:param redis: Redis 客户端
- :return: 无返回值
:raises OAuthProtocolException: 客户端地址缺失、请求超限或限流服务不可用时抛出
"""
# 使用 HMAC-IP 固定窗口限流,Redirect 校验前不执行外跳
@@ -112,13 +109,11 @@ async def _enforce_authorization_rate_limit(request: Request, redis: Redis) -> N
async def _record_authorization_failure_audit(db: AsyncSession, **fields: Any) -> None:
"""
- 尝试记录授权失败审计,审计异常不影响原协议错误
+ 尝试记录授权失败审计,审计异常不影响原协议错误。
:param db: 异步数据库会话
:param fields: 审计字段
- :return: 无返回值
"""
-
try:
await AuditService.record_independent(
db, OidcAuditEvent.AUTHORIZE_DENIED, 'failure', risk_level='high', **fields
@@ -129,24 +124,22 @@ async def _record_authorization_failure_audit(db: AsyncSession, **fields: Any) -
def _oidc_not_found_response() -> Response:
"""
- 构造 OIDC 关闭时的本地 404 响应
+ 构造 OIDC 关闭时的本地 404 响应。
:return: OIDC 未启用时的本地 404 响应
"""
-
return JSONResponse(content={'error': 'not_found'}, status_code=404, headers=_NO_STORE)
def _logout_page(title: str, body: str, *, redirect_origin: str | None = None) -> HTMLResponse:
"""
- 构造仅包含服务端固定内容的退出页面
+ 构造仅包含服务端固定内容的退出页面。
:param title: 页面标题
:param body: 服务端生成的页面正文
:param redirect_origin: 已校验的客户端回调源地址
:return: 带有内容安全策略的退出页面响应
"""
-
form_sources = "'self'" + (f' {redirect_origin}' if redirect_origin else '')
content = (
' '
@@ -172,13 +165,12 @@ def _logout_page(title: str, body: str, *, redirect_origin: str | None = None) -
def _confirmation_response(token: str, redirect_origin: str | None = None) -> HTMLResponse:
"""
- 构造绑定一次性凭据的退出确认页面
+ 构造绑定一次性凭据的退出确认页面。
:param token: 一次性退出确认凭据
:param redirect_origin: 已校验的客户端回调源地址
:return: 退出确认页面响应
"""
-
return _logout_page(
'退出认证中心?',
(
@@ -196,23 +188,21 @@ def _confirmation_response(token: str, redirect_origin: str | None = None) -> HT
def _local_response(_request: Request) -> HTMLResponse:
"""
- 构造不回显退出参数的同源完成页
+ 构造不回显退出参数的同源完成页。
:param _request: 当前 HTTP 请求
:return: 同源退出完成页
"""
-
return _logout_page('已退出', '此次登录已结束,可以关闭此页面。
')
async def _logout_parameters(request: Request) -> dict[str, str] | None:
"""
- 读取并校验 GET Query 或 POST Form 退出参数
+ 读取并校验 GET Query 或 POST Form 退出参数。
:param request: 当前 HTTP 请求
:return: 通过校验的退出参数,校验失败时返回 None
"""
-
if request.method == 'POST':
try:
values = await read_form(request)
@@ -229,12 +219,11 @@ async def _logout_parameters(request: Request) -> dict[str, str] | None:
def _valid_logout_parameters(values: Iterable[tuple[str, str]]) -> bool:
"""
- 校验退出参数的字段白名单和长度
+ 校验退出参数的字段白名单和长度。
:param values: 待校验的退出参数
:return: 参数是否全部通过校验
"""
-
return all(key in _LOGOUT_QUERY_FIELDS and len(value) <= _LOGOUT_QUERY_LIMITS[key] for key, value in values)
diff --git a/ruoyi-fastapi-backend/module_identity/controller/discovery_controller.py b/ruoyi-fastapi-backend/module_identity/controller/discovery_controller.py
index 9618915ce..bbb41b1aa 100644
--- a/ruoyi-fastapi-backend/module_identity/controller/discovery_controller.py
+++ b/ruoyi-fastapi-backend/module_identity/controller/discovery_controller.py
@@ -20,11 +20,10 @@
def _disabled_response() -> Response:
"""
- 返回协议端点关闭时的标准 404 响应
+ 返回协议端点关闭时的标准 404 响应。
:return: 协议端点关闭时的标准 404 响应
"""
-
return JSONResponse(
content={'error': 'not_found'}, status_code=404, headers={'Cache-Control': 'no-store', 'Pragma': 'no-cache'}
)
@@ -32,13 +31,12 @@ def _disabled_response() -> Response:
def _etag_response(request: Request, payload: dict[str, Any]) -> Response:
"""
- 按 If-None-Match 返回标准 JSON 或 304 响应
+ 按 If-None-Match 返回标准 JSON 或 304 响应。
:param request: 当前 HTTP 请求
:param payload: 待返回的 JSON 数据
:return: 标准 JSON 响应或 304 响应
"""
-
etag = OidcUtil.json_etag(payload)
headers = {'Cache-Control': _CACHE_CONTROL, 'ETag': etag}
if_none_match = request.headers.get('if-none-match', '')
diff --git a/ruoyi-fastapi-backend/module_identity/controller/interaction_controller.py b/ruoyi-fastapi-backend/module_identity/controller/interaction_controller.py
index 1d4436592..418b702d1 100644
--- a/ruoyi-fastapi-backend/module_identity/controller/interaction_controller.py
+++ b/ruoyi-fastapi-backend/module_identity/controller/interaction_controller.py
@@ -45,13 +45,12 @@
def _redis(request: Request) -> Redis:
"""
- 读取应用生命周期创建的 Redis 客户端
+ 读取应用生命周期创建的 Redis 客户端。
:param request: 当前 HTTP 请求
:return: 应用 Redis 客户端
:raises OidcInteractionException: Redis 客户端不可用
"""
-
value = getattr(request.app.state, 'redis', None)
if value is None:
raise OidcInteractionException(error='server_error', status_code=503, message='认证服务不可用')
@@ -60,34 +59,31 @@ def _redis(request: Request) -> Redis:
def _not_found() -> Response:
"""
- 构造认证中心未启用时的响应
+ 构造认证中心未启用时的响应。
:return: 认证中心未启用的 404 响应
"""
-
return _failure_response(I18nMessage('认证服务未启用', msg_key='identity.interaction.disabled'), 404)
def _invalid_body() -> Response:
"""
- 构造认证交互请求无效时的响应
+ 构造认证交互请求无效时的响应。
:return: 请求无效的 400 响应
"""
-
return _failure_response(I18nMessage('认证交互请求无效', msg_key='identity.interaction.invalidRequest'), 400)
def _failure_response(msg: str, status_code: int, headers: dict[str, str] | None = None) -> Response:
"""
- 构造项目统一错误响应并保留安全 HTTP 状态码
+ 构造项目统一错误响应并保留安全 HTTP 状态码。
:param msg: 错误消息
:param status_code: HTTP 状态码
:param headers: 可选响应头
:return: 统一错误响应
"""
-
response = ResponseUtil.failure(msg=msg, headers=headers or _NO_STORE)
response.status_code = status_code
@@ -96,12 +92,12 @@ def _failure_response(msg: str, status_code: int, headers: dict[str, str] | None
def _login_response(outcome: InteractionLoginOutcome) -> Response:
"""
- 构造认证登录或改密响应
+ 构造认证登录或改密响应。
:param outcome: 登录流程结果
:return: 统一认证响应
+ :raises SsoSessionError: 无法为登录结果建立有效的单点登录会话
"""
-
if outcome.failure_message is not None:
return ResponseUtil.failure(msg=outcome.failure_message, headers=_NO_STORE)
response = ResponseUtil.success(data=outcome.result, headers=_NO_STORE)
@@ -116,7 +112,7 @@ def _login_response(outcome: InteractionLoginOutcome) -> Response:
async def _safe_json_body(request: Request, model: type[_MODEL]) -> _MODEL:
"""
- 读取并校验认证交互 JSON 请求体
+ 读取并校验认证交互 JSON 请求体。
:param request: 当前 HTTP 请求
:param model: 请求体模型类型
diff --git a/ruoyi-fastapi-backend/module_identity/controller/oauth_client_controller.py b/ruoyi-fastapi-backend/module_identity/controller/oauth_client_controller.py
index fc960382b..fb2b84367 100644
--- a/ruoyi-fastapi-backend/module_identity/controller/oauth_client_controller.py
+++ b/ruoyi-fastapi-backend/module_identity/controller/oauth_client_controller.py
@@ -38,13 +38,12 @@
def _actor(current_user: CurrentUserModel) -> str:
"""
- 提取管理操作者标识
+ 提取管理操作者标识。
:param current_user: 当前登录用户
:return: 安全截断后的用户名
:raises ServiceException: 当前用户不可用
"""
-
try:
return OidcUtil.actor_name(
getattr(getattr(current_user, 'user', None), 'user_name', None), error_message='当前操作者不可用'
diff --git a/ruoyi-fastapi-backend/module_identity/controller/oauth_resource_controller.py b/ruoyi-fastapi-backend/module_identity/controller/oauth_resource_controller.py
index 54d030704..3c3f35295 100644
--- a/ruoyi-fastapi-backend/module_identity/controller/oauth_resource_controller.py
+++ b/ruoyi-fastapi-backend/module_identity/controller/oauth_resource_controller.py
@@ -41,13 +41,12 @@
def _actor(current_user: CurrentUserModel) -> str:
"""
- 提取管理操作者标识
+ 提取管理操作者标识。
:param current_user: 当前登录用户
:return: 安全截断后的用户名
:raises ServiceException: 当前用户不可用
"""
-
try:
return OidcUtil.actor_name(
getattr(getattr(current_user, 'user', None), 'user_name', None), error_message='当前操作者不可用'
diff --git a/ruoyi-fastapi-backend/module_identity/controller/oauth_session_controller.py b/ruoyi-fastapi-backend/module_identity/controller/oauth_session_controller.py
index fed6c4879..aa27856bc 100644
--- a/ruoyi-fastapi-backend/module_identity/controller/oauth_session_controller.py
+++ b/ruoyi-fastapi-backend/module_identity/controller/oauth_session_controller.py
@@ -39,13 +39,12 @@
def _actor(user: CurrentUserModel) -> str:
"""
- 提取管理操作者标识
+ 提取管理操作者标识。
:param user: 当前登录用户
:return: 安全截断后的用户名
:raises ServiceException: 当前用户不可用
"""
-
try:
return OidcUtil.actor_name(
getattr(getattr(user, 'user', None), 'user_name', None), error_message='当前操作者不可用'
diff --git a/ruoyi-fastapi-backend/module_identity/controller/oidc_key_controller.py b/ruoyi-fastapi-backend/module_identity/controller/oidc_key_controller.py
index dc276f29b..c8c26155c 100644
--- a/ruoyi-fastapi-backend/module_identity/controller/oidc_key_controller.py
+++ b/ruoyi-fastapi-backend/module_identity/controller/oidc_key_controller.py
@@ -27,13 +27,12 @@
def _actor(current_user: CurrentUserModel) -> str:
"""
- 提取管理操作者标识
+ 提取管理操作者标识。
:param current_user: 当前登录用户
:return: 安全截断后的用户名
:raises ServiceException: 当前用户不可用
"""
-
try:
return OidcUtil.actor_name(
getattr(getattr(current_user, 'user', None), 'user_name', None), error_message='当前操作者不可用'
diff --git a/ruoyi-fastapi-backend/module_identity/controller/token_controller.py b/ruoyi-fastapi-backend/module_identity/controller/token_controller.py
index 91b663d8a..e5659a035 100644
--- a/ruoyi-fastapi-backend/module_identity/controller/token_controller.py
+++ b/ruoyi-fastapi-backend/module_identity/controller/token_controller.py
@@ -54,7 +54,7 @@
def _invalid_userinfo_response() -> JSONResponse:
"""
- 构造不泄露原因的 UserInfo 401 响应
+ 构造不泄露原因的 UserInfo 401 响应。
:return: 不泄露校验细节的 UserInfo 401 响应
"""
@@ -68,13 +68,12 @@ def _invalid_userinfo_response() -> JSONResponse:
def _request_redis(request: Request) -> Redis:
"""
- 读取应用 Redis 客户端
+ 读取应用 Redis 客户端。
:param request: 当前 HTTP 请求
:return: Redis 客户端
:raises OAuthProtocolException: Redis 客户端不可用时抛出
"""
-
redis = getattr(request.app.state, 'redis', None)
if redis is None:
raise OAuthProtocolException('server_error', 'Token endpoint is unavailable', 503)
@@ -83,13 +82,12 @@ def _request_redis(request: Request) -> Redis:
async def _pre_auth_rate_limit(request: Request, redis: Redis, form: dict[str, str], endpoint: str) -> None:
"""
- 在 Client Secret 校验前按可见 Client ID 限流
+ 在 Client Secret 校验前按可见 Client ID 限流。
:param request: 当前 HTTP 请求
:param redis: Redis 客户端
:param form: 已解析的协议表单
:param endpoint: 当前协议端点标识
- :return: 无返回值
:raises RateLimitExceeded: 请求超过限流阈值时抛出
:raises RateLimitUnavailable: 限流服务不可用时抛出
"""
@@ -117,11 +115,10 @@ async def _pre_auth_rate_limit(request: Request, redis: Redis, form: dict[str, s
def _validate_protocol_form(form: dict[str, str], allowed: set[str]) -> None:
"""
- 校验协议表单字段白名单和长度
+ 校验协议表单字段白名单和长度。
:param form: 已解析的协议表单
:param allowed: 当前端点允许的字段集合
- :return: 无返回值
:raises OAuthProtocolException: 包含未知字段或超长字段时抛出
"""
# 拒绝未知或超长的协议表单字段
@@ -133,7 +130,7 @@ def _validate_protocol_form(form: dict[str, str], allowed: set[str]) -> None:
def _rate_limit_error(error: RateLimitExceeded | RateLimitUnavailable) -> JSONResponse:
"""
- 构造协议限流错误响应
+ 构造协议限流错误响应。
:param error: 限流异常
:return: 裸标准限流错误响应
@@ -148,14 +145,12 @@ def _rate_limit_error(error: RateLimitExceeded | RateLimitUnavailable) -> JSONRe
async def _record_independent_audit(db: AsyncSession, event_type: str, **fields: object) -> None:
"""
- 尝试记录协议失败审计,审计异常不改变标准错误响应
+ 尝试记录协议失败审计,审计异常不改变标准错误响应。
:param db: 异步数据库会话
:param event_type: 审计事件类型
:param fields: 审计字段
- :return: 无返回值
"""
-
try:
await AuditService.record_independent(db, event_type, 'failure', **fields)
except Exception:
@@ -164,7 +159,7 @@ async def _record_independent_audit(db: AsyncSession, event_type: str, **fields:
async def _verification_key_or_none(token: str, query_db: AsyncSession) -> object:
"""
- 为 JWT 撤销和内省加载本地公钥
+ 为 JWT 撤销和内省加载本地公钥。
:param token: 待读取的访问令牌
:param query_db: 异步数据库会话
@@ -181,24 +176,22 @@ async def _verification_key_or_none(token: str, query_db: AsyncSession) -> objec
async def _verification_key_loader(query_db: AsyncSession, token: str) -> object:
"""
- 提供给 Service 事务入口的本地公钥加载回调
+ 提供给 Service 事务入口的本地公钥加载回调。
:param query_db: 异步数据库会话
:param token: 待读取的访问令牌
:return: 本地公钥或 None
"""
-
return await _verification_key_or_none(token, query_db)
def _oauth_error(error: OAuthProtocolException) -> JSONResponse:
"""
- 生成裸标准 OAuth 错误响应
+ 生成裸标准 OAuth 错误响应。
:param error: OAuth 协议异常
:return: 裸标准 OAuth 错误响应
"""
-
content = {'error': error.error}
if error.error_description:
content['error_description'] = error.error_description
@@ -212,12 +205,11 @@ def _oauth_error(error: OAuthProtocolException) -> JSONResponse:
def _http_error(error: HTTPException) -> JSONResponse:
"""
- 将输入边界 HTTP 错误转换为裸 JSON 响应
+ 将输入边界 HTTP 错误转换为裸 JSON 响应。
:param error: 输入边界 HTTP 异常
:return: 裸 JSON 错误响应
"""
-
code = 'not_found' if error.status_code == _NOT_FOUND else 'invalid_request'
return JSONResponse(content={'error': code}, status_code=error.status_code, headers=_NO_STORE)
diff --git a/ruoyi-fastapi-backend/module_identity/dao/identity_subject_dao.py b/ruoyi-fastapi-backend/module_identity/dao/identity_subject_dao.py
index dc4ec8beb..bd223f841 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/identity_subject_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/identity_subject_dao.py
@@ -12,20 +12,17 @@
class IdentitySubjectDao:
- """
- Identity Subject 数据库操作层
- """
+ """Identity Subject 数据库操作层。"""
@classmethod
async def get_by_user_id(cls, db: AsyncSession, user_id: int) -> SysIdentitySubject | None:
"""
- 按用户编号查询 Identity Subject
+ 按用户编号查询 Identity Subject。
:param db: orm对象
:param user_id: 用户编号
:return: Identity Subject,不存在时返回 None
"""
-
result = await db.execute(select(SysIdentitySubject).where(SysIdentitySubject.user_id == user_id))
return result.scalars().first()
@@ -33,13 +30,12 @@ async def get_by_user_id(cls, db: AsyncSession, user_id: int) -> SysIdentitySubj
@classmethod
async def get_by_subject_id(cls, db: AsyncSession, subject_id: str) -> SysIdentitySubject | None:
"""
- 按主体标识查询 Identity Subject
+ 按主体标识查询 Identity Subject。
:param db: orm对象
:param subject_id: 主体标识
:return: Identity Subject,不存在时返回 None
"""
-
result = await db.execute(select(SysIdentitySubject).where(SysIdentitySubject.subject_id == subject_id))
return result.scalars().first()
@@ -47,13 +43,12 @@ async def get_by_subject_id(cls, db: AsyncSession, subject_id: str) -> SysIdenti
@classmethod
async def list_for_users_for_update(cls, db: AsyncSession, user_ids: Sequence[int]) -> Sequence[SysIdentitySubject]:
"""
- 按用户编号锁定查询 Identity Subject
+ 按用户编号锁定查询 Identity Subject。
:param db: orm对象
:param user_ids: 用户编号序列
:return: 按用户编号排序的 Identity Subject 序列
"""
-
result = await db.execute(
select(SysIdentitySubject)
.where(SysIdentitySubject.user_id.in_(user_ids))
@@ -68,15 +63,15 @@ async def create_for_user(
cls, db: AsyncSession, user_id: int, create_by: str | None = None, subject_id: str | None = None
) -> SysIdentitySubject:
"""
- 新增用户 Identity Subject
+ 新增用户 Identity Subject。
:param db: orm对象
:param user_id: 用户编号
:param create_by: 创建人标识
:param subject_id: 主体标识
:return: 新建或已存在的 Identity Subject
+ :raises IntegrityError: 身份主体写入违反数据库完整性约束且无法复用已有映射
"""
-
existing = await cls.get_by_user_id(db, user_id)
if existing is not None:
return existing
@@ -103,14 +98,13 @@ async def backfill_for_users(
cls, db: AsyncSession, user_ids: Iterable[int], create_by: str = 'migration'
) -> Sequence[SysIdentitySubject]:
"""
- 批量补齐用户 Identity Subject
+ 批量补齐用户 Identity Subject。
:param db: orm对象
:param user_ids: 用户编号序列
:param create_by: 创建人标识
:return: 补齐后的 Identity Subject 序列
"""
-
ids = list(dict.fromkeys(user_ids))
if not ids:
return []
@@ -126,14 +120,13 @@ async def backfill_for_users(
@classmethod
async def increment_auth_version(cls, db: AsyncSession, user_id: int, expected_version: int | None = None) -> bool:
"""
- 递增单个用户认证版本
+ 递增单个用户认证版本。
:param db: orm对象
:param user_id: 用户编号
:param expected_version: 期望认证版本
:return: 是否更新成功
"""
-
conditions = [SysIdentitySubject.user_id == user_id]
if expected_version is not None:
conditions.append(SysIdentitySubject.auth_version == expected_version)
@@ -150,7 +143,7 @@ async def increment_auth_versions(
cls, db: AsyncSession, user_ids: Sequence[int], update_by: str, now: datetime | None = None
) -> int:
"""
- 批量递增用户认证版本
+ 批量递增用户认证版本。
:param db: orm对象
:param user_ids: 用户编号序列
@@ -158,7 +151,6 @@ async def increment_auth_versions(
:param now: 当前时间
:return: 成功更新的 Identity Subject 数量
"""
-
result = await db.execute(
update(SysIdentitySubject)
.where(SysIdentitySubject.user_id.in_(user_ids))
@@ -175,13 +167,12 @@ async def increment_auth_versions(
@classmethod
async def list_missing_user_ids(cls, db: AsyncSession, user_ids: Iterable[int] | None = None) -> list[int]:
"""
- 查询缺少 Identity Subject 的用户编号
+ 查询缺少 Identity Subject 的用户编号。
:param db: orm对象
:param user_ids: 用户编号序列
:return: 缺少 Identity Subject 的用户编号列表
"""
-
if user_ids is None:
result = await db.execute(select(SysUser.user_id).where(SysUser.del_flag == '0'))
ids = list(result.scalars().all())
diff --git a/ruoyi-fastapi-backend/module_identity/dao/identity_user_dao.py b/ruoyi-fastapi-backend/module_identity/dao/identity_user_dao.py
index d9eadb030..4f1b01706 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/identity_user_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/identity_user_dao.py
@@ -7,20 +7,17 @@
class IdentityUserDao:
- """
- Identity User 数据库操作层
- """
+ """Identity User 数据库操作层。"""
@classmethod
async def get_active_user(cls, db: AsyncSession, user_id: int) -> SysUser | None:
"""
- 按用户编号查询活跃用户
+ 按用户编号查询活跃用户。
:param db: orm对象
:param user_id: 用户编号
:return: SysUser,不存在时返回 None
"""
-
result = await db.execute(
select(SysUser).where(SysUser.status == '0', SysUser.del_flag == '0', SysUser.user_id == user_id)
)
@@ -30,25 +27,23 @@ async def get_active_user(cls, db: AsyncSession, user_id: int) -> SysUser | None
@classmethod
async def get_user(cls, db: AsyncSession, user_id: int) -> SysUser | None:
"""
- 按用户编号查询用户
+ 按用户编号查询用户。
:param db: orm对象
:param user_id: 用户编号
:return: SysUser,不存在时返回 None
"""
-
return await db.scalar(select(SysUser).where(SysUser.user_id == user_id))
@classmethod
async def list_user_ids_by_role_id(cls, db: AsyncSession, role_id: int) -> list[int]:
"""
- 按角色编号查询用户编号
+ 按角色编号查询用户编号。
:param db: orm对象
:param role_id: 角色编号
:return: 用户编号列表
"""
-
result = await db.execute(
select(SysUserRole.user_id).where(SysUserRole.role_id == role_id).order_by(SysUserRole.user_id)
)
@@ -58,13 +53,12 @@ async def list_user_ids_by_role_id(cls, db: AsyncSession, role_id: int) -> list[
@classmethod
async def get_claim_attributes(cls, db: AsyncSession, user_id: int) -> tuple[list[str], SysDept | None]:
"""
- 查询用户声明属性和部门
+ 查询用户声明属性和部门。
:param db: orm对象
:param user_id: 用户编号
:return: 声明名称列表和 SysDept,部门不存在时为 None
"""
-
role_result = await db.execute(
select(SysRole.role_key)
.join(SysUserRole, SysUserRole.role_id == SysRole.role_id)
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oauth_access_policy_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oauth_access_policy_dao.py
index 298def5f3..38830f9bc 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oauth_access_policy_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oauth_access_policy_dao.py
@@ -9,20 +9,16 @@
class OAuthAccessPolicyDao:
- """
- 用户应用访问控制数据库操作层
- """
+ """用户应用访问控制数据库操作层。"""
@staticmethod
async def lock_client(db: AsyncSession, client_pk: int) -> None:
"""
- 锁定 Client,统一授权签发、撤销和访问控制的事务顺序
+ 锁定 Client,统一授权签发、撤销和访问控制的事务顺序。
:param db: orm对象
:param client_pk: Client 内部主键
- :return: None
"""
-
await db.execute(
update(SysOAuthClient)
.where(SysOAuthClient.client_pk == client_pk)
@@ -40,7 +36,7 @@ async def get(
db: AsyncSession, user_id: int, client_pk: int, *, for_update: bool = False
) -> SysOAuthAccessPolicy | None:
"""
- 查询用户对 Client 的访问策略,未配置时默认允许
+ 查询用户对 Client 的访问策略,未配置时默认允许。
:param db: orm对象
:param user_id: 用户编号
@@ -48,7 +44,6 @@ async def get(
:param for_update: 是否使用当前读锁定策略
:return: 访问策略,不存在时返回 None
"""
-
query = select(SysOAuthAccessPolicy).where(
SysOAuthAccessPolicy.user_id == user_id, SysOAuthAccessPolicy.client_pk == client_pk
)
@@ -61,7 +56,7 @@ async def get(
@classmethod
async def is_blocked(cls, db: AsyncSession, user_id: int, client_pk: int, *, for_update: bool = False) -> bool:
"""
- 判断用户是否被禁止访问 Client
+ 判断用户是否被禁止访问 Client。
:param db: orm对象
:param user_id: 用户编号
@@ -69,7 +64,6 @@ async def is_blocked(cls, db: AsyncSession, user_id: int, client_pk: int, *, for
:param for_update: 是否使用当前读锁定策略
:return: 是否禁止访问
"""
-
row = await cls.get(db, user_id, client_pk, for_update=for_update)
return row is not None and row.access_status == 'blocked'
@@ -78,7 +72,7 @@ async def set_status(
cls, db: AsyncSession, user_id: int, client_pk: int, blocked: bool, actor: str, reason: str
) -> SysOAuthAccessPolicy:
"""
- 更新访问策略;调用方须先锁定 Client 并负责事务提交
+ 更新访问策略;调用方须先锁定 Client 并负责事务提交。
:param db: orm对象
:param user_id: 用户编号
@@ -88,7 +82,6 @@ async def set_status(
:param reason: 操作原因
:return: 更新后的访问策略
"""
-
row = await cls.get(db, user_id, client_pk, for_update=True)
if row is None:
row = SysOAuthAccessPolicy(user_id=user_id, client_pk=client_pk)
@@ -104,13 +97,12 @@ async def set_status(
@staticmethod
async def list_for_grants(db: AsyncSession, targets: list[tuple[int, int]]) -> list[SysOAuthAccessPolicy]:
"""
- 批量查询管理列表中用户与 Client 的访问策略
+ 批量查询管理列表中用户与 Client 的访问策略。
:param db: orm对象
:param targets: 用户编号和 Client 主键列表
:return: 用户访问策略列表
"""
-
result = await db.execute(
select(SysOAuthAccessPolicy).where(
tuple_(SysOAuthAccessPolicy.user_id, SysOAuthAccessPolicy.client_pk).in_(targets)
@@ -121,12 +113,11 @@ async def list_for_grants(db: AsyncSession, targets: list[tuple[int, int]]) -> l
@staticmethod
def _query(query: AccessPolicyPageQueryModel) -> Select:
"""
- 构建独立访问策略查询,不依赖用户已有授权记录
+ 构建独立访问策略查询,不依赖用户已有授权记录。
:param query: 访问策略分页查询参数
:return: 包含用户与客户端名称的查询语句
"""
-
statement = (
select(SysOAuthAccessPolicy, SysUser.user_name, SysOAuthClient.client_id, SysOAuthClient.client_name)
.join(SysUser, SysUser.user_id == SysOAuthAccessPolicy.user_id)
@@ -145,13 +136,12 @@ async def list_page(
cls, db: AsyncSession, query: AccessPolicyPageQueryModel
) -> list[tuple[SysOAuthAccessPolicy, str, str, str]]:
"""
- 分页查询访问策略及其关联名称
+ 分页查询访问策略及其关联名称。
:param db: orm对象
:param query: 访问策略分页查询参数
:return: 访问策略、用户名、客户端标识和名称的列表
"""
-
result = await db.execute(
cls._query(query)
.order_by(
@@ -167,11 +157,10 @@ async def list_page(
@classmethod
async def count(cls, db: AsyncSession, query: AccessPolicyPageQueryModel) -> int:
"""
- 统计匹配条件的独立访问策略数量
+ 统计匹配条件的独立访问策略数量。
:param db: orm对象
:param query: 访问策略分页查询参数
:return: 匹配的记录总数
"""
-
return int(await db.scalar(select(func.count()).select_from(cls._query(query).subquery())) or 0)
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oauth_audit_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oauth_audit_dao.py
index 8a69a2e3c..ae0c6e33d 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oauth_audit_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oauth_audit_dao.py
@@ -8,20 +8,17 @@
class OAuthAuditDao:
- """
- OAuth Audit 数据库操作层
- """
+ """OAuth Audit 数据库操作层。"""
@classmethod
async def append(cls, db: AsyncSession, event: SysOAuthAuditLog) -> SysOAuthAuditLog:
"""
- 新增 OAuth Audit 日志并刷新主键
+ 新增 OAuth Audit 日志并刷新主键。
:param db: orm对象
:param event: OAuth Audit 日志对象
:return: 已写入的 OAuth Audit 日志对象
"""
-
db.add(event)
await db.flush()
@@ -30,13 +27,11 @@ async def append(cls, db: AsyncSession, event: SysOAuthAuditLog) -> SysOAuthAudi
@classmethod
async def bulk_append(cls, db: AsyncSession, events: Iterable[SysOAuthAuditLog]) -> None:
"""
- 批量新增 OAuth Audit 日志
+ 批量新增 OAuth Audit 日志。
:param db: orm对象
:param events: OAuth Audit 日志对象序列
- :return: None
"""
-
rows = list(events)
if rows:
db.add_all(rows)
@@ -55,7 +50,7 @@ async def list_page(
before: datetime | None = None,
) -> Sequence[SysOAuthAuditLog]:
"""
- 分页查询 OAuth Audit 日志
+ 分页查询 OAuth Audit 日志。
:param db: orm对象
:param offset: 分页偏移量
@@ -67,7 +62,6 @@ async def list_page(
:param before: 归档截止时间
:return: OAuth Audit 日志序列
"""
-
conditions = []
if client_id:
conditions.append(SysOAuthAuditLog.client_id == client_id)
@@ -98,7 +92,7 @@ def _conditions(
end_time: datetime | None = None,
) -> list:
"""
- 构造 OAuth Audit 查询条件
+ 构造 OAuth Audit 查询条件。
:param client_id: Client 公开标识
:param user_id: 用户编号
@@ -109,7 +103,6 @@ def _conditions(
:param end_time: 查询结束时间
:return: SQLAlchemy 条件列表
"""
-
conditions = []
if client_id:
conditions.append(SysOAuthAuditLog.client_id == client_id)
@@ -143,7 +136,7 @@ async def list_admin_page(
end_time: datetime | None = None,
) -> Sequence[SysOAuthAuditLog]:
"""
- 分页查询管理端 OAuth Audit 日志
+ 分页查询管理端 OAuth Audit 日志。
:param db: orm对象
:param offset: 分页偏移量
@@ -157,7 +150,6 @@ async def list_admin_page(
:param end_time: 查询结束时间
:return: 管理端 OAuth Audit 日志序列
"""
-
query = (
select(SysOAuthAuditLog)
.where(
@@ -193,7 +185,7 @@ async def count_admin(
end_time: datetime | None = None,
) -> int:
"""
- 统计管理端 OAuth Audit 日志数量
+ 统计管理端 OAuth Audit 日志数量。
:param db: orm对象
:param client_id: Client 公开标识
@@ -205,7 +197,6 @@ async def count_admin(
:param end_time: 查询结束时间
:return: 符合条件的 OAuth Audit 日志数量
"""
-
result = await db.execute(
select(func.count())
.select_from(SysOAuthAuditLog)
@@ -227,14 +218,13 @@ async def count_admin(
@classmethod
async def archive_before(cls, db: AsyncSession, before: datetime, limit: int = 1000) -> int:
"""
- 归档指定时间前的 OAuth Audit 日志
+ 归档指定时间前的 OAuth Audit 日志。
:param db: orm对象
:param before: 归档截止时间
:param limit: 单次归档数量上限
:return: 已归档的 OAuth Audit 日志数量
"""
-
result = await db.execute(
select(SysOAuthAuditLog)
.where(SysOAuthAuditLog.create_time < before)
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oauth_client_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oauth_client_dao.py
index ce6304408..cf73f8b1a 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oauth_client_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oauth_client_dao.py
@@ -18,46 +18,38 @@
class OAuthClientDao:
- """
- OAuth Client 数据库操作层
- """
+ """OAuth Client 数据库操作层。"""
@classmethod
async def add_client(cls, db: AsyncSession, client: SysOAuthClient) -> None:
"""
- 新增 OAuth Client 并刷新主键
+ 新增 OAuth Client 并刷新主键。
:param db: orm对象
:param client: OAuth Client 对象
- :return: None
"""
-
db.add(client)
await db.flush()
@classmethod
async def add_uri(cls, db: AsyncSession, uri: SysOAuthClientUri) -> None:
"""
- 新增 OAuth Client 回调地址并刷新主键
+ 新增 OAuth Client 回调地址并刷新主键。
:param db: orm对象
:param uri: 回调地址
- :return: None
"""
-
db.add(uri)
await db.flush()
@classmethod
async def persist_client_policy_change(cls, db: AsyncSession, client: SysOAuthClient) -> None:
"""
- 刷新 OAuth Client 策略变更
+ 刷新 OAuth Client 策略变更。
:param db: orm对象
:param client: OAuth Client 对象
- :return: None
"""
-
await db.flush()
@classmethod
@@ -65,7 +57,7 @@ async def get_by_client_id(
cls, db: AsyncSession, client_id: str, active_only: bool = True, for_update: bool = False
) -> SysOAuthClient | None:
"""
- 按公开标识查询 OAuth Client
+ 按公开标识查询 OAuth Client。
:param db: orm对象
:param client_id: Client 公开标识
@@ -73,7 +65,6 @@ async def get_by_client_id(
:param for_update: 是否锁定查询结果
:return: OAuth Client,不存在时返回 None
"""
-
conditions = [SysOAuthClient.client_id == client_id]
if active_only:
conditions.append(SysOAuthClient.status == '0')
@@ -89,7 +80,7 @@ async def get_by_pk(
cls, db: AsyncSession, client_pk: int, active_only: bool = True, for_update: bool = False
) -> SysOAuthClient | None:
"""
- 按内部主键查询 OAuth Client
+ 按内部主键查询 OAuth Client。
:param db: orm对象
:param client_pk: Client 内部主键
@@ -97,7 +88,6 @@ async def get_by_pk(
:param for_update: 是否锁定查询结果
:return: OAuth Client,不存在时返回 None
"""
-
conditions = [SysOAuthClient.client_pk == client_pk]
if active_only:
conditions.append(SysOAuthClient.status == '0')
@@ -111,13 +101,12 @@ async def get_by_pk(
@classmethod
async def id_map(cls, db: AsyncSession, client_pks: Sequence[int]) -> Mapping[int, str]:
"""
- 批量查询 Client 主键与公开标识映射
+ 批量查询 Client 主键与公开标识映射。
:param db: orm对象
:param client_pks: Client 内部主键序列
:return: Client 内部主键到公开标识的映射
"""
-
if not client_pks:
return {}
result = await db.execute(
@@ -129,13 +118,12 @@ async def id_map(cls, db: AsyncSession, client_pks: Sequence[int]) -> Mapping[in
@classmethod
async def id_for_pk(cls, db: AsyncSession, client_pk: int) -> str | None:
"""
- 按内部主键查询 Client 公开标识
+ 按内部主键查询 Client 公开标识。
:param db: orm对象
:param client_pk: Client 内部主键
:return: Client 公开标识,不存在时返回 None
"""
-
result = await db.execute(select(SysOAuthClient.client_id).where(SysOAuthClient.client_pk == client_pk))
return result.scalar_one_or_none()
@@ -143,14 +131,13 @@ async def id_for_pk(cls, db: AsyncSession, client_pk: int) -> str | None:
@classmethod
async def has_disabled_bound_resource(cls, db: AsyncSession, client_id: str, audience: str) -> bool:
"""
- 查询 Client 是否绑定停用 Resource
+ 查询 Client 是否绑定停用 Resource。
:param db: orm对象
:param client_id: Client 公开标识
:param audience: Resource 受众
:return: 是否绑定停用 Resource
"""
-
result = await db.execute(
select(SysOAuthResource.resource_pk)
.join(SysOAuthClientResource, SysOAuthClientResource.resource_pk == SysOAuthResource.resource_pk)
@@ -169,7 +156,7 @@ async def list_secrets(
cls, db: AsyncSession, client_pk: int, active_only: bool = True, for_update: bool = False
) -> Sequence[SysOAuthClientSecret]:
"""
- 查询 OAuth Client 密钥列表
+ 查询 OAuth Client 密钥列表。
:param db: orm对象
:param client_pk: Client 内部主键
@@ -177,7 +164,6 @@ async def list_secrets(
:param for_update: 是否锁定查询结果
:return: OAuth Client Secret 序列
"""
-
conditions = [SysOAuthClientSecret.client_pk == client_pk]
if active_only:
now = TimezoneUtil.utc_now()
@@ -198,13 +184,12 @@ async def list_secrets(
@classmethod
async def get_secret_for_update(cls, db: AsyncSession, secret_id: str) -> SysOAuthClientSecret | None:
"""
- 按密钥标识锁定查询 Client Secret
+ 按密钥标识锁定查询 Client Secret。
:param db: orm对象
:param secret_id: Client Secret 标识
:return: Client Secret,不存在时返回 None
"""
-
result = await db.execute(
select(SysOAuthClientSecret).where(SysOAuthClientSecret.secret_id == secret_id).with_for_update()
)
@@ -214,13 +199,12 @@ async def get_secret_for_update(cls, db: AsyncSession, secret_id: str) -> SysOAu
@classmethod
async def mark_secret_used(cls, db: AsyncSession, secret_id: str) -> bool:
"""
- 标记 Client Secret 已使用
+ 标记 Client Secret 已使用。
:param db: orm对象
:param secret_id: Client Secret 标识
:return: 是否更新成功
"""
-
result = await db.execute(
update(SysOAuthClientSecret)
.where(SysOAuthClientSecret.secret_id == secret_id)
@@ -234,7 +218,7 @@ async def list_uris(
cls, db: AsyncSession, client_pk: int, uri_type: str | None = None, active_only: bool = True
) -> Sequence[SysOAuthClientUri]:
"""
- 查询 OAuth Client 回调地址列表
+ 查询 OAuth Client 回调地址列表。
:param db: orm对象
:param client_pk: Client 内部主键
@@ -242,7 +226,6 @@ async def list_uris(
:param active_only: 是否仅查询启用记录
:return: OAuth Client 回调地址序列
"""
-
conditions = [SysOAuthClientUri.client_pk == client_pk]
if uri_type:
conditions.append(SysOAuthClientUri.uri_type == uri_type)
@@ -257,7 +240,7 @@ async def find_exact_uri(
cls, db: AsyncSession, client_pk: int, uri_type: str, uri: str
) -> SysOAuthClientUri | None:
"""
- 按完整地址查询 OAuth Client 回调地址
+ 按完整地址查询 OAuth Client 回调地址。
:param db: orm对象
:param client_pk: Client 内部主键
@@ -265,7 +248,6 @@ async def find_exact_uri(
:param uri: 回调地址
:return: Client 回调地址,不存在时返回 None
"""
-
result = await db.execute(
select(SysOAuthClientUri).where(
SysOAuthClientUri.client_pk == client_pk,
@@ -283,7 +265,7 @@ async def find_uri(
cls, db: AsyncSession, client_pk: int, uri_type: str, uri_hash: str, uri: str
) -> SysOAuthClientUri | None:
"""
- 按地址摘要查询 OAuth Client 回调地址
+ 按地址摘要查询 OAuth Client 回调地址。
:param db: orm对象
:param client_pk: Client 内部主键
@@ -292,7 +274,6 @@ async def find_uri(
:param uri: 回调地址
:return: Client 回调地址,不存在时返回 None
"""
-
result = await db.execute(
select(SysOAuthClientUri).where(
SysOAuthClientUri.client_pk == client_pk,
@@ -307,13 +288,12 @@ async def find_uri(
@classmethod
async def get_uri_for_update(cls, db: AsyncSession, uri_id: int) -> SysOAuthClientUri | None:
"""
- 按内部主键锁定查询 Client 回调地址
+ 按内部主键锁定查询 Client 回调地址。
:param db: orm对象
:param uri_id: 回调地址内部主键
:return: Client 回调地址,不存在时返回 None
"""
-
result = await db.execute(select(SysOAuthClientUri).where(SysOAuthClientUri.uri_id == uri_id).with_for_update())
return result.scalars().first()
@@ -321,13 +301,12 @@ async def get_uri_for_update(cls, db: AsyncSession, uri_id: int) -> SysOAuthClie
@classmethod
async def list_scope_bindings(cls, db: AsyncSession, client_pk: int) -> Sequence[SysOAuthClientScope]:
"""
- 查询 Client 权限范围绑定列表
+ 查询 Client 权限范围绑定列表。
:param db: orm对象
:param client_pk: Client 内部主键
:return: Client Scope 绑定序列
"""
-
result = await db.execute(select(SysOAuthClientScope).where(SysOAuthClientScope.client_pk == client_pk))
return result.scalars().all()
@@ -335,13 +314,12 @@ async def list_scope_bindings(cls, db: AsyncSession, client_pk: int) -> Sequence
@classmethod
async def list_resource_bindings(cls, db: AsyncSession, client_pk: int) -> Sequence[SysOAuthClientResource]:
"""
- 查询 Client Resource 绑定列表
+ 查询 Client Resource 绑定列表。
:param db: orm对象
:param client_pk: Client 内部主键
:return: Client Resource 绑定序列
"""
-
result = await db.execute(select(SysOAuthClientResource).where(SysOAuthClientResource.client_pk == client_pk))
return result.scalars().all()
@@ -349,13 +327,12 @@ async def list_resource_bindings(cls, db: AsyncSession, client_pk: int) -> Seque
@classmethod
async def list_scopes(cls, db: AsyncSession, client_pk: int) -> Sequence[SysOAuthScope]:
"""
- 查询 Client 权限范围列表
+ 查询 Client 权限范围列表。
:param db: orm对象
:param client_pk: Client 内部主键
:return: OAuth Scope 序列
"""
-
result = await db.execute(
select(SysOAuthScope)
.join(SysOAuthClientScope, SysOAuthClientScope.scope_pk == SysOAuthScope.scope_pk)
@@ -368,13 +345,12 @@ async def list_scopes(cls, db: AsyncSession, client_pk: int) -> Sequence[SysOAut
@classmethod
async def list_resources(cls, db: AsyncSession, client_pk: int) -> Sequence[SysOAuthResource]:
"""
- 查询 Client Resource 列表
+ 查询 Client Resource 列表。
:param db: orm对象
:param client_pk: Client 内部主键
:return: OAuth Resource 序列
"""
-
result = await db.execute(
select(SysOAuthResource)
.join(SysOAuthClientResource, SysOAuthClientResource.resource_pk == SysOAuthResource.resource_pk)
@@ -387,13 +363,12 @@ async def list_resources(cls, db: AsyncSession, client_pk: int) -> Sequence[SysO
@classmethod
async def list_scope_definitions(cls, db: AsyncSession, active_only: bool = True) -> Sequence[SysOAuthScope]:
"""
- 查询启用或全部 Scope 定义
+ 查询启用或全部 Scope 定义。
:param db: orm对象
:param active_only: 是否仅查询启用记录
:return: OAuth Scope 定义序列
"""
-
query = select(SysOAuthScope)
if active_only:
query = query.where(SysOAuthScope.status == '0')
@@ -404,13 +379,12 @@ async def list_scope_definitions(cls, db: AsyncSession, active_only: bool = True
@classmethod
async def get_active_scopes_by_codes(cls, db: AsyncSession, scope_codes: Sequence[str]) -> Sequence[SysOAuthScope]:
"""
- 按编码批量查询启用 Scope
+ 按编码批量查询启用 Scope。
:param db: orm对象
:param scope_codes: Scope 编码序列
:return: 启用的 OAuth Scope 序列
"""
-
if not scope_codes:
return ()
result = await db.execute(
@@ -424,13 +398,12 @@ async def get_active_resources_by_ids(
cls, db: AsyncSession, resource_ids: Sequence[str]
) -> Sequence[SysOAuthResource]:
"""
- 按资源标识批量查询启用 Resource
+ 按资源标识批量查询启用 Resource。
:param db: orm对象
:param resource_ids: Resource 公开标识序列
:return: 启用的 OAuth Resource 序列
"""
-
if not resource_ids:
return ()
result = await db.execute(
@@ -455,7 +428,7 @@ async def replace_bindings(
allowed_role_keys: Sequence[str] = (),
) -> None:
"""
- 替换 Client 的 Scope、Resource 与回调地址绑定
+ 替换 Client 的 Scope、Resource 与回调地址绑定。
:param db: orm对象
:param client_pk: Client 内部主键
@@ -465,9 +438,7 @@ async def replace_bindings(
:param pre_authorized: 是否预授权
:param now: 当前时间
:param allowed_role_keys: 允许向客户端发布的角色权限字符,空列表表示不发布角色
- :return: None
"""
-
await db.execute(delete(SysOAuthClientScope).where(SysOAuthClientScope.client_pk == client_pk))
await db.execute(delete(SysOAuthClientResource).where(SysOAuthClientResource.client_pk == client_pk))
await db.execute(delete(SysOAuthClientUri).where(SysOAuthClientUri.client_pk == client_pk))
@@ -516,26 +487,23 @@ async def replace_bindings(
@classmethod
async def add_secret(cls, db: AsyncSession, secret: SysOAuthClientSecret) -> None:
"""
- 新增 OAuth Client Secret 并刷新主键
+ 新增 OAuth Client Secret 并刷新主键。
:param db: orm对象
:param secret: OAuth Client Secret 对象
- :return: None
"""
-
db.add(secret)
await db.flush()
@classmethod
async def find_active_introspection_client(cls, db: AsyncSession, client_id: str) -> SysOAuthClient | None:
"""
- 按公开标识查询启用的内省 OAuth Client
+ 按公开标识查询启用的内省 OAuth Client。
:param db: orm对象
:param client_id: Client 公开标识
:return: 内省 OAuth Client,不存在时返回 None
"""
-
result = await db.execute(
select(SysOAuthClient).where(
SysOAuthClient.client_id == client_id,
@@ -550,13 +518,12 @@ async def find_active_introspection_client(cls, db: AsyncSession, client_id: str
@classmethod
async def lock_clients_for_resource(cls, db: AsyncSession, resource_pk: int) -> Sequence[SysOAuthClient]:
"""
- 锁定查询 Resource 关联的 OAuth Client
+ 锁定查询 Resource 关联的 OAuth Client。
:param db: orm对象
:param resource_pk: Resource 内部主键
:return: 按 Resource 关联的 OAuth Client 序列
"""
-
direct = await db.execute(
select(SysOAuthClient.client_pk)
.join(SysOAuthClientResource, SysOAuthClientResource.client_pk == SysOAuthClient.client_pk)
@@ -579,13 +546,12 @@ async def lock_clients_for_resource(cls, db: AsyncSession, resource_pk: int) ->
@classmethod
async def lock_clients_for_scope(cls, db: AsyncSession, scope_pk: int) -> Sequence[SysOAuthClient]:
"""
- 锁定查询 Scope 关联的 OAuth Client
+ 锁定查询 Scope 关联的 OAuth Client。
:param db: orm对象
:param scope_pk: Scope 内部主键
:return: 按 Scope 关联的 OAuth Client 序列
"""
-
result = await db.execute(
select(SysOAuthClient)
.join(SysOAuthClientScope, SysOAuthClientScope.client_pk == SysOAuthClient.client_pk)
@@ -598,14 +564,12 @@ async def lock_clients_for_scope(cls, db: AsyncSession, scope_pk: int) -> Sequen
@classmethod
async def revoke_client_credentials(cls, db: AsyncSession, client_pk: int, now: datetime) -> None:
"""
- 撤销 OAuth Client 的全部凭据
+ 撤销 OAuth Client 的全部凭据。
:param db: orm对象
:param client_pk: Client 内部主键
:param now: 当前时间
- :return: None
"""
-
await db.execute(
update(SysOAuthGrant)
.where(SysOAuthGrant.client_pk == client_pk, SysOAuthGrant.status == 'active')
@@ -622,13 +586,12 @@ async def get_client_detail_rows(
cls, db: AsyncSession, client_id: str
) -> tuple[SysOAuthClient, list[tuple[SysOAuthScope, int]], list[str], Sequence[SysOAuthClientUri]] | None:
"""
- 查询 OAuth Client 详情及关联数据
+ 查询 OAuth Client 详情及关联数据。
:param db: orm对象
:param client_id: Client 公开标识
:return: OAuth Client、Scope 绑定统计、Resource 标识和回调地址组成的元组,不存在时返回 None
"""
-
client = await cls.get_by_client_id(db, client_id, active_only=False)
if client is None:
return None
@@ -651,13 +614,12 @@ async def get_client_detail_rows(
@classmethod
async def list_clients_page(cls, db: AsyncSession, page: ClientPageQueryModel) -> Sequence[SysOAuthClient]:
"""
- 分页查询 OAuth Client
+ 分页查询 OAuth Client。
:param db: orm对象
:param page: 分页查询条件对象
:return: OAuth Client 序列
"""
-
conditions = []
if page.client_name:
conditions.append(SysOAuthClient.client_name.contains(page.client_name, autoescape=True, escape='\\'))
@@ -678,13 +640,12 @@ async def list_clients_page(cls, db: AsyncSession, page: ClientPageQueryModel) -
@classmethod
async def count_clients(cls, db: AsyncSession, page: ClientPageQueryModel) -> int:
"""
- 统计 OAuth Client 数量
+ 统计 OAuth Client 数量。
:param db: orm对象
:param page: 分页查询条件对象
:return: OAuth Client 数量
"""
-
conditions = []
if page.client_name:
conditions.append(SysOAuthClient.client_name.contains(page.client_name, autoescape=True, escape='\\'))
@@ -699,12 +660,11 @@ async def count_clients(cls, db: AsyncSession, page: ClientPageQueryModel) -> in
@classmethod
async def list_cors_origins(cls, db: AsyncSession) -> tuple[str, ...]:
"""
- 查询 OAuth Client 跨域来源
+ 查询 OAuth Client 跨域来源。
:param db: orm对象
:return: 去重后的 CORS 来源元组
"""
-
result = await db.execute(
select(SysOAuthClientUri.uri)
.join(SysOAuthClient, SysOAuthClient.client_pk == SysOAuthClientUri.client_pk)
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oauth_grant_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oauth_grant_dao.py
index 92fab90d8..3ab3eac85 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oauth_grant_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oauth_grant_dao.py
@@ -15,7 +15,23 @@
@dataclass(frozen=True, slots=True)
class OAuthGrantSnapshot:
"""
- OAuth Grant 可恢复快照
+ OAuth Grant 可恢复快照。
+
+ :ivar grant_id: Grant 公开标识
+ :ivar user_id: 用户的唯一标识
+ :ivar subject_id: 主体标识
+ :ivar client_pk: Client 内部主键
+ :ivar granted_scopes: 授权 Scope 编码序列
+ :ivar granted_resources: 授权 Resource 标识序列
+ :ivar client_policy_version: Client 策略版本
+ :ivar status: 状态过滤值
+ :ivar consented_at: 用户同意授权的时间
+ :ivar expires_at: 授权过期时间
+ :ivar revoked_at: 撤销时间
+ :ivar revoke_reason: 撤销原因
+ :ivar last_used_at: 授权最近使用时间
+ :ivar remembered_scopes: 后续可免确认的权限列表
+ :ivar remembered_resources: 后续可免确认的资源列表
"""
grant_id: str
@@ -36,23 +52,20 @@ class OAuthGrantSnapshot:
class OAuthGrantDao:
- """
- OAuth Grant 数据库操作层
- """
+ """OAuth Grant 数据库操作层。"""
@classmethod
async def get_by_grant_id_for_update(
cls, db: AsyncSession, grant_id: str, *, refresh: bool = False
) -> SysOAuthGrant | None:
"""
- 按授权标识锁定查询 OAuth Grant
+ 按授权标识锁定查询 OAuth Grant。
:param db: orm对象
:param grant_id: Grant 公开标识
:param refresh: 是否使用数据库当前值刷新已有对象
:return: OAuth Grant,不存在时返回 None
"""
-
query = select(SysOAuthGrant).where(SysOAuthGrant.grant_id == grant_id).with_for_update()
if refresh:
query = query.execution_options(populate_existing=True)
@@ -65,7 +78,7 @@ async def get_active_for_user_client(
cls, db: AsyncSession, user_id: int, client_pk: int, for_update: bool = False
) -> SysOAuthGrant | None:
"""
- 查询用户与 Client 的活跃 OAuth Grant
+ 查询用户与 Client 的活跃 OAuth Grant。
:param db: orm对象
:param user_id: 用户编号
@@ -73,7 +86,6 @@ async def get_active_for_user_client(
:param for_update: 是否锁定查询结果
:return: 活跃 OAuth Grant,不存在时返回 None
"""
-
query = select(SysOAuthGrant).where(
SysOAuthGrant.user_id == user_id,
SysOAuthGrant.client_pk == client_pk,
@@ -91,14 +103,13 @@ async def list_active_for_user_client(
cls, db: AsyncSession, user_id: int, client_pk: int
) -> Sequence[SysOAuthGrant]:
"""
- 查询用户与 Client 的活跃 OAuth Grant 列表
+ 查询用户与 Client 的活跃 OAuth Grant 列表。
:param db: orm对象
:param user_id: 用户编号
:param client_pk: Client 内部主键
:return: 活跃 OAuth Grant 序列
"""
-
result = await db.execute(
select(SysOAuthGrant).where(
SysOAuthGrant.user_id == user_id,
@@ -124,7 +135,7 @@ async def merge_active_grant(
remember_consent: bool = True,
) -> SysOAuthGrant:
"""
- 合并用户与 Client 的活跃 OAuth Grant
+ 合并用户与 Client 的活跃 OAuth Grant。
:param db: orm对象
:param user_id: 用户编号
@@ -137,7 +148,6 @@ async def merge_active_grant(
:param remember_consent: 是否允许后续请求复用本次同意,独立于离线授权
:return: 新增或更新后的 OAuth Grant
"""
-
await OAuthAccessPolicyDao.lock_client(db, client_pk)
grant = await cls.get_active_for_user_client(db, user_id, client_pk, for_update=True)
now = TimezoneUtil.utc_now()
@@ -181,12 +191,11 @@ async def merge_active_grant(
@staticmethod
def snapshot(grant: SysOAuthGrant) -> OAuthGrantSnapshot:
"""
- 生成 OAuth Grant 可恢复快照
+ 生成 OAuth Grant 可恢复快照。
:param grant: OAuth Grant 对象
:return: OAuth Grant 快照
"""
-
return OAuthGrantSnapshot(
grant_id=grant.grant_id,
user_id=grant.user_id,
@@ -213,14 +222,13 @@ async def restore_snapshot(
expected: OAuthGrantSnapshot,
) -> bool:
"""
- 恢复 OAuth Grant 可恢复快照
+ 恢复 OAuth Grant 可恢复快照。
:param db: orm对象
:param snapshot: OAuth Grant 快照
:param expected: 期望状态
:return: 是否恢复成功
"""
-
await OAuthAccessPolicyDao.lock_client(db, snapshot.client_pk)
grant = await cls.get_by_grant_id_for_update(db, snapshot.grant_id, refresh=True)
if grant is None or cls.snapshot(grant) != expected:
@@ -244,14 +252,13 @@ async def restore_snapshot(
@classmethod
async def revoke_snapshot(cls, db: AsyncSession, snapshot: OAuthGrantSnapshot, reason: str) -> bool:
"""
- 撤销快照对应的 OAuth Grant
+ 撤销快照对应的 OAuth Grant。
:param db: orm对象
:param snapshot: OAuth Grant 快照
:param reason: 撤销或标记原因
:return: 是否撤销成功
"""
-
await OAuthAccessPolicyDao.lock_client(db, snapshot.client_pk)
grant = await cls.get_by_grant_id_for_update(db, snapshot.grant_id, refresh=True)
if grant is None or cls.snapshot(grant) != snapshot:
@@ -277,7 +284,7 @@ async def get_valid_for_user_client(
cls, db: AsyncSession, user_id: int, client_pk: int, for_update: bool = False
) -> SysOAuthGrant | None:
"""
- 查询用户与 Client 的有效 OAuth Grant
+ 查询用户与 Client 的有效 OAuth Grant。
:param db: orm对象
:param user_id: 用户编号
@@ -285,7 +292,6 @@ async def get_valid_for_user_client(
:param for_update: 是否锁定查询结果
:return: 有效 OAuth Grant,不存在时返回 None
"""
-
query = (
select(SysOAuthGrant)
.join(SysOAuthClient, SysOAuthClient.client_pk == SysOAuthGrant.client_pk)
@@ -307,14 +313,13 @@ async def get_valid_for_user_client(
@classmethod
async def revoke(cls, db: AsyncSession, grant_id: str, reason: str | None = None) -> bool:
"""
- 撤销 OAuth Grant
+ 撤销 OAuth Grant。
:param db: orm对象
:param grant_id: Grant 公开标识
:param reason: 撤销或标记原因
:return: 是否撤销成功
"""
-
grant = await db.execute(select(SysOAuthGrant).where(SysOAuthGrant.grant_id == grant_id).with_for_update())
row = grant.scalars().first()
if row is None:
@@ -344,13 +349,12 @@ async def revoke(cls, db: AsyncSession, grant_id: str, reason: str | None = None
@staticmethod
async def targets(db: AsyncSession, grant_ids: list[str]) -> list[tuple[int, int]]:
"""
- 将选中授权归并为用户和 Client,按 Client 排序以统一批量锁序
+ 将选中授权归并为用户和 Client,按 Client 排序以统一批量锁序。
:param db: orm对象
:param grant_ids: 选中的授权标识
:return: 去重后的 Client 主键和用户编号列表
"""
-
result = await db.execute(
select(SysOAuthGrant.client_pk, SysOAuthGrant.user_id)
.where(SysOAuthGrant.grant_id.in_(grant_ids))
@@ -362,7 +366,7 @@ async def targets(db: AsyncSession, grant_ids: list[str]) -> list[tuple[int, int
@classmethod
async def revoke_for_user_client(cls, db: AsyncSession, user_id: int, client_pk: int, reason: str) -> list[str]:
"""
- 撤销用户对 Client 的全部现有授权;调用方须先锁定 Client
+ 撤销用户对 Client 的全部现有授权;调用方须先锁定 Client。
:param db: orm对象
:param user_id: 用户编号
@@ -370,7 +374,6 @@ async def revoke_for_user_client(cls, db: AsyncSession, user_id: int, client_pk:
:param reason: 撤销原因
:return: 实际撤销的授权标识列表
"""
-
result = await db.execute(
select(SysOAuthGrant.grant_id)
.where(
@@ -389,14 +392,13 @@ async def revoke_for_user_client(cls, db: AsyncSession, user_id: int, client_pk:
@classmethod
async def revoke_for_user(cls, db: AsyncSession, user_id: int, reason: str | None = None) -> int:
"""
- 撤销用户的 OAuth Grant
+ 撤销用户的 OAuth Grant。
:param db: orm对象
:param user_id: 用户编号
:param reason: 撤销或标记原因
:return: 已撤销的 OAuth Grant 数量
"""
-
result = await db.execute(
update(SysOAuthGrant)
.where(SysOAuthGrant.user_id == user_id, SysOAuthGrant.status == 'active')
@@ -408,14 +410,13 @@ async def revoke_for_user(cls, db: AsyncSession, user_id: int, reason: str | Non
@classmethod
async def list_for_user(cls, db: AsyncSession, user_id: int, status: str | None = None) -> Sequence[SysOAuthGrant]:
"""
- 查询用户 OAuth Grant 列表
+ 查询用户 OAuth Grant 列表。
:param db: orm对象
:param user_id: 用户编号
:param status: 状态过滤值
:return: 用户 OAuth Grant 序列
"""
-
query = select(SysOAuthGrant).where(SysOAuthGrant.user_id == user_id)
if status:
query = query.where(SysOAuthGrant.status == status)
@@ -426,14 +427,13 @@ async def list_for_user(cls, db: AsyncSession, user_id: int, status: str | None
@classmethod
async def get_by_grant_id(cls, db: AsyncSession, grant_id: str, for_update: bool = False) -> SysOAuthGrant | None:
"""
- 按授权标识查询 OAuth Grant
+ 按授权标识查询 OAuth Grant。
:param db: orm对象
:param grant_id: Grant 公开标识
:param for_update: 是否锁定查询结果
:return: OAuth Grant,不存在时返回 None
"""
-
query = select(SysOAuthGrant).where(SysOAuthGrant.grant_id == grant_id)
if for_update:
query = query.with_for_update().execution_options(populate_existing=True)
@@ -456,7 +456,7 @@ async def list_page(
limit: int = 200,
) -> Sequence[SysOAuthGrant]:
"""
- 分页查询 OAuth Grant
+ 分页查询 OAuth Grant。
:param db: orm对象
:param user_id: 用户编号
@@ -467,7 +467,6 @@ async def list_page(
:param limit: 分页大小
:return: OAuth Grant 序列
"""
-
conditions = []
if user_id is not None:
conditions.append(SysOAuthGrant.user_id == user_id)
@@ -513,7 +512,7 @@ async def count(
access_status: str | None = None,
) -> int:
"""
- 统计 OAuth Grant 数量
+ 统计 OAuth Grant 数量。
:param db: orm对象
:param user_id: 用户编号
@@ -522,7 +521,6 @@ async def count(
:param access_status: 用户对应用的访问策略
:return: OAuth Grant 数量
"""
-
conditions = []
if user_id is not None:
conditions.append(SysOAuthGrant.user_id == user_id)
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oauth_resource_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oauth_resource_dao.py
index 192a274bd..09fdc3a20 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oauth_resource_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oauth_resource_dao.py
@@ -16,58 +16,48 @@
class OAuthResourceDao:
- """
- OAuth Resource 数据库操作层
- """
+ """OAuth Resource 数据库操作层。"""
@classmethod
async def add_resource(cls, db: AsyncSession, resource: SysOAuthResource) -> None:
"""
- 新增 OAuth Resource 并刷新主键
+ 新增 OAuth Resource 并刷新主键。
:param db: orm对象
:param resource: OAuth Resource 对象
- :return: None
"""
-
db.add(resource)
await db.flush()
@classmethod
async def add_scope(cls, db: AsyncSession, scope: SysOAuthScope) -> None:
"""
- 新增 OAuth Scope 并刷新主键
+ 新增 OAuth Scope 并刷新主键。
:param db: orm对象
:param scope: OAuth Scope 对象
- :return: None
"""
-
db.add(scope)
await db.flush()
@classmethod
async def persist_resource_change(cls, db: AsyncSession, resource: SysOAuthResource) -> None:
"""
- 刷新 OAuth Resource 变更
+ 刷新 OAuth Resource 变更。
:param db: orm对象
:param resource: OAuth Resource 对象
- :return: None
"""
-
await db.flush()
@classmethod
async def persist_scope_change(cls, db: AsyncSession, scope: SysOAuthScope) -> None:
"""
- 刷新 OAuth Scope 变更
+ 刷新 OAuth Scope 变更。
:param db: orm对象
:param scope: OAuth Scope 对象
- :return: None
"""
-
await db.flush()
@classmethod
@@ -75,14 +65,13 @@ async def get_resource(
cls, db: AsyncSession, resource_id: str, *, for_update: bool = False
) -> SysOAuthResource | None:
"""
- 按资源标识查询 OAuth Resource
+ 按资源标识查询 OAuth Resource。
:param db: orm对象
:param resource_id: Resource 公开标识
:param for_update: 是否锁定查询结果
:return: OAuth Resource,不存在时返回 None
"""
-
query = select(SysOAuthResource).where(SysOAuthResource.resource_id == resource_id)
if for_update:
query = query.with_for_update()
@@ -93,14 +82,13 @@ async def get_resource(
@classmethod
async def find_resource_duplicate(cls, db: AsyncSession, resource_id: str, audience: str) -> bool:
"""
- 按资源标识和受众查询重复 Resource
+ 按资源标识和受众查询重复 Resource。
:param db: orm对象
:param resource_id: Resource 公开标识
:param audience: Resource 受众
:return: 是否存在重复 Resource
"""
-
result = await db.execute(
select(SysOAuthResource.resource_pk).where(
(SysOAuthResource.resource_id == resource_id) | (SysOAuthResource.audience == audience)
@@ -112,13 +100,12 @@ async def find_resource_duplicate(cls, db: AsyncSession, resource_id: str, audie
@classmethod
async def list_resources_page(cls, db: AsyncSession, page: ResourcePageQueryModel) -> Sequence[SysOAuthResource]:
"""
- 分页查询 OAuth Resource
+ 分页查询 OAuth Resource。
:param db: orm对象
:param page: 分页查询条件对象
:return: OAuth Resource 序列
"""
-
conditions = []
if page.resource_name:
conditions.append(SysOAuthResource.resource_name.contains(page.resource_name, autoescape=True, escape='\\'))
@@ -137,13 +124,12 @@ async def list_resources_page(cls, db: AsyncSession, page: ResourcePageQueryMode
@classmethod
async def count_resources(cls, db: AsyncSession, page: ResourcePageQueryModel) -> int:
"""
- 统计 OAuth Resource 数量
+ 统计 OAuth Resource 数量。
:param db: orm对象
:param page: 分页查询条件对象
:return: OAuth Resource 数量
"""
-
conditions = []
if page.resource_name:
conditions.append(SysOAuthResource.resource_name.contains(page.resource_name, autoescape=True, escape='\\'))
@@ -156,13 +142,12 @@ async def count_resources(cls, db: AsyncSession, page: ResourcePageQueryModel) -
@classmethod
async def active_resource(cls, db: AsyncSession, resource_id: str | None) -> SysOAuthResource | None:
"""
- 按资源标识查询启用 OAuth Resource
+ 按资源标识查询启用 OAuth Resource。
:param db: orm对象
:param resource_id: Resource 公开标识
:return: 启用 OAuth Resource,不存在时返回 None
"""
-
if not resource_id:
return None
result = await db.execute(
@@ -174,13 +159,12 @@ async def active_resource(cls, db: AsyncSession, resource_id: str | None) -> Sys
@classmethod
async def active_by_audiences(cls, db: AsyncSession, audiences: Sequence[str]) -> Sequence[SysOAuthResource]:
"""
- 按受众批量查询启用 OAuth Resource
+ 按受众批量查询启用 OAuth Resource。
:param db: orm对象
:param audiences: Resource 受众序列
:return: 启用 OAuth Resource 序列
"""
-
if not audiences:
return ()
result = await db.execute(
@@ -192,14 +176,13 @@ async def active_by_audiences(cls, db: AsyncSession, audiences: Sequence[str]) -
@classmethod
async def get_scope(cls, db: AsyncSession, scope_code: str, *, for_update: bool = False) -> SysOAuthScope | None:
"""
- 按 Scope 编码查询 OAuth Scope
+ 按 Scope 编码查询 OAuth Scope。
:param db: orm对象
:param scope_code: Scope 编码
:param for_update: 是否锁定查询结果
:return: OAuth Scope,不存在时返回 None
"""
-
query = select(SysOAuthScope).where(SysOAuthScope.scope_code == scope_code)
if for_update:
query = query.with_for_update()
@@ -210,13 +193,12 @@ async def get_scope(cls, db: AsyncSession, scope_code: str, *, for_update: bool
@classmethod
async def find_scope_duplicate(cls, db: AsyncSession, scope_code: str) -> bool:
"""
- 按 Scope 编码查询重复 OAuth Scope
+ 按 Scope 编码查询重复 OAuth Scope。
:param db: orm对象
:param scope_code: Scope 编码
:return: 是否存在重复 Scope
"""
-
result = await db.execute(select(SysOAuthScope.scope_pk).where(SysOAuthScope.scope_code == scope_code))
return result.scalar_one_or_none() is not None
@@ -224,13 +206,12 @@ async def find_scope_duplicate(cls, db: AsyncSession, scope_code: str) -> bool:
@classmethod
async def list_scopes_page(cls, db: AsyncSession, page: ScopePageQueryModel) -> Sequence[SysOAuthScope]:
"""
- 分页查询 OAuth Scope
+ 分页查询 OAuth Scope。
:param db: orm对象
:param page: 分页查询条件对象
:return: OAuth Scope 序列
"""
-
conditions = []
if page.scope_name:
conditions.append(SysOAuthScope.scope_name.contains(page.scope_name, autoescape=True, escape='\\'))
@@ -251,13 +232,12 @@ async def list_scopes_page(cls, db: AsyncSession, page: ScopePageQueryModel) ->
@classmethod
async def count_scopes(cls, db: AsyncSession, page: ScopePageQueryModel) -> int:
"""
- 统计 OAuth Scope 数量
+ 统计 OAuth Scope 数量。
:param db: orm对象
:param page: 分页查询条件对象
:return: OAuth Scope 数量
"""
-
conditions = []
if page.scope_name:
conditions.append(SysOAuthScope.scope_name.contains(page.scope_name, autoescape=True, escape='\\'))
@@ -272,13 +252,12 @@ async def count_scopes(cls, db: AsyncSession, page: ScopePageQueryModel) -> int:
@classmethod
async def resource_id_for_scope(cls, db: AsyncSession, resource_pk: int) -> str | None:
"""
- 按 Resource 主键查询资源标识
+ 按 Resource 主键查询资源标识。
:param db: orm对象
:param resource_pk: Resource 内部主键
:return: Resource 公开标识,不存在时返回 None
"""
-
result = await db.execute(
select(SysOAuthResource.resource_id).where(SysOAuthResource.resource_pk == resource_pk)
)
@@ -288,13 +267,12 @@ async def resource_id_for_scope(cls, db: AsyncSession, resource_pk: int) -> str
@classmethod
async def lock_scope_clients(cls, db: AsyncSession, scope_pk: int) -> Sequence[SysOAuthClient]:
"""
- 锁定查询 Scope 关联的 OAuth Client
+ 锁定查询 Scope 关联的 OAuth Client。
:param db: orm对象
:param scope_pk: Scope 内部主键
:return: Scope 关联的 OAuth Client 序列
"""
-
result = await db.execute(
select(SysOAuthClient)
.join(SysOAuthClientScope, SysOAuthClientScope.client_pk == SysOAuthClient.client_pk)
@@ -307,13 +285,12 @@ async def lock_scope_clients(cls, db: AsyncSession, scope_pk: int) -> Sequence[S
@classmethod
async def client_ids_for_resource(cls, db: AsyncSession, resource_pk: int) -> Sequence[tuple[int, str]]:
"""
- 查询 Resource 直接绑定的 Client 主键和公开标识
+ 查询 Resource 直接绑定的 Client 主键和公开标识。
:param db: orm对象
:param resource_pk: Resource 内部主键
:return: Client 内部主键和公开标识元组序列
"""
-
result = await db.execute(
select(SysOAuthClient.client_pk, SysOAuthClient.client_id)
.join(SysOAuthClientResource, SysOAuthClientResource.client_pk == SysOAuthClient.client_pk)
@@ -326,13 +303,12 @@ async def client_ids_for_resource(cls, db: AsyncSession, resource_pk: int) -> Se
@classmethod
async def client_ids_for_resource_scope(cls, db: AsyncSession, resource_pk: int) -> Sequence[tuple[int, str]]:
"""
- 查询 Resource 通过 Scope 绑定的 Client 主键和公开标识
+ 查询 Resource 通过 Scope 绑定的 Client 主键和公开标识。
:param db: orm对象
:param resource_pk: Resource 内部主键
:return: 通过 Scope 关联的 Client 内部主键和公开标识元组序列
"""
-
result = await db.execute(
select(SysOAuthClient.client_pk, SysOAuthClient.client_id)
.join(SysOAuthClientScope, SysOAuthClientScope.client_pk == SysOAuthClient.client_pk)
@@ -346,13 +322,12 @@ async def client_ids_for_resource_scope(cls, db: AsyncSession, resource_pk: int)
@classmethod
async def active_grants(cls, db: AsyncSession, client_pks: Sequence[int]) -> Sequence[SysOAuthGrant]:
"""
- 按 Client 主键查询活跃 OAuth Grant
+ 按 Client 主键查询活跃 OAuth Grant。
:param db: orm对象
:param client_pks: Client 内部主键序列
:return: 活跃 OAuth Grant 序列
"""
-
if not client_pks:
return ()
result = await db.execute(
@@ -364,13 +339,12 @@ async def active_grants(cls, db: AsyncSession, client_pks: Sequence[int]) -> Seq
@classmethod
async def active_refresh_tokens(cls, db: AsyncSession, client_pks: Sequence[int]) -> Sequence[SysOAuthRefreshToken]:
"""
- 按 Client 主键查询活跃 Refresh Token
+ 按 Client 主键查询活跃 Refresh Token。
:param db: orm对象
:param client_pks: Client 内部主键序列
:return: 活跃 OAuth Refresh Token 序列
"""
-
if not client_pks:
return ()
result = await db.execute(
@@ -384,15 +358,13 @@ async def active_refresh_tokens(cls, db: AsyncSession, client_pks: Sequence[int]
@classmethod
async def revoke_credentials(cls, db: AsyncSession, client_pks: Sequence[int], now: datetime, reason: str) -> None:
"""
- 撤销 Client 主键对应的 Grant 和 Refresh Token
+ 撤销 Client 主键对应的 Grant 和 Refresh Token。
:param db: orm对象
:param client_pks: Client 内部主键序列
:param now: 当前时间
:param reason: 撤销或标记原因
- :return: None
"""
-
if not client_pks:
return
await db.execute(
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oauth_token_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oauth_token_dao.py
index cb31104cf..c2bad8d06 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oauth_token_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oauth_token_dao.py
@@ -9,20 +9,17 @@
class OAuthTokenDao:
- """
- OAuth Token 数据库操作层
- """
+ """OAuth Token 数据库操作层。"""
@classmethod
async def create(cls, db: AsyncSession, row: SysOAuthRefreshToken) -> SysOAuthRefreshToken:
"""
- 新增 OAuth Refresh Token 并刷新主键
+ 新增 OAuth Refresh Token 并刷新主键。
:param db: orm对象
:param row: OAuth Refresh Token 对象
:return: 已写入的 OAuth Refresh Token
"""
-
db.add(row)
await db.flush()
@@ -33,14 +30,13 @@ async def get_by_token_id(
cls, db: AsyncSession, token_id: str, for_update: bool = False
) -> SysOAuthRefreshToken | None:
"""
- 按 Token 标识查询 OAuth Refresh Token
+ 按 Token 标识查询 OAuth Refresh Token。
:param db: orm对象
:param token_id: Token 公开标识
:param for_update: 是否锁定查询结果
:return: OAuth Refresh Token,不存在时返回 None
"""
-
query = select(SysOAuthRefreshToken).where(SysOAuthRefreshToken.token_id == token_id)
if for_update:
query = query.with_for_update()
@@ -53,14 +49,13 @@ async def get_by_hash(
cls, db: AsyncSession, token_hash: str, for_update: bool = False
) -> SysOAuthRefreshToken | None:
"""
- 按 Token 摘要查询 OAuth Refresh Token
+ 按 Token 摘要查询 OAuth Refresh Token。
:param db: orm对象
:param token_hash: Token 摘要
:param for_update: 是否锁定查询结果
:return: OAuth Refresh Token,不存在时返回 None
"""
-
query = select(SysOAuthRefreshToken).where(SysOAuthRefreshToken.token_hash == token_hash)
if for_update:
query = query.with_for_update()
@@ -71,13 +66,12 @@ async def get_by_hash(
@classmethod
async def lock_family(cls, db: AsyncSession, family_id: str) -> Sequence[SysOAuthRefreshToken]:
"""
- 锁定查询 OAuth Refresh Token 家族
+ 锁定查询 OAuth Refresh Token 家族。
:param db: orm对象
:param family_id: Token 家族标识
:return: OAuth Refresh Token 序列
"""
-
result = await db.execute(
select(SysOAuthRefreshToken)
.where(SysOAuthRefreshToken.family_id == family_id)
@@ -90,13 +84,12 @@ async def lock_family(cls, db: AsyncSession, family_id: str) -> Sequence[SysOAut
@classmethod
async def family_is_active(cls, db: AsyncSession, family_id: str) -> bool:
"""
- 查询 OAuth Refresh Token 家族是否活跃
+ 查询 OAuth Refresh Token 家族是否活跃。
:param db: orm对象
:param family_id: Token 家族标识
:return: OAuth Refresh Token 家族是否活跃
"""
-
rows = await cls.lock_family(db, family_id)
return bool(rows) and not any(row.status in {'revoked', 'reuse_detected', 'family_revoked'} for row in rows)
@@ -104,13 +97,12 @@ async def family_is_active(cls, db: AsyncSession, family_id: str) -> bool:
@classmethod
async def list_for_sid_for_update(cls, db: AsyncSession, sid: str) -> Sequence[SysOAuthRefreshToken]:
"""
- 按 Session 标识锁定查询 Refresh Token
+ 按 Session 标识锁定查询 Refresh Token。
:param db: orm对象
:param sid: SSO Session 标识
:return: SSO Session 关联的 Refresh Token 序列
"""
-
result = await db.execute(select(SysOAuthRefreshToken).where(SysOAuthRefreshToken.sid == sid).with_for_update())
return result.scalars().all()
@@ -125,7 +117,7 @@ async def mark_used(
now: datetime | None = None,
) -> bool:
"""
- 标记 OAuth Refresh Token 已使用
+ 标记 OAuth Refresh Token 已使用。
:param db: orm对象
:param token_id: Token 公开标识
@@ -133,7 +125,6 @@ async def mark_used(
:param now: 当前时间
:return: 是否更新成功
"""
-
values: dict[str, object] = {'status': 'used', 'last_used_at': now or TimezoneUtil.utc_now()}
if replaced_by_token_id is not None:
values['replaced_by_token_id'] = replaced_by_token_id
@@ -148,14 +139,13 @@ async def mark_used(
@classmethod
async def mark_reuse_detected(cls, db: AsyncSession, token_id: str, reason: str = 'refresh_token_reuse') -> bool:
"""
- 标记 OAuth Refresh Token 重用
+ 标记 OAuth Refresh Token 重用。
:param db: orm对象
:param token_id: Token 公开标识
:param reason: 撤销或标记原因
:return: 是否更新成功
"""
-
now = TimezoneUtil.utc_now()
result = await db.execute(
update(SysOAuthRefreshToken)
@@ -176,7 +166,7 @@ async def refresh_token_family_reuse(
now: datetime | None = None,
) -> int:
"""
- 处理 OAuth Refresh Token 家族重用
+ 处理 OAuth Refresh Token 家族重用。
:param db: orm对象
:param family_id: Token 家族标识
@@ -185,7 +175,6 @@ async def refresh_token_family_reuse(
:param now: 当前时间
:return: 已撤销的 OAuth Refresh Token 数量
"""
-
await cls.lock_family(db, family_id)
current = now or TimezoneUtil.utc_now()
other_result = await db.execute(
@@ -208,14 +197,13 @@ async def refresh_token_family_reuse(
@classmethod
async def revoke_family(cls, db: AsyncSession, family_id: str, reason: str | None = None) -> int:
"""
- 撤销 OAuth Refresh Token 家族
+ 撤销 OAuth Refresh Token 家族。
:param db: orm对象
:param family_id: Token 家族标识
:param reason: 撤销或标记原因
:return: 已撤销的 OAuth Refresh Token 数量
"""
-
result = await db.execute(
update(SysOAuthRefreshToken)
.where(
@@ -230,14 +218,13 @@ async def revoke_family(cls, db: AsyncSession, family_id: str, reason: str | Non
@classmethod
async def revoke_for_user(cls, db: AsyncSession, user_id: int, reason: str | None = None) -> int:
"""
- 撤销用户的 OAuth Refresh Token
+ 撤销用户的 OAuth Refresh Token。
:param db: orm对象
:param user_id: 用户编号
:param reason: 撤销或标记原因
:return: 已撤销的 OAuth Refresh Token 数量
"""
-
result = await db.execute(
update(SysOAuthRefreshToken)
.where(SysOAuthRefreshToken.user_id == user_id, SysOAuthRefreshToken.status.not_in(['revoked', 'expired']))
@@ -251,7 +238,7 @@ async def revoke_for_users(
cls, db: AsyncSession, user_ids: Sequence[int], reason: str | None = None, now: datetime | None = None
) -> int:
"""
- 批量撤销用户的 OAuth Refresh Token
+ 批量撤销用户的 OAuth Refresh Token。
:param db: orm对象
:param user_ids: 用户编号序列
@@ -259,7 +246,6 @@ async def revoke_for_users(
:param now: 当前时间
:return: 已撤销的 OAuth Refresh Token 数量
"""
-
result = await db.execute(
update(SysOAuthRefreshToken)
.where(
@@ -275,12 +261,11 @@ async def revoke_for_users(
@classmethod
async def expire_due(cls, db: AsyncSession) -> int:
"""
- 处理已到期的 OAuth Refresh Token
+ 处理已到期的 OAuth Refresh Token。
:param db: orm对象
:return: 已过期的 OAuth Refresh Token 数量
"""
-
result = await db.execute(
update(SysOAuthRefreshToken)
.where(
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oidc_key_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oidc_key_dao.py
index c10dfe690..1bf622003 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oidc_key_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oidc_key_dao.py
@@ -9,23 +9,20 @@
class OidcKeyDao:
- """
- OIDC Key 数据库操作层
- """
+ """OIDC Key 数据库操作层。"""
@classmethod
async def get_active(
cls, db: AsyncSession, alg: str = 'RS256', for_update: bool = False
) -> SysOidcSigningKey | None:
"""
- 按签名算法查询活跃 OIDC Signing Key
+ 按签名算法查询活跃 OIDC Signing Key。
:param db: orm对象
:param alg: 签名算法
:param for_update: 是否锁定查询结果
:return: 活跃 OIDC Signing Key,不存在时返回 None
"""
-
query = select(SysOidcSigningKey).where(
SysOidcSigningKey.status == 'active',
SysOidcSigningKey.alg == alg,
@@ -40,13 +37,12 @@ async def get_active(
@classmethod
async def list_published(cls, db: AsyncSession, now: datetime | None = None) -> Sequence[SysOidcSigningKey]:
"""
- 查询已发布的 OIDC Signing Key
+ 查询已发布的 OIDC Signing Key。
:param db: orm对象
:param now: 当前时间
:return: 已发布的 OIDC Signing Key 序列
"""
-
current = now or TimezoneUtil.utc_now()
result = await db.execute(
select(SysOidcSigningKey)
@@ -63,14 +59,13 @@ async def list_published(cls, db: AsyncSession, now: datetime | None = None) ->
@classmethod
async def get_verifying(cls, db: AsyncSession, kid: str, now: datetime) -> SysOidcSigningKey | None:
"""
- 按 kid 查询可用于验签的 OIDC Signing Key
+ 按 kid 查询可用于验签的 OIDC Signing Key。
:param db: orm对象
:param kid: Signing Key 标识
:param now: 当前时间
:return: 可验签的 OIDC Signing Key,不存在时返回 None
"""
-
result = await db.execute(
select(SysOidcSigningKey).where(
SysOidcSigningKey.kid == kid,
@@ -88,7 +83,7 @@ async def list_admin(
cls, db: AsyncSession, *, status: str | None = None, offset: int = 0, limit: int = 200
) -> Sequence[SysOidcSigningKey]:
"""
- 分页查询管理端 OIDC Signing Key
+ 分页查询管理端 OIDC Signing Key。
:param db: orm对象
:param status: 状态过滤值
@@ -96,7 +91,6 @@ async def list_admin(
:param limit: 分页大小
:return: 管理端 OIDC Signing Key 序列
"""
-
query = select(SysOidcSigningKey)
if status:
query = query.where(SysOidcSigningKey.status == status)
@@ -109,13 +103,12 @@ async def list_admin(
@classmethod
async def list_due_pending(cls, db: AsyncSession, now: datetime | None = None) -> Sequence[SysOidcSigningKey]:
"""
- 查询待发布时间已到的 OIDC Signing Key
+ 查询待发布时间已到的 OIDC Signing Key。
:param db: orm对象
:param now: 当前时间
:return: 待激活 OIDC Signing Key 序列
"""
-
current = now or TimezoneUtil.utc_now()
result = await db.execute(
select(SysOidcSigningKey)
@@ -133,13 +126,12 @@ async def list_due_pending(cls, db: AsyncSession, now: datetime | None = None) -
@classmethod
async def count_admin(cls, db: AsyncSession, *, status: str | None = None) -> int:
"""
- 统计管理端 OIDC Signing Key 数量
+ 统计管理端 OIDC Signing Key 数量。
:param db: orm对象
:param status: 状态过滤值
:return: 管理端 OIDC Signing Key 数量
"""
-
query = select(func.count()).select_from(SysOidcSigningKey)
if status:
query = query.where(SysOidcSigningKey.status == status)
@@ -150,13 +142,12 @@ async def count_admin(cls, db: AsyncSession, *, status: str | None = None) -> in
@classmethod
async def get_by_kid_for_update(cls, db: AsyncSession, kid: str) -> SysOidcSigningKey | None:
"""
- 按 kid 锁定查询 OIDC Signing Key
+ 按 kid 锁定查询 OIDC Signing Key。
:param db: orm对象
:param kid: Signing Key 标识
:return: OIDC Signing Key,不存在时返回 None
"""
-
result = await db.execute(select(SysOidcSigningKey).where(SysOidcSigningKey.kid == kid).with_for_update())
return result.scalars().first()
@@ -164,13 +155,12 @@ async def get_by_kid_for_update(cls, db: AsyncSession, kid: str) -> SysOidcSigni
@classmethod
async def create(cls, db: AsyncSession, record: SysOidcSigningKey) -> SysOidcSigningKey:
"""
- 新增 OIDC Signing Key 并刷新主键
+ 新增 OIDC Signing Key 并刷新主键。
:param db: orm对象
:param record: OIDC Signing Key 对象
:return: 已写入的 OIDC Signing Key
"""
-
db.add(record)
await db.flush()
@@ -185,7 +175,7 @@ async def set_retiring(
now: datetime,
) -> bool:
"""
- 设置 OIDC Signing Key 退役信息
+ 设置 OIDC Signing Key 退役信息。
:param db: orm对象
:param kid: Signing Key 标识
@@ -193,7 +183,6 @@ async def set_retiring(
:param now: 当前时间
:return: 是否更新成功
"""
-
result = await db.execute(
update(SysOidcSigningKey)
.where(SysOidcSigningKey.kid == kid, SysOidcSigningKey.status.in_(['active', 'retiring']))
@@ -205,13 +194,12 @@ async def set_retiring(
@classmethod
async def delete_retired(cls, db: AsyncSession, kid: str) -> bool:
"""
- 删除已退役的 OIDC Signing Key
+ 删除已退役的 OIDC Signing Key。
:param db: orm对象
:param kid: Signing Key 标识
:return: 是否删除成功
"""
-
result = await db.execute(delete(SysOidcSigningKey).where(SysOidcSigningKey.kid == kid))
return bool(result.rowcount)
@@ -219,13 +207,12 @@ async def delete_retired(cls, db: AsyncSession, kid: str) -> bool:
@classmethod
async def lock_algorithm_for_update(cls, db: AsyncSession, alg: str = 'RS256') -> Sequence[SysOidcSigningKey]:
"""
- 按签名算法锁定查询 OIDC Signing Key
+ 按签名算法锁定查询 OIDC Signing Key。
:param db: orm对象
:param alg: 签名算法
:return: 同一算法的 OIDC Signing Key 序列
"""
-
result = await db.execute(
select(SysOidcSigningKey)
.where(SysOidcSigningKey.alg == alg)
@@ -238,7 +225,7 @@ async def lock_algorithm_for_update(cls, db: AsyncSession, alg: str = 'RS256') -
@classmethod
async def activate(cls, db: AsyncSession, kid: str, alg: str = 'RS256', now: datetime | None = None) -> bool:
"""
- 激活 OIDC Signing Key
+ 激活 OIDC Signing Key。
:param db: orm对象
:param kid: Signing Key 标识
@@ -246,7 +233,6 @@ async def activate(cls, db: AsyncSession, kid: str, alg: str = 'RS256', now: dat
:param now: 当前时间
:return: 是否激活成功
"""
-
current = now or TimezoneUtil.utc_now()
await cls.lock_algorithm_for_update(db, alg=alg)
target_result = await db.execute(
@@ -277,13 +263,12 @@ async def activate(cls, db: AsyncSession, kid: str, alg: str = 'RS256', now: dat
@classmethod
async def mark_compromised(cls, db: AsyncSession, kid: str) -> bool:
"""
- 标记 OIDC Signing Key 已泄露
+ 标记 OIDC Signing Key 已泄露。
:param db: orm对象
:param kid: Signing Key 标识
:return: 是否标记成功
"""
-
result = await db.execute(
update(SysOidcSigningKey)
.where(SysOidcSigningKey.kid == kid, SysOidcSigningKey.status != 'retired')
@@ -295,12 +280,11 @@ async def mark_compromised(cls, db: AsyncSession, kid: str) -> bool:
@classmethod
async def retire_due(cls, db: AsyncSession) -> int:
"""
- 处理到期退役的 OIDC Signing Key
+ 处理到期退役的 OIDC Signing Key。
:param db: orm对象
:return: 已退役的 OIDC Signing Key 数量
"""
-
result = await db.execute(
update(SysOidcSigningKey)
.where(
diff --git a/ruoyi-fastapi-backend/module_identity/dao/sso_session_dao.py b/ruoyi-fastapi-backend/module_identity/dao/sso_session_dao.py
index 8482feb6a..4af4f69b7 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/sso_session_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/sso_session_dao.py
@@ -10,20 +10,17 @@
class SsoSessionDao:
- """
- SSO Session 数据库操作层
- """
+ """SSO Session 数据库操作层。"""
@classmethod
async def create(cls, db: AsyncSession, row: SysSsoSession) -> SysSsoSession:
"""
- 新增 SSO Session 并刷新主键
+ 新增 SSO Session 并刷新主键。
:param db: orm对象
:param row: SSO Session 对象
:return: 已写入的 SSO Session
"""
-
db.add(row)
await db.flush()
@@ -34,7 +31,7 @@ async def get_active(
cls, db: AsyncSession, sid: str, for_update: bool = False, now: datetime | None = None
) -> SysSsoSession | None:
"""
- 按 Session 标识查询活跃 SSO Session
+ 按 Session 标识查询活跃 SSO Session。
:param db: orm对象
:param sid: SSO Session 标识
@@ -42,7 +39,6 @@ async def get_active(
:param now: 当前时间
:return: 活跃 SSO Session,不存在时返回 None
"""
-
now = now or TimezoneUtil.utc_now()
query = select(SysSsoSession).where(
SysSsoSession.sid == sid,
@@ -59,14 +55,13 @@ async def get_active(
@classmethod
async def get_by_sid(cls, db: AsyncSession, sid: str, for_update: bool = False) -> SysSsoSession | None:
"""
- 按 Session 标识查询 SSO Session
+ 按 Session 标识查询 SSO Session。
:param db: orm对象
:param sid: SSO Session 标识
:param for_update: 是否锁定查询结果
:return: SSO Session,不存在时返回 None
"""
-
query = select(SysSsoSession).where(SysSsoSession.sid == sid)
if for_update:
query = query.with_for_update()
@@ -79,7 +74,7 @@ async def get_for_token(
cls, db: AsyncSession, sid: str, *, now: datetime, allow_offline: bool = False
) -> SysSsoSession | None:
"""
- 获取令牌校验所需的 SSO 会话
+ 获取令牌校验所需的 SSO 会话。
自然过期的会话仍可用于离线授权,显式撤销的会话不可继续使用。
@@ -89,7 +84,6 @@ async def get_for_token(
:param allow_offline: 是否允许使用自然过期的离线授权会话
:return: 可用于令牌校验的会话,校验失败时返回None
"""
-
session = await cls.get_active(db, sid, now=now)
if session is not None or not allow_offline:
return session
@@ -105,7 +99,7 @@ async def get_for_token(
@classmethod
async def touch(cls, db: AsyncSession, sid: str, idle_expires_at: datetime, now: datetime | None = None) -> bool:
"""
- 更新 SSO Session 闲置过期时间
+ 更新 SSO Session 闲置过期时间。
:param db: orm对象
:param sid: SSO Session 标识
@@ -113,7 +107,6 @@ async def touch(cls, db: AsyncSession, sid: str, idle_expires_at: datetime, now:
:param now: 当前时间
:return: 是否更新成功
"""
-
current = now or TimezoneUtil.utc_now()
result = await db.execute(
update(SysSsoSession)
@@ -133,7 +126,7 @@ async def touch(cls, db: AsyncSession, sid: str, idle_expires_at: datetime, now:
@classmethod
async def revoke(cls, db: AsyncSession, sid: str, reason: str | None = None, now: datetime | None = None) -> bool:
"""
- 撤销 SSO Session
+ 撤销 SSO Session。
:param db: orm对象
:param sid: SSO Session 标识
@@ -141,7 +134,6 @@ async def revoke(cls, db: AsyncSession, sid: str, reason: str | None = None, now
:param now: 当前时间
:return: 是否撤销成功
"""
-
result = await db.execute(
update(SysSsoSession)
.where(SysSsoSession.sid == sid, SysSsoSession.status.in_(('active', 'expired')))
@@ -156,7 +148,7 @@ async def revoke_for_user(
cls, db: AsyncSession, user_id: int, reason: str | None = None, now: datetime | None = None
) -> int:
"""
- 撤销用户的 SSO Session
+ 撤销用户的 SSO Session。
:param db: orm对象
:param user_id: 用户编号
@@ -164,7 +156,6 @@ async def revoke_for_user(
:param now: 当前时间
:return: 已撤销的 SSO Session 数量
"""
-
result = await db.execute(
update(SysSsoSession)
.where(SysSsoSession.user_id == user_id, SysSsoSession.status.in_(('active', 'expired')))
@@ -184,7 +175,7 @@ async def revoke_for_users(
exclude_sid: str | None = None,
) -> int:
"""
- 批量撤销用户的 SSO Session
+ 批量撤销用户的 SSO Session。
:param db: orm对象
:param user_ids: 用户编号序列
@@ -193,7 +184,6 @@ async def revoke_for_users(
:param exclude_sid: 排除的 SSO Session 标识
:return: 已撤销的 SSO Session 数量
"""
-
conditions = [SysSsoSession.user_id.in_(user_ids), SysSsoSession.status.in_(('active', 'expired'))]
if exclude_sid is not None:
conditions.append(SysSsoSession.sid != exclude_sid)
@@ -209,13 +199,12 @@ async def revoke_for_users(
@classmethod
async def expire_due(cls, db: AsyncSession, now: datetime | None = None) -> int:
"""
- 处理已到期的 SSO Session
+ 处理已到期的 SSO Session。
:param db: orm对象
:param now: 当前时间
:return: 已过期的 SSO Session 数量
"""
-
now = now or TimezoneUtil.utc_now()
result = await db.execute(
update(SysSsoSession)
@@ -234,14 +223,13 @@ async def list_due(
cls, db: AsyncSession, now: datetime | None = None, for_update: bool = False
) -> Sequence[SysSsoSession]:
"""
- 查询待过期的 SSO Session
+ 查询待过期的 SSO Session。
:param db: orm对象
:param now: 当前时间
:param for_update: 是否锁定查询结果
:return: 待过期的 SSO Session 序列
"""
-
current = now or TimezoneUtil.utc_now()
query = select(SysSsoSession).where(
SysSsoSession.status == 'active',
@@ -256,14 +244,13 @@ async def list_due(
@classmethod
async def expire(cls, db: AsyncSession, sid: str, now: datetime | None = None) -> bool:
"""
- 使 SSO Session 过期
+ 使 SSO Session 过期。
:param db: orm对象
:param sid: SSO Session 标识
:param now: 当前时间
:return: 是否过期成功
"""
-
current = now or TimezoneUtil.utc_now()
result = await db.execute(
update(SysSsoSession)
@@ -288,7 +275,7 @@ async def rotate_secret(
now: datetime | None = None,
) -> bool:
"""
- 轮换 SSO Session 密钥摘要
+ 轮换 SSO Session 密钥摘要。
:param db: orm对象
:param sid: SSO Session 标识
@@ -297,7 +284,6 @@ async def rotate_secret(
:param now: 当前时间
:return: 是否轮换成功
"""
-
current = now or TimezoneUtil.utc_now()
result = await db.execute(
update(SysSsoSession)
@@ -325,7 +311,7 @@ async def list_for_user(
revocable_only: bool = False,
) -> Sequence[SysSsoSession]:
"""
- 查询用户 SSO Session 列表
+ 查询用户 SSO Session 列表。
:param db: orm对象
:param user_id: 用户编号
@@ -334,7 +320,6 @@ async def list_for_user(
:param revocable_only: 是否仅查询可撤销的在线或自然过期会话
:return: 用户 SSO Session 序列
"""
-
query = select(SysSsoSession).where(SysSsoSession.user_id == user_id)
if active_only:
query = query.where(SysSsoSession.status == 'active')
@@ -361,7 +346,7 @@ async def list_page(
limit: int = 200,
) -> Sequence[SysSsoSession]:
"""
- 分页查询 SSO Session
+ 分页查询 SSO Session。
:param db: orm对象
:param user_id: 用户编号
@@ -373,7 +358,6 @@ async def list_page(
:param limit: 分页大小
:return: SSO Session 序列
"""
-
conditions = []
if user_id is not None:
conditions.append(SysSsoSession.user_id == user_id)
@@ -417,7 +401,7 @@ async def count(
end_time: datetime | None = None,
) -> int:
"""
- 统计 SSO Session 数量
+ 统计 SSO Session 数量。
:param db: orm对象
:param user_id: 用户编号
@@ -427,7 +411,6 @@ async def count(
:param end_time: 查询结束时间
:return: SSO Session 数量
"""
-
conditions = []
if user_id is not None:
conditions.append(SysSsoSession.user_id == user_id)
@@ -455,15 +438,13 @@ async def count(
@classmethod
async def record_client(cls, db: AsyncSession, sid: str, client_pk: int, now: datetime) -> None:
"""
- 记录成功兑换授权码的会话与应用;调用方须先锁定 Client
+ 记录成功兑换授权码的会话与应用;调用方须先锁定 Client。
:param db: orm对象
:param sid: SSO Session 标识
:param client_pk: Client 内部主键
:param now: 本次授权时间
- :return: None
"""
-
row = await db.scalar(
select(SysSsoSessionClient).where(
SysSsoSessionClient.sid == sid, SysSsoSessionClient.client_pk == client_pk
@@ -478,25 +459,23 @@ async def record_client(cls, db: AsyncSession, sid: str, client_pk: int, now: da
@classmethod
async def client_ids_for_sid(cls, db: AsyncSession, sid: str) -> Sequence[str]:
"""
- 查询精确绑定该会话的参与应用,兼容升级前已有的离线凭据
+ 查询精确绑定该会话的参与应用,兼容升级前已有的离线凭据。
:param db: orm对象
:param sid: SSO Session 标识
:return: 去重后的 Client 公开标识序列
"""
-
return (await cls.client_ids_for_sids(db, [sid])).get(sid, [])
@classmethod
async def client_ids_for_sids(cls, db: AsyncSession, sids: list[str]) -> dict[str, list[str]]:
"""
- 批量查询会话关联应用,避免管理列表逐行查询
+ 批量查询会话关联应用,避免管理列表逐行查询。
:param db: orm对象
:param sids: SSO Session 标识列表
:return: 会话标识与去重客户端标识列表的映射
"""
-
if not sids:
return {}
participants = union(
diff --git a/ruoyi-fastapi-backend/module_identity/dependencies.py b/ruoyi-fastapi-backend/module_identity/dependencies.py
index 0e2dca628..22c09b1cb 100644
--- a/ruoyi-fastapi-backend/module_identity/dependencies.py
+++ b/ruoyi-fastapi-backend/module_identity/dependencies.py
@@ -32,7 +32,10 @@
@dataclass(frozen=True, slots=True)
class AccessTokenContext:
"""
- 已验签且绑定 UserInfo audience 的 Access Token 快照
+ 已验签且绑定 UserInfo audience 的 Access Token 快照。
+
+ :ivar token: 待验证的 JWT;仅用于读取 header kid,不信任其中的公钥材料
+ :ivar claims: 令牌携带的身份声明
"""
token: str
@@ -50,7 +53,7 @@ async def load_access_verification_key(
now: datetime | None = None,
) -> RSAPublicKey:
"""
- 按 Access Token header kid 加载发布窗口内的本地公钥
+ 按 Access Token header kid 加载发布窗口内的本地公钥。
:param token: 待验证的 JWT;仅用于读取 header kid,不信任其中的公钥材料
:param query_db: 异步数据库会话
@@ -58,7 +61,6 @@ async def load_access_verification_key(
:return: 数据库记录对应的 RSA 公钥对象
:raises JwtProfileError: Header、kid 或本地公钥不可用
"""
-
try:
header = jwt.get_unverified_header(token)
except (PyJWTError, TypeError, ValueError) as exc:
@@ -80,9 +82,10 @@ async def load_access_verification_key(
def _disabled() -> None:
"""
- 在 OIDC 关闭时返回本地 404,不执行协议认证
- """
+ 在 OIDC 关闭时返回本地 404,不执行协议认证。
+ :raises HTTPException: 请求的资源不存在
+ """
if not OidcConfig.oidc_enabled:
raise HTTPException(
status_code=404,
@@ -96,17 +99,15 @@ async def require_oidc_protocol_ready(
query_db: AsyncSession = DBSessionDependency(),
) -> None:
"""
- 在 OIDC 已启用但签名能力尚未就绪时阻断公共协议端点
+ 在 OIDC 已启用但签名能力尚未就绪时阻断公共协议端点。
OIDC 关闭时仍由各控制器维持原有本地 404 行为;启用但缺少有效
active 密钥时统一返回标准 OAuth 503,不影响后台管理接口。
:param request: 当前 HTTP 请求
:param query_db: 异步数据库会话
- :return: None
:raises OAuthProtocolException: OIDC 协议尚未具备签名能力
"""
-
if not OidcConfig.oidc_enabled:
return
readiness = await OidcRuntimeService.cached_readiness(request.app, query_db)
@@ -120,12 +121,12 @@ async def require_oidc_protocol_ready(
def _redis(request: Request) -> Redis:
"""
- 读取应用生命周期创建的 Redis 客户端
+ 读取应用生命周期创建的 Redis 客户端。
:param request: 当前HTTP请求
:return: 应用生命周期创建的Redis客户端
+ :raises HTTPException: 认证服务暂不可用
"""
-
value = getattr(request.app.state, 'redis', None)
if value is None:
raise HTTPException(status_code=503, detail='认证服务暂不可用')
@@ -134,13 +135,12 @@ def _redis(request: Request) -> Redis:
async def read_form(request: Request) -> dict[str, str]:
"""
- 严格读取 URL encoded 表单并拒绝重复字段
+ 严格读取 URL encoded 表单并拒绝重复字段。
:param request: 当前 HTTP 请求
:return: 唯一字段映射
:raises HTTPException: Content-Type 错误或字段重复
"""
-
_disabled()
content_type = request.headers.get('content-type', '').split(';', 1)[0].strip().lower()
if content_type != 'application/x-www-form-urlencoded':
@@ -190,13 +190,13 @@ async def get_oidc_client(
query_db: AsyncSession = DBSessionDependency(),
) -> OAuthClientPrincipal:
"""
- 验证 Basic 或 Public Client 表单认证
+ 验证 Basic 或 Public Client 表单认证。
:param request: 当前 HTTP 请求
:param query_db: 异步数据库会话
:return: 已完成认证的 Client Principal
+ :raises HTTPException: 客户端认证失败
"""
-
form = await read_form(request)
authorization = request.headers.get('authorization')
try:
@@ -217,13 +217,13 @@ async def get_oidc_client(
async def _load_access_context(request: Request, query_db: AsyncSession) -> AccessTokenContext:
"""
- 按 JWT header kid 查询数据库公钥并验证严格 Access Token Profile
+ 按 JWT header kid 查询数据库公钥并验证严格 Access Token Profile。
:param request: 当前HTTP请求
:param query_db: orm对象
:return: 已校验的访问令牌及声明上下文
+ :raises HTTPException: Bearer 令牌格式无效或校验失败
"""
-
_disabled()
authorization = request.headers.get('authorization', '')
if authorization[:7].lower() != 'bearer ' or ',' in authorization:
@@ -260,13 +260,12 @@ async def get_oidc_access_token(
query_db: AsyncSession = DBSessionDependency(),
) -> AccessTokenContext:
"""
- 验证 UserInfo 使用的 Bearer Access Token
+ 验证 UserInfo 使用的 Bearer Access Token。
:param request: 当前HTTP请求
:param query_db: orm对象
:return: UserInfo使用的访问令牌上下文
"""
-
return await _load_access_context(request, query_db)
@@ -275,13 +274,13 @@ async def get_interaction_csrf(
interaction_id: str,
) -> dict[str, Any]:
"""
- 验证 Interaction CSRF Header,并返回内部状态记录
+ 验证 Interaction CSRF Header,并返回内部状态记录。
:param request: 当前 HTTP 请求
:param interaction_id: 路径中的 Interaction 标识
:return: 已验证的内部 Interaction 记录
+ :raises HTTPException: CSRF 校验失败,请重新发起认证;认证交互不存在
"""
-
_disabled()
redis = _redis(request)
csrf_token = request.headers.get('x-csrf-token')
@@ -298,9 +297,10 @@ async def get_interaction_csrf(
def _invalid_token() -> HTTPException:
"""
- 构造不泄露验证细节的 Bearer 401
- """
+ 构造不泄露验证细节的 Bearer 401。
+ :return: 不泄露验证细节的 Bearer 401
+ """
return HTTPException(
status_code=401, detail='访问令牌无效', headers={'WWW-Authenticate': 'Bearer error="invalid_token"'}
)
@@ -308,23 +308,26 @@ def _invalid_token() -> HTTPException:
def OidcClientDependency() -> params.Depends: # noqa: N802
"""
- 返回 Client Authentication 依赖
- """
+ 返回 Client Authentication 依赖。
+ :return: Client Authentication 依赖
+ """
return Depends(get_oidc_client)
def OidcAccessTokenDependency() -> params.Depends: # noqa: N802
"""
- 返回严格 Access Token 依赖
- """
+ 返回严格 Access Token 依赖。
+ :return: 严格 Access Token 依赖
+ """
return Depends(get_oidc_access_token)
def InteractionCsrfDependency() -> params.Depends: # noqa: N802
"""
- 返回 Interaction CSRF 依赖
- """
+ 返回 Interaction CSRF 依赖。
+ :return: Interaction CSRF 依赖
+ """
return Depends(get_interaction_csrf)
diff --git a/ruoyi-fastapi-backend/module_identity/entity/do/identity_subject_do.py b/ruoyi-fastapi-backend/module_identity/entity/do/identity_subject_do.py
index c22edcc00..493d923cd 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/do/identity_subject_do.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/do/identity_subject_do.py
@@ -6,9 +6,7 @@
class SysIdentitySubject(Base):
- """
- 统一认证主体关联表
- """
+ """统一认证主体关联表。"""
__tablename__ = 'sys_identity_subject'
__table_args__ = (
@@ -31,7 +29,7 @@ class SysIdentitySubject(Base):
nullable=False,
comment='本地用户ID',
)
- subject_id = Column(String(36), nullable=False, comment='OIDC Subject')
+ subject_id = Column(String(36), nullable=False, comment='OIDC 主体标识')
auth_version = Column(BigInteger, nullable=False, server_default='1', comment='认证安全版本')
create_by = Column(String(64), nullable=True, comment='创建者')
create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_audit_do.py b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_audit_do.py
index f654a5b45..8e0dd578a 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_audit_do.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_audit_do.py
@@ -6,9 +6,7 @@
class SysOAuthAuditLog(Base):
- """
- OAuth/OIDC安全审计日志表
- """
+ """OAuth/OIDC安全审计日志表。"""
__tablename__ = 'sys_oauth_audit_log'
__table_args__ = (
@@ -35,9 +33,9 @@ class SysOAuthAuditLog(Base):
resource_id = Column(String(64), nullable=True, comment='Resource ID 快照')
user_id = Column(BigInteger, nullable=True, comment='用户ID快照')
subject_id = Column(String(36), nullable=True, comment='Subject 快照')
- sid = Column(String(36), nullable=True, comment='SSO Session ID')
- grant_id = Column(String(36), nullable=True, comment='Grant ID')
- token_id = Column(String(36), nullable=True, comment='Token ID')
+ sid = Column(String(36), nullable=True, comment='单点登录会话标识')
+ grant_id = Column(String(36), nullable=True, comment='授权记录标识')
+ token_id = Column(String(36), nullable=True, comment='令牌标识')
ip_address = Column(String(128), nullable=True, comment='客户端 IP')
user_agent = Column(String(500), nullable=True, comment='脱敏 User-Agent')
failure_code = Column(String(64), nullable=True, comment='失败码')
@@ -46,9 +44,7 @@ class SysOAuthAuditLog(Base):
class SysOAuthAuditArchive(Base):
- """
- OAuth/OIDC安全审计归档表
- """
+ """OAuth/OIDC安全审计归档表。"""
__tablename__ = 'sys_oauth_audit_archive'
__table_args__ = (
@@ -66,9 +62,9 @@ class SysOAuthAuditArchive(Base):
resource_id = Column(String(64), nullable=True, comment='Resource ID 快照')
user_id = Column(BigInteger, nullable=True, comment='用户ID快照')
subject_id = Column(String(36), nullable=True, comment='Subject 快照')
- sid = Column(String(36), nullable=True, comment='SSO Session ID')
- grant_id = Column(String(36), nullable=True, comment='Grant ID')
- token_id = Column(String(36), nullable=True, comment='Token ID')
+ sid = Column(String(36), nullable=True, comment='单点登录会话标识')
+ grant_id = Column(String(36), nullable=True, comment='授权记录标识')
+ token_id = Column(String(36), nullable=True, comment='令牌标识')
ip_address = Column(String(128), nullable=True, comment='客户端 IP')
user_agent = Column(String(500), nullable=True, comment='脱敏 User-Agent')
failure_code = Column(String(64), nullable=True, comment='失败码')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_client_do.py b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_client_do.py
index 8dc730c7d..9bf8fc500 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_client_do.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_client_do.py
@@ -19,9 +19,7 @@
class SysOAuthClient(Base):
- """
- OAuth客户端表
- """
+ """OAuth客户端表。"""
__tablename__ = 'sys_oauth_client'
__table_args__ = (
@@ -37,7 +35,7 @@ class SysOAuthClient(Base):
autoincrement=True,
comment='内部主键',
)
- client_id = Column(String(64), nullable=False, comment='Client ID')
+ client_id = Column(String(64), nullable=False, comment='客户端标识')
client_name = Column(String(100), nullable=False, comment='客户端名称')
client_type = Column(String(20), nullable=False, comment='Client 类型')
token_endpoint_auth_method = Column(String(32), nullable=False, comment='Token 端点认证方式')
@@ -52,7 +50,7 @@ class SysOAuthClient(Base):
access_token_ttl_seconds = Column(Integer, nullable=True, comment='Access Token 有效期')
refresh_token_idle_seconds = Column(Integer, nullable=True, comment='Refresh Token 闲置有效期')
refresh_token_absolute_seconds = Column(Integer, nullable=True, comment='Refresh Token 绝对有效期')
- logo_uri = Column(String(500), nullable=True, comment='Logo URI')
+ logo_uri = Column(String(500), nullable=True, comment='标志图片地址')
policy_uri = Column(String(500), nullable=True, comment='隐私政策 URI')
tos_uri = Column(String(500), nullable=True, comment='服务条款 URI')
backchannel_logout_session_required = Column(
@@ -69,9 +67,7 @@ class SysOAuthClient(Base):
class SysOAuthClientSecret(Base):
- """
- OAuth客户端密钥表,仅保存密钥强哈希
- """
+ """OAuth客户端密钥表,仅保存密钥强哈希。"""
__tablename__ = 'sys_oauth_client_secret'
__table_args__ = (
@@ -79,7 +75,7 @@ class SysOAuthClientSecret(Base):
{'comment': 'OAuth Client Secret'},
)
- secret_id = Column(String(36), primary_key=True, nullable=False, comment='Secret ID')
+ secret_id = Column(String(36), primary_key=True, nullable=False, comment='密钥标识')
client_pk = Column(
BigInteger,
ForeignKey('sys_oauth_client.client_pk', name='fk_oauth_client_secret_client', ondelete='RESTRICT'),
@@ -99,9 +95,7 @@ class SysOAuthClientSecret(Base):
class SysOAuthClientUri(Base):
- """
- OAuth客户端注册地址表
- """
+ """OAuth客户端注册地址表。"""
__tablename__ = 'sys_oauth_client_uri'
__table_args__ = (
@@ -133,13 +127,12 @@ class SysOAuthClientUri(Base):
@validates('uri')
def derive_uri_hash(self, key: str, value: str) -> str:
"""
- 根据 URI 更新摘要
+ 根据 URI 更新摘要。
:param key: 触发校验的属性名称
:param value: 待写入的注册地址
:return: 用于继续写入的原始注册地址
"""
-
self.uri_hash = OidcUtil.sha256_digest(value)
return value
diff --git a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_grant_do.py b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_grant_do.py
index c2edc6ef4..c573dd7fc 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_grant_do.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_grant_do.py
@@ -6,9 +6,7 @@
class SysOAuthAccessPolicy(Base):
- """
- 用户与 OAuth Client 的访问控制表
- """
+ """用户与 OAuth Client 的访问控制表。"""
__tablename__ = 'sys_oauth_access_policy'
__table_args__ = ({'comment': 'OAuth 用户应用访问控制'},)
@@ -34,9 +32,7 @@ class SysOAuthAccessPolicy(Base):
class SysOAuthGrant(Base):
- """
- OAuth授权记录表
- """
+ """OAuth授权记录表。"""
__tablename__ = 'sys_oauth_grant'
__table_args__ = (
@@ -46,7 +42,7 @@ class SysOAuthGrant(Base):
{'comment': 'OAuth Grant'},
)
- grant_id = Column(String(36), primary_key=True, nullable=False, comment='Grant ID')
+ grant_id = Column(String(36), primary_key=True, nullable=False, comment='授权记录标识')
user_id = Column(
BigInteger,
ForeignKey('sys_user.user_id', name='fk_oauth_grant_user', ondelete='RESTRICT'),
@@ -64,7 +60,7 @@ class SysOAuthGrant(Base):
granted_resources = Column(JSON, nullable=False, comment='已同意 Resource audience')
remembered_scopes = Column(JSON, nullable=True, comment='后续可免确认的 Scope')
remembered_resources = Column(JSON, nullable=True, comment='后续可免确认的 Resource audience')
- client_policy_version = Column(BigInteger, nullable=False, comment='Client Policy Version')
+ client_policy_version = Column(BigInteger, nullable=False, comment='客户端策略版本')
status = Column(String(16), nullable=False, server_default='active', comment='Grant 状态')
consented_at = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='同意时间')
expires_at = Column(DbUtcDateTime(), nullable=True, comment='过期时间')
@@ -74,9 +70,7 @@ class SysOAuthGrant(Base):
class SysSsoSession(Base):
- """
- OIDC单点登录会话表
- """
+ """OIDC单点登录会话表。"""
__tablename__ = 'sys_sso_session'
__table_args__ = (
@@ -86,7 +80,7 @@ class SysSsoSession(Base):
{'comment': 'OIDC SSO Session'},
)
- sid = Column(String(36), primary_key=True, nullable=False, comment='OIDC Session ID')
+ sid = Column(String(36), primary_key=True, nullable=False, comment='OIDC 会话标识')
session_secret_hash = Column(CHAR(64), nullable=False, comment='SSO Cookie 摘要')
user_id = Column(
BigInteger,
@@ -112,9 +106,7 @@ class SysSsoSession(Base):
class SysSsoSessionClient(Base):
- """
- SSO 会话与参与应用关联表
- """
+ """SSO 会话与参与应用关联表。"""
__tablename__ = 'sys_sso_session_client'
__table_args__ = (Index('idx_sso_session_client_client', 'client_pk'), {'comment': 'SSO 会话参与应用'})
@@ -124,7 +116,7 @@ class SysSsoSessionClient(Base):
ForeignKey('sys_sso_session.sid', name='fk_sso_session_client_sid', ondelete='RESTRICT'),
primary_key=True,
nullable=False,
- comment='SSO Session ID',
+ comment='单点登录会话标识',
)
client_pk = Column(
BigInteger,
@@ -138,9 +130,7 @@ class SysSsoSessionClient(Base):
class SysOAuthRefreshToken(Base):
- """
- OAuth刷新令牌表,仅保存令牌摘要
- """
+ """OAuth刷新令牌表,仅保存令牌摘要。"""
__tablename__ = 'sys_oauth_refresh_token'
__table_args__ = (
@@ -153,9 +143,9 @@ class SysOAuthRefreshToken(Base):
{'comment': 'OAuth Refresh Token'},
)
- token_id = Column(String(36), primary_key=True, nullable=False, comment='Token ID')
+ token_id = Column(String(36), primary_key=True, nullable=False, comment='令牌标识')
token_hash = Column(CHAR(64), nullable=False, comment='Token HMAC 摘要')
- family_id = Column(String(36), nullable=False, comment='Token Family ID')
+ family_id = Column(String(36), nullable=False, comment='令牌族标识')
parent_token_id = Column(
String(36),
ForeignKey('sys_oauth_refresh_token.token_id', name='fk_oauth_refresh_parent', ondelete='RESTRICT'),
@@ -172,7 +162,7 @@ class SysOAuthRefreshToken(Base):
String(36),
ForeignKey('sys_oauth_grant.grant_id', name='fk_oauth_refresh_grant', ondelete='RESTRICT'),
nullable=False,
- comment='Grant ID',
+ comment='授权记录标识',
)
user_id = Column(
BigInteger,
@@ -192,7 +182,7 @@ class SysOAuthRefreshToken(Base):
String(36),
ForeignKey('sys_sso_session.sid', name='fk_oauth_refresh_sid', ondelete='RESTRICT'),
nullable=False,
- comment='SSO Session ID',
+ comment='单点登录会话标识',
)
scopes = Column(JSON, nullable=False, comment='绑定 Scope')
resources = Column(JSON, nullable=False, comment='绑定 Resource audience')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_resource_do.py b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_resource_do.py
index da8655a14..d3b01e95b 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_resource_do.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_resource_do.py
@@ -18,9 +18,7 @@
class SysOAuthResource(Base):
- """
- OAuth资源服务器表
- """
+ """OAuth资源服务器表。"""
__tablename__ = 'sys_oauth_resource'
__table_args__ = (
@@ -37,9 +35,9 @@ class SysOAuthResource(Base):
autoincrement=True,
comment='内部主键',
)
- resource_id = Column(String(64), nullable=False, comment='Resource ID')
+ resource_id = Column(String(64), nullable=False, comment='资源标识')
resource_name = Column(String(100), nullable=False, comment='Resource 名称')
- audience = Column(String(500), nullable=False, comment='Access Token audience')
+ audience = Column(String(500), nullable=False, comment='访问令牌受众')
token_format = Column(String(16), nullable=False, server_default='jwt', comment='Token 格式')
signing_alg = Column(String(16), nullable=False, server_default='RS256', comment='签名算法')
access_token_ttl_seconds = Column(Integer, nullable=True, comment='Access Token 有效期')
@@ -61,9 +59,7 @@ class SysOAuthResource(Base):
class SysOAuthScope(Base):
- """
- OAuth权限表
- """
+ """OAuth权限表。"""
__tablename__ = 'sys_oauth_scope'
__table_args__ = (
@@ -103,9 +99,7 @@ class SysOAuthScope(Base):
class SysOAuthClientScope(Base):
- """
- OAuth客户端与权限关联表
- """
+ """OAuth客户端与权限关联表。"""
__tablename__ = 'sys_oauth_client_scope'
__table_args__ = (
@@ -135,9 +129,7 @@ class SysOAuthClientScope(Base):
class SysOAuthClientResource(Base):
- """
- OAuth客户端与资源关联表
- """
+ """OAuth客户端与资源关联表。"""
__tablename__ = 'sys_oauth_client_resource'
__table_args__ = (
diff --git a/ruoyi-fastapi-backend/module_identity/entity/do/oidc_key_do.py b/ruoyi-fastapi-backend/module_identity/entity/do/oidc_key_do.py
index 398c30d13..719c6b319 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/do/oidc_key_do.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/do/oidc_key_do.py
@@ -6,9 +6,7 @@
class SysOidcSigningKey(Base):
- """
- OIDC签名密钥表
- """
+ """OIDC签名密钥表。"""
__tablename__ = 'sys_oidc_signing_key'
__table_args__ = (
@@ -30,7 +28,7 @@ class SysOidcSigningKey(Base):
autoincrement=True,
comment='内部主键',
)
- kid = Column(String(100), nullable=False, comment='JWKS Key ID')
+ kid = Column(String(100), nullable=False, comment='JWKS 密钥标识')
key_use = Column(String(16), nullable=False, server_default='sig', comment='JWK 用途')
alg = Column(String(16), nullable=False, server_default='RS256', comment='签名算法')
public_jwk = Column(JSON, nullable=False, comment='公开 JWK')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/vo/interaction_vo.py b/ruoyi-fastapi-backend/module_identity/entity/vo/interaction_vo.py
index d06b4e30b..bcc6805b7 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/vo/interaction_vo.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/vo/interaction_vo.py
@@ -8,7 +8,7 @@
class InteractionModel(BaseModel):
"""
- 认证交互 API 模型基类
+ 认证交互 API 模型基类。
交互字段使用 camelCase,并拒绝未定义字段。
"""
@@ -17,9 +17,7 @@ class InteractionModel(BaseModel):
class InteractionLoginModel(InteractionModel):
- """
- 认证中心登录提交模型
- """
+ """认证中心登录提交模型。"""
user_name: str = Field(min_length=1, max_length=64, description='用户账号')
password: str = Field(min_length=1, max_length=256, description='登录密码')
@@ -29,9 +27,7 @@ class InteractionLoginModel(InteractionModel):
class InteractionConsentModel(InteractionModel):
- """
- 认证中心授权同意提交模型
- """
+ """认证中心授权同意提交模型。"""
approved: bool = Field(description='是否同意本次授权')
scopes: list[str] = Field(default_factory=list, max_length=100, description='本次同意的权限范围')
@@ -40,9 +36,11 @@ class InteractionConsentModel(InteractionModel):
@model_validator(mode='after')
def validate_scopes(self) -> 'InteractionConsentModel':
"""
- 拒绝空 Scope、超长 Scope 和重复提交
- """
+ 拒绝空 Scope、超长 Scope 和重复提交。
+ :raises ValueError: 权限范围标识不能为空,且每项不得超过 100 个字符;权限范围不得重复
+ :return: 当前实例
+ """
if any(
not isinstance(scope, str) or not scope or len(scope) > _MAX_INTERACTION_SCOPE_LENGTH
for scope in self.scopes
@@ -54,9 +52,7 @@ def validate_scopes(self) -> 'InteractionConsentModel':
class ChangePasswordModel(InteractionModel):
- """
- 初始密码或过期密码修改模型
- """
+ """初始密码或过期密码修改模型。"""
old_password: str = Field(min_length=1, max_length=256, description='当前密码')
new_password: str = Field(min_length=1, max_length=256, description='新密码')
@@ -65,20 +61,18 @@ class ChangePasswordModel(InteractionModel):
@model_validator(mode='after')
def validate_confirmation(self) -> 'ChangePasswordModel':
"""
- 确保新密码与确认密码完全一致
+ 确保新密码与确认密码完全一致。
:return: 当前已校验的改密请求
+ :raises ValueError: 新密码与确认密码必须一致
"""
-
if self.new_password != self.confirm_password:
raise ValueError('新密码与确认密码必须一致')
return self
class CaptchaResponseModel(InteractionModel):
- """
- 认证交互验证码响应模型
- """
+ """认证交互验证码响应模型。"""
captcha_enabled: bool = Field(description='是否启用验证码')
uuid: str | None = Field(default=None, description='验证码唯一标识')
@@ -86,9 +80,7 @@ class CaptchaResponseModel(InteractionModel):
class InteractionClientModel(InteractionModel):
- """
- 授权交互页面展示的 Client 摘要
- """
+ """授权交互页面展示的 Client 摘要。"""
client_id: str = Field(description='客户端标识')
client_name: str = Field(description='客户端名称')
@@ -98,9 +90,7 @@ class InteractionClientModel(InteractionModel):
class RequestedScopeModel(InteractionModel):
- """
- 授权交互页面展示的 Scope 摘要
- """
+ """授权交互页面展示的 Scope 摘要。"""
scope: str = Field(description='权限标识')
name: str = Field(description='权限名称')
@@ -110,9 +100,7 @@ class RequestedScopeModel(InteractionModel):
class InteractionViewModel(InteractionModel):
- """
- Interaction 页面视图模型
- """
+ """Interaction 页面视图模型。"""
interaction_id: str = Field(description='认证交互标识')
client: InteractionClientModel = Field(description='发起认证的客户端摘要')
@@ -123,9 +111,7 @@ class InteractionViewModel(InteractionModel):
class InteractionResultModel(InteractionModel):
- """
- 登录、同意或改密后的下一步动作模型
- """
+ """登录、同意或改密后的下一步动作模型。"""
next_action: Literal['login', 'consent', 'redirect', 'changePassword'] = Field(description='认证交互的下一步动作')
interaction_id: str | None = Field(default=None, description='认证交互标识')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_client_vo.py b/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_client_vo.py
index f1b7ff3dd..2615089d1 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_client_vo.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_client_vo.py
@@ -10,17 +10,13 @@
class ClientModel(BaseModel):
- """
- OAuth Client 管理模型基类
- """
+ """OAuth Client 管理模型基类。"""
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True, extra='forbid')
class ClientCreateModel(ClientModel):
- """
- 创建 OAuth Client 请求
- """
+ """创建 OAuth Client 请求。"""
client_name: str = Field(min_length=1, max_length=100, description='客户端名称')
client_type: Literal['public', 'confidential'] = Field(
@@ -56,12 +52,11 @@ class ClientCreateModel(ClientModel):
@classmethod
def default_non_code_response_types(cls, value: Any) -> Any:
"""
- 为不含 authorization_code 的 Client 默认空 response_types
+ 为不含 authorization_code 的 Client 默认空 response_types。
:param value: 管理端提交的原始字段映射
:return: 应用默认值后的原始字段映射
"""
-
if isinstance(value, dict) and 'response_types' not in value and 'responseTypes' not in value:
grant_key = 'grant_types' if 'grant_types' in value else 'grantTypes'
response_key = 'response_types' if 'grant_types' in value else 'responseTypes'
@@ -73,12 +68,11 @@ def default_non_code_response_types(cls, value: Any) -> Any:
@model_validator(mode='after')
def validate_auth_policy(self) -> 'ClientCreateModel': # noqa: PLR0912
"""
- 校验 Client Authentication、Grant、PKCE 与 URI 注册策略
+ 校验 Client Authentication、Grant、PKCE 与 URI 注册策略。
:return: 当前已校验 Client 创建模型
:raises ValueError: 策略、Grant 或注册 URI 不符合规范
"""
-
if len(set(self.allowed_role_keys)) != len(self.allowed_role_keys) or any(
not role or len(role) > _MAX_ROLE_KEY_LENGTH or '*' in role or any(char.isspace() for char in role)
for role in self.allowed_role_keys
@@ -120,7 +114,7 @@ def validate_auth_policy(self) -> 'ClientCreateModel': # noqa: PLR0912
class ClientUpdateModel(ClientCreateModel):
"""
- 更新 OAuth Client 的管理请求
+ 更新 OAuth Client 的管理请求。
更新请求必须携带外部 client_id。
"""
@@ -130,7 +124,7 @@ class ClientUpdateModel(ClientCreateModel):
class ClientViewModel(ClientCreateModel):
"""
- OAuth Client 安全字段脱敏后的详情模型
+ OAuth Client 安全字段脱敏后的详情模型。
模型不包含任何明文或哈希 Client Secret。
"""
@@ -144,7 +138,7 @@ class ClientViewModel(ClientCreateModel):
class ClientSecretResponseModel(ClientModel):
"""
- Client Secret 一次性展示响应
+ Client Secret 一次性展示响应。
调用方必须在本次响应后立即安全保存明文 Secret。
"""
@@ -158,9 +152,7 @@ class ClientSecretResponseModel(ClientModel):
class SecretRotationModel(ClientModel):
- """
- Client Secret 轮换的时间策略
- """
+ """Client Secret 轮换的时间策略。"""
not_before: ApiUtcDateTime | None = Field(default=None, description='密钥生效时间')
expires_at: ApiUtcDateTime | None = Field(default=None, description='过期时间')
@@ -169,7 +161,7 @@ class SecretRotationModel(ClientModel):
class ClientUriModel(ClientModel):
"""
- 单个注册 URI 的管理模型
+ 单个注册 URI 的管理模型。
URI 在 DTO 边界执行精确匹配所需的安全校验。
"""
@@ -184,11 +176,10 @@ class ClientUriModel(ClientModel):
@model_validator(mode='after')
def validate_uri(self) -> 'ClientUriModel':
"""
- 校验并规范化单个注册 URI
+ 校验并规范化单个注册 URI。
:return: 当前已校验 URI 模型
"""
-
self.uri = OidcUtil.validate_registered_uri(self.uri_type, self.uri)
return self
@@ -196,7 +187,7 @@ def validate_uri(self) -> 'ClientUriModel':
class ClientPageQueryModel(ClientModel):
"""
- Client 分页查询参数
+ Client 分页查询参数。
page_num 与 page_size 使用管理端统一分页约束。
"""
@@ -212,7 +203,7 @@ class ClientPageQueryModel(ClientModel):
class ClientStatusModel(ClientModel):
"""
- Client 启停状态变更请求
+ Client 启停状态变更请求。
status 只允许项目约定的 0(正常)或 1(停用)。
"""
diff --git a/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_resource_vo.py b/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_resource_vo.py
index 5bf41b746..f59bde511 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_resource_vo.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_resource_vo.py
@@ -7,17 +7,13 @@
class ResourceModel(BaseModel):
- """
- Resource 与 Scope 管理模型基类
- """
+ """Resource 与 Scope 管理模型基类。"""
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True, extra='forbid')
class ScopeModel(ResourceModel):
- """
- OAuth Scope 管理模型
- """
+ """OAuth Scope 管理模型。"""
scope_code: str = Field(min_length=1, max_length=100, description='权限标识')
scope_name: str = Field(min_length=1, max_length=100, description='权限名称')
@@ -34,11 +30,11 @@ class ScopeModel(ResourceModel):
@model_validator(mode='after')
def validate_scope_resource(self) -> 'ScopeModel':
"""
- 校验 Resource Scope 与 Resource ID 的绑定关系
+ 校验 Resource Scope 与 Resource ID 的绑定关系。
:return: 当前已校验 Scope
+ :raises ValueError: 资源权限必须提供 resource_id;身份权限范围不能绑定业务资源
"""
-
if self.scope_type == 'resource' and not self.resource_id:
raise ValueError('资源权限必须提供 resource_id')
if self.scope_type == 'identity' and self.resource_id:
@@ -47,9 +43,7 @@ def validate_scope_resource(self) -> 'ScopeModel':
class ResourceCreateModel(ResourceModel):
- """
- Resource Server 创建模型
- """
+ """Resource Server 创建模型。"""
resource_id: str = Field(min_length=1, max_length=64, description='资源标识')
resource_name: str = Field(min_length=1, max_length=100, description='资源名称')
@@ -67,25 +61,19 @@ class ResourceCreateModel(ResourceModel):
class ResourceUpdateModel(ResourceCreateModel):
- """
- Resource Server 更新模型
- """
+ """Resource Server 更新模型。"""
status: Literal['0', '1'] = Field(default='0', description='状态(0正常 1停用)')
class ResourceViewModel(ResourceCreateModel):
- """
- Resource Server 管理详情模型
- """
+ """Resource Server 管理详情模型。"""
status: Literal['0', '1'] = Field(default='0', description='状态(0正常 1停用)')
class ClaimPolicyModel(ResourceModel):
- """
- Client/Resource Claim 允许列表模型
- """
+ """Client/Resource Claim 允许列表模型。"""
client_id: str | None = Field(default=None, description='客户端标识')
resource_id: str | None = Field(default=None, description='资源标识')
@@ -94,9 +82,7 @@ class ClaimPolicyModel(ResourceModel):
class ResourcePageQueryModel(ResourceModel):
- """
- Resource Server 分页查询模型
- """
+ """Resource Server 分页查询模型。"""
resource_name: str | None = Field(default=None, description='资源名称')
status: Literal['0', '1'] | None = Field(default=None, description='状态(0正常 1停用)')
@@ -105,9 +91,7 @@ class ResourcePageQueryModel(ResourceModel):
class ScopePageQueryModel(ResourceModel):
- """
- Scope 分页查询模型
- """
+ """Scope 分页查询模型。"""
scope_name: str | None = Field(default=None, description='权限名称')
scope_type: Literal['identity', 'resource'] | None = Field(
@@ -119,9 +103,7 @@ class ScopePageQueryModel(ResourceModel):
class ResourceStatusModel(ResourceModel):
- """
- Resource Server 启停状态模型
- """
+ """Resource Server 启停状态模型。"""
resource_id: str = Field(description='资源标识')
status: Literal['0', '1'] = Field(description='状态(0正常 1停用)')
@@ -132,9 +114,7 @@ class ResourceStatusModel(ResourceModel):
class ScopeStatusModel(ResourceModel):
- """
- Scope 启停状态模型
- """
+ """Scope 启停状态模型。"""
scope_code: str = Field(description='权限标识')
status: Literal['0', '1'] = Field(description='状态(0正常 1停用)')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_session_vo.py b/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_session_vo.py
index ab6a2786f..70386e8f0 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_session_vo.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_session_vo.py
@@ -8,7 +8,7 @@
class SessionModel(BaseModel):
"""
- Session、Grant 和 Audit 管理模型基类
+ Session、Grant 和 Audit 管理模型基类。
管理端字段接受 camelCase 别名并拒绝额外字段。
"""
@@ -17,9 +17,7 @@ class SessionModel(BaseModel):
class GrantModel(SessionModel):
- """
- 用户对 OAuth Client 的授权详情模型
- """
+ """用户对 OAuth Client 的授权详情模型。"""
grant_id: str = Field(description='授权记录标识')
user_id: int | None = Field(default=None, description='用户ID')
@@ -43,9 +41,7 @@ class GrantModel(SessionModel):
class SsoSessionModel(SessionModel):
- """
- 认证中心 SSO Session 脱敏详情模型
- """
+ """认证中心 SSO Session 脱敏详情模型。"""
sid: str = Field(description='SSO会话标识')
user_id: int | None = Field(default=None, description='用户ID')
@@ -69,25 +65,19 @@ class SsoSessionModel(SessionModel):
class SessionRevokeModel(SessionModel):
- """
- SSO Session 撤销请求模型
- """
+ """SSO Session 撤销请求模型。"""
reason: str = Field(min_length=1, max_length=200, description='会话或授权的撤销原因')
class GrantAccessModel(SessionRevokeModel):
- """
- 用户对应用的访问控制请求模型
- """
+ """用户对应用的访问控制请求模型。"""
blocked: bool = Field(strict=True, description='是否禁止用户访问应用')
class SessionPageQueryModel(SessionModel):
- """
- SSO Session 分页查询模型
- """
+ """SSO Session 分页查询模型。"""
user_id: int | None = Field(default=None, description='用户ID')
ip_address: str | None = Field(default=None, description='IP地址')
@@ -102,18 +92,18 @@ class SessionPageQueryModel(SessionModel):
@model_validator(mode='after')
def validate_time_range(self) -> 'SessionPageQueryModel':
"""
- 校验 Session 查询时间范围
- """
+ 校验 Session 查询时间范围。
+ :raises ValueError: 结束时间不得早于开始时间
+ :return: 当前实例
+ """
if self.start_time and self.end_time and self.end_time < self.start_time:
raise ValueError('结束时间不得早于开始时间')
return self
class GrantPageQueryModel(SessionModel):
- """
- OAuth Grant 分页查询模型
- """
+ """OAuth Grant 分页查询模型。"""
user_id: int | None = Field(default=None, description='用户ID')
client_id: str | None = Field(default=None, description='客户端标识')
@@ -126,9 +116,7 @@ class GrantPageQueryModel(SessionModel):
class AccessPolicyModel(SessionModel):
- """
- 用户应用访问策略管理模型
- """
+ """用户应用访问策略管理模型。"""
user_id: int = Field(description='用户ID')
user_name: str = Field(description='用户名称')
@@ -141,9 +129,7 @@ class AccessPolicyModel(SessionModel):
class AccessPolicyPageQueryModel(SessionModel):
- """
- 用户应用访问策略分页查询模型
- """
+ """用户应用访问策略分页查询模型。"""
user_id: int | None = Field(default=None, gt=0, description='用户ID')
client_id: str | None = Field(default=None, max_length=128, description='客户端标识')
@@ -154,7 +140,7 @@ class AccessPolicyPageQueryModel(SessionModel):
class AuditPageQueryModel(SessionModel):
"""
- OAuth 审计分页查询模型
+ OAuth 审计分页查询模型。
支持按 Client、用户、事件结果、风险和时间范围过滤。
"""
@@ -176,21 +162,18 @@ class AuditPageQueryModel(SessionModel):
@model_validator(mode='after')
def validate_time_range(self) -> 'AuditPageQueryModel':
"""
- 校验审计查询的起止时间顺序
+ 校验审计查询的起止时间顺序。
:return: 当前已校验查询模型
:raises ValueError: 结束时间早于开始时间
"""
-
if self.start_time and self.end_time and self.end_time < self.start_time:
raise ValueError('结束时间不得早于开始时间')
return self
class AuditModel(SessionModel):
- """
- 脱敏 OAuth 审计事件详情模型
- """
+ """脱敏 OAuth 审计事件详情模型。"""
audit_id: int = Field(description='审计记录ID')
event_type: str = Field(description='审计事件类型')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/vo/oidc_key_vo.py b/ruoyi-fastapi-backend/module_identity/entity/vo/oidc_key_vo.py
index a29260c55..e106a3729 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/vo/oidc_key_vo.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/vo/oidc_key_vo.py
@@ -9,17 +9,13 @@
class OidcKeyModel(BaseModel):
- """
- OIDC 签名密钥管理模型基类
- """
+ """OIDC 签名密钥管理模型基类。"""
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True, extra='forbid')
class OidcKeyRotateModel(OidcKeyModel):
- """
- OIDC 签名密钥轮换请求模型
- """
+ """OIDC 签名密钥轮换请求模型。"""
alg: Literal['RS256'] = Field(default='RS256', description='签名算法')
kid: str = Field(min_length=1, max_length=100, description='签名密钥标识')
@@ -31,19 +27,16 @@ class OidcKeyRotateModel(OidcKeyModel):
@classmethod
def validate_kid(cls, value: str) -> str:
"""
- 拒绝无法安全放入密钥路径的 kid
+ 拒绝无法安全放入密钥路径的 kid。
:param value: 待校验的签名密钥标识
:return: 校验通过的签名密钥标识
"""
-
return OidcUtil.validate_path_identifier(value, '签名密钥标识 kid')
class OidcKeyViewModel(OidcKeyModel):
- """
- 仅包含公开 JWK 的签名密钥详情模型
- """
+ """仅包含公开 JWK 的签名密钥详情模型。"""
kid: str = Field(description='签名密钥标识')
key_use: Literal['sig'] = Field(default='sig', description='密钥用途')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/vo/protocol_vo.py b/ruoyi-fastapi-backend/module_identity/entity/vo/protocol_vo.py
index 649f50484..78e279bae 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/vo/protocol_vo.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/vo/protocol_vo.py
@@ -7,7 +7,7 @@
class ProtocolModel(BaseModel):
"""
- 标准协议模型基类
+ 标准协议模型基类。
标准端点字段保持 snake_case,并拒绝未定义参数。
"""
@@ -17,7 +17,7 @@ class ProtocolModel(BaseModel):
class AuthorizeRequest(ProtocolModel):
"""
- Authorization Endpoint 请求参数
+ Authorization Endpoint 请求参数。
OIDC 请求必须携带 nonce,并固定使用 PKCE S256。
"""
@@ -40,12 +40,12 @@ class AuthorizeRequest(ProtocolModel):
@classmethod
def validate_code_challenge(cls, value: str) -> str:
"""
- 校验未填充的 base64url SHA-256 challenge
+ 校验未填充的 base64url SHA-256 challenge。
:param value: 客户端提交的 code_challenge
:return: 已校验 challenge
+ :raises ValueError: code_challenge 必须为不带填充的 Base64URL 编码 SHA-256 摘要
"""
-
if not OidcUtil.is_s256_challenge(value):
raise ValueError('code_challenge 必须为不带填充的 Base64URL 编码 SHA-256 摘要')
return value
@@ -54,22 +54,21 @@ def validate_code_challenge(cls, value: str) -> str:
@classmethod
def validate_prompt(cls, value: str | None) -> str | None:
"""
- 只接受规范支持的 prompt 值,且 none 不能和其他值混用
+ 只接受规范支持的 prompt 值,且 none 不能和其他值混用。
:param value: 空格分隔的 prompt 列表
:return: 规范化后的 prompt 或 None
"""
-
return OidcUtil.normalize_prompt(value)
@model_validator(mode='after')
def validate_oidc_nonce(self) -> 'AuthorizeRequest':
"""
- 校验 OIDC 授权请求必须绑定 nonce
+ 校验 OIDC 授权请求必须绑定 nonce。
:return: 当前已校验请求
+ :raises ValueError: 申请 openid 权限时必须提供 nonce
"""
-
if 'openid' in self.scope.split() and not self.nonce:
raise ValueError('申请 openid 权限时必须提供 nonce')
return self
@@ -77,7 +76,7 @@ def validate_oidc_nonce(self) -> 'AuthorizeRequest':
class TokenRequest(ProtocolModel):
"""
- Token Endpoint 表单参数
+ Token Endpoint 表单参数。
不同 grant_type 只允许携带其对应凭据。
"""
@@ -94,11 +93,11 @@ class TokenRequest(ProtocolModel):
@model_validator(mode='after')
def check_grant_fields(self) -> 'TokenRequest':
"""
- 拒绝与 grant type 不相符的凭据,避免跨流程混用
+ 拒绝与 grant type 不相符的凭据,避免跨流程混用。
:return: 当前已校验请求
+ :raises ValueError: 授权码兑换必须提供 code、redirect_uri 和 code_verifier;授权码兑换请求包含不适用的字段;刷新令牌请求必须提供 refresh_token;刷新令牌请求包含不适用的字段;客户端凭据授权请求包含不适用的字段
"""
-
if self.grant_type == 'authorization_code':
if not self.code or not self.code_verifier or not self.redirect_uri:
raise ValueError('授权码兑换必须提供 code、redirect_uri 和 code_verifier')
@@ -118,7 +117,7 @@ def check_grant_fields(self) -> 'TokenRequest':
class TokenResponse(ProtocolModel):
"""
- Token Endpoint 成功响应
+ Token Endpoint 成功响应。
字段直接对应 OAuth 2.0 标准 JSON 响应。
"""
@@ -133,7 +132,7 @@ class TokenResponse(ProtocolModel):
class ErrorResponse(ProtocolModel):
"""
- OAuth/OIDC 标准错误响应
+ OAuth/OIDC 标准错误响应。
不包含项目业务响应包装字段。
"""
@@ -144,17 +143,16 @@ class ErrorResponse(ProtocolModel):
def as_dict(self) -> dict[str, str]:
"""
- 返回可直接作为标准 JSON 响应的非空字段
+ 返回可直接作为标准 JSON 响应的非空字段。
:return: 排除 None 字段的标准错误字典
"""
-
return self.model_dump(exclude_none=True)
class Jwk(ProtocolModel):
"""
- 公开 RSA JWK
+ 公开 RSA JWK。
模型严格拒绝 d、p、q 等私钥参数。
"""
@@ -169,7 +167,7 @@ class Jwk(ProtocolModel):
class JwksResponse(ProtocolModel):
"""
- JWKS 响应
+ JWKS 响应。
keys 仅包含公开签名 JWK。
"""
@@ -179,7 +177,7 @@ class JwksResponse(ProtocolModel):
class DiscoveryResponse(ProtocolModel):
"""
- OIDC Discovery 响应
+ OIDC Discovery 响应。
元数据只宣称当前实现确实支持的端点和算法。
"""
@@ -224,7 +222,7 @@ class DiscoveryResponse(ProtocolModel):
class OAuthServerMetadata(ProtocolModel):
"""
- RFC 8414 OAuth Authorization Server Metadata 子集
+ RFC 8414 OAuth Authorization Server Metadata 子集。
不继承要求 OIDC 专属 userinfo_endpoint 和 end_session_endpoint 的模型。
"""
@@ -252,7 +250,7 @@ class OAuthServerMetadata(ProtocolModel):
class UserInfoResponse(ProtocolModel):
"""
- UserInfo 基础响应
+ UserInfo 基础响应。
允许的扩展字段对应已授权的标准身份声明。
"""
@@ -273,7 +271,7 @@ class UserInfoResponse(ProtocolModel):
class RevocationRequest(ProtocolModel):
"""
- Token Revocation 请求
+ Token Revocation 请求。
token_type_hint 只用于减少服务端查找歧义,不作为安全依据。
"""
@@ -284,7 +282,7 @@ class RevocationRequest(ProtocolModel):
class IntrospectionRequest(ProtocolModel):
"""
- Token Introspection 请求
+ Token Introspection 请求。
请求方权限和 audience 绑定由服务层继续校验。
"""
@@ -295,7 +293,7 @@ class IntrospectionRequest(ProtocolModel):
class IntrospectionResponse(ProtocolModel):
"""
- Token Introspection 响应
+ Token Introspection 响应。
inactive Token 只应返回 active=false。
"""
@@ -317,7 +315,7 @@ class IntrospectionResponse(ProtocolModel):
class LogoutRequest(ProtocolModel):
"""
- RP-Initiated Logout 请求
+ RP-Initiated Logout 请求。
post_logout_redirect_uri 必须由服务端按 Client 注册值精确匹配。
"""
diff --git a/ruoyi-fastapi-backend/module_identity/redis_keys.py b/ruoyi-fastapi-backend/module_identity/redis_keys.py
index 61e8274f8..73c839aa1 100644
--- a/ruoyi-fastapi-backend/module_identity/redis_keys.py
+++ b/ruoyi-fastapi-backend/module_identity/redis_keys.py
@@ -5,7 +5,11 @@
class OidcRedisKey:
"""
- 统一认证中心 Redis Key Builder
+ 统一认证中心 Redis Key Builder。
+
+ :cvar PREFIX: OIDC 缓存键使用的前缀
+ :cvar SESSION_REVOKED_CHANNEL: 发布会话撤销通知的 Redis 频道
+ :cvar USER_SECURITY_CHANGED_CHANNEL: 发布用户安全状态变更的 Redis 频道
"""
PREFIX: Final[str] = 'oidc'
@@ -15,45 +19,41 @@ class OidcRedisKey:
@classmethod
def interaction(cls, interaction_id: str) -> str:
"""
- 生成 Interaction 状态键
+ 生成 Interaction 状态键。
:param interaction_id: Interaction 标识
- :return: Redis Key
+ :return: Redis 缓存键
"""
-
return f'{cls.PREFIX}:interaction:{OidcUtil.redis_key_component(interaction_id, name="interaction_id")}'
@classmethod
def authorization_code(cls, code_id: str) -> str:
"""
- 生成授权码状态键
+ 生成授权码状态键。
:param code_id: 授权码内部标识
- :return: Redis Key
+ :return: Redis 缓存键
"""
-
return f'{cls.PREFIX}:authorization_code:{OidcUtil.redis_key_component(code_id, name="code_id")}'
@classmethod
def authorization_code_consumed(cls, code_id: str) -> str:
"""
- 生成授权码消费短期 tombstone 键
+ 生成授权码消费短期 tombstone 键。
:param code_id: 授权码公开标识部分
:return: 不含授权码 Secret 的消费状态键
"""
-
return f'{cls.PREFIX}:authorization_code_consumed:{OidcUtil.redis_key_component(code_id, name="code_id")}'
@classmethod
def authorization_code_consumed_payload(cls, code_id: str) -> str:
"""
- 生成授权码消费绑定载荷短期键
+ 生成授权码消费绑定载荷短期键。
:param code_id: 授权码公开标识部分
:return: 不含授权码 Secret 的消费绑定载荷键
"""
-
return (
f'{cls.PREFIX}:authorization_code_consumed_payload:{OidcUtil.redis_key_component(code_id, name="code_id")}'
)
@@ -61,158 +61,145 @@ def authorization_code_consumed_payload(cls, code_id: str) -> str:
@classmethod
def sso_session(cls, sid: str) -> str:
"""
- 生成 SSO 会话热缓存键
+ 生成 SSO 会话热缓存键。
:param sid: SSO 会话标识
- :return: Redis Key
+ :return: Redis 缓存键
"""
-
return f'{cls.PREFIX}:sso_session:{OidcUtil.redis_key_component(sid, name="sid")}'
@classmethod
def user_sessions(cls, user_id: str | int) -> str:
"""
- 生成用户 SSO 会话索引键
+ 生成用户 SSO 会话索引键。
:param user_id: 内部用户标识
- :return: Redis Key
+ :return: Redis 缓存键
"""
-
return f'{cls.PREFIX}:user_sessions:{OidcUtil.redis_key_component(user_id, name="user_id")}'
@classmethod
def sso_cookie(cls, session_hash: str) -> str:
"""
- 生成 SSO Cookie 摘要索引键
+ 生成 SSO Cookie 摘要索引键。
:param session_hash: Cookie Secret 的 SHA-256 摘要
- :return: Redis Key
+ :return: Redis 缓存键
"""
-
return f'{cls.PREFIX}:sso_cookie:{OidcUtil.sha256_hex_digest(session_hash)}'
@classmethod
def revoked_jti(cls, jti: str) -> str:
"""
- 生成 Access Token JTI 撤销键
+ 生成 Access Token JTI 撤销键。
:param jti: Access Token 的 JTI
- :return: Redis Key
+ :return: Redis 缓存键
"""
-
return f'{cls.PREFIX}:revoked_jti:{OidcUtil.redis_key_component(jti, name="jti")}'
@classmethod
def backchannel_retry_queue(cls) -> str:
"""
- 返回 Back-Channel Logout 有界重试队列键
- """
+ 返回 Back-Channel Logout 有界重试队列键。
+ :return: Back-Channel Logout 有界重试队列键
+ """
return f'{cls.PREFIX}:backchannel:retry'
@classmethod
def signing_key_rotation_lock(cls) -> str:
"""
- 返回跨实例签名密钥轮换锁键
+ 返回跨实例签名密钥轮换锁键。
:return: OIDC 签名密钥轮换专用 Redis 锁键
"""
-
return f'{cls.PREFIX}:signing_key:rotation_lock'
@classmethod
def authorize_ip_rate_limit(cls, ip_hash: str) -> str:
"""
- 生成按 IP 限流键
+ 生成按 IP 限流键。
:param ip_hash: 使用独立 Pepper 生成的 IP 摘要
- :return: Redis Key
+ :return: Redis 缓存键
"""
-
return f'{cls.PREFIX}:rate_limit:authorize:ip:{OidcUtil.sha256_hex_digest(ip_hash)}'
@classmethod
def login_user_rate_limit(cls, user_name_hash: str) -> str:
"""
- 生成按用户限流键
+ 生成按用户限流键。
:param user_name_hash: 使用独立 Pepper 生成的用户名摘要
- :return: Redis Key
+ :return: Redis 缓存键
"""
-
return f'{cls.PREFIX}:rate_limit:login:user:{OidcUtil.sha256_hex_digest(user_name_hash)}'
@classmethod
def interaction_captcha_rate_limit(cls, subject_hash: str) -> str:
"""
- 生成认证中心验证码专用限流键
+ 生成认证中心验证码专用限流键。
:param subject_hash: Interaction 与来源地址组合的 HMAC 摘要
:return: 验证码端点独立 Redis Key
"""
-
return f'{cls.PREFIX}:rate_limit:interaction:captcha:{OidcUtil.sha256_hex_digest(subject_hash)}'
@classmethod
def token_client_rate_limit(cls, client_id: str) -> str:
"""
- 生成按 Client 限流键
+ 生成按 Client 限流键。
:param client_id: 外部 Client ID
- :return: Redis Key
+ :return: Redis 缓存键
"""
-
return f'{cls.PREFIX}:rate_limit:token:client:{OidcUtil.redis_key_component(client_id, name="client_id")}'
@classmethod
def introspect_client_rate_limit(cls, client_id: str) -> str:
"""
- 生成按 introspection Client 限流键
+ 生成按 introspection Client 限流键。
- :param client_id: introspection Client ID
- :return: Redis Key
+ :param client_id: 执行令牌自省的客户端标识
+ :return: Redis 缓存键
"""
-
return f'{cls.PREFIX}:rate_limit:introspect:client:{OidcUtil.redis_key_component(client_id, name="client_id")}'
@classmethod
def revoke_client_rate_limit(cls, client_id: str) -> str:
"""
- 返回独立于 Token Endpoint 的撤销端点限流键
+ 返回独立于 Token Endpoint 的撤销端点限流键。
:param client_id: 撤销调用方的外部 Client ID 或匿名占位标识
:return: 撤销端点专用 Redis Key
"""
-
return f'{cls.PREFIX}:rate_limit:revoke:client:{OidcUtil.redis_key_component(client_id, name="client_id")}'
@classmethod
def logout_rate_limit(cls, scope: str = 'anonymous') -> str:
"""
- 返回按安全摘要隔离的 RP-Initiated Logout 限流键
+ 返回按安全摘要隔离的 RP-Initiated Logout 限流键。
:param scope: 已由调用方 HMAC 的 IP 或安全 fallback 摘要
:return: Logout Endpoint 专用 Redis Key
"""
-
return f'{cls.PREFIX}:rate_limit:logout:{OidcUtil.redis_key_component(scope, name="logout_scope")}'
@classmethod
def event_session_revoked(cls) -> str:
"""
- 返回 SSO 会话撤销事件频道
+ 返回 SSO 会话撤销事件频道。
:return: Redis Pub/Sub 频道名
"""
-
return cls.SESSION_REVOKED_CHANNEL
@classmethod
def event_user_security_changed(cls) -> str:
"""
- 返回用户安全变化事件频道
+ 返回用户安全变化事件频道。
:return: Redis Pub/Sub 频道名
"""
-
return cls.USER_SECURITY_CHANGED_CHANNEL
diff --git a/ruoyi-fastapi-backend/module_identity/security/backchannel_transport.py b/ruoyi-fastapi-backend/module_identity/security/backchannel_transport.py
index 1865c76b6..a3f22b6fe 100644
--- a/ruoyi-fastapi-backend/module_identity/security/backchannel_transport.py
+++ b/ruoyi-fastapi-backend/module_identity/security/backchannel_transport.py
@@ -15,11 +15,19 @@
class PermanentBackchannelError(ValueError):
"""
- 表示 Back-Channel 请求永久失败且不应继续重试
+ 表示 Back-Channel 请求永久失败且不应继续重试。
+
+ :ivar failure_code: 失败原因代码
+ :ivar message: 与当前结果一起返回的说明
"""
def __init__(self, failure_code: str, message: str | None = None) -> None:
- """分别保存稳定的审计错误码和中文异常说明。"""
+ """
+ 分别保存稳定的审计错误码和中文异常说明。
+
+ :param failure_code: 失败原因代码
+ :param message: 与当前结果一起返回的说明
+ """
self.failure_code = failure_code
self.message = message or '后端退出通知永久失败'
super().__init__(self.message)
@@ -27,25 +35,27 @@ def __init__(self, failure_code: str, message: str | None = None) -> None:
class _PinnedNetworkBackend(httpcore.AsyncNetworkBackend):
"""
- 保持注册域名的 TLS 和 SNI,同时将 TCP 连接固定到已验证 IP
+ 保持注册域名的 TLS 和 SNI,同时将 TCP 连接固定到已验证 IP。
+
+ :ivar _hostname: 已验证的注册主机名
+ :ivar _addresses: 已验证的公网 IP 集合
+ :ivar _backend: 用于建立网络连接的底层实现
"""
def __init__(self, hostname: str, addresses: set[str]) -> None:
"""
- 初始化固定目标地址的网络后端
+ 初始化固定目标地址的网络后端。
:param hostname: 已验证的注册主机名
:param addresses: 已验证的公网 IP 集合
- :return: None
"""
-
self._hostname = hostname
self._addresses = addresses
self._backend = AutoBackend()
async def connect_tcp(self, host: str, port: int, **kwargs: Any) -> httpcore.AsyncNetworkStream:
"""
- 连接已验证主机对应的固定公网地址
+ 连接已验证主机对应的固定公网地址。
:param host: HTTP Core 请求的原始主机名
:param port: 目标 TCP 端口
@@ -53,7 +63,6 @@ async def connect_tcp(self, host: str, port: int, **kwargs: Any) -> httpcore.Asy
:return: 已建立的异步网络流
:raises OSError: 主机未验证、地址为空或全部地址连接失败
"""
-
if host != self._hostname or not self._addresses:
raise OSError('网络目标未通过安全校验')
# 逐个尝试已验证地址,网络库仍以原始 origin 处理 TLS SNI 和 Host
@@ -68,28 +77,27 @@ async def connect_tcp(self, host: str, port: int, **kwargs: Any) -> httpcore.Asy
class PinnedHttpxTransport(httpx.AsyncBaseTransport):
"""
- 单次请求使用的 IP 固定 HTTPX Transport
+ 单次请求使用的 IP 固定 HTTPX Transport。
+
+ :ivar _pool: 复用底层资源的池
"""
def __init__(self, hostname: str, addresses: set[str]) -> None:
"""
- 初始化使用固定网络后端的连接池
+ 初始化使用固定网络后端的连接池。
:param hostname: 已验证的注册主机名
:param addresses: 已验证的公网 IP 集合
- :return: None
"""
-
self._pool = httpcore.AsyncConnectionPool(network_backend=_PinnedNetworkBackend(hostname, addresses))
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
"""
- 通过固定地址连接池发送异步 HTTP 请求
+ 通过固定地址连接池发送异步 HTTP 请求。
:param request: HTTPX 异步请求
:return: 限制响应体大小的 HTTPX 响应
"""
-
request_stream = httpcore.Request(
method=request.method,
url=httpcore.URL(
@@ -106,26 +114,22 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
class ResponseStream(httpx.AsyncByteStream):
"""
- 限制 Back-Channel 响应体大小的异步字节流
+ 限制 Back-Channel 响应体大小的异步字节流。
+
+ :ivar _received: 已接收的响应数据量
"""
def __init__(self) -> None:
- """
- 初始化已接收字节计数器
-
- :return: None
- """
-
+ """初始化已接收字节计数器。"""
self._received = 0
async def __aiter__(self) -> Any:
"""
- 逐块读取响应并执行大小限制
+ 逐块读取响应并执行大小限制。
- :return: HTTP 响应字节块异步迭代器
+ :yield: HTTP 响应字节块异步迭代器
:raises OSError: 响应体超过大小限制
"""
-
async for chunk in response.stream:
self._received += len(chunk)
if self._received > _MAX_BACKCHANNEL_RESPONSE_BYTES:
@@ -134,12 +138,7 @@ async def __aiter__(self) -> Any:
yield chunk
async def aclose(self) -> None:
- """
- 关闭底层 HTTP Core 响应流
-
- :return: None
- """
-
+ """关闭底层 HTTP Core 响应流。"""
await response.aclose()
return httpx.Response(
@@ -151,12 +150,7 @@ async def aclose(self) -> None:
)
async def aclose(self) -> None:
- """
- 关闭固定地址连接池
-
- :return: None
- """
-
+ """关闭固定地址连接池。"""
await self._pool.aclose()
@@ -172,18 +166,16 @@ async def send_backchannel_once(
addresses: set[str] | None = None,
) -> None:
"""
- 发送单次 Back-Channel 请求并分类永久失败
+ 发送单次 Back-Channel 请求并分类永久失败。
:param uri: 已验证的 Back-Channel URI
:param token: 待发送的 Logout Token
:param notifier: 可选的外部通知器
:param timeout_seconds: 请求超时秒数
:param addresses: 已验证的公网 IP 集合
- :return: None
:raises PermanentBackchannelError: 收到不可重试的 HTTP 客户端错误
:raises OSError: 未提供安全地址或网络传输失败
"""
-
if notifier is not None:
try:
await notifier(uri, token)
@@ -210,14 +202,12 @@ async def send_backchannel_once(
def _raise_permanent_http_error(exc: httpx.HTTPStatusError) -> None:
"""
- 将不可重试的 HTTP 客户端错误转换为永久失败
+ 将不可重试的 HTTP 客户端错误转换为永久失败。
:param exc: HTTPX 状态码异常
- :return: None
:raises PermanentBackchannelError: 状态码属于不可重试的客户端错误
:raises httpx.HTTPStatusError: 状态码仍允许调用方重试
"""
-
status = exc.response.status_code
if _HTTP_CLIENT_ERROR_MIN <= status < _HTTP_SERVER_ERROR_MIN and status not in {
_HTTP_REQUEST_TIMEOUT,
diff --git a/ruoyi-fastapi-backend/module_identity/security/client_auth.py b/ruoyi-fastapi-backend/module_identity/security/client_auth.py
index 90844ab59..a323ecd6f 100644
--- a/ruoyi-fastapi-backend/module_identity/security/client_auth.py
+++ b/ruoyi-fastapi-backend/module_identity/security/client_auth.py
@@ -11,7 +11,7 @@
class ClientAuthenticationError(ValueError):
"""
- 客户端认证失败
+ 客户端认证失败。
协议层应将此异常统一映射为 invalid_client,不能泄漏 Secret 细节
"""
@@ -19,12 +19,12 @@ class ClientAuthenticationError(ValueError):
def hash_client_secret(client_secret: str) -> str:
"""
- 使用项目密码哈希器保存 Client Secret
+ 使用项目密码哈希器保存 Client Secret。
:param client_secret: 仅在创建/轮换时可见的明文 Secret
:return: 可持久化的强哈希
+ :raises ValueError: 客户端密钥不能为空
"""
-
if not isinstance(client_secret, str) or not client_secret:
raise ValueError('客户端密钥不能为空')
return PwdUtil.get_password_hash(client_secret)
@@ -32,13 +32,12 @@ def hash_client_secret(client_secret: str) -> str:
def verify_client_secret(client_secret: str, secret_hash: str) -> bool:
"""
- 验证 Client Secret,错误输入统一返回 False
+ 验证 Client Secret,错误输入统一返回 False。
:param client_secret: 请求携带的明文 Secret
:param secret_hash: 已存储的 Secret 哈希
:return: Secret 是否匹配
"""
-
if not isinstance(client_secret, str) or not isinstance(secret_hash, str) or not secret_hash:
return False
try:
@@ -58,14 +57,14 @@ def authenticate_client( # noqa: PLR0912
secret_match_callback: Callable[[str], None] | None = None,
) -> OAuthClientPrincipal:
"""
- 按已注册 Client 策略认证
+ 按已注册 Client 策略认证。
机密 Client 仅接受 Basic;公共 Client 仅接受 form 的 client_id 且不得
携带 Secret。``client_lookup`` 仅用于在 Header client_id 与传入对象
分离时查找注册记录
:param client: 已注册 Client 或支持属性访问的对象
- :param authorization: RFC 7617 Basic Header
+ :param authorization: 符合 RFC 7617 的 Basic 认证头
:param client_id: 公共 Client 的表单 client_id
:param client_secret: 仅用于拒绝请求体 Secret 的参数
:param secret_hashes: 可注入的有效 Secret 哈希集合
@@ -74,7 +73,6 @@ def authenticate_client( # noqa: PLR0912
:return: 已认证的 OAuth Client 主体
:raises ClientAuthenticationError: Client 策略或凭据不匹配
"""
-
supplied_id = client_id
supplied_secret = client_secret
auth_method = 'none'
diff --git a/ruoyi-fastapi-backend/module_identity/security/jwt_profile.py b/ruoyi-fastapi-backend/module_identity/security/jwt_profile.py
index 908c02260..d2c00e2ee 100644
--- a/ruoyi-fastapi-backend/module_identity/security/jwt_profile.py
+++ b/ruoyi-fastapi-backend/module_identity/security/jwt_profile.py
@@ -16,21 +16,18 @@
class JwtProfileError(ValueError):
- """
- JWT Profile 校验失败
- """
+ """JWT Profile 校验失败。"""
def _key_for_kid(verification_keys: object, kid: str) -> object:
"""
- 按 Key ID 选择本地验签密钥
+ 按 Key ID 选择本地验签密钥。
:param verification_keys: 验签密钥、按 Key ID 索引的映射或查找回调
:param kid: JWT Header 中的 Key ID
:return: 匹配的验签密钥
:raises JwtProfileError: 验签密钥缺失或 Key ID 未知
"""
-
if verification_keys is None:
raise JwtProfileError('签名密钥不能为空')
if isinstance(verification_keys, Mapping):
@@ -48,13 +45,12 @@ def _key_for_kid(verification_keys: object, kid: str) -> object:
def _header(token: str) -> dict[str, Any]:
"""
- 读取并校验 JWT Header 安全字段
+ 读取并校验 JWT Header 安全字段。
:param token: 待读取的 JWT
:return: 通过固定算法与 Header 白名单校验的字段映射
:raises JwtProfileError: JWT 编码、算法或 Header 字段不合法
"""
-
try:
value = jwt.get_unverified_header(token)
except (PyJWTError, TypeError, ValueError) as exc:
@@ -70,16 +66,14 @@ def _header(token: str) -> dict[str, Any]:
def _numeric_claims(payload: Mapping[str, Any], *, now: float, skew: float, verify_exp: bool = True) -> None:
"""
- 校验 JWT NumericDate 类型和时效
+ 校验 JWT NumericDate 类型和时效。
:param payload: 已验签的 JWT Claims
:param now: 当前 UTC 时间戳
:param skew: 允许的时钟偏差秒数
:param verify_exp: 是否校验过期时间,仅退出提示流程可关闭
- :return: None
:raises JwtProfileError: NumericDate 类型或时效不合法
"""
-
for name in ('iat', 'exp', 'nbf', 'auth_time'):
if name not in payload:
if name == 'iat':
@@ -100,13 +94,11 @@ def _numeric_claims(payload: Mapping[str, Any], *, now: float, skew: float, veri
def _validate_numeric_types(payload: Mapping[str, Any]) -> None:
"""
- 仅校验 NumericDate 类型,不在签发时用当前时间判断有效期
+ 仅校验 NumericDate 类型,不在签发时用当前时间判断有效期。
:param payload: 待签发的 JWT Claims
- :return: None
:raises JwtProfileError: NumericDate 类型不合法
"""
-
for name in ('iat', 'exp', 'nbf', 'auth_time'):
if name in payload and (
isinstance(payload[name], bool)
@@ -118,13 +110,12 @@ def _validate_numeric_types(payload: Mapping[str, Any]) -> None:
def _audience_matches(actual: object, expected: str | Sequence[str] | None) -> bool:
"""
- 判断实际 Audience 是否匹配允许值
+ 判断实际 Audience 是否匹配允许值。
:param actual: JWT 中的 Audience
:param expected: 允许的单个或多个 Audience
:return: Audience 是否匹配
"""
-
if expected is None:
return True
values = [actual] if isinstance(actual, str) else actual
@@ -137,15 +128,13 @@ def _audience_matches(actual: object, expected: str | Sequence[str] | None) -> b
def _validate_string_claim(payload: Mapping[str, Any], name: str, required: bool = True) -> None:
"""
- 校验 JWT 字符串 Claim
+ 校验 JWT 字符串 Claim。
- :param payload: JWT Claims
+ :param payload: JWT 中的声明
:param name: Claim 名称
:param required: 是否要求 Claim 必须存在
- :return: None
:raises JwtProfileError: Claim 缺失或不是非空字符串
"""
-
value = payload.get(name)
if value is None and not required:
return
@@ -155,15 +144,13 @@ def _validate_string_claim(payload: Mapping[str, Any], name: str, required: bool
def _validate_string_list(payload: Mapping[str, Any], name: str, required: bool = True) -> None:
"""
- 校验 JWT 字符串列表 Claim
+ 校验 JWT 字符串列表 Claim。
- :param payload: JWT Claims
+ :param payload: JWT 中的声明
:param name: Claim 名称
:param required: 是否要求 Claim 必须存在
- :return: None
:raises JwtProfileError: Claim 缺失或不是非空字符串列表
"""
-
value = payload.get(name)
if value is None and not required:
return
@@ -173,13 +160,11 @@ def _validate_string_list(payload: Mapping[str, Any], name: str, required: bool
def _validate_audience_claim(payload: Mapping[str, Any]) -> None:
"""
- 校验 JWT Audience Claim
+ 校验 JWT Audience Claim。
- :param payload: JWT Claims
- :return: None
+ :param payload: JWT 中的声明
:raises JwtProfileError: Audience 结构、内容或唯一性不合法
"""
-
aud = payload.get('aud')
if not isinstance(aud, (str, list)):
raise JwtProfileError('JWT 受众声明 aud 无效')
@@ -193,13 +178,11 @@ def _validate_audience_claim(payload: Mapping[str, Any]) -> None:
def _validate_access_claims(payload: Mapping[str, Any]) -> None:
"""
- 校验 Access Token Profile Claims
+ 校验 Access Token Profile Claims。
- :param payload: Access Token Claims
- :return: None
+ :param payload: 访问令牌的声明
:raises JwtProfileError: 必需 Claim 或身份绑定不合法
"""
-
for name in ('iss', 'sub', 'client_id', 'scope'):
_validate_string_claim(payload, name)
_validate_audience_claim(payload)
@@ -233,13 +216,11 @@ def _validate_access_claims(payload: Mapping[str, Any]) -> None:
def _validate_access_authorization_context(payload: Mapping[str, Any]) -> None:
"""
- 校验 Access Token 的可选授权来源 Claims
+ 校验 Access Token 的可选授权来源 Claims。
:param payload: Access Token Claims,存量令牌可不包含授权来源字段
- :return: None
:raises JwtProfileError: Client 策略版本或 Grant 绑定不合法
"""
-
if 'client_policy_version' not in payload:
if 'grant_id' in payload:
raise JwtProfileError('访问令牌缺少客户端策略版本')
@@ -263,13 +244,11 @@ def _validate_access_authorization_context(payload: Mapping[str, Any]) -> None:
def _validate_id_claims(payload: Mapping[str, Any]) -> None:
"""
- 校验 ID Token Profile Claims
+ 校验 ID Token Profile Claims。
- :param payload: ID Token Claims
- :return: None
+ :param payload: 身份令牌的声明
:raises JwtProfileError: 必需 Claim 不合法
"""
-
for name in ('iss', 'sub', 'sid', 'acr', 'nonce'):
_validate_string_claim(payload, name)
_validate_audience_claim(payload)
@@ -281,13 +260,11 @@ def _validate_id_claims(payload: Mapping[str, Any]) -> None:
def _validate_logout_claims(payload: Mapping[str, Any]) -> None:
"""
- 校验 Logout Token Profile Claims
+ 校验 Logout Token Profile Claims。
- :param payload: Logout Token Claims
- :return: None
+ :param payload: 注销令牌的声明
:raises JwtProfileError: 必需 Claim、事件或主体绑定不合法
"""
-
for name in ('iss', 'jti'):
_validate_string_claim(payload, name)
_validate_audience_claim(payload)
@@ -307,14 +284,12 @@ def _validate_logout_claims(payload: Mapping[str, Any]) -> None:
def _validate_profile_claims(profile: str, payload: Mapping[str, Any]) -> None:
"""
- 按 JWT Profile 分派 Claims 校验
+ 按 JWT Profile 分派 Claims 校验。
:param profile: access、id 或 logout Profile
- :param payload: JWT Claims
- :return: None
+ :param payload: JWT 中的声明
:raises JwtProfileError: Profile Claims 不合法
"""
-
if profile == 'access':
_validate_access_claims(payload)
elif profile == 'id':
@@ -337,7 +312,7 @@ def _decode(
allow_expired_hint: bool = False,
) -> dict[str, Any]:
"""
- 按固定 Profile 验签并校验 JWT
+ 按固定 Profile 验签并校验 JWT。
:param token: 待验证的 JWT
:param verification_keys: 验签密钥、映射或查找回调
@@ -352,7 +327,6 @@ def _decode(
:return: 已验签并通过 Profile 校验的 Claims
:raises JwtProfileError: Header、签名、Issuer、Audience 或 Claims 不合法
"""
-
if clock_skew < 0:
raise JwtProfileError('时钟容差不得为负数')
headers = _header(token)
@@ -386,7 +360,7 @@ def _decode(
def _encode(claims: Mapping[str, Any], signing_key: RSAPrivateKey, kid: str, expected_type: str, profile: str) -> str:
"""
- 按固定 Profile Header 签发 JWT
+ 按固定 Profile Header 签发 JWT。
:param claims: 待签发且已包含协议必需字段的 Claims
:param signing_key: RSA 私钥
@@ -396,7 +370,6 @@ def _encode(claims: Mapping[str, Any], signing_key: RSAPrivateKey, kid: str, exp
:return: 签名后的 JWT 字符串
:raises JwtProfileError: Key ID、Claims 或编码过程不合法
"""
-
payload = dict(claims)
if not isinstance(kid, str) or not kid.strip():
raise JwtProfileError('JWT 缺少签名密钥标识 kid')
@@ -411,15 +384,14 @@ def _encode(claims: Mapping[str, Any], signing_key: RSAPrivateKey, kid: str, exp
def encode_access_token(claims: Mapping[str, Any], signing_key: RSAPrivateKey, kid: str) -> str:
"""
- 签发 JWT Access Token
+ 签发 JWT Access Token。
- :param claims: Access Token Claims
+ :param claims: 访问令牌的声明
:param signing_key: RSA 私钥
:param kid: 签名密钥标识
:return: typ 为 at+jwt 的 JWT
:raises JwtProfileError: Claims 或签名参数不合法
"""
-
return _encode(claims, signing_key, kid, ACCESS_TOKEN_TYPE, 'access')
@@ -433,7 +405,7 @@ def decode_access_token(
verification_key: RSAPublicKey | None = None,
) -> dict[str, Any]:
"""
- 验证 JWT Access Token Profile
+ 验证 JWT Access Token Profile。
:param token: 待验证 JWT
:param verification_keys: 按 kid 索引的公钥、单一公钥或查找回调
@@ -444,7 +416,6 @@ def decode_access_token(
:return: 已验签的 Access Token Claims
:raises JwtProfileError: Access Token 不符合固定 Profile
"""
-
if issuer is None:
raise JwtProfileError('签发者地址 issuer 不能为空')
return _decode(
@@ -462,15 +433,14 @@ def decode_access_token(
def encode_id_token(claims: Mapping[str, Any], signing_key: RSAPrivateKey, kid: str) -> str:
"""
- 签发 OIDC ID Token
+ 签发 OIDC ID Token。
- :param claims: ID Token Claims
+ :param claims: 身份令牌的声明
:param signing_key: RSA 私钥
:param kid: 签名密钥标识
:return: typ 为 JWT 的 ID Token
:raises JwtProfileError: Claims 或签名参数不合法
"""
-
return _encode(claims, signing_key, kid, ID_TOKEN_TYPE, 'id')
@@ -485,19 +455,18 @@ def decode_id_token(
verification_key: RSAPublicKey | None = None,
) -> dict[str, Any]:
"""
- 验证 OIDC ID Token 并可校验 nonce
+ 验证 OIDC ID Token 并可校验 nonce。
:param token: 待验证 ID Token
:param verification_keys: 按 kid 索引的公钥、单一公钥或查找回调
:param issuer: 必须精确匹配的 issuer
- :param audience: OIDC Client ID
+ :param audience: OIDC 客户端标识
:param nonce: 可选的原始授权 nonce
:param clock_skew: 允许的时钟偏差秒数
:param verification_key: 可选的单一 RSA 公钥
:return: 已验签的 ID Token Claims
:raises JwtProfileError: ID Token 不符合固定 Profile 或 nonce 不匹配
"""
-
if issuer is None:
raise JwtProfileError('签发者地址 issuer 不能为空')
claims = _decode(
@@ -525,7 +494,7 @@ def decode_id_token_hint(
clock_skew: float = 60,
) -> dict[str, Any]:
"""
- 校验退出请求中的ID Token提示
+ 校验退出请求中的ID Token提示。
仅退出流程允许使用过期ID Token,调用方仍需将其绑定到已知会话。
@@ -536,7 +505,6 @@ def decode_id_token_hint(
:param clock_skew: 允许的时钟偏差,单位为秒
:return: 已校验的ID Token声明
"""
-
return _decode(
token,
None,
@@ -553,15 +521,14 @@ def decode_id_token_hint(
def encode_logout_token(claims: Mapping[str, Any], signing_key: RSAPrivateKey, kid: str) -> str:
"""
- 签发 Back-Channel Logout Token
+ 签发 Back-Channel Logout Token。
- :param claims: Logout Token Claims
+ :param claims: 注销令牌的声明
:param signing_key: RSA 私钥
:param kid: 签名密钥标识
:return: typ 为 logout+jwt 的 JWT
:raises JwtProfileError: Claims 或签名参数不合法
"""
-
return _encode(claims, signing_key, kid, LOGOUT_TOKEN_TYPE, 'logout')
@@ -575,7 +542,7 @@ def decode_logout_token(
verification_key: RSAPublicKey | None = None,
) -> dict[str, Any]:
"""
- 验证 Back-Channel Logout Token
+ 验证 Back-Channel Logout Token。
:param token: 待验证 Logout Token
:param verification_keys: 按 kid 索引的公钥、单一公钥或查找回调
@@ -586,7 +553,6 @@ def decode_logout_token(
:return: 已验签的 Logout Token Claims
:raises JwtProfileError: Logout Token 不符合固定 Profile
"""
-
if issuer is None:
raise JwtProfileError('签发者地址 issuer 不能为空')
return _decode(
diff --git a/ruoyi-fastapi-backend/module_identity/security/opaque_token.py b/ruoyi-fastapi-backend/module_identity/security/opaque_token.py
index 6b854a3d8..f25c01e78 100644
--- a/ruoyi-fastapi-backend/module_identity/security/opaque_token.py
+++ b/ruoyi-fastapi-backend/module_identity/security/opaque_token.py
@@ -9,17 +9,19 @@
class OpaqueTokenError(ValueError):
- """
- 不透明令牌结构、类型或 Secret 不符合安全约束
- """
+ """不透明令牌结构、类型或 Secret 不符合安全约束。"""
@dataclass(frozen=True, slots=True)
class ParsedOpaqueToken:
"""
- 已解析但尚未证明有效的不透明令牌
+ 已解析但尚未证明有效的不透明令牌。
解析结果只描述格式,数据库摘要校验成功后才具有凭据语义
+
+ :ivar prefix: ac1、rt1 或 ss1
+ :ivar token_id: 会话编号
+ :ivar secret: 用于验证身份或令牌的秘密值
"""
prefix: str
@@ -29,11 +31,10 @@ class ParsedOpaqueToken:
@property
def value(self) -> str:
"""
- 返回完整的不透明令牌文本
+ 返回完整的不透明令牌文本。
:return: 带类型前缀的完整令牌
"""
-
return f'{self.prefix}.{self.token_id}.{self.secret}'
@@ -47,13 +48,13 @@ def value(self) -> str:
def generate_opaque_token(prefix: str, token_id: str | None = None) -> str:
"""
- 生成带类型前缀和 256 bit 随机 Secret 的不透明令牌
+ 生成带类型前缀和 256 bit 随机 Secret 的不透明令牌。
:param prefix: ac1、rt1 或 ss1
:param token_id: 可选的外部 ID
:return: 完整不透明令牌
+ :raises OpaqueTokenError: 不透明令牌标识无效
"""
-
if prefix not in _PREFIXES:
raise OpaqueTokenError(f'不支持的不透明令牌前缀:{prefix}')
identifier = token_id or str(uuid.uuid4())
@@ -64,47 +65,43 @@ def generate_opaque_token(prefix: str, token_id: str | None = None) -> str:
def generate_authorization_code(code_id: str | None = None) -> str:
"""
- 生成授权码
+ 生成授权码。
:param code_id: 可选的授权码 ID
:return: ac1 前缀的不透明授权码
"""
-
return generate_opaque_token('ac1', code_id)
def generate_refresh_token(token_id: str | None = None) -> str:
"""
- 生成 Refresh Token
+ 生成 Refresh Token。
:param token_id: 可选的 Refresh Token ID
:return: rt1 前缀的不透明 Refresh Token
"""
-
return generate_opaque_token('rt1', token_id)
def generate_sso_cookie(sid: str | None = None) -> str:
"""
- 生成 SSO Cookie Secret
+ 生成 SSO Cookie Secret。
:param sid: 可选的 SSO Session ID
:return: ss1 前缀的 Cookie 值
"""
-
return generate_opaque_token('ss1', sid)
def parse_opaque_token(token: str, expected_prefix: str | None = None) -> ParsedOpaqueToken:
"""
- 解析令牌结构,不把 token_id 当作 Secret 证明
+ 解析令牌结构,不把 token_id 当作 Secret 证明。
:param token: 待解析的不透明令牌
:param expected_prefix: 可选的预期类型前缀
:return: 结构化令牌
:raises OpaqueTokenError: 令牌结构、类型或 Secret 不合法
"""
-
if not isinstance(token, str):
raise OpaqueTokenError('不透明令牌必须为字符串')
parts = token.split('.')
@@ -128,13 +125,12 @@ def parse_opaque_token(token: str, expected_prefix: str | None = None) -> Parsed
def _pepper_bytes(pepper: str | bytes) -> bytes:
"""
- 校验并转换令牌摘要 Pepper
+ 校验并转换令牌摘要 Pepper。
:param pepper: 字符串或字节形式的摘要 Pepper
:return: 长度满足安全约束的 Pepper 字节
:raises ValueError: Pepper 类型或长度不符合安全约束
"""
-
value = pepper.encode('utf-8') if isinstance(pepper, str) else pepper
if not isinstance(value, bytes) or len(value) < _MIN_PEPPER_BYTES:
raise ValueError('身份令牌摘要密钥至少需要 256 位')
@@ -143,26 +139,24 @@ def _pepper_bytes(pepper: str | bytes) -> bytes:
def token_digest(token: str, pepper: str | bytes) -> str:
"""
- 返回完整不透明令牌的 HMAC-SHA256 十六进制摘要
+ 返回完整不透明令牌的 HMAC-SHA256 十六进制摘要。
:param token: 完整 typed opaque token
:param pepper: 独立的摘要 Pepper
:return: 64 位十六进制摘要
"""
-
return OidcUtil.hmac_sha256(token.encode('utf-8'), _pepper_bytes(pepper))
def verify_token_digest(token: str, expected_digest: str, pepper: str | bytes) -> bool:
"""
- 恒定时间校验摘要,畸形 token 或 digest 时拒绝验证
+ 恒定时间校验摘要,畸形 token 或 digest 时拒绝验证。
:param token: 完整 typed opaque token
:param expected_digest: 数据库存储的摘要
:param pepper: 独立的摘要 Pepper
:return: 摘要是否匹配完整令牌
"""
-
if not isinstance(expected_digest, str) or not re.fullmatch(r'[0-9a-fA-F]{64}', expected_digest):
return False
try:
diff --git a/ruoyi-fastapi-backend/module_identity/security/pkce.py b/ruoyi-fastapi-backend/module_identity/security/pkce.py
index 185781aff..f4077a9d4 100644
--- a/ruoyi-fastapi-backend/module_identity/security/pkce.py
+++ b/ruoyi-fastapi-backend/module_identity/security/pkce.py
@@ -7,9 +7,7 @@
class PkceError(ValueError):
- """
- PKCE 参数格式错误或使用了不支持的算法
- """
+ """PKCE 参数格式错误或使用了不支持的算法。"""
_MIN_VERIFIER_LENGTH = 43
@@ -19,13 +17,12 @@ class PkceError(ValueError):
def validate_code_verifier(code_verifier: str) -> str:
"""
- 校验并返回 RFC 7636 code_verifier
+ 校验并返回 RFC 7636 code_verifier。
:param code_verifier: 客户端生成的 PKCE verifier
:return: 原样返回已校验 verifier
:raises PkceError: 长度、字符集或类型不合法
"""
-
if not isinstance(code_verifier, str):
raise PkceError('code_verifier 必须为字符串')
if not _MIN_VERIFIER_LENGTH <= len(code_verifier) <= _MAX_VERIFIER_LENGTH:
@@ -37,12 +34,12 @@ def validate_code_verifier(code_verifier: str) -> str:
def generate_code_verifier(length: int = 64) -> str:
"""
- 生成至少 256 bit 熵的 code_verifier
+ 生成至少 256 bit 熵的 code_verifier。
:param length: verifier 长度,范围为 43 至 128
:return: 随机 code_verifier
+ :raises ValueError: code_verifier 长度必须为 43 至 128 个字符
"""
-
if not _MIN_VERIFIER_LENGTH <= length <= _MAX_VERIFIER_LENGTH:
raise ValueError('code_verifier 长度必须为 43 至 128 个字符')
# token_urlsafe 的结果可能略长;截断仍保留足够熵且满足 RFC 字符集
@@ -51,12 +48,11 @@ def generate_code_verifier(length: int = 64) -> str:
def generate_code_challenge(code_verifier: str) -> str:
"""
- 计算未填充的 base64url(SHA-256(verifier))
+ 计算未填充的 base64url(SHA-256(verifier))。
:param code_verifier: 已校验的 PKCE verifier
- :return: S256 code_challenge
+ :return: 使用 S256 计算的 PKCE 挑战值
"""
-
verifier = validate_code_verifier(code_verifier)
return OidcUtil.base64url_encode(hashlib.sha256(verifier.encode('ascii')).digest())
@@ -64,7 +60,7 @@ def generate_code_challenge(code_verifier: str) -> str:
def verify_code_challenge(code_verifier: str, code_challenge: str, method: str = 'S256') -> bool:
"""
- 以恒定时间比较 challenge,畸形值统一返回 False
+ 以恒定时间比较 challenge,畸形值统一返回 False。
:param code_verifier: Token Endpoint 提交的 verifier
:param code_challenge: Authorization Endpoint 保存的 challenge
@@ -72,7 +68,6 @@ def verify_code_challenge(code_verifier: str, code_challenge: str, method: str =
:return: verifier 是否匹配 challenge
:raises PkceError: 使用不支持的 PKCE 方法
"""
-
if method != 'S256':
raise PkceError('仅支持 PKCE S256 算法')
try:
diff --git a/ruoyi-fastapi-backend/module_identity/security/principal.py b/ruoyi-fastapi-backend/module_identity/security/principal.py
index 0cdaa267f..37ab5d418 100644
--- a/ruoyi-fastapi-backend/module_identity/security/principal.py
+++ b/ruoyi-fastapi-backend/module_identity/security/principal.py
@@ -4,7 +4,14 @@
@dataclass(frozen=True, slots=True)
class OidcUserPrincipal:
"""
- OIDC 用户主体,不承载可变数据库 user_id
+ OIDC 用户主体,不承载可变数据库 user_id。
+
+ :ivar subject_id: 身份主体的唯一标识
+ :ivar client_id: 客户端标识
+ :ivar scopes: 已授予或请求的权限范围
+ :ivar audience: 令牌适用的目标资源标识
+ :ivar sid: 关联的单点登录会话标识
+ :ivar auth_version: 用户认证安全版本
"""
subject_id: str
@@ -17,18 +24,21 @@ class OidcUserPrincipal:
@property
def sub(self) -> str:
"""
- 返回稳定的 OIDC Subject
+ 返回稳定的 OIDC Subject。
- :return: OIDC Subject
+ :return: OIDC 主体标识
"""
-
return self.subject_id
@dataclass(frozen=True, slots=True)
class OAuthClientPrincipal:
"""
- 已完成 Client Authentication 的外部应用主体
+ 已完成 Client Authentication 的外部应用主体。
+
+ :ivar client_id: 客户端标识
+ :ivar client_type: 客户端类型(public公开客户端 confidential机密客户端)
+ :ivar auth_method: 客户端使用的认证方式
"""
client_id: str
@@ -39,7 +49,12 @@ class OAuthClientPrincipal:
@dataclass(frozen=True, slots=True)
class MachinePrincipal:
"""
- 明确的 client_credentials 身份,绝不伪装为用户
+ 明确的 client_credentials 身份,绝不伪装为用户。
+
+ :ivar client_id: 客户端标识
+ :ivar subject: 令牌所代表的主体
+ :ivar scopes: 已授予或请求的权限范围
+ :ivar audience: 令牌适用的目标资源标识
"""
client_id: str
@@ -50,9 +65,8 @@ class MachinePrincipal:
@property
def is_machine(self) -> bool:
"""
- 标识该主体来自 client_credentials 机器身份
+ 标识该主体来自 client_credentials 机器身份。
:return: 固定返回 True
"""
-
return True
diff --git a/ruoyi-fastapi-backend/module_identity/security/uri_validator.py b/ruoyi-fastapi-backend/module_identity/security/uri_validator.py
index 0290b3a7f..7236385db 100644
--- a/ruoyi-fastapi-backend/module_identity/security/uri_validator.py
+++ b/ruoyi-fastapi-backend/module_identity/security/uri_validator.py
@@ -6,25 +6,23 @@
async def public_dns_only(hostname: str, port: int) -> bool:
"""
- 解析目标主机全部 A/AAAA 记录并拒绝任一受限地址
+ 解析目标主机全部 A/AAAA 记录并拒绝任一受限地址。
:param hostname: 已从 URI 解析出的主机名
:param port: 目标 TCP 端口
:return: 解析成功且全部地址为公网地址时返回 ``True``
"""
-
return bool(await public_dns_addresses(hostname, port))
async def public_dns_addresses(hostname: str, port: int) -> set[str]:
"""
- 解析并返回本次连接允许固定使用的公网地址集合
+ 解析并返回本次连接允许固定使用的公网地址集合。
:param hostname: 已解析的主机名
:param port: 目标 TCP 端口
:return: 全部解析结果均安全时的地址集合,失败返回空集合
"""
-
loop = asyncio.get_running_loop()
try:
records = await loop.run_in_executor(
@@ -40,12 +38,11 @@ async def public_dns_addresses(hostname: str, port: int) -> set[str]:
async def is_safe_backchannel_uri(uri: object) -> bool:
"""
- 校验 Back-Channel URI 结构并执行 DNS 公网重解析
+ 校验 Back-Channel URI 结构并执行 DNS 公网重解析。
:param uri: 待校验的注册或发送 URI
:return: 仅 HTTPS、无用户信息、查询、片段且 DNS 目标全部公网时返回 ``True``
"""
-
parsed = OidcUtil.parse_backchannel_uri(uri)
if parsed is None:
return False
diff --git a/ruoyi-fastapi-backend/module_identity/service/audit_service.py b/ruoyi-fastapi-backend/module_identity/service/audit_service.py
index 8a742c826..ac4aabc44 100644
--- a/ruoyi-fastapi-backend/module_identity/service/audit_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/audit_service.py
@@ -15,7 +15,11 @@
class AuditService:
"""
- 认证审计模块服务层
+ 认证审计模块服务层。
+
+ :cvar EVENT_FIELDS: 审计事件允许记录的字段
+ :cvar HIGH_RISK_EVENTS: 标记为高风险的审计事件类型
+ :cvar _EVENT_TYPE_MAX_LENGTH: 审计事件类型名允许的最大长度
"""
EVENT_FIELDS = frozenset(
@@ -59,13 +63,12 @@ class AuditService:
@classmethod
def _risk_level(cls, event_type: str, risk_level: str | None) -> str:
"""
- 计算事件风险等级
+ 计算事件风险等级。
:param event_type: 审计事件类型
:param risk_level: 风险等级
:return: 审计风险等级
"""
-
if event_type in cls.HIGH_RISK_EVENTS:
return 'high'
return risk_level if risk_level in {'normal', 'medium', 'high', 'critical'} else 'normal'
@@ -73,13 +76,12 @@ def _risk_level(cls, event_type: str, risk_level: str | None) -> str:
@classmethod
def build_event(cls, **fields: Any) -> SysOAuthAuditLog:
"""
- 按审计模型字段白名单构建安全事件对象
+ 按审计模型字段白名单构建安全事件对象。
:param fields: 审计字段;白名单以外的字段会被丢弃
:return: 未提交的审计日志实体
:raises ValueError: 缺少事件类型或结果时抛出
"""
-
event_type = fields.get('event_type')
result = fields.get('result')
if (
@@ -124,7 +126,7 @@ async def record(
**fields: Any,
) -> SysOAuthAuditLog:
"""
- 脱敏并追加一条审计事件,不提交调用方事务
+ 脱敏并追加一条审计事件,不提交调用方事务。
:param db: 异步数据库会话
:param event_type: 事件类型
@@ -133,7 +135,6 @@ async def record(
:param fields: 其余白名单审计字段
:return: 已刷新但尚未提交的审计日志实体
"""
-
event = cls.build_event(event_type=event_type, result=result, risk_level=risk_level, **fields)
return await OAuthAuditDao.append(db, event)
@@ -149,7 +150,7 @@ async def record_independent(
**fields: Any,
) -> SysOAuthAuditLog:
"""
- 在不依赖业务事务的独立会话中提交审计事件
+ 在不依赖业务事务的独立会话中提交审计事件。
:param db: 当前业务会话,用于测试环境复用其绑定引擎
:param event_type: 事件类型
@@ -158,7 +159,6 @@ async def record_independent(
:param fields: 经过白名单过滤的安全字段
:return: 已提交的审计日志实体
"""
-
engine = db.info.get('service_engine') or getattr(db, 'bind', None)
if engine is not None:
factory = async_sessionmaker(engine, expire_on_commit=False)
@@ -186,13 +186,12 @@ async def record_independent(
@classmethod
async def append(cls, db: AsyncSession, event: SysOAuthAuditLog | Mapping[str, Any]) -> SysOAuthAuditLog:
"""
- 追加事件对象或字段映射,并保留调用方提交边界
+ 追加事件对象或字段映射,并保留调用方提交边界。
:param db: 异步数据库会话
:param event: 审计实体或待构建字段映射
:return: 已刷新但尚未提交的审计日志实体
"""
-
row = event if isinstance(event, SysOAuthAuditLog) else cls.build_event(**dict(event))
return await OAuthAuditDao.append(db, row)
@@ -200,12 +199,11 @@ async def append(cls, db: AsyncSession, event: SysOAuthAuditLog | Mapping[str, A
@staticmethod
def _admin_filters(query: AuditPageQueryModel) -> dict[str, object]:
"""
- 构造管理端审计查询条件
+ 构造管理端审计查询条件。
:param query: 管理端审计分页查询条件
:return: 传给审计 DAO 的筛选条件
"""
-
return {
'client_id': query.client_id,
'user_id': query.user_id,
@@ -219,12 +217,11 @@ def _admin_filters(query: AuditPageQueryModel) -> dict[str, object]:
@staticmethod
def _admin_model(row: SysOAuthAuditLog) -> dict[str, object]:
"""
- 将审计实体投影为脱敏管理端模型
+ 将审计实体投影为脱敏管理端模型。
:param row: 审计日志实体
:return: 不含详情敏感字段的管理端模型字典
"""
-
return AuditModel(
audit_id=row.event_id,
event_type=row.event_type,
@@ -244,13 +241,12 @@ def _admin_model(row: SysOAuthAuditLog) -> dict[str, object]:
@classmethod
async def list_admin_page(cls, db: AsyncSession, query: AuditPageQueryModel) -> tuple[list[dict[str, object]], int]:
"""
- 查询管理端审计分页并返回脱敏结果
+ 查询管理端审计分页并返回脱敏结果。
:param db: 异步数据库会话
:param query: 管理端审计分页查询条件
:return: 脱敏审计行列表及总数
"""
-
params = cls._admin_filters(query)
rows = await OAuthAuditDao.list_admin_page(
db, offset=(query.page_num - 1) * query.page_size, limit=query.page_size, **params
@@ -262,13 +258,12 @@ async def list_admin_page(cls, db: AsyncSession, query: AuditPageQueryModel) ->
@classmethod
async def export_admin(cls, db: AsyncSession, query: AuditPageQueryModel) -> bytes:
"""
- 导出管理端审计分页范围内的脱敏数据
+ 导出管理端审计分页范围内的脱敏数据。
:param db: 异步数据库会话
:param query: 管理端审计筛选条件
:return: 脱敏审计 Excel 文件字节
"""
-
rows = await OAuthAuditDao.list_admin_page(db, offset=0, limit=5000, **cls._admin_filters(query))
mapping = {field.alias or name: field.alias or name for name, field in AuditModel.model_fields.items()}
@@ -277,15 +272,13 @@ async def export_admin(cls, db: AsyncSession, query: AuditPageQueryModel) -> byt
@classmethod
async def record_interaction_failure(cls, db: AsyncSession, event_type: str, **fields: Any) -> None:
"""
- 回滚交互事务并独立提交高风险失败审计
+ 回滚交互事务并独立提交高风险失败审计。
:param db: 认证交互使用的异步数据库会话
:param event_type: 失败审计事件类型
:param fields: 经过白名单过滤的审计字段
- :return: None
:raises OidcInteractionException: 独立审计提交失败时抛出
"""
-
await db.rollback()
try:
await cls.record_independent(db, event_type, 'failure', risk_level='high', **fields)
@@ -296,7 +289,7 @@ async def record_interaction_failure(cls, db: AsyncSession, event_type: str, **f
@staticmethod
def interaction_subject_writer(db: AsyncSession) -> Callable[[int], Awaitable[object]]:
"""
- 构造缺失身份主体的独立审计写入器
+ 构造缺失身份主体的独立审计写入器。
:param db: 认证交互使用的异步数据库会话
:return: 接收用户 ID 并独立写入审计的异步回调
@@ -304,12 +297,11 @@ def interaction_subject_writer(db: AsyncSession) -> Callable[[int], Awaitable[ob
async def write(user_id: int) -> object:
"""
- 写入审计记录
+ 写入审计记录。
:param user_id: 本地用户 ID
:return: 已提交的审计日志实体
"""
-
return await AuditService.record_independent(
db,
OidcAuditEvent.IDENTITY_SUBJECT_MISSING,
diff --git a/ruoyi-fastapi-backend/module_identity/service/authorization_service.py b/ruoyi-fastapi-backend/module_identity/service/authorization_service.py
index 4f187f010..a5166c2ae 100644
--- a/ruoyi-fastapi-backend/module_identity/service/authorization_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/authorization_service.py
@@ -46,7 +46,16 @@
@dataclass(frozen=True, slots=True)
class ClientSnapshot:
"""
- 授权流程使用的 Client 只读标量快照
+ 授权流程使用的 Client 只读标量快照。
+
+ :ivar client_pk: OAuth Client 主键
+ :ivar client_id: OAuth Client 标识
+ :ivar policy_version: 客户端策略版本
+ :ivar grant_types: 允许使用的授权类型
+ :ivar response_types: 允许使用的授权响应类型
+ :ivar require_pkce: 是否强制使用PKCE
+ :ivar require_consent: 是否要求用户确认授权
+ :ivar trusted_client: 是否为受信任客户端
"""
client_pk: int
@@ -60,12 +69,10 @@ class ClientSnapshot:
def __post_init__(self) -> None:
"""
- 拒绝可变容器,确保冻结快照不会被原地修改
+ 拒绝可变容器,确保冻结快照不会被原地修改。
- :return: None
:raises TypeError: Grant 或 Response 类型不是不可变元组时抛出
"""
-
if not isinstance(self.grant_types, tuple) or not isinstance(self.response_types, tuple):
raise TypeError('客户端快照的 grant_types 和 response_types 必须为元组')
@@ -73,7 +80,13 @@ def __post_init__(self) -> None:
@dataclass(frozen=True, slots=True)
class ScopeSnapshot:
"""
- 授权流程使用的 Scope 只读标量快照
+ 授权流程使用的 Scope 只读标量快照。
+
+ :ivar scope_pk: Scope 内部主键
+ :ivar scope_code: Scope 编码
+ :ivar scope_type: 权限类型(identity身份权限 resource资源权限)
+ :ivar resource_pk: Resource 内部主键
+ :ivar consent_required: 是否要求用户确认该权限
"""
scope_pk: int
@@ -86,7 +99,10 @@ class ScopeSnapshot:
@dataclass(frozen=True, slots=True)
class ResourceSnapshot:
"""
- 授权流程使用的 Resource 只读标量快照
+ 授权流程使用的 Resource 只读标量快照。
+
+ :ivar resource_pk: Resource 内部主键
+ :ivar audience: 令牌适用的目标资源标识
"""
resource_pk: int
@@ -96,9 +112,23 @@ class ResourceSnapshot:
@dataclass(frozen=True, slots=True)
class AuthorizationContext:
"""
- 已完成协议校验的不可变授权上下文
+ 已完成协议校验的不可变授权上下文。
上下文只保存后续交互和签码所需的白名单字段,不携带未定义查询参数
+
+ :ivar client: 授权流程使用的 Client 只读标量快照
+ :ivar redirect_uri: 已注册的授权回调地址
+ :ivar scopes: 已授予或请求的权限范围
+ :ivar scope_models: 本次授权涉及的权限范围模型
+ :ivar pre_authorized_scopes: 已经预先授权的权限范围
+ :ivar resource: 当前授权或管理的资源
+ :ivar state: 当前流程的状态
+ :ivar nonce: 将认证响应与请求绑定的随机值
+ :ivar code_challenge: Authorization Endpoint 保存的 challenge
+ :ivar code_challenge_method: PKCE挑战方法
+ :ivar prompt: 客户端要求的登录或授权交互方式
+ :ivar max_age: 最大认证时效
+ :ivar required_scopes: 发布声明所需的权限列表
"""
client: ClientSnapshot
@@ -118,11 +148,10 @@ class AuthorizationContext:
@property
def requires_consent(self) -> bool:
"""
- 判断当前请求是否存在尚未预授权的用户 Scope
+ 判断当前请求是否存在尚未预授权的用户 Scope。
:return: 需要显示同意页时为 True
"""
-
consentable = set(self.scopes) - set(self.required_scopes)
if 'consent' in frozenset((self.prompt or '').split()):
return bool(consentable)
@@ -133,21 +162,19 @@ def requires_consent(self) -> bool:
@property
def resources(self) -> tuple[str, ...]:
"""
- 返回授权上下文中的 Resource audience
+ 返回授权上下文中的 Resource audience。
:return: 最多一个 audience 的元组
"""
-
return (self.resource.audience,) if self.resource is not None else ()
def to_internal_payload(self, interaction_id: str) -> dict[str, Any]:
"""
- 构建仅供服务端 Redis Interaction 使用的完整绑定载荷
+ 构建仅供服务端 Redis Interaction 使用的完整绑定载荷。
:param interaction_id: 服务端生成的 Interaction ID
:return: 包含后续签码所需绑定字段且不含 ORM 对象的内部载荷
"""
-
return {
'interactionId': interaction_id,
'clientPk': self.client.client_pk,
@@ -167,12 +194,11 @@ def to_internal_payload(self, interaction_id: str) -> dict[str, Any]:
def to_interaction_payload(self, interaction_id: str) -> dict[str, Any]:
"""
- 构建交互页面可见的非敏感载荷
+ 构建交互页面可见的非敏感载荷。
:param interaction_id: 服务端生成的 Interaction ID
:return: 不包含 state、nonce 和 PKCE challenge 的页面载荷
"""
-
return {
'interactionId': interaction_id,
'clientId': self.client.client_id,
@@ -186,7 +212,10 @@ def to_interaction_payload(self, interaction_id: str) -> dict[str, Any]:
@dataclass(frozen=True, slots=True)
class AuthorizationResult:
"""
- 授权流程完成后交给 HTTP Controller 的纯领域结果
+ 授权流程完成后交给 HTTP Controller 的纯领域结果。
+
+ :ivar location: 客户端接下来应访问的重定向地址
+ :ivar status_code: 响应使用的 HTTP 状态码
"""
location: str
@@ -195,7 +224,7 @@ class AuthorizationResult:
class AuthorizationService:
"""
- 授权模块服务层
+ 授权模块服务层。
校验顺序固定为 Client、精确 Redirect、响应类型、PKCE、Scope 和 Resource,
只有 Redirect 已验证后才允许协议错误携带 redirect_uri 和 state
@@ -204,14 +233,13 @@ class AuthorizationService:
@classmethod
async def _parse_request(cls, db: AsyncSession, raw: dict[str, str]) -> tuple[AuthorizeRequest, str]:
"""
- 先验证 Client 和完整 Redirect,再解析其余协议字段
+ 先验证 Client 和完整 Redirect,再解析其余协议字段。
:param db: 异步数据库会话
:param raw: 已拒绝重复键的 Query 参数
:return: 解析后的授权请求及已验证 Redirect URI
:raises OAuthProtocolException: Client、Redirect 或协议字段无效
"""
-
client_id = raw.get('client_id')
redirect_uri = raw.get('redirect_uri')
if not isinstance(client_id, str) or not isinstance(redirect_uri, str):
@@ -246,7 +274,7 @@ async def process_authorization_request(
sso_cookie: str | None = None,
) -> AuthorizationResult:
"""
- 执行授权请求业务流程并在服务层完成数据库事务
+ 执行授权请求业务流程并在服务层完成数据库事务。
:param db: 异步数据库会话,由本方法提交或回滚
:param redis: 认证中心 Redis 客户端
@@ -255,7 +283,6 @@ async def process_authorization_request(
:return: 交互页面或 Client 回调的 URL 结果
:raises OAuthProtocolException: 协议错误,必要时携带已验证 Redirect
"""
-
request, verified_redirect = await cls._parse_request(db, raw)
if request.resource and await cls.has_disabled_resource(db, request):
raise OAuthProtocolException('not_found', 'Resource is unavailable', 404)
@@ -331,7 +358,7 @@ async def _load_sso_session(
coordinator: AfterCommitCoordinator,
) -> SysSsoSession | None:
"""
- 校验认证中心 SSO Cookie 并更新 Session 空闲期限
+ 校验认证中心 SSO Cookie 并更新 Session 空闲期限。
仅接受认证中心 SSO Cookie,拒绝 Legacy Token 作为登录态
@@ -341,7 +368,6 @@ async def _load_sso_session(
:param coordinator: 提交后副作用协调器
:return: SSO Session 或 None
"""
-
if cookie is None:
return None
try:
@@ -359,14 +385,16 @@ async def _load_sso_session(
@classmethod
async def _complete_authorization(cls, db: AsyncSession, redis: Any, interaction_id: str) -> AuthorizationResult:
"""
- 消费已完成 Interaction 并生成一次性授权码回调结果
+ 消费已完成 Interaction 并生成一次性授权码回调结果。
:param db: 异步数据库会话
:param redis: Redis 客户端
:param interaction_id: 交互流程标识
:return: 授权码重定向结果
+ :raises OidcInteractionException: 认证交互尚未完成;认证交互已完成,请勿重复提交
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises OAuthProtocolException: 无法完成授权并生成一次性授权码
"""
-
record = await InteractionService.get_record(redis, interaction_id)
if record.get('status') != 'completed':
raise OidcInteractionException(interaction_id, '认证交互尚未完成', error='interaction_required')
@@ -429,14 +457,14 @@ async def _complete_authorization(cls, db: AsyncSession, redis: Any, interaction
@classmethod
async def _completion_grant(cls, db: AsyncSession, record: dict[str, Any], session: SysSsoSession) -> SysOAuthGrant:
"""
- 重新检查访问策略并为免确认流程补齐授权记录
+ 重新检查访问策略并为免确认流程补齐授权记录。
:param db: 异步数据库会话
:param record: 已完成的交互记录
:param session: 当前有效 SSO Session
:return: 本次授权码绑定的有效 Grant
+ :raises OAuthProtocolException: 应用访问受限、已有授权失效或需要重新征得同意
"""
-
client_pk = record['clientPk']
await OAuthAccessPolicyDao.lock_client(db, client_pk)
if await OAuthAccessPolicyDao.is_blocked(db, session.user_id, client_pk, for_update=True):
@@ -490,13 +518,12 @@ async def _completion_grant(cls, db: AsyncSession, record: dict[str, Any], sessi
@staticmethod
async def _reserve_completion(redis: Any, interaction_id: str) -> str | None:
"""
- 以 Interaction 剩余 TTL 保留一次终态完成权
+ 以 Interaction 剩余 TTL 保留一次终态完成权。
:param redis: Redis 客户端
:param interaction_id: 交互流程标识
:return: 完成标记 Key 或 None
"""
-
ttl = await redis.ttl(OidcRedisKey.interaction(interaction_id))
if not isinstance(ttl, int) or ttl <= 0:
return None
@@ -508,13 +535,11 @@ async def _reserve_completion(redis: Any, interaction_id: str) -> str | None:
@staticmethod
async def _best_effort_delete(redis: Any, marker: str) -> None:
"""
- 尽力删除授权完成 marker
+ 尽力删除授权完成 marker。
:param redis: Redis 客户端
:param marker: 完成标记 Key
- :return: None
"""
-
try:
await redis.delete(marker)
except Exception:
@@ -523,13 +548,12 @@ async def _best_effort_delete(redis: Any, marker: str) -> None:
@staticmethod
def _requires_reauthentication(auth_time: datetime | None, max_age: int) -> bool:
"""
- 判断 SSO Session 是否超过授权请求的 max_age
+ 判断 SSO Session 是否超过授权请求的 max_age。
:param auth_time: 认证时间
:param max_age: 最大认证时效
:return: 是否需要重新认证
"""
-
if auth_time is None:
return True
current = TimezoneUtil.to_utc(auth_time)
@@ -539,14 +563,14 @@ def _requires_reauthentication(auth_time: datetime | None, max_age: int) -> bool
@staticmethod
def _success_url(redirect_uri: str, code: str, state: str | None) -> str:
"""
- 构建已验证 Client Redirect 的授权码回调地址
+ 构建已验证 Client Redirect 的授权码回调地址。
:param redirect_uri: 已验证的重定向 URI
- :param code: Authorization Code
+ :param code: 授权码
:param state: 协议 state 值
:return: 授权码回调 URL
+ :raises OAuthProtocolException: 回调地址不是有效的绝对地址或带有片段
"""
-
parsed = urlsplit(redirect_uri)
if parsed.fragment or not parsed.scheme or not parsed.netloc:
raise OAuthProtocolException('server_error', 'Validated redirect URI is invalid', 500)
@@ -563,14 +587,13 @@ def _with_verified_redirect(
exc: OidcInteractionException, redirect_uri: str, state: str | None
) -> OAuthProtocolException:
"""
- 把 Interaction 错误绑定到已验证 Redirect
+ 把 Interaction 错误绑定到已验证 Redirect。
:param exc: 协议异常
:param redirect_uri: 待核验的请求重定向 URI
:param state: 协议 state 值
:return: 绑定重定向的协议异常
"""
-
return OAuthProtocolException(
exc.error,
exc.message,
@@ -584,14 +607,13 @@ def _with_verified_redirect(
@staticmethod
async def _record_failure_audit(db: AsyncSession, event_type: str, **fields: Any) -> None:
"""
- 尝试记录授权失败审计,审计异常不改变原协议错误响应
+ 尝试记录授权失败审计,审计异常不改变原协议错误响应。
:param db: 异步数据库会话
:param event_type: 审计事件类型
:param fields: 失败审计字段映射
- :return: None
+ :raises OAuthProtocolException: 授权审计服务不可用
"""
-
try:
await AuditService.record_independent(db, event_type, 'failure', risk_level='high', **fields)
except Exception as exc:
@@ -600,14 +622,14 @@ async def _record_failure_audit(db: AsyncSession, event_type: str, **fields: Any
@staticmethod
async def verified_redirect(db: AsyncSession, client_id: str, redirect_uri: str) -> str:
"""
- 返回已注册的精确 Redirect URI
+ 返回已注册的精确 Redirect URI。
:param db: 异步数据库会话
:param client_id: OAuth Client 标识
:param redirect_uri: 已验证的重定向 URI
:return: 已注册的精确重定向 URI
+ :raises OAuthProtocolException: 客户端未注册或回调地址未登记
"""
-
client = await OAuthClientDao.get_by_client_id(db, client_id, active_only=True)
if client is None:
raise OAuthProtocolException('unauthorized_client', 'Client is not registered')
@@ -619,14 +641,13 @@ async def verified_redirect(db: AsyncSession, client_id: str, redirect_uri: str)
@staticmethod
async def verified_redirect_for_client(db: AsyncSession, client_pk: int, redirect_uri: str) -> str | None:
"""
- 按内部 Client 主键确认已注册的 Redirect URI
+ 按内部 Client 主键确认已注册的 Redirect URI。
:param db: 异步数据库会话
:param client_pk: OAuth Client 主键
:param redirect_uri: 已验证的重定向 URI
:return: 匹配的重定向 URI 或 None
"""
-
registered = await OAuthClientDao.find_exact_uri(db, client_pk, 'redirect', redirect_uri)
return registered.uri if registered is not None else None
@@ -634,26 +655,24 @@ async def verified_redirect_for_client(db: AsyncSession, client_pk: int, redirec
@staticmethod
async def valid_grant(db: AsyncSession, user_id: int, client_pk: int) -> SysOAuthGrant | None:
"""
- 读取用户对 Client 的有效 Grant
+ 读取用户对 Client 的有效 Grant。
:param db: 异步数据库会话
:param user_id: 本地用户 ID
:param client_pk: OAuth Client 主键
:return: 有效 Grant 或 None
"""
-
return await OAuthGrantDao.get_valid_for_user_client(db, user_id, client_pk)
@staticmethod
async def has_disabled_resource(db: AsyncSession, request: AuthorizeRequest) -> bool:
"""
- 判断请求 Resource 是否为该 Client 已绑定的停用资源
+ 判断请求 Resource 是否为该 Client 已绑定的停用资源。
:param db: 异步数据库会话
:param request: 当前 HTTP 请求
:return: 是否存在禁用 Resource
"""
-
return bool(request.resource) and await OAuthClientDao.has_disabled_bound_resource(
db, request.client_id, request.resource
)
@@ -661,14 +680,13 @@ async def has_disabled_resource(db: AsyncSession, request: AuthorizeRequest) ->
@staticmethod
async def active_session(db: AsyncSession, sid: str, now: datetime | None = None) -> SysSsoSession | None:
"""
- 读取当前有效 SSO Session
+ 读取当前有效 SSO Session。
:param db: 异步数据库会话
:param sid: SSO Session 标识
:param now: 当前时间
:return: 活动 SSO Session 或 None
"""
-
return await SsoSessionDao.get_active(
db, sid, now=TimezoneUtil.to_utc(now) if now is not None else TimezoneUtil.utc_now()
)
@@ -676,14 +694,13 @@ async def active_session(db: AsyncSession, sid: str, now: datetime | None = None
@classmethod
async def validate_request(cls, db: AsyncSession, request: AuthorizeRequest) -> AuthorizationContext: # noqa: PLR0912, PLR0915
"""
- 校验授权请求并构建不可变授权上下文
+ 校验授权请求并构建不可变授权上下文。
:param db: 异步数据库会话
:param request: 已完成基础字段校验的 Authorization 请求
:return: 可交给 Interaction 和 Authorization Code 服务的上下文
:raises OAuthProtocolException: 请求不符合 OAuth/OIDC 协议时抛出
"""
-
if not OidcConfig.oidc_enabled:
raise OAuthProtocolException('temporarily_unavailable', 'OIDC provider is disabled', 503)
@@ -828,13 +845,12 @@ async def _load_scope_models(
db: AsyncSession, bindings: list[SysOAuthClientScope] | tuple[SysOAuthClientScope, ...]
) -> list[SysOAuthScope]:
"""
- 加载 Client Scope 绑定对应的有效 Scope 定义
+ 加载 Client Scope 绑定对应的有效 Scope 定义。
:param db: 异步数据库会话
:param bindings: Client-Scope 绑定集合
:return: Scope 定义列表
"""
-
scope_ids = {binding.scope_pk for binding in bindings}
if not scope_ids:
return []
@@ -847,13 +863,12 @@ async def load_scope_models(
db: AsyncSession, bindings: list[SysOAuthClientScope] | tuple[SysOAuthClientScope, ...]
) -> list[SysOAuthScope]:
"""
- 加载 Client Scope 绑定对应的 Scope 定义
+ 加载 Client Scope 绑定对应的 Scope 定义。
:param db: 异步数据库会话
:param bindings: Client-Scope 绑定集合
:return: Scope 定义列表
"""
-
return await AuthorizationService._load_scope_models(db, bindings)
@staticmethod
@@ -866,7 +881,7 @@ def _resolve_resource(
state: str | None,
) -> SysOAuthResource | None:
"""
- 解析并校验最多一个 Resource audience
+ 解析并校验最多一个 Resource audience。
:param requested_resource: 请求中的 Resource audience
:param resources: Client 已注册的 Resource 集合
@@ -875,8 +890,8 @@ def _resolve_resource(
:param redirect_uri: 已精确验证的 Redirect URI
:param state: 原样绑定的客户端 state
:return: 选中的 Resource,或无 Resource 时返回 None
+ :raises OAuthProtocolException: 目标受众缺失或客户端无权访问目标资源
"""
-
resource_scopes = [scope for scope in requested_scopes if scope.scope_type == 'resource']
if requested_resource:
resource = next((item for item in resources if item.audience == requested_resource), None)
@@ -898,7 +913,7 @@ def _resolve_resource(
@staticmethod
def _redirect_error(error: str, description: str, redirect_uri: str, state: str | None) -> OAuthProtocolException:
"""
- 创建已完成 Redirect 校验后的安全协议异常
+ 创建已完成 Redirect 校验后的安全协议异常。
:param error: OAuth 标准错误码
:param description: 不泄漏内部数据的错误描述
@@ -906,7 +921,6 @@ def _redirect_error(error: str, description: str, redirect_uri: str, state: str
:param state: 客户端原样 state
:return: 标记为可安全重定向的协议异常
"""
-
return OAuthProtocolException(
error,
description,
@@ -920,13 +934,12 @@ def _redirect_error(error: str, description: str, redirect_uri: str, state: str
@staticmethod
def consent_is_satisfied(context: AuthorizationContext, grant: SysOAuthGrant | None) -> bool:
"""
- 判断有效 Grant 是否覆盖当前授权请求
+ 判断有效 Grant 是否覆盖当前授权请求。
:param context: 已验证授权上下文
:param grant: 当前用户和 Client 的 Grant
:return: Grant 有效且覆盖全部非预授权 Scope/Resource 时为 True
"""
-
if not context.requires_consent:
return True
prompt_tokens = frozenset((context.prompt or '').split())
@@ -950,25 +963,29 @@ def consent_is_satisfied(context: AuthorizationContext, grant: SysOAuthGrant | N
class AuthorizationCodeReuseError(OAuthProtocolException):
"""
- 表示一个已成功消费的 Authorization Code 被再次提交
+ 表示一个已成功消费的 Authorization Code 被再次提交。
+
+ :ivar must_commit: 抛出异常后是否仍须提交状态更改
"""
def __init__(self) -> None:
- """
- 初始化对象状态
-
- :return: None
- """
-
+ """初始化对象状态。"""
super().__init__('invalid_grant', 'Authorization code is invalid or expired', 400)
self.must_commit = True
class AuthorizationCodeService:
"""
- 授权码模块服务层
+ 授权码模块服务层。
Redis 只保存 codeHash 和服务端白名单字段,不保存 Authorization Code 明文
+
+ :cvar _CONSUME_SCRIPT: 原子消费授权码并记录状态的 Redis 脚本
+ :cvar _REQUIRED_FIELDS: 授权码记录必须包含的字段
+ :cvar _MAX_SCOPES: 单次请求允许的最大权限范围数
+ :cvar _MAX_RESOURCES: 单次授权允许绑定的最大资源数
+ :cvar _REUSE_TOMBSTONE_TTL_SECONDS: 识别重复使用的标记保留时长(秒)
+ :cvar _CONSUMED_TOMBSTONE_RESULT: 表示授权码已经消费的标记
"""
_CONSUME_SCRIPT = """
@@ -1027,7 +1044,7 @@ async def issue(
pepper: str | None = None,
) -> str:
"""
- 签发短期 Authorization Code 并以 NX 写入 Redis
+ 签发短期 Authorization Code 并以 NX 写入 Redis。
:param redis: 异步 Redis 客户端
:param payload: 已由服务端构建的白名单标量载荷
@@ -1037,7 +1054,6 @@ async def issue(
:raises ValueError: 载荷或 Pepper 不符合安全约束
:raises OAuthProtocolException: Redis 写入失败时抛出
"""
-
record = cls._validate_payload(payload)
code = generate_authorization_code()
parsed = parse_opaque_token(code, 'ac1')
@@ -1062,15 +1078,15 @@ async def consume(
pepper: str | None = None,
) -> dict[str, Any]:
"""
- 使用 Redis Lua 原子校验并消费 Authorization Code
+ 使用 Redis Lua 原子校验并消费 Authorization Code。
:param redis: 异步 Redis 客户端
:param code: 客户端提交的 Authorization Code 明文
:param pepper: 独立 OIDC Token Hash Pepper
:return: 去除内部 codeHash/version 后的服务端载荷
:raises OAuthProtocolException: Code 格式、Secret、状态或 TTL 无效时抛出统一错误
+ :raises AuthorizationCodeReuseError: 授权码先前已被消费
"""
-
try:
parsed = parse_opaque_token(code, 'ac1')
digest = token_digest(code, pepper or OidcConfig.oidc_token_hash_pepper)
@@ -1115,14 +1131,13 @@ async def consumed_payload(
pepper: str | None = None,
) -> dict[str, Any] | None:
"""
- 读取已消费授权码的短期绑定载荷
+ 读取已消费授权码的短期绑定载荷。
:param redis: Authorization Code Redis 客户端
:param code: 客户端提交的 Authorization Code 明文
:param pepper: 独立 OIDC Token Hash Pepper
:return: 与授权码摘要匹配的绑定载荷,不存在或摘要不匹配时返回 None
"""
-
try:
parsed = parse_opaque_token(code, 'ac1')
digest = token_digest(code, pepper or OidcConfig.oidc_token_hash_pepper)
@@ -1149,13 +1164,11 @@ async def consumed_payload(
@classmethod
async def invalidate(cls, redis: Redis, code: str) -> None:
"""
- 精确删除一个已签发但未安全完成交付的授权码
+ 精确删除一个已签发但未安全完成交付的授权码。
:param redis: Authorization Code Redis 客户端
:param code: 仅用于解析 code_id,不会写入 Redis
- :return: None
"""
-
try:
parsed = parse_opaque_token(code, 'ac1')
except (OpaqueTokenError, TypeError, ValueError):
@@ -1166,13 +1179,12 @@ async def invalidate(cls, redis: Redis, code: str) -> None:
@classmethod
def _validate_payload(cls, payload: Mapping[str, Any]) -> dict[str, Any]:
"""
- 校验 Authorization Code 的服务端白名单标量载荷
+ 校验 Authorization Code 的服务端白名单标量载荷。
:param payload: 待校验映射
:return: 可稳定 JSON 序列化的复制载荷
:raises ValueError: 存在未知、缺失或类型不安全字段时抛出
"""
-
if not isinstance(payload, Mapping):
raise ValueError('授权码载荷必须为映射对象')
keys = set(payload)
@@ -1226,21 +1238,20 @@ def _validate_payload(cls, payload: Mapping[str, Any]) -> dict[str, Any]:
class InteractionCompletionService:
- """
- 交互完成模块服务层
- """
+ """交互完成模块服务层。"""
@staticmethod
async def complete(redis: Redis, interaction_id: str, db: AsyncSession) -> 'InteractionCompletionResult':
"""
- 完成服务端校验并跳转至已注册的 Client Redirect URI
+ 完成服务端校验并跳转至已注册的 Client Redirect URI。
:param redis: 交互 Redis
:param interaction_id: Interaction 标识
:param db: 异步数据库会话
:return: 外部 Client 重定向响应
+ :raises OidcInteractionException: 认证交互尚未完成;认证交互已完成,请勿重复提交
+ :raises OAuthProtocolException: 已验证的回调地址不可用或授权完成失败
"""
-
record = await InteractionService.get_record(redis, interaction_id)
if record.get('status') not in {'completed', 'denied'}:
raise OidcInteractionException(interaction_id, '认证交互尚未完成', error='interaction_required')
@@ -1272,13 +1283,12 @@ async def complete(redis: Redis, interaction_id: str, db: AsyncSession) -> 'Inte
@staticmethod
async def active_session(db: AsyncSession, record: dict[str, Any]) -> SysSsoSession | None:
"""
- 读取活动会话
+ 读取活动会话。
:param db: 异步数据库会话
:param record: 交互记录
:return: 活动 SSO Session 或 None
"""
-
sid = record.get('authenticatedSid')
if not isinstance(sid, str):
return None
@@ -1298,7 +1308,7 @@ async def _issue_code(
db: AsyncSession, redis: Any, record: dict[str, Any], redirect_uri: str, marker: str
) -> 'InteractionCompletionResult':
"""
- 签发授权码
+ 签发授权码。
:param db: 异步数据库会话
:param redis: Redis 客户端
@@ -1306,8 +1316,9 @@ async def _issue_code(
:param redirect_uri: 已验证的重定向 URI
:param marker: 完成标记 Key
:return: 授权码
+ :raises OAuthProtocolException: 缺少有效登录会话或授权码签发失败
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
-
try:
active = await InteractionCompletionService.active_session(db, record)
except Exception:
@@ -1370,7 +1381,7 @@ def _redirect(
error: str | None = None,
) -> 'InteractionCompletionResult':
"""
- 构建重定向响应
+ 构建重定向响应。
:param redirect_uri: 已验证的重定向 URI
:param record: 交互记录
@@ -1378,7 +1389,6 @@ def _redirect(
:param error: 协议错误码
:return: 重定向结果
"""
-
query = []
if code is not None:
query.append(('code', code))
@@ -1396,7 +1406,9 @@ def _redirect(
@dataclass(frozen=True)
class InteractionCompletionResult:
"""
- 完成交互后的重定向目标;Controller 负责构造 HTTP 跳转
+ 完成交互后的重定向目标;Controller 负责构造 HTTP 跳转。
+
+ :ivar location: 客户端接下来应访问的重定向地址
"""
location: str
diff --git a/ruoyi-fastapi-backend/module_identity/service/consent_service.py b/ruoyi-fastapi-backend/module_identity/service/consent_service.py
index f2cd565b7..cf593300c 100644
--- a/ruoyi-fastapi-backend/module_identity/service/consent_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/consent_service.py
@@ -27,8 +27,10 @@
@dataclass(frozen=True, slots=True)
class ConsentResult:
"""
- 授权确认结果
+ 授权确认结果。
+ :ivar previous_grant: 变更前的用户授权
+ :ivar persisted_grant: 已写入数据库的授权
:ivar approved: 是否批准授权
:ivar scopes: 服务端从原请求范围内收敛后的 Scope
:ivar grant: 本次同意关联的可撤销 Grant
@@ -43,7 +45,7 @@ class ConsentResult:
class ConsentService:
"""
- 授权同意模块服务层
+ 授权同意模块服务层。
用户提交只能取消原始请求中的可选 Scope,不能增加 Scope,也不能取消服务端必需 Scope
每次同意均保存可撤销 Grant,记住同意仅控制后续是否需要再次确认
@@ -52,7 +54,7 @@ class ConsentService:
@staticmethod
def validate_submission(context: AuthorizationContext, approved: bool, scopes: Iterable[str]) -> tuple[str, ...]:
"""
- 校验并收敛用户提交的授权 Scope
+ 校验并收敛用户提交的授权 Scope。
:param context: 已完成协议校验的授权上下文
:param approved: 用户是否批准授权
@@ -60,7 +62,6 @@ def validate_submission(context: AuthorizationContext, approved: bool, scopes: I
:return: 按原请求顺序返回的有效 Scope
:raises OAuthProtocolException: 拒绝授权、扩大 Scope 或取消必需 Scope 时抛出
"""
-
requested = tuple(context.scopes)
submitted = tuple(dict.fromkeys(scopes))
requested_set = set(requested)
@@ -83,7 +84,7 @@ async def remember_consent(
scopes: Iterable[str],
) -> SysOAuthGrant:
"""
- 持久化用户同意的 Scope
+ 持久化用户同意的 Scope。
:param db: 异步数据库会话
:param context: 已完成协议校验的授权上下文
@@ -94,7 +95,6 @@ async def remember_consent(
调用方负责提交事务;本方法不执行 commit。Grant 撤销与 Token 联动不在本接口内完成
"""
-
selected_scopes = cls.validate_submission(context, True, scopes)
return await OAuthGrantDao.merge_active_grant(
@@ -119,7 +119,7 @@ async def submit_consent(
subject_id: str | None = None,
) -> ConsentResult:
"""
- 处理授权确认并写入可撤销 Grant
+ 处理授权确认并写入可撤销 Grant。
:param db: 异步数据库会话
:param context: 已完成协议校验的授权上下文
@@ -129,10 +129,11 @@ async def submit_consent(
:param user_id: 持久化 Grant 所需的本地用户 ID
:param subject_id: 持久化 Grant 所需的稳定 Subject
:return: 授权处理结果
+ :raises ValueError: 创建授权记录必须提供用户编号和主体标识
+ :raises OAuthProtocolException: 当前策略禁止用户访问该客户端
调用方负责 commit;拒绝授权不会写入 Grant
"""
-
selected_scopes = cls.validate_submission(context, approved, scopes)
if user_id is None or subject_id is None:
raise ValueError('创建授权记录必须提供用户编号和主体标识')
@@ -162,13 +163,12 @@ async def submit_consent(
@staticmethod
async def compensate_persisted_grant(db: AsyncSession, result: ConsentResult) -> None:
"""
- 补偿已提交但 Interaction CAS 失败的持久授权
+ 补偿已提交但 Interaction CAS 失败的持久授权。
:param db: 用于独立补偿事务的数据库会话
:param result: 已提交的授权结果及更新前快照
- :return: None
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
-
if result.grant is None or result.persisted_grant is None:
return
try:
@@ -206,26 +206,24 @@ async def compensate_persisted_grant(db: AsyncSession, result: ConsentResult) ->
@staticmethod
def consent_is_satisfied(context: AuthorizationContext, grant: SysOAuthGrant | None) -> bool:
"""
- 判断已有 Grant 是否可以跳过本次同意页
+ 判断已有 Grant 是否可以跳过本次同意页。
:param context: 已完成协议校验的授权上下文
:param grant: 当前用户和 Client 的候选 Grant
:return: 仅当策略版本、范围和 Resource 均匹配时返回 True
"""
-
return AuthorizationService.consent_is_satisfied(context, grant)
@staticmethod
def _redirect_error(context: AuthorizationContext, error: str, description: str) -> OAuthProtocolException:
"""
- 创建带已验证 Redirect 的授权错误
+ 创建带已验证 Redirect 的授权错误。
:param context: 已完成 Redirect 校验的上下文
:param error: OAuth 标准错误码
:param description: 安全错误描述
:return: 可安全重定向的协议异常
"""
-
return OAuthProtocolException(
error,
description,
@@ -238,20 +236,18 @@ def _redirect_error(context: AuthorizationContext, error: str, description: str)
class InteractionConsentService:
- """
- 认证中心授权同意流程模块服务层
- """
+ """认证中心授权同意流程模块服务层。"""
@staticmethod
async def context_from_record(db: AsyncSession, record: dict[str, object]) -> AuthorizationContext:
"""
- 从 Interaction 白名单记录和当前数据库策略重建同意上下文
+ 从 Interaction 白名单记录和当前数据库策略重建同意上下文。
:param db: 异步数据库会话
:param record: Interaction 内部记录
:return: 当前策略下的授权上下文
+ :raises OidcInteractionException: 客户端已停用或不可用;权限范围策略已变更,请重新授权;资源访问策略已变更,请重新授权
"""
-
client = await OAuthClientDao.get_by_pk(db, record['clientPk'], active_only=True)
if client is None:
raise OidcInteractionException(
@@ -323,7 +319,7 @@ async def consent(
csrf_token: str | None,
) -> InteractionResultModel:
"""
- 校验并提交授权同意,只允许原始 Scope 子集
+ 校验并提交授权同意,只允许原始 Scope 子集。
:param redis: 交互 Redis
:param interaction_id: Interaction 标识
@@ -331,8 +327,8 @@ async def consent(
:param db: 异步数据库会话
:param csrf_token: Interaction CSRF 原文
:return: 同源完成跳转动作
+ :raises OAuthProtocolException: 处理同意请求时发生需要继续传播的协议错误
"""
-
record = await InteractionFlowService.csrf_record(redis, interaction_id, csrf_token)
InteractionFlowService.require_status(record, 'awaiting_consent')
context = await InteractionConsentService.context_from_record(db, record)
@@ -382,12 +378,7 @@ async def consent(
)
async def compensate() -> None:
- """
- 执行事务补偿
-
- :return: None
- """
-
+ """执行事务补偿。"""
await ConsentService.compensate_persisted_grant(db, result)
await InteractionFlowService.commit_transition(
@@ -410,15 +401,15 @@ async def cancel(
csrf_token: str | None,
) -> InteractionResultModel:
"""
- 以 CSRF 保护的原子状态迁移拒绝当前授权
+ 以 CSRF 保护的原子状态迁移拒绝当前授权。
:param redis: 交互 Redis
:param interaction_id: Interaction 标识
:param db: 异步数据库会话
:param csrf_token: Interaction CSRF 原文
:return: 同源完成跳转动作
+ :raises OidcInteractionException: 认证交互已失效,请重新发起认证
"""
-
record = await InteractionFlowService.csrf_record(redis, interaction_id, csrf_token)
if record.get('status') not in {'awaiting_login', 'awaiting_consent', 'password_change_required'}:
raise OidcInteractionException(
diff --git a/ruoyi-fastapi-backend/module_identity/service/discovery_service.py b/ruoyi-fastapi-backend/module_identity/service/discovery_service.py
index 42df9d998..215940d48 100644
--- a/ruoyi-fastapi-backend/module_identity/service/discovery_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/discovery_service.py
@@ -5,19 +5,16 @@
class DiscoveryService:
- """
- OIDC Discovery 模块服务层
- """
+ """OIDC Discovery 模块服务层。"""
@staticmethod
async def supported_scopes(db: AsyncSession) -> list[str]:
"""
- 读取启用 Scope 并稳定合并到协议元数据
+ 读取启用 Scope 并稳定合并到协议元数据。
:param db: 异步数据库会话
:return: 启用 Scope 名称列表
"""
-
scopes = await OAuthClientDao.list_scope_definitions(db, active_only=True)
dynamic = tuple(
value if isinstance(value, str) else value.scope_code
@@ -32,21 +29,19 @@ async def supported_scopes(db: AsyncSession) -> list[str]:
@staticmethod
def _issuer() -> str:
"""
- 读取签发者地址
+ 读取签发者地址。
:return: OIDC 签发者地址
"""
-
return OidcConfig.oidc_issuer.rstrip('/')
@classmethod
def openid_metadata(cls) -> dict[str, object]:
"""
- 构建 OpenID 元数据
+ 构建 OpenID 元数据。
:return: 协议元数据映射
"""
-
issuer = cls._issuer()
return {
@@ -91,11 +86,10 @@ def openid_metadata(cls) -> dict[str, object]:
@classmethod
def oauth_metadata(cls) -> dict[str, object]:
"""
- 构建 OAuth 元数据
+ 构建 OAuth 元数据。
:return: 协议元数据映射
"""
-
issuer = cls._issuer()
return {
@@ -117,12 +111,11 @@ def oauth_metadata(cls) -> dict[str, object]:
@classmethod
async def openid_metadata_with_scopes(cls, db: AsyncSession) -> dict[str, object]:
"""
- 构建带动态 Scope 的 OpenID 元数据
+ 构建带动态 Scope 的 OpenID 元数据。
:param db: 异步数据库会话
:return: 协议元数据映射
"""
-
payload = cls.openid_metadata()
payload['scopes_supported'] = await cls.supported_scopes(db)
@@ -131,12 +124,11 @@ async def openid_metadata_with_scopes(cls, db: AsyncSession) -> dict[str, object
@classmethod
async def oauth_metadata_with_scopes(cls, db: AsyncSession) -> dict[str, object]:
"""
- 构建带动态 Scope 的 OAuth 元数据
+ 构建带动态 Scope 的 OAuth 元数据。
:param db: 异步数据库会话
:return: 协议元数据映射
"""
-
payload = cls.oauth_metadata()
payload['scopes_supported'] = await cls.supported_scopes(db)
diff --git a/ruoyi-fastapi-backend/module_identity/service/identity_service.py b/ruoyi-fastapi-backend/module_identity/service/identity_service.py
index ff2b97aae..643943ca4 100644
--- a/ruoyi-fastapi-backend/module_identity/service/identity_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/identity_service.py
@@ -68,15 +68,15 @@
@dataclass(frozen=True)
class CredentialAuthenticationResult:
"""
- 凭据校验成功后的稳定结果,不包含任何 Token
-
- :param user: 已通过密码检查的本地用户对象
- :param dept: 用户所属的部门对象或 None
- :param acr: 密码认证上下文引用
- :param amr: 实际使用的认证方法集合
- :param remember_me: 后续 SSO 服务处理的记住登录选择
- :param password_change_required: 是否必须修改初始或过期密码
- :param password_change_reason: 修改密码原因
+ 凭据校验成功后的稳定结果,不包含任何 Token。
+
+ :ivar user: 已通过密码检查的本地用户对象
+ :ivar dept: 用户所属的部门对象或 None
+ :ivar acr: 密码认证上下文引用
+ :ivar amr: 实际使用的认证方法集合
+ :ivar remember_me: 后续 SSO 服务处理的记住登录选择
+ :ivar password_change_required: 是否必须修改初始或过期密码
+ :ivar password_change_reason: 修改密码原因
"""
user: SysUser
@@ -90,21 +90,19 @@ class CredentialAuthenticationResult:
class CredentialAuthenticationError(Exception):
"""
- 凭据校验失败的内部分类异常
+ 凭据校验失败的内部分类异常。
- :param reason: 脱敏后的失败原因分类
- :param legacy_message: Legacy 登录必须保持的中文错误消息
+ :ivar reason: 脱敏后的失败原因分类
+ :ivar legacy_message: Legacy 登录必须保持的中文错误消息
"""
def __init__(self, reason: CredentialReason, legacy_message: str) -> None:
"""
- 初始化对象状态
+ 初始化对象状态。
:param reason: 凭据校验失败原因
:param legacy_message: Legacy 登录错误消息
- :return: None
"""
-
self.reason = reason
self.legacy_message = legacy_message
super().__init__(legacy_message)
@@ -112,7 +110,9 @@ def __init__(self, reason: CredentialReason, legacy_message: str) -> None:
class CredentialAuthenticationService:
"""
- 凭据认证模块服务层
+ 凭据认证模块服务层。
+
+ :cvar ACR_PASSWORD: 表示密码认证的认证上下文类别
"""
ACR_PASSWORD = 'urn:ruoyi:acr:pwd'
@@ -128,7 +128,7 @@ async def authenticate_legacy(
skip_captcha: bool = False,
) -> Row[tuple[SysUser, SysDept]]:
"""
- 执行 Legacy 登录的原有凭据检查,不签发 JWT
+ 执行 Legacy 登录的原有凭据检查,不签发 JWT。
:param redis: Legacy 登录使用的 Redis 客户端
:param query_db: 异步数据库会话
@@ -138,7 +138,6 @@ async def authenticate_legacy(
:return: 通过检查的用户和部门行
:raises CredentialAuthenticationError: 使用 Legacy 中文语义分类失败
"""
-
await cls._check_ip(client_ip, redis)
user_name = login_user.user_name
lock_key = f'{RedisInitKeyConfig.ACCOUNT_LOCK.key}:{user_name}'
@@ -179,7 +178,7 @@ async def authenticate_oidc(
remember_me: bool = False,
) -> CredentialAuthenticationResult:
"""
- 执行 OIDC 交互的本地凭据校验,不触发 Legacy Token 流程
+ 执行 OIDC 交互的本地凭据校验,不触发 Legacy Token 流程。
用户不存在和密码错误共享 ``invalid_credentials`` 分类;用户名只用于
HMAC 计算,OIDC 错误计数与锁定键不会包含用户名原文
@@ -196,7 +195,6 @@ async def authenticate_oidc(
:return: 凭据成功结果,不含 Token
:raises CredentialAuthenticationError: 脱敏分类的凭据失败
"""
-
await cls._check_ip(client_ip, redis)
username_digest = OidcUtil.hash_sensitive_identifier(user_name, OidcConfig.oidc_token_hash_pepper)
failure_key = OidcRedisKey.login_user_rate_limit(username_digest)
@@ -237,13 +235,12 @@ async def authenticate_oidc(
@staticmethod
def _verify(password: str, stored_hash: str | None) -> bool:
"""
- 使用项目 PwdUtil 验证密码,异常哈希按失败处理
+ 使用项目 PwdUtil 验证密码,异常哈希按失败处理。
:param password: 用户密码
:param stored_hash: 已存储的密码摘要
:return: 密码是否匹配
"""
-
try:
return bool(PwdUtil.verify_password(password, stored_hash or _DUMMY_PASSWORD_HASH))
except (TypeError, ValueError):
@@ -252,13 +249,12 @@ def _verify(password: str, stored_hash: str | None) -> bool:
@classmethod
async def _check_ip(cls, client_ip: str | None, redis: Redis) -> None:
"""
- 拒绝系统配置黑名单中的客户端 IP
+ 拒绝系统配置黑名单中的客户端 IP。
:param client_ip: 客户端 IP 地址
:param redis: Redis 客户端
- :return: None
+ :raises CredentialAuthenticationError: 客户端 IP 命中禁止登录名单
"""
-
value = await redis.get(f'{RedisInitKeyConfig.SYS_CONFIG.key}:sys.login.blackIPList')
if client_ip in (value.split(',') if value else []):
raise CredentialAuthenticationError('ip_blocked', I18nMessage('当前IP禁止登录', msg_key='auth.ipBlocked'))
@@ -266,13 +262,12 @@ async def _check_ip(cls, client_ip: str | None, redis: Redis) -> None:
@classmethod
async def _check_legacy_captcha(cls, redis: Redis, login_user: UserLogin) -> None:
"""
- 按原有非消费语义校验 Legacy 验证码
+ 按原有非消费语义校验 Legacy 验证码。
:param redis: Redis 客户端
:param login_user: Legacy 登录请求
- :return: None
+ :raises CredentialAuthenticationError: 验证码缺失、已失效或不匹配
"""
-
value = await redis.get(f'{RedisInitKeyConfig.CAPTCHA_CODES.key}:{login_user.uuid}')
if not value:
raise CredentialAuthenticationError(
@@ -286,14 +281,13 @@ async def _check_legacy_captcha(cls, redis: Redis, login_user: UserLogin) -> Non
@classmethod
async def _check_oidc_captcha(cls, redis: Redis, code: str | None, uuid: str | None) -> None:
"""
- 原子消费 OIDC 验证码,阻止验证码重放
+ 原子消费 OIDC 验证码,阻止验证码重放。
:param redis: Redis 客户端
:param code: OIDC 验证码
:param uuid: 验证码标识
- :return: None
+ :raises CredentialAuthenticationError: 验证码标识缺失、验证码已失效或不匹配
"""
-
if not uuid:
raise CredentialAuthenticationError(
'captcha_missing', I18nMessage('验证码已失效或不存在', msg_key='auth.captchaMissing')
@@ -313,13 +307,12 @@ async def _check_oidc_captcha(cls, redis: Redis, code: str | None, uuid: str | N
@classmethod
async def _record_legacy_password_error(cls, redis: Redis, user_name: str) -> None:
"""
- 保持 Legacy 错误计数、阈值和十分钟 TTL 完全不变
+ 保持 Legacy 错误计数、阈值和十分钟 TTL 完全不变。
:param redis: Redis 客户端
:param user_name: 用户名
- :return: None
+ :raises CredentialAuthenticationError: 密码错误或连续失败次数已触发账号锁定
"""
-
key = f'{RedisInitKeyConfig.PASSWORD_ERROR_COUNT.key}:{user_name}'
cached = await redis.get(key)
count = int(cached or 0) + 1
@@ -338,14 +331,13 @@ async def _record_legacy_password_error(cls, redis: Redis, user_name: str) -> No
@classmethod
async def _record_oidc_password_error(cls, redis: Redis, failure_key: str, lock_key: str) -> None:
"""
- 记录 OIDC 摘要命名空间错误状态,不写入用户名
+ 记录 OIDC 摘要命名空间错误状态,不写入用户名。
:param redis: Redis 客户端
:param failure_key: OIDC 失败计数 Key
:param lock_key: OIDC 锁定 Key
- :return: None
+ :raises CredentialAuthenticationError: 失败次数达到限制,账号已锁定
"""
-
result = await redis.eval(
_OIDC_FAILURE_SCRIPT,
2,
@@ -362,13 +354,12 @@ async def _record_oidc_password_error(cls, redis: Redis, failure_key: str, lock_
@classmethod
async def _password_policy(cls, redis: Redis, user: SysUser) -> tuple[bool, str | None]:
"""
- 复用系统初始密码和密码有效期配置,处理 naive/aware 时间
+ 复用系统初始密码和密码有效期配置,处理 naive/aware 时间。
:param redis: Redis 客户端
:param user: 系统用户对象
:return: 密码修改要求及原因
"""
-
init_modify = await redis.get(f'{RedisInitKeyConfig.SYS_CONFIG.key}:sys.account.initPasswordModify')
update_time = getattr(user, 'pwd_update_date', None)
if init_modify == '1' and update_time is None:
@@ -390,7 +381,10 @@ async def _password_policy(cls, redis: Redis, user: SysUser) -> tuple[bool, str
class ClaimService:
"""
- OIDC Claim 模块服务层
+ OIDC Claim 模块服务层。
+
+ :cvar SCOPE_CLAIMS: 按权限范围允许返回的身份声明
+ :cvar FORBIDDEN_CLAIMS: 禁止由客户端指定的身份声明
"""
SCOPE_CLAIMS = {
@@ -420,12 +414,11 @@ class ClaimService:
@classmethod
def _claim_set(cls, value: Any) -> set[str]:
"""
- 规范化策略或白名单中的 Claim 名称
+ 规范化策略或白名单中的 Claim 名称。
:param value: 待规范化的 Claim 名称集合
:return: 规范化 Claim 集合
"""
-
if value is True:
return set(cls.SCOPE_CLAIMS['openid'] | cls.SCOPE_CLAIMS['profile'])
if isinstance(value, str):
@@ -439,13 +432,12 @@ def _claim_set(cls, value: Any) -> set[str]:
@classmethod
def _client_claims_for_scope(cls, scope: str, policy: Any) -> set[str]:
"""
- 取得 Client 对某一 Scope 的 Claim 策略
+ 取得 Client 对某一 Scope 的 Claim 策略。
:param scope: 待读取策略的 Scope 名称
:param policy: Scope Claim 策略
:return: Scope 对应 Claim 集合
"""
-
if isinstance(policy, Mapping):
if scope in policy:
value = policy[scope]
@@ -468,14 +460,13 @@ def effective_claims(
resource_allowed_claims: Any,
) -> set[str]:
"""
- 计算请求 Scope、Client 策略和 Resource 白名单的三重交集
+ 计算请求 Scope、Client 策略和 Resource 白名单的三重交集。
:param requested_scopes: 请求的空格分隔 Scope 或 Scope 集合
:param client_scope_policy: Client 的 Scope 到 Claim 策略映射
:param resource_allowed_claims: Resource 允许的 Claim 列表
:return: 可安全生成的 Claim 名称集合
"""
-
requested = OidcUtil.scope_set(requested_scopes)
client_claims = set().union(*(cls._client_claims_for_scope(scope, client_scope_policy) for scope in requested))
resource_claims = cls._claim_set(resource_allowed_claims)
@@ -485,7 +476,7 @@ def effective_claims(
@classmethod
def _safe_values(cls, user: Any, subject_id: str | None, roles: Any, department: Any) -> dict[str, Any]:
"""
- 抽取允许的用户属性,明确排除本地 ID 和密码
+ 抽取允许的用户属性,明确排除本地 ID 和密码。
:param user: SysUser ORM 记录或用户 Claim 字段映射
:param subject_id: 稳定身份主体 ID
@@ -493,7 +484,6 @@ def _safe_values(cls, user: Any, subject_id: str | None, roles: Any, department:
:param department: 部门对象或部门映射
:return: 安全 Claim 字段映射
"""
-
values = {
'sub': subject_id or OidcUtil.read_field(user, 'subject_id'),
'name': OidcUtil.read_field(user, 'name', OidcUtil.read_field(user, 'nick_name')),
@@ -537,7 +527,7 @@ def build_claims(
department: Any = None,
) -> dict[str, Any]:
"""
- 为用户构建经过三重授权和敏感字段过滤的 OIDC Claims
+ 为用户构建经过三重授权和敏感字段过滤的 OIDC Claims。
:param user: 已加载的用户 ORM 对象或安全字段映射
:param requested_scopes: 请求 Scope
@@ -547,8 +537,8 @@ def build_claims(
:param roles: 已按项目角色 DAO 查询的角色 key 集合
:param department: 已按项目部门 DAO 查询的部门对象或映射
:return: 最小 OIDC Claim 映射
+ :raises OAuthProtocolException: 用户身份映射不可用或缺少 OpenID 所需的主体声明
"""
-
requested = OidcUtil.scope_set(requested_scopes)
allowed = cls.effective_claims(requested, client_scope_policy, resource_allowed_claims)
stable_subject = subject_id or OidcUtil.read_field(user, 'subject_id')
@@ -577,13 +567,12 @@ def build_claims(
@classmethod
async def load_roles_and_department(cls, db: AsyncSession, user_id: int) -> tuple[list[str], SysDept | None]:
"""
- 按现有 ORM DAO 使用的启用状态规则加载角色和部门
+ 按现有 ORM DAO 使用的启用状态规则加载角色和部门。
:param db: 异步数据库会话
:param user_id: 本地用户 ID,仅用于内部查询,不会进入 Claim
:return: 角色名称列表和部门对象
"""
-
return await IdentityUserDao.get_claim_attributes(db, user_id)
@classmethod
@@ -596,7 +585,7 @@ async def resolve_scope_policy(
resource_allowed_claims: Iterable[str] | None = None,
) -> tuple[dict[str, Any], set[str]]:
"""
- 解析 Client Scope 策略及最终 Claim 白名单
+ 解析 Client Scope 策略及最终 Claim 白名单。
:param db: 异步数据库会话
:param client_pk: Client 内部主键
@@ -604,7 +593,6 @@ async def resolve_scope_policy(
:param resource_allowed_claims: 可选 Resource Claim 白名单
:return: Scope 策略映射和可用 Claim 集合
"""
-
requested = set(scopes)
bindings = await OAuthClientDao.list_scope_bindings(db, client_pk)
definitions = await OAuthClientDao.list_scope_definitions(db)
@@ -623,9 +611,7 @@ async def resolve_scope_policy(
class IdentitySubjectService:
- """
- 身份主体模块服务层
- """
+ """身份主体模块服务层。"""
@classmethod
async def require_by_user_id(
@@ -637,18 +623,17 @@ async def require_by_user_id(
audit_writer: Callable[[int], Awaitable[object]] | None = None,
) -> SysIdentitySubject:
"""
- 获取用户的稳定 Subject,缺失时拒绝继续签发
+ 获取用户的稳定 Subject,缺失时拒绝继续签发。
:param db: 与当前业务事务相同的异步数据库会话
:param user_id: 本地用户 ID
:param audit_db: 可选独立审计会话,避免主事务回滚时丢失完整性告警
:param audit_writer: 可选外部审计写入器,提交边界由写入器负责
- 生产签发链路必须提供其中之一;两者均省略时审计仅随当前事务 flush,
- 主事务回滚会一并回滚,不能作为持久化告警
+ 生产签发链路必须提供其中之一;两者均省略时审计仅随当前事务 flush,
+ 主事务回滚会一并回滚,不能作为持久化告警
:return: 已存在的主体关联
:raises OAuthProtocolException: 主体关联缺失或用户标识无效时抛出
"""
-
if not isinstance(user_id, int) or isinstance(user_id, bool) or user_id <= 0:
await cls._write_missing_audit(db, user_id, audit_db=audit_db, audit_writer=audit_writer)
raise OAuthProtocolException('server_error', 'User identity mapping is unavailable', 500)
@@ -668,7 +653,7 @@ async def _write_missing_audit(
audit_writer: Callable[[int], Awaitable[object]] | None = None,
) -> None:
"""
- 写入主体完整性审计;审计失败不能把缺失主体变成可签发状态
+ 写入主体完整性审计;审计失败不能把缺失主体变成可签发状态。
未传入独立会话或写入器时只在调用方事务中 flush,调用方必须自行承担
回滚丢失告警的后果;持久化安全告警应使用 ``audit_writer``
@@ -677,9 +662,7 @@ async def _write_missing_audit(
:param user_id: 本地用户 ID
:param audit_db: 独立审计数据库会话
:param audit_writer: 外部审计写入器
- :return: None
"""
-
try:
if audit_writer is not None:
await audit_writer(user_id)
@@ -707,7 +690,7 @@ async def create_for_new_user(
subject_id: str | None = None,
) -> SysIdentitySubject:
"""
- 在用户创建事务中建立稳定 Subject,不提交调用方事务
+ 在用户创建事务中建立稳定 Subject,不提交调用方事务。
:param db: 用户创建事务使用的异步数据库会话
:param user_id: 已创建的本地用户 ID
@@ -716,7 +699,6 @@ async def create_for_new_user(
:return: 已存在或新建的主体关联
:raises ValueError: 用户 ID 无效时抛出
"""
-
if not isinstance(user_id, int) or isinstance(user_id, bool) or user_id <= 0:
raise ValueError('身份用户编号 identity_user_id 必须为正整数')
return await IdentitySubjectDao.create_for_user(db, user_id, create_by, subject_id)
@@ -726,15 +708,15 @@ async def repair_missing_subject(
cls, db: AsyncSession, user_id: int, create_by: str = 'identity-repair'
) -> SysIdentitySubject:
"""
- 幂等修复单个用户的缺失 Subject
+ 幂等修复单个用户的缺失 Subject。
:param db: 异步数据库会话
:param user_id: 待修复的本地用户 ID
:param create_by: 回填记录的创建者标识
:return: 已存在或本次创建的主体关联
:raises ValueError: 用户 ID 无效时抛出
+ :raises IntegrityError: 无法通过重读已有映射解决身份主体的完整性冲突
"""
-
if not isinstance(user_id, int) or isinstance(user_id, bool) or user_id <= 0:
raise ValueError('身份用户编号 identity_user_id 必须为正整数')
try:
@@ -753,14 +735,14 @@ async def repair_missing_subjects(
create_by: str = 'identity-repair',
) -> Sequence[SysIdentitySubject]:
"""
- 幂等批量修复缺失 Subject,不提交调用方事务
+ 幂等批量修复缺失 Subject,不提交调用方事务。
:param db: 异步数据库会话
:param user_ids: 可选用户 ID 集合;省略时检查所有未删除用户
:param create_by: 回填记录的创建者标识
:return: 本次调用新建的主体记录集合
+ :raises ValueError: 身份用户编号 identity_user_id 必须为正整数
"""
-
if user_ids is not None:
values = list(user_ids)
if any(not isinstance(item, int) or isinstance(item, bool) or item <= 0 for item in values):
@@ -774,7 +756,7 @@ async def increment_auth_version(
cls, db: AsyncSession, user_id: int, expected_version: int | None = None
) -> SysIdentitySubject:
"""
- 原子递增用户认证版本并返回最新主体
+ 原子递增用户认证版本并返回最新主体。
:param db: 异步数据库会话
:param user_id: 本地用户 ID
@@ -782,7 +764,6 @@ async def increment_auth_version(
:return: 更新后的主体关联
:raises OAuthProtocolException: 主体不存在或版本竞争失败时抛出
"""
-
if not await IdentitySubjectDao.increment_auth_version(db, user_id, expected_version):
raise OAuthProtocolException('server_error', 'User identity version could not be updated', 500)
subject = await IdentitySubjectDao.get_by_user_id(db, user_id)
@@ -793,13 +774,12 @@ async def increment_auth_version(
@classmethod
async def get_by_subject_id(cls, db: AsyncSession, subject_id: str) -> SysIdentitySubject | None:
"""
- 按稳定 Subject 查询主体关联
+ 按稳定 Subject 查询主体关联。
:param db: 异步数据库会话
:param subject_id: 稳定 OIDC Subject
:return: 主体关联,不存在时返回 None
"""
-
return await IdentitySubjectDao.get_by_subject_id(db, subject_id)
@@ -816,15 +796,17 @@ async def get_by_subject_id(cls, db: AsyncSession, subject_id: str) -> SysIdenti
class IdentitySecurityEventError(ValueError):
- """
- 身份安全事件缺少主体映射或输入不满足事务约束
- """
+ """身份安全事件缺少主体映射或输入不满足事务约束。"""
@dataclass(frozen=True, slots=True)
class IdentitySecurityEventResult:
"""
- 一次身份安全失效操作的不可变结果
+ 一次身份安全失效操作的不可变结果。
+
+ :ivar affected_users: 受本次安全事件影响的用户
+ :ivar revoked_sessions: 本次撤销的登录会话
+ :ivar revoked_refresh_tokens: 本次撤销的刷新令牌
"""
affected_users: tuple[int, ...]
@@ -834,7 +816,14 @@ class IdentitySecurityEventResult:
class IdentitySecurityEventService:
"""
- 身份安全事件模块服务层
+ 身份安全事件模块服务层。
+
+ :cvar _EVENTS: 可识别的身份安全事件类型
+ :cvar _ALWAYS_REVOKE_SSO: 必须撤销单点登录会话的安全事件
+ :cvar _CLAIM_EVENTS: 会影响令牌身份声明的事件
+ :cvar _TERMINAL_REFRESH_STATUSES: 刷新令牌不再可用的终止状态集合
+ :cvar _MAX_BATCH_USERS: 一批安全事件允许处理的最大用户数
+ :cvar _MAX_SID_LENGTH: 会话标识允许的最大长度
"""
_EVENTS = frozenset(
@@ -870,7 +859,7 @@ async def handle_user_event(
now: datetime | None = None,
) -> IdentitySecurityEventResult:
"""
- 处理单个用户事件,但不提交调用方事务
+ 处理单个用户事件,但不提交调用方事务。
:param db: 与用户或角色变更共用的数据库会话
:param user_id: 本地用户 ID
@@ -881,7 +870,6 @@ async def handle_user_event(
:param now: 可注入的 项目当前时间
:return: 版本递增及凭据撤销数量
"""
-
return await cls.handle_users_event(
db,
(user_id,),
@@ -905,7 +893,7 @@ async def handle_users_event(
now: datetime | None = None,
) -> IdentitySecurityEventResult:
"""
- 按固定锁顺序批量处理身份安全事件,不提交事务
+ 按固定锁顺序批量处理身份安全事件,不提交事务。
:param db: 异步数据库会话
:param user_ids: 本地用户 ID 集合
@@ -917,7 +905,6 @@ async def handle_users_event(
:return: 安全事件处理结果
:raises IdentitySecurityEventError: 事件、用户或主体映射不完整
"""
-
try:
ids = OidcUtil.normalize_user_ids(user_ids, max_size=cls._MAX_BATCH_USERS)
except ValueError as exc:
@@ -978,7 +965,7 @@ async def handle_role_event(
now: datetime | None = None,
) -> IdentitySecurityEventResult:
"""
- 查询角色当前成员并批量触发身份安全失效
+ 查询角色当前成员并批量触发身份安全失效。
:param db: 异步数据库会话
:param role_id: 角色 ID
@@ -987,8 +974,8 @@ async def handle_role_event(
:param revoke_sso_on_claim_change: Claim 变化时是否撤销 SSO
:param now: 当前时间
:return: 安全事件处理结果
+ :raises IdentitySecurityEventError: 角色编号 role_id 必须为正整数;角色安全事件无效
"""
-
if not isinstance(role_id, int) or isinstance(role_id, bool) or role_id <= 0:
raise IdentitySecurityEventError('角色编号 role_id 必须为正整数')
if event not in {'role_claim_changed', 'role_disabled', 'role_deleted'}:
diff --git a/ruoyi-fastapi-backend/module_identity/service/infrastructure_service.py b/ruoyi-fastapi-backend/module_identity/service/infrastructure_service.py
index f88f16c97..492cfdc6a 100644
--- a/ruoyi-fastapi-backend/module_identity/service/infrastructure_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/infrastructure_service.py
@@ -6,30 +6,30 @@
class RateLimitExceeded(ValueError):
"""
- 请求超过 Redis 原子窗口限额
+ 请求超过 Redis 原子窗口限额。
+
+ :ivar retry_after: 建议重试等待秒数
"""
def __init__(self, retry_after: int) -> None:
"""
- 创建限流异常
+ 创建限流异常。
:param retry_after: 建议重试等待秒数
- :return: None
"""
-
super().__init__('请求过于频繁,请稍后重试')
self.retry_after = max(1, retry_after)
class RateLimitUnavailable(RuntimeError):
- """
- Redis 限流依赖不可用,调用方必须 fail closed
- """
+ """Redis 限流依赖不可用,调用方必须 fail closed。"""
class OidcRateLimiter:
"""
- 认证限流模块服务层
+ 认证限流模块服务层。
+
+ :cvar _SCRIPT: Redis 执行限流检查和计数的脚本
"""
_SCRIPT = """
@@ -42,17 +42,15 @@ class OidcRateLimiter:
@classmethod
async def enforce(cls, redis: Redis, key: str, *, limit: int, window_seconds: int) -> None:
"""
- 原子增加计数,超限或 Redis 故障均不静默放行
+ 原子增加计数,超限或 Redis 故障均不静默放行。
:param redis: Redis 客户端
:param key: 不含 Token、Secret 或用户名原文的限流 Key
:param limit: 窗口最大请求数
:param window_seconds: 窗口秒数
- :return: None
:raises RateLimitExceeded: 请求超过限额
:raises RateLimitUnavailable: Redis 执行失败
"""
-
try:
result = await redis.eval(cls._SCRIPT, 1, key, window_seconds)
count, ttl = int(result[0]), max(1, int(result[1]))
@@ -67,64 +65,56 @@ async def enforce(cls, redis: Redis, key: str, *, limit: int, window_seconds: in
class AfterCommitCoordinator:
"""
- 提交后副作用协调模块服务层
+ 提交后副作用协调模块服务层。
``register`` 只登记闭包,不会执行;生产调用方必须使用 ``commit`` 或
``rollback`` 完成事务,避免在数据库事实落盘前修改缓存
+
+ :ivar _callbacks: 事务提交后执行的回调
+ :ivar _callback_errors: 提交后执行回调时捕获的错误
"""
def __init__(self) -> None:
- """
- 创建空的提交后回调队列
-
- :return: None
- """
-
+ """创建空的提交后回调队列。"""
self._callbacks: list[AfterCommitCallback] = []
self._callback_errors: list[Exception] = []
@property
def pending_count(self) -> int:
"""
- 返回尚未处理的回调数量
+ 返回尚未处理的回调数量。
:return: 尚未执行的回调数量
"""
-
return len(self._callbacks)
@property
def callback_errors(self) -> tuple[Exception, ...]:
"""
- 返回已记录的提交后回调异常
+ 返回已记录的提交后回调异常。
:return: 提交后回调异常元组
"""
-
return tuple(self._callback_errors)
async def register(self, callback: AfterCommitCallback) -> None:
"""
- 登记一个只应在数据库提交成功后运行的异步闭包
+ 登记一个只应在数据库提交成功后运行的异步闭包。
:param callback: 不读取可变 ORM 状态的异步副作用闭包
- :return: None
:raises TypeError: callback 不是可调用对象
"""
-
if not callable(callback):
raise TypeError('事务提交后回调必须为可调用对象')
self._callbacks.append(callback)
async def commit(self, db: AsyncSession) -> None:
"""
- 先提交数据库,再按登记顺序执行副作用
+ 先提交数据库,再按登记顺序执行副作用。
:param db: 要提交的异步数据库会话
- :return: None
:raises Exception: 数据库提交失败
"""
-
callbacks, self._callbacks = self._callbacks, []
try:
await db.commit()
@@ -140,11 +130,9 @@ async def commit(self, db: AsyncSession) -> None:
async def rollback(self, db: AsyncSession) -> None:
"""
- 回滚数据库并丢弃全部提交后副作用
+ 回滚数据库并丢弃全部提交后副作用。
:param db: 要回滚的异步数据库会话
- :return: None
"""
-
self._callbacks.clear()
await db.rollback()
diff --git a/ruoyi-fastapi-backend/module_identity/service/interaction_service.py b/ruoyi-fastapi-backend/module_identity/service/interaction_service.py
index b97e6d8a7..48c5266d6 100644
--- a/ruoyi-fastapi-backend/module_identity/service/interaction_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/interaction_service.py
@@ -66,7 +66,7 @@
@dataclass(frozen=True, slots=True)
class InteractionCreated:
"""
- Interaction 创建结果的最小一次性返回值
+ Interaction 创建结果的最小一次性返回值。
:ivar interaction_id: 新建 Interaction 标识
:ivar csrf_token: 仅首次返回的原始 CSRF Token
@@ -80,10 +80,24 @@ class InteractionCreated:
class InteractionService:
"""
- 交互流程模块服务层
+ 交互流程模块服务层。
Redis 只保存 CSRF 摘要;原始 CSRF 仅由创建接口返回一次。页面读取接口只返回
白名单投影,不建立新 CSRF,也不返回授权协议内部绑定字段
+
+ :cvar _ALLOWED_STATUSES: 交互记录可以使用的状态
+ :cvar _TERMINAL_STATUSES: 交互结束后不再接受变更的状态
+ :cvar _TRANSITIONS: 允许的源状态和目标状态组合
+ :cvar _PROTECTED_FIELDS: 更新交互记录时受保护的字段
+ :cvar _UPDATABLE_FIELDS: 允许通过交互更新操作修改的字段
+ :cvar _PROMPT_VALUES: 认证交互接受的 prompt 选项
+ :cvar _MAX_STATE_LENGTH: OAuth state 值允许的最大长度
+ :cvar _MAX_SCOPE_LENGTH: 单个权限范围名称允许的最大长度
+ :cvar _MAX_SCOPES: 单次请求允许的最大权限范围数
+ :cvar _MAX_INTERACTION_ID_LENGTH: 交互标识允许的最大长度
+ :cvar _MAX_GRANT_ID_LENGTH: 授权标识允许的最大长度
+ :cvar _NO_TTL_RESULT: Redis 返回记录无有效期时使用的标记
+ :cvar _TRANSITION_SCRIPT: 原子更新交互状态的 Redis 脚本
"""
_ALLOWED_STATUSES = frozenset(
@@ -146,7 +160,7 @@ async def create(
pepper: str | None = None,
) -> InteractionCreated:
"""
- 创建短期 Interaction,并原子占用随机 ID
+ 创建短期 Interaction,并原子占用随机 ID。
:param redis: 异步 Redis 客户端
:param payload: AuthorizationContext 生成的服务端白名单载荷
@@ -156,7 +170,6 @@ async def create(
:raises OidcInteractionException: prompt=none 无法静默完成时抛出
:raises ValueError: payload、Prompt 或 TTL 不合法时抛出
"""
-
record = cls._validate_payload(payload)
prompt = record['prompt']
authenticated_sid = record.get('authenticatedSid')
@@ -201,7 +214,7 @@ async def create(
@classmethod
async def get(cls, redis: Redis, interaction_id: str, db: AsyncSession) -> dict[str, Any]:
"""
- 从当前启用的应用及权限定义构建页面,不公开管理备注或协议内部字段
+ 从当前启用的应用及权限定义构建页面,不公开管理备注或协议内部字段。
:param redis: 异步 Redis 客户端
:param interaction_id: Interaction 标识
@@ -209,7 +222,6 @@ async def get(cls, redis: Redis, interaction_id: str, db: AsyncSession) -> dict[
:return: 页面安全载荷
:raises OidcInteractionException: Interaction 缺失、过期或状态损坏时抛出
"""
-
record = await cls._get_record(redis, interaction_id)
client = await OAuthClientDao.get_by_pk(db, record['clientPk'])
if client is None or client.client_id != record['clientId']:
@@ -224,14 +236,13 @@ async def get(cls, redis: Redis, interaction_id: str, db: AsyncSession) -> dict[
@classmethod
async def get_record(cls, redis: Redis, interaction_id: str) -> dict[str, Any]:
"""
- 获取仅供后端状态处理使用的完整 Interaction 记录
+ 获取仅供后端状态处理使用的完整 Interaction 记录。
:param redis: 异步 Redis 客户端
:param interaction_id: Interaction 标识
:return: 完整内部记录;调用方不得直接返回给页面
:raises OidcInteractionException: Interaction 缺失或记录损坏时抛出
"""
-
return await cls._get_record(redis, interaction_id)
@classmethod
@@ -245,7 +256,7 @@ async def transition(
expected_version: int | None = None,
) -> dict[str, Any]:
"""
- 使用 Redis Lua CAS 原子推进 Interaction 状态并保留 TTL
+ 使用 Redis Lua CAS 原子推进 Interaction 状态并保留 TTL。
:param redis: 异步 Redis 客户端
:param interaction_id: Interaction 标识
@@ -257,7 +268,6 @@ async def transition(
:raises OidcInteractionException: Interaction 缺失或并发状态已变化时抛出
:raises ValueError: 状态、字段或流转方向不合法时抛出
"""
-
if target_status not in cls._ALLOWED_STATUSES:
raise ValueError('认证交互的目标状态不受支持')
expected = set(expected_statuses)
@@ -309,14 +319,13 @@ async def transition(
@classmethod
def verify_csrf(cls, record: Mapping[str, Any], csrf_token: str, *, pepper: str | None = None) -> bool:
"""
- 使用恒定时间比较验证 Interaction CSRF
+ 使用恒定时间比较验证 Interaction CSRF。
:param record: 后端读取的完整 Interaction 记录
:param csrf_token: 请求携带的原始 CSRF Token
:param pepper: CSRF 摘要 Pepper
:return: 摘要匹配时为 True
"""
-
stored = record.get('csrfHash') if isinstance(record, Mapping) else None
if not isinstance(stored, str) or not isinstance(csrf_token, str) or not csrf_token:
return False
@@ -329,13 +338,13 @@ def verify_csrf(cls, record: Mapping[str, Any], csrf_token: str, *, pepper: str
@classmethod
async def _get_record(cls, redis: Redis, interaction_id: str) -> dict[str, Any]:
"""
- 读取并校验后端完整记录
+ 读取并校验后端完整记录。
:param redis: Redis 客户端
:param interaction_id: 交互流程标识
:return: 通过校验的完整 Interaction 记录
+ :raises OidcInteractionException: 认证交互不存在或已过期;认证交互状态无效
"""
-
if (
not isinstance(interaction_id, str)
or not interaction_id
@@ -365,12 +374,11 @@ async def _get_record(cls, redis: Redis, interaction_id: str) -> dict[str, Any]:
@classmethod
def _validate_record(cls, record: Mapping[str, Any]) -> None:
"""
- 校验 Redis 中 Interaction 的完整结构和身份字段组合
+ 校验 Redis 中 Interaction 的完整结构和身份字段组合。
:param record: 交互记录
- :return: None
+ :raises ValueError: 认证交互记录必须为映射对象;认证交互记录不完整;认证交互状态标识无效;认证交互版本无效;认证交互的 CSRF 摘要无效;认证交互的请求时间 requestedAt 无效;认证交互的请求时间 requestedAt 必须使用 UTC;认证交互的用户身份字段必须完整
"""
-
if not isinstance(record, Mapping):
raise ValueError('认证交互记录必须为映射对象')
required = {'interactionId', 'requestedAt', 'csrfHash', 'status', 'version'}
@@ -401,12 +409,12 @@ def _validate_record(cls, record: Mapping[str, Any]) -> None:
@classmethod
def _validate_payload(cls, payload: Mapping[str, Any]) -> dict[str, Any]: # noqa: PLR0912, PLR0915
"""
- 校验 AuthorizationContext 生成的 Interaction 载荷
+ 校验 AuthorizationContext 生成的 Interaction 载荷。
:param payload: Interaction 载荷
:return: 通过校验的交互载荷
+ :raises ValueError: 交互记录缺少必需字段,或客户端、授权参数、用户身份和安全状态的格式不符合协议约定
"""
-
if not isinstance(payload, Mapping):
raise ValueError('认证交互载荷必须为映射对象')
allowed = {
@@ -572,12 +580,11 @@ def _validate_payload(cls, payload: Mapping[str, Any]) -> dict[str, Any]: # noq
@staticmethod
def _next_action(status: str) -> str:
"""
- 将内部交互状态转换为页面的下一步动作
+ 将内部交互状态转换为页面的下一步动作。
:param status: 当前交互状态
:return: 页面下一步动作
"""
-
return {
'awaiting_login': 'login',
'awaiting_consent': 'consent',
@@ -595,7 +602,7 @@ def _page_projection(
scopes: Mapping[str, 'SysOAuthScope'],
) -> dict[str, Any]:
"""
- 构建不含协议内部绑定和 CSRF 摘要的页面投影
+ 构建不含协议内部绑定和 CSRF 摘要的页面投影。
:param record: 交互记录
:param ttl: 剩余有效期秒数
@@ -603,7 +610,6 @@ def _page_projection(
:param scopes: 当前应用允许的启用权限定义
:return: 交互页面数据
"""
-
next_action = InteractionService._next_action(record['status'])
return {
@@ -634,7 +640,12 @@ def _page_projection(
@dataclass(frozen=True)
class CaptchaOutcome:
"""
- 验证码业务结果;HTTP 状态和响应头由 Controller 决定
+ 验证码业务结果;HTTP 状态和响应头由 Controller 决定。
+
+ :ivar result: 执行当前操作得到的结果
+ :ivar rate_limited: 请求是否触发频率限制
+ :ivar retry_after: 建议重试等待秒数
+ :ivar unavailable: 依赖服务是否不可用
"""
result: CaptchaResponseModel | None = None
@@ -644,9 +655,7 @@ class CaptchaOutcome:
class InteractionFlowService:
- """
- 交互状态模块服务层
- """
+ """交互状态模块服务层。"""
@staticmethod
async def commit_transition(
@@ -659,7 +668,7 @@ async def commit_transition(
compensate: Callable[[], Awaitable[None]] | None = None,
) -> None:
"""
- 提交数据库事务并推进交互状态
+ 提交数据库事务并推进交互状态。
:param db: 异步数据库会话
:param coordinator: 提交后副作用协调器
@@ -668,9 +677,9 @@ async def commit_transition(
:param target: 交互状态目标值
:param updates: 状态更新字段
:param compensate: 失败时执行的补偿回调
- :return: None
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises OidcInteractionException: 认证交互状态更新失败;认证交互缓存更新回调执行失败
"""
-
initial = await InteractionService.get_record(redis, interaction_id)
expected_status = initial['status']
expected_version = initial['version']
@@ -678,11 +687,10 @@ async def commit_transition(
async def transition() -> None:
"""
- 推进交互状态
+ 推进交互状态。
- :return: 状态转换结果
+ :raises Exception: 底层操作失败时向调用方传播异常
"""
-
try:
await InteractionService.transition(
redis, interaction_id, {expected_status}, target, updates, expected_version=expected_version
@@ -714,14 +722,14 @@ async def transition() -> None:
@staticmethod
async def csrf_record(redis: Redis, interaction_id: str, csrf_token: str | None) -> dict[str, Any]:
"""
- 校验 CSRF 并返回交互记录
+ 校验 CSRF 并返回交互记录。
:param redis: Redis 客户端
:param interaction_id: 交互流程标识
- :param csrf_token: CSRF Token
+ :param csrf_token: 防止跨站请求伪造的令牌
:return: 已校验的交互记录
+ :raises OidcInteractionException: CSRF 校验失败,请重新发起认证
"""
-
record = await InteractionService.get_record(redis, interaction_id)
if not InteractionService.verify_csrf(record, csrf_token or '', pepper=OidcConfig.oidc_token_hash_pepper):
raise OidcInteractionException(
@@ -732,13 +740,12 @@ async def csrf_record(redis: Redis, interaction_id: str, csrf_token: str | None)
@staticmethod
def require_status(record: dict[str, Any], expected: str) -> None:
"""
- 校验业务前置条件
+ 校验业务前置条件。
:param record: 交互记录
:param expected: 期望的状态
- :return: None
+ :raises OidcInteractionException: 认证交互状态已变更,请刷新后重试
"""
-
if record.get('status') != expected:
raise OidcInteractionException(
record.get('interactionId'),
@@ -750,14 +757,13 @@ def require_status(record: dict[str, Any], expected: str) -> None:
@staticmethod
async def captcha(redis: Redis, interaction_id: str, client_ip: str | None) -> CaptchaOutcome:
"""
- 生成交互验证码响应
+ 生成交互验证码响应。
:param redis: Redis 客户端
:param interaction_id: 交互流程标识
:param client_ip: 客户端 IP 地址
:return: 验证码响应结果
"""
-
try:
await OidcRateLimiter.enforce(
redis,
@@ -788,12 +794,11 @@ async def captcha(redis: Redis, interaction_id: str, client_ip: str | None) -> C
@staticmethod
async def captcha_enabled(redis: Redis) -> bool:
"""
- 读取交互验证码开关
+ 读取交互验证码开关。
:param redis: Redis 客户端
:return: 是否启用验证码
"""
-
value = await redis.get(f'{RedisInitKeyConfig.SYS_CONFIG.key}:sys.account.captchaEnabled')
return value in {'true', b'true', True}
@@ -801,13 +806,12 @@ async def captcha_enabled(redis: Redis) -> bool:
@staticmethod
async def reserve_completion(redis: Redis, interaction_id: str) -> str | None:
"""
- 保留交互完成标记 Key
+ 保留交互完成标记 Key。
:param redis: Redis 客户端
:param interaction_id: 交互流程标识
:return: 完成标记 Key 或 None
"""
-
ttl = await redis.ttl(OidcRedisKey.interaction(interaction_id))
if not isinstance(ttl, int) or ttl <= 0:
return None
@@ -819,13 +823,12 @@ async def reserve_completion(redis: Redis, interaction_id: str) -> str | None:
@staticmethod
def interaction_result(interaction_id: str, next_action: str) -> InteractionResultModel:
"""
- 构建交互结果响应
+ 构建交互结果响应。
:param interaction_id: 交互流程标识
:param next_action: 下一步交互动作
:return: 交互响应
"""
-
return InteractionResultModel(
next_action=next_action,
interaction_id=interaction_id,
@@ -835,13 +838,11 @@ def interaction_result(interaction_id: str, next_action: str) -> InteractionResu
@staticmethod
async def best_effort_delete(redis: Redis, key: str) -> None:
"""
- 尽力删除 Redis Key 并吞掉删除异常
+ 尽力删除 Redis Key 并吞掉删除异常。
:param redis: Redis 客户端
- :param key: Redis Key
- :return: None
+ :param key: Redis 缓存键
"""
-
try:
await redis.delete(key)
except Exception:
@@ -850,12 +851,10 @@ async def best_effort_delete(redis: Redis, key: str) -> None:
@staticmethod
async def rollback(db: AsyncSession) -> None:
"""
- 回滚数据库事务
+ 回滚数据库事务。
:param db: 异步数据库会话
- :return: None
"""
-
try:
await db.rollback()
except Exception:
@@ -865,7 +864,12 @@ async def rollback(db: AsyncSession) -> None:
@dataclass(frozen=True)
class InteractionLoginOutcome:
"""
- 登录/改密业务结果;Cookie 和 JSON 响应由 Controller 写出
+ 登录/改密业务结果;Cookie 和 JSON 响应由 Controller 写出。
+
+ :ivar result: 执行当前操作得到的结果
+ :ivar cookie: 写入或校验的会话 Cookie
+ :ivar failure_message: 流程失败时显示的提示
+ :ivar cookie_max_age: Cookie 的有效秒数
"""
result: InteractionResultModel | None = None
@@ -875,9 +879,7 @@ class InteractionLoginOutcome:
class InteractionLoginService:
- """
- 交互登录模块服务层
- """
+ """交互登录模块服务层。"""
@staticmethod
async def login(
@@ -890,7 +892,7 @@ async def login(
user_agent: str | None = None,
) -> InteractionLoginOutcome:
"""
- 校验本地凭据并推进认证交互
+ 校验本地凭据并推进认证交互。
:param redis: 交互 Redis
:param interaction_id: Interaction 标识
@@ -901,7 +903,6 @@ async def login(
:param user_agent: 客户端 User-Agent
:return: 下一步交互动作
"""
-
record = await InteractionFlowService.csrf_record(redis, interaction_id, csrf_token)
InteractionFlowService.require_status(record, 'awaiting_login')
try:
@@ -982,12 +983,7 @@ async def login(
)
async def compensate() -> None:
- """
- 执行事务补偿
-
- :return: None
- """
-
+ """执行事务补偿。"""
if session is None:
return
await InteractionFlowService.best_effort_delete(redis, OidcRedisKey.interaction(interaction_id))
@@ -1042,7 +1038,7 @@ async def change_password(
csrf_token: str | None,
) -> InteractionLoginOutcome:
"""
- 修改初始或过期密码并重新建立当前 SSO Session
+ 修改初始或过期密码并重新建立当前 SSO Session。
:param redis: 交互 Redis
:param interaction_id: Interaction 标识
@@ -1051,7 +1047,6 @@ async def change_password(
:param csrf_token: Interaction CSRF 原文
:return: 下一步交互动作
"""
-
record = await InteractionFlowService.csrf_record(redis, interaction_id, csrf_token)
InteractionFlowService.require_status(record, 'password_change_required')
user = await IdentityUserDao.get_active_user(db, int(record.get('userId') or 0))
@@ -1132,12 +1127,7 @@ async def change_password(
)
async def compensate() -> None:
- """
- 执行事务补偿
-
- :return: None
- """
-
+ """执行事务补偿。"""
await InteractionFlowService.best_effort_delete(redis, OidcRedisKey.interaction(interaction_id))
try:
cleanup = AfterCommitCoordinator()
diff --git a/ruoyi-fastapi-backend/module_identity/service/key_service.py b/ruoyi-fastapi-backend/module_identity/service/key_service.py
index a2b898d1f..6b4ef54de 100644
--- a/ruoyi-fastapi-backend/module_identity/service/key_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/key_service.py
@@ -41,14 +41,14 @@
class KeyServiceError(ValueError):
- """
- 表示 OIDC 签名密钥管理错误
- """
+ """表示 OIDC 签名密钥管理错误。"""
class KeyService:
"""
- OIDC 签名密钥模块服务层
+ OIDC 签名密钥模块服务层。
+
+ :cvar CACHE_MAX_AGE: 密钥集响应允许的缓存时长
"""
CACHE_MAX_AGE = 300
@@ -56,13 +56,11 @@ class KeyService:
@classmethod
def _require_enabled(cls, *, management: bool = False) -> None:
"""
- 校验 OIDC 签名密钥功能是否可用
+ 校验 OIDC 签名密钥功能是否可用。
:param management: 是否允许管理模式
- :return: None
:raises KeyServiceError: OIDC 未启用
"""
-
if not OidcConfig.oidc_enabled and not management:
raise KeyServiceError('统一认证中心未启用')
@@ -70,13 +68,12 @@ def _require_enabled(cls, *, management: bool = False) -> None:
@asynccontextmanager
async def _rotation_lock(redis: Any) -> AsyncGenerator[None, None]:
"""
- 获取密钥轮换锁
+ 获取密钥轮换锁。
:param redis: 应用共享 Redis 客户端;离线数据库单元测试可传 ``None``
- :return: 异步上下文管理器
+ :yield: 异步上下文管理器
:raises KeyServiceError: 锁已被其他实例持有
"""
-
if redis is None:
yield
return
@@ -102,14 +99,13 @@ async def _private_material_async( # noqa: PLR0912
decrypt_private_key: Callable[[str], bytes | str | Awaitable[bytes | str]] | None,
) -> bytes:
"""
- 异步读取私钥材料
+ 异步读取私钥材料。
:param record: 数据库密钥记录
:param decrypt_private_key: 可同步或异步的解密回调
:return: PEM 编码私钥字节
:raises KeyServiceError: 私钥来源不合法或无法解密
"""
-
reference = getattr(record, 'private_key_ref', None)
ciphertext = getattr(record, 'private_key_ciphertext', None)
if bool(reference) == bool(ciphertext):
@@ -153,15 +149,13 @@ async def _private_material_async( # noqa: PLR0912
@classmethod
def _validate_record_window(cls, record: Any, now: datetime, *, require_active: bool = True) -> None:
"""
- 校验签名密钥状态、算法和时间窗口
+ 校验签名密钥状态、算法和时间窗口。
:param record: 数据库密钥记录
:param now: 当前项目时间
:param require_active: 是否要求密钥处于 active 状态
- :return: None
:raises KeyServiceError: 记录不能用于签名
"""
-
expected_status = 'active' if require_active else 'pending'
if getattr(record, 'status', None) != expected_status:
raise KeyServiceError(f'签名密钥状态不符合要求,预期状态为 {expected_status}')
@@ -185,7 +179,7 @@ async def load_private_key_async(
management: bool = False,
) -> RSAPrivateKey:
"""
- 异步加载并校验签名密钥 RSA 私钥
+ 异步加载并校验签名密钥 RSA 私钥。
:param record: 数据库中的签名密钥记录
:param now: 可注入的当前时间
@@ -195,7 +189,6 @@ async def load_private_key_async(
:return: 已验证且不会被序列化的 RSA 私钥
:raises KeyServiceError: 状态、来源、格式或公私钥不匹配
"""
-
cls._require_enabled(management=management)
current = TimezoneUtil.to_optional_utc(now or TimezoneUtil.utc_now())
cls._validate_record_window(record, current, require_active=require_active)
@@ -226,7 +219,7 @@ def load_private_key(
require_active: bool = True,
) -> RSAPrivateKey:
"""
- 同步加载签名密钥 RSA 私钥
+ 同步加载签名密钥 RSA 私钥。
:param record: 数据库中的签名密钥记录
:param now: 可注入的当前时间
@@ -234,7 +227,6 @@ def load_private_key(
:return: 已验证的 RSA 私钥
:raises KeyServiceError: 私钥不合法或无法同步加载
"""
-
try:
asyncio.get_running_loop()
except RuntimeError:
@@ -250,7 +242,7 @@ async def get_signing_key(
decrypt_private_key: Callable[[str], bytes | str | Awaitable[bytes | str]] | None = None,
) -> RSAPrivateKey:
"""
- 获取当前 active 签名密钥的 RSA 私钥
+ 获取当前 active 签名密钥的 RSA 私钥。
:param db: 异步数据库会话
:param now: 可注入当前时间
@@ -258,7 +250,6 @@ async def get_signing_key(
:return: 已验证 RSA 私钥
:raises KeyServiceError: 没有匹配的 active 密钥
"""
-
cls._require_enabled()
record = await OidcKeyDao.get_active(db, alg=RS256)
if record is None:
@@ -268,14 +259,13 @@ async def get_signing_key(
@classmethod
async def build_jwks(cls, db: AsyncSession, *, now: datetime | None = None) -> dict[str, list[dict[str, str]]]:
"""
- 构造发布中的签名公钥 JWKS
+ 构造发布中的签名公钥 JWKS。
:param db: 异步数据库会话
:param now: 可注入当前时间
:return: 标准 ``{'keys': [...]}`` JSON 结构
:raises KeyServiceError: OIDC 关闭或公开密钥记录不合法
"""
-
cls._require_enabled()
current = TimezoneUtil.to_optional_utc(now or TimezoneUtil.utc_now())
records = await OidcKeyDao.list_published(db, now=current)
@@ -311,7 +301,7 @@ async def activate_key(
redis: Any = None,
) -> bool:
"""
- 激活 pending 签名密钥并安排旧密钥退役
+ 激活 pending 签名密钥并安排旧密钥退役。
:param db: 异步数据库会话,调用方负责提交事务
:param kid: 待激活的 pending 密钥 kid
@@ -322,7 +312,6 @@ async def activate_key(
:return: 成功完成切换时返回 True
:raises KeyServiceError: 目标密钥未到发布时间或算法不符
"""
-
cls._require_enabled(management=True)
if not OidcUtil.is_valid_kid(kid):
raise KeyServiceError('签名密钥标识 kid 包含不允许的字符')
@@ -381,7 +370,7 @@ async def create_pending_key(
now: datetime | None = None,
) -> SysOidcSigningKey:
"""
- 创建加密保存的 pending 签名密钥记录
+ 创建加密保存的 pending 签名密钥记录。
:param db: 异步数据库会话,提交边界由调用方控制
:param kid: 新密钥标识
@@ -393,7 +382,6 @@ async def create_pending_key(
:return: 不含私钥明文的数据库实体
:raises KeyServiceError: 配置、标识或密钥加密条件不满足
"""
-
cls._require_enabled(management=True)
if not isinstance(actor, str) or not actor.strip():
raise KeyServiceError('签名密钥标识 kid 和操作者不能为空')
@@ -455,7 +443,7 @@ async def bootstrap_signing_key(
now: datetime | None = None,
) -> tuple[SysOidcSigningKey, bool]:
"""
- 幂等创建并激活首把 OIDC 签名密钥
+ 幂等创建并激活首把 OIDC 签名密钥。
已存在可用 active 密钥时只校验并返回;否则在 Redis 轮换锁与
数据库行锁保护下创建和激活密钥。事务提交由调用方统一处理。
@@ -468,7 +456,6 @@ async def bootstrap_signing_key(
:return: 签名密钥记录与本次是否创建新密钥
:raises KeyServiceError: 密钥配置、状态或材料不可用
"""
-
current = TimezoneUtil.to_optional_utc(now or TimezoneUtil.utc_now())
async with cls._rotation_lock(redis):
records = await OidcKeyDao.lock_algorithm_for_update(db, alg=RS256)
@@ -527,7 +514,7 @@ async def retire_key(
actor: str = 'system:lifecycle',
) -> bool:
"""
- 将 active 签名密钥转为 retiring 状态
+ 将 active 签名密钥转为 retiring 状态。
:param db: 异步数据库会话
:param kid: 密钥标识
@@ -536,7 +523,6 @@ async def retire_key(
:return: 本次是否将签名密钥转为退役中状态
:raises KeyServiceError: 签名密钥状态、材料或配置不符合要求
"""
-
cls._require_enabled(management=True)
if not OidcUtil.is_valid_kid(kid):
raise KeyServiceError('签名密钥标识 kid 包含不允许的字符')
@@ -570,12 +556,11 @@ async def retire_key(
@classmethod
async def retire_due(cls, db: AsyncSession) -> int:
"""
- 退役已结束 JWKS 保留期的签名密钥
+ 退役已结束 JWKS 保留期的签名密钥。
:param db: 异步数据库会话
:return: 更新的记录数量
"""
-
cls._require_enabled()
return await OidcKeyDao.retire_due(db)
@@ -590,7 +575,7 @@ async def activate_due(
audit_writer: Callable[..., Awaitable[Any]] | None = None,
) -> int:
"""
- 批量激活已到签名开始时间的 pending 密钥
+ 批量激活已到签名开始时间的 pending 密钥。
:param db: 异步数据库会话;每次状态推进由调用方提交
:param redis: 应用共享 Redis 轮换锁客户端
@@ -598,7 +583,6 @@ async def activate_due(
:param audit_writer: 可注入的独立审计写入器,生产默认使用独立提交事务
:return: 本次成功激活的密钥数量
"""
-
cls._require_enabled()
current = TimezoneUtil.to_optional_utc(now or TimezoneUtil.utc_now())
pending = await OidcKeyDao.list_due_pending(db, now=current)
@@ -642,7 +626,7 @@ async def delete_key(
actor: str = 'system:lifecycle',
) -> bool:
"""
- 删除已退役且超过 JWKS 保留期的签名密钥
+ 删除已退役且超过 JWKS 保留期的签名密钥。
:param db: 异步数据库会话
:param kid: 待删除的 kid
@@ -650,7 +634,6 @@ async def delete_key(
:return: 删除成功时返回 True
:raises KeyServiceError: 密钥仍可能用于验签或不存在
"""
-
cls._require_enabled(management=True)
if not OidcUtil.is_valid_kid(kid):
raise KeyServiceError('签名密钥标识 kid 包含不允许的字符')
@@ -674,7 +657,9 @@ async def delete_key(
class OidcKeyManagementService:
"""
- OIDC 签名密钥管理模块服务层
+ OIDC 签名密钥管理模块服务层。
+
+ :cvar _ERROR_MESSAGES: 按错误类型查找的提示文本
"""
_ERROR_MESSAGES = {
@@ -686,12 +671,11 @@ class OidcKeyManagementService:
@staticmethod
def view(row: SysOidcSigningKey) -> dict[str, object]:
"""
- 将签名密钥 ORM 记录转换为管理视图
+ 将签名密钥 ORM 记录转换为管理视图。
:param row: 签名密钥 ORM 记录
:return: 签名密钥管理视图字段映射
"""
-
return OidcKeyViewModel(
kid=row.kid,
key_use=row.key_use,
@@ -716,7 +700,7 @@ async def bootstrap(
now: datetime | None = None,
) -> tuple[dict[str, object], bool]:
"""
- 幂等创建并激活首把 OIDC 签名密钥
+ 幂等创建并激活首把 OIDC 签名密钥。
已存在可用 active 密钥时只校验并返回;否则在 Redis 轮换锁与
数据库行锁保护下创建、激活并提交,适合部署流水线并发调用。
@@ -729,7 +713,6 @@ async def bootstrap(
:return: 管理视图与本次是否创建新密钥
:raises ServiceException: 签名密钥初始化失败
"""
-
row, created = await cls._execute(
db,
lambda: KeyService.bootstrap_signing_key(
@@ -753,7 +736,7 @@ async def list_page(
page_size: int,
) -> tuple[list[dict[str, object]], int]:
"""
- 分页查询签名密钥管理视图
+ 分页查询签名密钥管理视图。
:param db: 异步数据库会话
:param status: 密钥状态筛选值
@@ -761,7 +744,6 @@ async def list_page(
:param page_size: 页大小
:return: 管理视图列表和总数
"""
-
rows = await OidcKeyDao.list_admin(db, status=status, offset=(page_num - 1) * page_size, limit=page_size)
total = await OidcKeyDao.count_admin(db, status=status)
@@ -770,14 +752,13 @@ async def list_page(
@staticmethod
async def rotate(db: AsyncSession, payload: OidcKeyRotateModel, actor: str) -> dict[str, object]:
"""
- 创建 pending 签名密钥并返回管理视图
+ 创建 pending 签名密钥并返回管理视图。
:param db: 异步数据库会话
:param payload: 签名密钥轮换参数
:param actor: 操作人标识
:return: 新建签名密钥的管理视图字段映射
"""
-
result = await OidcKeyManagementService._execute(
db,
lambda: KeyService.create_pending_key(
@@ -795,7 +776,7 @@ async def rotate(db: AsyncSession, payload: OidcKeyRotateModel, actor: str) -> d
@staticmethod
async def activate(db: AsyncSession, kid: str, actor: str, redis: object) -> bool:
"""
- 激活指定签名密钥并提交事务
+ 激活指定签名密钥并提交事务。
:param db: 异步数据库会话
:param kid: 密钥标识
@@ -804,7 +785,6 @@ async def activate(db: AsyncSession, kid: str, actor: str, redis: object) -> boo
:return: 本次是否激活签名密钥
:raises ServiceException: 签名密钥无法开始使用
"""
-
return await OidcKeyManagementService._execute(
db, lambda: KeyService.activate_key(db, kid, actor=actor, redis=redis)
)
@@ -812,40 +792,37 @@ async def activate(db: AsyncSession, kid: str, actor: str, redis: object) -> boo
@staticmethod
async def retire(db: AsyncSession, kid: str, actor: str) -> bool:
"""
- 退役指定签名密钥并提交事务
+ 退役指定签名密钥并提交事务。
:param db: 异步数据库会话
:param kid: 密钥标识
:param actor: 操作人标识
:return: 本次是否将签名密钥转为退役中状态
"""
-
return await OidcKeyManagementService._execute(db, lambda: KeyService.retire_key(db, kid, actor=actor))
@staticmethod
async def delete(db: AsyncSession, kid: str, actor: str) -> bool:
"""
- 删除指定已退役签名密钥并提交事务
+ 删除指定已退役签名密钥并提交事务。
:param db: 异步数据库会话
:param kid: 密钥标识
:param actor: 操作人标识
:return: 本次是否删除签名密钥
"""
-
return await OidcKeyManagementService._execute(db, lambda: KeyService.delete_key(db, kid, actor=actor))
@staticmethod
async def _execute(db: AsyncSession, operation: Callable[[], Awaitable[T]]) -> T:
"""
- 执行签名密钥管理事务并统一处理回滚
+ 执行签名密钥管理事务并统一处理回滚。
:param db: 异步数据库会话
:param operation: 事务操作回调
:return: operation 回调的返回值
:raises ServiceException: 签名密钥管理事务失败时抛出
"""
-
try:
result = await operation()
await db.commit()
diff --git a/ruoyi-fastapi-backend/module_identity/service/logout_confirmation_service.py b/ruoyi-fastapi-backend/module_identity/service/logout_confirmation_service.py
index 09fbd5895..9bb45e401 100644
--- a/ruoyi-fastapi-backend/module_identity/service/logout_confirmation_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/logout_confirmation_service.py
@@ -17,7 +17,12 @@
class LogoutConfirmationService:
"""
- 认证中心退出确认服务层
+ 认证中心退出确认服务层。
+
+ :cvar COOKIE_NAME: 用于登出确认的 Cookie 名
+ :cvar TTL_SECONDS: 有效期(秒)
+ :cvar _TOKEN_LENGTH: 登出确认令牌的长度
+ :cvar _CONSUME: 原子消费登出确认记录的 Redis 脚本
"""
COOKIE_NAME = '__Host-oidc_logout_confirmation'
@@ -32,7 +37,7 @@ class LogoutConfirmationService:
@classmethod
async def issue(cls, redis: Redis, parameters: dict[str, str], sso_cookie: str | None) -> tuple[str, str]:
"""
- 签发短期有效且仅可使用一次的退出确认凭据
+ 签发短期有效且仅可使用一次的退出确认凭据。
:param redis: Redis连接对象
:param parameters: 已校验的退出请求参数
@@ -40,7 +45,6 @@ async def issue(cls, redis: Redis, parameters: dict[str, str], sso_cookie: str |
:return: 退出确认凭据和浏览器随机数
:raises RuntimeError: 确认记录保存失败
"""
-
token = secrets.token_urlsafe(32)
nonce = secrets.token_urlsafe(32)
record = json.dumps(
@@ -68,7 +72,7 @@ async def consume(
cls, redis: Redis, token: str, sso_cookie: str | None, browser_nonce: str | None
) -> dict[str, str]:
"""
- 消费一次性退出确认凭据并校验浏览器归属
+ 消费一次性退出确认凭据并校验浏览器归属。
:param redis: Redis连接对象
:param token: 用户提交的退出确认凭据
@@ -77,7 +81,6 @@ async def consume(
:return: 原始退出请求参数
:raises ValueError: 凭据无效、已使用、已过期或浏览器绑定不匹配
"""
-
if not isinstance(token, str) or len(token) != cls._TOKEN_LENGTH or not browser_nonce:
raise ValueError('退出确认信息无效')
raw = await redis.eval(cls._CONSUME, 1, 'oidc:logout:confirmation:' + OidcUtil.sha256_digest(token))
@@ -97,7 +100,7 @@ async def consume(
@classmethod
async def form_redirect_origin(cls, db: AsyncSession, parameters: dict[str, str]) -> str | None:
"""
- 获取退出确认页内容安全策略允许的客户端回调源
+ 获取退出确认页内容安全策略允许的客户端回调源。
校验ID Token提示,并精确匹配已启用的注册回调地址。
@@ -105,7 +108,6 @@ async def form_redirect_origin(cls, db: AsyncSession, parameters: dict[str, str]
:param parameters: 已校验的退出请求参数
:return: 允许的回调源地址,校验失败时返回None
"""
-
hint = parameters.get('id_token_hint')
uri = parameters.get('post_logout_redirect_uri')
if not hint or not OidcUtil.is_safe_post_logout_uri(uri):
diff --git a/ruoyi-fastapi-backend/module_identity/service/oauth_management_service.py b/ruoyi-fastapi-backend/module_identity/service/oauth_management_service.py
index f54aaa502..a96b4dc81 100644
--- a/ruoyi-fastapi-backend/module_identity/service/oauth_management_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/oauth_management_service.py
@@ -47,7 +47,12 @@
@dataclass(frozen=True, slots=True)
class ResourceInvalidationTargets:
"""
- 保存 Resource 变更后需要撤销的 Grant 和 Refresh Token 标识
+ 保存 Resource 变更后需要撤销的 Grant 和 Refresh Token 标识。
+
+ :ivar resource_id: 资源标识
+ :ivar client_ids: 要操作的 OAuth 客户端标识列表
+ :ivar grant_ids: 当前操作涉及的授权记录标识
+ :ivar refresh_token_ids: 需要失效的刷新令牌标识
"""
resource_id: str
@@ -58,24 +63,32 @@ class ResourceInvalidationTargets:
class OAuthClientManagementError(ServiceException):
"""
- 表示 OAuth Client 管理错误
+ 表示 OAuth Client 管理错误。
+
+ :ivar args: 传给被调用对象的位置参数
"""
def __init__(self, message: str) -> None:
"""
- 初始化 OAuth Client 管理异常
+ 初始化 OAuth Client 管理异常。
:param message: 错误消息
- :return: None
"""
-
super().__init__(message=message)
self.args = (message,)
class OAuthManagementBaseService:
"""
- OAuth 管理模块公共服务层
+ OAuth 管理模块公共服务层。
+
+ :cvar _OAUTH_RESPONSE_QUERY_KEYS: OAuth 响应在重定向查询串中使用的保留键
+ :cvar _MAX_AUDIENCE_LENGTH: 受众标识允许的最大长度
+ :cvar _MAX_CLAIMS: 单个资源允许声明的最多身份字段数
+ :cvar _MAX_CLAIM_NAME_LENGTH: 身份声明名称允许的最大长度
+ :cvar _MAX_CLIENT_ID_LENGTH: 客户端标识允许的最大长度
+ :cvar _URI_TYPES: 管理接口支持注册的 URI 类型
+ :cvar _ALLOWED_CLAIMS: 允许客户端选用的身份声明
"""
@classmethod
@@ -86,15 +99,15 @@ async def _transaction(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> T:
"""
- 执行事务操作
+ 执行事务操作。
:param db: 异步数据库会话
:param operation: 事务内的管理变更操作
:param after_commit: 事务提交成功后执行的异步回调
:return: operation 回调的返回值
:raises OAuthClientManagementError: 敏感凭据相关 ServiceException 被转换为安全管理异常
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
-
try:
result = await operation()
await db.commit()
@@ -155,7 +168,7 @@ async def _record_audit(
detail: dict[str, str] | None = None,
) -> None:
"""
- 记录管理审计
+ 记录管理审计。
:param db: 异步数据库会话
:param event_type: 审计事件类型
@@ -165,9 +178,7 @@ async def _record_audit(
:param sid: Session 标识
:param grant_id: Grant 标识
:param detail: 审计详情
- :return: None
"""
-
safe_detail = {'actor': actor[:64]}
if detail:
safe_detail.update({key: value[:200] for key, value in detail.items() if key in {'reason', 'action'}})
@@ -185,13 +196,12 @@ async def _record_audit(
@staticmethod
def _now(value: datetime | None) -> datetime:
"""
- 将输入时间规范化为项目时间
+ 将输入时间规范化为项目时间。
:param value: 调用方提供的当前时间值
:return: 规范化后的带时区的 UTC 时间
:raises OAuthClientManagementError: now 不是 datetime 时抛出
"""
-
if value is None:
return TimezoneUtil.utc_now()
if not isinstance(value, datetime):
@@ -201,13 +211,12 @@ def _now(value: datetime | None) -> datetime:
@staticmethod
def _actor(actor: str) -> str:
"""
- 校验操作人标识
+ 校验操作人标识。
:param actor: 操作人标识
:return: 规范化后的操作者标识
:raises OAuthClientManagementError: actor 为空或不是字符串时抛出
"""
-
try:
return OidcUtil.actor_name(actor)
except ValueError as exc:
@@ -216,13 +225,11 @@ def _actor(actor: str) -> str:
@classmethod
def _validate_client_ttls(cls, payload: ClientCreateModel) -> None:
"""
- 校验 Client 令牌时效策略
+ 校验 Client 令牌时效策略。
:param payload: Client 创建参数
- :return: None
:raises OAuthClientManagementError: Client TTL 非正数、超出平台上限或闲置 TTL 超过绝对 TTL 时抛出
"""
-
access = payload.access_token_ttl_seconds or OidcConfig.oidc_access_token_ttl_seconds
refresh_idle = payload.refresh_token_idle_seconds or OidcConfig.oidc_refresh_token_idle_seconds
refresh_absolute = payload.refresh_token_absolute_seconds or OidcConfig.oidc_refresh_token_absolute_seconds
@@ -241,13 +248,11 @@ def _validate_client_ttls(cls, payload: ClientCreateModel) -> None:
@classmethod
def _validate_resource_ttls(cls, payload: ResourceCreateModel) -> None:
"""
- 校验 Resource Access Token 时效策略
+ 校验 Resource Access Token 时效策略。
:param payload: Resource 创建或更新参数
- :return: None
:raises OAuthClientManagementError: Resource TTL 非正数或超出平台上限时抛出
"""
-
value = payload.access_token_ttl_seconds or OidcConfig.oidc_access_token_ttl_seconds
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
raise OAuthClientManagementError('资源访问令牌有效期配置无效')
@@ -257,14 +262,13 @@ def _validate_resource_ttls(cls, payload: ResourceCreateModel) -> None:
@classmethod
def _validate_uri(cls, uri_type: str, uri: str) -> str:
"""
- 校验并规范化 Client 注册 URI
+ 校验并规范化 Client 注册 URI。
:param uri_type: URI 类型
:param uri: 回调 URI
:return: 校验后的完整 URI
:raises OAuthClientManagementError: URI 格式不合法、包含保留参数或 Back-Channel 地址不安全时抛出
"""
-
try:
value = ClientUriModel(uri_type=uri_type, uri=uri).uri
except (TypeError, ValueError) as exc:
@@ -289,13 +293,12 @@ def _validate_uri(cls, uri_type: str, uri: str) -> str:
@classmethod
def _uri_values(cls, payload: ClientCreateModel) -> dict[str, list[str]]:
"""
- 收集并校验 Client 注册 URI
+ 收集并校验 Client 注册 URI。
:param payload: Client 创建参数
:return: 按 URI 类型分组的注册地址映射
:raises OAuthClientManagementError: URI 重复或格式不合法时抛出
"""
-
values: dict[str, list[str]] = {}
for uri_type, field_name in cls._URI_TYPES:
uris = list(getattr(payload, field_name))
@@ -307,13 +310,12 @@ def _uri_values(cls, payload: ClientCreateModel) -> dict[str, list[str]]:
@classmethod
async def _uri_values_async(cls, payload: ClientCreateModel) -> dict[str, list[str]]:
"""
- 收集 URI 并执行 Back-Channel DNS 校验
+ 收集 URI 并执行 Back-Channel DNS 校验。
:param payload: Client 创建参数
:return: 完成 DNS 校验的注册地址映射
:raises OAuthClientManagementError: Back-Channel URI DNS 目标不是公网地址时抛出
"""
-
values = cls._uri_values(payload)
backchannels = values.get('backchannel_logout', [])
for uri in backchannels:
@@ -326,14 +328,13 @@ async def _load_bindings(
cls, db: AsyncSession, payload: ClientCreateModel
) -> tuple[list[SysOAuthScope], list[SysOAuthResource]]:
"""
- 查询并校验 Client 的 Scope 与 Resource 绑定
+ 查询并校验 Client 的 Scope 与 Resource 绑定。
:param db: 异步数据库会话
:param payload: Client 创建参数
:return: 已校验的 Scope ORM 列表和 Resource ORM 列表
:raises OAuthClientManagementError: Scope 或 Resource 不存在、未启用或绑定关系不合法时抛出
"""
-
try:
scope_codes = OidcUtil.unique_codes(payload.scope_codes, 'scope_codes')
resource_ids = OidcUtil.unique_codes(payload.resource_ids, 'resource_ids')
@@ -373,7 +374,7 @@ async def _replace_bindings(
now: datetime,
) -> None:
"""
- 写入 Client 的 Scope、Resource 与 URI 绑定
+ 写入 Client 的 Scope、Resource 与 URI 绑定。
:param db: 异步数据库会话
:param client_pk: 客户端主键
@@ -381,9 +382,7 @@ async def _replace_bindings(
:param scopes: Scope 集合
:param resources: Resource 集合
:param now: 当前时间
- :return: None
"""
-
uri_values = await cls._uri_values_async(payload)
await OAuthClientDao.replace_bindings(
db,
@@ -399,12 +398,11 @@ async def _replace_bindings(
@staticmethod
def _client_values(payload: ClientCreateModel) -> dict[str, object]:
"""
- 转换 Client DTO 为 ORM 字段
+ 转换 Client DTO 为 ORM 字段。
:param payload: Client 创建参数
:return: 可写入 Client ORM 的字段映射
"""
-
return {
'client_name': payload.client_name,
'client_type': payload.client_type,
@@ -426,14 +424,13 @@ def _client_values(payload: ClientCreateModel) -> dict[str, object]:
@staticmethod
def _secret_response(client_id: str, secret: SysOAuthClientSecret, plaintext: str) -> ClientSecretResponseModel:
"""
- 构造 Client Secret 返回模型
+ 构造 Client Secret 返回模型。
:param client_id: 客户端标识
:param secret: 已保存的 Client Secret ORM 记录
:param plaintext: 明文密钥
:return: 包含一次性明文的 ClientSecretResponseModel
"""
-
return ClientSecretResponseModel(
client_id=client_id,
secret_id=secret.secret_id,
@@ -455,7 +452,7 @@ async def _new_secret(
expires_at: datetime | None = None,
) -> ClientSecretResponseModel:
"""
- 创建并 flush Client Secret ORM 记录
+ 创建并 flush Client Secret ORM 记录。
:param db: 异步数据库会话
:param client: Client ORM 记录
@@ -465,7 +462,6 @@ async def _new_secret(
:param expires_at: 过期时间
:return: 已 flush 的 ClientSecretResponseModel
"""
-
plaintext = OidcUtil.generate_client_secret()
secret = SysOAuthClientSecret(
secret_id=str(uuid4()),
@@ -485,14 +481,13 @@ async def _new_secret(
@classmethod
def _validate_claims(cls, values: Iterable[str], field_name: str = 'claims') -> list[str]:
"""
- 校验 Resource Claim 白名单
+ 校验 Resource Claim 白名单。
:param values: Resource Claim 名称列表
:param field_name: 字段名称
:return: 已校验的 Resource Claim 名称列表
:raises OAuthClientManagementError: Claim 列表不是允许的字符串列表或包含重复项时抛出
"""
-
if not isinstance(values, list) or len(values) > cls._MAX_CLAIMS:
raise OAuthClientManagementError(f'{field_name} 必须为列表,且最多包含 64 项')
result: list[str] = []
@@ -509,12 +504,11 @@ def _validate_claims(cls, values: Iterable[str], field_name: str = 'claims') ->
@staticmethod
def _resource_values(payload: ResourceCreateModel) -> dict[str, object]:
"""
- 转换 Resource DTO 为 ORM 字段
+ 转换 Resource DTO 为 ORM 字段。
:param payload: Resource 创建或更新参数
:return: 可写入 Resource ORM 的字段映射
"""
-
return {
'resource_name': payload.resource_name,
'audience': payload.audience,
@@ -528,14 +522,13 @@ def _resource_values(payload: ResourceCreateModel) -> dict[str, object]:
@classmethod
async def _resolve_introspection_client(cls, db: AsyncSession, client_id: str | None) -> SysOAuthClient | None:
"""
- 解析 Resource 使用的 introspection Client
+ 解析 Resource 使用的 introspection Client。
:param db: 异步数据库会话
:param client_id: 客户端标识
:return: 启用的 introspection Client ORM 记录或 None
:raises OAuthClientManagementError: introspection Client 不存在、未启用或不是机密 Client 时抛出
"""
-
if client_id is None:
return None
if not isinstance(client_id, str) or not client_id or len(client_id) > cls._MAX_CLIENT_ID_LENGTH:
@@ -548,13 +541,12 @@ async def _resolve_introspection_client(cls, db: AsyncSession, client_id: str |
@staticmethod
def _resource_view(resource: SysOAuthResource, introspection_client_id: str | None = None) -> ResourceViewModel:
"""
- 转换 Resource ORM 记录为 ResourceViewModel
+ 转换 Resource ORM 记录为 ResourceViewModel。
:param resource: Resource ORM 记录
:param introspection_client_id: 用于内省的客户端标识
:return: ResourceViewModel 管理视图
"""
-
return ResourceViewModel.model_validate(
{
'resource_id': resource.resource_id,
@@ -573,13 +565,12 @@ def _resource_view(resource: SysOAuthResource, introspection_client_id: str | No
@staticmethod
def _scope_view(scope: SysOAuthScope, resource_id: str | None) -> ScopeModel:
"""
- 转换 Scope ORM 记录为 ScopeModel
+ 转换 Scope ORM 记录为 ScopeModel。
:param scope: Scope ORM 记录
:param resource_id: 资源标识
:return: ScopeModel 管理视图
"""
-
return ScopeModel.model_validate(
{
'scope_code': scope.scope_code,
@@ -597,26 +588,23 @@ def _scope_view(scope: SysOAuthScope, resource_id: str | None) -> ScopeModel:
@classmethod
async def _lock_resource_clients(cls, db: AsyncSession, resource_pk: int) -> list[SysOAuthClient]:
"""
- 锁定关联 Resource 的 Client 记录
+ 锁定关联 Resource 的 Client 记录。
:param db: 异步数据库会话
:param resource_pk: 资源主键
:return: 已锁定的 Client ORM 记录列表
"""
-
return list(await OAuthClientDao.lock_clients_for_resource(db, resource_pk))
@staticmethod
def _bump_clients(clients: Iterable[SysOAuthClient], actor: str, now: datetime) -> None:
"""
- 递增 Client 策略版本并记录操作者
+ 递增 Client 策略版本并记录操作者。
:param clients: 需要递增策略版本的客户端集合
:param actor: 操作人标识
:param now: 当前时间
- :return: None
"""
-
for client in clients:
client.policy_version = int(client.policy_version or 0) + 1
client.update_by, client.update_time = actor, now
@@ -624,21 +612,17 @@ def _bump_clients(clients: Iterable[SysOAuthClient], actor: str, now: datetime)
@staticmethod
async def _revoke_client_credentials(db: AsyncSession, client_pk: int, now: datetime) -> None:
"""
- 撤销 Client 的 Grant 与 Refresh Token
+ 撤销 Client 的 Grant 与 Refresh Token。
:param db: 异步数据库会话
:param client_pk: 客户端主键
:param now: 当前时间
- :return: None
"""
-
await OAuthClientDao.revoke_client_credentials(db, client_pk, now)
class OAuthClientManagementService(OAuthManagementBaseService):
- """
- OAuth Client 管理模块服务层
- """
+ """OAuth Client 管理模块服务层。"""
@classmethod
async def create_client(
@@ -651,7 +635,7 @@ async def create_client(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> ClientViewModel:
"""
- 创建 OAuth Client 及其绑定配置
+ 创建 OAuth Client 及其绑定配置。
:param db: 异步数据库会话
:param payload: Client 创建参数
@@ -660,7 +644,6 @@ async def create_client(
:param after_commit: 事务提交成功后执行的异步回调
:return: 创建后的 Client 详情
"""
-
return await cls._transaction(db, lambda: cls._create_client(db, payload, actor=actor, now=now), after_commit)
@classmethod
@@ -674,7 +657,7 @@ async def update_client(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> ClientViewModel:
"""
- 更新 OAuth Client 及其绑定配置
+ 更新 OAuth Client 及其绑定配置。
:param db: 异步数据库会话
:param payload: Client 更新参数
@@ -683,7 +666,6 @@ async def update_client(
:param after_commit: 事务提交成功后执行的异步回调
:return: 更新后的 Client 详情
"""
-
return await cls._transaction(db, lambda: cls._update_client(db, payload, actor=actor, now=now), after_commit)
@classmethod
@@ -696,22 +678,16 @@ async def disable_clients(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> None:
"""
- 禁用指定 OAuth Client 并撤销其凭据
+ 禁用指定 OAuth Client 并撤销其凭据。
:param db: 异步数据库会话
:param identifiers: Client 公开标识列表
:param actor: 操作者标识
:param after_commit: 事务提交成功后执行的异步回调
- :return: None
"""
async def operation() -> None:
- """
- 在同一事务中批量禁用指定 Client
-
- :return: None
- """
-
+ """在同一事务中批量禁用指定 Client。"""
for identifier in identifiers:
await cls._soft_disable(db, identifier, actor=actor)
@@ -727,7 +703,7 @@ async def change_client_status(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> ClientViewModel:
"""
- 变更 OAuth Client 启用状态
+ 变更 OAuth Client 启用状态。
:param db: 异步数据库会话
:param payload: Client 状态变更参数
@@ -735,7 +711,6 @@ async def change_client_status(
:param after_commit: 事务提交成功后执行的异步回调
:return: 更新后的 Client 详情
"""
-
return await cls._transaction(db, lambda: cls._change_status(db, payload, actor=actor), after_commit)
@classmethod
@@ -752,7 +727,7 @@ async def rotate_secret(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> ClientSecretResponseModel:
"""
- 轮换 OAuth Client Secret 并安排旧凭据退役
+ 轮换 OAuth Client Secret 并安排旧凭据退役。
:param db: 异步数据库会话
:param client_id: Client 公开标识
@@ -764,7 +739,6 @@ async def rotate_secret(
:param after_commit: 事务提交成功后执行的异步回调
:return: 只包含一次性明文的 Secret 响应
"""
-
return await cls._transaction(
db,
lambda: cls._rotate_secret(
@@ -791,7 +765,7 @@ async def revoke_secret(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> bool:
"""
- 撤销指定 Client Secret
+ 撤销指定 Client Secret。
:param db: 异步数据库会话
:param client_id: Client 公开标识
@@ -801,7 +775,6 @@ async def revoke_secret(
:param after_commit: 事务提交成功后执行的异步回调
:return: 本次是否发生状态变更
"""
-
return await cls._transaction(
db, lambda: cls._revoke_secret(db, client_id, secret_id, actor=actor, now=now), after_commit
)
@@ -818,7 +791,7 @@ async def add_uri(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> int:
"""
- 添加注册 URI
+ 添加注册 URI。
:param db: 异步数据库会话
:param client_id: Client 公开标识
@@ -828,7 +801,6 @@ async def add_uri(
:param after_commit: 事务提交成功后执行的异步回调
:return: 新增 URI 的内部标识
"""
-
return await cls._transaction(
db, lambda: cls._add_uri(db, client_id, payload, actor=actor, now=now), after_commit
)
@@ -845,7 +817,7 @@ async def remove_uri(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> bool:
"""
- 删除注册 URI
+ 删除注册 URI。
:param db: 异步数据库会话
:param client_id: Client 公开标识
@@ -855,7 +827,6 @@ async def remove_uri(
:param after_commit: 事务提交成功后执行的异步回调
:return: 本次是否发生状态变更
"""
-
return await cls._transaction(
db, lambda: cls._remove_uri(db, client_id, uri_id, actor=actor, now=now), after_commit
)
@@ -870,7 +841,7 @@ async def _create_client(
now: datetime | None = None,
) -> ClientViewModel:
"""
- 在事务中创建 Client ORM 记录及关联配置
+ 在事务中创建 Client ORM 记录及关联配置。
:param db: 异步数据库会话
:param payload: Client 创建参数
@@ -879,7 +850,6 @@ async def _create_client(
:return: ClientViewModel 详情
:raises OAuthClientManagementError: Client DTO 校验失败或公开标识已存在时抛出
"""
-
if not isinstance(payload, ClientCreateModel) or isinstance(payload, ClientUpdateModel):
raise OAuthClientManagementError('客户端创建参数必须为 ClientCreateModel')
actor_value, current = cls._actor(actor), cls._now(now)
@@ -912,7 +882,7 @@ async def _update_client(
now: datetime | None = None,
) -> ClientViewModel:
"""
- 在事务中更新 Client ORM 记录及关联配置
+ 在事务中更新 Client ORM 记录及关联配置。
:param db: 异步数据库会话
:param payload: Client 更新参数
@@ -921,7 +891,6 @@ async def _update_client(
:return: ClientViewModel 详情
:raises OAuthClientManagementError: Client 不存在、DTO 校验失败或策略绑定不合法时抛出
"""
-
if not isinstance(payload, ClientUpdateModel):
raise OAuthClientManagementError('客户端更新参数必须为 ClientUpdateModel')
actor_value, current = cls._actor(actor), cls._now(now)
@@ -956,13 +925,12 @@ async def _update_client(
@staticmethod
def _client_policy_changed(current: ClientViewModel, payload: ClientUpdateModel) -> bool:
"""
- 比较 Client 授权与令牌策略是否变化
+ 比较 Client 授权与令牌策略是否变化。
:param current: 当前客户端 ORM 记录
:param payload: Client 更新参数
:return: Client 授权或令牌策略是否发生变化
"""
-
scalar_fields = (
'client_type',
'token_endpoint_auth_method',
@@ -997,14 +965,13 @@ def _client_policy_changed(current: ClientViewModel, payload: ClientUpdateModel)
@classmethod
async def detail(cls, db: AsyncSession, client_id: str) -> ClientViewModel:
"""
- 查询 OAuth Client 详情
+ 查询 OAuth Client 详情。
:param db: 异步数据库会话
:param client_id: 客户端标识
:return: ClientViewModel 详情
:raises OAuthClientManagementError: Client 不存在时抛出
"""
-
detail_rows = await OAuthClientDao.get_client_detail_rows(db, client_id)
if detail_rows is None:
raise OAuthClientManagementError('客户端不存在')
@@ -1068,7 +1035,7 @@ async def _add_uri(
now: datetime | None = None,
) -> int:
"""
- 添加 Client 注册 URI
+ 添加 Client 注册 URI。
:param db: 异步数据库会话
:param client_id: 客户端标识
@@ -1078,7 +1045,6 @@ async def _add_uri(
:return: 新增 URI 的内部主键
:raises OAuthClientManagementError: Client 不存在或 URI 已注册时抛出
"""
-
actor_value, current = cls._actor(actor), cls._now(now)
client = await OAuthClientDao.get_by_client_id(db, client_id, active_only=False, for_update=True)
if client is None:
@@ -1117,7 +1083,7 @@ async def _remove_uri(
cls, db: AsyncSession, client_id: str, uri_id: int, *, actor: str, now: datetime | None = None
) -> bool:
"""
- 删除 Client 注册 URI
+ 删除 Client 注册 URI。
:param db: 异步数据库会话
:param client_id: 客户端标识
@@ -1127,7 +1093,6 @@ async def _remove_uri(
:return: 本次是否停用注册 URI
:raises OAuthClientManagementError: Client 不存在或注册 URI 不存在
"""
-
actor_value, current = cls._actor(actor), cls._now(now)
client = await OAuthClientDao.get_by_client_id(db, client_id, active_only=False, for_update=True)
if client is None:
@@ -1156,13 +1121,12 @@ async def _remove_uri(
@classmethod
async def list_clients(cls, db: AsyncSession, query: ClientPageQueryModel | None = None) -> list[ClientViewModel]:
"""
- 分页查询 OAuth Client
+ 分页查询 OAuth Client。
:param db: 异步数据库会话
:param query: Client 分页查询参数
:return: ClientViewModel 列表
"""
-
page = query or ClientPageQueryModel()
rows = await OAuthClientDao.list_clients_page(db, page)
@@ -1171,13 +1135,12 @@ async def list_clients(cls, db: AsyncSession, query: ClientPageQueryModel | None
@classmethod
async def count_clients(cls, db: AsyncSession, query: ClientPageQueryModel | None = None) -> int:
"""
- 统计 OAuth Client 数量
+ 统计 OAuth Client 数量。
:param db: 异步数据库会话
:param query: Client 分页统计参数
:return: Client 数量
"""
-
page = query or ClientPageQueryModel()
return await OAuthClientDao.count_clients(db, page)
@@ -1187,7 +1150,7 @@ async def _change_status(
cls, db: AsyncSession, payload: ClientStatusModel, *, actor: str, now: datetime | None = None
) -> ClientViewModel:
"""
- 在事务中变更 Client 状态
+ 在事务中变更 Client 状态。
:param db: 异步数据库会话
:param payload: Client 状态变更参数
@@ -1196,7 +1159,6 @@ async def _change_status(
:return: ClientViewModel 详情
:raises OAuthClientManagementError: Client 不存在或状态值不合法时抛出
"""
-
actor_value, current = cls._actor(actor), cls._now(now)
client = await OAuthClientDao.get_by_client_id(db, payload.client_id, active_only=False, for_update=True)
if client is None:
@@ -1222,7 +1184,7 @@ async def _soft_disable(
cls, db: AsyncSession, client_id: str, *, actor: str, now: datetime | None = None
) -> ClientViewModel:
"""
- 在事务中禁用 Client 并撤销凭据
+ 在事务中禁用 Client 并撤销凭据。
:param db: 异步数据库会话
:param client_id: 客户端标识
@@ -1230,7 +1192,6 @@ async def _soft_disable(
:param now: 当前时间
:return: ClientViewModel 详情
"""
-
return await cls._change_status(db, ClientStatusModel(client_id=client_id, status='1'), actor=actor, now=now)
@classmethod
@@ -1246,7 +1207,7 @@ async def _rotate_secret(
retirement_seconds: int | None = None,
) -> ClientSecretResponseModel:
"""
- 在事务中创建新的 Client Secret
+ 在事务中创建新的 Client Secret。
:param db: 异步数据库会话
:param client_id: 客户端标识
@@ -1258,7 +1219,6 @@ async def _rotate_secret(
:return: ClientSecretResponseModel(含一次性明文)
:raises OAuthClientManagementError: Client 不存在或 Secret 时效不合法时抛出
"""
-
actor_value, current = cls._actor(actor), cls._now(now)
retirement_ttl = retirement_seconds
if retirement_ttl is None:
@@ -1302,7 +1262,7 @@ async def _revoke_secret(
cls, db: AsyncSession, client_id: str, secret_id: str, *, actor: str, now: datetime | None = None
) -> bool:
"""
- 在事务中撤销 Client Secret
+ 在事务中撤销 Client Secret。
:param db: 异步数据库会话
:param client_id: 客户端标识
@@ -1312,7 +1272,6 @@ async def _revoke_secret(
:return: 本次是否撤销 Client Secret
:raises OAuthClientManagementError: Client Secret 不存在或已经撤销时抛出
"""
-
actor_value, current = cls._actor(actor), cls._now(now)
client = await OAuthClientDao.get_by_client_id(db, client_id, active_only=False, for_update=True)
if client is None:
@@ -1341,19 +1300,16 @@ async def _revoke_secret(
@staticmethod
async def list_active_cors_origins(db: AsyncSession) -> tuple[str, ...]:
"""
- 查询当前启用的 CORS Origin
+ 查询当前启用的 CORS Origin。
:param db: 异步数据库会话
:return: 启用的 CORS Origin 元组
"""
-
return await OAuthClientDao.list_cors_origins(db)
class OAuthResourceManagementService(OAuthManagementBaseService):
- """
- OAuth Resource 和 Scope 管理模块服务层
- """
+ """OAuth Resource 和 Scope 管理模块服务层。"""
@classmethod
async def create_resource(
@@ -1366,7 +1322,7 @@ async def create_resource(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> ResourceViewModel:
"""
- 创建 OAuth Resource 及其 Claim 配置
+ 创建 OAuth Resource 及其 Claim 配置。
:param db: 异步数据库会话
:param payload: Resource 创建参数
@@ -1375,7 +1331,6 @@ async def create_resource(
:param after_commit: 事务提交成功后执行的异步回调
:return: 创建后的 Resource 详情
"""
-
return await cls._transaction(
db,
lambda: cls._create_resource(db, payload, actor=actor, now=now),
@@ -1393,7 +1348,7 @@ async def update_resource(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> ResourceViewModel:
"""
- 更新 OAuth Resource 及其 Claim 配置
+ 更新 OAuth Resource 及其 Claim 配置。
:param db: 异步数据库会话
:param payload: Resource 更新参数
@@ -1402,7 +1357,6 @@ async def update_resource(
:param after_commit: 事务提交成功后执行的异步回调
:return: 更新后的 Resource 详情
"""
-
return await cls._transaction(
db,
lambda: cls._update_resource(db, payload, actor=actor, now=now),
@@ -1419,22 +1373,16 @@ async def disable_resources(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> None:
"""
- 禁用指定 OAuth Resource 并失效关联授权
+ 禁用指定 OAuth Resource 并失效关联授权。
:param db: 异步数据库会话
:param identifiers: Resource 公开标识列表
:param actor: 操作者标识
:param after_commit: 事务提交成功后执行的异步回调
- :return: None
"""
async def operation() -> None:
- """
- 在同一事务中批量禁用指定 Resource
-
- :return: None
- """
-
+ """在同一事务中批量禁用指定 Resource。"""
for identifier in identifiers:
await cls._soft_disable_resource(db, identifier, actor=actor)
@@ -1451,7 +1399,7 @@ async def change_resource_status(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> ResourceViewModel:
"""
- 变更 OAuth Resource 启用状态
+ 变更 OAuth Resource 启用状态。
:param db: 异步数据库会话
:param payload: Resource 状态变更参数
@@ -1460,7 +1408,6 @@ async def change_resource_status(
:param after_commit: 事务提交成功后执行的异步回调
:return: 更新后的 Resource 详情
"""
-
return await cls._transaction(
db, lambda: cls._change_resource_status(db, payload, actor=actor, now=now), after_commit
)
@@ -1476,7 +1423,7 @@ async def create_scope(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> ScopeModel:
"""
- 创建 OAuth Scope 及其 Resource 关联
+ 创建 OAuth Scope 及其 Resource 关联。
:param db: 异步数据库会话
:param payload: Scope 创建参数
@@ -1485,7 +1432,6 @@ async def create_scope(
:param after_commit: 事务提交成功后执行的异步回调
:return: 创建后的 Scope 详情
"""
-
return await cls._transaction(db, lambda: cls._create_scope(db, payload, actor=actor, now=now), after_commit)
@classmethod
@@ -1499,7 +1445,7 @@ async def update_scope(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> ScopeModel:
"""
- 更新 OAuth Scope 及其 Resource 关联
+ 更新 OAuth Scope 及其 Resource 关联。
:param db: 异步数据库会话
:param payload: Scope 更新参数
@@ -1508,7 +1454,6 @@ async def update_scope(
:param after_commit: 事务提交成功后执行的异步回调
:return: 更新后的 Scope 详情
"""
-
return await cls._transaction(db, lambda: cls._update_scope(db, payload, actor=actor, now=now), after_commit)
@classmethod
@@ -1521,22 +1466,16 @@ async def disable_scopes(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> None:
"""
- 禁用指定 OAuth Scope 并失效关联授权
+ 禁用指定 OAuth Scope 并失效关联授权。
:param db: 异步数据库会话
:param identifiers: Scope 编码列表
:param actor: 操作者标识
:param after_commit: 事务提交成功后执行的异步回调
- :return: None
"""
async def operation() -> None:
- """
- 在同一事务中批量禁用指定 Scope
-
- :return: None
- """
-
+ """在同一事务中批量禁用指定 Scope。"""
for identifier in identifiers:
await cls._soft_disable_scope(db, identifier, actor=actor)
@@ -1553,7 +1492,7 @@ async def change_scope_status(
after_commit: Callable[[], Awaitable[None]] | None = None,
) -> ScopeModel:
"""
- 变更 OAuth Scope 启用状态
+ 变更 OAuth Scope 启用状态。
:param db: 异步数据库会话
:param payload: Scope 状态变更参数
@@ -1562,7 +1501,6 @@ async def change_scope_status(
:param after_commit: 事务提交成功后执行的异步回调
:return: 更新后的 Scope 详情
"""
-
return await cls._transaction(
db, lambda: cls._change_scope_status(db, payload, actor=actor, now=now), after_commit
)
@@ -1577,7 +1515,7 @@ async def _create_resource(
now: datetime | None = None,
) -> ResourceViewModel:
"""
- 在事务中创建 Resource ORM 记录
+ 在事务中创建 Resource ORM 记录。
:param db: 异步数据库会话
:param payload: Resource 创建参数
@@ -1586,7 +1524,6 @@ async def _create_resource(
:return: ResourceViewModel 详情
:raises OAuthClientManagementError: Resource DTO 校验失败或 resource_id/audience 已存在时抛出
"""
-
if not isinstance(payload, ResourceCreateModel) or isinstance(payload, ResourceUpdateModel):
raise OAuthClientManagementError('资源创建参数必须为 ResourceCreateModel')
actor_value, current = cls._actor(actor), cls._now(now)
@@ -1630,7 +1567,7 @@ async def _update_resource(
now: datetime | None = None,
) -> ResourceViewModel:
"""
- 在事务中更新 Resource ORM 记录
+ 在事务中更新 Resource ORM 记录。
:param db: 异步数据库会话
:param payload: Resource 更新参数
@@ -1639,7 +1576,6 @@ async def _update_resource(
:return: ResourceViewModel 详情
:raises OAuthClientManagementError: Resource 不存在、DTO 校验失败或关联 Client 不存在时抛出
"""
-
if not isinstance(payload, ResourceUpdateModel):
raise OAuthClientManagementError('资源更新参数必须为 ResourceUpdateModel')
actor_value, current = cls._actor(actor), cls._now(now)
@@ -1689,14 +1625,13 @@ async def _update_resource(
@classmethod
async def detail_resource(cls, db: AsyncSession, resource_id: str) -> ResourceViewModel:
"""
- 查询 OAuth Resource 详情
+ 查询 OAuth Resource 详情。
:param db: 异步数据库会话
:param resource_id: 资源标识
:return: ResourceViewModel 详情
:raises OAuthClientManagementError: Resource 不存在时抛出
"""
-
resource = await OAuthResourceDao.get_resource(db, resource_id)
if resource is None:
raise OAuthClientManagementError('资源不存在')
@@ -1712,13 +1647,12 @@ async def list_resources(
cls, db: AsyncSession, query: ResourcePageQueryModel | None = None
) -> list[ResourceViewModel]:
"""
- 分页查询 OAuth Resource
+ 分页查询 OAuth Resource。
:param db: 异步数据库会话
:param query: Resource 分页查询参数
:return: ResourceViewModel 列表
"""
-
page = query or ResourcePageQueryModel()
rows = await OAuthResourceDao.list_resources_page(db, page)
@@ -1727,13 +1661,12 @@ async def list_resources(
@classmethod
async def count_resources(cls, db: AsyncSession, query: ResourcePageQueryModel | None = None) -> int:
"""
- 统计 OAuth Resource 数量
+ 统计 OAuth Resource 数量。
:param db: 异步数据库会话
:param query: Resource 分页统计参数
:return: Resource 数量
"""
-
page = query or ResourcePageQueryModel()
return await OAuthResourceDao.count_resources(db, page)
@@ -1743,7 +1676,7 @@ async def _change_resource_status(
cls, db: AsyncSession, payload: ResourceStatusModel, *, actor: str, now: datetime | None = None
) -> ResourceViewModel:
"""
- 在事务中变更 Resource 状态
+ 在事务中变更 Resource 状态。
:param db: 异步数据库会话
:param payload: Resource 状态变更参数
@@ -1752,7 +1685,6 @@ async def _change_resource_status(
:return: ResourceViewModel 详情
:raises OAuthClientManagementError: Resource 不存在或状态值不合法时抛出
"""
-
actor_value, current = cls._actor(actor), cls._now(now)
resource = await OAuthResourceDao.get_resource(db, payload.resource_id, for_update=True)
if resource is None:
@@ -1777,7 +1709,7 @@ async def _soft_disable_resource(
cls, db: AsyncSession, resource_id: str, *, actor: str, now: datetime | None = None
) -> ResourceViewModel:
"""
- 在事务中禁用 Resource 并失效关联授权
+ 在事务中禁用 Resource 并失效关联授权。
:param db: 异步数据库会话
:param resource_id: 资源标识
@@ -1785,7 +1717,6 @@ async def _soft_disable_resource(
:param now: 当前时间
:return: ResourceViewModel 详情
"""
-
return await cls._change_resource_status(
db, ResourceStatusModel(resource_id=resource_id, status='1'), actor=actor, now=now
)
@@ -1795,7 +1726,7 @@ async def _create_scope(
cls, db: AsyncSession, payload: ScopeModel, *, actor: str, now: datetime | None = None
) -> ScopeModel:
"""
- 在事务中创建 Scope ORM 记录
+ 在事务中创建 Scope ORM 记录。
:param db: 异步数据库会话
:param payload: Scope 创建参数
@@ -1804,7 +1735,6 @@ async def _create_scope(
:return: ScopeModel 详情
:raises OAuthClientManagementError: Scope DTO 校验失败、编码重复或关联 Resource 不存在时抛出
"""
-
actor_value, current = cls._actor(actor), cls._now(now)
claims = cls._validate_claims(payload.claims)
if payload.scope_code == 'openid' and (
@@ -1844,14 +1774,13 @@ async def _create_scope(
@classmethod
async def _get_active_resource(cls, db: AsyncSession, resource_id: str | None) -> SysOAuthResource:
"""
- 查询启用的 Resource ORM 记录
+ 查询启用的 Resource ORM 记录。
:param db: 异步数据库会话
:param resource_id: 资源标识
:return: 启用的 Resource ORM 记录
:raises OAuthClientManagementError: Resource 标识为空、未知或 Resource 未启用时抛出
"""
-
if not resource_id:
raise OAuthClientManagementError('资源权限必须绑定已启用的资源')
resource = await OAuthResourceDao.active_resource(db, resource_id)
@@ -1864,7 +1793,7 @@ async def _update_scope(
cls, db: AsyncSession, payload: ScopeModel, *, actor: str, now: datetime | None = None
) -> ScopeModel:
"""
- 在事务中更新 Scope ORM 记录
+ 在事务中更新 Scope ORM 记录。
:param db: 异步数据库会话
:param payload: Scope 更新参数
@@ -1873,7 +1802,6 @@ async def _update_scope(
:return: ScopeModel 详情
:raises OAuthClientManagementError: Scope 不存在、DTO 校验失败或关联 Resource 不存在时抛出
"""
-
actor_value, current = cls._actor(actor), cls._now(now)
claims = cls._validate_claims(payload.claims)
scope = await OAuthResourceDao.get_scope(db, payload.scope_code, for_update=True)
@@ -1920,26 +1848,24 @@ async def _update_scope(
@classmethod
async def _lock_scope_clients(cls, db: AsyncSession, scope_pk: int) -> list[SysOAuthClient]:
"""
- 锁定关联 Scope 的 Client 记录
+ 锁定关联 Scope 的 Client 记录。
:param db: 异步数据库会话
:param scope_pk: Scope 主键
:return: 已锁定的 Client ORM 记录列表
"""
-
return list(await OAuthResourceDao.lock_scope_clients(db, scope_pk))
@classmethod
async def detail_scope(cls, db: AsyncSession, scope_code: str) -> ScopeModel:
"""
- 查询 OAuth Scope 详情
+ 查询 OAuth Scope 详情。
:param db: 异步数据库会话
:param scope_code: Scope 编码
:return: ScopeModel 详情
:raises OAuthClientManagementError: Scope 不存在时抛出
"""
-
scope = await OAuthResourceDao.get_scope(db, scope_code)
if scope is None:
raise OAuthClientManagementError('权限范围不存在')
@@ -1951,13 +1877,12 @@ async def detail_scope(cls, db: AsyncSession, scope_code: str) -> ScopeModel:
@classmethod
async def list_scopes(cls, db: AsyncSession, query: ScopePageQueryModel | None = None) -> list[ScopeModel]:
"""
- 分页查询 OAuth Scope
+ 分页查询 OAuth Scope。
:param db: 异步数据库会话
:param query: Scope 分页查询参数
:return: ScopeModel 列表
"""
-
page = query or ScopePageQueryModel()
rows = await OAuthResourceDao.list_scopes_page(db, page)
@@ -1966,13 +1891,12 @@ async def list_scopes(cls, db: AsyncSession, query: ScopePageQueryModel | None =
@classmethod
async def count_scopes(cls, db: AsyncSession, query: ScopePageQueryModel | None = None) -> int:
"""
- 统计 OAuth Scope 数量
+ 统计 OAuth Scope 数量。
:param db: 异步数据库会话
:param query: Scope 分页统计参数
:return: Scope 数量
"""
-
page = query or ScopePageQueryModel()
return await OAuthResourceDao.count_scopes(db, page)
@@ -1982,7 +1906,7 @@ async def _change_scope_status(
cls, db: AsyncSession, payload: ScopeStatusModel, *, actor: str, now: datetime | None = None
) -> ScopeModel:
"""
- 在事务中变更 Scope 状态
+ 在事务中变更 Scope 状态。
:param db: 异步数据库会话
:param payload: Scope 状态变更参数
@@ -1991,7 +1915,6 @@ async def _change_scope_status(
:return: ScopeModel 详情
:raises OAuthClientManagementError: Scope 不存在或状态值不合法时抛出
"""
-
actor_value, current = cls._actor(actor), cls._now(now)
scope = await OAuthResourceDao.get_scope(db, payload.scope_code, for_update=True)
if scope is None:
@@ -2014,7 +1937,7 @@ async def _soft_disable_scope(
cls, db: AsyncSession, scope_code: str, *, actor: str, now: datetime | None = None
) -> ScopeModel:
"""
- 在事务中禁用 Scope 并失效关联授权
+ 在事务中禁用 Scope 并失效关联授权。
:param db: 异步数据库会话
:param scope_code: Scope 编码
@@ -2022,7 +1945,6 @@ async def _soft_disable_scope(
:param now: 当前时间
:return: ScopeModel 详情
"""
-
return await cls._change_scope_status(
db, ScopeStatusModel(scope_code=scope_code, status='1'), actor=actor, now=now
)
@@ -2032,14 +1954,13 @@ async def collect_resource_invalidation_targets(
cls, db: AsyncSession, resource_id: str
) -> ResourceInvalidationTargets:
"""
- 收集 Resource 变更后需撤销的授权记录
+ 收集 Resource 变更后需撤销的授权记录。
:param db: 异步数据库会话
:param resource_id: 资源标识
:return: Resource 失效目标集合
:raises OAuthClientManagementError: Resource 不存在时抛出
"""
-
resource = await OAuthResourceDao.get_resource(db, resource_id)
if resource is None:
raise OAuthClientManagementError('资源不存在')
diff --git a/ruoyi-fastapi-backend/module_identity/service/oauth_session_management_service.py b/ruoyi-fastapi-backend/module_identity/service/oauth_session_management_service.py
index 53d994aba..3a327cb48 100644
--- a/ruoyi-fastapi-backend/module_identity/service/oauth_session_management_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/oauth_session_management_service.py
@@ -24,19 +24,16 @@
class OAuthSessionManagementService:
- """
- OAuth Session 管理模块服务层
- """
+ """OAuth Session 管理模块服务层。"""
@staticmethod
def session_view(row: SysSsoSession) -> SsoSessionModel:
"""
- 将 SSO Session ORM 记录转换为 SsoSessionModel
+ 将 SSO Session ORM 记录转换为 SsoSessionModel。
:param row: SSO Session ORM 记录
:return: Session 管理视图
"""
-
status = row.status
if (
status == 'active'
@@ -66,14 +63,13 @@ def session_view(row: SysSsoSession) -> SsoSessionModel:
@staticmethod
def grant_view(row: SysOAuthGrant, client_id: str | None, policy: SysOAuthAccessPolicy | None = None) -> GrantModel:
"""
- 将 OAuth Grant ORM 记录转换为 GrantModel
+ 将 OAuth Grant ORM 记录转换为 GrantModel。
:param row: OAuth Grant ORM 记录
:param client_id: 客户端标识
:param policy: 当前用户对应用的独立访问策略
:return: Grant 管理视图
"""
-
status = row.status
if (
status == 'active'
@@ -103,13 +99,12 @@ def grant_view(row: SysOAuthGrant, client_id: str | None, policy: SysOAuthAccess
@staticmethod
async def list_sessions(db: AsyncSession, query: SessionPageQueryModel) -> tuple[list[SsoSessionModel], int]:
"""
- 分页查询 SSO Session
+ 分页查询 SSO Session。
:param db: 异步数据库会话
:param query: Session 分页查询参数
:return: Session 管理视图列表和总数
"""
-
rows = await SsoSessionDao.list_page(
db,
user_id=query.user_id,
@@ -140,13 +135,12 @@ async def list_sessions(db: AsyncSession, query: SessionPageQueryModel) -> tuple
@staticmethod
async def get_session(db: AsyncSession, sid: str) -> SsoSessionModel | None:
"""
- 按 sid 查询 SSO Session
+ 按 sid 查询 SSO Session。
:param db: 异步数据库会话
:param sid: Session 标识
:return: Session 管理视图,不存在时返回 None
"""
-
row = await SsoSessionDao.get_by_sid(db, sid)
if row is None:
return None
@@ -157,13 +151,12 @@ async def get_session(db: AsyncSession, sid: str) -> SsoSessionModel | None:
@staticmethod
async def list_grants(db: AsyncSession, query: GrantPageQueryModel) -> tuple[list[GrantModel], int]:
"""
- 分页查询 OAuth Grant
+ 分页查询 OAuth Grant。
:param db: 异步数据库会话
:param query: Grant 分页查询参数
:return: Grant 管理视图列表和总数
"""
-
rows = await OAuthGrantDao.list_page(
db,
user_id=query.user_id,
@@ -195,13 +188,12 @@ async def list_access_policies(
db: AsyncSession, query: AccessPolicyPageQueryModel
) -> tuple[list[AccessPolicyModel], int]:
"""
- 查询独立访问策略,包含尚未授权过的用户与应用
+ 查询独立访问策略,包含尚未授权过的用户与应用。
:param db: 异步数据库会话
:param query: 访问策略分页查询参数
:return: 访问策略管理视图列表和总数
"""
-
rows = await OAuthAccessPolicyDao.list_page(db, query)
total = await OAuthAccessPolicyDao.count(db, query)
return [
@@ -221,13 +213,12 @@ async def list_access_policies(
@staticmethod
async def get_grant(db: AsyncSession, grant_id: str) -> GrantModel | None:
"""
- 按 grant_id 查询 OAuth Grant
+ 按 grant_id 查询 OAuth Grant。
:param db: 异步数据库会话
:param grant_id: Grant 标识
:return: Grant 管理视图,不存在时返回 None
"""
-
row = await OAuthGrantDao.get_by_grant_id(db, grant_id)
if row is None:
return None
@@ -239,7 +230,7 @@ async def get_grant(db: AsyncSession, grant_id: str) -> GrantModel | None:
@staticmethod
async def revoke_user(db: AsyncSession, redis: Redis, user_id: int, actor: str, reason: str) -> int:
"""
- 撤销用户全部在线及自然过期的 SSO Session
+ 撤销用户全部在线及自然过期的 SSO Session。
:param db: 异步数据库会话
:param redis: SSO Session 热缓存客户端
@@ -249,7 +240,6 @@ async def revoke_user(db: AsyncSession, redis: Redis, user_id: int, actor: str,
:return: 实际发生状态变更的 Session 数量
:raises ServiceException: 撤销用户 Session 事务失败
"""
-
coordinator = AfterCommitCoordinator()
try:
count = await SsoSessionService.revoke_user(db, redis, user_id, reason=reason, coordinator=coordinator)
@@ -269,7 +259,7 @@ async def revoke_user(db: AsyncSession, redis: Redis, user_id: int, actor: str,
@staticmethod
async def revoke_sessions(db: AsyncSession, redis: Redis, sids: list[str], actor: str, reason: str) -> int:
"""
- 按 sid 集合撤销 SSO Session
+ 按 sid 集合撤销 SSO Session。
:param db: 异步数据库会话
:param redis: SSO Session 热缓存客户端
@@ -279,7 +269,6 @@ async def revoke_sessions(db: AsyncSession, redis: Redis, sids: list[str], actor
:return: 实际发生状态变更的 Session 数量
:raises ServiceException: 批量撤销指定 Session 事务失败
"""
-
coordinator, count = AfterCommitCoordinator(), 0
try:
for sid in sids:
@@ -302,7 +291,7 @@ async def revoke_sessions(db: AsyncSession, redis: Redis, sids: list[str], actor
@staticmethod
async def revoke_grants(db: AsyncSession, grant_ids: list[str], actor: str, reason: str) -> int:
"""
- 撤销选中记录所属用户对应用的全部现有授权
+ 撤销选中记录所属用户对应用的全部现有授权。
:param db: 异步数据库会话
:param grant_ids: 用于确定用户和应用的 Grant 标识集合
@@ -311,7 +300,6 @@ async def revoke_grants(db: AsyncSession, grant_ids: list[str], actor: str, reas
:return: 实际撤销的 Grant 数量
:raises ServiceException: 批量撤销 Grant 事务失败
"""
-
try:
count = 0
for client_pk, user_id in await OAuthGrantDao.targets(db, grant_ids):
@@ -338,7 +326,7 @@ async def revoke_grants(db: AsyncSession, grant_ids: list[str], actor: str, reas
@staticmethod
async def set_access(db: AsyncSession, user_id: int, client_id: str, blocked: bool, actor: str, reason: str) -> int:
"""
- 更新用户对应用的访问策略,禁止时撤销全部授权,解除时保留撤销状态
+ 更新用户对应用的访问策略,禁止时撤销全部授权,解除时保留撤销状态。
:param db: 异步数据库会话
:param user_id: 用户编号
@@ -349,7 +337,6 @@ async def set_access(db: AsyncSession, user_id: int, client_id: str, blocked: bo
:return: 本次撤销的授权数量
:raises ServiceException: 用户或应用不存在,或事务失败
"""
-
try:
client = await OAuthClientDao.get_by_client_id(db, client_id)
user = await IdentityUserDao.get_user(db, user_id)
diff --git a/ruoyi-fastapi-backend/module_identity/service/runtime_service.py b/ruoyi-fastapi-backend/module_identity/service/runtime_service.py
index 9f16029bf..95cb37868 100644
--- a/ruoyi-fastapi-backend/module_identity/service/runtime_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/runtime_service.py
@@ -23,11 +23,16 @@
@dataclass(frozen=True, slots=True)
class OidcReadiness:
"""
- OIDC 协议运行时就绪快照
+ OIDC 协议运行时就绪快照。
``enabled`` 只表示部署配置已开启协议,``ready`` 还要求数据库中
存在可加载的 active 签名密钥。两者分离后,管理后台可以在协议
尚未就绪时继续启动并完成首把密钥初始化。
+
+ :ivar enabled: 是否启用该项功能
+ :ivar ready: 依赖检查是否已就绪
+ :ivar reason: 作出该决定或状态变化的原因
+ :ivar checked_at: 最近一次执行检查的时间
"""
enabled: bool
@@ -37,11 +42,10 @@ class OidcReadiness:
def as_dict(self) -> dict[str, object]:
"""
- 转换为可安全返回给管理端的状态字段
+ 转换为可安全返回给管理端的状态字段。
:return: OIDC 运行时状态字段映射
"""
-
return {
'enabled': self.enabled,
'ready': self.ready,
@@ -52,7 +56,12 @@ def as_dict(self) -> dict[str, object]:
class OidcRuntimeService:
"""
- OIDC 运行时模块服务层
+ OIDC 运行时模块服务层。
+
+ :cvar _AUDIT_ARCHIVE_INTERVAL_SECONDS: 审计归档间隔(秒)
+ :cvar _READINESS_CACHE_SECONDS: 就绪状态的缓存时长(秒)
+ :cvar _CORS_CACHE_SECONDS: 跨域规则的缓存时长(秒)
+ :cvar _CORS_VERSION_KEY: 标记跨域配置版本的 Redis 键
"""
_AUDIT_ARCHIVE_INTERVAL_SECONDS = 86400
@@ -63,11 +72,10 @@ class OidcRuntimeService:
@staticmethod
def _disabled_readiness() -> OidcReadiness:
"""
- 构造 OIDC 协议关闭状态
+ 构造 OIDC 协议关闭状态。
:return: OIDC 协议关闭时的就绪快照
"""
-
return OidcReadiness(
enabled=False,
ready=False,
@@ -78,7 +86,7 @@ def _disabled_readiness() -> OidcReadiness:
@classmethod
async def inspect_readiness(cls, db: AsyncSession) -> OidcReadiness:
"""
- 检查 OIDC 是否具备对外提供协议服务的签名能力
+ 检查 OIDC 是否具备对外提供协议服务的签名能力。
密钥不存在或密钥材料不可用都会被收敛为未就绪状态,不会影响
管理后台启动;数据库基础设施异常仍向上抛出,由应用通用健康
@@ -87,7 +95,6 @@ async def inspect_readiness(cls, db: AsyncSession) -> OidcReadiness:
:param db: 异步数据库会话
:return: OIDC 运行时就绪快照
"""
-
if not OidcConfig.oidc_enabled:
return cls._disabled_readiness()
try:
@@ -109,13 +116,12 @@ async def inspect_readiness(cls, db: AsyncSession) -> OidcReadiness:
@classmethod
async def refresh_readiness(cls, app: FastAPI, db: AsyncSession | None = None) -> OidcReadiness:
"""
- 刷新并保存当前 Worker 的 OIDC 就绪快照
+ 刷新并保存当前 Worker 的 OIDC 就绪快照。
:param app: FastAPI 应用
:param db: 可复用的异步数据库会话
:return: 刷新后的 OIDC 运行时就绪快照
"""
-
if not OidcConfig.oidc_enabled:
readiness = cls._disabled_readiness()
elif db is not None:
@@ -130,7 +136,7 @@ async def refresh_readiness(cls, app: FastAPI, db: AsyncSession | None = None) -
@classmethod
async def cached_readiness(cls, app: FastAPI, db: AsyncSession) -> OidcReadiness:
"""
- 读取带短时缓存的 OIDC 就绪状态
+ 读取带短时缓存的 OIDC 就绪状态。
缓存避免每个协议请求都重复解密私钥;未就绪状态也会很快重新
检查,因此其他 Worker 在首把密钥激活后无需重启即可恢复。
@@ -139,7 +145,6 @@ async def cached_readiness(cls, app: FastAPI, db: AsyncSession) -> OidcReadiness
:param db: 异步数据库会话
:return: 当前 Worker 的 OIDC 运行时就绪快照
"""
-
current = TimezoneUtil.utc_now()
readiness = getattr(app.state, 'oidc_readiness', None)
if isinstance(readiness, OidcReadiness):
@@ -162,7 +167,7 @@ async def cached_readiness(cls, app: FastAPI, db: AsyncSession) -> OidcReadiness
@classmethod
async def validate_runtime(cls, app: FastAPI | None = None) -> OidcReadiness:
"""
- 检查启动阶段的 OIDC 就绪状态,但不阻断管理后台启动
+ 检查启动阶段的 OIDC 就绪状态,但不阻断管理后台启动。
协议启用但尚无 active 密钥时记录明确告警,公共 OIDC 端点随后
返回 503;管理员仍可登录后台创建并激活首把密钥。
@@ -170,7 +175,6 @@ async def validate_runtime(cls, app: FastAPI | None = None) -> OidcReadiness:
:param app: 需要保存就绪快照的 FastAPI 应用
:return: 启动阶段的 OIDC 运行时就绪快照
"""
-
if not OidcConfig.oidc_enabled:
readiness = cls._disabled_readiness()
else:
@@ -186,11 +190,10 @@ async def validate_runtime(cls, app: FastAPI | None = None) -> OidcReadiness:
@staticmethod
async def load_cors_origins() -> tuple[str, ...]:
"""
- 加载启用的 CORS Origin
+ 加载启用的 CORS Origin。
:return: 启用的 CORS Origin 元组
"""
-
async with DataSourceRegistry.session() as db:
origins = await OAuthClientManagementService.list_active_cors_origins(db)
return tuple(origins)
@@ -198,12 +201,11 @@ async def load_cors_origins() -> tuple[str, ...]:
@classmethod
async def refresh_cors_snapshot(cls, app: FastAPI) -> tuple[str, ...]:
"""
- 刷新应用的 CORS Origin 快照
+ 刷新应用的 CORS Origin 快照。
:param app: FastAPI 应用
:return: 刷新后的 CORS Origin 元组
"""
-
if not OidcConfig.oidc_enabled:
app.state.oidc_registered_cors_origins = ()
return ()
@@ -216,14 +218,12 @@ async def refresh_cors_snapshot(cls, app: FastAPI) -> tuple[str, ...]:
@classmethod
async def ensure_cors_snapshot(cls, app: FastAPI) -> None:
"""
- 刷新当前Worker的客户端跨域策略快照
+ 刷新当前Worker的客户端跨域策略快照。
通过共享版本号发现变更,并以有时限的数据库缓存兜底。
:param app: FastAPI应用对象
- :return: 无
"""
-
if not OidcConfig.oidc_enabled:
app.state.oidc_registered_cors_origins = ()
return
@@ -257,19 +257,14 @@ async def ensure_cors_snapshot(cls, app: FastAPI) -> None:
@classmethod
def cors_snapshot_callback(cls, app: FastAPI) -> Callable[[], Awaitable[None]]:
"""
- 构造提交后刷新 CORS 快照的回调
+ 构造提交后刷新 CORS 快照的回调。
:param app: 需要更新 CORS Origin 快照的 FastAPI 应用
:return: 无参数异步 CORS 快照刷新回调
"""
async def refresh() -> None:
- """
- 刷新应用 CORS Origin 快照
-
- :return: None
- """
-
+ """刷新应用 CORS Origin 快照。"""
redis = getattr(app.state, 'redis', None)
try:
if redis is not None:
@@ -284,12 +279,10 @@ async def refresh() -> None:
@classmethod
async def start_background_tasks(cls, app: FastAPI) -> None:
"""
- 每个 Worker 启动待命循环,仅当前 Leader 执行业务;重新获租后自动恢复
+ 每个 Worker 启动待命循环,仅当前 Leader 执行业务;重新获租后自动恢复。
:param app: FastAPI 应用
- :return: None
"""
-
redis = app.state.redis
app.state.oidc_key_lifecycle_task = (
asyncio.create_task(cls.key_lifecycle_loop(app)) if OidcConfig.oidc_enabled else None
@@ -301,12 +294,11 @@ async def start_background_tasks(cls, app: FastAPI) -> None:
@classmethod
async def key_lifecycle_loop(cls, app: FastAPI) -> None:
"""
- 运行签名密钥生命周期后台循环
+ 运行签名密钥生命周期后台循环。
:param app: FastAPI 应用,包含 Redis 与 OIDC 就绪状态
- :return: None
+ :raises asyncio.CancelledError: 异步操作被取消时
"""
-
last_archive_at: datetime | None = None
redis = app.state.redis
while True:
@@ -344,12 +336,11 @@ async def key_lifecycle_loop(cls, app: FastAPI) -> None:
@staticmethod
async def backchannel_retry_loop(redis: object) -> None:
"""
- 运行 Back-Channel 重试后台循环
+ 运行 Back-Channel 重试后台循环。
:param redis: 异步 Redis 客户端
- :return: None
+ :raises asyncio.CancelledError: 异步操作被取消时
"""
-
while True:
await asyncio.sleep(1)
if not SchedulerManager.is_application_leader():
@@ -365,12 +356,10 @@ async def backchannel_retry_loop(redis: object) -> None:
@staticmethod
async def stop_background_tasks(app: FastAPI) -> None:
"""
- 停止 OIDC 后台任务
+ 停止 OIDC 后台任务。
:param app: FastAPI 应用
- :return: None
"""
-
for name in ('oidc_key_lifecycle_task', 'oidc_backchannel_retry_task'):
task = getattr(app.state, name, None)
if task is None:
diff --git a/ruoyi-fastapi-backend/module_identity/service/session_service.py b/ruoyi-fastapi-backend/module_identity/service/session_service.py
index a731ba7e6..483580ca1 100644
--- a/ruoyi-fastapi-backend/module_identity/service/session_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/session_service.py
@@ -61,15 +61,27 @@
class SsoSessionError(ValueError):
- """
- SSO Session 创建、校验和撤销错误类型
- """
+ """SSO Session 创建、校验和撤销错误类型。"""
@dataclass(frozen=True)
class SsoSessionSnapshot:
"""
- 记录 SSO Session 缓存所需的不可变字段
+ 记录 SSO Session 缓存所需的不可变字段。
+
+ :ivar sid: 关联的单点登录会话标识
+ :ivar user_id: 用户的唯一标识
+ :ivar subject_id: 身份主体的唯一标识
+ :ivar auth_version: 创建时的身份安全版本
+ :ivar auth_time: 用户认证时间
+ :ivar last_seen_at: 会话最近活动时间
+ :ivar idle_expires_at: 闲置过期时间
+ :ivar absolute_expires_at: Session 绝对过期时间
+ :ivar acr: 认证上下文
+ :ivar amr: 认证方式列表
+ :ivar remember_me: 是否使用 remember-me 绝对 TTL
+ :ivar status: 操作或记录所处的状态
+ :ivar session_secret_hash: 会话密钥单向计算后的哈希
"""
sid: str
@@ -88,20 +100,17 @@ class SsoSessionSnapshot:
class SsoSessionService:
- """
- OIDC SSO Session 模块服务层
- """
+ """OIDC SSO Session 模块服务层。"""
@staticmethod
def _require_coordinator(coordinator: AfterCommitCoordinator | None) -> AfterCommitCoordinator:
"""
- 确认提交后副作用协调器可用
+ 确认提交后副作用协调器可用。
:param coordinator: 只登记提交后副作用的协调器
:return: 通过校验的协调器
:raises SsoSessionError: 未提供有效协调器
"""
-
if not isinstance(coordinator, AfterCommitCoordinator):
raise SsoSessionError('缺少事务提交后副作用协调器')
return coordinator
@@ -109,12 +118,10 @@ def _require_coordinator(coordinator: AfterCommitCoordinator | None) -> AfterCom
@staticmethod
def _validate_config_ttls() -> None:
"""
- 检查会话相关 TTL 配置均为正整数
+ 检查会话相关 TTL 配置均为正整数。
- :return: None
:raises SsoSessionError: TTL 不是正整数
"""
-
for field_name in _SESSION_TTL_FIELDS:
value = getattr(OidcConfig, field_name, None)
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
@@ -123,14 +130,13 @@ def _validate_config_ttls() -> None:
@staticmethod
def _remaining_ttl(absolute_expires_at: datetime, now: datetime) -> int:
"""
- 根据绝对过期时间计算 Redis 缓存剩余 TTL
+ 根据绝对过期时间计算 Redis 缓存剩余 TTL。
:param absolute_expires_at: Session 绝对过期时间
:param now: 当前项目时间
:return: 至少一秒的 Redis TTL
:raises SsoSessionError: Session 已过期
"""
-
seconds = int((absolute_expires_at - now).total_seconds())
if seconds < _SESSION_CACHE_TTL_FLOOR:
raise SsoSessionError('会话已过期')
@@ -139,12 +145,11 @@ def _remaining_ttl(absolute_expires_at: datetime, now: datetime) -> int:
@classmethod
def _snapshot(cls, row: SysSsoSession) -> SsoSessionSnapshot:
"""
- 从 ORM 行提取不依赖数据库会话的 Session 快照
+ 从 ORM 行提取不依赖数据库会话的 Session 快照。
:param row: 数据库 Session ORM 行
:return: 不再依赖 ORM 生命周期的 Session 快照
"""
-
return SsoSessionSnapshot(
sid=row.sid,
user_id=row.user_id,
@@ -164,12 +169,11 @@ def _snapshot(cls, row: SysSsoSession) -> SsoSessionSnapshot:
@classmethod
def _cache_payload(cls, row: SsoSessionSnapshot) -> dict[str, Any]:
"""
- 将 Session 快照编码为 Redis 缓存载荷
+ 将 Session 快照编码为 Redis 缓存载荷。
:param row: 数据库 Session
:return: 可 JSON 序列化的缓存摘要
"""
-
return {
'sid': row.sid,
'user_id': row.user_id,
@@ -196,14 +200,12 @@ def _cache_payload(cls, row: SsoSessionSnapshot) -> dict[str, Any]:
@classmethod
async def _cache_row(cls, redis: Redis, row: SsoSessionSnapshot, now: datetime) -> None:
"""
- 将 Session 快照写入会话、Cookie 和用户索引缓存
+ 将 Session 快照写入会话、Cookie 和用户索引缓存。
:param redis: 异步 Redis 客户端
:param row: SSO Session 快照
:param now: 当前时间
- :return: None
"""
-
ttl = cls._remaining_ttl(TimezoneUtil.to_optional_utc(row.absolute_expires_at) or now, now)
payload = json.dumps(cls._cache_payload(row), ensure_ascii=False, separators=(',', ':'))
await redis.set(OidcRedisKey.sso_session(row.sid), payload, ex=ttl)
@@ -217,14 +219,12 @@ async def _cache_row(cls, redis: Redis, row: SsoSessionSnapshot, now: datetime)
@classmethod
async def _clear_cache(cls, redis: Redis, row: SsoSessionSnapshot, extra_secret_hash: str | None = None) -> None:
"""
- 删除 Session、Cookie 和用户索引缓存
+ 删除 Session、Cookie 和用户索引缓存。
:param redis: 异步 Redis 客户端
:param row: SSO Session 快照
:param extra_secret_hash: 需要额外清理的 Cookie Secret 摘要
- :return: None
"""
-
hashes = {row.session_secret_hash}
if extra_secret_hash:
hashes.add(extra_secret_hash)
@@ -236,14 +236,12 @@ async def _clear_cache(cls, redis: Redis, row: SsoSessionSnapshot, extra_secret_
@classmethod
async def _publish_revoked(cls, redis: Redis, sid: str, reason: str) -> None:
"""
- 发布 Session 已撤销事件
+ 发布 Session 已撤销事件。
:param redis: 异步 Redis 客户端
:param sid: Session 标识
:param reason: 撤销原因
- :return: None
"""
-
await redis.publish(
OidcRedisKey.event_session_revoked(),
json.dumps({'event': 'session_revoked', 'sid': sid, 'reason': reason}, separators=(',', ':')),
@@ -259,15 +257,13 @@ async def _best_effort_cleanup(
reason: str | None = None,
) -> None:
"""
- 尽力清理 Session 缓存并发布撤销事件
+ 尽力清理 Session 缓存并发布撤销事件。
:param redis: 异步 Redis 客户端
:param row: SSO Session 快照
:param presented_digest: 当前 Cookie 摘要
:param reason: 撤销原因
- :return: None
"""
-
try:
await cls._clear_cache(redis, row, presented_digest)
except Exception:
@@ -297,7 +293,7 @@ async def create( # noqa: PLR0913
coordinator: AfterCommitCoordinator | None = None,
) -> tuple[str, SysSsoSession]:
"""
- 校验身份状态并创建 SSO Session 与 Cookie
+ 校验身份状态并创建 SSO Session 与 Cookie。
:param db: 异步数据库会话,调用方负责提交事务
:param redis: Redis 热缓存客户端
@@ -309,13 +305,12 @@ async def create( # noqa: PLR0913
:param ip_address: 登录来源 IP
:param user_agent: 登录 User-Agent,仅保存摘要
:param remember_me: 是否使用 remember-me 绝对 TTL
- :param pepper: OIDC Token Pepper
+ :param pepper: 用于 OIDC 令牌摘要的独立密钥
:param now: 可注入当前项目时间
:param coordinator: 必须由调用方在数据库提交成功后执行缓存写入
:return: ``(Cookie 原文, 数据库 Session)``
:raises SsoSessionError: Session 状态或事务操作不符合要求
"""
-
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
coordinator = cls._require_coordinator(coordinator)
cls._validate_config_ttls()
@@ -383,12 +378,7 @@ async def create( # noqa: PLR0913
snapshot = cls._snapshot(row)
async def cache_after_commit() -> None:
- """
- 在事务提交后写入新建 Session 的缓存
-
- :return: None
- """
-
+ """在事务提交后写入新建 Session 的缓存。"""
try:
await cls._cache_row(redis, snapshot, current)
except Exception:
@@ -401,7 +391,7 @@ async def cache_after_commit() -> None:
@classmethod
async def validate_logout_cookie(cls, db: AsyncSession, cookie: str) -> SysSsoSession:
"""
- 校验退出确认时的浏览器会话归属
+ 校验退出确认时的浏览器会话归属。
允许用户显式退出自然过期的会话,并继续撤销其关联离线授权。
@@ -410,7 +400,6 @@ async def validate_logout_cookie(cls, db: AsyncSession, cookie: str) -> SysSsoSe
:return: 已校验归属的SSO会话
:raises SsoSessionError: 会话不存在、已撤销或凭据不匹配
"""
-
try:
sid, secret = OidcUtil.parse_sso_cookie(cookie)
digest = OidcUtil.session_secret_digest(secret, OidcConfig.oidc_token_hash_pepper)
@@ -437,18 +426,17 @@ async def validate( # noqa: PLR0915
coordinator: AfterCommitCoordinator | None = None,
) -> SysSsoSession:
"""
- 验证 Cookie、Session 有效期和用户身份安全版本
+ 验证 Cookie、Session 有效期和用户身份安全版本。
:param db: 异步数据库会话
:param redis: Redis 热缓存客户端
:param cookie: 客户端 Cookie 原文
- :param pepper: OIDC Token Pepper
+ :param pepper: 用于 OIDC 令牌摘要的独立密钥
:param now: 可注入当前项目时间
:param coordinator: 必须由调用方在数据库提交成功后执行缓存清理或失效事件
:return: 已验证的数据库 Session
:raises SsoSessionError: Cookie 或任何安全状态校验失败
"""
-
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
coordinator = cls._require_coordinator(coordinator)
try:
@@ -464,12 +452,7 @@ async def validate( # noqa: PLR0915
if row is None:
async def clear_missing_cookie() -> None:
- """
- 在 Session 不存在时删除 Cookie 索引
-
- :return: None
- """
-
+ """在 Session 不存在时删除 Cookie 索引。"""
try:
await redis.delete(OidcRedisKey.sso_cookie(digest))
except Exception:
@@ -480,12 +463,7 @@ async def clear_missing_cookie() -> None:
if not hmac.compare_digest(row.session_secret_hash, digest):
async def clear_presented_cookie() -> None:
- """
- 在 Cookie Secret 不匹配时删除当前索引
-
- :return: None
- """
-
+ """在 Cookie Secret 不匹配时删除当前索引。"""
try:
await redis.delete(OidcRedisKey.sso_cookie(digest))
except Exception:
@@ -508,12 +486,7 @@ async def clear_presented_cookie() -> None:
snapshot = cls._snapshot(row)
async def clear_expired() -> None:
- """
- 在 Session 到期后清理缓存
-
- :return: None
- """
-
+ """在 Session 到期后清理缓存。"""
await cls._best_effort_cleanup(redis, snapshot, presented_digest=digest)
await coordinator.register(clear_expired)
@@ -536,12 +509,7 @@ async def clear_expired() -> None:
snapshot = cls._snapshot(row)
async def refresh_cache() -> None:
- """
- 在校验成功后刷新 Session 缓存
-
- :return: None
- """
-
+ """在校验成功后刷新 Session 缓存。"""
try:
await cls._cache_row(redis, snapshot, current)
except Exception:
@@ -563,7 +531,7 @@ async def _invalidate(
coordinator: AfterCommitCoordinator,
) -> None:
"""
- 将无效 Session 标记为撤销并登记提交后清理动作
+ 将无效 Session 标记为撤销并登记提交后清理动作。
:param db: 异步数据库会话
:param redis: 异步 Redis 客户端
@@ -572,9 +540,7 @@ async def _invalidate(
:param reason: 撤销原因
:param now: 当前时间
:param coordinator: 事务提交协调器
- :return: None
"""
-
changed = False
if row.status == _SESSION_STATUS_ACTIVE:
changed = await SsoSessionDao.revoke(db, row.sid, reason=reason, now=now)
@@ -592,12 +558,7 @@ async def _invalidate(
snapshot = cls._snapshot(row)
async def cleanup() -> None:
- """
- 在撤销或过期后清理 Session 缓存
-
- :return: None
- """
-
+ """在撤销或过期后清理 Session 缓存。"""
await cls._best_effort_cleanup(
redis,
snapshot,
@@ -619,18 +580,17 @@ async def touch(
coordinator: AfterCommitCoordinator | None = None,
) -> SysSsoSession:
"""
- 刷新活动 Session 的最近访问时间和空闲过期时间
+ 刷新活动 Session 的最近访问时间和空闲过期时间。
:param db: 异步数据库会话
:param redis: Redis 热缓存客户端
:param cookie: 当前 Cookie 原文
- :param pepper: OIDC Token Pepper
+ :param pepper: 用于 OIDC 令牌摘要的独立密钥
:param now: 可注入当前项目时间
:param coordinator: 必须由调用方在数据库提交成功后执行缓存更新
:return: 更新后的数据库 Session
:raises SsoSessionError: Session 状态或事务操作不符合要求
"""
-
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
coordinator = cls._require_coordinator(coordinator)
cls._validate_config_ttls()
@@ -647,12 +607,7 @@ async def touch(
snapshot = cls._snapshot(refreshed)
async def refresh_cache() -> None:
- """
- 在校验成功后刷新 Session 缓存
-
- :return: None
- """
-
+ """在校验成功后刷新 Session 缓存。"""
try:
await cls._cache_row(redis, snapshot, current)
except Exception:
@@ -674,18 +629,17 @@ async def rotate_cookie(
coordinator: AfterCommitCoordinator | None = None,
) -> str:
"""
- 轮换 Session Cookie Secret 并更新缓存索引
+ 轮换 Session Cookie Secret 并更新缓存索引。
:param db: 异步数据库会话
:param redis: Redis 热缓存客户端
:param cookie: 旧 Cookie 原文
- :param pepper: OIDC Token Pepper
+ :param pepper: 用于 OIDC 令牌摘要的独立密钥
:param now: 可注入当前项目时间
:param coordinator: 必须由调用方在数据库提交成功后执行缓存更新
:return: 新 Cookie 原文
:raises SsoSessionError: Session 状态或事务操作不符合要求
"""
-
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
coordinator = cls._require_coordinator(coordinator)
row = await cls.validate(db, redis, cookie, pepper=pepper, now=current, coordinator=coordinator)
@@ -702,12 +656,7 @@ async def rotate_cookie(
snapshot = cls._snapshot(row)
async def refresh_rotated_cache() -> None:
- """
- 在 Cookie 轮换后更新新旧缓存索引
-
- :return: None
- """
-
+ """在 Cookie 轮换后更新新旧缓存索引。"""
try:
await redis.delete(OidcRedisKey.sso_cookie(old_digest))
await cls._cache_row(redis, snapshot, current)
@@ -730,7 +679,7 @@ async def revoke(
coordinator: AfterCommitCoordinator | None = None,
) -> bool:
"""
- 撤销指定 Session 并清理其 Cookie 凭据
+ 撤销指定 Session 并清理其 Cookie 凭据。
:param db: 异步数据库会话
:param redis: Redis 热缓存客户端
@@ -740,7 +689,6 @@ async def revoke(
:param coordinator: 必须由调用方在数据库提交成功后执行清理闭包
:return: 数据库状态实际改变时返回 True
"""
-
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
coordinator = cls._require_coordinator(coordinator)
row = await SsoSessionDao.get_by_sid(db, sid, for_update=True)
@@ -761,12 +709,7 @@ async def revoke(
snapshot = cls._snapshot(row)
async def cleanup() -> None:
- """
- 在撤销或过期后清理 Session 缓存
-
- :return: None
- """
-
+ """在撤销或过期后清理 Session 缓存。"""
await cls._best_effort_cleanup(redis, snapshot, reason=reason if changed else None)
await coordinator.register(cleanup)
@@ -785,7 +728,7 @@ async def revoke_user(
coordinator: AfterCommitCoordinator | None = None,
) -> int:
"""
- 撤销指定用户全部在线及自然过期的 Session,终止其离线访问
+ 撤销指定用户全部在线及自然过期的 Session,终止其离线访问。
:param db: 异步数据库会话
:param redis: Redis 热缓存客户端
@@ -795,7 +738,6 @@ async def revoke_user(
:param coordinator: 必须由调用方在数据库提交成功后执行清理闭包
:return: 数据库更新的 Session 数量
"""
-
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
coordinator = cls._require_coordinator(coordinator)
rows = list(await SsoSessionDao.list_for_user(db, user_id, for_update=True, revocable_only=True))
@@ -815,12 +757,7 @@ async def revoke_user(
)
async def cleanup() -> None:
- """
- 在撤销或过期后清理 Session 缓存
-
- :return: None
- """
-
+ """在撤销或过期后清理 Session 缓存。"""
for snapshot in changed_snapshots:
await cls._best_effort_cleanup(redis, snapshot, reason=reason)
@@ -838,7 +775,7 @@ async def expire_due(
coordinator: AfterCommitCoordinator | None = None,
) -> int:
"""
- 批量标记已到期的 Session 并登记缓存清理
+ 批量标记已到期的 Session 并登记缓存清理。
:param db: 异步数据库会话
:param redis: Redis 热缓存客户端
@@ -846,7 +783,6 @@ async def expire_due(
:param coordinator: 必须由调用方在数据库提交成功后执行缓存清理
:return: 数据库更新数量
"""
-
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
coordinator = cls._require_coordinator(coordinator)
rows = list(await SsoSessionDao.list_due(db, now=current, for_update=True))
@@ -856,12 +792,7 @@ async def expire_due(
changed_snapshots.append(cls._snapshot(row)) # noqa: PERF401
async def cleanup() -> None:
- """
- 在撤销或过期后清理 Session 缓存
-
- :return: None
- """
-
+ """在撤销或过期后清理 Session 缓存。"""
for snapshot in changed_snapshots:
await cls._best_effort_cleanup(redis, snapshot)
@@ -872,14 +803,13 @@ async def cleanup() -> None:
@classmethod
def cookie_max_age(cls, session: SysSsoSession, *, now: datetime | None = None) -> int | None:
"""
- 根据 Session 的绝对过期时间计算保持登录 Cookie 的剩余寿命
+ 根据 Session 的绝对过期时间计算保持登录 Cookie 的剩余寿命。
:param session: 当前 SSO Session ORM
:param now: 可注入当前项目时间
:return: 保持登录 Cookie 的剩余秒数,普通登录返回 None
:raises SsoSessionError: Session 缺少绝对过期时间或已过期
"""
-
if not session.remember_me:
return None
absolute = TimezoneUtil.to_optional_utc(session.absolute_expires_at)
@@ -890,13 +820,12 @@ def cookie_max_age(cls, session: SysSsoSession, *, now: datetime | None = None)
@staticmethod
def cookie_parameters(*, max_age: int | None = None) -> dict[str, str | bool | int]:
"""
- 根据配置构造 SSO Cookie 的 HTTP 属性
+ 根据配置构造 SSO Cookie 的 HTTP 属性。
:param max_age: 可选 Cookie 最大寿命秒数
:return: 由 Controller 传给 HTTP Response 的 Cookie 参数
:raises SsoSessionError: Logout Session 校验失败
"""
-
if not OidcConfig.oidc_sso_cookie_name.startswith('__Host-') or not OidcConfig.oidc_sso_cookie_secure:
raise SsoSessionError('使用 __Host- 前缀的单点登录 Cookie 必须启用 Secure')
if OidcConfig.oidc_sso_cookie_domain or OidcConfig.oidc_sso_cookie_samesite != 'lax':
@@ -938,7 +867,11 @@ def cookie_parameters(*, max_age: int | None = None) -> dict[str, str | bool | i
@dataclass(frozen=True, slots=True)
class LogoutResult:
"""
- 记录 RP-Initiated Logout 的重定向结果和错误信息
+ 记录 RP-Initiated Logout 的重定向结果和错误信息。
+
+ :ivar redirect_uri: 已注册的授权回调地址
+ :ivar state: 当前流程的状态
+ :ivar session_revoked: 会话是否已被撤销
"""
redirect_uri: str | None
@@ -948,18 +881,15 @@ class LogoutResult:
@property
def is_local(self) -> bool:
"""
- 判断退出回调是否指向本地地址
+ 判断退出回调是否指向本地地址。
:return: LogoutResult 未提供重定向 URI 时是否在本地完成退出
"""
-
return self.redirect_uri is None
class LogoutServiceError(ValueError):
- """
- RP-Initiated Logout 参数或回调校验错误类型
- """
+ """RP-Initiated Logout 参数或回调校验错误类型。"""
BackchannelAuditWriter = Callable[..., Awaitable[None]]
@@ -967,9 +897,7 @@ class LogoutServiceError(ValueError):
class LogoutService:
- """
- OIDC Logout 模块服务层
- """
+ """OIDC Logout 模块服务层。"""
@classmethod
async def execute_logout( # noqa: PLR0913
@@ -990,11 +918,11 @@ async def execute_logout( # noqa: PLR0913
retry_queue: BackchannelRetryQueue | None = None,
) -> LogoutResult:
"""
- 编排 RP-Initiated Logout 的校验、撤销和响应
+ 编排 RP-Initiated Logout 的校验、撤销和响应。
:param db: 异步数据库会话
:param redis: SSO 热缓存客户端
- :param id_token_hint: OIDC ID Token Hint
+ :param id_token_hint: 用于提示会话身份的 OIDC 身份令牌
:param cookie: 当前 SSO Cookie
:param post_logout_redirect_uri: 请求的退出后重定向 URI
:param state: 仅在重定向 URI 验证成功后返回的状态值
@@ -1008,7 +936,6 @@ async def execute_logout( # noqa: PLR0913
:return: 不包含敏感材料的退出结果
:raises Exception: 核心流程或数据库提交失败时原样抛出异常
"""
-
coordinator = AfterCommitCoordinator()
try:
result = await cls._logout(
@@ -1056,7 +983,7 @@ async def _logout( # noqa: PLR0912, PLR0913, PLR0915
retry_queue: BackchannelRetryQueue | None = None,
) -> LogoutResult:
"""
- 在事务中处理 Logout Hint、Session 撤销和通知登记
+ 在事务中处理 Logout Hint、Session 撤销和通知登记。
:param db: 异步数据库会话;事务由公共编排入口提交或回滚
:param redis: SSO 热缓存客户端,仅传递给 Session 服务
@@ -1075,7 +1002,6 @@ async def _logout( # noqa: PLR0912, PLR0913, PLR0915
:return: 不包含敏感材料的退出结果
:raises LogoutServiceError: 请求违反安全边界
"""
-
if not OidcConfig.oidc_enabled:
raise LogoutServiceError('统一认证中心未启用')
if not confirmed:
@@ -1155,7 +1081,7 @@ async def _logout( # noqa: PLR0912, PLR0913, PLR0915
@classmethod
async def _validate_id_token_hint(cls, db: AsyncSession, token: str, now: datetime) -> tuple[dict[str, Any], Any]:
"""
- 验证 ID Token Hint 的签名、发行者和 Session 绑定
+ 验证 ID Token Hint 的签名、发行者和 Session 绑定。
:param db: 异步数据库会话
:param token: 令牌值
@@ -1163,7 +1089,6 @@ async def _validate_id_token_hint(cls, db: AsyncSession, token: str, now: dateti
:return: 包含协议字段的字典
:raises LogoutServiceError: Logout 参数或回调地址不符合要求
"""
-
if not isinstance(token, str) or not token or token.count('.') != _JWT_DOT_COUNT:
raise LogoutServiceError('退出请求中的身份令牌提示 id_token_hint 无效')
try:
@@ -1203,13 +1128,12 @@ async def _validate_id_token_hint(cls, db: AsyncSession, token: str, now: dateti
@classmethod
async def _lock_session_refresh_tokens(cls, db: AsyncSession, sid: str) -> list[Any]:
"""
- 锁定指定 Session 关联的 Refresh Token 记录
+ 锁定指定 Session 关联的 Refresh Token 记录。
:param db: 异步数据库会话
:param sid: Session 标识
:return: 规范化后的列表
"""
-
return list(await OAuthTokenDao.list_for_sid_for_update(db, sid))
@classmethod
@@ -1223,7 +1147,7 @@ async def _revoke_session_state(
coordinator: AfterCommitCoordinator,
) -> None:
"""
- 标记 Session 及其 Refresh Token 为撤销并登记缓存清理
+ 标记 Session 及其 Refresh Token 为撤销并登记缓存清理。
:param db: 异步数据库会话
:param redis: 异步 Redis 客户端
@@ -1231,9 +1155,7 @@ async def _revoke_session_state(
:param refresh_rows: Refresh 记录集合
:param now: 当前时间
:param coordinator: 事务提交协调器
- :return: None
"""
-
await SsoSessionService.revoke(db, redis, sid, reason='rp_initiated_logout', now=now, coordinator=coordinator)
for family_id in {row.family_id for row in refresh_rows}:
await OAuthTokenDao.revoke_family(db, family_id, reason='rp_initiated_logout')
@@ -1255,7 +1177,7 @@ async def _register_backchannel( # noqa: PLR0913
retry_queue: BackchannelRetryQueue | None,
) -> None:
"""
- 为已撤销 Session 登记各 Client 的 Back-Channel 通知
+ 为已撤销 Session 登记各 Client 的 Back-Channel 通知。
:param db: 异步数据库会话
:param redis: 异步 Redis 客户端
@@ -1268,9 +1190,7 @@ async def _register_backchannel( # noqa: PLR0913
:param notifier: 通知器
:param audit_writer: 审计写入回调
:param retry_queue: 重试队列回调
- :return: None
"""
-
effective_retry_queue = retry_queue or cls._redis_retry_queue(redis)
effective_audit_writer = audit_writer or cls._audit_writer(db)
callbacks: list[Callable[[], Awaitable[None]]] = []
@@ -1305,13 +1225,11 @@ async def _register_backchannel( # noqa: PLR0913
async def permanent_failure(uri_value: str = uri, client_value: str = client.client_id) -> None:
"""
- 记录 Back-Channel 通知的永久失败
+ 记录 Back-Channel 通知的永久失败。
:param uri_value: URI 值
:param client_value: 客户端值
- :return: None
"""
-
await cls._write_backchannel_audit(
effective_audit_writer,
OidcAuditEvent.BACKCHANNEL_LOGOUT_FAILED,
@@ -1332,16 +1250,14 @@ async def signing_failure(
include_sid_value: bool = include_sid,
) -> None:
"""
- 记录 Logout Token 签名失败
+ 记录 Logout Token 签名失败。
:param uri_value: URI 值
:param client_value: 客户端值
:param event_jti_value: 事件 JTI
:param subject_id_value: Subject 标识
:param include_sid_value: 是否包含 Session 标识
- :return: None
"""
-
await cls._write_backchannel_audit(
effective_audit_writer,
OidcAuditEvent.BACKCHANNEL_LOGOUT_FAILED,
@@ -1379,20 +1295,14 @@ async def signing_failure(
semaphore = asyncio.Semaphore(_BACKCHANNEL_MAX_CONCURRENCY)
async def notify_all() -> None:
- """
- 向已登记的 Client 发送退出通知
-
- :return: None
- """
+ """向已登记的 Client 发送退出通知。"""
async def run(callback: Callable[[], Awaitable[None]]) -> None:
"""
- 执行一次通知回调并统一处理发送异常
+ 执行一次通知回调并统一处理发送异常。
:param callback: 提交后回调
- :return: None
"""
-
async with semaphore:
await callback()
@@ -1411,7 +1321,7 @@ async def consume_backchannel_retry( # noqa: PLR0912, PLR0915
max_items: int = _BACKCHANNEL_MAX_QUEUE_ITEMS,
) -> int:
"""
- 读取并处理 Back-Channel Logout 重试队列
+ 读取并处理 Back-Channel Logout 重试队列。
:param db: 异步数据库会话
:param redis: Redis 队列客户端
@@ -1422,7 +1332,6 @@ async def consume_backchannel_retry( # noqa: PLR0912, PLR0915
:raises PermanentBackchannelError: Back-Channel 通知达到永久失败条件
:raises ValueError: 输入值不符合约束
"""
-
limit = max(1, min(int(max_items), _BACKCHANNEL_MAX_QUEUE_ITEMS))
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
processed = 0
@@ -1526,36 +1435,33 @@ async def consume_backchannel_retry( # noqa: PLR0912, PLR0915
@staticmethod
async def _safe_backchannel_uri(uri: Any) -> bool:
"""
- 验证 Back-Channel URI 使用允许的网络地址
+ 验证 Back-Channel URI 使用允许的网络地址。
:param uri: 回调 URI
:return: URI 是否通过 Back-Channel 网络地址安全检查
"""
-
return await is_safe_backchannel_uri(uri)
@staticmethod
async def _public_dns_only(hostname: str, port: int) -> bool:
"""
- 解析主机名并确认所有地址均为公网地址
+ 解析主机名并确认所有地址均为公网地址。
:param hostname: 主机名
:param port: 端口
:return: 主机解析得到的所有地址是否均为公网地址
"""
-
return await public_dns_only(hostname, port)
@staticmethod
async def _verified_addresses(hostname: str, port: int) -> set[str]:
"""
- 获取通过公网地址校验的主机地址集合
+ 获取通过公网地址校验的主机地址集合。
:param hostname: 主机名
:param port: 端口
:return: 通过校验的地址集合
"""
-
return await public_dns_addresses(hostname, port)
@classmethod
@@ -1573,7 +1479,7 @@ async def _make_logout_token(
db: AsyncSession,
) -> str | None:
"""
- 为指定 Client 和 Session 签发 Back-Channel Logout Token
+ 为指定 Client 和 Session 签发 Back-Channel Logout Token。
:param client_id: 客户端标识
:param sid: Session 标识
@@ -1586,7 +1492,6 @@ async def _make_logout_token(
:param db: 异步数据库会话
:return: 已签名的 Back-Channel Logout JWT,签名材料不可用时返回 None
"""
-
if signing_key is None or signing_kid is None:
record = await OidcKeyDao.get_active(db, alg=_RS256)
if record is None:
@@ -1626,7 +1531,7 @@ def _notification_callback( # noqa: PLR0913
retry_queue: BackchannelRetryQueue | None = None,
) -> Callable[[], Awaitable[None]]:
"""
- 创建发送 Back-Channel Logout 通知并处理失败的回调
+ 创建发送 Back-Channel Logout 通知并处理失败的回调。
:param uri: 回调 URI
:param token: 令牌值
@@ -1643,12 +1548,7 @@ def _notification_callback( # noqa: PLR0913
"""
async def notify() -> None:
- """
- 发送一次 Back-Channel Logout 通知
-
- :return: None
- """
-
+ """发送一次 Back-Channel Logout 通知。"""
last_error: Exception | None = None
for attempt in range(_BACKCHANNEL_MAX_ATTEMPTS):
try:
@@ -1696,16 +1596,14 @@ async def _send_backchannel_once(
uri: str, token: str, notifier: BackchannelNotifier | None, timeout_seconds: float
) -> None:
"""
- 向 Client 的 Back-Channel URI 发送 Logout Token
+ 向 Client 的 Back-Channel URI 发送 Logout Token。
:param uri: 已注册的 Back-Channel URI
:param token: 仅存在于本次内存请求中的 Logout Token
:param notifier: 可注入发送器
:param timeout_seconds: 有界网络超时
- :return: None
:raises LogoutServiceError: Logout 参数或回调地址不符合要求
"""
-
addresses: set[str] | None = None
if notifier is None:
parsed = urlsplit(uri)
@@ -1724,7 +1622,7 @@ async def _send_backchannel_once(
@staticmethod
def _audit_writer(db: AsyncSession) -> BackchannelAuditWriter:
"""
- 创建绑定数据库会话的 Back-Channel 审计写入器
+ 创建绑定数据库会话的 Back-Channel 审计写入器。
:param db: 异步数据库会话
:return: 绑定当前数据库会话的 Back-Channel 审计写入器
@@ -1739,16 +1637,14 @@ async def write(
failure_code: str | None = None,
) -> None:
"""
- 写入一次 Back-Channel 审计事件
+ 写入一次 Back-Channel 审计事件。
:param event: 事件类型
:param uri: 回调 URI
:param client_id: 客户端标识
:param sid: Session 标识
:param failure_code: 失败代码
- :return: None
"""
-
try:
await AuditService.record_independent(
db,
@@ -1774,7 +1670,7 @@ async def _write_backchannel_audit(
failure_code: str | None = None,
) -> None:
"""
- 记录一次 Back-Channel 通知结果
+ 记录一次 Back-Channel 通知结果。
:param audit_writer: 审计写入回调
:param event: 事件类型
@@ -1782,9 +1678,7 @@ async def _write_backchannel_audit(
:param client_id: 客户端标识
:param sid: Session 标识
:param failure_code: 失败代码
- :return: None
"""
-
if audit_writer is not None:
try:
await audit_writer(event, uri, client_id, sid, failure_code=failure_code)
@@ -1803,7 +1697,7 @@ async def _enqueue_backchannel_retry(
include_sid: bool = True,
) -> None:
"""
- 将失败的 Back-Channel 通知加入重试队列
+ 将失败的 Back-Channel 通知加入重试队列。
:param retry_queue: 重试队列回调
:param uri: 回调 URI
@@ -1812,9 +1706,7 @@ async def _enqueue_backchannel_retry(
:param event_jti: 事件 JTI
:param subject_id: Subject 标识
:param include_sid: 是否包含 Session 标识
- :return: None
"""
-
if retry_queue is not None:
try:
await retry_queue(
@@ -1831,7 +1723,7 @@ async def _enqueue_backchannel_retry(
@staticmethod
def _redis_retry_queue(redis: Redis) -> BackchannelRetryQueue:
"""
- 创建基于 Redis 的 Back-Channel 重试队列适配器
+ 创建基于 Redis 的 Back-Channel 重试队列适配器。
:param redis: 异步 Redis 客户端
:return: 基于 Redis 的 Back-Channel 重试队列适配器
@@ -1847,7 +1739,7 @@ async def enqueue(
include_sid: bool = True,
) -> None:
"""
- 加入一条 Back-Channel 重试任务
+ 加入一条 Back-Channel 重试任务。
:param uri: 回调 URI
:param client_id: 客户端标识
@@ -1855,9 +1747,7 @@ async def enqueue(
:param event_jti: 事件 JTI
:param subject_id: Subject 标识
:param include_sid: 是否包含 Session 标识
- :return: None
"""
-
payload = json.dumps(
{
'uri': uri,
@@ -1879,11 +1769,10 @@ async def enqueue(
@staticmethod
def _backchannel_timeout() -> float:
"""
- 读取 Back-Channel 请求超时配置
+ 读取 Back-Channel 请求超时配置。
:return: 超时时间(秒)
"""
-
value = getattr(OidcConfig, 'oidc_backchannel_logout_timeout_seconds', _BACKCHANNEL_TIMEOUT_SECONDS)
if (
isinstance(value, bool)
diff --git a/ruoyi-fastapi-backend/module_identity/service/token_protocol_service.py b/ruoyi-fastapi-backend/module_identity/service/token_protocol_service.py
index 9588656b2..0316790d8 100644
--- a/ruoyi-fastapi-backend/module_identity/service/token_protocol_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/token_protocol_service.py
@@ -32,7 +32,16 @@
class IntrospectionService:
"""
- OAuth Token 内省模块服务层
+ OAuth Token 内省模块服务层。
+
+ :cvar _USERINFO_SUFFIX: 用户信息端点的路径后缀
+ :cvar _ACTIVE_CLIENT_STATUS: 表示客户端可用的状态值
+ :cvar _ACTIVE_USER_STATUS: 表示用户可用的状态值
+ :cvar _ACTIVE_GRANT_STATUS: 表示授权记录可用的状态值
+ :cvar _ACTIVE_SESSION_STATUS: 表示会话有效的状态值
+ :cvar _ACTIVE_TOKEN_STATUS: 表示令牌可用的状态值
+ :cvar _REFRESH_PREFIX: 标识刷新令牌的前缀
+ :cvar _STANDARD_CLAIMS: 协议定义的标准令牌声明
"""
_USERINFO_SUFFIX = '/oauth2/userinfo'
@@ -61,7 +70,7 @@ async def introspect(
pepper: str | bytes | None = None,
) -> dict[str, Any]:
"""
- 验证 Token 并生成 OAuth Introspection 响应
+ 验证 Token 并生成 OAuth Introspection 响应。
:param db: 异步数据库会话
:param redis: 统一认证中心 Redis 客户端
@@ -74,7 +83,6 @@ async def introspect(
:param pepper: 可选 Token HMAC Pepper 覆盖值
:return: 有效 Token 的声明,或严格的 ``{'active': False}``
"""
-
try:
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
client = await cls._resolve_caller(db, caller)
@@ -111,7 +119,7 @@ async def _introspect_transaction(
pepper: str | bytes | None = None,
) -> dict[str, Any]:
"""
- 在事务边界内执行 Token 内省
+ 在事务边界内执行 Token 内省。
:param db: 异步数据库会话,由本方法提交或回滚
:param redis: 认证中心 Redis 客户端
@@ -121,10 +129,10 @@ async def _introspect_transaction(
:param verification_key: 当前 Token 对应的公钥
:param now: 可注入的 项目当前时间
:param token_type_hint: Token 类型提示
- :param pepper: Refresh Token HMAC Pepper
+ :param pepper: 计算刷新令牌 HMAC 的独立密钥
:return: OAuth Introspection 响应
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
-
try:
result = await cls.introspect(
db,
@@ -158,12 +166,12 @@ async def introspect_request(
token_type_hint: str | None = None,
) -> dict[str, Any]:
"""
- 认证调用 Client 并处理内省请求
+ 认证调用 Client 并处理内省请求。
:param db: 异步数据库会话,由本方法提交或回滚
:param redis: 认证中心 Redis 客户端
:param token: 待内省的 OAuth Access Token 或 Refresh Token
- :param authorization: RFC 7617 Basic Header
+ :param authorization: 符合 RFC 7617 的 Basic 认证头
:param client_id: 表单 Client ID
:param client_secret: 表单 Client Secret
:param verification_key: 当前 Access Token 的本地公钥
@@ -171,8 +179,8 @@ async def introspect_request(
:param token_type_hint: Token 类型提示
:return: OAuth Introspection 响应
:raises OAuthProtocolException: 请求不符合 OAuth 协议约束
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
-
try:
client_row, principal = await TokenService.authenticate_client(
db,
@@ -199,13 +207,12 @@ async def introspect_request(
@classmethod
async def _resolve_caller(cls, db: AsyncSession, caller: OAuthClientPrincipal) -> Any:
"""
- 确认内省调用方 Client 处于有效状态
+ 确认内省调用方 Client 处于有效状态。
:param db: 异步数据库会话
:param caller: 已认证的 OAuth Client 主体
:return: 已启用且认证方式匹配的 OAuth Client ORM 对象,不满足条件时返回 None
"""
-
if not isinstance(caller, OAuthClientPrincipal) or caller.auth_method != 'client_secret_basic':
return None
client = await OAuthClientDao.get_by_client_id(db, caller.client_id, active_only=True)
@@ -232,7 +239,7 @@ async def _introspect_access( # noqa: PLR0912
verification_key: Any,
) -> dict[str, Any]:
"""
- 验证 Access Token 并生成内省声明
+ 验证 Access Token 并生成内省声明。
:param db: 异步数据库会话
:param redis: 异步 Redis 客户端
@@ -243,7 +250,6 @@ async def _introspect_access( # noqa: PLR0912
:param verification_key: 验证密钥
:return: 有效 Access Token 的 Introspection 声明,或严格的 ``{'active': False}``
"""
-
claims = decode_access_token(
token,
verification_keys,
@@ -297,7 +303,7 @@ async def _access_user_state(
cls, db: AsyncSession, claims: dict[str, Any], client: Any, resources: list[str], now: datetime
) -> Any:
"""
- 验证 Access Token 对应的用户、Session 和授权来源
+ 验证 Access Token 对应的用户、Session 和授权来源。
:param db: 异步数据库会话
:param claims: 令牌声明
@@ -306,7 +312,6 @@ async def _access_user_state(
:param now: 当前时间
:return: 当前身份对应的启用用户 ORM 对象,安全状态或授权来源不匹配时返回 None
"""
-
subject_id = claims.get('sub')
version = claims.get('ver')
sid = claims.get('sid')
@@ -364,7 +369,7 @@ async def _client_allows_access(
cls, db: AsyncSession, client: Any, claims: dict[str, Any], resources: list[str]
) -> bool:
"""
- 检查当前 Client 策略是否仍允许令牌中的 Scope 和 Resource
+ 检查当前 Client 策略是否仍允许令牌中的 Scope 和 Resource。
:param db: 异步数据库会话
:param client: 签发该 Access Token 的 OAuth Client ORM
@@ -372,7 +377,6 @@ async def _client_allows_access(
:param resources: 待检查的 Resource Audience 列表
:return: 策略版本及 Scope、Resource 绑定均有效时为 True
"""
-
scope = claims.get('scope')
if not isinstance(scope, str) or not scope.strip():
return False
@@ -398,7 +402,7 @@ async def _introspect_refresh(
pepper: str | bytes | None,
) -> dict[str, Any]:
"""
- 验证 Refresh Token 并生成内省声明
+ 验证 Refresh Token 并生成内省声明。
:param db: 异步数据库会话
:param token: 待内省的 Refresh Token
@@ -407,7 +411,6 @@ async def _introspect_refresh(
:param pepper: 摘要 Pepper
:return: 有效 Refresh Token 的 Introspection 声明,或严格的 ``{'active': False}``
"""
-
parsed = parse_opaque_token(token, cls._REFRESH_PREFIX)
secret_pepper = OidcConfig.oidc_token_hash_pepper if pepper is None else pepper
digest = token_digest(token, secret_pepper)
@@ -478,13 +481,12 @@ async def _introspect_refresh(
@classmethod
async def _refresh_family_active(cls, db: AsyncSession, family_id: str) -> bool:
"""
- 检查 Refresh Token Family 是否仍处于活动状态
+ 检查 Refresh Token Family 是否仍处于活动状态。
:param db: 异步数据库会话
:param family_id: Refresh Family 标识
:return: 仅在存在记录且没有全族终止状态时返回真
"""
-
return await OAuthTokenDao.family_is_active(db, family_id)
@classmethod
@@ -499,7 +501,7 @@ def _grant_active(
now: datetime,
) -> bool:
"""
- 检查 Grant 是否匹配当前身份、Client 和授权范围
+ 检查 Grant 是否匹配当前身份、Client 和授权范围。
:param grant: Grant 对象
:param user_id: 用户标识
@@ -510,7 +512,6 @@ def _grant_active(
:param now: 当前时间
:return: Grant 匹配用户、Subject、OAuth Client、Scope、Resource 且未过期时为 True
"""
-
return bool(
grant is not None
and grant.user_id == user_id
@@ -526,14 +527,13 @@ def _grant_active(
@classmethod
async def _resources_owned_by_caller(cls, db: AsyncSession, audiences: list[str], client_pk: int) -> bool:
"""
- 检查调用方是否拥有资源的内省权限
+ 检查调用方是否拥有资源的内省权限。
:param db: 异步数据库会话
:param audiences: Token 声明中的 Audience 列表
:param client_pk: 已认证 OAuth Client 的主键
:return: 所有业务 Resource Audience 均归属于该 OAuth Client 的内省权限时为 True
"""
-
userinfo = f'{OidcConfig.oidc_issuer.rstrip("/")}{cls._USERINFO_SUFFIX}'
resource_audiences = [value for value in audiences if value != userinfo]
if not resource_audiences:
@@ -547,12 +547,11 @@ async def _resources_owned_by_caller(cls, db: AsyncSession, audiences: list[str]
@classmethod
def _resource_audiences(cls, audiences: list[str]) -> list[str]:
"""
- 移除 UserInfo audience 并保留业务资源
+ 移除 UserInfo audience 并保留业务资源。
:param audiences: Token 声明中的 Audience 列表
:return: 移除 UserInfo Audience 后的业务 Resource Audience 列表
"""
-
userinfo = f'{OidcConfig.oidc_issuer.rstrip("/")}{cls._USERINFO_SUFFIX}'
return [value for value in audiences if value != userinfo]
@@ -560,30 +559,31 @@ def _resource_audiences(cls, audiences: list[str]) -> list[str]:
@staticmethod
async def _redis_key_exists(redis: Redis, key: str) -> bool:
"""
- 检查 Redis 撤销键是否存在
+ 检查 Redis 撤销键是否存在。
:param redis: Redis 异步客户端
:param key: 待检查的 Redis 撤销键
:return: 键存在时返回 True
"""
-
return bool(await redis.exists(key))
class RevocationError(ValueError):
"""
- 令牌撤销参数错误类型
+ 令牌撤销参数错误类型。
+
+ :ivar message: 与当前结果一起返回的说明
+ :ivar error: OAuth 错误代码
+ :ivar description: 可向上层映射的安全错误描述
"""
def __init__(self, error: str, description: str) -> None:
"""
- 保存 OAuth 撤销错误代码和描述
+ 保存 OAuth 撤销错误代码和描述。
:param error: OAuth 错误代码
:param description: 可向上层映射的安全错误描述
- :return: None
"""
-
self.message = OidcUtil.localized_oauth_message(error, description)
super().__init__(self.message)
self.error = error
@@ -592,7 +592,9 @@ def __init__(self, error: str, description: str) -> None:
class RevocationService:
"""
- OAuth Token 撤销模块服务层
+ OAuth Token 撤销模块服务层。
+
+ :cvar _REFRESH_PREFIX: 标识刷新令牌的前缀
"""
_REFRESH_PREFIX = 'rt1'
@@ -613,7 +615,7 @@ async def revoke(
coordinator: AfterCommitCoordinator | None = None,
) -> None:
"""
- 按 Token 类型撤销 Access Token 或 Refresh Token
+ 按 Token 类型撤销 Access Token 或 Refresh Token。
:param db: 异步数据库会话;事务由提交协调器或调用方管理
:param redis: 统一认证中心 Redis 客户端
@@ -625,10 +627,8 @@ async def revoke(
:param token_type_hint: 可选 Token 类型提示
:param pepper: 可选 Token HMAC Pepper 覆盖值
:param coordinator: 提交后副作用协调器;Access 撤销必须提供
- :return: None
:raises RevocationError: Client 未认证或副作用边界不可用
"""
-
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
client = await cls._resolve_caller(db, caller)
if client is None:
@@ -667,7 +667,7 @@ async def _revoke_transaction(
pepper: str | bytes | None = None,
) -> bool:
"""
- 在事务边界内执行 Token 撤销
+ 在事务边界内执行 Token 撤销。
:param db: 异步数据库会话,由本方法提交或回滚
:param redis: 认证中心 Redis 客户端
@@ -677,11 +677,11 @@ async def _revoke_transaction(
:param verification_key: 当前 Token 对应的公钥
:param now: 可注入的 项目当前时间
:param token_type_hint: Token 类型提示
- :param pepper: Refresh Token HMAC Pepper
+ :param pepper: 计算刷新令牌 HMAC 的独立密钥
:return: 提交后副作用全部成功时为 True
:raises RevocationError: 令牌撤销失败且事务已回滚
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
-
coordinator = AfterCommitCoordinator()
try:
await cls.revoke(
@@ -717,20 +717,20 @@ async def revoke_request(
token_type_hint: str | None = None,
) -> bool:
"""
- 认证调用 Client 并处理撤销请求
+ 认证调用 Client 并处理撤销请求。
:param db: 异步数据库会话,由本方法提交或回滚
:param redis: 认证中心 Redis 客户端
:param token: 待撤销的完整 Token
- :param authorization: RFC 7617 Basic Header
+ :param authorization: 符合 RFC 7617 的 Basic 认证头
:param client_id: 表单 Client ID
:param client_secret: 表单 Client Secret
:param verification_key: 当前 Access Token 的本地公钥
:param verification_key_loader: 验证密钥加载回调
:param token_type_hint: Token 类型提示
:return: 提交后副作用全部成功时为 True
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
-
try:
_, principal = await TokenService.authenticate_client(
db,
@@ -755,13 +755,12 @@ async def revoke_request(
@staticmethod
async def _resolve_caller(db: AsyncSession, caller: OAuthClientPrincipal) -> Any:
"""
- 确认内省调用方 Client 处于有效状态
+ 确认内省调用方 Client 处于有效状态。
:param db: 异步数据库会话
:param caller: 已认证的 OAuth Client 主体
:return: 已通过认证和资源校验的 OAuth Client ORM 对象,不满足条件时返回 None
"""
-
if not isinstance(caller, OAuthClientPrincipal):
return None
client = await OAuthClientDao.get_by_client_id(db, caller.client_id, active_only=True)
@@ -797,16 +796,14 @@ async def _revoke_refresh(
pepper: str | bytes | None,
) -> None:
"""
- 撤销 Refresh Token 及其 Family
+ 撤销 Refresh Token 及其 Family。
:param db: 异步数据库会话
:param token: 待撤销的 Refresh Token
:param client: 发起撤销请求的 OAuth Client ORM
:param now: 当前时间
:param pepper: 摘要 Pepper
- :return: None
"""
-
try:
parsed = parse_opaque_token(token, cls._REFRESH_PREFIX)
secret_pepper = OidcConfig.oidc_token_hash_pepper if pepper is None else pepper
@@ -845,7 +842,7 @@ async def _revoke_access(
coordinator: AfterCommitCoordinator | None,
) -> None:
"""
- 验证并撤销 Access Token
+ 验证并撤销 Access Token。
:param db: 异步数据库会话
:param redis: 异步 Redis 客户端
@@ -855,10 +852,8 @@ async def _revoke_access(
:param verification_keys: 验证密钥集合
:param verification_key: 验证密钥
:param coordinator: 事务提交协调器
- :return: None
:raises RevocationError: 令牌撤销操作失败
"""
-
try:
claims = decode_access_token(
token,
@@ -884,12 +879,7 @@ async def _revoke_access(
key = OidcRedisKey.revoked_jti(jti)
async def write_revocation() -> None:
- """
- 执行 write_revocation 的校验和转换
-
- :return: None
- """
-
+ """执行 write_revocation 的校验和转换。"""
await redis.set(key, '1', ex=ttl)
await AuditService.record_independent(
db,
@@ -905,14 +895,12 @@ async def write_revocation() -> None:
class UserInfoService:
- """
- OIDC UserInfo 模块服务层
- """
+ """OIDC UserInfo 模块服务层。"""
@classmethod
async def build(cls, db: AsyncSession, claims: dict[str, Any], redis: Redis | None) -> dict[str, Any]:
"""
- 验证 Access Token 声明并构造 UserInfo 响应
+ 验证 Access Token 声明并构造 UserInfo 响应。
:param db: 异步数据库会话
:param claims: 令牌声明
@@ -920,7 +908,6 @@ async def build(cls, db: AsyncSession, claims: dict[str, Any], redis: Redis | No
:return: 包含协议字段的字典
:raises ValueError: 输入值不符合约束
"""
-
client = await OAuthClientDao.get_by_client_id(db, claims['client_id'], active_only=True)
if client is None or client.status != '0':
raise ValueError('客户端已停用')
@@ -949,14 +936,12 @@ async def build(cls, db: AsyncSession, claims: dict[str, Any], redis: Redis | No
@staticmethod
async def _check_revocation(redis: Redis | None, jti: str) -> None:
"""
- 检查 Access Token 是否已被撤销
+ 检查 Access Token 是否已被撤销。
:param redis: 异步 Redis 客户端
:param jti: 令牌 JTI
- :return: None
:raises ValueError: 输入值不符合约束
"""
-
if redis is None:
raise ValueError('令牌已撤销')
try:
diff --git a/ruoyi-fastapi-backend/module_identity/service/token_service.py b/ruoyi-fastapi-backend/module_identity/service/token_service.py
index 409e9a17e..7ef64788f 100644
--- a/ruoyi-fastapi-backend/module_identity/service/token_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/token_service.py
@@ -48,7 +48,13 @@
@dataclass(frozen=True, slots=True)
class TokenResult:
"""
- 记录 Token Endpoint 生成的各类令牌
+ 记录 Token Endpoint 生成的各类令牌。
+
+ :ivar access_token: 用于访问资源的令牌
+ :ivar expires_in: 剩余有效时间,单位为秒
+ :ivar refresh_token: 用于换取新访问令牌的刷新令牌
+ :ivar scope: 当前操作使用的作用域
+ :ivar id_token: 包含用户身份声明的 ID 令牌
"""
access_token: str
@@ -60,20 +66,18 @@ class TokenResult:
@property
def token_type(self) -> str:
"""
- 返回 OAuth Bearer 令牌类型
+ 返回 OAuth Bearer 令牌类型。
:return: 固定为 OAuth 2.0 Bearer token 类型的字符串
"""
-
return 'Bearer'
def as_dict(self) -> dict[str, Any]:
"""
- 将令牌结果转换为 Token Endpoint 响应字典
+ 将令牌结果转换为 Token Endpoint 响应字典。
:return: 包含协议字段的字典
"""
-
result: dict[str, Any] = {
'access_token': self.access_token,
'token_type': 'Bearer',
@@ -89,35 +93,39 @@ def as_dict(self) -> dict[str, Any]:
def __getitem__(self, key: str) -> Any:
"""
- 按字段名读取 Token Endpoint 响应值
+ 按字段名读取 Token Endpoint 响应值。
:param key: 要读取的 Token Endpoint 响应字段名
:return: 对应字段的 Access Token、有效期或可选令牌值
"""
-
return self.as_dict()[key]
class RefreshTokenReuseDetected(OAuthProtocolException):
"""
- Refresh Token 重放检测错误类型
+ Refresh Token 重放检测错误类型。
+
+ :cvar must_commit: 抛出异常后是否仍须提交状态更改
"""
must_commit = True
def __init__(self) -> None:
- """
- 保存 OAuth 撤销错误代码和描述
-
- :return: None
- """
-
+ """保存 OAuth 撤销错误代码和描述。"""
super().__init__('invalid_grant', 'The authorization grant is invalid or expired', 400)
class TokenService:
"""
- OAuth Token 模块服务层
+ OAuth Token 模块服务层。
+
+ :cvar _USERINFO_AUDIENCE_SUFFIX: 构造用户信息接口受众标识的后缀
+ :cvar _MACHINE_SCOPE_TYPE: 用于机器身份授权的权限范围类型
+ :cvar _ACTIVE_CLIENT_STATUSES: 签发令牌时允许的客户端状态
+ :cvar _ACTIVE_GRANT_STATUS: 表示授权记录可用的状态值
+ :cvar _ACTIVE_SESSION_STATUS: 表示会话有效的状态值
+ :cvar _MAX_RESOURCE_COUNT: 单次令牌请求允许的最大资源数量
+ :cvar _MIN_TOKEN_PEPPER_BYTES: 计算令牌摘要所用服务端密钥的最小字节数
"""
_USERINFO_AUDIENCE_SUFFIX = '/oauth2/userinfo'
@@ -138,7 +146,7 @@ async def authenticate_client(
client_secret: str | None = None,
) -> tuple[SysOAuthClient, OAuthClientPrincipal]:
"""
- 解析凭据并验证 OAuth Client 身份
+ 解析凭据并验证 OAuth Client 身份。
:param db: 异步数据库会话
:param authorization: RFC 7617 Basic Header;机密 Client 必须使用该方式
@@ -147,7 +155,6 @@ async def authenticate_client(
:return: 已启用 Client 行和不可伪造的 Client Principal
:raises OAuthProtocolException: Client 凭据无效时抛出 invalid_client
"""
-
if authorization is not None and client_secret is not None:
cls._invalid_client()
lookup_id = client_id
@@ -166,12 +173,10 @@ async def authenticate_client(
def capture_secret_match(secret_hash: str) -> None:
"""
- 保存认证过程中匹配的 Client Secret 哈希
+ 保存认证过程中匹配的 Client Secret 哈希。
:param secret_hash: 已匹配的持久化 Secret 哈希
- :return: None
"""
-
nonlocal matched_secret_hash
matched_secret_hash = secret_hash
@@ -209,17 +214,15 @@ async def _handle_authorization_code_reuse(
pepper: str | bytes,
) -> None:
"""
- 撤销重用授权码关联的 Grant 并记录高风险审计
+ 撤销重用授权码关联的 Grant 并记录高风险审计。
:param db: 异步数据库会话
:param redis: Authorization Code Redis 客户端
:param code: 被重复提交的 Authorization Code 明文
:param client_id: 已认证 Client 公开标识
:param pepper: Authorization Code 摘要 Pepper
- :return: None
:raises OAuthProtocolException: 撤销或审计无法安全持久化时抛出
"""
-
try:
consumed_payload = await AuthorizationCodeService.consumed_payload(redis, code, pepper=pepper)
grant_id = consumed_payload.get('grantId') if consumed_payload else None
@@ -250,7 +253,7 @@ async def authorization_code(
token_pepper: str | bytes | None = None,
) -> TokenResult:
"""
- 消费授权码并签发用户令牌
+ 消费授权码并签发用户令牌。
:param db: 异步数据库会话,调用方负责提交或回滚事务
:param redis: Authorization Code 所在 Redis 客户端
@@ -259,11 +262,11 @@ async def authorization_code(
:param signing_key: 可注入的 RSA 私钥;省略时从 KeyService 读取
:param kid: 注入私钥对应的签名 Key ID
:param now: 可注入 项目当前时间
- :param token_pepper: Refresh Token HMAC Pepper
+ :param token_pepper: 计算刷新令牌 HMAC 的独立密钥
:return: 标准 Token 结果
:raises OAuthProtocolException: 任一授权绑定或安全状态无效时抛出统一错误
+ :raises AuthorizationCodeReuseError: 检测到已消费授权码被重用
"""
-
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
parsed = cls._request(request)
if parsed.get('grant_type') != 'authorization_code':
@@ -399,7 +402,7 @@ async def refresh_token( # noqa: PLR0915
token_pepper: str | bytes | None = None,
) -> TokenResult:
"""
- 校验 Refresh Token 并完成令牌轮换
+ 校验 Refresh Token 并完成令牌轮换。
:param db: 异步数据库会话,调用方负责提交或回滚事务
:param request: Refresh Token 请求或字段映射
@@ -407,12 +410,11 @@ async def refresh_token( # noqa: PLR0915
:param signing_key: 可注入的 RSA 私钥
:param kid: 注入私钥对应的 Key ID
:param now: 可注入 项目当前时间
- :param token_pepper: Refresh Token HMAC Pepper
+ :param token_pepper: 计算刷新令牌 HMAC 的独立密钥
:return: 新 Access Token 与轮换后的 Refresh Token
:raises OAuthProtocolException: Token 无效、过期、重放或绑定状态失效
:raises RefreshTokenReuseDetected: 检测到 Refresh Token 重放
"""
-
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
parsed = cls._request(request)
if parsed.get('grant_type') != 'refresh_token' or not isinstance(parsed.get('refresh_token'), str):
@@ -544,7 +546,7 @@ async def client_credentials(
now: datetime | None = None,
) -> TokenResult:
"""
- 按 Client Credentials Grant 签发机器令牌
+ 按 Client Credentials Grant 签发机器令牌。
:param db: 异步数据库会话,调用方负责提交事务
:param request: Client Credentials 请求或字段映射
@@ -555,7 +557,6 @@ async def client_credentials(
:return: 不包含 Refresh/ID Token 的机器 Token 结果
:raises OAuthProtocolException: Client、Scope 或 Resource 策略无效时抛出
"""
-
current = TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now()
parsed = cls._request(request)
if parsed.get('grant_type') != 'client_credentials':
@@ -611,7 +612,7 @@ async def issue_token(
**kwargs: Any,
) -> TokenResult:
"""
- 根据 Grant Type 调度令牌签发流程
+ 根据 Grant Type 调度令牌签发流程。
:param db: 异步数据库会话
:param redis: 异步 Redis 客户端
@@ -621,7 +622,6 @@ async def issue_token(
:return: 包含 Access Token 及有效期的 Token Endpoint 响应对象
:raises AssertionError: 内部令牌状态不满足签发条件
"""
-
if not isinstance(client, OAuthClientPrincipal):
cls._invalid_client()
grant_type = request.grant_type if isinstance(request, TokenRequest) else request.get('grant_type')
@@ -644,7 +644,7 @@ async def _issue_token_transaction(
**kwargs: Any,
) -> TokenResult:
"""
- 在事务边界内执行令牌签发
+ 在事务边界内执行令牌签发。
:param db: 异步数据库会话,由本方法提交或回滚
:param redis: Authorization Code 所在 Redis 客户端
@@ -654,8 +654,9 @@ async def _issue_token_transaction(
:return: 标准 Token 领域结果
:raises RefreshTokenReuseDetected: Family 撤销已写入但需映射为 invalid_grant
:raises OAuthProtocolException: 业务失败且事务已回滚
+ :raises AuthorizationCodeReuseError: 事务失败并回滚后重新抛出原异常
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
-
try:
result = await cls.issue_token(db, redis, request, client, **kwargs)
except (RefreshTokenReuseDetected, AuthorizationCodeReuseError):
@@ -689,18 +690,18 @@ async def issue_token_request(
**kwargs: Any,
) -> TokenResult:
"""
- 认证 Client 并处理 Token Endpoint 请求
+ 认证 Client 并处理 Token Endpoint 请求。
:param db: 异步数据库会话,由本方法提交或回滚
:param redis: Authorization Code 所在 Redis 客户端
:param request: 已解析的 Token Endpoint 字段
- :param authorization: RFC 7617 Basic Header
+ :param authorization: 符合 RFC 7617 的 Basic 认证头
:param client_id: 表单 Client ID
:param client_secret: 表单 Client Secret
:param kwargs: 传给令牌签发流程的可选参数
:return: 标准 Token 领域结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
-
try:
_, principal = await cls.authenticate_client(
db,
@@ -732,13 +733,13 @@ async def _issue_access_token( # noqa: PLR0913
now: datetime,
) -> tuple[str, int]:
"""
- 构造并签署 Access Token
+ 构造并签署 Access Token。
:param db: 异步数据库会话
- :param client: OAuth Client ORM(SysOAuthClient)
+ :param client: OAuth 客户端的 ORM 记录
:param user: 系统用户 ORM(SysUser)
:param subject: 身份 Subject ORM(SysIdentitySubject)
- :param session: SSO Session ORM(SysSsoSession)
+ :param session: 单点登录会话的 ORM 记录
:param scopes: 已授权且经 Client 绑定校验的 Scope code 列表
:param resources: 已校验的 Resource audience 列表
:param resource: 与 Resource audience 对应的 OAuth Resource ORM,或 None
@@ -749,7 +750,6 @@ async def _issue_access_token( # noqa: PLR0913
:param now: 生成 JWT 的 项目当前时间
:return: 签名后的 JWT Access Token 文本及其有效秒数
"""
-
ttl = cls._access_ttl(client, resource)
claims = await cls._user_claims(db, client, user, subject, scopes, resource)
auth_time = cls._numeric_time(session.auth_time)
@@ -798,13 +798,13 @@ async def _issue_id_token( # noqa: PLR0913
now: datetime,
) -> str:
"""
- 构造包含用户声明的 ID Token
+ 构造包含用户声明的 ID Token。
:param db: 异步数据库会话
- :param client: OAuth Client ORM(SysOAuthClient)
+ :param client: OAuth 客户端的 ORM 记录
:param user: 系统用户 ORM(SysUser)
:param subject: 身份 Subject ORM(SysIdentitySubject)
- :param session: SSO Session ORM(SysSsoSession)
+ :param session: 单点登录会话的 ORM 记录
:param scopes: 已授权并用于筛选 ID Token 用户声明的 Scope code 列表
:param nonce: 授权请求绑定的 OIDC nonce 字符串
:param access_token: 同一 Token Endpoint 响应中的 JWT Access Token 文本
@@ -813,7 +813,6 @@ async def _issue_id_token( # noqa: PLR0913
:param now: 生成 JWT 的 项目当前时间
:return: 签名后的 OIDC ID Token JWT 文本
"""
-
ttl = cls._id_ttl(client)
resource = None
claims = await cls._user_claims(db, client, user, subject, scopes, resource)
@@ -849,17 +848,16 @@ async def _user_claims(
resource: SysOAuthResource | None,
) -> dict[str, Any]:
"""
- 收集 ID Token 所需的用户声明
+ 收集 ID Token 所需的用户声明。
:param db: 异步数据库会话
- :param client: OAuth Client ORM(SysOAuthClient)
+ :param client: OAuth 客户端的 ORM 记录
:param user: 系统用户 ORM(SysUser)
:param subject: 身份 Subject ORM(SysIdentitySubject)
:param scopes: 用于解析声明策略的 Scope code 列表
:param resource: 目标 OAuth Resource ORM,或 None(ID Token 不绑定资源)
:return: 按 Scope 策略生成的 OIDC 用户声明字典
"""
-
policy, allowed = await ClaimService.resolve_scope_policy(
db,
client.client_pk,
@@ -899,10 +897,10 @@ async def _create_refresh_token( # noqa: PLR0913
absolute_expires_at: datetime | None = None,
) -> str:
"""
- 创建并持久化 Refresh Token 记录
+ 创建并持久化 Refresh Token 记录。
:param db: 异步数据库会话
- :param client: OAuth Client ORM(SysOAuthClient)
+ :param client: OAuth 客户端的 ORM 记录
:param grant: 用户对该 Client 的 OAuth Grant ORM(SysOAuthGrant)
:param user: 系统用户 ORM(SysUser)
:param subject: 身份 Subject ORM(SysIdentitySubject)
@@ -917,7 +915,6 @@ async def _create_refresh_token( # noqa: PLR0913
:param absolute_expires_at: 轮换族已有的绝对过期时间,或 None
:return: 新建 opaque Refresh Token 文本
"""
-
raw = token or generate_refresh_token()
parsed = parse_opaque_token(raw, 'rt1')
pepper = cls._token_pepper(token_pepper)
@@ -957,16 +954,15 @@ async def _validate_client_scope_resource(
machine_only: bool = False,
) -> tuple[list[str], list[str], SysOAuthResource | None]:
"""
- 校验 Client 请求的 Scope 和 Resource
+ 校验 Client 请求的 Scope 和 Resource。
:param db: 异步数据库会话
- :param client: OAuth Client ORM(SysOAuthClient)
+ :param client: OAuth 客户端的 ORM 记录
:param scopes: 请求或授权记录中的 Scope code 列表
:param resources: 请求或授权记录中的 Resource audience 列表
:param machine_only: 是否限制为 resource 类型的机器 Scope
:return: 去重后的 Scope code 列表、Resource audience 列表及匹配的 Resource ORM
"""
-
if len(resources) > cls._MAX_RESOURCE_COUNT or len(set(scopes)) != len(scopes):
cls._invalid_scope()
bindings = await OAuthClientDao.list_scope_bindings(db, client.client_pk)
@@ -1008,7 +1004,7 @@ async def _require_grant(
now: datetime,
) -> SysOAuthGrant:
"""
- 加载并验证用户授权 Grant
+ 加载并验证用户授权 Grant。
:param db: 异步数据库会话
:param grant_id: 授权记录的非空 grant_id 字符串
@@ -1020,7 +1016,6 @@ async def _require_grant(
:return: 匹配请求范围的有效授权 Grant
:raises OAuthProtocolException: 授权记录或用户访问策略无效
"""
-
if not isinstance(grant_id, str) or not grant_id:
cls._invalid_grant()
if await OAuthAccessPolicyDao.is_blocked(db, user_id, client_pk, for_update=True):
@@ -1046,7 +1041,7 @@ async def _require_user_identity(
cls, db: AsyncSession, user_id: int, subject_id: str, auth_version: int
) -> tuple[SysUser, SysIdentitySubject]:
"""
- 验证用户与 Subject 的身份版本
+ 验证用户与 Subject 的身份版本。
:param db: 异步数据库会话
:param user_id: 系统用户主键
@@ -1054,7 +1049,6 @@ async def _require_user_identity(
:param auth_version: 必须与用户 Subject 和 SSO Session 一致的认证版本
:return: 通过状态、删除标记及认证版本校验的系统用户 ORM 与 Subject ORM
"""
-
user = await IdentityUserDao.get_user(db, user_id)
try:
subject = await IdentitySubjectService.require_by_user_id(
@@ -1094,7 +1088,7 @@ async def _require_session(
allow_offline: bool = False,
) -> SysSsoSession:
"""
- 加载并验证关联的 SSO Session
+ 加载并验证关联的 SSO Session。
:param db: 异步数据库会话
:param sid: SSO Session 的 sid 字符串
@@ -1105,7 +1099,6 @@ async def _require_session(
:param allow_offline: 是否允许自然过期但未撤销的SSO会话继续离线续期
:return: 与用户身份和 Token 绑定一致的 SSO Session
"""
-
session = await SsoSessionDao.get_for_token(db, sid, now=now, allow_offline=allow_offline)
if (
session is None
@@ -1120,13 +1113,12 @@ async def _require_session(
@classmethod
async def _resolve_client(cls, db: AsyncSession, client: OAuthClientPrincipal) -> SysOAuthClient:
"""
- 确认 OAuth Client 处于可用状态
+ 确认 OAuth Client 处于可用状态。
:param db: 异步数据库会话
:param client: 已认证的 OAuthClientPrincipal 主体
:return: 通过 active 状态、Client 类型及认证方式校验的 OAuth Client ORM
"""
-
if not isinstance(client, OAuthClientPrincipal):
cls._invalid_client()
row = await OAuthClientDao.get_by_client_id(db, client.client_id, active_only=True)
@@ -1148,7 +1140,7 @@ async def _resolve_signer(
now: datetime,
) -> tuple[RSAPrivateKey, str]:
"""
- 加载或确认 JWT 签名密钥
+ 加载或确认 JWT 签名密钥。
:param db: 异步数据库会话
:param signing_key: 可注入的 RSA JWT 签名私钥,或 None
@@ -1156,7 +1148,6 @@ async def _resolve_signer(
:param now: 读取 active OIDC 签名密钥的 项目当前时间
:return: 用于 JWT 签名的 RSA 私钥及其 Key ID
"""
-
if signing_key is not None:
if not isinstance(kid, str) or not kid:
cls._server_error()
@@ -1177,13 +1168,12 @@ def _access_ttl(
resource: SysOAuthResource | None,
) -> int:
"""
- 计算 Access Token 的有效秒数
+ 计算 Access Token 的有效秒数。
- :param client: OAuth Client ORM(SysOAuthClient)
+ :param client: OAuth 客户端的 ORM 记录
:param resource: 目标 OAuth Resource ORM,或 None
:return: Access Token 有效秒数(取 Client、Resource 与 OIDC 上限的最小值)
"""
-
values: list[int] = []
if client.access_token_ttl_seconds is not None:
values.append(client.access_token_ttl_seconds)
@@ -1201,13 +1191,12 @@ def _access_ttl(
@staticmethod
def _id_ttl(client: SysOAuthClient) -> int:
"""
- 计算 ID Token 的有效秒数
+ 计算 ID Token 的有效秒数。
:param client: OAuth Client ORM(此方法仅按统一签名接收)
:return: OIDC ID Token 的有效秒数
:raises OAuthProtocolException: 请求不符合 OAuth 协议约束
"""
-
value = OidcConfig.oidc_id_token_ttl_seconds
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
raise OAuthProtocolException('server_error', 'Token policy is unavailable', 500)
@@ -1216,13 +1205,12 @@ def _id_ttl(client: SysOAuthClient) -> int:
@staticmethod
def _refresh_idle_ttl(client: SysOAuthClient) -> int:
"""
- 计算 Refresh Token 空闲有效秒数
+ 计算 Refresh Token 空闲有效秒数。
- :param client: OAuth Client ORM(SysOAuthClient)
+ :param client: OAuth 客户端的 ORM 记录
:return: Refresh Token 空闲有效秒数(不超过 OIDC 配置上限)
:raises OAuthProtocolException: 请求不符合 OAuth 协议约束
"""
-
value = client.refresh_token_idle_seconds
if value is None:
value = OidcConfig.oidc_refresh_token_idle_seconds
@@ -1236,13 +1224,12 @@ def _refresh_idle_ttl(client: SysOAuthClient) -> int:
@staticmethod
def _refresh_absolute_ttl(client: SysOAuthClient) -> int:
"""
- 计算 Refresh Token 绝对有效秒数
+ 计算 Refresh Token 绝对有效秒数。
- :param client: OAuth Client ORM(SysOAuthClient)
+ :param client: OAuth 客户端的 ORM 记录
:return: Refresh Token 绝对有效秒数(不超过 OIDC 配置上限)
:raises OAuthProtocolException: 请求不符合 OAuth 协议约束
"""
-
value = client.refresh_token_absolute_seconds
if value is None:
value = OidcConfig.oidc_refresh_token_absolute_seconds
@@ -1256,12 +1243,11 @@ def _refresh_absolute_ttl(client: SysOAuthClient) -> int:
@classmethod
def _request(cls, request: TokenRequest | Mapping[str, Any]) -> dict[str, Any]:
"""
- 将 TokenRequest 或映射转换为请求字典
+ 将 TokenRequest 或映射转换为请求字典。
:param request: TokenRequest 实例或包含 Token Endpoint 字段的映射
:return: 用于 Grant Type 分派的已验证 Token Endpoint 字段字典
"""
-
if isinstance(request, TokenRequest):
return request.model_dump()
if isinstance(request, Mapping):
@@ -1276,12 +1262,11 @@ def _request(cls, request: TokenRequest | Mapping[str, Any]) -> dict[str, Any]:
@staticmethod
def _token_pepper(override: str | bytes | None) -> str | bytes:
"""
- 选择 Token HMAC Pepper 配置
+ 选择 Token HMAC Pepper 配置。
:param override: 覆盖配置
:return: 用于令牌摘要计算的 Pepper 文本或字节串
"""
-
value = OidcConfig.oidc_token_hash_pepper if override is None else override
if not isinstance(value, (str, bytes)):
TokenService._server_error()
@@ -1293,13 +1278,12 @@ def _token_pepper(override: str | bytes | None) -> str | bytes:
@classmethod
def _requested_scopes(cls, value: Any, fallback: Sequence[str]) -> list[str]:
"""
- 解析请求中的 Scope 列表
+ 解析请求中的 Scope 列表。
:param value: Token Endpoint 的 scope 字符串,或已解析的 Scope code 序列
:param fallback: 请求未提供 scope 时使用的已持久化 Scope code 序列
:return: 去重校验后的 Scope code 字符串列表
"""
-
raw = fallback if value is None else value.split() if isinstance(value, str) else value
if not isinstance(raw, (list, tuple)) or not raw or any(not isinstance(item, str) or not item for item in raw):
cls._invalid_scope()
@@ -1310,13 +1294,12 @@ def _requested_scopes(cls, value: Any, fallback: Sequence[str]) -> list[str]:
@classmethod
def _requested_resources(cls, value: Any, fallback: Sequence[str]) -> list[str]:
"""
- 解析请求中的 Resource 列表
+ 解析请求中的 Resource 列表。
:param value: Token Endpoint 的 resource audience 字符串或序列
:param fallback: 请求未提供 resource 时使用的已持久化 audience 序列
:return: 通过单 Resource 限制校验的 audience 字符串列表
"""
-
raw = fallback if value is None else [value] if isinstance(value, str) else value
if not isinstance(raw, (list, tuple)) or len(raw) > cls._MAX_RESOURCE_COUNT:
cls._invalid_scope()
@@ -1327,12 +1310,11 @@ def _requested_resources(cls, value: Any, fallback: Sequence[str]) -> list[str]:
@staticmethod
def _numeric_time(value: datetime | None) -> int:
"""
- 将时间值转换为整数时间戳
+ 将时间值转换为整数时间戳。
:param value: 认证时间等需要编码进 JWT claim 的 datetime,或 None
:return: Unix 整数时间戳
"""
-
current = TimezoneUtil.to_optional_utc(value)
if current is None:
TokenService._server_error()
@@ -1341,14 +1323,12 @@ def _numeric_time(value: datetime | None) -> int:
@staticmethod
def _map_oauth_failure(error: Exception, fallback: str) -> None:
"""
- 将底层异常映射为 OAuth 协议错误
+ 将底层异常映射为 OAuth 协议错误。
:param error: Authorization Code 消费等底层流程抛出的异常
:param fallback: 非 OAuthProtocolException 时使用的 OAuth error code
- :return: None
:raises OAuthProtocolException: 请求不符合 OAuth 协议约束
"""
-
if isinstance(error, OAuthProtocolException):
raise OAuthProtocolException(error.error, 'The authorization grant is invalid or expired', 400) from None
raise OAuthProtocolException(fallback, 'The authorization grant is invalid or expired', 400) from None
@@ -1356,54 +1336,44 @@ def _map_oauth_failure(error: Exception, fallback: str) -> None:
@staticmethod
def _invalid_request() -> None:
"""
- 抛出 invalid_request 协议错误
+ 抛出 invalid_request 协议错误。
- :return: None
:raises OAuthProtocolException: 请求不符合 OAuth 协议约束
"""
-
raise OAuthProtocolException('invalid_request', 'Invalid token request', 400)
@staticmethod
def _invalid_client() -> None:
"""
- 抛出 invalid_client 协议错误
+ 抛出 invalid_client 协议错误。
- :return: None
:raises OAuthProtocolException: 请求不符合 OAuth 协议约束
"""
-
raise OAuthProtocolException('invalid_client', 'Client authentication failed', 401)
@staticmethod
def _invalid_grant() -> None:
"""
- 抛出 invalid_grant 协议错误
+ 抛出 invalid_grant 协议错误。
- :return: None
:raises OAuthProtocolException: 请求不符合 OAuth 协议约束
"""
-
raise OAuthProtocolException('invalid_grant', 'The authorization grant is invalid or expired', 400)
@staticmethod
def _invalid_scope() -> None:
"""
- 抛出 invalid_scope 协议错误
+ 抛出 invalid_scope 协议错误。
- :return: None
:raises OAuthProtocolException: 请求不符合 OAuth 协议约束
"""
-
raise OAuthProtocolException('invalid_scope', 'Requested scope is not authorized', 400)
@staticmethod
def _server_error() -> None:
"""
- 抛出 server_error 协议错误
+ 抛出 server_error 协议错误。
- :return: None
:raises OAuthProtocolException: 请求不符合 OAuth 协议约束
"""
-
raise OAuthProtocolException('server_error', 'Token issuance is unavailable', 500)
diff --git a/ruoyi-fastapi-backend/module_plugin/service/plugin_service.py b/ruoyi-fastapi-backend/module_plugin/service/plugin_service.py
index 9a2da24a2..3a4772cbd 100644
--- a/ruoyi-fastapi-backend/module_plugin/service/plugin_service.py
+++ b/ruoyi-fastapi-backend/module_plugin/service/plugin_service.py
@@ -23,6 +23,8 @@ class PluginOperationService:
插件管理操作服务。
使用 Facade 模式复用插件应用运行时能力,为插件管理页面接口提供检查、安装和升级入口。
+
+ :ivar runtime_service: 插件运行时服务
"""
def __init__(self, runtime_service: PluginRuntimeService | None = None) -> None:
@@ -30,7 +32,6 @@ def __init__(self, runtime_service: PluginRuntimeService | None = None) -> None:
初始化插件管理操作服务。
:param runtime_service: 插件运行时服务
- :return: None
"""
self.runtime_service = runtime_service or get_plugin_runtime_service()
diff --git a/ruoyi-fastapi-backend/module_task/file_task.py b/ruoyi-fastapi-backend/module_task/file_task.py
index a97bac1f6..77b3ba330 100644
--- a/ruoyi-fastapi-backend/module_task/file_task.py
+++ b/ruoyi-fastapi-backend/module_task/file_task.py
@@ -8,11 +8,10 @@
async def scan_retention_reminders(remind_days: int = 7, batch_size: int = 500) -> None:
"""
- 扫描文件保留期限并生成提醒
+ 扫描文件保留期限并生成提醒。
:param remind_days: 提前提醒天数
:param batch_size: 单类提醒单批处理数量
- :return: None
"""
expiring_count = 0
expired_count = 0
@@ -34,11 +33,10 @@ async def scan_retention_reminders(remind_days: int = 7, batch_size: int = 500)
async def purge_recycle_bin(retention_days: int = 30, batch_size: int = 100) -> None:
"""
- 永久清理超过保留期限的回收站文件
+ 永久清理超过保留期限的回收站文件。
:param retention_days: 回收站保留天数
:param batch_size: 单批处理数量
- :return: None
"""
purge_count = 0
async with DataSourceRegistry.session() as query_db:
@@ -58,9 +56,8 @@ async def purge_recycle_bin(retention_days: int = 30, batch_size: int = 100) ->
async def reconcile_file_storage(check_hash: bool = False) -> None:
"""
- 执行数据库和本地文件系统双向对账
+ 执行数据库和本地文件系统双向对账。
:param check_hash: 是否校验文件SHA-256
- :return: None
"""
await FileReconcileService.run_scheduled_reconcile_services(check_hash)
diff --git a/ruoyi-fastapi-backend/module_task/scheduler_test.py b/ruoyi-fastapi-backend/module_task/scheduler_test.py
index 563f5f452..45061cffa 100644
--- a/ruoyi-fastapi-backend/module_task/scheduler_test.py
+++ b/ruoyi-fastapi-backend/module_task/scheduler_test.py
@@ -3,7 +3,10 @@
def job(*args, **kwargs) -> None:
"""
- 定时任务执行同步函数示例
+ 定时任务执行同步函数示例。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
"""
print(args)
print(kwargs)
@@ -12,7 +15,10 @@ def job(*args, **kwargs) -> None:
async def async_job(*args, **kwargs) -> None:
"""
- 定时任务执行异步函数示例
+ 定时任务执行异步函数示例。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
"""
print(args)
print(kwargs)
diff --git a/ruoyi-fastapi-backend/plugins/ai/dao/ai_chat_dao.py b/ruoyi-fastapi-backend/plugins/ai/dao/ai_chat_dao.py
index eacbf34bf..772bfa96c 100644
--- a/ruoyi-fastapi-backend/plugins/ai/dao/ai_chat_dao.py
+++ b/ruoyi-fastapi-backend/plugins/ai/dao/ai_chat_dao.py
@@ -6,14 +6,12 @@
class AiChatConfigDao:
- """
- AI对话配置数据库操作层
- """
+ """AI对话配置数据库操作层。"""
@classmethod
async def get_chat_config_detail_by_user_id(cls, db: AsyncSession, user_id: int) -> AiChatConfig | None:
"""
- 根据用户ID获取配置
+ 根据用户ID获取配置。
:param db: orm对象
:param user_id: 用户ID
@@ -28,7 +26,7 @@ async def get_chat_config_detail_by_user_id(cls, db: AsyncSession, user_id: int)
@classmethod
async def add_chat_config_dao(cls, db: AsyncSession, chat_config: AiChatConfigModel) -> AiChatConfig:
"""
- 新增对话配置数据库操作
+ 新增对话配置数据库操作。
:param db: orm对象
:param chat_config: 对话配置对象
@@ -45,11 +43,10 @@ async def add_chat_config_dao(cls, db: AsyncSession, chat_config: AiChatConfigMo
@classmethod
async def edit_chat_config_dao(cls, db: AsyncSession, chat_config: dict) -> None:
"""
- 编辑对话配置数据库操作
+ 编辑对话配置数据库操作。
:param db: orm对象
:param chat_config: 需要更新的对话配置字典
- :return:
"""
await db.execute(
update(AiChatConfig),
diff --git a/ruoyi-fastapi-backend/plugins/ai/dao/ai_model_dao.py b/ruoyi-fastapi-backend/plugins/ai/dao/ai_model_dao.py
index 99e296208..71c450191 100644
--- a/ruoyi-fastapi-backend/plugins/ai/dao/ai_model_dao.py
+++ b/ruoyi-fastapi-backend/plugins/ai/dao/ai_model_dao.py
@@ -10,14 +10,12 @@
class AiModelDao:
- """
- AI模型管理数据库操作层
- """
+ """AI模型管理数据库操作层。"""
@classmethod
async def get_ai_model_detail_by_id(cls, db: AsyncSession, model_id: int) -> AiModels | None:
"""
- 根据AI模型id获取AI模型详细信息
+ 根据AI模型id获取AI模型详细信息。
:param db: orm对象
:param model_id: AI模型id
@@ -32,7 +30,7 @@ async def get_ai_model_list(
cls, db: AsyncSession, query_object: AiModelPageQueryModel, data_scope_sql: ColumnElement, is_page: bool = False
) -> PageModel | list[dict[str, Any]]:
"""
- 根据查询参数获取AI模型列表信息
+ 根据查询参数获取AI模型列表信息。
:param db: orm对象
:param query_object: 查询参数对象
@@ -61,7 +59,7 @@ async def get_ai_model_list(
@classmethod
async def add_ai_model_dao(cls, db: AsyncSession, ai_model: AiModelModel) -> AiModels:
"""
- 新增AI模型数据库操作
+ 新增AI模型数据库操作。
:param db: orm对象
:param ai_model: AI模型对象
@@ -76,11 +74,10 @@ async def add_ai_model_dao(cls, db: AsyncSession, ai_model: AiModelModel) -> AiM
@classmethod
async def edit_ai_model_dao(cls, db: AsyncSession, ai_model: dict) -> None:
"""
- 编辑AI模型数据库操作
+ 编辑AI模型数据库操作。
:param db: orm对象
:param ai_model: 需要更新的AI模型字典
- :return:
"""
await db.execute(
update(AiModels),
@@ -90,10 +87,9 @@ async def edit_ai_model_dao(cls, db: AsyncSession, ai_model: dict) -> None:
@classmethod
async def delete_ai_model_dao(cls, db: AsyncSession, ai_model: AiModelModel) -> None:
"""
- 删除AI模型数据库操作
+ 删除AI模型数据库操作。
:param db: orm对象
:param ai_model: AI模型对象
- :return:
"""
await db.execute(delete(AiModels).where(AiModels.model_id.in_([ai_model.model_id])))
diff --git a/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_chat_do.py b/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_chat_do.py
index 084e2daa1..70fc8b69d 100644
--- a/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_chat_do.py
+++ b/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_chat_do.py
@@ -5,9 +5,7 @@
class AiChatConfig(AuditTimeMixin, Base):
- """
- AI对话配置表
- """
+ """AI对话配置表。"""
__tablename__ = 'ai_chat_config'
__table_args__ = {'comment': 'AI对话配置表'}
diff --git a/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_model_do.py b/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_model_do.py
index 87bf34221..0b91ce90f 100644
--- a/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_model_do.py
+++ b/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_model_do.py
@@ -7,9 +7,7 @@
class AiModels(AuditTimeMixin, Base):
- """
- AI模型表
- """
+ """AI模型表。"""
__tablename__ = 'ai_models'
__table_args__ = {'comment': 'AI模型表'}
@@ -28,13 +26,13 @@ class AiModels(AuditTimeMixin, Base):
String(255),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
- comment='API Key',
+ comment='接口访问密钥',
)
base_url = Column(
String(255),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
- comment='Base URL',
+ comment='服务基础地址',
)
model_type = Column(
String(50),
diff --git a/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_chat_vo.py b/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_chat_vo.py
index e4cd0baaa..969be1f18 100644
--- a/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_chat_vo.py
+++ b/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_chat_vo.py
@@ -7,9 +7,7 @@
class AiChatRequestModel(BaseModel):
- """
- AI对话请求模型
- """
+ """AI对话请求模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -21,9 +19,7 @@ class AiChatRequestModel(BaseModel):
class AiChatConfigModel(BaseModel):
- """
- AI对话配置模型
- """
+ """AI对话配置模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -41,9 +37,7 @@ class AiChatConfigModel(BaseModel):
class AiChatSessionBaseModel(BaseModel):
- """
- AI对话会话基础模型
- """
+ """AI对话会话基础模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -56,9 +50,7 @@ class AiChatSessionBaseModel(BaseModel):
class ModelInfoModel(BaseModel):
- """
- 对话会话数据模型-模型信息模型
- """
+ """对话会话数据模型-模型信息模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -69,9 +61,7 @@ class ModelInfoModel(BaseModel):
class AgentDataModel(BaseModel):
- """
- 对话会话数据模型-智能体数据模型
- """
+ """对话会话数据模型-智能体数据模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -80,9 +70,7 @@ class AgentDataModel(BaseModel):
class SessionMetricsModel(BaseModel):
- """
- 对话会话数据模型-会话指标模型
- """
+ """对话会话数据模型-会话指标模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -104,9 +92,7 @@ class SessionMetricsModel(BaseModel):
class SessionDataModel(BaseModel):
- """
- 对话会话数据模型
- """
+ """对话会话数据模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -115,9 +101,7 @@ class SessionDataModel(BaseModel):
class MessageMetrics(BaseModel):
- """
- 对话消息模型-消息指标模型
- """
+ """对话消息模型-消息指标模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -130,9 +114,7 @@ class MessageMetrics(BaseModel):
class ChatMessageModel(BaseModel):
- """
- 对话消息模型
- """
+ """对话消息模型。"""
model_config = ConfigDict(alias_generator=to_camel)
@@ -148,9 +130,7 @@ class ChatMessageModel(BaseModel):
class AiChatSessionModel(AiChatSessionBaseModel):
- """
- AI对话会话模型
- """
+ """AI对话会话模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_model_vo.py b/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_model_vo.py
index dcafb30ca..e4c164df1 100644
--- a/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_model_vo.py
+++ b/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_model_vo.py
@@ -9,9 +9,7 @@
class AiModelModel(BaseModel):
- """
- AI模型表对应pydantic模型
- """
+ """AI模型表对应pydantic模型。"""
model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
@@ -20,8 +18,8 @@ class AiModelModel(BaseModel):
model_name: str | None = Field(default=None, description='模型名称')
provider: str | None = Field(default=None, description='提供商')
model_sort: int | None = Field(default=None, description='显示顺序')
- api_key: str | None = Field(default=None, description='API Key')
- base_url: str | None = Field(default=None, description='Base URL')
+ api_key: str | None = Field(default=None, description='接口访问密钥')
+ base_url: str | None = Field(default=None, description='服务基础地址')
max_tokens: int | None = Field(default=None, description='最大输出token')
temperature: float | None = Field(default=None, description='默认温度')
support_reasoning: Literal['Y', 'N'] | None = Field(default=None, description='是否支持推理(深度思考)')
@@ -44,6 +42,11 @@ class AiModelModel(BaseModel):
message=I18nMessage('模型编码长度不能超过100个字符', msg_key='validation.modelCodeLength'),
)
def get_model_code(self) -> str | None:
+ """
+ 校验并返回模型编码。
+
+ :return: 模型编码
+ """
return self.model_code
@NotBlank(field_name='base_url', message=I18nMessage('Base URL不能为空', msg_key='validation.baseUrlRequired'))
@@ -54,22 +57,23 @@ def get_model_code(self) -> str | None:
message=I18nMessage('Base URL长度不能超过255个字符', msg_key='validation.baseUrlLength'),
)
def get_base_url(self) -> str | None:
+ """
+ 校验并返回Base URL。
+
+ :return: 模型服务的基础地址
+ """
return self.base_url
class AiModelPageQueryModel(AiModelModel):
- """
- AI模型管理分页查询模型
- """
+ """AI模型管理分页查询模型。"""
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
class DeleteAiModelModel(BaseModel):
- """
- 删除AI模型模型
- """
+ """删除AI模型模型。"""
model_config = ConfigDict(alias_generator=to_camel)
diff --git a/ruoyi-fastapi-backend/plugins/ai/service/ai_chat_service.py b/ruoyi-fastapi-backend/plugins/ai/service/ai_chat_service.py
index 85a38be61..95f20c59e 100644
--- a/ruoyi-fastapi-backend/plugins/ai/service/ai_chat_service.py
+++ b/ruoyi-fastapi-backend/plugins/ai/service/ai_chat_service.py
@@ -43,14 +43,12 @@
class AiChatService:
- """
- AI对话服务层
- """
+ """AI对话服务层。"""
@classmethod
def _resolve_temperature(cls, user_config: AiChatConfigModel, model_config: AiModelModel) -> float:
"""
- 解析温度配置,优先级为 用户配置 > 模型配置
+ 解析温度配置,优先级为 用户配置 > 模型配置。
:param user_config: 用户配置对象
:param model_config: 模型配置对象
@@ -62,7 +60,7 @@ def _resolve_temperature(cls, user_config: AiChatConfigModel, model_config: AiMo
@classmethod
def _resolve_is_reasoning(cls, chat_req: AiChatRequestModel, model_config: AiModelModel) -> bool:
"""
- 解析深度思考开关,结合请求参数与模型配置确定最终是否开启
+ 解析深度思考开关,结合请求参数与模型配置确定最终是否开启。
:param chat_req: 对话请求对象
:param model_config: 模型配置对象
@@ -75,7 +73,7 @@ def _resolve_is_reasoning(cls, chat_req: AiChatRequestModel, model_config: AiMod
@classmethod
def _resolve_history_config(cls, user_config: AiChatConfigModel) -> tuple[bool, int]:
"""
- 解析历史消息配置,确定是否附带历史以及轮数
+ 解析历史消息配置,确定是否附带历史以及轮数。
:param user_config: 用户配置对象
:return: (是否附带历史, 历史轮数)
@@ -97,7 +95,7 @@ def _build_agent(
num_history: int,
) -> Agent:
"""
- 构建对话Agent对象
+ 构建对话Agent对象。
:param model_config: 模型配置对象
:param temperature: 对话温度
@@ -139,7 +137,7 @@ def _build_run_kwargs(
user_config: AiChatConfigModel,
) -> dict[str, Any]:
"""
- 构造Agent运行参数
+ 构造Agent运行参数。
:param chat_req: 对话请求对象
:param user_config: 用户配置对象
@@ -184,7 +182,7 @@ def _resolve_upload_image_path(cls, image_path: str | None) -> str | None:
@classmethod
def _convert_images_to_upload_paths(cls, images: list[Image] | None) -> list[str] | None:
"""
- 将Agno Image对象列表转换为前端可访问的上传路径列表
+ 将Agno Image对象列表转换为前端可访问的上传路径列表。
:param images: Image对象列表
:return: 上传路径列表
@@ -229,7 +227,7 @@ async def _stream_agent(
locale_context: LocaleContext | None = None,
) -> AsyncGenerator[str, None]:
"""
- 将Agent输出流式转换为前端SSE消息
+ 将Agent输出流式转换为前端SSE消息。
:param agent: Agent实例
:param chat_req: 对话请求对象
@@ -237,7 +235,7 @@ async def _stream_agent(
:param is_reasoning: 是否输出推理内容
:param session_id: 会话ID
:param locale_context: 流创建时的语言上下文
- :return: SSE消息生成器
+ :yield: SSE消息生成器
"""
locale_context = locale_context or RequestContext.get_current_locale()
full_response = ''
@@ -280,7 +278,7 @@ async def _stream_agent(
@staticmethod
def _stream_error(error: Exception, context: LocaleContext) -> str:
"""
- 使用流创建时的语言快照生成错误事件,保留原有事件类型
+ 使用流创建时的语言快照生成错误事件,保留原有事件类型。
:param error: 平台或模型调用异常
:param context: 流创建时的语言上下文
@@ -307,13 +305,13 @@ async def chat_services(
locale_context: LocaleContext | None = None,
) -> AsyncGenerator[str, None]:
"""
- 在流生命周期内固定语言,并将初始化错误转换为平台错误事件
+ 在流生命周期内固定语言,并将初始化错误转换为平台错误事件。
:param query_db: orm对象
:param chat_req: 对话请求对象
:param user_id: 用户ID
:param locale_context: 请求创建流时捕获的语言上下文
- :return: 对话响应流
+ :yield: 对话响应流
"""
snapshot = locale_context or RequestContext.get_current_locale()
try:
@@ -327,13 +325,14 @@ async def _chat_services(
cls, query_db: AsyncSession, chat_req: AiChatRequestModel, user_id: int, locale_context: LocaleContext
) -> AsyncGenerator[str, None]:
"""
- 流式对话
+ 流式对话。
:param query_db: orm对象
:param chat_req: 对话请求对象
:param user_id: 用户ID
:param locale_context: 流创建时的语言上下文
- :return: 对话响应流
+ :yield: 对话响应流
+ :raises ServiceException: 模型不存在;模型已停用
"""
ai_model = await AiModelDao.get_ai_model_detail_by_id(query_db, chat_req.model_id)
if ai_model is None:
@@ -378,7 +377,7 @@ async def _chat_services(
@classmethod
async def ai_chat_config_detail_services(cls, query_db: AsyncSession, user_id: int) -> AiChatConfigModel:
"""
- 获取用户配置
+ 获取用户配置。
:param query_db: orm对象
:param user_id: 用户ID
@@ -396,12 +395,13 @@ async def save_ai_chat_config_services(
cls, query_db: AsyncSession, user_id: int, page_object: AiChatConfigModel
) -> CrudResponseModel:
"""
- 保存用户配置
+ 保存用户配置。
:param query_db: orm对象
:param user_id: 用户ID
:param page_object: AI对话配置对象
:return: 更新后的配置模型
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
chat_config = await AiChatConfigDao.get_chat_config_detail_by_user_id(query_db, user_id)
if page_object.user_id is None:
@@ -431,7 +431,7 @@ async def save_ai_chat_config_services(
@classmethod
async def get_chat_session_list_services(cls, user_id: int) -> list[AiChatSessionBaseModel]:
"""
- 获取用户会话列表
+ 获取用户会话列表。
:param user_id: 用户ID
:return: 用户会话列表
@@ -472,6 +472,7 @@ async def _get_owned_session(cls, storage: Any, session_id: str, user_id: int) -
:param session_id: 会话ID
:param user_id: 用户ID
:return: 会话对象
+ :raises ServiceException: 会话不存在;无权访问该会话
"""
session: Session | None = await storage.get_session(session_id=session_id, session_type=SessionType.AGENT)
if not session:
@@ -484,11 +485,12 @@ async def _get_owned_session(cls, storage: Any, session_id: str, user_id: int) -
@classmethod
async def delete_chat_session_services(cls, session_id: str, user_id: int) -> CrudResponseModel:
"""
- 删除会话
+ 删除会话。
:param session_id: 会话ID
:param user_id: 用户ID
:return: 删除结果
+ :raises ServiceException: 删除会话失败
"""
storage = AiUtil.get_storage_engine()
await cls._get_owned_session(storage, session_id, user_id)
@@ -500,7 +502,7 @@ async def delete_chat_session_services(cls, session_id: str, user_id: int) -> Cr
@classmethod
async def get_chat_session_detail_services(cls, session_id: str, user_id: int) -> AiChatSessionModel:
"""
- 获取会话消息详情
+ 获取会话消息详情。
:param session_id: 会话ID
:param user_id: 用户ID
@@ -569,11 +571,12 @@ async def get_chat_session_detail_services(cls, session_id: str, user_id: int) -
@classmethod
async def cancel_run_services(cls, run_id: str, user_id: int) -> CrudResponseModel:
"""
- 取消运行
+ 取消运行。
:param run_id: 运行ID
:param user_id: 用户ID
:return: 取消结果
+ :raises ServiceException: 无权取消该运行;取消运行失败
"""
if not await cls._user_owns_run(run_id, user_id):
raise ServiceException(message='无权取消该运行', msg_key='ai.run.cancelForbidden', domain='plugin.ai')
diff --git a/ruoyi-fastapi-backend/plugins/ai/service/ai_model_service.py b/ruoyi-fastapi-backend/plugins/ai/service/ai_model_service.py
index 95070868e..f92501d00 100644
--- a/ruoyi-fastapi-backend/plugins/ai/service/ai_model_service.py
+++ b/ruoyi-fastapi-backend/plugins/ai/service/ai_model_service.py
@@ -12,9 +12,7 @@
class AiModelService:
- """
- AI模型管理服务层
- """
+ """AI模型管理服务层。"""
@classmethod
async def get_ai_model_list_services(
@@ -25,7 +23,7 @@ async def get_ai_model_list_services(
is_page: bool = False,
) -> PageModel | list[dict[str, Any]]:
"""
- 获取AI模型列表信息service
+ 获取AI模型列表信息service。
:param query_db: orm对象
:param query_object: 查询参数对象
@@ -50,12 +48,13 @@ async def check_ai_model_data_scope_services(
data_scope_sql: ColumnElement,
) -> CrudResponseModel:
"""
- 校验用户是否有AI模型数据权限service
+ 校验用户是否有AI模型数据权限service。
:param query_db: orm对象
:param model_id: 模型主键
:param data_scope_sql: 数据权限对应的查询sql语句
:return: 校验结果
+ :raises ServiceException: 没有权限访问AI模型数据
"""
ai_models = await AiModelDao.get_ai_model_list(
query_db, AiModelModel(modelId=model_id), data_scope_sql, is_page=False
@@ -67,12 +66,12 @@ async def check_ai_model_data_scope_services(
@classmethod
async def add_ai_model_services(cls, query_db: AsyncSession, page_object: AiModelModel) -> CrudResponseModel:
"""
- 新增AI模型信息service
+ 新增AI模型信息service。
- :param request: Request对象
:param query_db: orm对象
:param page_object: 新增AI模型对象
:return: 新增AI模型校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
try:
if page_object.api_key:
@@ -87,11 +86,13 @@ async def add_ai_model_services(cls, query_db: AsyncSession, page_object: AiMode
@classmethod
async def edit_ai_model_services(cls, query_db: AsyncSession, page_object: AiModelModel) -> CrudResponseModel:
"""
- 编辑AI模型信息service
+ 编辑AI模型信息service。
:param query_db: orm对象
:param page_object: 编辑AI模型对象
:return: 编辑AI模型校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: AI模型不存在
"""
edit_ai_model = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'update_time'})
if page_object.api_key:
@@ -118,11 +119,13 @@ async def delete_ai_model_services(
cls, query_db: AsyncSession, page_object: DeleteAiModelModel
) -> CrudResponseModel:
"""
- 删除AI模型信息service
+ 删除AI模型信息service。
:param query_db: orm对象
:param page_object: 删除AI模型对象
:return: 删除AI模型校验结果
+ :raises Exception: 事务失败并回滚后重新抛出原异常
+ :raises ServiceException: 传入AI模型id为空
"""
if page_object.model_ids:
model_id_list = page_object.model_ids.split(',')
@@ -140,7 +143,7 @@ async def delete_ai_model_services(
@classmethod
async def ai_model_detail_services(cls, query_db: AsyncSession, model_id: int) -> AiModelModel:
"""
- 获取AI模型详细信息service
+ 获取AI模型详细信息service。
:param query_db: orm对象
:param model_id: AI模型id
diff --git a/ruoyi-fastapi-backend/plugins/ai/utils/ai_util.py b/ruoyi-fastapi-backend/plugins/ai/utils/ai_util.py
index 416abf748..30b33a697 100644
--- a/ruoyi-fastapi-backend/plugins/ai/utils/ai_util.py
+++ b/ruoyi-fastapi-backend/plugins/ai/utils/ai_util.py
@@ -63,14 +63,12 @@
class AiUtil:
- """
- AI工具类
- """
+ """AI工具类。"""
@classmethod
def _resolve_provider_class(cls, provider: str) -> 'type[Model] | None':
"""
- 按需加载并缓存提供商模型类
+ 按需加载并缓存提供商模型类。
:param provider: 提供商名称
:return: 模型类,未找到返回None
@@ -88,7 +86,7 @@ def _resolve_provider_class(cls, provider: str) -> 'type[Model] | None':
@classmethod
def _resolve_storage_class(cls, db_type: str) -> 'type[AsyncBaseDb]':
"""
- 按需加载并缓存存储引擎类
+ 按需加载并缓存存储引擎类。
:param db_type: 数据库类型
:return: 存储引擎类
@@ -107,7 +105,7 @@ def _resolve_storage_class(cls, db_type: str) -> 'type[AsyncBaseDb]':
@classmethod
def get_storage_engine(cls) -> 'AsyncBaseDb':
"""
- 获取存储引擎实例
+ 获取存储引擎实例。
:return: 存储引擎实例
"""
@@ -136,6 +134,7 @@ def _validate_base_url(cls, base_url: str | None) -> str | None:
:param base_url: 基础URL
:return: 校验后的基础URL
+ :raises ValueError: Base URL 只支持 http/https 且必须包含主机名;Base URL 不允许指向本机或内网地址
"""
if not base_url:
return None
@@ -178,8 +177,9 @@ def get_model_from_factory(
**kwargs,
) -> 'Model':
"""
- 从工厂获取模型实例
+ 从工厂获取模型实例。
+ :param kwargs: 传给被调用对象的关键字参数
:param provider: 提供商
:param model_code: 模型编码
:param model_name: 模型名称
@@ -188,6 +188,7 @@ def get_model_from_factory(
:param temperature: 温度
:param max_tokens: 最大令牌数
:return: 模型实例
+ :raises ValueError: 模型提供商没有注册对应的实现
"""
safe_base_url = cls._validate_base_url(base_url)
params = {
diff --git a/ruoyi-fastapi-backend/plugins/core/artifacts/package.py b/ruoyi-fastapi-backend/plugins/core/artifacts/package.py
index 1e7a89562..a139f93d9 100644
--- a/ruoyi-fastapi-backend/plugins/core/artifacts/package.py
+++ b/ruoyi-fastapi-backend/plugins/core/artifacts/package.py
@@ -99,7 +99,6 @@ def _payload_path(name: str) -> None:
校验部署文件路径,拒绝源码工程、环境文件和构建缓存。
:param name: 制品内文件的规范相对路径
- :return: None
:raises ValueError: 路径不安全或包含禁止交付的文件
"""
path = safe_artifact_path(name)
@@ -207,7 +206,6 @@ def _preflight_zip(path: Path, limits: ArtifactLimits) -> None:
:param path: 待处理的文件路径
:param limits: 文件数量、大小及压缩容器的资源上限
- :return: None
:raises ValueError: ZIP 结束记录、中央目录或容器类型不受支持
"""
with path.open('rb') as stream:
@@ -242,7 +240,6 @@ def _preflight_entries(stream: BinaryIO, central_end: int, count: int, limits: A
:param central_end: 中央目录结束位置的绝对字节偏移
:param count: ZIP 结束记录声明的条目数量
:param limits: 文件数量、大小及压缩容器的资源上限
- :return: None
:raises ValueError: 中央目录记录不完整、越界或实际数量不匹配
"""
actual_count = 0
diff --git a/ruoyi-fastapi-backend/plugins/core/artifacts/schema.py b/ruoyi-fastapi-backend/plugins/core/artifacts/schema.py
index d0154e982..5f5168c69 100644
--- a/ruoyi-fastapi-backend/plugins/core/artifacts/schema.py
+++ b/ruoyi-fastapi-backend/plugins/core/artifacts/schema.py
@@ -31,6 +31,16 @@
class ArtifactLimits:
"""
制品压缩容器、元数据和实际展开内容的独立资源上限。
+
+ :ivar max_files: 制品归档允许的最大文件数
+ :ivar max_file_bytes: 归档中单个文件允许的最大字节数
+ :ivar max_total_bytes: 解压后的内容允许占用的最大字节数
+ :ivar max_archive_bytes: 归档本身允许的最大字节数
+ :ivar max_central_directory_bytes: ZIP 中央目录允许的最大字节数
+ :ivar max_metadata_bytes: 制品元数据允许的最大字节数
+ :ivar max_signature_bytes: 签名文件允许的最大字节数
+ :ivar max_manifest_bytes: 插件清单允许的最大字节数
+ :ivar max_compression_ratio: 解压后大小与压缩大小的最大比值
"""
max_files: int = 10000
@@ -83,7 +93,6 @@ def validate_path_inventory(files: list[str] | tuple[str, ...], directories: set
:param files: 全部文件的相对路径列表
:param directories: 压缩容器显式声明的目录集合,可不提供
- :return: None
:raises ValueError: 文件或目录存在重复、大小写歧义或层级冲突
"""
all_spellings: dict[str, str] = {}
@@ -139,7 +148,6 @@ def invalid_constant(value: str) -> None:
拒绝 JSON 中不属于标准数值范围的常量。
:param value: JSON 解析器识别到的非法常量文本
- :return: None
:raises ValueError: 遇到 NaN、Infinity 等非标准 JSON 常量
"""
raise ValueError(f'制品 JSON 包含非法常量:{value}')
@@ -154,15 +162,13 @@ def invalid_constant(value: str) -> None:
class ArtifactFile(BaseModel):
- """
- 签名文件记录,路径相对于 rpk 根目录并位于自身 payload 目录中。
- """
+ """签名文件记录,路径相对于 rpk 根目录并位于自身 payload 目录中。"""
model_config = ConfigDict(strict=True, extra='forbid', frozen=True)
- path: str
- size: int = Field(ge=0)
- sha256: str = Field(pattern=r'^[a-f0-9]{64}$')
+ path: str = Field(description='文件或资源路径')
+ size: int = Field(ge=0, description='文件大小(字节)')
+ sha256: str = Field(pattern=r'^[a-f0-9]{64}$', description='文件内容的 SHA-256 摘要')
@field_validator('path')
@classmethod
@@ -179,16 +185,14 @@ def validate_path(cls, value: str) -> str:
class ArtifactMetadata(BaseModel):
- """
- 签名覆盖的制品元数据,字段及文件列表顺序共同确定签名内容。
- """
+ """签名覆盖的制品元数据,字段及文件列表顺序共同确定签名内容。"""
model_config = ConfigDict(strict=True, extra='forbid', frozen=True)
- schema_version: Literal[1] = Field(alias='schemaVersion')
- plugin_id: str = Field(alias='pluginId')
- version: str = Field(min_length=1, max_length=32, pattern=r'^[0-9][a-z0-9._+\-]*$')
- files: tuple[ArtifactFile, ...]
+ schema_version: Literal[1] = Field(alias='schemaVersion', description='数据结构的版本')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ version: str = Field(min_length=1, max_length=32, pattern=r'^[0-9][a-z0-9._+\-]*$', description='插件版本')
+ files: tuple[ArtifactFile, ...] = Field(description='制品中包含的文件及其校验信息')
@field_validator('schema_version', mode='before')
@classmethod
@@ -271,15 +275,13 @@ def canonical_bytes(self) -> bytes:
class ArtifactSignature(BaseModel):
- """
- Ed25519 签名记录,密钥标识仅用于查询宿主提供的信任配置。
- """
+ """Ed25519 签名记录,密钥标识仅用于查询宿主提供的信任配置。"""
model_config = ConfigDict(strict=True, extra='forbid', frozen=True)
- algorithm: Literal['Ed25519']
- key_id: str = Field(alias='keyId', pattern=KEY_ID_PATTERN.pattern)
- signature: str
+ algorithm: Literal['Ed25519'] = Field(description='制品签名算法')
+ key_id: str = Field(alias='keyId', pattern=KEY_ID_PATTERN.pattern, description='签名密钥标识')
+ signature: str = Field(description='对制品元数据计算的签名')
def signature_bytes(self) -> bytes:
"""
@@ -363,6 +365,16 @@ def _key_bytes(value: bytes | str) -> bytes:
class VerifiedArtifact:
"""
完成静态校验的容器信息,不替代文件变化后的重新验证。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar version: 当前记录的版本
+ :ivar digest: 用于验证内容完整性的摘要
+ :ivar key_id: 验证签名时选择密钥的标识
+ :ivar files: 全部文件的相对路径列表
+ :ivar metadata: 签名覆盖的制品元数据,字段及文件列表顺序共同确定签名内容
+ :ivar signature: Ed25519 签名记录,密钥标识仅用于查询宿主提供的信任配置
+ :ivar manifest: 插件主清单
+ :ivar artifact_path: 插件制品在文件系统中的路径
"""
plugin_id: str
@@ -380,6 +392,17 @@ class VerifiedArtifact:
class StoredArtifact:
"""
完成验证的不可变存储信息,供平台预检与发布服务读取。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar version: 当前记录的版本
+ :ivar digest: 用于验证内容完整性的摘要
+ :ivar key_id: 验证签名时选择密钥的标识
+ :ivar files: 全部文件的相对路径列表
+ :ivar metadata: 签名覆盖的制品元数据,字段及文件列表顺序共同确定签名内容
+ :ivar signature: Ed25519 签名记录,密钥标识仅用于查询宿主提供的信任配置
+ :ivar manifest: 插件主清单
+ :ivar root_path: 应用或制品使用的根路径
+ :ivar plugin_path: 插件目录
"""
plugin_id: str
diff --git a/ruoyi-fastapi-backend/plugins/core/artifacts/store.py b/ruoyi-fastapi-backend/plugins/core/artifacts/store.py
index d81c676fb..de0bb3d37 100644
--- a/ruoyi-fastapi-backend/plugins/core/artifacts/store.py
+++ b/ruoyi-fastapi-backend/plugins/core/artifacts/store.py
@@ -42,6 +42,9 @@
class ArtifactStore:
"""
不可变制品存储,每次使用时重新检查签名和内容。
+
+ :ivar root: 不可变制品存储的根目录
+ :ivar limits: 文件数量、大小及压缩容器的资源上限
"""
def __init__(self, root: Path | str, *, limits: ArtifactLimits = DEFAULT_LIMITS) -> None:
@@ -50,7 +53,6 @@ def __init__(self, root: Path | str, *, limits: ArtifactLimits = DEFAULT_LIMITS)
:param root: 不可变制品存储的根目录
:param limits: 文件数量、大小及压缩容器的资源上限
- :return: None
"""
self.root = Path(os.path.abspath(root))
self.limits = limits
@@ -62,7 +64,6 @@ def _assert_real_path(path: Path) -> None:
从文件系统根逐级检查路径,拒绝符号链接和 Windows 重解析点。
:param path: 待处理的文件路径
- :return: None
:raises ValueError: 路径本身或某一级父路径为链接或重解析点
"""
for current in reversed([path, *path.parents]):
@@ -78,7 +79,7 @@ def _mkdir(self, path: Path) -> None:
校验父路径后创建普通目录,并重新检查目录边界。
:param path: 待创建的存储内部目录路径
- :return: None
+ :raises ValueError: 制品存储路径越界;制品存储路径不是目录
"""
if not path.is_relative_to(self.root):
raise ValueError('制品存储路径越界')
@@ -149,7 +150,7 @@ def _snapshot(self, source: Path, target: Path) -> None:
:param source: 待复制内容的源文件路径
:param target: 本次导入独占的容器快照路径
- :return: None
+ :raises ValueError: 制品容器大小超过限制
"""
if _regular_file(source).st_size > self.limits.max_archive_bytes:
raise ValueError('制品容器大小超过限制')
@@ -163,7 +164,7 @@ def _extract(self, snapshot: Path, candidate: Path, verified: VerifiedArtifact)
:param snapshot: 已经完成验签的私有容器快照路径
:param candidate: 本次导入独占的候选根目录
:param verified: 私有容器快照对应的验证结果
- :return: None
+ :raises ValueError: 制品解压目标越界;制品快照在解压期间发生变化
"""
candidate.mkdir()
expected = {item.path: item for item in verified.files}
@@ -191,7 +192,6 @@ def _validate_candidate(
:param candidate: 待执行静态检查的候选制品对象
:param trusted_keys: 由宿主提供的签名密钥标识与可信公钥映射
:param callback: 同步只读检查回调,为 None 时跳过附加检查
- :return: None
:raises ValueError: 回调拒绝候选或修改了受保护内容
:raises TypeError: 回调返回异步对象,无法同步完成检查
"""
@@ -294,8 +294,10 @@ def _digest_lock(self, digest: str) -> Iterator[None]:
使用操作系统文件锁串行化同一摘要的发布,进程退出时自动释放。
:param digest: 制品规范元数据的小写 SHA256 摘要
- :return: 持有对应摘要锁的上下文
+ :yield: 持有对应摘要锁的上下文
:raises TimeoutError: 等待同一制品摘要的文件锁超时
+ :raises ValueError: 制品锁文件必须为普通文件
+ :raises OSError: 获取文件锁时遇到无法通过等待重试的系统错误
"""
lock_root = self.root / '.locks'
self._mkdir(lock_root)
@@ -335,7 +337,6 @@ def _lock_file(descriptor: int, *, unlock: bool) -> None:
:param descriptor: 本次发布锁文件的文件描述符
:param unlock: 是否释放已有锁,为 False 时尝试获取锁
- :return: None
"""
os.lseek(descriptor, 0, os.SEEK_SET)
if os.name == 'nt':
diff --git a/ruoyi-fastapi-backend/plugins/core/capability.py b/ruoyi-fastapi-backend/plugins/core/capability.py
index 81e4b99b9..c46c7e438 100644
--- a/ruoyi-fastapi-backend/plugins/core/capability.py
+++ b/ruoyi-fastapi-backend/plugins/core/capability.py
@@ -39,6 +39,17 @@
class PluginRuntimeCapability:
"""
插件运行时操作能力。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar frontend_mode: 前端运行模式
+ :ivar backend_runtime_mode: 后端运行模式
+ :ivar has_frontend_resources: 插件是否声明了前端资源
+ :ivar frontend_build_required: 启用前端资源前是否需要构建
+ :ivar frontend_runtime_manageable: 是否支持在运行时管理插件前端
+ :ivar backend_runtime_manageable: 是否支持在运行时管理插件后端
+ :ivar runtime_manageable: 是否支持运行时管理
+ :ivar blocked_operations: 插件当前无法执行的管理操作
+ :ivar warnings: 检查插件能力时产生的提示
"""
plugin_id: str
@@ -94,6 +105,9 @@ def to_payload(self) -> dict[str, object]:
class PluginRuntimeCapabilityResolver:
"""
插件运行时能力解析器。
+
+ :ivar frontend_mode: 前端运行模式
+ :ivar backend_runtime_mode: 后端运行模式
"""
def __init__(self, *, frontend_mode: str, backend_runtime_mode: str) -> None:
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/catalog.py b/ruoyi-fastapi-backend/plugins/core/deployment/catalog.py
index 0c76003ff..8fca10e93 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/catalog.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/catalog.py
@@ -34,6 +34,11 @@ def artifact_payload(artifact: Any) -> dict[str, Any]:
class PluginArtifactCatalog:
"""
已验证制品文件与数据库索引之间的访问服务。
+
+ :ivar config: 制品发布配置快照
+ :ivar session_factory: 异步数据库会话工厂,未提供时使用宿主数据源
+ :ivar dao: 制品、发布目标及进程报告的数据访问接口
+ :ivar lifecycle_lock: 与维护、清理和轮换共用的全局生命周期锁
"""
def __init__(
@@ -51,7 +56,6 @@ def __init__(
:param session_factory: 异步数据库会话工厂,未提供时使用宿主数据源
:param dao: 制品、发布目标及进程报告的数据访问接口
:param lifecycle_lock: 与维护、清理和轮换共用的全局生命周期锁
- :return: None
"""
self.config = config
self.session_factory = session_factory or DataSourceRegistry.session
@@ -62,7 +66,7 @@ def require_no_pending_maintenance(self) -> None:
"""
拒绝在文件与索引尚未完成恢复时导入或加载制品。
- :return: None
+ :raises ValueError: 存在未完成的制品维护,请先执行 artifact reconcile
"""
pending = self.config.store_root / '.maintenance'
ArtifactStore._assert_real_path(pending)
@@ -84,7 +88,6 @@ def reject_source_conflict(self, plugin_id: str) -> None:
检查目标插件ID是否与已有源码目录冲突。
:param plugin_id: 插件ID
- :return: None
:raises ValueError: 源码插件目录与制品插件ID冲突
"""
if (self.config.backend_root / 'plugins' / plugin_id).exists():
@@ -106,7 +109,6 @@ def validate_candidate(self, artifact: StoredArtifact) -> None:
校验候选制品的交付协议、发布者授权及静态平台兼容性。
:param artifact: 已完成签名和文件校验的制品对象
- :return: None
:raises ValueError: 协议、信任授权、源码目录或运行平台校验失败
"""
if (
@@ -165,6 +167,7 @@ async def _import_locked(self, path: Path | str, keys: dict[str, Any], actor: st
:param keys: 当前可信公钥
:param actor: 操作者
:return: 导入后的制品身份
+ :raises asyncio.CancelledError: 异步操作被取消时
"""
work = asyncio.create_task(
asyncio.to_thread(self.store.import_artifact, path, keys, validate_candidate=self.validate_candidate)
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/config.py b/ruoyi-fastapi-backend/plugins/core/deployment/config.py
index 1d6132c70..d86458fcf 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/config.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/config.py
@@ -11,15 +11,13 @@
class TrustedPublisher(BaseModel):
- """
- 将公钥与可发布插件ID显式绑定的发布者配置。
- """
+ """将公钥与可发布插件ID显式绑定的发布者配置。"""
model_config = ConfigDict(extra='forbid', populate_by_name=True, strict=True)
- key_id: str = Field(alias='keyId', pattern=r'^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$')
- public_key: str = Field(alias='publicKey', min_length=1, max_length=8192)
- plugin_ids: list[str] = Field(alias='pluginIds', min_length=1, max_length=256)
- enabled: bool = True
+ key_id: str = Field(alias='keyId', pattern=r'^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$', description='签名密钥标识')
+ public_key: str = Field(alias='publicKey', min_length=1, max_length=8192, description='用于验证制品签名的公钥')
+ plugin_ids: list[str] = Field(alias='pluginIds', min_length=1, max_length=256, description='插件标识列表')
+ enabled: bool = Field(default=True, description='是否启用')
@field_validator('plugin_ids')
@classmethod
@@ -41,13 +39,11 @@ def validate_plugin_ids(cls, values: list[str]) -> list[str]:
class PluginTrustDocument(BaseModel):
- """
- 由宿主管理的发布者公钥及授权范围配置文档。
- """
+ """由宿主管理的发布者公钥及授权范围配置文档。"""
model_config = ConfigDict(extra='forbid', populate_by_name=True, strict=True)
- schema_version: int = Field(alias='schemaVersion', ge=1, le=1)
- keys: list[TrustedPublisher] = Field(max_length=256)
+ schema_version: int = Field(alias='schemaVersion', ge=1, le=1, description='数据结构的版本')
+ keys: list[TrustedPublisher] = Field(max_length=256, description='受信任的制品签发者及其密钥')
def _unique_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
@@ -70,6 +66,13 @@ def _unique_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
class PluginDeploymentConfig:
"""
制品发布配置快照,支持为测试和维护实例注入独立目录。
+
+ :ivar backend_root: 后端项目的根目录
+ :ivar store_root: 保存已验证插件制品的根目录
+ :ivar trust_file: 本次验收使用的临时发布者公钥文件
+ :ivar enabled: 是否启用该项功能
+ :ivar heartbeat_seconds: 两次发送心跳的时间间隔(秒)
+ :ivar worker_ttl_seconds: 发布 worker 的有效心跳秒数
"""
backend_root: Path
@@ -104,7 +107,6 @@ def require_enabled(self) -> None:
"""
检查发布功能已启用且制品存储与源码目录相互隔离。
- :return: None
:raises ValueError: 功能未启用或制品存储与宿主源码路径重叠
"""
if not self.enabled:
@@ -148,7 +150,6 @@ def authorize_publisher(self, key_id: str, plugin_id: str) -> None:
:param key_id: 签名公钥在宿主信任配置中的标识
:param plugin_id: 插件ID
- :return: None
:raises ValueError: 发布者不受信任、已停用或未获准发布指定插件
"""
publisher = self.read_publishers().get(key_id)
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/convergence.py b/ruoyi-fastapi-backend/plugins/core/deployment/convergence.py
index a34a85eab..102626401 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/convergence.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/convergence.py
@@ -47,7 +47,14 @@
@dataclass(frozen=True)
class _ReleaseTarget:
- """调用方固定的插件、制品、代际和预期容量,轮询期间不跟随数据库目标变化。"""
+ """
+ 调用方固定的插件、制品、代际和预期容量,轮询期间不跟随数据库目标变化。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar digest: 固定验收的制品 SHA256 摘要
+ :ivar generation: 当前发布或部署的代次
+ :ivar expected_workers: 必须与发布记录一致的预期 worker 数量
+ """
plugin_id: str
digest: str
@@ -58,7 +65,6 @@ def __post_init__(self) -> None:
"""
校验固定发布身份及容量,拒绝布尔值冒充预期 worker 数量。
- :return: None
:raises ValueError: 插件 ID、摘要、代际或预期数量不合法
"""
validate_plugin_id_value(self.plugin_id)
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/enablement.py b/ruoyi-fastapi-backend/plugins/core/deployment/enablement.py
index ba9a3d1c8..d208d2b8a 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/enablement.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/enablement.py
@@ -13,9 +13,7 @@
class PluginArtifactEnablementService(PluginDeploymentService):
- """
- 在停机维护窗口原子更新制品启停状态与声明资源的服务。
- """
+ """在停机维护窗口原子更新制品启停状态与声明资源的服务。"""
async def set_enabled(
self,
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/maintenance.py b/ruoyi-fastapi-backend/plugins/core/deployment/maintenance.py
index d895d918f..1076a9299 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/maintenance.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/maintenance.py
@@ -22,9 +22,7 @@
class PluginArtifactMaintenanceService(PluginDeploymentService):
- """
- 停机维护制品存储,使用可恢复日志连接文件变更与数据库事务。
- """
+ """停机维护制品存储,使用可恢复日志连接文件变更与数据库事务。"""
def _object_path(self, relative: str) -> Path:
"""
@@ -32,6 +30,7 @@ def _object_path(self, relative: str) -> Path:
:param relative: 存储内的插件、版本和摘要路径
:return: 已检查的绝对目录
+ :raises ValueError: 制品维护目录必须是 plugin/version/digest
"""
parts = safe_artifact_path(relative).parts
if len(parts) != OBJECT_PATH_PARTS or not DIGEST_PATTERN.fullmatch(parts[-1]):
@@ -55,6 +54,7 @@ def _paths(self) -> list[Path]:
有界枚举普通制品目录,在进入每级目录前排除链接。
:return: 已检查边界的摘要目录列表
+ :raises ValueError: 制品数量超过单次维护检查上限
"""
root = self.catalog.store.root
result = []
@@ -85,6 +85,7 @@ async def inspect(self, *, keep_last: int = 2, min_age_days: int = 7) -> dict[st
:param keep_last: 每个插件至少保留的最近导入制品数量
:param min_age_days: 制品最短保留天数
:return: 完整检查结果、候选摘要与计划摘要
+ :raises ValueError: 保留数量和天数不能为负数
"""
self.config.require_enabled()
if keep_last < 0 or min_age_days < 0:
@@ -145,7 +146,6 @@ def _inspect_object(
:param reasons: 当前保护原因
:param cutoff: 最短保留时间边界
:param keys: 当前可信公钥
- :return: None
"""
relative = row['relativePath']
try:
@@ -193,6 +193,7 @@ def _quarantine(self, digest: str) -> Path:
:param digest: 已校验的制品摘要
:return: 存储内部的隔离路径
+ :raises ValueError: 维护日志摘要无效
"""
if not DIGEST_PATTERN.fullmatch(digest):
raise ValueError('维护日志摘要无效')
@@ -208,7 +209,7 @@ def _remove_quarantine(self, path: Path, digest: str) -> None:
:param path: 本次维护隔离目录
:param digest: 授权清理的摘要
- :return: None
+ :raises ValueError: 制品清理目录越界;隔离制品摘要不一致
"""
root = (self.catalog.store.root / '.maintenance' / 'objects').resolve()
ArtifactStore._assert_real_path(path)
@@ -239,6 +240,7 @@ async def prune(
:param maintenance: 是否确认全部宿主进程已停止
:param actor: 操作者
:return: 计划或实际清理摘要
+ :raises ValueError: 制品清理计划已变化,请重新预演并核对 --expected-plan;隔离目录已存在,须先恢复维护日志
"""
if dry_run:
return await self.inspect(keep_last=keep_last, min_age_days=min_age_days)
@@ -276,7 +278,6 @@ def _replace_signature(self, path: Path, signature: str) -> None:
:param path: 已验证的制品根目录
:param signature: 待写入的签名 JSON
- :return: None
"""
temporary_root = self.catalog.store.root / '.maintenance'
ArtifactStore._assert_real_path(temporary_root)
@@ -308,6 +309,7 @@ async def rotate_signature(
:param maintenance: 是否确认全部宿主进程已停止
:param actor: 操作者
:return: 保持摘要与版本不变的轮换结果
+ :raises ValueError: 制品未登记或签名密钥已变化;新旧签名密钥标识必须不同;轮换制品内容与原索引不一致;制品签名索引发生并发变化
"""
self._require_maintenance(maintenance)
async with self.lifecycle_lock.lock('__artifacts__', 'artifact_rotate_signature') as lock:
@@ -383,6 +385,7 @@ async def reconcile(self, *, maintenance: bool = False, actor: str | None = None
:param maintenance: 是否确认全部宿主进程已停止
:param actor: 操作者
:return: 已恢复的制品摘要列表
+ :raises ValueError: 制品维护日志过大;制品维护日志身份无效;维护日志目录与摘要不一致;未知制品维护日志操作
"""
self._require_maintenance(maintenance)
restored = []
@@ -432,7 +435,7 @@ def _recover_prune(self, journal: dict[str, Any], path: Path, record: Any) -> No
:param journal: 已检查的维护日志
:param path: 规范制品目录
:param record: 当前已提交的索引
- :return: None
+ :raises ValueError: 原目录和隔离目录同时存在,拒绝自动覆盖;隔离对象与日志摘要不一致;恢复目标与制品索引不一致;索引仍存在但原目录和隔离目录均已丢失
"""
digest = journal['digest']
quarantine = self._quarantine(digest)
@@ -458,7 +461,7 @@ def _recover_rotation(self, journal: dict[str, Any], path: Path, record: Any) ->
:param journal: 已检查的维护日志
:param path: 规范制品目录
:param record: 当前已提交的索引
- :return: None
+ :raises ValueError: 轮换恢复缺少匹配的制品索引;签名索引已被其他操作更新;轮换恢复签名与日志身份不一致
"""
digest = journal['digest']
if record is None or record.relative_path != journal['relativePath']:
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/service.py b/ruoyi-fastapi-backend/plugins/core/deployment/service.py
index a53fb7055..f13e15adb 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/service.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/service.py
@@ -60,6 +60,13 @@ def build_maintenance_runtime(config: PluginDeploymentConfig, plugins: list[Disc
class PluginDeploymentService:
"""
签名制品维护准备、发布目标选择及集群状态查询服务。
+
+ :ivar config: 制品发布配置快照
+ :ivar session_factory: 异步数据库会话工厂,未提供时使用宿主数据源
+ :ivar dao: 制品、发布目标及进程报告的数据访问接口
+ :ivar catalog: 当前运行时使用的插件目录
+ :ivar lifecycle_lock: 与插件维护发布共用的生命周期锁
+ :ivar runtime_factory: 用于创建独立维护运行时的工厂
"""
def __init__(
@@ -79,7 +86,6 @@ def __init__(
:param dao: 制品、发布目标及进程报告的数据访问接口
:param lifecycle_lock: 与插件维护发布共用的生命周期锁
:param runtime_factory: 用于创建独立维护运行时的工厂
- :return: None
"""
self.config = config
self.session_factory = session_factory or DataSourceRegistry.session
@@ -176,7 +182,6 @@ async def _require_quiescent(self) -> None:
该检查依赖已上报的进程状态,调用方仍须先实际停止全部宿主进程。
- :return: None
:raises ValueError: 仍存在有效期内且尚未停止的宿主进程报告
"""
cutoff = TimezoneUtil.utc_now() - timedelta(seconds=self.config.worker_ttl_seconds)
@@ -194,7 +199,6 @@ def _require_maintenance(maintenance: bool) -> None:
要求调用方显式确认已进入停机维护窗口。
:param maintenance: 是否已显式确认在停止全部宿主进程后执行维护
- :return: None
:raises ValueError: 调用方未显式确认停机维护
"""
if not maintenance:
@@ -206,7 +210,6 @@ def _require_clean_process(plugin: DiscoveredPlugin) -> None:
拒绝已加载目标插件模块的进程继续执行制品维护准备。
:param plugin: 本次拟执行维护准备的插件发现对象
- :return: None
:raises ValueError: 当前进程已经导入该插件的模块命名空间
"""
namespace = plugin.manifest.backend.module
@@ -328,6 +331,7 @@ async def prepare(
:param dry_run: 是否只执行预检而不写入文件或数据库
:return: 维护准备结果或只读预检计划
:raises ValueError: 维护条件、版本顺序或生命周期准备结果不符合发布要求
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
if dry_run:
return await self.plan(plugin_id, digest)
@@ -549,7 +553,6 @@ async def _audit(db: Any, payload: dict[str, Any], actor: str | None) -> None:
:param db: 当前操作使用的数据库会话
:param payload: 需要写入审计的操作结果数据
:param actor: 本次操作的执行者,未提供时不记录执行者名称
- :return: None
"""
await PluginService.add_plugin_operation_log_services(
db, {**payload, 'operatedBy': actor}, dry_run=False, continue_on_error=False
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/state.py b/ruoyi-fastapi-backend/plugins/core/deployment/state.py
index 9d0c3460b..6ffeb11dd 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/state.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/state.py
@@ -101,6 +101,22 @@ def _release_status(target_digest: str | None, live: int, healthy: int, failed:
class PluginReleaseSummary:
"""
发布目标在全部存活宿主进程中的状态汇总。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar target_digest: 当前发布目标的制品摘要
+ :ivar generation: 发布代际标识
+ :ivar status: 操作或记录所处的状态
+ :ivar restart_required: 当前发布是否需要重启工作进程
+ :ivar expected_workers: 预期参与部署的工作进程
+ :ivar live_workers: 仍在发送心跳的工作进程
+ :ivar healthy_workers: 健康检查通过的工作进程
+ :ivar disabled_workers: 已停用的工作进程
+ :ivar mismatch_workers: 当前版本与目标不一致的工作进程
+ :ivar stale_workers: 最近心跳已过期的工作进程
+ :ivar missing_workers: 尚未报告状态的目标工作进程
+ :ivar failed_workers: 准备或加载插件失败的工作进程
+ :ivar prepare_status: 制品准备阶段的状态
+ :ivar last_error: 最近一次错误信息
"""
plugin_id: str
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/worker.py b/ruoyi-fastapi-backend/plugins/core/deployment/worker.py
index 235d92b62..871de6d2d 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/worker.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/worker.py
@@ -22,6 +22,12 @@
class WorkerTarget:
"""
当前宿主进程固定的插件目标、发布代际和维护准备状态快照。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar digest: 用于验证内容完整性的摘要
+ :ivar generation: 当前发布或部署的代次
+ :ivar enabled: 是否启用该项功能
+ :ivar prepared: 工作进程是否已准备好目标制品
"""
plugin_id: str
@@ -34,6 +40,20 @@ class WorkerTarget:
class PluginReleaseWorker:
"""
宿主发布快照与心跳上报器,注册时与维护服务共用全局锁。
+
+ :ivar config: 制品发布配置快照
+ :ivar session_factory: 异步数据库会话工厂,未提供时使用宿主数据源
+ :ivar dao: 制品、发布目标及进程报告的数据访问接口
+ :ivar catalog: 当前运行时使用的插件目录
+ :ivar worker_id: 工作进程的标识
+ :ivar targets: 当前工作进程需要加载的发布目标
+ :ivar reserved_ids: 已被制品发布记录占用的插件 ID 集合
+ :ivar versions: 按插件标识记录的版本
+ :ivar errors: 按条目收集的异常或失败原因
+ :ivar state: 当前流程的状态
+ :ivar task: 在后台执行当前工作的异步任务
+ :ivar app: 当前宿主应用对象
+ :ivar registered: 已注册的对象集合
"""
def __init__(
@@ -49,7 +69,6 @@ def __init__(
:param config: 制品发布配置快照
:param session_factory: 异步数据库会话工厂,未提供时使用宿主数据源
:param dao: 制品、发布目标及进程报告的数据访问接口
- :return: None
"""
self.config = config
self.session_factory = session_factory or DataSourceRegistry.session
@@ -73,7 +92,6 @@ async def start(self, app: Any, builder: Any, lifecycle_lock: Any, *, lock_wait_
:param builder: 接收制品发现快照的插件运行时构建器
:param lifecycle_lock: 与插件维护发布共用的生命周期锁
:param lock_wait_seconds: 等待生命周期锁的最长时间,单位为秒
- :return: None
:raises TimeoutError: 在等待时限内未能取得维护发布锁
"""
self.config.require_enabled()
@@ -118,11 +136,7 @@ async def start(self, app: Any, builder: Any, lifecycle_lock: Any, *, lock_wait_
await self.report()
async def _register_snapshot(self) -> None:
- """
- 固定当前发布目标和保留插件ID,并登记正在启动的宿主进程。
-
- :return: None
- """
+ """固定当前发布目标和保留插件ID,并登记正在启动的宿主进程。"""
async with self.session_factory() as db:
targets = []
# 即使尚未选择目标,已导入制品的 ID 也不能回退为同名源码插件。
@@ -175,7 +189,6 @@ async def assert_snapshot_current(self) -> None:
"""
在导入或就绪前确认数据库发布目标仍与当前进程快照一致。
- :return: None
:raises RuntimeError: 当前发布目标或代际与进程启动快照不一致
"""
async with self.session_factory() as db:
@@ -192,7 +205,6 @@ async def ready(self) -> None:
"""
确认发布快照未变后上报宿主就绪及各插件的实际状态。
- :return: None
:raises RuntimeError: 当前发布目标或代际在启动过程中发生变化
"""
await self.assert_snapshot_current()
@@ -223,11 +235,7 @@ def _plugin_state(self, target: WorkerTarget) -> tuple[str, str | None]:
return 'failed', '当前 worker 未完成目标制品激活或健康检查'
async def report(self) -> None:
- """
- 以同一心跳时间写入宿主状态及全部目标插件的实际加载状态。
-
- :return: None
- """
+ """以同一心跳时间写入宿主状态及全部目标插件的实际加载状态。"""
if not self.registered:
return
now = TimezoneUtil.utc_now()
@@ -251,11 +259,7 @@ async def report(self) -> None:
await db.commit()
async def _heartbeat(self) -> None:
- """
- 周期性刷新进程报告,数据库暂不可用时保留旧报告等待自然过期。
-
- :return: None
- """
+ """周期性刷新进程报告,数据库暂不可用时保留旧报告等待自然过期。"""
while True:
await asyncio.sleep(self.config.heartbeat_seconds)
try:
@@ -269,7 +273,6 @@ async def stop(self, *, failed: bool = False) -> None:
停止心跳任务,并上报正常停止或宿主失败状态。
:param failed: 是否以失败状态结束宿主报告,为 False 时报告正常停止
- :return: None
"""
if self.task is not None:
self.task.cancel()
diff --git a/ruoyi-fastapi-backend/plugins/core/discovery/registry.py b/ruoyi-fastapi-backend/plugins/core/discovery/registry.py
index ff28df01d..b929ebab1 100644
--- a/ruoyi-fastapi-backend/plugins/core/discovery/registry.py
+++ b/ruoyi-fastapi-backend/plugins/core/discovery/registry.py
@@ -10,6 +10,11 @@
class RegisteredPlugin:
"""
已注册插件运行时快照。
+
+ :ivar discovered_plugin: 扫描插件目录后得到的插件描述
+ :ivar database_plugin: 数据库插件状态
+ :ivar enabled: 是否启用
+ :ivar status: 操作或记录所处的状态
"""
discovered_plugin: DiscoveredPlugin
@@ -41,6 +46,8 @@ class PluginRegistry:
插件运行时注册表。
使用 Registry 模式维护已发现插件与数据库状态合并后的运行时快照。
+
+ :ivar _registered_plugins: 已注册插件运行时快照列表
"""
def __init__(self, registered_plugins: list[RegisteredPlugin]) -> None:
diff --git a/ruoyi-fastapi-backend/plugins/core/discovery/scanner.py b/ruoyi-fastapi-backend/plugins/core/discovery/scanner.py
index 7eab247b1..6c38e420f 100644
--- a/ruoyi-fastapi-backend/plugins/core/discovery/scanner.py
+++ b/ruoyi-fastapi-backend/plugins/core/discovery/scanner.py
@@ -15,6 +15,12 @@
class DiscoveredPlugin:
"""
已发现插件。
+
+ :ivar manifest: 插件主清单
+ :ivar backend_path: 后端插件相对路径
+ :ivar manifest_path: 插件清单路径
+ :ivar artifact_digest: 进程实际加载的制品摘要,宿主报告不设置此值
+ :ivar artifact_generation: 发现该插件时对应的制品代次
"""
manifest: PluginManifest
@@ -41,6 +47,10 @@ class PluginDiscoveryError:
插件发现错误。
用于在容错扫描模式下记录单个插件加载失败,便于上层隔离损坏插件。
+
+ :ivar manifest_path: 插件清单路径
+ :ivar plugin_dir: 保存插件清单和资源的目录
+ :ivar error_message: 记录到结果或审计日志中的错误详情
"""
manifest_path: Path | None
@@ -54,6 +64,9 @@ class PluginDiscoveryResult:
插件发现结果。
同时承载成功发现的插件和加载失败明细,避免单个错误插件拖垮整体扫描。
+
+ :ivar plugins: 参与当前操作的插件集合
+ :ivar errors: 按条目收集的异常或失败原因
"""
plugins: list[DiscoveredPlugin] = field(default_factory=list)
@@ -78,6 +91,8 @@ class PluginScanner:
- :meth:`discover`:严格扫描,任一插件清单错误立即抛出 ``PluginManifestError``。
- :meth:`discover_with_errors`:容错扫描,逐插件隔离失败,plugin.yml 文件名错误、
YAML 损坏、清单校验失败等都作为对应插件的错误记录,不影响其他插件。
+
+ :ivar plugins_root: 后端插件根目录
"""
def __init__(self, plugins_root: Path | str) -> None:
@@ -217,7 +232,6 @@ def _ensure_plugins_root_is_dir(self) -> None:
校验插件根路径是目录。
:raises PluginManifestError: 根路径不是目录
- :return: None
"""
if not self.plugins_root.is_dir():
raise PluginManifestError(f'插件根路径不是目录:{self.plugins_root}')
@@ -227,7 +241,6 @@ def _reject_unsupported_manifest_names_strict(self) -> None:
严格模式下检查不支持的插件清单文件名,任一存在立即抛错。
:raises PluginManifestError: 存在不支持的清单文件名
- :return: None
"""
for manifest_name in UNSUPPORTED_PLUGIN_MANIFEST_NAMES:
unsupported_manifest_paths = sorted(self.plugins_root.glob(f'*/{manifest_name}'))
diff --git a/ruoyi-fastapi-backend/plugins/core/environment.py b/ruoyi-fastapi-backend/plugins/core/environment.py
index 6db39f31f..a2e670765 100644
--- a/ruoyi-fastapi-backend/plugins/core/environment.py
+++ b/ruoyi-fastapi-backend/plugins/core/environment.py
@@ -20,6 +20,13 @@ class PluginRuntimeEnvironmentService:
插件运行时环境服务。
为插件运行时提供前后端工程目录、Python 可执行文件和运行模式。
+
+ :ivar backend_root: 后端项目根目录
+ :ivar frontend_root: 前端项目根目录或统一前端目录
+ :ivar frontend_framework: 前端框架标识,auto 使用环境变量,未配置时默认 vue3
+ :ivar python_executable: Python 可执行文件路径
+ :ivar frontend_mode: 当前使用的前端集成模式
+ :ivar backend_runtime_mode: 后端运行模式
"""
def __init__(
@@ -36,7 +43,6 @@ def __init__(
:param frontend_root: 前端项目根目录或统一前端目录
:param python_executable: Python 可执行文件路径
:param frontend_framework: 前端框架标识,auto 使用环境变量,未配置时默认 vue3
- :return: None
"""
self.backend_root = self._resolve_backend_root(backend_root)
self.frontend_root = resolve_frontend_root(self.backend_root, frontend_root, frontend_framework)
diff --git a/ruoyi-fastapi-backend/plugins/core/frontend.py b/ruoyi-fastapi-backend/plugins/core/frontend.py
index ce6efab1e..fd1ef8ed4 100644
--- a/ruoyi-fastapi-backend/plugins/core/frontend.py
+++ b/ruoyi-fastapi-backend/plugins/core/frontend.py
@@ -18,6 +18,7 @@ def validate_frontend_framework(value: str) -> str:
:param value: 待校验的前端框架标识
:return: 校验通过的前端框架标识
+ :raises ValueError: frontend_framework 必须以小写字母开头,且仅包含小写字母、数字、下划线或连字符,不能为 auto
"""
if not isinstance(value, str) or value == 'auto' or FRONTEND_FRAMEWORK_PATTERN.fullmatch(value) is None:
raise ValueError('frontend_framework 必须以小写字母开头,且仅包含小写字母、数字、下划线或连字符,不能为 auto')
@@ -137,6 +138,8 @@ def resolve_frontend_root(
class PluginFrontendFrameworkResolver:
"""
前端框架解析器。
+
+ :cvar AUTO: 表示自动选择前端框架的配置值
"""
AUTO = 'auto'
@@ -152,6 +155,7 @@ def resolve(cls, frontend_root: Path, requested_framework: str = AUTO) -> Fronte
:param frontend_root: 前端项目根目录
:param requested_framework: 前端框架标识,auto 表示自动识别
:return: 解析后的前端框架标识
+ :raises ValueError: 前端包描述文件不可读、格式错误或无法据此识别框架
"""
normalized_framework = (requested_framework or cls.AUTO).strip().lower()
if normalized_framework != cls.AUTO:
diff --git a/ruoyi-fastapi-backend/plugins/core/lifecycle/jobs.py b/ruoyi-fastapi-backend/plugins/core/lifecycle/jobs.py
index a9f1cbc63..05a57eeb4 100644
--- a/ruoyi-fastapi-backend/plugins/core/lifecycle/jobs.py
+++ b/ruoyi-fastapi-backend/plugins/core/lifecycle/jobs.py
@@ -13,8 +13,12 @@ class PluginJobModelBuilder:
"""
插件任务模型构建器。
- 使用 Builder 模式将插件 manifest 中的任务声明转换为系统已有的 `JobModel`,
+ 使用 Builder 模式将插件 manifest 中的任务声明转换为系统已有的 ``JobModel``,
让插件任务复用平台原有定时任务表、调度器和日志能力。
+
+ :cvar JOB_GROUP: 插件调度任务使用的分组
+ :cvar JOB_NAME_MAX_LENGTH: 插件任务名称允许的最大长度
+ :cvar REMARK_PREFIX: 标识插件任务的备注前缀
"""
JOB_GROUP = 'default'
@@ -33,6 +37,7 @@ def build(
:param enabled: 任务是否启用
:param manifest: 用于校验任务归属并选择 v2 分发入口的插件清单
:return: 系统定时任务模型
+ :raises ValueError: 任务不属于当前插件清单;任务 callable 越过插件模块边界
"""
target, args, kwargs = job.callable, job.args, job.kwargs
if manifest is not None and manifest.uses_entrypoint:
@@ -74,7 +79,7 @@ def _validate_callable_belongs_to_plugin(cls, plugin_id: str, callable_path: str
:param plugin_id: 插件ID
:param callable_path: 任务调用目标
- :return: None
+ :raises ValueError: 任务回调不属于当前插件模块
"""
expected_prefix = f'plugins.{plugin_id}.'
if not callable_path.startswith(expected_prefix):
@@ -108,8 +113,10 @@ class PluginJobRepository:
"""
插件任务仓储。
- 插件任务复用系统 `sys_job` 表,但插件专用查询和批量清理逻辑收敛在插件模块内,
+ 插件任务复用系统 ``sys_job`` 表,但插件专用查询和批量清理逻辑收敛在插件模块内,
避免向原任务 DAO 暴露插件语义。
+
+ :ivar query_db: orm对象
"""
def __init__(self, query_db: AsyncSession) -> None:
@@ -117,7 +124,6 @@ def __init__(self, query_db: AsyncSession) -> None:
初始化插件任务仓储。
:param query_db: orm对象
- :return: None
"""
self.query_db = query_db
@@ -147,7 +153,6 @@ async def pause_jobs_by_name_prefix(self, job_name_prefix: str) -> None:
根据任务名称前缀暂停插件任务。
:param job_name_prefix: 任务名称前缀
- :return: None
"""
escaped_prefix = escape_sql_like(job_name_prefix)
escaped_remark_prefix = escape_sql_like(f'{PluginJobModelBuilder.REMARK_PREFIX} {job_name_prefix}')
@@ -187,7 +192,6 @@ async def delete_jobs_by_name_prefix(self, job_name_prefix: str) -> None:
根据任务名称前缀删除插件任务。
:param job_name_prefix: 任务名称前缀
- :return: None
"""
escaped_prefix = escape_sql_like(job_name_prefix)
escaped_remark_prefix = escape_sql_like(f'{PluginJobModelBuilder.REMARK_PREFIX} {job_name_prefix}')
@@ -207,7 +211,6 @@ async def delete_plugin_jobs_except(self, plugin_id: str, desired_job_names: set
:param plugin_id: 插件ID
:param desired_job_names: manifest 当前声明的完整任务名称集合
- :return: None
"""
job_name_prefix = f'{plugin_id}:'
escaped_prefix = escape_sql_like(job_name_prefix)
@@ -225,8 +228,11 @@ class PluginJobInstaller:
"""
插件定时任务安装器。
- 使用 Installer 模式负责将启用插件的任务声明幂等写入 `sys_job`,并在插件停用或
+ 使用 Installer 模式负责将启用插件的任务声明幂等写入 ``sys_job``,并在插件停用或
出错时暂停对应任务。
+
+ :ivar query_db: orm对象
+ :ivar repository: 保存任务配置的仓储对象
"""
def __init__(self, query_db: AsyncSession) -> None:
@@ -234,7 +240,6 @@ def __init__(self, query_db: AsyncSession) -> None:
初始化插件定时任务安装器。
:param query_db: orm对象
- :return: None
"""
self.query_db = query_db
self.repository = PluginJobRepository(query_db)
@@ -264,6 +269,7 @@ async def upsert_plugin_job(self, job_model: JobModel) -> SysJob:
:param job_model: 系统定时任务模型
:return: 写入后的系统任务对象
+ :raises ValueError: 同组已有同名的非插件任务
"""
existing_job = await self.repository.get_job_detail_by_name_group(job_model.job_name, job_model.job_group)
if existing_job:
@@ -302,6 +308,5 @@ async def pause_plugin_jobs(self, plugin_id: str) -> None:
暂停指定插件的所有任务。
:param plugin_id: 插件ID
- :return: None
"""
await self.repository.pause_jobs_by_name_prefix(f'{plugin_id}:')
diff --git a/ruoyi-fastapi-backend/plugins/core/lifecycle/migration.py b/ruoyi-fastapi-backend/plugins/core/lifecycle/migration.py
index 32bd2601a..eb1fa6eea 100644
--- a/ruoyi-fastapi-backend/plugins/core/lifecycle/migration.py
+++ b/ruoyi-fastapi-backend/plugins/core/lifecycle/migration.py
@@ -21,6 +21,10 @@
class PluginMigrationError(RuntimeError):
"""
插件 migration 可恢复错误。
+
+ :ivar migration_path: migration 相对插件根目录路径
+ :ivar status: 当前 migration 状态
+ :ivar recovery_suggestion: 恢复建议
"""
def __init__(
@@ -62,9 +66,9 @@ class PluginMigrationHistoryRecord:
"""
插件 migration 历史记录。
- :param checksum: migration 内容校验值
- :param status: 执行状态
- :param error_message: 失败错误信息
+ :ivar checksum: migration 内容校验值
+ :ivar status: 执行状态
+ :ivar error_message: 失败错误信息
"""
checksum: str
@@ -77,14 +81,14 @@ class PluginMigrationResult:
"""
插件 migration 执行结果。
- :param migration_path: migration 相对插件根目录路径
- :param module_name: migration 模块名
- :param statement_count: SQL 语句数量
- :param checksum: migration 内容校验值
- :param skipped: 是否跳过执行
- :param status: 执行状态
- :param duration_ms: 执行耗时,单位毫秒
- :param recovery_suggestion: 恢复建议
+ :ivar migration_path: migration 相对插件根目录路径
+ :ivar module_name: migration 模块名
+ :ivar statement_count: SQL 语句数量
+ :ivar checksum: migration 内容校验值
+ :ivar skipped: 是否跳过执行
+ :ivar status: 执行状态
+ :ivar duration_ms: 执行耗时,单位毫秒
+ :ivar recovery_suggestion: 恢复建议
"""
migration_path: str
@@ -98,9 +102,7 @@ class PluginMigrationResult:
class PluginMigrationHistoryStore:
- """
- 插件 migration 历史存储接口。
- """
+ """插件 migration 历史存储接口。"""
async def get_record(
self,
@@ -115,6 +117,7 @@ async def get_record(
:param plugin_id: 插件ID
:param migration_path: migration 相对路径
:return: migration 执行历史,不存在时返回 None
+ :raises NotImplementedError: 调用尚未实现的接口时
"""
raise NotImplementedError
@@ -150,7 +153,7 @@ async def record_running(
:param checksum: 内容校验值
:param version: 执行时插件版本
:param statement_count: SQL 语句数量
- :return: None
+ :raises NotImplementedError: 调用尚未实现的接口时
"""
raise NotImplementedError
@@ -172,7 +175,7 @@ async def record_success(
:param checksum: 内容校验值
:param version: 执行时插件版本
:param statement_count: SQL 语句数量
- :return: None
+ :raises NotImplementedError: 调用尚未实现的接口时
"""
raise NotImplementedError
@@ -196,7 +199,7 @@ async def record_failure(
:param version: 执行时插件版本
:param statement_count: 已解析 SQL 语句数量
:param error_message: 失败错误信息
- :return: None
+ :raises NotImplementedError: 调用尚未实现的接口时
"""
raise NotImplementedError
@@ -206,7 +209,11 @@ class PluginMigrationRunner:
插件 migration 运行器。
使用 Command Runner 模式按 manifest 声明顺序执行插件结构迁移脚本。
- Python migration 模块需要暴露 `run(query_db)` 函数,SQL migration 会按分号拆分并逐条执行。
+ Python migration 模块需要暴露 ``run(query_db)`` 函数,SQL migration 会按分号拆分并逐条执行。
+
+ :ivar discovered_plugin: 已发现插件对象
+ :ivar history_store: migration 执行历史存储
+ :ivar manage_execution_transaction: 是否由 runner 提交或回滚执行 session
"""
def __init__(
@@ -222,7 +229,6 @@ def __init__(
:param discovered_plugin: 已发现插件对象
:param history_store: migration 执行历史存储
:param manage_execution_transaction: 是否由 runner 提交或回滚执行 session
- :return: None
"""
self.discovered_plugin = discovered_plugin
self.history_store = history_store
@@ -249,6 +255,7 @@ async def _run_migration(self, migration_path: str, query_db: Any) -> PluginMigr
:param migration_path: migration 相对插件根目录路径
:param query_db: orm对象
:return: migration 执行结果
+ :raises PluginMigrationError: 迁移记录的状态或已执行脚本的校验值阻止再次执行
"""
migration_file = self._resolve_migration_file(migration_path)
checksum = await asyncio.to_thread(self._calculate_checksum, migration_file)
@@ -352,7 +359,6 @@ async def _commit_execution_transaction(self, query_db: Any) -> None:
提交 migration 执行事务。
:param query_db: migration 执行 session
- :return: None
"""
if not self.manage_execution_transaction:
return
@@ -364,7 +370,6 @@ async def _rollback_execution_transaction(self, query_db: Any) -> None:
回滚 migration 执行事务。
:param query_db: migration 执行 session
- :return: None
"""
if not self.manage_execution_transaction:
return
@@ -377,7 +382,7 @@ async def _call_execution_transaction_method(self, query_db: Any, method_name: s
:param query_db: migration 执行 session
:param method_name: 事务方法名
- :return: None
+ :raises RuntimeError: 执行迁移的会话缺少所需的事务方法
"""
method = getattr(query_db, method_name, None)
if not callable(method):
@@ -402,6 +407,7 @@ async def _run_python_migration(
:param query_db: orm对象
:param checksum: migration 内容校验值
:return: migration 执行结果
+ :raises RuntimeError: Python 迁移脚本未提供 run 入口
"""
migration_module = self._load_migration_module(migration_file)
migration_runner = getattr(migration_module, 'run', None)
@@ -465,7 +471,6 @@ async def _record_running(self, query_db: Any, migration_path: str, checksum: st
:param query_db: orm对象
:param migration_path: migration 相对路径
:param checksum: migration 内容校验值
- :return: None
"""
if not self.history_store:
return
@@ -485,7 +490,6 @@ async def _record_success(self, query_db: Any, result: PluginMigrationResult) ->
:param query_db: orm对象
:param result: migration 执行结果
- :return: None
"""
if not self.history_store or not result.checksum:
return
@@ -513,7 +517,6 @@ async def _record_failure(
:param migration_path: migration 相对路径
:param checksum: migration 内容校验值
:param error_message: 失败错误信息
- :return: None
"""
if not self.history_store:
return
diff --git a/ruoyi-fastapi-backend/plugins/core/lifecycle/precheck.py b/ruoyi-fastapi-backend/plugins/core/lifecycle/precheck.py
index 565222acb..6a559b6e7 100644
--- a/ruoyi-fastapi-backend/plugins/core/lifecycle/precheck.py
+++ b/ruoyi-fastapi-backend/plugins/core/lifecycle/precheck.py
@@ -11,6 +11,8 @@
class PluginLifecycleScriptPrecheckResult:
"""
插件生命周期脚本预检结果。
+
+ :ivar issues: 预检发现的脚本问题
"""
issues: list[PluginValidationIssue]
@@ -46,6 +48,9 @@ def warning_issues(self) -> list[PluginValidationIssue]:
class PluginLifecycleScriptPrechecker:
"""
插件生命周期脚本执行前预检器。
+
+ :ivar discovered_plugin: 已发现插件对象
+ :ivar migration_runner: migration 运行器
"""
def __init__(self, discovered_plugin: DiscoveredPlugin, migration_runner: PluginMigrationRunner) -> None:
@@ -54,7 +59,6 @@ def __init__(self, discovered_plugin: DiscoveredPlugin, migration_runner: Plugin
:param discovered_plugin: 已发现插件对象
:param migration_runner: migration 运行器
- :return: None
"""
self.discovered_plugin = discovered_plugin
self.migration_runner = migration_runner
diff --git a/ruoyi-fastapi-backend/plugins/core/lifecycle/purge.py b/ruoyi-fastapi-backend/plugins/core/lifecycle/purge.py
index 5c162f97d..f00af2000 100644
--- a/ruoyi-fastapi-backend/plugins/core/lifecycle/purge.py
+++ b/ruoyi-fastapi-backend/plugins/core/lifecycle/purge.py
@@ -8,12 +8,12 @@ class PluginPurgePlanItem:
"""
插件物理清理计划项。
- :param name: 计划项名称
- :param label: 计划项展示名称
- :param enabled: 是否启用该计划项
- :param destructive: 是否为破坏性操作
- :param count: 计划项数量
- :param target: 计划项目标
+ :ivar name: 计划项名称
+ :ivar label: 计划项展示名称
+ :ivar enabled: 是否启用该计划项
+ :ivar destructive: 是否为破坏性操作
+ :ivar count: 计划项数量
+ :ivar target: 计划项目标
"""
name: str
@@ -29,10 +29,10 @@ class PluginPurgePlan:
"""
插件物理清理计划。
- :param plugin_id: 插件ID
- :param items: 清理计划项列表
- :param removes_source: 是否删除源码目录
- :param requires_hook: 是否需要执行清理钩子
+ :ivar plugin_id: 插件ID
+ :ivar items: 清理计划项列表
+ :ivar removes_source: 是否删除源码目录
+ :ivar requires_hook: 是否需要执行清理钩子
"""
plugin_id: str
diff --git a/ruoyi-fastapi-backend/plugins/core/lifecycle/script.py b/ruoyi-fastapi-backend/plugins/core/lifecycle/script.py
index 0b440dbe9..40935bcaa 100644
--- a/ruoyi-fastapi-backend/plugins/core/lifecycle/script.py
+++ b/ruoyi-fastapi-backend/plugins/core/lifecycle/script.py
@@ -23,6 +23,7 @@ def split_sql_statements(sql_content: str) -> list[str]:
:param sql_content: SQL 文件内容
:return: SQL 语句列表
+ :raises RuntimeError: 插件 SQL 脚本暂不支持 DELIMITER,请改用 Python migration 或拆分为简单 SQL 文件
"""
for line in sql_content.splitlines():
if SQL_DELIMITER_PATTERN.match(line):
@@ -165,6 +166,7 @@ def resolve_file(
:param supported_suffixes: 支持的文件后缀
:param label: 脚本类型展示名
:return: 脚本文件绝对路径
+ :raises RuntimeError: 脚本越出插件根目录、扩展名不受支持或文件缺失
"""
script_file = (plugin_root / script_path).resolve()
resolved_plugin_root = plugin_root.resolve()
@@ -186,6 +188,7 @@ def load_module(module_name: str, script_file: Path, *, label: str) -> ModuleTyp
:param script_file: 脚本文件绝对路径
:param label: 脚本类型展示名
:return: Python 模块
+ :raises RuntimeError: 无法为插件脚本创建模块加载器
"""
module_spec = importlib.util.spec_from_file_location(module_name, script_file)
if module_spec is None or module_spec.loader is None:
diff --git a/ruoyi-fastapi-backend/plugins/core/lifecycle/seed.py b/ruoyi-fastapi-backend/plugins/core/lifecycle/seed.py
index 9f09a2684..8e02b57e7 100644
--- a/ruoyi-fastapi-backend/plugins/core/lifecycle/seed.py
+++ b/ruoyi-fastapi-backend/plugins/core/lifecycle/seed.py
@@ -16,6 +16,10 @@
class PluginSeedResult:
"""
插件 seed 执行结果。
+
+ :ivar seed_path: seed 相对插件根目录路径
+ :ivar module_name: 生成模块名
+ :ivar statement_count: SQL 语句数量
"""
seed_path: str
@@ -28,7 +32,9 @@ class PluginSeedRunner:
插件 seed 运行器。
使用 Command Runner 模式按 manifest 声明顺序执行插件初始化脚本。
- Python seed 模块需要暴露 `run(query_db)` 函数,SQL seed 会按分号拆分并逐条执行。
+ Python seed 模块需要暴露 ``run(query_db)`` 函数,SQL seed 会按分号拆分并逐条执行。
+
+ :ivar discovered_plugin: 已发现插件对象
"""
def __init__(self, discovered_plugin: DiscoveredPlugin) -> None:
@@ -73,6 +79,7 @@ async def _run_python_seed(self, seed_path: str, seed_file: Path, query_db: Any)
:param seed_file: seed 文件绝对路径
:param query_db: orm对象
:return: seed 执行结果
+ :raises RuntimeError: 种子脚本缺少可调用的 run 入口
"""
seed_module = self._load_seed_module(seed_file)
seed_runner = getattr(seed_module, 'run', None)
diff --git a/ruoyi-fastapi-backend/plugins/core/management/dao/dao.py b/ruoyi-fastapi-backend/plugins/core/management/dao/dao.py
index ad91b35d3..40ac1385b 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/dao/dao.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/dao/dao.py
@@ -45,9 +45,7 @@
class PluginDao:
- """
- 插件系统数据库操作层。
- """
+ """插件系统数据库操作层。"""
@classmethod
async def get_plugin_by_id(cls, db: AsyncSession, plugin_id: str) -> SysPlugin | None:
@@ -146,7 +144,6 @@ async def update_plugin(cls, db: AsyncSession, plugin: dict) -> None:
:param db: orm对象
:param plugin: 插件更新字典
- :return: None
"""
await db.execute(
update(SysPlugin),
@@ -160,7 +157,6 @@ async def delete_plugin(cls, db: AsyncSession, plugin_id: str) -> None:
:param db: orm对象
:param plugin_id: 插件ID
- :return: None
"""
await db.execute(delete(SysPlugin).where(SysPlugin.plugin_id == plugin_id))
@@ -243,7 +239,6 @@ async def update_plugin_menu_by_key(cls, db: AsyncSession, plugin_menu: PluginMe
:param db: orm对象
:param plugin_menu: 插件菜单关联对象
- :return: None
"""
await db.execute(
update(SysPluginMenu)
@@ -258,7 +253,6 @@ async def update_plugin_menu_key_by_menu_id(cls, db: AsyncSession, plugin_menu:
:param db: orm对象
:param plugin_menu: 插件菜单关联对象
- :return: None
"""
await db.execute(
update(SysPluginMenu)
@@ -276,7 +270,6 @@ async def delete_plugin_menus(cls, db: AsyncSession, plugin_id: str) -> None:
:param db: orm对象
:param plugin_id: 插件ID
- :return: None
"""
await db.execute(delete(SysPluginMenu).where(SysPluginMenu.plugin_id == plugin_id))
@@ -288,7 +281,6 @@ async def delete_plugin_menus_by_ids(cls, db: AsyncSession, plugin_id: str, menu
:param db: orm对象
:param plugin_id: 插件ID
:param menu_ids: 菜单ID列表
- :return: None
"""
if menu_ids:
await db.execute(
@@ -305,7 +297,6 @@ async def delete_sys_menus_by_ids(cls, db: AsyncSession, menu_ids: list[int]) ->
:param db: orm对象
:param menu_ids: 菜单ID列表
- :return: None
"""
if menu_ids:
await db.execute(delete(SysRoleMenu).where(SysRoleMenu.menu_id.in_(menu_ids)))
@@ -335,7 +326,6 @@ async def delete_plugin_migrations(cls, db: AsyncSession, plugin_id: str) -> Non
:param db: orm对象
:param plugin_id: 插件ID
- :return: None
"""
await db.execute(delete(SysPluginMigration).where(SysPluginMigration.plugin_id == plugin_id))
@@ -491,7 +481,6 @@ def _apply_migration_observability_payload(
:param payload: 待写入 payload
:param existing_plugin_migration: 已有 migration 历史
:param now: 当前时间
- :return: None
"""
status = payload.get('status', 'success')
if existing_plugin_migration is None:
@@ -548,7 +537,6 @@ async def delete_plugin_configs(cls, db: AsyncSession, plugin_id: str) -> None:
:param db: orm对象
:param plugin_id: 插件ID
- :return: None
"""
await db.execute(delete(SysPluginConfig).where(SysPluginConfig.plugin_id == plugin_id))
@@ -560,7 +548,6 @@ async def delete_plugin_configs_except(cls, db: AsyncSession, plugin_id: str, co
:param db: orm对象
:param plugin_id: 插件ID
:param config_keys: 当前 manifest 配置键集合
- :return: None
"""
query = delete(SysPluginConfig).where(SysPluginConfig.plugin_id == plugin_id)
if config_keys:
@@ -621,7 +608,6 @@ async def update_plugin_config(cls, db: AsyncSession, plugin_config: dict) -> No
:param db: orm对象
:param plugin_config: 插件配置更新字典
- :return: None
"""
await db.execute(
update(SysPluginConfig),
@@ -947,7 +933,6 @@ async def update_sys_menu(cls, db: AsyncSession, menu: dict) -> None:
:param db: orm对象
:param menu: 菜单更新字典
- :return: None
"""
if 'menu_name_i18n' in menu:
current = await db.scalar(
@@ -967,7 +952,6 @@ async def update_sys_menu_status_by_ids(cls, db: AsyncSession, menu_ids: list[in
:param db: orm对象
:param menu_ids: 菜单ID列表
:param status: 菜单状态
- :return: None
"""
if menu_ids:
await db.execute(update(SysMenu).where(SysMenu.menu_id.in_(menu_ids)).values(status=status))
diff --git a/ruoyi-fastapi-backend/plugins/core/management/dao/release_dao.py b/ruoyi-fastapi-backend/plugins/core/management/dao/release_dao.py
index 53870fd78..ffe04026b 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/dao/release_dao.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/dao/release_dao.py
@@ -17,9 +17,7 @@
class PluginReleaseConflictError(ValueError):
- """
- 发布代际或维护证据发生并发变化,需要调用方重新读取并确认目标。
- """
+ """发布代际或维护证据发生并发变化,需要调用方重新读取并确认目标。"""
def _check_digest(value: str) -> None:
@@ -27,7 +25,6 @@ def _check_digest(value: str) -> None:
校验制品摘要是否为64位小写 SHA256 字符串。
:param value: 待校验的制品摘要
- :return: None
:raises ValueError: 摘要不是64位小写十六进制字符串
"""
if not re.fullmatch(r'[0-9a-f]{64}', value):
@@ -39,7 +36,6 @@ def _check_generation(value: str) -> None:
校验发布代际或进程标识是否为32位小写 UUID 十六进制字符串。
:param value: 待校验的发布代际或宿主进程标识
- :return: None
:raises ValueError: 标识不是32位小写十六进制字符串
"""
if not re.fullmatch(r'[0-9a-f]{32}', value):
@@ -55,7 +51,6 @@ async def _insert_if_missing(db: AsyncSession, model: Any, values: dict[str, Any
:param db: 当前操作使用的数据库会话
:param model: 待插入记录的 ORM 模型类
:param values: 字段名与待插入值组成的字典
- :return: None
:raises ValueError: 当前数据库方言不受制品发布模块支持
"""
dialect = db.get_bind().dialect.name
@@ -73,9 +68,7 @@ async def _insert_if_missing(db: AsyncSession, model: Any, values: dict[str, Any
class PluginReleaseDao:
- """
- 制品、发布目标及进程报告的数据访问层,事务提交由调用方负责。
- """
+ """制品、发布目标及进程报告的数据访问层,事务提交由调用方负责。"""
@classmethod
async def register_artifact(
diff --git a/ruoyi-fastapi-backend/plugins/core/management/entity/do/release_models.py b/ruoyi-fastapi-backend/plugins/core/management/entity/do/release_models.py
index 153d1da4d..68fa331d9 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/entity/do/release_models.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/entity/do/release_models.py
@@ -6,9 +6,7 @@
class SysPluginArtifact(CreateTimeMixin, Base):
- """
- 已验证不可变制品索引,同一插件版本允许登记多个平台构建。
- """
+ """已验证不可变制品索引,同一插件版本允许登记多个平台构建。"""
__tablename__ = 'sys_plugin_artifact'
__table_args__ = (
@@ -26,9 +24,7 @@ class SysPluginArtifact(CreateTimeMixin, Base):
class SysPluginRelease(AuditTimeMixin, Base):
- """
- 代码发布目标及维护准备证据,与数据结构安装版本分别保存。
- """
+ """代码发布目标及维护准备证据,与数据结构安装版本分别保存。"""
__tablename__ = 'sys_plugin_release'
__table_args__ = (
@@ -54,9 +50,7 @@ class SysPluginRelease(AuditTimeMixin, Base):
class SysPluginWorker(AuditTimeMixin, Base):
- """
- 宿主和插件实际运行报告,__runtime__ 行记录宿主存活状态。
- """
+ """宿主和插件实际运行报告,__runtime__ 行记录宿主存活状态。"""
__tablename__ = 'sys_plugin_worker'
__table_args__ = (
diff --git a/ruoyi-fastapi-backend/plugins/core/management/service/config.py b/ruoyi-fastapi-backend/plugins/core/management/service/config.py
index 65f33c870..d31eb9f18 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/service/config.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/service/config.py
@@ -14,6 +14,9 @@ class PluginConfigManager:
插件配置管理器。
使用 Manager 模式集中处理配置声明、配置值序列化、默认值安装和脱敏输出。
+
+ :cvar MASK_VALUE: 隐藏敏感配置值时使用的占位文本
+ :cvar ENCRYPTED_PREFIX: 用于识别加密配置值的前缀
"""
MASK_VALUE = '******'
@@ -181,6 +184,7 @@ def deserialize_config_value(
:param config_type: 配置类型
:param secret: 是否敏感配置
:return: 反序列化后的配置值
+ :raises ValueError: 敏感插件配置不是加密存储格式
"""
raw_value = value
if secret and raw_value not in (None, ''):
@@ -217,7 +221,7 @@ def validate_update_value(cls, item: PluginConfigItemManifest, value: PluginConf
:param item: 插件配置项声明
:param value: 待更新配置值
- :return: None
+ :raises ValueError: 配置缺失必填值,或类型、选项及格式未通过声明的校验
"""
if item.required and value in (None, ''):
raise ValueError(f'配置 {item.key} 不能为空')
@@ -246,7 +250,7 @@ def _validate_number_range(cls, item: PluginConfigItemManifest, value: int | flo
:param item: 插件配置项声明
:param value: 待更新配置值
- :return: None
+ :raises ValueError: 数值超出配置声明的最小值或最大值
"""
if item.min_value is not None and value < item.min_value:
raise ValueError(f'配置 {item.key} 不能小于 {item.min_value}')
diff --git a/ruoyi-fastapi-backend/plugins/core/management/service/gateway.py b/ruoyi-fastapi-backend/plugins/core/management/service/gateway.py
index 346f428ec..eb9111c6d 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/service/gateway.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/service/gateway.py
@@ -27,6 +27,11 @@
class PluginManagementLifecycleUnitOfWork:
"""
插件管理生命周期主事务工作单元。
+
+ :ivar async_session_local: 异步数据库会话工厂
+ :ivar plugin_service: 插件管理服务类
+ :ivar session_context: 当前会话的上下文
+ :ivar session: 数据库会话
"""
def __init__(
@@ -39,7 +44,6 @@ def __init__(
:param async_session_local: 异步数据库会话工厂
:param plugin_service: 插件管理服务类
- :return: None
"""
self.async_session_local = async_session_local
self.plugin_service = plugin_service
@@ -63,7 +67,6 @@ async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> N
:param exc_type: 异常类型
:param exc: 异常对象
:param traceback: 异常堆栈
- :return: None
"""
if self.session_context is None:
return
@@ -107,7 +110,6 @@ async def install_plugin_menu(self, discovered_plugin: object, *, enabled: bool)
:param discovered_plugin: 已发现插件
:param enabled: 是否启用菜单
- :return: None
"""
await self.plugin_service.install_plugin_menu_services(self.session, discovered_plugin, enabled=enabled)
@@ -126,7 +128,6 @@ async def install_plugin_jobs(self, discovered_plugin: object, *, enabled: bool)
:param discovered_plugin: 已发现插件
:param enabled: 插件任务是否启用
- :return: None
"""
await self.plugin_service.install_plugin_job_services(
self.session,
@@ -180,11 +181,7 @@ async def purge_plugin_metadata_by_id(self, plugin_id: str) -> object:
return await self.plugin_service.purge_plugin_metadata_by_id_services(self.session, plugin_id)
async def commit(self) -> None:
- """
- 提交生命周期主事务。
-
- :return: None
- """
+ """提交生命周期主事务。"""
await self.session.commit()
@@ -405,7 +402,6 @@ async def _ensure_plugin_installed(
:param session: 数据库会话
:param plugin_service: 插件管理服务类
:param plugin_id: 插件ID
- :return: None
:raises ValueError: 插件尚未安装
"""
if not await plugin_service.is_plugin_installed_services(session, plugin_id):
@@ -424,7 +420,6 @@ async def add_plugin_operation_log(
:param payload: 操作日志负载
:param dry_run: 是否预演
:param continue_on_error: 失败后是否继续
- :return: None
"""
async_session_local = self.get_async_session_local()
plugin_service = self.get_plugin_service()
@@ -618,6 +613,8 @@ def build_migration_record(
"""
构建插件 migration 执行历史对象。
+ :param status: 执行状态
+ :param error_message: 记录到结果或审计日志中的错误详情
:param plugin_id: 插件ID
:param migration_path: migration 相对路径
:param checksum: 内容校验值
diff --git a/ruoyi-fastapi-backend/plugins/core/management/service/menus.py b/ruoyi-fastapi-backend/plugins/core/management/service/menus.py
index 6f48e14a6..003ee887d 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/service/menus.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/service/menus.py
@@ -29,6 +29,8 @@ class PluginMenuInstaller:
插件管理模块菜单安装器。
使用 Service Object 模式封装插件菜单幂等写入、状态切换和关联维护逻辑。
+
+ :ivar query_db: orm对象
"""
def __init__(self, query_db: AsyncSession) -> None:
@@ -36,7 +38,6 @@ def __init__(self, query_db: AsyncSession) -> None:
初始化插件菜单安装器。
:param query_db: orm对象
- :return: None
"""
self.query_db = query_db
@@ -76,7 +77,6 @@ async def set_plugin_menu_status(self, plugin_id: str, status: str) -> None:
:param plugin_id: 插件ID
:param status: 菜单状态(0正常 1停用)
- :return: None
"""
plugin_menus = await PluginDao.get_plugin_menu_list(self.query_db, plugin_id)
menu_ids = [plugin_menu.menu_id for plugin_menu in plugin_menus]
@@ -99,6 +99,7 @@ async def _install_menu_tree(
:param parent_key: 父级菜单自然键
:param seen_menu_keys: 当前插件已处理自然键集合
:return: 已安装插件菜单快照列表
+ :raises ValueError: 菜单树出现重复的自然键
"""
menu_key = PluginMenuKeyBuilder.build(menu, parent_key)
if menu_key in seen_menu_keys:
@@ -285,7 +286,6 @@ async def _upsert_plugin_menu(self, plugin_id: str, menu_id: int, menu_key: str)
:param plugin_id: 插件ID
:param menu_id: 菜单ID
:param menu_key: 插件菜单自然键
- :return: None
"""
plugin_menu_model = PluginMenuModel(pluginId=plugin_id, menuId=menu_id, menuKey=menu_key)
existing_plugin_menu = await PluginDao.get_plugin_menu_by_key(self.query_db, plugin_id, menu_key)
@@ -304,7 +304,6 @@ async def _remove_stale_menus(self, plugin_id: str, desired_menu_keys: set[str])
:param plugin_id: 插件ID
:param desired_menu_keys: manifest 当前菜单自然键集合
- :return: None
"""
plugin_menus = await PluginDao.get_plugin_menu_list(self.query_db, plugin_id)
stale_menu_ids = [
diff --git a/ruoyi-fastapi-backend/plugins/core/management/service/router_metadata.py b/ruoyi-fastapi-backend/plugins/core/management/service/router_metadata.py
index 97f3d651d..03605ede6 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/service/router_metadata.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/service/router_metadata.py
@@ -8,9 +8,7 @@
class PluginRouterMetadataService:
- """
- 按平台菜单关联读取插件页面归属,仅查询当前用户可见的插件页面。
- """
+ """按平台菜单关联读取插件页面归属,仅查询当前用户可见的插件页面。"""
@staticmethod
async def get_menu_plugin_ids(query_db: AsyncSession, menus: Iterable[SysMenu]) -> dict[int, str]:
diff --git a/ruoyi-fastapi-backend/plugins/core/management/service/service.py b/ruoyi-fastapi-backend/plugins/core/management/service/service.py
index cb010a773..b6de87bdb 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/service/service.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/service/service.py
@@ -45,6 +45,8 @@
class PluginService:
"""
插件系统服务层。
+
+ :cvar ORPHAN_PLUGIN_REASON: 缺少插件资源时记录的原因
"""
ORPHAN_PLUGIN_REASON = '插件源码不存在,仅允许物理清理平台元数据'
@@ -343,7 +345,6 @@ async def install_plugin_menu_services(
:param query_db: orm对象
:param discovered_plugin: 已发现插件对象
:param enabled: 插件菜单是否启用
- :return: None
"""
menu_installer = PluginMenuInstaller(query_db)
await menu_installer.install_manifest_menus(discovered_plugin.manifest)
@@ -408,7 +409,6 @@ async def install_plugin_job_services(
:param query_db: orm对象
:param discovered_plugin: 已发现插件对象
:param enabled: 插件任务是否允许启用
- :return: None
"""
await PluginJobInstaller(query_db).install_plugin_jobs(discovered_plugin, enabled=enabled)
@@ -466,6 +466,7 @@ async def update_plugin_config_services(
:param discovered_plugin: 已发现插件对象
:param update_model: 插件配置更新模型
:return: 更新后的插件配置值列表
+ :raises ValueError: 待更新的配置键未在插件清单声明
"""
await cls.install_plugin_default_config_services(query_db, discovered_plugin)
manifest_items = {item.key: item for item in discovered_plugin.manifest.config.items}
@@ -832,6 +833,7 @@ async def build_plugin_purge_plan_by_id_services(
:param query_db: orm对象
:param plugin_id: 插件ID
:return: 插件物理清理计划
+ :raises ValueError: 制品插件不能通过孤儿元数据清理入口删除,请使用维护发布流程
"""
plugin = await PluginDao.get_plugin_by_id(query_db, plugin_id)
if getattr(plugin, 'source', None) == 'artifact':
@@ -875,7 +877,7 @@ async def _purge_plugin_metadata_by_id(cls, query_db: AsyncSession, plugin_id: s
:param query_db: orm对象
:param plugin_id: 插件ID
- :return: None
+ :raises ValueError: 制品插件不能通过普通purge删除平台状态,请使用维护发布流程
"""
plugin = await PluginDao.get_plugin_by_id(query_db, plugin_id)
if getattr(plugin, 'source', None) == 'artifact':
@@ -1171,6 +1173,13 @@ def _filter_plugin_page_items(
"""
def contains(value: object, keyword: str | None) -> bool:
+ """
+ 检查插件字段是否匹配列表过滤条件。
+
+ :param value: 待处理的输入值
+ :param keyword: 要匹配的关键字
+ :return: 是否插件字段是否匹配列表过滤条件
+ """
return keyword is None or keyword in str(value or '')
return [
diff --git a/ruoyi-fastapi-backend/plugins/core/management/service/startup_gateway.py b/ruoyi-fastapi-backend/plugins/core/management/service/startup_gateway.py
index 272469422..ef59d5826 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/service/startup_gateway.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/service/startup_gateway.py
@@ -13,9 +13,7 @@
class PluginManagementStartupGateway:
- """
- 插件启动期管理端口适配器。
- """
+ """插件启动期管理端口适配器。"""
async def list_plugins(self, query_db: AsyncSession) -> list[Any]:
"""
@@ -39,7 +37,6 @@ async def install_plugin_resources(
:param query_db: orm对象
:param discovered_plugin: 已发现插件对象
:param enabled: 插件资源是否启用
- :return: None
"""
await PluginService.install_plugin_menu_services(query_db, discovered_plugin, enabled=enabled)
await PluginService.install_plugin_default_config_services(query_db, discovered_plugin)
@@ -155,6 +152,8 @@ def build_migration_record(
"""
构建插件 migration 执行历史对象。
+ :param status: 操作或记录所处的状态
+ :param error_message: 错误信息
:param plugin_id: 插件ID
:param migration_path: migration 相对路径
:param checksum: 内容校验值
@@ -174,9 +173,7 @@ def build_migration_record(
class PluginManagementRouteStateGateway:
- """
- 插件路由状态读取适配器。
- """
+ """插件路由状态读取适配器。"""
@staticmethod
async def is_plugin_enabled(query_db: AsyncSession, plugin_id: str) -> bool:
diff --git a/ruoyi-fastapi-backend/plugins/core/manifest/menu_key.py b/ruoyi-fastapi-backend/plugins/core/manifest/menu_key.py
index 71db36bc7..b9369c145 100644
--- a/ruoyi-fastapi-backend/plugins/core/manifest/menu_key.py
+++ b/ruoyi-fastapi-backend/plugins/core/manifest/menu_key.py
@@ -7,6 +7,10 @@
class InstalledPluginMenu:
"""
已安装插件菜单快照。
+
+ :ivar menu_id: 菜单ID
+ :ivar menu_key: 插件内菜单自然键
+ :ivar manifest_menu: 插件菜单声明
"""
menu_id: int
diff --git a/ruoyi-fastapi-backend/plugins/core/manifest/schema.py b/ruoyi-fastapi-backend/plugins/core/manifest/schema.py
index 1a0a3a0f6..23fb6b359 100644
--- a/ruoyi-fastapi-backend/plugins/core/manifest/schema.py
+++ b/ruoyi-fastapi-backend/plugins/core/manifest/schema.py
@@ -33,7 +33,7 @@
def get_default_job_timezone() -> str:
"""
- 获取插件任务默认使用的业务时区
+ 获取插件任务默认使用的业务时区。
:return: 应用配置的IANA时区名称
"""
@@ -48,15 +48,11 @@ def get_default_job_timezone() -> str:
class PluginManifestError(ValueError):
- """
- 插件清单校验异常。
- """
+ """插件清单校验异常。"""
class RouterManifest(BaseModel):
- """
- 插件路由声明。
- """
+ """插件路由声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -64,9 +60,7 @@ class RouterManifest(BaseModel):
class HealthManifest(BaseModel):
- """
- 插件健康检查声明。
- """
+ """插件健康检查声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -80,6 +74,7 @@ def validate_checker(cls, value: str | None) -> str | None:
:param value: 健康检查 callable 声明
:return: 校验后的健康检查 callable 声明
+ :raises ValueError: 健康检查 checker 必须使用 : 格式
"""
if value is None or HOOK_PATTERN.match(value):
return value
@@ -87,9 +82,7 @@ def validate_checker(cls, value: str | None) -> str | None:
class HookManifest(BaseModel):
- """
- 插件生命周期钩子声明。
- """
+ """插件生命周期钩子声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -107,6 +100,7 @@ def validate_hook(cls, value: str | None) -> str | None:
:param value: 钩子声明字符串
:return: 校验后的钩子声明字符串
+ :raises ValueError: 生命周期钩子必须使用 : 格式
"""
if value is None or HOOK_PATTERN.match(value):
return value
@@ -114,9 +108,7 @@ def validate_hook(cls, value: str | None) -> str | None:
class PluginJobManifest(BaseModel):
- """
- 插件定时任务声明。
- """
+ """插件定时任务声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -150,6 +142,7 @@ def validate_job_id(cls, value: str) -> str:
:param value: 插件任务 ID
:return: 校验后的插件任务 ID
+ :raises ValueError: 插件任务 id 只能包含小写字母、数字、下划线和中划线,并且必须以小写字母开头
"""
if not JOB_ID_PATTERN.match(value):
raise ValueError('插件任务 id 只能包含小写字母、数字、下划线和中划线,并且必须以小写字母开头')
@@ -163,6 +156,7 @@ def validate_callable(cls, value: str) -> str:
:param value: 任务调用目标
:return: 校验后的任务调用目标
+ :raises ValueError: 插件任务 callable 必须使用 . 格式
"""
if not JOB_CALLABLE_PATTERN.match(value):
raise ValueError('插件任务 callable 必须使用 . 格式')
@@ -176,6 +170,7 @@ def validate_name(cls, value: str | None) -> str | None:
:param value: 任务展示名称
:return: 校验后的任务展示名称
+ :raises ValueError: 插件任务 name 不能为空白字符串
"""
if value is not None and not value.strip():
raise ValueError('插件任务 name 不能为空白字符串')
@@ -189,6 +184,7 @@ def validate_cron_expression_text(cls, value: str) -> str:
:param value: cron 表达式
:return: 校验后的 cron 表达式
+ :raises ValueError: 插件任务 cronExpression 不能为空
"""
if not value.strip():
raise ValueError('插件任务 cronExpression 不能为空')
@@ -198,7 +194,7 @@ def validate_cron_expression_text(cls, value: str) -> str:
@classmethod
def validate_time_zone(cls, value: str) -> str:
"""
- 校验插件任务的IANA时区名称
+ 校验插件任务的IANA时区名称。
:param value: 插件任务时区名称
:return: 去除首尾空白后的有效时区名称
@@ -218,9 +214,7 @@ def fill_name(self) -> 'PluginJobManifest':
class BackendManifest(BaseModel):
- """
- 插件后端声明。
- """
+ """插件后端声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -240,6 +234,7 @@ def validate_module(cls, value: str) -> str:
:param value: 后端模块路径
:return: 校验后的后端模块路径
+ :raises ValueError: backend.module 不能为空
"""
if not value.strip():
raise ValueError('backend.module 不能为空')
@@ -251,6 +246,7 @@ def validate_unique_jobs(self) -> 'BackendManifest':
校验插件定时任务 ID 唯一性。
:return: 校验后的后端声明
+ :raises ValueError: 插件声明了重复的任务标识
"""
job_id_counts = Counter(job.id for job in self.jobs)
duplicated_job_ids = {job_id for job_id, count in job_id_counts.items() if count > 1}
@@ -260,9 +256,7 @@ def validate_unique_jobs(self) -> 'BackendManifest':
class PluginDependencyManifest(BaseModel):
- """
- 插件间依赖声明。
- """
+ """插件间依赖声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -278,6 +272,7 @@ def normalize_dependency(cls, value: Any) -> dict[str, Any]:
:param value: 原始插件依赖声明
:return: 规范化后的插件依赖声明
+ :raises ValueError: 插件依赖字符串必须使用 格式;插件依赖必须是字符串或对象
"""
if isinstance(value, str):
matched_dependency = PLUGIN_DEPENDENCY_PATTERN.match(value)
@@ -308,6 +303,7 @@ def validate_version_constraint(cls, value: str | None) -> str | None:
:param value: 版本约束
:return: 校验后的版本约束
+ :raises ValueError: 依赖插件 version 必须是版本号或带操作符的版本约束
"""
if value is None:
return value
@@ -317,9 +313,7 @@ def validate_version_constraint(cls, value: str | None) -> str | None:
class FrontendDependencyManifest(BaseModel):
- """
- 指定前端框架的宿主前端依赖声明。
- """
+ """指定前端框架的宿主前端依赖声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -397,7 +391,7 @@ def _validate_python_requirement(requirement: str) -> None:
校验单条 Python 依赖声明。
:param requirement: Python 依赖声明
- :return: None
+ :raises ValueError: Python 依赖声明无法按要求解析
"""
try:
PythonRequirementParser.parse(requirement)
@@ -410,6 +404,7 @@ def validate_unique_plugins(self) -> 'DependencyManifest':
校验依赖插件 ID 唯一性。
:return: 校验后的依赖声明
+ :raises ValueError: 依赖清单中出现重复的插件标识
"""
plugin_id_counts = Counter(plugin.id for plugin in self.plugins)
duplicated_plugin_ids = {plugin_id for plugin_id, count in plugin_id_counts.items() if count > 1}
@@ -419,9 +414,7 @@ def validate_unique_plugins(self) -> 'DependencyManifest':
class PluginMetadataManifest(BaseModel):
- """
- 插件展示元数据声明。
- """
+ """插件展示元数据声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -453,6 +446,7 @@ def validate_url(cls, value: str, info: ValidationInfo) -> str:
:param value: 原始地址
:param info: 字段信息
:return: 校验后的地址
+ :raises ValueError: 元数据地址缺少 HTTP 或 HTTPS 协议
"""
value = value.strip()
if value and not EXTERNAL_URL_PATTERN.match(value):
@@ -467,6 +461,7 @@ def validate_tags(cls, value: list[str]) -> list[str]:
:param value: 原始标签列表
:return: 清理后的标签列表
+ :raises ValueError: 插件标签重复
"""
tags = [tag.strip() for tag in value if tag.strip()]
tag_counts = Counter(tags)
@@ -477,9 +472,7 @@ def validate_tags(cls, value: list[str]) -> list[str]:
class CompatibilityManifest(BaseModel):
- """
- 插件平台兼容性声明。
- """
+ """插件平台兼容性声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -497,6 +490,7 @@ def validate_version_constraint(cls, value: str | None) -> str | None:
:param value: 版本约束
:return: 校验后的版本约束
+ :raises ValueError: compatibility 版本约束必须是版本号或带操作符的版本约束
"""
if value is None:
return value
@@ -514,6 +508,7 @@ def validate_unique_databases(
:param value: 数据库类型列表
:return: 校验后的数据库类型列表
+ :raises ValueError: 兼容数据库清单含有重复项
"""
database_counts = Counter(value)
duplicated_databases = {database for database, count in database_counts.items() if count > 1}
@@ -523,9 +518,7 @@ def validate_unique_databases(
class PluginResourceManifest(BaseModel):
- """
- 插件资源声明。
- """
+ """插件资源声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -541,6 +534,7 @@ def validate_resource_paths(cls, value: list[str]) -> list[str]:
:param value: 资源相对路径列表
:return: 校验后的资源相对路径列表
+ :raises ValueError: 资源路径重复、越界或不是安全的相对路径
"""
path_counts = Counter(value)
duplicated_paths = {path for path, count in path_counts.items() if count > 1}
@@ -553,9 +547,7 @@ def validate_resource_paths(cls, value: list[str]) -> list[str]:
class PluginPermissionManifest(BaseModel):
- """
- 插件权限声明。
- """
+ """插件权限声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -568,7 +560,7 @@ class PluginPermissionManifest(BaseModel):
@classmethod
def validate_name_i18n(cls, value: object) -> dict[str, str | None]:
"""
- 校验名称译文,允许声明宿主尚未启用的语言
+ 校验名称译文,允许声明宿主尚未启用的语言。
:param value: 名称译文映射
:return: 语言标识规范化后的名称译文
@@ -596,6 +588,7 @@ def validate_code(cls, value: str) -> str:
:param value: 权限标识
:return: 校验后的权限标识
+ :raises ValueError: 权限码格式无效
"""
if not PERMISSION_PATTERN.match(value):
raise ValueError(f'插件权限格式无效:{value}')
@@ -609,6 +602,7 @@ def validate_name(cls, value: str | None) -> str | None:
:param value: 权限展示名称
:return: 校验后的权限展示名称
+ :raises ValueError: 插件权限 name 不能为空白字符串
"""
if value is None:
return value
@@ -630,9 +624,7 @@ def validate_description(cls, value: str) -> str:
class PluginConfigOptionManifest(BaseModel):
- """
- 插件配置选项声明。
- """
+ """插件配置选项声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -641,9 +633,7 @@ class PluginConfigOptionManifest(BaseModel):
class PluginConfigItemManifest(BaseModel):
- """
- 插件配置项声明。
- """
+ """插件配置项声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -691,6 +681,7 @@ def validate_key(cls, value: str) -> str:
:param value: 配置键名
:return: 校验后的配置键名
+ :raises ValueError: 配置 key 只能包含小写字母、数字、下划线、中划线和点号,并且必须以小写字母开头
"""
if not CONFIG_KEY_PATTERN.match(value):
raise ValueError('配置 key 只能包含小写字母、数字、下划线、中划线和点号,并且必须以小写字母开头')
@@ -735,7 +726,7 @@ def _validate_select_options(self) -> None:
"""
校验 select 配置选项。
- :return: None
+ :raises ValueError: 下拉配置没有选项、选项值重复或默认值不在选项中
"""
if self.type != 'select':
return
@@ -753,7 +744,7 @@ def _validate_default_value(self) -> None:
"""
校验配置默认值类型。
- :return: None
+ :raises ValueError: 默认值与声明的配置类型不符
"""
if self.default is None:
return
@@ -768,7 +759,7 @@ def _validate_number_range(self) -> None:
"""
校验数字配置范围。
- :return: None
+ :raises ValueError: 上下限互相矛盾或默认值超出范围
"""
if self.min_value is not None and self.max_value is not None and self.min_value > self.max_value:
raise ValueError(f'配置 {self.key} 的 min 不能大于 max')
@@ -783,7 +774,7 @@ def _validate_pattern(self) -> None:
"""
校验字符串配置正则表达式。
- :return: None
+ :raises ValueError: 正则表达式无效或默认值未匹配规则
"""
if not self.pattern:
return
@@ -800,9 +791,7 @@ def _validate_pattern(self) -> None:
class PluginConfigManifest(BaseModel):
- """
- 插件配置声明。
- """
+ """插件配置声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -816,6 +805,7 @@ def normalize_config(cls, value: Any) -> dict[str, Any]:
:param value: 原始配置声明
:return: 规范化后的配置声明
+ :raises ValueError: 插件 config 必须是对象或配置项列表
"""
if value is None:
return {'items': []}
@@ -839,6 +829,7 @@ def validate_unique_keys(self) -> 'PluginConfigManifest':
校验配置键名唯一性。
:return: 校验后的配置声明
+ :raises ValueError: 插件配置键重复
"""
key_counts = Counter(item.key for item in self.items)
duplicated_keys = {key for key, count in key_counts.items() if count > 1}
@@ -848,9 +839,7 @@ def validate_unique_keys(self) -> 'PluginConfigManifest':
class PluginMenuManifest(BaseModel):
- """
- 插件菜单声明。
- """
+ """插件菜单声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -874,7 +863,7 @@ class PluginMenuManifest(BaseModel):
@classmethod
def validate_name_i18n(cls, value: object) -> dict[str, str | None]:
"""
- 校验名称译文,允许声明宿主尚未启用的语言
+ 校验名称译文,允许声明宿主尚未启用的语言。
:param value: 名称译文映射
:return: 语言标识规范化后的名称译文
@@ -889,6 +878,7 @@ def validate_required_text(cls, value: str) -> str:
:param value: 菜单文本
:return: 校验后的菜单文本
+ :raises ValueError: 菜单 name 和 path 不能为空
"""
if not value.strip():
raise ValueError('菜单 name 和 path 不能为空')
@@ -915,6 +905,7 @@ def validate_perms(cls, value: str) -> str:
:param value: 菜单权限标识
:return: 校验后的菜单权限标识
+ :raises ValueError: 菜单 perms 必须使用小写冒号分隔格式,例如 demo:list
"""
if not value:
return value
@@ -930,6 +921,7 @@ def validate_path(cls, value: str) -> str:
:param value: 菜单路径
:return: 校验后的菜单路径
+ :raises ValueError: 菜单 path 必须是插件路由路径或 http/https 外链地址
"""
if not ROUTE_PATH_PATTERN.match(value) and not EXTERNAL_URL_PATTERN.match(value):
raise ValueError('菜单 path 必须是插件路由路径或 http/https 外链地址')
@@ -941,6 +933,7 @@ def validate_component_for_menu_type(self) -> 'PluginMenuManifest':
校验菜单组件和菜单类型的基础关系。
:return: 校验后的菜单声明
+ :raises ValueError: 非按钮菜单 component 不能为空;外链菜单 path 必须是 http/https 地址;非外链菜单 path 不能是 http/https 地址
"""
if self.type != 'F' and not self.component.strip():
raise ValueError('非按钮菜单 component 不能为空')
@@ -952,9 +945,7 @@ def validate_component_for_menu_type(self) -> 'PluginMenuManifest':
class FrontendDeliveryManifest(BaseModel):
- """
- 插件前端交付声明。
- """
+ """插件前端交付声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -963,9 +954,7 @@ class FrontendDeliveryManifest(BaseModel):
class FrontendManifest(BaseModel):
- """
- 插件前端声明。
- """
+ """插件前端声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -995,6 +984,7 @@ def validate_base_path(cls, value: str | None) -> str | None:
:param value: 前端基础路径
:return: 校验后的前端基础路径
+ :raises ValueError: frontend.basePath 只能包含小写字母、数字、下划线、中划线和正斜杠
"""
if value is not None and not FRONTEND_RELATIVE_PATH_PATTERN.match(value):
raise ValueError('frontend.basePath 只能包含小写字母、数字、下划线、中划线和正斜杠')
@@ -1008,6 +998,7 @@ def validate_relative_path(cls, value: str) -> str:
:param value: 前端相对目录路径
:return: 校验后的前端相对目录路径
+ :raises ValueError: frontend viewsPath/apiPath 只能包含小写字母、数字、下划线、中划线和正斜杠
"""
if not FRONTEND_RELATIVE_PATH_PATTERN.match(value):
raise ValueError('frontend viewsPath/apiPath 只能包含小写字母、数字、下划线、中划线和正斜杠')
@@ -1015,9 +1006,7 @@ def validate_relative_path(cls, value: str) -> str:
class PluginManifest(BaseModel):
- """
- 插件主清单。
- """
+ """插件主清单。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
@@ -1047,6 +1036,7 @@ def validate_plugin_id(cls, value: str) -> str:
:param value: 插件 ID
:return: 校验后的插件 ID
+ :raises ValueError: 插件标识使用了保留名称
"""
validate_plugin_id_value(value, field_name='插件 id')
if value in RESERVED_PLUGIN_IDS:
@@ -1061,6 +1051,7 @@ def validate_required_text(cls, value: str) -> str:
:param value: 插件文本
:return: 校验后的插件文本
+ :raises ValueError: 插件 name 和 version 不能为空
"""
if not value.strip():
raise ValueError('插件 name 和 version 不能为空')
@@ -1074,6 +1065,7 @@ def validate_permissions(cls, value: list[PluginPermissionManifest]) -> list[Plu
:param value: 权限声明列表
:return: 校验后的权限声明列表
+ :raises ValueError: 插件声明了重复的权限码
"""
permission_code_counts = Counter(permission.code for permission in value)
duplicated_permissions = {permission for permission, count in permission_code_counts.items() if count > 1}
@@ -1152,7 +1144,7 @@ def _validate_backend_module(self) -> None:
"""
校验后端模块路径与插件 ID 一致。
- :return: None
+ :raises ValueError: 后端模块名称与按插件标识约定的名称不一致
"""
expected_module = f'plugins.{self.id}'
if self.backend.module != expected_module:
@@ -1162,7 +1154,7 @@ def _validate_frontend_plugin_id(self) -> None:
"""
校验前端插件目录名与插件 ID 一致。
- :return: None
+ :raises ValueError: 前端标识与插件标识不一致
"""
if self.frontend.plugin_id != self.id:
raise ValueError(f'frontend.pluginId 必须与插件 id 一致:{self.id}')
@@ -1171,7 +1163,7 @@ def _validate_permission_prefixes(self) -> None:
"""
校验插件权限标识必须使用插件 ID 前缀。
- :return: None
+ :raises ValueError: 权限码没有使用当前插件的前缀
"""
expected_prefix = f'{self.id}:'
permission_set = set(self.permission_codes) | PluginMenuTree.collect_permissions(self.frontend.menus)
@@ -1182,11 +1174,7 @@ def _validate_permission_prefixes(self) -> None:
raise ValueError(f'插件权限必须使用 {expected_prefix} 前缀:{"、".join(invalid_permissions)}')
def _fill_frontend_delivery_defaults(self) -> None:
- """
- 根据前端声明和 npm 依赖补全前端交付默认值。
-
- :return: None
- """
+ """根据前端声明和 npm 依赖补全前端交付默认值。"""
has_frontend_resources = bool(self.frontend.menus or self.dependencies.has_frontend_dependencies)
if has_frontend_resources and self.frontend.delivery.type == 'none':
self.frontend.delivery.type = 'source'
@@ -1197,7 +1185,7 @@ def _validate_plugin_dependencies(self) -> None:
"""
校验插件间依赖声明。
- :return: None
+ :raises ValueError: 插件不能依赖自身
"""
if any(plugin.id == self.id for plugin in self.dependencies.plugins):
raise ValueError('插件不能依赖自身')
@@ -1206,7 +1194,7 @@ def _validate_menu_permissions_declared(self) -> None:
"""
校验菜单权限已在顶层 permissions 中声明。
- :return: None
+ :raises ValueError: 菜单引用了未在清单中声明的权限
"""
menu_permissions = PluginMenuTree.collect_permissions(self.frontend.menus)
undeclared_permissions = sorted(menu_permissions - set(self.permission_codes))
@@ -1217,7 +1205,7 @@ def _validate_menu_components(self) -> None:
"""
校验菜单组件路径符合插件前端视图或核心布局组件约定。
- :return: None
+ :raises ValueError: 菜单引用了不支持的组件
"""
for menu in PluginMenuTree.flatten(self.frontend.menus):
if menu.type == 'F' and not menu.component:
@@ -1233,7 +1221,7 @@ def _validate_plugin_component(self, component: str) -> None:
校验插件视图组件路径。
:param component: 菜单组件路径
- :return: None
+ :raises ValueError: 插件组件路径格式无效、跨插件或含有非法路径段
"""
parts = component.split('/')
if len(parts) < MIN_PLUGIN_COMPONENT_PARTS or parts[0] != 'plugin':
@@ -1248,7 +1236,7 @@ def _validate_unique_menu_paths(self) -> None:
"""
校验菜单路由路径在当前插件内不重复。
- :return: None
+ :raises ValueError: 清单中的菜单路径重复
"""
route_paths = PluginMenuTree.collect_route_paths(self.frontend.menus)
route_path_counts = Counter(route_paths)
@@ -1263,7 +1251,7 @@ def _validate_job_callable_prefixes(self) -> None:
定时任务由系统调度器直接 importlib 导入执行,不经过 PluginCallableLoader 的模块归属
校验,因此必须在清单校验阶段限制 callable 模块前缀,防止插件执行任意模块的函数。
- :return: None
+ :raises ValueError: 任务回调路径没有使用当前插件的模块前缀
"""
expected_prefix = f'plugins.{self.id}.'
invalid_callables = [job.callable for job in self.backend.jobs if not job.callable.startswith(expected_prefix)]
@@ -1278,7 +1266,7 @@ class PluginManifestFactory:
"""
插件清单工厂。
- 使用工厂模式集中处理从原始字典到 `PluginManifest` 的构造,避免发现器直接依赖
+ 使用工厂模式集中处理从原始字典到 ``PluginManifest`` 的构造,避免发现器直接依赖
Pydantic 的创建细节。
"""
diff --git a/ruoyi-fastapi-backend/plugins/core/manifest/v2.py b/ruoyi-fastapi-backend/plugins/core/manifest/v2.py
index 1bcde75be..e07da79f0 100644
--- a/ruoyi-fastapi-backend/plugins/core/manifest/v2.py
+++ b/ruoyi-fastapi-backend/plugins/core/manifest/v2.py
@@ -27,6 +27,7 @@ def validate_relative_resource(value: str) -> str:
:param value: 清单声明的相对资源路径
:return: 通过格式校验的相对资源路径
+ :raises ValueError: 资源必须使用安全相对路径,不能包含绝对路径、反斜杠或点目录
"""
if not SAFE_PATH_PATTERN.fullmatch(value) or any(part in {'.', '..'} for part in value.split('/')):
raise ValueError('资源必须使用安全相对路径,不能包含绝对路径、反斜杠或点目录')
@@ -34,50 +35,53 @@ def validate_relative_resource(value: str) -> str:
class NativeManifest(BaseModel):
- """
- 已经离线安装到插件目录的原生发行包声明。
- """
+ """已经离线安装到插件目录的原生发行包声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
- distribution: str = Field(pattern=r'^[A-Za-z0-9](?:[A-Za-z0-9_.-]*[A-Za-z0-9])?$')
- module_root: str = Field(default='native', alias='moduleRoot')
+ distribution: str = Field(
+ pattern=r'^[A-Za-z0-9](?:[A-Za-z0-9_.-]*[A-Za-z0-9])?$', description='已安装的原生发行包名称'
+ )
+ module_root: str = Field(default='native', alias='moduleRoot', description='原生模块在插件目录下的相对路径')
_validate_module_root = field_validator('module_root')(validate_relative_resource)
class AsgiManifest(BaseModel):
- """
- 子应用挂载与生命周期声明。
- """
+ """子应用挂载与生命周期声明。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
- mount_path: str | None = Field(default=None, alias='mountPath')
- lifespan: Literal['managed', 'none'] = 'managed'
+ mount_path: str | None = Field(default=None, alias='mountPath', description='ASGI 子应用的挂载路径')
+ lifespan: Literal['managed', 'none'] = Field(default='managed', description='子应用生命周期管理方式')
class PluginJobManifestV2(PluginJobManifest):
- """
- 在宿主事件循环中分发,禁止把原生对象发送至进程池。
- """
+ """在宿主事件循环中分发,禁止把原生对象发送至进程池。"""
- executor: Literal['default'] = 'default'
- timeout_seconds: float = Field(default=30.0, gt=0, le=86400, allow_inf_nan=False, alias='timeoutSeconds')
+ executor: Literal['default'] = Field(default='default', description='调度任务使用的执行器')
+ timeout_seconds: float = Field(
+ default=30.0,
+ gt=0,
+ le=86400,
+ allow_inf_nan=False,
+ alias='timeoutSeconds',
+ description='等待任务完成的超时时间(秒)',
+ )
class BackendManifestV2(BackendManifest):
- """
- 交付运行时和 Web 接入方式彼此独立。
- """
-
- runtime: Literal['python', 'native'] = 'python'
- integration: Literal['router', 'asgi'] = 'router'
- entrypoint: str
- routers: RouterManifest = Field(default_factory=lambda: RouterManifest(autoScan=False))
- native: NativeManifest | None = None
- asgi: AsgiManifest | None = None
- jobs: list[PluginJobManifestV2] = Field(default_factory=list)
+ """交付运行时和 Web 接入方式彼此独立。"""
+
+ runtime: Literal['python', 'native'] = Field(default='python', description='插件后端运行时类型')
+ integration: Literal['router', 'asgi'] = Field(default='router', description='插件接入宿主的方式')
+ entrypoint: str = Field(description='创建插件后端的入口函数路径')
+ routers: RouterManifest = Field(
+ default_factory=lambda: RouterManifest(autoScan=False), description='插件的路由注册配置'
+ )
+ native: NativeManifest | None = Field(default=None, description='原生后端的发行包配置')
+ asgi: AsgiManifest | None = Field(default=None, description='ASGI 子应用配置')
+ jobs: list[PluginJobManifestV2] = Field(default_factory=list, description='插件声明的调度任务')
@field_validator('entrypoint')
@classmethod
@@ -87,6 +91,7 @@ def validate_entrypoint(cls, value: str) -> str:
:param value: 清单声明的显式入口路径
:return: 通过格式校验的入口路径
+ :raises ValueError: backend.entrypoint 必须使用 : 格式
"""
if not HOOK_PATTERN.fullmatch(value):
raise ValueError('backend.entrypoint 必须使用 : 格式')
@@ -98,6 +103,7 @@ def validate_delivery(self) -> 'BackendManifestV2':
拒绝含糊或冲突的加载方式。
:return: 通过运行时及接入方式一致性校验的后端声明
+ :raises ValueError: 后端模块、原生运行时、回调或生命周期配置与声明的接入方式不符
"""
if not MODULE_PATTERN.fullmatch(self.module):
raise ValueError('backend.module 必须是合法 Python 模块名')
@@ -125,23 +131,19 @@ def validate_delivery(self) -> 'BackendManifestV2':
class FrontendDeliveryManifestV2(FrontendDeliveryManifest):
- """
- 独立构建产物不参与宿主前端构建。
- """
+ """独立构建产物不参与宿主前端构建。"""
- type: Literal['none', 'source', 'bundle'] = 'none'
+ type: Literal['none', 'source', 'bundle'] = Field(default='none', description='前端交付类型')
class FrontendBundleManifest(BaseModel):
- """
- 插件内的静态构建资源。
- """
+ """插件内的静态构建资源。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
- directory: str = 'web/dist'
- entry: str = 'index.html'
- spa_fallback: bool = Field(default=True, alias='spaFallback')
+ directory: str = Field(default='web/dist', description='前端资源包目录')
+ entry: str = Field(default='index.html', description='前端资源包的入口文件')
+ spa_fallback: bool = Field(default=True, alias='spaFallback', description='是否将页面导航回退到单页应用入口')
_validate_paths = field_validator('directory', 'entry')(validate_relative_resource)
@@ -153,6 +155,7 @@ def validate_html_entry(cls, value: str) -> str:
:param value: 前端构建产物的入口文件路径
:return: 通过 HTML 后缀校验的入口文件路径
+ :raises ValueError: bundle.entry 必须是 HTML 文件
"""
if not value.endswith('.html'):
raise ValueError('bundle.entry 必须是 HTML 文件')
@@ -160,20 +163,18 @@ def validate_html_entry(cls, value: str) -> str:
class FrontendManifestV2(FrontendManifest):
- """
- 兼容源码页面并增加构建产物声明。
- """
+ """兼容源码页面并增加构建产物声明。"""
- delivery: FrontendDeliveryManifestV2 = Field(default_factory=FrontendDeliveryManifestV2)
- bundle: FrontendBundleManifest | None = None
+ delivery: FrontendDeliveryManifestV2 = Field(
+ default_factory=FrontendDeliveryManifestV2, description='前端资源的交付配置'
+ )
+ bundle: FrontendBundleManifest | None = Field(default=None, description='预构建前端资源包的配置')
class CompatibilityManifestV2(CompatibilityManifest):
- """
- 宿主插件 API 与应用版本分别约束。
- """
+ """宿主插件 API 与应用版本分别约束。"""
- host_api_version: str = Field(default='^1.0.0', alias='hostApiVersion')
+ host_api_version: str = Field(default='^1.0.0', alias='hostApiVersion', description='插件兼容的宿主接口版本')
@field_validator('host_api_version')
@classmethod
@@ -183,6 +184,7 @@ def validate_host_api_version(cls, value: str) -> str:
:param value: 宿主插件 API 版本约束表达式
:return: 通过语法校验的版本约束表达式
+ :raises ValueError: compatibility.hostApiVersion 必须是版本号或带操作符的版本约束
"""
if not VERSION_CONSTRAINT_PATTERN.fullmatch(value):
raise ValueError('compatibility.hostApiVersion 必须是版本号或带操作符的版本约束')
@@ -190,20 +192,20 @@ def validate_host_api_version(cls, value: str) -> str:
class PluginManifestV2(PluginManifest):
- """
- 继承通用权限、菜单、配置及依赖规则,替换交付相关约束。
- """
+ """继承通用权限、菜单、配置及依赖规则,替换交付相关约束。"""
- manifest_version: Literal[2] = Field(default=2, alias='manifestVersion')
- backend: BackendManifestV2
- frontend: FrontendManifestV2 = Field(default_factory=FrontendManifestV2)
- compatibility: CompatibilityManifestV2 = Field(default_factory=CompatibilityManifestV2)
+ manifest_version: Literal[2] = Field(default=2, alias='manifestVersion', description='插件清单格式版本')
+ backend: BackendManifestV2 = Field(description='插件后端声明')
+ frontend: FrontendManifestV2 = Field(default_factory=FrontendManifestV2, description='插件前端声明')
+ compatibility: CompatibilityManifestV2 = Field(
+ default_factory=CompatibilityManifestV2, description='插件的宿主兼容性要求'
+ )
def _validate_backend_module(self) -> None:
"""
校验后端模块命名空间,并补全固定的 ASGI 挂载路径。
- :return: None
+ :raises ValueError: 后端模块或 ASGI 挂载路径与当前插件的命名不符
"""
expected = f'ruoyi_plugin_{self.id}' if self.backend.runtime == 'native' else f'plugins.{self.id}'
if self.backend.module != expected:
@@ -218,7 +220,7 @@ def _fill_frontend_delivery_defaults(self) -> None:
"""
补全前端交付默认值并校验独立构建产物的交付约束。
- :return: None
+ :raises ValueError: 仅 bundle 交付允许 frontend.bundle;bundle 前端需要 ASGI 接入方式;bundle 交付必须声明 frontend.bundle;bundle 不参与宿主构建,buildRequired 必须为 false;bundle 的 npm 构建依赖由插件独立管理,不能安装到宿主
"""
if self.frontend.delivery.type != 'bundle':
if self.frontend.bundle is not None:
@@ -238,7 +240,7 @@ def _validate_menu_components(self) -> None:
"""
校验独立构建产物菜单仅使用插件框架或核心布局组件。
- :return: None
+ :raises ValueError: bundle 菜单仅允许 PluginFrame 或核心布局组件
"""
if self.frontend.delivery.type != 'bundle':
super()._validate_menu_components()
@@ -253,7 +255,7 @@ def _validate_job_callable_prefixes(self) -> None:
"""
校验任务回调位于当前插件后端模块命名空间内。
- :return: None
+ :raises ValueError: 任务回调路径没有使用当前插件前缀
"""
expected_prefix = f'{self.backend.module}.'
if any(not job.callable.startswith(expected_prefix) for job in self.backend.jobs):
diff --git a/ruoyi-fastapi-backend/plugins/core/native/wheel.py b/ruoyi-fastapi-backend/plugins/core/native/wheel.py
index 9012e479d..deef02483 100644
--- a/ruoyi-fastapi-backend/plugins/core/native/wheel.py
+++ b/ruoyi-fastapi-backend/plugins/core/native/wheel.py
@@ -139,7 +139,6 @@ def _verify_dependency(value: str) -> None:
要求宿主已安装满足约束的依赖,不隐式联网安装。
:param value: METADATA 中的单条 Requires-Dist 依赖声明
- :return: None
:raises ValueError: 依赖使用未锁定 URL、尚未安装或版本不满足要求
"""
requirement = Requirement(value)
@@ -163,7 +162,6 @@ def _verify_metadata(archive: ZipFile, metadata_root: str, wheel: Path, manifest
:param metadata_root: wheel 内唯一的 dist-info 元数据目录名
:param wheel: 待验证或展开的原生 wheel 文件路径
:param manifest: 插件清单对象
- :return: None
:raises ValueError: 发行包元数据、平台标签或宿主依赖不匹配
"""
metadata_path = f'{metadata_root}/METADATA'
@@ -197,7 +195,6 @@ def _verify_record(archive: ZipFile, files: dict[str, ZipInfo], record_path: str
:param archive: 已打开的 ZIP 压缩容器
:param files: 通过安全清单校验的 wheel 文件条目映射
:param record_path: wheel 内 RECORD 文件的相对路径
- :return: None
:raises ValueError: RECORD 文件清单、大小或 SHA256 与实际内容不一致
"""
records = {}
@@ -234,9 +231,9 @@ def install_native_wheel(wheel: Path, destination: Path, manifest: PluginManifes
:param wheel: 待验证或展开的原生 wheel 文件路径
:param destination: 尚不存在的原生插件安装目录
:param manifest: 插件清单对象
- :return: None
:raises ValueError: wheel 类型、兼容性、文件内容或展开路径校验失败
:raises FileExistsError: 目标目录已经存在,不能覆盖安装
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
if manifest.runtime_kind != 'native':
raise ValueError('仅 native 插件可安装 wheel')
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/application.py b/ruoyi-fastapi-backend/plugins/core/runtime/application.py
index 74fb9009f..5678841dc 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/application.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/application.py
@@ -22,6 +22,16 @@ class PluginApplicationRuntime:
server.py 只依赖该适配器提供的高层扩展点,插件实体导入、二次建表、启动资源安装、
多 worker ready barrier 和生命周期钩子等细节留在插件运行时内部。
+
+ :ivar startup_manager: 插件启动协调器
+ :ivar ready_key: 插件启动 ready 标记 key
+ :ivar ready_expire_seconds: ready 标记过期时间
+ :ivar failed_expire_seconds: 失败标记过期时间
+ :ivar ready_wait_timeout_seconds: 等待 ready 超时时间
+ :ivar ready_wait_interval_seconds: 等待 ready 轮询间隔
+ :ivar lifecycle_lock: 插件生命周期全局锁
+ :ivar startup_generation: 测试或部署显式注入的启动代际
+ :ivar release_worker: 维护当前发布快照和 worker 心跳的可选协调器
"""
def __init__(
@@ -49,7 +59,6 @@ def __init__(
:param lifecycle_lock: 插件生命周期全局锁
:param startup_generation: 测试或部署显式注入的启动代际
:param release_worker: 维护当前发布快照和 worker 心跳的可选协调器
- :return: None
"""
self.startup_manager = startup_manager or PluginRuntimeStartupManager()
self.ready_key = ready_key
@@ -66,7 +75,6 @@ def bind_app(self, app: FastAPI) -> None:
绑定插件运行时到 FastAPI app。
:param app: FastAPI对象
- :return: None
"""
app.state.plugin_application_runtime = self
self.startup_manager.bind_app(app)
@@ -76,7 +84,6 @@ def prepare_metadata(self, app: FastAPI) -> None:
准备插件平台自身元数据。
:param app: FastAPI对象
- :return: None
"""
self._ensure_bound(app)
self.startup_manager.import_builtin_entities()
@@ -97,7 +104,7 @@ async def startup(
:param app: FastAPI对象
:param create_tables: 数据库建表回调
- :return: None
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
try:
if self.release_worker is not None:
@@ -148,7 +155,7 @@ async def _startup_coordinated(
:param app: 宿主 FastAPI 应用
:param create_tables: 在允许写入的 worker 中创建数据库表的异步回调
- :return: None
+ :raises TimeoutError: 等待操作超过时限时
"""
self._ensure_bound(app)
if self.release_worker is not None:
@@ -245,6 +252,7 @@ async def _process_startup_state(
:param ready_message: 复用ready时的日志
:param failed_message: 发现failed marker时的日志
:return: 是否已完成reader激活、是否已记录过期ready告警
+ :raises RuntimeError: 启动状态报告失败
"""
ready_status = ready_state.get('status', 'missing')
reader_logger = logger.bind(
@@ -311,7 +319,7 @@ async def _run_startup_writer(
:param app: FastAPI对象
:param generation: 插件启动代际
:param create_tables: 数据库建表回调
- :return: None
+ :raises Exception: 底层操作失败时向调用方传播异常
"""
app.state.plugin_startup_write_enabled = True
writer_logger = logger.bind(
@@ -347,7 +355,6 @@ async def _activate_startup_reader(self, app: FastAPI, generation: str) -> None:
:param app: FastAPI对象
:param generation: 插件启动代际
- :return: None
"""
reader_logger = logger.bind(
startup_generation=generation,
@@ -371,7 +378,6 @@ def _log_startup_completed(app: FastAPI, generation: str, *, role: str) -> None:
:param app: FastAPI对象
:param generation: 插件启动代际
:param role: 当前worker的插件启动角色
- :return: None
"""
plugin_registry = getattr(app.state, 'plugin_registry', None)
enabled_plugin_ids = (
@@ -393,7 +399,6 @@ async def shutdown(self, app: FastAPI) -> None:
关闭插件运行时。
:param app: FastAPI对象
- :return: None
"""
self._ensure_bound(app)
startup_write_enabled = bool(getattr(app.state, 'plugin_startup_write_enabled', False))
@@ -410,7 +415,6 @@ async def _stop_diagnostics(app: FastAPI) -> None:
关闭诊断采样,观测清理失败不阻止发布 worker 上报最终状态。
:param app: 宿主 FastAPI 应用
- :return: None
"""
reporter = getattr(app.state, 'plugin_diagnostics_reporter', None)
if isinstance(reporter, PluginDiagnosticsReporter):
@@ -425,7 +429,6 @@ async def clear_startup_ready(self, app: FastAPI, generation: str | None = None)
:param app: FastAPI对象
:param generation: 插件启动代际
- :return: None
"""
resolved_generation = generation or self.resolve_startup_generation()
await app.state.redis.delete(self.build_ready_key(resolved_generation))
@@ -436,7 +439,6 @@ async def mark_startup_ready(self, app: FastAPI, generation: str | None = None)
:param app: FastAPI对象
:param generation: 插件启动代际
- :return: None
"""
resolved_generation = generation or self.resolve_startup_generation()
await app.state.redis.set(
@@ -464,7 +466,6 @@ async def mark_startup_failed(self, app: FastAPI, generation: str, error: Except
:param app: FastAPI对象
:param generation: 插件启动代际
:param error: 启动异常
- :return: None
"""
await app.state.redis.set(
self.build_ready_key(generation),
@@ -515,7 +516,7 @@ def build_ready_key(self, generation: str) -> str:
构建代际隔离的 ready key。
:param generation: 插件启动代际
- :return: Redis key
+ :return: Redis 缓存键
"""
return f'{self.ready_key}:{generation}'
@@ -535,7 +536,6 @@ def _ensure_bound(self, app: FastAPI) -> None:
确保插件运行时已绑定到 app。
:param app: FastAPI对象
- :return: None
"""
if getattr(app.state, 'plugin_application_runtime', None) is not self:
self.bind_app(app)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/asgi.py b/ruoyi-fastapi-backend/plugins/core/runtime/asgi.py
index 9b98fc019..b25c41075 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/asgi.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/asgi.py
@@ -21,6 +21,18 @@
class PluginLifespanManager:
"""
通过 ASGI lifespan 协议驱动一个 worker 内的插件实例。
+
+ :ivar app: 插件 ASGI 应用
+ :ivar timeout: 生命周期事件确认的超时时间,单位为秒
+ :ivar cancel_timeout: 生命周期任务取消的等待上限秒数
+ :ivar managed: 是否由宿主驱动 ASGI 生命周期协议
+ :ivar state: 当前流程的状态
+ :ivar started: 是否已经完成启动
+ :ivar _stopping: 是否已经开始关闭
+ :ivar _operation_lock: 串行执行启动和关闭操作的锁
+ :ivar _task: 驱动插件生命周期的后台任务
+ :ivar _receive: 插件生命周期使用的 ASGI 接收回调
+ :ivar _send: 插件生命周期使用的 ASGI 发送回调
"""
def __init__(
@@ -38,7 +50,7 @@ def __init__(
:param timeout: 生命周期事件确认的超时时间,单位为秒
:param managed: 是否由宿主驱动 ASGI 生命周期协议
:param cancel_timeout: 生命周期任务取消的等待上限秒数
- :return: None
+ :raises ValueError: 生命周期等待时间必须大于零
"""
if any(not math.isfinite(value) or value <= 0 for value in (timeout, cancel_timeout)):
raise ValueError('生命周期等待时间必须大于零')
@@ -66,18 +78,14 @@ def has_pending_task(self) -> bool:
@property
def ready(self) -> bool:
"""
- lifespan 意外退出后不再接受业务请求。
+ 判断插件生命周期任务是否仍可接受业务请求。
:return: 插件是否已启动且生命周期任务仍然存活
"""
return self.started and not self._stopping and (not self.managed or self.has_pending_task)
async def startup(self) -> None:
- """
- 只有确认 startup.complete 后才允许接收业务请求。
-
- :return: None
- """
+ """只有确认 startup.complete 后才允许接收业务请求。"""
async with self._operation_lock:
self._stopping = False
await self._startup()
@@ -86,7 +94,8 @@ async def _startup(self) -> None:
"""
串行启动新一轮协议,旧任务退出后才允许重试。
- :return: None
+ :raises RuntimeError: 上一次插件生命周期尚未退出,不能重新启动
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
if self.started:
return
@@ -108,11 +117,7 @@ async def _startup(self) -> None:
raise
async def shutdown(self) -> None:
- """
- 即使协议失败或超时,也回收本 worker 创建的 lifespan task。
-
- :return: None
- """
+ """即使协议失败或超时,也回收本 worker 创建的 lifespan task。"""
self._stopping = True
async with self._operation_lock:
await self._shutdown()
@@ -121,7 +126,7 @@ async def _shutdown(self) -> None:
"""
串行发送关闭消息,避免并发调用消费同一个协议确认。
- :return: None
+ :raises TimeoutError: ASGI lifespan.shutdown 确认后未退出
"""
was_started = self.started
self.started = False
@@ -140,7 +145,6 @@ async def _invoke(self, scope: Scope) -> None:
在独立协程中等待 ASGI 应用返回的任意 awaitable。
:param scope: 当前启动轮次的独立生命周期作用域
- :return: None
"""
await self.app(scope, self._receive.get, self._send.put)
@@ -149,7 +153,8 @@ async def _exchange(self, event: str) -> None:
发送生命周期事件并等待子应用确认。
:param event: 生命周期事件名称,支持 startup 和 shutdown
- :return: None
+ :raises RuntimeError: ASGI lifespan 在 startup 后提前退出
+ :raises TimeoutError: 等待 ASGI 生命周期应答超时
"""
await self._receive.put({'type': f'lifespan.{event}'})
response = asyncio.create_task(self._send.get())
@@ -177,18 +182,14 @@ def _check_task_result(self) -> None:
"""
将子应用自行取消作为协议失败,保留宿主调用者自身的取消语义。
- :return: None
+ :raises RuntimeError: ASGI 生命周期任务自行取消
"""
if self._task.cancelled():
raise RuntimeError('ASGI 生命周期任务自行取消')
self._task.result()
async def _cancel_task(self) -> None:
- """
- 取消并回收当前 worker 的生命周期任务。
-
- :return: None
- """
+ """取消并回收当前 worker 的生命周期任务。"""
if self._task is None:
return
if await cancel_plugin_tasks({self._task}, grace_seconds=self.cancel_timeout):
@@ -203,6 +204,11 @@ class PluginGatewayASGI:
接受宿主 Bearer 或限定 bundle 的插件会话,由宿主授权器校验。
静态资源与业务接口都必须经过同一身份门禁。
+
+ :ivar app: 受保护的插件 ASGI 应用
+ :ivar lifespan: 当前插件的生命周期管理器
+ :ivar authorize: 根据 ASGI 请求作用域构建宿主身份上下文的异步授权器
+ :ivar connections: 当前由网关管理的连接
"""
def __init__(
@@ -224,7 +230,6 @@ def __init__(
:param recheck_interval: 已建立长连接的身份复核间隔秒数
:param recheck_timeout: 每次长连接身份复核的超时秒数
:param cancel_timeout: 长连接任务取消的等待秒数
- :return: None
"""
self.app = app
self.lifespan = lifespan
@@ -244,7 +249,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
:param scope: ASGI 请求作用域
:param receive: ASGI 消息接收函数
:param send: ASGI 消息发送函数
- :return: None
+ :raises RuntimeError: 插件 lifespan 必须由宿主管理器驱动
"""
if scope['type'] not in {'http', 'websocket'}:
raise RuntimeError('插件 lifespan 必须由宿主管理器驱动')
@@ -264,11 +269,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.connections.run(self.app, scope, child_scope, context, receive, send)
async def drain(self) -> None:
- """
- 在释放插件资源前停止当前 worker 的 SSE 与 WebSocket。
-
- :return: None
- """
+ """在释放插件资源前停止当前 worker 的 SSE 与 WebSocket。"""
await self.connections.drain()
@staticmethod
@@ -281,7 +282,6 @@ async def _reject(scope: Scope, receive: Receive, send: Send, status: int, messa
:param send: ASGI 消息发送函数
:param status: HTTP 拒绝响应状态码
:param message: 拒绝原因
- :return: None
"""
if scope['type'] == 'websocket':
await send({'type': 'websocket.close', 'code': 1008, 'reason': message})
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/bootstrap.py b/ruoyi-fastapi-backend/plugins/core/runtime/bootstrap.py
index 2bff74cda..fbfef42bf 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/bootstrap.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/bootstrap.py
@@ -15,18 +15,14 @@
class PluginEntityImportFailure(BaseModel):
- """
- 插件实体导入失败结果。
- """
+ """插件实体导入失败结果。"""
plugin_id: str = Field(description='插件ID')
error_message: str = Field(description='错误信息')
class PluginEntityImportResult(BaseModel):
- """
- 插件实体导入结果。
- """
+ """插件实体导入结果。"""
imported_count: int = Field(default=0, description='成功导入实体模块数量')
failures: list[PluginEntityImportFailure] = Field(default_factory=list, description='实体导入失败结果列表')
@@ -38,6 +34,16 @@ class PluginRuntimeBuilder:
使用 Builder 模式封装插件发现和运行时注册表构建过程,便于后续逐步加入数据库状态、
依赖检查和生命周期处理。
+
+ :ivar backend_root: 后端项目根目录
+ :ivar plugins_root: 后端插件根目录
+ :ivar frontend_plugins_root: 存放前端插件资源的根目录
+ :ivar entity_importer: 加载插件实体模型的导入器
+ :ivar _discovered_plugins: 本次扫描发现的插件
+ :ivar _discovery_errors: 扫描插件目录时收集的错误
+ :ivar _artifact_plugins: 从制品存储发现的插件
+ :ivar _artifact_errors: 读取插件制品时遇到的错误
+ :ivar _artifact_plugin_ids: 由制品存储管理的插件标识
"""
def __init__(self, backend_root: Path | str | None = None) -> None:
@@ -71,7 +77,6 @@ def set_artifact_plugins(
:param plugins: 启动时已通过验签的发布插件快照
:param reserved_ids: 已被制品发布记录占用的插件 ID 集合
:param errors: 制品解析过程中收集的插件发现错误列表
- :return: None
"""
self._artifact_plugins = list(plugins)
self._artifact_plugin_ids = set(reserved_ids)
@@ -130,11 +135,7 @@ def build_registry(self, database_plugins: list[PluginStateRecord] | None = None
return PluginRegistry.build(self.discover_plugins(), database_plugins)
def import_builtin_entities(self) -> None:
- """
- 导入内置业务模块实体。
-
- :return: None
- """
+ """导入内置业务模块实体。"""
self.entity_importer.import_builtin_entities()
def import_plugin_entities(self, plugin_registry: PluginRegistry) -> PluginEntityImportResult:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/browser_session.py b/ruoyi-fastapi-backend/plugins/core/runtime/browser_session.py
index 1496eab8d..7513f88d0 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/browser_session.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/browser_session.py
@@ -24,20 +24,18 @@
class PluginBrowserSession(BaseModel):
- """
- Redis 内部记录;不作为 API 响应或日志字段。
- """
+ """Redis 内部记录;不作为 API 响应或日志字段。"""
model_config = ConfigDict(extra='forbid', frozen=True)
- plugin_id: str
- version: str
- main_key: str
- main_digest: str = Field(pattern=r'^[a-f0-9]{64}$')
- user_id: int = Field(gt=0)
- origin: str
- nonce: str = Field(pattern=r'^[A-Za-z0-9_-]{43}$')
- csrf: str = Field(pattern=r'^[A-Za-z0-9_-]{43}$')
+ plugin_id: str = Field(description='插件标识')
+ version: str = Field(description='插件版本')
+ main_key: str = Field(description='当前登录会话的缓存键')
+ main_digest: str = Field(pattern=r'^[a-f0-9]{64}$', description='主登录凭据的绑定摘要')
+ user_id: int = Field(gt=0, description='用户标识')
+ origin: str = Field(description='会话绑定的浏览器来源')
+ nonce: str = Field(pattern=r'^[A-Za-z0-9_-]{43}$', description='绑定该会话的随机数')
+ csrf: str = Field(pattern=r'^[A-Za-z0-9_-]{43}$', description='防止跨站请求伪造的令牌')
def _digest(value: str) -> str:
@@ -68,6 +66,7 @@ def plugin_browser_base(request: Request, plugin_id: str) -> str:
:param request: 签发插件会话的宿主请求
:param plugin_id: 插件 ID
:return: 包含宿主部署前缀的插件浏览器入口路径
+ :raises ValueError: 插件浏览器入口需要安全的部署 root_path
"""
root = str(request.scope.get('root_path', '')).rstrip('/')
if not SAFE_ROOT_PATTERN.fullmatch(root):
@@ -81,6 +80,7 @@ def _parse_record(raw: str | bytes | None) -> PluginBrowserSession:
:param raw: Redis 返回的会话 JSON 字符串或字节串
:return: 验证后的插件浏览器会话记录
+ :raises LookupError: 插件浏览器会话缺失、过期或内容无效
"""
if not raw:
raise LookupError(I18nMessage('插件会话已过期', msg_key='plugin.session.expired'))
@@ -105,6 +105,8 @@ async def issue_browser_session(
:param main_token: 当前用户的宿主登录凭证
:param user_id: 已认证的用户 ID
:return: 插件 Cookie 值、CSRF 凭证和有效秒数
+ :raises PermissionError: 请求来源与宿主不同源或用户身份不匹配
+ :raises LookupError: 主会话缺少标识、已失效或已过期
"""
origin = request_origin(request)
if request.headers.get('origin') not in (None, origin):
@@ -175,6 +177,8 @@ async def authenticate_browser_session(
:param query_db: 用于查询用户及权限的数据库会话
:param websocket: 是否按 WebSocket 请求执行来源校验
:return: 通过宿主身份及权限校验的当前用户
+ :raises LookupError: 缺少插件会话;插件会话无效;主登录会话已失效
+ :raises PermissionError: 插件会话不适用于此插件或版本;插件会话来源不匹配;插件请求缺少同源 Origin;插件请求 CSRF 校验失败;插件会话用户身份不匹配
"""
cookie = request.cookies.get(f'{COOKIE_NAME_PREFIX}{plugin_id}', '')
matched = COOKIE_PATTERN.fullmatch(cookie)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/bundle.py b/ruoyi-fastapi-backend/plugins/core/runtime/bundle.py
index 1f8a74e8b..fd7538ffe 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/bundle.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/bundle.py
@@ -40,6 +40,13 @@ class PluginBundleASGI:
构建目录应在部署后保持只读。此类只负责静态交付,不签发会话、不公开资源,
也不改变外层传输加密策略。lifespan 和非 UI 请求始终委派原始子应用。
+
+ :ivar child_app: 接收非 UI 请求的原始插件 ASGI 应用
+ :ivar plugin_id: 插件 ID
+ :ivar plugin_root: 插件资源根目录
+ :ivar bundle_manifest: 插件前端构建产物声明
+ :ivar bundle_root: 前端资源包所在的根目录
+ :ivar entry_path: 前端资源包入口所在的路径
"""
def __init__(
@@ -56,7 +63,7 @@ def __init__(
:param plugin_id: 插件 ID
:param plugin_root: 插件资源根目录
:param bundle_manifest: 插件前端构建产物声明
- :return: None
+ :raises ValueError: 插件 bundle 目录不存在;插件 bundle 入口不存在
"""
self.child_app = child_app
self.plugin_id = plugin_id
@@ -76,7 +83,6 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
:param scope: ASGI 请求作用域
:param receive: ASGI 消息接收函数
:param send: ASGI 消息发送函数
- :return: None
"""
if scope['type'] != 'http':
await self.child_app(scope, receive, send)
@@ -243,6 +249,7 @@ def _resolve_declared_path(cls, root: Path, relative_path: str) -> Path:
:param root: 允许访问的资源根目录
:param relative_path: 清单声明的相对资源路径
:return: 位于允许目录内的资源绝对路径
+ :raises ValueError: 插件 bundle 资源路径非法;插件 bundle 资源路径越界
"""
if not cls._safe_parts(relative_path):
raise ValueError('插件 bundle 资源路径非法')
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/callable.py b/ruoyi-fastapi-backend/plugins/core/runtime/callable.py
index a590e6474..f8e183aa5 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/callable.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/callable.py
@@ -14,9 +14,9 @@ class LoadedPluginCallable:
"""
已加载的插件 callable。
- :param module_name: 完整 Python 模块名
- :param callable_name: callable 名称
- :param callable_object: callable 对象
+ :ivar module_name: 完整 Python 模块名
+ :ivar callable_name: callable 名称
+ :ivar callable_object: callable 对象
"""
module_name: str
@@ -30,6 +30,9 @@ class PluginCallableLoader:
使用 Loader 模式统一插件生命周期钩子、健康检查等 manifest callable 的模块边界校验、
本地文件加载和 Python import fallback。
+
+ :ivar discovered_plugin: 已发现插件对象
+ :ivar label: callable 类型标签,用于错误信息
"""
def __init__(self, discovered_plugin: DiscoveredPlugin, *, label: str) -> None:
@@ -38,7 +41,6 @@ def __init__(self, discovered_plugin: DiscoveredPlugin, *, label: str) -> None:
:param discovered_plugin: 已发现插件对象
:param label: callable 类型标签,用于错误信息
- :return: None
"""
self.discovered_plugin = discovered_plugin
self.label = label
@@ -49,6 +51,7 @@ def load(self, callable_path: str) -> LoadedPluginCallable:
:param callable_path: manifest 中声明的 callable 路径,格式为 :
:return: 已加载 callable
+ :raises RuntimeError: 插件回调不存在或不可调用
"""
if self.discovered_plugin.manifest.uses_entrypoint:
from plugins.core.runtime.entrypoint import PluginEntrypointLoader # noqa: PLC0415
@@ -76,6 +79,7 @@ def resolve_module_name(self, module_path: str) -> str:
:param module_path: manifest 中声明的模块路径
:return: 完整 Python 模块名
+ :raises RuntimeError: 模块路径不属于当前插件
"""
plugin_module = self.discovered_plugin.manifest.backend.module
if module_path == plugin_module or module_path.startswith(f'{plugin_module}.'):
@@ -134,6 +138,7 @@ def load_module_from_file(module_name: str, module_file: Path) -> ModuleType:
:param module_name: 完整 Python 模块名
:param module_file: 模块文件路径
:return: Python 模块对象
+ :raises RuntimeError: 无法为目标文件创建模块加载器
"""
module_spec = importlib.util.spec_from_file_location(module_name, module_file)
if module_spec is None or module_spec.loader is None:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/configuration.py b/ruoyi-fastapi-backend/plugins/core/runtime/configuration.py
index 4d6f5c20b..4ad99c7a5 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/configuration.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/configuration.py
@@ -32,25 +32,29 @@ def config_revision(plugin_id: str, values: Mapping[str, Any]) -> str:
class PluginConfigObservation(BaseModel):
- """
- 当前 worker 的启动配置和最近一次按需读取版本,不包含配置值。
- """
+ """当前 worker 的启动配置和最近一次按需读取版本,不包含配置值。"""
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra='forbid', strict=True)
- plugin_id: str = Field(pattern=r'^[a-z][a-z0-9_]{1,63}$')
- version: str = Field(max_length=128)
- digest: str | None = Field(default=None, pattern=r'^[0-9a-f]{64}$')
- generation: str | None = Field(default=None, pattern=r'^[0-9a-f]{32}$')
- active: bool = False
- startup_revision: str = Field(pattern=r'^[0-9a-f]{64}$')
- last_read_revision: str | None = Field(default=None, pattern=r'^[0-9a-f]{64}$')
- last_read_at: float | None = Field(default=None, ge=0, allow_inf_nan=False)
+ plugin_id: str = Field(pattern=r'^[a-z][a-z0-9_]{1,63}$', description='插件标识')
+ version: str = Field(max_length=128, description='插件版本')
+ digest: str | None = Field(default=None, pattern=r'^[0-9a-f]{64}$', description='已加载制品的内容摘要')
+ generation: str | None = Field(default=None, pattern=r'^[0-9a-f]{32}$', description='当前插件发布代次')
+ active: bool = Field(default=False, description='是否处于活动状态')
+ startup_revision: str = Field(pattern=r'^[0-9a-f]{64}$', description='启动时读取的配置版本')
+ last_read_revision: str | None = Field(
+ default=None, pattern=r'^[0-9a-f]{64}$', description='最近一次读取的配置版本'
+ )
+ last_read_at: float | None = Field(default=None, ge=0, allow_inf_nan=False, description='最近一次读取配置的时间戳')
class PluginConfigReader:
"""
绑定已加载清单的配置读取器,每次读取使用自己的数据库会话。
+
+ :ivar plugin: 当前进程实际加载的插件
+ :ivar session_factory: 宿主提供的数据库会话工厂
+ :ivar observation: 不包含敏感值的运行观测记录
"""
def __init__(
@@ -65,7 +69,6 @@ def __init__(
:param plugin: 当前进程实际加载的插件
:param session_factory: 宿主提供的数据库会话工厂
:param observation: 不包含敏感值的运行观测记录
- :return: None
"""
self.plugin = plugin
self.session_factory = session_factory
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/connections.py b/ruoyi-fastapi-backend/plugins/core/runtime/connections.py
index 44173ca27..8152c6373 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/connections.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/connections.py
@@ -26,11 +26,11 @@ class ConnectionClosure:
"""
可公开的连接关闭原因,不携带凭证或底层异常详情。
- :param code: 对应的 HTTP 状态
- :param reason: 稳定的机器可读原因
- :param message: WebSocket 关闭提示
- :param outcome: 运行观测的终态分类
- :param websocket_code: WebSocket 关闭码
+ :ivar code: 对应的 HTTP 状态
+ :ivar reason: 稳定的机器可读原因
+ :ivar message: WebSocket 关闭提示
+ :ivar outcome: 运行观测的终态分类
+ :ivar websocket_code: WebSocket 关闭码
"""
code: int
@@ -67,6 +67,15 @@ def _user_id(context: PluginRequestContext) -> Any:
class PluginConnectionManager:
"""
复核当前 worker 的 SSE 与 WebSocket,关闭前先取消业务任务。
+
+ :ivar authorize: 使用独立数据库会话重新鉴权的授权器
+ :ivar ready: 当前插件是否仍然就绪
+ :ivar recheck_interval: 相邻复核的等待秒数
+ :ivar recheck_timeout: 单次复核的超时秒数
+ :ivar cancel_timeout: 业务取消及关闭消息发送分别允许的等待秒数
+ :ivar closing: 是否正在关闭连接
+ :ivar connections: 当前由网关管理的连接
+ :ivar _unfinished: 尚未完成关闭的连接
"""
def __init__(
@@ -86,7 +95,7 @@ def __init__(
:param recheck_interval: 相邻复核的等待秒数
:param recheck_timeout: 单次复核的超时秒数
:param cancel_timeout: 业务取消及关闭消息发送分别允许的等待秒数
- :return: None
+ :raises ValueError: 连接复核和关闭时间必须大于零
"""
if any(not math.isfinite(value) or value <= 0 for value in (recheck_interval, recheck_timeout, cancel_timeout)):
raise ValueError('连接复核和关闭时间必须大于零')
@@ -136,17 +145,12 @@ async def run(
:param context: 首次鉴权所得的权限快照
:param receive: 原始 ASGI 消息接收函数
:param send: 原始 ASGI 消息发送函数
- :return: None
"""
connection = _PluginConnection(self, scope, context, receive, send)
await connection.run(app, child_scope)
async def drain(self) -> None:
- """
- 拒绝新连接并并发关闭当前流,在有限时间内等待请求退出。
-
- :return: None
- """
+ """拒绝新连接并并发关闭当前流,在有限时间内等待请求退出。"""
self.closing = True
connections = tuple(self.connections)
for connection in connections:
@@ -162,7 +166,6 @@ async def cancel_task(self, task: asyncio.Task[Any]) -> None:
有界等待协作式取消,保留未退出任务并回收它们最终的异常。
:param task: 需要停止的异步任务
- :return: None
"""
if not task.done():
task.cancel()
@@ -180,7 +183,6 @@ def _finish_task(self, task: asyncio.Task[Any]) -> None:
释放迟到任务并读取异常,避免未处理任务异常告警。
:param task: 已完成的迟到任务
- :return: None
"""
self._unfinished.discard(task)
with suppress(asyncio.CancelledError, Exception):
@@ -190,6 +192,20 @@ def _finish_task(self, task: asyncio.Task[Any]) -> None:
class _PluginConnection:
"""
单条请求的收发状态及权限复核任务。
+
+ :ivar manager: 当前插件的连接管理器
+ :ivar scope: 宿主请求作用域
+ :ivar auth_scope: 建立连接时取得的授权范围
+ :ivar context: 初始权限快照
+ :ivar receive: 原始接收函数
+ :ivar send: 原始发送函数
+ :ivar owner: 负责当前操作的对象
+ :ivar closed: 是否已经关闭该连接
+ :ivar checker: 用于取得或验证健康状态的检查器
+ :ivar started: 是否已经完成启动
+ :ivar completed: 命令执行完成后的进程结果
+ :ivar disconnected: 对端是否已断开连接
+ :ivar line_ended: 当前响应行是否已结束
"""
def __init__(
@@ -208,7 +224,6 @@ def __init__(
:param context: 初始权限快照
:param receive: 原始接收函数
:param send: 原始发送函数
- :return: None
"""
self.manager = manager
self.scope = scope
@@ -229,7 +244,6 @@ def stop(self, reason: ConnectionClosure) -> None:
记录首次关闭原因并阻止后续业务消息进入连接。
:param reason: 已脱敏的关闭原因
- :return: None
"""
if not self.closed.done() and not self.completed:
self.closed.set_result(reason)
@@ -238,7 +252,7 @@ def _open(self) -> None:
"""
仅为事件流及已接受的 WebSocket 启动周期复核。
- :return: None
+ :raises asyncio.CancelledError: 管理器关闭时取消启动
"""
if self.manager.closing:
self.stop(PLUGIN_SHUTDOWN)
@@ -249,11 +263,7 @@ def _open(self) -> None:
self.checker = asyncio.create_task(self._check())
async def _check(self) -> None:
- """
- 定期重新鉴权;权限减配、用户变化或无法确认身份时关闭连接。
-
- :return: None
- """
+ """定期重新鉴权;权限减配、用户变化或无法确认身份时关闭连接。"""
try:
while True:
await asyncio.sleep(self.manager.recheck_interval)
@@ -295,7 +305,7 @@ async def _send(self, message: Message) -> None:
识别长连接并隔离已撤销连接的迟到输出。
:param message: 插件发送的 ASGI 消息
- :return: None
+ :raises asyncio.CancelledError: 通道关闭时取消发送
"""
if self.closed.done():
raise asyncio.CancelledError
@@ -323,7 +333,7 @@ async def run(self, app: ASGIApp, child_scope: Scope) -> None:
:param app: 插件 ASGI 应用
:param child_scope: 已注入宿主上下文的请求作用域
- :return: None
+ :raises asyncio.CancelledError: 异步操作被取消时
"""
task = asyncio.create_task(self._invoke(app, child_scope))
try:
@@ -355,7 +365,6 @@ async def _invoke(self, app: ASGIApp, child_scope: Scope) -> None:
:param app: 插件 ASGI 应用
:param child_scope: 已注入宿主上下文的请求作用域
- :return: None
"""
await app(child_scope, self._receive, self._send)
@@ -364,7 +373,6 @@ async def _close_response(self, reason: ConnectionClosure) -> None:
发送协议内的终止消息;SSE 控制事件由宿主适配器转换为失败。
:param reason: 首次记录的关闭原因
- :return: None
"""
if self.scope['type'] == 'websocket':
message = {'type': 'websocket.close', 'code': reason.websocket_code, 'reason': reason.message}
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics.py b/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics.py
index 06a517de2..f5fe861eb 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics.py
@@ -29,6 +29,7 @@ def require_complete_wire_fields(cls, value: Any, info: ValidationInfo) -> Any:
:param value: 当前层级待校验的输入,远端协议只接受 JSON 对象
:param info: 校验上下文,仅 require_complete_snapshot 开启时要求完整协议字段
:return: 字段完整的原始输入;本地构造仍保留模型默认值
+ :raises ValueError: 远端运行诊断必须使用完整 JSON 对象
"""
if not isinstance(info.context, Mapping) or not info.context.get('require_complete_snapshot'):
return value
@@ -45,61 +46,69 @@ def require_complete_wire_fields(cls, value: Any, info: ValidationInfo) -> Any:
class PluginActivationHealth(_DiagnosticModel):
"""最近一次激活健康检查摘要,不表示持续健康且不保存插件返回的描述或详情。"""
- status: Literal['unknown', 'healthy', 'unhealthy', 'error', 'timeout'] = 'unknown'
- checked_at: float | None = Field(default=None, ge=0, allow_inf_nan=False)
- duration_ms: float | None = Field(default=None, ge=0, allow_inf_nan=False)
+ status: Literal['unknown', 'healthy', 'unhealthy', 'error', 'timeout'] = Field(
+ default='unknown', description='当前状态'
+ )
+ checked_at: float | None = Field(default=None, ge=0, allow_inf_nan=False, description='最近一次健康检查的时间戳')
+ duration_ms: float | None = Field(default=None, ge=0, allow_inf_nan=False, description='本次操作耗时(毫秒)')
class PluginLifespanDiagnostic(_DiagnosticModel):
"""宿主管理的生命周期状态;正常存活的任务不等于等待取消的任务。"""
- managed: bool
- started: bool
- ready: bool
- task_active: bool
+ managed: bool = Field(description='是否由宿主管理生命周期')
+ started: bool = Field(description='是否已经启动')
+ ready: bool = Field(description='是否就绪')
+ task_active: bool = Field(description='生命周期任务是否仍在运行')
class PluginConnectionDiagnostic(_DiagnosticModel):
"""已经接受的 WebSocket 和已开始响应的 SSE 连接数量。"""
- sse: NonNegativeInt = 0
- websocket: NonNegativeInt = 0
+ sse: NonNegativeInt = Field(default=0, description='已开始响应的 SSE 连接数')
+ websocket: NonNegativeInt = Field(default=0, description='已接受的 WebSocket 连接数')
class PluginConfigDiagnostic(_DiagnosticModel):
"""不透明配置版本;按需读取完成不代表插件业务已经应用新配置。"""
- startup_revision: str | None = Field(default=None, pattern=r'^[0-9a-f]{64}$')
- last_read_revision: str | None = Field(default=None, pattern=r'^[0-9a-f]{64}$')
- last_read_at: float | None = Field(default=None, ge=0, allow_inf_nan=False)
+ startup_revision: str | None = Field(default=None, pattern=r'^[0-9a-f]{64}$', description='启动时读取的配置版本')
+ last_read_revision: str | None = Field(
+ default=None, pattern=r'^[0-9a-f]{64}$', description='最近一次读取的配置版本'
+ )
+ last_read_at: float | None = Field(default=None, ge=0, allow_inf_nan=False, description='最近一次读取配置的时间戳')
class PluginDiagnosticError(_DiagnosticModel):
"""宿主指标中最近错误的关联字段,不包含异常消息或请求内容。"""
- error_type: str = Field(min_length=1, max_length=80)
- request_id: str | None = Field(default=None, max_length=128)
- at: float = Field(ge=0, allow_inf_nan=False)
+ error_type: str = Field(min_length=1, max_length=80, description='异常类型')
+ request_id: str | None = Field(default=None, max_length=128, description='关联错误的请求标识')
+ at: float = Field(ge=0, allow_inf_nan=False, description='错误发生的时间戳')
class PluginRuntimeDiagnostic(_DiagnosticModel):
"""一个 worker 已加载的显式插件状态;身份始终来自实际加载对象。"""
- plugin_id: str = Field(pattern=r'^[a-z][a-z0-9_]{1,63}$')
- version: str = Field(max_length=128)
- digest: str | None = Field(default=None, pattern=r'^[0-9a-f]{64}$')
- generation: str | None = Field(default=None, pattern=r'^[0-9a-f]{32}$')
- active: bool
- ready: bool
- closing: bool
- lifespan: PluginLifespanDiagnostic | None = None
- connections: PluginConnectionDiagnostic = Field(default_factory=PluginConnectionDiagnostic)
- active_jobs: NonNegativeInt = 0
- pending_connection_tasks: NonNegativeInt = 0
- pending_job_tasks: NonNegativeInt = 0
- activation_health: PluginActivationHealth = Field(default_factory=PluginActivationHealth)
- config: PluginConfigDiagnostic = Field(default_factory=PluginConfigDiagnostic)
- last_error: PluginDiagnosticError | None = None
+ plugin_id: str = Field(pattern=r'^[a-z][a-z0-9_]{1,63}$', description='插件标识')
+ version: str = Field(max_length=128, description='插件版本')
+ digest: str | None = Field(default=None, pattern=r'^[0-9a-f]{64}$', description='已加载制品的内容摘要')
+ generation: str | None = Field(default=None, pattern=r'^[0-9a-f]{32}$', description='当前插件发布代次')
+ active: bool = Field(description='是否处于活动状态')
+ ready: bool = Field(description='是否就绪')
+ closing: bool = Field(description='是否正在关闭')
+ lifespan: PluginLifespanDiagnostic | None = Field(default=None, description='子应用生命周期的观测状态')
+ connections: PluginConnectionDiagnostic = Field(
+ default_factory=PluginConnectionDiagnostic, description='当前插件的活动连接统计'
+ )
+ active_jobs: NonNegativeInt = Field(default=0, description='正在执行的调度任务数')
+ pending_connection_tasks: NonNegativeInt = Field(default=0, description='等待回收的连接任务数')
+ pending_job_tasks: NonNegativeInt = Field(default=0, description='等待回收的调度任务数')
+ activation_health: PluginActivationHealth = Field(
+ default_factory=PluginActivationHealth, description='最近一次插件激活健康检查结果'
+ )
+ config: PluginConfigDiagnostic = Field(default_factory=PluginConfigDiagnostic, description='插件配置信息')
+ last_error: PluginDiagnosticError | None = Field(default=None, description='最近一次错误的信息')
class PluginRuntimeDiagnosticSnapshot(_DiagnosticModel):
@@ -110,12 +119,14 @@ class PluginRuntimeDiagnosticSnapshot(_DiagnosticModel):
包含各插件的待回收子项,不能与它们再次相加。未受宿主跟踪的业务任务不在此范围内。
"""
- schema_version: Literal[1] = 1
- worker_id: str = Field(pattern=r'^[0-9a-f]{32}$')
- collected_at: float = Field(ge=0, allow_inf_nan=False)
- plugins: list[PluginRuntimeDiagnostic] = Field(default_factory=list, max_length=MAX_DIAGNOSTIC_PLUGINS)
- worker_pending_cleanup_tasks: NonNegativeInt = 0
- dropped_plugins: NonNegativeInt = 0
+ schema_version: Literal[1] = Field(default=1, description='数据结构的版本')
+ worker_id: str = Field(pattern=r'^[0-9a-f]{32}$', description='工作进程标识')
+ collected_at: float = Field(ge=0, allow_inf_nan=False, description='采集快照的时间戳')
+ plugins: list[PluginRuntimeDiagnostic] = Field(
+ default_factory=list, max_length=MAX_DIAGNOSTIC_PLUGINS, description='插件列表'
+ )
+ worker_pending_cleanup_tasks: NonNegativeInt = Field(default=0, description='工作进程中等待清理的任务总数')
+ dropped_plugins: NonNegativeInt = Field(default=0, description='因快照容量限制而舍弃的插件数')
@field_validator('schema_version', mode='before')
@classmethod
@@ -125,6 +136,7 @@ def validate_schema_version(cls, value: Any) -> int:
:param value: 显式提供的协议版本
:return: 通过严格类型与版本检查的整数
+ :raises ValueError: schemaVersion 必须为整数 1
"""
if type(value) is not int or value != 1:
raise ValueError('schemaVersion 必须为整数 1')
@@ -136,6 +148,7 @@ def validate_unique_plugins(self) -> 'PluginRuntimeDiagnosticSnapshot':
拒绝单个 worker 在同一快照中重复报告同一插件。
:return: 插件身份唯一的诊断快照
+ :raises ValueError: 插件运行诊断快照包含重复插件 ID
"""
if len({plugin.plugin_id for plugin in self.plugins}) != len(self.plugins):
raise ValueError('插件运行诊断快照包含重复插件 ID')
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics_store.py b/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics_store.py
index 2056005eb..7f9ca0179 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics_store.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics_store.py
@@ -159,6 +159,14 @@ def _worker_payload(snapshot: PluginRuntimeDiagnosticSnapshot, plugin_id: str |
class PluginDiagnosticsReporter:
"""
发布独立版本的运行诊断快照,查询故障时仅返回当前进程的真实观测。
+
+ :ivar snapshot_provider: 复制当前运行时状态的同步函数
+ :ivar worker_id: 与发布心跳和指标一致的进程标识
+ :ivar redis: 用于缓存或发布消息的 Redis 客户端
+ :ivar namespace: 隔离当前资源的命名空间
+ :ivar task: 在后台执行当前工作的异步任务
+ :ivar publication_failed: 最近一次发布是否失败
+ :ivar _stopping: 是否已经开始关闭
"""
def __init__(self, snapshot_provider: Callable[[], PluginRuntimeDiagnosticSnapshot], worker_id: str) -> None:
@@ -167,7 +175,7 @@ def __init__(self, snapshot_provider: Callable[[], PluginRuntimeDiagnosticSnapsh
:param snapshot_provider: 复制当前运行时状态的同步函数
:param worker_id: 与发布心跳和指标一致的进程标识
- :return: None
+ :raises ValueError: 诊断 worker 标识无效
"""
if re.fullmatch(r'[0-9a-f]{32}', worker_id) is None:
raise ValueError('诊断 worker 标识无效')
@@ -194,7 +202,6 @@ def start(self, redis: Any, namespace: str) -> None:
:param redis: 当前宿主 Redis 客户端
:param namespace: 当前部署的诊断键空间
- :return: None
"""
if self.task is not None:
return
@@ -209,6 +216,7 @@ def _snapshot(self) -> PluginRuntimeDiagnosticSnapshot:
校验采样身份,防止误用其他 worker 的快照。
:return: 当前 worker 的独立采样
+ :raises ValueError: 诊断快照的 worker 标识不匹配
"""
snapshot = self.snapshot_provider()
if snapshot.worker_id != self.worker_id:
@@ -216,11 +224,7 @@ def _snapshot(self) -> PluginRuntimeDiagnosticSnapshot:
return snapshot
async def publish(self) -> None:
- """
- 发布有大小限制和 TTL 的运行快照,失败时保留本地查询能力。
-
- :return: None
- """
+ """发布有大小限制和 TTL 的运行快照,失败时保留本地查询能力。"""
if self.redis is None:
return
try:
@@ -238,11 +242,7 @@ async def publish(self) -> None:
self.publication_failed = False
async def _run(self) -> None:
- """
- 在启动后尽快发布,随后定期复制纯内存状态。
-
- :return: None
- """
+ """在启动后尽快发布,随后定期复制纯内存状态。"""
while not self._stopping:
await self.publish()
if not self._stopping:
@@ -271,11 +271,7 @@ async def read(self, plugin_id: str | None = None) -> dict[str, Any]:
return result
async def stop(self) -> None:
- """
- 停止周期发布并仅删除本 worker 的快照,删除失败时依赖 TTL。
-
- :return: None
- """
+ """停止周期发布并仅删除本 worker 的快照,删除失败时依赖 TTL。"""
self._stopping = True
if self.task is not None:
self.task.cancel()
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/entities.py b/ruoyi-fastapi-backend/plugins/core/runtime/entities.py
index a643db06f..10d3bb88f 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/entities.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/entities.py
@@ -11,7 +11,9 @@ class EntityModuleImporter:
实体模块导入器。
使用 Template Method 模式统一实体文件扫描、模块名转换和导入流程,确保
- SQLAlchemy 在执行 `Base.metadata.create_all` 前可以收集到已启用模块的 DO 元数据。
+ SQLAlchemy 在执行 ``Base.metadata.create_all`` 前可以收集到已启用模块的 DO 元数据。
+
+ :ivar backend_root: 后端项目根目录
"""
def __init__(self, backend_root: Path | str | None = None) -> None:
@@ -70,11 +72,7 @@ def import_entity_dirs(self, entity_do_dirs: list[Path], strict: bool) -> list[M
return imported_modules
def _extend_plugins_package_path(self) -> None:
- """
- 扩展已加载 plugins 包的搜索路径。
-
- :return: None
- """
+ """扩展已加载 plugins 包的搜索路径。"""
plugins_root = self.backend_root / 'plugins'
if not plugins_root.is_dir():
return
@@ -107,6 +105,7 @@ def _import_entity_file(self, entity_file: Path, strict: bool) -> ModuleType | N
:param entity_file: 实体文件路径
:param strict: 是否在导入失败时抛出异常
:return: 已导入模块,导入失败且非严格模式时返回 None
+ :raises Exception: 严格模式下无法导入实体模块
"""
module_name = self._to_module_name(entity_file)
try:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/entrypoint.py b/ruoyi-fastapi-backend/plugins/core/runtime/entrypoint.py
index 44098be12..2a8bdce05 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/entrypoint.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/entrypoint.py
@@ -25,9 +25,9 @@ class PluginModuleLocation:
"""
静态定位结果,不执行包初始化或原生模块代码。
- :param module_name: 插件模块完整名称
- :param path: 模块文件的绝对路径
- :param is_package: 模块是否为 Python 包
+ :ivar module_name: 插件模块完整名称
+ :ivar path: 模块文件的绝对路径
+ :ivar is_package: 模块是否为 Python 包
"""
module_name: str
@@ -38,6 +38,9 @@ class PluginModuleLocation:
class PluginEntrypointLoader:
"""
只加载当前插件目录下的模块,拒绝复用其他版本或其他路径的缓存。
+
+ :ivar plugin: 待加载的已发现插件
+ :ivar backend: 后端部分的配置或处理对象
"""
def __init__(self, plugin: DiscoveredPlugin) -> None:
@@ -45,7 +48,7 @@ def __init__(self, plugin: DiscoveredPlugin) -> None:
初始化显式入口加载器并确认插件使用 v2 清单。
:param plugin: 待加载的已发现插件
- :return: None
+ :raises ValueError: 显式入口加载器仅用于 manifestVersion 2
"""
self.plugin = plugin
self.backend = plugin.manifest.backend
@@ -69,6 +72,7 @@ def _contained(self, path: Path) -> Path:
:param path: 待校验的模块或资源路径
:return: 通过目录边界校验的绝对路径
+ :raises ValueError: 模块或资源路径越出插件根目录
"""
resolved = path.resolve()
if not resolved.is_relative_to(self.plugin.backend_path.resolve()):
@@ -81,6 +85,8 @@ def locate_module(self, module_name: str) -> PluginModuleLocation:
:param module_name: 当前插件命名空间内的完整模块名
:return: 模块文件路径及包类型信息
+ :raises ValueError: 入口或回调指向其他插件的模块
+ :raises ImportError: 插件模块不存在
"""
prefix = self.backend.module
if module_name != prefix and not module_name.startswith(f'{prefix}.'):
@@ -105,6 +111,7 @@ def check_entrypoint(self) -> PluginModuleLocation:
执行静态来源和原生平台校验,不执行入口。
:return: 通过来源及平台校验的入口模块位置
+ :raises ValueError: native entrypoint 必须位于原生 Python 扩展模块
"""
module_name = self.backend.entrypoint.split(':', 1)[0]
location = self.locate_module(module_name)
@@ -119,7 +126,7 @@ def _check_native_distribution(self, location: PluginModuleLocation) -> None:
校验原生发行包版本、平台标签及入口文件摘要。
:param location: 已定位的原生入口模块
- :return: None
+ :raises ValueError: 当前 native 运行时仅支持带 GIL 的 CPython;native.moduleRoot 必须包含唯一匹配的已安装 wheel 元数据;原生发行包版本必须与插件版本一致;原生 wheel 平台、Python 或 ABI 与当前解释器不兼容;原生入口必须包含在发行包 RECORD 中并声明 SHA256;原生入口 SHA256 与发行包 RECORD 不一致
"""
if platform.python_implementation() != 'CPython' or sysconfig.get_config_var('Py_GIL_DISABLED'):
raise ValueError('当前 native 运行时仅支持带 GIL 的 CPython')
@@ -155,6 +162,7 @@ def import_module(self, module_name: str) -> ModuleType:
:param module_name: 当前插件命名空间内的完整模块名
:return: 已从绑定路径加载的模块对象
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
self.locate_module(module_name)
before = set(sys.modules)
@@ -184,6 +192,7 @@ def _import_one(self, module_name: str) -> ModuleType:
:param module_name: 当前插件命名空间内的完整模块名
:return: 来源路径一致的模块对象
+ :raises ImportError: 模块已从其他位置加载或无法创建加载器
"""
location = self.locate_module(module_name)
cached = sys.modules.get(module_name)
@@ -214,6 +223,7 @@ def load_callable(self, callable_path: str) -> Any:
:param callable_path: 采用模块路径与函数名冒号分隔格式的入口或回调路径
:return: 通过可调用性校验的入口或回调对象
+ :raises TypeError: 插件入口或回调不可调用
"""
module_name, callable_name = callable_path.split(':', 1)
module = self.import_module(module_name)
@@ -228,6 +238,8 @@ def load(self, host: PluginHostContext) -> PluginDefinition:
:param host: 与当前插件身份及资源目录绑定的宿主上下文
:return: 通过协议校验的插件能力定义
+ :raises ValueError: HostContext 与待加载插件不匹配
+ :raises TypeError: 插件入口工厂必须同步返回 PluginDefinition,资源初始化请使用生命周期;插件入口必须返回 PluginDefinition
"""
self.check_entrypoint()
if host.plugin_id != self.plugin.manifest.id or host.resource_root != self.plugin.backend_path.resolve():
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/explicit.py b/ruoyi-fastapi-backend/plugins/core/runtime/explicit.py
index 81313be29..12c31865d 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/explicit.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/explicit.py
@@ -45,14 +45,14 @@ class LoadedExplicitPlugin:
"""
一个 worker 的已加载定义及可选 lifespan。
- :param plugin: 注册表中的插件记录
- :param host: 当前插件的宿主能力上下文
- :param definition: 入口返回的插件能力定义
- :param lifespan: ASGI 子应用生命周期管理器
- :param active: 插件是否已完成激活
- :param jobs: 当前 worker 中的插件任务绑定
- :param gateway: 当前 worker 的 ASGI 长连接管理入口
- :param activation_health: 最近一次激活健康检查的安全摘要,不表示持续健康
+ :ivar plugin: 注册表中的插件记录
+ :ivar host: 当前插件的宿主能力上下文
+ :ivar definition: 入口返回的插件能力定义
+ :ivar lifespan: ASGI 子应用生命周期管理器
+ :ivar active: 插件是否已完成激活
+ :ivar jobs: 当前 worker 中的插件任务绑定
+ :ivar gateway: 当前 worker 的 ASGI 长连接管理入口
+ :ivar activation_health: 最近一次激活健康检查的安全摘要,不表示持续健康
"""
plugin: RegisteredPlugin
@@ -68,6 +68,12 @@ class LoadedExplicitPlugin:
class ExplicitPluginRuntime:
"""
仅负责当前 worker 的代码和资源,全局迁移仍由原有 writer 处理。
+
+ :ivar route_state_gateway: 插件启用状态查询网关
+ :ivar loaded: 当前 worker 已准备的插件实例
+ :ivar metrics: 当前运行状态的指标
+ :ivar metrics_reporter: 采集并发布插件指标的对象
+ :ivar _closing: 是否正在关闭运行时
"""
def __init__(self, route_state_gateway: PluginRouteStateGateway) -> None:
@@ -75,7 +81,6 @@ def __init__(self, route_state_gateway: PluginRouteStateGateway) -> None:
初始化当前 worker 的显式插件运行时。
:param route_state_gateway: 插件启用状态查询网关
- :return: None
"""
self.route_state_gateway = route_state_gateway
self.loaded: dict[str, LoadedExplicitPlugin] = {}
@@ -109,7 +114,7 @@ def visit(plugin_id: str) -> None:
递归访问插件依赖并记录拓扑顺序。
:param plugin_id: 当前访问的插件 ID
- :return: None
+ :raises ValueError: 依赖关系存在循环或依赖插件未启用
"""
if plugin_id in visited:
return
@@ -151,7 +156,7 @@ def collect(current: str, closure: dict[str, RegisteredPlugin] = closure) -> Non
:param current: 当前访问的插件 ID
:param closure: 当前入口已收集的依赖插件映射
- :return: None
+ :raises ValueError: 依赖插件未启用
"""
if current in closure:
return
@@ -184,7 +189,8 @@ def prepare(
:param app: 宿主 FastAPI 应用
:param startup_write_enabled: 当前 worker 是否允许执行启动期全局写入
:param config_values: 插件专属配置快照,未提供时使用清单默认值
- :return: None
+ :raises ValueError: 插件结构或兼容性未通过检查
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
if plugin.plugin_id in self.loaded:
return
@@ -258,7 +264,8 @@ async def activate(self, plugin_id: str, app: FastAPI) -> None:
:param plugin_id: 已完成准备的插件 ID
:param app: 宿主 FastAPI 应用
- :return: None
+ :raises RuntimeError: 插件运行时已进入关闭阶段,不能激活插件
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
if self._closing:
raise RuntimeError('插件运行时已进入关闭阶段,不能激活插件')
@@ -297,7 +304,10 @@ async def _activate_web(self, loaded: LoadedExplicitPlugin, app: FastAPI) -> Non
:param loaded: 当前 worker 已准备的插件实例
:param app: 宿主 FastAPI 应用
- :return: None
+ :raises RuntimeError: 插件运行时已进入关闭阶段,不能注册路由
+ :raises TypeError: app_factory 必须同步返回 ASGI 应用;app_factory 必须返回 ASGI callable
+ :raises ValueError: 挂载路径与应用已有路由冲突
+ :raises BaseException: 启动或挂载过程中断,清理资源后传播原异常
"""
plugin_id = loaded.plugin.plugin_id
manifest = loaded.plugin.discovered_plugin.manifest
@@ -348,7 +358,7 @@ async def _check_health(loaded: LoadedExplicitPlugin, app: FastAPI) -> None:
:param loaded: 当前 worker 已准备的插件实例
:param app: 宿主 FastAPI 应用
- :return: None
+ :raises RuntimeError: 插件启动后的健康检查失败
"""
if loaded.plugin.discovered_plugin.manifest.backend.health.checker:
result = await PluginHealthChecker(loaded.plugin.discovered_plugin).check(app=app)
@@ -362,7 +372,7 @@ def _register_routers(self, loaded: LoadedExplicitPlugin, app: FastAPI) -> None:
:param loaded: 当前 worker 已准备的插件实例
:param app: 宿主 FastAPI 应用
- :return: None
+ :raises ValueError: v2 Router 的 WebSocket 或嵌套 Mount 请使用 ASGI 接入
"""
plugin_id = loaded.plugin.plugin_id
@@ -372,7 +382,7 @@ async def set_context(request: Request, user: Any = Depends(LoginService.get_cur
:param request: 插件接口请求
:param user: 宿主登录依赖返回的当前用户
- :return: None
+ :raises HTTPException: 插件未就绪
"""
if not loaded.active:
raise HTTPException(status_code=503, detail='插件未就绪')
@@ -415,6 +425,8 @@ async def authorize(scope: Scope) -> PluginRequestContext:
:param scope: HTTP 或 WebSocket 的 ASGI 请求作用域
:return: 已通过宿主身份及插件访问权限校验的请求上下文
+ :raises PermissionError: 插件未激活或正在关闭;插件未启用
+ :raises LookupError: Bearer 凭证无效;登录已失效;缺少 Bearer 凭证
"""
auth_scope = dict(scope, type='http', app=app)
request = Request(auth_scope)
@@ -459,6 +471,7 @@ def _request_context(loaded: LoadedExplicitPlugin, user: Any) -> PluginRequestCo
:param loaded: 当前 worker 已准备的插件实例
:param user: 宿主登录服务返回的当前用户
:return: 绑定插件能力与当前用户身份的请求上下文
+ :raises PermissionError: 当前用户不具备已声明的插件访问权限
"""
permissions = frozenset(user.permissions)
declared = set(loaded.plugin.discovered_plugin.manifest.permission_codes)
@@ -467,11 +480,7 @@ def _request_context(loaded: LoadedExplicitPlugin, user: Any) -> PluginRequestCo
return PluginRequestContext(loaded.host, user, permissions, request_id=current_plugin_request_id())
async def shutdown(self) -> None:
- """
- 逆序关闭,每个实例的失败不阻止其他实例释放资源。
-
- :return: None
- """
+ """逆序关闭,每个实例的失败不阻止其他实例释放资源。"""
self._closing = True
instances = list(reversed(self.loaded.values()))
for loaded in instances:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/health.py b/ruoyi-fastapi-backend/plugins/core/runtime/health.py
index 5c13d374f..83fa1ff16 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/health.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/health.py
@@ -17,10 +17,10 @@ class PluginHealthContext:
"""
插件健康检查上下文。
- :param plugin_id: 插件 ID
- :param discovered_plugin: 已发现插件对象
- :param app: FastAPI 应用对象
- :param query_db: orm对象
+ :ivar plugin_id: 插件 ID
+ :ivar discovered_plugin: 已发现插件对象
+ :ivar app: FastAPI 应用对象
+ :ivar query_db: orm对象
"""
plugin_id: str
@@ -34,14 +34,14 @@ class PluginHealthResult:
"""
插件健康检查结果。
- :param plugin_id: 插件 ID
- :param ok: 健康检查是否通过
- :param status: 健康状态
- :param message: 健康检查说明
- :param checker: 健康检查声明路径
- :param duration_ms: 检查耗时毫秒
- :param details: 健康检查扩展详情
- :param error: 健康检查异常信息
+ :ivar plugin_id: 插件 ID
+ :ivar ok: 健康检查是否通过
+ :ivar status: 健康状态
+ :ivar message: 健康检查说明
+ :ivar checker: 健康检查声明路径
+ :ivar duration_ms: 检查耗时毫秒
+ :ivar details: 健康检查扩展详情
+ :ivar error: 健康检查异常信息
"""
plugin_id: str
@@ -59,6 +59,9 @@ class PluginHealthChecker:
插件健康检查器。
使用 Strategy + Command Runner 思路执行插件 manifest 中声明的只读健康检查 callable。
+
+ :ivar discovered_plugin: 已发现插件对象
+ :ivar timeout_seconds: 异步健康检查超时时间
"""
def __init__(
@@ -72,7 +75,6 @@ def __init__(
:param discovered_plugin: 已发现插件对象
:param timeout_seconds: 异步健康检查超时时间
- :return: None
"""
self.discovered_plugin = discovered_plugin
self.timeout_seconds = timeout_seconds or PluginRuntimeConstant.PLUGIN_HEALTH_TIMEOUT_SECONDS
@@ -145,6 +147,7 @@ async def _invoke_checker_with_timeout(
:param checker_callable: 已加载的健康检查 callable
:param context: 健康检查上下文
:return: 健康检查原始返回值
+ :raises TypeError: 插件健康检查必须使用 async def 声明,平台不会在线程中执行不可终止的同步检查
"""
callable_object = checker_callable.callable_object
if self.discovered_plugin.manifest.uses_entrypoint:
@@ -181,6 +184,7 @@ def _normalize_result(self, raw_result: object, checker_path: str, started_at: f
:param checker_path: 健康检查声明路径
:param started_at: 检查开始时间
:return: 插件健康检查结果
+ :raises TypeError: v2 插件健康检查必须返回 bool 或包含 bool 类型 ok 字段的字典
"""
if self.discovered_plugin.manifest.uses_entrypoint and not (
isinstance(raw_result, bool) or (isinstance(raw_result, dict) and isinstance(raw_result.get('ok'), bool))
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/hooks.py b/ruoyi-fastapi-backend/plugins/core/runtime/hooks.py
index d814df09c..dabac15e4 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/hooks.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/hooks.py
@@ -15,14 +15,14 @@ class PluginHookContext:
"""
插件生命周期钩子上下文。
- :param plugin_id: 插件 ID
- :param hook_name: 钩子名称
- :param discovered_plugin: 已发现插件对象
- :param app: FastAPI 应用对象
- :param query_db: orm对象
- :param startup_write_enabled: 当前 worker 是否允许执行启动期全局写入
- :param startup_generation: 插件启动代际
- :param plugin_startup_role_at_creation: Hook 创建时的插件启动角色
+ :ivar plugin_id: 插件 ID
+ :ivar hook_name: 钩子名称
+ :ivar discovered_plugin: 已发现插件对象
+ :ivar app: FastAPI 应用对象
+ :ivar query_db: orm对象
+ :ivar startup_write_enabled: 当前 worker 是否允许执行启动期全局写入
+ :ivar startup_generation: 插件启动代际
+ :ivar plugin_startup_role_at_creation: Hook 创建时的插件启动角色
"""
plugin_id: str
@@ -40,9 +40,9 @@ class PluginHookResult:
"""
插件生命周期钩子执行结果。
- :param hook_name: 钩子名称
- :param hook_path: 钩子声明路径
- :param module_name: 钩子模块名
+ :ivar hook_name: 钩子名称
+ :ivar hook_path: 钩子声明路径
+ :ivar module_name: 钩子模块名
"""
hook_name: str
@@ -54,11 +54,14 @@ class PluginHookRunner:
"""
插件生命周期钩子运行器。
- 使用 Command Runner 模式解析并执行 `plugin.yaml` 中声明的生命周期钩子。
- 钩子必须使用 async def 声明,签名支持 `hook()` 或 `hook(context)`。
+ 使用 Command Runner 模式解析并执行 ``plugin.yaml`` 中声明的生命周期钩子。
+ 钩子必须使用 async def 声明,签名支持 ``hook()`` 或 ``hook(context)``。
同步函数在线程池超时后无法被 Python 安全终止,可能在生命周期事务已经回滚后
继续产生副作用,因此平台拒绝执行同步生命周期钩子。
+
+ :ivar discovered_plugin: 已发现插件对象
+ :ivar timeout_seconds: 钩子执行超时时间
"""
def __init__(
@@ -87,11 +90,12 @@ async def run(
"""
执行指定生命周期钩子。
- :param hook_name: 钩子名称,例如 `on_install`
+ :param hook_name: 钩子名称,例如 ``on_install``
:param app: FastAPI 应用对象
:param query_db: orm对象
:param startup_write_enabled: 当前 worker 是否允许执行启动期全局写入
:return: 钩子执行结果,未声明时返回 None
+ :raises TimeoutError: 等待操作超过时限时
"""
hook_path = getattr(self.discovered_plugin.manifest.backend.hooks, hook_name, None)
if not hook_path:
@@ -149,7 +153,7 @@ async def _invoke_hook_with_timeout(
:param hook_callable: 已加载的钩子函数
:param context: 钩子上下文
- :return: None
+ :raises TypeError: 生命周期钩子必须使用 async def 声明,平台不会在线程中执行不可终止的同步钩子
"""
callable_object = hook_callable.callable_object
if self.discovered_plugin.manifest.uses_entrypoint:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/host_services.py b/ruoyi-fastapi-backend/plugins/core/runtime/host_services.py
index b1cc70462..887316712 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/host_services.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/host_services.py
@@ -18,6 +18,7 @@ def _require_request(context: PluginRequestContext, plugin_id: str, capability:
:param plugin_id: 服务绑定的插件 ID
:param capability: 当前服务要求的插件权限后缀
:return: 当前登录用户 ID
+ :raises PermissionError: 请求上下文不属于当前插件;缺少有效的当前用户身份
"""
if not isinstance(context, PluginRequestContext) or context.host.plugin_id != plugin_id:
raise PermissionError('请求上下文不属于当前插件')
@@ -35,7 +36,7 @@ async def _request_session(context: PluginRequestContext, factory: Callable[...,
:param context: 当前插件请求上下文
:param factory: 宿主数据库会话工厂
- :return: 当前服务允许使用的数据库会话
+ :yield: 当前服务允许使用的数据库会话
"""
transaction = context.transaction_session()
if transaction is not None:
@@ -63,6 +64,7 @@ async def current_user_profile(context: PluginRequestContext) -> dict[str, Any]:
:param context: 宿主鉴权层建立的插件请求上下文
:return: 仅包含允许向插件公开字段的当前用户资料
+ :raises LookupError: 当前用户不存在
"""
user_id = _require_request(context, plugin_id, 'profile')
@@ -89,6 +91,7 @@ async def dictionary_items(context: PluginRequestContext, dict_type: str) -> lis
:param context: 当前插件请求上下文
:param dict_type: 非空字典类型标识
:return: 按宿主字典顺序排列的选项数据
+ :raises ValueError: 字典类型必须是有效的非空标识
"""
_require_request(context, plugin_id, 'dict')
if not isinstance(dict_type, str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_]{0,99}', dict_type):
@@ -116,6 +119,8 @@ def cache_key(context: PluginRequestContext, key: str) -> str:
:param context: 当前插件请求上下文
:param key: 当前插件内的缓存键
:return: 带有插件前缀的完整 Redis 键
+ :raises ValueError: 插件缓存键必须是 1 至 128 位字母、数字或 _ . : -
+ :raises RuntimeError: 宿主未提供 Redis 缓存能力
"""
_require_request(context, plugin_id, 'cache')
if not isinstance(key, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}', key):
@@ -131,6 +136,7 @@ async def cache_get(context: PluginRequestContext, key: str) -> Any:
:param context: 当前插件请求上下文
:param key: 当前插件内的缓存键
:return: 已解码的 JSON 数据或 None
+ :raises ValueError: 插件缓存内容超过大小限制;插件缓存内容不是有效 JSON
"""
name = cache_key(context, key)
value = await redis.get(name)
@@ -154,7 +160,7 @@ async def cache_set(context: PluginRequestContext, key: str, value: Any, ttl_sec
:param key: 当前插件内的缓存键
:param value: 可序列化的 JSON 数据
:param ttl_seconds: 有效期秒数,范围为 1 至 86400
- :return: None
+ :raises ValueError: 插件缓存有效期必须在 1 至 86400 秒之间;插件缓存内容超过大小限制
"""
name = cache_key(context, key)
if type(ttl_seconds) is not int or not 1 <= ttl_seconds <= MAX_CACHE_TTL_SECONDS:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/job_dispatcher.py b/ruoyi-fastapi-backend/plugins/core/runtime/job_dispatcher.py
index 6e87ea531..af72b3278 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/job_dispatcher.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/job_dispatcher.py
@@ -21,14 +21,14 @@ class PluginJobBinding:
"""
当前进程中已准备好的插件任务能力。
- :param plugin: 任务所属的已发现插件
- :param host: 任务使用的宿主能力上下文
- :param gateway: 插件启用状态查询网关
- :param ready: 查询插件是否就绪的回调
- :param loop: 所属宿主事件循环
- :param tasks: 当前仍在执行的插件异步任务集合
- :param metrics: 可选的当前 worker 指标收集器
- :param closing: 是否已停止接收新任务并正在回收旧任务
+ :ivar plugin: 任务所属的已发现插件
+ :ivar host: 任务使用的宿主能力上下文
+ :ivar gateway: 插件启用状态查询网关
+ :ivar ready: 查询插件是否就绪的回调
+ :ivar loop: 所属宿主事件循环
+ :ivar tasks: 当前仍在执行的插件异步任务集合
+ :ivar metrics: 可选的当前 worker 指标收集器
+ :ivar closing: 是否已停止接收新任务并正在回收旧任务
"""
plugin: DiscoveredPlugin
@@ -44,7 +44,7 @@ def ensure_open(self) -> None:
"""
关闭后不再启动业务回调,也不把迟到结果报告为成功。
- :return: None
+ :raises asyncio.CancelledError: 绑定已进入关闭流程
"""
if self.closing:
raise asyncio.CancelledError
@@ -70,6 +70,8 @@ def bind_plugin_jobs(
:param ready: 查询插件是否就绪的回调
:param metrics: 可选的运行指标收集器
:return: 绑定到当前事件循环的插件任务能力
+ :raises RuntimeError: 旧任务尚未退出或运行时已绑定
+ :raises ValueError: 任务宿主身份不匹配或缺少数据库会话工厂
"""
plugin_id = plugin.manifest.id
existing = _bindings.get(plugin_id)
@@ -89,7 +91,6 @@ def _release_binding(binding: PluginJobBinding) -> None:
全部旧任务退出后才释放绑定,防止同进程启动重叠实例。
:param binding: 已进入关闭阶段的插件任务绑定
- :return: None
"""
plugin_id = binding.plugin.manifest.id
if binding.closing and not any(not task.done() for task in binding.tasks) and _bindings.get(plugin_id) is binding:
@@ -102,7 +103,6 @@ async def unbind_plugin_jobs(binding: PluginJobBinding, *, grace_seconds: float
:param binding: 待解除的插件任务绑定
:param grace_seconds: 整批运行任务的取消等待上限秒数
- :return: None
"""
if not binding.closing:
binding.closing = True
@@ -124,6 +124,11 @@ async def dispatch_plugin_job(plugin_id: str, job_id: str, version: str) -> Any:
:param job_id: 插件清单声明的任务 ID
:param version: 调度记录绑定的插件版本
:return: 插件异步任务回调的执行结果
+ :raises RuntimeError: 插件任务必须在所属宿主事件循环执行
+ :raises LookupError: 插件未声明指定的任务
+ :raises asyncio.CancelledError: 异步操作被取消时
+ :raises PermissionError: 当前执行上下文缺少调用所需的权限
+ :raises Exception: 底层操作失败时向调用方传播异常
"""
binding = _bindings.get(plugin_id)
if binding is None or binding.closing or not binding.ready():
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/metrics.py b/ruoyi-fastapi-backend/plugins/core/runtime/metrics.py
index 6b1634aed..e75a7f59d 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/metrics.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/metrics.py
@@ -23,34 +23,33 @@
class PluginMetricSeries(BaseModel):
- """
- 一个 worker 上某插件和操作的累计指标,不包含请求参数、路径或用户数据。
- """
+ """一个 worker 上某插件和操作的累计指标,不包含请求参数、路径或用户数据。"""
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra='forbid', strict=True)
- plugin_id: str = Field(pattern=r'^[a-z][a-z0-9_]{1,63}$')
- version: str = Field(max_length=128)
- digest: str | None = Field(default=None, pattern=r'^[0-9a-f]{64}$')
- generation: str | None = Field(default=None, pattern=r'^[0-9a-f]{32}$')
- operation: str = Field(pattern=r'^(http|websocket|job:[a-z][a-z0-9_-]{0,63})$')
- started: NonNegativeInt = 0
- active: NonNegativeInt = 0
- succeeded: NonNegativeInt = 0
- rejected: NonNegativeInt = 0
- failed: NonNegativeInt = 0
- cancelled: NonNegativeInt = 0
- timed_out: NonNegativeInt = 0
- duration_sum_ms: float = Field(default=0.0, ge=0, allow_inf_nan=False)
- duration_max_ms: float = Field(default=0.0, ge=0, allow_inf_nan=False)
+ plugin_id: str = Field(pattern=r'^[a-z][a-z0-9_]{1,63}$', description='插件标识')
+ version: str = Field(max_length=128, description='插件版本')
+ digest: str | None = Field(default=None, pattern=r'^[0-9a-f]{64}$', description='已加载制品的内容摘要')
+ generation: str | None = Field(default=None, pattern=r'^[0-9a-f]{32}$', description='当前插件发布代次')
+ operation: str = Field(pattern=r'^(http|websocket|job:[a-z][a-z0-9_-]{0,63})$', description='执行的操作类型')
+ started: NonNegativeInt = Field(default=0, description='已开始执行的操作总数')
+ active: NonNegativeInt = Field(default=0, description='正在执行的操作数')
+ succeeded: NonNegativeInt = Field(default=0, description='成功的操作数')
+ rejected: NonNegativeInt = Field(default=0, description='被拒绝的操作数')
+ failed: NonNegativeInt = Field(default=0, description='失败的操作数')
+ cancelled: NonNegativeInt = Field(default=0, description='被取消的操作数')
+ timed_out: NonNegativeInt = Field(default=0, description='超时的操作数')
+ duration_sum_ms: float = Field(default=0.0, ge=0, allow_inf_nan=False, description='操作耗时总和(毫秒)')
+ duration_max_ms: float = Field(default=0.0, ge=0, allow_inf_nan=False, description='最长单次操作耗时(毫秒)')
latency_buckets: list[NonNegativeInt] = Field(
default_factory=lambda: [0] * (len(LATENCY_BUCKETS_MS) + 1),
min_length=len(LATENCY_BUCKETS_MS) + 1,
max_length=len(LATENCY_BUCKETS_MS) + 1,
+ description='按延迟区间统计的操作次数',
)
- last_error_type: str | None = Field(default=None, max_length=80)
- last_error_request_id: str | None = Field(default=None, max_length=128)
- last_error_at: float | None = Field(default=None, ge=0, allow_inf_nan=False)
+ last_error_type: str | None = Field(default=None, max_length=80, description='最近一次错误的异常类型')
+ last_error_request_id: str | None = Field(default=None, max_length=128, description='最近一次错误的关联请求标识')
+ last_error_at: float | None = Field(default=None, ge=0, allow_inf_nan=False, description='最近一次错误的时间戳')
@model_validator(mode='after')
def validate_counters(self) -> 'PluginMetricSeries':
@@ -58,6 +57,7 @@ def validate_counters(self) -> 'PluginMetricSeries':
拒绝损坏或不一致的跨 worker 计数,避免将错误快照混入汇总。
:return: 校验通过的指标序列
+ :raises ValueError: 插件运行指标计数不一致;插件超时次数不能大于失败次数
"""
completed = self.succeeded + self.rejected + self.failed + self.cancelled
if self.started != self.active + completed or sum(self.latency_buckets) != completed:
@@ -91,18 +91,18 @@ def to_payload(self) -> dict[str, Any]:
class PluginMetricSnapshot(BaseModel):
- """
- 带采样时间和进程标识的有界指标快照。
- """
+ """带采样时间和进程标识的有界指标快照。"""
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra='forbid', strict=True)
- schema_version: Literal[1] = 1
- worker_id: str = Field(pattern=r'^[0-9a-f]{32}$')
- collected_at: float = Field(ge=0, allow_inf_nan=False)
- dropped_series: NonNegativeInt = 0
- series: list[PluginMetricSeries] = Field(max_length=MAX_METRIC_SERIES)
- configurations: list[PluginConfigObservation] = Field(default_factory=list, max_length=MAX_METRIC_SERIES)
+ schema_version: Literal[1] = Field(default=1, description='数据结构的版本')
+ worker_id: str = Field(pattern=r'^[0-9a-f]{32}$', description='工作进程标识')
+ collected_at: float = Field(ge=0, allow_inf_nan=False, description='采集快照的时间戳')
+ dropped_series: NonNegativeInt = Field(default=0, description='因容量限制而舍弃的指标序列数')
+ series: list[PluginMetricSeries] = Field(max_length=MAX_METRIC_SERIES, description='按插件和操作维度聚合的指标序列')
+ configurations: list[PluginConfigObservation] = Field(
+ default_factory=list, max_length=MAX_METRIC_SERIES, description='各插件的配置观测记录'
+ )
@dataclass
@@ -110,11 +110,11 @@ class PluginMetricInvocation:
"""
单次调用的计时记录,结束方法幂等,避免异常分支重复计数。
- :param series: 当前操作的可变指标序列
- :param request_id: 本次调用的追踪标识
- :param clock: 单调计时函数
- :param started_at: 本次调用的开始时间
- :param finished: 是否已记录结束结果
+ :ivar series: 当前操作的可变指标序列
+ :ivar request_id: 本次调用的追踪标识
+ :ivar clock: 单调计时函数
+ :ivar started_at: 本次调用的开始时间
+ :ivar finished: 是否已记录结束结果
"""
series: PluginMetricSeries
@@ -130,7 +130,6 @@ def finish(self, outcome: MetricOutcome, *, error_type: str | None = None, timed
:param outcome: 成功、客户端拒绝、失败或取消
:param error_type: 可选的错误类型名称
:param timed_out: 是否为超时失败
- :return: None
"""
if self.finished:
return
@@ -157,12 +156,12 @@ class PluginRuntimeMetrics:
"""
当前事件循环内的插件指标收集器,操作标签仅来自宿主和已声明任务。
- :param worker_id: 当前 worker 唯一标识
- :param clock: 单调计时函数
- :param identities: 插件加载版本、摘要和发布代际
- :param series: 按插件及操作索引的计数器
- :param dropped_series: 超出容量而未采集的调用数
- :param configurations: 当前进程的配置版本观测,不保存配置明文
+ :ivar worker_id: 当前 worker 唯一标识
+ :ivar clock: 单调计时函数
+ :ivar identities: 插件加载版本、摘要和发布代际
+ :ivar series: 按插件及操作索引的计数器
+ :ivar dropped_series: 超出容量而未采集的调用数
+ :ivar configurations: 当前进程的配置版本观测,不保存配置明文
"""
worker_id: str = field(default_factory=lambda: uuid4().hex)
@@ -180,7 +179,6 @@ def register(self, plugin_id: str, version: str, digest: str | None, generation:
:param version: 实际加载版本
:param digest: 签名制品摘要,源码插件为 None
:param generation: 实际加载的发布代际
- :return: None
"""
if plugin_id in self.identities:
return
@@ -266,6 +264,10 @@ def log_fields(self, plugin_id: str, operation: str) -> dict[str, Any]:
class PluginObservedASGI:
"""
统计完整 HTTP 请求与 WebSocket 生命周期,并为插件日志关联宿主追踪上下文。
+
+ :ivar app: 包含权限门禁的插件应用或路由
+ :ivar metrics: 当前 worker 的指标收集器
+ :ivar plugin_id: 当前插件 ID
"""
def __init__(self, app: ASGIApp, metrics: PluginRuntimeMetrics, plugin_id: str) -> None:
@@ -275,7 +277,6 @@ def __init__(self, app: ASGIApp, metrics: PluginRuntimeMetrics, plugin_id: str)
:param app: 包含权限门禁的插件应用或路由
:param metrics: 当前 worker 的指标收集器
:param plugin_id: 当前插件 ID
- :return: None
"""
self.app = app
self.metrics = metrics
@@ -288,7 +289,8 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
:param scope: 当前请求作用域
:param receive: 请求消息接收器
:param send: 响应消息发送器
- :return: None
+ :raises asyncio.CancelledError: 异步操作被取消时
+ :raises Exception: 底层操作失败时向调用方传播异常
"""
if scope['type'] not in {'http', 'websocket'}:
await self.app(scope, receive, send)
@@ -307,7 +309,6 @@ async def observed_send(message: Message) -> None:
观察状态码及 WebSocket 握手结果,不读取或复制响应体。
:param message: 应用输出的 ASGI 消息
- :return: None
"""
nonlocal status_code
if message['type'] == 'http.response.start':
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/metrics_store.py b/ruoyi-fastapi-backend/plugins/core/runtime/metrics_store.py
index d0152a108..6432e5e3a 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/metrics_store.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/metrics_store.py
@@ -18,6 +18,12 @@
class PluginMetricsReporter:
"""
将进程累计指标定期发布到 Redis;观测失败不影响插件业务或发布状态。
+
+ :ivar metrics: 当前 worker 的本地指标收集器
+ :ivar redis: 当前宿主 Redis 客户端
+ :ivar namespace: 当前环境的指标命名空间
+ :ivar task: 在后台执行当前工作的异步任务
+ :ivar publication_failed: 最近一次发布是否失败
"""
def __init__(self, metrics: PluginRuntimeMetrics) -> None:
@@ -25,7 +31,6 @@ def __init__(self, metrics: PluginRuntimeMetrics) -> None:
初始化尚未连接外部存储的指标报告器。
:param metrics: 当前 worker 的本地指标收集器
- :return: None
"""
self.metrics = metrics
self.redis: Any = None
@@ -48,7 +53,6 @@ def start(self, redis: Any, namespace: str) -> None:
:param redis: 当前宿主 Redis 客户端
:param namespace: 当前环境的指标命名空间
- :return: None
"""
if self.task is not None:
return
@@ -58,11 +62,7 @@ def start(self, redis: Any, namespace: str) -> None:
self.task = asyncio.create_task(self._run(), name=f'plugin-metrics-{self.metrics.worker_id}')
async def publish(self) -> None:
- """
- 发布有界快照并设置过期时间,避免异常退出的进程永久计入汇总。
-
- :return: None
- """
+ """发布有界快照并设置过期时间,避免异常退出的进程永久计入汇总。"""
if self.redis is None:
return
try:
@@ -80,21 +80,13 @@ async def publish(self) -> None:
self.publication_failed = False
async def _run(self) -> None:
- """
- 定期采样,不在请求路径同步写入 Redis。
-
- :return: None
- """
+ """定期采样,不在请求路径同步写入 Redis。"""
while True:
await asyncio.sleep(METRICS_PUBLISH_SECONDS)
await self.publish()
async def stop(self) -> None:
- """
- 取消采样任务并仅移除本 worker 的快照;清理失败时依赖 TTL。
-
- :return: None
- """
+ """取消采样任务并仅移除本 worker 的快照;清理失败时依赖 TTL。"""
if self.task is not None:
self.task.cancel()
with suppress(asyncio.CancelledError):
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/result.py b/ruoyi-fastapi-backend/plugins/core/runtime/result.py
index 7fed58831..38803dea1 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/result.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/result.py
@@ -9,6 +9,10 @@
class PluginOperationResult:
"""
插件操作结果视图。
+
+ :ivar payload: 插件运行时负载
+ :ivar ok: 操作或检查是否成功
+ :ivar message: 与当前结果一起返回的说明
"""
payload: Mapping[str, object]
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/route_guard.py b/ruoyi-fastapi-backend/plugins/core/runtime/route_guard.py
index 4e31fc7c5..6d8bfc729 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/route_guard.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/route_guard.py
@@ -9,9 +9,7 @@
@runtime_checkable
class PluginRouteStateGateway(Protocol):
- """
- 插件路由状态读取端口。
- """
+ """插件路由状态读取端口。"""
async def is_plugin_enabled(self, db: AsyncSession, plugin_id: str) -> bool:
"""
@@ -24,9 +22,7 @@ async def is_plugin_enabled(self, db: AsyncSession, plugin_id: str) -> bool:
class UnavailablePluginRouteStateGateway:
- """
- 不可用的插件路由状态读取端口。
- """
+ """不可用的插件路由状态读取端口。"""
@staticmethod
async def is_plugin_enabled(db: AsyncSession, plugin_id: str) -> bool:
@@ -44,6 +40,9 @@ async def is_plugin_enabled(db: AsyncSession, plugin_id: str) -> bool:
class CheckPluginEnabled:
"""
校验插件路由运行时启用状态。
+
+ :ivar plugin_id: 插件ID
+ :ivar state_gateway: 插件路由状态读取端口
"""
def __init__(self, plugin_id: str, state_gateway: PluginRouteStateGateway | None = None) -> None:
@@ -62,6 +61,7 @@ async def __call__(self, db: AsyncSession = DBSessionDependency()) -> bool:
:param db: orm对象
:return: 是否通过
+ :raises PermissionException: 插件未启用,接口不可访问
"""
if not await self.state_gateway.is_plugin_enabled(db, self.plugin_id):
raise PermissionException(data='', message='插件未启用,接口不可访问', msg_key='plugin.disabled')
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/audit.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/audit.py
index ef7bf2e26..8e26c3206 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/audit.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/audit.py
@@ -9,6 +9,8 @@
class PluginAuditUseCase:
"""
插件操作审计和失败状态记录 use case。
+
+ :ivar dependencies: 插件运行时依赖容器
"""
def __init__(self, dependencies: PluginRuntimeDependencies) -> None:
@@ -34,7 +36,6 @@ async def record_plugin_operation_log(
:param payload: 插件操作结果负载
:param dry_run: 是否预演
:param continue_on_error: 失败后是否继续执行后续插件
- :return: None
"""
await self.dependencies.audit_gateway.add_plugin_operation_log(
dict(payload),
@@ -54,7 +55,6 @@ async def record_plugin_failure_state(
:param payload: 插件操作返回负载
:param default_message: 缺省失败信息
- :return: None
"""
if payload.get('ok') is not False:
return
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/batch.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/batch.py
index bf928d0e9..eefe81c48 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/batch.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/batch.py
@@ -20,9 +20,7 @@
class PluginBatchRuntimeOperations(Protocol):
- """
- 批量工作流所需的运行时协作能力。
- """
+ """批量工作流所需的运行时协作能力。"""
async def install_plugin(
self,
@@ -87,7 +85,6 @@ async def record_plugin_operation_log(
:param payload: 插件操作结果负载
:param dry_run: 是否预演
:param continue_on_error: 失败后是否继续
- :return: None
"""
async def execute_batch_plugin_item(
@@ -107,6 +104,10 @@ async def execute_batch_plugin_item(
class PluginBatchUseCase:
"""
插件批量计划和批量执行 use case。
+
+ :ivar dependencies: 插件运行时依赖容器
+ :ivar runtime_operations: 批量工作流所需的运行时协作能力
+ :ivar context: 插件运行时上下文服务
"""
def __init__(
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/config.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/config.py
index e0a7a4cdb..68fc0f6db 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/config.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/config.py
@@ -17,6 +17,9 @@
class PluginConfigUseCase:
"""
插件配置 use case。
+
+ :ivar dependencies: 插件运行时依赖容器
+ :ivar context: 插件运行时上下文服务
"""
def __init__(self, dependencies: PluginRuntimeDependencies, context: PluginRuntimeContextService) -> None:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/context.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/context.py
index d81afe199..7bd5c70c9 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/context.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/context.py
@@ -43,6 +43,11 @@ class PluginRuntimeContextService:
集中提供插件发现、注册表构建、数据库状态读取和预检上下文构建能力,
让 runtime facade 和组合式 use case 只关注插件操作编排。
+
+ :ivar dependencies: 插件运行时依赖容器
+ :ivar _discovered_plugins_cache: 最近一次插件扫描结果
+ :ivar _discovery_errors_cache: 最近一次扫描收集的错误
+ :ivar _discovery_override: 替代默认扫描行为的发现结果
"""
def __init__(self, dependencies: PluginRuntimeDependencies) -> None:
@@ -61,7 +66,7 @@ def set_discovery_snapshot(self, plugins: list[DiscoveredPlugin]) -> None:
维护流程注入已验证目录,不修改全局扫描器或运行中进程的发现缓存。
:param plugins: 维护流程已验证的插件发现快照
- :return: None
+ :raises ValueError: 插件发现快照包含重复 ID
"""
ids = [plugin.manifest.id for plugin in plugins]
if len(ids) != len(set(ids)):
@@ -203,6 +208,7 @@ async def get_readonly_discovered_plugin(self, plugin_id: str) -> DiscoveredPlug
:param plugin_id: 待读取配置的插件 ID
:return: 已发现源码插件或重新验签的当前制品,未找到时返回 None
+ :raises ValueError: 无法确认插件来源,配置读取已中止;插件状态适配器未提供已选制品的只读解析能力
"""
if isinstance(self.dependencies.state_query_gateway, UnavailablePluginStateQueryGateway):
return self.get_discovered_plugin(plugin_id)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/dependencies.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/dependencies.py
index 696a50849..aff2cfae9 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/dependencies.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/dependencies.py
@@ -30,6 +30,9 @@
class PluginDependencyUseCase:
"""
插件 Python/npm 依赖检查和安装 use case。
+
+ :ivar dependencies: 插件运行时依赖容器
+ :ivar context: 插件运行时上下文服务
"""
def __init__(self, dependencies: PluginRuntimeDependencies, context: PluginRuntimeContextService) -> None:
@@ -240,6 +243,7 @@ def install_plugin_dependencies_from_result(
:param confirmed: 是否已显式确认
:param output_callback: 依赖安装实时输出回调
:return: 插件依赖安装负载
+ :raises Exception: 底层操作失败时向调用方传播异常
"""
discovered_plugin = discovered_plugin or self._get_discovered_plugin(plugin_id)
install_plan = PluginDependencyInstallPlanner(
@@ -346,6 +350,7 @@ async def install_plugin_dependencies_from_result_async(
:param confirmed: 是否已显式确认
:param output_callback: 依赖安装实时输出回调
:return: 插件依赖安装负载
+ :raises Exception: 底层操作失败时向调用方传播异常
"""
discovered_plugin = discovered_plugin or self._get_discovered_plugin(plugin_id)
install_plan = PluginDependencyInstallPlanner(
@@ -447,7 +452,6 @@ def _emit_install_status(
:param total: 安装项总数
:param requirement: 依赖声明
:param status: 当前状态
- :return: None
"""
if output_callback is not None:
output_callback('status', f'[{index}/{total}] {status}:{requirement}\n')
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/dependency_container.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/dependency_container.py
index cb9f2e7d9..7a77c8ec2 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/dependency_container.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/dependency_container.py
@@ -23,6 +23,15 @@ class PluginRuntimeGatewayOverrides:
插件运行时窄端口覆盖项。
该对象用于测试或特殊组合根显式覆盖某个窄端口,避免 facade 构造器随着端口拆分持续膨胀。
+
+ :ivar config_gateway: 读写插件配置的网关
+ :ivar audit_gateway: 写入插件操作审计记录的网关
+ :ivar state_query_gateway: 读取插件运行状态的网关
+ :ivar migration_history_gateway: migration 历史查询端口
+ :ivar purge_plan_gateway: 生成插件清理计划的网关
+ :ivar lifecycle_state_gateway: 管理插件生命周期状态的网关
+ :ivar lifecycle_uow_gateway: 创建生命周期事务工作单元的网关
+ :ivar migration_execution_gateway: 执行插件数据库迁移的网关
"""
config_gateway: PluginConfigGateway | None = None
@@ -39,6 +48,19 @@ class PluginRuntimeGatewayOverrides:
class PluginRuntimeDependencies:
"""
插件运行时基础依赖集合。
+
+ :ivar runtime_environment: 运行时环境服务
+ :ivar dependency_checker: 插件依赖检查器
+ :ivar config_gateway: 插件配置网关协议
+ :ivar audit_gateway: 插件审计网关协议
+ :ivar state_query_gateway: 插件状态查询网关协议
+ :ivar migration_history_gateway: migration 历史查询端口
+ :ivar purge_plan_gateway: 插件清理计划网关协议
+ :ivar lifecycle_state_gateway: 插件生命周期状态写入网关协议
+ :ivar lifecycle_uow_gateway: 插件生命周期主事务工作单元网关协议
+ :ivar migration_execution_gateway: 插件 migration 独立执行网关协议
+ :ivar model_gateway: 插件管理模型工厂网关
+ :ivar command_gateway: 插件命令执行网关
"""
runtime_environment: PluginRuntimeEnvironmentService
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/facade.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/facade.py
index 625883af5..f0504f39b 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/facade.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/facade.py
@@ -61,6 +61,22 @@ class PluginRuntimeService:
使用 Facade + 组合式 use case 管理插件查询、检查、生命周期、配置、测试和模板等核心能力。
数据库状态、管理模型和命令执行等外部依赖通过显式端口注入。
+
+ :ivar lifecycle_lock: 插件生命周期操作锁
+ :ivar dependencies: 新的插件运行时依赖容器
+ :ivar context: 当前操作所需的上下文
+ :ivar audit: 执行插件操作审计的服务
+ :ivar batch: 执行批量插件操作的服务
+ :ivar config: 当前对象使用的配置
+ :ivar dependency: 当前需要展开的依赖
+ :ivar enable: 是否启用目标功能
+ :ivar install: 安装插件资源的服务
+ :ivar migration: 插件的数据迁移配置
+ :ivar precheck: 执行操作前取得的检查结果
+ :ivar purge: 清理插件数据和资源的服务
+ :ivar query: 限制查询结果的条件
+ :ivar tools: 提供插件辅助操作的服务
+ :ivar upgrade: 管理插件升级的服务
"""
def __init__(
@@ -82,7 +98,6 @@ def __init__(
:param model_gateway: 插件管理模型工厂网关
:param command_gateway: 插件命令执行网关
:param lifecycle_lock: 插件生命周期操作锁
- :return: None
"""
resolved_environment = runtime_environment or PLUGIN_RUNTIME_ENVIRONMENT
resolved_dependency_checker = dependency_checker or PluginDependencyChecker(
@@ -122,7 +137,6 @@ def _replace_dependencies(self, dependencies: PluginRuntimeDependencies) -> None
替换插件运行时依赖容器并刷新组合 use case。
:param dependencies: 新的插件运行时依赖容器
- :return: None
"""
self.dependencies = dependencies
self.context = PluginRuntimeContextService(dependencies)
@@ -144,16 +158,11 @@ def set_dependency_checker(self, dependency_checker: PluginDependencyChecker) ->
替换插件依赖检查器。
:param dependency_checker: 新的依赖检查器
- :return: None
"""
self.dependencies.dependency_checker = dependency_checker
def refresh_dependency_checker(self) -> None:
- """
- 刷新插件 Python/npm 依赖检查器。
-
- :return: None
- """
+ """刷新插件 Python/npm 依赖检查器。"""
self.set_dependency_checker(
PluginDependencyChecker(
npm_inspector=NpmDependencyInspector(
@@ -465,6 +474,11 @@ def _execute_plugin_dependency_install(
"""
def install_dependencies() -> PluginDependencyInstallResponse:
+ """
+ 执行运行时插件依赖安装。
+
+ :return: 依赖安装器返回的执行结果
+ """
if output_callback is None:
return installer(plugin_id, dry_run=dry_run, policy_config=policy_config, confirmed=confirmed)
return installer(
@@ -476,6 +490,11 @@ def install_dependencies() -> PluginDependencyInstallResponse:
)
async def execute_with_source_check() -> PluginDependencyInstallResponse:
+ """
+ 校验插件来源后执行依赖安装操作。
+
+ :return: 来源检查的拒绝信息或依赖安装结果
+ """
# 来源查询与审计共用同一个循环,避免异步连接池复用已关闭loop的连接。
blocked = await self.context.guard_artifact_operation(
plugin_id, 'dependency_install', check_capability=False
@@ -574,7 +593,6 @@ async def record_plugin_operation_log(
:param payload: 插件操作结果负载
:param dry_run: 是否预演
:param continue_on_error: 失败后是否继续
- :return: None
"""
await self.audit.record_plugin_operation_log(
cast('dict[str, object]', payload),
@@ -588,7 +606,6 @@ async def record_plugin_failure_state(self, payload: Mapping[str, object], defau
:param payload: 插件操作返回负载
:param default_message: 缺省失败信息
- :return: None
"""
await self.audit.record_plugin_failure_state(cast('dict[str, object]', payload), default_message)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/gateway.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/gateway.py
index 798449271..15736e972 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/gateway.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/gateway.py
@@ -42,6 +42,7 @@ def run_plugin_command(
:param timeout: 命令超时时间
:param output_callback: 实时输出回调
:return: 命令执行结果
+ :raises subprocess.TimeoutExpired: 插件系统命令超过指定运行时限
"""
if output_callback is None:
return subprocess.run(
@@ -70,7 +71,13 @@ def consume_stream(
kind: Literal['stdout', 'stderr'],
output_parts: list[str],
) -> None:
- """持续读取并转发单个子进程输出流。"""
+ """
+ 持续读取并转发单个子进程输出流。
+
+ :param stream: 需要逐块读取的流
+ :param kind: 当前条目的类别
+ :param output_parts: 按接收顺序保存输出片段的列表
+ """
try:
for text in iter(stream.readline, ''):
output_parts.append(text)
@@ -118,9 +125,7 @@ def consume_stream(
@runtime_checkable
class AsyncSessionFactoryProtocol(Protocol):
- """
- 异步数据库会话工厂协议。
- """
+ """异步数据库会话工厂协议。"""
def __call__(self) -> AbstractAsyncContextManager[AsyncSession]:
"""
@@ -132,9 +137,7 @@ def __call__(self) -> AbstractAsyncContextManager[AsyncSession]:
@runtime_checkable
class PluginManagementServiceProtocol(Protocol):
- """
- 插件运行时依赖的管理服务协议。
- """
+ """插件运行时依赖的管理服务协议。"""
@classmethod
async def get_plugin_list_services(cls, query_db: AsyncSession) -> list[PluginStateRecord]:
@@ -229,7 +232,6 @@ async def install_plugin_menu_services(
:param query_db: orm对象
:param discovered_plugin: 已发现插件对象
:param enabled: 是否启用
- :return: None
"""
@classmethod
@@ -260,7 +262,6 @@ async def install_plugin_job_services(
:param query_db: orm对象
:param discovered_plugin: 已发现插件
:param enabled: 插件任务是否启用
- :return: None
"""
@classmethod
@@ -491,9 +492,7 @@ async def mark_plugin_migration_status_services(
@runtime_checkable
class PluginConfigGateway(Protocol):
- """
- 插件配置网关协议。
- """
+ """插件配置网关协议。"""
async def get_plugin_config(
self,
@@ -543,9 +542,7 @@ async def set_plugin_config(
@runtime_checkable
class PluginAuditGateway(Protocol):
- """
- 插件审计网关协议。
- """
+ """插件审计网关协议。"""
async def list_plugin_operation_logs(self, *, export_limit: int) -> list[PluginOperationLogDetailModel]:
"""
@@ -568,7 +565,6 @@ async def add_plugin_operation_log(
:param payload: 操作日志负载
:param dry_run: 是否预演
:param continue_on_error: 失败后是否继续
- :return: None
"""
async def mark_plugin_error(self, plugin_id: str, error_message: str) -> bool:
@@ -583,9 +579,7 @@ async def mark_plugin_error(self, plugin_id: str, error_message: str) -> bool:
@runtime_checkable
class PluginStateQueryGateway(Protocol):
- """
- 插件状态查询网关协议。
- """
+ """插件状态查询网关协议。"""
async def list_plugin_states(self) -> list[PluginStateRecord]:
"""
@@ -605,9 +599,7 @@ async def get_plugin_state(self, plugin_id: str) -> PluginStateRecord | None:
@runtime_checkable
class PluginMigrationHistoryGateway(Protocol):
- """
- 插件 migration 历史网关协议。
- """
+ """插件 migration 历史网关协议。"""
async def list_plugin_migrations(
self,
@@ -651,9 +643,7 @@ async def mark_plugin_migration_status(
@runtime_checkable
class PluginPurgePlanGateway(Protocol):
- """
- 插件清理计划网关协议。
- """
+ """插件清理计划网关协议。"""
async def build_plugin_purge_plan(self, discovered_plugin: DiscoveredPlugin) -> PluginPurgePlan:
"""
@@ -666,9 +656,7 @@ async def build_plugin_purge_plan(self, discovered_plugin: DiscoveredPlugin) ->
@runtime_checkable
class PluginLifecycleStateGateway(Protocol):
- """
- 插件生命周期状态写入网关协议。
- """
+ """插件生命周期状态写入网关协议。"""
async def set_plugin_enabled_state(
self,
@@ -698,6 +686,8 @@ async def mark_plugin_uninstalled_state(self, plugin_id: str) -> CrudResponseMod
class PluginLifecycleUnitOfWork(Protocol):
"""
插件生命周期主事务工作单元协议。
+
+ :ivar session: 当前操作共用的会话
"""
session: AsyncSession
@@ -731,7 +721,6 @@ async def install_plugin_menu(self, discovered_plugin: DiscoveredPlugin, *, enab
:param discovered_plugin: 已发现插件
:param enabled: 是否启用菜单
- :return: None
"""
async def install_plugin_default_config(self, discovered_plugin: DiscoveredPlugin) -> list[PluginConfigModel]:
@@ -748,7 +737,6 @@ async def install_plugin_jobs(self, discovered_plugin: DiscoveredPlugin, *, enab
:param discovered_plugin: 已发现插件
:param enabled: 插件任务是否启用
- :return: None
"""
async def mark_plugin_installed(self, discovered_plugin: DiscoveredPlugin) -> PluginModel:
@@ -792,18 +780,12 @@ async def purge_plugin_metadata_by_id(self, plugin_id: str) -> PluginPurgePlan:
"""
async def commit(self) -> None:
- """
- 提交生命周期主事务。
-
- :return: None
- """
+ """提交生命周期主事务。"""
@runtime_checkable
class PluginLifecycleUnitOfWorkGateway(Protocol):
- """
- 插件生命周期主事务工作单元网关协议。
- """
+ """插件生命周期主事务工作单元网关协议。"""
def open_lifecycle_unit_of_work(self) -> AbstractAsyncContextManager[PluginLifecycleUnitOfWork]:
"""
@@ -815,9 +797,7 @@ def open_lifecycle_unit_of_work(self) -> AbstractAsyncContextManager[PluginLifec
@runtime_checkable
class PluginMigrationExecutionGateway(Protocol):
- """
- 插件 migration 独立执行网关协议。
- """
+ """插件 migration 独立执行网关协议。"""
async def run_plugin_migrations(self, discovered_plugin: DiscoveredPlugin) -> list[PluginMigrationResult]:
"""
@@ -830,9 +810,7 @@ async def run_plugin_migrations(self, discovered_plugin: DiscoveredPlugin) -> li
@runtime_checkable
class PluginManagementModelGateway(Protocol):
- """
- 插件管理模型工厂网关协议。
- """
+ """插件管理模型工厂网关协议。"""
def build_operation_log_export_query(self, export_limit: int) -> PluginOperationLogExportQueryModel:
"""
@@ -863,6 +841,8 @@ def build_migration_record(
"""
构建插件 migration 执行历史对象。
+ :param status: 执行状态
+ :param error_message: 记录到结果或审计日志中的错误详情
:param plugin_id: 插件ID
:param migration_path: migration 相对路径
:param checksum: 内容校验值
@@ -874,9 +854,7 @@ def build_migration_record(
@runtime_checkable
class PluginCommandRunnerGateway(Protocol):
- """
- 插件命令执行网关协议。
- """
+ """插件命令执行网关协议。"""
def run_command(
self,
@@ -898,9 +876,7 @@ def run_command(
class UnavailablePluginStateQueryGateway:
- """
- 不可用的插件状态查询网关。
- """
+ """不可用的插件状态查询网关。"""
@staticmethod
async def list_plugin_states() -> list[PluginStateRecord]:
@@ -925,9 +901,7 @@ async def get_plugin_state(plugin_id: str) -> PluginStateRecord | None:
class UnavailablePluginMigrationHistoryGateway:
- """
- 不可用的插件 migration 历史网关。
- """
+ """不可用的插件 migration 历史网关。"""
@staticmethod
async def list_plugin_migrations(
@@ -977,9 +951,7 @@ async def mark_plugin_migration_status(
class UnavailablePluginPurgePlanGateway:
- """
- 不可用的插件清理计划网关。
- """
+ """不可用的插件清理计划网关。"""
@staticmethod
async def build_plugin_purge_plan(discovered_plugin: DiscoveredPlugin) -> PluginPurgePlan:
@@ -994,9 +966,7 @@ async def build_plugin_purge_plan(discovered_plugin: DiscoveredPlugin) -> Plugin
class UnavailablePluginLifecycleStateGateway:
- """
- 不可用的插件生命周期状态写入网关。
- """
+ """不可用的插件生命周期状态写入网关。"""
@staticmethod
async def set_plugin_enabled_state(
@@ -1028,9 +998,7 @@ async def mark_plugin_uninstalled_state(plugin_id: str) -> CrudResponseModel:
class UnavailablePluginLifecycleUnitOfWorkGateway:
- """
- 不可用的插件生命周期主事务工作单元网关。
- """
+ """不可用的插件生命周期主事务工作单元网关。"""
@staticmethod
def open_lifecycle_unit_of_work() -> AbstractAsyncContextManager[PluginLifecycleUnitOfWork]:
@@ -1044,9 +1012,7 @@ def open_lifecycle_unit_of_work() -> AbstractAsyncContextManager[PluginLifecycle
class UnavailablePluginMigrationExecutionGateway:
- """
- 不可用的插件 migration 独立执行网关。
- """
+ """不可用的插件 migration 独立执行网关。"""
@staticmethod
async def run_plugin_migrations(discovered_plugin: DiscoveredPlugin) -> list[PluginMigrationResult]:
@@ -1061,9 +1027,7 @@ async def run_plugin_migrations(discovered_plugin: DiscoveredPlugin) -> list[Plu
class UnavailablePluginConfigGateway:
- """
- 不可用的插件配置网关。
- """
+ """不可用的插件配置网关。"""
@staticmethod
async def get_plugin_config(
@@ -1118,9 +1082,7 @@ async def set_plugin_config(
class UnavailablePluginAuditGateway:
- """
- 不可用的插件审计网关。
- """
+ """不可用的插件审计网关。"""
@staticmethod
async def list_plugin_operation_logs(*, export_limit: int) -> list[PluginOperationLogDetailModel]:
@@ -1164,9 +1126,7 @@ async def mark_plugin_error(plugin_id: str, error_message: str) -> bool:
class UnavailablePluginManagementModelGateway:
- """
- 不可用的插件管理模型工厂网关。
- """
+ """不可用的插件管理模型工厂网关。"""
@staticmethod
def build_operation_log_export_query(export_limit: int) -> PluginOperationLogExportQueryModel:
@@ -1203,6 +1163,8 @@ def build_migration_record(
"""
构建插件 migration 执行历史对象。
+ :param status: 执行状态
+ :param error_message: 记录到结果或审计日志中的错误详情
:param plugin_id: 插件ID
:param migration_path: migration 相对路径
:param checksum: 内容校验值
@@ -1215,9 +1177,7 @@ def build_migration_record(
class DefaultPluginCommandRunnerGateway:
- """
- 默认插件命令执行网关。
- """
+ """默认插件命令执行网关。"""
@staticmethod
def run_command(
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/common.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/common.py
index c56be55b2..1123e2cc8 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/common.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/common.py
@@ -11,6 +11,9 @@
class PluginLifecycleSessionContext(Protocol):
"""
带数据库会话的生命周期上下文。
+
+ :ivar session_context: 当前会话的上下文
+ :ivar session: 当前操作共用的会话
"""
session_context: Any | None
@@ -20,6 +23,8 @@ class PluginLifecycleSessionContext(Protocol):
class PluginLifecycleUseCaseSupport:
"""
生命周期 use case 公共协作能力。
+
+ :ivar context: 生命周期上下文
"""
context: PluginRuntimeContextService
@@ -111,7 +116,6 @@ async def _close_lifecycle_session(self, context: object) -> None:
关闭生命周期上下文中的数据库会话。
:param context: 生命周期上下文
- :return: None
"""
lifecycle_context = cast('PluginLifecycleSessionContext', context)
session_context = lifecycle_context.session_context
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/enable.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/enable.py
index f76942d68..942479edc 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/enable.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/enable.py
@@ -27,6 +27,22 @@
class PluginEnabledLifecycleContext:
"""
插件启停声明式生命周期上下文。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar enabled: 是否启用
+ :ivar dry_run: 是否只预览操作结果
+ :ivar operation: 当前处理的操作
+ :ivar backend_root: 后端项目的根目录
+ :ivar discovered_plugins: 已发现插件列表
+ :ivar discovered_plugin: 扫描插件目录后得到的插件描述
+ :ivar precheck: 执行操作前取得的检查结果
+ :ivar actions: 即将执行或已记录的操作步骤
+ :ivar dependency_payload: 插件依赖检查负载
+ :ivar response: 当前调用产生的响应
+ :ivar session: 当前操作共用的会话
+ :ivar plugin_service: 执行插件业务操作的服务
+ :ivar session_context: 当前会话的上下文
+ :ivar catalog_snapshot: 操作开始时捕获的插件目录快照
"""
plugin_id: str
@@ -50,6 +66,19 @@ class PluginEnabledLifecycleContext:
class PluginUninstallLifecycleContext:
"""
插件卸载声明式生命周期上下文。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar dry_run: 是否只预览操作结果
+ :ivar backend_root: 后端项目的根目录
+ :ivar discovered_plugins: 已发现插件列表
+ :ivar discovered_plugin: 扫描插件目录后得到的插件描述
+ :ivar precheck: 执行操作前取得的检查结果
+ :ivar actions: 即将执行或已记录的操作步骤
+ :ivar dependency_payload: 插件依赖检查负载
+ :ivar response: 当前调用产生的响应
+ :ivar session: 当前操作共用的会话
+ :ivar plugin_service: 执行插件业务操作的服务
+ :ivar session_context: 当前会话的上下文
"""
plugin_id: str
@@ -69,6 +98,10 @@ class PluginUninstallLifecycleContext:
class PluginEnableUseCase(PluginLifecycleUseCaseSupport):
"""
插件启停和安全卸载 use case。
+
+ :ivar dependencies: 插件运行时依赖容器
+ :ivar runtime_operations: 生命周期工作流所需的运行时协作能力
+ :ivar context: 插件运行时上下文服务
"""
def __init__(
@@ -428,7 +461,6 @@ async def _close_enabled_session(self, context: PluginEnabledLifecycleContext) -
关闭插件启停数据库会话。
:param context: 插件启停上下文
- :return: None
"""
await self._close_lifecycle_session(context)
@@ -657,6 +689,5 @@ async def _close_uninstall_session(self, context: PluginUninstallLifecycleContex
关闭插件卸载数据库会话。
:param context: 插件卸载上下文
- :return: None
"""
await self._close_lifecycle_session(context)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/install.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/install.py
index ec88c6f7a..a72af4925 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/install.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/install.py
@@ -29,6 +29,24 @@
class PluginInstallLifecycleContext:
"""
插件安装声明式生命周期上下文。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar dry_run: 是否只预览操作结果
+ :ivar backend_root: 后端项目的根目录
+ :ivar discovered_plugins: 已发现插件列表
+ :ivar discovered_plugin: 扫描插件目录后得到的插件描述
+ :ivar precheck: 插件预检上下文
+ :ivar actions: 即将执行或已记录的操作步骤
+ :ivar dependency_install_view: 当前依赖安装计划的视图
+ :ivar plugin: 当前处理的插件
+ :ivar installed_configs: 已安装配置列表
+ :ivar migration_results: migration 执行结果列表
+ :ivar seed_results: seed 执行结果列表
+ :ivar hook_result: 清理钩子执行结果
+ :ivar session: 当前操作共用的会话
+ :ivar lifecycle_uow: 当前生命周期操作共享的事务工作单元
+ :ivar session_context: 当前会话的上下文
+ :ivar catalog_snapshot: 操作开始时捕获的插件目录快照
"""
plugin_id: str
@@ -53,6 +71,10 @@ class PluginInstallLifecycleContext:
class PluginInstallUseCase(PluginLifecycleUseCaseSupport):
"""
插件安装 use case。
+
+ :ivar dependencies: 插件运行时依赖容器
+ :ivar runtime_operations: 生命周期工作流所需的运行时协作能力
+ :ivar context: 插件运行时上下文服务
"""
def __init__(
@@ -297,7 +319,6 @@ async def _install_step_open_session(
打开安装数据库会话。
:param context: 插件安装上下文
- :return: None
"""
context.session_context = self.dependencies.lifecycle_uow_gateway.open_lifecycle_unit_of_work()
context.lifecycle_uow = await context.session_context.__aenter__()
@@ -339,7 +360,6 @@ async def _install_step_upsert_plugin(
写入插件基础状态。
:param context: 插件安装上下文
- :return: None
"""
context.plugin = await context.lifecycle_uow.upsert_discovered_plugin(
context.discovered_plugin,
@@ -357,7 +377,6 @@ async def _install_step_install_menus(
安装插件菜单。
:param context: 插件安装上下文
- :return: None
"""
plugin_enabled = getattr(context.plugin, 'enabled', '0') == '0'
await context.lifecycle_uow.install_plugin_menu(
@@ -375,7 +394,6 @@ async def _install_step_install_configs(
安装插件默认配置。
:param context: 插件安装上下文
- :return: None
"""
context.installed_configs = await context.lifecycle_uow.install_plugin_default_config(
context.discovered_plugin,
@@ -391,7 +409,6 @@ async def _install_step_install_jobs(
同步插件定时任务。
:param context: 插件安装上下文
- :return: None
"""
plugin_enabled = getattr(context.plugin, 'enabled', '0') == '0'
await context.lifecycle_uow.install_plugin_jobs(
@@ -409,7 +426,6 @@ async def _install_step_run_migrations(
执行插件 migration。
:param context: 插件安装上下文
- :return: None
"""
context.migration_results = await self.dependencies.migration_execution_gateway.run_plugin_migrations(
context.discovered_plugin,
@@ -425,7 +441,6 @@ async def _install_step_run_seeds(
执行插件 seed。
:param context: 插件安装上下文
- :return: None
"""
context.seed_results = await PluginSeedRunner(context.discovered_plugin).run(context.session)
@@ -439,7 +454,6 @@ async def _install_step_run_install_hook(
执行插件安装钩子。
:param context: 插件安装上下文
- :return: None
"""
context.hook_result = await PluginHookRunner(context.discovered_plugin).run(
'on_install',
@@ -456,7 +470,6 @@ async def _install_step_mark_installed(
标记插件已安装。
:param context: 插件安装上下文
- :return: None
"""
context.plugin = await context.lifecycle_uow.mark_plugin_installed(
context.discovered_plugin,
@@ -472,7 +485,6 @@ async def _install_step_commit(
提交安装事务。
:param context: 插件安装上下文
- :return: None
"""
await context.lifecycle_uow.commit()
CatalogRegistry.commit_plugin(
@@ -489,7 +501,6 @@ async def _install_step_close_session(
关闭安装数据库会话。
:param context: 插件安装上下文
- :return: None
"""
if context.session_context is not None:
await self._close_install_session(context)
@@ -501,7 +512,6 @@ async def _close_install_session(self, context: PluginInstallLifecycleContext) -
关闭安装数据库会话。
:param context: 插件安装上下文
- :return: None
"""
await self._close_lifecycle_session(context)
@@ -531,7 +541,6 @@ def _refresh_install_actions(
:param precheck: 插件预检上下文
:param context: 插件安装上下文
- :return: None
"""
context.precheck = precheck
context.actions = PluginPayloadBuilder.build_install_actions(
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/operations.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/operations.py
index 2318a561d..ae6c2c69a 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/operations.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/operations.py
@@ -9,6 +9,9 @@
class PluginLifecycleRuntimeOperations(Protocol):
"""
生命周期工作流所需的运行时协作能力。
+
+ :ivar dependencies: 插件运行时基础依赖集合
+ :ivar context: 插件应用运行时上下文服务
"""
dependencies: PluginRuntimeDependencies
@@ -27,7 +30,6 @@ async def record_plugin_operation_log(
:param payload: 插件操作结果负载
:param dry_run: 是否预演
:param continue_on_error: 失败后是否继续
- :return: None
"""
async def record_plugin_failure_state(self, payload: Mapping[str, object], default_message: str) -> None:
@@ -36,7 +38,6 @@ async def record_plugin_failure_state(self, payload: Mapping[str, object], defau
:param payload: 插件操作返回负载
:param default_message: 缺省失败信息
- :return: None
"""
def install_plugin_dependencies_from_result(
@@ -76,8 +77,4 @@ async def install_plugin_dependencies_from_result_async(
"""
def refresh_dependency_checker(self) -> None:
- """
- 刷新插件 Python/npm 依赖检查器。
-
- :return: None
- """
+ """刷新插件 Python/npm 依赖检查器。"""
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/purge.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/purge.py
index 9a0e29b14..fb7286c73 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/purge.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/purge.py
@@ -28,6 +28,20 @@
class PluginPurgeLifecycleContext:
"""
插件物理清理声明式生命周期上下文。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar dry_run: 是否只预览操作结果
+ :ivar backend_root: 后端项目的根目录
+ :ivar discovered_plugins: 已发现插件列表
+ :ivar discovered_plugin: 扫描插件目录后得到的插件描述
+ :ivar precheck: 执行操作前取得的检查结果
+ :ivar dependency_payload: 插件依赖检查负载
+ :ivar actions: 即将执行或已记录的操作步骤
+ :ivar plan: 清理插件时采用的执行计划
+ :ivar hook_result: 清理钩子执行结果
+ :ivar session: 当前操作共用的会话
+ :ivar lifecycle_uow: 当前生命周期操作共享的事务工作单元
+ :ivar session_context: 当前会话的上下文
"""
plugin_id: str
@@ -48,6 +62,10 @@ class PluginPurgeLifecycleContext:
class PluginPurgeUseCase(PluginLifecycleUseCaseSupport):
"""
插件物理清理 use case。
+
+ :ivar dependencies: 插件运行时依赖容器
+ :ivar runtime_operations: 生命周期工作流所需的运行时协作能力
+ :ivar context: 插件运行时上下文服务
"""
def __init__(
@@ -273,7 +291,6 @@ async def _purge_step_discover_plugins(
发现本地插件列表。
:param context: 插件物理清理上下文
- :return: None
"""
context.backend_root = context.discovered_plugin.backend_path.parent.parent
context.discovered_plugins = self._discover_plugins(context.backend_root)
@@ -288,7 +305,6 @@ async def _purge_step_build_precheck(
构建物理清理预检。
:param context: 插件物理清理上下文
- :return: None
"""
context.precheck = await self._build_precheck_context(
cast('Path', context.backend_root),
@@ -311,7 +327,6 @@ async def _purge_step_check_enabled_dependents(
检查物理清理目标的已启用依赖方。
:param context: 插件物理清理上下文
- :return: None
"""
context.dependency_payload = await self._build_enabled_dependents_payload(
context.plugin_id,
@@ -328,7 +343,6 @@ async def _purge_step_build_purge_plan(
构建物理清理计划。
:param context: 插件物理清理上下文
- :return: None
"""
context.session_context = self.dependencies.lifecycle_uow_gateway.open_lifecycle_unit_of_work()
context.lifecycle_uow = await context.session_context.__aenter__()
@@ -389,7 +403,6 @@ async def _purge_step_run_purge_hook(
执行物理清理钩子。
:param context: 插件物理清理上下文
- :return: None
"""
context.hook_result = await PluginHookRunner(context.discovered_plugin).run(
'on_purge',
@@ -406,7 +419,6 @@ async def _purge_step_purge_metadata(
清理插件平台元数据。
:param context: 插件物理清理上下文
- :return: None
"""
await context.lifecycle_uow.purge_plugin_metadata(context.discovered_plugin)
@@ -420,7 +432,6 @@ async def _purge_step_commit(
提交物理清理事务。
:param context: 插件物理清理上下文
- :return: None
"""
await context.lifecycle_uow.commit()
await self._close_purge_session(context)
@@ -432,6 +443,5 @@ async def _close_purge_session(self, context: PluginPurgeLifecycleContext) -> No
关闭物理清理数据库会话。
:param context: 插件物理清理上下文
- :return: None
"""
await self._close_lifecycle_session(context)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/runner.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/runner.py
index a04d4689e..f989360ff 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/runner.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/runner.py
@@ -11,6 +11,9 @@
class PluginLifecycleStepFailed(Exception):
"""
插件生命周期步骤执行失败。
+
+ :ivar step_name: 失败步骤名称
+ :ivar original_error: 原始异常
"""
def __init__(self, step_name: str, original_error: Exception) -> None:
@@ -29,6 +32,9 @@ def __init__(self, step_name: str, original_error: Exception) -> None:
class PluginLifecycleStepStop:
"""
插件生命周期步骤中止结果。
+
+ :ivar step_name: 失败步骤名称
+ :ivar payload: 随调用传入或返回的结构化数据
"""
step_name: str
@@ -39,6 +45,9 @@ class PluginLifecycleStepStop:
class PluginLifecycleStep(Generic[TContext]):
"""
插件生命周期声明式步骤。
+
+ :ivar name: 用于查找或标识当前对象的名称
+ :ivar handler: 执行该生命周期步骤的回调
"""
name: str
@@ -49,6 +58,9 @@ class PluginLifecycleStep(Generic[TContext]):
class PluginLifecycleStepRunResult(Generic[TContext]):
"""
插件生命周期步骤运行结果。
+
+ :ivar context: 生命周期上下文
+ :ivar stop: 通知正在运行的任务停止的信号
"""
context: TContext
@@ -58,6 +70,8 @@ class PluginLifecycleStepRunResult(Generic[TContext]):
class PluginLifecycleStepRunner(Generic[TContext]):
"""
插件生命周期声明式步骤运行器。
+
+ :ivar steps: 生命周期步骤列表
"""
def __init__(self, steps: list[PluginLifecycleStep[TContext]]) -> None:
@@ -74,6 +88,7 @@ async def run(self, context: TContext) -> PluginLifecycleStepRunResult[TContext]
:param context: 生命周期上下文
:return: 生命周期运行结果
+ :raises PluginLifecycleStepFailed: 当前生命周期步骤执行失败
"""
for step in self.steps:
try:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/upgrade.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/upgrade.py
index c0ad73d4d..66fb803b7 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/upgrade.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/upgrade.py
@@ -30,6 +30,26 @@
class PluginUpgradeLifecycleContext:
"""
插件升级声明式生命周期上下文。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar dry_run: 是否只预览操作结果
+ :ivar backend_root: 后端项目的根目录
+ :ivar discovered_plugins: 已发现插件列表
+ :ivar discovered_plugin: 扫描插件目录后得到的插件描述
+ :ivar precheck: 插件预检上下文
+ :ivar actions: 即将执行或已记录的操作步骤
+ :ivar database_plugin: 数据库插件状态
+ :ivar database_error: 执行数据库操作时捕获的异常
+ :ivar version_state: 插件升级版本状态
+ :ivar plugin: 当前处理的插件
+ :ivar installed_configs: 已安装配置列表
+ :ivar migration_results: migration 执行结果列表
+ :ivar seed_results: seed 执行结果列表
+ :ivar hook_result: 清理钩子执行结果
+ :ivar session: 当前操作共用的会话
+ :ivar lifecycle_uow: 当前生命周期操作共享的事务工作单元
+ :ivar session_context: 当前会话的上下文
+ :ivar catalog_snapshot: 操作开始时捕获的插件目录快照
"""
plugin_id: str
@@ -56,6 +76,10 @@ class PluginUpgradeLifecycleContext:
class PluginUpgradeUseCase(PluginLifecycleUseCaseSupport):
"""
插件升级 use case。
+
+ :ivar dependencies: 插件运行时依赖容器
+ :ivar runtime_operations: 生命周期工作流所需的运行时协作能力
+ :ivar context: 插件运行时上下文服务
"""
def __init__(
@@ -255,7 +279,6 @@ async def _upgrade_step_load_installed_plugin(
读取已安装插件状态。
:param context: 插件升级上下文
- :return: None
"""
context.database_plugin = await self.dependencies.state_query_gateway.get_plugin_state(context.plugin_id)
context.version_state = PluginPayloadBuilder.build_upgrade_version_state(
@@ -273,7 +296,6 @@ async def _upgrade_step_open_session(
打开升级生命周期主事务工作单元。
:param context: 插件升级上下文
- :return: None
"""
context.session_context = self.dependencies.lifecycle_uow_gateway.open_lifecycle_unit_of_work()
context.lifecycle_uow = await context.session_context.__aenter__()
@@ -351,7 +373,6 @@ async def _upgrade_step_upsert_plugin(
更新插件基础状态。
:param context: 插件升级上下文
- :return: None
"""
await context.lifecycle_uow.upsert_discovered_plugin(
context.discovered_plugin,
@@ -369,7 +390,6 @@ async def _upgrade_step_install_menus(
安装已启用插件菜单。
:param context: 插件升级上下文
- :return: None
"""
plugin_enabled = getattr(context.database_plugin, 'enabled', '1') == '0'
await context.lifecycle_uow.install_plugin_menu(
@@ -387,7 +407,6 @@ async def _upgrade_step_install_configs(
安装新增默认配置。
:param context: 插件升级上下文
- :return: None
"""
context.installed_configs = await context.lifecycle_uow.install_plugin_default_config(
context.discovered_plugin,
@@ -403,7 +422,6 @@ async def _upgrade_step_install_jobs(
同步升级后插件定时任务。
:param context: 插件升级上下文
- :return: None
"""
plugin_enabled = getattr(context.database_plugin, 'enabled', '1') == '0'
await context.lifecycle_uow.install_plugin_jobs(
@@ -421,7 +439,6 @@ async def _upgrade_step_run_migrations(
执行升级 migration。
:param context: 插件升级上下文
- :return: None
"""
context.migration_results = await self.dependencies.migration_execution_gateway.run_plugin_migrations(
context.discovered_plugin,
@@ -437,7 +454,6 @@ async def _upgrade_step_run_seeds(
执行升级 seed。
:param context: 插件升级上下文
- :return: None
"""
context.seed_results = await PluginSeedRunner(context.discovered_plugin).run(context.session)
@@ -451,7 +467,6 @@ async def _upgrade_step_run_upgrade_hook(
执行升级钩子。
:param context: 插件升级上下文
- :return: None
"""
context.hook_result = await PluginHookRunner(context.discovered_plugin).run(
'on_upgrade',
@@ -468,7 +483,6 @@ async def _upgrade_step_mark_installed(
标记插件已安装。
:param context: 插件升级上下文
- :return: None
"""
context.plugin = await context.lifecycle_uow.mark_plugin_installed(
context.discovered_plugin,
@@ -484,7 +498,6 @@ async def _upgrade_step_commit(
提交升级事务。
:param context: 插件升级上下文
- :return: None
"""
await context.lifecycle_uow.commit()
CatalogRegistry.commit_plugin(
@@ -501,7 +514,6 @@ async def _upgrade_step_close_session(
关闭升级数据库会话。
:param context: 插件升级上下文
- :return: None
"""
await self._close_upgrade_session(context)
@@ -533,7 +545,6 @@ def _refresh_upgrade_actions(
:param precheck: 插件预检上下文
:param context: 插件升级上下文
- :return: None
"""
context.precheck = precheck
context.actions = PluginPayloadBuilder.build_upgrade_actions(
@@ -598,6 +609,5 @@ async def _close_upgrade_session(self, context: PluginUpgradeLifecycleContext) -
关闭升级数据库会话。
:param context: 插件升级上下文
- :return: None
"""
await self._close_lifecycle_session(context)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle_lock.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle_lock.py
index 22135ff2c..5389a024c 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle_lock.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle_lock.py
@@ -19,6 +19,9 @@
class PluginLifecycleLockResult:
"""
插件生命周期操作锁获取结果。
+
+ :ivar acquired: 是否成功取得锁或租约
+ :ivar message: 与当前结果一起返回的说明
"""
acquired: bool
@@ -26,9 +29,7 @@ class PluginLifecycleLockResult:
class PluginLifecycleLockLost(ServiceException):
- """
- 插件生命周期锁在操作期间丢失。
- """
+ """插件生命周期锁在操作期间丢失。"""
def __str__(self) -> str:
"""
@@ -40,9 +41,7 @@ def __str__(self) -> str:
class PluginLifecycleLock(Protocol):
- """
- 插件生命周期操作锁接口。
- """
+ """插件生命周期操作锁接口。"""
def lock(self, plugin_id: str, operation: str) -> AbstractAsyncContextManager[PluginLifecycleLockResult]:
"""
@@ -55,9 +54,7 @@ def lock(self, plugin_id: str, operation: str) -> AbstractAsyncContextManager[Pl
class NoopPluginLifecycleLock:
- """
- 空插件生命周期锁,用于测试和离线运行时。
- """
+ """空插件生命周期锁,用于测试和离线运行时。"""
@asynccontextmanager
async def lock(self, plugin_id: str, operation: str) -> AsyncGenerator[PluginLifecycleLockResult, None]:
@@ -66,7 +63,7 @@ async def lock(self, plugin_id: str, operation: str) -> AsyncGenerator[PluginLif
:param plugin_id: 插件ID
:param operation: 操作类型
- :return: 锁获取结果上下文
+ :yield: 锁获取结果上下文
"""
yield PluginLifecycleLockResult(acquired=True)
@@ -77,6 +74,10 @@ class RedisPluginLifecycleLock:
插件生命周期操作会写入菜单、任务、配置等共享资源,因此生产环境使用全局锁串行化
写操作,避免不同插件并发安装/升级时绕过应用层幂等检查。
+
+ :cvar _RELEASE_SCRIPT: 仅在令牌匹配时释放 Redis 锁的脚本
+ :cvar _RENEW_SCRIPT: 验证锁所有权并延长有效期的 Redis 脚本
+ :ivar expire_seconds: 锁自动过期时间
"""
_RELEASE_SCRIPT = """
@@ -97,7 +98,6 @@ def __init__(self, expire_seconds: int | None = None) -> None:
初始化 Redis 插件生命周期锁。
:param expire_seconds: 锁自动过期时间
- :return: None
"""
self.expire_seconds = expire_seconds or LockConstant.PLUGIN_LIFECYCLE_LOCK_EXPIRE_SECONDS
@@ -108,7 +108,10 @@ async def lock(self, plugin_id: str, operation: str) -> AsyncGenerator[PluginLif
:param plugin_id: 插件ID
:param operation: 操作类型
- :return: 锁获取结果上下文
+ :yield: 锁获取结果上下文
+ :raises Exception: 执行期间无法为持有的锁续期
+ :raises asyncio.CancelledError: 异步操作被取消时
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
redis: aioredis.Redis | None = None
lock_key = self._build_lock_key()
@@ -194,7 +197,7 @@ async def _renew_lock_loop(
:param lock_key: 锁 key
:param lock_value: 锁值
:param owner_task: 持锁执行生命周期操作的任务
- :return: None
+ :raises PluginLifecycleLockLost: 续期时已失去插件生命周期锁
"""
interval_seconds = self._renew_interval_seconds()
while True:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/migration.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/migration.py
index 7eb42fd71..b876e1b8a 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/migration.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/migration.py
@@ -15,6 +15,8 @@
class PluginMigrationUseCase:
"""
插件 migration 历史查询和人工恢复 use case。
+
+ :ivar dependencies: 插件运行时依赖容器
"""
def __init__(self, dependencies: PluginRuntimeDependencies) -> None:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/migration_store.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/migration_store.py
index 303d15868..0108ec6d0 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/migration_store.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/migration_store.py
@@ -18,6 +18,10 @@ class PluginDatabaseMigrationHistoryStore(PluginMigrationHistoryStore):
插件数据库 migration 历史存储。
使用 Adapter 模式将插件 core runner 需要的历史接口适配到外部 migration 历史服务。
+
+ :ivar plugin_service: 插件服务类
+ :ivar model_gateway: 插件管理模型工厂网关
+ :ivar async_session_local: 独立数据库会话工厂
"""
def __init__(
@@ -30,7 +34,6 @@ def __init__(
:param plugin_service: 插件服务类
:param async_session_local: 独立数据库会话工厂
- :return: None
"""
self.plugin_service = plugin_service
self.model_gateway: PluginManagementModelGateway | None = None
@@ -96,7 +99,7 @@ async def record_running(
:param checksum: 内容校验值
:param version: 执行时插件版本
:param statement_count: SQL 语句数量
- :return: None
+ :raises RuntimeError: 插件运行时缺少 migration 历史记录模型网关
"""
if self.model_gateway is None:
raise RuntimeError('插件运行时缺少 migration 历史记录模型网关')
@@ -130,7 +133,7 @@ async def record_success(
:param checksum: 内容校验值
:param version: 执行时插件版本
:param statement_count: SQL 语句数量
- :return: None
+ :raises RuntimeError: 插件运行时缺少 migration 历史记录模型网关
"""
if self.model_gateway is None:
raise RuntimeError('插件运行时缺少 migration 历史记录模型网关')
@@ -165,7 +168,7 @@ async def record_failure(
:param version: 执行时插件版本
:param statement_count: SQL 语句数量
:param error_message: 失败错误信息
- :return: None
+ :raises RuntimeError: 插件运行时缺少 migration 历史记录模型网关
"""
if self.model_gateway is None:
raise RuntimeError('插件运行时缺少 migration 历史记录模型网关')
@@ -188,7 +191,6 @@ async def _add_plugin_migration(self, query_db: 'AsyncSession', plugin_migration
:param query_db: 当前生命周期 orm对象
:param plugin_migration: migration 历史模型
- :return: None
"""
if self.async_session_local is None:
await self.plugin_service.add_plugin_migration_services(query_db, plugin_migration)
@@ -204,6 +206,8 @@ class PluginMigrationHistoryGatewayStore(PluginMigrationHistoryStore):
插件 migration 历史查询端口适配器。
仅用于生命周期脚本预检读取历史状态,执行期写入仍由 PluginDatabaseMigrationHistoryStore 负责。
+
+ :ivar migration_history_gateway: migration 历史查询端口
"""
def __init__(self, migration_history_gateway: PluginMigrationHistoryGateway) -> None:
@@ -211,7 +215,6 @@ def __init__(self, migration_history_gateway: PluginMigrationHistoryGateway) ->
初始化 migration 历史查询适配器。
:param migration_history_gateway: migration 历史查询端口
- :return: None
"""
self.migration_history_gateway = migration_history_gateway
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/precheck.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/precheck.py
index c75ac270e..cc7ce5e30 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/precheck.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/precheck.py
@@ -17,6 +17,9 @@
class PluginPrecheckUseCase:
"""
插件预检 use case。
+
+ :ivar dependencies: 插件运行时依赖容器
+ :ivar context: 插件运行时上下文服务
"""
def __init__(self, dependencies: PluginRuntimeDependencies, context: PluginRuntimeContextService) -> None:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/query.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/query.py
index ff061a73e..84dc4154b 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/query.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/query.py
@@ -38,9 +38,7 @@
class PluginQueryRuntimeOperations(Protocol):
- """
- 查询诊断所需的运行时协作能力。
- """
+ """查询诊断所需的运行时协作能力。"""
async def get_plugin_config(self, plugin_id: str, *, reveal_secret: bool = False) -> PluginConfigStateResponse:
"""
@@ -55,6 +53,10 @@ async def get_plugin_config(self, plugin_id: str, *, reveal_secret: bool = False
class PluginQueryUseCase:
"""
插件查询 use case。
+
+ :ivar dependencies: 插件运行时依赖容器
+ :ivar runtime_operations: 查询诊断所需的运行时协作能力
+ :ivar context: 插件运行时上下文服务
"""
def __init__(
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/responses.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/responses.py
index 4ba88339e..2c6656fa8 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/responses.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/responses.py
@@ -34,55 +34,49 @@
class PluginCatalogListResponsePayload(PluginPayloadModel):
- """
- 插件列表响应 payload。
- """
+ """插件列表响应 payload。"""
- ok: bool
- count: int
- plugins: list[dict[str, object]]
- database_available: bool | None = Field(default=None, alias='databaseAvailable')
- database_error: str | None = Field(default=None, alias='databaseError')
+ ok: bool = Field(description='本次操作是否成功')
+ count: int = Field(description='结果条数')
+ plugins: list[dict[str, object]] = Field(description='插件列表')
+ database_available: bool | None = Field(default=None, alias='databaseAvailable', description='数据库是否可用')
+ database_error: str | None = Field(default=None, alias='databaseError', description='数据库访问失败的原因')
class PluginCatalogInfoResponsePayload(PluginPayloadModel):
- """
- 插件详情响应 payload。
- """
+ """插件详情响应 payload。"""
- ok: bool
- plugin: dict[str, object]
+ ok: bool = Field(description='本次操作是否成功')
+ plugin: dict[str, object] = Field(description='插件详情')
class PluginBatchRunResponsePayload(PluginPayloadModel):
- """
- 插件批量执行响应 payload。
- """
+ """插件批量执行响应 payload。"""
- ok: bool | None = None
- message: str | None = None
- dry_run: bool | None = Field(default=None, alias='dryRun')
- continue_on_error: bool | None = Field(default=None, alias='continueOnError')
- executed: list[dict[str, object]] | None = None
- failed: dict[str, object] | None = None
- summary: dict[str, object] | None = None
- exit_code: int | None = None
+ ok: bool | None = Field(default=None, description='本次操作是否成功')
+ message: str | None = Field(default=None, description='面向调用方的结果说明')
+ dry_run: bool | None = Field(default=None, alias='dryRun', description='是否仅预演本次操作')
+ continue_on_error: bool | None = Field(
+ default=None, alias='continueOnError', description='遇到单项错误时是否继续处理'
+ )
+ executed: list[dict[str, object]] | None = Field(default=None, description='已执行的插件操作明细')
+ failed: dict[str, object] | None = Field(default=None, description='导致批处理失败的操作明细')
+ summary: dict[str, object] | None = Field(default=None, description='操作结果摘要')
+ exit_code: int | None = Field(default=None, description='命令行退出码')
class PluginRuntimeBlockedPayload(PluginPayloadModel):
- """
- 插件运行模式阻断响应 payload。
- """
-
- ok: bool
- status: str
- operation: str
- plugin_id: str = Field(alias='pluginId')
- message: str
- suggestion: str
- capability: dict[str, object]
- dry_run: bool | None = Field(default=None, alias='dryRun')
- exit_code: int
+ """插件运行模式阻断响应 payload。"""
+
+ ok: bool = Field(description='本次操作是否成功')
+ status: str = Field(description='当前状态')
+ operation: str = Field(description='执行的操作类型')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ message: str = Field(description='面向调用方的结果说明')
+ suggestion: str = Field(description='建议的后续处理方式')
+ capability: dict[str, object] = Field(description='当前环境对该操作的支持情况')
+ dry_run: bool | None = Field(default=None, alias='dryRun', description='是否仅预演本次操作')
+ exit_code: int = Field(description='命令行退出码')
PluginCatalogListResponseDict: TypeAlias = dict[str, object]
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/tools.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/tools.py
index 76ad1647f..91457d3a7 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/tools.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/tools.py
@@ -16,6 +16,9 @@
class PluginToolUseCase:
"""
插件运行时工具 use case。
+
+ :ivar dependencies: 插件运行时依赖容器
+ :ivar context: 插件运行时上下文服务
"""
def __init__(self, dependencies: PluginRuntimeDependencies, context: PluginRuntimeContextService) -> None:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/startup.py b/ruoyi-fastapi-backend/plugins/core/runtime/startup.py
index f29cb77d8..cc19e8998 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/startup.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/startup.py
@@ -45,6 +45,9 @@
class PluginStartupMigrationHistoryStore(PluginMigrationHistoryStore):
"""
启动期插件 migration 历史存储适配器。
+
+ :ivar management_gateway: 插件启动期管理端口
+ :ivar async_session_local: 独立数据库会话工厂
"""
def __init__(self, management_gateway: PluginStartupManagementGateway, async_session_local: Any = None) -> None:
@@ -53,7 +56,6 @@ def __init__(self, management_gateway: PluginStartupManagementGateway, async_ses
:param management_gateway: 插件启动期管理端口
:param async_session_local: 独立数据库会话工厂
- :return: None
"""
self.management_gateway = management_gateway
self.async_session_local = async_session_local
@@ -99,7 +101,6 @@ async def record_running(
:param checksum: 内容校验值
:param version: 执行时插件版本
:param statement_count: SQL 语句数量
- :return: None
"""
await self._add_plugin_migration(
query_db,
@@ -131,7 +132,6 @@ async def record_success(
:param checksum: 内容校验值
:param version: 执行时插件版本
:param statement_count: SQL 语句数量
- :return: None
"""
await self._add_plugin_migration(
query_db,
@@ -164,7 +164,6 @@ async def record_failure(
:param version: 执行时插件版本
:param statement_count: SQL 语句数量
:param error_message: 失败错误信息
- :return: None
"""
await self._add_plugin_migration(
query_db,
@@ -185,7 +184,6 @@ async def _add_plugin_migration(self, query_db: Any, plugin_migration: Any) -> N
:param query_db: 当前启动期 orm对象
:param plugin_migration: migration 历史模型
- :return: None
"""
if self.async_session_local is None:
await self.management_gateway.add_plugin_migration(query_db, plugin_migration)
@@ -202,6 +200,14 @@ class PluginRuntimeStartupManager:
将插件发现、实体导入、资源安装、路由注册和生命周期钩子从应用入口中隔离出来,
让 server.py 只保留高层启动顺序。
+
+ :ivar builder: 插件运行时构建器
+ :ivar management_gateway: 插件启动期管理端口
+ :ivar route_state_gateway: 插件路由状态读取端口
+ :ivar python_dependency_inspector_factory: Python 依赖检查器工厂
+ :ivar python_dependency_inspector: Python 依赖检查器
+ :ivar command_runner_gateway: 插件命令执行网关
+ :ivar default_enabled_builtin_plugin_ids: 首次启动默认安装启用的内置插件 ID 集合
"""
def __init__(
@@ -224,7 +230,6 @@ def __init__(
:param python_dependency_inspector_factory: Python 依赖检查器工厂
:param command_runner_gateway: 插件命令执行网关
:param default_enabled_builtin_plugin_ids: 首次启动默认安装启用的内置插件 ID 集合
- :return: None
"""
self.builder = builder or PluginRuntimeBuilder()
self.management_gateway = management_gateway or UnavailablePluginStartupManagementGateway()
@@ -243,7 +248,6 @@ def bind_app(self, app: FastAPI) -> None:
绑定插件运行时对象到 FastAPI state。
:param app: FastAPI对象
- :return: None
"""
app.state.plugin_runtime_startup = self
app.state.plugin_runtime_builder = self.builder
@@ -253,11 +257,7 @@ def bind_app(self, app: FastAPI) -> None:
app.state.plugin_routes_registered = False
def import_builtin_entities(self) -> None:
- """
- 导入内置业务模块实体。
-
- :return: None
- """
+ """导入内置业务模块实体。"""
self.builder.import_builtin_entities()
@staticmethod
@@ -276,7 +276,6 @@ async def prepare_enabled_plugins(self, app: FastAPI, *, startup_write_enabled:
:param app: FastAPI对象
:param startup_write_enabled: 是否允许执行启动期写库操作
- :return: None
"""
default_dependency_failed_plugin_ids: set[str] = set()
if startup_write_enabled:
@@ -300,11 +299,10 @@ async def prepare_enabled_plugins(self, app: FastAPI, *, startup_write_enabled:
async def prepare_enabled_plugin_catalogs(self, app: FastAPI, *, startup_write_enabled: bool) -> None:
"""
- 为当前工作进程加载插件词库,失败时仅隔离相应插件
+ 为当前工作进程加载插件词库,失败时仅隔离相应插件。
:param app: 宿主 FastAPI 应用
:param startup_write_enabled: 是否允许执行启动期全局写入
- :return: None
"""
registry = getattr(app.state, 'plugin_registry', None)
if not isinstance(registry, PluginRegistry):
@@ -326,7 +324,6 @@ async def prepare_explicit_plugins(self, app: FastAPI, *, startup_write_enabled:
:param app: 宿主 FastAPI 应用
:param startup_write_enabled: 当前 worker 是否允许执行启动期全局写入
- :return: None
"""
registry = getattr(app.state, 'plugin_registry', None)
if not isinstance(registry, PluginRegistry):
@@ -377,7 +374,7 @@ async def activate_explicit_plugins(self, app: FastAPI, *, startup_write_enabled
:param app: 宿主 FastAPI 应用
:param startup_write_enabled: 当前 worker 是否允许执行启动期全局写入
- :return: None
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
runtime = getattr(app.state, 'plugin_explicit_runtime', None)
if not isinstance(runtime, ExplicitPluginRuntime):
@@ -536,7 +533,6 @@ async def recover_plugin_dependency_errors(
:param app: FastAPI对象
:param plugins: 依赖已恢复的插件列表
- :return: None
"""
recovered = False
async with DataSourceRegistry.session() as query_db:
@@ -655,7 +651,6 @@ async def _install_plugin_python_dependencies(self, dependency_result: Dependenc
安装插件 Python 依赖。
:param dependency_result: 依赖检查结果
- :return: None
"""
install_plan = PluginDependencyInstallPlanner().build_plan(dependency_result)
for item in install_plan.items:
@@ -680,7 +675,6 @@ async def activate_enabled_plugins(self, app: FastAPI, *, startup_write_enabled:
:param app: FastAPI对象
:param startup_write_enabled: 是否允许执行启动期写库操作
- :return: None
"""
if startup_write_enabled:
await self.sync_enabled_plugin_install_states(app)
@@ -695,7 +689,6 @@ async def shutdown(self, app: FastAPI, *, startup_write_enabled: bool = True) ->
:param app: FastAPI对象
:param startup_write_enabled: 是否允许执行启动期写库操作
- :return: None
"""
runtime = getattr(app.state, 'plugin_explicit_runtime', None)
try:
@@ -715,7 +708,6 @@ async def load_registry_from_database(self, app: FastAPI) -> None:
从数据库插件状态构建运行时插件注册表。
:param app: FastAPI对象
- :return: None
"""
async with DataSourceRegistry.session() as query_db:
plugin_list = await self.management_gateway.list_plugins(query_db)
@@ -767,7 +759,6 @@ async def install_enabled_plugin_resources(self, app: FastAPI) -> None:
不再回滚其他插件或阻断宿主应用启动。
:param app: FastAPI对象
- :return: None
"""
plugin_registry = getattr(app.state, 'plugin_registry', None)
if plugin_registry is None:
@@ -789,7 +780,6 @@ async def install_plugin_resources_with_isolation(
:param app: FastAPI对象
:param plugin: 插件运行时快照
- :return: None
"""
with logger.contextualize(
plugin_id=plugin.plugin_id,
@@ -821,7 +811,6 @@ async def sync_enabled_plugin_install_states(self, app: FastAPI) -> None:
将默认启用且尚未持久化安装状态的插件标记为已安装。
:param app: FastAPI对象
- :return: None
"""
plugin_registry = getattr(app.state, 'plugin_registry', None)
if plugin_registry is None:
@@ -850,7 +839,6 @@ async def sync_plugin_install_with_isolation(
:param app: FastAPI对象
:param plugin: 插件运行时快照
- :return: None
"""
try:
await self.sync_plugin_install(plugin.discovered_plugin, enabled=True)
@@ -869,7 +857,7 @@ async def sync_plugin_install(self, discovered_plugin: Any, *, enabled: bool) ->
:param discovered_plugin: 已发现插件对象
:param enabled: 插件资源是否启用
- :return: None
+ :raises Exception: 事务失败并回滚后重新抛出原异常
"""
plugin_id = discovered_plugin.manifest.id
with logger.contextualize(
@@ -908,7 +896,6 @@ async def run_plugin_install_hook(query_db: Any, discovered_plugin: Any) -> None
:param query_db: orm对象
:param discovered_plugin: 已发现插件对象
- :return: None
"""
await PluginHookRunner(discovered_plugin).run('on_install', query_db=query_db)
@@ -917,7 +904,6 @@ def validate_plugin_structure(self, discovered_plugin: Any) -> None:
校验启动期首次安装插件的目录和声明引用。
:param discovered_plugin: 已发现插件对象
- :return: None
:raises ValueError: 插件结构校验失败
"""
result = PluginStructureChecker(
@@ -954,7 +940,6 @@ async def run_plugin_install_scripts(self, query_db: Any, discovered_plugin: Any
:param query_db: orm对象
:param discovered_plugin: 已发现插件对象
- :return: None
"""
async with DataSourceRegistry.session() as migration_session:
await PluginMigrationRunner(
@@ -971,7 +956,6 @@ async def run_plugin_seed_scripts(query_db: Any, discovered_plugin: Any) -> None
:param query_db: orm对象
:param discovered_plugin: 已发现插件对象
- :return: None
"""
await PluginSeedRunner(discovered_plugin).run(query_db)
@@ -986,7 +970,6 @@ def register_enabled_plugin_routers(
:param app: FastAPI对象
:param startup_write_enabled: 当前worker是否为插件启动writer
- :return: None
"""
if getattr(app.state, 'plugin_routes_registered', False):
return
@@ -1072,7 +1055,6 @@ async def run_enabled_plugin_hooks(
:param app: FastAPI对象
:param hook_name: 钩子名称
:param startup_write_enabled: 是否允许执行启动期写库操作
- :return: None
"""
plugin_registry = getattr(app.state, 'plugin_registry', None)
if plugin_registry is None:
@@ -1101,7 +1083,6 @@ async def run_single_plugin_hook(
:param plugin: 插件运行时快照
:param hook_name: 钩子名称
:param startup_write_enabled: 是否允许执行启动期写库操作
- :return: None
"""
try:
await PluginHookRunner(plugin.discovered_plugin).run(
@@ -1130,7 +1111,6 @@ async def mark_plugin_runtime_error(self, app: FastAPI, plugin_id: str, error_me
:param app: FastAPI对象
:param plugin_id: 插件ID
:param error_message: 错误信息
- :return: None
"""
registered_plugin = self.get_registered_plugin(app, plugin_id)
if registered_plugin and is_artifact_plugin(registered_plugin.discovered_plugin):
@@ -1223,7 +1203,6 @@ async def mark_discovered_plugin_startup_error(
:param discovered_plugin: 已发现插件对象
:param error_message: 错误信息
- :return: None
"""
plugin_id = discovered_plugin.manifest.id
async with DataSourceRegistry.session() as query_db:
@@ -1281,7 +1260,6 @@ def disable_runtime_plugins(app: FastAPI, plugin_ids: set[str]) -> None:
:param app: FastAPI对象
:param plugin_ids: 需要在当前 worker 跳过的插件 ID 集合
- :return: None
"""
if not plugin_ids:
return
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/startup_coordination.py b/ruoyi-fastapi-backend/plugins/core/runtime/startup_coordination.py
index e8cdc6e6a..1da116740 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/startup_coordination.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/startup_coordination.py
@@ -17,6 +17,9 @@ class PluginStartupGenerationResolver:
生产部署可通过 ``APP_RELEASE_ID`` 显式提供发布代际。未配置时,对应用版本和插件
后端源码生成稳定指纹,使同一发布的多个 worker 共享代际,而源码变化后的滚动发布
不会复用旧版本 ready 状态。
+
+ :ivar backend_root: 后端项目根目录
+ :ivar release_id: 显式发布标识
"""
def __init__(self, backend_root: Path | str, *, release_id: str | None = None) -> None:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/startup_gateway.py b/ruoyi-fastapi-backend/plugins/core/runtime/startup_gateway.py
index add46e110..ac95d6987 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/startup_gateway.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/startup_gateway.py
@@ -10,9 +10,7 @@
@runtime_checkable
class PluginStartupManagementGateway(Protocol):
- """
- 插件启动期依赖的管理端口。
- """
+ """插件启动期依赖的管理端口。"""
async def list_plugins(self, query_db: AsyncSession) -> list[Any]:
"""
@@ -35,7 +33,6 @@ async def install_plugin_resources(
:param query_db: orm对象
:param discovered_plugin: 已发现插件对象
:param enabled: 插件资源是否启用
- :return: None
"""
async def mark_plugin_error(
@@ -137,6 +134,8 @@ def build_migration_record(
"""
构建插件 migration 执行历史对象。
+ :param status: 操作或记录所处的状态
+ :param error_message: 错误信息
:param plugin_id: 插件ID
:param migration_path: migration 相对路径
:param checksum: 内容校验值
@@ -147,16 +146,13 @@ def build_migration_record(
class UnavailablePluginStartupManagementGateway:
- """
- 不可用的插件启动期管理端口。
- """
+ """不可用的插件启动期管理端口。"""
@staticmethod
def _raise_unavailable() -> NoReturn:
"""
抛出启动期管理端口不可用异常。
- :return: NoReturn
:raises RuntimeError: 默认端口不提供管理服务能力
"""
raise RuntimeError('插件启动期缺少管理服务适配器')
@@ -183,7 +179,6 @@ async def install_plugin_resources(
:param query_db: orm对象
:param discovered_plugin: 已发现插件对象
:param enabled: 插件资源是否启用
- :return: None
"""
self._raise_unavailable()
@@ -292,6 +287,8 @@ def build_migration_record(
"""
构建插件 migration 执行历史对象。
+ :param status: 操作或记录所处的状态
+ :param error_message: 错误信息
:param plugin_id: 插件ID
:param migration_path: migration 相对路径
:param checksum: 内容校验值
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/batch_report.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/batch_report.py
index e96c34855..b32f38061 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/batch_report.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/batch_report.py
@@ -11,27 +11,27 @@
class BatchOperationResult(PluginPayloadModel):
- """
- 批量单项运行时结果 payload。
- """
+ """批量单项运行时结果 payload。"""
- ok: bool | None = None
- message: str | None = None
- plugin_dependency_errors: object | None = Field(default=None, alias='pluginDependencyErrors')
- structure_errors: object | None = Field(default=None, alias='structureErrors')
- menu_conflicts: object | None = Field(default=None, alias='menuConflicts')
- error: object | None = None
+ ok: bool | None = Field(default=None, description='本次操作是否成功')
+ message: str | None = Field(default=None, description='面向调用方的结果说明')
+ plugin_dependency_errors: object | None = Field(
+ default=None, alias='pluginDependencyErrors', description='插件之间的依赖检查错误'
+ )
+ structure_errors: object | None = Field(
+ default=None, alias='structureErrors', description='插件目录或文件结构检查错误'
+ )
+ menu_conflicts: object | None = Field(default=None, alias='menuConflicts', description='检测到的菜单冲突')
+ error: object | None = Field(default=None, description='失败原因')
class BatchSummary(PluginPayloadModel):
- """
- 批量执行汇总 payload。
- """
+ """批量执行汇总 payload。"""
- total: int
- succeeded: int
- failed: int
- skipped: int
+ total: int = Field(description='条目总数')
+ succeeded: int = Field(description='成功的操作数')
+ failed: int = Field(description='失败的操作数')
+ skipped: int = Field(description='跳过的条目数')
@dataclass(frozen=True)
@@ -39,13 +39,13 @@ class PluginBatchItemReport:
"""
插件批量执行单项报告。
- :param plugin_id: 插件ID
- :param operation: 批量操作类型
- :param ok: 是否执行成功
- :param status: 执行状态
- :param message: 执行消息
- :param duration_ms: 耗时毫秒数
- :param suggestion: 失败建议
+ :ivar plugin_id: 插件ID
+ :ivar operation: 批量操作类型
+ :ivar ok: 是否执行成功
+ :ivar status: 执行状态
+ :ivar message: 执行消息
+ :ivar duration_ms: 耗时毫秒数
+ :ivar suggestion: 失败建议
"""
plugin_id: str
@@ -58,36 +58,32 @@ class PluginBatchItemReport:
class BatchFailedItem(PluginPayloadModel):
- """
- 批量失败项 payload。
- """
+ """批量失败项 payload。"""
- plugin_id: str = Field(alias='pluginId')
- operation: str | None = None
- ok: bool | None = None
- status: str | None = None
- message: str | None = None
- duration_ms: int | None = Field(default=None, alias='durationMs')
- suggestion: str | None = None
- result: dict[str, object]
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ operation: str | None = Field(default=None, description='执行的操作类型')
+ ok: bool | None = Field(default=None, description='本次操作是否成功')
+ status: str | None = Field(default=None, description='当前状态')
+ message: str | None = Field(default=None, description='面向调用方的结果说明')
+ duration_ms: int | None = Field(default=None, alias='durationMs', description='本次操作耗时(毫秒)')
+ suggestion: str | None = Field(default=None, description='建议的后续处理方式')
+ result: dict[str, object] = Field(description='单项操作的详细结果')
class PluginBatchRunPayload(PluginPayloadModel):
- """
- 插件批量执行响应 payload。
- """
-
- ok: bool | None = None
- message: str
- operation: str | None = None
- database_available: bool | None = Field(default=None, alias='databaseAvailable')
- database_error: str | None = Field(default=None, alias='databaseError')
- plan: dict[str, object] | None = None
- dry_run: bool = Field(alias='dryRun')
- continue_on_error: bool = Field(alias='continueOnError')
- executed: list[dict[str, object]]
- failed: dict[str, object] | None
- summary: dict[str, object]
+ """插件批量执行响应 payload。"""
+
+ ok: bool | None = Field(default=None, description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ operation: str | None = Field(default=None, description='执行的操作类型')
+ database_available: bool | None = Field(default=None, alias='databaseAvailable', description='数据库是否可用')
+ database_error: str | None = Field(default=None, alias='databaseError', description='数据库访问失败的原因')
+ plan: dict[str, object] | None = Field(default=None, description='预定执行的操作计划')
+ dry_run: bool = Field(alias='dryRun', description='是否仅预演本次操作')
+ continue_on_error: bool = Field(alias='continueOnError', description='遇到单项错误时是否继续处理')
+ executed: list[dict[str, object]] = Field(description='已执行的插件操作明细')
+ failed: dict[str, object] | None = Field(description='导致批处理失败的操作明细')
+ summary: dict[str, object] = Field(description='操作结果摘要')
BatchOperationResultPayload: TypeAlias = dict[str, object]
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/npm_package.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/npm_package.py
index 6658e852f..457b673d4 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/npm_package.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/npm_package.py
@@ -25,7 +25,6 @@ def sync_successful_items(
:param install_plan_items: 依赖安装计划项
:param install_results: 依赖安装执行结果
- :return: None
"""
for item, result in zip(install_plan_items, install_results, strict=False):
if item.kind not in {'npm', 'npmDev'} or result['returnCode'] != 0:
@@ -38,7 +37,6 @@ def sync_item(item: DependencyInstallPlanItem) -> None:
同步单个 npm 依赖版本声明。
:param item: 依赖安装计划项
- :return: None
"""
# pnpm add 同时维护 package.json 和 pnpm-lock.yaml。不要在安装后单独
# 改写版本声明,否则下次 frozen-lockfile 安装会失败;离线 tarball 同理。
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/audit.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/audit.py
index 66b97f54a..bbc091d88 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/audit.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/audit.py
@@ -9,39 +9,33 @@
class PluginAuditItemPayload(PluginPayloadModel):
- """
- 插件审计单项 payload。
- """
+ """插件审计单项 payload。"""
- operation_id: object = Field(alias='operationId')
- operation: object
- plugin_ids: list[object] = Field(alias='pluginIds')
- dry_run: bool = Field(alias='dryRun')
- continue_on_error: bool = Field(alias='continueOnError')
- status: object
- summary: object
- create_time: object = Field(alias='createTime')
- remark: object
+ operation_id: object = Field(alias='operationId', description='操作记录标识')
+ operation: object = Field(description='执行的操作类型')
+ plugin_ids: list[object] = Field(alias='pluginIds', description='插件标识列表')
+ dry_run: bool = Field(alias='dryRun', description='是否仅预演本次操作')
+ continue_on_error: bool = Field(alias='continueOnError', description='遇到单项错误时是否继续处理')
+ status: object = Field(description='当前状态')
+ summary: object = Field(description='操作结果摘要')
+ create_time: object = Field(alias='createTime', description='操作记录创建时间')
+ remark: object = Field(description='补充说明')
class PluginAuditSnapshotPayload(PluginPayloadModel):
- """
- 插件最近审计快照 payload。
- """
+ """插件最近审计快照 payload。"""
- available: bool
- count: int
- items: list[Mapping[str, object]]
+ available: bool = Field(description='数据是否可用')
+ count: int = Field(description='结果条数')
+ items: list[Mapping[str, object]] = Field(description='结果条目列表')
class PluginAuditSnapshotFailurePayload(PluginPayloadModel):
- """
- 插件最近审计快照读取失败 payload。
- """
+ """插件最近审计快照读取失败 payload。"""
- available: bool
- message: str
- items: list[Mapping[str, object]]
+ available: bool = Field(description='数据是否可用')
+ message: str = Field(description='面向调用方的结果说明')
+ items: list[Mapping[str, object]] = Field(description='结果条目列表')
PluginAuditItemPayloadDict: TypeAlias = dict[str, object]
@@ -50,9 +44,7 @@ class PluginAuditSnapshotFailurePayload(PluginPayloadModel):
class SupportsAuditModelDump(Protocol):
- """
- 支持审计记录别名序列化的对象协议。
- """
+ """支持审计记录别名序列化的对象协议。"""
def model_dump(self, *, by_alias: bool = False) -> Mapping[str, object]:
"""
@@ -65,9 +57,7 @@ def model_dump(self, *, by_alias: bool = False) -> Mapping[str, object]:
class PluginAuditPayloadBuilder:
- """
- 插件审计负载构建器。
- """
+ """插件审计负载构建器。"""
@staticmethod
def build_recent_snapshot_failure(error: Exception) -> PluginAuditSnapshotFailurePayloadDict:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/base.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/base.py
index 6d6a757ce..030b0286a 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/base.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/base.py
@@ -6,9 +6,7 @@
class PluginPayloadModel(BaseModel):
- """
- 插件运行时 payload 模型基类。
- """
+ """插件运行时 payload 模型基类。"""
model_config = ConfigDict(populate_by_name=True, extra='forbid')
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/catalog.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/catalog.py
index b45713960..d67abcfc6 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/catalog.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/catalog.py
@@ -18,118 +18,104 @@
class PluginCatalogSummaryPayload(PluginPayloadModel):
- """
- 插件目录摘要 payload。
- """
-
- plugin_id: str = Field(alias='pluginId')
- name: str
- version: str
- enabled: bool
- status: str
- description: str
- backend_path: str = Field(alias='backendPath')
- menu_count: int = Field(alias='menuCount')
- permission_count: int = Field(alias='permissionCount')
- capability: dict[str, object] | None
+ """插件目录摘要 payload。"""
+
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ name: str = Field(description='插件名称')
+ version: str = Field(description='插件版本')
+ enabled: bool = Field(description='是否启用')
+ status: str = Field(description='当前状态')
+ description: str = Field(description='插件功能说明')
+ backend_path: str = Field(alias='backendPath', description='插件后端所在路径')
+ menu_count: int = Field(alias='menuCount', description='插件菜单数')
+ permission_count: int = Field(alias='permissionCount', description='插件权限数')
+ capability: dict[str, object] | None = Field(description='当前环境对该操作的支持情况')
class PluginCatalogDatabaseStatePayload(PluginPayloadModel):
- """
- 插件目录数据库状态 payload。
- """
+ """插件目录数据库状态 payload。"""
- available: bool
- installed: bool
- error: str | None = None
- installed_version: str | None = Field(default=None, alias='installedVersion')
- enabled: str | None
- status: str | None
- last_error: str | None = Field(default=None, alias='lastError')
+ available: bool = Field(description='数据是否可用')
+ installed: bool = Field(description='是否已经安装')
+ error: str | None = Field(default=None, description='失败原因')
+ installed_version: str | None = Field(default=None, alias='installedVersion', description='已安装的版本')
+ enabled: str | None = Field(description='是否启用')
+ status: str | None = Field(description='当前状态')
+ last_error: str | None = Field(default=None, alias='lastError', description='最近一次错误的信息')
class PluginManifestConfigItemPayload(PluginPayloadModel):
- """
- manifest 配置声明 payload。
- """
-
- key: str
- label: str | None
- type: str
- default: object
- required: bool
- secret: bool
- group: str
- order: int
- placeholder: str
- min_value: float | None = Field(alias='min')
- max_value: float | None = Field(alias='max')
- pattern: str | None
- description: str
- options: list[dict[str, object]]
+ """manifest 配置声明 payload。"""
+
+ key: str = Field(description='配置项的键')
+ label: str | None = Field(description='面向用户的显示名称')
+ type: str = Field(description='配置项的数据类型')
+ default: object = Field(description='配置项的默认值')
+ required: bool = Field(description='是否为必填配置')
+ secret: bool = Field(description='是否包含敏感值')
+ group: str = Field(description='配置项所属分组')
+ order: int = Field(description='排列顺序')
+ placeholder: str = Field(description='输入配置值时显示的提示')
+ min_value: float | None = Field(alias='min', description='允许的最小数值')
+ max_value: float | None = Field(alias='max', description='允许的最大数值')
+ pattern: str | None = Field(description='配置值必须匹配的正则表达式')
+ description: str = Field(description='配置项的用途说明')
+ options: list[dict[str, object]] = Field(description='可供选择的配置值及标签')
class PluginManifestPermissionItemPayload(PluginPayloadModel):
- """
- manifest 权限声明 payload。
- """
+ """manifest 权限声明 payload。"""
- code: str
- name: str | None
- description: str
+ code: str = Field(description='权限标识')
+ name: str | None = Field(description='权限名称')
+ description: str = Field(description='权限允许执行的操作')
class PluginMenuDiagnosticPlanItemPayload(PluginPayloadModel):
- """
- 菜单诊断计划项 payload。
- """
-
- name: str
- path: str
- component: str
- perms: str
- type: str
- query: str | None
- route_name: str | None = Field(alias='routeName')
- is_frame: int = Field(alias='isFrame')
- is_cache: int = Field(alias='isCache')
- visible: str
- status: str
- children: int
+ """菜单诊断计划项 payload。"""
+
+ name: str = Field(description='菜单名称')
+ path: str = Field(description='菜单路由路径')
+ component: str = Field(description='菜单对应的前端组件')
+ perms: str = Field(description='访问菜单所需的权限码')
+ type: str = Field(description='菜单类型')
+ query: str | None = Field(description='菜单路由的查询参数')
+ route_name: str | None = Field(alias='routeName', description='前端路由名称')
+ is_frame: int = Field(alias='isFrame', description='菜单的外链标志')
+ is_cache: int = Field(alias='isCache', description='页面缓存标志')
+ visible: str = Field(description='菜单显示状态')
+ status: str = Field(description='当前状态')
+ children: int = Field(description='直接子菜单的数量')
class PluginMenuDiagnosticPlanPayload(PluginPayloadModel):
- """
- 菜单诊断计划 payload。
- """
+ """菜单诊断计划 payload。"""
- total: int
- permission_count: int = Field(alias='permissionCount')
- enabled_count: int = Field(alias='enabledCount')
- visible_count: int = Field(alias='visibleCount')
- items: list[dict[str, object]]
+ total: int = Field(description='条目总数')
+ permission_count: int = Field(alias='permissionCount', description='插件权限数')
+ enabled_count: int = Field(alias='enabledCount', description='已启用的条目数')
+ visible_count: int = Field(alias='visibleCount', description='可见条目数')
+ items: list[dict[str, object]] = Field(description='结果条目列表')
class PluginManifestJobItemPayload(PluginPayloadModel):
- """
- manifest 定时任务声明 payload。
- """
-
- id: str
- name: str | None
- callable: str
- trigger: str
- cron_expression: str = Field(alias='cronExpression')
- time_zone: str = Field(alias='timeZone')
- args: list[object]
- kwargs: dict[str, object]
- enabled: bool
- description: str
- misfire_grace_time: int | None = Field(alias='misfireGraceTime')
- coalesce: bool
- max_instances: int = Field(alias='maxInstances')
- job_store: str = Field(alias='jobStore')
- executor: str
+ """manifest 定时任务声明 payload。"""
+
+ id: str = Field(description='调度任务标识')
+ name: str | None = Field(description='调度任务名称')
+ callable: str = Field(description='调度任务调用的函数路径')
+ trigger: str = Field(description='调度触发器类型')
+ cron_expression: str = Field(alias='cronExpression', description='调度使用的 Cron 表达式')
+ time_zone: str = Field(alias='timeZone', description='解析调度时间的时区')
+ args: list[object] = Field(description='传给任务的位置参数')
+ kwargs: dict[str, object] = Field(description='传给任务的关键字参数')
+ enabled: bool = Field(description='是否启用')
+ description: str = Field(description='调度任务的用途说明')
+ misfire_grace_time: int | None = Field(alias='misfireGraceTime', description='错过计划时间后仍允许执行的宽限秒数')
+ coalesce: bool = Field(description='是否合并积压的任务执行')
+ max_instances: int = Field(alias='maxInstances', description='同一任务允许同时运行的最大实例数')
+ job_store: str = Field(alias='jobStore', description='保存任务定义的调度存储')
+ executor: str = Field(description='调度任务使用的执行器')
PluginCatalogSummaryPayloadDict: TypeAlias = dict[str, object]
@@ -137,9 +123,7 @@ class PluginManifestJobItemPayload(PluginPayloadModel):
class PluginCatalogPayloadMixin:
- """
- 插件目录、详情和 manifest 基础信息负载构建能力。
- """
+ """插件目录、详情和 manifest 基础信息负载构建能力。"""
@classmethod
def build_plugin_list_payload(cls, plugins: list[RegisteredPlugin]) -> dict[str, object]:
@@ -166,6 +150,7 @@ def build_plugin_info_payload(
"""
构建插件详情响应负载。
+ :param capability: 插件运行时管理能力及操作限制
:param plugin: 已注册插件运行时快照或已发现插件
:param dependency_items: 依赖检查项列表
:param database_error: 数据库状态读取错误信息
@@ -192,6 +177,7 @@ def build_plugin_summary(
"""
构建插件摘要负载。
+ :param capability: 插件运行时管理能力及操作限制
:param plugin: 已发现插件
:param enabled: 是否启用
:param status: 插件状态
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/common.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/common.py
index d61c59032..46f9b77ec 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/common.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/common.py
@@ -8,25 +8,21 @@
class PluginNotFoundPayload(PluginPayloadModel):
- """
- 插件不存在 payload。
- """
+ """插件不存在 payload。"""
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- operation: str | None = None
- dry_run: bool | None = Field(default=None, alias='dryRun')
- enabled: bool | None = None
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ operation: str | None = Field(default=None, description='执行的操作类型')
+ dry_run: bool | None = Field(default=None, alias='dryRun', description='是否仅预演本次操作')
+ enabled: bool | None = Field(default=None, description='是否启用')
PluginNotFoundPayloadDict: TypeAlias = dict[str, object]
class PluginCommonPayloadMixin:
- """
- 插件运行时通用 payload 构建能力。
- """
+ """插件运行时通用 payload 构建能力。"""
@staticmethod
def build_plugin_not_found_payload(
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/config.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/config.py
index b7ea6b528..000594a7b 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/config.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/config.py
@@ -10,103 +10,87 @@
class PluginConfigStatePayload(PluginPayloadModel):
- """
- 插件配置读取/更新 payload。
- """
+ """插件配置读取/更新 payload。"""
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- configs: list[dict[str, object]]
- operation: str | None = None
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ configs: list[dict[str, object]] = Field(description='插件配置项列表')
+ operation: str | None = Field(default=None, description='执行的操作类型')
class PluginConfigExportFailurePayload(PluginPayloadModel):
- """
- 插件配置导出失败 payload。
- """
+ """插件配置导出失败 payload。"""
- ok: object
- message: object
- plugin_id: str = Field(alias='pluginId')
- reveal_secret: bool = Field(alias='revealSecret')
- values: dict[str, object]
- metadata: list[dict[str, object]]
+ ok: object = Field(description='本次操作是否成功')
+ message: object = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ reveal_secret: bool = Field(alias='revealSecret', description='是否显示敏感配置的原值')
+ values: dict[str, object] = Field(description='按配置键索引的值')
+ metadata: list[dict[str, object]] = Field(description='导出配置的元数据')
class PluginConfigExportPayload(PluginPayloadModel):
- """
- 插件配置导出 payload。
- """
+ """插件配置导出 payload。"""
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- reveal_secret: bool = Field(alias='revealSecret')
- configs: list[dict[str, object]]
- values: dict[str, object]
- metadata: list[dict[str, object]]
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ reveal_secret: bool = Field(alias='revealSecret', description='是否显示敏感配置的原值')
+ configs: list[dict[str, object]] = Field(description='插件配置项列表')
+ values: dict[str, object] = Field(description='按配置键索引的值')
+ metadata: list[dict[str, object]] = Field(description='导出配置的元数据')
class PluginConfigDiagnosticSummaryPayload(PluginPayloadModel):
- """
- 插件配置诊断摘要 payload。
- """
+ """插件配置诊断摘要 payload。"""
- total: int
- secret_count: int = Field(alias='secretCount')
- required_count: int = Field(alias='requiredCount')
- configured_count: int = Field(alias='configuredCount')
- missing_required_count: int = Field(alias='missingRequiredCount')
- missing_required_keys: list[str] = Field(alias='missingRequiredKeys')
- masked: bool
+ total: int = Field(description='条目总数')
+ secret_count: int = Field(alias='secretCount', description='敏感配置项数')
+ required_count: int = Field(alias='requiredCount', description='必填配置项数')
+ configured_count: int = Field(alias='configuredCount', description='已设置值的配置项数')
+ missing_required_count: int = Field(alias='missingRequiredCount', description='尚未填写的必填配置项数')
+ missing_required_keys: list[str] = Field(alias='missingRequiredKeys', description='尚未填写的必填配置键')
+ masked: bool = Field(description='敏感值是否已遮盖')
class PluginConfigImportPayload(PluginPayloadModel):
- """
- 插件配置导入 payload。
- """
+ """插件配置导入 payload。"""
- ok: object | None = None
- message: object | None = None
- plugin_id: object | None = Field(default=None, alias='pluginId')
- operation: str | None = None
- configs: list[dict[str, object]] | None = None
- imported_keys: list[str] = Field(alias='importedKeys')
+ ok: object | None = Field(default=None, description='本次操作是否成功')
+ message: object | None = Field(default=None, description='面向调用方的结果说明')
+ plugin_id: object | None = Field(default=None, alias='pluginId', description='插件标识')
+ operation: str | None = Field(default=None, description='执行的操作类型')
+ configs: list[dict[str, object]] | None = Field(default=None, description='插件配置项列表')
+ imported_keys: list[str] = Field(alias='importedKeys', description='本次导入的配置键')
class PluginConfigAuditChangePayload(PluginPayloadModel):
- """
- 插件配置审计变更项 payload。
- """
+ """插件配置审计变更项 payload。"""
- key: str
- label: object
- secret: bool
- before: object
- after: object
+ key: str = Field(description='配置项的键')
+ label: object = Field(description='面向用户的显示名称')
+ secret: bool = Field(description='是否包含敏感值')
+ before: object = Field(description='变更前的配置值')
+ after: object = Field(description='变更后的配置值')
class PluginConfigAuditSummaryPayload(PluginPayloadModel):
- """
- 插件配置审计摘要 payload。
- """
+ """插件配置审计摘要 payload。"""
- changed_count: int = Field(alias='changedCount')
- changed_keys: list[str] = Field(alias='changedKeys')
- changes: list[dict[str, object]]
+ changed_count: int = Field(alias='changedCount', description='已变更的配置项数')
+ changed_keys: list[str] = Field(alias='changedKeys', description='本次变更的配置键')
+ changes: list[dict[str, object]] = Field(description='逐项记录的配置变更')
class PluginConfigAuditPayload(PluginPayloadModel):
- """
- 插件配置审计 payload。
- """
+ """插件配置审计 payload。"""
- ok: bool
- operation: str
- plugin_id: str = Field(alias='pluginId')
- message: str
- summary: dict[str, object]
+ ok: bool = Field(description='本次操作是否成功')
+ operation: str = Field(description='执行的操作类型')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ message: str = Field(description='面向调用方的结果说明')
+ summary: dict[str, object] = Field(description='操作结果摘要')
PluginConfigStatePayloadDict: TypeAlias = dict[str, object]
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/dependencies.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/dependencies.py
index 85540bb0d..82e9a7356 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/dependencies.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/dependencies.py
@@ -12,30 +12,28 @@
class PluginDependencyInstallPayload(PluginPayloadModel):
- """
- 插件依赖安装 payload。
- """
-
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- dependency_ok: bool = Field(alias='dependencyOk')
- dependencies: list[dict[str, object]]
- missing_dependencies: list[str] = Field(alias='missingDependencies')
- unsatisfied_dependencies: list[str] = Field(alias='unsatisfiedDependencies')
- dry_run: bool = Field(alias='dryRun')
- plan: list[dict[str, object]]
- plan_count: int = Field(alias='planCount')
- results: list[dict[str, object]] | None = None
- policy: dict[str, object] | None = None
+ """插件依赖安装 payload。"""
+
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ dependency_ok: bool = Field(alias='dependencyOk', description='软件包依赖是否满足要求')
+ dependencies: list[dict[str, object]] = Field(description='软件包依赖及其检查结果')
+ missing_dependencies: list[str] = Field(alias='missingDependencies', description='尚未安装的依赖')
+ unsatisfied_dependencies: list[str] = Field(
+ alias='unsatisfiedDependencies', description='已安装但不满足版本要求的依赖'
+ )
+ dry_run: bool = Field(alias='dryRun', description='是否仅预演本次操作')
+ plan: list[dict[str, object]] = Field(description='预定执行的操作计划')
+ plan_count: int = Field(alias='planCount', description='计划中的安装操作数')
+ results: list[dict[str, object]] | None = Field(default=None, description='各项依赖的安装结果')
+ policy: dict[str, object] | None = Field(default=None, description='安装插件依赖时采用的策略')
class DependencyInstallReturnCode(PluginPayloadModel):
- """
- 依赖安装命令返回码 payload。
- """
+ """依赖安装命令返回码 payload。"""
- return_code: int = Field(alias='returnCode')
+ return_code: int = Field(alias='returnCode', description='子进程退出码')
PluginDependencyInstallPayloadDict: TypeAlias = dict[str, object]
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/documentation.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/documentation.py
index 3a556c13d..31a229829 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/documentation.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/documentation.py
@@ -10,16 +10,14 @@
class PluginDocumentationPayload(PluginPayloadModel):
- """
- 插件文档生成 payload。
- """
-
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- format: Literal['markdown']
- markdown: str
- length: int
+ """插件文档生成 payload。"""
+
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ format: Literal['markdown'] = Field(description='文档内容格式')
+ markdown: str = Field(description='插件文档的 Markdown 正文')
+ length: int = Field(description='文档内容长度')
PluginDocumentationPayloadDict: TypeAlias = dict[str, object]
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/enable.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/enable.py
index 285e365ee..7f89f1341 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/enable.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/enable.py
@@ -11,76 +11,88 @@
class PluginEnableDependencyPayload(PluginPayloadModel):
- """
- 插件启停依赖检查 payload。
- """
+ """插件启停依赖检查 payload。"""
- plugin_dependency_ok: bool = Field(alias='pluginDependencyOk')
- plugin_dependency_errors: list[dict[str, object]] = Field(alias='pluginDependencyErrors')
- plugin_dependencies: list[dict[str, object]] = Field(alias='pluginDependencies')
+ plugin_dependency_ok: bool = Field(alias='pluginDependencyOk', description='依赖的其他插件是否满足要求')
+ plugin_dependency_errors: list[dict[str, object]] = Field(
+ alias='pluginDependencyErrors', description='插件之间的依赖检查错误'
+ )
+ plugin_dependencies: list[dict[str, object]] = Field(
+ alias='pluginDependencies', description='插件之间的依赖及其状态'
+ )
class PluginEnableStatePayload(PluginPayloadModel):
- """
- 插件启停状态 payload。
- """
-
- ok: bool
- message: object
- plugin_id: str = Field(alias='pluginId')
- operation: str
- enabled: bool
- dry_run: bool = Field(alias='dryRun')
- actions: list[dict[str, object]]
- plugin_dependency_ok: object | None = Field(default=None, alias='pluginDependencyOk')
- plugin_dependency_errors: object | None = Field(default=None, alias='pluginDependencyErrors')
- plugin_dependencies: object | None = Field(default=None, alias='pluginDependencies')
+ """插件启停状态 payload。"""
+
+ ok: bool = Field(description='本次操作是否成功')
+ message: object = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ operation: str = Field(description='执行的操作类型')
+ enabled: bool = Field(description='是否启用')
+ dry_run: bool = Field(alias='dryRun', description='是否仅预演本次操作')
+ actions: list[dict[str, object]] = Field(description='待执行或已执行的操作明细')
+ plugin_dependency_ok: object | None = Field(
+ default=None, alias='pluginDependencyOk', description='依赖的其他插件是否满足要求'
+ )
+ plugin_dependency_errors: object | None = Field(
+ default=None, alias='pluginDependencyErrors', description='插件之间的依赖检查错误'
+ )
+ plugin_dependencies: object | None = Field(
+ default=None, alias='pluginDependencies', description='插件之间的依赖及其状态'
+ )
class PluginEnableUpdateFailurePayload(PluginPayloadModel):
- """
- 插件启停写入失败 payload。
- """
+ """插件启停写入失败 payload。"""
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- operation: str
- enabled: bool
- dry_run: bool = Field(alias='dryRun')
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ operation: str = Field(description='执行的操作类型')
+ enabled: bool = Field(description='是否启用')
+ dry_run: bool = Field(alias='dryRun', description='是否仅预演本次操作')
class PluginSafeUninstallPayload(PluginPayloadModel):
- """
- 插件安全卸载 payload。
- """
-
- ok: object | None = None
- message: object | None = None
- plugin_id: object | None = Field(default=None, alias='pluginId')
- operation: str
- enabled: bool | None = None
- dry_run: bool | None = Field(default=None, alias='dryRun')
- safe_mode: bool = Field(alias='safeMode')
- removes_source: bool = Field(alias='removesSource')
- removes_menus: bool = Field(alias='removesMenus')
- actions: list[dict[str, object]] | None = None
- precheck: dict[str, object] | None = None
- manifest_ok: object | None = Field(default=None, alias='manifestOk')
- dependency_ok: object | None = Field(default=None, alias='dependencyOk')
- plugin_dependency_ok: object | None = Field(default=None, alias='pluginDependencyOk')
- structure_ok: object | None = Field(default=None, alias='structureOk')
- menu_conflict_ok: object | None = Field(default=None, alias='menuConflictOk')
- manifest_issues: object | None = Field(default=None, alias='manifestIssues')
- manifest_warnings: object | None = Field(default=None, alias='manifestWarnings')
- plugin_dependency_errors: object | None = Field(default=None, alias='pluginDependencyErrors')
- structure_errors: object | None = Field(default=None, alias='structureErrors')
- menu_conflicts: object | None = Field(default=None, alias='menuConflicts')
- dependencies: object | None = None
- plugin_dependencies: object | None = Field(default=None, alias='pluginDependencies')
- error: object | None = None
- failed_step: str | None = Field(default=None, alias='failedStep')
- capability: dict[str, object] | None = None
+ """插件安全卸载 payload。"""
+
+ ok: object | None = Field(default=None, description='本次操作是否成功')
+ message: object | None = Field(default=None, description='面向调用方的结果说明')
+ plugin_id: object | None = Field(default=None, alias='pluginId', description='插件标识')
+ operation: str = Field(description='执行的操作类型')
+ enabled: bool | None = Field(default=None, description='是否启用')
+ dry_run: bool | None = Field(default=None, alias='dryRun', description='是否仅预演本次操作')
+ safe_mode: bool = Field(alias='safeMode', description='是否使用安全操作模式')
+ removes_source: bool = Field(alias='removesSource', description='本次操作是否移除插件源码')
+ removes_menus: bool = Field(alias='removesMenus', description='本次操作是否移除插件菜单')
+ actions: list[dict[str, object]] | None = Field(default=None, description='待执行或已执行的操作明细')
+ precheck: dict[str, object] | None = Field(default=None, description='操作开始前的检查结果')
+ manifest_ok: object | None = Field(default=None, alias='manifestOk', description='插件清单是否通过校验')
+ dependency_ok: object | None = Field(default=None, alias='dependencyOk', description='软件包依赖是否满足要求')
+ plugin_dependency_ok: object | None = Field(
+ default=None, alias='pluginDependencyOk', description='依赖的其他插件是否满足要求'
+ )
+ structure_ok: object | None = Field(default=None, alias='structureOk', description='插件文件结构是否通过校验')
+ menu_conflict_ok: object | None = Field(
+ default=None, alias='menuConflictOk', description='插件是否通过菜单冲突检查'
+ )
+ manifest_issues: object | None = Field(default=None, alias='manifestIssues', description='插件清单中的错误')
+ manifest_warnings: object | None = Field(default=None, alias='manifestWarnings', description='插件清单中的警告')
+ plugin_dependency_errors: object | None = Field(
+ default=None, alias='pluginDependencyErrors', description='插件之间的依赖检查错误'
+ )
+ structure_errors: object | None = Field(
+ default=None, alias='structureErrors', description='插件目录或文件结构检查错误'
+ )
+ menu_conflicts: object | None = Field(default=None, alias='menuConflicts', description='检测到的菜单冲突')
+ dependencies: object | None = Field(default=None, description='软件包依赖及其检查结果')
+ plugin_dependencies: object | None = Field(
+ default=None, alias='pluginDependencies', description='插件之间的依赖及其状态'
+ )
+ error: object | None = Field(default=None, description='失败原因')
+ failed_step: str | None = Field(default=None, alias='failedStep', description='发生错误的操作步骤')
+ capability: dict[str, object] | None = Field(default=None, description='当前环境对该操作的支持情况')
PluginEnableDependencyPayloadDict: TypeAlias = dict[str, object]
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/lifecycle.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/lifecycle.py
index 54b799816..9f9d43fe7 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/lifecycle.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/lifecycle.py
@@ -19,6 +19,8 @@
class SupportsOk(Protocol):
"""
支持 ok 属性的检查结果协议。
+
+ :ivar ok: 操作或检查是否成功
"""
ok: bool
@@ -27,6 +29,16 @@ class SupportsOk(Protocol):
class PluginLifecyclePrecheckProtocol(Protocol):
"""
lifecycle payload 所需的预检上下文协议。
+
+ :ivar ok: 操作或检查是否成功
+ :ivar dependency_result: 依赖检查结果
+ :ivar manifest_result: manifest 非阻断检查结果
+ :ivar plugin_dependency_result: 插件间依赖检查结果
+ :ivar structure_result: 插件结构检查结果
+ :ivar menu_conflict_result: 菜单冲突检查结果
+ :ivar operation_payload: 描述当前操作的结构化数据
+ :ivar check_payload: 预检结果的结构化数据
+ :ivar menu_conflicts: 菜单冲突负载
"""
ok: bool
@@ -41,43 +53,53 @@ class PluginLifecyclePrecheckProtocol(Protocol):
class PluginLifecyclePayload(PluginPayloadModel):
- """
- 插件生命周期通用 payload。
- """
-
- ok: bool | None = None
- message: str | None = None
- plugin_id: str | None = Field(default=None, alias='pluginId')
- dry_run: bool | None = Field(default=None, alias='dryRun')
- operation: str | None = None
- actions: list[dict[str, object]] | None = None
- precheck: dict[str, object] | None = None
- plugin: dict[str, object] | None = None
- configs: list[dict[str, object]] | None = None
- migrations: list[dict[str, object]] | None = None
- seeds: list[dict[str, object]] | None = None
- hooks: list[dict[str, object]] | None = None
- menu_conflicts: list[dict[str, object]] | None = Field(default=None, alias='menuConflicts')
- menu_conflict_ok: object | None = Field(default=None, alias='menuConflictOk')
- manifest_ok: object | None = Field(default=None, alias='manifestOk')
- dependency_ok: object | None = Field(default=None, alias='dependencyOk')
- plugin_dependency_ok: object | None = Field(default=None, alias='pluginDependencyOk')
- structure_ok: object | None = Field(default=None, alias='structureOk')
- manifest_issues: object | None = Field(default=None, alias='manifestIssues')
- manifest_warnings: object | None = Field(default=None, alias='manifestWarnings')
- plugin_dependency_errors: object | None = Field(default=None, alias='pluginDependencyErrors')
- structure_errors: object | None = Field(default=None, alias='structureErrors')
- dependencies: object | None = None
- plugin_dependencies: object | None = Field(default=None, alias='pluginDependencies')
- installed: bool | None = None
- installed_version: str | None = Field(default=None, alias='installedVersion')
- current_version: str | None = Field(default=None, alias='currentVersion')
- needs_upgrade: bool | None = Field(default=None, alias='needsUpgrade')
- dependency_install: object | None = Field(default=None, alias='dependencyInstall')
- enabled: bool | None = None
- safe_mode: bool | None = Field(default=None, alias='safeMode')
- removes_source: bool | None = Field(default=None, alias='removesSource')
- plan: dict[str, object] | None = None
+ """插件生命周期通用 payload。"""
+
+ ok: bool | None = Field(default=None, description='本次操作是否成功')
+ message: str | None = Field(default=None, description='面向调用方的结果说明')
+ plugin_id: str | None = Field(default=None, alias='pluginId', description='插件标识')
+ dry_run: bool | None = Field(default=None, alias='dryRun', description='是否仅预演本次操作')
+ operation: str | None = Field(default=None, description='执行的操作类型')
+ actions: list[dict[str, object]] | None = Field(default=None, description='待执行或已执行的操作明细')
+ precheck: dict[str, object] | None = Field(default=None, description='操作开始前的检查结果')
+ plugin: dict[str, object] | None = Field(default=None, description='插件详情')
+ configs: list[dict[str, object]] | None = Field(default=None, description='插件配置项列表')
+ migrations: list[dict[str, object]] | None = Field(default=None, description='插件数据库迁移的执行信息')
+ seeds: list[dict[str, object]] | None = Field(default=None, description='插件初始数据的执行信息')
+ hooks: list[dict[str, object]] | None = Field(default=None, description='插件生命周期钩子的执行信息')
+ menu_conflicts: list[dict[str, object]] | None = Field(
+ default=None, alias='menuConflicts', description='检测到的菜单冲突'
+ )
+ menu_conflict_ok: object | None = Field(
+ default=None, alias='menuConflictOk', description='插件是否通过菜单冲突检查'
+ )
+ manifest_ok: object | None = Field(default=None, alias='manifestOk', description='插件清单是否通过校验')
+ dependency_ok: object | None = Field(default=None, alias='dependencyOk', description='软件包依赖是否满足要求')
+ plugin_dependency_ok: object | None = Field(
+ default=None, alias='pluginDependencyOk', description='依赖的其他插件是否满足要求'
+ )
+ structure_ok: object | None = Field(default=None, alias='structureOk', description='插件文件结构是否通过校验')
+ manifest_issues: object | None = Field(default=None, alias='manifestIssues', description='插件清单中的错误')
+ manifest_warnings: object | None = Field(default=None, alias='manifestWarnings', description='插件清单中的警告')
+ plugin_dependency_errors: object | None = Field(
+ default=None, alias='pluginDependencyErrors', description='插件之间的依赖检查错误'
+ )
+ structure_errors: object | None = Field(
+ default=None, alias='structureErrors', description='插件目录或文件结构检查错误'
+ )
+ dependencies: object | None = Field(default=None, description='软件包依赖及其检查结果')
+ plugin_dependencies: object | None = Field(
+ default=None, alias='pluginDependencies', description='插件之间的依赖及其状态'
+ )
+ installed: bool | None = Field(default=None, description='是否已经安装')
+ installed_version: str | None = Field(default=None, alias='installedVersion', description='已安装的版本')
+ current_version: str | None = Field(default=None, alias='currentVersion', description='当前发现的插件版本')
+ needs_upgrade: bool | None = Field(default=None, alias='needsUpgrade', description='是否需要升级已安装版本')
+ dependency_install: object | None = Field(default=None, alias='dependencyInstall', description='软件包依赖安装信息')
+ enabled: bool | None = Field(default=None, description='是否启用')
+ safe_mode: bool | None = Field(default=None, alias='safeMode', description='是否使用安全操作模式')
+ removes_source: bool | None = Field(default=None, alias='removesSource', description='本次操作是否移除插件源码')
+ plan: dict[str, object] | None = Field(default=None, description='预定执行的操作计划')
PluginLifecyclePayloadDict: TypeAlias = dict[str, object]
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/plan.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/plan.py
index 8d02c9ffc..88f6d69b5 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/plan.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/plan.py
@@ -25,191 +25,173 @@
class SupportsOk(Protocol):
"""
支持 ok 属性的检查结果协议。
+
+ :ivar ok: 操作或检查是否成功
"""
ok: bool
class PluginPlanBlockerPayload(PluginPayloadModel):
- """
- 插件批量操作计划阻塞项 payload。
- """
+ """插件批量操作计划阻塞项 payload。"""
- plugin_id: str = Field(alias='pluginId')
- dependency_id: str = Field(alias='dependencyId')
- status: str
- message: str
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ dependency_id: str = Field(alias='dependencyId', description='被依赖的插件标识')
+ status: str = Field(description='当前状态')
+ message: str = Field(description='面向调用方的结果说明')
class PluginPlanItemPayload(PluginPayloadModel):
- """
- 插件批量操作计划项 payload。
- """
-
- plugin_id: str = Field(alias='pluginId')
- name: str
- version: str
- operation: str
- order: int
- requested: bool
- dependencies: list[str]
- installed_version: str | None = Field(alias='installedVersion')
- enabled: str | None
- status: str | None
- ready: bool
- blockers: list[dict[str, object]]
+ """插件批量操作计划项 payload。"""
+
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ name: str = Field(description='插件名称')
+ version: str = Field(description='插件版本')
+ operation: str = Field(description='执行的操作类型')
+ order: int = Field(description='排列顺序')
+ requested: bool = Field(description='是否由本次请求显式指定')
+ dependencies: list[str] = Field(description='当前插件依赖的插件标识')
+ installed_version: str | None = Field(alias='installedVersion', description='已安装的版本')
+ enabled: str | None = Field(description='是否启用')
+ status: str | None = Field(description='当前状态')
+ ready: bool = Field(description='执行该计划项的前置条件是否已满足')
+ blockers: list[dict[str, object]] = Field(description='阻止执行计划的原因')
class PluginPlanPayload(PluginPayloadModel):
- """
- 插件批量操作拓扑计划 payload。
- """
+ """插件批量操作拓扑计划 payload。"""
- operation: str
- ok: bool
- requested_plugin_ids: list[str] = Field(alias='requestedPluginIds')
- ordered_plugin_ids: list[str] = Field(alias='orderedPluginIds')
- items: list[dict[str, object]]
- blockers: list[dict[str, object]]
- blocker_count: int = Field(alias='blockerCount')
+ operation: str = Field(description='执行的操作类型')
+ ok: bool = Field(description='本次操作是否成功')
+ requested_plugin_ids: list[str] = Field(alias='requestedPluginIds', description='调用方指定的插件标识列表')
+ ordered_plugin_ids: list[str] = Field(alias='orderedPluginIds', description='按执行顺序排列的插件标识列表')
+ items: list[dict[str, object]] = Field(description='结果条目列表')
+ blockers: list[dict[str, object]] = Field(description='阻止执行计划的原因')
+ blocker_count: int = Field(alias='blockerCount', description='阻止执行计划的问题数')
class PluginPlanResponsePayload(PluginPayloadModel):
- """
- 插件批量操作计划响应 payload。
- """
+ """插件批量操作计划响应 payload。"""
- ok: bool
- message: str
- operation: str
- database_available: bool = Field(alias='databaseAvailable')
- database_error: str | None = Field(alias='databaseError')
- plan: dict[str, object]
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ operation: str = Field(description='执行的操作类型')
+ database_available: bool = Field(alias='databaseAvailable', description='数据库是否可用')
+ database_error: str | None = Field(alias='databaseError', description='数据库访问失败的原因')
+ plan: dict[str, object] = Field(description='预定执行的操作计划')
class DependencyInstallPlanItemPayload(PluginPayloadModel):
- """
- 依赖安装计划项 payload。
- """
+ """依赖安装计划项 payload。"""
- kind: str
- requirement: str
- name: str
- command: list[str]
- command_text: str = Field(alias='commandText')
- workdir: str
- reason: str
- status: str
+ kind: str = Field(description='依赖使用的软件包管理方式')
+ requirement: str = Field(description='软件包依赖声明')
+ name: str = Field(description='待安装的软件包名称')
+ command: list[str] = Field(description='用于执行命令的参数列表')
+ command_text: str = Field(alias='commandText', description='供展示的命令文本')
+ workdir: str = Field(description='执行命令的工作目录')
+ reason: str = Field(description='安排该操作的原因')
+ status: str = Field(description='当前状态')
class DependencyInstallResultPayload(PluginPayloadModel):
- """
- 依赖安装执行结果 payload。
- """
+ """依赖安装执行结果 payload。"""
- kind: str
- requirement: str
- name: str
- command: list[str]
- command_text: str = Field(alias='commandText')
- workdir: str
- return_code: int = Field(alias='returnCode')
- stdout: str
- stderr: str
+ kind: str = Field(description='依赖使用的软件包管理方式')
+ requirement: str = Field(description='软件包依赖声明')
+ name: str = Field(description='执行安装的软件包名称')
+ command: list[str] = Field(description='用于执行命令的参数列表')
+ command_text: str = Field(alias='commandText', description='供展示的命令文本')
+ workdir: str = Field(description='执行命令的工作目录')
+ return_code: int = Field(alias='returnCode', description='子进程退出码')
+ stdout: str = Field(description='命令的标准输出')
+ stderr: str = Field(description='命令的标准错误输出')
class CommandResultPayload(PluginPayloadModel):
- """
- 系统命令执行结果 payload。
- """
+ """系统命令执行结果 payload。"""
- return_code: int = Field(alias='returnCode')
- stdout: str
- stderr: str
+ return_code: int = Field(alias='returnCode', description='子进程退出码')
+ stdout: str = Field(description='命令的标准输出')
+ stderr: str = Field(description='命令的标准错误输出')
class PurgePlanItemPayload(PluginPayloadModel):
- """
- 插件物理清理计划项 payload。
- """
+ """插件物理清理计划项 payload。"""
- name: str
- label: str
- enabled: bool
- destructive: bool
- count: int | None
- target: str | None
+ name: str = Field(description='清理操作名称')
+ label: str = Field(description='面向用户的显示名称')
+ enabled: bool = Field(description='是否启用')
+ destructive: bool = Field(description='是否会删除已有数据或资源')
+ count: int | None = Field(description='结果条数')
+ target: str | None = Field(description='本项操作的目标')
class PurgePlanPayload(PluginPayloadModel):
- """
- 插件物理清理计划 payload。
- """
+ """插件物理清理计划 payload。"""
- plugin_id: str = Field(alias='pluginId')
- removes_source: bool = Field(alias='removesSource')
- requires_hook: bool = Field(alias='requiresHook')
- destructive_count: int = Field(alias='destructiveCount')
- items: list[dict[str, object]]
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ removes_source: bool = Field(alias='removesSource', description='本次操作是否移除插件源码')
+ requires_hook: bool = Field(alias='requiresHook', description='是否需要运行清理钩子')
+ destructive_count: int = Field(alias='destructiveCount', description='涉及删除已有数据或资源的操作数')
+ items: list[dict[str, object]] = Field(description='结果条目列表')
class ActionPayload(PluginPayloadModel):
- """
- 插件操作动作项 payload。
- """
+ """插件操作动作项 payload。"""
- name: str | None = None
- label: str | None = None
- enabled: bool | None = None
- count: int | None = None
- ok: bool | None = None
- hook: str | None = None
- target_enabled: bool | None = Field(default=None, alias='targetEnabled')
- target_status: str | None = Field(default=None, alias='targetStatus')
+ name: str | None = Field(default=None, description='操作名称')
+ label: str | None = Field(default=None, description='面向用户的显示名称')
+ enabled: bool | None = Field(default=None, description='是否启用')
+ count: int | None = Field(default=None, description='结果条数')
+ ok: bool | None = Field(default=None, description='本次操作是否成功')
+ hook: str | None = Field(default=None, description='本项操作调用的生命周期钩子')
+ target_enabled: bool | None = Field(default=None, alias='targetEnabled', description='操作后期望的启用状态')
+ target_status: str | None = Field(default=None, alias='targetStatus', description='操作后期望达到的状态')
class VersionStatePayload(PluginPayloadModel):
- """
- 插件升级版本状态 payload。
- """
+ """插件升级版本状态 payload。"""
- installed: bool
- installed_version: str | None = Field(alias='installedVersion')
- current_version: str = Field(alias='currentVersion')
- needs_upgrade: bool = Field(alias='needsUpgrade')
+ installed: bool = Field(description='是否已经安装')
+ installed_version: str | None = Field(alias='installedVersion', description='已安装的版本')
+ current_version: str = Field(alias='currentVersion', description='当前发现的插件版本')
+ needs_upgrade: bool = Field(alias='needsUpgrade', description='是否需要升级已安装版本')
UpgradeDryRunPayloadContext: TypeAlias = dict[str, object]
class UpgradeDryRunPayload(PluginPayloadModel):
- """
- 插件升级 dry-run payload。
- """
-
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- dry_run: bool = Field(alias='dryRun')
- installed: bool
- installed_version: str | None = Field(alias='installedVersion')
- current_version: str = Field(alias='currentVersion')
- needs_upgrade: bool = Field(alias='needsUpgrade')
- database_available: bool = Field(alias='databaseAvailable')
- database_error: str | None = Field(alias='databaseError')
- dependency_ok: bool = Field(alias='dependencyOk')
- manifest_ok: bool = Field(alias='manifestOk')
- plugin_dependency_ok: bool = Field(alias='pluginDependencyOk')
- structure_ok: bool = Field(alias='structureOk')
- menu_conflict_ok: bool = Field(alias='menuConflictOk')
- actions: list[dict[str, object]]
- manifest_issues: list[dict[str, object]] = Field(alias='manifestIssues')
- manifest_warnings: list[dict[str, object]] = Field(alias='manifestWarnings')
- plugin_dependency_errors: list[dict[str, object]] = Field(alias='pluginDependencyErrors')
- structure_errors: list[dict[str, object]] = Field(alias='structureErrors')
- menu_conflicts: list[dict[str, object]] = Field(alias='menuConflicts')
- dependencies: list[dict[str, object]]
- plugin_dependencies: list[dict[str, object]] = Field(alias='pluginDependencies')
+ """插件升级 dry-run payload。"""
+
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ dry_run: bool = Field(alias='dryRun', description='是否仅预演本次操作')
+ installed: bool = Field(description='是否已经安装')
+ installed_version: str | None = Field(alias='installedVersion', description='已安装的版本')
+ current_version: str = Field(alias='currentVersion', description='当前发现的插件版本')
+ needs_upgrade: bool = Field(alias='needsUpgrade', description='是否需要升级已安装版本')
+ database_available: bool = Field(alias='databaseAvailable', description='数据库是否可用')
+ database_error: str | None = Field(alias='databaseError', description='数据库访问失败的原因')
+ dependency_ok: bool = Field(alias='dependencyOk', description='软件包依赖是否满足要求')
+ manifest_ok: bool = Field(alias='manifestOk', description='插件清单是否通过校验')
+ plugin_dependency_ok: bool = Field(alias='pluginDependencyOk', description='依赖的其他插件是否满足要求')
+ structure_ok: bool = Field(alias='structureOk', description='插件文件结构是否通过校验')
+ menu_conflict_ok: bool = Field(alias='menuConflictOk', description='插件是否通过菜单冲突检查')
+ actions: list[dict[str, object]] = Field(description='待执行或已执行的操作明细')
+ manifest_issues: list[dict[str, object]] = Field(alias='manifestIssues', description='插件清单中的错误')
+ manifest_warnings: list[dict[str, object]] = Field(alias='manifestWarnings', description='插件清单中的警告')
+ plugin_dependency_errors: list[dict[str, object]] = Field(
+ alias='pluginDependencyErrors', description='插件之间的依赖检查错误'
+ )
+ structure_errors: list[dict[str, object]] = Field(alias='structureErrors', description='插件目录或文件结构检查错误')
+ menu_conflicts: list[dict[str, object]] = Field(alias='menuConflicts', description='检测到的菜单冲突')
+ dependencies: list[dict[str, object]] = Field(description='软件包依赖及其检查结果')
+ plugin_dependencies: list[dict[str, object]] = Field(
+ alias='pluginDependencies', description='插件之间的依赖及其状态'
+ )
PluginPlanPayloadDict: TypeAlias = dict[str, object]
@@ -217,9 +199,7 @@ class UpgradeDryRunPayload(PluginPayloadModel):
class PluginPlanPayloadMixin:
- """
- 插件依赖拓扑、执行动作和物理清理计划负载构建能力。
- """
+ """插件依赖拓扑、执行动作和物理清理计划负载构建能力。"""
@staticmethod
def build_plugin_plan_blocker(item: PluginDependencyPlanBlocker) -> PluginPlanBlockerPayload:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/purge.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/purge.py
index edb05e028..537657301 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/purge.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/purge.py
@@ -10,19 +10,17 @@
class PluginPurgeStatePayload(PluginPayloadModel):
- """
- 插件物理清理状态 payload。
- """
-
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- operation: str
- dry_run: bool = Field(alias='dryRun')
- safe_mode: bool = Field(alias='safeMode')
- removes_source: bool = Field(alias='removesSource')
- plan: dict[str, object]
- hooks: list[dict[str, object]] | None = None
+ """插件物理清理状态 payload。"""
+
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ operation: str = Field(description='执行的操作类型')
+ dry_run: bool = Field(alias='dryRun', description='是否仅预演本次操作')
+ safe_mode: bool = Field(alias='safeMode', description='是否使用安全操作模式')
+ removes_source: bool = Field(alias='removesSource', description='本次操作是否移除插件源码')
+ plan: dict[str, object] = Field(description='预定执行的操作计划')
+ hooks: list[dict[str, object]] | None = Field(default=None, description='插件生命周期钩子的执行信息')
PluginPurgeStatePayloadDict: TypeAlias = dict[str, object]
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/runtime.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/runtime.py
index 32e7de808..a2230fdbd 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/runtime.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/runtime.py
@@ -19,6 +19,8 @@
class SupportsOk(Protocol):
"""
支持 ok 属性的检查结果协议。
+
+ :ivar ok: 操作或检查是否成功
"""
ok: bool
@@ -27,6 +29,15 @@ class SupportsOk(Protocol):
class PluginRuntimePrecheckProtocol(Protocol):
"""
runtime payload 所需的预检上下文协议。
+
+ :ivar ok: 操作或检查是否成功
+ :ivar dependency_result: 依赖检查结果
+ :ivar manifest_result: manifest 非阻断检查结果
+ :ivar plugin_dependency_result: 插件间依赖检查结果
+ :ivar structure_result: 插件结构检查结果
+ :ivar menu_conflict_result: 菜单冲突检查结果
+ :ivar operation_payload: 描述当前操作的结构化数据
+ :ivar check_payload: 插件检查负载
"""
ok: bool
@@ -42,6 +53,15 @@ class PluginRuntimePrecheckProtocol(Protocol):
class PluginHealthResultProtocol(Protocol):
"""
runtime 健康检查结果协议。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar ok: 操作或检查是否成功
+ :ivar status: 操作或记录所处的状态
+ :ivar message: 与当前结果一起返回的说明
+ :ivar checker: 用于取得或验证健康状态的检查器
+ :ivar duration_ms: 健康检查实际耗用的毫秒数
+ :ivar details: 用于诊断健康状态的详情
+ :ivar error: 异常对象
"""
plugin_id: str
@@ -55,150 +75,162 @@ class PluginHealthResultProtocol(Protocol):
class PluginRuntimeDiagnosePayload(PluginPayloadModel):
- """
- 插件诊断包 payload。
- """
+ """插件诊断包 payload。"""
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- info: object
- check: dict[str, object]
- menu_plan: dict[str, object] = Field(alias='menuPlan')
- config: dict[str, object]
- audit: dict[str, object]
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ info: object = Field(description='插件的基本信息')
+ check: dict[str, object] = Field(description='插件检查结果')
+ menu_plan: dict[str, object] = Field(alias='menuPlan', description='注册插件菜单的计划')
+ config: dict[str, object] = Field(description='插件配置信息')
+ audit: dict[str, object] = Field(description='插件的操作审计信息')
class PluginRuntimeHealthPayload(PluginPayloadModel):
- """
- 插件健康检查 payload。
- """
+ """插件健康检查 payload。"""
- plugin_id: str = Field(alias='pluginId')
- ok: bool
- status: str
- message: str
- checker: str | None
- duration_ms: float = Field(alias='durationMs')
- details: object
- error: str | None
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ ok: bool = Field(description='本次操作是否成功')
+ status: str = Field(description='当前状态')
+ message: str = Field(description='面向调用方的结果说明')
+ checker: str | None = Field(description='执行健康检查的组件')
+ duration_ms: float = Field(alias='durationMs', description='本次操作耗时(毫秒)')
+ details: object = Field(description='健康检查的详细结果')
+ error: str | None = Field(description='失败原因')
class PluginRuntimeHealthResponsePayload(PluginPayloadModel):
- """
- 插件健康检查响应 payload。
- """
+ """插件健康检查响应 payload。"""
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- health: dict[str, object]
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ health: dict[str, object] = Field(description='插件健康状态和诊断结果')
class PluginRuntimePrecheckPayload(PluginPayloadModel):
- """
- 插件操作预检 payload。
- """
-
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- operation: str
- database_available: bool = Field(alias='databaseAvailable')
- database_error: str | None = Field(alias='databaseError')
- purge_plan_error: str | None = Field(default=None, alias='purgePlanError')
- installed: bool | None = None
- installed_version: str | None = Field(default=None, alias='installedVersion')
- current_version: str | None = Field(default=None, alias='currentVersion')
- needs_upgrade: bool | None = Field(default=None, alias='needsUpgrade')
- manifest_ok: bool | None = Field(default=None, alias='manifestOk')
- dependency_ok: bool | None = Field(default=None, alias='dependencyOk')
- plugin_dependency_ok: bool | None = Field(default=None, alias='pluginDependencyOk')
- structure_ok: bool | None = Field(default=None, alias='structureOk')
- menu_conflict_ok: bool | None = Field(default=None, alias='menuConflictOk')
- manifest_issues: list[dict[str, object]] | None = Field(default=None, alias='manifestIssues')
- manifest_warnings: list[dict[str, object]] | None = Field(default=None, alias='manifestWarnings')
- plugin_dependency_errors: list[dict[str, object]] | None = Field(default=None, alias='pluginDependencyErrors')
- structure_errors: list[dict[str, object]] | None = Field(default=None, alias='structureErrors')
- menu_conflicts: list[dict[str, object]] | None = Field(default=None, alias='menuConflicts')
- dependencies: list[dict[str, object]] | None = None
- plugin_dependencies: list[dict[str, object]] | None = Field(default=None, alias='pluginDependencies')
- actions: list[dict[str, object]]
- precheck: dict[str, object]
- plan: dict[str, object] | None = None
+ """插件操作预检 payload。"""
+
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ operation: str = Field(description='执行的操作类型')
+ database_available: bool = Field(alias='databaseAvailable', description='数据库是否可用')
+ database_error: str | None = Field(alias='databaseError', description='数据库访问失败的原因')
+ purge_plan_error: str | None = Field(default=None, alias='purgePlanError', description='无法生成清理计划的原因')
+ installed: bool | None = Field(default=None, description='是否已经安装')
+ installed_version: str | None = Field(default=None, alias='installedVersion', description='已安装的版本')
+ current_version: str | None = Field(default=None, alias='currentVersion', description='当前发现的插件版本')
+ needs_upgrade: bool | None = Field(default=None, alias='needsUpgrade', description='是否需要升级已安装版本')
+ manifest_ok: bool | None = Field(default=None, alias='manifestOk', description='插件清单是否通过校验')
+ dependency_ok: bool | None = Field(default=None, alias='dependencyOk', description='软件包依赖是否满足要求')
+ plugin_dependency_ok: bool | None = Field(
+ default=None, alias='pluginDependencyOk', description='依赖的其他插件是否满足要求'
+ )
+ structure_ok: bool | None = Field(default=None, alias='structureOk', description='插件文件结构是否通过校验')
+ menu_conflict_ok: bool | None = Field(default=None, alias='menuConflictOk', description='插件是否通过菜单冲突检查')
+ manifest_issues: list[dict[str, object]] | None = Field(
+ default=None, alias='manifestIssues', description='插件清单中的错误'
+ )
+ manifest_warnings: list[dict[str, object]] | None = Field(
+ default=None, alias='manifestWarnings', description='插件清单中的警告'
+ )
+ plugin_dependency_errors: list[dict[str, object]] | None = Field(
+ default=None, alias='pluginDependencyErrors', description='插件之间的依赖检查错误'
+ )
+ structure_errors: list[dict[str, object]] | None = Field(
+ default=None, alias='structureErrors', description='插件目录或文件结构检查错误'
+ )
+ menu_conflicts: list[dict[str, object]] | None = Field(
+ default=None, alias='menuConflicts', description='检测到的菜单冲突'
+ )
+ dependencies: list[dict[str, object]] | None = Field(default=None, description='软件包依赖及其检查结果')
+ plugin_dependencies: list[dict[str, object]] | None = Field(
+ default=None, alias='pluginDependencies', description='插件之间的依赖及其状态'
+ )
+ actions: list[dict[str, object]] = Field(description='待执行或已执行的操作明细')
+ precheck: dict[str, object] = Field(description='操作开始前的检查结果')
+ plan: dict[str, object] | None = Field(default=None, description='预定执行的操作计划')
class PluginRuntimeExceptionPayload(PluginPayloadModel):
- """
- 插件运行时异常 payload。
- """
+ """插件运行时异常 payload。"""
- ok: bool
- message: str
- error: str
- plugin_id: str | None = Field(default=None, alias='pluginId')
- failed_step: str | None = Field(default=None, alias='failedStep')
- migration_recovery: object | None = Field(default=None, alias='migrationRecovery')
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ error: str = Field(description='失败原因')
+ plugin_id: str | None = Field(default=None, alias='pluginId', description='插件标识')
+ failed_step: str | None = Field(default=None, alias='failedStep', description='发生错误的操作步骤')
+ migration_recovery: object | None = Field(
+ default=None, alias='migrationRecovery', description='迁移失败后的恢复信息'
+ )
class PluginRuntimeInvalidOperationPayload(PluginPayloadModel):
- """
- 插件非法操作 payload。
- """
+ """插件非法操作 payload。"""
- ok: bool
- message: str
- operation: str
- plugin_id: str | None = Field(default=None, alias='pluginId')
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ operation: str = Field(description='执行的操作类型')
+ plugin_id: str | None = Field(default=None, alias='pluginId', description='插件标识')
class PluginRuntimeBatchItemUnsupportedPayload(PluginPayloadModel):
- """
- 插件批量单项不支持 payload。
- """
+ """插件批量单项不支持 payload。"""
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
class PluginRuntimeDiagnoseFailurePayload(PluginPayloadModel):
- """
- 插件诊断包失败 payload。
- """
+ """插件诊断包失败 payload。"""
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- info: dict[str, object]
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ info: dict[str, object] = Field(description='插件的基本信息')
class PluginRuntimeUpgradeBlockerPayload(PluginPayloadModel):
- """
- 插件升级前置阻断 payload。
- """
-
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- dry_run: bool = Field(alias='dryRun')
- installed: bool
- installed_version: str | None = Field(alias='installedVersion')
- current_version: str = Field(alias='currentVersion')
- needs_upgrade: bool = Field(alias='needsUpgrade')
- manifest_ok: bool = Field(alias='manifestOk')
- dependency_ok: bool = Field(alias='dependencyOk')
- plugin_dependency_ok: bool | None = Field(default=None, alias='pluginDependencyOk')
- structure_ok: bool | None = Field(default=None, alias='structureOk')
- menu_conflict_ok: bool | None = Field(default=None, alias='menuConflictOk')
- manifest_issues: list[dict[str, object]] | None = Field(default=None, alias='manifestIssues')
- manifest_warnings: list[dict[str, object]] | None = Field(default=None, alias='manifestWarnings')
- plugin_dependency_errors: list[dict[str, object]] | None = Field(default=None, alias='pluginDependencyErrors')
- structure_errors: list[dict[str, object]] | None = Field(default=None, alias='structureErrors')
- menu_conflicts: list[dict[str, object]] | None = Field(default=None, alias='menuConflicts')
- dependencies: list[dict[str, object]] | None = None
- plugin_dependencies: list[dict[str, object]] | None = Field(default=None, alias='pluginDependencies')
- actions: list[dict[str, object]]
+ """插件升级前置阻断 payload。"""
+
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ dry_run: bool = Field(alias='dryRun', description='是否仅预演本次操作')
+ installed: bool = Field(description='是否已经安装')
+ installed_version: str | None = Field(alias='installedVersion', description='已安装的版本')
+ current_version: str = Field(alias='currentVersion', description='当前发现的插件版本')
+ needs_upgrade: bool = Field(alias='needsUpgrade', description='是否需要升级已安装版本')
+ manifest_ok: bool = Field(alias='manifestOk', description='插件清单是否通过校验')
+ dependency_ok: bool = Field(alias='dependencyOk', description='软件包依赖是否满足要求')
+ plugin_dependency_ok: bool | None = Field(
+ default=None, alias='pluginDependencyOk', description='依赖的其他插件是否满足要求'
+ )
+ structure_ok: bool | None = Field(default=None, alias='structureOk', description='插件文件结构是否通过校验')
+ menu_conflict_ok: bool | None = Field(default=None, alias='menuConflictOk', description='插件是否通过菜单冲突检查')
+ manifest_issues: list[dict[str, object]] | None = Field(
+ default=None, alias='manifestIssues', description='插件清单中的错误'
+ )
+ manifest_warnings: list[dict[str, object]] | None = Field(
+ default=None, alias='manifestWarnings', description='插件清单中的警告'
+ )
+ plugin_dependency_errors: list[dict[str, object]] | None = Field(
+ default=None, alias='pluginDependencyErrors', description='插件之间的依赖检查错误'
+ )
+ structure_errors: list[dict[str, object]] | None = Field(
+ default=None, alias='structureErrors', description='插件目录或文件结构检查错误'
+ )
+ menu_conflicts: list[dict[str, object]] | None = Field(
+ default=None, alias='menuConflicts', description='检测到的菜单冲突'
+ )
+ dependencies: list[dict[str, object]] | None = Field(default=None, description='软件包依赖及其检查结果')
+ plugin_dependencies: list[dict[str, object]] | None = Field(
+ default=None, alias='pluginDependencies', description='插件之间的依赖及其状态'
+ )
+ actions: list[dict[str, object]] = Field(description='待执行或已执行的操作明细')
PluginRuntimeDiagnosePayloadDict: TypeAlias = dict[str, object]
@@ -213,9 +245,7 @@ class PluginRuntimeUpgradeBlockerPayload(PluginPayloadModel):
class PluginRuntimePayloadBuilder:
- """
- 插件运行时通用负载构建器。
- """
+ """插件运行时通用负载构建器。"""
@staticmethod
def build_exception_payload(
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/validation.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/validation.py
index ec86015fb..076a457ab 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/validation.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/validation.py
@@ -13,129 +13,133 @@
class DependencyItemPayload(PluginPayloadModel):
- """
- Python/npm 依赖检查项 payload。
- """
-
- kind: str
- requirement: str
- name: str
- installed: bool
- version_satisfied: bool = Field(alias='versionSatisfied')
- installed_version: str | None = Field(alias='installedVersion')
- declared_version: str | None = Field(default=None, alias='declaredVersion')
- required_version: str | None = Field(alias='requiredVersion')
- ok: bool
- status: str
- level: ValidationLevel
- message: str
+ """Python/npm 依赖检查项 payload。"""
+
+ kind: str = Field(description='依赖使用的软件包管理方式')
+ requirement: str = Field(description='软件包依赖声明')
+ name: str = Field(description='软件包名称')
+ installed: bool = Field(description='是否已经安装')
+ version_satisfied: bool = Field(alias='versionSatisfied', description='已安装版本是否满足约束')
+ installed_version: str | None = Field(alias='installedVersion', description='已安装的版本')
+ declared_version: str | None = Field(default=None, alias='declaredVersion', description='依赖声明中的版本')
+ required_version: str | None = Field(alias='requiredVersion', description='所需的版本约束')
+ ok: bool = Field(description='本次操作是否成功')
+ status: str = Field(description='当前状态')
+ level: ValidationLevel = Field(description='问题严重程度')
+ message: str = Field(description='面向调用方的结果说明')
class PluginDependencyItemPayload(PluginPayloadModel):
- """
- 插件间依赖检查项 payload。
- """
+ """插件间依赖检查项 payload。"""
- plugin_id: str = Field(alias='pluginId')
- dependency_id: str = Field(alias='dependencyId')
- required_version: str | None = Field(alias='requiredVersion')
- installed_version: str | None = Field(alias='installedVersion')
- status: str
- ok: bool
- level: ValidationLevel
- message: str
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ dependency_id: str = Field(alias='dependencyId', description='被依赖的插件标识')
+ required_version: str | None = Field(alias='requiredVersion', description='所需的版本约束')
+ installed_version: str | None = Field(alias='installedVersion', description='已安装的版本')
+ status: str = Field(description='当前状态')
+ ok: bool = Field(description='本次操作是否成功')
+ level: ValidationLevel = Field(description='问题严重程度')
+ message: str = Field(description='面向调用方的结果说明')
class ValidationIssuePayload(PluginPayloadModel):
- """
- manifest 校验问题项 payload。
- """
+ """manifest 校验问题项 payload。"""
- level: ValidationLevel
- category: str
- kind: str
- path: str
- ok: bool
- message: str
- suggestion: str
+ level: ValidationLevel = Field(description='问题严重程度')
+ category: str = Field(description='校验问题的分类')
+ kind: str = Field(description='项目类别')
+ path: str = Field(description='文件或资源路径')
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ suggestion: str = Field(description='建议的后续处理方式')
class StructureItemPayload(PluginPayloadModel):
- """
- 插件结构检查项 payload。
- """
+ """插件结构检查项 payload。"""
- kind: str
- path: str
- ok: bool
- level: ValidationLevel
- message: str
- suggestion: str
+ kind: str = Field(description='项目类别')
+ path: str = Field(description='文件或资源路径')
+ ok: bool = Field(description='本次操作是否成功')
+ level: ValidationLevel = Field(description='问题严重程度')
+ message: str = Field(description='面向调用方的结果说明')
+ suggestion: str = Field(description='建议的后续处理方式')
class MenuConflictItemPayload(PluginPayloadModel):
- """
- 菜单冲突检查项 payload。
- """
+ """菜单冲突检查项 payload。"""
- kind: str
- plugin_id: str = Field(alias='pluginId')
- conflict_plugin_id: str | None = Field(alias='conflictPluginId')
- value: str
- ok: bool
- level: ValidationLevel
- message: str
+ kind: str = Field(description='项目类别')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ conflict_plugin_id: str | None = Field(alias='conflictPluginId', description='与当前插件冲突的插件标识')
+ value: str = Field(description='引发冲突的实际值')
+ ok: bool = Field(description='本次操作是否成功')
+ level: ValidationLevel = Field(description='问题严重程度')
+ message: str = Field(description='面向调用方的结果说明')
class PluginDependencyCheckPayload(PluginPayloadModel):
- """
- 插件依赖检查 payload。
- """
+ """插件依赖检查 payload。"""
- ok: bool
- message: str
- plugin_id: str = Field(alias='pluginId')
- dependency_ok: bool = Field(alias='dependencyOk')
- dependencies: list[dict[str, object]]
- missing_dependencies: list[str] = Field(alias='missingDependencies')
- unsatisfied_dependencies: list[str] = Field(alias='unsatisfiedDependencies')
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ dependency_ok: bool = Field(alias='dependencyOk', description='软件包依赖是否满足要求')
+ dependencies: list[dict[str, object]] = Field(description='软件包依赖及其检查结果')
+ missing_dependencies: list[str] = Field(alias='missingDependencies', description='尚未安装的依赖')
+ unsatisfied_dependencies: list[str] = Field(
+ alias='unsatisfiedDependencies', description='已安装但不满足版本要求的依赖'
+ )
class PluginCheckItemPayload(PluginPayloadModel):
- """
- 插件检查单项 payload。
- """
-
- plugin_id: str = Field(alias='pluginId')
- ok: bool
- manifest_ok: bool | None = Field(default=None, alias='manifestOk')
- dependency_ok: bool | None = Field(default=None, alias='dependencyOk')
- plugin_dependency_ok: bool | None = Field(default=None, alias='pluginDependencyOk')
- structure_ok: bool | None = Field(default=None, alias='structureOk')
- menu_conflict_ok: bool | None = Field(default=None, alias='menuConflictOk')
- dependencies: list[dict[str, object]] | None = None
- plugin_dependencies: list[dict[str, object]] | None = Field(default=None, alias='pluginDependencies')
- plugin_dependency_errors: list[dict[str, object]] | None = Field(default=None, alias='pluginDependencyErrors')
- manifest_issues: list[dict[str, object]] | None = Field(default=None, alias='manifestIssues')
- manifest_warnings: list[dict[str, object]] | None = Field(default=None, alias='manifestWarnings')
- structure: list[dict[str, object]] | None = None
- missing_dependencies: list[str] | None = Field(default=None, alias='missingDependencies')
- unsatisfied_dependencies: list[str] | None = Field(default=None, alias='unsatisfiedDependencies')
- structure_errors: list[dict[str, object]] | None = Field(default=None, alias='structureErrors')
- menu_conflicts: list[dict[str, object]] | None = Field(default=None, alias='menuConflicts')
+ """插件检查单项 payload。"""
+
+ plugin_id: str = Field(alias='pluginId', description='插件标识')
+ ok: bool = Field(description='本次操作是否成功')
+ manifest_ok: bool | None = Field(default=None, alias='manifestOk', description='插件清单是否通过校验')
+ dependency_ok: bool | None = Field(default=None, alias='dependencyOk', description='软件包依赖是否满足要求')
+ plugin_dependency_ok: bool | None = Field(
+ default=None, alias='pluginDependencyOk', description='依赖的其他插件是否满足要求'
+ )
+ structure_ok: bool | None = Field(default=None, alias='structureOk', description='插件文件结构是否通过校验')
+ menu_conflict_ok: bool | None = Field(default=None, alias='menuConflictOk', description='插件是否通过菜单冲突检查')
+ dependencies: list[dict[str, object]] | None = Field(default=None, description='软件包依赖及其检查结果')
+ plugin_dependencies: list[dict[str, object]] | None = Field(
+ default=None, alias='pluginDependencies', description='插件之间的依赖及其状态'
+ )
+ plugin_dependency_errors: list[dict[str, object]] | None = Field(
+ default=None, alias='pluginDependencyErrors', description='插件之间的依赖检查错误'
+ )
+ manifest_issues: list[dict[str, object]] | None = Field(
+ default=None, alias='manifestIssues', description='插件清单中的错误'
+ )
+ manifest_warnings: list[dict[str, object]] | None = Field(
+ default=None, alias='manifestWarnings', description='插件清单中的警告'
+ )
+ structure: list[dict[str, object]] | None = Field(default=None, description='插件目录结构检查结果')
+ missing_dependencies: list[str] | None = Field(
+ default=None, alias='missingDependencies', description='尚未安装的依赖'
+ )
+ unsatisfied_dependencies: list[str] | None = Field(
+ default=None, alias='unsatisfiedDependencies', description='已安装但不满足版本要求的依赖'
+ )
+ structure_errors: list[dict[str, object]] | None = Field(
+ default=None, alias='structureErrors', description='插件目录或文件结构检查错误'
+ )
+ menu_conflicts: list[dict[str, object]] | None = Field(
+ default=None, alias='menuConflicts', description='检测到的菜单冲突'
+ )
class PluginCheckPayload(PluginPayloadModel):
- """
- 插件检查聚合 payload。
- """
+ """插件检查聚合 payload。"""
- ok: bool
- message: str
- count: int
- database_available: bool = Field(alias='databaseAvailable')
- database_error: str | None = Field(alias='databaseError')
- checks: list[dict[str, object]]
+ ok: bool = Field(description='本次操作是否成功')
+ message: str = Field(description='面向调用方的结果说明')
+ count: int = Field(description='结果条数')
+ database_available: bool = Field(alias='databaseAvailable', description='数据库是否可用')
+ database_error: str | None = Field(alias='databaseError', description='数据库访问失败的原因')
+ checks: list[dict[str, object]] = Field(description='各插件的检查结果')
DependencyItemPayloadDict: TypeAlias = dict[str, object]
@@ -149,14 +153,15 @@ class PluginCheckPayload(PluginPayloadModel):
class PluginValidationPayloadBuilderProtocol(Protocol):
- """
- 插件校验 payload builder 协议。
- """
+ """插件校验 payload builder 协议。"""
@staticmethod
def build_dependency_item(item: DependencyCheckItem) -> DependencyItemPayloadDict:
"""
构建依赖检查项负载。
+
+ :param item: 依赖检查项
+ :return: 依赖检查项负载
"""
...
@@ -164,6 +169,9 @@ def build_dependency_item(item: DependencyCheckItem) -> DependencyItemPayloadDic
def build_plugin_dependency_item(item: PluginDependencyCheckItem) -> PluginDependencyItemPayloadDict:
"""
构建插件间依赖检查项负载。
+
+ :param item: 插件间依赖检查项
+ :return: 插件间依赖检查项负载
"""
...
@@ -171,6 +179,9 @@ def build_plugin_dependency_item(item: PluginDependencyCheckItem) -> PluginDepen
def build_validation_issue(item: PluginValidationIssue) -> ValidationIssuePayloadDict:
"""
构建统一校验问题项负载。
+
+ :param item: 统一校验问题项
+ :return: 统一校验问题项负载
"""
...
@@ -178,6 +189,9 @@ def build_validation_issue(item: PluginValidationIssue) -> ValidationIssuePayloa
def build_structure_item(item: PluginStructureCheckItem) -> StructureItemPayloadDict:
"""
构建结构检查项负载。
+
+ :param item: 结构检查项
+ :return: 结构检查项负载
"""
...
@@ -185,6 +199,9 @@ def build_structure_item(item: PluginStructureCheckItem) -> StructureItemPayload
def build_menu_conflict_item(item: PluginMenuConflictItem) -> MenuConflictItemPayloadDict:
"""
构建菜单冲突检查项负载。
+
+ :param item: 菜单冲突检查项
+ :return: 菜单冲突检查项负载
"""
...
@@ -192,6 +209,8 @@ def build_menu_conflict_item(item: PluginMenuConflictItem) -> MenuConflictItemPa
class PluginCheckPrecheckProtocol(Protocol):
"""
插件检查单项所需的预检上下文协议。
+
+ :ivar ok: 操作或检查是否成功
"""
ok: bool
@@ -200,14 +219,14 @@ class PluginCheckPrecheckProtocol(Protocol):
def check_payload(self) -> Mapping[str, object]:
"""
获取插件检查命令通用负载片段。
+
+ :return: 插件检查命令通用负载片段
"""
...
class PluginValidationPayloadMixin:
- """
- 插件依赖、结构、manifest 和菜单冲突检查结果负载构建能力。
- """
+ """插件依赖、结构、manifest 和菜单冲突检查结果负载构建能力。"""
@staticmethod
def build_dependency_item(item: DependencyCheckItem) -> DependencyItemPayloadDict:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/precheck.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/precheck.py
index 052e9b1d1..239083640 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/precheck.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/precheck.py
@@ -41,32 +41,34 @@
class PluginPrecheckOperationPayload(PluginPayloadModel):
- """
- 插件预检操作片段 payload。
- """
-
- manifest_ok: bool = Field(alias='manifestOk')
- dependency_ok: bool = Field(alias='dependencyOk')
- plugin_dependency_ok: bool = Field(alias='pluginDependencyOk')
- structure_ok: bool = Field(alias='structureOk')
- menu_conflict_ok: bool = Field(alias='menuConflictOk')
- manifest_issues: list[dict[str, object]] = Field(alias='manifestIssues')
- manifest_warnings: list[dict[str, object]] = Field(alias='manifestWarnings')
- plugin_dependency_errors: list[dict[str, object]] = Field(alias='pluginDependencyErrors')
- structure_errors: list[dict[str, object]] = Field(alias='structureErrors')
- menu_conflicts: list[dict[str, object]] = Field(alias='menuConflicts')
- dependencies: list[dict[str, object]]
- plugin_dependencies: list[dict[str, object]] = Field(alias='pluginDependencies')
+ """插件预检操作片段 payload。"""
+
+ manifest_ok: bool = Field(alias='manifestOk', description='插件清单是否通过校验')
+ dependency_ok: bool = Field(alias='dependencyOk', description='软件包依赖是否满足要求')
+ plugin_dependency_ok: bool = Field(alias='pluginDependencyOk', description='依赖的其他插件是否满足要求')
+ structure_ok: bool = Field(alias='structureOk', description='插件文件结构是否通过校验')
+ menu_conflict_ok: bool = Field(alias='menuConflictOk', description='插件是否通过菜单冲突检查')
+ manifest_issues: list[dict[str, object]] = Field(alias='manifestIssues', description='插件清单中的错误')
+ manifest_warnings: list[dict[str, object]] = Field(alias='manifestWarnings', description='插件清单中的警告')
+ plugin_dependency_errors: list[dict[str, object]] = Field(
+ alias='pluginDependencyErrors', description='插件之间的依赖检查错误'
+ )
+ structure_errors: list[dict[str, object]] = Field(alias='structureErrors', description='插件目录或文件结构检查错误')
+ menu_conflicts: list[dict[str, object]] = Field(alias='menuConflicts', description='检测到的菜单冲突')
+ dependencies: list[dict[str, object]] = Field(description='软件包依赖及其检查结果')
+ plugin_dependencies: list[dict[str, object]] = Field(
+ alias='pluginDependencies', description='插件之间的依赖及其状态'
+ )
class PluginPrecheckCheckPayload(PluginPrecheckOperationPayload):
- """
- 插件预检检查片段 payload。
- """
+ """插件预检检查片段 payload。"""
- structure: list[dict[str, object]]
- missing_dependencies: list[str] = Field(alias='missingDependencies')
- unsatisfied_dependencies: list[str] = Field(alias='unsatisfiedDependencies')
+ structure: list[dict[str, object]] = Field(description='插件目录结构检查结果')
+ missing_dependencies: list[str] = Field(alias='missingDependencies', description='尚未安装的依赖')
+ unsatisfied_dependencies: list[str] = Field(
+ alias='unsatisfiedDependencies', description='已安装但不满足版本要求的依赖'
+ )
@dataclass(frozen=True)
@@ -77,21 +79,21 @@ class PluginPrecheckContext:
使用 Context Object 模式聚合依赖、manifest、插件间依赖、结构和菜单冲突检查结果,
避免插件运行时在安装、升级和检查流程中重复拼装 payload。
- :param dependency_result: Python/npm 依赖检查结果
- :param manifest_result: manifest 非阻断检查结果
- :param plugin_dependency_result: 插件间依赖检查结果
- :param structure_result: 插件结构检查结果
- :param menu_conflict_result: 菜单冲突检查结果
- :param manifest_issues: manifest error 负载
- :param manifest_warnings: manifest warning 负载
- :param plugin_dependency_errors: 插件依赖错误负载
- :param structure_errors: 结构错误负载
- :param menu_conflicts: 菜单冲突负载
- :param dependencies: Python/npm 依赖检查负载
- :param plugin_dependencies: 插件依赖检查负载
- :param structure: 结构检查完整负载
- :param missing_dependencies: 缺失依赖名称列表
- :param unsatisfied_dependencies: 版本不满足依赖名称列表
+ :ivar dependency_result: Python/npm 依赖检查结果
+ :ivar manifest_result: manifest 非阻断检查结果
+ :ivar plugin_dependency_result: 插件间依赖检查结果
+ :ivar structure_result: 插件结构检查结果
+ :ivar menu_conflict_result: 菜单冲突检查结果
+ :ivar manifest_issues: manifest error 负载
+ :ivar manifest_warnings: manifest warning 负载
+ :ivar plugin_dependency_errors: 插件依赖错误负载
+ :ivar structure_errors: 结构错误负载
+ :ivar menu_conflicts: 菜单冲突负载
+ :ivar dependencies: Python/npm 依赖检查负载
+ :ivar plugin_dependencies: 插件依赖检查负载
+ :ivar structure: 结构检查完整负载
+ :ivar missing_dependencies: 缺失依赖名称列表
+ :ivar unsatisfied_dependencies: 版本不满足依赖名称列表
"""
dependency_result: object
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/task_cleanup.py b/ruoyi-fastapi-backend/plugins/core/runtime/task_cleanup.py
index fc49d2b90..d2858f936 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/task_cleanup.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/task_cleanup.py
@@ -24,7 +24,6 @@ def _finish_task(task: asyncio.Task[Any]) -> None:
回收延迟退出的任务及其异常,避免丢失后台任务引用。
:param task: 已经结束的插件任务
- :return: None
"""
_unfinished_tasks.discard(task)
with suppress(asyncio.CancelledError, Exception):
@@ -42,6 +41,7 @@ async def cancel_plugin_tasks(
:param tasks: 本次需要回收的任务,不取消调用者自身
:param grace_seconds: 整批任务允许的取消等待秒数
:return: 等待结束后仍未退出的任务
+ :raises ValueError: 任务取消等待时间必须大于零
"""
if not math.isfinite(grace_seconds) or grace_seconds <= 0:
raise ValueError('任务取消等待时间必须大于零')
diff --git a/ruoyi-fastapi-backend/plugins/core/sdk/asgi.py b/ruoyi-fastapi-backend/plugins/core/sdk/asgi.py
index 64a6a8db8..49252bfb8 100644
--- a/ruoyi-fastapi-backend/plugins/core/sdk/asgi.py
+++ b/ruoyi-fastapi-backend/plugins/core/sdk/asgi.py
@@ -72,14 +72,22 @@ def plugin_endpoint(
:param body_model: 可选的请求体校验模型,设置后自动读取 JSON 请求体
:param max_body_bytes: JSON 请求体最大字节数,默认 1 MiB
:return: 具有固定 Request 参数的 FastAPI 端点函数
+ :raises ValueError: 插件请求体大小限制必须是正整数
+ :raises TypeError: 插件请求体模型必须是 Pydantic BaseModel 子类
"""
-
if type(max_body_bytes) is not int or max_body_bytes <= 0:
raise ValueError('插件请求体大小限制必须是正整数')
if body_model is not None and (not isinstance(body_model, type) or not issubclass(body_model, BaseModel)):
raise TypeError('插件请求体模型必须是 Pydantic BaseModel 子类')
async def endpoint(request: Request) -> Any:
+ """
+ 将 ASGI 请求适配为插件端点上下文并返回处理结果。
+
+ :param request: 当前 HTTP 请求
+ :raises HTTPException: 缺少宿主插件请求上下文;插件调用超时
+ :return: 处理结果
+ """
context = getattr(request.state, 'plugin_context', None)
if not isinstance(context, PluginRequestContext):
raise HTTPException(status_code=401, detail='缺少宿主插件请求上下文')
@@ -135,7 +143,8 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[dict[str, Any], None]:
执行插件启动和关闭回调,并在请求期间提供共享状态。
:param app: 使用该生命周期管理器的 FastAPI 子应用
- :return: 供子应用请求使用的共享状态字典迭代器
+ :yield: 供子应用请求使用的共享状态字典迭代器
+ :raises TypeError: 插件启动回调必须返回状态字典或 None
"""
try:
state = await await_plugin_callback(on_startup, host, timeout=timeout)
diff --git a/ruoyi-fastapi-backend/plugins/core/sdk/config.py b/ruoyi-fastapi-backend/plugins/core/sdk/config.py
index 5aa4c0abe..b8b317a06 100644
--- a/ruoyi-fastapi-backend/plugins/core/sdk/config.py
+++ b/ruoyi-fastapi-backend/plugins/core/sdk/config.py
@@ -10,17 +10,13 @@ class PluginConfigSnapshot:
"""
一次读取的插件专属配置,版本用于判断是否需要重新应用业务设置。
- :param values: 当前插件的配置明文,只能在插件服务端使用
- :param revision: 宿主生成的不透明配置版本
+ :ivar values: 当前插件的配置明文,只能在插件服务端使用
+ :ivar revision: 宿主生成的不透明配置版本
"""
values: Mapping[str, Any] = field(repr=False)
revision: str
def __post_init__(self) -> None:
- """
- 深拷贝配置以隔离调用方修改,再保护顶层映射。
-
- :return: None
- """
+ """深拷贝配置以隔离调用方修改,再保护顶层映射。"""
object.__setattr__(self, 'values', MappingProxyType(deepcopy(dict(self.values))))
diff --git a/ruoyi-fastapi-backend/plugins/core/sdk/context.py b/ruoyi-fastapi-backend/plugins/core/sdk/context.py
index fdb6e6bab..5fa372530 100644
--- a/ruoyi-fastapi-backend/plugins/core/sdk/context.py
+++ b/ruoyi-fastapi-backend/plugins/core/sdk/context.py
@@ -19,17 +19,17 @@ class PluginHostContext:
services 只包含宿主显式登记的接口,不提供通过字符串导入任意服务的执行器。
具体服务仍负责权限和事务规则;该对象不是针对不可信代码的沙箱。
- :param plugin_id: 插件 ID
- :param resource_root: 插件资源根目录
- :param config: 当前插件的只读配置快照
- :param services: 宿主显式注册的只读服务映射
- :param session_factory: 由宿主提供的数据库会话工厂
- :param redis: 宿主共享的 Redis 客户端
- :param logger: 绑定插件标识的日志对象
- :param startup_write_enabled: 当前实例是否允许执行启动期全局写入
- :param api_version: 宿主插件 API 版本
- :param config_revision: 启动配置快照的不透明版本,手动构造上下文时可为空
- :param config_reader: 宿主绑定的当前插件配置读取器
+ :ivar plugin_id: 插件 ID
+ :ivar resource_root: 插件资源根目录
+ :ivar config: 当前插件的只读配置快照
+ :ivar services: 宿主显式注册的只读服务映射
+ :ivar session_factory: 由宿主提供的数据库会话工厂
+ :ivar redis: 宿主共享的 Redis 客户端
+ :ivar logger: 绑定插件标识的日志对象
+ :ivar startup_write_enabled: 当前实例是否允许执行启动期全局写入
+ :ivar api_version: 宿主插件 API 版本
+ :ivar config_revision: 启动配置快照的不透明版本,手动构造上下文时可为空
+ :ivar config_reader: 宿主绑定的当前插件配置读取器
"""
plugin_id: str
@@ -45,11 +45,7 @@ class PluginHostContext:
config_reader: Callable[[], Awaitable[PluginConfigSnapshot]] | None = field(default=None, repr=False, compare=False)
def __post_init__(self) -> None:
- """
- 规范化资源根目录,并将配置和服务映射转换为只读快照。
-
- :return: None
- """
+ """规范化资源根目录,并将配置和服务映射转换为只读快照。"""
object.__setattr__(self, 'resource_root', self.resource_root.resolve())
object.__setattr__(self, 'config', MappingProxyType(dict(self.config)))
object.__setattr__(self, 'services', MappingProxyType(dict(self.services)))
@@ -71,6 +67,7 @@ def resource(self, relative_path: str) -> Path:
:param relative_path: 相对于当前插件资源根目录的路径
:return: 通过插件目录边界校验的资源绝对路径
+ :raises ValueError: 插件资源路径不能越过插件根目录
"""
path = (self.resource_root / relative_path).resolve()
if not path.is_relative_to(self.resource_root):
@@ -83,6 +80,7 @@ def service(self, name: str) -> Any:
:param name: 宿主注册的版本化服务名称
:return: 对应的宿主服务能力对象
+ :raises LookupError: 宿主未注册指定名称的服务
"""
if name not in self.services:
raise LookupError(f'宿主未提供插件服务:{name}')
@@ -94,13 +92,13 @@ class PluginRequestContext:
"""
由宿主鉴权层建立的请求身份,不能由客户端字段直接构造。
- :param host: 当前插件的宿主能力上下文
- :param user: 宿主登录服务返回的当前用户
- :param permissions: 当前用户的接口权限集合
- :param request_id: 宿主提供的请求关联标识
- :param query_db: 显式事务块内有效的数据库会话,不得跨任务共享
- :param request: SDK 接口适配器提供的 HTTP 请求数据快照
- :param _transaction: 宿主内部的会话所有权记录,业务代码不应自行构造
+ :ivar host: 当前插件的宿主能力上下文
+ :ivar user: 宿主登录服务返回的当前用户
+ :ivar permissions: 当前用户的接口权限集合
+ :ivar request_id: 宿主提供的请求关联标识
+ :ivar query_db: 显式事务块内有效的数据库会话,不得跨任务共享
+ :ivar request: SDK 接口适配器提供的 HTTP 请求数据快照
+ :ivar _transaction: 宿主内部的会话所有权记录,业务代码不应自行构造
"""
host: PluginHostContext
@@ -116,7 +114,7 @@ def require_permission(self, permission: str) -> None:
执行接口权限检查;数据权限由具体服务按当前用户处理。
:param permission: 当前操作要求的接口权限标识
- :return: None
+ :raises PermissionError: 当前上下文缺少指定权限
"""
if permission not in self.permissions and '*:*:*' not in self.permissions:
raise PermissionError(f'缺少权限:{permission}')
@@ -126,7 +124,7 @@ async def transaction(self) -> AsyncIterator['PluginRequestContext']:
"""
为当前任务创建显式事务,成功提交、异常或取消回滚,并关闭独占会话。
- :return: 仅在当前事务块和当前 asyncio 任务内有效的请求上下文
+ :yield: 仅在当前事务块和当前 asyncio 任务内有效的请求上下文
:raises RuntimeError: 嵌套事务、缺少会话工厂或在失效上下文上重新开启事务
"""
if self.query_db is not None or self._transaction is not None:
@@ -163,9 +161,9 @@ class _PluginTransactionState:
"""
记录显式事务的会话、所属任务和有效期。
- :param session: 当前事务独占的数据库会话
- :param owner: 开启事务的 asyncio 任务
- :param active: 事务块是否仍有效
+ :ivar session: 当前事务独占的数据库会话
+ :ivar owner: 开启事务的 asyncio 任务
+ :ivar active: 事务块是否仍有效
"""
session: Any
@@ -178,9 +176,9 @@ class PluginTaskContext:
"""
后台任务身份;不隐式授予请求用户或管理员权限。
- :param host: 当前插件的宿主能力上下文
- :param job_id: 插件清单声明的任务 ID
- :param request_id: 本次任务执行的独立追踪标识
+ :ivar host: 当前插件的宿主能力上下文
+ :ivar job_id: 插件清单声明的任务 ID
+ :ivar request_id: 本次任务执行的独立追踪标识
"""
host: PluginHostContext
diff --git a/ruoyi-fastapi-backend/plugins/core/sdk/definition.py b/ruoyi-fastapi-backend/plugins/core/sdk/definition.py
index 161d4c253..1edb80756 100644
--- a/ruoyi-fastapi-backend/plugins/core/sdk/definition.py
+++ b/ruoyi-fastapi-backend/plugins/core/sdk/definition.py
@@ -18,10 +18,10 @@ class PluginDefinition:
原生扩展通过 PyO3 导入这个类并创建实例即可,无需继承 Python 基类。
生命周期 Hook 继续在清单中声明,避免安装命令和请求 worker 得到不同的能力清单。
- :param api_version: 插件能力对象协议版本
- :param routers: Router 接入方式显式提供的路由集合
- :param app_factory: ASGI 接入方式创建子应用的同步工厂
- :param register_models: 同步注册 ORM 元数据的可选回调
+ :ivar api_version: 插件能力对象协议版本
+ :ivar routers: Router 接入方式显式提供的路由集合
+ :ivar app_factory: ASGI 接入方式创建子应用的同步工厂
+ :ivar register_models: 同步注册 ORM 元数据的可选回调
"""
api_version: int = 1
@@ -34,7 +34,8 @@ def validate(self, integration: str) -> None:
导入后验证对象协议,不依赖 Rust 函数的反射签名。
:param integration: 清单声明的 Web 接入方式
- :return: None
+ :raises ValueError: ASGI 插件必须提供 app_factory,且不能同时返回 routers;Router 插件不能返回 app_factory
+ :raises TypeError: PluginDefinition.routers 必须包含 APIRouter 实例;register_models 必须可调用
"""
if type(self.api_version) is not int or self.api_version != 1:
raise ValueError(f'不支持的 PluginDefinition API 版本:{self.api_version}')
@@ -72,6 +73,12 @@ def await_plugin_callback(
"""
async def invoke() -> Any:
+ """
+ 在宿主运行环境中调用插件回调并等待结果。
+
+ :raises TypeError: v2 插件异步回调必须立即返回 awaitable
+ :return: 插件回调完成后的值
+ """
result = callback(*args, **(kwargs or {}))
if not inspect.isawaitable(result):
raise TypeError('v2 插件异步回调必须立即返回 awaitable')
diff --git a/ruoyi-fastapi-backend/plugins/core/sdk/request.py b/ruoyi-fastapi-backend/plugins/core/sdk/request.py
index a54dbbe90..8ea2c96b2 100644
--- a/ruoyi-fastapi-backend/plugins/core/sdk/request.py
+++ b/ruoyi-fastapi-backend/plugins/core/sdk/request.py
@@ -22,11 +22,11 @@ class PluginHttpRequest:
"""
提供给 Python 和原生回调的 HTTP 数据快照,不携带 Cookie、令牌或 Request 对象。
- :param method: HTTP 请求方法
- :param path: 当前请求的路径,不包含查询串
- :param path_params: 路由已解析的路径参数,值为可序列化数据
- :param query: 保留同名多值的查询参数
- :param body: 显式开启 JSON 读取后获得的请求体
+ :ivar method: HTTP 请求方法
+ :ivar path: 当前请求的路径,不包含查询串
+ :ivar path_params: 路由已解析的路径参数,值为可序列化数据
+ :ivar query: 保留同名多值的查询参数
+ :ivar body: 显式开启 JSON 读取后获得的请求体
"""
method: str
@@ -36,11 +36,7 @@ class PluginHttpRequest:
body: Any = None
def __post_init__(self) -> None:
- """
- 复制路径和查询参数,避免调用方修改原始请求的参数映射。
-
- :return: None
- """
+ """复制路径和查询参数,避免调用方修改原始请求的参数映射。"""
object.__setattr__(self, 'path_params', MappingProxyType(dict(self.path_params)))
object.__setattr__(self, 'query', MappingProxyType({key: tuple(values) for key, values in self.query.items()}))
diff --git a/ruoyi-fastapi-backend/plugins/core/state.py b/ruoyi-fastapi-backend/plugins/core/state.py
index f84845f03..b6b186979 100644
--- a/ruoyi-fastapi-backend/plugins/core/state.py
+++ b/ruoyi-fastapi-backend/plugins/core/state.py
@@ -20,10 +20,10 @@ class PluginStateTransition:
"""
插件状态流转规则。
- :param source: 来源状态,None 表示数据库中尚无插件状态
- :param operation: 状态流转操作
- :param target: 目标状态
- :param description: 流转说明
+ :ivar source: 来源状态,None 表示数据库中尚无插件状态
+ :ivar operation: 状态流转操作
+ :ivar target: 目标状态
+ :ivar description: 流转说明
"""
source: PluginStatus | None
@@ -37,10 +37,10 @@ class PluginStateSnapshot:
"""
插件状态输入快照。
- :param source_version: 当前源码版本
- :param installed_version: 已安装版本
- :param enabled: 是否启用
- :param current_status: 当前持久化状态
+ :ivar source_version: 当前源码版本
+ :ivar installed_version: 已安装版本
+ :ivar enabled: 是否启用
+ :ivar current_status: 当前持久化状态
"""
source_version: str | None
@@ -97,7 +97,7 @@ def enabled_to_db_value(enabled: bool) -> str:
将布尔启停状态转换为数据库枚举值。
:param enabled: 是否启用
- :return: 数据库启停枚举值,`0` 表示启用,`1` 表示停用
+ :return: 数据库启停枚举值,``0`` 表示启用,``1`` 表示停用
"""
return '0' if enabled else '1'
@@ -150,6 +150,8 @@ class PluginStateTransitionTable:
插件状态流转表。
使用 Table Driven 模式集中维护可观察的插件状态流转,供文档、测试和后续预检复用。
+
+ :cvar _TRANSITIONS: 允许的源状态和目标状态组合
"""
_TRANSITIONS = (
diff --git a/ruoyi-fastapi-backend/plugins/core/types.py b/ruoyi-fastapi-backend/plugins/core/types.py
index 1116c59ff..806bd03dd 100644
--- a/ruoyi-fastapi-backend/plugins/core/types.py
+++ b/ruoyi-fastapi-backend/plugins/core/types.py
@@ -10,9 +10,7 @@
class SupportsModelDump(Protocol):
- """
- 支持 Pydantic 风格序列化的对象协议。
- """
+ """支持 Pydantic 风格序列化的对象协议。"""
def model_dump(self, *, by_alias: bool = False) -> dict[str, Any]:
"""
@@ -25,9 +23,7 @@ def model_dump(self, *, by_alias: bool = False) -> dict[str, Any]:
class SupportsToPayload(Protocol):
- """
- 支持运行时 payload 序列化的对象协议。
- """
+ """支持运行时 payload 序列化的对象协议。"""
def to_payload(self) -> dict[str, object]:
"""
@@ -41,6 +37,15 @@ def to_payload(self) -> dict[str, object]:
class PluginStateRecord(Protocol):
"""
插件数据库状态记录协议。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar installed_version: 已安装版本
+ :ivar enabled: 是否启用该项功能
+ :ivar status: 操作或记录所处的状态
+ :ivar last_error: 最近一次错误信息
+ :ivar source: 待检查的源文本或输入来源
+ :ivar backend_path: 后端插件相对路径
+ :ivar frontend_path: 前端插件相对路径
"""
plugin_id: str
diff --git a/ruoyi-fastapi-backend/plugins/core/utils.py b/ruoyi-fastapi-backend/plugins/core/utils.py
index 50fda132d..105765f89 100644
--- a/ruoyi-fastapi-backend/plugins/core/utils.py
+++ b/ruoyi-fastapi-backend/plugins/core/utils.py
@@ -7,7 +7,12 @@
from pathlib import PureWindowsPath
def is_windows_reserved(name: str) -> bool:
- """按 Windows 规则识别保留路径名。"""
+ """
+ 按 Windows 规则识别保留路径名。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 是否按 Windows 规则识别保留路径名
+ """
return PureWindowsPath(name).is_reserved()
@@ -22,6 +27,7 @@ def validate_plugin_id_value(plugin_id: str, *, field_name: str = '插件ID') ->
:param plugin_id: 插件 ID
:param field_name: 错误提示中的字段名称
:return: 校验后的插件 ID
+ :raises ValueError: 插件标识的长度、首字符或字符集不合法
"""
if not PLUGIN_ID_PATTERN.match(plugin_id):
raise ValueError(f'{field_name}必须以小写字母开头,且只能包含小写字母、数字和下划线,长度为2-64')
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/dependencies.py b/ruoyi-fastapi-backend/plugins/core/validation/dependencies.py
index b6f14d1d4..625daedf6 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/dependencies.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/dependencies.py
@@ -25,6 +25,17 @@
class DependencyCheckItem:
"""
单条依赖检查结果。
+
+ :ivar kind: 当前条目的类别
+ :ivar requirement: 依赖声明,包括包名和版本约束
+ :ivar name: 用于查找或标识当前对象的名称
+ :ivar installed: 当前环境中已安装的版本
+ :ivar version_satisfied: 版本是否满足
+ :ivar installed_version: 已安装版本
+ :ivar required_version: 约束版本
+ :ivar message: 与当前结果一起返回的说明
+ :ivar status: 操作或记录所处的状态
+ :ivar declared_version: 插件清单声明的依赖版本
"""
kind: DependencyKind
@@ -52,6 +63,9 @@ def ok(self) -> bool:
class DependencyCheckResult:
"""
插件依赖检查结果。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar items: 逐项记录的检查或计划明细
"""
plugin_id: str
@@ -91,6 +105,13 @@ def unsatisfied_items(self) -> list[DependencyCheckItem]:
class DependencyInstallPlanItem:
"""
依赖安装计划项。
+
+ :ivar kind: 当前条目的类别
+ :ivar requirement: 依赖声明,包括包名和版本约束
+ :ivar name: 用于查找或标识当前对象的名称
+ :ivar command: 执行的命令及其参数
+ :ivar workdir: 命令执行时使用的工作目录
+ :ivar reason: 作出该决定或状态变化的原因
"""
kind: DependencyKind
@@ -105,6 +126,9 @@ class DependencyInstallPlanItem:
class DependencyInstallPlan:
"""
插件依赖安装计划。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar items: 逐项记录的检查或计划明细
"""
plugin_id: str
@@ -124,6 +148,10 @@ def has_actions(self) -> bool:
class ParsedDependency:
"""
已解析依赖声明。
+
+ :ivar name: 用于查找或标识当前对象的名称
+ :ivar operator: 依赖表达式中的比较运算符
+ :ivar version: npm 版本声明
"""
name: str
@@ -169,9 +197,7 @@ def parse(cls, requirement: str) -> ParsedDependency:
class VersionConstraintMatcher:
- """
- 版本约束匹配器。
- """
+ """版本约束匹配器。"""
@classmethod
def is_satisfied(cls, installed_version: str | None, parsed_dependency: ParsedDependency) -> bool:
@@ -234,6 +260,9 @@ def _can_compare(installed_version: str, required_version: str) -> bool:
class PythonDependencyInspector:
"""
Python 依赖检查器。
+
+ :ivar _installed_packages_overridden: 是否使用调用方提供的已安装包清单
+ :ivar installed_packages: 已安装 Python 包版本映射
"""
def __init__(self, installed_packages: dict[str, str] | None = None) -> None:
@@ -255,8 +284,6 @@ def refresh(self) -> None:
显式传入 ``installed_packages`` 的检查器保持固定快照,便于测试和离线检查;
从运行环境创建的检查器会重新读取 distribution 元数据。
-
- :return: None
"""
if self._installed_packages_overridden:
return
@@ -397,6 +424,9 @@ def _build_message(
class NpmDependencyInspector:
"""
npm 依赖检查器。
+
+ :ivar frontend_root: 前端项目根目录
+ :ivar installed_packages: 已声明 npm 包版本映射
"""
def __init__(
@@ -538,6 +568,11 @@ def _build_message(
class PluginDependencyChecker:
"""
插件依赖检查器。
+
+ :ivar runtime_environment: 保留当前宿主显式框架选择的运行时环境
+ :ivar python_inspector: Python 依赖检查器
+ :ivar npm_inspector: 当前宿主前端的 npm 依赖检查器
+ :ivar frontend_mode: 前端运行模式,已构建模式跳过 npm 依赖实际检查
"""
def __init__(
@@ -554,7 +589,6 @@ def __init__(
:param npm_inspector: 当前宿主前端的 npm 依赖检查器
:param frontend_mode: 前端运行模式,已构建模式跳过 npm 依赖实际检查
:param runtime_environment: 保留当前宿主显式框架选择的运行时环境
- :return: None
"""
self.runtime_environment = runtime_environment or PLUGIN_RUNTIME_ENVIRONMENT
self.python_inspector = python_inspector or PythonDependencyInspector()
@@ -595,6 +629,9 @@ class PluginDependencyInstallPlanner:
插件依赖安装计划生成器。
使用 Planner 模式将依赖检查结果转换为可审计、可 dry-run 的安装计划。
+
+ :ivar python_executable: Python 可执行文件路径
+ :ivar frontend_root: 前端工程根目录
"""
def __init__(self, python_executable: str | None = None, frontend_root: Path | str | None = None) -> None:
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/dependency_policy.py b/ruoyi-fastapi-backend/plugins/core/validation/dependency_policy.py
index 4319342eb..44bce07b0 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/dependency_policy.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/dependency_policy.py
@@ -33,6 +33,21 @@
class DependencyInstallPolicyConfig:
"""
插件依赖安装策略配置。
+
+ :ivar mode: 控制执行方式的模式
+ :ivar env: 当前运行环境
+ :ivar allow_prod: 是否允许生产环境危险命令
+ :ivar allow_prod_install: 是否允许在生产环境安装依赖
+ :ivar require_yes: 是否要求显式确认安装
+ :ivar require_lockfile: 是否要求锁文件
+ :ivar require_allowlist: 是否只允许安装白名单中的依赖
+ :ivar allow_unlisted: 是否允许未命中 allowlist 的依赖仅告警
+ :ivar lockfile_path: 锁文件路径
+ :ivar offline_dir: 保存离线依赖包的目录
+ :ivar allowlist_path: 依赖允许列表路径
+ :ivar pip_index_url: Python 包索引地址
+ :ivar npm_registry: 前端依赖的 npm 注册表地址
+ :ivar install_timeout_seconds: 安装依赖时允许等待的秒数
"""
mode: DependencyInstallPolicyMode | None = None
@@ -51,11 +66,7 @@ class DependencyInstallPolicyConfig:
install_timeout_seconds: int = 600
def __post_init__(self) -> None:
- """
- 归一化路径和默认模式。
-
- :return: None
- """
+ """归一化路径和默认模式。"""
object.__setattr__(self, 'env', (self.env or 'dev').strip() or 'dev')
object.__setattr__(self, 'mode', self.mode or self._default_mode(self.env))
for field_name in ('lockfile_path', 'offline_dir', 'allowlist_path'):
@@ -219,6 +230,7 @@ def _load_environment_settings(cls) -> Any | None:
延迟加载统一配置入口中的插件依赖策略配置。
:return: 插件依赖策略配置对象,缺失时返回 None
+ :raises ValueError: 插件依赖策略的布尔配置不合法
"""
try:
from config.env import get_config # noqa: PLC0415
@@ -282,6 +294,7 @@ def _normalize_mode(value: str, default: DependencyInstallPolicyMode) -> Depende
:param value: 原始模式
:param default: 默认模式
:return: 策略模式
+ :raises ValueError: 依赖安装策略模式不受支持
"""
normalized_value = value.strip()
if normalized_value in {'disabled', 'plan_only', 'explicit', 'locked', 'offline'}:
@@ -298,6 +311,7 @@ def _parse_bool(value: object, *, name: str) -> bool:
:param value: 原始配置值
:param name: 配置名称
:return: 布尔值
+ :raises ValueError: 配置值不能解析为布尔值
"""
if isinstance(value, bool):
return value
@@ -382,6 +396,17 @@ def resolved_require_allowlist(self) -> bool:
class DependencyInstallPolicyItemDecision:
"""
单条依赖安装计划的策略判定。
+
+ :ivar kind: 依赖类型
+ :ivar name: 用于查找或标识当前对象的名称
+ :ivar requirement: 依赖声明,包括包名和版本约束
+ :ivar allowed: 策略检查是否允许该操作
+ :ivar reasons: 阻断原因
+ :ivar warnings: 告警列表
+ :ivar requirements: 满足策略需要的条件或依赖
+ :ivar locked_version: 锁文件指定的版本
+ :ivar artifact_path: 插件制品在文件系统中的路径
+ :ivar artifact_verified: 制品是否已通过完整性校验
"""
kind: DependencyKind
@@ -423,6 +448,14 @@ def to_payload(self) -> dict[str, object]:
class DependencyInstallPolicyDecision:
"""
依赖安装策略判定结果。
+
+ :ivar allowed: 策略检查是否允许该操作
+ :ivar mode: 控制执行方式的模式
+ :ivar reasons: 阻断原因
+ :ivar warnings: 告警列表
+ :ivar requirements: 满足策略需要的条件或依赖
+ :ivar items: 字符串列表
+ :ivar install_plan_items: 依赖安装计划项列表
"""
allowed: bool
@@ -453,6 +486,13 @@ def to_payload(self) -> dict[str, object]:
class DependencyLockEntry:
"""
锁文件中的单条依赖。
+
+ :ivar kind: 依赖类型
+ :ivar name: 用于查找或标识当前对象的名称
+ :ivar requirement: 依赖声明,包括包名和版本约束
+ :ivar resolved_version: 最终解析出的依赖版本
+ :ivar hashes: 用于校验依赖制品的哈希值
+ :ivar integrity: 依赖锁记录要求的制品完整性校验值
"""
kind: DependencyKind
@@ -468,9 +508,9 @@ class DependencyLockfile:
"""
插件依赖锁文件。
- :param path: 锁文件路径
- :param entries: 按依赖类型和包名索引的锁定依赖
- :param frontend_framework: 锁文件对应的宿主前端框架,未声明时不检查框架
+ :ivar path: 锁文件路径
+ :ivar entries: 按依赖类型和包名索引的锁定依赖
+ :ivar frontend_framework: 锁文件对应的宿主前端框架,未声明时不检查框架
"""
path: Path
@@ -535,6 +575,9 @@ def get_entry(self, item: DependencyInstallPlanItem) -> DependencyLockEntry | No
class DependencyVersionBound:
"""
依赖版本范围边界。
+
+ :ivar version: 版本
+ :ivar inclusive: 版本边界是否包含端点
"""
version: str
@@ -545,6 +588,10 @@ class DependencyVersionBound:
class DependencyVersionRange:
"""
可保守比较的依赖版本范围。
+
+ :ivar lower: 允许版本的下界
+ :ivar upper: 允许版本的上界
+ :ivar exact: 必须匹配的确切版本
"""
lower: DependencyVersionBound | None = None
@@ -556,6 +603,8 @@ class DependencyVersionRange:
class DependencyAllowlist:
"""
插件依赖允许列表。
+
+ :ivar entries: 按依赖类型和包名索引的锁定依赖
"""
entries: dict[DependencyKind, dict[str, dict[str, Any]]]
@@ -620,6 +669,8 @@ def is_allowed(self, item: DependencyInstallPlanItem) -> bool:
class DependencyArtifactStore:
"""
离线依赖制品仓库。
+
+ :ivar offline_dir: 离线制品根目录
"""
def __init__(self, offline_dir: Path | str | None) -> None:
@@ -627,7 +678,6 @@ def __init__(self, offline_dir: Path | str | None) -> None:
初始化离线制品仓库。
:param offline_dir: 离线制品根目录
- :return: None
"""
self.offline_dir = Path(offline_dir) if offline_dir is not None else None
@@ -743,6 +793,9 @@ def _verify_npm_artifact(entry: DependencyLockEntry, artifact_path: Path) -> str
class DependencyInstallPolicyEvaluator:
"""
插件依赖安装策略判定器。
+
+ :ivar config: 策略配置
+ :ivar runtime_environment: 保留当前宿主显式框架选择的运行时环境
"""
def __init__(
@@ -756,7 +809,6 @@ def __init__(
:param config: 策略配置
:param runtime_environment: 保留当前宿主显式框架选择的运行时环境
- :return: None
"""
self.config = config or DependencyInstallPolicyConfig.from_environment()
self.runtime_environment = runtime_environment or PLUGIN_RUNTIME_ENVIRONMENT
@@ -928,7 +980,6 @@ def _evaluate_allowlist(
:param allowlist: 允许列表
:param reasons: 阻断原因
:param warnings: 告警列表
- :return: None
"""
if allowlist.is_allowed(item):
return
@@ -1397,7 +1448,6 @@ def append_unique(items: list[str], item: str) -> None:
:param items: 字符串列表
:param item: 待追加字符串
- :return: None
"""
if item not in items:
items.append(item)
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/manifest.py b/ruoyi-fastapi-backend/plugins/core/validation/manifest.py
index f9009a232..496243da0 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/manifest.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/manifest.py
@@ -26,8 +26,8 @@ class PluginManifestCheckResult:
"""
插件 manifest 非阻断检查结果。
- :param plugin_id: 插件 ID
- :param issues: manifest 检查问题项列表
+ :ivar plugin_id: 插件 ID
+ :ivar issues: manifest 检查问题项列表
"""
plugin_id: str
@@ -66,6 +66,12 @@ class PluginManifestChecker:
插件 manifest 非阻断检查器。
使用 Checker 模式承载不适合放入 Pydantic 强校验的提示类规则。
+
+ :cvar _node_version_cache: 已查询的 Node.js 版本缓存
+ :ivar backend_root: 后端项目根目录
+ :ivar frontend_root: 前端项目根目录
+ :ivar python_version: 当前 Python 版本
+ :ivar node_version: 当前 Node.js 版本
"""
_node_version_cache: ClassVar[object | str | None] = UNRESOLVED_NODE_VERSION
@@ -85,7 +91,6 @@ def __init__(
:param frontend_root: 前端项目根目录
:param python_version: 当前 Python 版本
:param node_version: 当前 Node.js 版本
- :return: None
"""
self.backend_root = backend_root or Path(__file__).resolve().parents[3]
self.frontend_root = frontend_root or Path(
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/menus.py b/ruoyi-fastapi-backend/plugins/core/validation/menus.py
index 59b7a396f..f20aac533 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/menus.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/menus.py
@@ -10,11 +10,11 @@ class PluginMenuConflictItem:
"""
插件菜单冲突检查项。
- :param kind: 冲突类型
- :param plugin_id: 当前插件 ID
- :param value: 冲突值
- :param message: 冲突说明
- :param conflict_plugin_id: 冲突插件 ID
+ :ivar kind: 冲突类型
+ :ivar plugin_id: 当前插件 ID
+ :ivar value: 冲突值
+ :ivar message: 冲突说明
+ :ivar conflict_plugin_id: 冲突插件 ID
"""
kind: str
@@ -29,8 +29,8 @@ class PluginMenuConflictResult:
"""
插件菜单冲突检查结果。
- :param plugin_id: 插件 ID
- :param items: 冲突检查项列表
+ :ivar plugin_id: 插件 ID
+ :ivar items: 冲突检查项列表
"""
plugin_id: str
@@ -51,9 +51,9 @@ class PluginMenuSnapshot:
"""
插件菜单快照。
- :param plugin_id: 插件 ID
- :param menu: 插件菜单声明
- :param menu_key: 插件内菜单自然键
+ :ivar plugin_id: 插件 ID
+ :ivar menu: 插件菜单声明
+ :ivar menu_key: 插件内菜单自然键
"""
plugin_id: str
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/plugin_deps.py b/ruoyi-fastapi-backend/plugins/core/validation/plugin_deps.py
index 66954c588..54830b77f 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/plugin_deps.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/plugin_deps.py
@@ -76,6 +76,13 @@ def _parse_constraint(version_constraint: str) -> ParsedDependency:
class PluginDependencyCheckItem:
"""
插件间依赖检查项。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar dependency_id: 依赖插件ID
+ :ivar required_version: 约束版本
+ :ivar installed_version: 已安装版本
+ :ivar status: 操作或记录所处的状态
+ :ivar message: 与当前结果一起返回的说明
"""
plugin_id: str
@@ -99,6 +106,9 @@ def ok(self) -> bool:
class PluginDependencyCheckResult:
"""
插件间依赖检查结果。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar items: 逐项记录的检查或计划明细
"""
plugin_id: str
@@ -127,6 +137,11 @@ def failed_items(self) -> list[PluginDependencyCheckItem]:
class PluginDependencyPlanBlocker:
"""
插件批量操作计划阻塞项。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar dependency_id: 依赖插件ID
+ :ivar status: 操作或记录所处的状态
+ :ivar message: 与当前结果一起返回的说明
"""
plugin_id: str
@@ -139,6 +154,18 @@ class PluginDependencyPlanBlocker:
class PluginDependencyPlanItem:
"""
插件批量操作计划项。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar name: 用于查找或标识当前对象的名称
+ :ivar version: 当前记录的版本
+ :ivar operation: 批量操作类型
+ :ivar order: 执行顺序
+ :ivar requested: 是否为用户显式指定插件
+ :ivar dependencies: 执行当前步骤所需的依赖
+ :ivar installed_version: 已安装版本
+ :ivar enabled: 是否启用该项功能
+ :ivar status: 操作或记录所处的状态
+ :ivar blockers: 阻塞项列表
"""
plugin_id: str
@@ -167,6 +194,12 @@ def ready(self) -> bool:
class PluginDependencyPlan:
"""
插件批量操作拓扑计划。
+
+ :ivar operation: 批量操作类型
+ :ivar requested_plugin_ids: 请求的插件ID列表
+ :ivar ordered_plugin_ids: 按依赖顺序排列的插件标识
+ :ivar items: 逐项记录的检查或计划明细
+ :ivar blockers: 阻塞项列表
"""
operation: PluginBatchOperation
@@ -190,6 +223,9 @@ class PluginDependencyChecker:
插件间依赖检查器。
使用 Checker 模式校验插件之间的存在性、安装状态、启用状态、版本约束和循环依赖。
+
+ :ivar discovered_plugin_map: 已发现插件映射
+ :ivar database_plugin_map: 按插件标识索引的数据库记录
"""
def __init__(
@@ -202,7 +238,6 @@ def __init__(
:param discovered_plugins: 已发现插件列表
:param database_plugins: 数据库插件状态列表
- :return: None
"""
self.discovered_plugin_map = {plugin.manifest.id: plugin for plugin in discovered_plugins}
self.database_plugin_map = {plugin.plugin_id: plugin for plugin in database_plugins or []}
@@ -382,6 +417,8 @@ class PluginDependencyGraph:
插件依赖图。
使用 Graph 模式为插件间依赖提供循环检测,并为后续拓扑排序保留扩展点。
+
+ :ivar discovered_plugin_map: 已发现插件映射
"""
def __init__(self, discovered_plugin_map: dict[str, DiscoveredPlugin]) -> None:
@@ -389,7 +426,6 @@ def __init__(self, discovered_plugin_map: dict[str, DiscoveredPlugin]) -> None:
初始化插件依赖图。
:param discovered_plugin_map: 已发现插件映射
- :return: None
"""
self.discovered_plugin_map = discovered_plugin_map
@@ -448,6 +484,9 @@ class PluginDependencyPlanBuilder:
插件批量操作拓扑计划生成器。
使用 Planner 模式为批量安装、启用和升级生成依赖优先的执行顺序,并输出阻塞原因。
+
+ :ivar discovered_plugin_map: 已发现插件映射
+ :ivar database_plugin_map: 按插件标识索引的数据库记录
"""
def __init__(
@@ -460,7 +499,6 @@ def __init__(
:param discovered_plugins: 已发现插件列表
:param database_plugins: 数据库插件状态列表
- :return: None
"""
self.discovered_plugin_map = {plugin.manifest.id: plugin for plugin in discovered_plugins}
self.database_plugin_map = {plugin.plugin_id: plugin for plugin in database_plugins or []}
@@ -519,6 +557,12 @@ def _collect_dependency_closure(
visiting: list[str] = []
def visit(plugin_id: str, requested_by: str) -> None:
+ """
+ 递归收集插件的传递依赖并检查循环引用。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param requested_by: 手动执行提交者
+ """
if plugin_id in visiting:
blockers.extend(self._build_cycle_blockers([*visiting[visiting.index(plugin_id) :], plugin_id]))
return
@@ -566,6 +610,11 @@ def _sort_dependency_first(
visited: set[str] = set()
def visit(plugin_id: str) -> None:
+ """
+ 遍历依赖图并按依赖优先的顺序加入插件。
+
+ :param plugin_id: 插件清单中的唯一标识
+ """
if plugin_id in visited:
return
if plugin_id in visiting:
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/python_requirements.py b/ruoyi-fastapi-backend/plugins/core/validation/python_requirements.py
index b57d031bd..52aed611d 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/python_requirements.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/python_requirements.py
@@ -11,6 +11,9 @@ class ParsedPythonRequirement:
保留 packaging 的解析结果,供 manifest 校验、运行时检查和依赖安装策略
共享同一套名称、版本范围和环境 marker 语义。
+
+ :ivar raw: 尚未解析或规范化的原始值
+ :ivar requirement: Python 依赖声明
"""
raw: str
@@ -48,7 +51,7 @@ def marker(self) -> str | None:
"""
获取环境 marker。
- :return: PEP 508 marker
+ :return: 符合 PEP 508 的环境标记
"""
return str(self.requirement.marker) if self.requirement.marker else None
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/result.py b/ruoyi-fastapi-backend/plugins/core/validation/result.py
index d82ed0b5a..805f18a9b 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/result.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/result.py
@@ -9,13 +9,13 @@ class PluginValidationIssue:
"""
插件校验问题项。
- :param level: 校验等级
- :param category: 校验分类
- :param kind: 校验项类型
- :param path: 问题路径或目标
- :param message: 问题说明
- :param suggestion: 修复建议
- :param ok: 当前校验项是否通过
+ :ivar level: 校验等级
+ :ivar category: 校验分类
+ :ivar kind: 校验项类型
+ :ivar path: 问题路径或目标
+ :ivar message: 问题说明
+ :ivar suggestion: 修复建议
+ :ivar ok: 当前校验项是否通过
"""
level: ValidationLevel
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/structure.py b/ruoyi-fastapi-backend/plugins/core/validation/structure.py
index d47f831cd..2eaf7d815 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/structure.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/structure.py
@@ -26,6 +26,12 @@
class PluginStructureCheckItem:
"""
插件结构检查项。
+
+ :ivar kind: 检查类型
+ :ivar path: 要读取或处理的路径
+ :ivar ok: 操作或检查是否成功
+ :ivar message: 与当前结果一起返回的说明
+ :ivar suggestion: 对当前检查结果给出的处理建议
"""
kind: str
@@ -64,6 +70,9 @@ def to_issue(self) -> PluginValidationIssue:
class PluginStructureCheckResult:
"""
插件结构检查结果。
+
+ :ivar plugin_id: 插件清单中的唯一标识
+ :ivar items: 已收集的结构检查项
"""
plugin_id: str
@@ -102,6 +111,10 @@ class PluginStructureChecker:
插件结构检查器。
使用 Checker 模式集中验证 manifest 引用的后端目录、seed 文件和前端页面是否存在。
+
+ :ivar backend_root: 后端项目根目录
+ :ivar runtime_environment: 运行时环境服务
+ :ivar frontend_root: 前端插件根目录,默认使用运行时环境解析出的 plugins 目录
"""
def __init__(self, backend_root: Path | str, frontend_root: Path | str | None = None) -> None:
@@ -522,6 +535,7 @@ def _resolve_backend_module_file(self, module_path: str) -> Path:
:param module_path: Python 模块路径
:return: 模块文件路径
+ :raises ImportError: 后端模块对应的 Python 文件不存在
"""
module_file = self.backend_root / Path(*module_path.split('.')).with_suffix('.py')
if module_file.is_file():
@@ -540,6 +554,7 @@ def _resolve_plugin_module_file(self, discovered_plugin: DiscoveredPlugin, modul
:param discovered_plugin: 已发现插件对象
:param module_path: Python 模块路径
:return: 模块文件路径
+ :raises ImportError: 插件模块对应的 Python 文件不存在
"""
backend_module = discovered_plugin.manifest.backend.module
if module_path == backend_module:
@@ -622,7 +637,7 @@ def _check_migration_files(self, discovered_plugin: DiscoveredPlugin) -> list[Pl
@staticmethod
def _check_migration_time_types(migration_file: Path, migration_path: str) -> PluginStructureCheckItem:
"""
- 检查插件SQL脚本中的真实时刻列类型
+ 检查插件SQL脚本中的真实时刻列类型。
:param migration_file: 待检查的SQL文件路径
:param migration_path: SQL文件相对插件根目录的路径
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/versioning.py b/ruoyi-fastapi-backend/plugins/core/validation/versioning.py
index b9121577a..45b02b901 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/versioning.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/versioning.py
@@ -14,6 +14,11 @@ class PluginVersion:
插件版本值对象。
使用 Value Object 模式封装插件版本解析和比较所需的结构化信息。
+
+ :ivar raw: 尚未解析或规范化的原始值
+ :ivar release: 发布号
+ :ivar prerelease_label: 预发布版本的阶段标签
+ :ivar prerelease_number: 同一预发布阶段的顺序号
"""
raw: str
@@ -86,6 +91,8 @@ class PluginVersionComparator:
插件版本比较器。
使用 Comparator 模式提供插件版本相等、排序和升级判断能力。
+
+ :cvar PRERELEASE_ORDER: 比较同一正式版本的预发布阶段时使用的顺序
"""
PRERELEASE_ORDER = {
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/__init__.py b/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/__init__.py
index 6882fd7ce..c43942889 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/__init__.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/__init__.py
@@ -9,11 +9,9 @@
class EchoBody(BaseModel):
- """
- SDK 请求体模型,约束示例消息长度。
- """
+ """SDK 请求体模型,约束示例消息长度。"""
- message: str = Field(min_length=1, max_length=200)
+ message: str = Field(min_length=1, max_length=200, description='需要原样回显的消息')
async def echo(context: PluginRequestContext) -> dict[str, Any]:
@@ -44,7 +42,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[dict[str, str], None]:
演示插件自有资源的启动与关闭。
:param app: 正在启动或关闭的 ASGI 子应用
- :return: 可供请求访问的生命周期状态
+ :yield: 可供请求访问的生命周期状态
"""
host.logger.info('ASGI 示例启动')
try:
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/__init__.py b/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/__init__.py
index be4279340..329f72b89 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/__init__.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/__init__.py
@@ -9,11 +9,9 @@
class EchoInput(BaseModel):
- """
- 用于验证 POST 链路的回显请求参数。
- """
+ """用于验证 POST 链路的回显请求参数。"""
- message: str = Field(min_length=1, max_length=80)
+ message: str = Field(min_length=1, max_length=80, description='需要原样回显的消息')
async def summary(context: PluginRequestContext) -> dict[str, str]:
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/events.py b/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/events.py
index 7c26244a5..c8bbba3bd 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/events.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/events.py
@@ -18,7 +18,6 @@ def register_event_routes(app: FastAPI, *, permission: str = 'bundle_demo:view',
:param app: 当前插件的 ASGI 子应用
:param permission: 访问事件流所需的接口权限
:param interval: 示例事件发送间隔,单位为秒
- :return: None
"""
@app.get(
@@ -37,7 +36,7 @@ async def generate() -> AsyncIterator[str]:
"""
逐条生成有界示例事件,由 ASGI 响应负责取消断开的请求。
- :return: 已编码的 SSE 事件片段
+ :yield: 已编码的 SSE 事件片段
"""
for index in range(int(cursor) + 1, count + 1):
await asyncio.sleep(interval)
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/files.py b/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/files.py
index 326268449..52dcfadf7 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/files.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/bundle_demo/files.py
@@ -14,9 +14,7 @@
class FileInspection(BaseModel):
- """
- 返回文件元数据与摘要,不保存上传内容。
- """
+ """返回文件元数据与摘要,不保存上传内容。"""
filename: str = Field(description='客户端提交的文件名,仅作展示')
size: int = Field(description='文件实际字节数')
@@ -29,7 +27,6 @@ def register_file_routes(app: FastAPI, *, permission: str = 'bundle_demo:view')
:param app: 插件所属的子应用
:param permission: 两个文件接口要求的插件权限
- :return: None
"""
@app.post(
@@ -46,6 +43,7 @@ async def limited_receive() -> Message:
累计实际请求体大小,在解析 multipart 之前执行硬上限检查。
:return: 当前 ASGI 消息
+ :raises MultiPartException: 上传请求超过大小限制
"""
nonlocal received
message = await request.receive()
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/__init__.py b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/__init__.py
index 52314527c..19334640a 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/__init__.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/__init__.py
@@ -23,6 +23,7 @@ def _validate(model: type[BaseModel], values: dict[str, Any]) -> Any:
:param model: 目标参数模型
:param values: 原始参数字段
:return: 已校验的模型;无效输入返回 HTTP 422
+ :raises HTTPException: 路径或查询参数未通过模型校验
"""
try:
return model.model_validate(values)
@@ -88,24 +89,48 @@ def create_app(context: PluginHostContext) -> FastAPI:
:return: 任务管理 ASGI 子应用
"""
app = FastAPI(title='持久化任务示例', docs_url=None, redoc_url=None, openapi_url=None)
- app.add_api_route('/api/info', plugin_endpoint(info, permission='task_demo:view'), methods=['GET'])
- app.add_api_route('/api/tasks', plugin_endpoint(list_tasks, permission='task_demo:view'), methods=['GET'])
app.add_api_route(
- '/api/tasks/{task_id}', plugin_endpoint(get_task, permission='task_demo:view'), methods=['GET']
+ '/api/info',
+ plugin_endpoint(info, permission='task_demo:view'),
+ summary='查询任务插件信息',
+ description='返回插件标识、版本,以及当前用户是否可以修改任务。',
+ methods=['GET'],
+ )
+ app.add_api_route(
+ '/api/tasks',
+ plugin_endpoint(list_tasks, permission='task_demo:view'),
+ summary='分页查询任务',
+ description='按完成状态筛选任务,并返回指定页的任务记录。',
+ methods=['GET'],
+ )
+ app.add_api_route(
+ '/api/tasks/{task_id}',
+ plugin_endpoint(get_task, permission='task_demo:view'),
+ summary='查询任务详情',
+ description='按路径中的任务标识读取单条任务记录。',
+ methods=['GET'],
)
app.add_api_route(
'/api/tasks',
plugin_endpoint(create_task, permission='task_demo:write', body_model=TaskInput, max_body_bytes=8192),
+ summary='创建任务',
+ description='校验任务标题、内容、状态与优先级,保存并返回新建的任务。',
methods=['POST'],
status_code=201,
)
app.add_api_route(
'/api/tasks/{task_id}',
plugin_endpoint(update_task, permission='task_demo:write', body_model=TaskInput, max_body_bytes=8192),
+ summary='更新任务',
+ description='按任务标识替换标题、内容、状态和优先级,并返回更新结果。',
methods=['PUT'],
)
app.add_api_route(
- '/api/tasks/{task_id}', plugin_endpoint(delete_task, permission='task_demo:write'), methods=['DELETE']
+ '/api/tasks/{task_id}',
+ plugin_endpoint(delete_task, permission='task_demo:write'),
+ summary='删除任务',
+ description='删除指定标识的任务并返回删除结果。',
+ methods=['DELETE'],
)
return app
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/build_release.py b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/build_release.py
index 1faacc6d9..3dcc90a14 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/build_release.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/build_release.py
@@ -13,7 +13,12 @@
from pathlib import PureWindowsPath
def is_windows_reserved(name: str) -> bool:
- """按 Windows 规则识别保留路径名。"""
+ """
+ 按 Windows 规则识别保留路径名。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 是否按 Windows 规则识别保留路径名
+ """
return PureWindowsPath(name).is_reserved()
@@ -67,6 +72,7 @@ def checked_file(path: Path) -> Path:
:param path: 待交付的源码文件路径
:return: 通过检查的源码文件路径
+ :raises ValueError: 交付文件越出源码目录或路径包含不允许的链接
"""
for part in (path, *path.parents):
if part == SOURCE:
@@ -88,6 +94,7 @@ def checked_relative_path(value: str) -> tuple[str, ...]:
:param value: 清单或 bundle 中的相对路径
:return: 未经折叠或重写的路径组件
+ :raises ValueError: 交付路径必须为字符串
"""
if not isinstance(value, str):
raise ValueError('交付路径必须为字符串')
@@ -119,7 +126,7 @@ def checked_inventory(names: list[str]) -> None:
拒绝重复文件、文件与目录冲突以及任一级目录的大小写歧义。
:param names: 全部交付文件的相对路径
- :return: None
+ :raises ValueError: 交付清单存在文件与父目录冲突
"""
spellings: dict[str, str] = {}
files: set[str] = set()
@@ -146,6 +153,7 @@ def unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
:param pairs: JSON 对象按原始顺序出现的字段
:return: 不包含重复字段的对象
+ :raises ValueError: 交付清单的 JSON 对象中出现重复字段
"""
result = {}
for key, value in pairs:
@@ -160,6 +168,7 @@ def source_resources() -> list[Path]:
按有大小和数量上限的显式清单读取 Python、SQL 资源,不扫描业务源码。
:return: 已通过路径、类型和链接检查的源码文件列表
+ :raises ValueError: release-files.json 超过 64 KiB 上限;release-files.json 必须包含 schemaVersion: 1 和 files;交付清单 files 必须为包含 1 至 1024 项的列表
"""
path = checked_file(SOURCE / RELEASE_MANIFEST)
with path.open('rb') as source:
@@ -197,6 +206,7 @@ def bundle_resources() -> list[Path]:
收集已构建 bundle,保留原有静态扩展名、隐藏文件和链接限制。
:return: 已通过检查的 web/dist 文件列表
+ :raises ValueError: bundle 入口必须使用准确的 index.html 文件名
"""
dist = SOURCE / 'web' / 'dist'
checked_file(dist / 'index.html')
@@ -215,11 +225,7 @@ def bundle_resources() -> list[Path]:
def main() -> None:
- """
- 按显式文件清单组装新交付目录,不安装依赖、导入插件或生成签名。
-
- :return: None
- """
+ """按显式文件清单组装新交付目录,不安装依赖、导入插件或生成签名。"""
parser = argparse.ArgumentParser(
description='按 release-files.json 组装交付文件;不安装依赖、不导入插件、不生成签名。'
)
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/models.py b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/models.py
index b95ecefcd..a196ab40e 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/models.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/models.py
@@ -10,13 +10,13 @@
tasks = Table(
'ruoyi_plugin_task_demo',
metadata,
- Column('id', String(32), primary_key=True),
- Column('title', String(120), nullable=False),
- Column('description', String(500), nullable=False, server_default=''),
- Column('status', String(4), nullable=False, server_default='todo'),
- Column('created_at', DbUtcDateTime, nullable=False),
- Column('updated_at', DbUtcDateTime, nullable=False),
- Column('priority', String(6), nullable=False, server_default='normal'),
+ Column('id', String(32), primary_key=True, comment='任务标识'),
+ Column('title', String(120), nullable=False, comment='任务标题'),
+ Column('description', String(500), nullable=False, server_default='', comment='任务内容说明'),
+ Column('status', String(4), nullable=False, server_default='todo', comment='任务完成状态'),
+ Column('created_at', DbUtcDateTime, nullable=False, comment='任务创建时间'),
+ Column('updated_at', DbUtcDateTime, nullable=False, comment='任务更新时间'),
+ Column('priority', String(6), nullable=False, server_default='normal', comment='任务优先级'),
CheckConstraint("status IN ('todo', 'done')", name='ck_task_demo_status'),
CheckConstraint("priority IN ('normal', 'high')", name='ck_task_demo_priority'),
)
@@ -27,10 +27,12 @@ class TaskInput(BaseModel):
model_config = ConfigDict(extra='forbid')
- title: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=120)]
- description: str = Field(default='', max_length=500)
- status: Literal['todo', 'done'] = 'todo'
- priority: Literal['normal', 'high'] = 'normal'
+ title: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=120)] = Field(
+ description='任务标题'
+ )
+ description: str = Field(default='', max_length=500, description='任务内容说明')
+ status: Literal['todo', 'done'] = Field(default='todo', description='当前状态')
+ priority: Literal['normal', 'high'] = Field(default='normal', description='任务优先级')
@field_validator('title', 'description')
@classmethod
@@ -40,6 +42,7 @@ def reject_control_characters(cls, value: str) -> str:
:param value: 标题或描述文本
:return: 已校验的文本
+ :raises ValueError: 文本不能包含不可显示的控制字符
"""
if any(ord(character) < MIN_PRINTABLE_CODEPOINT and character not in '\n\r\t' for character in value):
raise ValueError('文本不能包含不可显示的控制字符')
@@ -51,12 +54,12 @@ class TaskQuery(BaseModel):
model_config = ConfigDict(extra='forbid')
- page: int = Field(default=1, ge=1, le=1_000_000)
- page_size: int = Field(default=10, ge=1, le=20, alias='pageSize')
- status: Literal['todo', 'done'] | None = None
+ page: int = Field(default=1, ge=1, le=1_000_000, description='查询页码')
+ page_size: int = Field(default=10, ge=1, le=20, alias='pageSize', description='每页返回的记录数')
+ status: Literal['todo', 'done'] | None = Field(default=None, description='当前状态')
class TaskIdentifier(BaseModel):
"""用于路径参数的插件任务标识。"""
- id: str = Field(pattern=r'^[0-9a-f]{32}$')
+ id: str = Field(pattern=r'^[0-9a-f]{32}$', description='任务标识')
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/service.py b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/service.py
index 80036c74f..e5d2a953c 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/service.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/service.py
@@ -75,6 +75,7 @@ async def get_task(context: PluginRequestContext, task_id: str) -> dict[str, Any
:param context: 宿主提供的请求身份
:param task_id: 已校验的任务标识
:return: 任务对象;不存在时返回 HTTP 404
+ :raises HTTPException: 任务不存在
"""
async with context.transaction() as transaction:
result = await transaction.transaction_session().execute(select(tasks).where(tasks.c.id == task_id))
@@ -107,6 +108,7 @@ async def update_task(context: PluginRequestContext, task_id: str, values: dict[
:param task_id: 已校验的任务标识
:param values: 已校验的任务输入
:return: 更新后的任务对象;不存在时返回 HTTP 404
+ :raises HTTPException: 任务不存在
"""
async with context.transaction() as transaction:
db = transaction.transaction_session()
@@ -126,6 +128,7 @@ async def delete_task(context: PluginRequestContext, task_id: str) -> dict[str,
:param context: 宿主提供的请求身份
:param task_id: 已校验的任务标识
:return: 删除确认;不存在时返回 HTTP 404
+ :raises HTTPException: 任务不存在
"""
async with context.transaction() as transaction:
result = await transaction.transaction_session().execute(delete(tasks).where(tasks.c.id == task_id))
diff --git a/ruoyi-fastapi-backend/requirements-pg.txt b/ruoyi-fastapi-backend/requirements-pg.txt
index 36c04c2da..02cf298b6 100644
--- a/ruoyi-fastapi-backend/requirements-pg.txt
+++ b/ruoyi-fastapi-backend/requirements-pg.txt
@@ -5,6 +5,7 @@ async-lru==2.4.0
asyncpg==0.32.0
Babel==2.18.0
bcrypt==5.0.0
+docutils==0.22.4
fastapi[all]==0.165.0
loguru==0.8.0
nh3==0.3.8
@@ -19,6 +20,7 @@ pydantic-validation-decorator==0.1.5
PyJWT[crypto]==2.15.1
redis==8.1.0
ruff==0.17.6
+Sphinx==9.0.4
SQLAlchemy[asyncio]==2.1.9
sqlglot==30.33.0
textual==8.2.8
diff --git a/ruoyi-fastapi-backend/requirements.txt b/ruoyi-fastapi-backend/requirements.txt
index 73d5ee9c4..5c86e9130 100644
--- a/ruoyi-fastapi-backend/requirements.txt
+++ b/ruoyi-fastapi-backend/requirements.txt
@@ -5,6 +5,7 @@ async-lru==2.4.0
asyncmy==0.2.18
Babel==2.18.0
bcrypt==5.0.0
+docutils==0.22.4
fastapi[all]==0.165.0
loguru==0.8.0
nh3==0.3.8
@@ -19,6 +20,7 @@ PyJWT[crypto]==2.15.1
PyMySQL==1.2.4
redis==8.1.0
ruff==0.17.6
+Sphinx==9.0.4
SQLAlchemy[asyncio]==2.1.9
sqlglot==30.33.0
textual==8.2.8
diff --git a/ruoyi-fastapi-backend/ruff.toml b/ruoyi-fastapi-backend/ruff.toml
index 5d6399b8c..c7ef22486 100644
--- a/ruoyi-fastapi-backend/ruff.toml
+++ b/ruoyi-fastapi-backend/ruff.toml
@@ -12,6 +12,10 @@ select = [
"A", # flake8-builtins
"COM", # flake8-commas
"C4", # flake8-comprehensions
+ "D2", # docstring layout; dev lint checks presence with route and model context
+ "D213", # 多行文档字符串的摘要从第二行开始
+ "D3", # docstring quotation marks
+ "D4", # docstring content
"ISC", # flake8-implicit-str-concat
"ICN", # flake8-import-conventions
"PIE", # flake8-pie
@@ -37,6 +41,7 @@ ignore = [
"ANN401", # dynamically typed expressions (typing.Any) are disallowed in {name}
"B008", # do not perform function calls in argument defaults
"COM812", # trailing comma missing
+ "D400", # dev lint checks terminal punctuation in both Chinese and English
"RET504", # unnecessary assignment to {name} before return statement
"SIM105", # use contextlib.suppress({exception}) instead of try-except-pass
"C901", # too complex
@@ -49,12 +54,20 @@ ignore = [
"RUF012", # mutable class attributes should be annotated with typing.ClassVar
]
+[lint.per-file-ignores]
+"alembic/env.py" = ["D"] # Preserve Alembic's original documentation.
+"common/router.py" = ["D205"] # APIRouterPro retains the original FastAPI example.
+
[lint.flake8-type-checking]
runtime-evaluated-base-classes = ["pydantic.BaseModel", "sqlalchemy.orm.DeclarativeBase"]
[lint.isort]
known-third-party = ["alembic"]
+[lint.pydocstyle]
+# Use general layout rules; parameters and return values use reST fields.
+convention = "pep257"
+
[lint.pylint]
max-args = 10
max-returns = 10
@@ -65,4 +78,4 @@ keep-runtime-typing = true
[format]
docstring-code-format = true
-quote-style = "single"
\ No newline at end of file
+quote-style = "single"
diff --git a/ruoyi-fastapi-backend/scripts/build_native_plugin.py b/ruoyi-fastapi-backend/scripts/build_native_plugin.py
index c328a4338..662bdfe32 100644
--- a/ruoyi-fastapi-backend/scripts/build_native_plugin.py
+++ b/ruoyi-fastapi-backend/scripts/build_native_plugin.py
@@ -19,6 +19,7 @@ def _resource_roots(source: Path, manifest: Any, output: Path) -> list[Path]:
:param manifest: 已解析的插件清单
:param output: 待创建的构建输出目录
:return: 通过路径检查的部署资源根路径
+ :raises ValueError: 缺少 bundle HTML 入口,请先独立构建前端后再组装制品;输出目录不能位于待交付资源目录内
"""
from plugins.core.artifacts.package import is_link_or_reparse # noqa: PLC0415
from plugins.core.artifacts.schema import safe_artifact_path # noqa: PLC0415
@@ -57,6 +58,7 @@ def collect_deployment_resources(source: Path, manifest: Any, output: Path) -> d
:param manifest: 已解析的插件清单
:param output: 待创建的构建输出目录
:return: 插件内相对路径与对应源码文件的映射
+ :raises ValueError: 交付资源超过制品文件数量或大小限制
"""
from plugins.core.artifacts.package import ( # noqa: PLC0415
CACHE_DIRECTORIES,
@@ -117,7 +119,7 @@ def main() -> None:
"""
构建原生 wheel 并组装可离线交付的插件目录与 ZIP。
- :return: None
+ :raises ValueError: 交付资源不能越过插件目录
"""
parser = argparse.ArgumentParser(
description='构建、静态验证并组装原生插件;使用当前 Python 环境,不写入运行中的 plugins。'
diff --git a/ruoyi-fastapi-backend/scripts/check_docstrings.py b/ruoyi-fastapi-backend/scripts/check_docstrings.py
new file mode 100644
index 000000000..067915ef5
--- /dev/null
+++ b/ruoyi-fastapi-backend/scripts/check_docstrings.py
@@ -0,0 +1,1326 @@
+import ast
+import builtins
+import re
+import subprocess
+import sys
+import tokenize
+from collections.abc import Iterator
+from contextlib import contextmanager
+from dataclasses import dataclass
+from functools import cache
+from io import StringIO
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from docutils import frontend, nodes, utils
+from docutils.parsers.rst import Parser
+from sphinx.application import Sphinx
+from sphinx.domains.python import PyObject
+from sphinx.errors import SphinxWarning
+from sphinx.util.docstrings import prepare_docstring
+from sphinx.util.docutils import docutils_namespace, sphinx_domains
+
+# key 是 Python 域文档列出的参数别名,meta 由 autodoc 消费。
+FIELD_KINDS = {'key': 'parameter', 'meta': 'meta', 'yield': 'yieldvalue', 'yields': 'yieldvalue'}
+CHINESE = re.compile(r'[\u3400-\u9fff\U00020000-\U0002fa1f]')
+KEYWORD_FIELDS = {'key', 'keyword', 'kwarg', 'kwparam'}
+MAX_TYPED_FIELD_WORDS = 2
+for field_type in PyObject.doc_field_types:
+ FIELD_KINDS.update(dict.fromkeys(field_type.names, field_type.name))
+ FIELD_KINDS.update(dict.fromkeys(getattr(field_type, 'typenames', ()), f'{field_type.name}type'))
+ROLE = re.compile(r'^:(?:[\w-]+:)+`')
+SECTION = re.compile(
+ r'(?:Args?|Arguments?|Parameters?|Other Parameters|Keyword (?:Args|Arguments|Parameters)|'
+ r'Returns?|Yields?|Raises?|Warns?|Warnings?|Attributes?|Methods?|Receives|'
+ r'参数|返回值?|异常)([::]?)',
+ re.IGNORECASE,
+)
+FOREIGN_MARKUP = re.compile(
+ r'^(?:@(?:param|type|returns?|rtype|raises?|throws|yields?|brief)\b|#{1,6}\s|`{3}|~{3,}\w|'
+ r'(?:Examples?|Notes?|See Also|References):$|(?:param|raises)\s+\w+:|:\w+)',
+ re.IGNORECASE,
+)
+MARKDOWN_LINK = re.compile(r'\[[^]\n]+\]\([^\s)]+\)')
+UNPARSED_LITERAL = re.compile(r'(? Iterator[ast.stmt]:
+ """
+ 遍历当前作用域的语句,在新函数和类的边界停止。
+
+ :param suite: 当前词法作用域中的语句列表
+ :yield: 当前词法作用域中的语句
+ """
+ for statement in suite:
+ yield statement
+ if not isinstance(statement, DEFINITIONS):
+ for child in ast.iter_child_nodes(statement):
+ if isinstance(child, ast.stmt):
+ yield from scoped_statements([child])
+ elif isinstance(child, (ast.ExceptHandler, ast.match_case)):
+ yield from scoped_statements(child.body)
+
+
+def statement_calls(item: ast.stmt) -> Iterator[ast.Call]:
+ """
+ 遍历语句表达式中的调用,包括推导式,子语句由其作用域单独处理。
+
+ :param item: 当前作用域的语句
+ :yield: 语句自身包含的调用表达式
+ """
+ for expr in ast.iter_child_nodes(item):
+ if isinstance(expr, ast.expr):
+ yield from (call for call in ast.walk(expr) if isinstance(call, ast.Call))
+
+
+def model_symbols(
+ tree: ast.Module, module: str, package: str, tables: dict[ast.Call, Bindings] | None = None
+) -> tuple[dict[str, tuple[str, ...]], dict[ast.ClassDef, tuple[str, Bindings]]]:
+ """
+ 从源码收集导入别名、基类和声明式模型工厂,无需导入业务模块。
+
+ :param tree: 待校验源码的抽象语法树
+ :param module: 当前源码模块的完整名称
+ :param package: 用于解析相对导入的包名
+ :param tables: 接收当前文件显式 Table 声明及其名称绑定的索引
+ :return: 依次为 ``symbols``、``classes`` 的元组
+ """
+ symbols = {}
+ classes = {}
+
+ def visit(suite: list[ast.stmt], prefix: str, names: dict[str, str], bindings: Bindings) -> None:
+ """
+ 解析当前作用域的绑定,并记录每个类的完整名称。
+
+ :param suite: 当前词法作用域中的语句列表
+ :param prefix: 当前作用域的完整名称前缀
+ :param names: 当前作用域中可用的名称绑定
+ :param bindings: 字段声明能引用的导入和赋值
+ """
+
+ def reference(expr: ast.expr) -> str:
+ """
+ 将基类表达式展开为带模块名的引用。
+
+ :param expr: 需要解析的基类或别名表达式
+ :return: 含模块前缀的基类名称,无法解析时为空字符串
+ """
+ if isinstance(expr, ast.Subscript):
+ return reference(expr.value)
+ if isinstance(expr, ast.Name):
+ return names.get(expr.id, expr.id)
+ if isinstance(expr, ast.Attribute):
+ return f'{reference(expr.value)}.{expr.attr}'
+ return ''
+
+ for item in scoped_statements(suite):
+ if tables is not None:
+ tables.update(
+ (call, bindings.copy())
+ for call in statement_calls(item)
+ if imported_name(call.func, bindings) in TABLE_CALLS
+ )
+ if isinstance(item, ast.Import):
+ for alias in item.names:
+ head = alias.name.split('.')[0]
+ names[alias.asname or head] = alias.name if alias.asname else head
+ bindings[alias.asname or head] = names[alias.asname or head]
+ elif isinstance(item, ast.ImportFrom):
+ parts = package.split('.') if item.level else []
+ if item.level > 1:
+ parts = parts[: 1 - item.level]
+ origin = '.'.join(filter(None, [*parts, item.module]))
+ for alias in item.names:
+ name = alias.asname or alias.name
+ names[name] = f'{origin}.{alias.name}'.strip('.')
+ bindings[name] = names[name]
+ symbols[f'{prefix}.{name}'] = (names[name],)
+ elif isinstance(item, ast.Assign) and len(item.targets) == 1 and isinstance(item.targets[0], ast.Name):
+ name = item.targets[0].id
+ base = reference(item.value.func) + '()' if isinstance(item.value, ast.Call) else reference(item.value)
+ names[name] = f'{prefix}.{name}'
+ symbols[names[name]] = (base,)
+ bindings[name] = item.value
+ elif isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name) and item.value is not None:
+ bindings[item.target.id] = item.value
+ elif isinstance(item, DEFINITIONS):
+ qualified = f'{prefix}.{item.name}'
+ if isinstance(item, ast.ClassDef):
+ decorators = (d.func if isinstance(d, ast.Call) else d for d in item.decorator_list)
+ mapped = (
+ d
+ for d in decorators
+ if isinstance(d, ast.Attribute) and d.attr in {'mapped', 'mapped_as_dataclass'}
+ )
+ symbols[qualified] = tuple(reference(base) for base in (*item.bases, *mapped))
+ classes[item] = (qualified, bindings.copy())
+ names[item.name] = qualified
+ visit(item.body, qualified, names.copy(), bindings.copy())
+
+ visit(tree.body, module, {}, {})
+ return symbols, classes
+
+
+def model_classes(
+ tree: ast.Module, path: Path, tables: dict[ast.Call, Bindings]
+) -> dict[ast.ClassDef, tuple[str | None, Bindings]]:
+ """
+ 沿本地源码的继承关系识别模型,支持单文件检查及跨模块派生。
+
+ :param tree: 待校验源码的抽象语法树
+ :param path: 要读取或处理的路径
+ :param tables: 接收显式声明的数据库表
+ :return: 每个类对应的模型种类和字段可见的名称绑定
+ """
+ path = path.resolve()
+ root = next((folder for folder in path.parents if (folder / 'ruff.toml').is_file()), path.parent)
+ while (root / '__init__.py').is_file():
+ root = root.parent
+ roots = (root, path.parent, BACKEND)
+ module = '.'.join(path.relative_to(root).with_suffix('').parts).removesuffix('.__init__')
+ package = module if path.stem == '__init__' else module.rpartition('.')[0]
+ symbols, classes = model_symbols(tree, module, package, tables)
+
+ @cache
+ def load_module(name: str) -> dict[str, tuple[str, ...]]:
+ """
+ 读取导入目标的基类索引,包括包对基类的重新导出。
+
+ :param name: 要读取的本地模块的完整名称
+ :return: 导入目标的基类索引
+ """
+ relative = Path(*name.split('.'))
+ for folder in roots:
+ for target in (folder / relative.with_suffix('.py'), folder / relative / '__init__.py'):
+ if target.is_file():
+ with tokenize.open(target) as stream:
+ imported = ast.parse(stream.read(), filename=str(target))
+ parent = name if target.stem == '__init__' else name.rpartition('.')[0]
+ return model_symbols(imported, name, parent)[0]
+ return {}
+
+ def model_kind(name: str, seen: set[str], registry: bool = False) -> str | None:
+ """
+ 判断引用是否最终指向已知模型基类或工厂,遇到循环引用时停止。
+
+ :param name: 待解析的基类或注册表引用
+ :param seen: 当前解析链中已访问的名称
+ :param registry: 是否只匹配 SQLAlchemy 映射注册表
+ :return: 识别到的模型种类,普通类返回空值
+ """
+ if name in seen or not name:
+ return None
+ if registry and name == 'sqlalchemy.orm.registry()':
+ return 'sqlalchemy'
+ if not registry:
+ if name in MODEL_BASES or (name.endswith('()') and name[:-2] in MODEL_FACTORIES):
+ return 'pydantic' if name.startswith('pydantic') else 'sqlalchemy'
+ owner, _, method = name.rpartition('.')
+ if method in {'generate_base()', 'mapped', 'mapped_as_dataclass'}:
+ return model_kind(owner, seen | {name}, registry=True)
+ bases = symbols.get(name)
+ if bases is None:
+ origin, _, _ = name.rpartition('.')
+ bases = load_module(origin).get(name, ()) if all(part.isidentifier() for part in origin.split('.')) else ()
+ return next((kind for base in bases if (kind := model_kind(base, seen | {name}, registry))), None)
+
+ return {node: (model_kind(name, set()), bindings) for node, (name, bindings) in classes.items()}
+
+
+def resolve_binding(expr: ast.expr | None, bindings: Bindings) -> ast.expr | str | None:
+ """
+ 展开当前作用域中的别名与常量,保留无法静态求值的表达式。
+
+ :param expr: 字段声明中的表达式
+ :param bindings: 当前可用的名称绑定
+ :return: 导入的完整名称、绑定的表达式或空值
+ """
+ seen = set()
+ while isinstance(expr, ast.Name) and expr.id in bindings and expr.id not in seen:
+ seen.add(expr.id)
+ expr = bindings[expr.id]
+ return expr
+
+
+def imported_name(expr: ast.expr | None, bindings: Bindings) -> str:
+ """
+ 解析调用、装饰器或类型标注引用的导入名称。
+
+ :param expr: 要解析的名称或属性访问
+ :param bindings: 当前可用的名称绑定
+ :return: 导入的完整名称,无法解析时返回空字符串
+ """
+ parts = []
+ seen = set()
+ resolved = resolve_binding(expr, bindings)
+ while isinstance(resolved, ast.Attribute) and resolved not in seen:
+ seen.add(resolved)
+ parts.append(resolved.attr)
+ resolved = resolve_binding(resolved.value, bindings)
+ return '.'.join([resolved, *reversed(parts)]) if isinstance(resolved, str) else ''
+
+
+def field_annotation(annotation: ast.expr | None, bindings: Bindings) -> tuple[set[str], list[ast.expr]]:
+ """
+ 提取直接作用于字段的类型包装和 Annotated 元数据。
+
+ :param annotation: 字段的类型标注
+ :param bindings: 当前可用的名称绑定
+ :return: 字段的外层类型和按覆盖顺序排列的元数据
+ """
+ wrappers = set()
+ metadata = []
+ seen = set()
+ while annotation is not None:
+ value = resolve_binding(annotation, bindings)
+ if value in seen:
+ break
+ seen.add(value)
+ if isinstance(value, ast.Constant) and isinstance(value.value, str):
+ try:
+ annotation = ast.parse(value.value, mode='eval').body
+ except SyntaxError:
+ break
+ continue
+ if not isinstance(value, ast.Subscript):
+ wrappers.add(imported_name(annotation, bindings))
+ break
+ kind = imported_name(value.value, bindings)
+ wrappers.add(kind)
+ if kind in ANNOTATED and isinstance(value.slice, ast.Tuple):
+ annotation, *items = value.slice.elts
+ metadata[:0] = items
+ elif kind == 'sqlalchemy.orm.Mapped':
+ annotation = value.slice
+ else:
+ break
+ return wrappers, metadata
+
+
+def missing_chinese_text(expr: ast.expr | None, bindings: Bindings) -> bool:
+ """
+ 判断说明是否缺失,或其可静态解析的值不是含中文的文本。
+
+ :param expr: 提供说明的表达式
+ :param bindings: 当前作用域的名称绑定
+ :return: 是否应报告说明无效
+ """
+ value = resolve_binding(expr, bindings)
+ if isinstance(value, ast.Constant):
+ return not isinstance(value.value, str) or CHINESE.search(value.value) is None
+ return value is None or isinstance(value, (ast.List, ast.Tuple, ast.Set, ast.Dict))
+
+
+def metadata_problem(calls: list[ast.expr], keyword: str, bindings: Bindings) -> bool:
+ """
+ 检查字段的有效说明,允许引用共享说明和运行时计算的文本。
+
+ :param calls: 按字段元数据覆盖顺序排列的声明
+ :param keyword: 指定说明的关键字名称
+ :param bindings: 当前可用的名称绑定
+ :return: 是否缺少说明或已知说明未包含中文
+ """
+ values = [
+ kw.value
+ for expr in calls
+ if isinstance(call := resolve_binding(expr, bindings), ast.Call)
+ for kw in call.keywords
+ if kw.arg == keyword
+ ]
+ return missing_chinese_text(values[-1] if values else None, bindings)
+
+
+def model_field_errors(owner: ast.ClassDef, kind: str | None, bindings: Bindings) -> Iterator[tuple[int, str]]:
+ """
+ 校验 Pydantic 模型字段、计算字段和 SQLAlchemy 映射列的说明。
+
+ :param owner: 包含字段声明的类
+ :param kind: 从继承关系解析出的模型种类
+ :param bindings: 类定义可见的导入和赋值
+ :yield: 字段声明行号及缺失的元数据
+ """
+
+ def call_name(expr: ast.expr | None) -> str:
+ """
+ 解析字段构造器的导入名称。
+
+ :param expr: 可能通过别名引用的调用表达式
+ :return: 构造器的完整名称
+ """
+ value = resolve_binding(expr, bindings)
+ return imported_name(value.func, bindings) if isinstance(value, ast.Call) else ''
+
+ def check(name: str, line: int, keyword: str, declarations: list[ast.expr]) -> Iterator[tuple[int, str]]:
+ """
+ 将无效的字段说明转换为包含类名的诊断。
+
+ :param name: 字段名称
+ :param line: 声明所在行号
+ :param keyword: 字段说明的关键字
+ :param declarations: 提供元数据的字段声明
+ :yield: 行号和诊断文本
+ """
+ if metadata_problem(declarations, keyword, bindings):
+ yield line, f'{owner.name}.{name} 必须填写含中文的 {keyword}'
+
+ def method_fields(method: ast.FunctionDef | ast.AsyncFunctionDef) -> Iterator[tuple[int, str]]:
+ """
+ 检查装饰器声明的计算字段和由方法创建的映射列。
+
+ :param method: 可能用于构造模型字段的方法
+ :yield: 计算字段或映射列的诊断
+ """
+ for decorator in method.decorator_list:
+ name = imported_name(decorator.func if isinstance(decorator, ast.Call) else decorator, bindings)
+ if kind == 'pydantic' and name in COMPUTED_FIELD:
+ yield from check(method.name, method.lineno, 'description', [decorator])
+ if name == 'sqlalchemy.orm.declared_attr':
+ for stmt in scoped_statements(method.body):
+ if (
+ isinstance(stmt, ast.Return)
+ and stmt.value is not None
+ and call_name(stmt.value) in COLUMN_CALLS
+ ):
+ yield from check(method.name, stmt.lineno, 'comment', [stmt.value])
+
+ for item in scoped_statements(owner.body):
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ yield from method_fields(item)
+ if not isinstance(item, (ast.Assign, ast.AnnAssign)):
+ continue
+ targets = item.targets if isinstance(item, ast.Assign) else [item.target]
+ annotation = item.annotation if isinstance(item, ast.AnnAssign) else None
+ wrappers, metadata = field_annotation(annotation, bindings)
+ candidates = [*metadata, item.value] if item.value is not None else metadata
+ for target in targets:
+ if not isinstance(target, ast.Name):
+ continue
+ name = target.id
+ if (
+ kind == 'pydantic'
+ and annotation
+ and not (name.startswith('_') or name == 'model_config' or wrappers & CLASS_VAR)
+ ):
+ fields = [expr for expr in candidates if call_name(expr) in FIELD_CALLS]
+ yield from check(name, item.lineno, 'description', fields)
+ else:
+ columns = [expr for expr in candidates if call_name(expr) in COLUMN_CALLS]
+ if columns or (item.value is None and 'sqlalchemy.orm.Mapped' in wrappers):
+ yield from check(name, item.lineno, 'comment', columns)
+ if item.value is not None:
+ bindings[name] = item.value
+
+
+def table_field_errors(tables: dict[ast.Call, Bindings]) -> Iterator[tuple[int, str]]:
+ """
+ 检查通过 SQLAlchemy Table 显式传入的列,覆盖插件独立定义的表。
+
+ :param tables: 按源码顺序收集的表声明及其名称绑定
+ :yield: 缺少列说明的位置与诊断
+ """
+ for table, bindings in tables.items():
+ for expr in table.args:
+ column = resolve_binding(expr, bindings)
+ if (
+ isinstance(column, ast.Call)
+ and imported_name(column.func, bindings) in COLUMN_CALLS
+ and metadata_problem([column], 'comment', bindings)
+ ):
+ table_name = ast.unparse(table.args[0]).strip('"\'')
+ name = ast.unparse(column.args[0]).strip('"\'') if column.args else '列'
+ yield column.lineno, f'{table_name}.{name} 必须填写含中文的 comment'
+
+
+def assigned_names(target: ast.expr, receiver: str | None) -> Iterator[str]:
+ """
+ 提取单一或解包赋值中属于当前类或绑定方法接收者的属性。
+
+ :param target: 赋值语句左侧的表达式
+ :param receiver: 方法的隐式接收者名称,类体赋值时为空
+ :yield: 归属于该类或接收者的属性名称
+ """
+ if isinstance(target, (ast.Tuple, ast.List)):
+ for element in target.elts:
+ yield from assigned_names(element, receiver)
+ elif isinstance(target, ast.Starred):
+ yield from assigned_names(target.value, receiver)
+ elif receiver is None and isinstance(target, ast.Name):
+ yield target.id
+ elif isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == receiver:
+ yield target.attr
+
+
+def class_attributes(owner: ast.ClassDef) -> set[str]:
+ """
+ 收集类体的属性声明,以及绑定方法直接写入的实例或类属性。
+
+ :param owner: 要收集属性的类定义
+ :return: 类体的属性声明
+ """
+
+ def assignments(suite: list[ast.stmt], receiver: str | None) -> Iterator[str]:
+ """
+ 从当前作用域的赋值语句中读取属性名。
+
+ :param suite: 当前词法作用域中的语句列表
+ :param receiver: 方法的隐式接收者名称,类体赋值时为空
+ :yield: 委托迭代器逐项提供的元素
+ """
+ for item in scoped_statements(suite):
+ if isinstance(item, (ast.AnnAssign, ast.Assign)):
+ targets = item.targets if isinstance(item, ast.Assign) else [item.target]
+ for target in targets:
+ if receiver is None and isinstance(target, ast.Name) and target.id == '__slots__':
+ value = item.value
+ slots = value.elts if isinstance(value, (ast.Tuple, ast.List)) else [value]
+ if isinstance(value, ast.Dict):
+ slots = value.keys
+ yield from (s.value for s in slots if isinstance(s, ast.Constant) and isinstance(s.value, str))
+ else:
+ yield from assigned_names(target, receiver)
+
+ names = set(assignments(owner.body, None))
+ for method in scoped_statements(owner.body):
+ if isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)) and (receiver := bound_receiver(method)):
+ names.update(assignments(method.body, receiver))
+ return names
+
+
+def bound_receiver(method: ast.FunctionDef | ast.AsyncFunctionDef) -> str | None:
+ """
+ 返回绑定方法的首个位置参数,静态方法没有隐式参数。
+
+ :param method: 待分析的方法定义
+ :return: 绑定方法的首个位置参数
+ """
+ positional = method.args.posonlyargs or method.args.args
+ if not positional or any(
+ ast.unparse(d) in {'staticmethod', 'builtins.staticmethod'} for d in method.decorator_list
+ ):
+ return None
+ return positional[0].arg
+
+
+def route_doc_errors(call: ast.Call, bindings: Bindings) -> Iterator[tuple[int, str]]:
+ """
+ 检查单次 HTTP 路径操作注册的摘要和说明,支持共享的元数据字典。
+
+ :param call: 路由装饰器或注册调用
+ :param bindings: 注册时可见的局部赋值
+ :yield: 缺失或无效的路由文档字段及其行号
+ """
+ fields = {}
+ for kw in call.keywords:
+ if kw.arg is not None:
+ fields[kw.arg] = kw.value
+ elif isinstance(mapping := resolve_binding(kw.value, bindings), ast.Dict):
+ fields.update(
+ (key.value, value)
+ for key, value in zip(mapping.keys, mapping.values, strict=True)
+ if isinstance(key, ast.Constant)
+ )
+ for field in ('summary', 'description'):
+ if missing_chinese_text(fields.get(field), bindings):
+ yield call.lineno, f'HTTP 路由必须填写含中文的 {field}'
+
+
+def registered_callback(call: ast.Call) -> ast.expr | None:
+ """
+ 取出显式注册的端点,包括 SDK 权限包装器内的插件回调。
+
+ :param call: 注册路由端点的调用表达式
+ :return: 注册调用中的原始端点表达式
+ """
+ callback = next((kw.value for kw in call.keywords if kw.arg == 'endpoint'), None)
+ if callback is None and len(call.args) > 1:
+ callback = call.args[1]
+ if (
+ isinstance(callback, ast.Call)
+ and ast.unparse(callback.func).split('.')[-1] == 'plugin_endpoint'
+ and callback.args
+ ):
+ return callback.args[0]
+ return callback
+
+
+def router_method(call: ast.expr, methods: set[str], routers: set[str]) -> bool:
+ """
+ 判断调用是否来自路由对象或应用自带的路由器。
+
+ :param call: 待识别的装饰器或注册调用
+ :param methods: 需要匹配的路由方法名
+ :param routers: 当前作用域的路由对象名称
+ :return: 调用是否来自路由对象或应用自带的路由器
+ """
+ if not isinstance(call, ast.Call) or not isinstance(call.func, ast.Attribute) or call.func.attr not in methods:
+ return False
+ receiver = call.func.value
+ if ast.unparse(receiver) in routers:
+ return True
+ if isinstance(receiver, ast.Attribute) and receiver.attr in {'router', 'webhooks'}:
+ receiver = receiver.value
+ return ast.unparse(receiver) in routers or (isinstance(receiver, ast.Attribute) and receiver.attr == 'app')
+
+
+def inspect_routes(tree: ast.Module) -> tuple[set[ast.AST], list[tuple[int, str]]]:
+ """
+ 识别路径操作装饰器和显式注册的端点,按作用域匹配回调。
+
+ :param tree: 待校验源码的抽象语法树
+ :return: 免写函数文档的端点集合,以及每次 HTTP 注册的文档诊断
+ """
+ routes = set()
+ errors = []
+ router_types = {'FastAPI', 'APIRouter', 'APIRouterPro', 'Starlette', 'Router'}
+ router_types.update(
+ alias.asname
+ for item in ast.walk(tree)
+ if isinstance(item, ast.ImportFrom)
+ for alias in item.names
+ if alias.name in router_types and alias.asname
+ )
+ factories = router_types | {
+ node.name
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef)
+ and node.returns
+ and ast.unparse(node.returns).strip('"\'').split('.')[-1] in router_types
+ }
+ api_route_types = {'fastapi.routing.APIRoute'} | {
+ alias.asname or alias.name
+ for node in ast.walk(tree)
+ if isinstance(node, ast.ImportFrom) and node.module == 'fastapi.routing'
+ for alias in node.names
+ if alias.name == 'APIRoute'
+ }
+
+ def router_names(statements: list[ast.stmt], owner: ast.AST, inherited: set[str]) -> set[str]:
+ """
+ 收集作用域中的路由对象,包括导入、类型标注和局部别名。
+
+ :param statements: 当前作用域的语句
+ :param owner: 定义当前作用域的节点
+ :param inherited: 外层作用域可引用的路由对象
+ :return: 当前作用域可识别的路由对象名称
+ """
+ names = inherited.copy()
+ if isinstance(owner, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ names.update(
+ arg.arg
+ for arg in (*owner.args.posonlyargs, *owner.args.args, *owner.args.kwonlyargs)
+ if arg.annotation and ast.unparse(arg.annotation).strip('"\'').split('.')[-1] in router_types
+ )
+ for node in statements:
+ if isinstance(node, ast.ImportFrom):
+ names.update(
+ alias.asname or alias.name
+ for alias in node.names
+ if alias.name.endswith(('router', 'controller', 'app'))
+ )
+ elif isinstance(node, (ast.Assign, ast.AnnAssign)):
+ typed = (
+ isinstance(node, ast.AnnAssign)
+ and ast.unparse(node.annotation).strip('"\'').split('.')[-1] in router_types
+ )
+ constructed = (
+ isinstance(node.value, ast.Call) and ast.unparse(node.value.func).split('.')[-1] in factories
+ )
+ if (
+ typed
+ or constructed
+ or (isinstance(node.value, (ast.Name, ast.Attribute)) and ast.unparse(node.value) in names)
+ ):
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
+ names.update(ast.unparse(target) for target in targets)
+ return names
+
+ def visit(
+ owner: ast.Module | ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef,
+ functions: dict[str, ast.AST],
+ routers: set[str],
+ bindings: Bindings,
+ ) -> None:
+ """
+ 在当前作用域中解析路由对象和注册调用,再检查嵌套定义。
+
+ :param owner: 定义当前作用域的模块、类或函数
+ :param functions: 当前作用域可引用的函数定义
+ :param routers: 当前作用域可见的路由器名称
+ :param bindings: 当前作用域可见的路由元数据
+ """
+ statements = list(scoped_statements(owner.body))
+ functions = functions | {node.name: node for node in statements if isinstance(node, DEFINITIONS)}
+ routers = router_names(statements, owner, routers)
+ bindings = bindings.copy()
+
+ def check_registration(call: ast.Call) -> None:
+ """
+ 匹配显式注册、显式路径操作对象及直接应用的路由装饰器。
+
+ :param call: 当前语句中的调用
+ """
+ if router_method(call.func, ROUTE_METHODS, routers) and call.args:
+ operation, callback = call.func, call.args[0]
+ elif (
+ (isinstance(call.func, ast.Attribute) and call.func.attr == 'add_api_route')
+ or ast.unparse(call.func) in api_route_types
+ or router_method(call, ROUTE_REGISTRATIONS, routers)
+ ):
+ operation, callback = call, registered_callback(call)
+ else:
+ return
+ if ast.unparse(operation.func) in api_route_types or operation.func.attr in HTTP_OPERATIONS | {
+ 'add_api_route'
+ }:
+ errors.extend(route_doc_errors(operation, bindings))
+ if isinstance(callback, ast.Name) and callback.id in functions:
+ routes.add(functions[callback.id])
+
+ for node in statements:
+ if not isinstance(node, DEFINITIONS):
+ for call in statement_calls(node):
+ check_registration(call)
+ if isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value is not None:
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
+ bindings.update((target.id, node.value) for target in targets if isinstance(target, ast.Name))
+ elif isinstance(node, DEFINITIONS):
+ for decorator in node.decorator_list:
+ if router_method(decorator, ROUTE_METHODS, routers):
+ routes.add(node)
+ if decorator.func.attr in HTTP_OPERATIONS:
+ errors.extend(route_doc_errors(decorator, bindings))
+ visit(node, functions, routers, bindings)
+
+ visit(tree, {}, set(), {})
+ return routes, errors
+
+
+def preserved_router(tree: ast.Module, path: Path) -> ast.ClassDef | None:
+ """
+ 定位需要保留原始 FastAPI 文档的路由器类。
+
+ :param tree: 待校验源码的抽象语法树
+ :param path: 要读取或处理的路径
+ :return: 指定模块中的路由器类,其他文件或没有该类时返回空值
+ """
+ if path.resolve() == ROUTER_MODULE:
+ for node in tree.body:
+ if isinstance(node, ast.ClassDef) and node.name == 'APIRouterPro':
+ return node
+ return None
+
+
+def test_functions(tree: ast.Module, path: Path) -> set[ast.AST]:
+ """
+ 识别 pytest 从测试模块顶层或测试类中收集的函数。
+
+ :param tree: 待校验源码的抽象语法树
+ :param path: 要读取或处理的路径
+ :return: 会被 pytest 收集的测试函数定义
+ """
+ if not (path.name.startswith('test_') or path.stem.endswith('_test')):
+ return set()
+ fixtures = {'pytest.fixture'}
+ for item in ast.walk(tree):
+ if isinstance(item, ast.ImportFrom) and item.module == 'pytest':
+ fixtures.update(alias.asname or alias.name for alias in item.names if alias.name == 'fixture')
+ elif isinstance(item, ast.Import):
+ fixtures.update(
+ f'{alias.asname}.fixture' for alias in item.names if alias.name == 'pytest' and alias.asname
+ )
+ suites = [
+ tree.body,
+ *(cls.body for cls in tree.body if isinstance(cls, ast.ClassDef) and cls.name.startswith('Test')),
+ ]
+ return {
+ node
+ for suite in suites
+ for node in suite
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ and node.name.startswith('test')
+ and not any(ast.unparse(d.func if isinstance(d, ast.Call) else d) in fixtures for d in node.decorator_list)
+ }
+
+
+@contextmanager
+def sphinx_settings() -> Iterator[frontend.Values]:
+ """
+ 初始化一次 Sphinx 内置域和指令,供同一次扫描的文档共用。
+
+ :yield: 共享 Sphinx 环境的 reST 解析设置
+ """
+ with TemporaryDirectory() as temporary, docutils_namespace():
+ root = Path(temporary)
+ app = Sphinx(
+ root, None, root / 'out', root / 'trees', 'dummy', status=None, warning=None, exception_on_warning=True
+ )
+ settings = frontend.get_default_settings(Parser)
+ settings.env = app.env
+ settings.file_insertion_enabled = settings.raw_enabled = False
+ settings.warning_stream = False # 解析器诊断由 reporter 收集并统一输出源文件行号。
+ settings.halt_level = utils.Reporter.SEVERE_LEVEL + 1
+ yield settings
+
+
+@dataclass
+class Parameters:
+ """
+ 保存可出现在 API 文档中的参数名称及关键字参数能力。
+
+ :ivar names: 可在 Sphinx 字段中引用的参数名
+ :ivar accepts_keywords: 签名是否接受任意关键字参数
+ """
+
+ names: set[str]
+ accepts_keywords: bool
+
+
+def parameters_for(owner: ast.AST, methods: set[ast.AST]) -> Parameters | None:
+ """
+ 取函数或显式构造函数的签名,省略实例和类方法的隐式首参。
+
+ :param owner: 声明参数的函数或类
+ :param methods: 类体中声明的方法集合
+ :return: ``Parameters`` 实例
+ """
+ if isinstance(owner, ast.ClassDef):
+ owner = next(
+ (item for item in owner.body if isinstance(item, ast.FunctionDef) and item.name == '__init__'), None
+ )
+ if not isinstance(owner, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ return None
+ args = owner.args
+ positional = [*args.posonlyargs, *args.args]
+ if owner in methods and bound_receiver(owner):
+ positional = positional[1:]
+ names = {arg.arg for arg in (*positional, *args.kwonlyargs)}
+ for prefix, arg in (('*', args.vararg), ('**', args.kwarg)):
+ if arg:
+ names.update((arg.arg, prefix + arg.arg))
+ return Parameters(names, args.kwarg is not None)
+
+
+def field_error(field: nodes.field, parameters: Parameters | None, required: dict[str, str]) -> str:
+ """
+ 按照 Python 域的字段类型校验名称、描述及参数引用。
+
+ :param field: 待验证的 reST 字段节点
+ :param parameters: 对应函数的签名信息
+ :param required: 尚未找到有效描述的参数或属性
+ :return: 字段无效时的诊断,通过时为空字符串
+ """
+ name, *arguments = field[0].astext().split()
+ kind = FIELD_KINDS.get(name)
+ if kind is None:
+ return f'未知 Sphinx Python 字段 :{name},请使用 :param、:return:、:raises 等字段'
+ if not field[1].astext().strip() and kind != 'meta':
+ return f'请填写 :{name} 字段的内容,或移除空字段'
+ if kind in {'parameter', 'variable', 'returnvalue', 'yieldvalue', 'exceptions'} and not CHINESE.search(
+ field[1].astext()
+ ):
+ return f':{name} 字段须用中文说明其含义'
+ if kind in {'returnvalue', 'returntype', 'yieldvalue'}:
+ return f'请使用 :{name}: 描述' if arguments else ''
+ if not arguments:
+ return f'字段 :{name} 需要名称,例如 :param name: 或 :raises ValueError:'
+ if kind in {'parameter', 'variable'}:
+ if len(arguments) > MAX_TYPED_FIELD_WORDS:
+ return f'请将复杂类型写入单独的 :type 或 :vartype 字段;当前为 :{name} {" ".join(arguments)}:'
+ elif len(arguments) != 1:
+ return f'字段 :{name} 只接受一个名称'
+ identifier = arguments[-1]
+ if kind in {'parameter', 'parametertype'} and (error := parameter_error(field, name, identifier, parameters)):
+ return error
+ if kind in {'variable', 'variabletype'} and not arguments[-1].isidentifier():
+ return f'字段 :{name} 需要有效的 Python 属性名'
+ identifier = identifier.lstrip('*')
+ if required.get(identifier) == kind:
+ del required[identifier]
+ return ''
+
+
+def parameter_error(field: nodes.field, name: str, param: str, parameters: Parameters | None) -> str:
+ """
+ 比对函数签名,包括可变参数和通过关键字字典接收的选项。
+
+ :param field: 包含参数描述或类型的字段节点
+ :param name: Sphinx 字段名
+ :param param: 字段引用的参数名称
+ :param parameters: 允许使用的签名参数
+ :return: 参数引用无效时的诊断,通过时为空字符串
+ """
+ identifier = param.removeprefix('**') if param.startswith('**') else param.removeprefix('*')
+ if not identifier.isidentifier():
+ return f'字段 :{name} 需要有效的 Python 参数名'
+ if parameters is None or param in parameters.names:
+ return ''
+ if parameters.accepts_keywords and identifier == param:
+ if name in KEYWORD_FIELDS:
+ return ''
+ if FIELD_KINDS[name] == 'parametertype':
+ for sibling in field.parent.findall(nodes.field):
+ words = sibling[0].astext().split()
+ if words[0] in KEYWORD_FIELDS and words[-1] == param:
+ return ''
+ return f'文档参数 {param} 不在函数签名中'
+
+
+def header_comments(source: str) -> Iterator[tuple[int, str]]:
+ """
+ 检查首条语句之前的注释,保留解释器指令和有效位置上的编码声明。
+
+ :param source: 待检查文件的源代码
+ :yield: 违规位置的源码行号和诊断信息
+ """
+ for token in tokenize.generate_tokens(StringIO(source).readline):
+ if token.type == tokenize.NL:
+ continue
+ if token.type != tokenize.COMMENT:
+ break
+ line, column = token.start
+ if line == 1 and column == 0 and token.string.startswith('#!'):
+ continue
+ if line in (1, 2) and re.match(r'^#.*?coding[:=][ \t]*[-\w.]+', token.string, re.ASCII):
+ continue
+ yield line, '请移除 Python 文件顶部的注释'
+
+
+def comment_language(source: str, tree: ast.Module, path: Path) -> Iterator[tuple[int, str]]:
+ """
+ 检查普通注释使用中文,保留解释器声明和工具指令。
+
+ :param source: 文件原文
+ :param tree: 源码的抽象语法树
+ :param path: 用于识别保留原文范围的源码路径
+ :yield: 全英文注释的行号及说明
+ """
+ if path.resolve() == ALEMBIC_ENV:
+ return
+ router = preserved_router(tree, path)
+ preserved = range(router.lineno, router.end_lineno + 1) if router else ()
+ for token in tokenize.generate_tokens(StringIO(source).readline):
+ line = token.start[0]
+ if token.type != tokenize.COMMENT or line in preserved:
+ continue
+ content = token.string[1:].strip()
+ if line in (1, 2) and (content.startswith('!') or re.search(r'coding[:=]\s*[-\w.]+', content)):
+ continue
+ if re.fullmatch(
+ r'(?:noqa(?:\s*:\s*[A-Z]+\d+(?:[ ,]+[A-Z]+\d+)*)?|type:\s*ignore(?:\[[\w, -]+\])?|'
+ r'fmt:\s*(?:off|on|skip)|pragma:\s*no (?:cover|branch))',
+ content,
+ ):
+ continue
+ if re.search('[a-zA-Z]', content) and not CHINESE.search(content):
+ yield line, '普通注释必须使用中文,可混用技术术语'
+
+
+def overload_signatures(tree: ast.Module) -> set[ast.AST]:
+ """
+ 识别由 typing 声明且在同一作用域有具体实现的重载签名。
+
+ :param tree: 待校验源码的抽象语法树
+ :return: 已由具体实现提供文档的重载声明
+ """
+ decorators = set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and node.module in {'typing', 'typing_extensions'}:
+ decorators.update(alias.asname or alias.name for alias in node.names if alias.name == 'overload')
+ elif isinstance(node, ast.Import):
+ decorators.update(
+ f'{alias.asname or alias.name}.overload'
+ for alias in node.names
+ if alias.name in {'typing', 'typing_extensions'}
+ )
+ if not decorators:
+ return set()
+ signatures = set()
+ for parent in ast.walk(tree):
+ for _, suite in ast.iter_fields(parent):
+ if not isinstance(suite, list):
+ continue
+ implementations = set()
+ for definition in reversed(suite):
+ if not isinstance(definition, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ if not any(ast.unparse(item) in decorators for item in definition.decorator_list):
+ implementations.add(definition.name)
+ elif definition.name in implementations:
+ signatures.add(definition)
+ return signatures
+
+
+def exception_names(expr: ast.expr | None) -> tuple[str, ...]:
+ """
+ 读取异常名称或元组中的各个异常类型。
+
+ :param expr: 捕获或抛出的异常表达式
+ :return: 源码中可识别的异常类型名称
+ """
+ if expr is None:
+ return ('BaseException',)
+ if isinstance(expr, ast.Tuple):
+ return tuple(name for child in expr.elts for name in exception_names(child))
+ if isinstance(expr, ast.Call):
+ expr = expr.func
+ if isinstance(expr, (ast.Attribute, ast.Name)):
+ name = ast.unparse(expr)
+ if name.split('.')[-1][:1].isupper():
+ return (name,)
+ return ()
+
+
+def catches_exception(name: str, handlers: set[str]) -> bool:
+ """
+ 比对处理器捕获的类型,包括内置异常的继承关系。
+
+ :param name: 抛出异常的名称
+ :param handlers: 当前受保护范围内的捕获类型
+ :return: 该异常是否已由本地处理器捕获
+ """
+ short = name.rsplit('.', 1)[-1]
+ exception = getattr(builtins, short, None)
+ if isinstance(exception, type) and issubclass(exception, BaseException):
+ return any(cls.__name__ in handlers for cls in exception.__mro__)
+ return bool({short, 'BaseException'} & handlers or ('Exception' in handlers and short != 'CancelledError'))
+
+
+def function_outcomes(function: ast.FunctionDef | ast.AsyncFunctionDef) -> Iterator[tuple[str, ast.AST]]:
+ """
+ 定位当前函数返回或生成的值以及显式抛出的未捕获异常。
+
+ :param function: 要检查的函数定义
+ :yield: 应记录的字段名称及其来源语句
+ """
+
+ def visit(
+ node: ast.AST, caught: set[str], active: tuple[str, ...], alias: str | None
+ ) -> Iterator[tuple[str, ast.AST]]:
+ """
+ 在当前处理器作用域内查找对调用方可见的结果。
+
+ :param node: 当前语法节点
+ :param caught: 外层处理器捕获的异常类型
+ :param active: 当前正在处理的异常类型
+ :param alias: 当前处理器绑定的异常变量
+ :yield: 结果字段和对应的语法节点
+ """
+ if isinstance(node, (*DEFINITIONS, ast.Lambda)):
+ return
+ if isinstance(node, (ast.Try, ast.TryStar)):
+ local = {name.split('.')[-1] for h in node.handlers for name in exception_names(h.type)}
+ for stmt in node.body:
+ yield from visit(stmt, caught | local, active, alias)
+ for handler in node.handlers:
+ for stmt in handler.body:
+ yield from visit(stmt, caught, exception_names(handler.type), handler.name)
+ for stmt in (*node.orelse, *node.finalbody):
+ yield from visit(stmt, caught, active, alias)
+ return
+ if isinstance(node, (ast.Yield, ast.YieldFrom)):
+ yield 'yield', node
+ elif (
+ isinstance(node, ast.Return)
+ and node.value is not None
+ and not (isinstance(node.value, ast.Constant) and node.value.value is None)
+ ):
+ yield 'return', node
+ elif isinstance(node, ast.Raise):
+ reraised = node.exc is None or (isinstance(node.exc, ast.Name) and node.exc.id == alias)
+ names = active if reraised else exception_names(node.exc)
+ for name in names or ('',):
+ if not catches_exception(name, caught):
+ yield f'raises {name}'.rstrip(), node
+ for child in ast.iter_child_nodes(node):
+ yield from visit(child, caught, active, alias)
+
+ for statement in function.body:
+ yield from visit(statement, set(), (), None)
+ if function.returns and isinstance(function.body[-1], (ast.Pass, ast.Expr)):
+ stub = isinstance(function.body[-1], ast.Pass) or (
+ isinstance(function.body[-1].value, ast.Constant) and function.body[-1].value.value is Ellipsis
+ )
+ if stub and ast.unparse(function.returns).split('.')[-1] not in {'None', 'Never', 'NoReturn'}:
+ yield 'return', function
+
+
+def violations(
+ tree: ast.Module, settings: frontend.Values, path: Path = Path('sample.py')
+) -> Iterator[tuple[int, str]]:
+ """
+ 拒绝模块文档字符串,校验每个类和函数实现的文档字符串。
+
+ :param tree: 待校验源码的抽象语法树
+ :param settings: Sphinx 解析器配置
+ :param path: 源文件路径,用于解析模型的导入关系
+ :yield: 违规位置的源码行号和诊断信息
+ """
+ if path.resolve() == ALEMBIC_ENV:
+ return
+ if ast.get_docstring(tree, clean=False) is not None:
+ yield tree.body[0].lineno, '请移除文件顶部的模块 docstring,将说明写在对应的类或函数上'
+ methods = {item for cls in ast.walk(tree) if isinstance(cls, ast.ClassDef) for item in scoped_statements(cls.body)}
+ routes, route_errors = inspect_routes(tree)
+ yield from route_errors
+ router = preserved_router(tree, path)
+ preserved = set(ast.walk(router)) if router else set()
+ tables = {}
+ models = {node: info for node, info in model_classes(tree, path, tables).items() if node not in preserved}
+ yield from table_field_errors(tables)
+ for node, (kind, bindings) in models.items():
+ yield from model_field_errors(node, kind, bindings)
+ tests = test_functions(tree, path)
+ overloads = overload_signatures(tree)
+ for node in ast.walk(tree):
+ if not isinstance(node, DEFINITIONS) or node in preserved:
+ continue
+ doc = ast.get_docstring(node, clean=False)
+ if doc is None and (node in routes or node in overloads):
+ continue
+ if node in overloads:
+ yield node.lineno, f'请将 {node.name} 的文档写在重载的具体实现上'
+ continue
+ if doc is None:
+ yield node.lineno, f'{node.name} 缺少 Sphinx/reST docstring'
+ continue
+ expression = node.body[0]
+ if not doc.strip():
+ yield expression.lineno, '请填写文档摘要'
+ continue
+ start = expression.lineno + next(i for i, line in enumerate(doc.splitlines()) if line.strip())
+ parameters = parameters_for(node, methods)
+ required = {}
+ if isinstance(node, ast.ClassDef) and not models[node][0]:
+ required = dict.fromkeys(class_attributes(node), 'variable')
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node not in tests and node not in routes:
+ required = dict.fromkeys((name for name in parameters.names if name.isidentifier()), 'parameter')
+ yield from check_docstring(doc, parameters, start, settings, required, node, node in tests, node in routes)
+ for identifier, kind in sorted(required.items()):
+ label = (
+ f'参数 {identifier} 缺少 :param' if kind == 'parameter' else f'属性 {identifier} 缺少 :ivar 或 :cvar'
+ )
+ yield start, f'{label} 描述'
+
+
+def check_docstring(
+ doc: str,
+ parameters: Parameters | None,
+ start: int,
+ settings: frontend.Values,
+ required: dict[str, str],
+ owner: ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef,
+ is_test: bool,
+ is_route: bool,
+) -> Iterator[tuple[int, str]]:
+ """
+ 解析单个文档,返回标记、字段和排版诊断的源码位置。
+
+ :param doc: 原始文档字符串
+ :param parameters: 文档对应的签名信息
+ :param start: 摘要在源文件中的行号
+ :param settings: Sphinx 解析器配置
+ :param required: 需要在文档中逐项说明的名称及字段类别
+ :param owner: 声明文档的类或函数
+ :param is_test: 当前函数是否会被 pytest 收集
+ :param is_route: 当前函数是否为路由端点
+ :yield: 违规位置的源码行号和诊断信息
+ """
+ lines = prepare_docstring(doc)
+ if not lines[0].endswith(('.', '。', '!', '!', '?', '?')):
+ yield start, '请以句末标点结束文档摘要'
+ if not CHINESE.search(lines[0]):
+ yield start, '文档摘要必须使用中文,可混用技术术语'
+ document = utils.new_document('', settings)
+ messages = []
+ document.reporter.attach_observer(messages.append)
+ settings.env.prepare_settings('docstring')
+ try:
+ with sphinx_domains(settings.env):
+ Parser().parse('\n'.join(lines), document)
+ except SphinxWarning as error:
+ yield start, str(error)
+ for message in messages:
+ if message['level'] >= utils.Reporter.WARNING_LEVEL:
+ yield start + (message.get('line') or 1) - 1, message[0].astext()
+ fields = []
+ for block in document.findall(nodes.Element):
+ if block.line is None:
+ continue
+ lineno = start + block.line - 1
+ if isinstance(block, nodes.field) and isinstance(block.parent.parent, (nodes.document, nodes.section)):
+ fields.append(block)
+ if error := field_error(block, parameters, required):
+ yield lineno, error
+ elif isinstance(block, (nodes.paragraph, nodes.term, nodes.title)):
+ yield from check_prose(block, lineno)
+ if not is_route:
+ yield from check_contract(fields, owner, is_test, start)
+
+
+def check_contract(
+ fields: list[nodes.field],
+ owner: ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef,
+ is_test: bool,
+ start: int,
+) -> Iterator[tuple[int, str]]:
+ """
+ 对照声明种类、函数体和顶层字段检查文档约定。
+
+ :param fields: 文档中用于说明接口的字段
+ :param owner: 定义该文档的类或函数
+ :param is_test: 是否为测试用例
+ :param start: 摘要在源码中的位置
+ :yield: 不符合约定的行号和说明
+ """
+ documented = set()
+ params = set()
+ attributes = set()
+ for field in fields:
+ name, *args = field[0].astext().split()
+ kind = FIELD_KINDS.get(name)
+ if kind in {'returnvalue', 'yieldvalue'}:
+ documented.add('return' if kind == 'returnvalue' else 'yield')
+ elif kind == 'exceptions' and args:
+ documented.update(('raises', 'raises ' + args[-1].split('.')[-1]))
+ elif kind == 'parameter' and args:
+ params.add(args[-1])
+ elif kind == 'variable' and args:
+ attributes.add(args[-1])
+ if is_test:
+ if fields:
+ yield start, '测试函数只写测试意图,请移除接口字段'
+ return
+ if isinstance(owner, ast.ClassDef):
+ for name in sorted(params & attributes):
+ yield start, f'类属性 {name} 重复使用参数和属性字段,请只保留属性说明'
+ return
+ required = {
+ field if '.' not in field else 'raises ' + field.split('.')[-1] for field, _ in function_outcomes(owner)
+ }
+ for key in sorted(required - documented):
+ field_name = 'raises 异常类型' if key == 'raises' else key
+ yield start, f'缺少 :{field_name}: 描述'
+
+
+def check_prose(block: nodes.Element, start: int) -> Iterator[tuple[int, str]]:
+ """
+ 识别正文和标题中的其他 API 文档风格。
+
+ :param block: 待检查的 reST 正文节点
+ :param start: 正文在源文件中的起始行号
+ :yield: 违规位置的源码行号和诊断信息
+ """
+ source = block.rawsource
+ parent = block.parent
+ type_field = isinstance(parent, nodes.field_body) and FIELD_KINDS.get(parent.parent[0].astext().split()[0], '') in {
+ 'returntype',
+ 'parametertype',
+ 'variabletype',
+ 'meta',
+ }
+ if (
+ not type_field
+ and re.search('[a-zA-Z]', source)
+ and not CHINESE.search(block.astext())
+ and not all(isinstance(child, (nodes.literal, nodes.reference)) for child in block.children)
+ ):
+ yield start, '文档说明必须使用中文,可混用技术术语'
+ for inline in block.findall(nodes.Inline):
+ markup = inline.rawsource
+ if markup.startswith('`') and not markup.startswith('```'):
+ source = source.replace(markup, '…' + '\n' * markup.count('\n'), 1)
+ is_title = isinstance(block, nodes.title)
+ # Docutils 将章节标题定位到标题下方的装饰线。
+ for index, raw in enumerate(source.splitlines(), start - int(is_title)):
+ line = raw.strip()
+ section = SECTION.fullmatch(line)
+ if section and (section[1] or is_title):
+ yield index, f'章节 {line} 请改用 reST 字段或指令'
+ elif FOREIGN_MARKUP.match(line) or MARKDOWN_LINK.search(line):
+ yield index, f'请将 {line} 改为 reST 字段、标题或代码块'
+ elif UNPARSED_LITERAL.search(line):
+ yield index, '行内字面量的双反引号必须成对,并与相邻正文分隔'
+ elif line.startswith(':') and line != '::' and not ROLE.match(line):
+ yield index, f'请使用独立的 reST 字段列表,格式为 :字段 名称: 描述;当前为 {line}'
+
+
+def main(targets: list[str]) -> int:
+ """
+ 使用与 Ruff 相同的目标文件和排除规则,发现违规时返回非零状态。
+
+ :param targets: 交给 Ruff 解析的文件或目录
+ :return: 检查通过时为零,否则为非零退出码
+ """
+ files = subprocess.run(
+ [sys.executable, '-m', 'ruff', 'check', '--show-files', '--', *targets],
+ stdout=subprocess.PIPE,
+ encoding='utf-8',
+ check=False,
+ )
+ if files.returncode:
+ return files.returncode
+ failed = False
+ with sphinx_settings() as settings:
+ for path in map(Path, files.stdout.splitlines()):
+ if path.suffix not in {'.py', '.pyi', '.pyw'} or path.resolve() == ALEMBIC_ENV:
+ continue
+ with tokenize.open(path) as stream:
+ source = stream.read()
+ tree = ast.parse(source, filename=str(path))
+ for lineno, error in (
+ *header_comments(source),
+ *comment_language(source, tree, path),
+ *violations(tree, settings, path),
+ ):
+ print(f'{path}:{lineno}: {error}')
+ failed = True
+ return int(failed)
+
+
+if __name__ == '__main__':
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/ruoyi-fastapi-backend/scripts/compile_i18n.py b/ruoyi-fastapi-backend/scripts/compile_i18n.py
index 7e551dc7e..a1997e7ae 100644
--- a/ruoyi-fastapi-backend/scripts/compile_i18n.py
+++ b/ruoyi-fastapi-backend/scripts/compile_i18n.py
@@ -20,7 +20,14 @@
def _read_catalog(path: Path, code: str) -> Catalog:
- """读取 PO 源文件,拒绝未审校、缺失和格式错误的译文。"""
+ """
+ 读取 PO 源文件,拒绝未审校、缺失和格式错误的译文。
+
+ :param path: 要读取或处理的路径
+ :param code: 与当前结果对应的编码
+ :raises ValueError: PO 词库不可解析,或译文缺失、未审核或格式错误
+ :return: PO 源文件
+ """
try:
with path.open('rb') as source:
catalog = read_po(source, locale=code.replace('-', '_'), abort_invalid=True)
@@ -38,7 +45,14 @@ def _read_catalog(path: Path, code: str) -> Catalog:
def _read_core_modules(spec: CatalogSpec, code: str) -> tuple[Catalog, CoreModuleKeys]:
- """按文件名合并核心词库,并记录各模块的消息标识、上下文和复数标识。"""
+ """
+ 按文件名合并核心词库,并记录各模块的消息标识、上下文和复数标识。
+
+ :param spec: 已注册词库的资源目录和回退配置
+ :param code: 与当前结果对应的编码
+ :raises ValueError: 核心词库路径越界或源文件与语言声明不符
+ :return: 依次为 ``merged``、``modules`` 的元组
+ """
directory = (spec.root / code / 'LC_MESSAGES' / 'core').resolve()
if not directory.is_relative_to(spec.root):
raise ValueError(f'Core catalog directory escapes its root: {directory}')
@@ -71,10 +85,10 @@ def _read_core_modules(spec: CatalogSpec, code: str) -> tuple[Catalog, CoreModul
def _compile_specs(specs: tuple[CatalogSpec, ...]) -> None:
"""
- 校验已注册词库的复数项和审校状态,并生成 MO 文件
+ 校验已注册词库的复数项和审校状态,并生成 MO 文件。
:param specs: 本次编译的受信词库配置
- :return: None
+ :raises ValueError: 不同语言的核心模块集合或消息键不一致
"""
compiled = []
for spec in specs:
@@ -111,11 +125,14 @@ def _compile_specs(specs: tuple[CatalogSpec, ...]) -> None:
def compile_catalogs(extra_specs: tuple[CatalogSpec, ...] = (), *, isolate_plugin_errors: bool = False) -> None:
"""
- 编译核心与源码插件词库,插件域由启停流程注册
+ 编译核心与源码插件词库,插件域由启停流程注册。
:param extra_specs: 构建时显式指定的受信词库配置
:param isolate_plugin_errors: 应用启动时单独报告源码插件错误,仍可启动宿主
- :return: None
+ :raises OSError: 未隔离插件错误时,读写插件词库失败
+ :raises ValueError: 未隔离插件错误时,词库内容未通过校验
+ :raises TypeError: 未隔离插件错误时,词库声明的数据类型错误
+ :raises KeyError: 未隔离插件错误时,词库缺少所需的键
"""
active = CatalogRegistry.specs()
specs = {spec.domain: spec for spec in (*active, *extra_specs)}
diff --git a/ruoyi-fastapi-backend/scripts/migrate_job_fields.py b/ruoyi-fastapi-backend/scripts/migrate_job_fields.py
index 74ca349f2..68994f844 100644
--- a/ruoyi-fastapi-backend/scripts/migrate_job_fields.py
+++ b/ruoyi-fastapi-backend/scripts/migrate_job_fields.py
@@ -15,10 +15,11 @@
def plan_store_dictionary(connection: Connection) -> dict[str, Any]:
"""
- 检查旧任务分组字典,生成复用原记录的调度存储字典迁移计划
+ 检查旧任务分组字典,生成复用原记录的调度存储字典迁移计划。
:param connection: 数据库连接
:return: 字典迁移计划
+ :raises ValueError: 新旧调度存储字典同时存在,请先处理 sys_job_group 和 sys_job_store 冲突;调度存储字典存在重复键值,请先处理冲突
"""
metadata = MetaData()
types = Table('sys_dict_type', metadata, autoload_with=connection)
@@ -50,7 +51,7 @@ def plan_store_dictionary(connection: Connection) -> dict[str, Any]:
def migrate_store_dictionary(connection: Connection, plan: dict[str, Any]) -> dict[str, Any]:
"""
- 将任务分组字典改为调度存储字典,保留已有编号、排序和自定义标签
+ 将任务分组字典改为调度存储字典,保留已有编号、排序和自定义标签。
:param connection: 数据库连接
:param plan: 只读检查生成的字典迁移计划
@@ -97,7 +98,7 @@ def migrate_store_dictionary(connection: Connection, plan: dict[str, Any]) -> di
def parse_legacy_args(value: Any) -> list[Any]:
"""
- 按旧调度器的规则迁移位置参数,保留原有值类型和逗号分隔语义
+ 按旧调度器的规则迁移位置参数,保留原有值类型和逗号分隔语义。
:param value: 旧位置参数
:return: JSON位置参数数组
@@ -115,10 +116,11 @@ def parse_legacy_args(value: Any) -> list[Any]:
def parse_legacy_kwargs(value: Any) -> dict[str, Any]:
"""
- 将旧关键字参数转换为JSON对象
+ 将旧关键字参数转换为JSON对象。
:param value: 旧关键字参数
:return: JSON关键字参数对象
+ :raises ValueError: 关键字参数不是JSON对象
"""
parsed = {} if value is None or value == '' else (json.loads(value) if isinstance(value, str) else value)
if not isinstance(parsed, dict):
@@ -128,14 +130,22 @@ def parse_legacy_kwargs(value: Any) -> dict[str, Any]:
def convert_configuration(row: dict[str, Any], *, snapshot: bool = False) -> dict[str, Any]:
"""
- 转换旧任务字段,修正放弃执行的宽限时间并保留旧并发上限
+ 转换旧任务字段,修正放弃执行的宽限时间并保留旧并发上限。
:param row: 旧任务记录或执行快照
:param snapshot: 是否使用接口驼峰字段名
:return: 新字段和值
+ :raises ValueError: 旧执行策略或并发配置无效;旧分组无法对应已注册的调度存储
"""
def read(name: str, default: Any = None) -> Any:
+ """
+ 从新旧任务配置字段中读取配置值。
+
+ :param name: 用于查找或标识当前对象的名称
+ :param default: 未提供有效值时使用的默认值
+ :return: 优先从新字段读取的配置值
+ """
key = (
''.join(part.title() if index else part for index, part in enumerate(name.split('_'))) if snapshot else name
)
@@ -168,7 +178,7 @@ def read(name: str, default: Any = None) -> Any:
def table_columns(connection: Connection, name: str) -> dict[str, dict]:
"""
- 读取当前表结构,支持DDL部分完成后的再次运行
+ 读取当前表结构,支持DDL部分完成后的再次运行。
:param connection: 数据库连接
:param name: 表名
@@ -179,7 +189,7 @@ def table_columns(connection: Connection, name: str) -> dict[str, dict]:
def is_current_schema(connection: Connection) -> bool:
"""
- 检查新字段、主键及唯一规则,避免重复转换已升级的数据
+ 检查新字段、主键及唯一规则,避免重复转换已升级的数据。
:param connection: 数据库连接
:return: 是否已完成第二轮字段迁移
@@ -202,10 +212,11 @@ def is_current_schema(connection: Connection) -> bool:
def preflight(connection: Connection) -> dict[str, Any]:
"""
- 只读检查主键、名称冲突及参数,所有定义通过后才允许修改表结构
+ 只读检查主键、名称冲突及参数,所有定义通过后才允许修改表结构。
:param connection: 数据库连接
:return: 迁移计划及转换后的任务数据
+ :raises ValueError: 有重复标识、无效任务配置或尚未完成的任务执行
"""
if is_current_schema(connection):
return {'current': True, 'jobs': [], 'requests': [], 'policies': {}}
@@ -252,13 +263,12 @@ def preflight(connection: Connection) -> dict[str, Any]:
def add_column(connection: Connection, table: str, name: str, definition: str) -> None:
"""
- 仅添加尚不存在的迁移字段
+ 仅添加尚不存在的迁移字段。
:param connection: 数据库连接
:param table: 表名
:param name: 字段名
:param definition: 固定的DDL字段定义
- :return: None
"""
if name not in table_columns(connection, table):
connection.exec_driver_sql(f'ALTER TABLE {table} ADD COLUMN {name} {definition}')
@@ -266,12 +276,11 @@ def add_column(connection: Connection, table: str, name: str, definition: str) -
def archive_column(connection: Connection, table: str, name: str) -> None:
"""
- 保留旧字段原文,供升级审计和备份恢复时核对
+ 保留旧字段原文,供升级审计和备份恢复时核对。
:param connection: 数据库连接
:param table: 表名
:param name: 旧字段名
- :return: None
"""
columns = table_columns(connection, table)
if f'legacy_{name}' not in columns and name in columns:
@@ -280,7 +289,7 @@ def archive_column(connection: Connection, table: str, name: str) -> None:
def migrate_logs(connection: Connection) -> int:
"""
- 分批转换日志参数,只从明确的日志编号信息补全关联,不按名称猜测
+ 分批转换日志参数,只从明确的日志编号信息补全关联,不按名称猜测。
:param connection: 数据库连接
:return: 转换的日志数量
@@ -315,11 +324,12 @@ def migrate_logs(connection: Connection) -> int:
def apply_migration(connection: Connection, plan: dict[str, Any]) -> dict[str, Any]:
"""
- 应用已通过检查的迁移计划,PostgreSQL使用事务,MySQL可从保留的旧字段重试
+ 应用已通过检查的迁移计划,PostgreSQL使用事务,MySQL可从保留的旧字段重试。
:param connection: 所有应用worker停止后的独占数据库连接
:param plan: 只读预检产生的迁移计划
:return: 迁移数量报告
+ :raises ValueError: 字段迁移仅支持MySQL和PostgreSQL
"""
if plan['current']:
return {'current': True, 'jobs': 0, 'requests': 0, 'logs': 0}
@@ -368,10 +378,9 @@ def apply_migration(connection: Connection, plan: dict[str, Any]) -> dict[str, A
def finalize_schema(connection: Connection) -> None:
"""
- 数据转换完成后建立主键、索引和约束
+ 数据转换完成后建立主键、索引和约束。
:param connection: 数据库连接
- :return: None
"""
mysql = connection.dialect.name == 'mysql'
inspector = inspect(connection)
@@ -413,11 +422,7 @@ def finalize_schema(connection: Connection) -> None:
def main() -> None:
- """
- 默认只读预检,显式选择应用迁移时才修改指定数据源
-
- :return: None
- """
+ """默认只读预检,显式选择应用迁移时才修改指定数据源。"""
parser = argparse.ArgumentParser(description='迁移第二轮任务字段,默认只读检查')
parser.add_argument('--env-file', default='.env.dev', help='数据源配置文件')
parser.add_argument('--source', help='指定数据源别名')
diff --git a/ruoyi-fastapi-backend/scripts/migrate_legacy_files.py b/ruoyi-fastapi-backend/scripts/migrate_legacy_files.py
index df8dae595..626bb777f 100644
--- a/ruoyi-fastapi-backend/scripts/migrate_legacy_files.py
+++ b/ruoyi-fastapi-backend/scripts/migrate_legacy_files.py
@@ -27,7 +27,13 @@
@dataclass(frozen=True)
class FileSignature:
"""
- 文件稳定性签名
+ 文件稳定性签名。
+
+ :ivar file_size: 文件大小
+ :ivar modified_time_ns: 文件内容最后修改的时间戳(纳秒)
+ :ivar changed_time_ns: 文件元数据最后变更的时间戳(纳秒)
+ :ivar device_id: 文件所在存储设备的标识
+ :ivar inode: 操作系统为文件分配的 inode 编号
"""
file_size: int
@@ -40,7 +46,16 @@ class FileSignature:
@dataclass(frozen=True)
class LegacyFileInfo:
"""
- 历史文件信息
+ 历史文件信息。
+
+ :ivar filepath: 文件路径
+ :ivar storage_key: 存储相对路径
+ :ivar filename: 存储文件名
+ :ivar extension: 文件扩展名
+ :ivar content_type: 文件内容类型
+ :ivar file_size: 文件大小
+ :ivar file_time: 旧版路径信息中记录的文件时间
+ :ivar signature: 文件稳定性签名
"""
filepath: Path
@@ -55,10 +70,11 @@ class LegacyFileInfo:
def get_file_signature(filepath: Path) -> FileSignature:
"""
- 获取普通文件的稳定性签名
+ 获取普通文件的稳定性签名。
:param filepath: 文件路径
:return: 文件稳定性签名
+ :raises ValueError: 文件不是普通文件
"""
file_stat = filepath.lstat()
if not stat.S_ISREG(file_stat.st_mode):
@@ -80,7 +96,7 @@ def get_legacy_file_skip_reason(
file_size: int,
) -> str | None:
"""
- 获取历史文件跳过原因
+ 获取历史文件跳过原因。
:param storage_key: 存储相对路径
:param filename: 存储文件名
@@ -106,7 +122,7 @@ def get_legacy_file_skip_reason(
def collect_legacy_files() -> tuple[list[LegacyFileInfo], int]:
"""
- 收集待迁移的历史文件
+ 收集待迁移的历史文件。
:return: 符合要求的文件信息和跳过数量
"""
@@ -156,11 +172,12 @@ def collect_legacy_files() -> tuple[list[LegacyFileInfo], int]:
async def calculate_file_hash(filepath: Path, expected_signature: FileSignature | None = None) -> str:
"""
- 计算稳定文件的SHA-256
+ 计算稳定文件的SHA-256。
:param filepath: 文件路径
:param expected_signature: 扫描阶段记录的文件签名
:return: 文件SHA-256
+ :raises ValueError: 文件在扫描后发生变化;文件在哈希计算期间发生变化
"""
before_signature = await asyncio.to_thread(get_file_signature, filepath)
if expected_signature is not None and before_signature != expected_signature:
@@ -179,7 +196,7 @@ async def calculate_file_hash(filepath: Path, expected_signature: FileSignature
async def build_legacy_file_info(legacy_file: LegacyFileInfo) -> FileInfoModel:
"""
- 构造历史文件信息模型
+ 构造历史文件信息模型。
:param legacy_file: 历史文件信息
:return: 文件信息模型
@@ -207,12 +224,13 @@ async def migrate_legacy_files(
maintenance_confirmed: bool = False,
) -> tuple[int, int]:
"""
- 将公开目录中的历史文件登记到文件信息表
+ 将公开目录中的历史文件登记到文件信息表。
:param dry_run: 是否仅扫描不写入数据库
:param batch_size: 每批提交数量
:param maintenance_confirmed: 是否已确认停止公开文件上传
:return: 新增数量和跳过数量
+ :raises ValueError: 每批提交数量必须大于0;正式迁移前必须停止公开文件上传并确认维护窗口
"""
if batch_size < 1:
raise ValueError('每批提交数量必须大于0')
@@ -258,7 +276,7 @@ async def migrate_legacy_files(
def parse_args() -> argparse.Namespace:
"""
- 解析命令行参数
+ 解析命令行参数。
:return: 命令行参数
"""
diff --git a/ruoyi-fastapi-backend/scripts/plugin_release_integration.py b/ruoyi-fastapi-backend/scripts/plugin_release_integration.py
index e22519d71..85acdb08a 100644
--- a/ruoyi-fastapi-backend/scripts/plugin_release_integration.py
+++ b/ruoyi-fastapi-backend/scripts/plugin_release_integration.py
@@ -30,6 +30,10 @@
class RunSpec:
"""
可跨进程序列化的隔离运行信息,不包含连接密码。
+
+ :ivar engine: 执行当前任务的引擎
+ :ivar run_id: 任务ID
+ :ivar root: 路径解析的基准目录
"""
engine: str
@@ -58,7 +62,7 @@ def validate(self) -> None:
"""
校验数据库类型、运行标识和绝对输出路径。
- :return: None
+ :raises ValueError: 运行标识无效或输出根目录不是绝对路径
"""
if self.engine not in {'mysql', 'postgresql'} or not re.fullmatch(r'[0-9a-f]{32}', self.run_id):
raise ValueError('Invalid isolated integration run identity')
@@ -71,7 +75,7 @@ def require_opt_in(engine: str) -> None:
在导入服务依赖前检查显式授权和连接凭据环境变量。
:param engine: 验收使用的数据库引擎
- :return: None
+ :raises ValueError: 未显式启用真实服务测试、选择数据库或提供凭据
"""
if os.environ.get(OPT_IN) != '1':
raise ValueError(f'Real-service tests are disabled; explicitly set {OPT_IN}=1')
@@ -103,7 +107,7 @@ def check(condition: bool, message: str) -> None:
:param condition: 预期成立的验收条件
:param message: 条件不成立时的错误说明
- :return: None
+ :raises AssertionError: 验收条件未满足
"""
if not condition:
raise AssertionError(message)
@@ -115,7 +119,6 @@ def emit(phase: str, **details: Any) -> None:
:param phase: 验收阶段标识
:param details: 当前阶段的结构化结果
- :return: None
"""
print(json.dumps({'phase': phase, **details}, ensure_ascii=False), flush=True)
@@ -125,7 +128,6 @@ def configure_process(spec: RunSpec) -> None:
配置隔离环境并禁用默认应用连接,避免意外使用业务配置。
:param spec: 当前验收的隔离运行信息,不包含连接密码
- :return: None
"""
require_opt_in(spec.engine)
spec.validate()
@@ -234,7 +236,8 @@ async def isolated_session(*args: Any, **kwargs: Any) -> AsyncGenerator[Any, Non
:param args: 宿主会话工厂的位置参数,验收时禁止指定命名数据源
:param kwargs: 宿主会话工厂的关键字参数
- :return: 异步上下文中的隔离数据库会话
+ :yield: 异步上下文中的隔离数据库会话
+ :raises ValueError: 尝试在隔离验收中使用具名应用数据源
"""
if args or kwargs.get('name') is not None:
raise ValueError('Named application data sources are forbidden in integration acceptance')
@@ -267,7 +270,6 @@ async def create_isolated_database(spec: RunSpec, admin: Any) -> None:
:param spec: 当前验收的隔离运行信息,不包含连接密码
:param admin: 用于创建和删除隔离数据库的管理连接池
- :return: None
"""
spec.validate()
quote = '`' if spec.engine == 'mysql' else '"'
@@ -283,7 +285,6 @@ async def drop_isolated_database(spec: RunSpec, admin: Any) -> None:
:param spec: 当前验收的隔离运行信息,不包含连接密码
:param admin: 用于创建和删除隔离数据库的管理连接池
- :return: None
"""
spec.validate()
quote = '`' if spec.engine == 'mysql' else '"'
@@ -317,7 +318,6 @@ async def prepare_schema(spec: RunSpec, engine: Any) -> None:
:param spec: 当前验收的隔离运行信息,不包含连接密码
:param engine: 隔离数据库的异步连接池
- :return: None
"""
from sqlalchemy import select # noqa: PLC0415
@@ -452,7 +452,6 @@ async def test_real_lock(spec: RunSpec) -> None:
验证真实 Redis 锁的互斥、自动续租和按所有者释放行为。
:param spec: 当前验收的隔离运行信息,不包含连接密码
- :return: None
"""
from plugins.core.runtime.service.lifecycle_lock import RedisPluginLifecycleLock # noqa: PLC0415
@@ -485,6 +484,7 @@ async def maintenance_process(spec: RunSpec, action: str, digest: str | None) ->
:param action: 当前命令需要执行的操作
:param digest: 已导入制品的 SHA256 摘要
:return: 维护操作结果
+ :raises ValueError: 请求的隔离维护操作不受支持
"""
from plugins.core.deployment.service import PluginDeploymentService # noqa: PLC0415
from plugins.core.management.dao.release_dao import PluginReleaseDao # noqa: PLC0415
@@ -529,7 +529,6 @@ async def worker_process(spec: RunSpec, queue: Any, stop: Any, launch: str, fail
:param stop: 当前 worker 独享的停止事件
:param launch: 本轮 worker 启动标识
:param fail: 是否让当前 worker 在插件启动时主动失败
- :return: None
"""
from fastapi import FastAPI # noqa: PLC0415
@@ -570,11 +569,7 @@ async def worker_process(spec: RunSpec, queue: Any, stop: Any, launch: str, fail
async def create_tables() -> None:
# 表结构已经准备完成,此处只通过真实 Redis 统计启动写入回调的执行次数。
- """
- 通过 Redis 计数验证只有启动写入进程执行此回调。
-
- :return: None
- """
+ """通过 Redis 计数验证只有启动写入进程执行此回调。"""
await client.incr(f'{spec.redis_prefix}writer:{launch}')
started = False
@@ -616,7 +611,7 @@ def child_entry(spec: RunSpec, queue: Any, action: str, payload: Any, stop: Any
:param action: 当前命令需要执行的操作
:param payload: 当前子进程操作需要的参数
:param stop: 当前 worker 独享的停止事件
- :return: None
+ :raises SystemExit: 命令行校验失败或需要终止进程时
"""
try:
configure_process(spec)
@@ -660,6 +655,16 @@ async def run_maintenance(spec: RunSpec, action: str, digest: str | None = None)
class Workers:
"""
负责全部验收 worker 的启动与回收,包括启动未完成的进程组。
+
+ :ivar spec: 当前验收的隔离运行信息,不包含连接密码
+ :ivar retired_worker_ids: 已确认退出但其诊断快照仍可能保留的本轮 worker 身份
+ :ivar launch: 本轮 worker 启动标识
+ :ivar context: 当前操作所需的上下文
+ :ivar queue: 仅传递结果和脱敏错误的进程队列
+ :ivar stops: 用于通知各子进程退出的信号
+ :ivar processes: 由当前实例管理的子进程
+ :ivar reports: 保存各工作进程报告的集合
+ :ivar killed: 已强制终止的工作进程
"""
def __init__(
@@ -671,7 +676,6 @@ def __init__(
:param spec: 当前验收的隔离运行信息,不包含连接密码
:param one_fails: 是否让第二个 worker 主动触发启动失败
:param retired_worker_ids: 已确认退出但其诊断快照仍可能保留的本轮 worker 身份
- :return: None
"""
self.spec = spec
self.retired_worker_ids = retired_worker_ids
@@ -702,6 +706,7 @@ async def __aenter__(self) -> Workers:
启动全部 worker,并验证身份、发布代际和单写入进程约束。
:return: 已启动并收集上报结果的 worker 管理器
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
from plugins.core.runtime.diagnostics_store import ( # noqa: PLC0415
diagnostics_namespace,
@@ -760,11 +765,7 @@ async def __aenter__(self) -> Workers:
async def kill_failed_worker(self) -> None:
# 预设失败的是第二个进程,不能根据队列上报顺序判断进程身份。
- """
- 终止预设失败的第二个 worker,供心跳过期验收使用。
-
- :return: None
- """
+ """终止预设失败的第二个 worker,供心跳过期验收使用。"""
process = self.processes[1]
self.killed.add(1)
process.terminate()
@@ -772,11 +773,7 @@ async def kill_failed_worker(self) -> None:
check(not process.is_alive(), 'Failed worker did not terminate')
async def close(self) -> None:
- """
- 停止仍存活的 worker 并关闭队列,异常退出时给出验收错误。
-
- :return: None
- """
+ """停止仍存活的 worker 并关闭队列,异常退出时给出验收错误。"""
for index, process in enumerate(self.processes):
if index not in self.killed and process.pid is not None and process.is_alive():
self.stops[index].set()
@@ -800,7 +797,6 @@ async def __aexit__(self, *args: Any) -> None:
离开上下文时回收全部 worker 和队列。
:param args: 异步上下文管理协议传入的异常信息
- :return: None
"""
await self.close()
@@ -910,7 +906,7 @@ async def verify_release_wait_cli(spec: RunSpec, selected: dict[str, Any], scena
:param selected: 选择操作返回的固定制品摘要和发布代际
:param scenario: 本次验收场景的输出标识
:param reason: 预期的机器可读结果原因
- :return: None
+ :raises AssertionError: 冷启动的等待命令未按约定返回单份 JSON
"""
child_env = cli_wait_environment(spec)
command = [
@@ -983,7 +979,7 @@ async def expect_maintenance_blocked(service: Any, digest: str) -> None:
:param service: 连接到隔离数据库的发布服务
:param digest: 已导入制品的 SHA256 摘要
- :return: None
+ :raises AssertionError: 仍有在线工作进程时维护操作被错误放行
"""
try:
await service.prepare(PLUGIN_ID, digest, maintenance=True)
@@ -1000,7 +996,6 @@ async def verify_migrations(sessions: Any, installed: str, rows: int) -> None:
:param sessions: 隔离数据库的异步会话工厂
:param installed: 预期数据库安装版本
:param rows: 预期迁移探针数据和迁移历史的记录数
- :return: None
"""
from sqlalchemy import select, text # noqa: PLC0415
@@ -1029,7 +1024,6 @@ async def exercise_release_recovery(spec: RunSpec, service: Any, target: dict[st
:param spec: 当前验收的隔离运行信息,不包含连接密码
:param service: 连接到隔离数据库的发布服务
:param target: 回滚后固定的制品摘要和新发布代际
- :return: None
"""
async with Workers(spec, one_fails=True) as workers:
state = await release_state(service)
@@ -1073,7 +1067,6 @@ async def exercise_release(spec: RunSpec, engine: Any) -> None:
:param spec: 当前验收的隔离运行信息,不包含连接密码
:param engine: 隔离数据库的异步连接池
- :return: None
"""
from plugins.core.deployment.service import PluginDeploymentService # noqa: PLC0415
@@ -1149,7 +1142,8 @@ async def run(spec: RunSpec) -> None:
创建隔离资源并执行完整验收,结束时回收本轮资源。
:param spec: 当前验收的隔离运行信息,不包含连接密码
- :return: None
+ :raises ValueError: 请先按 task_demo/README.md 安装前端依赖并构建 web/dist,再运行真实发布验收
+ :raises RuntimeError: 隔离资源清理失败
"""
task_source = BACKEND_ROOT / 'plugins' / 'examples' / 'python' / 'task_demo'
if not (task_source / 'web' / 'dist' / 'index.html').is_file():
diff --git a/ruoyi-fastapi-backend/scripts/plugin_task_integration.py b/ruoyi-fastapi-backend/scripts/plugin_task_integration.py
index aaa97d7fa..2c4c20536 100644
--- a/ruoyi-fastapi-backend/scripts/plugin_task_integration.py
+++ b/ruoyi-fastapi-backend/scripts/plugin_task_integration.py
@@ -23,6 +23,8 @@ def build_task_artifacts(source: Path, root: Path, trust_file: Path) -> tuple[Pa
:param root: 本次验收专用且尚不存在的输出目录
:param trust_file: 本次验收使用的临时发布者公钥文件
:return: 旧结构夹具和当前业务插件的签名制品路径
+ :raises ValueError: 交付构建输出目录已存在
+ :raises RuntimeError: 任务包构建子进程失败
"""
import yaml # noqa: PLC0415
from cryptography.hazmat.primitives import serialization # noqa: PLC0415
@@ -86,6 +88,7 @@ async def exercise_task_delivery(service: Any, sessions: Any, source: Path, root
:param source: 包含已构建页面的 task_demo 源码目录
:param root: 当前任务验收专用的新输出目录
:return: 可用于 CI 输出的验收结果摘要
+ :raises AssertionError: 迁移执行次数不符或不可变制品出现写入
"""
from sqlalchemy import select, text # noqa: PLC0415
@@ -150,7 +153,7 @@ async def exercise_task_api(plugin: Any, sessions: Any) -> None:
:param plugin: 从签名制品目录发现的任务插件
:param sessions: 隔离数据库会话工厂
- :return: None
+ :raises AssertionError: 迁移改变原业务数据、权限边界失效或 CRUD 结果不符
"""
from httpx import ASGITransport, AsyncClient # noqa: PLC0415
@@ -164,6 +167,13 @@ async def exercise_task_api(plugin: Any, sessions: Any) -> None:
@app.middleware('http')
async def authenticated_fixture(request: Any, call_next: Any) -> Any:
+ """
+ 为任务插件的集成检查提供已认证请求上下文。
+
+ :param request: 当前 HTTP 请求
+ :param call_next: 调用下一层请求处理器的异步回调
+ :return: 带有插件请求上下文的下游响应
+ """
request.state.plugin_context = PluginRequestContext(host, user=None, permissions=permissions)
return await call_next(request)
diff --git a/ruoyi-fastapi-backend/scripts/verify_timezone_database.py b/ruoyi-fastapi-backend/scripts/verify_timezone_database.py
index 29e4afcc6..894666c7e 100644
--- a/ruoyi-fastapi-backend/scripts/verify_timezone_database.py
+++ b/ruoyi-fastapi-backend/scripts/verify_timezone_database.py
@@ -27,7 +27,7 @@
def load_source(args: argparse.Namespace) -> DataSourceSettings:
"""
- 从本地配置读取待验证数据源
+ 从本地配置读取待验证数据源。
:param args: 命令行参数
:return: 数据源连接配置
@@ -41,7 +41,7 @@ def load_source(args: argparse.Namespace) -> DataSourceSettings:
def initialize(source: DataSourceSettings, report: dict) -> DataSourceSettings: # noqa: PLR0915
"""
- 创建隔离测试库并验证UTC种子数据
+ 创建隔离测试库并验证UTC种子数据。
:param source: 具备建库权限的源连接配置
:param report: 原地补充数据库版本和初始化结果的报告字典
@@ -70,14 +70,14 @@ def initialize(source: DataSourceSettings, report: dict) -> DataSourceSettings:
}
before = TimezoneUtil.utc_now() - timedelta(seconds=1)
if target.db_type == 'mysql':
- import pymysql # noqa: PLC0415 - load only the selected driver
+ import pymysql # noqa: PLC0415 - 只加载选定的驱动
from pymysql.constants import CLIENT # noqa: PLC0415
connection = pymysql.connect(
**connection_args, charset='utf8mb4', autocommit=True, client_flag=CLIENT.MULTI_STATEMENTS
)
else:
- import psycopg2 # noqa: PLC0415 - load only the selected driver
+ import psycopg2 # noqa: PLC0415 - 只加载选定的驱动
connection = psycopg2.connect(**connection_args)
connection.autocommit = True
@@ -119,7 +119,7 @@ def initialize(source: DataSourceSettings, report: dict) -> DataSourceSettings:
def inspect_schema(source: DataSourceSettings, report: dict) -> None:
"""
- 逐列核对实际数据库和ORM的时间类型约定
+ 逐列核对实际数据库和ORM的时间类型约定。
:param source: 隔离测试库的数据源配置
:param report: 原地补充验证结果的报告字典
@@ -178,7 +178,7 @@ def inspect_schema(source: DataSourceSettings, report: dict) -> None:
async def verify_drivers(source: DataSourceSettings, report: dict) -> None:
"""
- 验证同步和异步驱动的UTC会话、精度及重连行为
+ 验证同步和异步驱动的UTC会话、精度及重连行为。
:param source: 隔离测试库的数据源配置
:param report: 原地补充验证结果的报告字典
@@ -187,7 +187,10 @@ async def verify_drivers(source: DataSourceSettings, report: dict) -> None:
async_engine = create_async_db_engine(config=source, echo=False)
metadata = MetaData()
probe = Table(
- 'timezone_verify_probe', metadata, Column('id', Integer, primary_key=True), Column('instant', DbUtcDateTime())
+ 'timezone_verify_probe',
+ metadata,
+ Column('id', Integer, primary_key=True, comment='验证记录标识'),
+ Column('instant', DbUtcDateTime(), comment='用于验证 UTC 转换的时刻'),
)
metadata.create_all(engine)
values = [
@@ -225,7 +228,7 @@ async def verify_drivers(source: DataSourceSettings, report: dict) -> None:
async def verify_generator(source: DataSourceSettings, report: dict) -> None:
"""
- 使用真实数据库验证普通表、树表和主子表生成代码
+ 使用真实数据库验证普通表、树表和主子表生成代码。
:param source: 隔离测试库的数据源配置
:param report: 原地补充验证结果的报告字典
@@ -255,7 +258,7 @@ async def verify_generator(source: DataSourceSettings, report: dict) -> None:
async def verify_metadata_and_scheduler(source: DataSourceSettings, report: dict) -> None:
"""
- 验证数据库元数据时间及持久化调度行为
+ 验证数据库元数据时间及持久化调度行为。
:param source: 隔离测试库的数据源配置
:param report: 原地补充验证结果的报告字典
@@ -297,9 +300,7 @@ async def verify_metadata_and_scheduler(source: DataSourceSettings, report: dict
def main() -> None:
- """
- 运行真实数据库的时区契约验收并输出报告
- """
+ """运行真实数据库的时区契约验收并输出报告。"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--env-file', default='.env.dev')
parser.add_argument('--source')
diff --git a/ruoyi-fastapi-backend/server.py b/ruoyi-fastapi-backend/server.py
index 0d2ff7ae1..8dffd2910 100644
--- a/ruoyi-fastapi-backend/server.py
+++ b/ruoyi-fastapi-backend/server.py
@@ -26,10 +26,9 @@
async def _start_background_tasks(app: FastAPI) -> None:
"""
- 启动应用后台任务
+ 启动应用后台任务。
:param app: FastAPI对象
- :return: None
"""
await SchedulerManager.init_system_scheduler(app.state.redis)
app.state.log_aggregator_task = asyncio.create_task(LogAggregatorService.consume_stream(app.state.redis))
@@ -38,10 +37,9 @@ async def _start_background_tasks(app: FastAPI) -> None:
async def _stop_background_tasks(app: FastAPI) -> None:
"""
- 停止应用后台任务并释放资源
+ 停止应用后台任务并释放资源。
:param app: FastAPI对象
- :return: None
"""
try:
log_task = getattr(app.state, 'log_aggregator_task', None)
@@ -72,7 +70,6 @@ async def _initialize_application_runtime(app: FastAPI, application_leader: bool
:param app: FastAPI对象
:param application_leader: 当前worker是否为Application leader
- :return: None
"""
await DataSourceRegistry.initialize(log_enabled=application_leader)
@@ -91,9 +88,7 @@ async def _initialize_application_runtime(app: FastAPI, application_leader: bool
await OidcRuntimeService.validate_runtime(app)
async def create_plugin_entity_tables() -> None:
- """
- 在插件 writer 导入实体后同步插件表。
- """
+ """在插件 writer 导入实体后同步插件表。"""
await init_create_table(
stage='plugin_entities',
log_success_enabled=True,
@@ -120,7 +115,6 @@ async def _shutdown_application_runtime(app: FastAPI) -> None:
关闭插件运行时并保证基础设施资源始终释放。
:param app: FastAPI对象
- :return: None
"""
try:
if getattr(app.state, 'plugin_application_runtime_started', False):
@@ -155,11 +149,7 @@ def _log_address_group(
def _show_startup_addresses() -> None:
- """
- 显示应用及接口文档访问地址
-
- :return: None
- """
+ """显示应用及接口文档访问地址。"""
host = AppConfig.app_host
if host == '0.0.0.0':
local_ip = IPUtil.get_local_ip()
@@ -181,10 +171,10 @@ def _show_startup_addresses() -> None:
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"""
- 应用生命周期管理
+ 应用生命周期管理。
:param app: FastAPI对象
- :return: None
+ :yield: 上下文就绪后将控制权交给调用方
"""
I18nUtil.validate_catalogs()
app.state.redis = None
@@ -240,7 +230,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
def create_app() -> FastAPI:
"""
- 创建FastAPI应用
+ 创建FastAPI应用。
:return: FastAPI对象
"""
diff --git a/ruoyi-fastapi-backend/sub_applications/handle.py b/ruoyi-fastapi-backend/sub_applications/handle.py
index 325193e90..215a57c18 100644
--- a/ruoyi-fastapi-backend/sub_applications/handle.py
+++ b/ruoyi-fastapi-backend/sub_applications/handle.py
@@ -5,7 +5,9 @@
def handle_sub_applications(app: FastAPI) -> None:
"""
- 全局处理子应用挂载
+ 全局处理子应用挂载。
+
+ :param app: 正在配置或处理请求的 ASGI 应用
"""
# 挂载静态文件
mount_staticfiles(app)
diff --git a/ruoyi-fastapi-backend/sub_applications/staticfiles.py b/ruoyi-fastapi-backend/sub_applications/staticfiles.py
index 7d99031f7..94c0c418f 100644
--- a/ruoyi-fastapi-backend/sub_applications/staticfiles.py
+++ b/ruoyi-fastapi-backend/sub_applications/staticfiles.py
@@ -11,14 +11,16 @@
class SecureStaticFiles(StaticFiles):
"""
- 安全静态文件服务类
+ 安全静态文件服务类。
+
+ :cvar DOWNLOAD_ONLY_EXTENSIONS: 仅允许以附件形式下载的文件扩展名
"""
DOWNLOAD_ONLY_EXTENSIONS = {'.html', '.htm'}
async def get_response(self, path: str, scope: Scope) -> Response:
"""
- 获取带有安全响应头的静态文件响应
+ 获取带有安全响应头的静态文件响应。
:param path: 静态文件路径
:param scope: ASGI连接作用域
@@ -39,7 +41,9 @@ async def get_response(self, path: str, scope: Scope) -> Response:
def mount_staticfiles(app: FastAPI) -> None:
"""
- 挂载静态文件
+ 挂载静态文件。
+
+ :param app: 正在配置或处理请求的 ASGI 应用
"""
app.mount(
f'{UploadConfig.UPLOAD_PREFIX}',
diff --git a/ruoyi-fastapi-backend/tests/cli/completion/test_installers.py b/ruoyi-fastapi-backend/tests/cli/completion/test_installers.py
index 00b21b026..7fe8d3adb 100644
--- a/ruoyi-fastapi-backend/tests/cli/completion/test_installers.py
+++ b/ruoyi-fastapi-backend/tests/cli/completion/test_installers.py
@@ -13,11 +13,7 @@
def test_build_source_command_uses_shell_runtime_policy() -> None:
- """
- 校验安装服务会按 shell 运行时策略构建 source 命令。
-
- :return: None
- """
+ """校验安装服务会按 shell 运行时策略构建 source 命令。"""
installer = CompletionInstallerService()
target_file = Path('/tmp/ruoyi-completion')
@@ -31,11 +27,7 @@ def test_build_source_command_uses_shell_runtime_policy() -> None:
def test_make_bash_completion_script_compatible_wraps_legacy_instructions() -> None:
- """
- 校验 Bash 兼容转换会包装旧版 shell 不支持的指令。
-
- :return: None
- """
+ """校验 Bash 兼容转换会包装旧版 shell 不支持的指令。"""
script_text = 'compopt -o dirnames\ncompopt -o default\ncomplete -o nosort -F _ruoyi_completion ruoyi'
compatible_script = CompletionInstallerShellSupport.make_bash_completion_script_compatible(script_text)
@@ -46,17 +38,10 @@ def test_make_bash_completion_script_compatible_wraps_legacy_instructions() -> N
def test_render_completion_script_uses_runtime_policy_transformer(monkeypatch: MonkeyPatch) -> None:
- """
- 校验脚本渲染会通过 shell 运行时策略执行脚本后处理。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验脚本渲染会通过 shell 运行时策略执行脚本后处理。"""
class DummyComplete:
- """
- 模拟 Click completion 生成器。
- """
+ """模拟 Click completion 生成器。"""
def __init__(self, *args, **kwargs) -> None:
"""
@@ -64,7 +49,6 @@ def __init__(self, *args, **kwargs) -> None:
:param args: 位置参数
:param kwargs: 关键字参数
- :return: None
"""
@staticmethod
@@ -95,17 +79,14 @@ def source() -> str:
def test_render_powershell_completion_script_contains_native_completer() -> None:
- """
- 校验 PowerShell completion 脚本会注册原生命令补全器。
-
- :return: None
- """
+ """校验 PowerShell completion 脚本会注册原生命令补全器。"""
installer = CompletionInstallerService()
root_cli = typer.Typer()
@root_cli.command()
def demo() -> None:
- return None
+ """完成无需返回值的回调。"""
+ return
rendered_script = installer.render_completion_script(root_cli, 'powershell')
@@ -114,11 +95,13 @@ def demo() -> None:
def test_render_bash_script_does_not_execute_the_host_shell() -> None:
+ """渲染 Bash 脚本时不执行宿主命令。"""
root_cli = typer.Typer()
@root_cli.command()
def demo() -> None:
- return None
+ """完成无需返回值的回调。"""
+ return
with patch('click.shell_completion.BashComplete._check_version', side_effect=AssertionError('host shell invoked')):
rendered = CompletionInstallerService().render_completion_script(root_cli, 'bash')
diff --git a/ruoyi-fastapi-backend/tests/cli/completion/test_providers.py b/ruoyi-fastapi-backend/tests/cli/completion/test_providers.py
index 32d8c712b..3e77ab342 100644
--- a/ruoyi-fastapi-backend/tests/cli/completion/test_providers.py
+++ b/ruoyi-fastapi-backend/tests/cli/completion/test_providers.py
@@ -20,13 +20,7 @@ def test_complete_alembic_revisions_returns_default_choices_and_local_revisions(
tmp_path: Path,
monkeypatch: MonkeyPatch,
) -> None:
- """
- 校验 Alembic 版本补全会返回默认候选和本地迁移版本。
-
- :param tmp_path: pytest 临时目录
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验 Alembic 版本补全会返回默认候选和本地迁移版本。"""
versions_dir = tmp_path / 'alembic' / 'versions'
versions_dir.mkdir(parents=True)
(versions_dir / '2026_04_29_1000-abc123_add_demo_table.py').write_text('# test', encoding='utf-8')
@@ -47,13 +41,7 @@ def test_complete_sql_files_returns_project_relative_sql_paths(
tmp_path: Path,
monkeypatch: MonkeyPatch,
) -> None:
- """
- 校验 SQL 文件补全会返回项目相对路径。
-
- :param tmp_path: pytest 临时目录
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验 SQL 文件补全会返回项目相对路径。"""
sql_dir = tmp_path / 'sql'
sql_dir.mkdir()
(sql_dir / 'demo.sql').write_text('select 1;', encoding='utf-8')
@@ -66,16 +54,13 @@ def test_complete_sql_files_returns_project_relative_sql_paths(
def test_complete_cache_names_returns_static_cache_name_choices(monkeypatch: MonkeyPatch) -> None:
- """
- 校验缓存名称补全会返回系统内置缓存名称。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验缓存名称补全会返回系统内置缓存名称。"""
class _FakeCacheKeyConfig:
"""
模拟缓存键配置对象。
+
+ :ivar key: 缓存名称
"""
def __init__(self, key: str) -> None:
@@ -83,13 +68,14 @@ def __init__(self, key: str) -> None:
初始化模拟缓存键配置对象。
:param key: 缓存名称
- :return: None
"""
self.key = key
class _FakeEnumsModule:
"""
模拟枚举模块。
+
+ :cvar RedisInitKeyConfig: 测试使用的 Redis 初始化键配置
"""
RedisInitKeyConfig = [_FakeCacheKeyConfig('sys_config'), _FakeCacheKeyConfig('login_tokens')]
@@ -107,13 +93,7 @@ def test_complete_output_paths_returns_directories_and_zip_files(
tmp_path: Path,
monkeypatch: MonkeyPatch,
) -> None:
- """
- 校验导出路径补全会返回目录和 zip 文件。
-
- :param tmp_path: pytest 临时目录
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验导出路径补全会返回目录和 zip 文件。"""
build_dir = tmp_path / 'build'
build_dir.mkdir()
(build_dir / 'gen.zip').write_text('zip', encoding='utf-8')
@@ -128,22 +108,17 @@ def test_complete_output_paths_returns_directories_and_zip_files(
def test_complete_config_keys_returns_dynamic_readonly_choices(monkeypatch: MonkeyPatch) -> None:
- """
- 校验参数键名补全会返回动态只读查询结果。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验参数键名补全会返回动态只读查询结果。"""
class _FakeConfigRuntime:
"""
模拟配置运行时模块。
+
+ :cvar CONFIG_RUNTIME: 配置命令的测试运行时
"""
class ConfigRuntime:
- """
- 模拟配置运行时服务对象。
- """
+ """模拟配置运行时服务对象。"""
@staticmethod
def list_configs(**kwargs: str) -> dict:
@@ -178,22 +153,17 @@ def list_configs(**kwargs: str) -> dict:
def test_complete_gen_table_names_returns_dynamic_readonly_choices(monkeypatch: MonkeyPatch) -> None:
- """
- 校验代码生成业务表补全会返回动态只读查询结果。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验代码生成业务表补全会返回动态只读查询结果。"""
class _FakeGenRuntime:
"""
模拟代码生成运行时模块。
+
+ :cvar GEN_RUNTIME: 生成器命令的测试运行时
"""
class GenRuntime:
- """
- 模拟代码生成运行时服务对象。
- """
+ """模拟代码生成运行时服务对象。"""
@staticmethod
def list_gen_tables(**kwargs: str) -> dict:
@@ -236,12 +206,7 @@ def list_gen_db_tables(**kwargs: str) -> dict:
def test_dynamic_completion_returns_empty_list_when_runtime_fails(monkeypatch: MonkeyPatch) -> None:
- """
- 校验动态补全在运行时失败时会优雅降级为空列表。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验动态补全在运行时失败时会优雅降级为空列表。"""
monkeypatch.setattr(
completion_registry.dynamic_service,
'load_runtime_module',
@@ -254,22 +219,17 @@ def test_dynamic_completion_returns_empty_list_when_runtime_fails(monkeypatch: M
def test_complete_cache_keys_returns_dynamic_readonly_choices(monkeypatch: MonkeyPatch) -> None:
- """
- 校验缓存键名补全会基于缓存名称返回动态只读查询结果。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验缓存键名补全会基于缓存名称返回动态只读查询结果。"""
class _FakeCacheRuntime:
"""
模拟缓存运行时模块。
+
+ :cvar CACHE_RUNTIME: 缓存命令的测试运行时
"""
class CacheRuntime:
- """
- 模拟缓存运行时服务对象。
- """
+ """模拟缓存运行时服务对象。"""
@staticmethod
def list_cache_keys(cache_name: str) -> dict[str, str]:
@@ -286,6 +246,8 @@ def list_cache_keys(cache_name: str) -> dict[str, str]:
class _FakeContext:
"""
模拟 Click 上下文。
+
+ :cvar params: 调用时传入的参数
"""
params = {'cache_name': 'sys_config'}
@@ -308,22 +270,17 @@ class _FakeContext:
def test_complete_job_names_returns_dynamic_readonly_choices(monkeypatch: MonkeyPatch) -> None:
- """
- 校验任务名称补全会返回动态只读查询结果。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验任务名称补全会返回动态只读查询结果。"""
class _FakeJobRuntime:
"""
模拟任务运行时模块。
+
+ :cvar JOB_RUNTIME: 调度命令的测试运行时
"""
class JobRuntime:
- """
- 模拟任务运行时服务对象。
- """
+ """模拟任务运行时服务对象。"""
@staticmethod
def list_jobs(**kwargs: str) -> dict:
@@ -356,22 +313,17 @@ def list_jobs(**kwargs: str) -> dict:
def test_complete_job_ids_returns_dynamic_readonly_choices(monkeypatch: MonkeyPatch) -> None:
- """
- 校验任务 ID 补全会返回动态只读查询结果。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验任务 ID 补全会返回动态只读查询结果。"""
class _FakeJobRuntime:
"""
模拟任务运行时模块。
+
+ :cvar JOB_RUNTIME: 调度命令的测试运行时
"""
class JobRuntime:
- """
- 模拟任务运行时服务对象。
- """
+ """模拟任务运行时服务对象。"""
@staticmethod
def list_jobs(**kwargs: str) -> dict:
@@ -404,16 +356,16 @@ def list_jobs(**kwargs: str) -> dict:
def test_run_completion_coroutine_scopes_app_env(monkeypatch: MonkeyPatch) -> None:
- """
- 校验动态补全执行时会临时注入 APP_ENV,并在结束后恢复原值。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验动态补全执行时会临时注入 APP_ENV,并在结束后恢复原值。"""
monkeypatch.setenv('APP_ENV', 'prod')
captured: dict[str, str | None] = {}
async def _read_env() -> str | None:
+ """
+ 记录调用期间可见的应用环境。
+
+ :return: 被测调用期间读取的环境标记
+ """
captured['during'] = os.environ.get('APP_ENV')
return captured['during']
@@ -425,15 +377,15 @@ async def _read_env() -> str | None:
def test_run_completion_coroutine_clears_scoped_app_env_when_original_missing(monkeypatch: MonkeyPatch) -> None:
- """
- 校验动态补全执行结束后会移除临时注入的 APP_ENV。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验动态补全执行结束后会移除临时注入的 APP_ENV。"""
monkeypatch.delenv('APP_ENV', raising=False)
async def _read_env() -> str | None:
+ """
+ 记录调用期间可见的应用环境。
+
+ :return: 环境变量中记录的运行环境
+ """
return os.environ.get('APP_ENV')
result = completion_registry.dynamic_service.run_completion_coroutine(_read_env(), env='dockerpg')
diff --git a/ruoyi-fastapi-backend/tests/cli/core/test_app_bootstrap.py b/ruoyi-fastapi-backend/tests/cli/core/test_app_bootstrap.py
index bc24730e3..decd043f0 100644
--- a/ruoyi-fastapi-backend/tests/cli/core/test_app_bootstrap.py
+++ b/ruoyi-fastapi-backend/tests/cli/core/test_app_bootstrap.py
@@ -16,17 +16,30 @@
class FakeRuntimeEnvironment(RuntimeEnvironmentService):
+ """提供启动测试使用的后端路径和解释器。"""
+
@staticmethod
def get_backend_dir() -> str:
+ """
+ 返回测试环境使用的后端根目录。
+
+ :return: 测试环境使用的后端根目录
+ """
return 'C:\\project\\ruoyi-fastapi-backend'
@staticmethod
def get_python_executable() -> str:
+ """
+ 返回测试使用的 Python 解释器路径。
+
+ :return: 测试使用的 Python 解释器路径
+ """
return 'C:\\Python\\python.exe'
@pytest.mark.parametrize('module_name,expected', [('__main__', 'server:create_app'), ('app', 'create_app')])
def test_app_entry_compiles_catalogs_before_startup(module_name: str, expected: str, monkeypatch: MonkeyPatch) -> None:
+ """应用启动前编译翻译目录。"""
calls = []
monkeypatch.setattr(
'scripts.compile_i18n.compile_catalogs', lambda *, isolate_plugin_errors: calls.append(isolate_plugin_errors)
@@ -41,6 +54,7 @@ def test_app_entry_compiles_catalogs_before_startup(module_name: str, expected:
@pytest.mark.parametrize('module_name', ['__main__', 'app'])
def test_app_entry_stops_on_catalog_error(module_name: str, monkeypatch: MonkeyPatch) -> None:
+ """翻译目录编译失败时中止启动。"""
monkeypatch.setattr('scripts.compile_i18n.compile_catalogs', Mock(side_effect=ValueError('invalid catalog')))
start = Mock()
monkeypatch.setattr('uvicorn.run', start)
@@ -53,6 +67,7 @@ def test_app_entry_stops_on_catalog_error(module_name: str, monkeypatch: MonkeyP
def test_exec_app_run_command_waits_for_child_process_on_windows(monkeypatch: MonkeyPatch) -> None:
+ """Windows 启动器等待子进程结束。"""
service = AppBootstrapService(runtime_environment=FakeRuntimeEnvironment())
expected_command = [
'C:\\Python\\python.exe',
@@ -63,6 +78,13 @@ def test_exec_app_run_command_waits_for_child_process_on_windows(monkeypatch: Mo
captured: dict[str, object] = {}
def fake_run(command: list[str], *, check: bool) -> subprocess.CompletedProcess[str]:
+ """
+ 模拟子进程运行并记录命令参数。
+
+ :param command: 执行的命令及其参数
+ :param check: 对源码运行文档检查并返回行号和诊断的测试夹具
+ :return: ``subprocess.CompletedProcess`` 实例
+ """
captured['command'] = command
captured['check'] = check
return subprocess.CompletedProcess(command, CHILD_EXIT_CODE)
@@ -78,9 +100,17 @@ def fake_run(command: list[str], *, check: bool) -> subprocess.CompletedProcess[
def test_exec_app_run_command_returns_interrupt_exit_code_on_windows(monkeypatch: MonkeyPatch) -> None:
+ """Windows 启动器在中断时返回相应退出码。"""
service = AppBootstrapService(runtime_environment=FakeRuntimeEnvironment())
def fake_run(command: list[str], *, check: bool) -> subprocess.CompletedProcess[str]:
+ """
+ 模拟此操作抛出 KeyboardInterrupt 的情形。
+
+ :param command: 执行的命令及其参数
+ :param check: 对源码运行文档检查并返回行号和诊断的测试夹具
+ :raises KeyboardInterrupt: 执行期间收到中断信号时
+ """
raise KeyboardInterrupt
monkeypatch.setattr(bootstrap, '_IS_WINDOWS', True)
@@ -93,10 +123,17 @@ def fake_run(command: list[str], *, check: bool) -> subprocess.CompletedProcess[
def test_exec_app_run_command_uses_exec_on_posix(monkeypatch: MonkeyPatch) -> None:
+ """POSIX 启动器通过 exec 替换当前进程。"""
service = AppBootstrapService(runtime_environment=FakeRuntimeEnvironment())
captured: dict[str, object] = {}
def fake_execvp(executable: str, command: list[str]) -> None:
+ """
+ 捕获将要替换进程的可执行文件和参数。
+
+ :param executable: 需要启动的可执行文件
+ :param command: 执行的命令及其参数
+ """
captured['executable'] = executable
captured['command'] = command
diff --git a/ruoyi-fastapi-backend/tests/cli/core/test_context_factory.py b/ruoyi-fastapi-backend/tests/cli/core/test_context_factory.py
index 35018152a..2595a8dc7 100644
--- a/ruoyi-fastapi-backend/tests/cli/core/test_context_factory.py
+++ b/ruoyi-fastapi-backend/tests/cli/core/test_context_factory.py
@@ -9,6 +9,7 @@
def test_suppress_sqlalchemy_logs_disables_echo_for_all_sources(monkeypatch: MonkeyPatch) -> None:
+ """关闭 SQLAlchemy 日志时禁用全部数据源的 echo。"""
sources = {
'primary': SimpleNamespace(db_echo=True),
'reporting': SimpleNamespace(db_echo=True),
@@ -19,6 +20,12 @@ def test_suppress_sqlalchemy_logs_disables_echo_for_all_sources(monkeypatch: Mon
monkeypatch.setattr(context_factory, 'import_module', lambda _name: env_module)
def get_logger(name: str) -> MagicMock:
+ """
+ 按名称创建并记录日志替身。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 供调用方使用的 ``logger``
+ """
logger = MagicMock()
loggers[name] = logger
return logger
diff --git a/ruoyi-fastapi-backend/tests/cli/core/test_execution_service.py b/ruoyi-fastapi-backend/tests/cli/core/test_execution_service.py
index 802c3c6c7..88e7e2f40 100644
--- a/ruoyi-fastapi-backend/tests/cli/core/test_execution_service.py
+++ b/ruoyi-fastapi-backend/tests/cli/core/test_execution_service.py
@@ -16,11 +16,7 @@
def test_build_result_does_not_mutate_payload_and_removes_exit_code_from_result_data() -> None:
- """
- 校验结果翻译不会修改调用方 payload,且会从结果数据中移除 exit_code 字段。
-
- :return: None
- """
+ """校验结果翻译不会修改调用方 payload,且会从结果数据中移除 exit_code 字段。"""
payload = {'ok': True, 'message': 'done', 'exit_code': EXPLICIT_EXIT_CODE}
result = cli_execution.CliExecutionService.build_result(payload)
@@ -31,11 +27,7 @@ def test_build_result_does_not_mutate_payload_and_removes_exit_code_from_result_
def test_build_result_uses_runtime_error_when_failed_payload_has_no_explicit_exit_code() -> None:
- """
- 校验失败 payload 未显式提供退出码时,会回退到统一运行时错误码。
-
- :return: None
- """
+ """校验失败 payload 未显式提供退出码时,会回退到统一运行时错误码。"""
payload = {'ok': False, 'message': 'failed'}
result = cli_execution.CliExecutionService.build_result(payload)
@@ -46,11 +38,7 @@ def test_build_result_uses_runtime_error_when_failed_payload_has_no_explicit_exi
def test_build_result_uses_default_exit_code_without_mutating_payload() -> None:
- """
- 校验显式默认退出码会参与结果翻译,且不会修改原始 payload。
-
- :return: None
- """
+ """校验显式默认退出码会参与结果翻译,且不会修改原始 payload。"""
payload = {'ok': True, 'message': 'warn'}
result = cli_execution.CliExecutionService.build_result(payload, default_exit_code=DEFAULT_EXIT_CODE)
@@ -61,11 +49,7 @@ def test_build_result_uses_default_exit_code_without_mutating_payload() -> None:
def test_build_result_uses_runtime_error_when_failed_payload_keeps_default_zero() -> None:
- """
- 校验失败 payload 在未显式提供退出码且默认退出码为 0 时,会回退到统一运行时错误码。
-
- :return: None
- """
+ """校验失败 payload 在未显式提供退出码且默认退出码为 0 时,会回退到统一运行时错误码。"""
payload = {'ok': False, 'message': 'failed'}
result = cli_execution.CliExecutionService.build_result(payload, default_exit_code=0)
diff --git a/ruoyi-fastapi-backend/tests/cli/root/conftest.py b/ruoyi-fastapi-backend/tests/cli/root/conftest.py
index 2a0716b6d..f29ab5dd6 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/conftest.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/conftest.py
@@ -13,12 +13,31 @@
@pytest.fixture
def backend_dir() -> Path:
+ """
+ 提供测试使用的后端工程根目录。
+
+ :return: 测试使用的后端工程根目录
+ """
return Path(__file__).resolve().parents[3]
@pytest.fixture
def run_cli_command(backend_dir: Path) -> Callable[..., subprocess.CompletedProcess[str]]:
+ """
+ 提供执行 CLI 子进程并捕获输出的测试入口。
+
+ :param backend_dir: 后端项目目录
+ :return: 执行 CLI 子进程并捕获输出的测试入口
+ """
+
def _run_cli_command(*args: str, env: Mapping[str, str] | None = None) -> subprocess.CompletedProcess[str]:
+ """
+ 运行指定 CLI 命令并收集退出码和输出。
+
+ :param args: 传给被调用对象的位置参数
+ :param env: 当前运行环境
+ :return: 包含退出码和标准输出、错误输出的子进程结果
+ """
return subprocess.run(
[sys.executable, '-X', 'utf8', '-m', 'cli.main', *args],
cwd=backend_dir,
@@ -37,7 +56,20 @@ def _run_cli_command(*args: str, env: Mapping[str, str] | None = None) -> subpro
def run_text_cli_command(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> Callable[..., subprocess.CompletedProcess[str]]:
+ """
+ 提供纯文本输出模式的 CLI 调用入口。
+
+ :param run_cli_command: 执行 CLI 子命令并返回进程结果的测试工具
+ :return: 纯文本输出模式的 CLI 调用入口
+ """
+
def _run_text_cli_command(*args: str) -> subprocess.CompletedProcess[str]:
+ """
+ 关闭颜色和图标后运行 CLI 命令。
+
+ :param args: 传给被调用对象的位置参数
+ :return: 关闭颜色和图标后的命令执行结果
+ """
return run_cli_command('--color=never', '--icon=none', *args)
return _run_text_cli_command
@@ -47,12 +79,27 @@ def _run_text_cli_command(*args: str) -> subprocess.CompletedProcess[str]:
def run_cli_completion_command(
backend_dir: Path,
) -> Callable[..., subprocess.CompletedProcess[str]]:
+ """
+ 提供模拟 Shell 补全请求的运行入口。
+
+ :param backend_dir: 后端项目目录
+ :return: 模拟 Shell 补全请求的运行入口
+ """
+
def _run_cli_completion_command(
*,
comp_words: str,
comp_cword: int | str,
instruction: str = 'bash_complete',
) -> subprocess.CompletedProcess[str]:
+ """
+ 执行补全请求并捕获候选项输出。
+
+ :param comp_words: 当前补全请求的命令行词列表
+ :param comp_cword: 光标所在词的位置
+ :param instruction: 请求补全时传给 shell 的指令
+ :return: 包含候选项或诊断的补全进程结果
+ """
return subprocess.run(
[sys.executable, '-X', 'utf8', '-m', 'cli.main'],
cwd=backend_dir,
@@ -97,7 +144,19 @@ def untracked_bundle_project(tmp_path: Path) -> Path:
@pytest.fixture
def parse_json_stdout() -> Callable[[subprocess.CompletedProcess[str]], dict[str, Any]]:
+ """
+ 提供从命令标准输出读取 JSON 的解析器。
+
+ :return: 从命令标准输出读取 JSON 的解析器
+ """
+
def _parse_json_stdout(completed: subprocess.CompletedProcess[str]) -> dict[str, Any]:
+ """
+ 从 CLI 标准输出中解析 JSON 结果。
+
+ :param completed: 命令执行完成后的进程结果
+ :return: 从命令标准输出解码的数据
+ """
return json.loads(completed.stdout)
return _parse_json_stdout
@@ -105,7 +164,19 @@ def _parse_json_stdout(completed: subprocess.CompletedProcess[str]) -> dict[str,
@pytest.fixture
def assert_check_payload_contract() -> Callable[[dict[str, Any], bool], None]:
+ """
+ 提供 CLI 检查结果的结构断言。
+
+ :return: CLI 检查结果的结构断言
+ """
+
def _assert_check_payload_contract(payload: dict[str, Any], allow_exit_code: bool) -> None:
+ """
+ 校验检查命令结果中的公共字段和类型。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :param allow_exit_code: 契约允许的退出码
+ """
assert isinstance(payload, dict)
assert isinstance(payload.get('ok'), bool)
assert isinstance(payload.get('message'), str)
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_bootstrap.py b/ruoyi-fastapi-backend/tests/cli/root/test_bootstrap.py
index 6cb1c3c77..d3dff2a84 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_bootstrap.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_bootstrap.py
@@ -46,11 +46,7 @@ def test_config_env_loads_app_env_from_selected_run_env() -> None:
def test_bootstrap_import_does_not_eagerly_load_heavy_runtime_modules() -> None:
- """
- 校验导入 `cli.bootstrap` 时不会提前加载重依赖模块。
-
- :return: None
- """
+ """校验导入 ``cli.bootstrap`` 时不会提前加载重依赖模块。"""
script = """
import json
import sys
@@ -98,11 +94,7 @@ def test_bootstrap_import_does_not_eagerly_load_heavy_runtime_modules() -> None:
def test_build_cli_does_not_eagerly_load_heavy_runtime_dependencies() -> None:
- """
- 校验构建 CLI 根应用时不会提前加载 DB、Redis、Scheduler 和业务服务依赖。
-
- :return: None
- """
+ """校验构建 CLI 根应用时不会提前加载 DB、Redis、Scheduler 和业务服务依赖。"""
script = """
import json
import sys
@@ -170,11 +162,7 @@ def test_build_cli_does_not_eagerly_load_heavy_runtime_dependencies() -> None:
def test_build_wizard_app_does_not_eagerly_load_flow_modules() -> None:
- """
- 校验构建 `wizard` 子应用时不会提前加载各个 flow 模块。
-
- :return: None
- """
+ """校验构建 ``wizard`` 子应用时不会提前加载各个 flow 模块。"""
script = """
import json
import sys
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_contract_app_ops.py b/ruoyi-fastapi-backend/tests/cli/root/test_contract_app_ops.py
index a2af1271b..e46dc091d 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_contract_app_ops.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_contract_app_ops.py
@@ -18,6 +18,7 @@ def test_app_config_json_output_is_pure_json(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """应用配置命令只输出 JSON。"""
completed = run_cli_command('app', 'config', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -34,6 +35,7 @@ def test_app_config_json_output_is_pure_json(
def test_app_config_text_output_has_stable_section_structure(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """应用配置文本按约定分节。"""
completed = run_text_cli_command('app', 'config', '--env=dev', '--output=text')
assert completed.returncode == SUCCESS
@@ -51,6 +53,7 @@ def test_app_config_text_output_has_stable_section_structure(
def test_app_env_text_output_has_stable_section_structure(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """环境信息文本按约定分节。"""
completed = run_text_cli_command('app', 'env', '--env=dev', '--output=text')
assert completed.returncode == SUCCESS
@@ -69,6 +72,7 @@ def test_app_env_text_output_has_stable_section_structure(
def test_app_doctor_text_output_has_stable_check_structure(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """应用诊断文本按检查项组织。"""
completed = run_text_cli_command('app', 'doctor', '--env=dev', '--output=text')
assert completed.returncode in {SUCCESS, DEPENDENCY_ERROR}
@@ -88,6 +92,7 @@ def test_app_doctor_json_output_has_stable_contract(
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
assert_check_payload_contract: Callable[[dict, bool], None],
) -> None:
+ """应用诊断按约定输出 JSON。"""
completed = run_cli_command('app', 'doctor', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -106,6 +111,7 @@ def test_app_env_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """环境信息按约定输出 JSON。"""
completed = run_cli_command('app', 'env', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -134,6 +140,7 @@ def test_app_routes_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """路由列表按约定输出 JSON。"""
completed = run_cli_command('app', 'routes', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -177,6 +184,7 @@ def test_app_routes_json_output_has_stable_contract(
def test_server_info_text_output_has_stable_section_structure(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """服务器信息文本按约定分节。"""
completed = run_text_cli_command('ops', 'server-info', '--env=dev')
assert completed.returncode == 0
@@ -193,6 +201,7 @@ def test_server_info_text_output_has_stable_section_structure(
def test_ops_health_text_output_has_stable_check_structure(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """健康检查文本按检查项组织。"""
completed = run_text_cli_command('ops', 'health', '--env=dev', '--output=text')
assert completed.returncode in {SUCCESS, DEPENDENCY_ERROR}
@@ -208,6 +217,7 @@ def test_ops_health_text_output_has_stable_check_structure(
def test_ops_deps_text_output_has_stable_structure(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """依赖检查文本按约定组织。"""
completed = run_text_cli_command('ops', 'deps', '--env=dev', '--output=text')
assert completed.returncode in {SUCCESS, DEPENDENCY_ERROR}
@@ -226,6 +236,7 @@ def test_ops_health_json_output_has_stable_contract(
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
assert_check_payload_contract: Callable[[dict, bool], None],
) -> None:
+ """健康检查按约定输出 JSON。"""
completed = run_cli_command('ops', 'health', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -242,6 +253,7 @@ def test_ops_deps_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """依赖检查按约定输出 JSON。"""
completed = run_cli_command('ops', 'deps', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -266,6 +278,7 @@ def test_ops_server_info_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """服务器信息按约定输出 JSON。"""
completed = run_cli_command('ops', 'server-info', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -327,6 +340,7 @@ def test_plugin_list_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """插件列表按约定输出 JSON。"""
completed = run_cli_command('plugin', 'list', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -345,6 +359,7 @@ def test_plugin_check_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """插件检查按约定输出 JSON。"""
completed = run_cli_command('plugin', 'check', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -373,6 +388,7 @@ def test_plugin_check_deps_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """插件依赖检查按约定输出 JSON。"""
completed = run_cli_command('plugin', 'check-deps', 'ai', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -394,6 +410,7 @@ def test_plugin_install_deps_dry_run_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """插件依赖安装预演按约定输出 JSON。"""
completed = run_cli_command('plugin', 'install-deps', 'ai', '--dry-run', '--yes', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -409,6 +426,7 @@ def test_plugin_plan_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """插件操作计划按约定输出 JSON。"""
completed = run_cli_command('plugin', 'plan', 'install', 'ai', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -424,6 +442,7 @@ def test_plugin_plan_json_output_has_stable_contract(
def test_plugin_plan_rejects_invalid_operation_at_cli_boundary(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """命令行拒绝无效的插件计划操作。"""
completed = run_cli_command('plugin', 'plan', 'remove', 'ai', '--env=dev', '--output=json')
assert completed.returncode != SUCCESS
@@ -434,6 +453,7 @@ def test_plugin_batch_dry_run_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """批量插件操作预演按约定输出 JSON。"""
completed = run_cli_command('plugin', 'batch', 'install', 'ai', '--dry-run', '--yes', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -451,6 +471,7 @@ def test_plugin_batch_dry_run_json_output_has_stable_contract(
def test_plugin_list_text_output_has_stable_structure(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """插件列表文本按约定组织。"""
completed = run_text_cli_command('plugin', 'list', '--env=dev', '--output=text')
assert completed.returncode == SUCCESS
@@ -463,6 +484,7 @@ def test_plugin_create_dry_run_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """创建插件的预演按约定输出 JSON。"""
completed = run_cli_command('plugin', 'create', 'contract_demo', '--dry-run', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -486,6 +508,7 @@ def test_plugin_create_optional_parts_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """创建插件时在 JSON 中列出可选组件。"""
completed = run_cli_command(
'plugin',
'create',
@@ -515,6 +538,7 @@ def test_plugin_create_frontend_framework_override_json_output_has_stable_contra
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """创建插件时在 JSON 中反映指定的前端框架。"""
completed = run_cli_command(
'plugin',
'create',
@@ -566,6 +590,7 @@ def test_plugin_install_dry_run_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """安装插件的预演按约定输出 JSON。"""
completed = run_cli_command(
'plugin', 'install', 'missing_plugin', '--dry-run', '--yes', '--env=dev', '--output=json'
)
@@ -581,6 +606,7 @@ def test_plugin_upgrade_dry_run_json_output_has_stable_contract(
backend_dir: Path,
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """升级插件的预演按约定输出 JSON。"""
# 成功契约需要已确认的目录插件来源;CI 不应连接宿主数据库来决定测试结果。
script = dedent(
"""
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_contract_cli.py b/ruoyi-fastapi-backend/tests/cli/root/test_contract_cli.py
index e5f657055..d877d2c3f 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_contract_cli.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_contract_cli.py
@@ -12,6 +12,7 @@
def test_root_help_shows_commands_without_completion_options(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """顶层帮助列出命令并隐藏补全选项。"""
completed = run_cli_command('--help')
assert completed.returncode == 0
@@ -59,6 +60,7 @@ def test_oidc_key_bootstrap_dry_run_has_stable_contract(
def test_completion_show_bash_outputs_completion_script(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """输出 Bash 补全脚本。"""
completed = run_cli_command('completion', 'show', 'bash')
assert completed.returncode == SUCCESS
@@ -73,6 +75,7 @@ def test_completion_show_bash_outputs_completion_script(
def test_completion_show_powershell_outputs_completion_script(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """输出 PowerShell 补全脚本。"""
completed = run_cli_command('completion', 'show', 'powershell')
assert completed.returncode == SUCCESS
@@ -84,6 +87,7 @@ def test_completion_show_powershell_outputs_completion_script(
def test_bash_completion_protocol_returns_candidates_without_not_supported_error(
run_cli_completion_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """Bash 补全协议正常返回候选项。"""
completed = run_cli_completion_command(comp_words='ruoyi comp', comp_cword=1)
assert completed.returncode == SUCCESS
@@ -95,6 +99,7 @@ def test_bash_completion_protocol_returns_candidates_without_not_supported_error
def test_powershell_completion_protocol_returns_candidates_without_not_supported_error(
run_cli_completion_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """PowerShell 补全协议正常返回候选项。"""
completed = run_cli_completion_command(
comp_words='ruoyi comp',
comp_cword='comp',
@@ -111,6 +116,7 @@ def test_completion_doctor_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """补全诊断按约定输出 JSON。"""
completed = run_cli_command('completion', 'doctor', '--output=json')
payload = parse_json_stdout(completed)
@@ -145,6 +151,7 @@ def test_completion_install_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """安装补全脚本按约定输出 JSON。"""
target_file = tmp_path / 'ruoyi.bash'
rc_file = tmp_path / '.bashrc'
completed = run_cli_command(
@@ -198,6 +205,7 @@ def test_completion_install_powershell_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """安装 PowerShell 补全时按约定输出 JSON。"""
target_file = tmp_path / 'ruoyi.ps1'
rc_file = tmp_path / 'Microsoft.PowerShell_profile.ps1'
completed = run_cli_command(
@@ -233,6 +241,7 @@ def test_completion_install_powershell_json_output_has_stable_contract(
def test_app_run_help_only_exposes_env_option(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """应用启动帮助仅显示环境选项。"""
completed = run_cli_command('app', 'run', '--help')
assert completed.returncode == 0
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_contract_config.py b/ruoyi-fastapi-backend/tests/cli/root/test_contract_config.py
index 81a0adbd7..bbe2f5c4e 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_contract_config.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_contract_config.py
@@ -12,6 +12,7 @@ def test_config_doctor_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """配置诊断按约定输出 JSON。"""
completed = run_cli_command('config', 'doctor', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_contract_db_cache_dev.py b/ruoyi-fastapi-backend/tests/cli/root/test_contract_db_cache_dev.py
index 45c7b96ab..f33d4e5d7 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_contract_db_cache_dev.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_contract_db_cache_dev.py
@@ -14,6 +14,7 @@ def test_dangerous_command_is_rejected_without_yes_in_non_interactive_mode(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """非交互执行危险命令时必须显式确认。"""
completed = run_cli_command('db', 'revision', '--env=dev', '--message=test-contract', '--output=json')
payload = parse_json_stdout(completed)
@@ -27,6 +28,7 @@ def test_prod_dangerous_command_is_rejected_without_allow_prod(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """生产环境的危险命令需要显式授权。"""
completed = run_cli_command('db', 'revision', '--env=prod', '--message=test-contract', '--output=json')
payload = parse_json_stdout(completed)
@@ -42,6 +44,7 @@ def test_dry_run_command_returns_structured_preview_payload(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """命令预演返回结构化预览。"""
completed = run_cli_command(
'db',
'upgrade',
@@ -65,6 +68,7 @@ def test_db_heads_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """数据库迁移头按约定输出 JSON。"""
completed = run_cli_command('db', 'heads', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -94,6 +98,7 @@ def test_db_history_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """数据库迁移历史按约定输出 JSON。"""
completed = run_cli_command(
'db',
'history',
@@ -122,6 +127,7 @@ def test_cache_ttl_json_output_has_stable_contract_for_missing_key_or_redis_erro
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """缓存键缺失或 Redis 报错时仍按约定输出 TTL 信息。"""
completed = run_cli_command(
'cache',
'ttl',
@@ -149,6 +155,7 @@ def test_cache_ttl_json_output_has_stable_contract_for_missing_key_or_redis_erro
def test_dangerous_command_rejection_text_output_is_human_readable(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """以可读文本说明拒绝危险命令的原因。"""
completed = run_text_cli_command('db', 'revision', '--env=dev', '--message=test-contract', '--output=text')
assert completed.returncode == GUARD_REJECTED
@@ -163,6 +170,7 @@ def test_dry_run_text_output_contains_preview_command_and_workdir(
backend_dir: Path,
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """预演文本显示命令和工作目录。"""
completed = run_text_cli_command(
'db',
'upgrade',
@@ -186,6 +194,7 @@ def test_dev_lint_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """代码检查按约定输出 JSON。"""
completed = run_cli_command(
'dev',
'lint',
@@ -208,6 +217,7 @@ def test_dev_lint_json_output_has_stable_contract(
assert isinstance(payload['check'], dict)
assert payload['format']['ok'] is True
assert payload['check']['ok'] is True
+ assert payload['docstrings']['ok'] is True
assert isinstance(payload['format']['command'], list)
assert isinstance(payload['check']['command'], list)
@@ -215,6 +225,7 @@ def test_dev_lint_json_output_has_stable_contract(
def test_dev_test_text_output_has_stable_summary(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """测试命令输出约定格式的摘要。"""
completed = run_text_cli_command(
'dev',
'test',
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_contract_job_gen.py b/ruoyi-fastapi-backend/tests/cli/root/test_contract_job_gen.py
index 0426aafa8..7d82c1253 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_contract_job_gen.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_contract_job_gen.py
@@ -16,6 +16,7 @@ def test_job_detail_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """任务详情按约定输出 JSON。"""
list_completed = run_cli_command('job', 'list', '--env=dev', '--output=json')
list_payload = parse_json_stdout(list_completed)
job_id = MISSING_JOB_ID
@@ -50,6 +51,7 @@ def test_job_logs_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """任务日志按约定输出 JSON。"""
completed = run_cli_command('job', 'logs', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -76,6 +78,7 @@ def test_gen_list_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """生成表列表按约定输出 JSON。"""
completed = run_cli_command('gen', 'list', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -102,6 +105,7 @@ def test_gen_db_list_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """数据库表列表按约定输出 JSON。"""
completed = run_cli_command('gen', 'db-list', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -127,6 +131,7 @@ def test_gen_detail_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """生成表详情按约定输出 JSON。"""
list_completed = run_cli_command('gen', 'list', '--env=dev', '--output=json')
list_payload = parse_json_stdout(list_completed)
table_id = MISSING_GEN_TABLE_ID
@@ -166,6 +171,7 @@ def test_gen_sync_db_is_rejected_without_yes_in_non_interactive_mode(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """非交互同步数据库表前必须显式确认。"""
completed = run_cli_command('gen', 'sync-db', 'demo_table', '--env=dev', '--output=json')
payload = parse_json_stdout(completed)
@@ -178,6 +184,7 @@ def test_gen_sync_db_is_rejected_without_yes_in_non_interactive_mode(
def test_gen_export_dry_run_text_output_has_stable_structure(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """导出预演按约定组织文本。"""
completed = run_text_cli_command(
'gen',
'export',
@@ -204,6 +211,7 @@ def test_gen_export_dry_run_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """导出预演按约定输出 JSON。"""
completed = run_cli_command(
'gen',
'export',
@@ -229,6 +237,7 @@ def test_gen_export_dry_run_json_output_has_stable_contract(
def test_gen_create_table_dry_run_text_output_has_stable_structure(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """建表预演按约定组织文本。"""
completed = run_text_cli_command(
'gen',
'create-table',
@@ -255,6 +264,7 @@ def test_gen_create_table_dry_run_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """建表预演按约定输出 JSON。"""
completed = run_cli_command(
'gen',
'create-table',
@@ -280,6 +290,7 @@ def test_gen_create_table_dry_run_json_output_has_stable_contract(
def test_gen_create_table_rejects_non_create_sql_in_text_output(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """文本模式拒绝非建表 SQL。"""
completed = run_text_cli_command(
'gen',
'create-table',
@@ -301,6 +312,7 @@ def test_gen_create_table_rejects_non_create_sql_in_json_output(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """JSON 模式拒绝非建表 SQL。"""
completed = run_cli_command(
'gen',
'create-table',
@@ -325,6 +337,7 @@ def test_gen_create_table_rejects_non_create_sql_in_json_output(
def test_gen_create_table_rejects_conflicting_sql_inputs_in_text_output(
run_text_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
+ """文本模式拒绝冲突的 SQL 输入。"""
completed = run_text_cli_command(
'gen',
'create-table',
@@ -348,6 +361,7 @@ def test_gen_create_table_rejects_conflicting_sql_inputs_in_json_output(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
) -> None:
+ """JSON 模式拒绝冲突的 SQL 输入。"""
completed = run_cli_command(
'gen',
'create-table',
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_effective_environment.py b/ruoyi-fastapi-backend/tests/cli/root/test_effective_environment.py
index fa6f640bd..dd8884087 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_effective_environment.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_effective_environment.py
@@ -34,6 +34,7 @@ def test_guard_uses_loaded_environment_without_resource_access(
expected_app: str,
rejected: bool,
) -> None:
+ """守卫从已加载环境判断而无需访问资源。"""
(tmp_path / f'.env.{expected_selector}').write_text(f'APP_ENV={file_env}\n', encoding='utf-8')
script = """
import json
@@ -82,11 +83,17 @@ def test_guard_uses_loaded_environment_without_resource_access(
def test_env_option_uses_external_default_and_preserves_explicit_choice(monkeypatch: pytest.MonkeyPatch) -> None:
+ """环境选项采用外部默认值并保留显式选择。"""
app = typer.Typer()
selected = []
@app.command()
def run(env: EnvOption = 'dev') -> None:
+ """
+ 记录测试命令的运行参数。
+
+ :param env: 当前运行环境
+ """
selected.append(env)
monkeypatch.setenv('APP_ENV', 'prod')
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_guards.py b/ruoyi-fastapi-backend/tests/cli/root/test_guards.py
index fa42e2f6b..d4a326c85 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_guards.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_guards.py
@@ -15,11 +15,7 @@
def test_dangerous_command_rules_cover_expected_commands() -> None:
- """
- 校验危险命令规则表已覆盖当前设计文档中约定的命令范围。
-
- :return: None
- """
+ """校验危险命令规则表已覆盖当前设计文档中约定的命令范围。"""
assert set(DEFAULT_DANGEROUS_COMMAND_RULES) == {
'cache clear',
'cache warmup',
@@ -65,11 +61,7 @@ def test_dangerous_command_rules_cover_expected_commands() -> None:
def test_dangerous_command_rules_expose_risk_level_and_dry_run_metadata() -> None:
- """
- 校验危险命令规则能够提供风险级别和 dry-run 能力元数据。
-
- :return: None
- """
+ """校验危险命令规则能够提供风险级别和 dry-run 能力元数据。"""
db_upgrade_rule = DEFAULT_DANGEROUS_COMMAND_RULE_REGISTRY.get_rule('db upgrade')
cache_warmup_rule = DEFAULT_DANGEROUS_COMMAND_RULE_REGISTRY.get_rule('cache warmup')
@@ -83,10 +75,6 @@ def test_dangerous_command_rules_expose_risk_level_and_dry_run_metadata() -> Non
def test_require_dangerous_command_rule_rejects_unknown_command() -> None:
- """
- 校验未注册的危险命令名称会被显式拒绝。
-
- :return: None
- """
+ """校验未注册的危险命令名称会被显式拒绝。"""
with pytest.raises(ValueError, match='危险命令未注册保护规则'):
DEFAULT_DANGEROUS_COMMAND_RULE_REGISTRY.require_rule('unknown dangerous command')
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_json_output_suppression.py b/ruoyi-fastapi-backend/tests/cli/root/test_json_output_suppression.py
index 2e9fcbe9f..88079ca75 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_json_output_suppression.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_json_output_suppression.py
@@ -5,12 +5,7 @@
def test_config_doctor_json_stdout_is_not_polluted_by_sqlalchemy_logs(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
) -> None:
- """
- 校验 JSON 输出模式下不会混入 SQLAlchemy engine 日志。
-
- :param run_cli_command: CLI 子进程执行器
- :return: None
- """
+ """校验 JSON 输出模式下不会混入 SQLAlchemy engine 日志。"""
completed = run_cli_command('config', 'doctor', '--env=dev', '--output=json')
assert 'sqlalchemy.engine.Engine' not in completed.stdout
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_main.py b/ruoyi-fastapi-backend/tests/cli/root/test_main.py
index f68f8e7a8..0428ca88d 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_main.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_main.py
@@ -2,11 +2,7 @@
def test_cli_main_runner_reuses_single_project_runtime_locator() -> None:
- """
- 校验 CLI 根运行器与导入期参数作用域共享同一个项目定位器实例。
-
- :return: None
- """
+ """校验 CLI 根运行器与导入期参数作用域共享同一个项目定位器实例。"""
cli_main = importlib.import_module('cli.main')
assert cli_main.CLI_MAIN_RUNNER.project_runtime_locator is cli_main.PROJECT_RUNTIME_LOCATOR
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_output.py b/ruoyi-fastapi-backend/tests/cli/root/test_output.py
index c4e0ce15a..8c8cc9ead 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_output.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_output.py
@@ -19,10 +19,16 @@ class _FakeStream:
"""
模拟终端输出流。
+ :ivar _is_tty: 模拟输出流是否连接到终端
:param is_tty: 是否模拟为 TTY
"""
def __init__(self, *, is_tty: bool) -> None:
+ """
+ 初始化测试夹具的 ``_is_tty``。
+
+ :param is_tty: 是否模拟为 TTY
+ """
self._is_tty = is_tty
def isatty(self) -> bool:
@@ -45,11 +51,7 @@ def _strip_ansi(text: str) -> str:
def test_decorate_text_output_promotes_success_header_with_emoji_icon() -> None:
- """
- 校验成功结果头在 emoji 模式下会被提升为统一状态头。
-
- :return: None
- """
+ """校验成功结果头在 emoji 模式下会被提升为统一状态头。"""
OUTPUT_RENDERER.set_icon_mode('emoji')
rendered = OUTPUT_RENDERER.decorate_text_output('ok: true\nenv: dev')
@@ -58,11 +60,7 @@ def test_decorate_text_output_promotes_success_header_with_emoji_icon() -> None:
def test_decorate_text_output_promotes_failure_header_with_emoji_icon() -> None:
- """
- 校验失败结果头在 emoji 模式下会被提升为统一状态头。
-
- :return: None
- """
+ """校验失败结果头在 emoji 模式下会被提升为统一状态头。"""
OUTPUT_RENDERER.set_icon_mode('emoji')
rendered = OUTPUT_RENDERER.decorate_text_output('ok: false\nerror: boom')
@@ -71,11 +69,7 @@ def test_decorate_text_output_promotes_failure_header_with_emoji_icon() -> None:
def test_colorize_text_output_renders_inline_status_segments_with_emoji_icon() -> None:
- """
- 校验文本着色后会为 message、hint、error 等字段附加状态标签。
-
- :return: None
- """
+ """校验文本着色后会为 message、hint、error 等字段附加状态标签。"""
OUTPUT_RENDERER.set_icon_mode('emoji')
OUTPUT_RENDERER.set_color_mode('always')
decorated = OUTPUT_RENDERER.decorate_text_output('ok: false\nmessage: retry later\nhint: use --yes\nerror: boom')
@@ -89,11 +83,7 @@ def test_colorize_text_output_renders_inline_status_segments_with_emoji_icon() -
def test_colorize_text_output_supports_warning_and_info_field_aliases() -> None:
- """
- 校验 `warning` 与 `info` 字段也会使用统一状态图标渲染。
-
- :return: None
- """
+ """校验 ``warning`` 与 ``info`` 字段也会使用统一状态图标渲染。"""
OUTPUT_RENDERER.set_icon_mode('emoji')
OUTPUT_RENDERER.set_color_mode('always')
decorated = OUTPUT_RENDERER.decorate_text_output('ok: true\nwarning: rotate key soon\ninfo: cache refreshed')
@@ -104,11 +94,7 @@ def test_colorize_text_output_supports_warning_and_info_field_aliases() -> None:
def test_colorize_text_output_styles_status_segments_inside_list_items() -> None:
- """
- 校验列表项中的带标签状态片段也会应用统一视觉规则。
-
- :return: None
- """
+ """校验列表项中的带标签状态片段也会应用统一视觉规则。"""
OUTPUT_RENDERER.set_icon_mode('emoji')
OUTPUT_RENDERER.set_color_mode('always')
rendered = OUTPUT_RENDERER.colorize_text_output(
@@ -122,11 +108,7 @@ def test_colorize_text_output_styles_status_segments_inside_list_items() -> None
def test_colorize_text_output_supports_ascii_icon_mode() -> None:
- """
- 校验 ascii 图标模式会渲染为纯 ASCII 状态标签。
-
- :return: None
- """
+ """校验 ascii 图标模式会渲染为纯 ASCII 状态标签。"""
OUTPUT_RENDERER.set_icon_mode('ascii')
OUTPUT_RENDERER.set_color_mode('always')
decorated = OUTPUT_RENDERER.decorate_text_output('ok: true\nhint: use --yes')
@@ -137,11 +119,7 @@ def test_colorize_text_output_supports_ascii_icon_mode() -> None:
def test_colorize_text_output_skips_ansi_when_color_mode_is_never() -> None:
- """
- 校验关闭颜色后不会输出 ANSI 转义序列。
-
- :return: None
- """
+ """校验关闭颜色后不会输出 ANSI 转义序列。"""
OUTPUT_RENDERER.set_icon_mode('emoji')
OUTPUT_RENDERER.set_color_mode('never')
decorated = OUTPUT_RENDERER.decorate_text_output('ok: false\nhint: use --yes')
@@ -153,11 +131,7 @@ def test_colorize_text_output_skips_ansi_when_color_mode_is_never() -> None:
def test_render_error_text_uses_status_token_in_emoji_mode() -> None:
- """
- 校验标准错误输出在 emoji 模式下使用统一错误图标。
-
- :return: None
- """
+ """校验标准错误输出在 emoji 模式下使用统一错误图标。"""
OUTPUT_RENDERER.set_icon_mode('emoji')
OUTPUT_RENDERER.set_color_mode('never')
@@ -167,11 +141,7 @@ def test_render_error_text_uses_status_token_in_emoji_mode() -> None:
def test_render_error_text_supports_ascii_mode_with_color() -> None:
- """
- 校验标准错误输出在 ascii 模式下仍保持统一错误前缀与颜色。
-
- :return: None
- """
+ """校验标准错误输出在 ascii 模式下仍保持统一错误前缀与颜色。"""
OUTPUT_RENDERER.set_icon_mode('ascii')
OUTPUT_RENDERER.set_color_mode('always')
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_artifact_commands.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_artifact_commands.py
index 6218399a1..0cfe6ea83 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_artifact_commands.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_artifact_commands.py
@@ -31,6 +31,8 @@
def preserve_environment(monkeypatch: pytest.MonkeyPatch) -> None:
"""
隔离测试对当前应用环境的修改。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
"""
monkeypatch.setenv('APP_ENV', os.environ.get('APP_ENV', 'dev'))
@@ -38,13 +40,29 @@ def preserve_environment(monkeypatch: pytest.MonkeyPatch) -> None:
class CapturingController:
"""
记录命令转发参数的控制器替身。
+
+ :ivar calls: 测试替身记录的调用信息
"""
def __init__(self) -> None:
+ """初始化测试夹具的 ``calls``。"""
self.calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = []
def __getattr__(self, name: str) -> Any:
+ """
+ 处理测试替身上的动态属性访问。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 供调用方使用的 ``capture``
+ """
+
def capture(*args: Any, **kwargs: Any) -> None:
+ """
+ 保存调用参数供断言使用。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
self.calls.append((name, args, kwargs))
return capture
@@ -53,6 +71,9 @@ def capture(*args: Any, **kwargs: Any) -> None:
def app_for(controller: Any) -> typer.Typer:
"""
构建仅包含被测插件命令的 Typer 应用。
+
+ :param controller: 接受请求的控制器
+ :return: 仅包含被测插件命令的 Typer 应用
"""
app = typer.Typer()
register_artifact_commands(app, lambda: controller)
@@ -193,9 +214,7 @@ def app_for(controller: Any) -> typer.Typer:
def test_cli_dispatches_artifact_and_release_parameters(
arguments: list[str], method: str, options: dict[str, Any]
) -> None:
- """
- 验证制品与发布命令将参数完整转交控制器。
- """
+ """验证制品与发布命令将参数完整转交控制器。"""
controller = CapturingController()
result = CliRunner().invoke(app_for(controller), [*arguments, '--env', 'test', '--output', 'json'])
assert result.exit_code == 0, result.output
@@ -218,9 +237,7 @@ def test_cli_dispatches_artifact_and_release_parameters(
],
)
def test_cli_rejects_missing_concurrency_token_and_unsupported_flags(arguments: list[str]) -> None:
- """
- 验证缺失发布代际和不支持的选项会被拒绝。
- """
+ """验证缺失发布代际和不支持的选项会被拒绝。"""
controller = CapturingController()
result = CliRunner().invoke(app_for(controller), arguments)
assert result.exit_code == ARGUMENT_ERROR
@@ -238,9 +255,7 @@ def test_cli_rejects_missing_concurrency_token_and_unsupported_flags(arguments:
],
)
def test_help_keeps_config_crypto_database_and_plugin_code_unloaded(help_arguments: list[str]) -> None:
- """
- 验证帮助查询不加载配置、加密、数据库或插件代码。
- """
+ """验证帮助查询不加载配置、加密、数据库或插件代码。"""
observed = (
'config.env',
'config.database',
@@ -268,18 +283,46 @@ def test_help_keeps_config_crypto_database_and_plugin_code_unloaded(help_argumen
class RecordingContextFactory:
"""
记录上下文创建顺序的工厂替身。
+
+ :ivar events: 保存已发出事件的序列
"""
def __init__(self, events: list[str]) -> None:
+ """
+ 初始化测试夹具的 ``events``。
+
+ :param events: 保存已发出事件的序列
+ """
self.events = events
def build_regular(self, env: str, output: str, allow_prod: bool, yes: bool, dry_run: bool) -> CliContext:
+ """
+ 保存上下文创建顺序和 CLI 选项。
+
+ :param env: 当前运行环境
+ :param output: 命令或操作的输出
+ :param allow_prod: 是否允许生产环境危险命令
+ :param yes: 是否跳过交互确认
+ :param dry_run: 是否只预览操作结果
+ :return: ``CliContext`` 实例
+ """
self.events.append('context')
return CliContext(env=env, output=output, allow_prod=allow_prod, yes=yes, dry_run=dry_run)
def build_dangerous(
self, env: str, output: str, allow_prod: bool, yes: bool, dry_run: bool, *, command_name: str
) -> CliContext:
+ """
+ 捕获危险命令名称并构建测试上下文。
+
+ :param env: 当前运行环境
+ :param output: 命令或操作的输出
+ :param allow_prod: 是否允许生产环境危险命令
+ :param yes: 是否跳过交互确认
+ :param dry_run: 是否只预览操作结果
+ :param command_name: 命令唯一标识
+ :return: 带危险操作名称的测试上下文
+ """
self.events.append(command_name)
return self.build_regular(env, output, allow_prod, yes, dry_run)
@@ -287,22 +330,39 @@ def build_dangerous(
class RecordingExecution:
"""
记录命令结果的执行服务替身。
+
+ :ivar payload: 随调用传入或返回的结构化数据
"""
def __init__(self) -> None:
+ """初始化测试夹具的 ``payload``。"""
self.payload: dict[str, Any] = {}
@staticmethod
def run_async(coroutine: Any) -> Any:
+ """
+ 在事件循环中执行传入的协程。
+
+ :param coroutine: 需要调度的协程
+ :return: 协程执行完毕后的返回值
+ """
return asyncio.run(coroutine)
def complete_payload(self, ctx: CliContext, payload: dict[str, Any]) -> None:
+ """
+ 保存 CLI 命令最终输出的结果。
+
+ :param ctx: CLI 运行上下文
+ :param payload: 随调用传入或返回的结构化数据
+ """
self.payload = payload
def quiet_context_factory() -> CliContextFactory:
"""
创建不初始化日志输出的测试上下文工厂。
+
+ :return: 不初始化日志输出的测试上下文工厂
"""
return CliContextFactory(
runtime_state=SimpleNamespace(suppress_logs=lambda: None, suppress_sqlalchemy_logs=lambda: None)
@@ -310,15 +370,13 @@ def quiet_context_factory() -> CliContextFactory:
def test_production_mutations_are_guarded_before_loading_runtime(monkeypatch: pytest.MonkeyPatch) -> None:
- """
- 验证生产写入保护先于运行时加载执行。
- """
-
+ """验证生产写入保护先于运行时加载执行。"""
env_module = importlib.import_module('config.env')
monkeypatch.setattr(env_module.get_config, 'run_env', 'prod')
monkeypatch.setattr(env_module.AppConfig, 'app_env', 'prod')
def forbidden_config() -> None:
+ """若执行到此操作则立即使测试失败。"""
pytest.fail('rejected CLI must not construct runtime')
controller = PluginArtifactCommandController(
@@ -344,21 +402,34 @@ def forbidden_config() -> None:
def test_dry_run_is_readonly_and_environment_precedes_runtime(monkeypatch: pytest.MonkeyPatch) -> None:
- """
- 验证预演保持只读,且不会用配置选择名覆盖外部应用环境。
- """
+ """验证预演保持只读,且不会用配置选择名覆盖外部应用环境。"""
monkeypatch.setenv('APP_ENV', 'dev')
events: list[str] = []
execution = RecordingExecution()
def config() -> object:
+ """
+ 记录配置加载期间使用的环境和调用顺序。
+
+ :return: 代表已加载配置的测试对象
+ """
assert events == ['context']
assert os.environ['APP_ENV'] == 'dev'
events.append('config')
return object()
class Catalog:
+ """提供插件制品目录的测试替身。"""
+
async def import_artifact(self, path: Path, *, actor: str, dry_run: bool) -> dict[str, Any]:
+ """
+ 校验制品导入参数并返回预演结果。
+
+ :param path: 要读取或处理的路径
+ :param actor: 发起操作的主体
+ :param dry_run: 是否只预览操作结果
+ :return: 预演结果
+ """
assert actor
assert dry_run
return {'ok': True, 'dryRun': dry_run}
@@ -375,16 +446,30 @@ async def import_artifact(self, path: Path, *, actor: str, dry_run: bool) -> dic
def test_controller_forwards_maintenance_cas_and_schema_compatibility() -> None:
- """
- 验证维护、并发校验与数据兼容选项完整传递。
- """
+ """验证维护、并发校验与数据兼容选项完整传递。"""
events: list[str] = []
execution = RecordingExecution()
calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = []
class Service:
+ """捕获发往插件服务的动态方法调用。"""
+
def __getattr__(self, name: str) -> Any:
+ """
+ 处理测试替身上的动态属性访问。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 需要执行或验证的调用
+ """
+
async def call(*args: Any, **kwargs: Any) -> dict[str, Any]:
+ """
+ 记录动态方法名及参数,并返回成功结果。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 成功结果
+ """
calls.append((name, args, kwargs))
return {'ok': True}
@@ -431,9 +516,7 @@ async def call(*args: Any, **kwargs: Any) -> dict[str, Any]:
def test_offline_build_encrypted_key_never_imports_plugin_or_requires_feature_config(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
- """
- 验证离线构建使用加密私钥且不导入插件或部署配置。
- """
+ """验证离线构建使用加密私钥且不导入插件或部署配置。"""
source = tmp_path / 'artifact_demo'
source.mkdir()
(source / 'plugin.yaml').write_text(
@@ -455,6 +538,7 @@ def test_offline_build_encrypted_key_never_imports_plugin_or_requires_feature_co
execution = RecordingExecution()
def forbidden_config() -> None:
+ """若执行到此操作则立即使测试失败。"""
pytest.fail('offline build must not require feature config')
controller = PluginArtifactCommandController(
@@ -488,14 +572,21 @@ def forbidden_config() -> None:
@pytest.mark.parametrize('enabled', [True, False])
def test_controller_enablement_forwards_maintenance_and_cas(enabled: bool) -> None:
- """
- 验证制品启停传递维护确认与发布代际。
- """
+ """验证制品启停传递维护确认与发布代际。"""
recorded: dict[str, Any] = {}
class Enablement:
+ """模拟插件启用状态的更新。"""
+
@staticmethod
async def set_enabled(plugin_id: str, **kwargs: Any) -> dict[str, Any]:
+ """
+ 捕获插件启用状态的变更请求。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 包含 ``ok``、``restartRequired`` 的数据
+ """
recorded.update(pluginId=plugin_id, **kwargs)
return {'ok': True, 'restartRequired': True}
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_command_controller.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_command_controller.py
index 1a8ad8fc9..a34b8869d 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_command_controller.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_command_controller.py
@@ -13,9 +13,7 @@
class FakeContextFactory:
- """
- 测试用 CLI 上下文工厂。
- """
+ """测试用 CLI 上下文工厂。"""
def build_dangerous(
self,
@@ -27,7 +25,17 @@ def build_dangerous(
*,
command_name: str,
) -> Any:
- """构造危险命令上下文。"""
+ """
+ 构造危险命令上下文。
+
+ :param env: 当前运行环境
+ :param output: 命令或操作的输出
+ :param allow_prod: 是否允许生产环境危险命令
+ :param yes: 是否跳过交互确认
+ :param dry_run: 是否只预览操作结果
+ :param command_name: 命令唯一标识
+ :return: 危险命令上下文
+ """
return type('FakeContext', (), {'env': env, 'output': output})()
def build_regular(
@@ -38,7 +46,16 @@ def build_regular(
yes: bool,
dry_run: bool,
) -> Any:
- """构造普通命令上下文。"""
+ """
+ 构造普通命令上下文。
+
+ :param env: 当前运行环境
+ :param output: 命令或操作的输出
+ :param allow_prod: 是否允许生产环境危险命令
+ :param yes: 是否跳过交互确认
+ :param dry_run: 是否只预览操作结果
+ :return: 普通命令上下文
+ """
return type(
'FakeContext',
(),
@@ -46,13 +63,22 @@ def build_regular(
)()
def build_readonly(self, env: str, output: str) -> Any:
- """构造只读命令上下文。"""
+ """
+ 构造只读命令上下文。
+
+ :param env: 当前运行环境
+ :param output: 命令或操作的输出
+ :return: 只读命令上下文
+ """
return type('FakeContext', (), {'env': env, 'output': output})()
class FakeExecutionService:
"""
测试用 CLI 执行服务。
+
+ :ivar completed_payload: 命令成功结束时返回的结果
+ :ivar default_exit_code: 默认退出码
"""
def __init__(self) -> None:
@@ -61,7 +87,12 @@ def __init__(self) -> None:
self.default_exit_code: int | None = None
def run_async(self, value: Any) -> Any:
- """直接返回测试中的 awaitable 结果。"""
+ """
+ 直接返回测试中的 awaitable 结果。
+
+ :param value: 待处理的输入值
+ :return: 可等待对象执行完毕后的值
+ """
if inspect.isawaitable(value):
return asyncio.run(value)
return value
@@ -74,65 +105,119 @@ def complete_payload_with_text(
text_builder: Any,
default_exit_code: int,
) -> None:
- """记录完成参数。"""
+ """
+ 记录完成参数。
+
+ :param ctx: 当前命令的执行上下文
+ :param payload: 随调用传入或返回的结构化数据
+ :param text_builder: 文本结果构建函数
+ :param default_exit_code: 默认退出码
+ """
self.completed_payload = payload
self.default_exit_code = default_exit_code
class FakePresenter:
- """
- 测试用 presenter。
- """
+ """测试用 presenter。"""
@staticmethod
def build_list_text(payload: dict[str, Any]) -> str:
- """构造列表文本。"""
+ """
+ 构造列表文本。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 列表文本
+ """
return str(payload)
@staticmethod
def build_info_text(payload: dict[str, Any]) -> str:
- """构造详情文本。"""
+ """
+ 构造详情文本。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 详情文本
+ """
return str(payload)
@staticmethod
def build_enabled_text(payload: dict[str, Any]) -> str:
- """构造启停文本。"""
+ """
+ 构造启停文本。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 启停文本
+ """
return str(payload)
@staticmethod
def build_install_text(payload: dict[str, Any]) -> str:
- """构造安装文本。"""
+ """
+ 构造安装文本。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 安装文本
+ """
return str(payload)
@staticmethod
def build_check_text(payload: dict[str, Any]) -> str:
- """构造检查文本。"""
+ """
+ 构造检查文本。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 检查文本
+ """
return str(payload)
@staticmethod
def build_config_text(payload: dict[str, Any]) -> str:
- """构造配置文本。"""
+ """
+ 构造配置文本。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 配置文本
+ """
return str(payload)
@staticmethod
def build_dependency_install_text(payload: dict[str, Any]) -> str:
- """构造依赖安装文本。"""
+ """
+ 构造依赖安装文本。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 依赖安装文本
+ """
return str(payload)
@staticmethod
def build_dependency_lock_text(payload: dict[str, Any]) -> str:
- """构造依赖锁文件文本。"""
+ """
+ 构造依赖锁文件文本。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 依赖锁文件文本
+ """
return str(payload)
@staticmethod
def build_dependency_allowlist_example_text(payload: dict[str, Any]) -> str:
- """构造允许列表示例文本。"""
+ """
+ 构造允许列表示例文本。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 允许列表示例文本
+ """
return str(payload)
class FakeCoreRuntime:
"""
测试用核心插件运行时。
+
+ :ivar dependency_install_calls: 记录 ``dependency_install`` 的调用情况
+ :ivar config_set_calls: 记录 ``config_set`` 的调用情况
+ :ivar list_with_state_called: 记录 ``list_with_state`` 的调用情况
"""
def __init__(self) -> None:
@@ -142,7 +227,11 @@ def __init__(self) -> None:
self.list_with_state_called = False
async def list_plugins_with_state(self) -> dict[str, Any]:
- """返回合并状态后的插件列表。"""
+ """
+ 返回合并状态后的插件列表。
+
+ :return: 合并状态后的插件列表
+ """
self.list_with_state_called = True
return {
'ok': True,
@@ -159,16 +248,33 @@ async def list_plugins_with_state(self) -> dict[str, Any]:
}
async def install_plugin(self, plugin_id: str, *, dry_run: bool = False) -> dict[str, Any]:
- """返回失败安装结果。"""
+ """
+ 返回失败安装结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param dry_run: 是否只预览操作结果
+ :return: 失败安装结果
+ """
return {'ok': False, 'message': '插件安装失败', 'pluginId': plugin_id}
@staticmethod
def check_plugin(plugin_id: str | None = None) -> dict[str, Any]:
- """返回缺失 ok 字段的检查结果。"""
+ """
+ 返回缺失 ok 字段的检查结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 缺失 ok 字段的检查结果
+ """
return {'message': '插件检查结果缺失 ok', 'pluginId': plugin_id}
async def set_plugin_config(self, plugin_id: str, values: dict[str, Any]) -> dict[str, Any]:
- """返回失败配置更新结果。"""
+ """
+ 返回失败配置更新结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param values: 当前处理的值集合
+ :return: 失败配置更新结果
+ """
self.config_set_calls.append({'plugin_id': plugin_id, 'values': values})
return {'ok': False, 'message': '插件配置更新失败', 'pluginId': plugin_id, 'values': values}
@@ -181,7 +287,16 @@ def install_plugin_dependencies_from_cli(
confirmed: bool = False,
output_callback: object | None = None,
) -> dict[str, Any]:
- """返回 CLI 依赖安装测试结果。"""
+ """
+ 返回 CLI 依赖安装测试结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param dry_run: 是否只预览操作结果
+ :param policy_config: 依赖安装策略配置
+ :param confirmed: 是否已确认该操作
+ :param output_callback: 依赖安装实时输出回调
+ :return: CLI 依赖安装测试结果
+ """
self.dependency_install_calls.append(
{
'plugin_id': plugin_id,
@@ -204,6 +319,10 @@ def install_plugin_dependencies_from_cli(
class FakePluginRuntime:
"""
测试用插件 CLI 运行时。
+
+ :ivar core_runtime: 被测命令使用的核心运行时
+ :ivar dependency_lock_calls: 记录 ``dependency_lock`` 的调用情况
+ :ivar dependency_allowlist_example_calls: 记录 ``dependency_allowlist_example`` 的调用情况
"""
def __init__(self) -> None:
@@ -221,7 +340,16 @@ def lock_plugin_dependencies(
dry_run: bool = False,
overwrite: bool = False,
) -> dict[str, Any]:
- """返回依赖锁文件测试结果。"""
+ """
+ 返回依赖锁文件测试结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param output_path: 写入命令结果的目标路径
+ :param offline_dir: 保存离线依赖包的目录
+ :param dry_run: 是否只预览操作结果
+ :param overwrite: 是否允许替换已有文件
+ :return: 依赖锁文件测试结果
+ """
self.dependency_lock_calls.append(
{
'plugin_id': plugin_id,
@@ -248,7 +376,14 @@ def generate_plugin_dependency_allowlist_example(
dry_run: bool = False,
overwrite: bool = False,
) -> dict[str, Any]:
- """返回允许列表示例测试结果。"""
+ """
+ 返回允许列表示例测试结果。
+
+ :param output_path: 写入命令结果的目标路径
+ :param dry_run: 是否只预览操作结果
+ :param overwrite: 是否允许替换已有文件
+ :return: 允许列表示例测试结果
+ """
self.dependency_allowlist_example_calls.append(
{
'output_path': output_path,
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_create_templates.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_create_templates.py
index 07af5a9a6..bc30e8575 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_create_templates.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_create_templates.py
@@ -13,14 +13,19 @@
@pytest.mark.parametrize('template', ['python-asgi', 'python-bundle', 'rust-asgi', 'rust-bundle'])
def test_create_cli_forwards_v2_template_without_changing_default_options(template: str) -> None:
- """
- 验证 v2 模板参数传递且不改变既有默认选项。
- """
+ """验证 v2 模板参数传递且不改变既有默认选项。"""
recorded: list[tuple[Any, ...]] = []
class Controller:
+ """捕获插件命令委托给控制器的参数。"""
+
@staticmethod
def create_plugin(*args: Any) -> None:
+ """
+ 捕获插件创建请求及其参数。
+
+ :param args: 传给被调用对象的位置参数
+ """
recorded.append(args)
app = typer.Typer()
@@ -35,14 +40,22 @@ def create_plugin(*args: Any) -> None:
def test_create_cli_defaults_to_existing_v1_full_stack_template() -> None:
- """
- 验证未指定模板时继续生成原有 v1 完整模板。
- """
+ """验证未指定模板时继续生成原有 v1 完整模板。"""
recorded: list[PluginCreateCommandOptions] = []
class Controller:
+ """捕获插件命令委托给控制器的参数。"""
+
@staticmethod
def create_plugin(plugin_id: str, env: str, output: str, options: PluginCreateCommandOptions) -> None:
+ """
+ 捕获插件创建请求及其参数。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param env: 当前运行环境
+ :param output: 命令或操作的输出
+ :param options: 插件创建命令选项
+ """
recorded.append(options)
app = typer.Typer()
@@ -58,8 +71,18 @@ def test_create_cli_accepts_fixed_frontend_framework_choices(framework: str) ->
recorded: list[PluginCreateCommandOptions] = []
class Controller:
+ """捕获插件命令委托给控制器的参数。"""
+
@staticmethod
def create_plugin(plugin_id: str, env: str, output: str, options: PluginCreateCommandOptions) -> None:
+ """
+ 捕获插件创建请求及其参数。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param env: 当前运行环境
+ :param output: 命令或操作的输出
+ :param options: 插件创建命令选项
+ """
recorded.append(options)
app = typer.Typer()
@@ -74,7 +97,11 @@ def test_create_cli_rejects_framework_before_resolving_controller(framework: str
"""校验非法框架选项在加载控制器或运行时之前被拒绝。"""
def unavailable_controller() -> None:
- """禁止参数错误路径加载控制器。"""
+ """
+ 禁止参数错误路径加载控制器。
+
+ :raises AssertionError: 不应加载控制器
+ """
raise AssertionError('不应加载控制器')
app = typer.Typer()
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_diagnostics.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_diagnostics.py
index d031a2e16..2730a38fc 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_diagnostics.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_diagnostics.py
@@ -11,6 +11,7 @@
@pytest.mark.asyncio
async def test_cli_diagnose_appends_runtime_without_changing_static_result(monkeypatch: pytest.MonkeyPatch) -> None:
+ """命令行诊断在静态结果后追加运行时信息。"""
read = AsyncMock(return_value={'state': 'unavailable', 'observedTotals': None})
monkeypatch.setattr('plugins.core.runtime.diagnostics_query.read_cli_runtime_diagnostics', read)
runtime = CliPluginRuntimeService(runtime_environment=SimpleNamespace(get_backend_dir=lambda: '/backend'))
@@ -22,6 +23,7 @@ async def test_cli_diagnose_appends_runtime_without_changing_static_result(monke
def test_runtime_shared_contract_and_unknown_text_are_preserved() -> None:
+ """保留共享运行时响应约定和未知文本。"""
payload = {
'ok': True,
'runtime': {
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_frontend_environment.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_frontend_environment.py
index f3ce6adfa..8a5ad5b16 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_frontend_environment.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_frontend_environment.py
@@ -21,11 +21,8 @@ def test_cold_cli_preserves_frontend_framework_across_scaffold_sdk_and_dependenc
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
framework: str,
) -> None:
- """
- 校验独立进程从框架环境变量启动后,模板、SDK 与依赖锁选择相同工程。
-
- 所有宿主文件位于临时目录;创建和锁定只预演,SDK 更新仅修改测试副本。
- """
+ """校验独立进程从框架环境变量启动后,模板、SDK 与依赖锁选择相同工程。"""
+ # 所有宿主文件位于临时目录,创建和锁定只预演,SDK 更新仅修改测试副本。
backend = tmp_path / 'backend'
frontend_container = tmp_path / 'ruoyi-fastapi-frontend'
for host_framework in ('vue2', 'vue3', 'react'):
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_lazy_import.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_lazy_import.py
index 43e0fb34f..d3b21d8c1 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_lazy_import.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_lazy_import.py
@@ -11,7 +11,13 @@
def inspect_cold_import(module_name: str, observed_modules: tuple[str, ...]) -> dict[str, bool]:
- """在隔离解释器中检查目标模块的冷导入边界。"""
+ """
+ 在隔离解释器中检查目标模块的冷导入边界。
+
+ :param module_name: 生成模块名
+ :param observed_modules: 记录在运行期间加载的模块
+ :return: 隔离解释器记录的已加载模块信息
+ """
script = (
'import importlib, json, sys; '
f'importlib.import_module({module_name!r}); '
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_release_wait.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_release_wait.py
index 5b9be51fa..c222d211f 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_release_wait.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_release_wait.py
@@ -25,7 +25,6 @@ def preserve_environment(monkeypatch: pytest.MonkeyPatch) -> None:
恢复命令运行前的环境选择,避免影响其他 CLI 测试。
:param monkeypatch: pytest 环境隔离工具
- :return: None
"""
monkeypatch.setenv('APP_ENV', os.environ.get('APP_ENV', 'dev'))
@@ -125,12 +124,7 @@ def wait_arguments(*overrides: str) -> list[str]:
],
)
def test_wait_outputs_exactly_one_final_json_and_preserves_service_exit_semantics(reason: str) -> None:
- """
- 成功、超时和各种失败都只输出一个最终对象,并使用统一退出码。
-
- :param reason: 服务的终止原因
- :return: None
- """
+ """成功、超时和各种失败都只输出一个最终对象,并使用统一退出码。"""
payload = result_payload(reason)
wait = AsyncMock(return_value=payload)
result = CliRunner().invoke(app_for(controller_for(SimpleNamespace(wait=wait))), wait_arguments())
@@ -167,12 +161,7 @@ def test_wait_outputs_exactly_one_final_json_and_preserves_service_exit_semantic
],
)
def test_wait_requires_all_pins_and_rejects_write_options_before_loading_service(arguments: list[str]) -> None:
- """
- 缺少固定目标、无效计数或写入选项均由参数层拒绝。
-
- :param arguments: 缺少必填项或包含不受支持选项的命令行
- :return: None
- """
+ """缺少固定目标、无效计数或写入选项均由参数层拒绝。"""
config = Mock(side_effect=AssertionError('参数错误时不能加载配置'))
result = CliRunner().invoke(app_for(controller_for(SimpleNamespace(), config_factory=config)), arguments)
assert result.exit_code == ARGUMENT_ERROR
@@ -206,13 +195,7 @@ def test_wait_requires_all_pins_and_rejects_write_options_before_loading_service
def test_wait_controller_validates_before_context_and_service_creation(
overrides: dict[str, Any], capsys: pytest.CaptureFixture[str]
) -> None:
- """
- 非法目标或非有限时间参数不能触发配置读取,也不会输出 NaN 或 Infinity。
-
- :param overrides: 替换正常调用的无效参数
- :param capsys: 标准输出捕获器
- :return: None
- """
+ """非法目标或非有限时间参数不能触发配置读取,也不会输出 NaN 或 Infinity。"""
config = Mock(side_effect=AssertionError('不能读取配置'))
controller = controller_for(SimpleNamespace(), config_factory=config)
controller._context = Mock(side_effect=AssertionError('不能创建运行上下文'))
@@ -243,13 +226,7 @@ def test_wait_controller_validates_before_context_and_service_creation(
@pytest.mark.parametrize('option', ['--timeout', '--interval'])
@pytest.mark.parametrize('value', ['nan', 'inf', '-inf'])
def test_wait_cli_rejects_non_finite_durations(option: str, value: str) -> None:
- """
- 命令行浮点解析不能让 NaN 或无穷大进入等待服务。
-
- :param option: 超时或查询间隔选项
- :param value: 非有限数值文本
- :return: None
- """
+ """命令行浮点解析不能让 NaN 或无穷大进入等待服务。"""
config = Mock(side_effect=AssertionError('不能读取配置'))
result = CliRunner().invoke(
app_for(controller_for(SimpleNamespace(), config_factory=config)), wait_arguments(option, value)
@@ -260,12 +237,7 @@ def test_wait_cli_rejects_non_finite_durations(option: str, value: str) -> None:
@pytest.mark.parametrize('exception', [asyncio.CancelledError, KeyboardInterrupt])
def test_wait_cli_cancellation_is_redacted_and_does_not_invent_progress(exception: type[BaseException]) -> None:
- """
- 取消和用户中断都返回固定结果,不泄露异常文本或伪造已查询次数。
-
- :param exception: 异步取消或键盘中断异常类型
- :return: None
- """
+ """取消和用户中断都返回固定结果,不泄露异常文本或伪造已查询次数。"""
wait = AsyncMock(side_effect=exception('private-cancellation-detail'))
result = CliRunner().invoke(app_for(controller_for(SimpleNamespace(wait=wait))), wait_arguments())
assert result.exit_code == RUNTIME_ERROR, result.output
@@ -280,11 +252,7 @@ def test_wait_cli_cancellation_is_redacted_and_does_not_invent_progress(exceptio
def test_wait_initialization_failure_is_redacted_and_uses_final_result_schema() -> None:
- """
- 部署配置初始化失败不能暴露连接凭据,仍返回同一最终结果结构。
-
- :return: None
- """
+ """部署配置初始化失败不能暴露连接凭据,仍返回同一最终结果结构。"""
config = Mock(side_effect=RuntimeError('private-database-password'))
result = CliRunner().invoke(app_for(controller_for(SimpleNamespace(), config_factory=config)), wait_arguments())
assert result.exit_code == RUNTIME_ERROR
@@ -297,11 +265,7 @@ def test_wait_initialization_failure_is_redacted_and_uses_final_result_schema()
def test_release_status_query_success_keeps_existing_ok_meaning() -> None:
- """
- 查询未就绪发布仍表示查询成功,不改变已有 status 命令的退出契约。
-
- :return: None
- """
+ """查询未就绪发布仍表示查询成功,不改变已有 status 命令的退出契约。"""
payload = {'ok': True, 'releases': [{'pluginId': 'demo', 'status': 'pending_restart'}], 'workers': []}
service = SimpleNamespace(status=AsyncMock(return_value=payload))
result = CliRunner().invoke(
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_sdk_commands.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_sdk_commands.py
index 1bbdda39c..9f42e78b5 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_sdk_commands.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_sdk_commands.py
@@ -55,12 +55,7 @@ def invoke_sdk(operation: str, project: Path, *options: str) -> tuple[int, dict]
def test_sdk_cli_requires_explicit_force_for_untracked_copy_and_dry_run_does_not_write(project: Path) -> None:
- """
- 验证旧工程纳管前可预演,默认拒绝写入且强制更新只修改 SDK。
-
- :param project: 未跟踪 SDK 的隔离工程
- :return: None
- """
+ """验证旧工程纳管前可预演,默认拒绝写入且强制更新只修改 SDK。"""
before = {path.relative_to(project): path.read_bytes() for path in project.rglob('*') if path.is_file()}
code, payload = invoke_sdk('check', project)
assert code == DEPENDENCY_ERROR and payload['status'] == 'untracked'
@@ -79,13 +74,7 @@ def test_sdk_cli_requires_explicit_force_for_untracked_copy_and_dry_run_does_not
def test_sdk_cli_bad_source_is_json_and_nonzero(project: Path, tmp_path: Path) -> None:
- """
- 验证来源 SDK 缺失时返回单份 JSON 和非零状态。
-
- :param project: 独立测试工程
- :param tmp_path: 不包含 SDK 的来源目录
- :return: None
- """
+ """验证来源 SDK 缺失时返回单份 JSON 和非零状态。"""
result = CliRunner().invoke(
sdk_app(), ['sdk', 'check', str(project), '--frontend-root', str(tmp_path), '--output', 'json']
)
@@ -177,23 +166,13 @@ def test_sdk_cli_rejects_removed_frontend_version_option(project: Path) -> None:
def test_sdk_cli_invalid_output_is_argument_error(project: Path) -> None:
- """
- 验证 SDK 子命令复用 CLI 输出格式约束。
-
- :param project: 独立测试工程
- :return: None
- """
+ """验证 SDK 子命令复用 CLI 输出格式约束。"""
result = CliRunner().invoke(sdk_app(), ['sdk', 'check', str(project), '--output', 'xml'])
assert result.exit_code == ARGUMENT_ERROR
def test_sdk_check_cold_process_does_not_load_host_configuration_or_project(project: Path) -> None:
- """
- 验证实际根命令能在无宿主配置条件下离线运行,不导入业务或数据库。
-
- :param project: 包含禁止执行代码的独立工程
- :return: None
- """
+ """验证实际根命令能在无宿主配置条件下离线运行,不导入业务或数据库。"""
script = """
import json, sys
from typer.testing import CliRunner
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_utils.py b/ruoyi-fastapi-backend/tests/cli/root/test_utils.py
index 0f39f0cfe..663a16ad3 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_utils.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_utils.py
@@ -13,14 +13,16 @@
def test_run_nested_cli_command_extracts_json_from_noisy_stdout(monkeypatch: MonkeyPatch) -> None:
- """
- 校验内部 CLI 调用可从带噪声的标准输出中提取 JSON 负载。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验内部 CLI 调用可从带噪声的标准输出中提取 JSON 负载。"""
def _fake_subprocess_run(*args: object, **kwargs: object) -> SimpleNamespace:
+ """
+ 捕获子进程调用并返回测试指定的执行结果。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 测试指定的执行结果
+ """
del args, kwargs
return SimpleNamespace(
stdout='debug line before json\n{"ok": true, "message": "success"}\ndebug line after json\n',
@@ -38,14 +40,16 @@ def _fake_subprocess_run(*args: object, **kwargs: object) -> SimpleNamespace:
def test_run_nested_cli_command_extracts_first_json_object_from_mixed_stdout(
monkeypatch: MonkeyPatch,
) -> None:
- """
- 校验内部 CLI 调用可从混杂文本中提取首个合法 JSON 对象。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验内部 CLI 调用可从混杂文本中提取首个合法 JSON 对象。"""
def _fake_subprocess_run(*args: object, **kwargs: object) -> SimpleNamespace:
+ """
+ 捕获子进程调用并返回测试指定的执行结果。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 测试指定的执行结果
+ """
del args, kwargs
return SimpleNamespace(
stdout='preface\ntrace {not-json}\n{"ok": true, "message": "job done"}\ntrailer\n',
@@ -63,14 +67,16 @@ def _fake_subprocess_run(*args: object, **kwargs: object) -> SimpleNamespace:
def test_run_nested_cli_command_falls_back_to_text_payload_when_json_missing(
monkeypatch: MonkeyPatch,
) -> None:
- """
- 校验内部 CLI 未返回 JSON 时会回退为文本结果负载。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验内部 CLI 未返回 JSON 时会回退为文本结果负载。"""
def _fake_subprocess_run(*args: object, **kwargs: object) -> SimpleNamespace:
+ """
+ 捕获子进程调用并返回测试指定的执行结果。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 测试指定的执行结果
+ """
del args, kwargs
return SimpleNamespace(
stdout='任务已提交到调度器',
@@ -89,15 +95,17 @@ def _fake_subprocess_run(*args: object, **kwargs: object) -> SimpleNamespace:
def test_run_nested_cli_command_uses_backend_dir_and_pythonpath(monkeypatch: MonkeyPatch) -> None:
- """
- 校验内部 CLI 调用会固定后端工作目录并注入项目路径。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验内部 CLI 调用会固定后端工作目录并注入项目路径。"""
recorded_kwargs: dict[str, object] = {}
def _fake_subprocess_run(*args: object, **kwargs: object) -> SimpleNamespace:
+ """
+ 捕获子进程调用并返回测试指定的执行结果。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 测试指定的执行结果
+ """
del args
recorded_kwargs.update(kwargs)
return SimpleNamespace(stdout='{}', stderr='', returncode=0)
@@ -114,16 +122,18 @@ def _fake_subprocess_run(*args: object, **kwargs: object) -> SimpleNamespace:
def test_run_nested_cli_command_live_uses_backend_dir_without_capturing_output(monkeypatch: MonkeyPatch) -> None:
- """
- 校验交互式内部 CLI 调用会复用后端工作目录并直接占用当前终端。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验交互式内部 CLI 调用会复用后端工作目录并直接占用当前终端。"""
recorded_kwargs: dict[str, object] = {}
recorded_args: tuple[object, ...] = ()
def _fake_subprocess_run(*args: object, **kwargs: object) -> SimpleNamespace:
+ """
+ 捕获子进程调用并返回测试指定的执行结果。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 测试指定的执行结果
+ """
nonlocal recorded_args
recorded_args = args
recorded_kwargs.update(kwargs)
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/conftest.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/conftest.py
index d305dc064..b1fbb7241 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/conftest.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/conftest.py
@@ -17,54 +17,98 @@
class FakeRuntimeEnvironment:
"""
测试用插件 CLI 运行时环境服务。
+
+ :ivar backend_dir: 后端项目目录
+ :ivar frontend_dir: 前端项目目录
"""
def __init__(self, backend_dir: Path, frontend_dir: Path | None = None) -> None:
- """初始化测试用插件 CLI 运行时环境服务。"""
+ """
+ 初始化测试用插件 CLI 运行时环境服务。
+
+ :param backend_dir: 后端项目目录
+ :param frontend_dir: 前端项目目录
+ """
self.backend_dir = backend_dir
self.frontend_dir = frontend_dir or Path(
PluginRuntimeEnvironmentService(backend_root=backend_dir).get_frontend_dir()
)
def get_backend_dir(self) -> str:
- """获取后端项目根目录。"""
+ """
+ 获取后端项目根目录。
+
+ :return: 后端项目根目录
+ """
return str(self.backend_dir)
def get_backend_plugins_dir(self) -> str:
- """获取后端插件根目录。"""
+ """
+ 获取后端插件根目录。
+
+ :return: 后端插件根目录
+ """
return str(self.backend_dir / 'plugins')
def get_frontend_dir(self) -> str:
- """获取前端项目根目录。"""
+ """
+ 获取前端项目根目录。
+
+ :return: 前端项目根目录
+ """
return str(self.frontend_dir)
def get_frontend_framework(self, frontend_root: Path | None = None) -> str:
- """获取指定测试前端工程的框架标识。"""
+ """
+ 获取指定测试前端工程的框架标识。
+
+ :param frontend_root: 前端项目的根目录
+ :return: 指定测试前端工程的框架标识
+ """
return PluginFrontendFrameworkResolver.resolve(frontend_root or self.frontend_dir)
def get_frontend_plugins_dir(self) -> str:
- """获取前端插件根目录。"""
+ """
+ 获取前端插件根目录。
+
+ :return: 前端插件根目录
+ """
return str(self.frontend_dir / 'plugins')
@staticmethod
def get_frontend_mode() -> str:
- """获取测试用前端运行模式。"""
+ """
+ 获取测试用前端运行模式。
+
+ :return: 此分支的固定值 ``'dev'``
+ """
return 'dev'
@staticmethod
def get_backend_runtime_mode() -> str:
- """获取测试用后端运行模式。"""
+ """
+ 获取测试用后端运行模式。
+
+ :return: 此分支的固定值 ``'dev'``
+ """
return 'dev'
@staticmethod
def get_python_executable() -> str:
- """获取测试用 Python 解释器。"""
+ """
+ 获取测试用 Python 解释器。
+
+ :return: 测试用 Python 解释器
+ """
return sys.executable
class FakePluginRuntimeGateway:
"""
测试用插件 CLI 运行时适配器。
+
+ :ivar completed_process: 用于模拟子进程执行结果的对象
+ :ivar commands: 测试替身收到的命令
"""
def __init__(self) -> None:
@@ -79,13 +123,26 @@ def run_command(
*,
timeout: int | None = None,
) -> CompletedProcess[str]:
- """记录测试用系统命令。"""
+ """
+ 记录测试用系统命令。
+
+ :param command: 执行的命令及其参数
+ :param workdir: 命令执行时使用的工作目录
+ :param timeout: 等待操作完成的超时限制
+ :return: 供调用方使用的 ``self.completed_process``
+ """
self.commands.append((command, workdir, timeout))
return self.completed_process
def build_runtime(backend_root: Path, frontend_root: Path | None = None) -> CliPluginRuntimeService:
- """构建测试用插件 CLI 运行时服务。"""
+ """
+ 构建测试用插件 CLI 运行时服务。
+
+ :param backend_root: 后端项目的根目录
+ :param frontend_root: 前端项目的根目录
+ :return: 测试用插件 CLI 运行时服务
+ """
return CliPluginRuntimeService(
runtime_environment=FakeRuntimeEnvironment(backend_root, frontend_root),
dependency_checker=PluginDependencyChecker(
@@ -100,7 +157,14 @@ def build_runtime_with_gateway(
gateway: FakePluginRuntimeGateway,
frontend_root: Path | None = None,
) -> CliPluginRuntimeService:
- """构建带测试运行时适配器的插件 CLI 运行时服务。"""
+ """
+ 构建带测试运行时适配器的插件 CLI 运行时服务。
+
+ :param backend_root: 后端项目的根目录
+ :param gateway: 测试用插件运行时适配器
+ :param frontend_root: 前端项目的根目录
+ :return: 带测试运行时适配器的插件 CLI 运行时服务
+ """
return CliPluginRuntimeService(
runtime_environment=FakeRuntimeEnvironment(backend_root, frontend_root),
dependency_checker=PluginDependencyChecker(
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_dependency_lock.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_dependency_lock.py
index e2b7abfd9..7f90b327a 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_dependency_lock.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_dependency_lock.py
@@ -10,7 +10,11 @@
def write_demo_dependency_manifest(backend_root: Path) -> None:
- """为 demo 插件补充外部依赖声明。"""
+ """
+ 为 demo 插件补充外部依赖声明。
+
+ :param backend_root: 后端项目的根目录
+ """
manifest_path = backend_root / 'plugins' / 'demo' / 'plugin.yaml'
manifest = yaml.safe_load(manifest_path.read_text(encoding='utf-8'))
manifest['dependencies'] = {
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold.py
index 9eed23f6f..1426313d8 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold.py
@@ -11,7 +11,12 @@
def write_frontend_package(frontend_root: Path, dependencies: dict[str, str]) -> None:
- """写入测试用前端 package.json。"""
+ """
+ 写入测试用前端 package.json。
+
+ :param frontend_root: 前端项目的根目录
+ :param dependencies: 执行当前步骤所需的依赖
+ """
frontend_root.mkdir(parents=True, exist_ok=True)
(frontend_root / 'package.json').write_text(
json.dumps({'dependencies': dependencies}),
@@ -22,21 +27,38 @@ def write_frontend_package(frontend_root: Path, dependencies: dict[str, str]) ->
class LazyPluginGateway:
"""
测试用 CLI 插件网关,验证开发者能力可懒解析运行时依赖。
+
+ :ivar backend_root: 后端项目的根目录
+ :ivar runtime_environment_requested: 是否已请求创建运行环境
"""
def __init__(self, backend_root: Path) -> None:
- """初始化测试用 CLI 插件网关。"""
+ """
+ 初始化测试用 CLI 插件网关。
+
+ :param backend_root: 后端项目的根目录
+ """
self.backend_root = backend_root
self.runtime_environment_requested = False
def get_core_runtime_environment(self) -> FakeRuntimeEnvironment:
- """获取测试运行时环境。"""
+ """
+ 获取测试运行时环境。
+
+ :return: 测试运行时环境
+ """
self.runtime_environment_requested = True
return FakeRuntimeEnvironment(self.backend_root)
@staticmethod
def build_exception_payload(message: str, exc: Exception) -> dict[str, object]:
- """构建测试异常负载。"""
+ """
+ 构建测试异常负载。
+
+ :param message: 与当前结果一起返回的说明
+ :param exc: 捕获到的异常实例
+ :return: 测试异常负载
+ """
return {'ok': False, 'message': message, 'error': str(exc)}
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold_v2.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold_v2.py
index a9bd70015..b4da97897 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold_v2.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold_v2.py
@@ -27,6 +27,11 @@
def generate(tmp_path: Path, template: str, **kwargs: object) -> tuple[dict, Path]:
"""
在临时宿主目录中生成指定 v2 模板。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param template: 用于生成文件的模板
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 生成结果及生成的插件目录
"""
backend = tmp_path / 'backend'
payload = build_runtime(backend, frontend_root=FRONTEND_ROOT).create_plugin(PLUGIN_ID, template=template, **kwargs)
@@ -37,6 +42,10 @@ def generate(tmp_path: Path, template: str, **kwargs: object) -> tuple[dict, Pat
def run_builder(source: Path, output: Path) -> subprocess.CompletedProcess[str]:
"""
通过独立 Python 进程执行生成的交付构建脚本。
+
+ :param source: 隔离插件工程根目录
+ :param output: 命令或操作的输出
+ :return: 交付构建子进程的退出码及输出
"""
return subprocess.run(
[sys.executable, '-X', 'utf8', str(source / 'build_release.py'), '--output', str(output)],
@@ -52,6 +61,8 @@ def run_builder(source: Path, output: Path) -> subprocess.CompletedProcess[str]:
def write_bundle(source: Path) -> None:
"""
写入最小已构建前端资源,供离线交付测试使用。
+
+ :param source: 隔离插件工程根目录
"""
dist = source / 'web' / 'dist'
(dist / 'assets').mkdir(parents=True)
@@ -65,7 +76,6 @@ def write_release_files(source: Path, names: list[object]) -> None:
:param source: 隔离插件工程根目录
:param names: 清单中的完整文件列表
- :return: None
"""
(source / 'release-files.json').write_text(
json.dumps({'schemaVersion': 1, 'files': names}, ensure_ascii=False), encoding='utf-8'
@@ -76,9 +86,7 @@ def write_release_files(source: Path, names: list[object]) -> None:
def test_v2_templates_create_independent_projects_without_importing_or_installing(
tmp_path: Path, template: str
) -> None:
- """
- 验证四类模板生成独立工程且不安装或导入插件。
- """
+ """验证四类模板生成独立工程且不安装或导入插件。"""
payload, source = generate(tmp_path, template)
plugin = PluginScanner(source.parent).load_manifest(source / 'plugin.yaml')
native = template.startswith('rust-')
@@ -133,9 +141,7 @@ def test_v2_templates_create_independent_projects_without_importing_or_installin
@pytest.mark.parametrize('template', ['python-bundle', 'rust-bundle'])
def test_bundle_templates_record_sdk_identity_and_source_hashes(tmp_path: Path, template: str) -> None:
- """
- 验证 bundle 工程包含独立 SDK 版本、协议能力及与实际副本一致的来源摘要。
- """
+ """验证 bundle 工程包含独立 SDK 版本、协议能力及与实际副本一致的来源摘要。"""
_, source = generate(tmp_path, template)
vendor = source / 'web' / 'vendor'
sdk = json.loads((vendor / 'pluginBridge.sdk.json').read_text(encoding='utf-8'))
@@ -187,9 +193,7 @@ def test_api_template_does_not_resolve_unknown_independent_host_framework(tmp_pa
def test_bundle_sdk_source_hashes_are_stable_across_crlf_checkout(tmp_path: Path) -> None:
- """
- 验证使用 CRLF 的宿主源码副本生成工程后,SDK 溯源摘要仍与规范化内容一致。
- """
+ """验证使用 CRLF 的宿主源码副本生成工程后,SDK 溯源摘要仍与规范化内容一致。"""
frontend = tmp_path / 'frontend'
sdk_source = frontend / 'src' / 'utils'
sdk_source.mkdir(parents=True)
@@ -210,9 +214,7 @@ def test_bundle_sdk_source_hashes_are_stable_across_crlf_checkout(tmp_path: Path
@pytest.mark.parametrize('template', TEMPLATES)
def test_v2_template_readme_matches_browser_capabilities(tmp_path: Path, template: str) -> None:
- """
- 验证生成说明区分浏览器 SDK 能力与模板自带接口,并保留协商和传输限制。
- """
+ """验证生成说明区分浏览器 SDK 能力与模板自带接口,并保留协商和传输限制。"""
_, source = generate(tmp_path, template)
readme = (source / 'README.md').read_text(encoding='utf-8')
assert (
@@ -252,9 +254,7 @@ def test_v2_template_readme_matches_browser_capabilities(tmp_path: Path, templat
@pytest.mark.parametrize('template', TEMPLATES)
def test_v2_template_dry_run_and_conflict_never_overwrite(tmp_path: Path, template: str) -> None:
- """
- 验证预演不写文件,目录冲突时不覆盖已有内容。
- """
+ """验证预演不写文件,目录冲突时不覆盖已有内容。"""
payload, source = generate(tmp_path, template, dry_run=True)
assert payload['dryRun'] is True
assert not source.exists()
@@ -271,13 +271,7 @@ def test_v2_template_dry_run_and_conflict_never_overwrite(tmp_path: Path, templa
@pytest.mark.parametrize('template', TEMPLATES)
def test_v2_python_templates_describe_explicit_release_files(tmp_path: Path, template: str) -> None:
- """
- 验证仅 Python 模板生成受控交付清单,并说明模块和迁移的扩展方法。
-
- :param tmp_path: 隔离宿主目录
- :param template: 待检查的 v2 模板
- :return: None
- """
+ """验证仅 Python 模板生成受控交付清单,并说明模块和迁移的扩展方法。"""
_, source = generate(tmp_path, template)
config = source / 'release-files.json'
readme = (source / 'README.md').read_text(encoding='utf-8')
@@ -303,9 +297,7 @@ def test_v2_python_templates_describe_explicit_release_files(tmp_path: Path, tem
def test_v2_templates_reject_incompatible_legacy_options(
tmp_path: Path, template: str, options: dict, error: str
) -> None:
- """
- 验证 v2 模板拒绝不兼容的旧版选项。
- """
+ """验证 v2 模板拒绝不兼容的旧版选项。"""
payload = build_runtime(tmp_path / 'backend', frontend_root=FRONTEND_ROOT).create_plugin(
PLUGIN_ID, template=template, **options
)
@@ -315,9 +307,7 @@ def test_v2_templates_reject_incompatible_legacy_options(
def test_bundle_template_requires_verified_host_sdk_and_no_test_is_honored(tmp_path: Path) -> None:
- """
- 验证 bundle 需要宿主桥接 SDK,且遵守不生成测试的选项。
- """
+ """验证 bundle 需要宿主桥接 SDK,且遵守不生成测试的选项。"""
missing = build_runtime(tmp_path / 'backend').create_plugin(PLUGIN_ID, template='python-bundle')
assert missing['ok'] is False
assert '桥接 SDK' in missing['error']
@@ -329,9 +319,7 @@ def test_bundle_template_requires_verified_host_sdk_and_no_test_is_honored(tmp_p
@pytest.mark.parametrize('template', ['python-asgi', 'python-bundle'])
def test_generated_python_release_passes_structure_and_generated_contract_tests(tmp_path: Path, template: str) -> None:
- """
- 验证生成的 Python 交付通过结构检查与其自身合约测试。
- """
+ """验证生成的 Python 交付通过结构检查与其自身合约测试。"""
_, source = generate(tmp_path, template)
if template.endswith('-bundle'):
write_bundle(source)
@@ -380,9 +368,7 @@ def test_generated_python_release_passes_structure_and_generated_contract_tests(
'invalid_file', ['assets/app.js.map', 'assets/private.pem', '.env', 'assets/entry.ts', 'assets/.private.js']
)
def test_python_bundle_packaging_rejects_nonrelease_content(tmp_path: Path, invalid_file: str) -> None:
- """
- 验证 Python 交付拒绝源码、密钥和其他非交付资源。
- """
+ """验证 Python 交付拒绝源码、密钥和其他非交付资源。"""
_, source = generate(tmp_path, 'python-bundle')
write_bundle(source)
(source / 'web' / 'dist' / invalid_file).write_text('must not package', encoding='utf-8')
@@ -392,9 +378,7 @@ def test_python_bundle_packaging_rejects_nonrelease_content(tmp_path: Path, inva
def test_python_bundle_packaging_rejects_missing_build_and_overlapping_output(tmp_path: Path) -> None:
- """
- 验证 Python 交付拒绝缺失前端构建及输出目录重叠。
- """
+ """验证 Python 交付拒绝缺失前端构建及输出目录重叠。"""
_, source = generate(tmp_path, 'python-bundle')
output = tmp_path / 'missing-build'
assert run_builder(source, output).returncode != 0
@@ -405,9 +389,7 @@ def test_python_bundle_packaging_rejects_missing_build_and_overlapping_output(tm
def test_python_release_rejects_hardlinked_resources(tmp_path: Path) -> None:
- """
- 验证 Python 交付拒绝硬链接资源。
- """
+ """验证 Python 交付拒绝硬链接资源。"""
_, source = generate(tmp_path, 'python-asgi')
os.link(source / '__init__.py', tmp_path / 'entry-copy.py')
output = tmp_path / 'hardlink-release'
@@ -417,13 +399,7 @@ def test_python_release_rejects_hardlinked_resources(tmp_path: Path) -> None:
@pytest.mark.parametrize('template', ['python-asgi', 'python-bundle'])
def test_python_release_copies_declared_modules_and_sql_without_importing(tmp_path: Path, template: str) -> None:
- """
- 验证新增模块和 SQL 按清单交付,未声明的私有文件不会混入且业务入口不会执行。
-
- :param tmp_path: 隔离构建目录
- :param template: Python API 或 bundle 模板
- :return: None
- """
+ """验证新增模块和 SQL 按清单交付,未声明的私有文件不会混入且业务入口不会执行。"""
_, source = generate(tmp_path, template)
names = ['__init__.py', 'models.py', 'api/__init__.py', 'api/reports.py', 'migrations/mysql/001_init.sql']
for name in names:
@@ -478,14 +454,7 @@ def test_python_release_copies_declared_modules_and_sql_without_importing(tmp_pa
],
)
def test_python_release_rejects_unsafe_declared_paths_before_output(tmp_path: Path, name: object, reason: str) -> None:
- """
- 验证显式声明仍不能绕过路径、资源类型和开发目录限制。
-
- :param tmp_path: 隔离源码及输出目录
- :param name: 清单中的非法资源路径
- :param reason: 预期的拒绝原因片段
- :return: None
- """
+ """验证显式声明仍不能绕过路径、资源类型和开发目录限制。"""
_, source = generate(tmp_path, 'python-asgi')
write_release_files(source, ['__init__.py', name])
output = tmp_path / 'unsafe-release'
@@ -505,13 +474,7 @@ def test_python_release_rejects_unsafe_declared_paths_before_output(tmp_path: Pa
],
)
def test_python_release_rejects_duplicate_and_conflicting_inventory(tmp_path: Path, names: list[str]) -> None:
- """
- 验证重复文件、大小写目录歧义及文件目录冲突在访问资源前被拒绝。
-
- :param tmp_path: 隔离源码及输出目录
- :param names: 存在重复或冲突的完整清单
- :return: None
- """
+ """验证重复文件、大小写目录歧义及文件目录冲突在访问资源前被拒绝。"""
_, source = generate(tmp_path, 'python-asgi')
write_release_files(source, names)
output = tmp_path / 'collision-release'
@@ -549,13 +512,7 @@ def test_python_release_rejects_duplicate_and_conflicting_inventory(tmp_path: Pa
],
)
def test_python_release_rejects_invalid_or_oversized_config(tmp_path: Path, content: str) -> None:
- """
- 验证清单结构、重复字段和资源上限,拒绝时不创建输出目录。
-
- :param tmp_path: 隔离源码及输出目录
- :param content: 非法交付清单文本
- :return: None
- """
+ """验证清单结构、重复字段和资源上限,拒绝时不创建输出目录。"""
_, source = generate(tmp_path, 'python-asgi')
(source / 'release-files.json').write_text(content, encoding='utf-8')
output = tmp_path / 'invalid-config-release'
@@ -565,13 +522,7 @@ def test_python_release_rejects_invalid_or_oversized_config(tmp_path: Path, cont
@pytest.mark.parametrize('missing', ['release-files.json', 'module.py', 'directory.py'])
def test_python_release_requires_existing_config_and_regular_declared_files(tmp_path: Path, missing: str) -> None:
- """
- 验证缺失清单、缺失资源及伪装为 .py 的目录均不会留下半成品输出。
-
- :param tmp_path: 隔离源码及输出目录
- :param missing: 缺失清单或不可用的声明资源
- :return: None
- """
+ """验证缺失清单、缺失资源及伪装为 .py 的目录均不会留下半成品输出。"""
_, source = generate(tmp_path, 'python-asgi')
if missing == 'release-files.json':
(source / missing).unlink()
@@ -586,13 +537,7 @@ def test_python_release_requires_existing_config_and_regular_declared_files(tmp_
@pytest.mark.parametrize('kind', ['file', 'directory'])
def test_python_release_rejects_linked_declared_resources(tmp_path: Path, kind: str) -> None:
- """
- 验证文件或父目录符号链接不能将工程外内容引入交付。
-
- :param tmp_path: 隔离源码、外部文件及输出目录
- :param kind: 文件链接或目录链接
- :return: None
- """
+ """验证文件或父目录符号链接不能将工程外内容引入交付。"""
_, source = generate(tmp_path, 'python-asgi')
outside = tmp_path / 'outside'
outside.mkdir()
@@ -613,13 +558,7 @@ def test_python_release_rejects_linked_declared_resources(tmp_path: Path, kind:
def test_python_release_rejects_reparse_resource_before_output(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- """
- 验证 Windows 重解析标志独立于符号链接权限,且校验失败发生在输出创建之前。
-
- :param tmp_path: 隔离源码及输出目录
- :param monkeypatch: 模拟文件系统重解析标志和命令参数
- :return: None
- """
+ """验证 Windows 重解析标志独立于符号链接权限,且校验失败发生在输出创建之前。"""
_, source = generate(tmp_path, 'python-asgi')
namespace = runpy.run_path(str(source / 'build_release.py'))
original_lstat = Path.lstat
@@ -646,11 +585,7 @@ def reparse_lstat(path: Path) -> object:
def test_task_demo_release_builder_matches_scaffold_template() -> None:
- """
- 验证任务示例和 Python 脚手架共用同一独立构建逻辑,防止安全约束漂移。
-
- :return: None
- """
+ """验证任务示例和 Python 脚手架共用同一独立构建逻辑,防止安全约束漂移。"""
example = BACKEND_ROOT / 'plugins' / 'examples' / 'python' / 'task_demo'
template = BACKEND_ROOT / 'cli' / 'runtime' / 'plugin' / 'scaffold' / 'assets' / 'python' / 'build_release.py.tmpl'
expected = template.read_text(encoding='utf-8').replace('__PLUGIN_ID__', 'task_demo').replace('__BUNDLE__', 'True')
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_sdk.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_sdk.py
index 37d9e8ed5..d68c44a56 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_sdk.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_sdk.py
@@ -229,7 +229,12 @@ def test_update_previews_then_backs_up_exact_bytes_and_writes_metadata_last(
replace = os.replace
def record_replace(source: Path, target: Path) -> None:
- """记录原子替换顺序以验证元数据只在代码之后发布。"""
+ """
+ 记录原子替换顺序以验证元数据只在代码之后发布。
+
+ :param source: 本次文件操作的源路径
+ :param target: 本次操作的目标
+ """
calls.append(target.name)
replace(source, target)
@@ -389,7 +394,13 @@ def test_failed_update_restores_originals_and_keeps_backup(
failed = False
def fail_once(source: Path, target: Path) -> None:
- """模拟磁盘替换失败一次,使后续回滚仍可写回原内容。"""
+ """
+ 模拟磁盘替换失败一次,使后续回滚仍可写回原内容。
+
+ :param source: 本次文件操作的源路径
+ :param target: 本次操作的目标
+ :raises OSError: 模拟替换文件失败
+ """
nonlocal failed
if target.name == failure_file and not failed:
failed = True
@@ -417,7 +428,12 @@ def test_final_content_verification_failure_rolls_back(
corrupted = False
def corrupt_once(source: Path, target: Path) -> None:
- """模拟元数据发布后发现实际文件字节不同。"""
+ """
+ 模拟元数据发布后发现实际文件字节不同。
+
+ :param source: 本次文件操作的源路径
+ :param target: 本次操作的目标
+ """
nonlocal corrupted
replace(source, target)
if target.name == SDK_METADATA and not corrupted:
@@ -443,7 +459,13 @@ def test_untracked_creation_failure_removes_new_files(
replace = os.replace
def fail_metadata(source: Path, target: Path) -> None:
- """模拟首次创建副本时发布元数据失败。"""
+ """
+ 模拟首次创建副本时发布元数据失败。
+
+ :param source: 本次文件操作的源路径
+ :param target: 本次操作的目标
+ :raises OSError: 模拟写入元数据失败
+ """
if target.name == SDK_METADATA:
raise OSError('metadata write failed')
replace(source, target)
@@ -465,7 +487,13 @@ def test_rollback_failure_reports_backup_and_continues_other_files(
replace = os.replace
def fail_types(source: Path, target: Path) -> None:
- """模拟类型声明文件持续无法替换。"""
+ """
+ 模拟类型声明文件持续无法替换。
+
+ :param source: 本次文件操作的源路径
+ :param target: 本次操作的目标
+ :raises OSError: 模拟类型声明文件不可用
+ """
if target.name == SDK_FILES[1]:
raise OSError('type file unavailable')
replace(source, target)
@@ -492,7 +520,12 @@ def test_windows_reparse_components_are_rejected(
lstat = Path.lstat
def reparse_lstat(path: Path) -> Any:
- """将指定路径模拟为 Windows 重解析点。"""
+ """
+ 将指定路径模拟为 Windows 重解析点。
+
+ :param path: 要读取或处理的路径
+ :return: 具有模拟重解析点属性的文件状态
+ """
if path == rejected:
return SimpleNamespace(st_mode=stat.S_IFDIR, st_file_attributes=0x400)
return lstat(path)
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_testing.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_testing.py
index e1d9954be..ea1be1697 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_testing.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_testing.py
@@ -16,28 +16,52 @@
class LazyPluginGateway:
"""
测试用 CLI 插件网关,验证测试命令可懒解析运行时依赖。
+
+ :ivar backend_root: 后端项目的根目录
+ :ivar runtime_gateway: 封装运行时调用的测试网关
+ :ivar runtime_environment_requested: 是否已请求创建运行环境
+ :ivar runtime_gateway_requested: 是否已请求运行时网关
"""
def __init__(self, backend_root: Path, runtime_gateway: FakePluginRuntimeGateway) -> None:
- """初始化测试用 CLI 插件网关。"""
+ """
+ 初始化测试用 CLI 插件网关。
+
+ :param backend_root: 后端项目的根目录
+ :param runtime_gateway: 测试用插件运行时适配器
+ """
self.backend_root = backend_root
self.runtime_gateway = runtime_gateway
self.runtime_environment_requested = False
self.runtime_gateway_requested = False
def get_core_runtime_environment(self) -> FakeRuntimeEnvironment:
- """获取测试运行时环境。"""
+ """
+ 获取测试运行时环境。
+
+ :return: 测试运行时环境
+ """
self.runtime_environment_requested = True
return FakeRuntimeEnvironment(self.backend_root)
def get_management_runtime_gateway(self) -> FakePluginRuntimeGateway:
- """获取测试运行时适配器。"""
+ """
+ 获取测试运行时适配器。
+
+ :return: 测试运行时适配器
+ """
self.runtime_gateway_requested = True
return self.runtime_gateway
@staticmethod
def build_exception_payload(message: str, exc: Exception) -> dict[str, object]:
- """构建测试异常负载。"""
+ """
+ 构建测试异常负载。
+
+ :param message: 与当前结果一起返回的说明
+ :param exc: 捕获到的异常实例
+ :return: 测试异常负载
+ """
return {'ok': False, 'message': message, 'error': str(exc)}
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_scaffold_locales.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_scaffold_locales.py
index 464dd8886..a5e794c1e 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_scaffold_locales.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_scaffold_locales.py
@@ -11,6 +11,7 @@
@pytest.mark.parametrize('framework', ['vue2', 'vue3', 'react'])
def test_source_plugin_views_use_local_namespace_and_reactive_host_adapter(framework: str) -> None:
+ """源码插件视图使用本地命名空间及响应式宿主适配器。"""
view = PluginFrontendScaffoldTemplateBuilder.build_crud_view('demo', framework)
assert "from '../i18n'" in view
assert 'plugin.demo:nameRequired' in view
@@ -28,6 +29,7 @@ def test_source_plugin_views_use_local_namespace_and_reactive_host_adapter(frame
def test_plugin_locale_scaffold_keeps_future_languages_pending_in_its_own_directory(tmp_path: Path) -> None:
+ """插件翻译脚手架在自身目录保留待支持的语言。"""
frontend = tmp_path / 'web'
meta = PluginLocaleScaffoldBuilder.load_metadata(frontend)
meta['locales'].append({'code': 'ja-JP', 'enabled': True, 'fallback': ['en-US'], 'direction': 'ltr'})
@@ -53,6 +55,7 @@ def test_plugin_locale_scaffold_keeps_future_languages_pending_in_its_own_direct
def test_plugin_locale_scaffold_rejects_locale_paths_outside_plugin(tmp_path: Path) -> None:
+ """插件翻译脚手架拒绝越出插件目录的路径。"""
meta = PluginLocaleScaffoldBuilder.load_metadata(tmp_path)
meta['locales'].append({'code': '../escape'})
path = tmp_path / 'src' / 'i18n' / 'locale-meta.json'
@@ -65,6 +68,7 @@ def test_plugin_locale_scaffold_rejects_locale_paths_outside_plugin(tmp_path: Pa
def test_bundle_registry_honors_its_own_declared_language_families() -> None:
+ """资源包注册表遵循自身声明的语系。"""
node = shutil.which('node')
if not node:
pytest.skip('Node is required for the generated bundle runtime check')
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_app_runtime.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_app_runtime.py
index 02d55bdd3..502a4ea5c 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_app_runtime.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_app_runtime.py
@@ -13,20 +13,31 @@
def _build_app_with_included_router() -> FastAPI:
+ """
+ 构建包含待检查路由的测试应用。
+
+ :return: 包含待检查路由的测试应用
+ """
app = FastAPI()
router = APIRouter()
@router.get(
'/visible',
name='visible_route',
- summary='Visible route',
+ summary='查看公开的示例路由',
+ description='返回成功状态,用于核对路由清单中的摘要、标签和操作标识。',
operation_id='visibleRoute',
tags=['route'],
)
async def visible_route() -> dict[str, bool]:
return {'ok': True}
- @router.get('/hidden', include_in_schema=False)
+ @router.get(
+ '/hidden',
+ summary='查看隐藏的示例路由',
+ description='返回成功状态,用于核对隐藏路由在命令行清单中的可见性。',
+ include_in_schema=False,
+ )
async def hidden_route() -> dict[str, bool]:
return {'ok': True}
@@ -35,11 +46,16 @@ async def hidden_route() -> dict[str, bool]:
def _expected_visible_route() -> dict[str, object]:
+ """
+ 返回含 ``path``, ``methods``, ``name``, ``summary`` 等字段 的测试数据。
+
+ :return: 含 ``path``, ``methods``, ``name``, ``summary`` 等字段 的测试数据
+ """
return {
'path': '/api/visible',
'methods': ['GET'],
'name': 'visible_route',
- 'summary': 'Visible route',
+ 'summary': '查看公开的示例路由',
'operationId': 'visibleRoute',
'tags': ['included', 'route'],
'includeInSchema': True,
@@ -47,9 +63,7 @@ def _expected_visible_route() -> dict[str, object]:
class FakeRuntimeEnvironment(RuntimeEnvironmentService):
- """
- 模拟运行时环境服务。
- """
+ """模拟运行时环境服务。"""
@staticmethod
def get_backend_dir() -> str:
@@ -71,11 +85,7 @@ def get_python_executable() -> str:
def test_app_snapshot_support_builds_config_snapshot() -> None:
- """
- 校验应用快照支持对象会构建应用配置快照。
-
- :return: None
- """
+ """校验应用快照支持对象会构建应用配置快照。"""
gateway = AppInfrastructureGateway()
support = AppSnapshotSupport(gateway, FakeRuntimeEnvironment())
@@ -108,6 +118,11 @@ def test_app_snapshot_support_builds_config_snapshot() -> None:
)
def _fake_get_env_module() -> SimpleNamespace:
+ """
+ 向调用方返回 ``fake_env_module``。
+
+ :return: 模拟应用环境配置的模块
+ """
return fake_env_module
object.__setattr__(gateway, 'get_env_module', _fake_get_env_module)
@@ -121,12 +136,7 @@ def _fake_get_env_module() -> SimpleNamespace:
def test_app_snapshot_support_builds_env_snapshot(monkeypatch: MonkeyPatch) -> None:
- """
- 校验应用快照支持对象会构建环境解析快照。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验应用快照支持对象会构建环境解析快照。"""
gateway = AppInfrastructureGateway()
support = AppSnapshotSupport(gateway, FakeRuntimeEnvironment())
fake_env_module = SimpleNamespace(
@@ -134,6 +144,11 @@ def test_app_snapshot_support_builds_env_snapshot(monkeypatch: MonkeyPatch) -> N
)
def _fake_get_env_module() -> SimpleNamespace:
+ """
+ 向调用方返回 ``fake_env_module``。
+
+ :return: 模拟应用环境配置的模块
+ """
return fake_env_module
object.__setattr__(gateway, 'get_env_module', _fake_get_env_module)
@@ -154,11 +169,7 @@ def _fake_get_env_module() -> SimpleNamespace:
def test_app_runtime_service_builds_app_instance() -> None:
- """
- 校验应用运行时 facade 会通过基础设施网关构建应用实例。
-
- :return: None
- """
+ """校验应用运行时 facade 会通过基础设施网关构建应用实例。"""
gateway = AppInfrastructureGateway()
service = AppRuntimeService(
runtime_environment=FakeRuntimeEnvironment(),
@@ -166,9 +177,7 @@ def test_app_runtime_service_builds_app_instance() -> None:
)
class FakeServerModule:
- """
- 模拟 server 模块。
- """
+ """模拟 server 模块。"""
@staticmethod
def create_app() -> dict[str, str]:
@@ -185,11 +194,16 @@ def _register_application_routers(app: dict[str, str]) -> None:
模拟不存在于当前 server 模块的旧私有扩展点。
:param app: 模拟应用实例
- :return: None
+ :raises AssertionError: 不应调用私有路由注册扩展点
"""
raise AssertionError('不应调用私有路由注册扩展点')
def _fake_get_server_module() -> FakeServerModule:
+ """
+ 创建测试使用的 ``FakeServerModule`` 实例。
+
+ :return: 测试使用的 ``FakeServerModule`` 实例
+ """
return FakeServerModule()
object.__setattr__(gateway, 'get_server_module', _fake_get_server_module)
@@ -200,6 +214,7 @@ def _fake_get_server_module() -> FakeServerModule:
def test_app_runtime_service_expands_included_router_routes() -> None:
+ """应用运行时展开嵌入的路由。"""
app = _build_app_with_included_router()
gateway = AppInfrastructureGateway()
service = AppRuntimeService(
@@ -209,6 +224,11 @@ def test_app_runtime_service_expands_included_router_routes() -> None:
fake_server_module = SimpleNamespace(create_app=lambda: app)
def _fake_get_server_module() -> SimpleNamespace:
+ """
+ 向调用方返回 ``fake_server_module``。
+
+ :return: 模拟服务器运行信息的模块
+ """
return fake_server_module
object.__setattr__(gateway, 'get_server_module', _fake_get_server_module)
@@ -223,6 +243,7 @@ def _fake_get_server_module() -> SimpleNamespace:
def test_app_command_controller_serializes_included_router_routes() -> None:
+ """应用命令序列化嵌入的路由。"""
app = _build_app_with_included_router()
routes = AppCommandController._serialize_routes(app)
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_base.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_base.py
index 70504768b..f594e3a0c 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_base.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_base.py
@@ -6,12 +6,7 @@
def test_backend_project_dir_detection_uses_consistent_rule(tmp_path: Path) -> None:
- """
- 校验不同入口的后端目录判定规则保持一致。
-
- :param tmp_path: pytest 临时目录
- :return: None
- """
+ """校验不同入口的后端目录判定规则保持一致。"""
(tmp_path / 'app.py').write_text('', encoding='utf-8')
(tmp_path / 'config').mkdir()
(tmp_path / 'config' / 'env.py').write_text('', encoding='utf-8')
@@ -26,12 +21,7 @@ def test_backend_project_dir_detection_uses_consistent_rule(tmp_path: Path) -> N
def test_backend_project_dir_detection_rejects_directory_without_cli_package(tmp_path: Path) -> None:
- """
- 校验缺少 cli 目录时不会被误判为后端项目根目录。
-
- :param tmp_path: pytest 临时目录
- :return: None
- """
+ """校验缺少 cli 目录时不会被误判为后端项目根目录。"""
(tmp_path / 'app.py').write_text('', encoding='utf-8')
(tmp_path / 'config').mkdir()
(tmp_path / 'config' / 'env.py').write_text('', encoding='utf-8')
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_cache.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_cache.py
index 0c5e3969d..f65f48731 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_cache.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_cache.py
@@ -8,11 +8,7 @@
def test_cache_domain_support_extracts_scoped_keys() -> None:
- """
- 校验缓存领域支持对象会提取指定缓存名前缀下的相对键名。
-
- :return: None
- """
+ """校验缓存领域支持对象会提取指定缓存名前缀下的相对键名。"""
support = CacheDomainSupport(CacheInfrastructureGateway())
key_items = support.extract_cache_key_items(
@@ -24,11 +20,7 @@ def test_cache_domain_support_extracts_scoped_keys() -> None:
def test_cache_domain_support_builds_missing_cache_result() -> None:
- """
- 校验缓存领域支持对象会生成统一的缓存不存在结果。
-
- :return: None
- """
+ """校验缓存领域支持对象会生成统一的缓存不存在结果。"""
support = CacheDomainSupport(CacheInfrastructureGateway())
payload = support.build_missing_cache_result('sys_config', 'site_name')
@@ -40,16 +32,10 @@ def test_cache_domain_support_builds_missing_cache_result() -> None:
@pytest.mark.asyncio
async def test_cache_runtime_service_ttl_returns_missing_result() -> None:
- """
- 校验缓存运行时在 TTL 返回不存在标记时会输出统一缺失结果。
-
- :return: None
- """
+ """校验缓存运行时在 TTL 返回不存在标记时会输出统一缺失结果。"""
class FakeRedis:
- """
- 模拟 Redis 客户端。
- """
+ """模拟 Redis 客户端。"""
@staticmethod
async def ttl(full_cache_key: str) -> int:
@@ -64,16 +50,10 @@ async def ttl(full_cache_key: str) -> int:
@staticmethod
async def close() -> None:
- """
- 关闭客户端。
-
- :return: None
- """
+ """关闭客户端。"""
class FakeRedisUtil:
- """
- 模拟 Redis 工具类。
- """
+ """模拟 Redis 工具类。"""
@staticmethod
async def create_redis_pool(*, log_enabled: bool = False) -> FakeRedis:
@@ -90,6 +70,11 @@ async def create_redis_pool(*, log_enabled: bool = False) -> FakeRedis:
service = CacheRuntimeService(infrastructure_gateway=gateway)
def _fake_get_redis_util() -> FakeRedisUtil:
+ """
+ 创建测试使用的 ``FakeRedisUtil`` 实例。
+
+ :return: 测试使用的 ``FakeRedisUtil`` 实例
+ """
return FakeRedisUtil()
object.__setattr__(gateway, 'get_redis_util', _fake_get_redis_util)
@@ -102,16 +87,10 @@ def _fake_get_redis_util() -> FakeRedisUtil:
@pytest.mark.asyncio
async def test_cache_runtime_service_clear_cache_dry_run_reports_scope() -> None:
- """
- 校验缓存运行时 dry-run 清理会返回匹配键与清理范围。
-
- :return: None
- """
+ """校验缓存运行时 dry-run 清理会返回匹配键与清理范围。"""
class FakeRedis:
- """
- 模拟 Redis 客户端。
- """
+ """模拟 Redis 客户端。"""
@staticmethod
async def keys(pattern: str) -> list[str]:
@@ -126,16 +105,10 @@ async def keys(pattern: str) -> list[str]:
@staticmethod
async def close() -> None:
- """
- 关闭客户端。
-
- :return: None
- """
+ """关闭客户端。"""
class FakeRedisUtil:
- """
- 模拟 Redis 工具类。
- """
+ """模拟 Redis 工具类。"""
@staticmethod
async def create_redis_pool(*, log_enabled: bool = False) -> FakeRedis:
@@ -152,6 +125,11 @@ async def create_redis_pool(*, log_enabled: bool = False) -> FakeRedis:
service = CacheRuntimeService(infrastructure_gateway=gateway)
def _fake_get_redis_util() -> FakeRedisUtil:
+ """
+ 创建测试使用的 ``FakeRedisUtil`` 实例。
+
+ :return: 测试使用的 ``FakeRedisUtil`` 实例
+ """
return FakeRedisUtil()
object.__setattr__(gateway, 'get_redis_util', _fake_get_redis_util)
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_config.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_config.py
index 47a7b2f42..f41f4b113 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_config.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_config.py
@@ -9,11 +9,7 @@
def test_config_domain_support_builds_missing_config_result() -> None:
- """
- 校验参数配置领域支持对象会生成统一的缺失结果。
-
- :return: None
- """
+ """校验参数配置领域支持对象会生成统一的缺失结果。"""
support = ConfigDomainSupport(ConfigInfrastructureGateway())
payload = support.build_missing_config_result(MISSING_CONFIG_KEY, 'cache')
@@ -27,16 +23,10 @@ def test_config_domain_support_builds_missing_config_result() -> None:
def test_config_domain_support_serializes_cache_payload_with_sanitizer() -> None:
- """
- 校验参数配置领域支持对象会对缓存配置做脱敏序列化。
-
- :return: None
- """
+ """校验参数配置领域支持对象会对缓存配置做脱敏序列化。"""
class FakeSanitizer:
- """
- 模拟脱敏工具。
- """
+ """模拟脱敏工具。"""
@staticmethod
def sanitize_data(payload: dict[str, str]) -> dict[str, str]:
@@ -52,6 +42,11 @@ def sanitize_data(payload: dict[str, str]) -> dict[str, str]:
support = ConfigDomainSupport(gateway)
def _fake_get_log_sanitizer() -> FakeSanitizer:
+ """
+ 创建测试使用的 ``FakeSanitizer`` 实例。
+
+ :return: 测试使用的 ``FakeSanitizer`` 实例
+ """
return FakeSanitizer()
object.__setattr__(gateway, 'get_log_sanitizer', _fake_get_log_sanitizer)
@@ -66,15 +61,22 @@ def _fake_get_log_sanitizer() -> FakeSanitizer:
def test_config_runtime_service_builds_cli_config_model_from_orm_record() -> None:
- """
- 校验 CLI 会将 ORM 配置记录显式映射为可序列化的配置模型。
-
- :return: None
- """
+ """校验 CLI 会将 ORM 配置记录显式映射为可序列化的配置模型。"""
class FakeOrmConfigRecord:
"""
模拟 ORM 配置记录。
+
+ :cvar config_id: 参数配置id
+ :cvar config_name: 参数名称
+ :cvar config_key: 用于查找配置项的键
+ :cvar config_value: 参数键值
+ :cvar config_type: 当前配置的类型
+ :cvar create_by: 创建者
+ :cvar create_time: 创建时间
+ :cvar update_by: 更新者
+ :cvar update_time: 更新时间
+ :cvar remark: 供用户阅读的补充说明
"""
config_id = 2
@@ -91,14 +93,23 @@ class FakeOrmConfigRecord:
class FakeConfigModel:
"""
模拟 VO 配置模型。
+
+ :ivar kwargs: 传给被调用对象的关键字参数
"""
def __init__(self, **kwargs: object) -> None:
+ """
+ 初始化测试夹具的 ``kwargs``。
+
+ :param kwargs: 传给被调用对象的关键字参数
+ """
self.kwargs = kwargs
class FakeConfigVoModule:
"""
模拟配置 VO 模块。
+
+ :cvar ConfigModel: 测试暴露的配置模型
"""
ConfigModel = FakeConfigModel
@@ -122,18 +133,17 @@ class FakeConfigVoModule:
@pytest.mark.asyncio
async def test_config_runtime_service_returns_missing_db_config_result() -> None:
- """
- 校验参数配置运行时在数据库中未找到配置时会返回统一结果。
-
- :return: None
- """
+ """校验参数配置运行时在数据库中未找到配置时会返回统一结果。"""
class FakeSession:
- """
- 模拟异步会话。
- """
+ """模拟异步会话。"""
async def __aenter__(self) -> 'FakeSession':
+ """
+ 向调用方返回 ``self``。
+
+ :return: 当前测试对象
+ """
return self
async def __aexit__(
@@ -142,35 +152,52 @@ async def __aexit__(
exc: BaseException | None,
tb: object,
) -> None:
+ """
+ 结束测试资源的异步上下文。
+
+ :param exc_type: 退出上下文时的异常类型
+ :param exc: 捕获到的异常实例
+ :param tb: 异常发生时的回溯信息
+ """
del exc_type, exc, tb
class FakeSessionFactory:
- """
- 模拟异步会话工厂。
- """
+ """模拟异步会话工厂。"""
def __call__(self) -> FakeSession:
+ """
+ 创建测试使用的 ``FakeSession`` 实例。
+
+ :return: 测试使用的 ``FakeSession`` 实例
+ """
return FakeSession()
class FakeConfigModel:
"""
模拟配置模型。
+
+ :ivar kwargs: 传给被调用对象的关键字参数
"""
def __init__(self, **kwargs: str) -> None:
+ """
+ 初始化测试夹具的 ``kwargs``。
+
+ :param kwargs: 传给被调用对象的关键字参数
+ """
self.kwargs = kwargs
class FakeConfigVoModule:
"""
模拟配置 VO 模块。
+
+ :cvar ConfigModel: 测试暴露的配置模型
"""
ConfigModel = FakeConfigModel
class FakeConfigDao:
- """
- 模拟配置 DAO。
- """
+ """模拟配置 DAO。"""
@staticmethod
async def get_config_detail_by_info(session: FakeSession, config_model: FakeConfigModel) -> None:
@@ -179,7 +206,6 @@ async def get_config_detail_by_info(session: FakeSession, config_model: FakeConf
:param session: 数据库会话
:param config_model: 配置模型
- :return: None
"""
assert isinstance(session, FakeSession)
assert config_model.kwargs == {'configKey': MISSING_CONFIG_KEY}
@@ -188,12 +214,27 @@ async def get_config_detail_by_info(session: FakeSession, config_model: FakeConf
service = ConfigRuntimeService(infrastructure_gateway=gateway)
def _fake_get_async_session_local() -> FakeSessionFactory:
+ """
+ 创建测试使用的 ``FakeSessionFactory`` 实例。
+
+ :return: 测试使用的 ``FakeSessionFactory`` 实例
+ """
return FakeSessionFactory()
def _fake_get_config_dao() -> FakeConfigDao:
+ """
+ 创建测试使用的 ``FakeConfigDao`` 实例。
+
+ :return: 测试使用的 ``FakeConfigDao`` 实例
+ """
return FakeConfigDao()
def _fake_get_config_vo_module() -> FakeConfigVoModule:
+ """
+ 创建测试使用的 ``FakeConfigVoModule`` 实例。
+
+ :return: 测试使用的 ``FakeConfigVoModule`` 实例
+ """
return FakeConfigVoModule()
object.__setattr__(gateway, 'get_async_session_local', _fake_get_async_session_local)
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_crypto.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_crypto.py
index b68b82fb6..9bdb23352 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_crypto.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_crypto.py
@@ -11,11 +11,7 @@
def test_crypto_domain_support_rejects_invalid_rsa_key_size() -> None:
- """
- 校验传输加密领域支持对象会拒绝非法 RSA 密钥长度。
-
- :return: None
- """
+ """校验传输加密领域支持对象会拒绝非法 RSA 密钥长度。"""
support = CryptoDomainSupport(CryptoInfrastructureGateway())
try:
@@ -27,15 +23,16 @@ def test_crypto_domain_support_rejects_invalid_rsa_key_size() -> None:
def test_crypto_domain_support_rejects_non_list_legacy_key_pairs() -> None:
- """
- 校验传输加密领域支持对象会拒绝非数组格式的历史密钥配置。
-
- :return: None
- """
+ """校验传输加密领域支持对象会拒绝非数组格式的历史密钥配置。"""
gateway = CryptoInfrastructureGateway()
support = CryptoDomainSupport(gateway)
def _fake_transport_crypto_config() -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(transport_crypto_legacy_key_pairs='{"kid": "legacy"}')
object.__setattr__(gateway, 'get_transport_crypto_config', _fake_transport_crypto_config)
@@ -49,11 +46,7 @@ def _fake_transport_crypto_config() -> SimpleNamespace:
def test_crypto_runtime_service_keygen_returns_argument_error_for_invalid_size() -> None:
- """
- 校验传输加密运行时在非法密钥长度下返回参数错误结果。
-
- :return: None
- """
+ """校验传输加密运行时在非法密钥长度下返回参数错误结果。"""
service = CryptoRuntimeService()
payload = service.generate_crypto_key_pair('kid-20260511', INVALID_RSA_KEY_SIZE)
@@ -64,11 +57,7 @@ def test_crypto_runtime_service_keygen_returns_argument_error_for_invalid_size()
def test_crypto_runtime_service_rotation_rejects_same_kid() -> None:
- """
- 校验传输加密运行时会拒绝与当前版本相同的新密钥版本。
-
- :return: None
- """
+ """校验传输加密运行时会拒绝与当前版本相同的新密钥版本。"""
gateway = CryptoInfrastructureGateway()
service = CryptoRuntimeService(infrastructure_gateway=gateway)
@@ -92,11 +81,7 @@ def test_crypto_runtime_service_rotation_rejects_same_kid() -> None:
def test_crypto_runtime_service_rotation_builds_merged_payload() -> None:
- """
- 校验传输加密运行时会生成包含历史密钥合并结果的轮换辅助数据。
-
- :return: None
- """
+ """校验传输加密运行时会生成包含历史密钥合并结果的轮换辅助数据。"""
gateway = CryptoInfrastructureGateway()
domain_support = CryptoDomainSupport(gateway)
service = CryptoRuntimeService(
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_db.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_db.py
index bb179442a..4947a64d5 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_db.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_db.py
@@ -9,9 +9,7 @@
class FakeRuntimeEnvironment(RuntimeEnvironmentService):
- """
- 模拟运行时环境服务。
- """
+ """模拟运行时环境服务。"""
@staticmethod
def get_backend_dir() -> str:
@@ -24,15 +22,18 @@ def get_backend_dir() -> str:
def test_database_revision_support_serializes_revision() -> None:
- """
- 校验数据库迁移版本支持对象会序列化 Alembic revision。
-
- :return: None
- """
+ """校验数据库迁移版本支持对象会序列化 Alembic revision。"""
class FakeRevision:
"""
模拟 Alembic revision 对象。
+
+ :cvar revision: 当前数据库迁移的版本标识
+ :cvar down_revision: 此次迁移的父版本标识
+ :cvar branch_labels: Alembic 迁移分支的标签
+ :cvar dependencies: 执行当前步骤所需的依赖
+ :cvar doc: 迁移脚本的说明
+ :cvar path: 要读取或处理的路径
"""
revision = '202605110001'
@@ -57,11 +58,7 @@ class FakeRevision:
def test_database_runtime_service_upgrade_dry_run_returns_command_payload() -> None:
- """
- 校验数据库运行时 dry-run 升级会返回命令预览结果。
-
- :return: None
- """
+ """校验数据库运行时 dry-run 升级会返回命令预览结果。"""
service = DatabaseRuntimeService(runtime_environment=FakeRuntimeEnvironment())
payload = service.upgrade_database('head', dry_run=True)
@@ -74,18 +71,17 @@ def test_database_runtime_service_upgrade_dry_run_returns_command_payload() -> N
@pytest.mark.asyncio
async def test_database_runtime_service_ping_database_returns_failure() -> None:
- """
- 校验数据库运行时在连接异常时会返回失败结果。
-
- :return: None
- """
+ """校验数据库运行时在连接异常时会返回失败结果。"""
class FakeConnection:
- """
- 模拟数据库连接对象。
- """
+ """模拟数据库连接对象。"""
async def __aenter__(self) -> 'FakeConnection':
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :raises RuntimeError: 模拟打开数据库连接失败
+ """
raise RuntimeError('db boom')
async def __aexit__(
@@ -94,12 +90,17 @@ async def __aexit__(
exc: BaseException | None,
tb: object,
) -> None:
+ """
+ 结束测试资源的异步上下文。
+
+ :param exc_type: 退出上下文时的异常类型
+ :param exc: 捕获到的异常实例
+ :param tb: 异常发生时的回溯信息
+ """
del exc_type, exc, tb
class FakeEngine:
- """
- 模拟数据库引擎。
- """
+ """模拟数据库引擎。"""
@staticmethod
def connect() -> FakeConnection:
@@ -112,11 +113,7 @@ def connect() -> FakeConnection:
@staticmethod
async def dispose() -> None:
- """
- 释放引擎资源。
-
- :return: None
- """
+ """释放引擎资源。"""
gateway = DatabaseInfrastructureGateway()
service = DatabaseRuntimeService(
@@ -125,13 +122,30 @@ async def dispose() -> None:
)
def _fake_get_async_db_engine_factory() -> object:
+ """
+ 提供异步数据库引擎工厂的测试替身。
+
+ :return: 异步数据库引擎工厂的测试替身
+ """
+
def _factory(*, echo: bool = False) -> FakeEngine:
+ """
+ 提供测试使用的数据库引擎。
+
+ :param echo: 是否回显执行内容
+ :return: 测试使用的数据库引擎
+ """
del echo
return FakeEngine()
return _factory
def _fake_get_sqlalchemy_text() -> object:
+ """
+ 提供 SQLAlchemy 文本表达式的测试替身。
+
+ :return: SQLAlchemy 文本表达式的测试替身
+ """
return lambda sql: sql
object.__setattr__(gateway, 'get_async_db_engine_factory', _fake_get_async_db_engine_factory)
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_dev.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_dev.py
index 23d9ef2ac..9f716577b 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_dev.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_dev.py
@@ -1,14 +1,43 @@
-from cli.exit_codes import DEPENDENCY_ERROR
+from pathlib import Path
+
+from cli.exit_codes import DEPENDENCY_ERROR, RUNTIME_ERROR
from cli.runtime.base import RuntimeEnvironmentService
from cli.runtime.dev import DevelopmentRuntimeService
from cli.runtime.dev.gateway import DevelopmentProcessGateway
from cli.runtime.dev.support import DevelopmentCommandSupport, DevelopmentToolingSupport
+def test_lint_reports_route_metadata_even_when_function_has_docstring(tmp_path: Path) -> None:
+ """验证 CLI 能报告具体注册位置及缺失的接口说明。"""
+ target = tmp_path / 'routes.py'
+ target.write_text(
+ "from fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get('/items', summary='查询事项')\n"
+ 'def items() -> None:\n """返回全部事项。"""\n',
+ encoding='utf-8',
+ )
+ payload = DevelopmentRuntimeService().run_lint([str(target)], check_only=True)
+ assert payload['exit_code'] == RUNTIME_ERROR
+ assert 'routes.py:6: HTTP 路由必须填写含中文的 description' in payload['docstrings']['stdout']
+
+
+def test_dev_lint_fails_for_bad_docstring(tmp_path: Path) -> None:
+ """文档违规时开发检查命令返回失败。"""
+ target = tmp_path / 'sample.py'
+ target.write_text(
+ 'def sample() -> int:\n """\n 示例。\n\n Returns:\n int\n """\n return 1\n',
+ encoding='utf-8',
+ )
+ payload = DevelopmentRuntimeService().run_lint([str(target)], check_only=True)
+ assert payload['format']['ok']
+ assert payload['check']['ok']
+ assert not payload['ok']
+ assert payload['exit_code'] == RUNTIME_ERROR
+ assert 'sample.py:5:' in payload['docstrings']['stdout']
+ assert '请改用 reST 字段或指令' in payload['docstrings']['stdout']
+
+
class FakeRuntimeEnvironment(RuntimeEnvironmentService):
- """
- 模拟运行时环境服务。
- """
+ """模拟运行时环境服务。"""
@staticmethod
def get_backend_dir() -> str:
@@ -30,23 +59,17 @@ def get_python_executable() -> str:
def test_development_runtime_service_returns_dependency_error_when_pytest_missing() -> None:
- """
- 校验开发运行时在 pytest 缺失时会返回依赖错误结果。
-
- :return: None
- """
+ """校验开发运行时在 pytest 缺失时会返回依赖错误结果。"""
class FakeToolingSupport(DevelopmentToolingSupport):
- """
- 模拟开发工具支持对象。
- """
+ """模拟开发工具支持对象。"""
@staticmethod
def is_pytest_available() -> bool:
"""
返回 pytest 不可用状态。
- :return: False
+ :return: 布尔值 False
"""
return False
@@ -66,21 +89,27 @@ def is_pytest_available() -> bool:
def test_development_runtime_service_run_lint_uses_command_support() -> None:
- """
- 校验开发运行时会通过命令支持对象串联 format/check 执行流程。
-
- :return: None
- """
+ """校验开发运行时会通过命令支持对象串联 format/check 执行流程。"""
class FakeCommandSupport(DevelopmentCommandSupport):
"""
模拟开发命令支持对象。
+
+ :ivar recorded_commands: 按执行顺序保存的命令
"""
def __init__(self) -> None:
+ """初始化测试夹具的 ``recorded_commands``。"""
self.recorded_commands: list[list[str]] = []
def build_format_command(self, normalized_targets: list[str], *, check_only: bool) -> list[str]:
+ """
+ 校验格式化参数并返回测试命令。
+
+ :param normalized_targets: 已规整目标列表
+ :param check_only: 是否只报告检查结果
+ :return: 测试命令
+ """
assert normalized_targets == ['tests/cli']
assert check_only is True
return ['format-command']
@@ -93,6 +122,15 @@ def build_check_command(
fix: bool,
unsafe_fixes: bool,
) -> list[str]:
+ """
+ 校验检查参数并提供静态检查命令。
+
+ :param normalized_targets: 已规整目标列表
+ :param check_only: 是否只报告检查结果
+ :param fix: 是否应用可用的修复
+ :param unsafe_fixes: 是否允许不安全修复
+ :return: 供断言比对的静态检查命令
+ """
assert normalized_targets == ['tests/cli']
assert check_only is True
assert fix is False
@@ -102,12 +140,21 @@ def build_check_command(
class FakeProcessGateway(DevelopmentProcessGateway):
"""
模拟开发子进程执行网关。
+
+ :ivar recorded_commands: 按执行顺序保存的命令
"""
def __init__(self) -> None:
+ """初始化测试夹具的 ``recorded_commands``。"""
self.recorded_commands: list[list[str]] = []
def run_command(self, command: list[str]) -> dict[str, object]:
+ """
+ 捕获开发命令并返回测试执行结果。
+
+ :param command: 执行的命令及其参数
+ :return: 测试执行结果
+ """
self.recorded_commands.append(command)
return {'ok': True, 'command': command, 'returnCode': 0}
@@ -123,4 +170,8 @@ def run_command(self, command: list[str]) -> dict[str, object]:
assert payload['ok'] is True
assert payload['targets'] == ['tests/cli']
- assert process_gateway.recorded_commands == [['format-command'], ['check-command']]
+ assert process_gateway.recorded_commands == [
+ ['format-command'],
+ ['check-command'],
+ ['/usr/bin/python3', 'scripts/check_docstrings.py', 'tests/cli'],
+ ]
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_gen.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_gen.py
index b0125687e..6903f1fc1 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_gen.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_gen.py
@@ -12,11 +12,7 @@
def test_gen_domain_support_resolves_sql_text_from_argument() -> None:
- """
- 校验代码生成领域支持对象会优先使用直接传入的 SQL 文本。
-
- :return: None
- """
+ """校验代码生成领域支持对象会优先使用直接传入的 SQL 文本。"""
support = GenDomainSupport(GenInfrastructureGateway())
payload = support.resolve_sql_text(' CREATE TABLE demo(id bigint); ', '')
@@ -25,12 +21,7 @@ def test_gen_domain_support_resolves_sql_text_from_argument() -> None:
def test_gen_domain_support_resolve_sql_text_rejects_invalid_inputs(tmp_path: Path) -> None:
- """
- 校验代码生成领域支持对象会拒绝无效 SQL 输入组合。
-
- :param tmp_path: pytest 临时目录
- :return: None
- """
+ """校验代码生成领域支持对象会拒绝无效 SQL 输入组合。"""
support = GenDomainSupport(GenInfrastructureGateway())
sql_file = tmp_path / 'demo.sql'
sql_file.write_text('select 1', encoding='utf-8')
@@ -44,12 +35,7 @@ def test_gen_domain_support_resolve_sql_text_rejects_invalid_inputs(tmp_path: Pa
def test_gen_domain_support_writes_export_zip(tmp_path: Path) -> None:
- """
- 校验代码生成领域支持对象会写出导出压缩包。
-
- :param tmp_path: pytest 临时目录
- :return: None
- """
+ """校验代码生成领域支持对象会写出导出压缩包。"""
support = GenDomainSupport(GenInfrastructureGateway())
target_file = tmp_path / 'exports' / 'gen.zip'
@@ -61,15 +47,16 @@ def test_gen_domain_support_writes_export_zip(tmp_path: Path) -> None:
@pytest.mark.asyncio
async def test_gen_runtime_service_export_code_dry_run_returns_preview_payload() -> None:
- """
- 校验代码生成运行时在 dry-run 导出时会返回结构化预览结果。
-
- :return: None
- """
+ """校验代码生成运行时在 dry-run 导出时会返回结构化预览结果。"""
gateway = GenInfrastructureGateway()
service = GenRuntimeService(infrastructure_gateway=gateway)
def _fake_get_gen_config() -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(allow_overwrite=True, GEN_PATH='/tmp/gen')
object.__setattr__(gateway, 'get_gen_config', _fake_get_gen_config)
@@ -84,11 +71,7 @@ def _fake_get_gen_config() -> SimpleNamespace:
@pytest.mark.asyncio
async def test_gen_runtime_service_import_tables_requires_at_least_one_table() -> None:
- """
- 校验代码生成运行时在未传入表名时会返回参数错误。
-
- :return: None
- """
+ """校验代码生成运行时在未传入表名时会返回参数错误。"""
service = GenRuntimeService()
payload = await service.import_tables([])
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_job.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_job.py
index 2f3b3c6f2..52e3bff52 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_job.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_job.py
@@ -14,11 +14,7 @@
def test_job_domain_support_builds_operation_metadata() -> None:
- """
- 校验任务领域支持对象会返回统一的任务操作元数据。
-
- :return: None
- """
+ """校验任务领域支持对象会返回统一的任务操作元数据。"""
support = JobDomainSupport(JobInfrastructureGateway())
payload = support.build_job_operation_metadata('pause')
@@ -30,16 +26,10 @@ def test_job_domain_support_builds_operation_metadata() -> None:
def test_job_domain_support_serializes_model_dump_items() -> None:
- """
- 校验任务领域支持对象会序列化带 `model_dump` 的任务项。
-
- :return: None
- """
+ """校验任务领域支持对象会序列化带 ``model_dump`` 的任务项。"""
class FakeJobModel:
- """
- 模拟任务模型。
- """
+ """模拟任务模型。"""
@staticmethod
def model_dump(*, by_alias: bool = False, exclude_none: bool = False) -> dict[str, object]:
@@ -63,45 +53,34 @@ def model_dump(*, by_alias: bool = False, exclude_none: bool = False) -> dict[st
@pytest.mark.asyncio
async def test_job_scheduler_support_closes_scheduler_and_redis() -> None:
- """
- 校验任务调度支持对象会关闭调度器和 Redis 资源。
-
- :return: None
- """
+ """校验任务调度支持对象会关闭调度器和 Redis 资源。"""
close_events: list[str] = []
class FakeRedis:
- """
- 模拟 Redis 客户端。
- """
+ """模拟 Redis 客户端。"""
@staticmethod
async def close() -> None:
- """
- 记录 Redis 关闭事件。
-
- :return: None
- """
+ """记录 Redis 关闭事件。"""
close_events.append('redis')
class FakeSchedulerManager:
- """
- 模拟调度器管理类。
- """
+ """模拟调度器管理类。"""
@staticmethod
async def close_system_scheduler() -> None:
- """
- 记录调度器关闭事件。
-
- :return: None
- """
+ """记录调度器关闭事件。"""
close_events.append('scheduler')
gateway = JobInfrastructureGateway()
support = JobSchedulerSupport(gateway)
def _fake_get_scheduler_manager() -> FakeSchedulerManager:
+ """
+ 创建测试使用的 ``FakeSchedulerManager`` 实例。
+
+ :return: 测试使用的 ``FakeSchedulerManager`` 实例
+ """
return FakeSchedulerManager()
object.__setattr__(gateway, 'get_scheduler_manager', _fake_get_scheduler_manager)
@@ -113,18 +92,17 @@ def _fake_get_scheduler_manager() -> FakeSchedulerManager:
@pytest.mark.asyncio
async def test_job_runtime_service_reports_missing_job_detail() -> None:
- """
- 校验任务运行时在任务详情不存在时会返回统一结果。
-
- :return: None
- """
+ """校验任务运行时在任务详情不存在时会返回统一结果。"""
class FakeSession:
- """
- 模拟异步会话。
- """
+ """模拟异步会话。"""
async def __aenter__(self) -> 'FakeSession':
+ """
+ 向调用方返回 ``self``。
+
+ :return: 当前测试对象
+ """
return self
async def __aexit__(
@@ -133,20 +111,28 @@ async def __aexit__(
exc: BaseException | None,
tb: object,
) -> None:
+ """
+ 结束测试资源的异步上下文。
+
+ :param exc_type: 退出上下文时的异常类型
+ :param exc: 捕获到的异常实例
+ :param tb: 异常发生时的回溯信息
+ """
del exc_type, exc, tb
class FakeSessionFactory:
- """
- 模拟异步会话工厂。
- """
+ """模拟异步会话工厂。"""
def __call__(self) -> FakeSession:
+ """
+ 创建测试使用的 ``FakeSession`` 实例。
+
+ :return: 测试使用的 ``FakeSession`` 实例
+ """
return FakeSession()
class FakeJobService:
- """
- 模拟任务服务。
- """
+ """模拟任务服务。"""
@staticmethod
async def job_detail_services(session: FakeSession, job_id: int) -> dict[str, object]:
@@ -165,9 +151,19 @@ async def job_detail_services(session: FakeSession, job_id: int) -> dict[str, ob
service = JobRuntimeService(infrastructure_gateway=gateway)
def _fake_get_async_session_local() -> FakeSessionFactory:
+ """
+ 创建测试使用的 ``FakeSessionFactory`` 实例。
+
+ :return: 测试使用的 ``FakeSessionFactory`` 实例
+ """
return FakeSessionFactory()
def _fake_get_job_service() -> FakeJobService:
+ """
+ 创建测试使用的 ``FakeJobService`` 实例。
+
+ :return: 测试使用的 ``FakeJobService`` 实例
+ """
return FakeJobService()
object.__setattr__(gateway, 'get_async_session_local', _fake_get_async_session_local)
@@ -185,6 +181,7 @@ def _fake_get_job_service() -> FakeJobService:
async def test_job_operation_retains_execution_and_sync_results(
operation: str, capsys: pytest.CaptureFixture[str]
) -> None:
+ """任务操作保留执行结果和同步结果。"""
result = (
{'executionId': 'execution-123', 'status': 'pending'}
if operation == 'run-once'
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_ops.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_ops.py
index 4ac07878d..283f5a0f7 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_ops.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_ops.py
@@ -9,12 +9,7 @@
def test_operations_dependency_inspector_reports_missing_required(monkeypatch: pytest.MonkeyPatch) -> None:
- """
- 校验运维依赖检查器会报告缺失的必需依赖。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验运维依赖检查器会报告缺失的必需依赖。"""
inspector = OperationsDependencyInspector()
monkeypatch.setattr(
inspector,
@@ -30,17 +25,10 @@ def test_operations_dependency_inspector_reports_missing_required(monkeypatch: p
def test_operations_server_info_support_resolves_non_loopback_ip(monkeypatch: pytest.MonkeyPatch) -> None:
- """
- 校验服务器信息支持对象会在主机名解析失败时回退到网卡地址。
-
- :param monkeypatch: pytest monkeypatch 工具
- :return: None
- """
+ """校验服务器信息支持对象会在主机名解析失败时回退到网卡地址。"""
class FakePsutil:
- """
- 模拟 psutil 模块。
- """
+ """模拟 psutil 模块。"""
@staticmethod
def net_if_addrs() -> dict[str, list[SimpleNamespace]]:
@@ -60,9 +48,20 @@ def net_if_addrs() -> dict[str, list[SimpleNamespace]]:
support = OperationsServerInfoSupport(gateway)
def _fake_get_psutil_module() -> FakePsutil:
+ """
+ 创建测试使用的 ``FakePsutil`` 实例。
+
+ :return: 测试使用的 ``FakePsutil`` 实例
+ """
return FakePsutil()
def _fake_gethostbyname(hostname: str) -> str:
+ """
+ 模拟主机名解析失败。
+
+ :param hostname: 要解析或检查的主机名
+ :raises OSError: 模拟解析主机名失败
+ """
del hostname
raise OSError('boom')
@@ -76,31 +75,19 @@ def _fake_gethostbyname(hostname: str) -> str:
@pytest.mark.asyncio
async def test_operations_runtime_service_sync_jobs_closes_resources_on_success() -> None:
- """
- 校验运维运行时在同步调度成功后会关闭调度器和 Redis 资源。
-
- :return: None
- """
+ """校验运维运行时在同步调度成功后会关闭调度器和 Redis 资源。"""
close_events: list[str] = []
class FakeRedis:
- """
- 模拟 Redis 客户端。
- """
+ """模拟 Redis 客户端。"""
@staticmethod
async def close() -> None:
- """
- 记录关闭事件。
-
- :return: None
- """
+ """记录关闭事件。"""
close_events.append('redis')
class FakeRedisUtil:
- """
- 模拟 Redis 工具。
- """
+ """模拟 Redis 工具。"""
@staticmethod
async def create_redis_pool(*, log_enabled: bool = False) -> FakeRedis:
@@ -116,6 +103,8 @@ async def create_redis_pool(*, log_enabled: bool = False) -> FakeRedis:
class FakeSchedulerManager:
"""
模拟调度器管理类。
+
+ :cvar _is_leader: 当前进程是否持有调度器主锁
"""
_is_leader = True
@@ -126,34 +115,35 @@ async def init_system_scheduler(redis: FakeRedis) -> None:
初始化调度器。
:param redis: Redis 客户端
- :return: None
"""
assert isinstance(redis, FakeRedis)
@staticmethod
async def request_scheduler_sync() -> None:
- """
- 发送调度同步请求。
-
- :return: None
- """
+ """发送调度同步请求。"""
@staticmethod
async def close_system_scheduler() -> None:
- """
- 记录调度器关闭事件。
-
- :return: None
- """
+ """记录调度器关闭事件。"""
close_events.append('scheduler')
gateway = OperationsInfrastructureGateway()
service = OperationsRuntimeService(infrastructure_gateway=gateway)
def _fake_get_redis_util() -> FakeRedisUtil:
+ """
+ 创建测试使用的 ``FakeRedisUtil`` 实例。
+
+ :return: 测试使用的 ``FakeRedisUtil`` 实例
+ """
return FakeRedisUtil()
def _fake_get_scheduler_manager() -> FakeSchedulerManager:
+ """
+ 创建测试使用的 ``FakeSchedulerManager`` 实例。
+
+ :return: 测试使用的 ``FakeSchedulerManager`` 实例
+ """
return FakeSchedulerManager()
object.__setattr__(gateway, 'get_redis_util', _fake_get_redis_util)
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/actions/test_action_execution.py b/ruoyi-fastapi-backend/tests/cli/tui/actions/test_action_execution.py
index b96b9d605..d08de7db6 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/actions/test_action_execution.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/actions/test_action_execution.py
@@ -22,7 +22,14 @@
def build_record(key: str, title: str, *, status: str = 'ok') -> object:
- """构建动作解析测试使用的浏览记录。"""
+ """
+ 构建动作解析测试使用的浏览记录。
+
+ :param key: 查找数据时使用的键
+ :param title: 当前界面或记录显示的标题
+ :param status: 操作或记录所处的状态
+ :return: 动作解析测试使用的浏览记录
+ """
return adapters_module.BrowserRecordSnapshot(
key=key,
title=title,
@@ -34,6 +41,7 @@ def build_record(key: str, title: str, *, status: str = 'ok') -> object:
def test_capabilities_registry_only_exposes_in_process_actions() -> None:
+ """能力注册表只公开进程内操作。"""
cache_capabilities = capabilities_module.TUI_CAPABILITY_REGISTRY.get_browser_capabilities('cache')
gen_capabilities = capabilities_module.TUI_CAPABILITY_REGISTRY.get_browser_capabilities('gen')
app_capabilities = capabilities_module.TUI_CAPABILITY_REGISTRY.get_detail_capabilities('app')
@@ -58,6 +66,7 @@ def test_capabilities_registry_only_exposes_in_process_actions() -> None:
def test_action_registry_builds_runtime_parameters_without_cli_arguments() -> None:
+ """操作注册表无需命令行参数即可构造运行参数。"""
job_record = build_record('job:101', '同步任务', status='warn')
cache_record = build_record('cache:sys_config', 'sys_config')
gen_record = build_record('gen:201', 'sys_user')
@@ -89,6 +98,7 @@ def test_action_registry_builds_runtime_parameters_without_cli_arguments() -> No
def test_action_registry_prunes_external_wizard_slots() -> None:
+ """操作注册表移除外部向导入口。"""
gen_record = build_record('gen:201', 'sys_user')
assert (
@@ -107,6 +117,7 @@ def test_action_registry_prunes_external_wizard_slots() -> None:
def test_action_templates_build_typed_parameters() -> None:
+ """操作模板生成带类型的参数。"""
job_record = build_record('job:88', '通知任务')
gen_record = build_record('gen:301', 'sys_notice')
@@ -127,6 +138,7 @@ def test_action_templates_build_typed_parameters() -> None:
@pytest.mark.asyncio
async def test_action_execution_service_calls_runtime_directly() -> None:
+ """操作执行服务直接调用运行时。"""
service = action_execution_module.TuiActionExecutionService()
service.config_runtime.sync_config_cache = AsyncMock(
return_value={'ok': True, 'message': '参数缓存刷新成功', 'count': 3}
@@ -153,6 +165,7 @@ async def test_action_execution_service_calls_runtime_directly() -> None:
@pytest.mark.asyncio
async def test_action_execution_service_dispatches_selected_job_id() -> None:
+ """操作执行服务分发选定的任务标识。"""
service = action_execution_module.TuiActionExecutionService()
service.job_runtime.run_job_once = AsyncMock(return_value={'ok': True, 'message': '任务执行完成', 'jobId': 42})
spec = actions_module.TuiActionSpec(
@@ -171,6 +184,7 @@ async def test_action_execution_service_dispatches_selected_job_id() -> None:
@pytest.mark.asyncio
async def test_action_execution_service_rejects_unknown_action_without_fallback() -> None:
+ """操作执行服务直接拒绝未知操作。"""
service = action_execution_module.TuiActionExecutionService()
service.operations_runtime.sync_jobs = AsyncMock(return_value={'ok': True})
spec = actions_module.TuiActionSpec(
@@ -193,10 +207,16 @@ async def test_action_execution_service_rejects_unknown_action_without_fallback(
async def test_action_execution_service_times_out_and_cancels(
monkeypatch: MonkeyPatch,
) -> None:
+ """操作超时后取消执行。"""
service = action_execution_module.TuiActionExecutionService()
cancelled = asyncio.Event()
async def slow_sync() -> dict[str, object]:
+ """
+ 模拟执行时间较长的同步操作。
+
+ :return: 包含 ``ok`` 的数据
+ """
try:
await asyncio.sleep(10)
finally:
@@ -222,6 +242,7 @@ async def slow_sync() -> dict[str, object]:
def test_action_result_lines_surface_common_payload_fields() -> None:
+ """操作结果行显示通用响应字段。"""
spec = actions_module.TuiActionSpec(
action_id='job-run-once',
label='执行一次任务',
@@ -250,6 +271,7 @@ def test_action_result_lines_surface_common_payload_fields() -> None:
def test_action_hints_match_reduced_action_surface() -> None:
+ """操作提示仅列出当前支持的操作。"""
browser_hint = actions_module.TUI_ACTION_PRESENTATION_SERVICE.build_browser_action_hint('gen')
detail_hint = actions_module.TUI_ACTION_PRESENTATION_SERVICE.build_detail_action_hint('app')
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/adapters/conftest.py b/ruoyi-fastapi-backend/tests/cli/tui/adapters/conftest.py
index 813cbbfd5..8572c3cf0 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/adapters/conftest.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/adapters/conftest.py
@@ -13,75 +13,209 @@
class RuntimeQueryStub:
- """把现有负载工厂映射为新的异步进程内查询接口。"""
+ """
+ 把现有负载工厂映射为新的异步进程内查询接口。
+
+ :ivar runner: 执行命令或后台任务的对象
+ """
def __init__(self, runner: Callable[..., object]) -> None:
+ """
+ 初始化测试夹具的 ``runner``。
+
+ :param runner: 执行命令或后台任务的对象
+ """
self.runner = runner
def _payload(self, *arguments: str) -> object:
+ """
+ 执行测试命令并提取其 JSON 结果。
+
+ :param arguments: 调用方传入的其余位置参数
+ :return: 随调用传入或返回的结构化数据
+ """
return self.runner(*arguments, parse_json=True).payload
async def get_app_env(self, env: str) -> object:
+ """
+ 提供用于界面测试的当前应用环境。
+
+ :param env: 当前运行环境
+ :return: 用于界面测试的当前应用环境
+ """
return self._payload('app', 'env', f'--env={env}', '--output=json')
async def get_app_config(self, env: str) -> object:
+ """
+ 提供用于界面测试的当前应用配置。
+
+ :param env: 当前运行环境
+ :return: 用于界面测试的当前应用配置
+ """
return self._payload('app', 'config', f'--env={env}', '--output=json')
async def get_app_routes(self, env: str) -> object:
+ """
+ 提供用于界面测试的已注册的应用路由。
+
+ :param env: 当前运行环境
+ :return: 用于界面测试的已注册的应用路由
+ """
return self._payload('app', 'routes', f'--env={env}', '--output=json')
async def get_doctor(self, env: str) -> object:
+ """
+ 提供用于界面测试的应用诊断结果。
+
+ :param env: 当前运行环境
+ :return: 用于界面测试的应用诊断结果
+ """
return self._payload('app', 'doctor', f'--env={env}', '--output=json')
async def get_completion_doctor(self) -> object:
+ """
+ 提供用于界面测试的命令补全环境的诊断结果。
+
+ :return: 用于界面测试的命令补全环境的诊断结果
+ """
return self._payload('completion', 'doctor', '--output=json')
async def get_completion_preview(self, shell: str) -> object:
+ """
+ 提供用于界面测试的指定 Shell 的补全脚本预览。
+
+ :param shell: 生成补全命令的目标 shell
+ :return: 用于界面测试的指定 Shell 的补全脚本预览
+ """
return self.runner('completion', 'show', f'--shell={shell}', parse_json=False)
async def get_database_ping(self) -> object:
+ """
+ 提供用于界面测试的数据库连接探测结果。
+
+ :return: 用于界面测试的数据库连接探测结果
+ """
return self._payload('ops', 'ping-db', '--output=json')
async def get_database_current(self) -> object:
+ """
+ 提供用于界面测试的数据库当前迁移版本。
+
+ :return: 用于界面测试的数据库当前迁移版本
+ """
return self._payload('db', 'current', '--output=json')
async def get_database_heads(self) -> object:
+ """
+ 提供用于界面测试的迁移脚本的最新版本。
+
+ :return: 用于界面测试的迁移脚本的最新版本
+ """
return self._payload('db', 'heads', '--output=json')
async def get_database_history(self, *, limit: int = 8) -> object:
+ """
+ 提供用于界面测试的数据库迁移历史。
+
+ :param limit: 允许读取或返回的最大条目数
+ :return: 用于界面测试的数据库迁移历史
+ """
return self._payload('db', 'history', f'--limit={limit}', '--output=json')
async def get_redis_ping(self) -> object:
+ """
+ 提供用于界面测试的Redis 连接探测结果。
+
+ :return: 用于界面测试的Redis 连接探测结果
+ """
return self._payload('ops', 'ping-redis', '--output=json')
async def get_dependencies(self) -> object:
+ """
+ 提供用于界面测试的服务依赖的可用性。
+
+ :return: 用于界面测试的服务依赖的可用性
+ """
return self._payload('ops', 'deps', '--output=json')
async def get_server_info(self) -> object:
+ """
+ 提供用于界面测试的服务器运行信息。
+
+ :return: 用于界面测试的服务器运行信息
+ """
return self._payload('ops', 'server-info', '--output=json')
async def get_crypto_validation(self) -> object:
+ """
+ 提供用于界面测试的传输加密配置的校验结果。
+
+ :return: 用于界面测试的传输加密配置的校验结果
+ """
return self._payload('crypto', 'validate', '--output=json')
async def get_crypto_public_key(self) -> object:
+ """
+ 提供用于界面测试的当前传输加密公钥。
+
+ :return: 用于界面测试的当前传输加密公钥
+ """
return self._payload('crypto', 'export-public', '--output=json')
async def get_cache_stats(self) -> object:
+ """
+ 提供用于界面测试的缓存命名空间统计。
+
+ :return: 用于界面测试的缓存命名空间统计
+ """
return self._payload('cache', 'stats', '--output=json')
async def get_cache_keys(self, cache_name: str) -> object:
+ """
+ 提供用于界面测试的指定命名空间中的缓存键。
+
+ :param cache_name: 缓存名称
+ :return: 用于界面测试的指定命名空间中的缓存键
+ """
return self._payload('cache', 'keys', cache_name, '--output=json')
async def get_cache_value(self, cache_name: str, cache_key: str) -> object:
+ """
+ 提供用于界面测试的指定缓存键的值。
+
+ :param cache_name: 缓存名称
+ :param cache_key: 缓存键名
+ :return: 用于界面测试的指定缓存键的值
+ """
return self._payload('cache', 'get', cache_name, cache_key, '--output=json')
async def get_cache_ttl(self, cache_name: str, cache_key: str) -> object:
+ """
+ 提供用于界面测试的指定缓存键的剩余有效期。
+
+ :param cache_name: 缓存名称
+ :param cache_key: 缓存键名
+ :return: 用于界面测试的指定缓存键的剩余有效期
+ """
return self._payload('cache', 'ttl', cache_name, cache_key, '--output=json')
async def get_jobs(self) -> object:
+ """
+ 提供用于界面测试的调度任务列表。
+
+ :return: 用于界面测试的调度任务列表
+ """
return self._payload('job', 'list', '--paged', '--page-size=8', '--output=json')
async def get_job_logs(self, *, job_name: str = '', status: str | None = None, page_size: int = 20) -> object:
+ """
+ 提供用于界面测试的任务执行日志。
+
+ :param job_name: 任务名称过滤条件
+ :param status: 操作或记录所处的状态
+ :param page_size: 每页数量
+ :return: 用于界面测试的任务执行日志
+ """
arguments = ['job', 'logs', '--paged', f'--page-size={page_size}', '--output=json']
if job_name:
arguments.append(f'--job-name={job_name}')
@@ -90,45 +224,113 @@ async def get_job_logs(self, *, job_name: str = '', status: str | None = None, p
return self._payload(*arguments)
async def get_job_detail(self, job_id: int) -> object:
+ """
+ 提供用于界面测试的指定调度任务的详情。
+
+ :param job_id: 任务ID
+ :return: 用于界面测试的指定调度任务的详情
+ """
return self._payload('job', 'detail', str(job_id), '--output=json')
async def get_gen_tables(self) -> object:
+ """
+ 提供用于界面测试的已导入代码生成器的表。
+
+ :return: 用于界面测试的已导入代码生成器的表
+ """
return self._payload('gen', 'list', '--paged', '--page-size=8', '--output=json')
async def get_gen_db_tables(self, *, table_name: str = '', page_size: int = 8) -> object:
+ """
+ 提供用于界面测试的可供导入的数据库表。
+
+ :param table_name: 表名称
+ :param page_size: 每页数量
+ :return: 用于界面测试的可供导入的数据库表
+ """
arguments = ['gen', 'db-list', '--paged', f'--page-size={page_size}', '--output=json']
if table_name:
arguments.append(f'--table-name={table_name}')
return self._payload(*arguments)
async def get_gen_detail(self, table_id: int) -> object:
+ """
+ 提供用于界面测试的生成表的详细配置。
+
+ :param table_id: 代码生成表的记录标识
+ :return: 用于界面测试的生成表的详细配置
+ """
return self._payload('gen', 'detail', str(table_id), '--output=json')
async def get_gen_preview(self, table_id: int) -> object:
+ """
+ 提供用于界面测试的所选表的代码预览。
+
+ :param table_id: 代码生成表的记录标识
+ :return: 用于界面测试的所选表的代码预览
+ """
return self._payload('gen', 'preview', str(table_id), '--output=json')
async def get_gen_export_dry_run(self, table_name: str) -> object:
+ """
+ 提供用于界面测试的生成代码导出的预演结果。
+
+ :param table_name: 表名称
+ :return: 用于界面测试的生成代码导出的预演结果
+ """
return self._payload('gen', 'export', table_name, '--dry-run', '--output=json')
async def get_configs(self) -> object:
+ """
+ 提供用于界面测试的系统参数列表。
+
+ :return: 用于界面测试的系统参数列表
+ """
return self._payload('config', 'list', '--paged', '--page-size=8', '--output=json')
async def get_config_diagnostics(self) -> object:
+ """
+ 提供用于界面测试的系统配置的诊断结果。
+
+ :return: 用于界面测试的系统配置的诊断结果
+ """
return self._payload('config', 'doctor', '--sample-limit=5', '--output=json')
async def get_config_detail(self, config_key: str) -> object:
+ """
+ 提供用于界面测试的指定系统参数的详情。
+
+ :param config_key: 用于查找配置项的键
+ :return: 用于界面测试的指定系统参数的详情
+ """
return self._payload('config', 'get', config_key, '--source=both', '--output=json')
@pytest.fixture
def install_query_service() -> Callable[[ModuleType, Callable[..., object]], RuntimeQueryStub]:
- """向适配器及其采集/分区协作对象注入异步查询桩。"""
+ """
+ 向适配器及其采集/分区协作对象注入异步查询桩。
+
+ :return: 供调用方使用的 ``install``
+ """
def install(module: ModuleType, runner: Callable[..., object]) -> RuntimeQueryStub:
+ """
+ 安装测试使用的运行时查询适配器。
+
+ :param module: 提供被测功能的模块
+ :param runner: 执行命令或后台任务的对象
+ :return: 供调用方使用的 ``query_service``
+ """
query_service = RuntimeQueryStub(runner)
visited: set[int] = set()
def inject(target: object) -> None:
+ """
+ 将查询替身注入待测试的组件。
+
+ :param target: 本次操作的目标
+ """
if id(target) in visited:
return
visited.add(id(target))
@@ -148,6 +350,12 @@ def inject(target: object) -> None:
def _load_adapter_module(module_name: str) -> ModuleType:
+ """
+ 重新导入测试需要的 TUI 适配器。
+
+ :param module_name: 生成模块名
+ :return: 重新加载的终端界面适配器模块
+ """
sys.modules.pop(module_name, None)
sys.modules.pop('cli', None)
return importlib.import_module(module_name)
@@ -155,51 +363,101 @@ def _load_adapter_module(module_name: str) -> ModuleType:
@pytest.fixture
def app_adapter() -> ModuleType:
+ """
+ 为测试加载 ``cli.tui.adapters.app`` 模块。
+
+ :return: 应用页面的适配器模块
+ """
return _load_adapter_module('cli.tui.adapters.app')
@pytest.fixture
def cache_adapter() -> ModuleType:
+ """
+ 为测试加载 ``cli.tui.adapters.cache`` 模块。
+
+ :return: 缓存页面的适配器模块
+ """
return _load_adapter_module('cli.tui.adapters.cache')
@pytest.fixture
def crypto_adapter() -> ModuleType:
+ """
+ 为测试加载 ``cli.tui.adapters.crypto`` 模块。
+
+ :return: 加密页面的适配器模块
+ """
return _load_adapter_module('cli.tui.adapters.crypto')
@pytest.fixture
def database_adapter() -> ModuleType:
+ """
+ 为测试加载 ``cli.tui.adapters.database`` 模块。
+
+ :return: 数据库页面的适配器模块
+ """
return _load_adapter_module('cli.tui.adapters.database')
@pytest.fixture
def jobs_adapter() -> ModuleType:
+ """
+ 为测试加载 ``cli.tui.adapters.jobs`` 模块。
+
+ :return: 任务页面的适配器模块
+ """
return _load_adapter_module('cli.tui.adapters.jobs')
@pytest.fixture
def gen_adapter() -> ModuleType:
+ """
+ 为测试加载 ``cli.tui.adapters.gen`` 模块。
+
+ :return: 生成器页面的适配器模块
+ """
return _load_adapter_module('cli.tui.adapters.gen')
@pytest.fixture
def configs_adapter() -> ModuleType:
+ """
+ 为测试加载 ``cli.tui.adapters.configs`` 模块。
+
+ :return: 配置页面的适配器模块
+ """
return _load_adapter_module('cli.tui.adapters.configs')
@pytest.fixture
def ops_adapter() -> ModuleType:
+ """
+ 为测试加载 ``cli.tui.adapters.ops`` 模块。
+
+ :return: 运维页面的适配器模块
+ """
return _load_adapter_module('cli.tui.adapters.ops')
@pytest.fixture
def health_adapter() -> ModuleType:
+ """
+ 为测试加载 ``cli.tui.adapters.health`` 模块。
+
+ :return: 健康检查页面的适配器模块
+ """
return _load_adapter_module('cli.tui.adapters.health')
@pytest.fixture
def load_adapter_module() -> Callable[[str], ModuleType]:
+ """
+ 向调用方返回 ``_load_adapter_module``。
+
+ :return: 加载终端界面适配器的函数
+ """
return _load_adapter_module
@@ -213,7 +471,7 @@ def dispose_async_db_engine_after_test() -> None:
SQLAlchemy 未归还连接告警。这里统一在测试后主动释放注册表资源,将清理职责
收口到测试夹具而非业务代码。
- :return: None
+ :yield: 上下文就绪后将控制权交给调用方
"""
yield
database_module = sys.modules.get('config.database')
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_app_ops_snapshots.py b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_app_ops_snapshots.py
index 6591ba0ed..4cadbbde3 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_app_ops_snapshots.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_app_ops_snapshots.py
@@ -11,7 +11,16 @@ async def test_collect_app_page_snapshot_builds_env_config_and_route_sections(
app_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """应用快照包含环境、配置和路由分区。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``app env``、``app config``、``app routes`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('app', 'env'):
return SimpleNamespace(
@@ -174,7 +183,16 @@ async def test_collect_app_page_snapshot_applies_query_filter(
app_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """应用快照按查询条件过滤。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``app env``、``app config``、``completion doctor`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('app', 'env'):
return SimpleNamespace(payload={'ok': True, 'runtime': {'cliEnv': 'dev', 'configEnv': 'dev'}})
@@ -234,7 +252,16 @@ async def test_collect_ops_page_snapshot_builds_health_dependency_and_server_sec
ops_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """运维快照包含健康、依赖和服务器分区。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``ops health``、``ops ping-db``、``ops ping-redis`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('ops', 'health'):
return SimpleNamespace(
@@ -329,7 +356,16 @@ async def test_collect_ops_page_snapshot_surfaces_health_risk_subtitle(
ops_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """运维快照在副标题显示健康风险。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``ops health``、``ops ping-db``、``ops ping-redis`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('ops', 'health'):
return SimpleNamespace(
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_cache_db_crypto_snapshots.py b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_cache_db_crypto_snapshots.py
index 236c97883..9a0e1466b 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_cache_db_crypto_snapshots.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_cache_db_crypto_snapshots.py
@@ -11,9 +11,17 @@ async def test_collect_cache_page_snapshot_builds_cache_browser_records(
cache_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """缓存快照生成可浏览的记录。"""
calls: list[tuple[str, ...]] = []
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``cache stats``、``cache keys``、``cache get`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
calls.append(arguments)
if arguments[0:2] == ('cache', 'stats'):
@@ -99,7 +107,16 @@ async def test_cache_browser_adapter_collect_snapshot_exposes_search_context(
cache_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """缓存浏览器快照提供搜索上下文。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``cache stats`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('cache', 'stats'):
return SimpleNamespace(
@@ -135,7 +152,16 @@ async def test_collect_database_page_snapshot_builds_check_heads_and_history_sec
database_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """数据库快照包含检查、迁移头和历史分区。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``db current``、``db check``、``db heads`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('db', 'current'):
return SimpleNamespace(payload={'ok': True, 'currentRevision': '202604300001'})
@@ -239,7 +265,16 @@ async def test_collect_database_page_snapshot_surfaces_failed_heads(
database_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """数据库快照显示异常迁移头。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``db current``、``db check``、``db heads`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('db', 'current'):
return SimpleNamespace(payload={'ok': True, 'currentRevision': '202604300001'})
@@ -280,7 +315,16 @@ async def test_collect_database_page_snapshot_applies_query_filter(
database_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """数据库快照按查询条件过滤。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``db current``、``db check``、``db heads`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('db', 'current'):
return SimpleNamespace(payload={'ok': True, 'currentRevision': '202604300001'})
@@ -313,7 +357,16 @@ async def test_collect_crypto_page_snapshot_builds_validate_and_public_key_secti
crypto_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """加密快照显示校验结果和公钥。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``crypto validate`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('crypto', 'validate'):
return SimpleNamespace(
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_configs_dashboard_snapshots.py b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_configs_dashboard_snapshots.py
index 2107191e3..6f220bc2b 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_configs_dashboard_snapshots.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_configs_dashboard_snapshots.py
@@ -11,7 +11,16 @@ async def test_collect_dashboard_snapshot_adds_risk_heat_panel(
health_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """仪表盘快照包含风险热度面板。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``app env``、``app doctor``、``app routes`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('app', 'env'):
return SimpleNamespace(
@@ -126,7 +135,16 @@ async def test_dashboard_adapter_collect_snapshot_exposes_metrics(
health_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """仪表盘适配器快照提供指标。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``app env``、``app routes``、``app doctor`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('app', 'env'):
return SimpleNamespace(payload={'ok': True, 'runtime': {'cliEnv': 'dev', 'configEnv': 'dev'}})
@@ -166,7 +184,16 @@ async def test_collect_dashboard_snapshot_uses_focus_hints_for_healthy_business_
health_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """业务入口健康时仪表盘提供焦点提示。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``app env``、``app routes``、``app doctor`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('app', 'env'):
return SimpleNamespace(payload={'ok': True, 'runtime': {'cliEnv': 'dev', 'configEnv': 'dev'}})
@@ -217,7 +244,16 @@ async def test_collect_configs_page_snapshot_surfaces_failure_message(
configs_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """配置快照显示失败原因。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 按子命令返回预设的 CLI 输出,供 TUI 生成快照。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: ``SimpleNamespace`` 实例
+ """
del arguments, parse_json
return SimpleNamespace(
payload={
@@ -246,7 +282,16 @@ async def test_configs_browser_adapter_collect_snapshot_exposes_search_context(
configs_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """配置浏览器快照提供搜索上下文。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``config doctor``、``config list`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('config', 'doctor'):
return SimpleNamespace(
@@ -299,9 +344,17 @@ async def test_collect_configs_page_snapshot_builds_browser_records(
configs_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """配置快照生成可浏览的记录。"""
calls: list[tuple[str, ...]] = []
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``config doctor``、``config list`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
calls.append(arguments)
if arguments[0:2] == ('config', 'doctor'):
@@ -394,7 +447,16 @@ async def test_collect_configs_page_snapshot_sorts_and_filters_risky_records(
configs_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """配置快照对风险记录排序并过滤。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``config doctor``、``config list`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('config', 'doctor'):
return SimpleNamespace(
@@ -476,7 +538,16 @@ async def test_collect_configs_page_snapshot_applies_query_filter(
configs_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """配置快照按查询条件过滤。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``config doctor``、``config list`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('config', 'doctor'):
return SimpleNamespace(
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_jobs_gen_snapshots.py b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_jobs_gen_snapshots.py
index 90a6eecd8..7b7f21ddb 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_jobs_gen_snapshots.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_jobs_gen_snapshots.py
@@ -11,9 +11,17 @@ async def test_collect_jobs_page_snapshot_links_first_job_detail_and_logs(
jobs_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """任务快照关联首个任务的详情和日志。"""
calls: list[tuple[str, ...]] = []
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``job list``、``job detail``、``job logs`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
calls.append(arguments)
if arguments[0:2] == ('job', 'list'):
@@ -127,7 +135,16 @@ async def test_collect_jobs_page_snapshot_applies_failed_filter(
jobs_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """任务快照可筛选失败任务。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``job list``、``job logs`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('job', 'list'):
return SimpleNamespace(
@@ -200,7 +217,16 @@ async def test_collect_jobs_page_snapshot_applies_query_filter(
jobs_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """任务快照按查询条件过滤。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``job list`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('job', 'list'):
return SimpleNamespace(
@@ -244,7 +270,16 @@ async def test_collect_jobs_page_snapshot_surfaces_failure_message(
jobs_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """任务快照显示失败原因。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 按子命令返回预设的 CLI 输出,供 TUI 生成快照。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: ``SimpleNamespace`` 实例
+ """
del arguments, parse_json
return SimpleNamespace(
payload={
@@ -270,9 +305,17 @@ async def test_collect_gen_page_snapshot_links_first_table_detail(
gen_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """生成器快照关联首张表的详情。"""
calls: list[tuple[str, ...]] = []
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``gen list``、``gen detail``、``gen preview`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
calls.append(arguments)
if arguments[0:2] == ('gen', 'list'):
@@ -427,7 +470,16 @@ async def test_gen_browser_adapter_collect_snapshot_exposes_search_context(
gen_adapter: ModuleType,
install_query_service: Callable[[ModuleType, Callable[..., object]], object],
) -> None:
+ """生成器浏览器快照提供搜索上下文。"""
+
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``gen list`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 指定子命令在此测试场景的模拟响应
+ """
del parse_json
if arguments[0:2] == ('gen', 'list'):
return SimpleNamespace(
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/conftest.py b/ruoyi-fastapi-backend/tests/cli/tui/conftest.py
index 16c69b465..d97d0c1ee 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/conftest.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/conftest.py
@@ -9,12 +9,18 @@
def _ensure_backend_on_path() -> None:
+ """将后端根目录加入测试进程的导入路径。"""
if str(BACKEND_DIR) not in sys.path:
sys.path.insert(0, str(BACKEND_DIR))
@pytest.fixture
def tui_base_modules() -> SimpleNamespace:
+ """
+ 重新加载终端界面的基础模块。
+
+ :return: ``SimpleNamespace`` 实例
+ """
_ensure_backend_on_path()
sys.modules.pop('cli.main', None)
sys.modules.pop('cli.tui.commands', None)
@@ -34,6 +40,12 @@ def tui_base_modules() -> SimpleNamespace:
@pytest.fixture
def tui_modules(tui_base_modules: SimpleNamespace) -> SimpleNamespace:
+ """
+ 加载并隔离依赖 Textual 的界面模块。
+
+ :param tui_base_modules: 重新加载终端界面的基础模块
+ :return: 并隔离依赖 Textual 的界面模块
+ """
pytest.importorskip('textual')
_ensure_backend_on_path()
for module_name in (
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_browser_screen.py b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_browser_screen.py
index f3ea35ca7..ffc89c4b7 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_browser_screen.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_browser_screen.py
@@ -6,6 +6,7 @@
def test_browser_screen_builds_sections_from_selected_record(tui_modules: SimpleNamespace) -> None:
+ """浏览界面按选中记录生成分区。"""
snapshot = tui_modules.cli_tui_adapters.BrowserPageSnapshot(
title='Jobs',
subtitle='subtitle',
@@ -43,6 +44,7 @@ def test_browser_screen_builds_sections_from_selected_record(tui_modules: Simple
def test_browser_screen_resolves_job_actions(tui_modules: SimpleNamespace) -> None:
+ """浏览界面解析任务操作。"""
snapshot = tui_modules.cli_tui_adapters.BrowserPageSnapshot(
title='Jobs',
subtitle='subtitle',
@@ -79,6 +81,7 @@ def test_browser_screen_resolves_job_actions(tui_modules: SimpleNamespace) -> No
def test_browser_screen_builds_action_panel_with_feedback(tui_modules: SimpleNamespace) -> None:
+ """浏览界面的操作面板显示反馈。"""
snapshot = tui_modules.cli_tui_adapters.BrowserPageSnapshot(
title='Jobs',
subtitle='subtitle',
@@ -116,6 +119,7 @@ async def test_browser_screen_executes_action_without_suspending_app(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """浏览界面执行操作时保持应用运行。"""
snapshot = tui_modules.cli_tui_adapters.BrowserPageSnapshot(
title='代码生成',
subtitle='subtitle',
@@ -147,7 +151,7 @@ async def test_browser_screen_executes_action_without_suspending_app(
assert action is not None
def refresh_current_view() -> None:
- pass
+ """记录当前视图的刷新请求。"""
fake_app = SimpleNamespace(
action_refresh_current_view=refresh_current_view,
@@ -171,7 +175,8 @@ def refresh_current_view() -> None:
monkeypatch.setattr(screen, 'notify', lambda *args, **kwargs: None)
async def fake_render_record_detail() -> None:
- return None
+ """完成无需返回值的回调。"""
+ return
monkeypatch.setattr(screen, '_render_record_detail', fake_render_record_detail)
@@ -184,6 +189,7 @@ def test_browser_screen_filter_shortcut_remembers_and_refreshes(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """筛选快捷键记住选择并刷新视图。"""
snapshot = tui_modules.cli_tui_adapters.BrowserPageSnapshot(
title='任务',
subtitle='subtitle',
@@ -227,7 +233,14 @@ def test_browser_screen_filter_shortcut_remembers_and_refreshes(
async def test_browser_screen_detail_loader_failure_falls_back_to_failure_section(
tui_modules: SimpleNamespace,
) -> None:
+ """详情加载失败时浏览界面显示错误分区。"""
+
async def failing_loader() -> list[object]:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :raises RuntimeError: 模拟加载详情失败
+ """
raise RuntimeError('boom')
snapshot = tui_modules.cli_tui_adapters.BrowserPageSnapshot(
@@ -257,6 +270,7 @@ async def failing_loader() -> list[object]:
rendered_calls: list[bool] = []
async def fake_render_record_detail() -> None:
+ """记录详情渲染请求并返回测试指定的内容。"""
rendered_calls.append(True)
screen._render_record_detail = fake_render_record_detail # type: ignore[method-assign]
@@ -278,6 +292,7 @@ def test_browser_screen_search_submit_remembers_and_refreshes(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """提交搜索时记住查询并刷新视图。"""
snapshot = tui_modules.cli_tui_adapters.BrowserPageSnapshot(
title='任务',
subtitle='subtitle',
@@ -316,6 +331,7 @@ def test_browser_screen_search_submit_remembers_and_refreshes(
def test_browser_screen_support_builds_summary_actions_and_fallbacks(
tui_modules: SimpleNamespace,
) -> None:
+ """浏览界面生成摘要操作及后备选项。"""
support = tui_modules.cli_tui_browser.BrowserScreenSupport()
snapshot = tui_modules.cli_tui_adapters.BrowserPageSnapshot(
title='任务',
@@ -369,6 +385,7 @@ def test_browser_screen_support_builds_summary_actions_and_fallbacks(
def test_browser_screen_focus_service_moves_and_scrolls_between_focus_targets(
tui_modules: SimpleNamespace,
) -> None:
+ """浏览界面在焦点目标间移动并滚动。"""
focus_service = tui_modules.cli_tui_browser.BrowserScreenFocusService()
focused: list[str] = []
sidebar = SimpleNamespace(focus=lambda: focused.append('sidebar'))
@@ -404,6 +421,7 @@ def test_browser_screen_clear_search_remembers_empty_and_refreshes(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """清空搜索时保存空查询并刷新视图。"""
snapshot = tui_modules.cli_tui_adapters.BrowserPageSnapshot(
title='任务',
subtitle='subtitle',
@@ -440,6 +458,7 @@ def test_browser_screen_clear_search_remembers_empty_and_refreshes(
def test_browser_screen_unmount_cancels_background_tasks(tui_modules: SimpleNamespace) -> None:
+ """卸载浏览界面时取消后台任务。"""
snapshot = tui_modules.cli_tui_adapters.BrowserPageSnapshot(
title='缓存',
subtitle='subtitle',
@@ -457,13 +476,30 @@ def test_browser_screen_unmount_cancels_background_tasks(tui_modules: SimpleName
cancelled: list[str] = []
class DummyTask:
+ """
+ 保存任务名称并记录取消操作。
+
+ :ivar name: 用于查找或标识当前对象的名称
+ """
+
def __init__(self, name: str) -> None:
+ """
+ 初始化测试夹具的 ``name``。
+
+ :param name: 用于查找或标识当前对象的名称
+ """
self.name = name
def done(self) -> bool:
+ """
+ 在此测试分支返回 False。
+
+ :return: 此分支的固定值 ``False``
+ """
return False
def cancel(self) -> None:
+ """记录任务的取消请求。"""
cancelled.append(self.name)
screen._record_detail_task = DummyTask('detail') # type: ignore[assignment]
@@ -477,6 +513,7 @@ def cancel(self) -> None:
def test_browser_screen_failure_sections_use_current_snapshot_title(tui_modules: SimpleNamespace) -> None:
+ """错误分区使用当前快照标题。"""
snapshot = tui_modules.cli_tui_adapters.BrowserPageSnapshot(
title='缓存',
subtitle='subtitle',
@@ -498,6 +535,7 @@ def test_browser_screen_failure_sections_use_current_snapshot_title(tui_modules:
@pytest.mark.asyncio
async def test_browser_screen_scrolls_in_small_viewport(tui_modules: SimpleNamespace) -> None:
+ """小视口中的浏览界面可以滚动。"""
thin_scrollbar_size = 1
app = tui_modules.cli_tui_app.RuoyiTuiApp('dev')
app.action_show_dashboard = lambda: None # type: ignore[method-assign]
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_command_app.py b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_command_app.py
index 1d2739e35..be7d580c4 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_command_app.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_command_app.py
@@ -13,10 +13,18 @@ def test_tui_command_returns_dependency_error_when_textual_missing(
monkeypatch: MonkeyPatch,
tui_base_modules: SimpleNamespace,
) -> None:
+ """缺少 Textual 时终端界面命令报告依赖错误。"""
runner = CliRunner()
monkeypatch.chdir(tui_base_modules.BACKEND_DIR)
def raise_missing_textual(module_name: str) -> Any:
+ """
+ 模拟缺少终端界面依赖。
+
+ :param module_name: 生成模块名
+ :raises ModuleNotFoundError: 模拟未安装 Textual
+ :return: 可正常导入的模块,缺少 Textual 时抛出导入异常
+ """
if module_name == 'cli.tui.app':
raise ModuleNotFoundError("No module named 'textual'", name='textual')
return importlib.import_module(module_name)
@@ -37,9 +45,20 @@ async def test_tui_app_mount_pushes_first_workspace_screen(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """终端应用挂载后打开首个工作区。"""
recorded_calls: list[tuple[str, object]] = []
class FakeDashboardScreen:
+ """
+ 捕获仪表盘的初始快照和导航选项。
+
+ :ivar snapshot: 用于比较状态的快照
+ :ivar env: 当前运行环境
+ :ivar active_view: 当前激活视图
+ :ivar navigation_items: 导航项列表
+ :ivar refreshed_at: 本次刷新时间
+ """
+
def __init__(
self,
snapshot: object,
@@ -48,6 +67,15 @@ def __init__(
navigation_items: list[object],
refreshed_at: str,
) -> None:
+ """
+ 初始化测试夹具的 ``snapshot``, ``env``, ``active_view``, ``navigation_items``。
+
+ :param snapshot: 用于比较状态的快照
+ :param env: 当前运行环境
+ :param active_view: 当前激活视图
+ :param navigation_items: 导航项列表
+ :param refreshed_at: 本次刷新时间
+ """
self.snapshot = snapshot
self.env = env
self.active_view = active_view
@@ -55,6 +83,12 @@ def __init__(
self.refreshed_at = refreshed_at
async def collect_dashboard(env: str) -> object:
+ """
+ 返回仪表盘视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :return: 仪表盘视图使用的测试快照
+ """
return tui_modules.cli_tui_app.DashboardSnapshot(env=env, panels=[])
monkeypatch.setitem(
@@ -83,10 +117,16 @@ async def collect_dashboard(env: str) -> object:
def test_open_view_switches_to_expected_action(tui_modules: SimpleNamespace) -> None:
+ """打开视图时切换到对应操作。"""
calls: list[str] = []
app = tui_modules.cli_tui_app.RuoyiTuiApp('dev')
def fake_show_view(view_key: str) -> None:
+ """
+ 记录界面切换后的视图键。
+
+ :param view_key: 选择视图所用的标识
+ """
calls.append(tui_modules.cli_tui_app.TUI_VIEW_REGISTRY.resolve_view_key(view_key))
app.show_view = fake_show_view # type: ignore[method-assign]
@@ -101,6 +141,7 @@ def fake_show_view(view_key: str) -> None:
def test_workspace_header_render_includes_particle_line(tui_modules: SimpleNamespace) -> None:
+ """工作区标题栏包含粒子装饰行。"""
header = tui_modules.cli_tui_widgets.WorkspaceHeader('dev', 'dashboard')
rendered = header.render()
@@ -113,6 +154,7 @@ def test_workspace_header_render_includes_particle_line(tui_modules: SimpleNames
def test_workspace_header_centers_title_using_runtime_width(tui_modules: SimpleNamespace) -> None:
+ """工作区标题按运行时宽度居中。"""
header = tui_modules.cli_tui_widgets.WorkspaceHeader('dev', 'dashboard')
header.styles.width = 140
@@ -126,6 +168,7 @@ def test_workspace_header_keeps_title_alignment_stable_across_frames(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """工作区标题在不同帧间保持对齐。"""
header = tui_modules.cli_tui_widgets.WorkspaceHeader('dev', 'dashboard')
monotonic_values = iter([10.0, 10.0, 11.0, 11.0])
workspace_module = importlib.import_module('cli.tui.widgets.workspace')
@@ -141,6 +184,7 @@ def test_workspace_hero_pulses_border_with_expected_palette(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """工作区主面板边框使用约定配色闪动。"""
hero = tui_modules.cli_tui_widgets.WorkspaceHero(
title='标题',
subtitle='副标题',
@@ -162,6 +206,7 @@ def test_workspace_hero_pulses_border_with_expected_palette(
def test_workspace_hero_render_uses_rich_text_for_title_glow(tui_modules: SimpleNamespace) -> None:
+ """工作区主面板以富文本渲染标题光效。"""
hero = tui_modules.cli_tui_widgets.WorkspaceHero(
title='标题',
subtitle='副标题',
@@ -180,14 +225,23 @@ def test_workspace_hero_render_uses_rich_text_for_title_glow(tui_modules: Simple
def test_tui_app_runner_runs_created_application(tui_modules: SimpleNamespace) -> None:
+ """终端运行器启动创建好的应用。"""
recorded_envs: list[str] = []
recorded_runs: list[str] = []
class FakeApp:
+ """记录终端应用使用的运行环境。"""
+
def __init__(self, env: str) -> None:
+ """
+ 记录构造测试对象时收到的参数。
+
+ :param env: 当前运行环境
+ """
recorded_envs.append(env)
def run(self) -> None:
+ """记录测试命令的运行参数。"""
recorded_runs.append('run')
runner = tui_modules.cli_tui_app.TuiAppRunner(FakeApp)
@@ -203,12 +257,21 @@ async def test_tui_app_show_jobs_uses_remembered_filter(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """任务视图使用上次的筛选条件。"""
recorded_filter_keys: list[tuple[str, str]] = []
app = tui_modules.cli_tui_app.RuoyiTuiApp('dev')
app.remember_browser_filter('jobs', 'failed')
app.remember_browser_query('jobs', 'sync')
async def collect_jobs(env: str, filter_key: str = 'all', query: str = '') -> object:
+ """
+ 返回调度任务视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param filter_key: 当前筛选键
+ :param query: 限制查询结果的条件
+ :return: 调度任务视图使用的测试快照
+ """
del env
recorded_filter_keys.append((filter_key, query))
return tui_modules.cli_tui_app.BrowserPageSnapshot(
@@ -238,12 +301,21 @@ async def test_tui_app_show_configs_uses_remembered_filter(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """配置视图使用上次的筛选条件。"""
recorded_filter_keys: list[tuple[str, str]] = []
app = tui_modules.cli_tui_app.RuoyiTuiApp('dev')
app.remember_browser_filter('configs', 'cache-drift')
app.remember_browser_query('configs', 'site')
async def collect_configs(env: str, filter_key: str = 'all', query: str = '') -> object:
+ """
+ 返回配置视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param filter_key: 当前筛选键
+ :param query: 限制查询结果的条件
+ :return: 配置视图使用的测试快照
+ """
del env
recorded_filter_keys.append((filter_key, query))
return tui_modules.cli_tui_app.BrowserPageSnapshot(
@@ -273,6 +345,7 @@ async def test_tui_app_show_cache_and_gen_use_remembered_query(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """缓存和生成器视图沿用上次查询。"""
cache_queries: list[str] = []
gen_queries: list[str] = []
app = tui_modules.cli_tui_app.RuoyiTuiApp('dev')
@@ -280,6 +353,13 @@ async def test_tui_app_show_cache_and_gen_use_remembered_query(
app.remember_browser_query('gen', 'user')
async def collect_cache(env: str, query: str = '') -> object:
+ """
+ 返回缓存视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 缓存视图使用的测试快照
+ """
del env
cache_queries.append(query)
return tui_modules.cli_tui_app.BrowserPageSnapshot(
@@ -293,6 +373,13 @@ async def collect_cache(env: str, query: str = '') -> object:
)
async def collect_gen(env: str, query: str = '') -> object:
+ """
+ 返回代码生成视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 代码生成视图使用的测试快照
+ """
del env
gen_queries.append(query)
return tui_modules.cli_tui_app.BrowserPageSnapshot(
@@ -330,6 +417,7 @@ async def test_tui_app_detail_views_use_remembered_query(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """终端详情视图沿用上次查询。"""
database_queries: list[str] = []
app_queries: list[str] = []
ops_queries: list[str] = []
@@ -341,21 +429,49 @@ async def test_tui_app_detail_views_use_remembered_query(
app.remember_browser_query('crypto', 'kid')
async def collect_database(env: str, query: str = '') -> object:
+ """
+ 返回数据库视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 数据库视图使用的测试快照
+ """
del env
database_queries.append(query)
return tui_modules.cli_tui_app.DetailPageSnapshot(title='数据库', subtitle='subtitle', sections=[])
async def collect_app(env: str, query: str = '') -> object:
+ """
+ 返回应用视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 应用视图使用的测试快照
+ """
del env
app_queries.append(query)
return tui_modules.cli_tui_app.DetailPageSnapshot(title='应用', subtitle='subtitle', sections=[])
async def collect_ops(env: str, query: str = '') -> object:
+ """
+ 返回运维视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 运维视图使用的测试快照
+ """
del env
ops_queries.append(query)
return tui_modules.cli_tui_app.DetailPageSnapshot(title='运维', subtitle='subtitle', sections=[])
async def collect_crypto(env: str, query: str = '') -> object:
+ """
+ 返回加密配置视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 加密配置视图使用的测试快照
+ """
del env
crypto_queries.append(query)
return tui_modules.cli_tui_app.DetailPageSnapshot(title='传输加密', subtitle='subtitle', sections=[])
@@ -401,10 +517,25 @@ async def test_tui_app_open_view_updates_screen_across_multiple_switches(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """多次切换视图时终端应用更新画面。"""
+
async def collect_dashboard(env: str) -> object:
+ """
+ 返回仪表盘视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :return: 仪表盘视图使用的测试快照
+ """
return tui_modules.cli_tui_app.DashboardSnapshot(env=env, panels=[])
async def collect_app(env: str, query: str = '') -> object:
+ """
+ 返回应用视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 应用视图使用的测试快照
+ """
del env
return tui_modules.cli_tui_app.DetailPageSnapshot(
title='应用详情',
@@ -419,6 +550,13 @@ async def collect_app(env: str, query: str = '') -> object:
)
async def collect_ops(env: str, query: str = '') -> object:
+ """
+ 返回运维视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 运维视图使用的测试快照
+ """
del env
return tui_modules.cli_tui_app.DetailPageSnapshot(
title='运维详情',
@@ -478,10 +616,25 @@ async def test_tui_sidebar_highlight_updates_screen_across_multiple_switches(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """多次切换侧栏高亮时更新画面。"""
+
async def collect_dashboard(env: str) -> object:
+ """
+ 返回仪表盘视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :return: 仪表盘视图使用的测试快照
+ """
return tui_modules.cli_tui_app.DashboardSnapshot(env=env, panels=[])
async def collect_app(env: str, query: str = '') -> object:
+ """
+ 返回应用视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 应用视图使用的测试快照
+ """
del env, query
return tui_modules.cli_tui_app.DetailPageSnapshot(
title='应用详情',
@@ -496,6 +649,13 @@ async def collect_app(env: str, query: str = '') -> object:
)
async def collect_ops(env: str, query: str = '') -> object:
+ """
+ 返回运维视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 运维视图使用的测试快照
+ """
del env, query
return tui_modules.cli_tui_app.DetailPageSnapshot(
title='运维详情',
@@ -555,13 +715,27 @@ async def test_navigation_cancels_stale_load_and_only_renders_latest_view(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """导航取消过期加载并只渲染最新视图。"""
app_started = asyncio.Event()
app_cancelled = asyncio.Event()
async def collect_dashboard(env: str) -> object:
+ """
+ 返回仪表盘视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :return: 仪表盘视图使用的测试快照
+ """
return tui_modules.cli_tui_app.DashboardSnapshot(env=env, panels=[])
async def collect_app(env: str, query: str = '') -> object:
+ """
+ 返回应用视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 应用视图使用的测试快照
+ """
del env, query
app_started.set()
try:
@@ -571,6 +745,13 @@ async def collect_app(env: str, query: str = '') -> object:
return tui_modules.cli_tui_app.DetailPageSnapshot(title='过期应用页', subtitle='', sections=[])
async def collect_ops(env: str, query: str = '') -> object:
+ """
+ 返回运维视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 运维视图使用的测试快照
+ """
del env, query
return tui_modules.cli_tui_app.DetailPageSnapshot(title='最新运维页', subtitle='', sections=[])
@@ -611,12 +792,26 @@ async def test_navigation_reuses_fresh_snapshot_cache(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """导航复用尚未过期的快照。"""
app_collect_count = 0
async def collect_dashboard(env: str) -> object:
+ """
+ 返回仪表盘视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :return: 仪表盘视图使用的测试快照
+ """
return tui_modules.cli_tui_app.DashboardSnapshot(env=env, panels=[])
async def collect_app(env: str, query: str = '') -> object:
+ """
+ 返回应用视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :param query: 限制查询结果的条件
+ :return: 应用视图使用的测试快照
+ """
nonlocal app_collect_count
del env, query
app_collect_count += 1
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_dashboard_search.py b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_dashboard_search.py
index cc8eb62c2..1be9580e5 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_dashboard_search.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_dashboard_search.py
@@ -4,6 +4,7 @@
def test_build_filter_bar_text_includes_search_context(tui_modules: SimpleNamespace) -> None:
+ """筛选栏文本包含搜索上下文。"""
text = tui_modules.cli_tui_search.TUI_SEARCH_SERVICE.build_filter_bar_text(
tui_modules.cli_tui_search.JOB_FILTER_OPTIONS,
'failed',
@@ -21,6 +22,7 @@ def test_build_filter_bar_text_includes_search_context(tui_modules: SimpleNamesp
def test_tui_search_service_builds_filter_context_and_section_filtering(
tui_modules: SimpleNamespace,
) -> None:
+ """终端搜索服务构建筛选上下文并过滤各分区。"""
service = tui_modules.cli_tui_search.TuiSearchService(
tui_modules.cli_tui_search.TuiSearchSuggestionProviderRegistry(
providers={
@@ -65,9 +67,16 @@ def test_tui_search_service_builds_filter_context_and_section_filtering(
def test_tui_search_service_skips_provider_when_query_is_empty(
tui_modules: SimpleNamespace,
) -> None:
+ """搜索词为空时跳过查询提供方。"""
provider_calls: list[str] = []
def record_provider(incomplete: str) -> list[str]:
+ """
+ 记录补全查询并提供候选值。
+
+ :param incomplete: 用户尚未输入完整的命令词
+ :return: 与当前补全查询匹配的候选值
+ """
provider_calls.append(incomplete)
return ['site_name']
@@ -91,6 +100,7 @@ def record_provider(incomplete: str) -> list[str]:
def test_search_highlight_helper_wraps_matches(tui_modules: SimpleNamespace) -> None:
+ """高亮包裹匹配的搜索文本。"""
highlighted = tui_modules.cli_tui_search.TUI_SEARCH_HIGHLIGHTER.highlight('sync-user job', 'sync')
assert highlighted == '【sync】-user job'
@@ -99,6 +109,7 @@ def test_search_highlight_helper_wraps_matches(tui_modules: SimpleNamespace) ->
def test_dashboard_screen_support_builds_summary_signal_and_status_track(
tui_modules: SimpleNamespace,
) -> None:
+ """仪表盘构建摘要信号和状态轨迹。"""
support = tui_modules.cli_tui_dashboard.DashboardScreenSupport()
snapshot = tui_modules.cli_tui_app.DashboardSnapshot(
env='dev',
@@ -122,6 +133,7 @@ def test_dashboard_screen_support_builds_summary_signal_and_status_track(
def test_dashboard_screen_focus_service_moves_and_scrolls_between_focus_targets(
tui_modules: SimpleNamespace,
) -> None:
+ """仪表盘在焦点目标间移动并滚动。"""
focus_service = tui_modules.cli_tui_dashboard.DashboardScreenFocusService()
focused: list[str] = []
sidebar = SimpleNamespace(focus=lambda: focused.append('sidebar'))
@@ -150,6 +162,7 @@ async def test_dashboard_grid_expands_to_fit_status_panels(
monkeypatch: pytest.MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """仪表盘网格扩展以容纳状态面板。"""
expected_dashboard_panel_count = 8
min_expanded_dashboard_grid_height = 20
snapshot = tui_modules.cli_tui_app.DashboardSnapshot(
@@ -173,6 +186,12 @@ async def test_dashboard_grid_expands_to_fit_status_panels(
)
async def collect_dashboard(env: str) -> object:
+ """
+ 返回仪表盘视图使用的测试快照。
+
+ :param env: 当前运行环境
+ :return: 仪表盘视图使用的测试快照
+ """
del env
return snapshot
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_detail_screen.py b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_detail_screen.py
index 4598c6f2b..19af9a3b3 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_detail_screen.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_detail_screen.py
@@ -7,6 +7,7 @@
def test_detail_screen_updates_section_detail_view(tui_modules: SimpleNamespace) -> None:
+ """详情界面更新分区内容。"""
snapshot = tui_modules.cli_tui_app.DetailPageSnapshot(
title='Jobs',
subtitle='subtitle',
@@ -26,7 +27,15 @@ def test_detail_screen_updates_section_detail_view(tui_modules: SimpleNamespace)
recorded_sections: list[object] = []
class FakeSectionDetailView:
+ """记录传入详情视图的区块。"""
+
def show_section(self, section: object, query: str = '') -> None:
+ """
+ 记录详情面板选中的区块。
+
+ :param section: 需要展示的详情分区
+ :param query: 限制查询结果的条件
+ """
del query
recorded_sections.append(section)
@@ -43,6 +52,7 @@ def test_detail_screen_search_submit_remembers_and_refreshes(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """提交详情搜索后记住查询并刷新。"""
snapshot = tui_modules.cli_tui_app.DetailPageSnapshot(
title='数据库',
subtitle='subtitle',
@@ -81,6 +91,7 @@ def test_detail_screen_clear_search_remembers_empty_and_refreshes(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """清空详情搜索后记住空查询并刷新。"""
snapshot = tui_modules.cli_tui_app.DetailPageSnapshot(
title='数据库',
subtitle='subtitle',
@@ -120,6 +131,7 @@ async def test_detail_screen_executes_database_preview_in_process(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """详情界面在进程内执行数据库预览。"""
snapshot = tui_modules.cli_tui_app.DetailPageSnapshot(
title='数据库',
subtitle='subtitle',
@@ -142,7 +154,7 @@ async def test_detail_screen_executes_database_preview_in_process(
assert action is not None
def refresh_current_view() -> None:
- pass
+ """记录当前视图的刷新请求。"""
fake_app = SimpleNamespace(
action_refresh_current_view=refresh_current_view,
@@ -175,6 +187,7 @@ async def test_detail_screen_executes_crypto_action_without_suspend(
monkeypatch: MonkeyPatch,
tui_modules: SimpleNamespace,
) -> None:
+ """详情界面执行加密操作时保持运行。"""
snapshot = tui_modules.cli_tui_app.DetailPageSnapshot(
title='传输加密',
subtitle='subtitle',
@@ -199,7 +212,10 @@ async def test_detail_screen_executes_crypto_action_without_suspend(
execute_calls: list[tuple[object, str]] = []
class DummySuspend:
+ """提供界面挂起期间使用的上下文管理器。"""
+
def __enter__(self) -> None:
+ """进入测试使用的上下文并返回资源。"""
suspend_calls.append('enter')
def __exit__(
@@ -208,14 +224,26 @@ def __exit__(
exc: BaseException | None,
tb: Any,
) -> None:
+ """
+ 结束测试资源的上下文。
+
+ :param exc_type: 退出上下文时的异常类型
+ :param exc: 捕获到的异常实例
+ :param tb: 异常发生时的回溯信息
+ """
del exc_type, exc, tb
suspend_calls.append('exit')
def build_suspend() -> DummySuspend:
+ """
+ 创建测试使用的 ``DummySuspend`` 实例。
+
+ :return: 测试使用的 ``DummySuspend`` 实例
+ """
return DummySuspend()
def refresh_current_view() -> None:
- pass
+ """记录当前视图的刷新请求。"""
fake_app = SimpleNamespace(
suspend=build_suspend,
@@ -251,6 +279,7 @@ def refresh_current_view() -> None:
def test_detail_screen_support_builds_summary_actions_and_fallbacks(
tui_modules: SimpleNamespace,
) -> None:
+ """详情界面构建摘要操作及后备选项。"""
support = tui_modules.cli_tui_detail.DetailScreenSupport()
snapshot = tui_modules.cli_tui_app.DetailPageSnapshot(
title='数据库',
@@ -282,6 +311,7 @@ def test_detail_screen_support_builds_summary_actions_and_fallbacks(
def test_detail_screen_focus_service_moves_and_scrolls_between_focus_targets(
tui_modules: SimpleNamespace,
) -> None:
+ """详情界面在焦点目标间移动并滚动。"""
focus_service = tui_modules.cli_tui_detail.DetailScreenFocusService()
focused: list[str] = []
sidebar = SimpleNamespace(focus=lambda: focused.append('sidebar'))
@@ -310,6 +340,7 @@ def test_detail_screen_focus_service_moves_and_scrolls_between_focus_targets(
def test_detail_screen_unmount_cancels_action_task(tui_modules: SimpleNamespace) -> None:
+ """卸载详情界面时取消操作任务。"""
snapshot = tui_modules.cli_tui_app.DetailPageSnapshot(
title='数据库',
subtitle='subtitle',
@@ -326,10 +357,18 @@ def test_detail_screen_unmount_cancels_action_task(tui_modules: SimpleNamespace)
cancelled: list[str] = []
class DummyTask:
+ """保存任务名称并记录取消操作。"""
+
def done(self) -> bool:
+ """
+ 在此测试分支返回 False。
+
+ :return: 此分支的固定值 ``False``
+ """
return False
def cancel(self) -> None:
+ """记录任务的取消请求。"""
cancelled.append('action')
screen._action_task = DummyTask() # type: ignore[assignment]
@@ -341,6 +380,7 @@ def cancel(self) -> None:
@pytest.mark.asyncio
async def test_detail_screen_scrolls_in_small_viewport(tui_modules: SimpleNamespace) -> None:
+ """小视口中的详情界面可以滚动。"""
thin_scrollbar_size = 1
app = tui_modules.cli_tui_app.RuoyiTuiApp('dev')
app.action_show_dashboard = lambda: None # type: ignore[method-assign]
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_platform.py b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_platform.py
index dd0bd358b..7be40260e 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_platform.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_platform.py
@@ -4,6 +4,7 @@
def test_windows_enables_reduced_motion_by_default(monkeypatch: MonkeyPatch) -> None:
+ """Windows 默认减少动画。"""
monkeypatch.delenv('RUOYI_TUI_REDUCED_MOTION', raising=False)
monkeypatch.setattr(platform_module.sys, 'platform', 'win32')
@@ -13,6 +14,7 @@ def test_windows_enables_reduced_motion_by_default(monkeypatch: MonkeyPatch) ->
def test_reduced_motion_environment_override_wins(monkeypatch: MonkeyPatch) -> None:
+ """环境变量优先决定是否减少动画。"""
monkeypatch.setattr(platform_module.sys, 'platform', 'win32')
monkeypatch.setenv('RUOYI_TUI_REDUCED_MOTION', 'off')
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_queries.py b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_queries.py
index 3a61913e8..26ec0fe4a 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_queries.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_queries.py
@@ -8,10 +8,16 @@
@pytest.mark.asyncio
async def test_remote_query_timeout_returns_standard_failure() -> None:
+ """远程查询超时后返回标准错误。"""
executor = TuiQueryExecutor(remote_timeout_seconds=0.01)
cancelled = asyncio.Event()
async def slow_query() -> dict[str, object]:
+ """
+ 模拟超时场景中的慢查询。
+
+ :return: 包含 ``ok`` 的数据
+ """
try:
await asyncio.sleep(10)
finally:
@@ -28,11 +34,17 @@ async def slow_query() -> dict[str, object]:
@pytest.mark.asyncio
async def test_cancelled_local_query_does_not_release_capacity_until_thread_finishes() -> None:
+ """取消本地查询后等待线程结束才释放容量。"""
executor = TuiQueryExecutor(local_timeout_seconds=0.1)
started = Event()
finish = Event()
def blocking_query() -> dict[str, object]:
+ """
+ 暂停查询以便测试任务超时和取消。
+
+ :return: 包含 ``ok`` 的数据
+ """
started.set()
finish.wait(timeout=2)
return {'ok': True}
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/conftest.py b/ruoyi-fastapi-backend/tests/cli/wizard/conftest.py
index 29f10f874..f1629ff3b 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/conftest.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/conftest.py
@@ -13,6 +13,12 @@
def _load_module(module_name: str) -> ModuleType:
+ """
+ 清除已有导入并重新加载指定模块。
+
+ :param module_name: 生成模块名
+ :return: 重新导入的模块对象
+ """
sys.modules.pop(module_name, None)
sys.modules.pop('cli', None)
return importlib.import_module(module_name)
@@ -20,49 +26,107 @@ def _load_module(module_name: str) -> ModuleType:
@pytest.fixture
def backend_dir() -> Path:
+ """
+ 向调用方返回 ``BACKEND_DIR``。
+
+ :return: 测试使用的后端工程根目录
+ """
return BACKEND_DIR
@pytest.fixture
def load_module() -> Callable[[str], ModuleType]:
+ """
+ 向调用方返回 ``_load_module``。
+
+ :return: 按名称重新加载模块的函数
+ """
return _load_module
@pytest.fixture
def cli_main(load_module: Callable[[str], ModuleType]) -> ModuleType:
+ """
+ 为测试加载 ``cli.main`` 模块。
+
+ :param load_module: 按名称加载测试模块的回调
+ :return: CLI 主入口模块
+ """
return load_module('cli.main')
@pytest.fixture
def app_run_flow(load_module: Callable[[str], ModuleType]) -> ModuleType:
+ """
+ 为测试加载 ``cli.wizard.flows.app_run`` 模块。
+
+ :param load_module: 按名称加载测试模块的回调
+ :return: 启动应用向导模块
+ """
return load_module('cli.wizard.flows.app_run')
@pytest.fixture
def cache_clear_flow(load_module: Callable[[str], ModuleType]) -> ModuleType:
+ """
+ 为测试加载 ``cli.wizard.flows.cache_clear`` 模块。
+
+ :param load_module: 按名称加载测试模块的回调
+ :return: 清理缓存向导模块
+ """
return load_module('cli.wizard.flows.cache_clear')
@pytest.fixture
def db_upgrade_flow(load_module: Callable[[str], ModuleType]) -> ModuleType:
+ """
+ 为测试加载 ``cli.wizard.flows.db_upgrade`` 模块。
+
+ :param load_module: 按名称加载测试模块的回调
+ :return: 数据库升级向导模块
+ """
return load_module('cli.wizard.flows.db_upgrade')
@pytest.fixture
def gen_export_flow(load_module: Callable[[str], ModuleType]) -> ModuleType:
+ """
+ 为测试加载 ``cli.wizard.flows.gen_export`` 模块。
+
+ :param load_module: 按名称加载测试模块的回调
+ :return: 导出代码向导模块
+ """
return load_module('cli.wizard.flows.gen_export')
@pytest.fixture
def gen_import_flow(load_module: Callable[[str], ModuleType]) -> ModuleType:
+ """
+ 为测试加载 ``cli.wizard.flows.gen_import`` 模块。
+
+ :param load_module: 按名称加载测试模块的回调
+ :return: 导入数据表向导模块
+ """
return load_module('cli.wizard.flows.gen_import')
@pytest.fixture
def prod_check_flow(load_module: Callable[[str], ModuleType]) -> ModuleType:
+ """
+ 为测试加载 ``cli.wizard.flows.prod_check`` 模块。
+
+ :param load_module: 按名称加载测试模块的回调
+ :return: 生产检查向导模块
+ """
return load_module('cli.wizard.flows.prod_check')
@pytest.fixture
def exit_codes(load_module: Callable[[str], ModuleType]) -> ModuleType:
+ """
+ 为测试加载 ``cli.exit_codes`` 模块。
+
+ :param load_module: 按名称加载测试模块的回调
+ :return: 退出码定义模块
+ """
return load_module('cli.exit_codes')
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/test_app_run.py b/ruoyi-fastapi-backend/tests/cli/wizard/test_app_run.py
index 53552f738..473c3dee8 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/test_app_run.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/test_app_run.py
@@ -7,6 +7,7 @@ def test_app_run_wizard_execs_nested_cli_after_confirmation(
monkeypatch: MonkeyPatch,
app_run_flow: ModuleType,
) -> None:
+ """确认启动向导后执行嵌套命令。"""
captured: dict[str, object] = {}
answers = iter(['dev', False, True])
monkeypatch.setattr(
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/test_cache_clear.py b/ruoyi-fastapi-backend/tests/cli/wizard/test_cache_clear.py
index 24897bec0..4b3bdc45e 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/test_cache_clear.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/test_cache_clear.py
@@ -8,6 +8,7 @@ def test_cache_clear_wizard_cancels_when_confirmation_rejected(
cache_clear_flow: ModuleType,
exit_codes: ModuleType,
) -> None:
+ """拒绝确认后取消清缓存操作。"""
captured: dict[str, object] = {}
answers = iter(['dev', 'cache-name', 'sys_config', True, False])
monkeypatch.setattr(
@@ -43,6 +44,7 @@ def test_cache_clear_wizard_accepts_default_context_values(
monkeypatch: MonkeyPatch,
cache_clear_flow: ModuleType,
) -> None:
+ """清缓存向导接受上下文默认值。"""
captured_defaults: dict[str, object] = {}
captured_confirm_defaults: list[tuple[str, bool]] = []
answers = iter(['dev', 'cache-name', 'sys_config', True, False])
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/test_commands.py b/ruoyi-fastapi-backend/tests/cli/wizard/test_commands.py
index 8fe0ca326..525a7cc82 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/test_commands.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/test_commands.py
@@ -10,6 +10,7 @@ def test_wizard_help_lists_supported_subcommands(
backend_dir: Path,
cli_main: ModuleType,
) -> None:
+ """向导帮助列出支持的子命令。"""
runner = CliRunner()
monkeypatch.chdir(backend_dir)
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/test_db_upgrade.py b/ruoyi-fastapi-backend/tests/cli/wizard/test_db_upgrade.py
index 17e108e9b..2819e50ee 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/test_db_upgrade.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/test_db_upgrade.py
@@ -7,6 +7,7 @@ def test_db_upgrade_wizard_executes_nested_cli_with_confirmed_inputs(
monkeypatch: MonkeyPatch,
db_upgrade_flow: ModuleType,
) -> None:
+ """数据库升级向导按确认的输入执行命令。"""
captured: dict[str, object] = {}
monkeypatch.setattr(
db_upgrade_flow.DbUpgradeWizardFlow,
@@ -60,6 +61,7 @@ def test_db_upgrade_wizard_accepts_default_context_values(
monkeypatch: MonkeyPatch,
db_upgrade_flow: ModuleType,
) -> None:
+ """数据库升级向导接受上下文默认值。"""
captured_defaults: dict[str, object] = {}
captured_confirm_defaults: list[tuple[str, bool]] = []
confirm_answers = iter([True, False])
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_export.py b/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_export.py
index bfd27936c..9d96dc637 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_export.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_export.py
@@ -7,6 +7,7 @@ def test_gen_export_wizard_executes_nested_cli_with_selected_tables(
monkeypatch: MonkeyPatch,
gen_export_flow: ModuleType,
) -> None:
+ """导出向导将选中的表传给嵌套命令。"""
captured: dict[str, object] = {}
answers = iter(['dev', 'sys_user,sys_role', 'zip', 'build/demo.zip', True, True])
monkeypatch.setattr(
@@ -71,6 +72,7 @@ def test_gen_export_wizard_accepts_default_context_values(
monkeypatch: MonkeyPatch,
gen_export_flow: ModuleType,
) -> None:
+ """导出向导接受上下文默认值。"""
captured_defaults: dict[str, object] = {}
captured_confirm_defaults: list[tuple[str, bool]] = []
answers = iter(['dev', 'sys_user', 'zip', 'build/demo.zip', True, False])
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_import.py b/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_import.py
index 76336af5c..1ac0ea839 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_import.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_import.py
@@ -7,6 +7,7 @@ def test_gen_import_wizard_executes_nested_cli_with_selected_tables(
monkeypatch: MonkeyPatch,
gen_import_flow: ModuleType,
) -> None:
+ """导入向导将选中的表传给嵌套命令。"""
captured: dict[str, object] = {}
answers = iter(['dev', 'sys_user,sys_role', True, True])
monkeypatch.setattr(
@@ -66,6 +67,7 @@ def test_gen_import_wizard_accepts_default_context_values(
monkeypatch: MonkeyPatch,
gen_import_flow: ModuleType,
) -> None:
+ """导入向导接受上下文默认值。"""
captured_defaults: dict[str, object] = {}
captured_confirm_defaults: list[tuple[str, bool]] = []
answers = iter(['dev', 'sys_user', True, False])
@@ -109,6 +111,7 @@ def test_gen_import_wizard_falls_back_to_failure_payload_when_nested_result_has_
monkeypatch: MonkeyPatch,
gen_import_flow: ModuleType,
) -> None:
+ """导入命令缺少字典结果时返回失败信息。"""
captured: dict[str, object] = {}
answers = iter(['dev', 'sys_notice', True, True])
monkeypatch.setattr(
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/test_prod_check.py b/ruoyi-fastapi-backend/tests/cli/wizard/test_prod_check.py
index c956a4c86..2e9ffd725 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/test_prod_check.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/test_prod_check.py
@@ -7,6 +7,7 @@ def test_prod_check_wizard_aggregates_nested_cli_payloads(
monkeypatch: MonkeyPatch,
prod_check_flow: ModuleType,
) -> None:
+ """生产检查向导汇总嵌套命令的结果。"""
captured: dict[str, object] = {}
answers = iter(['prod', True, True])
monkeypatch.setattr(
@@ -24,6 +25,13 @@ def test_prod_check_wizard_aggregates_nested_cli_payloads(
)
def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> SimpleNamespace:
+ """
+ 为 ``app env``、``app doctor`` 等子命令提供测试输出。
+
+ :param arguments: 调用方传入的其余位置参数
+ :param parse_json: 将命令返回的 JSON 文本转换为断言使用的数据
+ :return: 生产检查向导调用子命令的模拟响应
+ """
del parse_json
if arguments[0:2] == ('app', 'env'):
return SimpleNamespace(
@@ -77,6 +85,7 @@ def test_prod_check_wizard_accepts_default_context_values(
monkeypatch: MonkeyPatch,
prod_check_flow: ModuleType,
) -> None:
+ """生产检查向导接受上下文默认值。"""
captured_defaults: dict[str, object] = {}
confirm_answers = iter([True, False])
monkeypatch.setattr(
diff --git a/ruoyi-fastapi-backend/tests/common/test_auth_policy.py b/ruoyi-fastapi-backend/tests/common/test_auth_policy.py
index 173cac0bc..d5beb14a0 100644
--- a/ruoyi-fastapi-backend/tests/common/test_auth_policy.py
+++ b/ruoyi-fastapi-backend/tests/common/test_auth_policy.py
@@ -26,7 +26,12 @@
def _run_cold_import(script: str, *arguments: str) -> None:
- """在独立进程中验证导入边界,避免已加载的模块掩盖循环依赖。"""
+ """
+ 在独立进程中验证导入边界,避免已加载的模块掩盖循环依赖。
+
+ :param script: 需要运行的脚本
+ :param arguments: 调用方传入的其余位置参数
+ """
result = subprocess.run(
[sys.executable, '-c', dedent(script), *arguments],
cwd=BACKEND_ROOT,
@@ -39,6 +44,7 @@ def _run_cold_import(script: str, *arguments: str) -> None:
def test_auth_policy_import_does_not_load_authentication_consumers() -> None:
+ """导入认证策略时无需加载认证调用方。"""
_run_cold_import(
"""
import importlib.abc
@@ -64,6 +70,7 @@ def find_spec(self, fullname, path=None, target=None):
def test_login_service_runs_without_loading_pre_auth() -> None:
+ """登录服务可在未加载预认证模块时运行。"""
_run_cold_import(
"""
import asyncio
@@ -105,6 +112,7 @@ async def check_authentication():
],
)
def test_authentication_import_order_preserves_dependency_identity(modules: tuple[str, str]) -> None:
+ """不同认证导入顺序得到同一依赖对象。"""
_run_cold_import(
"""
import importlib
@@ -140,6 +148,7 @@ def test_authentication_import_order_preserves_dependency_identity(modules: tupl
],
)
def test_authentication_import_direction_has_no_local_back_imports(relative_path: str, forbidden: set[str]) -> None:
+ """认证模块之间没有反向局部导入。"""
tree = ast.parse((BACKEND_ROOT / relative_path).read_text(encoding='utf-8'))
imported = set()
for node in ast.walk(tree):
@@ -153,12 +162,18 @@ def test_authentication_import_direction_has_no_local_back_imports(relative_path
@pytest.mark.asyncio
async def test_registered_authentication_runs_without_importing_pre_auth_again(monkeypatch: pytest.MonkeyPatch) -> None:
+ """运行已注册的认证无需再次导入预认证模块。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '')
app = FastAPI()
handle_exception(app)
add_context_cleanup_middleware(app)
async def database() -> AsyncIterator[object]:
+ """
+ 提供依赖注入使用的数据库替身。
+
+ :yield: 依赖注入使用的数据库替身
+ """
yield object()
user = CurrentUserModel(
@@ -168,17 +183,36 @@ async def database() -> AsyncIterator[object]:
monkeypatch.setattr(LoginService, '_resolve_current_user', resolver)
app.dependency_overrides[get_db_session_provider(None)] = database
- @app.get('/public', dependencies=[PreAuthDependency([{'path': '/public'}])])
+ @app.get(
+ '/public',
+ summary='访问公开资源',
+ description='允许匿名访问并返回公开状态。',
+ dependencies=[PreAuthDependency([{'path': '/public'}])],
+ )
async def public() -> dict:
return {'public': True}
- @app.get('/protected', dependencies=[PreAuthDependency()])
+ @app.get(
+ '/protected',
+ summary='读取受保护用户标识',
+ description='认证成功后返回当前用户的标识。',
+ dependencies=[PreAuthDependency()],
+ )
async def protected(current_user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict:
return {'userId': current_user.user.user_id}
original_import = builtins.__import__
def import_without_pre_auth(name: str, *args: object, **kwargs: object) -> object:
+ """
+ 模拟预认证模块不可导入时的依赖解析。
+
+ :param name: 用于查找或标识当前对象的名称
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises AssertionError: 登录服务不应在执行时反向导入前置依赖
+ :return: 按原导入机制取得的模块
+ """
if name == 'common.aspect.pre_auth':
raise AssertionError('登录服务不应在执行时反向导入前置依赖')
return original_import(name, *args, **kwargs)
@@ -201,9 +235,17 @@ def import_without_pre_auth(name: str, *args: object, **kwargs: object) -> objec
@pytest.mark.asyncio
async def test_auth_policy_accepts_independent_authentication_dependencies() -> None:
+ """认证策略接受独立的认证依赖。"""
calls = []
async def authenticate(request: Request) -> str | None:
+ """
+ 按测试场景提供请求认证结果。
+
+ :param request: 当前 HTTP 请求
+ :raises HTTPException: 模拟认证失败并返回未授权状态
+ :return: 此分支的固定值 ``'independent'``
+ """
mode = AuthPolicy.get_auth_mode(request, (authenticate,))
calls.append(mode)
if mode == 'excluded':
@@ -213,14 +255,24 @@ async def authenticate(request: Request) -> str | None:
return 'independent'
class IndependentPreAuth(AuthRule):
+ """将认证结果作为独立的预认证依赖提供。"""
+
async def __call__(self, user: Annotated[str | None, Depends(authenticate)]) -> str | None:
+ """
+ 向调用方返回 ``user``。
+
+ :param user: 当前操作对应的用户
+ :return: 当前操作对应的用户
+ """
return user
app = FastAPI()
rule = IndependentPreAuth([{'path': '/plain/public'}, {'path': '/required/public'}])
router = APIRouter(dependencies=[Depends(rule)])
- @router.get('/public')
+ @router.get(
+ '/public', summary='访问独立认证示例', description='返回公开状态,用于验证单独注册的依赖所采用的认证策略。'
+ )
async def public() -> dict:
return {'public': True}
@@ -239,6 +291,7 @@ async def public() -> dict:
@pytest.mark.asyncio
@pytest.mark.parametrize('public', [False, True])
async def test_dependency_override_preserves_function_scope(public: bool, monkeypatch: pytest.MonkeyPatch) -> None:
+ """覆盖依赖时保留函数作用域。"""
app = FastAPI()
handle_exception(app)
add_context_cleanup_middleware(app)
@@ -249,9 +302,19 @@ async def test_dependency_override_preserves_function_scope(public: bool, monkey
events = []
async def original() -> str:
+ """
+ 返回固定值 ``original``。
+
+ :return: 此分支的固定值 ``'original'``
+ """
return 'original'
async def resource() -> AsyncIterator[str]:
+ """
+ 跟踪请求依赖资源的打开和释放。
+
+ :yield: 此分支的固定值 ``'resource'``
+ """
events.append('open')
try:
yield 'resource'
@@ -259,12 +322,23 @@ async def resource() -> AsyncIterator[str]:
events.append('close')
async def replacement(value: Annotated[str, Depends(resource, scope='function')]) -> AsyncIterator[str]:
+ """
+ 提供用于检验认证规则的替代依赖。
+
+ :param value: 待处理的输入值
+ :yield: 待处理的输入值
+ """
try:
yield value
finally:
events.append('release')
- @app.get('/scope', dependencies=[PreAuthDependency([{'path': '/scope'}] if public else [])])
+ @app.get(
+ '/scope',
+ summary='读取函数作用域依赖',
+ description='返回依赖提供的值,用于检查覆盖依赖后的生命周期。',
+ dependencies=[PreAuthDependency([{'path': '/scope'}] if public else [])],
+ )
async def endpoint(value: Annotated[str, Depends(original, scope='function')]) -> dict:
events.append('endpoint')
return {'value': value}
diff --git a/ruoyi-fastapi-backend/tests/common/test_data_scope.py b/ruoyi-fastapi-backend/tests/common/test_data_scope.py
index 4d4e30b4c..a3c2601f3 100644
--- a/ruoyi-fastapi-backend/tests/common/test_data_scope.py
+++ b/ruoyi-fastapi-backend/tests/common/test_data_scope.py
@@ -29,12 +29,18 @@
def test_data_scope_filters_real_query(
monkeypatch: pytest.MonkeyPatch, roles: list[tuple], admin: bool, expected: list[int]
) -> None:
+ """数据权限范围过滤实际查询。"""
metadata = MetaData()
- table = Table('records', metadata, Column('user_id', Integer, primary_key=True), Column('dept_id', Integer))
+ table = Table(
+ 'records',
+ metadata,
+ Column('user_id', Integer, primary_key=True, comment='用户标识'),
+ Column('dept_id', Integer, comment='部门标识'),
+ )
mapper = registry()
class Record:
- pass
+ """表示用于测试数据范围的记录。"""
mapper.map_imperatively(Record, table)
user = SimpleNamespace(
diff --git a/ruoyi-fastapi-backend/tests/common/test_exception_responses.py b/ruoyi-fastapi-backend/tests/common/test_exception_responses.py
index 29cbcc2e9..497ea8f0e 100644
--- a/ruoyi-fastapi-backend/tests/common/test_exception_responses.py
+++ b/ruoyi-fastapi-backend/tests/common/test_exception_responses.py
@@ -25,6 +25,12 @@
@pytest.fixture
def log_context(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
+ """
+ 为异常响应测试配置受控日志上下文。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: 供调用方使用的 ``diagnostic_logger``
+ """
monkeypatch.setattr(DependencyUtil, 'check_exclude_routes', lambda *args, **kwargs: None)
monkeypatch.setattr(Log, '_get_oper_location', AsyncMock(return_value='测试'))
monkeypatch.setattr(
@@ -42,14 +48,23 @@ def log_context(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
@pytest.mark.parametrize('decorated', [False, True])
def test_unexpected_error_is_safe_and_correlates_with_server_log(log_context: MagicMock, decorated: bool) -> None:
+ """意外错误隐藏内部细节并能关联服务端日志。"""
app = FastAPI()
handle_exception(app)
error = RuntimeError('SELECT secret FROM users; password=private-marker /srv/private/config')
async def endpoint(request: Request) -> None:
+ """
+ 模拟此操作抛出 error 的情形。
+
+ :param request: 当前 HTTP 请求
+ :raises Exception: 底层操作失败时向调用方传播异常
+ """
raise error
- app.get('/failure')(Log(title='测试', business_type=BusinessType.OTHER)(endpoint) if decorated else endpoint)
+ app.get('/failure', summary='触发服务端错误', description='抛出测试异常,用于核对公开错误编号与诊断日志。')(
+ Log(title='测试', business_type=BusinessType.OTHER)(endpoint) if decorated else endpoint
+ )
response = TestClient(app, raise_server_exceptions=False).get('/failure')
payload = response.json()
assert payload['code'] == HttpStatusConstant.ERROR
@@ -70,6 +85,7 @@ async def endpoint(request: Request) -> None:
def test_logged_known_errors_preserve_global_response(
log_context: MagicMock, monkeypatch: pytest.MonkeyPatch, exception_kind: str, audit_fails: bool
) -> None:
+ """记录已知错误后仍返回统一响应。"""
exceptions = {
'auth': AuthException(message='令牌失效'),
'permission': PermissionException(message='无权限'),
@@ -87,10 +103,18 @@ def test_logged_known_errors_preserve_global_response(
handle_exception(app)
async def endpoint(request: Request) -> None:
+ """
+ 模拟此操作抛出 exceptions[exception_kind] 的情形。
+
+ :param request: 当前 HTTP 请求
+ :raises Exception: 底层操作失败时向调用方传播异常
+ """
raise exceptions[exception_kind]
- app.get('/plain')(endpoint)
- app.get('/logged')(Log(title='测试', business_type=BusinessType.OTHER)(endpoint))
+ app.get('/plain', summary='获取标准错误响应', description='直接触发已知异常并返回全局异常处理器的响应。')(endpoint)
+ app.get('/logged', summary='获取审计后的错误响应', description='通过操作日志装饰器触发相同异常,以便比对响应。')(
+ Log(title='测试', business_type=BusinessType.OTHER)(endpoint)
+ )
if audit_fails:
monkeypatch.setattr(
LogQueueService, 'enqueue_operation_log', AsyncMock(side_effect=RuntimeError('queue unavailable'))
diff --git a/ruoyi-fastapi-backend/tests/common/test_pre_auth.py b/ruoyi-fastapi-backend/tests/common/test_pre_auth.py
index ed5e522d6..e1373d4c8 100644
--- a/ruoyi-fastapi-backend/tests/common/test_pre_auth.py
+++ b/ruoyi-fastapi-backend/tests/common/test_pre_auth.py
@@ -30,6 +30,12 @@
def _user(user_id: int) -> CurrentUserModel:
+ """
+ 创建测试使用的 ``CurrentUserModel`` 实例。
+
+ :param user_id: 用户的唯一标识
+ :return: 测试使用的 ``CurrentUserModel`` 实例
+ """
return CurrentUserModel(
permissions=[f'user:{user_id}:read'],
roles=['reader'],
@@ -43,15 +49,36 @@ def _user(user_id: int) -> CurrentUserModel:
@pytest.fixture
def auth_app(monkeypatch: pytest.MonkeyPatch) -> Iterator[SimpleNamespace]:
+ """
+ 构建带认证依赖和异常处理的测试应用。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :yield: 带认证依赖和异常处理的测试应用
+ """
monkeypatch.setattr(AppConfig, 'app_root_path', '')
app = FastAPI()
handle_exception(app)
add_context_cleanup_middleware(app)
async def database() -> AsyncIterator[object]:
+ """
+ 提供依赖注入使用的数据库替身。
+
+ :yield: 依赖注入使用的数据库替身
+ """
yield object()
async def authenticate(request: Request, token: str, db: object, *, refresh_session: bool) -> CurrentUserModel:
+ """
+ 按测试场景提供请求认证结果。
+
+ :param request: 当前 HTTP 请求
+ :param token: 用于身份验证或授权的令牌
+ :param db: 当前操作使用的数据库会话
+ :param refresh_session: 是否续期宿主主登录会话
+ :raises AuthException: 用户token已失效,请重新登录
+ :return: 当前登录用户及其权限信息
+ """
assert refresh_session
normalized = token.removeprefix('Bearer ').strip() if token.startswith('Bearer ') else token
if normalized not in USER_IDS:
@@ -66,7 +93,12 @@ async def authenticate(request: Request, token: str, db: object, *, refresh_sess
monkeypatch.setattr(LoginService, '_resolve_current_user', resolver)
app.dependency_overrides[get_db_session_provider(None)] = database
- @app.get('/both', dependencies=[PreAuthDependency()])
+ @app.get(
+ '/both',
+ summary='比较预认证与当前用户',
+ description='返回两种依赖解析出的用户标识及上下文状态。',
+ dependencies=[PreAuthDependency()],
+ )
async def both(
user: Annotated[CurrentUserModel, CurrentUserDependency()],
same_user: Annotated[CurrentUserModel, CurrentUserDependency()],
@@ -79,28 +111,49 @@ async def both(
'permissions': user.permissions,
}
- @app.get('/current')
+ @app.get('/current', summary='读取当前用户标识', description='通过当前用户依赖返回已登录用户的标识。')
async def current(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict:
return {'userId': user.user.user_id}
- @app.get('/direct', dependencies=[PreAuthDependency()])
+ @app.get(
+ '/direct',
+ summary='比较直接认证结果',
+ description='返回用户标识,并指出两条认证路径是否使用同一用户对象。',
+ dependencies=[PreAuthDependency()],
+ )
async def direct(
user: Annotated[CurrentUserModel, CurrentUserDependency()],
direct_user: Annotated[CurrentUserModel, Depends(LoginService.get_current_user)],
) -> dict:
return {'userId': user.user.user_id, 'sameUser': user is direct_user}
- @app.get('/pre', dependencies=[PreAuthDependency()])
+ @app.get(
+ '/pre',
+ summary='读取预认证上下文',
+ description='从当前请求上下文返回已通过预认证的用户标识。',
+ dependencies=[PreAuthDependency()],
+ )
async def pre() -> dict:
return {'userId': RequestContext.get_current_user().user.user_id}
excluded = PreAuthDependency([{'path': '/public/{name}', 'methods': ['GET'], 'ignore_paths': ['/public/private']}])
- @app.api_route('/public/{name}', methods=['GET', 'POST'], dependencies=[excluded])
+ @app.api_route(
+ '/public/{name}',
+ summary='访问公开名称',
+ description='按请求方法和路径应用排除规则,并回显路径中的名称。',
+ methods=['GET', 'POST'],
+ dependencies=[excluded],
+ )
async def public(name: str) -> dict:
return {'name': name}
- @app.get('/excluded-current', dependencies=[PreAuthDependency([{'path': '/excluded-current'}])])
+ @app.get(
+ '/excluded-current',
+ summary='读取显式认证用户',
+ description='即使路径命中预认证排除项,仍从显式依赖读取当前用户。',
+ dependencies=[PreAuthDependency([{'path': '/excluded-current'}])],
+ )
async def excluded_current(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict:
return {'userId': user.user.user_id}
@@ -113,6 +166,7 @@ async def excluded_current(user: Annotated[CurrentUserModel, CurrentUserDependen
@pytest.mark.asyncio
@pytest.mark.parametrize('path', ['/both', '/current', '/pre', '/direct'])
async def test_request_authentication_runs_once(auth_app: SimpleNamespace, path: str) -> None:
+ """单个请求只认证一次。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
response = await client.get(path, headers={'Authorization': 'Bearer alice'})
assert response.status_code == status.HTTP_200_OK
@@ -125,6 +179,7 @@ async def test_request_authentication_runs_once(auth_app: SimpleNamespace, path:
@pytest.mark.asyncio
async def test_new_requests_reauthenticate_even_with_the_same_token(auth_app: SimpleNamespace) -> None:
+ """同一令牌发起新请求仍需重新认证。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
for _ in range(2):
response = await client.get('/both', headers={'Authorization': 'Bearer alice'})
@@ -136,6 +191,7 @@ async def test_new_requests_reauthenticate_even_with_the_same_token(auth_app: Si
@pytest.mark.asyncio
async def test_parallel_requests_keep_user_and_context_separate(auth_app: SimpleNamespace) -> None:
+ """并发请求隔离用户及上下文。"""
tokens = ['alice', 'bob', 'alice', 'bob']
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
responses = await asyncio.gather(
@@ -151,6 +207,7 @@ async def test_parallel_requests_keep_user_and_context_separate(auth_app: Simple
@pytest.mark.asyncio
async def test_excluded_route_keeps_path_method_and_ignore_rules(auth_app: SimpleNamespace) -> None:
+ """排除路由时同时考虑路径、方法和忽略规则。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
response = await client.get('/public/free')
assert response.json() == {'name': 'free'}
@@ -166,6 +223,7 @@ async def test_excluded_route_keeps_path_method_and_ignore_rules(auth_app: Simpl
@pytest.mark.asyncio
@pytest.mark.parametrize('path', ['/both', '/current', '/pre'])
async def test_missing_token_preserves_existing_auth_response(auth_app: SimpleNamespace, path: str) -> None:
+ """缺少令牌时返回约定的认证响应。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
response = await client.get(path)
expected_status = status.HTTP_401_UNAUTHORIZED if path == '/current' else status.HTTP_200_OK
@@ -182,6 +240,7 @@ async def test_missing_token_preserves_existing_auth_response(auth_app: SimpleNa
async def test_invalid_token_and_header_cannot_reuse_authentication(
auth_app: SimpleNamespace, authorization: str, path: str
) -> None:
+ """无效令牌或请求头无法复用认证结果。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
valid = await client.get('/both', headers={'Authorization': 'Bearer alice'})
assert valid.json()['userId'] == USER_IDS['alice']
@@ -190,12 +249,14 @@ async def test_invalid_token_and_header_cannot_reuse_authentication(
def test_current_user_dependency_keeps_original_oauth_token_url(auth_app: SimpleNamespace) -> None:
+ """当前用户依赖保留原 OAuth 令牌地址。"""
security = auth_app.app.openapi()['components']['securitySchemes']['OAuth2PasswordBearer']
assert security['flows']['password']['tokenUrl'] == 'login'
@pytest.mark.asyncio
async def test_direct_calls_authenticate_each_time(monkeypatch: pytest.MonkeyPatch) -> None:
+ """每次直接调用均执行认证。"""
request = Request({'type': 'http', 'headers': []})
database = object()
resolver = AsyncMock(side_effect=[_user(USER_IDS['alice']), _user(USER_IDS['alice'])])
@@ -209,6 +270,7 @@ async def test_direct_calls_authenticate_each_time(monkeypatch: pytest.MonkeyPat
@pytest.mark.asyncio
async def test_failed_authentication_is_not_saved(monkeypatch: pytest.MonkeyPatch) -> None:
+ """认证失败时不缓存结果。"""
request = Request({'type': 'http', 'headers': []})
database = object()
user = _user(USER_IDS['alice'])
@@ -223,11 +285,19 @@ async def test_failed_authentication_is_not_saved(monkeypatch: pytest.MonkeyPatc
@pytest.mark.asyncio
async def test_cancelled_authentication_is_not_saved(monkeypatch: pytest.MonkeyPatch) -> None:
+ """取消认证时不缓存结果。"""
request = Request({'type': 'http', 'headers': []})
database = object()
entered = asyncio.Event()
async def blocked(*args: object, **kwargs: object) -> CurrentUserModel:
+ """
+ 将调用保持在等待状态以验证取消行为。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises AssertionError: 已取消的请求意外恢复了执行
+ """
entered.set()
await asyncio.Event().wait()
raise AssertionError('cancelled request resumed')
@@ -251,6 +321,7 @@ async def blocked(*args: object, **kwargs: object) -> CurrentUserModel:
async def test_excluded_route_matches_configured_root_path(
auth_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """排除规则能匹配配置的根路径。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '/dev-api')
transport = httpx.ASGITransport(app=auth_app.app, root_path='/dev-api')
async with httpx.AsyncClient(transport=transport, base_url='http://test') as client:
@@ -263,21 +334,36 @@ async def test_excluded_route_matches_configured_root_path(
@pytest.mark.asyncio
async def test_original_dependency_override_applies_to_both_declarations(auth_app: SimpleNamespace) -> None:
+ """原依赖覆盖对两处声明同时生效。"""
user = _user(USER_IDS['bob'])
override_calls = []
async def override() -> CurrentUserModel:
+ """
+ 记录覆盖依赖的调用并传递测试用户。
+
+ :return: 当前操作对应的用户
+ """
override_calls.append(user)
return user
@auth_app.app.get(
'/overridden',
+ summary='检查认证依赖覆盖',
+ description='返回覆盖依赖解析的用户标识,并与请求上下文进行比对。',
dependencies=[PreAuthDependency(), UserInterfaceAuthDependency(f'user:{USER_IDS["bob"]}:read')],
)
async def overridden(
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
direct_user: Annotated[CurrentUserModel, Depends(LoginService.get_current_user)],
) -> dict:
+ """
+ 返回含 ``userId``, ``contextUserId``, ``sameUser`` 的测试数据。
+
+ :param current_user: 当前登录用户及其权限信息
+ :param direct_user: 当前已认证用户及其权限信息
+ :return: 含 ``userId``, ``contextUserId``, ``sameUser`` 的测试数据
+ """
return {
'userId': current_user.user.user_id,
'contextUserId': RequestContext.get_current_user().user.user_id,
@@ -295,6 +381,7 @@ async def overridden(
@pytest.mark.asyncio
async def test_calls_without_request_state_authenticate_each_time(monkeypatch: pytest.MonkeyPatch) -> None:
+ """没有请求状态时每次调用均执行认证。"""
request = SimpleNamespace()
database = object()
resolver = AsyncMock(return_value=_user(USER_IDS['alice']))
@@ -307,6 +394,7 @@ async def test_calls_without_request_state_authenticate_each_time(monkeypatch: p
@pytest.mark.asyncio
async def test_plugin_session_validation_never_reuses_main_request_result(monkeypatch: pytest.MonkeyPatch) -> None:
+ """插件会话校验独立于主请求的认证结果。"""
request = Request({'type': 'http', 'headers': []})
database = object()
resolver = AsyncMock(return_value=_user(USER_IDS['alice']))
@@ -320,6 +408,7 @@ async def test_plugin_session_validation_never_reuses_main_request_result(monkey
@pytest.mark.asyncio
async def test_non_string_token_keeps_auth_exception_conversion() -> None:
+ """非字符串令牌仍按约定转换认证异常。"""
request = Request({'type': 'http', 'headers': []})
with pytest.raises(AuthException) as exc_info:
await LoginService.get_current_user(request, b'invalid', object())
@@ -329,11 +418,25 @@ async def test_non_string_token_keeps_auth_exception_conversion() -> None:
@pytest.mark.asyncio
async def test_use_cache_false_reauthenticates_after_pre_auth(auth_app: SimpleNamespace) -> None:
- @auth_app.app.get('/fresh', dependencies=[PreAuthDependency()])
+ """禁用缓存后在预认证完成时重新认证。"""
+
+ @auth_app.app.get(
+ '/fresh',
+ summary='重新认证当前用户',
+ description='在一次请求中重新验证凭证并比较前后两次的用户结果。',
+ dependencies=[PreAuthDependency()],
+ )
async def fresh(
first: Annotated[CurrentUserModel, CurrentUserDependency()],
current: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
) -> dict:
+ """
+ 返回含 ``sameUser``, ``userId``, ``currentContext`` 的测试数据。
+
+ :param first: 当前已认证用户及其权限信息
+ :param current: 当前已认证用户及其权限信息
+ :return: 含 ``sameUser``, ``userId``, ``currentContext`` 的测试数据
+ """
return {
'sameUser': first is current,
'userId': current.user.user_id,
@@ -348,10 +451,23 @@ async def fresh(
@pytest.mark.asyncio
async def test_use_cache_false_does_not_fall_back_to_previous_success(auth_app: SimpleNamespace) -> None:
- @auth_app.app.get('/fresh-denied', dependencies=[PreAuthDependency()])
+ """禁用缓存后无法沿用上次成功结果。"""
+
+ @auth_app.app.get(
+ '/fresh-denied',
+ summary='验证重新认证失败',
+ description='第二次认证失败时应拒绝请求,用于检查旧缓存的处理。',
+ dependencies=[PreAuthDependency()],
+ )
async def fresh_denied(
current: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
) -> dict:
+ """
+ 模拟此操作抛出 AssertionError 的情形。
+
+ :param current: 当前已认证用户及其权限信息
+ :raises AssertionError: 认证失败后仍然执行了端点
+ """
raise AssertionError('failed authentication was ignored')
auth_app.resolver.side_effect = [_user(USER_IDS['alice']), AuthException(message='令牌已撤销')]
@@ -366,6 +482,7 @@ async def fresh_denied(
async def test_later_pre_auth_cannot_restore_permissions_before_forced_authentication(
auth_app: SimpleNamespace,
) -> None:
+ """后续预认证无法在强制认证前恢复权限。"""
initial_user = _user(USER_IDS['bob'])
refreshed_user = _user(USER_IDS['bob'])
refreshed_user.permissions = []
@@ -373,22 +490,46 @@ async def test_later_pre_auth_cannot_restore_permissions_before_forced_authentic
observed_users = []
async def authenticate(request: Request, token: str, db: object, *, refresh_session: bool) -> CurrentUserModel:
+ """
+ 按测试场景提供请求认证结果。
+
+ :param request: 当前 HTTP 请求
+ :param token: 用于身份验证或授权的令牌
+ :param db: 当前操作使用的数据库会话
+ :param refresh_session: 是否续期宿主主登录会话
+ :return: 当前操作对应的用户
+ """
user = next(users)
RequestContext.set_current_user(user)
return user
async def observe_context() -> None:
+ """捕获当前请求上下文中的用户。"""
observed_users.append(RequestContext.get_current_user())
auth_app.resolver.side_effect = authenticate
- @auth_app.app.get('/revoked-permissions', dependencies=[PreAuthDependency()])
+ @auth_app.app.get(
+ '/revoked-permissions',
+ summary='验证撤销权限后的访问',
+ description='在强制重新认证后检查权限,验证撤销操作立即生效。',
+ dependencies=[PreAuthDependency()],
+ )
async def revoked_permissions(
fresh: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
another: Annotated[CurrentUserModel, PreAuthDependency()],
observed: Annotated[None, Depends(observe_context)],
permitted: Annotated[bool, UserInterfaceAuthDependency(f'user:{USER_IDS["bob"]}:read')],
) -> dict:
+ """
+ 模拟此操作抛出 AssertionError 的情形。
+
+ :param fresh: 当前已认证用户及其权限信息
+ :param another: 当前已认证用户及其权限信息
+ :param observed: 供断言检查的实际观测记录
+ :param permitted: 该请求是否拥有所需权限
+ :raises AssertionError: 依赖缓存错误地恢复已撤销的权限
+ """
raise AssertionError('revoked permission was restored from the dependency cache')
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -402,6 +543,7 @@ async def revoked_permissions(
@pytest.mark.asyncio
@pytest.mark.parametrize('authorization', [None, 'Bearer alice', 'Bearer invalid', 'Basic invalid'])
async def test_public_route_never_authenticates(auth_app: SimpleNamespace, authorization: str | None) -> None:
+ """公开路由无需认证。"""
headers = {'Authorization': authorization} if authorization is not None else {}
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
response = await client.get('/public/free', headers=headers)
@@ -412,6 +554,7 @@ async def test_public_route_never_authenticates(auth_app: SimpleNamespace, autho
@pytest.mark.asyncio
async def test_explicit_current_user_still_authenticates_on_excluded_route(auth_app: SimpleNamespace) -> None:
+ """排除路由中显式请求当前用户仍触发认证。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
response = await client.get('/excluded-current', headers={'Authorization': 'Bearer bob'})
assert response.json() == {'userId': USER_IDS['bob']}
@@ -422,11 +565,30 @@ async def test_explicit_current_user_still_authenticates_on_excluded_route(auth_
@pytest.mark.asyncio
async def test_nested_current_user_dependency_requires_login_on_excluded_route(auth_app: SimpleNamespace) -> None:
+ """排除路由中嵌套的当前用户依赖仍要求登录。"""
+
async def identity(user: Annotated[CurrentUserModel, Depends(LoginService.get_current_user)]) -> int:
+ """
+ 返回认证依赖解析出的用户标识。
+
+ :param user: 当前已认证用户及其权限信息
+ :return: 认证依赖解析出的用户标识
+ """
return user.user.user_id
- @auth_app.app.get('/nested', dependencies=[PreAuthDependency([{'path': '/nested'}])])
+ @auth_app.app.get(
+ '/nested',
+ summary='读取嵌套依赖的用户',
+ description='从嵌套的当前用户依赖返回用户标识。',
+ dependencies=[PreAuthDependency([{'path': '/nested'}])],
+ )
async def nested(user_id: Annotated[int, Depends(identity)]) -> dict:
+ """
+ 返回含 ``userId`` 的测试数据。
+
+ :param user_id: 用户的唯一标识
+ :return: 含 ``userId`` 的测试数据
+ """
return {'userId': user_id}
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -441,14 +603,38 @@ async def nested(user_id: Annotated[int, Depends(identity)]) -> dict:
async def test_override_cannot_add_authentication_to_an_excluded_dependency_without_login(
auth_app: SimpleNamespace,
) -> None:
+ """覆盖排除的依赖时不能绕开登录而追加认证。"""
+
async def identity() -> int:
+ """
+ 返回固定值 ``0``。
+
+ :return: 此分支的固定值 ``0``
+ """
return 0
async def authenticated_identity(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> int:
+ """
+ 返回认证依赖解析出的用户标识。
+
+ :param user: 当前已认证用户及其权限信息
+ :return: 认证依赖解析出的用户标识
+ """
return user.user.user_id
- @auth_app.app.get('/override-nested', dependencies=[PreAuthDependency([{'path': '/override-nested'}])])
+ @auth_app.app.get(
+ '/override-nested',
+ summary='检查被覆盖的嵌套依赖',
+ description='从覆盖后的依赖读取用户,验证额外认证要求生效。',
+ dependencies=[PreAuthDependency([{'path': '/override-nested'}])],
+ )
async def nested(user_id: Annotated[int, Depends(identity)]) -> dict:
+ """
+ 返回含 ``userId`` 的测试数据。
+
+ :param user_id: 用户的唯一标识
+ :return: 含 ``userId`` 的测试数据
+ """
return {'userId': user_id}
auth_app.app.dependency_overrides[identity] = authenticated_identity
@@ -462,6 +648,7 @@ async def nested(user_id: Annotated[int, Depends(identity)]) -> dict:
@pytest.mark.asyncio
async def test_direct_call_without_a_token_requires_login() -> None:
+ """直接调用时缺少令牌必须登录。"""
request = Request({'type': 'http', 'headers': []})
with pytest.raises(AuthException) as exc_info:
await LoginService.get_current_user(request, None, object())
@@ -473,12 +660,23 @@ async def test_direct_call_without_a_token_requires_login() -> None:
async def test_excluded_pre_auth_cannot_cancel_another_auth_requirement(
auth_app: SimpleNamespace, excluded_first: bool
) -> None:
+ """排除一处预认证不能取消其他认证要求。"""
dependencies = [PreAuthDependency([{'path': '/mixed'}]), PreAuthDependency()]
if not excluded_first:
dependencies.reverse()
- @auth_app.app.get('/mixed', dependencies=dependencies)
+ @auth_app.app.get(
+ '/mixed',
+ summary='检查多重预认证',
+ description='返回当前用户标识,用于验证多个依赖中仍生效的认证要求。',
+ dependencies=dependencies,
+ )
async def mixed() -> dict:
+ """
+ 返回含 ``userId`` 的测试数据。
+
+ :return: 含 ``userId`` 的测试数据
+ """
return {'userId': RequestContext.get_current_user().user.user_id}
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -492,14 +690,23 @@ async def mixed() -> dict:
@pytest.mark.asyncio
async def test_multiple_excluded_pre_auth_dependencies_do_not_require_login(auth_app: SimpleNamespace) -> None:
+ """多个被排除的预认证依赖不要求登录。"""
+
@auth_app.app.get(
'/all-public',
+ summary='访问全部依赖均放行的资源',
+ description='当所有预认证依赖都排除此路径时返回公开状态。',
dependencies=[
PreAuthDependency([{'path': '/all-public'}]),
PreAuthDependency([{'path': '/all-public', 'methods': ['GET']}]),
],
)
async def public() -> dict:
+ """
+ 返回含 ``public`` 的测试数据。
+
+ :return: 含 ``public`` 的测试数据
+ """
return {'public': True}
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -513,12 +720,23 @@ async def public() -> dict:
async def test_first_required_dependency_keeps_missing_token_response(
auth_app: SimpleNamespace, pre_auth_first: bool
) -> None:
+ """由首个强制认证依赖决定缺少令牌的响应。"""
dependencies = [PreAuthDependency(), CurrentUserDependency()]
if not pre_auth_first:
dependencies.reverse()
- @auth_app.app.get('/ordered', dependencies=dependencies)
+ @auth_app.app.get(
+ '/ordered',
+ summary='检查认证依赖顺序',
+ description='按注册顺序执行认证依赖,用于验证缺少令牌时的响应。',
+ dependencies=dependencies,
+ )
async def ordered() -> dict:
+ """
+ 返回含 ``ok`` 的测试数据。
+
+ :return: 含 ``ok`` 的测试数据
+ """
return {'ok': True}
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -531,6 +749,7 @@ async def ordered() -> dict:
@pytest.mark.asyncio
async def test_failed_request_does_not_reuse_a_previous_authentication(auth_app: SimpleNamespace) -> None:
+ """失败请求无法复用先前认证。"""
authenticate = auth_app.resolver.side_effect
auth_app.resolver.side_effect = AuthException(message='认证失败')
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -544,10 +763,18 @@ async def test_failed_request_does_not_reuse_a_previous_authentication(auth_app:
@pytest.mark.asyncio
async def test_cancelled_request_does_not_affect_following_authentication(auth_app: SimpleNamespace) -> None:
+ """取消请求后不影响后续认证。"""
authenticate = auth_app.resolver.side_effect
entered = asyncio.Event()
async def blocked(*args: object, **kwargs: object) -> CurrentUserModel:
+ """
+ 将调用保持在等待状态以验证取消行为。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises AssertionError: 已取消的请求意外恢复了执行
+ """
entered.set()
await asyncio.Event().wait()
raise AssertionError('cancelled request resumed')
@@ -567,8 +794,12 @@ async def blocked(*args: object, **kwargs: object) -> CurrentUserModel:
@pytest.mark.asyncio
async def test_interface_role_and_data_permissions_are_still_checked(auth_app: SimpleNamespace) -> None:
+ """接口权限、角色和数据权限均被检查。"""
+
@auth_app.app.get(
'/scope',
+ summary='查询用户数据范围',
+ description='返回当前用户标识和根据角色权限计算的数据范围条件。',
dependencies=[
PreAuthDependency(),
UserInterfaceAuthDependency(f'user:{USER_IDS["bob"]}:read'),
@@ -579,17 +810,33 @@ async def scope(
user: Annotated[CurrentUserModel, CurrentUserDependency()],
data_scope: Annotated[ColumnElement, DataScopeDependency(SysUser)],
) -> dict:
+ """
+ 返回含 ``userId``, ``scope`` 的测试数据。
+
+ :param user: 当前已认证用户及其权限信息
+ :param data_scope: 数据范围(1:全部数据权限 2:自定数据权限 3:本部门数据权限 4:本部门及以下数据权限 5:仅本人数据权限)
+ :return: 含 ``userId``, ``scope`` 的测试数据
+ """
return {'userId': user.user.user_id, 'scope': str(data_scope.compile(compile_kwargs={'literal_binds': True}))}
@auth_app.app.get(
'/forbidden-permission',
+ summary='验证接口权限限制',
+ description='尝试访问需要指定权限的资源,用于检查拒绝响应。',
dependencies=[PreAuthDependency(), UserInterfaceAuthDependency('system:user:delete')],
)
@auth_app.app.get(
'/forbidden-role',
+ summary='验证角色访问限制',
+ description='尝试访问需要指定角色的资源,用于检查拒绝响应。',
dependencies=[PreAuthDependency(), RoleInterfaceAuthDependency('administrator')],
)
async def forbidden() -> dict:
+ """
+ 模拟此操作抛出 AssertionError 的情形。
+
+ :raises AssertionError: 请求绕过了必需的权限检查
+ """
raise AssertionError('permission check was skipped')
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -607,6 +854,7 @@ async def forbidden() -> dict:
async def test_authentication_accepts_standard_bearer_scheme_case_insensitively(
auth_app: SimpleNamespace, path: str, scheme: str
) -> None:
+ """Bearer 认证方案忽略大小写。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
response = await client.get(path, headers={'Authorization': f'{scheme} alice'})
assert response.status_code == status.HTTP_200_OK
@@ -621,6 +869,7 @@ async def test_authentication_accepts_standard_bearer_scheme_case_insensitively(
async def test_authentication_rejects_non_bearer_authorization(
auth_app: SimpleNamespace, path: str, authorization: str
) -> None:
+ """认证拒绝非 Bearer 授权头。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
response = await client.get(path, headers={'Authorization': authorization})
assert response.json()['code'] == status.HTTP_401_UNAUTHORIZED
@@ -634,10 +883,22 @@ async def test_authentication_rejects_non_bearer_authorization(
async def test_explicit_oauth_dependency_returns_bare_token_and_still_requires_login(
auth_app: SimpleNamespace, excluded: bool
) -> None:
+ """显式 OAuth 依赖返回纯令牌并要求登录。"""
exclude_routes = [{'path': '/token'}] if excluded else None
- @auth_app.app.get('/token', dependencies=[PreAuthDependency(exclude_routes)])
+ @auth_app.app.get(
+ '/token',
+ summary='读取 OAuth 凭证',
+ description='从显式 OAuth 依赖读取并返回请求携带的令牌。',
+ dependencies=[PreAuthDependency(exclude_routes)],
+ )
async def token_endpoint(token: Annotated[str, Depends(oauth2_scheme)]) -> dict:
+ """
+ 返回含 ``token`` 的测试数据。
+
+ :param token: 用于身份验证或授权的令牌
+ :return: 含 ``token`` 的测试数据
+ """
return {'token': token}
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -651,15 +912,29 @@ async def token_endpoint(token: Annotated[str, Depends(oauth2_scheme)]) -> dict:
@pytest.mark.asyncio
async def test_unrelated_override_keeps_an_excluded_route_public(auth_app: SimpleNamespace) -> None:
+ """无关依赖覆盖后排除路由仍可公开访问。"""
+
async def language() -> str:
+ """
+ 返回固定值 ``en``。
+
+ :return: 此分支的固定值 ``'en'``
+ """
return 'en'
async def translated_language() -> str:
+ """
+ 返回固定值 ``zh``。
+
+ :return: 此分支的固定值 ``'zh'``
+ """
return 'zh'
router = APIRouter(dependencies=[PreAuthDependency([{'path': '/translated/public'}])])
- @router.get('/public')
+ @router.get(
+ '/public', summary='读取公开语言配置', description='返回语言依赖提供的值,用于检查无关依赖覆盖后的公开访问。'
+ )
async def public(locale: Annotated[str, Depends(language)]) -> dict:
return {'locale': locale}
@@ -678,9 +953,15 @@ async def public(locale: Annotated[str, Depends(language)]) -> dict:
async def test_parent_router_authentication_cannot_be_excluded_by_child(
auth_app: SimpleNamespace, nested: bool, requirement: str
) -> None:
+ """子路由无法排除父路由的认证要求。"""
users = []
async def require_user(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> None:
+ """
+ 记录受保护路由解析到的用户。
+
+ :param user: 当前已认证用户及其权限信息
+ """
users.append(user)
requirements = {
@@ -691,7 +972,7 @@ async def require_user(user: Annotated[CurrentUserModel, CurrentUserDependency()
path = '/parent/child/profile' if nested else '/parent/profile'
router = APIRouter(dependencies=[PreAuthDependency([{'path': path}])])
- @router.get('/profile')
+ @router.get('/profile', summary='访问父路由保护的资料', description='验证子路由挂载后仍执行父路由的认证依赖。')
async def profile() -> dict:
return {'protected': True}
@@ -714,12 +995,21 @@ async def profile() -> dict:
@pytest.mark.asyncio
async def test_router_inclusions_keep_their_own_authentication_requirements(auth_app: SimpleNamespace) -> None:
+ """分别挂载的路由保留各自的认证要求。"""
+
async def require_user(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> None:
+ """
+ 记录受保护路由解析到的用户。
+
+ :param user: 当前已认证用户及其权限信息
+ """
assert user.user.user_id == USER_IDS['alice']
router = APIRouter(dependencies=[PreAuthDependency([{'path': '/open/info'}, {'path': '/secured/info'}])])
- @router.get('/info')
+ @router.get(
+ '/info', summary='查询挂载路由状态', description='返回可用状态,用于比对同一路由在不同挂载位置的认证要求。'
+ )
async def info() -> dict:
return {'available': True}
@@ -739,15 +1029,23 @@ async def info() -> dict:
@pytest.mark.asyncio
async def test_parent_override_added_authentication_is_required(auth_app: SimpleNamespace) -> None:
+ """父级依赖覆盖增加的认证必须执行。"""
+
async def identity() -> None:
- return None
+ """完成无需返回值的回调。"""
+ return
async def authenticated_identity(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> None:
+ """
+ 返回认证依赖解析出的用户标识。
+
+ :param user: 当前已认证用户及其权限信息
+ """
assert user.user.user_id == USER_IDS['alice']
router = APIRouter(dependencies=[PreAuthDependency([{'path': '/overridden/public'}])])
- @router.get('/public')
+ @router.get('/public', summary='验证父级依赖覆盖', description='访问子路由以检查父级新增的认证要求。')
async def public() -> dict:
return {'available': True}
@@ -766,11 +1064,12 @@ async def public() -> dict:
async def test_business_prefix_is_not_removed_as_a_deployment_prefix(
auth_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, root_path: str
) -> None:
+ """识别部署路径时保留业务前缀。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '/api')
router = APIRouter(prefix='/api', dependencies=[PreAuthDependency([{'path': '/api/public'}, {'path': '/private'}])])
- @router.get('/public')
- @router.get('/private')
+ @router.get('/public', summary='访问带业务前缀的公开资源', description='按带前缀的公开路径检查匿名访问。')
+ @router.get('/private', summary='访问带业务前缀的受保护资源', description='按带前缀的受保护路径检查登录要求。')
async def endpoint() -> dict:
return {'available': True}
@@ -791,10 +1090,21 @@ async def endpoint() -> dict:
async def test_deployment_prefix_requires_a_path_segment_boundary(
auth_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, root_path: str
) -> None:
+ """部署前缀必须匹配完整路径段。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '/api')
- @auth_app.app.get('/api-extra/public', dependencies=[PreAuthDependency([{'path': '/api-extra/public'}])])
+ @auth_app.app.get(
+ '/api-extra/public',
+ summary='验证部署前缀边界',
+ description='访问与部署前缀相近的业务路径,确认按完整路径段匹配。',
+ dependencies=[PreAuthDependency([{'path': '/api-extra/public'}])],
+ )
async def public() -> dict:
+ """
+ 返回含 ``available`` 的测试数据。
+
+ :return: 含 ``available`` 的测试数据
+ """
return {'available': True}
transport = httpx.ASGITransport(app=auth_app.app, root_path=root_path)
@@ -810,6 +1120,7 @@ async def public() -> dict:
async def test_permission_dependencies_use_the_same_excluded_application_path(
auth_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, root_path: str, permission: str
) -> None:
+ """权限依赖使用相同的应用内排除路径。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '/api')
permissions = {
'interface': UserInterfaceAuthDependency(f'user:{USER_IDS["bob"]}:read'),
@@ -824,8 +1135,12 @@ async def test_permission_dependencies_use_the_same_excluded_application_path(
],
)
- @router.get('/public-scope')
- @router.get('/private-scope')
+ @router.get(
+ '/public-scope',
+ summary='检查公开路径的数据范围',
+ description='在公开路径上运行业务权限依赖,核对排除规则使用的路径。',
+ )
+ @router.get('/private-scope', summary='检查受限路径的数据范围', description='在受保护路径上执行业务权限检查。')
async def endpoint() -> dict:
return {'available': True}
@@ -851,11 +1166,23 @@ async def endpoint() -> dict:
async def test_encoded_path_separators_cannot_expand_public_routes(
auth_app: SimpleNamespace, root_path: str, encoded: str, decoded: str, ignore_path: bool
) -> None:
+ """编码后的分隔符无法扩大公开路由范围。"""
protected_path = f'/encoded/public{decoded}'
rule = {'path': '/encoded/{name}', 'ignore_paths': [protected_path]} if ignore_path else {'path': '/encoded/public'}
- @auth_app.app.get('/encoded/{name}', dependencies=[PreAuthDependency([rule])])
+ @auth_app.app.get(
+ '/encoded/{name}',
+ summary='回显编码后的名称',
+ description='回显已匹配的路径参数,用于验证编码分隔符的访问边界。',
+ dependencies=[PreAuthDependency([rule])],
+ )
async def endpoint(name: str) -> dict:
+ """
+ 返回含 ``name`` 的测试数据。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 含 ``name`` 的测试数据
+ """
return {'name': name}
transport = httpx.ASGITransport(app=auth_app.app, root_path=root_path)
@@ -879,14 +1206,24 @@ async def endpoint(name: str) -> dict:
async def test_permission_check_uses_the_full_decoded_path(
auth_app: SimpleNamespace, root_path: str, encoded: str, decoded: str
) -> None:
+ """权限校验使用完整解码路径。"""
+
@auth_app.app.get(
'/encoded-permission/{name}',
+ summary='校验编码路径权限',
+ description='根据完整的解码路径验证权限后返回名称。',
dependencies=[
PreAuthDependency([{'path': '/encoded-permission/public'}]),
UserInterfaceAuthDependency(f'user:{USER_IDS["bob"]}:read'),
],
)
async def endpoint(name: str) -> dict:
+ """
+ 返回含 ``name`` 的测试数据。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 含 ``name`` 的测试数据
+ """
return {'name': name}
transport = httpx.ASGITransport(app=auth_app.app, root_path=root_path)
@@ -907,6 +1244,7 @@ async def endpoint(name: str) -> dict:
async def test_mounted_application_uses_its_asgi_root_path(
auth_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """挂载的应用使用自身 ASGI 根路径。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '/api')
app = FastAPI()
app.mount('/gateway', auth_app.app)
@@ -923,6 +1261,7 @@ async def test_mounted_application_uses_its_asgi_root_path(
def test_direct_dependency_path_keeps_configured_prefix_fallback(
monkeypatch: pytest.MonkeyPatch, path: str, expected: str, with_scope: bool
) -> None:
+ """直接调用依赖时回退到配置的前缀。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '/api')
request = (
Request({'type': 'http', 'path': path, 'headers': []})
diff --git a/ruoyi-fastapi-backend/tests/common/test_query_time.py b/ruoyi-fastapi-backend/tests/common/test_query_time.py
index 8d69f6e33..283b38406 100644
--- a/ruoyi-fastapi-backend/tests/common/test_query_time.py
+++ b/ruoyi-fastapi-backend/tests/common/test_query_time.py
@@ -18,6 +18,7 @@
@pytest.mark.parametrize('zone', ['', 'Invalid/Zone', '/etc/localtime', '../UTC', 'UTC+08:00'])
def test_invalid_timezone_is_a_model_validation_error(zone: str) -> None:
+ """无效时区触发模型校验错误。"""
with pytest.raises(ValidationError, match='IANA'):
JobModel(timeZone=zone)
with pytest.raises(ValidationError, match='IANA'):
@@ -27,9 +28,12 @@ def test_invalid_timezone_is_a_model_validation_error(zone: str) -> None:
def test_http_boundaries_return_validation_errors() -> None:
+ """HTTP 入口返回校验错误。"""
app = FastAPI()
- @app.get('/query')
+ @app.get(
+ '/query', summary='校验日期查询参数', description='返回通过校验的日期查询条件,错误参数触发 HTTP 校验响应。'
+ )
def date_query(query: Annotated[ConfigPageQueryModel, Query()]) -> dict:
return query.model_dump()
@@ -46,6 +50,7 @@ def date_query(query: Annotated[ConfigPageQueryModel, Query()]) -> dict:
def test_instant_query_compares_instants_instead_of_offset_strings() -> None:
+ """时间点查询按实际时刻比较。"""
query = FileInfoQueryModel(beginTime='2026-08-28T10:00:00+08:00', endTime='2026-08-28T03:00:00Z')
assert TimezoneUtil.rfc3339_range_to_utc(query.begin_time, query.end_time) == (
datetime(2026, 8, 28, 2, tzinfo=UTC),
@@ -68,7 +73,17 @@ def test_instant_query_compares_instants_instead_of_offset_strings() -> None:
async def test_date_query_filters_only_provided_boundaries_in_business_timezone(
monkeypatch: pytest.MonkeyPatch, boundaries: dict[str, str], expected_times: list[datetime]
) -> None:
+ """日期查询按业务时区仅过滤指定的边界。"""
+
async def capture_query(_db: object, query: Select, *args: object) -> Select:
+ """
+ 向调用方返回 ``query``。
+
+ :param _db: 回调签名接收的数据库会话
+ :param query: 限制查询结果的条件
+ :param args: 传给被调用对象的位置参数
+ :return: 限制查询结果的条件
+ """
return query
monkeypatch.setattr(PageUtil, 'paginate', capture_query)
diff --git a/ruoyi-fastapi-backend/tests/common/test_request_timezone.py b/ruoyi-fastapi-backend/tests/common/test_request_timezone.py
index 49409c43e..328ad1ef5 100644
--- a/ruoyi-fastapi-backend/tests/common/test_request_timezone.py
+++ b/ruoyi-fastapi-backend/tests/common/test_request_timezone.py
@@ -21,17 +21,32 @@
@pytest.fixture
def timezone_app(monkeypatch: pytest.MonkeyPatch) -> FastAPI:
- """用真实中间件、DAO日期边界和Excel导出验证请求时区链路。"""
+ """
+ 用真实中间件、DAO日期边界和Excel导出验证请求时区链路。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: 正在配置或处理请求的 ASGI 应用
+ """
monkeypatch.setattr(AppConfig, 'app_timezone', 'Asia/Shanghai')
app = FastAPI()
add_context_cleanup_middleware(app)
async def capture_query(db: object, query: object, *args: object) -> dict:
+ """
+ 提取 SQL 语句的绑定参数。
+
+ :param db: 当前操作使用的数据库会话
+ :param query: 限制查询结果的条件
+ :param args: 传给被调用对象的位置参数
+ :return: SQL 语句的绑定参数
+ """
return query.compile().params
monkeypatch.setattr(PageUtil, 'paginate', capture_query)
- @app.get('/range')
+ @app.get(
+ '/range', summary='查询请求时区的日期边界', description='按本次请求的时区计算日期区间,并返回归一化的边界。'
+ )
async def date_range(request: Request, preference: str = 'auto') -> dict:
RequestContext.set_current_user(
CurrentUserModel(permissions=[], roles=[], user=UserInfoModel(userId=1, timeZone=preference))
@@ -56,7 +71,7 @@ async def date_range(request: Request, preference: str = 'auto') -> dict:
'businessZone': TimezoneUtil.get_app_timezone().key,
}
- @app.get('/failure')
+ @app.get('/failure', summary='触发时区请求异常', description='模拟请求失败,用于检查异常后时区上下文的清理。')
async def failure() -> None:
raise RuntimeError('request failed')
@@ -65,6 +80,7 @@ async def failure() -> None:
@pytest.mark.asyncio
async def test_parallel_requests_isolate_dates_exports_and_cache(timezone_app: FastAPI) -> None:
+ """并发请求隔离日期、导出和缓存。"""
transport = httpx.ASGITransport(app=timezone_app)
async with httpx.AsyncClient(transport=transport, base_url='http://test') as client:
responses = await asyncio.gather(
@@ -92,6 +108,7 @@ async def test_parallel_requests_isolate_dates_exports_and_cache(timezone_app: F
@pytest.mark.asyncio
async def test_request_timezone_fallback_validation_and_exception_cleanup(timezone_app: FastAPI) -> None:
+ """请求时区支持回退、校验和异常后的清理。"""
transport = httpx.ASGITransport(app=timezone_app, raise_app_exceptions=False)
async with httpx.AsyncClient(transport=transport, base_url='http://test') as client:
assert (await client.get('/range')).json()['zone'] == 'Asia/Shanghai'
@@ -113,6 +130,7 @@ async def test_request_timezone_fallback_validation_and_exception_cleanup(timezo
def test_background_exports_can_select_business_timezone_explicitly() -> None:
+ """后台导出可显式指定业务时区。"""
token = RequestContext.set_current_timezone('America/New_York')
try:
workbook = load_workbook(
diff --git a/ruoyi-fastapi-backend/tests/common/test_router_register.py b/ruoyi-fastapi-backend/tests/common/test_router_register.py
index 05ae9f155..c35bcd5c9 100644
--- a/ruoyi-fastapi-backend/tests/common/test_router_register.py
+++ b/ruoyi-fastapi-backend/tests/common/test_router_register.py
@@ -12,6 +12,8 @@
class RouterRegisterForTest(RouterRegister):
"""
测试用路由注册器。
+
+ :ivar project_root: 测试项目根目录
"""
def __init__(self, app: FastAPI, project_root: Path) -> None:
@@ -41,6 +43,7 @@ def touch_file(file_path: Path, content: str = '') -> Path:
def test_router_register_finds_builtin_controller_files(tmp_path: Path) -> None:
+ """路由注册器能找到内置控制器文件。"""
project_root = tmp_path / 'backend'
builtin_controller = touch_file(project_root / 'module_demo' / 'controller' / 'demo_controller.py')
@@ -52,12 +55,7 @@ def test_router_register_finds_builtin_controller_files(tmp_path: Path) -> None:
def test_router_register_finds_auto_register_false_controller_files(tmp_path: Path) -> None:
- """
- 校验路由注册器仍会发现 controller 文件,是否注册由 APIRouterPro.auto_register 决定。
-
- :param tmp_path: pytest 临时目录
- :return: None
- """
+ """校验路由注册器仍会发现 controller 文件,是否注册由 APIRouterPro.auto_register 决定。"""
project_root = tmp_path / 'backend'
builtin_controller = touch_file(project_root / 'module_demo' / 'controller' / 'demo_controller.py')
extra_controller = touch_file(project_root / 'module_extra' / 'controller' / 'extra_controller.py')
@@ -68,11 +66,7 @@ def test_router_register_finds_auto_register_false_controller_files(tmp_path: Pa
def test_router_register_skips_auto_register_false_router(tmp_path: Path) -> None:
- """
- 校验 auto_register=False 的 APIRouterPro 不会被注册到应用。
-
- :return: None
- """
+ """校验 auto_register=False 的 APIRouterPro 不会被注册到应用。"""
project_root = tmp_path / 'backend'
router_register = RouterRegisterForTest(FastAPI(), project_root=project_root)
controller_file = touch_file(
@@ -86,11 +80,7 @@ def test_router_register_skips_auto_register_false_router(tmp_path: Path) -> Non
def test_router_register_includes_plugin_management_controller() -> None:
- """
- 校验内置插件管理 controller 会参与自动注册。
-
- :return: None
- """
+ """校验内置插件管理 controller 会参与自动注册。"""
project_root = BACKEND_ROOT
router_register = RouterRegisterForTest(FastAPI(), project_root=project_root)
@@ -100,17 +90,14 @@ def test_router_register_includes_plugin_management_controller() -> None:
def test_auto_register_routers_uses_builtin_controller_registration(monkeypatch: object) -> None:
- """
- 校验 auto_register_routers 保持内置 controller 注册语义。
-
- :param monkeypatch: pytest monkeypatch fixture
- :return: None
- """
+ """校验 auto_register_routers 保持内置 controller 注册语义。"""
called = []
class FakeRouterRegister:
"""
测试用假路由注册器。
+
+ :ivar app: FastAPI对象
"""
def __init__(self, app: FastAPI) -> None:
@@ -122,11 +109,7 @@ def __init__(self, app: FastAPI) -> None:
self.app = app
def register_routers(self) -> None:
- """
- 记录路由注册调用。
-
- :return: None
- """
+ """记录路由注册调用。"""
called.append(True)
monkeypatch.setattr('common.router.RouterRegister', FakeRouterRegister)
@@ -137,12 +120,7 @@ def register_routers(self) -> None:
def test_router_register_register_routers_uses_common_controller_file_pipeline(tmp_path: Path) -> None:
- """
- 校验内置路由注册复用统一 controller 文件注册流水线。
-
- :param tmp_path: pytest 临时目录
- :return: None
- """
+ """校验内置路由注册复用统一 controller 文件注册流水线。"""
project_root = tmp_path / 'backend'
builtin_controller = touch_file(project_root / 'module_demo' / 'controller' / 'demo_controller.py')
captured_controller_files = []
@@ -153,7 +131,6 @@ def fake_register_controller_files(controller_files: list[str]) -> None:
记录注册的controller文件。
:param controller_files: controller文件列表
- :return: None
"""
captured_controller_files.extend(controller_files)
@@ -165,18 +142,15 @@ def fake_register_controller_files(controller_files: list[str]) -> None:
def test_auto_register_controller_files_delegates_to_router_register(monkeypatch: object) -> None:
- """
- 校验指定 controller 文件自动注册函数委托给 RouterRegister。
-
- :param monkeypatch: pytest monkeypatch fixture
- :return: None
- """
+ """校验指定 controller 文件自动注册函数委托给 RouterRegister。"""
captured_controller_files = []
captured_dependencies = []
class FakeRouterRegister:
"""
测试用假路由注册器。
+
+ :ivar app: FastAPI对象
"""
def __init__(self, app: FastAPI) -> None:
@@ -195,7 +169,6 @@ def _register_controller_files(
:param controller_files: controller文件列表
:param dependencies: 注册时附加到路由上的依赖项
- :return: None
"""
captured_controller_files.extend(controller_files)
captured_dependencies.extend(dependencies or [])
diff --git a/ruoyi-fastapi-backend/tests/common/test_types.py b/ruoyi-fastapi-backend/tests/common/test_types.py
index f6414be8f..da3bdcc5a 100644
--- a/ruoyi-fastapi-backend/tests/common/test_types.py
+++ b/ruoyi-fastapi-backend/tests/common/test_types.py
@@ -1,7 +1,7 @@
from datetime import UTC, date, datetime, time, timedelta, timezone
import pytest
-from pydantic import BaseModel, TypeAdapter, ValidationError
+from pydantic import BaseModel, Field, TypeAdapter, ValidationError
from sqlalchemy.dialects import mysql, postgresql, sqlite
from sqlalchemy.engine import Dialect
@@ -9,7 +9,9 @@
class TimestampModel(BaseModel):
- occurred_at: ApiUtcDateTime
+ """校验 API 的 UTC 时间字段。"""
+
+ occurred_at: ApiUtcDateTime = Field(description='事件发生的时刻')
class TestApiUtcDateTime:
@@ -24,6 +26,7 @@ class TestApiUtcDateTime:
],
)
def test_aware_inputs_keep_the_same_instant(self, value: object) -> None:
+ """带时区的输入保留同一时刻。"""
model = TimestampModel(occurred_at=value)
assert model.occurred_at == datetime(2026, 8, 28, 2, 30, 0, 123000, tzinfo=UTC)
@@ -46,6 +49,7 @@ def test_aware_inputs_keep_the_same_instant(self, value: object) -> None:
],
)
def test_datetime_requires_a_complete_valid_rfc3339_instant(self, value: object) -> None:
+ """日期时间必须是完整有效的 RFC 3339 时刻。"""
with pytest.raises(ValidationError, match='RFC 3339'):
TimestampModel(occurred_at=value)
@@ -55,6 +59,7 @@ class TestDbUtcDateTime:
@pytest.mark.parametrize('dialect', [mysql.dialect(), postgresql.dialect(), sqlite.dialect()])
def test_null_values_round_trip(self, dialect: Dialect) -> None:
+ """空值可原样读写。"""
column_type = DbUtcDateTime()
assert column_type.process_bind_param(None, dialect) is None
@@ -69,6 +74,7 @@ def test_null_values_round_trip(self, dialect: Dialect) -> None:
],
)
def test_column_uses_the_database_time_representation(self, dialect: Dialect, expected: str) -> None:
+ """列使用数据库的时间表示。"""
assert DbUtcDateTime().compile(dialect=dialect) == expected
@pytest.mark.parametrize(
@@ -78,6 +84,7 @@ def test_column_uses_the_database_time_representation(self, dialect: Dialect, ex
def test_database_roundtrip_preserves_utc_and_millisecond_precision(
self, dialect: Dialect, stored_timezone: timezone | None
) -> None:
+ """数据库读写保留 UTC 和毫秒精度。"""
column_type = DbUtcDateTime()
value = datetime(2026, 8, 28, 10, 30, 0, 123456, tzinfo=timezone(timedelta(hours=8)))
stored = column_type.process_bind_param(value, dialect)
@@ -89,6 +96,7 @@ def test_database_roundtrip_preserves_utc_and_millisecond_precision(
assert restored.tzinfo is UTC
def test_rejects_naive_values(self) -> None:
+ """拒绝未指定时区的时间值。"""
with pytest.raises(ValueError, match='只接受携带时区信息'):
DbUtcDateTime().process_bind_param(datetime(2026, 8, 28, 10, 30), sqlite.dialect())
@@ -98,6 +106,7 @@ class TestBusinessDate:
@pytest.mark.parametrize('value', ['2000-02-29', date(2000, 2, 29)])
def test_valid_date_keeps_its_calendar_value(self, value: object) -> None:
+ """有效日期保留原日历值。"""
adapter = TypeAdapter(BusinessDate)
result = adapter.validate_python(value)
@@ -116,6 +125,7 @@ def test_valid_date_keeps_its_calendar_value(self, value: object) -> None:
],
)
def test_invalid_dates_and_instants_are_rejected(self, value: object) -> None:
+ """拒绝无效日期和时刻。"""
with pytest.raises(ValidationError, match='YYYY-MM-DD'):
TypeAdapter(BusinessDate).validate_python(value)
@@ -125,6 +135,7 @@ class TestBusinessTime:
@pytest.mark.parametrize('value', ['09:15:00.123456', time(9, 15, 0, 123456)])
def test_valid_time_keeps_fractional_seconds(self, value: object) -> None:
+ """有效时间保留小数秒。"""
adapter = TypeAdapter(BusinessTime)
result = adapter.validate_python(value)
@@ -134,5 +145,6 @@ def test_valid_time_keeps_fractional_seconds(self, value: object) -> None:
@pytest.mark.parametrize('value', ['09:15', '24:00:00', '36:00:00', '09:15:00Z', time(9, tzinfo=UTC), 3600])
def test_incomplete_times_offsets_and_durations_are_rejected(self, value: object) -> None:
+ """拒绝不完整的时间、偏移和时长。"""
with pytest.raises(ValidationError, match='一天内时间'):
TypeAdapter(BusinessTime).validate_python(value)
diff --git a/ruoyi-fastapi-backend/tests/config/test_app_settings.py b/ruoyi-fastapi-backend/tests/config/test_app_settings.py
index 235c3dd50..a309beb5e 100644
--- a/ruoyi-fastapi-backend/tests/config/test_app_settings.py
+++ b/ruoyi-fastapi-backend/tests/config/test_app_settings.py
@@ -5,6 +5,7 @@
def test_app_timezone_accepts_valid_iana_name(monkeypatch: pytest.MonkeyPatch) -> None:
+ """应用时区接受有效的 IANA 名称。"""
monkeypatch.setenv('APP_TIMEZONE', 'America/New_York')
assert AppSettings(_env_file=None).app_timezone == 'America/New_York'
@@ -12,5 +13,6 @@ def test_app_timezone_accepts_valid_iana_name(monkeypatch: pytest.MonkeyPatch) -
@pytest.mark.parametrize('timezone_name', ['', 'Not/A-Timezone'])
def test_app_timezone_rejects_invalid_name(timezone_name: str) -> None:
+ """应用时区拒绝无效名称。"""
with pytest.raises(ValidationError, match='APP_TIMEZONE'):
AppSettings(_env_file=None, app_timezone=timezone_name)
diff --git a/ruoyi-fastapi-backend/tests/config/test_current_user_cache_resources.py b/ruoyi-fastapi-backend/tests/config/test_current_user_cache_resources.py
index 13cc26aa1..dda1490ca 100644
--- a/ruoyi-fastapi-backend/tests/config/test_current_user_cache_resources.py
+++ b/ruoyi-fastapi-backend/tests/config/test_current_user_cache_resources.py
@@ -20,7 +20,12 @@
@pytest.fixture
def shared_cache_client(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
- """提交后失效借用应用连接,只监测新建和关闭行为。"""
+ """
+ 提交后失效借用应用连接,只监测新建和关闭行为。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: ``SimpleNamespace`` 实例
+ """
redis = SimpleNamespace(aclose=AsyncMock())
create = AsyncMock(side_effect=AssertionError('借用应用Redis时不能另建连接池'))
invalidate = AsyncMock(return_value=True)
@@ -35,6 +40,7 @@ async def test_shared_redis_is_reused_across_commits(
shared_cache_client: SimpleNamespace,
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """多次提交复用共享 Redis 客户端。"""
monkeypatch.setattr(CurrentUserCacheSession, '_invalidate_cache', _ORIGINAL_INVALIDATE)
shared = shared_cache_client
async with cache_transactions.sessions(info={CurrentUserCacheSession._REDIS_KEY: shared.redis}) as db:
@@ -58,12 +64,19 @@ async def test_shared_cache_failure_preserves_commit_without_closing_pool(
monkeypatch: pytest.MonkeyPatch,
failure: str,
) -> None:
+ """共享缓存失败后保留数据库提交及连接池。"""
monkeypatch.setattr(CurrentUserCacheSession, '_invalidate_cache', _ORIGINAL_INVALIDATE)
monkeypatch.setattr(CurrentUserCacheSession, '_INVALIDATE_TIMEOUT_SECONDS', 0.01)
shared = shared_cache_client
stopped = anyio.Event()
async def invalidate(*args: Any) -> None:
+ """
+ 模拟缓存或会话的失效操作。
+
+ :param args: 传给被调用对象的位置参数
+ :raises RedisConnectionError: 模拟共享 Redis 缓存不可用
+ """
if failure == 'redis':
raise RedisConnectionError('shared cache unavailable')
try:
@@ -91,6 +104,7 @@ async def test_cancelled_shared_invalidation_preserves_borrowed_pool(
monkeypatch: pytest.MonkeyPatch,
cancellation: str,
) -> None:
+ """取消共享缓存失效操作后保留借用的连接池。"""
monkeypatch.setattr(CurrentUserCacheSession, '_invalidate_cache', _ORIGINAL_INVALIDATE)
shared = shared_cache_client
entered = anyio.Event()
@@ -98,6 +112,11 @@ async def test_cancelled_shared_invalidation_preserves_borrowed_pool(
cancelled = anyio.Event()
async def invalidate(*args: Any) -> None:
+ """
+ 模拟缓存或会话的失效操作。
+
+ :param args: 传给被调用对象的位置参数
+ """
entered.set()
try:
await anyio.sleep_forever()
@@ -109,6 +128,11 @@ async def invalidate(*args: Any) -> None:
await db.execute(update(CacheUser).where(CacheUser.user_id == 1).values(user_name='committed'))
async def commit() -> None:
+ """
+ 在测试会话中处理事务提交。
+
+ :raises asyncio.CancelledError: 异步操作被取消时
+ """
try:
await db.commit()
except asyncio.CancelledError:
@@ -141,7 +165,12 @@ async def commit() -> None:
def _registry(env: SimpleNamespace) -> _DataSourceRegistry:
- """使用隔离SQLite引擎验证会话资源注入,不访问配置中的业务数据源。"""
+ """
+ 使用隔离SQLite引擎验证会话资源注入,不访问配置中的业务数据源。
+
+ :param env: 当前运行环境
+ :return: 供调用方使用的 ``registry``
+ """
registry = _DataSourceRegistry(
SimpleNamespace(db_default_source='primary', db_sources={'primary': object(), 'reporting': object()})
)
@@ -162,6 +191,7 @@ async def test_registry_sessions_borrow_registered_cache_client(
source: str | None,
log_sql: bool,
) -> None:
+ """注册表会话借用已注册的缓存客户端。"""
registry = _registry(cache_transactions)
redis = shared_cache_client.redis
registry.set_cache_redis(redis)
@@ -182,6 +212,7 @@ async def test_detaching_shared_redis_only_changes_new_sessions(
cache_transactions: SimpleNamespace, # noqa: F811
shared_cache_client: SimpleNamespace,
) -> None:
+ """解除共享 Redis 绑定只影响新会话。"""
registry = _registry(cache_transactions)
redis = shared_cache_client.redis
registry.set_cache_redis(redis)
@@ -204,6 +235,7 @@ async def test_registry_disposal_releases_reference_without_closing_borrowed_cli
monkeypatch: pytest.MonkeyPatch,
dispose_failure: bool,
) -> None:
+ """释放注册表引用时保留借用的客户端。"""
registry = _registry(cache_transactions)
redis = shared_cache_client.redis
registry.set_cache_redis(redis)
diff --git a/ruoyi-fastapi-backend/tests/config/test_current_user_cache_transactions.py b/ruoyi-fastapi-backend/tests/config/test_current_user_cache_transactions.py
index f9099466d..e1ddaa6df 100644
--- a/ruoyi-fastapi-backend/tests/config/test_current_user_cache_transactions.py
+++ b/ruoyi-fastapi-backend/tests/config/test_current_user_cache_transactions.py
@@ -39,45 +39,65 @@
class CacheTestBase(DeclarativeBase):
- pass
+ """提供缓存集成测试的声明式模型基类。"""
class CacheUser(CacheTestBase):
+ """缓存集成测试使用的用户表映射。"""
+
__tablename__ = 'sys_user'
- user_id: Mapped[int] = mapped_column(Integer, primary_key=True)
- user_name: Mapped[str] = mapped_column(String, unique=True)
+ user_id: Mapped[int] = mapped_column(Integer, primary_key=True, comment='用户标识')
+ user_name: Mapped[str] = mapped_column(String, unique=True, comment='用户名称')
class CacheRole(CacheTestBase):
+ """缓存集成测试使用的角色表映射。"""
+
__tablename__ = 'sys_role'
- role_id: Mapped[int] = mapped_column(Integer, primary_key=True)
- role_name: Mapped[str] = mapped_column(String)
+ role_id: Mapped[int] = mapped_column(Integer, primary_key=True, comment='角色标识')
+ role_name: Mapped[str] = mapped_column(String, comment='角色名称')
class CacheUserRole(CacheTestBase):
+ """缓存集成测试使用的用户角色关联表映射。"""
+
__tablename__ = 'sys_user_role'
- user_id: Mapped[int] = mapped_column(Integer, primary_key=True)
- role_id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ user_id: Mapped[int] = mapped_column(Integer, primary_key=True, comment='用户标识')
+ role_id: Mapped[int] = mapped_column(Integer, primary_key=True, comment='角色标识')
class CacheJob(CacheTestBase):
+ """缓存集成测试使用的任务表映射。"""
+
__tablename__ = 'sys_job'
- job_id: Mapped[int] = mapped_column(Integer, primary_key=True)
- job_name: Mapped[str] = mapped_column(String)
+ job_id: Mapped[int] = mapped_column(Integer, primary_key=True, comment='任务标识')
+ job_name: Mapped[str] = mapped_column(String, comment='任务名称')
SHARED_TABLES = {
- name: Table(name, CacheTestBase.metadata, Column('id', Integer, primary_key=True), Column('name', String))
+ name: Table(
+ name,
+ CacheTestBase.metadata,
+ Column('id', Integer, primary_key=True, comment='测试记录标识'),
+ Column('name', String, comment='测试记录名称'),
+ )
for name in ('sys_menu', 'sys_dept', 'sys_post', 'sys_role_menu', 'sys_role_dept')
}
@pytest_asyncio.fixture
async def cache_transactions(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[SimpleNamespace]:
+ """
+ 为缓存事务测试准备数据库和运行配置。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :yield: ``SimpleNamespace`` 实例
+ """
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', True)
engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "cache-transactions.db"}')
async with engine.begin() as connection:
@@ -90,6 +110,12 @@ async def cache_transactions(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) ->
invalidations = []
async def invalidate(session: CurrentUserCacheSession, user_ids: set[int] | None) -> None:
+ """
+ 模拟缓存或会话的失效操作。
+
+ :param session: 登记当前用户资料和权限变更,在事务提交后使缓存失效
+ :param user_ids: 当前操作涉及的用户标识集合
+ """
async with engine.connect() as connection:
names = (await connection.execute(select(CacheUser.user_name).order_by(CacheUser.user_id))).scalars().all()
invalidations.append((user_ids, names))
@@ -103,6 +129,7 @@ async def invalidate(session: CurrentUserCacheSession, user_ids: set[int] | None
@pytest.mark.asyncio
async def test_user_change_invalidates_only_after_commit(cache_transactions: SimpleNamespace) -> None:
+ """用户变更仅在提交后使缓存失效。"""
env = cache_transactions
async with env.sessions() as db:
user = await db.get(CacheUser, 1)
@@ -117,6 +144,7 @@ async def test_user_change_invalidates_only_after_commit(cache_transactions: Sim
@pytest.mark.asyncio
@pytest.mark.parametrize('finish', ['rollback', 'close'])
async def test_rollback_and_close_discard_changes(cache_transactions: SimpleNamespace, finish: str) -> None:
+ """回滚和关闭会话时丢弃待处理变更。"""
env = cache_transactions
async with env.sessions() as db:
await db.execute(update(CacheUser).where(CacheUser.user_id == 1).values(user_name='changed'))
@@ -127,6 +155,7 @@ async def test_rollback_and_close_discard_changes(cache_transactions: SimpleName
@pytest.mark.asyncio
async def test_nested_commit_waits_for_outer_commit(cache_transactions: SimpleNamespace) -> None:
+ """嵌套提交等待外层事务提交。"""
env = cache_transactions
async with env.sessions.begin() as db:
await db.execute(update(CacheUser).where(CacheUser.user_id == 1).values(user_name='outer'))
@@ -138,6 +167,7 @@ async def test_nested_commit_waits_for_outer_commit(cache_transactions: SimpleNa
@pytest.mark.asyncio
async def test_nested_rollback_does_not_invalidate_rolled_back_user(cache_transactions: SimpleNamespace) -> None:
+ """嵌套回滚不使已回滚用户的缓存失效。"""
env = cache_transactions
async with env.sessions.begin() as db:
await db.execute(update(CacheUser).where(CacheUser.user_id == 1).values(user_name='outer'))
@@ -149,6 +179,7 @@ async def test_nested_rollback_does_not_invalidate_rolled_back_user(cache_transa
@pytest.mark.asyncio
async def test_nested_commit_then_outer_rollback_does_not_invalidate(cache_transactions: SimpleNamespace) -> None:
+ """嵌套提交后回滚外层事务不会使缓存失效。"""
env = cache_transactions
async with env.sessions() as db:
await db.execute(update(CacheUser).where(CacheUser.user_id == 1).values(user_name='outer'))
@@ -182,6 +213,7 @@ async def test_nested_commit_then_outer_rollback_does_not_invalidate(cache_trans
async def test_core_and_text_mutations_are_tracked(
cache_transactions: SimpleNamespace, statement: Any, expected: set[int] | None
) -> None:
+ """跟踪 Core 语句和文本 SQL 的修改。"""
env = cache_transactions
async with env.sessions.begin() as db:
await db.execute(statement)
@@ -209,6 +241,7 @@ async def test_alias_mutations_invalidate_only_auth_tables(
name_column: str,
tracked: bool,
) -> None:
+ """别名写入仅使认证表对应的缓存失效。"""
env = cache_transactions
if alias_type == 'orm':
target = aliased(model)
@@ -240,6 +273,7 @@ async def test_alias_mutations_invalidate_only_auth_tables(
async def test_alias_target_with_original_table_filter_invalidates_all_users(
cache_transactions: SimpleNamespace,
) -> None:
+ """别名目标使用原表过滤时使全部用户缓存失效。"""
env = cache_transactions
users = CacheUser.__table__
target = users.alias('target')
@@ -256,6 +290,7 @@ async def test_alias_target_with_original_table_filter_invalidates_all_users(
async def test_wrapped_write_invalidates_only_after_commit(
cache_transactions: SimpleNamespace, wrapper: str, finish: str
) -> None:
+ """包装后的写入仅在提交后使缓存失效。"""
env = cache_transactions
raw_sql = text("UPDATE sys_user SET user_name = 'changed' WHERE user_id = 1 RETURNING user_id, user_name")
if wrapper == 'columns':
@@ -282,6 +317,7 @@ async def test_wrapped_write_invalidates_only_after_commit(
async def test_readonly_wrappers_and_sql_fragments_do_not_invalidate(
cache_transactions: SimpleNamespace, wrapper: str
) -> None:
+ """只读包装和 SQL 片段不触发缓存失效。"""
env = cache_transactions
raw_sql = text('SELECT user_id, user_name FROM sys_user WHERE user_id = 1')
if wrapper == 'columns':
@@ -308,6 +344,7 @@ async def test_readonly_wrappers_and_sql_fragments_do_not_invalidate(
def test_nested_dml_cte_invalidates_auth_writes_conservatively(
monkeypatch: pytest.MonkeyPatch, operation: str, outer: str, auth_table: bool
) -> None:
+ """嵌套 DML 公用表表达式按保守策略使认证缓存失效。"""
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', True)
target = CacheUser.__table__ if auth_table else CacheJob.__table__
id_column, name_column = ('user_id', 'user_name') if auth_table else ('job_id', 'job_name')
@@ -353,6 +390,7 @@ def test_nested_dml_cte_invalidates_auth_writes_conservatively(
],
)
def test_explain_analyze_write_requires_invalidation(monkeypatch: pytest.MonkeyPatch, sql: str) -> None:
+ """分析实际执行的写语句时需要使缓存失效。"""
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', True)
with CurrentUserCacheSession() as db, db.begin() as transaction:
state = SimpleNamespace(
@@ -386,6 +424,7 @@ def test_join_update_tracks_auth_tables_after_sql_execution(
joined_id_column: str,
tracked: bool,
) -> None:
+ """连接更新在 SQL 执行后跟踪认证表。"""
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', True)
target = model.__table__
joined = joined_model.__table__.alias('joined')
@@ -419,6 +458,7 @@ def test_join_update_tracks_auth_tables_after_sql_execution(
@pytest.mark.asyncio
async def test_shared_change_overrides_user_scope(cache_transactions: SimpleNamespace) -> None:
+ """共享数据变更优先于单用户范围。"""
env = cache_transactions
async with env.sessions.begin() as db:
await db.execute(update(CacheUser).where(CacheUser.user_id == 1).values(user_name='changed'))
@@ -429,6 +469,7 @@ async def test_shared_change_overrides_user_scope(cache_transactions: SimpleName
@pytest.mark.asyncio
async def test_readonly_and_unchanged_orm_object_do_not_invalidate(cache_transactions: SimpleNamespace) -> None:
+ """只读或未发生变化的 ORM 对象不使缓存失效。"""
env = cache_transactions
async with env.sessions.begin() as db:
user = await db.get(CacheUser, 1)
@@ -441,6 +482,7 @@ async def test_readonly_and_unchanged_orm_object_do_not_invalidate(cache_transac
async def test_disabled_cache_does_not_register_mutations(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """禁用缓存后不登记变更。"""
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', False)
async with cache_transactions.sessions.begin() as db:
await db.execute(update(CacheUser).values(user_name=CacheUser.user_name + '-new'))
@@ -451,6 +493,7 @@ async def test_disabled_cache_does_not_register_mutations(
@pytest.mark.asyncio
async def test_failed_commit_does_not_invalidate(cache_transactions: SimpleNamespace) -> None:
+ """提交失败时不使缓存失效。"""
env = cache_transactions
async with env.sessions() as db:
user = await db.get(CacheUser, 1)
@@ -464,10 +507,12 @@ async def test_failed_commit_does_not_invalidate(cache_transactions: SimpleNames
@pytest.mark.asyncio
async def test_cancellation_before_commit_rolls_back(cache_transactions: SimpleNamespace) -> None:
+ """提交前取消操作将回滚事务。"""
env = cache_transactions
entered = asyncio.Event()
async def mutate() -> None:
+ """在测试事务中修改与缓存关联的数据。"""
async with env.sessions.begin() as db:
await db.execute(update(CacheUser).where(CacheUser.user_id == 1).values(user_name='cancelled'))
entered.set()
@@ -487,10 +532,17 @@ async def mutate() -> None:
async def test_cancellation_after_commit_does_not_undo_committed_data(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """提交后取消操作保留已提交的数据。"""
env = cache_transactions
entered = asyncio.Event()
async def invalidate(session: CurrentUserCacheSession, user_ids: set[int] | None) -> None:
+ """
+ 模拟缓存或会话的失效操作。
+
+ :param session: 登记当前用户资料和权限变更,在事务提交后使缓存失效
+ :param user_ids: 当前操作涉及的用户标识集合
+ """
assert user_ids == {1}
entered.set()
await asyncio.Event().wait()
@@ -498,6 +550,7 @@ async def invalidate(session: CurrentUserCacheSession, user_ids: set[int] | None
monkeypatch.setattr(CurrentUserCacheSession, '_invalidate_cache', invalidate)
async def mutate() -> None:
+ """在测试事务中修改与缓存关联的数据。"""
async with env.sessions() as db:
await db.execute(update(CacheUser).where(CacheUser.user_id == 1).values(user_name='committed'))
await db.commit()
@@ -517,6 +570,7 @@ async def mutate() -> None:
async def test_all_shared_permission_tables_invalidate_global(
cache_transactions: SimpleNamespace, table_name: str
) -> None:
+ """任意共享权限表变更均使全局缓存失效。"""
env = cache_transactions
async with env.sessions.begin() as db:
await db.execute(insert(SHARED_TABLES[table_name]).values(id=1, name='changed'))
@@ -525,6 +579,7 @@ async def test_all_shared_permission_tables_invalidate_global(
@pytest.mark.asyncio
async def test_multiple_savepoint_levels_preserve_parent_changes(cache_transactions: SimpleNamespace) -> None:
+ """多层保存点保留父事务的变更。"""
env = cache_transactions
async with env.sessions.begin() as db:
await db.execute(update(CacheUser).where(CacheUser.user_id == 1).values(user_name='outer'))
@@ -537,6 +592,7 @@ async def test_multiple_savepoint_levels_preserve_parent_changes(cache_transacti
@pytest.mark.asyncio
async def test_session_can_be_reused_after_commit_and_rollback(cache_transactions: SimpleNamespace) -> None:
+ """提交或回滚后可复用会话。"""
env = cache_transactions
async with env.sessions() as db:
await db.execute(update(CacheUser).where(CacheUser.user_id == 1).values(user_name='first-commit'))
@@ -552,10 +608,16 @@ async def test_session_can_be_reused_after_commit_and_rollback(cache_transaction
async def test_disabled_cache_does_not_compile_tracking_sql(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """禁用缓存后跳过跟踪 SQL 的编译。"""
env = cache_transactions
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', False)
def unexpected_scope(*args: Any) -> None:
+ """
+ 在调用时报告预期的测试失败:关闭缓存后不应分析用户变更范围。
+
+ :param args: 传给被调用对象的位置参数
+ """
pytest.fail('关闭缓存后不应分析用户变更范围')
monkeypatch.setattr(CurrentUserCacheSession, '_where_user_ids', unexpected_scope)
@@ -570,6 +632,7 @@ def unexpected_scope(*args: Any) -> None:
async def test_cache_failure_does_not_turn_committed_write_into_error(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, failure: str
) -> None:
+ """缓存失败不影响已提交写入的结果。"""
env = cache_transactions
redis = SimpleNamespace(aclose=AsyncMock())
create = AsyncMock(return_value=redis)
@@ -583,6 +646,11 @@ async def test_cache_failure_does_not_turn_committed_write_into_error(
else:
async def blocked(*args: Any) -> None:
+ """
+ 将调用保持在等待状态以验证取消行为。
+
+ :param args: 传给被调用对象的位置参数
+ """
await asyncio.Event().wait()
if failure == 'create_timeout':
@@ -606,6 +674,7 @@ async def blocked(*args: Any) -> None:
async def test_sync_session_commit_survives_missing_greenlet_and_closes_coroutine(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, recwarn: pytest.WarningsRecorder
) -> None:
+ """同步会话缺少 greenlet 时完成提交并关闭协程。"""
engine = create_engine(cache_transactions.engine.url.set(drivername='sqlite'))
create = AsyncMock()
monkeypatch.setattr(RedisUtil, 'create_redis_pool', create)
@@ -628,6 +697,7 @@ async def test_sync_session_commit_survives_missing_greenlet_and_closes_coroutin
async def test_listener_failure_does_not_change_committed_database_result(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, stage: str
) -> None:
+ """监听器失败不改变已提交的数据库结果。"""
invalidate = AsyncMock(side_effect=RuntimeError('cache listener unavailable'))
async with cache_transactions.sessions() as db:
await db.execute(update(CacheUser).where(CacheUser.user_id == 1).values(user_name='committed'))
@@ -651,6 +721,7 @@ async def test_listener_failure_does_not_change_committed_database_result(
async def test_commit_invalidates_cache_and_closes_redis(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """提交后使缓存失效并关闭 Redis 客户端。"""
redis = SimpleNamespace(aclose=AsyncMock())
create = AsyncMock(return_value=redis)
invalidate = AsyncMock(return_value=True)
@@ -670,6 +741,7 @@ async def test_commit_invalidates_cache_and_closes_redis(
async def test_unknown_namespace_does_not_invalidate_another_database(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """未知命名空间不会使其他数据库的缓存失效。"""
create = AsyncMock()
monkeypatch.setattr(RedisUtil, 'create_redis_pool', create)
monkeypatch.setattr(CurrentUserCacheUtil, 'namespace_for_bind', lambda bind: None)
@@ -683,6 +755,7 @@ async def test_unknown_namespace_does_not_invalidate_another_database(
async def test_cancellation_closes_cache_client_and_preserves_commit(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """取消操作时关闭缓存客户端并保留提交。"""
redis = SimpleNamespace(aclose=AsyncMock())
monkeypatch.setattr(RedisUtil, 'create_redis_pool', AsyncMock(return_value=redis))
monkeypatch.setattr(CurrentUserCacheUtil, 'invalidate', AsyncMock(side_effect=asyncio.CancelledError))
@@ -703,6 +776,7 @@ async def test_cancellation_closes_cache_client_and_preserves_commit(
async def test_anyio_cancellation_finishes_cache_cleanup_and_preserves_commit( # noqa: PLR0915
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, cancellation: str, stage: str
) -> None:
+ """AnyIO 取消操作后完成缓存清理并保留提交。"""
entered = anyio.Event()
release_close = anyio.Event()
closed = anyio.Event()
@@ -711,6 +785,11 @@ async def test_anyio_cancellation_finishes_cache_cleanup_and_preserves_commit(
cancel_scope = None
async def invalidate(*args: Any) -> None:
+ """
+ 模拟缓存或会话的失效操作。
+
+ :param args: 传给被调用对象的位置参数
+ """
if stage != 'invalidate':
return
entered.set()
@@ -721,6 +800,7 @@ async def invalidate(*args: Any) -> None:
await anyio.sleep_forever()
async def close() -> None:
+ """记录测试资源的关闭过程。"""
if stage == 'close':
entered.set()
if cancellation == 'scope':
@@ -735,6 +815,13 @@ async def close() -> None:
redis = SimpleNamespace(aclose=AsyncMock(side_effect=close))
async def invalidate_cache(session: CurrentUserCacheSession, user_ids: set[int] | None) -> None:
+ """
+ 模拟事务完成时清除缓存。
+
+ :param session: 登记当前用户资料和权限变更,在事务提交后使缓存失效
+ :param user_ids: 当前操作涉及的用户标识集合
+ :raises Exception: 底层操作失败时向调用方传播异常
+ """
try:
await _ORIGINAL_INVALIDATE(session, user_ids)
except anyio.get_cancelled_exc_class():
@@ -748,6 +835,11 @@ async def invalidate_cache(session: CurrentUserCacheSession, user_ids: set[int]
await db.execute(update(CacheUser).where(CacheUser.user_id == 1).values(user_name='committed'))
async def commit() -> None:
+ """
+ 在测试会话中处理事务提交。
+
+ :raises Exception: 底层操作失败时向调用方传播异常
+ """
try:
await db.commit()
except anyio.get_cancelled_exc_class():
@@ -780,11 +872,18 @@ async def commit() -> None:
async def test_concurrent_commits_invalidate_each_user_without_shared_state(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """并发提交分别使对应用户缓存失效。"""
entered = asyncio.Event()
release = asyncio.Event()
invalidations = []
async def invalidate(session: CurrentUserCacheSession, user_ids: set[int] | None) -> None:
+ """
+ 模拟缓存或会话的失效操作。
+
+ :param session: 登记当前用户资料和权限变更,在事务提交后使缓存失效
+ :param user_ids: 当前操作涉及的用户标识集合
+ """
if user_ids == {1}:
entered.set()
await release.wait()
@@ -793,6 +892,11 @@ async def invalidate(session: CurrentUserCacheSession, user_ids: set[int] | None
monkeypatch.setattr(CurrentUserCacheSession, '_invalidate_cache', invalidate)
async def mutate(user_id: int) -> None:
+ """
+ 在测试事务中修改与缓存关联的数据。
+
+ :param user_id: 用户的唯一标识
+ """
async with cache_transactions.sessions.begin() as db:
await db.execute(update(CacheUser).where(CacheUser.user_id == user_id).values(user_name=f'user-{user_id}'))
@@ -806,6 +910,7 @@ async def mutate(user_id: int) -> None:
@pytest.mark.asyncio
async def test_orm_bulk_user_update_uses_primary_key_scope(cache_transactions: SimpleNamespace) -> None:
+ """ORM 批量用户更新按主键确定范围。"""
env = cache_transactions
async with env.sessions.begin() as db:
await db.execute(update(CacheUser), [{'user_id': 1, 'user_name': 'changed'}])
@@ -816,6 +921,7 @@ async def test_orm_bulk_user_update_uses_primary_key_scope(cache_transactions: S
async def test_core_bulk_update_cannot_assume_parameter_is_a_primary_key_filter(
cache_transactions: SimpleNamespace,
) -> None:
+ """Core 批量更新不会将普通参数误作主键过滤条件。"""
env = cache_transactions
async with env.sessions.begin() as db:
await db.execute(
@@ -829,6 +935,7 @@ async def test_core_bulk_update_cannot_assume_parameter_is_a_primary_key_filter(
async def test_user_relation_move_invalidates_old_and_new_users(
cache_transactions: SimpleNamespace, assignment: str
) -> None:
+ """移动用户关联后同时使新旧用户缓存失效。"""
env = cache_transactions
relation = CacheUserRole.__table__
async with env.engine.begin() as connection:
@@ -859,6 +966,7 @@ async def test_user_relation_move_invalidates_old_and_new_users(
@pytest.mark.asyncio
async def test_core_tuple_parameters_commit_with_precise_user_scope(cache_transactions: SimpleNamespace) -> None:
+ """Core 元组参数提交后按准确的用户范围使缓存失效。"""
env = cache_transactions
users = CacheUser.__table__
statement = update(users).where(users.c.user_id == bindparam('target_id')).values(user_name=bindparam('next_name'))
@@ -872,9 +980,16 @@ async def test_core_tuple_parameters_commit_with_precise_user_scope(cache_transa
async def test_scope_analysis_failure_preserves_sql_result_and_invalidates_globally(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """范围分析失败时保留 SQL 结果并使全局缓存失效。"""
env = cache_transactions
def failed_scope(*args: Any) -> None:
+ """
+ 模拟此操作抛出 ValueError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :raises ValueError: 模拟 SQL 参数格式无法识别
+ """
raise ValueError('unexpected parameter format')
monkeypatch.setattr(CurrentUserCacheSession, '_where_user_ids', failed_scope)
@@ -888,9 +1003,15 @@ def failed_scope(*args: Any) -> None:
async def test_sql_execution_failure_still_propagates_before_scope_analysis(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """范围分析前的 SQL 执行错误继续传播。"""
env = cache_transactions
def unexpected_scope(*args: Any) -> None:
+ """
+ 在调用时报告预期的测试失败:SQL执行失败后不应分析缓存变更范围。
+
+ :param args: 传给被调用对象的位置参数
+ """
pytest.fail('SQL执行失败后不应分析缓存变更范围')
monkeypatch.setattr(CurrentUserCacheSession, '_where_user_ids', unexpected_scope)
@@ -906,9 +1027,16 @@ def unexpected_scope(*args: Any) -> None:
async def test_scope_analysis_cancellation_is_not_swallowed(
cache_transactions: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """范围分析期间的取消异常继续传播。"""
env = cache_transactions
def cancelled_scope(*args: Any) -> None:
+ """
+ 模拟此操作抛出 asyncio.CancelledError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :raises asyncio.CancelledError: 异步操作被取消时
+ """
raise asyncio.CancelledError
monkeypatch.setattr(CurrentUserCacheSession, '_where_user_ids', cancelled_scope)
diff --git a/ruoyi-fastapi-backend/tests/config/test_database_exception_handlers.py b/ruoyi-fastapi-backend/tests/config/test_database_exception_handlers.py
index 5b0f39631..4928b8887 100644
--- a/ruoyi-fastapi-backend/tests/config/test_database_exception_handlers.py
+++ b/ruoyi-fastapi-backend/tests/config/test_database_exception_handlers.py
@@ -23,6 +23,7 @@
],
)
async def test_data_source_exceptions_use_service_exception_handler(exception: Exception) -> None:
+ """数据源异常由服务异常处理器处理。"""
app = FastAPI()
handle_exception(app)
diff --git a/ruoyi-fastapi-backend/tests/config/test_database_registry.py b/ruoyi-fastapi-backend/tests/config/test_database_registry.py
index e8f428d00..23e464e05 100644
--- a/ruoyi-fastapi-backend/tests/config/test_database_registry.py
+++ b/ruoyi-fastapi-backend/tests/config/test_database_registry.py
@@ -16,6 +16,12 @@
def _source(*, required: bool = True) -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param required: 是否必须提供该字段
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(
db_type='mysql',
db_host='db.example',
@@ -34,6 +40,7 @@ def _source(*, required: bool = True) -> SimpleNamespace:
def test_database_urls_use_structured_url_and_hide_password() -> None:
+ """以结构化 URL 表示数据库地址并隐藏密码。"""
config = _source()
async_url = database.build_async_sqlalchemy_database_url(config)
sync_url = database.build_sync_sqlalchemy_database_url(config)
@@ -59,6 +66,7 @@ def test_engine_factories_use_driver_specific_connect_timeout(
async_timeout_key: str,
sync_timeout_key: str,
) -> None:
+ """引擎工厂使用驱动对应的连接超时。"""
config = _source()
config.db_type = db_type
config.db_port = db_port
@@ -67,10 +75,24 @@ def test_engine_factories_use_driver_specific_connect_timeout(
captured_options: dict[str, dict[str, object]] = {}
def create_async_engine(_url: URL, **options: object) -> object:
+ """
+ 捕获异步引擎的创建参数。
+
+ :param _url: 回调接收的目标 URL
+ :param options: 调用方按名称传入的附加选项
+ :return: 用于异步数据库操作的 SQLAlchemy 引擎
+ """
captured_options['async'] = options
return async_engine
def create_sync_engine(_url: URL, **options: object) -> object:
+ """
+ 捕获同步引擎的创建参数。
+
+ :param _url: 回调接收的目标 URL
+ :param options: 调用方按名称传入的附加选项
+ :return: 用于同步数据库操作的 SQLAlchemy 引擎
+ """
captured_options['sync'] = options
return sync_engine
@@ -94,41 +116,88 @@ def create_sync_engine(_url: URL, **options: object) -> object:
def test_async_session_factory_disables_expiration_after_commit() -> None:
+ """异步会话工厂禁用提交后过期。"""
factory = database.create_async_session_factory(MagicMock())
assert factory.kw['expire_on_commit'] is False
class _Begin:
+ """
+ 提供事务上下文的测试替身。
+
+ :ivar should_fail: 是否在此步骤模拟失败
+ :ivar session_timezone: 为数据库会话设置的时区
+ """
+
def __init__(self, should_fail: bool = False, session_timezone: str = '+00:00') -> None:
+ """
+ 初始化测试夹具的 ``should_fail``, ``session_timezone``。
+
+ :param should_fail: 是否在此步骤模拟失败
+ :param session_timezone: 为数据库会话设置的时区
+ """
self.should_fail = should_fail
self.session_timezone = session_timezone
async def __aenter__(self) -> Self:
+ """
+ 进入异步上下文并提供测试资源。
+
+ :raises RuntimeError: 模拟建立含敏感诊断的数据库会话失败
+ :return: 当前实例
+ """
if self.should_fail:
raise RuntimeError('password=secret')
return self
async def __aexit__(self, *_args: object) -> bool:
+ """
+ 在此测试分支返回 False。
+
+ :param _args: 调用方传入的其余位置参数
+ :return: 此分支的固定值 ``False``
+ """
return False
async def execute(self, statement: object) -> SimpleNamespace:
+ """
+ 按测试场景处理数据库查询并提供结果。
+
+ :param statement: 即将执行的数据库语句
+ :return: ``SimpleNamespace`` 实例
+ """
scalar_value = 1 if str(statement) == 'SELECT 1' else self.session_timezone
return SimpleNamespace(scalar_one=lambda: scalar_value)
class _Engine:
+ """
+ 提供数据库引擎的测试替身。
+
+ :ivar should_fail: 是否在此步骤模拟失败
+ :ivar session_timezone: 为数据库会话设置的时区
+ :ivar dispose: 释放测试资源时调用的函数
+ """
+
def __init__(self) -> None:
+ """初始化测试夹具的 ``should_fail``, ``session_timezone``, ``dispose``。"""
self.should_fail = True
self.session_timezone = '+00:00'
self.dispose = AsyncMock()
def begin(self) -> _Begin:
+ """
+ 提供受测试状态控制的事务上下文。
+
+ :return: 受测试状态控制的事务上下文
+ """
return _Begin(self.should_fail, self.session_timezone)
@pytest.mark.asyncio
async def test_health_check_rejects_non_utc_database_session(monkeypatch: pytest.MonkeyPatch) -> None:
+ """健康检查拒绝非 UTC 的数据库会话。"""
engine = _Engine()
engine.should_fail = False
engine.session_timezone = 'SYSTEM'
@@ -146,6 +215,7 @@ async def test_health_check_rejects_non_utc_database_session(monkeypatch: pytest
@pytest.mark.asyncio
async def test_initialize_can_suppress_worker_startup_logs(monkeypatch: pytest.MonkeyPatch) -> None:
+ """初始化时可关闭工作进程启动日志。"""
primary_engine = _Engine()
primary_engine.should_fail = False
optional_engine = _Engine()
@@ -179,6 +249,7 @@ async def test_initialize_can_suppress_worker_startup_logs(monkeypatch: pytest.M
@pytest.mark.asyncio
async def test_initialize_logs_source_name(monkeypatch: pytest.MonkeyPatch) -> None:
+ """初始化日志包含数据源名称。"""
engine = _Engine()
engine.should_fail = False
monkeypatch.setattr(database, 'create_async_db_engine', lambda config: engine)
@@ -199,6 +270,7 @@ async def test_initialize_logs_source_name(monkeypatch: pytest.MonkeyPatch) -> N
@pytest.mark.asyncio
async def test_optional_source_recovers_after_cooldown(monkeypatch: pytest.MonkeyPatch) -> None:
+ """可选数据源在冷却期后恢复。"""
primary_engine = _Engine()
primary_engine.should_fail = False
optional_engine = _Engine()
@@ -226,6 +298,7 @@ async def test_optional_source_recovers_after_cooldown(monkeypatch: pytest.Monke
@pytest.mark.asyncio
async def test_optional_engine_creation_failure_degrades_and_recovers(monkeypatch: pytest.MonkeyPatch) -> None:
+ """可选引擎创建失败后可降级并恢复。"""
primary_config = _source()
optional_config = _source(required=False)
primary_engine = _Engine()
@@ -235,6 +308,13 @@ async def test_optional_engine_creation_failure_degrades_and_recovers(monkeypatc
optional_creation_fails = True
def create_engine(config: SimpleNamespace) -> _Engine:
+ """
+ 根据测试数据源配置创建引擎替身。
+
+ :param config: 当前对象使用的配置
+ :raises ModuleNotFoundError: 模拟可选数据源的驱动未安装
+ :return: 为目标数据源选择的测试引擎
+ """
nonlocal optional_creation_fails
if config is optional_config and optional_creation_fails:
raise ModuleNotFoundError('driver is not installed')
@@ -265,12 +345,20 @@ def create_engine(config: SimpleNamespace) -> _Engine:
@pytest.mark.asyncio
async def test_required_engine_creation_failure_disposes_other_sources(monkeypatch: pytest.MonkeyPatch) -> None:
+ """必需引擎创建失败时释放其他数据源。"""
primary_config = _source()
optional_config = _source(required=False)
optional_engine = _Engine()
optional_engine.should_fail = False
def create_engine(config: SimpleNamespace) -> _Engine:
+ """
+ 根据测试数据源配置创建引擎替身。
+
+ :param config: 当前对象使用的配置
+ :raises ModuleNotFoundError: 模拟必需数据源的驱动未安装
+ :return: 供调用方使用的 ``optional_engine``
+ """
if config is primary_config:
raise ModuleNotFoundError('required driver is not installed')
return optional_engine
@@ -292,6 +380,7 @@ def create_engine(config: SimpleNamespace) -> _Engine:
@pytest.mark.asyncio
async def test_initialize_logs_all_sources_and_safe_failure_details(monkeypatch: pytest.MonkeyPatch) -> None:
+ """初始化日志列出全部数据源并隐藏敏感错误信息。"""
primary_engine = _Engine()
reporting_engine = _Engine()
reporting_engine.should_fail = False
@@ -335,6 +424,7 @@ async def test_initialize_logs_all_sources_and_safe_failure_details(monkeypatch:
@pytest.mark.asyncio
async def test_invalidated_operational_error_marks_source_down_then_recovers(monkeypatch: pytest.MonkeyPatch) -> None:
+ """连接失效时标记数据源离线并允许恢复。"""
engine = _Engine()
engine.should_fail = False
monkeypatch.setattr(database, 'create_async_db_engine', lambda config: engine)
@@ -347,6 +437,11 @@ async def test_invalidated_operational_error_marks_source_down_then_recovers(mon
@asynccontextmanager
async def session_factory() -> AsyncGenerator[object, None]:
+ """
+ 提供测试会话并跟踪关闭状态。
+
+ :yield: 测试会话并跟踪关闭状态
+ """
nonlocal session_closed
try:
yield object()
@@ -378,6 +473,7 @@ async def session_factory() -> AsyncGenerator[object, None]:
@pytest.mark.asyncio
async def test_non_invalidated_operational_error_does_not_mark_source_down(monkeypatch: pytest.MonkeyPatch) -> None:
+ """未使连接失效的操作异常不会标记数据源离线。"""
engine = _Engine()
engine.should_fail = False
monkeypatch.setattr(database, 'create_async_db_engine', lambda config: engine)
@@ -389,6 +485,11 @@ async def test_non_invalidated_operational_error_does_not_mark_source_down(monke
@asynccontextmanager
async def session_factory() -> AsyncGenerator[object, None]:
+ """
+ 提供测试会话并跟踪关闭状态。
+
+ :yield: 测试会话并跟踪关闭状态
+ """
yield object()
runtime.async_session_factory = session_factory
@@ -404,6 +505,7 @@ async def session_factory() -> AsyncGenerator[object, None]:
@pytest.mark.asyncio
async def test_multiple_sources_have_independent_engines_and_factories(monkeypatch: pytest.MonkeyPatch) -> None:
+ """多个数据源使用独立引擎和会话工厂。"""
primary_config = _source()
reporting_config = _source(required=False)
engines = {id(primary_config): _Engine(), id(reporting_config): _Engine()}
@@ -429,6 +531,7 @@ async def test_multiple_sources_have_independent_engines_and_factories(monkeypat
@pytest.mark.asyncio
async def test_dispose_all_releases_sync_and_async_engines(monkeypatch: pytest.MonkeyPatch) -> None:
+ """统一释放同步和异步引擎。"""
engine = _Engine()
engine.should_fail = False
sync_engine = MagicMock()
@@ -449,6 +552,7 @@ async def test_dispose_all_releases_sync_and_async_engines(monkeypatch: pytest.M
@pytest.mark.asyncio
async def test_dispose_all_attempts_every_engine_when_disposal_fails(monkeypatch: pytest.MonkeyPatch) -> None:
+ """某个引擎释放失败后仍尝试释放其他引擎。"""
registry = database._DataSourceRegistry(
SimpleNamespace(
db_default_source='primary',
@@ -479,6 +583,7 @@ async def test_dispose_all_attempts_every_engine_when_disposal_fails(monkeypatch
def test_dependency_provider_is_cached_per_source() -> None:
+ """按数据源缓存依赖提供器。"""
assert get_db_session_provider('reporting') is get_db_session_provider('reporting')
assert get_db_session_provider('reporting') is not get_db_session_provider('archive')
assert DBSessionDependency('reporting').dependency is get_db_session_provider('reporting')
diff --git a/ruoyi-fastapi-backend/tests/config/test_database_settings.py b/ruoyi-fastapi-backend/tests/config/test_database_settings.py
index 5fc7f48d9..c0ff82ac3 100644
--- a/ruoyi-fastapi-backend/tests/config/test_database_settings.py
+++ b/ruoyi-fastapi-backend/tests/config/test_database_settings.py
@@ -9,6 +9,12 @@
def _source(**overrides: object) -> dict[str, object]:
+ """
+ 构造数据库配置测试所需的数据源。
+
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 数据库配置测试所需的数据源
+ """
values: dict[str, object] = {
'db_type': 'mysql',
'db_host': 'db.example.test',
@@ -22,6 +28,7 @@ def _source(**overrides: object) -> dict[str, object]:
def test_db_sources_json_is_parsed_and_password_is_secret(monkeypatch: pytest.MonkeyPatch) -> None:
+ """解析数据源 JSON 并保护密码字段。"""
monkeypatch.setenv('DB_DEFAULT_SOURCE', 'primary')
monkeypatch.setenv('DB_SOURCES', json.dumps({'primary': _source()}))
@@ -37,12 +44,14 @@ def test_db_sources_json_is_parsed_and_password_is_secret(monkeypatch: pytest.Mo
def test_postgresql_uses_sqlglot_postgres_dialect() -> None:
+ """PostgreSQL 使用 sqlglot 的 postgres 方言。"""
source = DataSourceSettings(**_source(db_type='postgresql', db_port=5432))
assert source.sqlglot_parse_dialect == 'postgres'
def test_data_source_allows_disabling_pool_recycle() -> None:
+ """数据源支持禁用连接池回收。"""
source = DataSourceSettings(**_source(db_pool_recycle=-1))
assert source.db_pool_recycle == -1
@@ -50,6 +59,7 @@ def test_data_source_allows_disabling_pool_recycle() -> None:
@pytest.mark.parametrize('db_connect_timeout', [0, -1])
def test_data_source_rejects_invalid_connect_timeout(db_connect_timeout: int) -> None:
+ """数据源拒绝无效的连接超时。"""
with pytest.raises(ValidationError):
DataSourceSettings(**_source(db_connect_timeout=db_connect_timeout))
@@ -67,6 +77,7 @@ def test_database_settings_rejects_empty_or_unknown_default(
value: str,
message: str,
) -> None:
+ """数据库设置拒绝空的或未知的默认数据源。"""
monkeypatch.setenv('DB_SOURCES', json.dumps({'primary': _source()}))
monkeypatch.setenv('DB_DEFAULT_SOURCE', 'primary')
monkeypatch.setenv(field, value)
@@ -76,6 +87,7 @@ def test_database_settings_rejects_empty_or_unknown_default(
def test_database_settings_rejects_invalid_source_name() -> None:
+ """数据库设置拒绝无效的数据源名称。"""
with pytest.raises(ValidationError, match='数据源名称不合法'):
DataBaseSettings(
_env_file=None,
@@ -85,6 +97,7 @@ def test_database_settings_rejects_invalid_source_name() -> None:
def test_database_settings_does_not_expose_legacy_flat_fields() -> None:
+ """数据库设置不暴露旧的平铺字段。"""
settings = DataBaseSettings(
_env_file=None,
db_sources={'primary': DataSourceSettings(**_source())},
@@ -95,6 +108,7 @@ def test_database_settings_does_not_expose_legacy_flat_fields() -> None:
def test_get_source_rejects_unconfigured_name() -> None:
+ """获取未配置的数据源时报错。"""
settings = DataBaseSettings(
_env_file=None,
db_sources={'primary': DataSourceSettings(**_source())},
@@ -105,6 +119,7 @@ def test_get_source_rejects_unconfigured_name() -> None:
def test_malformed_sources_json_does_not_echo_password(monkeypatch: pytest.MonkeyPatch) -> None:
+ """数据源 JSON 格式错误时隐藏密码。"""
secret = 'must-not-leak'
monkeypatch.setenv('DB_SOURCES', f'{{"primary":{{"db_password":"{secret}"')
@@ -115,6 +130,7 @@ def test_malformed_sources_json_does_not_echo_password(monkeypatch: pytest.Monke
def test_invalid_source_fields_do_not_echo_password(monkeypatch: pytest.MonkeyPatch) -> None:
+ """数据源字段无效时隐藏密码。"""
secret = 'valid-json-secret'
monkeypatch.setenv('DB_SOURCES', json.dumps({'primary': {'db_type': 'mysql', 'db_password': secret}}))
diff --git a/ruoyi-fastapi-backend/tests/config/test_i18n_settings.py b/ruoyi-fastapi-backend/tests/config/test_i18n_settings.py
index 50378c2ad..f64ec5375 100644
--- a/ruoyi-fastapi-backend/tests/config/test_i18n_settings.py
+++ b/ruoyi-fastapi-backend/tests/config/test_i18n_settings.py
@@ -32,7 +32,14 @@ def test_i18n_settings_reject_invalid_length(locale: str) -> None:
def _load_i18n_config(
tmp_path: Path, file_locale: str | None, external_locale: str | None
) -> subprocess.CompletedProcess[str]:
- """在独立进程中读取指定环境文件和环境变量,返回配置加载结果。"""
+ """
+ 在独立进程中读取指定环境文件和环境变量,返回配置加载结果。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param file_locale: 配置文件中设置的语言
+ :param external_locale: 外部环境指定的语言
+ :return: 独立进程解析出的国际化配置
+ """
(tmp_path / '.env.i18n-test').write_text(
'' if file_locale is None else f'I18N_DEFAULT_LOCALE={file_locale}\n', encoding='utf-8'
)
diff --git a/ruoyi-fastapi-backend/tests/config/test_lifecycle.py b/ruoyi-fastapi-backend/tests/config/test_lifecycle.py
index 6a965e552..9fb588ee1 100644
--- a/ruoyi-fastapi-backend/tests/config/test_lifecycle.py
+++ b/ruoyi-fastapi-backend/tests/config/test_lifecycle.py
@@ -12,10 +12,16 @@
@pytest.mark.asyncio
async def test_init_create_table_uses_registry_connection(monkeypatch: pytest.MonkeyPatch) -> None:
+ """使用注册表连接初始化建表。"""
connection = SimpleNamespace(run_sync=AsyncMock())
@asynccontextmanager
async def connection_context() -> AsyncGenerator[object, None]:
+ """
+ 为生命周期测试提供受控连接。
+
+ :yield: 当前操作使用的连接
+ """
yield connection
registry = SimpleNamespace(connection=connection_context)
@@ -28,13 +34,24 @@ async def connection_context() -> AsyncGenerator[object, None]:
@pytest.mark.asyncio
async def test_startup_excludes_artifact_tables_from_implicit_schema_creation(monkeypatch: pytest.MonkeyPatch) -> None:
+ """启动时从隐式建表清单排除产物表。"""
metadata = MetaData()
- platform_table = Table('platform', metadata, Column('id', Integer, primary_key=True))
- Table('signed_plugin_data', metadata, Column('id', Integer, primary_key=True), info={'plugin_artifact': 'demo'})
+ platform_table = Table('platform', metadata, Column('id', Integer, primary_key=True, comment='平台记录标识'))
+ Table(
+ 'signed_plugin_data',
+ metadata,
+ Column('id', Integer, primary_key=True, comment='插件记录标识'),
+ info={'plugin_artifact': 'demo'},
+ )
connection = SimpleNamespace(run_sync=AsyncMock())
@asynccontextmanager
async def connection_context() -> AsyncGenerator[object, None]:
+ """
+ 为生命周期测试提供受控连接。
+
+ :yield: 当前操作使用的连接
+ """
yield connection
monkeypatch.setattr('config.lifecycle.DataSourceRegistry', SimpleNamespace(connection=connection_context))
diff --git a/ruoyi-fastapi-backend/tests/config/test_oidc_settings.py b/ruoyi-fastapi-backend/tests/config/test_oidc_settings.py
index d756d4a45..69d48ae90 100644
--- a/ruoyi-fastapi-backend/tests/config/test_oidc_settings.py
+++ b/ruoyi-fastapi-backend/tests/config/test_oidc_settings.py
@@ -5,6 +5,11 @@
def _enabled_values() -> dict[str, object]:
+ """
+ 返回含 ``_env_file``, ``oidc_enabled``, ``oidc_issuer``, ``oidc_public_base_url`` 等字段 的测试数据。
+
+ :return: 含 ``_env_file``, ``oidc_enabled``, ``oidc_issuer``, ``oidc_public_base_url`` 等字段 的测试数据
+ """
return {
'_env_file': None,
'oidc_enabled': True,
@@ -20,12 +25,14 @@ def _enabled_values() -> dict[str, object]:
def test_oidc_disabled_does_not_require_runtime_secrets() -> None:
+ """关闭 OIDC 时无需运行密钥。"""
settings = OidcSettings(_env_file=None, oidc_enabled=False, oidc_issuer='', oidc_public_base_url='')
assert settings.oidc_enabled is False
def test_oidc_enabled_accepts_secure_defaults() -> None:
+ """启用 OIDC 时接受安全默认值。"""
settings = OidcSettings(**_enabled_values())
assert settings.oidc_require_pkce is True
@@ -45,11 +52,13 @@ def test_oidc_enabled_accepts_secure_defaults() -> None:
],
)
def test_oidc_enabled_rejects_unsafe_configuration(overrides: dict[str, object]) -> None:
+ """启用 OIDC 时拒绝不安全配置。"""
with pytest.raises(ValidationError):
OidcSettings(**(_enabled_values() | overrides))
def test_oidc_cors_origin_rejects_userinfo_and_non_local_http(monkeypatch: pytest.MonkeyPatch) -> None:
+ """OIDC 跨域来源拒绝用户信息和非本地 HTTP。"""
with pytest.raises(ValidationError):
OidcSettings(**(_enabled_values() | {'oidc_cors_allowed_origins': 'https://user:pass@client.example'}))
@@ -65,6 +74,7 @@ def test_oidc_cors_origin_rejects_userinfo_and_non_local_http(monkeypatch: pytes
def test_oidc_pepper_cannot_reuse_signing_key_encryption_key() -> None:
+ """OIDC 的 pepper 不得复用签名密钥的加密密钥。"""
values = _enabled_values()
values['oidc_signing_key_encryption_key'] = values['oidc_token_hash_pepper']
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_database.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_database.py
index 44c88a591..9435958e4 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_database.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_database.py
@@ -14,6 +14,7 @@
def test_scheduler_database_engines_keep_jobstore_logging_isolated(monkeypatch: pytest.MonkeyPatch) -> None:
+ """调度器数据库引擎隔离任务存储日志。"""
jobstore_engine = MagicMock()
listener_engine = MagicMock()
create_engine = MagicMock(return_value=jobstore_engine)
@@ -32,6 +33,7 @@ def test_scheduler_database_engines_keep_jobstore_logging_isolated(monkeypatch:
def test_scheduler_cleanup_does_not_dispose_registry_listener_engine(monkeypatch: pytest.MonkeyPatch) -> None:
+ """清理调度器时保留注册表监听引擎。"""
jobstore_engine = MagicMock()
listener_engine = MagicMock()
monkeypatch.setattr(SchedulerManager._resources, '_jobstore_engine', jobstore_engine)
@@ -49,11 +51,13 @@ def test_scheduler_cleanup_does_not_dispose_registry_listener_engine(monkeypatch
@pytest.mark.parametrize('method_name', ['request_scheduler_sync', '_drain_execution_requests'])
def test_registered_scheduler_callbacks_survive_serialization(method_name: str) -> None:
+ """已注册的调度回调可正常序列化。"""
method = getattr(SchedulerManager, method_name)
assert ref_to_obj(obj_to_ref(method)) == method
def test_dao_can_import_adapter_before_scheduler_without_circular_import() -> None:
+ """DAO 可在调度器之前导入适配器且不产生循环导入。"""
script = """
import json
import sys
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py
index 25d3f3eda..cabc91cfd 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py
@@ -32,6 +32,7 @@
@pytest.mark.asyncio
async def test_two_processes_atomically_enforce_logical_job_limit(runtime: Runtime) -> None:
+ """两个进程以原子方式执行逻辑任务并发限制。"""
job = await runtime.save()
snapshot = job.model_dump(mode='json', by_alias=True)
with ProcessPoolExecutor(
@@ -49,11 +50,12 @@ async def test_two_processes_atomically_enforce_logical_job_limit(runtime: Runti
async def wait_for_process_file(path: Path, executor: TimedProcessPoolExecutor) -> dict:
"""
- 等待真实进程进入业务函数
+ 等待真实进程进入业务函数。
:param path: 进程启动标记文件路径
:param executor: 提供超时诊断的真实进程执行器
:return: 进程启动信息
+ :raises TimeoutError: 等待操作超过时限时
"""
startup_wait_seconds = 45
last_error = None
@@ -83,6 +85,7 @@ async def test_running_process_blocks_new_executor_and_can_finish_after_delete(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """运行中的进程阻止新执行器,并能在任务删除后结束。"""
started, release = tmp_path / 'started.json', tmp_path / 'release'
monkeypatch.setattr(task_module, 'runtime_process', held_process_job, raising=False)
executor = TimedProcessPoolExecutor(
@@ -141,6 +144,7 @@ async def test_running_process_blocks_new_executor_and_can_finish_after_delete(
@pytest.mark.asyncio
async def test_expired_dispatch_token_cannot_run_reclaimed_request(runtime: Runtime) -> None:
+ """过期的调度令牌不能执行已回收的请求。"""
job = await runtime.save()
async with runtime.sessions() as db:
request = await JobRuntimeDao.create_request(db, job, None)
@@ -172,6 +176,7 @@ async def test_expired_dispatch_token_cannot_run_reclaimed_request(runtime: Runt
@pytest.mark.asyncio
async def test_only_original_owner_can_finish_unknown_execution(runtime: Runtime) -> None:
+ """只有原所有者可以结束状态未知的执行。"""
job = await runtime.save()
execution_id = uuid4().hex
now = TimezoneUtil.utc_now()
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_retry.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_retry.py
index 71b5c06db..913b53c53 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_retry.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_retry.py
@@ -22,6 +22,14 @@
def database_error(code: int | str, *, attribute: str = 'sqlstate', invalidated: bool = False) -> DBAPIError:
+ """
+ 构造带有指定错误码的数据库异常。
+
+ :param code: 与当前结果对应的编码
+ :param attribute: 要读取或替换的属性名
+ :param invalidated: 本次失效操作影响的记录
+ :return: 带有指定错误码的数据库异常
+ """
original = RuntimeError(code, 'injected database failure')
if isinstance(code, str):
setattr(original, attribute, code)
@@ -35,7 +43,7 @@ def inject_finish_failures(
stage: str,
) -> tuple[list[Session], list[str], list[float]]:
"""
- 在真实 SQLite 事务执行更新后或提交前注入错误
+ 在真实 SQLite 事务执行更新后或提交前注入错误。
:param runtime: 隔离测试运行环境
:param monkeypatch: 测试替换对象
@@ -48,6 +56,11 @@ def inject_finish_failures(
delays: list[float] = []
def factory() -> Session:
+ """
+ 为当前测试步骤创建受控资源。
+
+ :return: 当前操作使用的数据库会话
+ """
if sessions:
assert lifecycle[-1] == 'close'
assert not sessions[-1].in_transaction()
@@ -57,19 +70,38 @@ def factory() -> Session:
original_close = db.close
def execute(state: ORMExecuteState) -> Result[Any]:
+ """
+ 按测试场景处理数据库查询并提供结果。
+
+ :param state: 当前流程的状态
+ :raises Exception: 执行测试注入的数据库故障
+ :return: 执行当前操作得到的结果
+ """
result = state.invoke_statement()
if stage == 'execute' and failure is not None:
raise failure
return result
def before_commit(_db: Session) -> None:
+ """
+ 在事务提交前触发配置的测试行为。
+
+ :param _db: 回调签名接收的数据库会话
+ :raises Exception: 执行提交前注入的故障
+ """
if stage == 'commit' and failure is not None:
raise failure
def after_rollback(_db: Session) -> None:
+ """
+ 记录事务回滚后的回调顺序。
+
+ :param _db: 回调签名接收的数据库会话
+ """
lifecycle.append('rollback')
def close() -> None:
+ """记录测试资源的关闭过程。"""
original_close()
lifecycle.append('close')
@@ -80,6 +112,11 @@ def close() -> None:
return db
def sleep(delay: float) -> None:
+ """
+ 在事务关闭后记录重试等待时间。
+
+ :param delay: 延迟时长
+ """
assert lifecycle[-1] == 'close'
assert not sessions[-1].in_transaction()
delays.append(delay)
@@ -90,6 +127,12 @@ def sleep(delay: float) -> None:
async def claimed_execution(runtime: Runtime) -> tuple[str, str, dict[str, Any]]:
+ """
+ 准备已认领的任务执行记录。
+
+ :param runtime: 隔离测试运行环境
+ :return: 已认领的执行标识、所有者令牌及预期结果
+ """
job = await runtime.save()
execution_id = uuid4().hex
start = TimezoneUtil.utc_now()
@@ -117,6 +160,7 @@ async def claimed_execution(runtime: Runtime) -> tuple[str, str, dict[str, Any]]
async def test_finish_retries_rolled_back_transaction_in_a_new_session(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch, stage: str, code: int | str, attribute: str, failed: bool
) -> None:
+ """结束任务时使用新会话重试已回滚的事务。"""
execution_id, token, result = await claimed_execution(runtime)
result['failed'] = failed
failures = [database_error(code, attribute=attribute), None]
@@ -147,6 +191,7 @@ async def test_finish_retries_rolled_back_transaction_in_a_new_session(
async def test_finish_does_not_retry_unrelated_or_invalidated_errors(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch, stage: str, error: DBAPIError
) -> None:
+ """结束任务时不重试无关错误或连接失效错误。"""
execution_id, token, result = await claimed_execution(runtime)
sessions, lifecycle, delays = inject_finish_failures(runtime, monkeypatch, [error], stage)
with pytest.raises(DBAPIError) as captured:
@@ -163,6 +208,7 @@ async def test_finish_does_not_retry_unrelated_or_invalidated_errors(
async def test_finish_stops_after_three_failed_transactions(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch, stage: str
) -> None:
+ """结束任务的事务连续失败三次后停止重试。"""
execution_id, token, result = await claimed_execution(runtime)
failures = [database_error(1213) for _ in range(3)]
sessions, lifecycle, delays = inject_finish_failures(runtime, monkeypatch, failures, stage)
@@ -179,6 +225,7 @@ async def test_finish_stops_after_three_failed_transactions(
async def test_finish_retry_keeps_owner_guard_and_does_not_overwrite_completed_result(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """结束任务的重试校验所有者并保留已有结果。"""
execution_id, token, result = await claimed_execution(runtime)
inject_finish_failures(runtime, monkeypatch, [database_error(1213), None, None, None], 'commit')
await asyncio.to_thread(JobExecutionStore.finish, execution_id, 'wrong-owner', **result)
@@ -190,6 +237,7 @@ async def test_finish_retry_keeps_owner_guard_and_does_not_overwrite_completed_r
@pytest.mark.asyncio
async def test_result_retry_does_not_repeat_the_user_job(runtime: Runtime, monkeypatch: pytest.MonkeyPatch) -> None:
+ """重试写入结果时不重复执行用户任务。"""
await runtime.save()
await SchedulerManager._sync_jobs_from_database()
job = runtime.scheduler.get_job('42')
@@ -197,6 +245,13 @@ async def test_result_retry_does_not_repeat_the_user_job(runtime: Runtime, monke
original_claim = JobExecutionStore.claim
def claim_then_inject(*args, **kwargs) -> job_execution.ExecutionClaim:
+ """
+ 在取得任务执行权后注入后续故障。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 当前执行的认领信息
+ """
claim = original_claim(*args, **kwargs)
inject_finish_failures(runtime, monkeypatch, [database_error(1213), None], 'commit')
return claim
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py
index aed1eec9c..53236769f 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py
@@ -30,6 +30,7 @@
def test_runner_keeps_scheduled_time_and_monotonic_duration_on_clock_rollback() -> None:
+ """系统时间回拨时保留计划时刻并按单调时钟计算耗时。"""
scheduler = BackgroundScheduler()
scheduler.start(paused=True)
try:
@@ -58,6 +59,7 @@ def test_runner_keeps_scheduled_time_and_monotonic_duration_on_clock_rollback()
def test_failure_and_misfire_have_distinct_execution_metadata() -> None:
+ """执行失败和错过调度使用不同的执行元数据。"""
scheduler = BackgroundScheduler()
scheduler.start(paused=True)
try:
@@ -78,12 +80,18 @@ def test_failure_and_misfire_have_distinct_execution_metadata() -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('kind', ['thread', 'async', 'process'])
async def test_executors_preserve_return_value_and_log_deleted_one_shot(kind: str) -> None:
+ """执行器保留返回值并记录已删除的一次性任务。"""
loop = asyncio.get_running_loop()
completed = loop.create_future()
executor = TimedProcessPoolExecutor(1) if kind == 'process' else TimedAsyncIOExecutor()
scheduler = AsyncIOScheduler(executors={'default': executor})
def receive(event: TimedJobExecutionEvent) -> None:
+ """
+ 为下游 ASGI 应用提供待接收的测试消息。
+
+ :param event: 包含任务快照、真实起止时刻和耗时的执行事件
+ """
if isinstance(event, TimedJobExecutionEvent):
loop.call_soon_threadsafe(completed.set_result, event)
@@ -134,6 +142,7 @@ def receive(event: TimedJobExecutionEvent) -> None:
@pytest.mark.asyncio
async def test_thread_queue_wait_does_not_become_execution_start() -> None:
+ """线程排队时间不计入实际执行开始时间。"""
loop = asyncio.get_running_loop()
pool = ThreadPoolExecutor(1)
release = threading.Event()
@@ -143,6 +152,11 @@ async def test_thread_queue_wait_does_not_become_execution_start() -> None:
scheduler = AsyncIOScheduler(executors={'default': TimedAsyncIOExecutor()})
def receive(event: object) -> None:
+ """
+ 为下游 ASGI 应用提供待接收的测试消息。
+
+ :param event: 待处理的事件
+ """
if isinstance(event, TimedJobExecutionEvent):
completed.set_result(event)
elif event.code == EVENT_JOB_SUBMITTED:
@@ -154,6 +168,14 @@ def receive(event: object) -> None:
original_run_in_executor = loop.run_in_executor
def use_single_worker(executor: object, function: object, *args) -> asyncio.Future:
+ """
+ 将执行任务提交给指定的工作线程池。
+
+ :param executor: 负责运行任务的执行器
+ :param function: 测试要调用或替换的函数
+ :param args: 传给被调用对象的位置参数
+ :return: 任务提交给线程池后的 Future
+ """
return original_run_in_executor(pool, function, *args)
try:
@@ -179,6 +201,7 @@ def use_single_worker(executor: object, function: object, *args) -> asyncio.Futu
async def test_scheduler_emits_one_standard_max_instances_event_and_preserves_rejected_logs(
kind: str, one_shot: bool
) -> None:
+ """调度器仅发出一次标准并发上限事件并保留拒绝日志。"""
executor = (
TimedProcessPoolExecutor(1, on_rejected=SchedulerManager.scheduler_event_listener)
if kind == 'process'
@@ -189,6 +212,11 @@ async def test_scheduler_emits_one_standard_max_instances_event_and_preserves_re
rejected = asyncio.Event()
def receive(event: JobSubmissionEvent) -> None:
+ """
+ 为下游 ASGI 应用提供待接收的测试消息。
+
+ :param event: 待处理的事件
+ """
events.append(event)
rejected.set()
@@ -240,6 +268,7 @@ def receive(event: JobSubmissionEvent) -> None:
@pytest.mark.asyncio
async def test_max_instances_event_does_not_invent_execution_times() -> None:
+ """并发上限事件不填充不存在的执行时间。"""
rejected = []
executor = TimedAsyncIOExecutor(on_rejected=rejected.append)
scheduler = AsyncIOScheduler(executors={'default': executor})
@@ -261,6 +290,7 @@ async def test_max_instances_event_does_not_invent_execution_times() -> None:
@pytest.mark.asyncio
async def test_rejection_log_failure_preserves_max_instances_error() -> None:
+ """拒绝日志写入失败时保留并发上限异常。"""
on_rejected = Mock(side_effect=RuntimeError('log unavailable'))
executor = TimedAsyncIOExecutor(on_rejected=on_rejected)
scheduler = AsyncIOScheduler(executors={'default': executor})
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_fields.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_fields.py
index befa8f283..0650ab702 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_fields.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_fields.py
@@ -40,6 +40,7 @@
],
)
def test_job_fields_reject_ambiguous_or_invalid_configuration(change: dict) -> None:
+ """任务字段拒绝有歧义或无效的配置。"""
with pytest.raises(ValidationError):
JobModel(**change)
@@ -61,6 +62,7 @@ async def test_real_scheduler_applies_misfire_window_and_backlog_policy(
expected_calls: int,
expected_events: int,
) -> None:
+ """真实调度器执行错过窗口和积压处理策略。"""
await runtime.save(
job_info(cronExpression='0 0 0 * * ?', timeZone='UTC', misfireGraceTime=grace, coalesce=coalesce)
)
@@ -75,6 +77,11 @@ async def test_real_scheduler_applies_misfire_window_and_backlog_policy(
complete = asyncio.Event()
def collect(event: object) -> None:
+ """
+ 收集测试事件并通知等待方。
+
+ :param event: 待处理的事件
+ """
events.append(event)
if len(events) == expected_events:
complete.set()
@@ -90,6 +97,7 @@ def collect(event: object) -> None:
@pytest.mark.asyncio
async def test_json_parameters_and_unlimited_delay_survive_database_roundtrip(runtime: Runtime) -> None:
+ """JSON 参数及无限延迟配置可经数据库原样读写。"""
value = {'text': 'x' * 600, 'flags': [True, None, 3.25], 'name': 'tenant,a'}
saved = await runtime.save(job_info(jobArgs=[value], misfireGraceTime=None))
async with runtime.sessions() as db:
@@ -105,6 +113,7 @@ async def test_json_parameters_and_unlimited_delay_survive_database_roundtrip(ru
@pytest.mark.asyncio
async def test_group_changes_preserve_storage_and_schedule_progress(runtime: Runtime, tmp_path: Path) -> None:
+ """更改任务组时保留存储和调度进度。"""
runtime.scheduler.add_jobstore(SQLAlchemyJobStore(url=f'sqlite:///{tmp_path / "jobstore.db"}'), 'sqlalchemy')
await runtime.save(job_info(jobGroup='报表', jobStore='sqlalchemy'))
await SchedulerManager._sync_jobs_from_database()
@@ -127,6 +136,7 @@ async def test_group_changes_preserve_storage_and_schedule_progress(runtime: Run
@pytest.mark.asyncio
async def test_id_is_unique_and_name_is_unique_within_business_group(runtime: Runtime) -> None:
+ """任务标识全局唯一,名称在业务组内唯一。"""
await runtime.save()
assert list(SysJob.__table__.primary_key.columns.keys()) == ['job_id']
async with runtime.sessions() as db:
@@ -154,6 +164,7 @@ async def test_actual_schedule_is_observed_from_leader_and_separate_from_preview
runtime: Runtime,
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """从主节点读取实际调度并与预览区分。"""
await runtime.save()
await SchedulerManager._sync_jobs_from_database()
actual = TimezoneUtil.utc_now() + timedelta(minutes=2)
@@ -186,6 +197,7 @@ async def test_log_ids_keep_history_queryable_after_rename_and_delete(
runtime: Runtime,
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """重命名或删除任务后仍可按日志标识查询历史。"""
metadata = MetaData()
logs = SysJobLog.__table__.to_metadata(metadata)
logs.c.job_log_id.type = Integer()
@@ -194,6 +206,11 @@ async def test_log_ids_keep_history_queryable_after_rename_and_delete(
logged = asyncio.Event()
def record(log: object) -> None:
+ """
+ 收集测试产生的事件或结果。
+
+ :param log: 记录操作过程的日志对象
+ """
recorded.append(log)
logged.set()
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_persistence.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_persistence.py
index f230eb4d3..1df9fe4b4 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_persistence.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_persistence.py
@@ -25,7 +25,7 @@
async def persisted_callable() -> str:
"""
- 无副作用的持久化任务
+ 无副作用的持久化任务。
:return: 执行结果标记
"""
@@ -39,13 +39,12 @@ async def verify_persistent_scheduler(
execution_engine: Engine | None = None,
) -> None:
"""
- 验证真实任务仓库重启校准及独立手动请求,全部访问调用方的隔离库
+ 验证真实任务仓库重启校准及独立手动请求,全部访问调用方的隔离库。
:param engine: 隔离测试数据库引擎
:param monkeypatch: 测试替换对象
:param sessions: 异步数据库会话工厂
:param execution_engine: 执行记录使用的数据库引擎,未指定时使用任务仓库引擎
- :return: None
"""
info = JobModel(
jobId=81,
@@ -66,6 +65,11 @@ async def verify_persistent_scheduler(
await db.commit()
def build_scheduler() -> AsyncIOScheduler:
+ """
+ 创建测试使用的 ``AsyncIOScheduler`` 实例。
+
+ :return: 测试使用的 ``AsyncIOScheduler`` 实例
+ """
return AsyncIOScheduler(
timezone=UTC,
jobstores={'default': SQLAlchemyJobStore(engine=engine, tablename='apscheduler_timezone_verify')},
@@ -123,6 +127,7 @@ async def test_persistent_restart_reconciles_timezone_and_preserves_cron_during_
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """持久化重启后校准时区,手动运行时保留 cron。"""
# SQLite 全库写锁与真实数据库的行锁不同,任务仓库使用另一文件以免伪造行锁死锁。
engine = create_engine(f'sqlite:///{tmp_path / "aps-jobs.db"}')
try:
@@ -140,16 +145,20 @@ async def assert_independent_manual_request(
sessions: async_sessionmaker[AsyncSession],
) -> None:
"""
- 断言手动请求和周期校准都不改写原 Cron,且真实结果可查询
+ 断言手动请求和周期校准都不改写原 Cron,且真实结果可查询。
:param current: 当前测试调度器
:param updated: 更新后的任务配置
:param sessions: 异步数据库会话工厂
- :return: None
"""
finished = asyncio.get_running_loop().create_future()
def on_complete(event: JobExecutionEvent) -> None:
+ """
+ 在目标任务完成时通知等待方。
+
+ :param event: 待处理的事件
+ """
if event.job_id.startswith('_manual:') and not finished.done():
finished.set_result(event)
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py
index b1fa9bea8..fb46f499e 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py
@@ -16,7 +16,11 @@
@pytest_asyncio.fixture
async def jobs() -> AsyncIterator[SchedulerJobs]:
- """每个用例使用独立的内存调度器和同步缓存。"""
+ """
+ 每个用例使用独立的内存调度器和同步缓存。
+
+ :yield: ``SchedulerJobs`` 实例
+ """
scheduler = AsyncIOScheduler(timezone=UTC)
scheduler.start(paused=True)
try:
@@ -75,6 +79,7 @@ async def test_timezone_only_update_rebuilds_trigger_and_failure_remains_retryab
async def test_non_leader_only_notifies_ids_and_tolerates_notification_failure(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch, immediate: bool, publish_fails: bool
) -> None:
+ """非主节点仅通知任务标识,并容忍通知失败。"""
monkeypatch.setattr(SchedulerManager, '_is_leader', False)
publish = SchedulerManager._redis.publish
publish.side_effect = RuntimeError('offline') if publish_fails else None
@@ -91,6 +96,7 @@ async def test_non_leader_only_notifies_ids_and_tolerates_notification_failure(
async def test_immediate_sync_notifies_new_leader_if_lease_is_lost_waiting_for_lock(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """等待锁时失去租约会向新主节点通知立即同步。"""
lock = SchedulerManager._sync_lock
await lock.acquire()
sync = AsyncMock()
@@ -110,11 +116,18 @@ async def test_immediate_sync_notifies_new_leader_if_lease_is_lost_waiting_for_l
async def test_immediate_sync_stops_local_updates_if_lease_is_lost_during_read(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """读取时失去租约会停止本地更新。"""
await runtime.save()
await SchedulerManager._sync_jobs_from_database()
original = runtime.scheduler.get_job('42')
async def read_jobs(_session: object) -> list:
+ """
+ 模拟调度工作进程读取任务列表。
+
+ :param _session: 回调签名接收的会话
+ :return: 测试工作进程可见的任务列表
+ """
monkeypatch.setattr(SchedulerManager, '_is_leader', False)
return []
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_leader_lease.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_leader_lease.py
index 1504f664b..f4df84c86 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_leader_lease.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_leader_lease.py
@@ -82,6 +82,12 @@ async def test_non_leader_scheduler_starts_reacquire_task() -> None:
SchedulerManager._is_closing = False
def create_task(coroutine: object) -> MagicMock:
+ """
+ 创建测试任务并将其交给调用方。
+
+ :param coroutine: 需要调度的协程
+ :return: 测试任务并将其交给调用方
+ """
coroutine.close()
return scheduled_task
@@ -216,6 +222,12 @@ def test_scheduler_lock_lost_callback_revokes_leader_state() -> None:
scheduled_task = MagicMock()
def create_task(coroutine: object) -> MagicMock:
+ """
+ 创建测试任务并将其交给调用方。
+
+ :param coroutine: 需要调度的协程
+ :return: 测试任务并将其交给调用方
+ """
coroutine.close()
return scheduled_task
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_runtime.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_runtime.py
index fcf2282b5..a437bc1f6 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_runtime.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_runtime.py
@@ -33,6 +33,7 @@
],
)
async def test_invalid_configuration_is_rejected_before_save(runtime: Runtime, change: dict) -> None:
+ """保存前拒绝无效配置。"""
async with runtime.sessions() as db:
with pytest.raises((ServiceException, ValidationError)):
await JobService.add_job_services(db, job_info(**change))
@@ -45,6 +46,7 @@ async def test_invalid_configuration_is_rejected_before_save(runtime: Runtime, c
async def test_registration_error_is_saved_and_can_be_retried(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """记录注册失败的原因并允许重试。"""
original_add = runtime.scheduler.add_job
monkeypatch.setattr(
runtime.scheduler, 'add_job', lambda **_kwargs: (_ for _ in ()).throw(RuntimeError('store offline'))
@@ -70,6 +72,7 @@ async def test_registration_error_is_saved_and_can_be_retried(
async def test_edit_is_targeted_and_invalid_edit_preserves_both_states(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """定向编辑任务,编辑无效时保留两端状态。"""
job = await runtime.save()
await runtime.save(job_info(jobId=43, jobName='unrelated'))
await SchedulerManager._sync_jobs_from_database()
@@ -95,16 +98,18 @@ async def test_edit_is_targeted_and_invalid_edit_preserves_both_states(
async def test_one_registration_failure_does_not_block_other_jobs(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """单个任务注册失败不阻塞其他任务。"""
await runtime.save()
await runtime.save(job_info(jobId=43, jobName='second'))
add = runtime.scheduler.add_job
def fail_first(**kwargs) -> object:
"""
- 模拟一个任务的存储故障,其余任务正常注册
+ 模拟一个任务的存储故障,其余任务正常注册。
:param kwargs: 关键字参数
:return: 注册后的任务对象
+ :raises RuntimeError: 模拟第一次调用失败
"""
if kwargs['id'] == '42':
raise RuntimeError('first failed')
@@ -120,6 +125,7 @@ def fail_first(**kwargs) -> object:
@pytest.mark.asyncio
@pytest.mark.parametrize('status', ['0', '1'])
async def test_manual_request_survives_sync_without_changing_cron(runtime: Runtime, status: str) -> None:
+ """手动请求在同步后保留且不修改 cron。"""
job = await runtime.save(job_info(status=status))
await SchedulerManager._sync_jobs_from_database()
original = runtime.scheduler.get_job('42')
@@ -142,6 +148,7 @@ async def test_manual_request_survives_sync_without_changing_cron(runtime: Runti
@pytest.mark.asyncio
@pytest.mark.parametrize('limit', [1, 2])
async def test_cron_and_manual_share_the_same_concurrency_limit(runtime: Runtime, limit: int) -> None:
+ """定时与手动执行共用并发限制。"""
job = await runtime.save(job_info(invokeTarget='module_task.scheduler_test.runtime_held', maxInstances=limit))
await SchedulerManager._sync_jobs_from_database()
runtime.scheduler.modify_job('42', next_run_time=TimezoneUtil.utc_now())
@@ -166,6 +173,7 @@ async def test_cron_and_manual_share_the_same_concurrency_limit(runtime: Runtime
async def test_lost_notification_is_recovered_and_duplicate_wakeup_does_not_repeat(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """恢复遗漏通知且重复唤醒不会重复执行。"""
job = await runtime.save()
monkeypatch.setattr(SchedulerManager, '_is_leader', False)
SchedulerManager._redis.publish.side_effect = RuntimeError('offline')
@@ -185,6 +193,7 @@ async def test_lost_notification_is_recovered_and_duplicate_wakeup_does_not_repe
@pytest.mark.asyncio
async def test_delete_cancels_unstarted_requests_and_keeps_queryable_tombstone(runtime: Runtime) -> None:
+ """删除任务时取消未启动请求并保留可查询的删除记录。"""
job = await runtime.save()
async with runtime.sessions() as db:
submitted = await JobService.execute_job_once_services(db, job)
@@ -209,6 +218,7 @@ async def test_delete_cancels_unstarted_requests_and_keeps_queryable_tombstone(r
@pytest.mark.asyncio
async def test_expired_started_request_is_not_replayed_but_unstarted_request_is_reclaimed(runtime: Runtime) -> None:
+ """过期的已启动请求不重放,未启动请求可回收。"""
job = await runtime.save()
async with runtime.sessions() as db:
first = await JobRuntimeDao.create_request(db, job, None)
@@ -245,6 +255,7 @@ async def test_overlapping_edits_and_late_notifications_apply_latest_version(
runtime: Runtime,
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """并发编辑和迟到通知使用最新版本。"""
await runtime.save()
await SchedulerManager._sync_jobs_from_database()
committed_ids = []
@@ -252,6 +263,13 @@ async def test_overlapping_edits_and_late_notifications_apply_latest_version(
sync = SchedulerManager.request_scheduler_sync
async def delayed_notification(job_ids: set[int], *, immediate: bool) -> dict:
+ """
+ 在指定版本提交后推迟调度通知。
+
+ :param job_ids: 需要删除的定时任务ID
+ :param immediate: 是否立即触发操作
+ :return: 延迟通知后的任务同步结果
+ """
committed_ids.append(job_ids)
if len(committed_ids) == UPDATED_CONFIG_VERSION:
both_committed.set()
@@ -259,6 +277,12 @@ async def delayed_notification(job_ids: set[int], *, immediate: bool) -> dict:
return await sync(job_ids, immediate=immediate)
async def edit(change: dict) -> dict:
+ """
+ 在测试会话中修改调度记录。
+
+ :param change: 本次测试要施加的变更
+ :return: 执行当前操作得到的结果
+ """
async with runtime.sessions() as db:
return (await JobService.edit_job_services(db, EditJobModel(jobId=42, **change))).result
@@ -279,6 +303,7 @@ async def test_deleted_configuration_remains_retryable_when_removal_fails(
runtime: Runtime,
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """移除失败后仍可重试清理已删除的配置。"""
await runtime.save()
await SchedulerManager._sync_jobs_from_database()
remove = runtime.scheduler.remove_job
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_sql_logging.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_sql_logging.py
index 729e45f2a..7a0cde814 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_sql_logging.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_sql_logging.py
@@ -17,6 +17,12 @@
def _sql_logs(caplog: pytest.LogCaptureFixture) -> str:
+ """
+ 提取 SQLAlchemy 日志供语句断言使用。
+
+ :param caplog: 用于捕获并断言日志记录的 pytest 夹具
+ :return: SQLAlchemy 日志供语句断言使用
+ """
return '\n'.join(record.getMessage() for record in caplog.records if record.name.startswith('sqlalchemy.engine.'))
@@ -24,6 +30,14 @@ def _sql_logs(caplog: pytest.LogCaptureFixture) -> str:
async def sql_engine(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest
) -> AsyncGenerator[AsyncEngine, None]:
+ """
+ 提供独立的 SQLite 调度测试引擎。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :param request: pytest 当前用例的请求上下文
+ :yield: 独立的 SQLite 调度测试引擎
+ """
engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "scheduler.sqlite"}', logging_name=request.node.name)
sessions = async_sessionmaker(engine, expire_on_commit=False)
registry = _DataSourceRegistry()
@@ -50,6 +64,7 @@ async def test_dispatch_poll_suppresses_sql_parameters_and_transactions(
caplog: pytest.LogCaptureFixture,
capsys: pytest.CaptureFixture[str],
) -> None:
+ """调度轮询隐藏 SQL 参数和事务日志。"""
sql_engine.echo = 'debug'
monkeypatch.setattr(SchedulerManager, '_is_leader', True)
monkeypatch.setattr(SchedulerManager._dispatcher, 'lock', asyncio.Lock())
@@ -71,9 +86,11 @@ async def test_dispatch_poll_suppresses_sql_parameters_and_transactions(
async def test_business_task_spawned_during_internal_session_keeps_sql_logging(
sql_engine: AsyncEngine, caplog: pytest.LogCaptureFixture, capsys: pytest.CaptureFixture[str]
) -> None:
+ """内部会话派生的业务任务保留 SQL 日志。"""
sql_engine.echo = 'debug'
async def business_query() -> None:
+ """在独立会话中执行用于对照的业务查询。"""
async with async_sessionmaker(sql_engine)() as db:
assert await db.scalar(text("SELECT 'business_sql_visible'")) == 'business_sql_visible'
await db.commit()
@@ -104,6 +121,7 @@ async def test_failed_or_cancelled_internal_session_keeps_errors_and_subsequent_
caplog: pytest.LogCaptureFixture,
exception_type: type[BaseException],
) -> None:
+ """内部会话失败或取消后保留错误和后续 SQL 日志。"""
sql_engine.echo = 'debug'
caplog.clear()
with pytest.raises(exception_type):
@@ -135,6 +153,7 @@ def test_execution_lease_sql_is_quiet_without_muting_shared_engine(
echo: bool | Literal['debug'],
logging_name: str | None,
) -> None:
+ """执行租约 SQL 保持静默且不影响共享引擎。"""
logger_name = 'sqlalchemy.engine.Engine' + (f'.{logging_name}' if logging_name else '')
engine_logger = logging.getLogger(logger_name)
original_handlers = engine_logger.handlers[:]
@@ -165,6 +184,7 @@ def test_execution_lease_sql_is_quiet_without_muting_shared_engine(
def test_sql_filter_is_idempotent_and_retains_tagged_warnings(caplog: pytest.LogCaptureFixture) -> None:
+ """重复应用 SQL 过滤器不会改变结果并保留已标记警告。"""
engine = create_engine('sqlite://', logging_name='quiet_filter')
engine_logger = logging.getLogger('sqlalchemy.engine.Engine.quiet_filter')
try:
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_catalog_domains.py b/ruoyi-fastapi-backend/tests/i18n/test_catalog_domains.py
index 88a45cecd..a107acc86 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_catalog_domains.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_catalog_domains.py
@@ -37,7 +37,11 @@
@pytest.fixture(autouse=True)
def isolate_catalogs() -> Generator[None, None, None]:
- """为每个用例编译核心词库,并在结束后恢复注册表和指纹。"""
+ """
+ 为每个用例编译核心词库,并在结束后恢复注册表和指纹。
+
+ :yield: 上下文就绪后将控制权交给调用方
+ """
compile_catalogs()
original = CatalogRegistry._snapshots.copy()
yield
@@ -46,7 +50,14 @@ def isolate_catalogs() -> Generator[None, None, None]:
def write_plugin(root: Path, plugin_id: str = 'counts', english: str = 'Plugin ready') -> CatalogSpec:
- """创建真实 PO/MO,俄语三种复数用于验证 ngettext 的实际选择。"""
+ """
+ 创建真实 PO/MO,俄语三种复数用于验证 ngettext 的实际选择。
+
+ :param root: 路径解析的基准目录
+ :param plugin_id: 插件清单中的唯一标识
+ :param english: 英文翻译或预期显示的英文文本
+ :return: 真实 PO/MO
+ """
directory = root / 'i18n'
directory.mkdir(parents=True, exist_ok=True)
(directory / 'locale-meta.json').write_text(
@@ -171,6 +182,12 @@ async def test_refresh_and_unload_change_cache_partition_without_request_file_re
assert t('common.success', domain='plugin.counts', locale='en-US') == 'New release'
def unexpected_read(path: Path) -> bytes:
+ """
+ 模拟此操作抛出 AssertionError 的情形。
+
+ :param path: 要读取或处理的路径
+ :raises AssertionError: 请求处理期间意外访问了词库文件
+ """
raise AssertionError(f'Request read catalog: {path}')
monkeypatch.setattr(Path, 'read_bytes', unexpected_read)
@@ -290,6 +307,12 @@ async def test_catalog_refresh_during_request_does_not_write_old_release_cache(t
@ApiCache('catalog-refresh', vary_by_user=False)
async def endpoint(request: Request) -> object:
+ """
+ 处理请求并提供供路由断言使用的响应。
+
+ :param request: 当前 HTTP 请求
+ :return: 路由测试读取的 HTTP 响应
+ """
write_plugin(tmp_path, english='New version')
CatalogRegistry.refresh('plugin.counts')
return ResponseUtil.success(msg=t('common.success', domain='plugin.counts', locale='en-US'))
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_core_catalog_modules.py b/ruoyi-fastapi-backend/tests/i18n/test_core_catalog_modules.py
index 023a252e1..41e9f87b9 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_core_catalog_modules.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_core_catalog_modules.py
@@ -10,7 +10,13 @@
@pytest.fixture
def core_modules(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
- """创建独立的核心词库,包含不同上下文的同名消息和按语言变化的复数。"""
+ """
+ 创建独立的核心词库,包含不同上下文的同名消息和按语言变化的复数。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: pytest 为当前用例创建的临时目录
+ """
monkeypatch.setattr('i18n.catalogs.CATALOG_ROOT', tmp_path)
monkeypatch.setattr('scripts.compile_i18n.SOURCE_PLUGINS', tmp_path / 'plugins')
monkeypatch.setattr(CatalogRegistry, '_snapshots', {})
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_database_initialization.py b/ruoyi-fastapi-backend/tests/i18n/test_database_initialization.py
index 2912487b0..b04959193 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_database_initialization.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_database_initialization.py
@@ -28,6 +28,7 @@ def test_translation_columns_compile_to_comparable_postgres_jsonb(dialect: Diale
def test_fresh_database_user_locale_defaults() -> None:
+ """新数据库为用户提供默认语言。"""
for filename, _ in SQL_FILES:
sql = (SQL_DIR / filename).read_text(encoding='utf-8')
schema = sql.split('create table sys_user (', 1)[1].split('\n)', 1)[0]
@@ -52,7 +53,14 @@ def test_fresh_database_scripts_insert_matching_translations(model: type, field:
for line in schema.strip().splitlines():
column = line.split()[0]
if column in model_table.c:
- columns.append(Column(column, model_table.c[column].type, primary_key=column == primary_key))
+ columns.append(
+ Column(
+ column,
+ model_table.c[column].type,
+ primary_key=column == primary_key,
+ comment=model_table.c[column].comment,
+ )
+ )
table = Table(name, MetaData(), *columns)
with create_engine('sqlite:///:memory:').begin() as connection:
table.create(connection)
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_dict_cache_publication.py b/ruoyi-fastapi-backend/tests/i18n/test_dict_cache_publication.py
index 7e2522779..10cb1abfc 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_dict_cache_publication.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_dict_cache_publication.py
@@ -38,6 +38,13 @@ async def test_late_dict_refresh_cannot_overwrite_a_newer_publication(
read_sessions: list[AsyncSession] = []
async def query(db: AsyncSession, name: str) -> list[dict | None]:
+ """
+ 模拟读取数据库快照并记录查询状态。
+
+ :param db: 当前操作使用的数据库会话
+ :param name: 用于查找或标识当前对象的名称
+ :return: 用于比较状态的快照
+ """
assert name == 'colors'
snapshot = rows.copy()
read_sessions.append(db)
@@ -66,6 +73,7 @@ async def query(db: AsyncSession, name: str) -> list[dict | None]:
@pytest.mark.asyncio
async def test_cache_tracks_type_and_data_crud(cache_redis: Redis) -> None: # noqa: F811
+ """缓存跟踪字典类型和字典数据的增删改查。"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=cache_redis)))
read = DictDataService.query_dict_data_list_from_cache_services
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_excel_i18n.py b/ruoyi-fastapi-backend/tests/i18n/test_excel_i18n.py
index 439af7cfc..da58c6413 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_excel_i18n.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_excel_i18n.py
@@ -24,6 +24,7 @@
async def test_published_user_templates_round_trip_independently_of_interface_language(
locale: str, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """已发布用户模板可跨界面语言原样导入导出。"""
token = RequestContext.set_current_locale(LocaleContext(locale))
try:
workbook = load_workbook(io.BytesIO(await UserService.get_user_import_template_services()))
@@ -73,6 +74,7 @@ async def test_published_user_templates_round_trip_independently_of_interface_la
def test_import_rejects_duplicate_aliases_missing_columns_and_unknown_enums() -> None:
+ """导入拒绝重复别名、缺失列及未知枚举值。"""
headers = [aliases[0] for aliases in UserImportUtil.HEADER_ALIASES.values()]
with pytest.raises(ServiceException) as duplicate:
UserImportUtil.normalize_headers([*headers, 'Login name'])
@@ -86,6 +88,7 @@ def test_import_rejects_duplicate_aliases_missing_columns_and_unknown_enums() ->
def test_export_uses_snapshot_for_headers_and_preserves_business_content() -> None:
+ """导出按快照生成表头并保留业务内容。"""
mapping = {'value': I18nMessage('用户名称', msg_key='export.userName')}
for context, expected in [
(LocaleContext('en-US'), 'Username'),
@@ -108,6 +111,7 @@ def test_export_uses_snapshot_for_headers_and_preserves_business_content() -> No
async def test_dictionary_data_export_matches_each_header_to_its_value(
locale: str, headers: list[str], label: str
) -> None:
+ """字典数据导出的表头与值一一对应。"""
token = RequestContext.set_current_locale(LocaleContext(locale))
try:
exported = await DictDataService.export_dict_data_list_services(
@@ -122,6 +126,7 @@ async def test_dictionary_data_export_matches_each_header_to_its_value(
@pytest.mark.asyncio
async def test_dictionary_export_localizes_name_and_status_without_changing_type() -> None:
+ """字典导出翻译名称和状态并保留类型。"""
token = RequestContext.set_current_locale(LocaleContext('en-US'))
try:
data = await DictTypeService.export_dict_type_list_services(
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_locale.py b/ruoyi-fastapi-backend/tests/i18n/test_locale.py
index 7926bcbab..b11a203de 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_locale.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_locale.py
@@ -160,12 +160,12 @@ async def test_concurrent_requests_negotiate_language_and_set_exception_headers(
add_context_cleanup_middleware(app)
add_locale_middleware(app)
- @app.get('/message')
+ @app.get('/message', summary='获取本地化响应', description='返回按请求语言生成的成功消息及协商响应头。')
async def message() -> Response:
await asyncio.sleep(0.001)
return ResponseUtil.success(headers={'Vary': 'Origin'})
- @app.get('/boom')
+ @app.get('/boom', summary='触发本地化错误', description='模拟服务异常,用于检查错误消息的语言和响应头。')
async def boom() -> None:
raise RuntimeError('secret-detail')
@@ -215,6 +215,11 @@ async def test_transport_key_errors_keep_retry_keys(
)
async def decrypt_request(*args: object) -> None:
+ """
+ 尝试使用指定密钥标识解析请求密钥。
+
+ :param args: 传给被调用对象的位置参数
+ """
TransportCryptoUtil.decrypt_request_key({'kid': kid, 'ek': ''})
monkeypatch.setattr(TransportCryptoMiddleware, '_decrypt_request', decrypt_request)
@@ -254,6 +259,13 @@ async def test_context_cleanup_preserves_outer_locale(raise_error: bool) -> None
token = RequestContext.set_current_locale(context)
async def call_next(request: Request) -> Response:
+ """
+ 模拟经过中间件后的下游响应。
+
+ :param request: 当前 HTTP 请求
+ :raises RuntimeError: 模拟下游请求处理失败
+ :return: 由下游模拟的业务响应
+ """
assert RequestContext.get_current_locale() == context
if raise_error:
raise RuntimeError('request failed')
@@ -313,6 +325,12 @@ async def test_t_uses_call_time_context_and_keeps_explicit_locale_local() -> Non
original = RequestContext.get_current_locale()
async def render(locale: str) -> tuple[str, str, str]:
+ """
+ 在指定语言上下文中渲染测试消息。
+
+ :param locale: 当前使用的语言区域标识
+ :return: 渲染文本及用于对照的期望值
+ """
context = LocaleContext(locale)
token = RequestContext.set_current_locale(context)
try:
@@ -334,6 +352,13 @@ def test_t_interpolates_parameters_and_preserves_safe_fallback(monkeypatch: pyte
"""验证参数插值、缺词回退和通用提示。"""
def load_catalog(code: str, domain: str = 'core') -> gettext.GNUTranslations:
+ """
+ 构建指定语言的测试消息目录。
+
+ :param code: 与当前结果对应的编码
+ :param domain: 用于查找翻译消息的域
+ :return: 指定语言的测试消息目录
+ """
catalog = Catalog(locale=code.replace('-', '_'))
if code == 'zh-CN':
catalog.add('example.greeting', '你好,%(name)s')
@@ -358,6 +383,11 @@ async def test_api_cache_uses_effective_language() -> None:
"""验证相同有效语言共享缓存,不同语言分别缓存。"""
async def receive() -> Message:
+ """
+ 提供下游 ASGI 应用读取的 HTTP 请求体消息。
+
+ :return: 下游 ASGI 应用读取的 HTTP 请求体消息
+ """
return {'type': 'http.request', 'body': b''}
request = Request(
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_locale_revision.py b/ruoyi-fastapi-backend/tests/i18n/test_locale_revision.py
index e3abdfb6b..4788bd7f6 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_locale_revision.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_locale_revision.py
@@ -29,6 +29,11 @@
@pytest_asyncio.fixture
async def sessions() -> AsyncIterator[async_sessionmaker[AsyncSession]]:
+ """
+ 在独立数据库中创建测试会话工厂。
+
+ :yield: 逐项产生的 ``factory``
+ """
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
async with engine.begin() as connection:
await connection.run_sync(SysUser.__table__.create)
@@ -50,8 +55,11 @@ async def sessions() -> AsyncIterator[async_sessionmaker[AsyncSession]]:
async def test_login_writes_only_an_explicit_valid_preference(
sessions: async_sessionmaker[AsyncSession], monkeypatch: pytest.MonkeyPatch
) -> None:
+ """登录仅写入显式指定且有效的偏好。"""
app = FastAPI()
- app.post('/login')(inspect.unwrap(login))
+ app.post('/login', summary='登录并设置语言', description='验证登录请求只保存显式提交且有效的语言偏好。')(
+ inspect.unwrap(login)
+ )
app.state.redis = AsyncMock()
async with sessions() as db:
app.dependency_overrides[get_db_session_provider(None)] = lambda: db
@@ -76,6 +84,7 @@ async def test_login_writes_only_an_explicit_valid_preference(
async def test_preference_endpoint_returns_monotonic_revision_and_get_info_preserves_bigint(
sessions: async_sessionmaker[AsyncSession],
) -> None:
+ """偏好接口返回递增版本且用户信息保留大整数精度。"""
current = SimpleNamespace(user=SimpleNamespace(user_id=1, user_name='one'))
async with sessions() as db:
first = await inspect.unwrap(change_system_user_locale)(
@@ -105,6 +114,7 @@ async def test_preference_endpoint_returns_monotonic_revision_and_get_info_prese
async def test_other_user_edits_cannot_overwrite_revision_and_locale_rollback_is_atomic(
sessions: async_sessionmaker[AsyncSession],
) -> None:
+ """其他用户编辑不能覆盖版本且语言变更可原子回滚。"""
async with sessions.begin() as db:
result = await UserDao.edit_user_dao(db, {'user_id': 1, 'locale': 'en-GB', 'locale_revision': 999})
assert result == {'locale': 'en-GB', 'revision': '1'}
@@ -124,6 +134,7 @@ async def test_other_user_edits_cannot_overwrite_revision_and_locale_rollback_is
@pytest.mark.asyncio
async def test_locale_update_locks_the_row_and_uses_database_increment() -> None:
+ """更新语言时锁定记录并通过数据库递增版本。"""
db = SimpleNamespace(scalar=AsyncMock(side_effect=[1, 42]), execute=AsyncMock())
assert await UserDao.edit_user_dao(db, {'user_id': 1, 'locale': 'en-US'}) == {'locale': 'en-US', 'revision': '42'}
lock = db.scalar.call_args_list[0].args[0]
@@ -138,6 +149,7 @@ async def test_locale_update_locks_the_row_and_uses_database_increment() -> None
async def test_missing_user_preference_does_not_report_a_successful_write(
sessions: async_sessionmaker[AsyncSession],
) -> None:
+ """用户偏好不存在时不会误报写入成功。"""
async with sessions() as db:
with pytest.raises(ServiceException):
await UserService.update_user_locale_services(db, 999, 'missing', 'en-US')
@@ -146,11 +158,13 @@ async def test_missing_user_preference_does_not_report_a_successful_write(
@pytest.mark.parametrize('tag', ['en-GB', 'en-AU', 'en-CA', 'en-Latn-GB', 'en-GB-u-ca-gregory'])
def test_explicit_english_language_family_fallback(tag: str) -> None:
+ """显式回退到英语语系。"""
assert LocaleRegistry.match_locale(tag) == 'en-US'
assert LocaleUtil.negotiate_language(f'{tag};q=0.9,zh-CN;q=0.5') == 'en-US'
def test_exact_registered_locale_wins_and_chinese_scripts_do_not_merge(monkeypatch: pytest.MonkeyPatch) -> None:
+ """已注册语言精确匹配优先且不合并不同中文书写体系。"""
monkeypatch.setitem(LOCALES, 'en-GB', {'aliases': (), 'fallback': ('en-US',)})
assert LocaleRegistry.match_locale('en-GB') == 'en-GB'
assert LocaleRegistry.match_locale('zh-TW') is None
@@ -161,5 +175,6 @@ def test_exact_registered_locale_wins_and_chinese_scripts_do_not_merge(monkeypat
def test_locale_endpoint_does_not_accept_client_revision() -> None:
+ """语言接口拒绝客户端提供的版本。"""
with pytest.raises(ValueError):
UserLocaleModel(locale='en-US', revision='12')
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_validation_messages.py b/ruoyi-fastapi-backend/tests/i18n/test_validation_messages.py
index b62be0e24..5edc7ea18 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_validation_messages.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_validation_messages.py
@@ -69,12 +69,20 @@ def test_explicit_type_messages_preserve_only_public_constraints(
class ValidationBody(BaseModel):
- name: str = Field(min_length=3)
+ """通过字段长度和校验器触发请求体验证。"""
+
+ name: str = Field(min_length=3, description='待校验的名称')
@field_validator('name')
@classmethod
def validate_name(cls, value: str) -> str:
- """构造含内部错误详情的校验失败,用于验证响应脱敏。"""
+ """
+ 构造含内部错误详情的校验失败,用于验证响应脱敏。
+
+ :param value: 待处理的输入值
+ :raises ValueError: 模拟数据校验产生内部数据库错误
+ :return: 待处理的输入值
+ """
if value == 'invalid':
raise ValueError('private database detail')
return value
@@ -87,11 +95,15 @@ async def test_real_422_handles_json_and_custom_validation_without_echoing_input
handle_exception(app)
add_locale_middleware(app)
- @app.post('/validate')
+ @app.post('/validate', summary='校验请求字段', description='校验请求体中的名称和查询参数中的数量,并返回有效值。')
async def validate(body: ValidationBody, count: Annotated[int, Query(ge=1)]) -> dict:
return {'name': body.name, 'count': count}
- @app.get('/non-json-input')
+ @app.get(
+ '/non-json-input',
+ summary='模拟不可序列化的校验输入',
+ description='构造含特殊输入值的校验异常,验证错误响应的字段和脱敏行为。',
+ )
async def non_json_input() -> None:
raise RequestValidationError(
[
diff --git a/ruoyi-fastapi-backend/tests/middlewares/test_oidc_cors_middleware.py b/ruoyi-fastapi-backend/tests/middlewares/test_oidc_cors_middleware.py
index 762c8008f..43114b568 100644
--- a/ruoyi-fastapi-backend/tests/middlewares/test_oidc_cors_middleware.py
+++ b/ruoyi-fastapi-backend/tests/middlewares/test_oidc_cors_middleware.py
@@ -12,23 +12,42 @@
@pytest.fixture(autouse=True)
def _mock_snapshot_refresh(monkeypatch: pytest.MonkeyPatch) -> None:
+ """
+ 用可控的异步调用替换跨域策略快照刷新。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
monkeypatch.setattr('middlewares.oidc_cors_middleware.OidcRuntimeService.ensure_cors_snapshot', AsyncMock())
def _client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ """
+ 创建启用了测试配置的请求客户端。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: 启用了测试配置的请求客户端
+ """
monkeypatch.setattr(OidcConfig, 'oidc_enabled', True)
monkeypatch.setattr(OidcConfig, 'oidc_cors_allowed_origins', 'https://allowed.example')
app = FastAPI()
- @app.get('/.well-known/openid-configuration')
+ @app.get(
+ '/.well-known/openid-configuration',
+ summary='获取 OIDC 发现信息',
+ description='返回测试认证中心的签发者地址,用于验证发现端点的跨域策略。',
+ )
async def discovery() -> dict[str, str]:
return {'issuer': 'https://auth.example.com'}
- @app.get('/oauth2/authorize')
+ @app.get('/oauth2/authorize', summary='访问授权端点', description='返回授权端点的测试响应,用于验证跨域请求处理。')
async def authorize() -> dict[str, bool]:
return {'ok': True}
- @app.post('/oauth2/token')
+ @app.post(
+ '/oauth2/token',
+ summary='获取测试访问令牌',
+ description='返回带有访问令牌的响应,用于检查令牌端点的跨域响应头。',
+ )
async def token() -> Response:
return Response(
content='{"access_token":"token"}',
@@ -36,7 +55,9 @@ async def token() -> Response:
headers={'Vary': 'Accept-Encoding, Origin'},
)
- @app.get('/business')
+ @app.get(
+ '/business', summary='访问普通业务端点', description='返回业务成功状态,用于比较协议路径和业务路径的跨域处理。'
+ )
async def business() -> dict[str, bool]:
return {'ok': True}
@@ -52,6 +73,7 @@ async def business() -> dict[str, bool]:
def test_authorize_disallows_cors_but_discovery_remains_public(monkeypatch: pytest.MonkeyPatch) -> None:
+ """授权端点禁止跨域访问而发现端点保持公开。"""
client = _client(monkeypatch)
origin = {'Origin': 'https://external.example'}
@@ -65,6 +87,7 @@ def test_authorize_disallows_cors_but_discovery_remains_public(monkeypatch: pyte
def test_token_preflight_requires_explicit_origin(monkeypatch: pytest.MonkeyPatch) -> None:
+ """令牌预检必须显式指定来源。"""
client = _client(monkeypatch)
allowed = client.options(
'/oauth2/token',
@@ -91,6 +114,7 @@ def test_token_preflight_requires_explicit_origin(monkeypatch: pytest.MonkeyPatc
def test_token_form_post_from_disallowed_origin_is_rejected_before_downstream(
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """令牌表单请求在进入下游前拒绝未许可来源。"""
response = _client(monkeypatch).post(
'/oauth2/token',
data={'grant_type': 'authorization_code', 'code': 'opaque-code'},
@@ -102,6 +126,7 @@ def test_token_form_post_from_disallowed_origin_is_rejected_before_downstream(
def test_allowed_response_preserves_non_origin_vary_tokens(monkeypatch: pytest.MonkeyPatch) -> None:
+ """允许跨域的响应保留 Vary 中其他字段。"""
client = _client(monkeypatch)
response = client.post('/oauth2/token', headers={'Origin': 'https://allowed.example'})
@@ -113,6 +138,7 @@ def test_allowed_response_preserves_non_origin_vary_tokens(monkeypatch: pytest.M
def test_existing_business_cors_remains_unchanged(monkeypatch: pytest.MonkeyPatch) -> None:
+ """保留原有业务跨域规则。"""
response = _client(monkeypatch).get('/business', headers={'Origin': 'https://current-web.example'})
assert response.status_code == status.HTTP_200_OK
@@ -132,7 +158,11 @@ def test_runtime_registered_origin_is_exact_and_does_not_allow_similar_hosts(
app = FastAPI()
app.state.oidc_registered_cors_origins = frozenset({'https://registered.example'})
- @app.post('/oauth2/token')
+ @app.post(
+ '/oauth2/token',
+ summary='验证令牌端点来源',
+ description='返回令牌端点的测试响应,用于核对动态注册来源的匹配边界。',
+ )
async def token() -> Response:
return Response('{}', media_type='application/json')
@@ -154,11 +184,17 @@ def test_interaction_api_requires_exact_issuer_origin(monkeypatch: pytest.Monkey
monkeypatch.setattr(OidcConfig, 'oidc_issuer', 'https://auth.example.com/oidc')
app = FastAPI()
- @app.post('/auth/interaction/i-1/login')
+ @app.post(
+ '/auth/interaction/i-1/login', summary='提交交互登录', description='模拟登录提交,用于检查交互端点的跨域限制。'
+ )
async def login() -> Response:
return Response('{}', media_type='application/json')
- @app.get('/auth/interaction/i-1/complete')
+ @app.get(
+ '/auth/interaction/i-1/complete',
+ summary='完成认证交互',
+ description='模拟认证交互结束,用于检查完成端点的跨域限制。',
+ )
async def complete() -> Response:
return Response('{}', media_type='application/json')
@@ -191,7 +227,11 @@ def test_interaction_preflight_rejects_cross_origin(monkeypatch: pytest.MonkeyPa
monkeypatch.setattr(OidcConfig, 'oidc_issuer', 'https://auth.example.com')
app = FastAPI()
- @app.post('/auth/interaction/i-1/change-password')
+ @app.post(
+ '/auth/interaction/i-1/change-password',
+ summary='提交交互密码变更',
+ description='模拟交互改密,用于检查预检请求的处理。',
+ )
async def change_password() -> Response:
return Response('{}')
@@ -210,7 +250,11 @@ def test_oidc_cors_is_bypassed_when_provider_is_disabled(monkeypatch: pytest.Mon
monkeypatch.setattr(OidcConfig, 'oidc_enabled', False)
app = FastAPI()
- @app.post('/oauth2/token')
+ @app.post(
+ '/oauth2/token',
+ summary='访问已关闭认证中心的令牌路径',
+ description='返回测试响应,用于验证关闭认证中心后的中间件行为。',
+ )
async def token() -> Response:
return Response('{}', media_type='application/json')
diff --git a/ruoyi-fastapi-backend/tests/middlewares/test_transport_crypto_oidc_exclusion.py b/ruoyi-fastapi-backend/tests/middlewares/test_transport_crypto_oidc_exclusion.py
index e5227f1a7..48bdc646d 100644
--- a/ruoyi-fastapi-backend/tests/middlewares/test_transport_crypto_oidc_exclusion.py
+++ b/ruoyi-fastapi-backend/tests/middlewares/test_transport_crypto_oidc_exclusion.py
@@ -5,6 +5,7 @@
def test_standard_oidc_paths_are_always_excluded_from_transport_envelope(monkeypatch: pytest.MonkeyPatch) -> None:
+ """标准 OIDC 路径始终排除在传输封装之外。"""
monkeypatch.setattr(TransportCryptoConfig, 'transport_crypto_exclude_paths', '')
assert all(
@@ -13,10 +14,12 @@ def test_standard_oidc_paths_are_always_excluded_from_transport_envelope(monkeyp
def test_interaction_api_is_not_implicitly_excluded() -> None:
+ """交互 API 不会被隐式排除。"""
assert not TransportCryptoMiddleware._is_excluded_path('/auth/interaction/interaction-id/login')
def test_app_root_path_is_removed_before_oidc_exclusion(monkeypatch: pytest.MonkeyPatch) -> None:
+ """匹配 OIDC 排除规则前移除应用根路径。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '/dev-api')
normalized_path = TransportCryptoMiddleware._normalize_path('/dev-api/oauth2/token')
diff --git a/ruoyi-fastapi-backend/tests/module_admin/controller/test_dept_controller.py b/ruoyi-fastapi-backend/tests/module_admin/controller/test_dept_controller.py
index ff8597563..928e982ab 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/controller/test_dept_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/controller/test_dept_controller.py
@@ -13,6 +13,7 @@
@pytest.mark.asyncio
async def test_add_dept_rejects_parent_outside_data_scope() -> None:
+ """新增部门时拒绝超出数据范围的上级部门。"""
current_user = SimpleNamespace(user=SimpleNamespace(admin=False, user_name='operator'))
parent_id = 200
with (
@@ -34,6 +35,7 @@ async def test_add_dept_rejects_parent_outside_data_scope() -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize(('parent_id', 'parent_changed'), [(100, False), (200, True)])
async def test_edit_dept_checks_changed_parent_scope(parent_id: int, parent_changed: bool) -> None:
+ """更换上级部门时校验其数据范围。"""
current_user = SimpleNamespace(user=SimpleNamespace(admin=False, user_name='operator'))
query_db, scope = object(), object()
with (
@@ -63,6 +65,7 @@ async def test_edit_dept_checks_changed_parent_scope(parent_id: int, parent_chan
@pytest.mark.asyncio
async def test_admin_add_dept_does_not_require_parent_data_scope() -> None:
+ """管理员新增部门无需校验上级部门的数据范围。"""
current_user = SimpleNamespace(user=SimpleNamespace(admin=True, user_name='admin'))
with (
patch.object(DeptService, 'check_dept_data_scope_services', AsyncMock()) as check_scope,
diff --git a/ruoyi-fastapi-backend/tests/module_admin/controller/test_job_controller.py b/ruoyi-fastapi-backend/tests/module_admin/controller/test_job_controller.py
index 060b72887..00305fa20 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/controller/test_job_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/controller/test_job_controller.py
@@ -5,8 +5,11 @@
def test_preview_endpoint_validates_fields_and_distinguishes_no_future_dates() -> None:
+ """预览端点校验字段并区分没有未来执行日期的情况。"""
app = FastAPI()
- app.post('/preview')(preview_system_job)
+ app.post('/preview', summary='预览任务执行时间', description='按 Cron 表达式、时区和起始时刻计算后续执行时间。')(
+ preview_system_job
+ )
client = TestClient(app)
base = {'cronExpression': '0 0 0 1 1 ? 2020', 'timeZone': 'UTC', 'startTime': '2026-01-01T00:00:00Z'}
response = client.post('/preview', json=base)
diff --git a/ruoyi-fastapi-backend/tests/module_admin/controller/test_login_logout.py b/ruoyi-fastapi-backend/tests/module_admin/controller/test_login_logout.py
index 594d7b8dd..c9447865e 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/controller/test_login_logout.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/controller/test_login_logout.py
@@ -22,6 +22,13 @@
def _token(*, expired: bool = False, session_id: str = _SESSION_ID) -> str:
+ """
+ 签发带有测试用户和会话标识的令牌。
+
+ :param expired: 当前记录是否已过期
+ :param session_id: 会话ID
+ :return: 用于访问受保护端点的测试令牌
+ """
return JwtUtil.encode(
{
'user_id': _USER_ID,
@@ -33,6 +40,12 @@ def _token(*, expired: bool = False, session_id: str = _SESSION_ID) -> str:
@pytest.fixture
def logout_app(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
+ """
+ 组装带注销路由的测试应用。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: 带注销路由的测试应用
+ """
app = FastAPI()
app.state.redis = object()
app.include_router(login_controller)
@@ -55,6 +68,7 @@ async def test_logout_passes_full_token_and_selected_session_to_service(
expired: bool,
scheme: str,
) -> None:
+ """注销时将完整令牌和选中会话传给服务。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
token = _token(expired=expired)
@@ -78,6 +92,7 @@ async def test_logout_passes_full_token_and_selected_session_to_service(
async def test_logout_rejects_invalid_credentials_before_session_or_cache_changes(
logout_app: SimpleNamespace, authorization: str | None
) -> None:
+ """注销凭据无效时拒绝更改会话或缓存。"""
headers = {'Authorization': authorization} if authorization else {}
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=logout_app.app), base_url='http://test') as client:
response = await client.post('/logout', headers=headers)
@@ -92,12 +107,21 @@ async def test_logout_rejects_invalid_credentials_before_session_or_cache_change
async def test_concurrent_logout_requests_keep_their_own_tokens(
logout_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
+ """并发注销各自使用本次请求的令牌。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
tokens = [_token(session_id='old-session'), _token(session_id='new-session')]
entered, resume = asyncio.Event(), asyncio.Event()
arguments = []
async def logout(request: Request, token_id: str, token: str) -> bool:
+ """
+ 记录会话注销并与并发请求同步。
+
+ :param request: 当前 HTTP 请求
+ :param token_id: 会话编号
+ :param token: 待撤销或内省的令牌
+ :return: 此分支的固定值 ``True``
+ """
arguments.append((token_id, token))
if len(arguments) == len(tokens):
entered.set()
@@ -123,6 +147,7 @@ async def logout(request: Request, token_id: str, token: str) -> bool:
async def test_logout_service_failure_does_not_report_success_or_clear_cache(
logout_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """注销服务失败时保留缓存并返回失败。"""
logout_app.logout.side_effect = RedisTimeoutError('redis timeout')
success = Mock(wraps=ResponseUtil.success)
monkeypatch.setattr(ResponseUtil, 'success', success)
@@ -139,9 +164,18 @@ async def test_logout_service_failure_does_not_report_success_or_clear_cache(
async def test_cancelled_logout_does_not_report_success_or_clear_cache(
logout_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """取消注销时保留缓存并返回失败。"""
entered, resume = asyncio.Event(), asyncio.Event()
async def logout(request: Request, token_id: str, token: str) -> bool:
+ """
+ 记录会话注销并与并发请求同步。
+
+ :param request: 当前 HTTP 请求
+ :param token_id: 会话编号
+ :param token: 待撤销或内省的令牌
+ :return: 此分支的固定值 ``True``
+ """
entered.set()
await resume.wait()
return True
diff --git a/ruoyi-fastapi-backend/tests/module_admin/controller/test_user_controller.py b/ruoyi-fastapi-backend/tests/module_admin/controller/test_user_controller.py
index f315c4553..4372a406e 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/controller/test_user_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/controller/test_user_controller.py
@@ -19,6 +19,7 @@
@pytest.mark.asyncio
async def test_admin_reset_password_uses_front_end_default_rule() -> None:
+ """管理员重置密码使用前端默认规则。"""
redis = SimpleNamespace()
request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis)))
reset_user = EditUserModel(userId=2, password='abcdef')
@@ -63,12 +64,14 @@ async def test_admin_reset_password_uses_front_end_default_rule() -> None:
],
)
def test_update_user_profile_model_rejects_management_fields(management_field: dict) -> None:
+ """用户资料模型拒绝管理字段。"""
with pytest.raises(ValidationError):
UpdateUserProfileModel(nickName='普通用户', **management_field)
@pytest.mark.asyncio
async def test_update_user_profile_only_forwards_editable_fields() -> None:
+ """更新用户资料仅转发可编辑字段。"""
request = SimpleNamespace()
user_info = UpdateUserProfileModel(
nickName='新昵称',
diff --git a/ruoyi-fastapi-backend/tests/module_admin/dao/test_user_auth_queries.py b/ruoyi-fastapi-backend/tests/module_admin/dao/test_user_auth_queries.py
index d04bdf715..3ce6bee3a 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/dao/test_user_auth_queries.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/dao/test_user_auth_queries.py
@@ -37,11 +37,24 @@
@compiles(TINYINT, 'sqlite')
def _compile_tinyint(_type: TINYINT, _compiler: object, **kwargs: object) -> str:
+ """
+ 返回固定值 ``SMALLINT``。
+
+ :param _type: 传递给编译器的类型对象
+ :param _compiler: 编译数据库表达式的对象
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``'SMALLINT'``
+ """
return 'SMALLINT'
@pytest_asyncio.fixture
async def user_query_env() -> AsyncIterator[SimpleNamespace]:
+ """
+ 为用户权限查询准备独立数据库。
+
+ :yield: ``SimpleNamespace`` 实例
+ """
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
tables = [SysUser, SysDept, SysRole, SysPost, SysMenu, SysUserRole, SysUserPost, SysRoleMenu]
sessions = async_sessionmaker(engine, expire_on_commit=False, autoflush=False)
@@ -109,6 +122,16 @@ async def user_query_env() -> AsyncIterator[SimpleNamespace]:
def record_query(
connection: object, cursor: object, statement: str, parameters: object, context: object, executemany: bool
) -> None:
+ """
+ 捕获 SQL 查询以检查访问次数。
+
+ :param connection: 当前操作使用的连接
+ :param cursor: 执行当前 SQL 的数据库游标
+ :param statement: 即将执行的数据库语句
+ :param parameters: 分派给目标命令的参数
+ :param context: 当前操作所需的上下文
+ :param executemany: 是否批量执行同一条语句
+ """
if statement.lstrip().upper().startswith('SELECT'):
statements.append(statement)
@@ -120,6 +143,7 @@ def record_query(
@pytest.mark.asyncio
async def test_user_auth_preserves_profile_roles_posts_and_permissions(user_query_env: SimpleNamespace) -> None:
+ """用户认证保留资料、角色、岗位和权限。"""
async with user_query_env.sessions() as db:
result = await UserDao.get_user_by_id(db, USER_ID, for_auth=True)
assert len(user_query_env.statements) == USER_QUERY_COUNT
@@ -137,6 +161,7 @@ async def test_user_auth_preserves_profile_roles_posts_and_permissions(user_quer
@pytest.mark.asyncio
async def test_admin_auth_skips_menus_but_keeps_roles_and_profile(user_query_env: SimpleNamespace) -> None:
+ """管理员认证跳过菜单并保留角色和资料。"""
async with user_query_env.sessions() as db:
result = await UserDao.get_user_by_id(db, ADMIN_ID, for_auth=True)
assert len(user_query_env.statements) == ADMIN_QUERY_COUNT
@@ -153,6 +178,7 @@ async def test_admin_auth_skips_menus_but_keeps_roles_and_profile(user_query_env
async def test_invalid_user_returns_after_one_query(
user_query_env: SimpleNamespace, for_auth: bool, condition: str
) -> None:
+ """无效用户仅查询一次。"""
async with user_query_env.sessions.begin() as db:
if condition == 'missing':
await db.execute(delete(SysUser).where(SysUser.user_id == USER_ID))
@@ -174,6 +200,7 @@ async def test_invalid_user_returns_after_one_query(
@pytest.mark.asyncio
@pytest.mark.parametrize('condition', ['disabled', 'deleted', 'missing', 'unassigned'])
async def test_invalid_department_does_not_hide_valid_user(user_query_env: SimpleNamespace, condition: str) -> None:
+ """无效部门不会隐藏有效用户。"""
async with user_query_env.sessions.begin() as db:
if condition == 'unassigned':
await db.execute(update(SysUser).where(SysUser.user_id == USER_ID).values(dept_id=None))
@@ -193,6 +220,7 @@ async def test_invalid_department_does_not_hide_valid_user(user_query_env: Simpl
@pytest.mark.asyncio
@pytest.mark.parametrize('user_id', [USER_ID, ADMIN_ID])
async def test_route_query_keeps_complete_menu_models(user_query_env: SimpleNamespace, user_id: int) -> None:
+ """路由查询保留完整菜单模型。"""
async with user_query_env.sessions() as db:
result = await UserDao.get_user_by_id(db, user_id)
assert len(user_query_env.statements) == USER_QUERY_COUNT
@@ -213,6 +241,7 @@ async def test_route_query_keeps_complete_menu_models(user_query_env: SimpleName
@pytest.mark.asyncio
async def test_new_request_observes_committed_permission_changes(user_query_env: SimpleNamespace) -> None:
+ """新请求读取已提交的权限变更。"""
async with user_query_env.sessions() as db:
before = await UserDao.get_user_by_id(db, USER_ID, for_auth=True)
async with user_query_env.sessions.begin() as db:
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_cached_session_races.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_cached_session_races.py
index 643bc76e5..901803afd 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_cached_session_races.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_cached_session_races.py
@@ -33,7 +33,14 @@
async def _prepare_cached_session(
env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> tuple[Request, str, str]:
- """使用真实鉴权预热快照,并设置当前登录模式对应的会话键。"""
+ """
+ 使用真实鉴权预热快照,并设置当前登录模式对应的会话键。
+
+ :param env: 当前运行环境
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :param same_time_login: 是否允许同一账号同时登录
+ :return: 依次为 ``request``、``token``、``token_key`` 的元组
+ """
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
token = env.headers[USER_ID]['Authorization'].removeprefix('Bearer ')
token_id = f'session-{USER_ID}' if same_time_login else str(USER_ID)
@@ -58,7 +65,15 @@ async def _prepare_cached_session(
async def _resolve_cached_session(
env: SimpleNamespace, request: Request, token: str, for_plugin: bool
) -> CurrentUserModel:
- """通过新数据库会话进入真实缓存命中及最终会话校验路径。"""
+ """
+ 通过新数据库会话进入真实缓存命中及最终会话校验路径。
+
+ :param env: 当前运行环境
+ :param request: 当前 HTTP 请求
+ :param token: 用于身份验证或授权的令牌
+ :param for_plugin: 要关联的插件标识
+ :return: 通过最终会话校验的当前用户
+ """
resolve = LoginService.get_current_user_for_plugin_session if for_plugin else LoginService.get_current_user
async with env.sessions() as db:
return await resolve(request, token, db)
@@ -75,11 +90,19 @@ async def test_cached_request_rejects_session_changed_after_snapshot_read(
for_plugin: bool,
change: str,
) -> None:
+ """读取缓存快照后会话变化时拒绝请求。"""
request, token, token_key = await _prepare_cached_session(cache_env, monkeypatch, same_time_login)
loaded, resume = asyncio.Event(), asyncio.Event()
original_eval = cache_env.redis.eval
async def pause_snapshot(script: str, *args: Any) -> Any:
+ """
+ 在读取缓存快照后暂停并发流程。
+
+ :param script: 需要运行的脚本
+ :param args: 传给被调用对象的位置参数
+ :return: 执行当前操作得到的结果
+ """
result = await original_eval(script, *args)
if script == CurrentUserCacheUtil._READ_SCRIPT:
assert result[4]
@@ -131,6 +154,7 @@ async def test_cached_final_session_check_failure_never_sets_authenticated_conte
for_plugin: bool,
failure: str,
) -> None:
+ """最终会话校验失败时不设置认证上下文。"""
request, token, token_key = await _prepare_cached_session(cache_env, monkeypatch, same_time_login)
await cache_env.redis.pexpire(token_key, 1000)
previous_deadline = await absolute_expiry_ms(cache_env.redis, token_key)
@@ -139,12 +163,24 @@ async def test_cached_final_session_check_failure_never_sets_authenticated_conte
session_reads = 0
async def fail_after_check() -> None:
+ """
+ 完成初始检查后模拟故障或超时。
+
+ :raises RedisTimeoutError: 模拟最终会话校验时 Redis 响应超时
+ """
checked.set()
if failure == 'timeout':
raise RedisTimeoutError('session response unavailable')
await resume.wait()
async def eval_then_fail(script: str, *args: Any) -> Any:
+ """
+ 在读取缓存快照后注入故障。
+
+ :param script: 需要运行的脚本
+ :param args: 传给被调用对象的位置参数
+ :return: 执行当前操作得到的结果
+ """
result = await original_eval(script, *args)
if script == CurrentUserCacheUtil._READ_SCRIPT:
assert result[4]
@@ -154,6 +190,12 @@ async def eval_then_fail(script: str, *args: Any) -> Any:
return result
async def get_then_fail(key: str) -> Any:
+ """
+ 在读取会话后注入缓存故障。
+
+ :param key: 查找数据时使用的键
+ :return: 执行当前操作得到的结果
+ """
nonlocal session_reads
result = await original_get(key)
if for_plugin and key == token_key:
@@ -200,6 +242,7 @@ async def test_browser_cookie_uses_cached_permissions_without_renewal_and_reject
monkeypatch: pytest.MonkeyPatch,
same_time_login: bool,
) -> None:
+ """浏览器 Cookie 复用缓存权限而不续期,并拒绝已注销会话。"""
request, token, token_key = await _prepare_cached_session(cache_env, monkeypatch, same_time_login)
cookie, _, _ = await issue_browser_session(
request, plugin_id='cache_test', version='1.0.0', main_token=token, user_id=USER_ID
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_common_file_security.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_common_file_security.py
index 9b0e3343d..b3b9af811 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_common_file_security.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_common_file_security.py
@@ -29,26 +29,58 @@
async def collect_stream(stream: AsyncGenerator[bytes, None]) -> bytes:
+ """
+ 合并异步流中的数据块。
+
+ :param stream: 需要逐块读取的流
+ :return: 按顺序拼接的流内容
+ """
return b''.join([chunk async for chunk in stream])
async def collect_first_chunk_and_close(stream: AsyncGenerator[bytes, None]) -> bytes:
+ """
+ 读取首块数据后关闭异步流。
+
+ :param stream: 需要逐块读取的流
+ :return: 首块数据后关闭异步流
+ """
chunk = await anext(stream)
await stream.aclose()
return chunk
def make_upload(filename: str, content: bytes) -> UploadFile:
+ """
+ 创建测试使用的 ``UploadFile`` 实例。
+
+ :param filename: 用于保存或展示的文件名
+ :param content: 需要读取或写入的内容
+ :return: 测试使用的 ``UploadFile`` 实例
+ """
return UploadFile(file=io.BytesIO(content), filename=filename)
def make_current_user(user_id: int = 10, admin: bool = False, dept_id: int = 100) -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param user_id: 用户的唯一标识
+ :param admin: 是否使用管理员身份
+ :param dept_id: 部门id
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(
user=SimpleNamespace(user_id=user_id, user_name=f'user{user_id}', admin=admin, dept_id=dept_id)
)
def make_query_db() -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
@@ -67,6 +99,7 @@ def test_parse_byte_range_supports_standard_single_ranges(
range_header: str | None,
expected: tuple[int, int, int, bool, int],
) -> None:
+ """解析标准单段字节范围。"""
byte_range = FileUtil.parse_byte_range(range_header, 10)
assert (
@@ -90,6 +123,7 @@ def test_parse_byte_range_supports_standard_single_ranges(
],
)
def test_parse_byte_range_rejects_invalid_or_multiple_ranges(range_header: str) -> None:
+ """拒绝无效或多段字节范围。"""
with pytest.raises(FileRangeNotSatisfiableException) as range_error:
FileUtil.parse_byte_range(range_header, RANGE_TEST_FILE_SIZE)
@@ -97,6 +131,7 @@ def test_parse_byte_range_rejects_invalid_or_multiple_ranges(range_header: str)
def test_parse_byte_range_allows_empty_full_download_but_rejects_empty_partial_download() -> None:
+ """空文件允许完整下载并拒绝部分下载。"""
byte_range = FileUtil.parse_byte_range(None, 0)
assert byte_range.length == 0
@@ -106,6 +141,7 @@ def test_parse_byte_range_allows_empty_full_download_but_rejects_empty_partial_d
def test_resolve_file_within_root_accepts_nested_relative_file(tmp_path: Path) -> None:
+ """允许解析根目录内的嵌套相对文件。"""
root = tmp_path / 'download'
target = root / 'nested' / 'report.txt'
target.parent.mkdir(parents=True)
@@ -129,6 +165,7 @@ def test_resolve_file_within_root_accepts_nested_relative_file(tmp_path: Path) -
],
)
def test_resolve_file_within_root_rejects_absolute_and_traversal_paths(tmp_path: Path, untrusted_path: str) -> None:
+ """拒绝绝对路径和目录穿越。"""
root = tmp_path / 'download'
root.mkdir()
@@ -137,6 +174,7 @@ def test_resolve_file_within_root_rejects_absolute_and_traversal_paths(tmp_path:
def test_resolve_file_within_root_rejects_symlink_escape(tmp_path: Path) -> None:
+ """拒绝通过符号链接越出文件根目录。"""
root = tmp_path / 'download'
root.mkdir()
outside = tmp_path / 'outside.txt'
@@ -152,6 +190,7 @@ def test_resolve_file_within_root_rejects_symlink_escape(tmp_path: Path) -> None
def test_download_rejects_absolute_path_without_scheduling_delete(tmp_path: Path) -> None:
+ """拒绝绝对下载路径且不安排删除。"""
download_root = tmp_path / 'download'
download_root.mkdir()
outside = tmp_path / 'outside.txt'
@@ -169,6 +208,7 @@ def test_download_rejects_absolute_path_without_scheduling_delete(tmp_path: Path
def test_download_keeps_delete_compatibility_inside_download_root(tmp_path: Path) -> None:
+ """保留下载根目录内下载后删除的行为。"""
download_root = tmp_path / 'download'
download_root.mkdir()
target = download_root / 'report.txt'
@@ -194,6 +234,7 @@ def test_download_keeps_delete_compatibility_inside_download_root(tmp_path: Path
def test_resource_download_is_confined_to_upload_root(tmp_path: Path) -> None:
+ """资源下载限于上传根目录。"""
upload_root = tmp_path / 'profile'
target = upload_root / 'upload' / '2026' / '07' / 'report_20260719120000A001.txt'
target.parent.mkdir(parents=True)
@@ -219,6 +260,7 @@ def test_resource_download_is_confined_to_upload_root(tmp_path: Path) -> None:
def test_resource_download_rejects_file_without_generated_filename(tmp_path: Path) -> None:
+ """拒绝下载缺少生成文件名的资源。"""
upload_root = tmp_path / 'profile'
target = upload_root / 'upload' / '2026' / '07' / 'report.txt'
target.parent.mkdir(parents=True)
@@ -232,6 +274,7 @@ def test_resource_download_rejects_file_without_generated_filename(tmp_path: Pat
def test_upload_uses_server_generated_filename_and_stays_in_upload_root(tmp_path: Path) -> None:
+ """上传使用服务端生成的名称并写入上传根目录。"""
upload_root = tmp_path / 'profile'
upload = make_upload('../../attack:bad?.txt', b'safe-content')
request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
@@ -270,6 +313,7 @@ def test_upload_uses_server_generated_filename_and_stays_in_upload_root(tmp_path
@pytest.mark.parametrize('extension', ['html', 'htm'])
def test_upload_accepts_html_as_download_only_file(tmp_path: Path, extension: str) -> None:
+ """允许上传 HTML 并仅供下载。"""
file_content = b''
upload = make_upload(f'attack.{extension}', file_content)
request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
@@ -293,6 +337,7 @@ def test_upload_accepts_html_as_download_only_file(tmp_path: Path, extension: st
def test_upload_enforces_total_size_and_removes_partial_file(tmp_path: Path) -> None:
+ """上传限制总大小并清理未完成文件。"""
upload = make_upload('large.txt', b'12345')
request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
query_db = make_query_db()
@@ -309,6 +354,7 @@ def test_upload_enforces_total_size_and_removes_partial_file(tmp_path: Path) ->
def test_upload_rejects_unknown_access_type_before_writing(tmp_path: Path) -> None:
+ """写入前拒绝未知访问类型。"""
upload = make_upload('report.txt', b'report-content')
request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
@@ -322,6 +368,7 @@ def test_upload_rejects_unknown_access_type_before_writing(tmp_path: Path) -> No
def test_upload_removes_file_when_metadata_write_fails(tmp_path: Path) -> None:
+ """元数据写入失败时清理已上传文件。"""
upload = make_upload('report.txt', b'report-content')
request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
query_db = make_query_db()
@@ -340,6 +387,7 @@ def test_upload_removes_file_when_metadata_write_fails(tmp_path: Path) -> None:
def test_upload_retries_name_collision_without_deleting_existing_file(tmp_path: Path) -> None:
+ """上传文件重名时重试并保留原文件。"""
fixed_time = datetime(2026, 7, 19, 4, 0, 0, tzinfo=UTC)
existing_file = tmp_path / 'upload' / '2026' / '07' / '19' / 'report_20260719120000A001.txt'
existing_file.parent.mkdir(parents=True)
@@ -364,6 +412,7 @@ def test_upload_retries_name_collision_without_deleting_existing_file(tmp_path:
def test_private_upload_is_physically_isolated_and_owner_can_download(tmp_path: Path) -> None:
+ """私有上传文件物理隔离且所有者可下载。"""
public_root = tmp_path / 'public'
private_root = tmp_path / 'private'
upload = make_upload('contract.pdf', b'private-content')
@@ -398,6 +447,7 @@ def test_private_upload_is_physically_isolated_and_owner_can_download(tmp_path:
def test_private_download_rejects_other_user(tmp_path: Path) -> None:
+ """拒绝其他用户下载私有文件。"""
private_root = tmp_path / 'private'
target = private_root / 'upload' / '2026' / '07' / 'contract_20260719120000A001.pdf'
target.parent.mkdir(parents=True)
@@ -429,6 +479,7 @@ def test_private_download_rejects_other_user(tmp_path: Path) -> None:
def test_file_manager_can_download_private_file_without_owner_match(tmp_path: Path) -> None:
+ """文件管理员无需匹配所有者即可下载私有文件。"""
private_root = tmp_path / 'private'
target = private_root / 'upload' / '2026' / '07' / 'contract_20260719120000A001.pdf'
target.parent.mkdir(parents=True)
@@ -466,6 +517,7 @@ def test_file_manager_can_download_private_file_without_owner_match(tmp_path: Pa
def test_file_manager_download_rejects_file_outside_data_scope() -> None:
+ """文件管理员不能下载数据范围外的文件。"""
request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
query_db = make_query_db()
file_manager = make_current_user(user_id=20)
@@ -503,6 +555,7 @@ def test_managed_download_allows_administrator_or_public_file(
access_type: str,
current_user: SimpleNamespace,
) -> None:
+ """托管下载允许管理员或公开文件访问。"""
storage_root = tmp_path / access_type
target = storage_root / 'upload' / '2026' / '07' / 'report_20260719120000A001.txt'
target.parent.mkdir(parents=True)
@@ -536,6 +589,7 @@ def test_managed_download_allows_administrator_or_public_file(
@pytest.mark.parametrize('admin', [False, True])
def test_private_download_rejects_expired_file(tmp_path: Path, admin: bool) -> None:
+ """拒绝下载已过期的私有文件。"""
private_root = tmp_path / 'private'
file_info = SimpleNamespace(
storage_type='local',
@@ -563,6 +617,7 @@ def test_private_download_rejects_expired_file(tmp_path: Path, admin: bool) -> N
def test_managed_download_records_interrupted_stream(tmp_path: Path) -> None:
+ """托管下载记录被中断的数据流。"""
target = tmp_path / 'report.txt'
target.write_bytes(b'partial-content')
request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
@@ -579,6 +634,7 @@ def test_managed_download_records_interrupted_stream(tmp_path: Path) -> None:
def test_managed_download_supports_range_and_records_partial_bytes(tmp_path: Path) -> None:
+ """托管下载支持范围请求并记录实际字节数。"""
storage_root = tmp_path / 'private'
target = storage_root / 'upload' / '2026' / '07' / 'report_20260719120000A001.txt'
target.parent.mkdir(parents=True)
@@ -625,6 +681,7 @@ def test_managed_download_supports_range_and_records_partial_bytes(tmp_path: Pat
def test_managed_download_audits_unsatisfied_range_without_disclosing_before_permission(tmp_path: Path) -> None:
+ """无权限时隐藏范围信息,获授权后审计不可满足的范围。"""
storage_root = tmp_path / 'private'
target = storage_root / 'upload' / '2026' / '07' / 'report_20260719120000A001.txt'
target.parent.mkdir(parents=True)
@@ -662,6 +719,7 @@ def test_managed_download_audits_unsatisfied_range_without_disclosing_before_per
def test_download_headers_force_attachment_and_disable_sniffing() -> None:
+ """下载响应强制作为附件并禁止类型嗅探。"""
byte_range = FileUtil.parse_byte_range('bytes=2-5', 10)
headers = UploadUtil.build_download_headers('../../report.html', byte_range)
@@ -676,6 +734,7 @@ def test_download_headers_force_attachment_and_disable_sniffing() -> None:
def test_static_files_force_only_html_to_download(tmp_path: Path) -> None:
+ """静态文件中仅 HTML 强制下载。"""
html_file = tmp_path / 'legacy.html'
html_file.write_text('', encoding='utf-8')
image_file = tmp_path / 'safe.png'
@@ -704,6 +763,7 @@ def test_static_files_force_only_html_to_download(tmp_path: Path) -> None:
def test_cors_exposes_download_headers() -> None:
+ """跨域响应公开下载所需的头部字段。"""
app = FastAPI()
add_cors_middleware(app)
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py
index 824c44ce8..05b60dedd 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py
@@ -49,7 +49,14 @@ async def cache_env(
cache_redis: Redis, # noqa: F811
monkeypatch: pytest.MonkeyPatch,
) -> AsyncIterator[SimpleNamespace]:
- """复用真实鉴权路由和数据库,缓存及会话命令均由隔离Redis执行。"""
+ """
+ 复用真实鉴权路由和数据库,缓存及会话命令均由隔离Redis执行。
+
+ :param resolution_env: 为当前用户解析测试准备隔离环境
+ :param cache_redis: 测试使用的 Redis 缓存客户端
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :yield: ``SimpleNamespace`` 实例
+ """
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', True)
monkeypatch.setattr(AppConfig, 'app_current_user_cache_ttl_seconds', 5)
for key, value in resolution_env.redis.values.items():
@@ -64,10 +71,22 @@ async def cache_env(
original_eval = cache_redis.eval
async def record_eval(script: str, *args: Any) -> Any:
+ """
+ 记录执行的 Redis 脚本并委托给原实现。
+
+ :param script: 需要运行的脚本
+ :param args: 传给被调用对象的位置参数
+ :return: 原 Redis 脚本的执行结果
+ """
calls.append(script)
return await original_eval(script, *args)
async def session_dependency() -> AsyncIterator[AsyncSession]:
+ """
+ 为当前请求提供测试数据库会话。
+
+ :yield: 当前操作使用的数据库会话
+ """
async with sessions() as db:
yield db
@@ -90,6 +109,7 @@ async def session_dependency() -> AsyncIterator[AsyncSession]:
@pytest.mark.asyncio
async def test_cache_hit_avoids_sql_and_still_renews_the_session(cache_env: SimpleNamespace) -> None:
+ """缓存命中时跳过 SQL 查询并续期会话。"""
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
assert first.status_code == HttpStatusConstant.SUCCESS
assert len(cache_env.statements) == REGULAR_QUERY_COUNT
@@ -109,6 +129,7 @@ async def test_cache_hit_avoids_sql_and_still_renews_the_session(cache_env: Simp
async def test_cache_hit_recomputes_password_policy(
cache_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """缓存命中时重新计算密码策略。"""
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
assert not first.json()['isPasswordExpired']
await cache_env.redis.mset(
@@ -131,6 +152,7 @@ async def test_cache_hit_recomputes_password_policy(
@pytest.mark.asyncio
async def test_concurrent_cache_hits_keep_users_and_context_separate(cache_env: SimpleNamespace) -> None:
+ """并发命中缓存时隔离用户和上下文。"""
for user_id in (ADMIN_ID, USER_ID):
await cache_env.client.get('/profile', headers=cache_env.headers[user_id])
initial_queries = len(cache_env.statements)
@@ -153,6 +175,7 @@ async def test_concurrent_cache_hits_keep_users_and_context_separate(cache_env:
async def test_cache_hit_never_accepts_revoked_or_replaced_token(
cache_env: SimpleNamespace, replacement: str | None
) -> None:
+ """缓存命中时仍拒绝已撤销或被替换的令牌。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
token_key = f'access_token:session-{USER_ID}'
if replacement is None:
@@ -170,13 +193,26 @@ async def test_cache_hit_never_accepts_revoked_or_replaced_token(
@pytest.mark.asyncio
async def test_use_cache_false_reauthenticates_even_when_both_calls_hit_cache(cache_env: SimpleNamespace) -> None:
+ """两次命中缓存时禁用依赖缓存仍会重新认证。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
- @cache_env.app.get('/revalidate-cached', dependencies=[PreAuthDependency()])
+ @cache_env.app.get(
+ '/revalidate-cached',
+ summary='比较缓存命中后的认证结果',
+ description='在同一请求内再次认证,并返回用户对象及上下文的比较结果。',
+ dependencies=[PreAuthDependency()],
+ )
async def revalidate(
first: Annotated[CurrentUserModel, CurrentUserDependency()],
second: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
) -> dict:
+ """
+ 返回含 ``sameUser``, ``contextIsFresh`` 的测试数据。
+
+ :param first: 当前已认证用户及其权限信息
+ :param second: 当前已认证用户及其权限信息
+ :return: 含 ``sameUser``, ``contextIsFresh`` 的测试数据
+ """
return {'sameUser': first is second, 'contextIsFresh': RequestContext.get_current_user() is second}
response = await cache_env.client.get('/revalidate-cached', headers=cache_env.headers[USER_ID])
@@ -188,15 +224,31 @@ async def revalidate(
@pytest.mark.asyncio
async def test_cached_use_cache_false_rejects_session_revoked_between_dependencies(cache_env: SimpleNamespace) -> None:
+ """禁用依赖缓存后拒绝在两次依赖调用间被撤销的会话。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
async def revoke(current_user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> None:
+ """
+ 在请求处理中撤销测试凭据。
+
+ :param current_user: 当前登录用户及其权限信息
+ """
await cache_env.redis.delete(f'access_token:session-{current_user.user.user_id}')
- @cache_env.app.get('/revoke-cached', dependencies=[PreAuthDependency(), Depends(revoke)])
+ @cache_env.app.get(
+ '/revoke-cached',
+ summary='验证缓存会话撤销',
+ description='在两次依赖调用间撤销会话,检查后续认证是否拒绝访问。',
+ dependencies=[PreAuthDependency(), Depends(revoke)],
+ )
async def revalidate(
current_user: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
) -> None:
+ """
+ 在调用时报告预期的测试失败:已撤销会话不应进入接口。
+
+ :param current_user: 当前登录用户及其权限信息
+ """
pytest.fail('已撤销会话不应进入接口')
response = await cache_env.client.get('/revoke-cached', headers=cache_env.headers[USER_ID])
@@ -210,20 +262,38 @@ async def revalidate(
async def test_cached_use_cache_false_applies_permission_change_between_dependencies(
cache_env: SimpleNamespace,
) -> None:
+ """禁用依赖缓存后应用两次依赖调用间的权限变更。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
async def revoke(
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> None:
+ """
+ 在请求处理中撤销测试凭据。
+
+ :param current_user: 当前登录用户及其权限信息
+ :param query_db: 当前操作使用的异步数据库会话
+ """
await query_db.execute(delete(SysRoleMenu).where(SysRoleMenu.role_id == USER_ID))
await query_db.commit()
- @cache_env.app.get('/revoke-cached-permission', dependencies=[PreAuthDependency(), Depends(revoke)])
+ @cache_env.app.get(
+ '/revoke-cached-permission',
+ summary='验证缓存权限撤销',
+ description='在两次依赖调用间撤销权限,检查后续授权是否拒绝访问。',
+ dependencies=[PreAuthDependency(), Depends(revoke)],
+ )
async def revalidate(
current_user: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
permitted: Annotated[bool, UserInterfaceAuthDependency('demo:read')],
) -> None:
+ """
+ 在调用时报告预期的测试失败:权限撤销后不应进入接口。
+
+ :param current_user: 当前登录用户及其权限信息
+ :param permitted: 该请求是否拥有所需权限
+ """
pytest.fail('权限撤销后不应进入接口')
response = await cache_env.client.get('/revoke-cached-permission', headers=cache_env.headers[USER_ID])
@@ -235,6 +305,7 @@ async def revalidate(
@pytest.mark.asyncio
async def test_plugin_cache_hit_does_not_renew_host_session(cache_env: SimpleNamespace) -> None:
+ """插件命中缓存时不续期宿主会话。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
token_key = f'access_token:session-{USER_ID}'
await cache_env.redis.pexpire(token_key, 2000)
@@ -256,6 +327,7 @@ async def test_plugin_cache_hit_does_not_renew_host_session(cache_env: SimpleNam
async def test_committed_permission_changes_invalidate_cached_authentication(
cache_env: SimpleNamespace, change: str
) -> None:
+ """提交权限变更后使认证缓存失效。"""
await cache_env.client.get('/permitted', headers=cache_env.headers[USER_ID])
async with cache_env.sessions.begin() as db:
if change in ('disable_user', 'delete_user'):
@@ -280,6 +352,7 @@ async def test_committed_permission_changes_invalidate_cached_authentication(
@pytest.mark.asyncio
@pytest.mark.parametrize('change', ['department', 'data_scope', 'post', 'menu'])
async def test_shared_changes_refresh_all_authorization_fields(cache_env: SimpleNamespace, change: str) -> None:
+ """共享数据变更后刷新全部授权字段。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
async with cache_env.sessions.begin() as db:
if change == 'department':
@@ -309,6 +382,7 @@ async def test_shared_changes_refresh_all_authorization_fields(cache_env: Simple
async def test_existing_transaction_bypasses_cache_without_publishing_uncommitted_permissions(
cache_env: SimpleNamespace,
) -> None:
+ """已有事务绕过缓存且不发布未提交权限。"""
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
async with cache_env.sessions() as db:
await db.execute(update(SysRole).where(SysRole.role_id == USER_ID).values(status='1'))
@@ -326,6 +400,7 @@ async def test_existing_transaction_bypasses_cache_without_publishing_uncommitte
@pytest.mark.asyncio
async def test_external_connection_transaction_cannot_publish_uncommitted_user(cache_env: SimpleNamespace) -> None:
+ """外部连接事务不能发布未提交的用户数据。"""
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
engine = cache_env.sessions.kw['bind']
async with engine.connect() as connection:
@@ -351,6 +426,7 @@ async def test_external_connection_transaction_cannot_publish_uncommitted_user(c
async def test_multi_bind_sessions_keep_original_database_resolution(
cache_env: SimpleNamespace, default_bind: bool, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """多绑定会话保留原数据库解析行为。"""
engine = cache_env.sessions.kw['bind']
secondary = create_async_engine(engine.url)
bindings = dict.fromkeys(
@@ -375,11 +451,19 @@ async def test_multi_bind_sessions_keep_original_database_resolution(
async def test_concurrent_permission_commit_prevents_old_query_refilling_cache(
cache_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """并发提交权限变更后阻止旧查询回填缓存。"""
loaded = asyncio.Event()
release = asyncio.Event()
original = LoginService._get_current_user_from_db
async def delayed(query_db: AsyncSession, user_id: int) -> CurrentUserModel:
+ """
+ 在读取用户后暂停以模拟并发变更。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param user_id: 用户的唯一标识
+ :return: 当前操作对应的用户
+ """
user = await original(query_db, user_id)
loaded.set()
await release.wait()
@@ -409,6 +493,7 @@ async def delayed(query_db: AsyncSession, user_id: int) -> CurrentUserModel:
@pytest.mark.asyncio
async def test_direct_orm_user_change_invalidates_only_affected_user(cache_env: SimpleNamespace) -> None:
+ """直接修改 ORM 用户只使受影响用户缓存失效。"""
for user_id in (ADMIN_ID, USER_ID):
await cache_env.client.get('/profile', headers=cache_env.headers[user_id])
async with cache_env.sessions.begin() as db:
@@ -426,6 +511,7 @@ async def test_direct_orm_user_change_invalidates_only_affected_user(cache_env:
@pytest.mark.asyncio
async def test_corrupt_cached_payload_falls_back_to_database(cache_env: SimpleNamespace) -> None:
+ """缓存内容损坏时回退到数据库。"""
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
key = CurrentUserCacheUtil._keys(cache_env.namespace, USER_ID)[2]
await cache_env.redis.hset(key, 'payload', '{invalid-json')
@@ -441,9 +527,18 @@ async def test_corrupt_cached_payload_falls_back_to_database(cache_env: SimpleNa
async def test_cache_failure_can_fall_back_without_bypassing_session_check(
cache_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """缓存故障时回退且继续校验会话。"""
original = cache_env.redis.eval
async def cache_failure(script: str, *args: Any) -> Any:
+ """
+ 在指定缓存操作上注入故障。
+
+ :param script: 需要运行的脚本
+ :param args: 传给被调用对象的位置参数
+ :raises RedisConnectionError: 模拟读取快照缓存时连接中断
+ :return: 未注入故障时原缓存操作的结果
+ """
if script != _SESSION_RENEW_SCRIPT:
raise RedisConnectionError('snapshot cache unavailable')
return await original(script, *args)
@@ -469,10 +564,19 @@ async def cache_failure(script: str, *args: Any) -> Any:
async def test_cache_cancellation_propagates_without_renewal_or_context(
cache_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, stage: str
) -> None:
+ """缓存操作被取消时传播取消信号且不续期或写入上下文。"""
original = cache_env.redis.eval
cancel_script = CurrentUserCacheUtil._READ_SCRIPT if stage == 'read' else CurrentUserCacheUtil._WRITE_SCRIPT
async def cancel(script: str, *args: Any) -> Any:
+ """
+ 记录任务的取消请求。
+
+ :param script: 需要运行的脚本
+ :param args: 传给被调用对象的位置参数
+ :raises asyncio.CancelledError: 模拟缓存操作被取消
+ :return: 原取消操作的执行结果
+ """
if script == cancel_script:
raise asyncio.CancelledError
return await original(script, *args)
@@ -491,6 +595,7 @@ async def cancel(script: str, *args: Any) -> Any:
async def test_cache_disabled_keeps_database_authentication(
cache_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """禁用缓存时使用数据库认证。"""
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', False)
for _ in range(2):
response = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_mutations.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_mutations.py
index 3bbba19ee..37d42cbff 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_mutations.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_mutations.py
@@ -42,6 +42,7 @@ async def test_user_dao_updates_refresh_profile_without_invalidating_other_users
changes: dict[str, Any],
expected: dict[str, Any],
) -> None:
+ """通过 DAO 更新用户资料不影响其他用户缓存。"""
for user_id in (ADMIN_ID, USER_ID):
await cache_env.client.get('/profile', headers=cache_env.headers[user_id])
async with cache_env.sessions.begin() as db:
@@ -60,6 +61,7 @@ async def test_user_dao_updates_refresh_profile_without_invalidating_other_users
@pytest.mark.asyncio
async def test_timezone_service_commit_refreshes_cached_preference(cache_env: SimpleNamespace) -> None: # noqa: F811
+ """提交时区变更后刷新偏好缓存。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
async with cache_env.sessions() as db:
result = await UserService.update_user_timezone_services(db, USER_ID, 'reader', 'Europe/London')
@@ -77,6 +79,7 @@ async def test_password_changes_refresh_policy_without_caching_hash(
cache_env: SimpleNamespace, # noqa: F811
mutation: str,
) -> None:
+ """修改密码后刷新策略且不缓存密码哈希。"""
await cache_env.redis.set('sys_config:sys.account.initPasswordModify', '1')
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
assert first.json()['isDefaultModifyPwd']
@@ -107,6 +110,7 @@ async def test_password_changes_refresh_policy_without_caching_hash(
async def test_user_role_assignment_and_revocation_refresh_admin_permission(
cache_env: SimpleNamespace, # noqa: F811
) -> None:
+ """分配或撤销用户角色后刷新管理员权限。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
assignment = UserRoleModel(userId=USER_ID, roleId=ADMIN_ID)
async with cache_env.sessions.begin() as db:
@@ -125,6 +129,7 @@ async def test_user_role_assignment_and_revocation_refresh_admin_permission(
@pytest.mark.asyncio
async def test_user_post_removal_and_assignment_refresh_cached_post_ids(cache_env: SimpleNamespace) -> None: # noqa: F811
+ """删除或分配用户岗位后刷新缓存的岗位标识。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
assignment = UserPostModel(userId=USER_ID, postId=USER_ID)
async with cache_env.sessions.begin() as db:
@@ -145,6 +150,7 @@ async def test_plugin_menu_mutations_revoke_cached_permission(
cache_env: SimpleNamespace, # noqa: F811
mutation: str,
) -> None:
+ """修改插件菜单后撤销已缓存的权限。"""
await cache_env.client.get('/permitted', headers=cache_env.headers[USER_ID])
async with cache_env.sessions.begin() as db:
if mutation == 'edit':
@@ -170,6 +176,7 @@ async def test_aliased_mutations_refresh_cached_user_and_permissions(
target_name: str,
mutation: str,
) -> None:
+ """通过别名修改数据后刷新用户及权限缓存。"""
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
assert first.json()['permissions'] == ['demo:read']
model = SysUser if target_name == 'user' else SysMenu
@@ -204,6 +211,7 @@ async def test_aliased_mutations_refresh_cached_user_and_permissions(
async def test_alias_update_with_original_table_condition_refreshes_all_affected_users(
cache_env: SimpleNamespace, # noqa: F811
) -> None:
+ """使用原表条件更新别名时刷新全部受影响用户。"""
for user_id in (ADMIN_ID, USER_ID):
response = await cache_env.client.get('/profile', headers=cache_env.headers[user_id])
assert response.json()['user']['userId'] == user_id
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py
index e1bac076d..a951080b4 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py
@@ -48,6 +48,14 @@
@compiles(TINYINT, 'sqlite')
def _compile_tinyint(_type: TINYINT, _compiler: object, **kwargs: object) -> str:
+ """
+ 返回固定值 ``SMALLINT``。
+
+ :param _type: 传递给编译器的类型对象
+ :param _compiler: 编译数据库表达式的对象
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``'SMALLINT'``
+ """
return 'SMALLINT'
@@ -55,16 +63,36 @@ class AuthenticationRedis(SessionRedis):
"""仅允许原有登录会话和系统配置访问,禁止新增用户快照缓存。"""
async def get(self, key: str) -> str | None:
+ """
+ 读取测试存储中的指定键。
+
+ :param key: 查找数据时使用的键
+ :return: 测试存储中的指定键
+ """
assert key.startswith(('access_token:', 'sys_config:'))
return await super().get(key)
async def set(self, key: str, value: str, *, ex: int) -> None:
+ """
+ 写入测试缓存键并设置过期时间。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :param ex: 捕获到的异常实例
+ """
assert key.startswith('access_token:')
await super().set(key, value, ex=ex)
@pytest_asyncio.fixture
async def resolution_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[SimpleNamespace]:
+ """
+ 为当前用户解析测试准备隔离环境。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :yield: ``SimpleNamespace`` 实例
+ """
monkeypatch.setattr(AppConfig, 'app_same_time_login', True)
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', False)
redis = AuthenticationRedis()
@@ -106,10 +134,23 @@ async def resolution_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Asy
@event.listens_for(engine.sync_engine, 'before_cursor_execute')
def record_select(connection: object, cursor: object, statement: str, *args: object) -> None:
+ """
+ 记录数据库执行的查询语句。
+
+ :param connection: 当前操作使用的连接
+ :param cursor: 执行当前 SQL 的数据库游标
+ :param statement: 即将执行的数据库语句
+ :param args: 传给被调用对象的位置参数
+ """
if statement.lstrip().upper().startswith('SELECT'):
statements.append(statement)
async def session_dependency() -> AsyncIterator[AsyncSession]:
+ """
+ 为当前请求提供测试数据库会话。
+
+ :yield: 当前操作使用的数据库会话
+ """
async with sessions() as db:
yield db
@@ -119,9 +160,11 @@ async def session_dependency() -> AsyncIterator[AsyncSession]:
handle_exception(app)
router = APIRouter(dependencies=[PreAuthDependency()])
- @router.get('/profile')
+ @router.get('/profile', summary='读取当前用户资料', description='通过认证依赖返回当前用户的资料和权限。')
@router.get(
'/permitted',
+ summary='读取权限保护的用户资料',
+ description='校验访问权限后返回当前用户资料。',
dependencies=[UserInterfaceAuthDependency('demo:read')],
)
async def profile(current_user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> CurrentUserModel:
@@ -153,6 +196,7 @@ async def profile(current_user: Annotated[CurrentUserModel, CurrentUserDependenc
@pytest.mark.asyncio
async def test_double_auth_declaration_queries_and_renews_once_per_request(resolution_env: SimpleNamespace) -> None:
+ """重复声明认证时单个请求只查询和续期一次。"""
first = await resolution_env.client.get('/profile', headers=resolution_env.headers[USER_ID])
assert first.status_code == HttpStatusConstant.SUCCESS
assert len(resolution_env.statements) == REGULAR_QUERY_COUNT
@@ -176,6 +220,7 @@ async def test_double_auth_declaration_queries_and_renews_once_per_request(resol
@pytest.mark.asyncio
async def test_admin_does_not_load_menus_for_authentication(resolution_env: SimpleNamespace) -> None:
+ """管理员认证不加载菜单。"""
response = await resolution_env.client.get('/permitted', headers=resolution_env.headers[ADMIN_ID])
assert response.json()['permissions'] == ['*:*:*']
assert response.json()['roles'] == ['admin']
@@ -187,11 +232,25 @@ async def test_admin_does_not_load_menus_for_authentication(resolution_env: Simp
@pytest.mark.asyncio
async def test_use_cache_false_queries_and_renews_again_in_the_same_request(resolution_env: SimpleNamespace) -> None:
- @resolution_env.app.get('/revalidate', dependencies=[PreAuthDependency()])
+ """禁用依赖缓存后同一请求再次查询并续期。"""
+
+ @resolution_env.app.get(
+ '/revalidate',
+ summary='检查请求内重新认证',
+ description='重新查询当前用户,返回权限和请求上下文的比较结果。',
+ dependencies=[PreAuthDependency()],
+ )
async def revalidate(
first: Annotated[CurrentUserModel, CurrentUserDependency()],
second: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
) -> dict:
+ """
+ 返回含 ``sameUser``, ``permissions``, ``contextIsFresh`` 的测试数据。
+
+ :param first: 当前已认证用户及其权限信息
+ :param second: 当前已认证用户及其权限信息
+ :return: 含 ``sameUser``, ``permissions``, ``contextIsFresh`` 的测试数据
+ """
return {
'sameUser': first is second,
'permissions': second.permissions,
@@ -208,14 +267,31 @@ async def revalidate(
@pytest.mark.asyncio
async def test_use_cache_false_rejects_a_session_revoked_in_the_same_request(resolution_env: SimpleNamespace) -> None:
+ """禁用依赖缓存后拒绝在同一请求中撤销的会话。"""
+
async def revoke_session(current_user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> None:
+ """
+ 移除当前用户的会话记录。
+
+ :param current_user: 当前登录用户及其权限信息
+ """
assert current_user.user.user_id == USER_ID
await resolution_env.redis.delete(f'access_token:session-{USER_ID}')
- @resolution_env.app.get('/revoke-session', dependencies=[PreAuthDependency(), Depends(revoke_session)])
+ @resolution_env.app.get(
+ '/revoke-session',
+ summary='检查请求内会话撤销',
+ description='在同一请求内撤销会话后重新认证,验证撤销生效。',
+ dependencies=[PreAuthDependency(), Depends(revoke_session)],
+ )
async def revalidate(
current_user: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
) -> CurrentUserModel:
+ """
+ 在调用时报告预期的测试失败:已撤销的会话不应进入接口。
+
+ :param current_user: 当前登录用户及其权限信息
+ """
pytest.fail('已撤销的会话不应进入接口')
response = await resolution_env.client.get('/revoke-session', headers=resolution_env.headers[USER_ID])
@@ -231,10 +307,18 @@ async def revalidate(
async def test_use_cache_false_applies_permission_changes_in_the_same_request(
resolution_env: SimpleNamespace, change: str
) -> None:
+ """禁用依赖缓存后同一请求可读取权限变更。"""
+
async def revoke_permission(
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> None:
+ """
+ 在用户已解析后提交权限变更。
+
+ :param current_user: 当前登录用户及其权限信息
+ :param query_db: 当前操作使用的异步数据库会话
+ """
assert current_user.permissions == ['demo:read']
if change == 'remove_menu':
await query_db.execute(delete(SysRoleMenu).where(SysRoleMenu.role_id == USER_ID))
@@ -244,6 +328,8 @@ async def revoke_permission(
@resolution_env.app.get(
'/revoke-permission',
+ summary='检查请求内权限变更',
+ description='在同一请求内调整用户权限,再次验证访问资格。',
dependencies=[
PreAuthDependency(),
Depends(revoke_permission),
@@ -253,6 +339,12 @@ async def revalidate(
current_user: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
permitted: Annotated[bool, UserInterfaceAuthDependency('demo:read')],
) -> None:
+ """
+ 在调用时报告预期的测试失败:权限撤销后不应进入接口。
+
+ :param current_user: 当前登录用户及其权限信息
+ :param permitted: 该请求是否拥有所需权限
+ """
pytest.fail('权限撤销后不应进入接口')
response = await resolution_env.client.get('/revoke-permission', headers=resolution_env.headers[USER_ID])
@@ -267,6 +359,7 @@ async def revalidate(
async def test_disabled_or_deleted_user_is_rejected_on_next_request(
resolution_env: SimpleNamespace, change: dict[str, str]
) -> None:
+ """后续请求拒绝已禁用或删除的用户。"""
first = await resolution_env.client.get('/profile', headers=resolution_env.headers[USER_ID])
assert first.json()['user']['userId'] == USER_ID
async with resolution_env.sessions.begin() as db:
@@ -281,6 +374,7 @@ async def test_disabled_or_deleted_user_is_rejected_on_next_request(
@pytest.mark.asyncio
@pytest.mark.parametrize('change', ['remove', 'disable', 'delete'])
async def test_role_revocation_applies_to_next_request(resolution_env: SimpleNamespace, change: str) -> None:
+ """后续请求应用角色撤销结果。"""
first = await resolution_env.client.get('/permitted', headers=resolution_env.headers[USER_ID])
assert first.json()['permissions'] == ['demo:read']
async with resolution_env.sessions.begin() as db:
@@ -303,6 +397,7 @@ async def test_role_revocation_applies_to_next_request(resolution_env: SimpleNam
async def test_password_policy_changes_are_recomputed_on_next_request(
resolution_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """后续请求重新计算已变更的密码策略。"""
first = await resolution_env.client.get('/profile', headers=resolution_env.headers[USER_ID])
assert first.json()['pwdChrtype'] == '0'
assert not first.json()['isDefaultModifyPwd']
@@ -329,6 +424,7 @@ async def test_password_policy_changes_are_recomputed_on_next_request(
async def test_password_expiry_advances_between_requests(
resolution_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """两次请求之间按时间推进密码有效期。"""
now = TimezoneUtil.utc_now()
async with resolution_env.sessions.begin() as db:
await db.execute(update(SysUser).where(SysUser.user_id == USER_ID).values(pwd_update_date=now))
@@ -343,6 +439,7 @@ async def test_password_expiry_advances_between_requests(
@pytest.mark.asyncio
async def test_concurrent_requests_keep_user_identity_and_permissions_separate(resolution_env: SimpleNamespace) -> None:
+ """并发请求隔离用户身份和权限。"""
admin, reader = await asyncio.gather(
resolution_env.client.get('/profile', headers=resolution_env.headers[ADMIN_ID]),
resolution_env.client.get('/profile', headers=resolution_env.headers[USER_ID]),
@@ -364,10 +461,21 @@ async def test_redis_failure_rejects_protected_requests_and_recovers_without_rel
operation: str,
failure: type[RedisError],
) -> None:
+ """Redis 故障时拒绝受保护请求并可在恢复后免重新登录。"""
resolution_env.app.add_middleware(ContextCleanupMiddleware)
- @resolution_env.app.get('/public-health', dependencies=[PreAuthDependency([{'path': '/public-health'}])])
+ @resolution_env.app.get(
+ '/public-health',
+ summary='读取公开健康状态',
+ description='返回服务健康状态,用于检查缓存服务故障时的公开访问。',
+ dependencies=[PreAuthDependency([{'path': '/public-health'}])],
+ )
async def public_health() -> dict:
+ """
+ 返回含 ``status`` 的测试数据。
+
+ :return: 含 ``status`` 的测试数据
+ """
return {'status': 'ok'}
original = getattr(resolution_env.redis, operation)
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_dept_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_dept_service.py
index a27e2bb1b..646e13f66 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_dept_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_dept_service.py
@@ -15,10 +15,21 @@
async def _create_dept_table() -> tuple[AsyncEngine, async_sessionmaker[AsyncSession]]:
+ """
+ 在内存数据库中准备部门表。
+
+ :return: 依次为 ``engine``、``session_maker`` 的元组
+ """
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
@event.listens_for(engine.sync_engine, 'connect')
def register_find_in_set(connection: Any, _record: Any) -> None:
+ """
+ 为 SQLite 测试连接注册集合成员查找函数。
+
+ :param connection: 当前操作使用的连接
+ :param _record: 回调接收的记录
+ """
connection.create_function('find_in_set', 2, lambda value, values: int(str(value) in (values or '').split(',')))
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
@@ -28,6 +39,7 @@ def register_find_in_set(connection: Any, _record: Any) -> None:
def test_parse_dept_sort_items_preserves_corresponding_order_values() -> None:
+ """解析部门排序时保留各部门对应的顺序值。"""
result = DeptService.parse_dept_sort_items(DeptSortModel(deptIds='101, 102', orderNums='3, 1'))
assert result == [
@@ -47,6 +59,7 @@ def test_parse_dept_sort_items_preserves_corresponding_order_values() -> None:
],
)
def test_parse_dept_sort_items_rejects_invalid_parameters(dept_ids: str, order_nums: str) -> None:
+ """部门排序拒绝无效参数。"""
with pytest.raises(ServiceException) as exc_info:
DeptService.parse_dept_sort_items(DeptSortModel(deptIds=dept_ids, orderNums=order_nums))
@@ -55,6 +68,7 @@ def test_parse_dept_sort_items_rejects_invalid_parameters(dept_ids: str, order_n
@pytest.mark.asyncio
async def test_update_dept_sort_updates_all_rows_in_one_transaction() -> None:
+ """在同一事务中更新全部部门排序。"""
engine, session_maker = await _create_dept_table()
try:
async with session_maker() as session:
@@ -80,6 +94,7 @@ async def test_update_dept_sort_updates_all_rows_in_one_transaction() -> None:
@pytest.mark.asyncio
async def test_update_dept_sort_rolls_back_and_wraps_database_error() -> None:
+ """部门排序遇到数据库错误时回滚并转换异常。"""
query_db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
with (
@@ -97,6 +112,11 @@ async def test_update_dept_sort_rolls_back_and_wraps_database_error() -> None:
async def _seed_dept_tree(session: AsyncSession) -> None:
+ """
+ 写入供层级查询使用的部门测试数据。
+
+ :param session: 当前操作共用的会话
+ """
session.add_all(
[
SysDept(dept_id=100, parent_id=0, ancestors='0', dept_name='总部门'),
@@ -113,6 +133,7 @@ async def _seed_dept_tree(session: AsyncSession) -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('parent_id', [101, 102, 103, 201, 999])
async def test_edit_dept_rejects_cycles_and_invalid_parents_without_writing(parent_id: int) -> None:
+ """编辑部门时拒绝循环关系或无效上级且不写库。"""
engine, sessions = await _create_dept_table()
try:
async with sessions() as session:
@@ -131,6 +152,7 @@ async def test_edit_dept_rejects_cycles_and_invalid_parents_without_writing(pare
@pytest.mark.asyncio
@pytest.mark.parametrize('parent_id', [0, 200])
async def test_edit_dept_moves_whole_subtree_and_rebuilds_ancestors(parent_id: int) -> None:
+ """移动整个部门子树并重建祖先关系。"""
engine, sessions = await _create_dept_table()
try:
async with sessions() as session:
@@ -160,6 +182,7 @@ async def test_edit_dept_moves_whole_subtree_and_rebuilds_ancestors(parent_id: i
@pytest.mark.asyncio
@pytest.mark.parametrize('dept_id', [100, 101])
async def test_edit_dept_preserves_omitted_parent_and_ignores_supplied_ancestors(dept_id: int) -> None:
+ """编辑部门时保留省略的上级并忽略外部提供的祖先。"""
engine, sessions = await _create_dept_table()
try:
async with sessions() as session:
@@ -177,6 +200,7 @@ async def test_edit_dept_preserves_omitted_parent_and_ignores_supplied_ancestors
@pytest.mark.asyncio
@pytest.mark.parametrize('parent_id', [None, 201, 999])
async def test_add_dept_rejects_missing_or_deleted_parent(parent_id: int | None) -> None:
+ """上级缺失或已删除时拒绝新增部门。"""
engine, sessions = await _create_dept_table()
try:
async with sessions() as session:
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_access_log.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_access_log.py
index 22e9e5176..6390e5e5d 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_access_log.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_access_log.py
@@ -19,24 +19,55 @@
class AsyncSessionContext:
- """测试用异步数据库会话上下文。"""
+ """
+ 测试用异步数据库会话上下文。
+
+ :ivar session: 当前操作共用的会话
+ """
def __init__(self, session: SimpleNamespace) -> None:
+ """
+ 初始化测试夹具的 ``session``。
+
+ :param session: 当前操作共用的会话
+ """
self.session = session
async def __aenter__(self) -> SimpleNamespace:
+ """
+ 向调用方返回 ``self.session``。
+
+ :return: 当前测试上下文持有的数据库会话
+ """
return self.session
async def __aexit__(self, exc_type: type | None, exc_value: BaseException | None, traceback: object) -> None:
- return None
+ """
+ 完成无需返回值的回调。
+
+ :param exc_type: 退出上下文时的异常类型
+ :param exc_value: 退出上下文时的异常实例
+ :param traceback: 异常的调用栈
+ """
+ return
def make_database_registry(session: SimpleNamespace) -> SimpleNamespace:
- """构造使用测试会话的数据库注册表。"""
+ """
+ 构造使用测试会话的数据库注册表。
+
+ :param session: 当前操作共用的会话
+ :return: 使用测试会话的数据库注册表
+ """
return SimpleNamespace(session=lambda: AsyncSessionContext(session))
def make_file_access_log() -> FileAccessLogModel:
+ """
+ 创建测试使用的 ``FileAccessLogModel`` 实例。
+
+ :return: 测试使用的 ``FileAccessLogModel`` 实例
+ """
return FileAccessLogModel(
fileId='file-id',
action='download',
@@ -54,6 +85,7 @@ def make_file_access_log() -> FileAccessLogModel:
def test_file_access_log_operation_detail_uses_unbounded_text_type() -> None:
+ """文件访问日志详情使用不限长度的文本类型。"""
operation_detail_column = SysFileAccessLog.__table__.c.operation_detail
assert isinstance(operation_detail_column.type, Text)
@@ -61,6 +93,7 @@ def test_file_access_log_operation_detail_uses_unbounded_text_type() -> None:
def test_file_access_log_is_enqueued_to_redis_stream() -> None:
+ """文件访问日志进入 Redis Stream。"""
redis = SimpleNamespace(xadd=AsyncMock())
request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis)))
@@ -84,6 +117,7 @@ def test_file_access_log_is_enqueued_to_redis_stream() -> None:
def test_file_access_log_event_is_persisted_and_acknowledged() -> None:
+ """持久化文件访问日志后确认事件。"""
session = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
redis = SimpleNamespace(set=AsyncMock(return_value=True), xack=AsyncMock(), delete=AsyncMock())
file_access_log = make_file_access_log()
@@ -119,6 +153,7 @@ def test_file_access_log_event_is_persisted_and_acknowledged() -> None:
def test_file_audit_batch_events_use_independent_deduplication_keys() -> None:
+ """批量审计事件使用独立的去重键。"""
redis = SimpleNamespace(xadd=AsyncMock())
request = SimpleNamespace(
app=SimpleNamespace(state=SimpleNamespace(redis=redis)),
@@ -128,6 +163,7 @@ def test_file_audit_batch_events_use_independent_deduplication_keys() -> None:
current_user = SimpleNamespace(user=SimpleNamespace(user_id=10, user_name='user10'))
async def enqueue_batch() -> None:
+ """向文件审计队列投递测试批次。"""
await FileAuditService.enqueue_file_audit(
request,
current_user,
@@ -162,6 +198,7 @@ async def enqueue_batch() -> None:
def test_file_audit_operation_detail_is_not_truncated() -> None:
+ """保留完整的文件审计操作详情。"""
reason = 'a' * LONG_OPERATION_DETAIL_LENGTH
serialized_detail = FileAuditService._serialize_operation_detail({'reason': reason})
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_acl.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_acl.py
index f554332a7..07c6bbc9f 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_acl.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_acl.py
@@ -21,6 +21,11 @@
def make_query_db() -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
@@ -31,6 +36,16 @@ def make_current_user(
ancestors: str = '',
admin: bool = False,
) -> SimpleNamespace:
+ """
+ 构造带有测试所需角色和权限的用户。
+
+ :param user_id: 用户的唯一标识
+ :param role_ids: 角色id
+ :param dept_id: 部门id
+ :param ancestors: 当前部门的祖先路径
+ :param admin: 是否使用管理员身份
+ :return: 带有测试所需角色和权限的用户
+ """
roles = [SimpleNamespace(role_id=role_id) for role_id in (role_ids or [])]
dept = SimpleNamespace(dept_id=dept_id, ancestors=ancestors) if dept_id else None
user = SimpleNamespace(
@@ -50,6 +65,14 @@ def make_file_info(
upload_user_id: int = 11,
uploader_access_enabled: str = '1',
) -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param owner_user_id: 新所有者用户ID
+ :param upload_user_id: 上传用户ID
+ :param uploader_access_enabled: 是否保留上传人访问权限
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(
owner_user_id=owner_user_id,
upload_user_id=upload_user_id,
@@ -63,6 +86,15 @@ def make_acl(
effect: str = 'allow',
include_children: str = '0',
) -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param subject_type: 主体类型
+ :param subject_id: 身份主体的唯一标识
+ :param effect: 更新权限或状态时采用的效果
+ :param include_children: 部门是否包含下级
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(
subject_type=subject_type,
subject_id=subject_id,
@@ -84,6 +116,7 @@ def test_private_file_acl_allows_matching_user_role_or_department(
current_user: SimpleNamespace,
file_acl: SimpleNamespace,
) -> None:
+ """私有文件授权匹配用户、角色或部门。"""
with patch.object(FileAclDao, 'get_effective_file_acl_list', new=AsyncMock(return_value=[file_acl])):
result = asyncio.run(
CommonService._has_private_file_download_permission(
@@ -99,6 +132,7 @@ def test_private_file_acl_allows_matching_user_role_or_department(
def test_private_file_acl_does_not_apply_parent_department_without_include_children() -> None:
+ """未启用包含子部门时不沿用上级部门的文件授权。"""
current_user = make_current_user(20, dept_id=120, ancestors='0,100,110')
file_acl = make_acl('dept', 100, include_children='0')
@@ -117,6 +151,7 @@ def test_private_file_acl_does_not_apply_parent_department_without_include_child
def test_file_acl_department_options_are_returned_as_tree() -> None:
+ """文件授权部门选项按树返回。"""
dept_list = [
SimpleNamespace(dept_id=PARENT_DEPT_ID, dept_name='研发中心', parent_id=0),
SimpleNamespace(dept_id=CHILD_DEPT_ID, dept_name='平台研发部', parent_id=PARENT_DEPT_ID),
@@ -130,6 +165,7 @@ def test_file_acl_department_options_are_returned_as_tree() -> None:
def test_file_acl_list_returns_current_version() -> None:
+ """文件授权列表返回当前版本。"""
acl_version = 7
with (
patch.object(
@@ -173,6 +209,7 @@ def test_file_acl_list_returns_current_version() -> None:
def test_file_acl_list_marks_uploader_permission_non_overridable_when_uploader_is_owner() -> None:
+ """上传者也是所有者时其权限标记为不可覆盖。"""
file_info = SimpleNamespace(
acl_version=0,
access_type='private',
@@ -210,6 +247,7 @@ def test_file_acl_list_marks_uploader_permission_non_overridable_when_uploader_i
def test_file_acl_list_exposes_disabled_uploader_permission() -> None:
+ """文件授权列表显示已禁用的上传者权限。"""
file_info = SimpleNamespace(
access_type='private',
owner_user_id=10,
@@ -230,6 +268,7 @@ def test_file_acl_list_exposes_disabled_uploader_permission() -> None:
def test_file_acl_role_options_exclude_roles_with_members_outside_user_data_scope() -> None:
+ """文件授权角色选项排除成员超出当前用户数据范围的角色。"""
query_db = SimpleNamespace(
execute=AsyncMock(
side_effect=[
@@ -251,6 +290,7 @@ def test_file_acl_role_options_exclude_roles_with_members_outside_user_data_scop
def test_private_file_acl_explicit_deny_overrides_uploader_and_allow_rule() -> None:
+ """显式拒绝优先于上传者身份及允许规则。"""
current_user = make_current_user(20, role_ids=[5])
file_acl_list = [make_acl('role', 5, effect='allow'), make_acl('user', 20, effect='deny')]
@@ -269,6 +309,7 @@ def test_private_file_acl_explicit_deny_overrides_uploader_and_allow_rule() -> N
def test_private_file_acl_does_not_allow_uploader_when_compatibility_access_is_disabled() -> None:
+ """关闭兼容访问后上传者不自动获得私有文件权限。"""
current_user = make_current_user(20)
with patch.object(FileAclDao, 'get_effective_file_acl_list', new=AsyncMock(return_value=[])):
@@ -287,6 +328,7 @@ def test_private_file_acl_does_not_allow_uploader_when_compatibility_access_is_d
@pytest.mark.parametrize('current_user', [make_current_user(20, admin=True), make_current_user(20)])
def test_private_file_acl_admin_or_owner_is_not_blocked_by_deny(current_user: SimpleNamespace) -> None:
+ """管理员或所有者不受私有文件拒绝规则阻拦。"""
file_info = make_file_info(owner_user_id=20 if not current_user.user.admin else 10)
get_acl_list = AsyncMock(return_value=[make_acl('user', 20, effect='deny')])
@@ -306,6 +348,7 @@ def test_private_file_acl_admin_or_owner_is_not_blocked_by_deny(current_user: Si
def test_save_file_acl_normalizes_department_scope_and_commits() -> None:
+ """保存文件授权时规范化部门范围并提交。"""
query_db = make_query_db()
current_user = make_current_user(1, admin=True)
acl_version = 3
@@ -368,6 +411,7 @@ def test_save_file_acl_normalizes_department_scope_and_commits() -> None:
def test_batch_save_file_acl_replaces_all_selected_private_files() -> None:
+ """批量保存替换全部选中私有文件的授权。"""
query_db = make_query_db()
current_user = make_current_user(1, admin=True)
file_infos = [
@@ -410,6 +454,7 @@ def test_batch_save_file_acl_replaces_all_selected_private_files() -> None:
def test_batch_save_file_acl_rejects_public_files() -> None:
+ """批量保存文件授权时拒绝公开文件。"""
query_db = make_query_db()
save_model = BatchSaveFileAclModel(fileIds=FILE_ID, entries=[])
file_infos = [SimpleNamespace(file_id=FILE_ID, access_type='public', acl_version=0)]
@@ -436,6 +481,7 @@ def test_batch_save_file_acl_rejects_public_files() -> None:
def test_save_file_acl_rejects_duplicate_or_expired_entries() -> None:
+ """保存文件授权时拒绝重复或过期条目。"""
query_db = make_query_db()
current_user = make_current_user(1, admin=True)
file_info = SimpleNamespace(access_type='private', acl_version=0)
@@ -489,6 +535,7 @@ def test_save_file_acl_rejects_duplicate_or_expired_entries() -> None:
def test_save_file_acl_rejects_subject_outside_data_scope() -> None:
+ """保存文件授权时拒绝数据范围外的主体。"""
query_db = make_query_db()
current_user = make_current_user(1, admin=True)
file_info = SimpleNamespace(access_type='private', acl_version=0)
@@ -518,6 +565,7 @@ def test_save_file_acl_rejects_subject_outside_data_scope() -> None:
def test_save_file_acl_rejects_file_outside_data_scope() -> None:
+ """保存文件授权时拒绝数据范围外的文件。"""
query_db = make_query_db()
current_user = make_current_user(20)
save_model = SaveFileAclModel(aclVersion=0, entries=[])
@@ -550,6 +598,7 @@ def test_save_file_acl_rejects_file_outside_data_scope() -> None:
def test_save_file_acl_rejects_stale_acl_version() -> None:
+ """保存文件授权时拒绝过期版本。"""
query_db = make_query_db()
file_info = SimpleNamespace(access_type='private', acl_version=2)
save_model = SaveFileAclModel(aclVersion=1, entries=[])
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_lifecycle_retention_execution.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_lifecycle_retention_execution.py
index e1c341d41..3f6f463de 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_lifecycle_retention_execution.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_lifecycle_retention_execution.py
@@ -31,10 +31,20 @@
def make_query_db() -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
def make_current_user() -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(user=SimpleNamespace(user_id=1, user_name='admin', admin=True))
@@ -42,6 +52,13 @@ def make_file_info(
access_type: str = 'private',
expire_time: datetime | None = None,
) -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param access_type: 文件访问类型
+ :param expire_time: 文件当前到期时间
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(
file_id=FILE_ID,
original_name='private.txt',
@@ -58,6 +75,7 @@ def make_file_info(
def test_purge_file_removes_recycle_content_and_metadata(tmp_path: Path) -> None:
+ """彻底删除文件时清理回收内容和元数据。"""
public_root = tmp_path / 'public'
trash_root = tmp_path / 'trash'
trash_file = trash_root / FILE_ID / 'private.txt'
@@ -101,6 +119,7 @@ def test_purge_file_removes_recycle_content_and_metadata(tmp_path: Path) -> None
def test_purge_file_rejects_business_reference(tmp_path: Path) -> None:
+ """仍有业务引用的文件不能彻底删除。"""
file_info = make_file_info()
query_db = make_query_db()
@@ -133,6 +152,7 @@ def test_purge_file_rejects_business_reference(tmp_path: Path) -> None:
def test_retention_scan_creates_expiring_and_expired_notices() -> None:
+ """保留期扫描生成即将过期和已过期通知。"""
current_time = datetime.now(UTC)
expired_file = make_file_info(expire_time=current_time - timedelta(days=1))
expiring_file = SimpleNamespace(
@@ -182,6 +202,7 @@ def test_retention_scan_creates_expiring_and_expired_notices() -> None:
def test_mark_retention_notice_read_checks_data_scope() -> None:
+ """标记保留期通知已读时检查数据范围。"""
query_db = make_query_db()
query_object = FileRetentionNoticePageQueryModel()
@@ -227,6 +248,7 @@ def test_mark_retention_notice_read_checks_data_scope() -> None:
def test_retention_policy_rejects_public_business_file() -> None:
+ """保留策略拒绝公开业务文件。"""
query_db = make_query_db()
public_file = make_file_info(access_type='public')
@@ -264,6 +286,7 @@ def test_retention_policy_rejects_public_business_file() -> None:
def test_extend_file_retention_updates_terminal_references() -> None:
+ """延长文件保留期时更新终止状态的引用。"""
current_time = datetime.now(UTC)
previous_expire_time = current_time + timedelta(days=1)
new_expire_time = current_time + timedelta(days=31)
@@ -313,6 +336,7 @@ def test_extend_file_retention_updates_terminal_references() -> None:
def test_dispose_expired_file_releases_expired_references() -> None:
+ """处置过期文件时释放过期引用。"""
current_time = datetime.now(UTC)
expire_time = current_time - timedelta(days=1)
file_info = make_file_info(expire_time=expire_time)
@@ -361,6 +385,7 @@ def test_dispose_expired_file_releases_expired_references() -> None:
def test_dispose_expired_file_rejects_active_reference() -> None:
+ """处置过期文件时拒绝仍然有效的引用。"""
expire_time = datetime.now(UTC) - timedelta(days=1)
file_info = make_file_info(expire_time=expire_time)
reference = SimpleNamespace(
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_management.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_management.py
index ded604c2b..6d4bc1204 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_management.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_management.py
@@ -27,11 +27,22 @@
def make_query_db(commit_error: Exception | None = None) -> SimpleNamespace:
+ """
+ 准备测试所需的异步数据库会话。
+
+ :param commit_error: 模拟事务提交失败时抛出的异常
+ :return: ``SimpleNamespace`` 实例
+ """
commit = AsyncMock(side_effect=commit_error) if commit_error else AsyncMock()
return SimpleNamespace(commit=commit, rollback=AsyncMock())
def make_current_user() -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(user=SimpleNamespace(user_id=1, user_name='admin', admin=True))
@@ -43,6 +54,17 @@ def make_file_info(
business_type: str | None = None,
business_id: str | None = None,
) -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param file_id: 文件ID
+ :param access_type: 文件访问类型
+ :param storage_key: 存储相对路径
+ :param stored_name: 存储文件名
+ :param business_type: 业务类型
+ :param business_id: 业务ID
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(
file_id=file_id,
original_name=stored_name,
@@ -56,20 +78,29 @@ def make_file_info(
def expire_model_attributes(*models: SimpleNamespace) -> None:
- """模拟SQLAlchemy事务结束后ORM属性过期。"""
+ """
+ 模拟SQLAlchemy事务结束后ORM属性过期。
+
+ :param models: 调用方传入的其余位置参数
+ """
for model in models:
model.__dict__.clear()
@pytest.fixture(autouse=True)
def mock_file_reference_count() -> Generator[None, None, None]:
- """默认模拟文件不存在业务引用。"""
+ """
+ 默认模拟文件不存在业务引用。
+
+ :yield: 上下文就绪后将控制权交给调用方
+ """
with patch.object(FileReferenceDao, 'get_file_reference_count_map', new=AsyncMock(return_value={})):
yield
@pytest.mark.parametrize('data_scope', [GetDataScope.DATA_SCOPE_DEPT, GetDataScope.DATA_SCOPE_DEPT_AND_CHILD])
def test_file_data_scope_does_not_match_unowned_files_when_user_has_no_department(data_scope: str) -> None:
+ """无所属部门的用户不能匹配无所有者文件。"""
current_user = SimpleNamespace(
user=SimpleNamespace(
user_id=20,
@@ -93,6 +124,7 @@ def test_file_data_scope_does_not_match_unowned_files_when_user_has_no_departmen
def test_file_detail_reads_sqlalchemy_attributes_and_outputs_camel_case() -> None:
+ """文件详情读取 SQLAlchemy 属性并使用驼峰字段输出。"""
file_info = SysFileInfo(
file_id=PUBLIC_FILE_ID,
original_name='report.pdf',
@@ -122,6 +154,7 @@ def test_file_detail_reads_sqlalchemy_attributes_and_outputs_camel_case() -> Non
def test_file_storage_status_distinguishes_normal_quarantined_and_missing(tmp_path: Path) -> None:
+ """存储状态区分正常、隔离及缺失文件。"""
public_root = tmp_path / 'public'
trash_root = tmp_path / 'trash'
source_file = public_root / 'upload' / 'public.txt'
@@ -151,6 +184,7 @@ def test_file_storage_status_distinguishes_normal_quarantined_and_missing(tmp_pa
def test_file_storage_status_marks_invalid_paths() -> None:
+ """存储状态标记无效路径。"""
file_info = {
'fileId': PUBLIC_FILE_ID,
'storageType': 'local',
@@ -164,6 +198,7 @@ def test_file_storage_status_marks_invalid_paths() -> None:
def test_transfer_file_updates_owner_and_department_with_data_scope() -> None:
+ """移交文件时按数据范围更新所有者和部门。"""
query_db = make_query_db()
transfer_model = TransferFileModel(
ownerUserId=TARGET_USER_ID,
@@ -220,12 +255,14 @@ def test_transfer_file_updates_owner_and_department_with_data_scope() -> None:
def test_transfer_file_model_retains_uploader_access_by_default() -> None:
+ """移交文件默认保留上传者访问权。"""
transfer_model = TransferFileModel(ownerUserId=TARGET_USER_ID, deptId=TARGET_DEPT_ID, reason='岗位调整')
assert transfer_model.retain_uploader_access is True
def test_transfer_file_rejects_target_outside_data_scope() -> None:
+ """拒绝向数据范围外的目标移交文件。"""
query_db = make_query_db()
transfer_model = TransferFileModel(ownerUserId=TARGET_USER_ID, deptId=TARGET_DEPT_ID, reason='岗位调整')
user_data_scope_sql = false()
@@ -259,6 +296,7 @@ def test_transfer_file_rejects_target_outside_data_scope() -> None:
def test_transfer_file_rejects_owner_department_mismatch() -> None:
+ """移交文件时拒绝所有者与部门不匹配的请求。"""
query_db = make_query_db()
transfer_model = TransferFileModel(ownerUserId=TARGET_USER_ID, deptId=TARGET_DEPT_ID, reason='岗位调整')
@@ -294,6 +332,7 @@ def test_transfer_file_rejects_owner_department_mismatch() -> None:
def test_transfer_file_rejects_source_outside_data_scope() -> None:
+ """拒绝移交数据范围外的源文件。"""
query_db = make_query_db()
transfer_model = TransferFileModel(ownerUserId=TARGET_USER_ID, deptId=TARGET_DEPT_ID, reason='岗位调整')
file_data_scope_sql = false()
@@ -332,6 +371,7 @@ def test_transfer_file_rejects_source_outside_data_scope() -> None:
def test_delete_file_moves_both_storage_types_to_recycle_bin(tmp_path: Path) -> None:
+ """删除两种存储类型的文件时均移入回收站。"""
public_root = tmp_path / 'public'
private_root = tmp_path / 'private'
trash_root = tmp_path / 'trash'
@@ -380,6 +420,7 @@ def test_delete_file_moves_both_storage_types_to_recycle_bin(tmp_path: Path) ->
def test_delete_file_rejects_business_reference_before_moving_file(tmp_path: Path) -> None:
+ """删除文件前检查业务引用。"""
public_root = tmp_path / 'public'
public_file = public_root / 'upload' / 'public.txt'
public_file.parent.mkdir(parents=True)
@@ -417,6 +458,7 @@ def test_delete_file_rejects_business_reference_before_moving_file(tmp_path: Pat
def test_delete_file_rejects_legacy_business_reference(tmp_path: Path) -> None:
+ """旧版业务引用仍阻止删除文件。"""
public_root = tmp_path / 'public'
public_file = public_root / 'upload' / 'public.txt'
public_file.parent.mkdir(parents=True)
@@ -455,6 +497,7 @@ def test_delete_file_rejects_legacy_business_reference(tmp_path: Path) -> None:
def test_delete_file_restores_physical_file_when_database_commit_fails(tmp_path: Path) -> None:
+ """删除事务提交失败时恢复物理文件。"""
public_root = tmp_path / 'public'
trash_root = tmp_path / 'trash'
public_file = public_root / 'upload' / 'public.txt'
@@ -485,6 +528,7 @@ def test_delete_file_restores_physical_file_when_database_commit_fails(tmp_path:
def test_delete_file_rejects_storage_path_escape(tmp_path: Path) -> None:
+ """删除文件时拒绝越界的存储路径。"""
public_root = tmp_path / 'public'
public_root.mkdir()
outside_file = tmp_path / 'outside.txt'
@@ -513,6 +557,7 @@ def test_delete_file_rejects_storage_path_escape(tmp_path: Path) -> None:
def test_delete_file_does_not_overwrite_existing_recycle_bin_file(tmp_path: Path) -> None:
+ """删除时保留回收站内的同名文件。"""
public_root = tmp_path / 'public'
trash_root = tmp_path / 'trash'
public_file = public_root / 'upload' / 'public.txt'
@@ -547,6 +592,7 @@ def test_delete_file_does_not_overwrite_existing_recycle_bin_file(tmp_path: Path
def test_delete_file_restores_already_staged_files_when_later_path_is_invalid(tmp_path: Path) -> None:
+ """后续路径无效时恢复先前已移入回收站的文件。"""
public_root = tmp_path / 'public'
valid_file = public_root / 'upload' / 'public.txt'
valid_file.parent.mkdir(parents=True)
@@ -581,6 +627,7 @@ def test_delete_file_restores_already_staged_files_when_later_path_is_invalid(tm
def test_delete_file_allows_missing_physical_file_to_close_metadata(tmp_path: Path) -> None:
+ """物理文件缺失时允许关闭元数据记录。"""
public_root = tmp_path / 'public'
public_root.mkdir()
file_infos = [make_file_info(PUBLIC_FILE_ID, 'public', 'upload/missing.txt', 'missing.txt')]
@@ -606,6 +653,7 @@ def test_delete_file_allows_missing_physical_file_to_close_metadata(tmp_path: Pa
def test_delete_file_rejects_invalid_or_missing_file_ids() -> None:
+ """删除时拒绝无效或缺失的文件标识。"""
with pytest.raises(ServiceException):
FileUtil.parse_file_ids('invalid-id')
@@ -627,6 +675,7 @@ def test_delete_file_rejects_invalid_or_missing_file_ids() -> None:
def test_delete_file_rejects_file_outside_data_scope() -> None:
+ """拒绝删除数据范围外的文件。"""
query_db = make_query_db()
file_data_scope_sql = false()
@@ -655,6 +704,7 @@ def test_delete_file_rejects_file_outside_data_scope() -> None:
def test_restore_file_moves_both_storage_types_out_of_recycle_bin(tmp_path: Path) -> None:
+ """两种存储类型的文件均可从回收站恢复。"""
public_root = tmp_path / 'public'
private_root = tmp_path / 'private'
trash_root = tmp_path / 'trash'
@@ -673,6 +723,12 @@ def test_restore_file_moves_both_storage_types_out_of_recycle_bin(tmp_path: Path
move_file = UploadUtil.move_file
def move_file_after_database_commit(source: Path, target: Path) -> None:
+ """
+ 确认数据库已提交后移动文件。
+
+ :param source: 本次文件操作的源路径
+ :param target: 本次操作的目标
+ """
query_db.commit.assert_awaited_once()
move_file(source, target)
@@ -713,6 +769,7 @@ def move_file_after_database_commit(source: Path, target: Path) -> None:
def test_restore_file_returns_physical_file_to_recycle_bin_when_database_commit_fails(tmp_path: Path) -> None:
+ """恢复事务提交失败时将物理文件移回回收站。"""
public_root = tmp_path / 'public'
trash_root = tmp_path / 'trash'
trash_file = trash_root / PUBLIC_FILE_ID / 'public.txt'
@@ -747,6 +804,7 @@ def test_restore_file_returns_physical_file_to_recycle_bin_when_database_commit_
def test_restore_file_compensates_metadata_when_file_move_fails(tmp_path: Path) -> None:
+ """移动文件失败时补偿恢复操作的元数据。"""
public_root = tmp_path / 'public'
private_root = tmp_path / 'private'
trash_root = tmp_path / 'trash'
@@ -767,6 +825,13 @@ def test_restore_file_compensates_metadata_when_file_move_fails(tmp_path: Path)
expected_commit_count = 2
def fail_second_move(source: Path, target: Path) -> None:
+ """
+ 在第二次文件移动时注入故障。
+
+ :param source: 本次文件操作的源路径
+ :param target: 本次操作的目标
+ :raises OSError: 模拟移动第二个文件失败
+ """
nonlocal move_count
move_count += 1
if move_count == failed_move_number:
@@ -806,6 +871,7 @@ def fail_second_move(source: Path, target: Path) -> None:
def test_restore_file_rejects_existing_original_path(tmp_path: Path) -> None:
+ """原路径已存在时拒绝恢复。"""
public_root = tmp_path / 'public'
trash_root = tmp_path / 'trash'
public_file = public_root / 'upload' / 'public.txt'
@@ -845,6 +911,7 @@ def test_restore_file_rejects_existing_original_path(tmp_path: Path) -> None:
def test_restore_file_rejects_file_outside_data_scope() -> None:
+ """拒绝恢复数据范围外的文件。"""
query_db = make_query_db()
file_data_scope_sql = false()
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reconcile.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reconcile.py
index 500570a1b..a88a37c6f 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reconcile.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reconcile.py
@@ -24,6 +24,12 @@
def make_roots(tmp_path: Path) -> dict[str, Path]:
+ """
+ 准备测试用的文件存储目录。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :return: 需要检查的文件存储根目录集合
+ """
roots = {
'public': tmp_path / 'public',
'private': tmp_path / 'private',
@@ -36,6 +42,13 @@ def make_roots(tmp_path: Path) -> dict[str, Path]:
def make_file_info(content: bytes, **overrides: object) -> dict[str, object]:
+ """
+ 构造文件信息记录。
+
+ :param content: 需要读取或写入的内容
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 文件信息记录
+ """
file_info: dict[str, object] = {
'file_id': FILE_ID,
'storage_type': 'local',
@@ -52,6 +65,14 @@ def make_file_info(content: bytes, **overrides: object) -> dict[str, object]:
def write_file(root: Path, relative_key: str, content: bytes) -> Path:
+ """
+ 在指定存储根目录下创建测试文件。
+
+ :param root: 路径解析的基准目录
+ :param relative_key: 相对路径
+ :param content: 需要读取或写入的内容
+ :return: 本次操作的目标
+ """
target = root / Path(relative_key)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(content)
@@ -63,11 +84,20 @@ def scan(
file_infos: list[dict[str, object]],
check_hash: bool = False,
) -> FileReconcileScanResult:
+ """
+ 在指定存储目录中进行文件对账扫描。
+
+ :param roots: 需要检查的文件存储根目录集合
+ :param file_infos: 文件信息列表
+ :param check_hash: 是否验证内容哈希
+ :return: 本次文件对账扫描发现的问题
+ """
with patch.object(FileReconcileUtil, 'get_storage_roots', return_value=roots):
return FileReconcileUtil.scan_storage(file_infos, check_hash)
def test_reconcile_scan_reports_normal_storage_without_findings(tmp_path: Path) -> None:
+ """存储正常时核对扫描不报告问题。"""
roots = make_roots(tmp_path)
content = b'normal file'
write_file(roots['public'], STORAGE_KEY, content)
@@ -80,6 +110,7 @@ def test_reconcile_scan_reports_normal_storage_without_findings(tmp_path: Path)
def test_reconcile_scan_detects_unexpected_trash_and_orphan_file(tmp_path: Path) -> None:
+ """核对扫描识别意外的回收内容和孤立文件。"""
roots = make_roots(tmp_path)
content = b'trash file'
write_file(roots['trash'], f'{FILE_ID}/{STORED_NAME}', content)
@@ -94,6 +125,7 @@ def test_reconcile_scan_detects_unexpected_trash_and_orphan_file(tmp_path: Path)
def test_reconcile_scan_detects_wrong_root_without_duplicate_orphan(tmp_path: Path) -> None:
+ """核对扫描识别根目录错位且不重复报告孤立文件。"""
roots = make_roots(tmp_path)
content = b'wrong root'
write_file(roots['private'], STORAGE_KEY, content)
@@ -106,6 +138,7 @@ def test_reconcile_scan_detects_wrong_root_without_duplicate_orphan(tmp_path: Pa
def test_reconcile_scan_ignores_recent_orphan_during_upload_window(tmp_path: Path) -> None:
+ """核对扫描在上传窗口内跳过新出现的孤立文件。"""
roots = make_roots(tmp_path)
write_file(roots['public'], 'uploading.txt', b'uploading')
@@ -116,6 +149,7 @@ def test_reconcile_scan_ignores_recent_orphan_during_upload_window(tmp_path: Pat
def test_reconcile_scan_detects_size_and_hash_mismatch(tmp_path: Path) -> None:
+ """核对扫描识别大小和哈希不匹配。"""
roots = make_roots(tmp_path)
actual_content = b'changed content'
write_file(roots['public'], STORAGE_KEY, actual_content)
@@ -130,6 +164,7 @@ def test_reconcile_scan_detects_size_and_hash_mismatch(tmp_path: Path) -> None:
def test_reconcile_scan_rejects_unsafe_metadata_path(tmp_path: Path) -> None:
+ """核对扫描拒绝不安全的元数据路径。"""
roots = make_roots(tmp_path)
result = scan(roots, [make_file_info(b'', storage_key='../outside.txt')])
@@ -139,6 +174,7 @@ def test_reconcile_scan_rejects_unsafe_metadata_path(tmp_path: Path) -> None:
def test_reconcile_available_actions_follow_issue_status() -> None:
+ """核对问题的状态决定可用操作。"""
open_orphan = SimpleNamespace(
status='open',
issue_type='orphan_file',
@@ -164,6 +200,7 @@ def test_reconcile_available_actions_follow_issue_status() -> None:
def test_reconcile_move_rejects_existing_target(tmp_path: Path) -> None:
+ """核对移动操作拒绝已存在的目标。"""
roots = make_roots(tmp_path)
write_file(roots['public'], 'source.txt', b'source')
write_file(roots['private'], 'target.txt', b'target')
@@ -176,6 +213,7 @@ def test_reconcile_move_rejects_existing_target(tmp_path: Path) -> None:
def test_reconcile_start_creates_manual_run_with_boolean_hash_flag() -> None:
+ """手动核对任务使用布尔值控制哈希检查。"""
query_db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
current_user = SimpleNamespace(user=SimpleNamespace(admin=True, user_name='admin'))
@@ -199,6 +237,7 @@ def test_reconcile_start_creates_manual_run_with_boolean_hash_flag() -> None:
def test_reconcile_run_page_converts_database_field_names() -> None:
+ """核对任务分页转换数据库字段名。"""
current_user = SimpleNamespace(user=SimpleNamespace(admin=True, user_name='admin'))
run_page = PageModel.model_validate(
{
@@ -238,6 +277,7 @@ def test_reconcile_run_page_converts_database_field_names() -> None:
def test_reconcile_issue_page_calculates_actions_from_camel_case_rows() -> None:
+ """核对问题分页根据驼峰字段推导可用操作。"""
current_user = SimpleNamespace(user=SimpleNamespace(admin=True, user_name='admin'))
current_time = datetime(2026, 7, 26, 12, 0, 0, tzinfo=UTC)
issue_page = PageModel(
@@ -283,6 +323,7 @@ def test_reconcile_issue_page_calculates_actions_from_camel_case_rows() -> None:
def test_reconcile_move_is_compensated_when_database_commit_fails(tmp_path: Path) -> None:
+ """提交失败时撤回核对过程中的文件移动。"""
roots = make_roots(tmp_path)
trash_key = f'{FILE_ID}/{STORED_NAME}'
source = write_file(roots['trash'], trash_key, b'content')
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reference.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reference.py
index 20b774a14..98237bb04 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reference.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reference.py
@@ -17,10 +17,16 @@
def make_query_db() -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
def test_get_file_reference_list_includes_legacy_reference() -> None:
+ """文件引用列表包含旧版引用。"""
file_info = {
'file_id': FILE_ID,
'business_type': 'notice',
@@ -49,6 +55,7 @@ def test_get_file_reference_list_includes_legacy_reference() -> None:
def test_get_file_reference_list_converts_orm_reference() -> None:
+ """文件引用列表转换 ORM 引用。"""
create_time = datetime(2026, 7, 26, 10, 0, 0, tzinfo=UTC)
file_info = {
'file_id': FILE_ID,
@@ -98,6 +105,7 @@ def test_get_file_reference_list_converts_orm_reference() -> None:
def test_replace_business_file_references_locks_files_without_committing() -> None:
+ """替换业务文件引用时锁定文件并保留事务控制权。"""
query_db = make_query_db()
file_infos = [SimpleNamespace(file_id=FILE_ID)]
with (
@@ -141,6 +149,7 @@ def test_replace_business_file_references_locks_files_without_committing() -> No
def test_replace_business_file_references_rejects_invalid_file() -> None:
+ """替换业务引用时拒绝无效文件。"""
query_db = make_query_db()
with (
patch.object(FileInfoDao, 'get_file_infos_by_ids_for_update', new=AsyncMock(return_value=[])),
@@ -167,6 +176,7 @@ def test_replace_business_file_references_rejects_invalid_file() -> None:
def test_remove_business_file_references_does_not_lock_files() -> None:
+ """移除业务文件引用无需锁定文件。"""
query_db = make_query_db()
with (
patch.object(
@@ -193,6 +203,7 @@ def test_remove_business_file_references_does_not_lock_files() -> None:
def test_replace_business_file_references_applies_retention_policy() -> None:
+ """替换业务文件引用时应用保留策略。"""
query_db = make_query_db()
create_time = datetime(2026, 7, 23, 10, 0, 0, tzinfo=UTC)
policy = FileRetentionPolicyModel(businessType='notice', retentionDays=30)
@@ -230,6 +241,7 @@ def test_replace_business_file_references_applies_retention_policy() -> None:
def test_replace_business_file_references_preserves_extended_expiration() -> None:
+ """替换业务文件引用时保留已延长的过期时间。"""
policy_expire_time = datetime(2026, 8, 22, 10, 0, 0, tzinfo=UTC)
extended_expire_time = datetime(2027, 7, 23, 10, 0, 0, tzinfo=UTC)
old_reference = SysFileReference(
@@ -254,6 +266,7 @@ def test_replace_business_file_references_preserves_extended_expiration() -> Non
def test_refresh_file_expire_times_uses_latest_reference_expiration() -> None:
+ """按最晚引用到期时间刷新文件的过期时间。"""
first_expire_time = datetime(2026, 8, 1, tzinfo=UTC)
last_expire_time = datetime(2026, 9, 1, tzinfo=UTC)
file_info = SimpleNamespace(
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_retention_policy.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_retention_policy.py
index 2f2347239..4b980511d 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_retention_policy.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_retention_policy.py
@@ -14,10 +14,16 @@
def make_query_db() -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
def test_get_file_retention_policy_list_maps_orm_field_names() -> None:
+ """文件保留策略列表映射 ORM 字段名。"""
query_db = make_query_db()
db_policy = SysFileRetentionPolicy(
business_type='notice',
@@ -38,6 +44,7 @@ def test_get_file_retention_policy_list_maps_orm_field_names() -> None:
def test_get_enabled_file_retention_policy_maps_orm_field_names() -> None:
+ """读取启用的文件保留策略时映射 ORM 字段名。"""
query_db = make_query_db()
db_policy = SysFileRetentionPolicy(
business_type='notice',
@@ -63,6 +70,7 @@ def test_get_enabled_file_retention_policy_maps_orm_field_names() -> None:
def test_add_file_retention_policy_commits_new_policy() -> None:
+ """新增文件保留策略后提交事务。"""
query_db = make_query_db()
policy = FileRetentionPolicyModel(
businessType='notice',
@@ -98,6 +106,7 @@ def test_add_file_retention_policy_commits_new_policy() -> None:
def test_add_file_retention_policy_rejects_duplicate_business_type() -> None:
+ """新增策略时拒绝重复的业务类型。"""
query_db = make_query_db()
policy = FileRetentionPolicyModel(businessType='notice', retentionDays=30)
with (
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_job_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_job_service.py
index 4c597cb5a..62c9d236d 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_job_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_job_service.py
@@ -19,6 +19,7 @@
async def test_job_mutations_only_request_targeted_sync_after_commit(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch, action: str, commit_fails: bool
) -> None:
+ """任务变更仅在提交后请求定向同步。"""
if action != 'add':
await runtime.save()
await SchedulerManager._sync_jobs_from_database()
@@ -28,6 +29,11 @@ async def test_job_mutations_only_request_targeted_sync_after_commit(
commit = db.commit
async def committing() -> None:
+ """
+ 在调度状态变更前验证提交顺序。
+
+ :raises RuntimeError: 模拟测试事务提交失败
+ """
assert runtime.scheduler.get_job('42') is original
events.append('commit')
if commit_fails:
@@ -35,6 +41,13 @@ async def committing() -> None:
await commit()
async def sync(job_ids: set[int], *, immediate: bool) -> dict:
+ """
+ 验证提交顺序后执行调度同步。
+
+ :param job_ids: 需要删除的定时任务ID
+ :param immediate: 是否立即触发操作
+ :return: 提交后的调度同步结果
+ """
assert immediate
assert events == ['commit']
events.append('sync')
@@ -81,6 +94,7 @@ async def sync(job_ids: set[int], *, immediate: bool) -> dict:
async def test_sync_failure_after_commit_reports_saved_and_keeps_retryable_state(
runtime: Runtime, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """提交后同步失败时报告已保存并保留重试状态。"""
await runtime.save()
monkeypatch.setattr(
SchedulerManager, 'request_scheduler_sync', AsyncMock(side_effect=RuntimeError('sync unavailable'))
@@ -99,6 +113,7 @@ async def test_sync_failure_after_commit_reports_saved_and_keeps_retryable_state
@pytest.mark.asyncio
async def test_disable_broken_target_remains_possible_but_enable_is_rejected(runtime: Runtime) -> None:
+ """允许停用损坏的任务目标并拒绝启用。"""
await runtime.save(job_info(invokeTarget='module_task.scheduler_test.missing'))
async with runtime.sessions() as db:
result = await JobService.edit_job_services(db, EditJobModel(jobId=42, status='1', type='status'))
@@ -111,11 +126,7 @@ async def test_disable_broken_target_remains_possible_but_enable_is_rejected(run
@pytest.mark.asyncio
async def test_add_job_rejects_plugin_invoke_target_from_system_job_form() -> None:
- """
- 校验系统定时任务入口不会放开到整个 plugins 包。
-
- :return: None
- """
+ """校验系统定时任务入口不会放开到整个 plugins 包。"""
job = JobModel(
jobName='plugin-core-task',
jobGroup='default',
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_plugin_routes.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_plugin_routes.py
index 4897366f8..3bae963ca 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_plugin_routes.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_plugin_routes.py
@@ -11,6 +11,15 @@
def _menu(menu_id: int, *, parent_id: int = 0, component: str = 'PluginFrame', menu_type: str = 'C') -> SysMenu:
+ """
+ 创建测试使用的 ``SysMenu`` 实例。
+
+ :param menu_id: 菜单ID
+ :param parent_id: 父菜单ID
+ :param component: 当前检查或渲染的组件
+ :param menu_type: 菜单类型(M目录 C菜单 F按钮)
+ :return: 测试使用的 ``SysMenu`` 实例
+ """
return SysMenu(
menu_id=menu_id,
parent_id=parent_id,
@@ -28,6 +37,13 @@ def _menu(menu_id: int, *, parent_id: int = 0, component: str = 'PluginFrame', m
def _plugin(plugin_id: str, **overrides: object) -> SysPlugin:
+ """
+ 根据指定的标识和覆盖项组装插件记录。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param overrides: 调用方按名称传入的附加选项
+ :return: ``SysPlugin`` 实例
+ """
values = {
'plugin_id': plugin_id,
'plugin_name': plugin_id,
@@ -42,6 +58,7 @@ def _plugin(plugin_id: str, **overrides: object) -> SysPlugin:
@pytest.mark.asyncio
async def test_plugin_metadata_uses_menu_ownership_for_nested_and_root_pages() -> None:
+ """嵌套页面及根页面均按菜单归属解析插件元数据。"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
try:
async with engine.begin() as connection:
@@ -85,6 +102,7 @@ async def test_plugin_metadata_uses_menu_ownership_for_nested_and_root_pages() -
@pytest.mark.asyncio
async def test_menu_ownership_rejects_inactive_uninstalled_and_ambiguous_plugins() -> None:
+ """菜单归属检查拒绝未启用、未安装或有歧义的插件。"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
try:
async with engine.begin() as connection:
@@ -127,6 +145,7 @@ async def test_menu_ownership_rejects_inactive_uninstalled_and_ambiguous_plugins
@pytest.mark.asyncio
async def test_ordinary_menus_do_not_query_plugin_tables() -> None:
+ """普通菜单不查询插件表。"""
query_db = AsyncMock()
assert await PluginRouterMetadataService.get_menu_plugin_ids(query_db, [_menu(1, component='system/user')]) == {}
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_service.py
index 7e64d84ad..85ab649d2 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_service.py
@@ -16,12 +16,19 @@
def _current_user(user_name: str = 'admin') -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param user_name: 当前用户的账号名称
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(user=SimpleNamespace(user_name=user_name))
@pytest.mark.asyncio
@pytest.mark.parametrize(('config_value', 'expected'), [(None, '0'), ('4', '4')])
async def test_get_sys_account_chrtype_uses_config_and_default(config_value: str | None, expected: str) -> None:
+ """密码字符类型取自配置并支持默认值。"""
redis = SimpleNamespace(get=AsyncMock(return_value=config_value))
request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis)))
@@ -32,6 +39,7 @@ async def test_get_sys_account_chrtype_uses_config_and_default(config_value: str
def test_current_user_model_exposes_password_character_type_alias() -> None:
+ """当前用户模型公开密码字符类型的别名。"""
current_user = CurrentUserModel(permissions=[], roles=[], user=None, pwdChrtype='3')
assert current_user.model_dump(by_alias=True)['pwdChrtype'] == '3'
@@ -39,6 +47,7 @@ def test_current_user_model_exposes_password_character_type_alias() -> None:
@pytest.mark.asyncio
async def test_get_current_user_rejects_malformed_user_id_claim() -> None:
+ """当前用户认证拒绝格式错误的用户标识声明。"""
token = jwt.encode(
{'user_id': 'invalid', 'session_id': 'session-id'},
JwtConfig.jwt_secret_key,
@@ -57,6 +66,7 @@ async def test_get_current_user_rejects_malformed_user_id_claim() -> None:
@pytest.mark.asyncio
async def test_unlock_screen_rejects_empty_password() -> None:
+ """解锁屏幕拒绝空密码。"""
with (
patch.object(UserDao, 'get_user_by_name', new_callable=AsyncMock) as get_user,
pytest.raises(ServiceException) as exc_info,
@@ -69,6 +79,7 @@ async def test_unlock_screen_rejects_empty_password() -> None:
@pytest.mark.asyncio
async def test_unlock_screen_rejects_missing_current_user() -> None:
+ """解锁屏幕时必须有当前用户。"""
with (
patch.object(UserDao, 'get_user_by_name', new=AsyncMock(return_value=None)) as get_user,
pytest.raises(ServiceException) as exc_info,
@@ -81,6 +92,7 @@ async def test_unlock_screen_rejects_missing_current_user() -> None:
@pytest.mark.asyncio
async def test_unlock_screen_rejects_wrong_password() -> None:
+ """解锁屏幕拒绝错误密码。"""
user = SimpleNamespace(password='hashed-password')
with (
patch.object(UserDao, 'get_user_by_name', new=AsyncMock(return_value=user)),
@@ -95,6 +107,7 @@ async def test_unlock_screen_rejects_wrong_password() -> None:
@pytest.mark.asyncio
async def test_unlock_screen_accepts_correct_password() -> None:
+ """正确密码可以解锁屏幕。"""
user = SimpleNamespace(password='hashed-password')
with (
patch.object(UserDao, 'get_user_by_name', new=AsyncMock(return_value=user)) as get_user,
@@ -110,6 +123,7 @@ async def test_unlock_screen_accepts_correct_password() -> None:
@pytest.mark.asyncio
async def test_register_uses_front_end_default_password_rule() -> None:
+ """注册使用前端默认的密码规则。"""
redis = SimpleNamespace(get=AsyncMock(side_effect=['true', 'false']))
request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis)))
user_register = UserRegister(
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_session_renewal.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_session_renewal.py
index d6b47b706..f1f00b352 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_session_renewal.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_session_renewal.py
@@ -19,9 +19,18 @@
class SessionRedis:
- """使用可控时间模拟登录会话和原子续期、退出命令。"""
+ """
+ 使用可控时间模拟登录会话和原子续期、退出命令。
+
+ :ivar now: 当前场景使用的基准时间
+ :ivar values: 当前处理的值集合
+ :ivar deadlines: 各操作的截止时间
+ :ivar renew_calls: 记录 ``renew`` 的调用情况
+ :ivar logout_calls: 记录 ``logout`` 的调用情况
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``now``, ``values``, ``deadlines``, ``renew_calls``。"""
self.now = 0
self.values: dict[str, str] = {}
self.deadlines: dict[str, int] = {}
@@ -29,22 +38,56 @@ def __init__(self) -> None:
self.logout_calls: list[tuple[str, str]] = []
def _read(self, key: str) -> str | None:
+ """
+ 返回仍在有效期内的缓存值。
+
+ :param key: 查找数据时使用的键
+ :return: 仍在有效期内的缓存值
+ """
if self.deadlines.get(key, float('inf')) <= self.now:
self.values.pop(key, None)
return self.values.get(key)
async def get(self, key: str) -> str | None:
+ """
+ 读取测试存储中的指定键。
+
+ :param key: 查找数据时使用的键
+ :return: 测试存储中的指定键
+ """
return self._read(key)
async def set(self, key: str, value: str, *, ex: int) -> None:
+ """
+ 写入测试缓存键并设置过期时间。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :param ex: 捕获到的异常实例
+ """
self.values[key] = value
self.deadlines[key] = self.now + ex
async def delete(self, key: str) -> None:
+ """
+ 删除测试缓存项及其过期状态。
+
+ :param key: 查找数据时使用的键
+ """
self.values.pop(key, None)
self.deadlines.pop(key, None)
async def eval(self, script: str, count: int, key: str, token: str, seconds: int | None = None) -> int:
+ """
+ 按测试约定模拟 Redis 脚本的执行。
+
+ :param script: 需要运行的脚本
+ :param count: 本次处理或预期的数量
+ :param key: 查找数据时使用的键
+ :param token: 用于身份验证或授权的令牌
+ :param seconds: 以秒计的时间值
+ :return: 对应 Redis 脚本分支的整数状态
+ """
assert count == 1
if script == _SESSION_LOGOUT_SCRIPT:
assert seconds is None
@@ -65,6 +108,12 @@ async def eval(self, script: str, count: int, key: str, token: str, seconds: int
@pytest.fixture
def session_case(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
+ """
+ 组合会话续期所需的请求、缓存和用户。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: ``SimpleNamespace`` 实例
+ """
redis = SessionRedis()
request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis)))
token = JwtUtil.encode(
@@ -84,6 +133,7 @@ def session_case(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
async def test_valid_session_renews_only_its_expiration(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
+ """有效会话仅更新自身的有效期。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
key = 'access_token:session-a' if same_time_login else 'access_token:7'
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
@@ -110,12 +160,19 @@ async def test_concurrent_session_change_cannot_be_overwritten_or_restored(
change: str,
for_plugin: bool,
) -> None:
+ """并发变更的会话不能被覆盖或恢复。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
key = 'access_token:session-a' if same_time_login else 'access_token:7'
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
loaded, resume = asyncio.Event(), asyncio.Event()
async def load_user(*args: object) -> CurrentUserModel:
+ """
+ 控制测试用户加载完成的时机。
+
+ :param args: 传给被调用对象的位置参数
+ :return: 当前操作对应的用户
+ """
loaded.set()
await resume.wait()
return session_case.user
@@ -153,6 +210,7 @@ async def load_user(*args: object) -> CurrentUserModel:
async def test_expired_session_does_not_load_user_or_renew(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """会话过期后不加载用户也不续期。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', True)
key = 'access_token:session-a'
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
@@ -170,6 +228,7 @@ async def test_expired_session_does_not_load_user_or_renew(
async def test_renewal_failure_does_not_authenticate_request(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """续期失败时拒绝认证请求。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', True)
key = 'access_token:session-a'
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
@@ -189,6 +248,7 @@ async def test_renewal_failure_does_not_authenticate_request(
async def test_committed_renewal_timeout_does_not_authenticate_request(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
+ """已提交的续期超时后拒绝认证请求。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
key = 'access_token:session-a' if same_time_login else 'access_token:7'
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
@@ -196,6 +256,16 @@ async def test_committed_renewal_timeout_does_not_authenticate_request(
original_eval = session_case.redis.eval
async def renew_then_timeout(script: str, count: int, cache_key: str, token: str, seconds: int) -> int:
+ """
+ 在续期写入后模拟 Redis 响应超时。
+
+ :param script: 需要运行的脚本
+ :param count: 本次处理或预期的数量
+ :param cache_key: 缓存键名
+ :param token: 用于身份验证或授权的令牌
+ :param seconds: 以秒计的时间值
+ :raises RedisTimeoutError: 模拟续期已提交但 Redis 响应超时
+ """
await original_eval(script, count, cache_key, token, seconds)
raise RedisTimeoutError('redis response timeout')
@@ -217,6 +287,7 @@ async def renew_then_timeout(script: str, count: int, cache_key: str, token: str
async def test_cancelled_committed_renewal_does_not_authenticate_request(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
+ """取消已提交的续期后拒绝认证请求。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
key = 'access_token:session-a' if same_time_login else 'access_token:7'
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
@@ -225,6 +296,16 @@ async def test_cancelled_committed_renewal_does_not_authenticate_request(
renewed, resume = asyncio.Event(), asyncio.Event()
async def renew_then_wait(script: str, count: int, cache_key: str, token: str, seconds: int) -> int:
+ """
+ 在续期成功后等待其他操作。
+
+ :param script: 需要运行的脚本
+ :param count: 本次处理或预期的数量
+ :param cache_key: 缓存键名
+ :param token: 用于身份验证或授权的令牌
+ :param seconds: 以秒计的时间值
+ :return: 执行当前操作得到的结果
+ """
result = await original_eval(script, count, cache_key, token, seconds)
renewed.set()
await resume.wait()
@@ -249,6 +330,7 @@ async def renew_then_wait(script: str, count: int, cache_key: str, token: str, s
async def test_concurrent_requests_can_renew_the_same_session(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """并发请求可续期同一会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', True)
key = 'access_token:session-a'
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
@@ -267,12 +349,19 @@ async def test_concurrent_requests_can_renew_the_same_session(
async def test_cancelled_request_does_not_renew_session(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """取消请求时不续期会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', True)
key = 'access_token:session-a'
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
loaded, resume = asyncio.Event(), asyncio.Event()
async def load_user(*args: object) -> CurrentUserModel:
+ """
+ 控制测试用户加载完成的时机。
+
+ :param args: 传给被调用对象的位置参数
+ :return: 当前操作对应的用户
+ """
loaded.set()
await resume.wait()
return session_case.user
@@ -294,6 +383,7 @@ async def load_user(*args: object) -> CurrentUserModel:
async def test_plugin_validation_never_renews_main_session(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
+ """插件校验不续期主会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
key = 'access_token:session-a' if same_time_login else 'access_token:7'
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
@@ -311,6 +401,7 @@ async def test_plugin_validation_never_renews_main_session(
async def test_plugin_final_session_check_failure_does_not_authenticate(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
+ """插件最终会话校验失败时拒绝认证。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
key = 'access_token:session-a' if same_time_login else 'access_token:7'
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
@@ -318,6 +409,13 @@ async def test_plugin_final_session_check_failure_does_not_authenticate(
session_reads = 0
async def read_session(cache_key: str) -> str | None:
+ """
+ 记录会话缓存的读取次数。
+
+ :param cache_key: 缓存键名
+ :raises RedisTimeoutError: 模拟读取会话时 Redis 超时
+ :return: 缓存中当前的会话记录
+ """
nonlocal session_reads
if cache_key == key:
session_reads += 1
@@ -345,6 +443,7 @@ async def read_session(cache_key: str) -> str | None:
async def test_cancelled_plugin_final_session_check_does_not_authenticate(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
+ """取消插件最终会话校验时拒绝认证。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
key = 'access_token:session-a' if same_time_login else 'access_token:7'
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
@@ -353,6 +452,12 @@ async def test_cancelled_plugin_final_session_check_does_not_authenticate(
session_reads = 0
async def read_session(cache_key: str) -> str | None:
+ """
+ 记录会话缓存的读取次数。
+
+ :param cache_key: 缓存键名
+ :return: 缓存中当前的会话记录
+ """
nonlocal session_reads
if cache_key == key:
session_reads += 1
@@ -385,6 +490,7 @@ async def read_session(cache_key: str) -> str | None:
async def test_logout_is_idempotent_and_only_removes_its_session(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
+ """重复注销只移除本次会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
token_id = 'session-a' if same_time_login else '7'
key = f'access_token:{token_id}'
@@ -416,6 +522,7 @@ async def test_logout_is_idempotent_and_only_removes_its_session(
async def test_logout_of_stale_token_keeps_current_session(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool, state: str
) -> None:
+ """旧令牌注销时保留当前会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
token_id = 'session-a' if same_time_login else '7'
key = f'access_token:{token_id}'
@@ -445,6 +552,7 @@ async def test_concurrent_new_login_survives_old_token_logout(
same_time_login: bool,
login_before_logout: bool,
) -> None:
+ """并发建立的新会话不受旧令牌注销影响。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
token_id = 'session-a' if same_time_login else '7'
key = f'access_token:{token_id}'
@@ -454,6 +562,15 @@ async def test_concurrent_new_login_survives_old_token_logout(
entered, resume = asyncio.Event(), asyncio.Event()
async def delayed_logout(script: str, count: int, cache_key: str, token: str) -> int:
+ """
+ 在退出登录的指定阶段等待并发操作。
+
+ :param script: 需要运行的脚本
+ :param count: 本次处理或预期的数量
+ :param cache_key: 缓存键名
+ :param token: 用于身份验证或授权的令牌
+ :return: 原注销服务的执行结果
+ """
result = None if login_before_logout else await original_eval(script, count, cache_key, token)
entered.set()
await resume.wait()
@@ -480,6 +597,7 @@ async def delayed_logout(script: str, count: int, cache_key: str, token: str) ->
async def test_logout_after_committed_renewal_does_not_restore_session(
session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
+ """续期提交后注销不会恢复会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
token_id = 'session-a' if same_time_login else '7'
key = f'access_token:{token_id}'
@@ -488,6 +606,16 @@ async def test_logout_after_committed_renewal_does_not_restore_session(
renewed, resume = asyncio.Event(), asyncio.Event()
async def delayed_renewal(script: str, count: int, cache_key: str, token: str, seconds: int | None = None) -> int:
+ """
+ 在会话续期期间暂停缓存操作。
+
+ :param script: 需要运行的脚本
+ :param count: 本次处理或预期的数量
+ :param cache_key: 缓存键名
+ :param token: 用于身份验证或授权的令牌
+ :param seconds: 以秒计的时间值
+ :return: 执行当前操作得到的结果
+ """
result = await original_eval(script, count, cache_key, token, seconds)
if script == _SESSION_RENEW_SCRIPT:
renewed.set()
@@ -520,6 +648,7 @@ async def test_failed_logout_and_retry_cannot_delete_new_login(
committed: bool,
failure: str,
) -> None:
+ """注销失败后的重试不能删除新登录会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
token_id = 'session-a' if same_time_login else '7'
key = f'access_token:{token_id}'
@@ -529,6 +658,15 @@ async def test_failed_logout_and_retry_cannot_delete_new_login(
entered, resume = asyncio.Event(), asyncio.Event()
async def failed_logout(script: str, count: int, cache_key: str, token: str) -> int:
+ """
+ 在指定注销阶段模拟缓存响应超时。
+
+ :param script: 需要运行的脚本
+ :param count: 本次处理或预期的数量
+ :param cache_key: 缓存键名
+ :param token: 用于身份验证或授权的令牌
+ :raises RedisTimeoutError: 模拟注销期间 Redis 响应超时
+ """
if committed:
await original_eval(script, count, cache_key, token)
entered.set()
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_menu_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_menu_service.py
index 0d6e1e062..d57b61bf9 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_menu_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_menu_service.py
@@ -22,6 +22,16 @@ def _menu(
route_name: str | None,
menu_name: str = '已有菜单',
) -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param menu_id: 菜单ID
+ :param parent_id: 父菜单ID
+ :param path: 要读取或处理的路径
+ :param route_name: 路由名称
+ :param menu_name: 菜单名称
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(
menu_id=menu_id,
parent_id=parent_id,
@@ -52,6 +62,7 @@ def _menu(
async def test_check_route_config_unique_rejects_route_conflicts(
page_object: MenuModel, existing_menu: SimpleNamespace
) -> None:
+ """路由配置唯一性检查拒绝冲突。"""
with patch.object(
MenuDao,
'get_menus_by_path_or_route_name',
@@ -64,6 +75,7 @@ async def test_check_route_config_unique_rejects_route_conflicts(
@pytest.mark.asyncio
async def test_check_route_config_unique_allows_same_path_under_different_parent_with_distinct_route_name() -> None:
+ """不同上级下的同路径可使用不同路由名。"""
page_object = MenuModel(menuId=2, parentId=2, path='system/user', routeName='SecondSystemUser')
existing_menu = _menu(menu_id=1, parent_id=1, path='system/user', route_name='FirstSystemUser')
with patch.object(
@@ -78,6 +90,7 @@ async def test_check_route_config_unique_allows_same_path_under_different_parent
@pytest.mark.asyncio
async def test_check_route_config_unique_ignores_current_menu() -> None:
+ """校验路由唯一性时排除当前菜单。"""
page_object = MenuModel(menuId=1, parentId=1, path='system/user', routeName='SystemUser')
current_menu = _menu(menu_id=1, parent_id=1, path='system/user', route_name='SystemUser')
with patch.object(
@@ -92,6 +105,7 @@ async def test_check_route_config_unique_ignores_current_menu() -> None:
@pytest.mark.asyncio
async def test_add_menu_rejects_duplicate_route_config() -> None:
+ """新增菜单拒绝重复路由配置。"""
page_object = MenuModel(menuName='用户管理', parentId=1, path='system/user', routeName='SystemUser', isFrame=1)
with (
patch.object(MenuService, 'check_menu_name_unique_services', new=AsyncMock(return_value=True)),
@@ -107,6 +121,7 @@ async def test_add_menu_rejects_duplicate_route_config() -> None:
@pytest.mark.asyncio
async def test_get_menus_by_path_or_route_name_is_case_insensitive_and_excludes_buttons() -> None:
+ """按路径或路由名查询时忽略大小写并排除按钮。"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
@@ -152,6 +167,7 @@ async def test_get_menus_by_path_or_route_name_is_case_insensitive_and_excludes_
def test_parse_menu_sort_items_preserves_corresponding_order_values() -> None:
+ """解析菜单排序时保留各菜单对应的顺序值。"""
result = MenuService.parse_menu_sort_items(MenuSortModel(menuIds='101, 102', orderNums='3, 1'))
assert result == [
@@ -171,6 +187,7 @@ def test_parse_menu_sort_items_preserves_corresponding_order_values() -> None:
],
)
def test_parse_menu_sort_items_rejects_invalid_parameters(menu_ids: str, order_nums: str) -> None:
+ """菜单排序拒绝无效参数。"""
with pytest.raises(ServiceException) as exc_info:
MenuService.parse_menu_sort_items(MenuSortModel(menuIds=menu_ids, orderNums=order_nums))
@@ -179,6 +196,7 @@ def test_parse_menu_sort_items_rejects_invalid_parameters(menu_ids: str, order_n
@pytest.mark.asyncio
async def test_update_menu_sort_updates_all_rows_in_one_transaction() -> None:
+ """在同一事务中更新全部菜单排序。"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
@@ -208,6 +226,7 @@ async def test_update_menu_sort_updates_all_rows_in_one_transaction() -> None:
@pytest.mark.asyncio
async def test_update_menu_sort_rolls_back_and_wraps_database_error() -> None:
+ """菜单排序遇到数据库错误时回滚并转换异常。"""
query_db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
with (
@@ -225,6 +244,11 @@ async def test_update_menu_sort_rolls_back_and_wraps_database_error() -> None:
async def _create_menu_tree() -> tuple[AsyncEngine, async_sessionmaker[AsyncSession]]:
+ """
+ 在独立数据库中准备菜单树数据。
+
+ :return: 依次为 ``engine``、``sessions`` 的元组
+ """
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
sessions = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
@@ -248,6 +272,7 @@ async def _create_menu_tree() -> tuple[AsyncEngine, async_sessionmaker[AsyncSess
@pytest.mark.asyncio
@pytest.mark.parametrize('parent_id', [501, 502, 503, 701, 800, 999])
async def test_edit_menu_rejects_invalid_parent_chains_without_writing(parent_id: int) -> None:
+ """编辑菜单时拒绝无效上级链且不写库。"""
engine, sessions = await _create_menu_tree()
try:
async with sessions() as session:
@@ -266,6 +291,7 @@ async def test_edit_menu_rejects_invalid_parent_chains_without_writing(parent_id
@pytest.mark.asyncio
@pytest.mark.parametrize('parent_id', [None, 0, 600])
async def test_edit_menu_preserves_root_or_moves_subtree_to_valid_parent(parent_id: int | None) -> None:
+ """编辑菜单时可保留根节点或移动子树至有效上级。"""
engine, sessions = await _create_menu_tree()
try:
async with sessions() as session:
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_html_security.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_html_security.py
index 9f8b4e339..1d603bfc2 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_html_security.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_html_security.py
@@ -13,6 +13,11 @@
def assert_safe(content: str) -> None:
+ """
+ 校验净化后的公告保留允许的内容和属性。
+
+ :param content: 需要读取或写入的内容
+ """
assert '重点 ' in content
assert 'src="/safe.png"' in content
assert 'onerror' not in content
@@ -21,9 +26,10 @@ def assert_safe(content: str) -> None:
def test_direct_api_input_is_cleaned_before_persistence() -> None:
+ """直接调用 API 写入前清理输入。"""
app = FastAPI()
- @app.post('/notice')
+ @app.post('/notice', summary='提交通知内容', description='返回通过模型校验的通知内容,用于验证写入前的 HTML 清理。')
def notice(payload: NoticeModel) -> NoticeModel:
assert_safe(payload.notice_content.decode())
return payload
@@ -34,6 +40,7 @@ def notice(payload: NoticeModel) -> NoticeModel:
@pytest.mark.asyncio
async def test_legacy_notice_detail_and_list_are_sanitized(monkeypatch: pytest.MonkeyPatch) -> None:
+ """清理旧公告详情和列表的内容。"""
monkeypatch.setattr(
NoticeDao,
'get_notice_detail_by_id',
@@ -54,6 +61,7 @@ async def test_legacy_notice_detail_and_list_are_sanitized(monkeypatch: pytest.M
@pytest.mark.parametrize('url', ['javascript:alert(1)', 'javascript:alert(1)', 'data:text/html,x', 'vbscript:x'])
def test_rejects_dangerous_urls_and_embedded_content(url: str) -> None:
+ """拒绝危险链接及嵌入内容。"""
result = NoticeModel(noticeContent=f'x ')
content = result.notice_content.decode()
assert 'href=' not in content
@@ -62,6 +70,7 @@ def test_rejects_dangerous_urls_and_embedded_content(url: str) -> None:
def test_legal_rich_text_and_partial_updates_are_preserved() -> None:
+ """保留合法富文本并支持部分更新。"""
content = '标题 '
result = NoticeModel(noticeContent=content).notice_content.decode()
assert '标题 ' in result and '正文 ' in result and 'colspan="2"' in result
@@ -69,6 +78,7 @@ def test_legal_rich_text_and_partial_updates_are_preserved() -> None:
def test_quill_text_styles_are_preserved_without_layout_styles() -> None:
+ """保留 Quill 文本样式并剔除布局样式。"""
content = NoticeModel(
noticeContent='正文
'
).notice_content.decode()
@@ -78,6 +88,7 @@ def test_quill_text_styles_are_preserved_without_layout_styles() -> None:
def test_quill_video_is_sandboxed_and_cannot_embed_inline_script() -> None:
+ """Quill 视频在沙箱中播放且不能嵌入内联脚本。"""
content = NoticeModel(
noticeContent=''
).notice_content.decode()
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_service.py
index 0edd7aab2..4c1beb40b 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_service.py
@@ -21,6 +21,11 @@
async def _create_notice_tables() -> tuple[AsyncEngine, async_sessionmaker[AsyncSession]]:
+ """
+ 为通知测试创建数据库表及会话。
+
+ :return: 依次为 ``engine``、``session_maker`` 的元组
+ """
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
@@ -50,6 +55,13 @@ async def _create_notice_tables() -> tuple[AsyncEngine, async_sessionmaker[Async
def _notice(notice_id: int, status: str = '0') -> SysNotice:
+ """
+ 创建测试使用的 ``SysNotice`` 实例。
+
+ :param notice_id: 公告ID
+ :param status: 操作或记录所处的状态
+ :return: 测试使用的 ``SysNotice`` 实例
+ """
return SysNotice(
notice_id=notice_id,
notice_title=f'公告{notice_id}',
@@ -63,6 +75,7 @@ def _notice(notice_id: int, status: str = '0') -> SysNotice:
@pytest.mark.asyncio
async def test_get_notice_top_returns_latest_normal_notices_with_read_status() -> None:
+ """置顶公告返回最新正常公告及阅读状态。"""
engine, session_maker = await _create_notice_tables()
try:
async with session_maker() as session:
@@ -83,6 +96,7 @@ async def test_get_notice_top_returns_latest_normal_notices_with_read_status() -
@pytest.mark.asyncio
async def test_mark_notice_read_is_idempotent_for_single_and_batch_requests() -> None:
+ """单个及批量标记已读均支持重复请求。"""
engine, session_maker = await _create_notice_tables()
try:
async with session_maker() as session:
@@ -101,6 +115,7 @@ async def test_mark_notice_read_is_idempotent_for_single_and_batch_requests() ->
@pytest.mark.asyncio
async def test_get_notice_read_user_list_supports_search_and_pagination() -> None:
+ """公告阅读用户列表支持搜索和分页。"""
engine, session_maker = await _create_notice_tables()
try:
async with session_maker() as session:
@@ -163,6 +178,7 @@ async def test_get_notice_read_user_list_supports_search_and_pagination() -> Non
@pytest.mark.asyncio
async def test_delete_notice_removes_read_records_in_same_transaction() -> None:
+ """删除公告时在同一事务清理阅读记录。"""
engine, session_maker = await _create_notice_tables()
try:
async with session_maker() as session:
@@ -182,6 +198,7 @@ async def test_delete_notice_removes_read_records_in_same_transaction() -> None:
def test_parse_notice_ids_deduplicates_values_and_rejects_invalid_input() -> None:
+ """解析公告标识时去重并拒绝无效输入。"""
assert NoticeService.parse_notice_ids('1, 2,1,,3') == [1, 2, 3]
with pytest.raises(ServiceException) as exc_info:
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_online_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_online_service.py
index 397f55c76..be3de7adb 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_online_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_online_service.py
@@ -10,6 +10,7 @@
@pytest.mark.asyncio
async def test_online_list_skips_tokens_that_cannot_be_decoded() -> None:
+ """在线列表跳过无法解码的令牌。"""
redis = SimpleNamespace(
keys=AsyncMock(return_value=['access_token:stale-session']),
get=AsyncMock(return_value='invalid-token'),
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_user_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_user_service.py
index adb6ff95b..81aa1c39f 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_user_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_user_service.py
@@ -58,6 +58,7 @@ async def test_edit_user_accepts_form_without_readonly_roles(
],
)
async def test_validate_password_accepts_each_character_type(pwd_chrtype: str, password: str) -> None:
+ """密码校验接受各类允许的字符。"""
redis = SimpleNamespace(get=AsyncMock(return_value=pwd_chrtype))
await UserService.validate_password_services(redis, password)
@@ -77,6 +78,7 @@ async def test_validate_password_accepts_each_character_type(pwd_chrtype: str, p
],
)
async def test_validate_password_rejects_invalid_character_type(pwd_chrtype: str, password: str, message: str) -> None:
+ """密码校验拒绝不允许的字符类型。"""
redis = SimpleNamespace(get=AsyncMock(return_value=pwd_chrtype))
with pytest.raises(ServiceException) as exc_info:
@@ -88,6 +90,7 @@ async def test_validate_password_rejects_invalid_character_type(pwd_chrtype: str
@pytest.mark.asyncio
@pytest.mark.parametrize('password', ['12345', '123456789012345678901'])
async def test_validate_password_rejects_invalid_length(password: str) -> None:
+ """密码校验拒绝无效长度。"""
redis = SimpleNamespace(get=AsyncMock(return_value='0'))
with pytest.raises(ServiceException) as exc_info:
@@ -98,6 +101,7 @@ async def test_validate_password_rejects_invalid_length(password: str) -> None:
@pytest.mark.asyncio
async def test_validate_password_uses_fixed_rule_without_reading_config() -> None:
+ """指定固定密码规则时无需读取配置。"""
redis = SimpleNamespace(get=AsyncMock(return_value='4'))
await UserService.validate_password_services(redis, 'abcdef', PasswordCharacterType.DEFAULT)
@@ -108,6 +112,7 @@ async def test_validate_password_uses_fixed_rule_without_reading_config() -> Non
@pytest.mark.asyncio
@pytest.mark.parametrize('config_value', [None, '', 'invalid'])
async def test_validate_password_falls_back_to_default_rule(config_value: str | None) -> None:
+ """密码校验支持回退到默认规则。"""
redis = SimpleNamespace(get=AsyncMock(return_value=config_value))
await UserService.validate_password_services(redis, 'abcdef')
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_user_timezone.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_user_timezone.py
index 86eab8f52..a74d30261 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_user_timezone.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_user_timezone.py
@@ -17,12 +17,14 @@
@pytest.mark.parametrize('value', ['auto', 'UTC', 'Asia/Shanghai', 'America/New_York', ' Asia/Kathmandu '])
def test_timezone_preference_validation(value: str) -> None:
+ """校验用户的时区偏好。"""
assert UserTimezoneModel(timeZone=value).time_zone == value.strip()
assert UserModel(timeZone=value).time_zone == value.strip()
@pytest.mark.parametrize('value', ['', None, 'Mars/Olympus', 'UTC+8', '../UTC', 'a' * 65])
def test_invalid_timezone_preference_rejected(value: object) -> None:
+ """拒绝无效的时区偏好。"""
with pytest.raises(ValidationError):
UserTimezoneModel(timeZone=value)
with pytest.raises(ValidationError):
@@ -30,6 +32,7 @@ def test_invalid_timezone_preference_rejected(value: object) -> None:
def test_timezone_endpoint_rejects_identity_and_management_fields() -> None:
+ """时区接口拒绝身份及管理字段。"""
with pytest.raises(ValidationError):
UserTimezoneModel(timeZone='UTC', userId=2)
with pytest.raises(ValidationError):
@@ -38,6 +41,7 @@ def test_timezone_endpoint_rejects_identity_and_management_fields() -> None:
@pytest.mark.asyncio
async def test_timezone_update_persists_only_current_account() -> None:
+ """更新时区只写入当前账号。"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
try:
async with engine.begin() as connection:
@@ -73,6 +77,7 @@ async def test_timezone_update_persists_only_current_account() -> None:
@pytest.mark.asyncio
async def test_timezone_update_rolls_back_on_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+ """时区更新失败时回滚。"""
db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
monkeypatch.setattr(UserDao, 'edit_user_dao', AsyncMock(side_effect=RuntimeError('database unavailable')))
with pytest.raises(RuntimeError):
diff --git a/ruoyi-fastapi-backend/tests/module_generator/dao/test_gen_dao.py b/ruoyi-fastapi-backend/tests/module_generator/dao/test_gen_dao.py
index 7b404012e..39838cbad 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/dao/test_gen_dao.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/dao/test_gen_dao.py
@@ -16,6 +16,7 @@
@pytest.mark.asyncio
async def test_get_gen_table_by_name_is_scoped_to_data_source() -> None:
+ """按名称获取生成表时限定数据源。"""
result = MagicMock()
result.scalars.return_value.first.return_value = None
db = MagicMock()
@@ -31,6 +32,7 @@ async def test_get_gen_table_by_name_is_scoped_to_data_source() -> None:
@pytest.mark.asyncio
async def test_get_gen_table_list_filters_source_when_requested() -> None:
+ """生成表列表可按指定数据源过滤。"""
query_object = GenTablePageQueryModel(dataSourceName='reporting')
with patch.object(PageUtil, 'paginate', new=AsyncMock(return_value=[])) as paginate:
@@ -42,6 +44,7 @@ async def test_get_gen_table_list_filters_source_when_requested() -> None:
@pytest.mark.asyncio
async def test_get_gen_db_table_list_does_not_bind_unreferenced_model_defaults() -> None:
+ """查询数据库表时跳过未引用的模型默认值。"""
query_object = GenTablePageQueryModel(formColNum=3)
with patch.object(PageUtil, 'paginate', new=AsyncMock(return_value=[])) as paginate:
@@ -54,6 +57,7 @@ async def test_get_gen_db_table_list_does_not_bind_unreferenced_model_defaults()
@pytest.mark.asyncio
async def test_get_gen_db_table_list_only_binds_active_sql_filters() -> None:
+ """查询数据库表时仅绑定启用的过滤条件。"""
query_object = GenTablePageQueryModel(
tableName='sys_user',
tableComment='用户',
@@ -79,6 +83,7 @@ async def test_get_gen_db_table_list_only_binds_active_sql_filters() -> None:
@pytest.mark.asyncio
async def test_get_gen_db_table_list_uses_target_source_config() -> None:
+ """数据库表列表使用目标数据源配置。"""
query_object = GenTablePageQueryModel()
with patch.object(PageUtil, 'paginate', new=AsyncMock(return_value=[])) as paginate:
@@ -96,6 +101,7 @@ async def test_get_gen_db_table_list_uses_target_source_config() -> None:
@pytest.mark.asyncio
async def test_edit_gen_table_keeps_alias_fields_while_excluding_audit_times() -> None:
+ """编辑生成表时保留别名字段并排除审计时间。"""
db = MagicMock()
db.execute = AsyncMock()
@@ -113,6 +119,7 @@ async def test_edit_gen_table_keeps_alias_fields_while_excluding_audit_times() -
@pytest.mark.asyncio
async def test_edit_gen_table_column_keeps_alias_fields_while_excluding_audit_times() -> None:
+ """编辑生成表列时保留别名字段并排除审计时间。"""
db = MagicMock()
db.execute = AsyncMock()
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_gen_service.py b/ruoyi-fastapi-backend/tests/module_generator/test_gen_service.py
index ea1c55ecc..456c11f7e 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_gen_service.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_gen_service.py
@@ -12,6 +12,7 @@
def test_get_data_source_list_services_returns_camel_case_response(monkeypatch: pytest.MonkeyPatch) -> None:
+ """数据源列表服务以驼峰字段返回。"""
settings = SimpleNamespace(
db_default_source='primary',
db_sources={
@@ -31,6 +32,7 @@ def test_get_data_source_list_services_returns_camel_case_response(monkeypatch:
@pytest.mark.asyncio
async def test_get_gen_db_table_list_by_name_services_transforms_rows(monkeypatch: pytest.MonkeyPatch) -> None:
+ """按名称查询数据库表的服务转换结果行。"""
engine = create_engine('sqlite:///:memory:')
with engine.connect() as connection:
rows = connection.execute(
@@ -39,6 +41,12 @@ async def test_get_gen_db_table_list_by_name_services_transforms_rows(monkeypatc
@asynccontextmanager
async def session(_source_name: str) -> AsyncGenerator[object, None]:
+ """
+ 为当前测试操作提供数据库会话。
+
+ :param _source_name: 数据源名称
+ :yield: 数据库会话
+ """
yield SimpleNamespace()
settings = SimpleNamespace(
@@ -61,6 +69,7 @@ async def session(_source_name: str) -> AsyncGenerator[object, None]:
@pytest.mark.asyncio
async def test_batch_gen_code_services_rejects_tables_from_other_sources() -> None:
+ """批量生成时拒绝其他数据源的表。"""
with (
patch(
'module_generator.service.gen_service.GenTableDao.get_gen_table_names',
@@ -81,6 +90,7 @@ async def test_batch_gen_code_services_rejects_tables_from_other_sources() -> No
@pytest.mark.asyncio
async def test_edit_gen_table_services_preserves_alias_fields_for_both_daos() -> None:
+ """编辑生成表时两个 DAO 均保留别名字段。"""
table_id = 7
column_id = 9
page_object = EditGenTableModel(
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_generated_i18n.py b/ruoyi-fastapi-backend/tests/module_generator/test_generated_i18n.py
index 979a129e6..36c762293 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_generated_i18n.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_generated_i18n.py
@@ -23,12 +23,24 @@
def render_info(table: GenTableModel) -> list[Any]:
+ """
+ 根据表定义生成模板预览内容。
+
+ :param table: 代码生成业务表模型
+ :return: 模板清单、对应的文件名及渲染上下文
+ """
context = TemplateUtils.prepare_context(table)
templates = TemplateUtils.get_template_list(table)
return [templates, [TemplateUtils.get_file_name(name, table) for name in templates], context, table]
def render_files(table: GenTableModel) -> tuple[list[Any], dict[str, str]]:
+ """
+ 使用测试上下文渲染代码生成文件。
+
+ :param table: 代码生成业务表模型
+ :return: 预览信息及渲染得到的文件
+ """
info = render_info(table)
env = TemplateInitializer.init_jinja2()
env.undefined = StrictUndefined
@@ -36,6 +48,13 @@ def render_files(table: GenTableModel) -> tuple[list[Any], dict[str, str]]:
def flatten(value: dict, prefix: str = '') -> dict:
+ """
+ 将嵌套翻译资源展开为键值映射。
+
+ :param value: 待处理的输入值
+ :param prefix: 路径或键的公共前缀
+ :return: 执行当前操作得到的结果
+ """
result = {}
for key, entry in value.items():
full = f'{prefix}.{key}' if prefix else key
@@ -51,6 +70,7 @@ def flatten(value: dict, prefix: str = '') -> dict:
def test_generated_sources_register_literal_module_keys_and_compile(
web_type: str, category: str, tmp_path: Path
) -> None:
+ """生成代码注册字面模块键并可编译。"""
table = make_table('mysql', category, web_type)
table.columns[1].is_required = '1'
table.columns[1].column_comment = '名称“业务”'
@@ -111,6 +131,7 @@ def test_generated_sources_register_literal_module_keys_and_compile(
def test_generator_uses_configured_locales_and_reports_unknown_translations() -> None:
+ """生成器采用配置的语言并报告未知译文。"""
table = make_table('mysql', 'crud', 'element-ui')
options = json.loads(table.options)
options.update(
@@ -135,6 +156,7 @@ def test_generator_uses_configured_locales_and_reports_unknown_translations() ->
def test_backend_only_generation_needs_no_frontend_checkout(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, explicit: bool
) -> None:
+ """仅生成后端代码无需前端工作目录。"""
monkeypatch.setattr(GenI18nUtil, 'PROJECT_ROOT', tmp_path)
table = make_table('mysql', 'crud', 'element-plus')
if explicit:
@@ -150,6 +172,7 @@ def test_backend_only_generation_needs_no_frontend_checkout(
def test_explicit_languages_do_not_require_reading_target_metadata(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """显式指定语言后无需读取目标元数据。"""
monkeypatch.setattr(GenI18nUtil, 'PROJECT_ROOT', tmp_path)
meta = tmp_path / 'ruoyi-fastapi-frontend/vue3/web/src/i18n/locale-meta.json'
meta.parent.mkdir(parents=True)
@@ -165,6 +188,7 @@ def test_explicit_languages_do_not_require_reading_target_metadata(
@pytest.mark.asyncio
@pytest.mark.parametrize('locale', ['zh-CN', 'en-US'])
async def test_generation_failure_keeps_internal_paths_out_of_messages(locale: str) -> None:
+ """生成失败的消息不泄露内部路径。"""
table = make_table('mysql', 'crud', 'element-ui')
secret = 'C:/private/application/secrets.py'
with (
@@ -195,6 +219,7 @@ async def test_generation_failure_keeps_internal_paths_out_of_messages(locale: s
],
)
def test_generator_rejects_conflicting_sources_and_invalid_locale_options(options: dict[str, Any]) -> None:
+ """生成器拒绝冲突的数据源和无效语言选项。"""
table = make_table('mysql', 'crud', 'element-ui')
table.options = json.dumps({**json.loads(table.options), **options})
with pytest.raises(ServiceWarning):
@@ -202,6 +227,7 @@ def test_generator_rejects_conflicting_sources_and_invalid_locale_options(option
def test_generator_parameter_model_keeps_explicit_language_options() -> None:
+ """生成参数模型保留显式语言选项。"""
value = GenTableParamsModel(
i18nSourceLocale='zh-CN', i18nLocales=['en-US', 'fr-FR'], i18nTranslations={'fr-FR': {'title': 'Titre'}}
).model_dump(by_alias=True, exclude_unset=True)
@@ -211,6 +237,7 @@ def test_generator_parameter_model_keeps_explicit_language_options() -> None:
def test_field_keys_are_stable_when_comments_change() -> None:
+ """修改注释后字段键保持稳定。"""
table = make_table('mysql', 'crud', 'element-ui')
first, first_files = render_files(table)
table.function_name = '另一个显示名称'
@@ -223,6 +250,7 @@ def test_field_keys_are_stable_when_comments_change() -> None:
@pytest.mark.asyncio
async def test_preview_zip_and_disk_include_resources_without_overwriting_translations(tmp_path: Path) -> None:
+ """预览、压缩包及磁盘输出均含资源且保留已有译文。"""
table = make_table('mysql', 'crud', 'element-ui')
table.gen_path = str(tmp_path)
info = render_info(table)
@@ -297,6 +325,7 @@ async def test_preview_zip_and_disk_include_resources_without_overwriting_transl
async def test_invalid_existing_catalog_stops_before_overwriting_generated_source(
tmp_path: Path, relative_path: str, invalid: str
) -> None:
+ """已有翻译目录无效时停止覆盖生成的源码。"""
table = make_table('mysql', 'crud', 'element-ui')
table.gen_path = str(tmp_path)
source = tmp_path / 'frontend/src/views/test/item/index.vue'
@@ -318,6 +347,7 @@ async def test_invalid_existing_catalog_stops_before_overwriting_generated_sourc
def test_invalid_po_is_rejected_and_unreviewed_translations_stay_pending() -> None:
+ """拒绝无效 PO 文件并将未审核译文保留为待审。"""
path = 'backend/i18n/catalogs/en-US/LC_MESSAGES/core/generated.test.item.po'
table = make_table('mysql', 'crud', 'element-ui')
info, files = render_files(table)
@@ -338,6 +368,7 @@ def test_invalid_po_is_rejected_and_unreviewed_translations_stay_pending() -> No
@pytest.mark.asyncio
async def test_batch_generation_writes_one_backend_catalog_per_business_module() -> None:
+ """批量生成对每个业务模块只写一份后端翻译目录。"""
first = make_table('mysql', 'crud', 'element-ui')
second = first.model_copy(deep=True)
second.table_name = 'second_table'
@@ -368,6 +399,7 @@ async def test_batch_generation_writes_one_backend_catalog_per_business_module()
def test_generated_output_does_not_write_directly_into_an_existing_application() -> None:
+ """生成文件不会直接写入已有应用。"""
table = make_table('mysql', 'crud', 'element-ui')
table.gen_path = str(GenI18nUtil.PROJECT_ROOT / 'ruoyi-fastapi-frontend/vue2/web/src')
with pytest.raises(ServiceWarning) as caught:
@@ -379,6 +411,7 @@ def test_generated_output_does_not_write_directly_into_an_existing_application()
def test_pinned_x18n_rejects_pending_translations_and_accepts_reviewed_generated_keys(
web_type: str, tmp_path: Path
) -> None:
+ """锁定版本的 x18n 拒绝待审译文并接受已审核的生成键。"""
table = make_table('mysql', 'crud', web_type)
info, files = render_files(table)
app = info[2]['generatedI18n'].app_root
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py b/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
index 88c3f3c39..f98e36f6a 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
@@ -1,5 +1,7 @@
+import ast
import importlib.util
import json
+import subprocess
import sys
from datetime import UTC, date, time
from pathlib import Path
@@ -15,6 +17,7 @@
from config.env import AppConfig
from exceptions.exception import ServiceWarning
from module_generator.entity.vo.gen_vo import GenTableColumnModel, GenTableModel
+from scripts.check_docstrings import BACKEND, sphinx_settings, violations
from utils import common_util
from utils.template_util import TemplateInitializer, TemplateUtils
@@ -22,6 +25,16 @@
def column(
name: str, sql_type: str, python_type: str, *, pk: bool = False, query_type: str = 'EQ'
) -> GenTableColumnModel:
+ """
+ 创建测试使用的 ``GenTableColumnModel`` 实例。
+
+ :param name: 用于查找或标识当前对象的名称
+ :param sql_type: 建表时使用的 SQL 列类型
+ :param python_type: PYTHON类型
+ :param pk: 该列是否为主键
+ :param query_type: 查询方式(等于、不等于、大于、小于、范围)
+ :return: 测试使用的 ``GenTableColumnModel`` 实例
+ """
return GenTableColumnModel(
columnName=name,
columnComment=name,
@@ -39,6 +52,14 @@ def column(
def make_table(db_type: str, category: str, web_type: str) -> GenTableModel:
+ """
+ 根据数据库类型及模板类别构造代码生成样表。
+
+ :param db_type: 数据库类型
+ :param category: 测试的模板或记录类别
+ :param web_type: 渲染模板的前端类型
+ :return: 供调用方使用的 ``table``
+ """
instant = 'timestamp(3)' if db_type == 'mysql' else 'timestamp(3) with time zone'
columns = [
column('item_id', 'bigint', 'int', pk=True),
@@ -97,9 +118,22 @@ def make_table(db_type: str, category: str, web_type: str) -> GenTableModel:
return table
-def render_case(db_type: str, category: str, web_type: str) -> dict[str, str]:
+def render_case(db_type: str, category: str, web_type: str, *, field_constraints: bool = False) -> dict[str, str]:
+ """
+ 使用样表实际渲染所选模板。
+
+ :param db_type: 数据库类型
+ :param category: 测试的模板或记录类别
+ :param web_type: 渲染模板的前端类型
+ :param field_constraints: 是否生成必填字段校验方法和唯一性检查
+ :return: 按模板名索引的生成代码
+ """
with patch.object(type(database.DataBaseConfig), 'get_source', return_value=SimpleNamespace(db_type=db_type)):
table = make_table(db_type, category, web_type)
+ if field_constraints:
+ table.columns[1].unique = table.columns[1].required = True
+ if table.sub_table:
+ table.sub_table.columns[1].required = True
context = TemplateUtils.prepare_context(table)
environment = TemplateInitializer.init_jinja2()
return {
@@ -107,11 +141,36 @@ def render_case(db_type: str, category: str, web_type: str) -> dict[str, str]:
}
+def test_generated_python_docstrings(tmp_path: Path) -> None:
+ """检查各类生成模板及插件脚手架输出的中文接口说明和多行摘要布局。"""
+ sources = {
+ f'{category}_{Path(name).stem}': source
+ for category in ('crud', 'tree', 'sub')
+ for name, source in render_case('mysql', category, 'element-plus', field_constraints=True).items()
+ if name.endswith('.py.jinja2')
+ }
+ assert ':raises ServiceException:' in sources['crud_service.py']
+ assert '校验子表的必填字段' in sources['sub_vo.py']
+ assets = BACKEND / 'cli/runtime/plugin/scaffold/assets'
+ for path in assets.rglob('*.py.tmpl'):
+ sources[f'{path.parent.name}_{path.stem}'] = path.read_text(encoding='utf-8')
+ with sphinx_settings() as settings:
+ for name, source in sources.items():
+ target = tmp_path / name
+ target.write_text(source, encoding='utf-8')
+ assert not list(violations(ast.parse(source), settings, target)), name
+ subprocess.run(
+ [sys.executable, '-m', 'ruff', 'check', '--no-cache', '--select', 'D213', str(tmp_path)],
+ check=True,
+ )
+
+
@pytest.mark.parametrize('category', ['crud', 'tree', 'sub'])
@pytest.mark.parametrize('web_type', ['element-ui', 'element-plus'])
def test_generated_frontend_contains_business_files_and_reuses_project_time_modules(
category: str, web_type: str
) -> None:
+ """生成的前端包含业务文件并复用项目时间模块。"""
table = make_table('mysql', category, web_type)
rendered = render_case('mysql', category, web_type)
files = {TemplateUtils.get_file_name(name, table): content for name, content in rendered.items()}
@@ -131,8 +190,17 @@ def test_generated_frontend_contains_business_files_and_reuses_project_time_modu
def import_generated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, rendered: dict[str, str]) -> tuple:
+ """
+ 加载已渲染的 Python 模块以测试生成代码。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :param rendered: 已渲染的模板内容
+ :return: 已渲染的 Python 模块以测试生成代码
+ """
+
class TestBase(DeclarativeBase):
- pass
+ """为生成模块提供独立的 ORM 模型基类。"""
monkeypatch.setattr(database, 'Base', TestBase)
monkeypatch.setattr(common_util, 'Base', TestBase)
@@ -159,12 +227,40 @@ class TestBase(DeclarativeBase):
return TestBase, *modules
+def test_generated_models_publish_column_metadata(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证主表和子表的列说明能传递到数据库元数据与接口模式。"""
+ table = make_table('mysql', 'sub', 'element-plus')
+ table.pk_column.column_comment = None
+ label = """客户的 "VIP" 生日和 O'Brien 备注"""
+ table.columns[2].column_comment = label
+ table.sub_table.columns[2].column_comment = ' '
+ with patch.object(type(database.DataBaseConfig), 'get_source', return_value=SimpleNamespace(db_type='mysql')):
+ context = TemplateUtils.prepare_context(table)
+ environment = TemplateInitializer.init_jinja2()
+ rendered = {
+ name: environment.get_template(name).render(**context)
+ for name in ('python/do.py.jinja2', 'python/vo.py.jinja2', 'python/dao.py.jinja2')
+ }
+ _, orm, vo, _ = import_generated(tmp_path, monkeypatch, rendered)
+ for mapped, model, name, expected in [
+ (orm.TimeItem, vo.ItemModel, 'item_id', '字段 item_id'),
+ (orm.TimeItem, vo.ItemModel, 'birthday', label),
+ (orm.TimeDetail, vo.DetailModel, 'birthday', '字段 birthday'),
+ ]:
+ assert mapped.__table__.c[name].comment == expected
+ assert model.model_fields[name].description == expected
+ assert vo.ItemQueryModel.model_fields['begin_birthday'].description == f'开始{label}'
+ assert vo.DetailModel.model_json_schema()['properties']['birthday']['description'] == '字段 birthday'
+ assert table.sub_table.columns[2].column_comment == ' '
+
+
@pytest.mark.parametrize('db_type', ['mysql', 'postgresql'])
@pytest.mark.parametrize('category', ['crud', 'tree', 'sub'])
@pytest.mark.asyncio
async def test_generated_import_crud_and_query(
db_type: str, category: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """验证生成模块的导入、增删改查和查询。"""
base, _do, vo, dao = import_generated(tmp_path, monkeypatch, render_case(db_type, category, 'element-plus'))
monkeypatch.setattr(AppConfig, 'app_timezone', 'America/New_York')
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
@@ -227,6 +323,7 @@ async def test_generated_import_crud_and_query(
@pytest.mark.parametrize('column_type', ['timestamp(3) without time zone', 'timestamp', 'TIMESTAMP(6)'])
def test_rejects_postgres_ambiguous_timestamp(column_type: str) -> None:
+ """拒绝 PostgreSQL 有歧义的时间戳。"""
table = make_table('postgresql', 'crud', 'element-plus')
table.columns[4].column_type = column_type
with patch.object(type(database.DataBaseConfig), 'get_source', return_value=SimpleNamespace(db_type='postgresql')):
@@ -236,6 +333,7 @@ def test_rejects_postgres_ambiguous_timestamp(column_type: str) -> None:
def test_mysql_time_requires_explicit_time_of_day_control() -> None:
+ """MySQL 时间字段需要明确的时刻控件。"""
table = make_table('mysql', 'crud', 'element-plus')
table.columns[3].html_type = 'datetime'
with patch.object(type(database.DataBaseConfig), 'get_source', return_value=SimpleNamespace(db_type='mysql')):
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_react_templates.py b/ruoyi-fastapi-backend/tests/module_generator/test_react_templates.py
index 25ad4bac1..785130829 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_react_templates.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_react_templates.py
@@ -1,5 +1,3 @@
-"""React templates preserve the generator's CRUD, tree, child-table and time contracts."""
-
import json
import subprocess
from pathlib import Path
@@ -16,6 +14,7 @@
@pytest.mark.parametrize('db_type', ['mysql', 'postgresql'])
@pytest.mark.parametrize('category', ['crud', 'tree', 'sub'])
def test_react_templates_render_all_business_files(db_type: str, category: str) -> None:
+ """React 模板渲染全部业务文件。"""
table = make_table(db_type, category, 'react-antd')
rendered = render_case(db_type, category, 'react-antd')
files = {TemplateUtils.get_file_name(name, table): text for name, text in rendered.items()}
@@ -47,6 +46,7 @@ def test_react_templates_render_all_business_files(db_type: str, category: str)
@pytest.mark.parametrize('category', ['crud', 'tree', 'sub'])
def test_react_templates_do_not_depend_on_missing_context(category: str) -> None:
+ """React 模板无需缺失的上下文项。"""
table = make_table('mysql', category, 'react-antd')
context = TemplateUtils.prepare_context(table)
environment = TemplateInitializer.init_jinja2()
@@ -58,6 +58,7 @@ def test_react_templates_do_not_depend_on_missing_context(category: str) -> None
@pytest.mark.parametrize('category', ['crud', 'tree', 'sub'])
def test_react_preview_preserves_unicode_and_safe_string_literals(category: str, tmp_path: Path) -> None:
+ """React 预览保留 Unicode 并安全生成字符串字面量。"""
table = make_table('mysql', category, 'react-antd')
label = '中文名称「测试」😀 "引号" \\路径 <标签> & 单引号\''
table.columns[1].column_comment = label
diff --git a/ruoyi-fastapi-backend/tests/module_identity/architecture/test_architecture_boundaries.py b/ruoyi-fastapi-backend/tests/module_identity/architecture/test_architecture_boundaries.py
index 066254220..524738063 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/architecture/test_architecture_boundaries.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/architecture/test_architecture_boundaries.py
@@ -9,17 +9,32 @@
def _python_files(directory: str) -> list[Path]:
- """返回指定认证模块目录下的生产 Python 文件。"""
+ """
+ 返回指定认证模块目录下的生产 Python 文件。
+
+ :param directory: 要查找或写入文件的目录
+ :return: 指定认证模块目录下的生产 Python 文件
+ """
return sorted((_IDENTITY_ROOT / directory).glob('*.py'))
def _parse(path: Path) -> ast.Module:
- """将生产文件解析为抽象语法树。"""
+ """
+ 将生产文件解析为抽象语法树。
+
+ :param path: 要读取或处理的路径
+ :return: 被检查模块的抽象语法树
+ """
return ast.parse(path.read_text(encoding='utf-8'), filename=str(path))
def _imported_modules(tree: ast.Module) -> set[str]:
- """收集语法树中的完整导入模块路径。"""
+ """
+ 收集语法树中的完整导入模块路径。
+
+ :param tree: 待校验源码的抽象语法树
+ :return: 语法树中的完整导入模块路径
+ """
modules: set[str] = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
@@ -95,7 +110,12 @@ def test_controller_dependencies_use_annotated_style() -> None:
def _route_decorators(node: ast.FunctionDef | ast.AsyncFunctionDef) -> list[ast.Call]:
- """返回函数上的 HTTP 路由装饰器。"""
+ """
+ 返回函数上的 HTTP 路由装饰器。
+
+ :param node: 当前检查的语法或结构节点
+ :return: 函数上的 HTTP 路由装饰器
+ """
return [
decorator
for decorator in node.decorator_list
@@ -106,7 +126,12 @@ def _route_decorators(node: ast.FunctionDef | ast.AsyncFunctionDef) -> list[ast.
def _doc_param_names(docstring: str) -> set[str]:
- """提取 Sphinx 文档字符串中的参数名称。"""
+ """
+ 提取 Sphinx 文档字符串中的参数名称。
+
+ :param docstring: 要检查的文档字符串
+ :return: Sphinx 文档字符串中的参数名称
+ """
return {
line.removeprefix(':param ').split(':', 1)[0].strip()
for line in docstring.splitlines()
@@ -115,7 +140,13 @@ def _doc_param_names(docstring: str) -> set[str]:
def _block_docstring(path: Path, node: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:
- """检查函数文档字符串是否采用项目统一的独占行格式。"""
+ """
+ 检查函数文档字符串是否采用项目统一的独占行格式。
+
+ :param path: 要读取或处理的路径
+ :param node: 当前检查的语法或结构节点
+ :return: 是否函数文档字符串是否采用项目统一的独占行格式
+ """
if not node.body or not isinstance(node.body[0], ast.Expr):
return False
expression = node.body[0].value
@@ -136,7 +167,14 @@ def _internal_doc_violations(
node: ast.FunctionDef | ast.AsyncFunctionDef,
first_route_lineno: int | None,
) -> list[str]:
- """返回内部函数的顺序和文档违规信息。"""
+ """
+ 返回内部函数的顺序和文档违规信息。
+
+ :param path: 要读取或处理的路径
+ :param node: 当前检查的语法或结构节点
+ :param first_route_lineno: 第一个路由声明在源码中的行号
+ :return: 内部函数的顺序和文档违规信息
+ """
violations: list[str] = []
docstring = ast.get_docstring(node)
if node.col_offset != 0:
@@ -167,7 +205,14 @@ def _route_doc_violations(
node: ast.FunctionDef | ast.AsyncFunctionDef,
route_decorators: list[ast.Call],
) -> list[str]:
- """返回路由函数文档和 OpenAPI 文案违规信息。"""
+ """
+ 返回路由函数文档和 OpenAPI 文案违规信息。
+
+ :param path: 要读取或处理的路径
+ :param node: 当前检查的语法或结构节点
+ :param route_decorators: 当前端点的路由装饰器
+ :return: 路由函数文档和 OpenAPI 文案违规信息
+ """
violations: list[str] = []
if ast.get_docstring(node) is not None:
violations.append(f'{path.name}:{node.lineno}: 路由函数不得使用 docstring')
diff --git a/ruoyi-fastapi-backend/tests/module_identity/conftest.py b/ruoyi-fastapi-backend/tests/module_identity/conftest.py
index 365de8b36..76f73928d 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/conftest.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/conftest.py
@@ -42,13 +42,24 @@
@compiles(TINYINT, 'sqlite')
def _compile_mysql_tinyint_for_sqlite(_type: TINYINT, _compiler: object, **_kwargs: object) -> str:
- """让现有 MySQL 布尔列可在认证模块的 SQLite 测试库中建表。"""
+ """
+ 让现有 MySQL 布尔列可在认证模块的 SQLite 测试库中建表。
+
+ :param _type: 传递给编译器的类型对象
+ :param _compiler: 编译数据库表达式的对象
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 此分支的固定值 ``'SMALLINT'``
+ """
return 'SMALLINT'
@pytest_asyncio.fixture
async def data_session() -> AsyncSession:
- """创建只包含认证模块表的独立内存 SQLite 异步会话。"""
+ """
+ 创建只包含认证模块表的独立内存 SQLite 异步会话。
+
+ :yield: 只包含认证模块表的独立内存 SQLite 异步会话
+ """
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
identity_tables = [
table
@@ -69,7 +80,12 @@ async def data_session() -> AsyncSession:
def interaction_page_metadata(
monkeypatch: pytest.MonkeyPatch,
) -> tuple[SysOAuthClient, list[SysOAuthScope]]:
- """提供当前已登记的页面元数据,管理备注必须保持私有。"""
+ """
+ 提供当前已登记的页面元数据,管理备注必须保持私有。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: 依次为 ``client``、``scopes`` 的元组
+ """
client = SysOAuthClient(
client_pk=1001,
client_id='portal-client',
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/conftest.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/conftest.py
index 6b14ab389..b312423fa 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/conftest.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/conftest.py
@@ -14,14 +14,26 @@
@pytest.fixture
def oauth_management_client(monkeypatch: pytest.MonkeyPatch) -> Callable[[APIRouter, object, object], AsyncClient]:
- """构造使用真实路由和全局异常处理器的管理端 HTTP 客户端。"""
+ """
+ 构造使用真实路由和全局异常处理器的管理端 HTTP 客户端。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: 使用真实路由和全局异常处理器的管理端 HTTP 客户端
+ """
monkeypatch.setattr(Log, '_get_oper_location', AsyncMock(return_value='测试'))
monkeypatch.setattr(
ApiRateLimit, '_acquire_rate_limit', AsyncMock(return_value={'allowed': True, 'remaining': 1, 'reset_at': 0})
)
def create_client(router: APIRouter, session: object, current_user: object) -> AsyncClient:
- """替换数据库和认证依赖,保留控制器、装饰器及异常响应链。"""
+ """
+ 替换数据库和认证依赖,保留控制器、装饰器及异常响应链。
+
+ :param router: 注册端点所用的路由器
+ :param session: 当前操作共用的会话
+ :param current_user: 当前登录用户及其权限信息
+ :return: ``AsyncClient`` 实例
+ """
app = FastAPI()
app.state.redis = SimpleNamespace()
app.state.oidc_registered_cors_origins = ('https://old.example',)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_authorization_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_authorization_controller.py
index 896fed4fe..8baa83141 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_authorization_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_authorization_controller.py
@@ -30,19 +30,48 @@
class _QueryParams:
- """提供 Starlette QueryParams 所需的多值读取接口。"""
+ """
+ 提供 Starlette QueryParams 所需的多值读取接口。
+
+ :ivar values: 当前处理的值集合
+ """
def __init__(self, values: list[tuple[str, str]]) -> None:
+ """
+ 初始化测试夹具的 ``values``。
+
+ :param values: 当前处理的值集合
+ """
self.values = values
def multi_items(self) -> list[tuple[str, str]]:
+ """
+ 向调用方返回 ``self.values``。
+
+ :return: 测试缓存当前保存的值
+ """
return self.values
class _Request:
- """构造不携带 Legacy 会话的认证请求。"""
+ """
+ 构造不携带 Legacy 会话的认证请求。
+
+ :ivar method: 当前请求的 HTTP 方法
+ :ivar query_params: 模拟 HTTP 请求中的查询参数
+ :ivar cookies: 模拟请求或响应携带的 Cookie
+ :ivar headers: 响应或请求携带的 HTTP 头
+ :ivar client: 发起当前调用的客户端
+ :ivar app: 正在配置或处理请求的 ASGI 应用
+ """
def __init__(self, values: list[tuple[str, str]], redis: FakeRedis | None = None) -> None:
+ """
+ 初始化测试夹具的 ``method``, ``query_params``, ``cookies``, ``headers``。
+
+ :param values: 当前处理的值集合
+ :param redis: 用于缓存或发布消息的 Redis 客户端
+ """
self.method = 'GET'
self.query_params = _QueryParams(values)
self.cookies: dict[str, str] = {}
@@ -55,6 +84,14 @@ class _RateRedis(FakeRedis):
"""仅实现授权端点固定窗口 Lua 等效语义的 FakeRedis。"""
async def eval(self, script: str, numkeys: int, *args: Any) -> Any:
+ """
+ 按测试约定模拟 Redis 脚本的执行。
+
+ :param script: 需要运行的脚本
+ :param numkeys: 传给 Redis 脚本的键数量
+ :param args: 传给被调用对象的位置参数
+ :return: 测试脚本按当前状态返回的结果
+ """
if script != infrastructure_service.OidcRateLimiter._SCRIPT:
return await super().eval(script, numkeys, *args)
async with self.lock:
@@ -66,7 +103,12 @@ async def eval(self, script: str, numkeys: int, *args: Any) -> Any:
def _values(**overrides: str) -> list[tuple[str, str]]:
- """构造有效授权 Query 参数。"""
+ """
+ 构造有效授权 Query 参数。
+
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 有效授权 Query 参数
+ """
values = {
'response_type': 'code',
'client_id': 'authorization-client',
@@ -83,7 +125,11 @@ def _values(**overrides: str) -> list[tuple[str, str]]:
@pytest.fixture
def oidc_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
- """配置控制器测试使用的安全 OIDC 参数。"""
+ """
+ 配置控制器测试使用的安全 OIDC 参数。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
monkeypatch.setattr(OidcConfig, 'oidc_enabled', True)
monkeypatch.setattr(OidcConfig, 'oidc_issuer', 'https://auth.example.com')
monkeypatch.setattr(OidcConfig, 'oidc_pkce_methods', 'S256')
@@ -139,6 +185,13 @@ async def test_authorize_max_age_discards_stale_sso(monkeypatch: pytest.MonkeyPa
)
async def load_stale(*args: object, **kwargs: object) -> Any:
+ """
+ 向调用方返回 ``stale``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 已经过期的快照
+ """
return stale
monkeypatch.setattr(AuthorizationService, '_load_sso_session', load_stale)
@@ -255,24 +308,42 @@ async def test_complete_code_audit_failure_cleans_code_and_marker(monkeypatch: p
class _Db:
- """记录授权完成测试的事务动作。"""
+ """
+ 记录授权完成测试的事务动作。
+
+ :ivar commits: 测试中记录的提交次数
+ :ivar rollbacks: 测试中记录的回滚次数
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``commits``, ``rollbacks``。"""
self.commits = 0
self.rollbacks = 0
async def commit(self) -> None:
+ """累加 ``commits`` 供后续断言检查。"""
self.commits += 1
async def rollback(self) -> None:
+ """累加 ``rollbacks`` 供后续断言检查。"""
self.rollbacks += 1
async def _async(value: object) -> Any:
- """构造异步测试结果。"""
+ """
+ 构造异步测试结果。
+
+ :param value: 待处理的输入值
+ :return: 待处理的输入值
+ """
return value
async def _raise_async(error: Exception) -> Any:
- """构造异步异常结果。"""
+ """
+ 构造异步异常结果。
+
+ :param error: 发生错误时返回的错误信息
+ :raises Exception: 底层操作失败时向调用方传播异常
+ """
raise error
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_client_ip_resolution.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_client_ip_resolution.py
index 8c6a400b4..c9a656140 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_client_ip_resolution.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_client_ip_resolution.py
@@ -28,9 +28,21 @@
def _request(peer: str | None, headers: dict[str, str]) -> Request:
+ """
+ 构造供当前场景使用的 HTTP 请求。
+
+ :param peer: 与当前连接对端有关的信息
+ :param headers: 响应或请求携带的 HTTP 头
+ :return: 供当前场景使用的 HTTP 请求
+ """
body = json.dumps({'userName': 'alice', 'password': 'test-password'}).encode()
async def receive() -> dict[str, object]:
+ """
+ 提供下游 ASGI 应用读取的 HTTP 请求体消息。
+
+ :return: 下游 ASGI 应用读取的 HTTP 请求体消息
+ """
return {'type': 'http.request', 'body': body, 'more_body': False}
return Request(
@@ -55,6 +67,11 @@ async def receive() -> dict[str, object]:
@pytest.fixture
def oidc_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
+ """
+ 为测试启用并配置 OIDC 服务。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
monkeypatch.setattr(OidcConfig, 'oidc_enabled', True)
monkeypatch.setattr(OidcConfig, 'oidc_issuer', 'https://auth.example')
monkeypatch.setattr(OidcConfig, 'oidc_token_hash_pepper', _PEPPER)
@@ -74,6 +91,14 @@ def oidc_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
def client_request(
request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, oidc_enabled: None
) -> tuple[Request, str]:
+ """
+ 按测试参数构造含代理信息的请求。
+
+ :param request: pytest 当前用例的请求上下文
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :param oidc_enabled: 为测试启用并配置 OIDC 服务
+ :return: 包含代理信息的请求及其预期客户端地址
+ """
peer, hops, headers, expected = request.param
monkeypatch.setattr(AppConfig, 'app_trusted_proxy_hops', hops)
return _request(peer, headers), expected
@@ -83,6 +108,7 @@ def client_request(
async def test_login_passes_resolved_ip_to_credentials_and_session_flow(
client_request: tuple[Request, str], monkeypatch: pytest.MonkeyPatch
) -> None:
+ """登录时将解析出的 IP 传给凭据和会话流程。"""
request, expected = client_request
request.scope['method'] = 'POST'
login = AsyncMock(return_value=InteractionLoginOutcome(failure_message='认证信息无效'))
@@ -97,6 +123,7 @@ async def test_login_passes_resolved_ip_to_credentials_and_session_flow(
async def test_captcha_uses_the_resolved_client_ip(
client_request: tuple[Request, str], monkeypatch: pytest.MonkeyPatch
) -> None:
+ """验证码使用解析出的客户端 IP。"""
request, expected = client_request
generate = AsyncMock(return_value=CaptchaOutcome(result=CaptchaResponseModel(captcha_enabled=False)))
monkeypatch.setattr(InteractionFlowService, 'captcha', generate)
@@ -110,6 +137,7 @@ async def test_captcha_uses_the_resolved_client_ip(
async def test_authorize_rate_limit_hashes_the_resolved_client_ip(
client_request: tuple[Request, str], monkeypatch: pytest.MonkeyPatch
) -> None:
+ """授权限流对解析出的客户端 IP 取哈希。"""
request, expected = client_request
enforce = AsyncMock()
monkeypatch.setattr(OidcRateLimiter, 'enforce', enforce)
@@ -124,6 +152,7 @@ async def test_authorize_rate_limit_hashes_the_resolved_client_ip(
async def test_logout_rate_limit_hashes_the_resolved_client_ip(
client_request: tuple[Request, str], monkeypatch: pytest.MonkeyPatch
) -> None:
+ """注销限流对解析出的客户端 IP 取哈希。"""
request, expected = client_request
enforce = AsyncMock()
monkeypatch.setattr(OidcRateLimiter, 'enforce', enforce)
@@ -140,6 +169,7 @@ async def test_logout_rate_limit_hashes_the_resolved_client_ip(
@pytest.mark.asyncio
@pytest.mark.usefixtures('oidc_enabled')
async def test_authorization_still_rejects_unknown_peer_ip(monkeypatch: pytest.MonkeyPatch) -> None:
+ """授权仍拒绝未知的对端 IP。"""
monkeypatch.setattr(AppConfig, 'app_trusted_proxy_hops', 1)
enforce = AsyncMock()
monkeypatch.setattr(OidcRateLimiter, 'enforce', enforce)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_discovery_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_discovery_controller.py
index b7decbb58..a5e0c4762 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_discovery_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_discovery_controller.py
@@ -14,14 +14,25 @@
def _request(headers: dict[str, str] | None = None, host: str = 'evil.example') -> Request:
- """创建带可控 Host 和缓存请求头的 Starlette 请求。"""
+ """
+ 创建带可控 Host 和缓存请求头的 Starlette 请求。
+
+ :param headers: 响应或请求携带的 HTTP 头
+ :param host: 连接目标或插件宿主上下文
+ :return: 带可控 Host 和缓存请求头的 Starlette 请求
+ """
raw_headers = [(b'host', host.encode())]
raw_headers.extend((key.lower().encode(), value.encode()) for key, value in (headers or {}).items())
return Request({'type': 'http', 'method': 'GET', 'path': '/', 'headers': raw_headers})
def _enabled(monkeypatch: pytest.MonkeyPatch) -> OidcConfig:
- """将全局配置设为启用且固定 issuer。"""
+ """
+ 将全局配置设为启用且固定 issuer。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: 供调用方使用的 ``OidcConfig``
+ """
monkeypatch.setattr(OidcConfig, 'oidc_enabled', True)
monkeypatch.setattr(OidcConfig, 'oidc_issuer', 'https://auth.example.com')
monkeypatch.setattr(controller, 'OidcConfig', OidcConfig)
@@ -32,14 +43,34 @@ class _DiscoveryDb:
"""提供 Discovery 动态 Scope 查询的最小显式会话替身。"""
class _Scalars:
+ """提供数据库查询结果的标量访问接口。"""
+
def all(self) -> list[str]:
+ """
+ 向测试用例返回空集合。
+
+ :return: 不含记录的查询列表
+ """
return []
class _Result:
+ """模拟数据库查询结果。"""
+
def scalars(self) -> '_DiscoveryDb._Scalars':
+ """
+ 提供 SQLAlchemy 标量查询结果的测试替身。
+
+ :return: SQLAlchemy 标量查询结果的测试替身
+ """
return _DiscoveryDb._Scalars()
async def execute(self, statement: object) -> '_DiscoveryDb._Result':
+ """
+ 按测试场景处理数据库查询并提供结果。
+
+ :param statement: 即将执行的数据库语句
+ :return: 包含模拟发现数据的查询结果
+ """
return _DiscoveryDb._Result()
@@ -95,15 +126,37 @@ async def test_discovery_publishes_only_active_database_scopes(monkeypatch: pyte
_enabled(monkeypatch)
class _Scalars:
+ """提供数据库查询结果的标量访问接口。"""
+
def all(self) -> list[str]:
+ """
+ 返回本次查询的全部测试行。
+
+ :return: 本次查询的全部测试行
+ """
return ['openid', 'orders.read', 'zzz.read']
class _Result:
+ """模拟数据库查询结果。"""
+
def scalars(self) -> _Scalars:
+ """
+ 提供 SQLAlchemy 标量查询结果的测试替身。
+
+ :return: SQLAlchemy 标量查询结果的测试替身
+ """
return _Scalars()
class _Db:
+ """模拟当前测试所需的数据库操作。"""
+
async def execute(self, statement: object) -> _Result:
+ """
+ 按测试场景处理数据库查询并提供结果。
+
+ :param statement: 即将执行的数据库语句
+ :return: 包含预设记录的查询结果
+ """
return _Result()
response = await controller.openid_configuration(_request(), _Db())
@@ -118,7 +171,15 @@ async def test_discovery_scope_query_failure_is_no_store_503(monkeypatch: pytest
_enabled(monkeypatch)
class _FailingDb:
+ """模拟数据库操作失败时的会话。"""
+
async def execute(self, statement: object) -> object:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param statement: 即将执行的数据库语句
+ :raises RuntimeError: 模拟数据库查询不可用
+ """
raise RuntimeError('database unavailable')
response = await controller.openid_configuration(_request(), _FailingDb())
@@ -144,6 +205,13 @@ async def test_jwks_is_raw_and_uses_key_service(monkeypatch: pytest.MonkeyPatch)
_enabled(monkeypatch)
async def build(*args: object, **kwargs: object) -> dict[str, list[dict[str, str]]]:
+ """
+ 返回含 ``keys`` 的测试数据。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 含 ``keys`` 的测试数据
+ """
return {'keys': [{'kty': 'RSA', 'use': 'sig', 'kid': 'k1', 'alg': 'RS256', 'n': 'n', 'e': 'AQAB'}]}
monkeypatch.setattr(controller.KeyService, 'build_jwks', build)
@@ -159,6 +227,13 @@ async def test_jwks_fails_closed_on_invalid_public_key(monkeypatch: pytest.Monke
_enabled(monkeypatch)
async def build(*args: object, **kwargs: object) -> dict[str, list[dict[str, str]]]:
+ """
+ 模拟此操作抛出 KeyServiceError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises KeyServiceError: 模拟公开 JWK 的 RSA 参数无效
+ """
raise KeyServiceError('public JWK RSA numbers are invalid')
monkeypatch.setattr(controller.KeyService, 'build_jwks', build)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_interaction_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_interaction_controller.py
index 7bb7ca3c0..1b5ea0fa4 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_interaction_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_interaction_controller.py
@@ -75,35 +75,60 @@
class _Db:
- """记录交互控制器事务边界。"""
+ """
+ 记录交互控制器事务边界。
+
+ :ivar commits: 测试中记录的提交次数
+ :ivar rollbacks: 测试中记录的回滚次数
+ :ivar events: 保存已发出事件的序列
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``commits``, ``rollbacks``, ``events``。"""
self.commits = 0
self.rollbacks = 0
self.events: list[object] = []
def add(self, value: object) -> None:
+ """
+ 将测试对象加入待检查的操作记录。
+
+ :param value: 待处理的输入值
+ """
self.events.append(value)
async def flush(self) -> None:
- return None
+ """完成无需返回值的回调。"""
+ return
async def commit(self) -> None:
+ """累加 ``commits`` 供后续断言检查。"""
self.commits += 1
async def rollback(self) -> None:
+ """累加 ``rollbacks`` 供后续断言检查。"""
self.rollbacks += 1
@dataclass
class _User:
- """登录成功所需的最小用户标量。"""
+ """
+ 登录成功所需的最小用户标量。
+
+ :ivar user_id: 用户的唯一标识
+ """
user_id: int = 2
def _payload(status: str = 'awaiting_login', **overrides: object) -> dict[str, object]:
- """构造 Interaction 内部白名单载荷。"""
+ """
+ 构造 Interaction 内部白名单载荷。
+
+ :param status: 操作或记录所处的状态
+ :param overrides: 调用方按名称传入的附加选项
+ :return: Interaction 内部白名单载荷
+ """
payload: dict[str, object] = {
'interactionId': 'interaction-controller-id',
'clientPk': 1001,
@@ -129,7 +154,13 @@ def _payload(status: str = 'awaiting_login', **overrides: object) -> dict[str, o
def _request(redis: FakeRedis, csrf: str | None = None) -> SimpleNamespace:
- """构造交互页面请求替身。"""
+ """
+ 构造交互页面请求替身。
+
+ :param redis: 测试用 Redis
+ :param csrf: 请求中的 CSRF 校验值
+ :return: 交互页面请求替身
+ """
return SimpleNamespace(
app=SimpleNamespace(state=SimpleNamespace(redis=redis)),
headers={'x-csrf-token': csrf} if csrf else {},
@@ -139,7 +170,11 @@ def _request(redis: FakeRedis, csrf: str | None = None) -> SimpleNamespace:
def _context() -> AuthorizationContext:
- """构造同意校验使用的不可变上下文。"""
+ """
+ 构造同意校验使用的不可变上下文。
+
+ :return: 同意校验使用的不可变上下文
+ """
return AuthorizationContext(
client=ClientSnapshot(1001, 'portal-client', 1, ('authorization_code',), ('code',), True, True, False),
redirect_uri='https://portal.example/callback',
@@ -161,7 +196,11 @@ def _context() -> AuthorizationContext:
@pytest.fixture
def oidc_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
- """配置安全 OIDC 参数。"""
+ """
+ 配置安全 OIDC 参数。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
monkeypatch.setattr(OidcConfig, 'oidc_enabled', True)
monkeypatch.setattr(OidcConfig, 'oidc_token_hash_pepper', _PEPPER)
monkeypatch.setattr(OidcConfig, 'oidc_authorization_code_ttl_seconds', 90)
@@ -197,12 +236,33 @@ async def test_login_and_complete_real_interaction_lifecycle(monkeypatch: pytest
)
async def authenticate(*args: object, **kwargs: object) -> CredentialAuthenticationResult:
+ """
+ 向调用方返回 ``result``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 为当前测试预设的操作结果
+ """
return result
async def require_subject(*args: object, **kwargs: object) -> Any:
+ """
+ 向调用方返回 ``subject``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 令牌中标识用户的主体
+ """
return subject
async def create_sso(*args: object, **kwargs: object) -> tuple[str, Any]:
+ """
+ 提供登录流程使用的测试会话。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 登录流程使用的测试会话
+ """
return 'ss1.sid-1.' + 'A' * 43, session
monkeypatch.setattr(CredentialAuthenticationService, 'authenticate_oidc', authenticate)
@@ -232,6 +292,12 @@ async def create_sso(*args: object, **kwargs: object) -> tuple[str, Any]:
audit_events: list[str] = []
async def record_audit(*args: object, **kwargs: object) -> None:
+ """
+ 记录本次提交的审计事件。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
audit_events.append(str(args[1]))
monkeypatch.setattr(AuditService, 'record', record_audit)
@@ -263,12 +329,33 @@ async def test_forced_password_login_creates_no_sso_cookie_or_active_session(
subject = SimpleNamespace(subject_id='11111111-1111-4111-8111-111111111111', auth_version=1)
async def authenticate(*args: object, **kwargs: object) -> CredentialAuthenticationResult:
+ """
+ 向调用方返回 ``result``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 为当前测试预设的操作结果
+ """
return result
async def require_subject(*args: object, **kwargs: object) -> Any:
+ """
+ 向调用方返回 ``subject``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 令牌中标识用户的主体
+ """
return subject
async def forbidden_sso(*args: object, **kwargs: object) -> Any:
+ """
+ 模拟此操作抛出 AssertionError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises AssertionError: 强制密码登录错误地尝试创建单点登录会话
+ """
raise AssertionError('forced password login must not create SSO')
monkeypatch.setattr(CredentialAuthenticationService, 'authenticate_oidc', authenticate)
@@ -360,7 +447,12 @@ async def test_captcha_endpoint_has_independent_oidc_limit_and_fail_closed(
async def _raise_async(error: Exception) -> Any:
- """在测试中构造异步异常结果。"""
+ """
+ 在测试中构造异步异常结果。
+
+ :param error: 发生错误时返回的错误信息
+ :raises Exception: 底层操作失败时向调用方传播异常
+ """
raise error
@@ -432,11 +524,28 @@ async def test_body_parser_rejects_duplicate_unknown_and_oversized_json_without_
"""JSON 解析错误统一脱敏,且受 16KiB 总体大小限制。"""
class BodyRequest:
+ """
+ 分块提供测试请求体。
+
+ :ivar headers: 响应或请求携带的 HTTP 头
+ :ivar value: 待处理的输入值
+ """
+
def __init__(self, value: bytes) -> None:
+ """
+ 初始化测试夹具的 ``headers``, ``value``。
+
+ :param value: 待处理的输入值
+ """
self.headers = {'content-type': 'application/json'}
self.value = value
async def stream(self) -> Any:
+ """
+ 将请求数据分段异步输出。
+
+ :yield: 按读取进度切分的请求体字节块
+ """
midpoint = len(self.value) // 2
yield self.value[:midpoint]
yield self.value[midpoint:]
@@ -462,6 +571,11 @@ def test_interaction_routes_stream_and_normalize_malformed_json_without_password
app.include_router(interaction_controller)
async def db_override() -> Any:
+ """
+ 为请求提供替代数据库会话。
+
+ :yield: 本次请求使用的模拟数据库会话
+ """
yield _Db()
app.dependency_overrides[get_db_session_provider(None)] = db_override
@@ -494,9 +608,17 @@ async def test_db_commit_then_redis_cas_failure_runs_compensation(monkeypatch: p
compensated = False
async def failed_transition(*args: object, **kwargs: object) -> object:
+ """
+ 模拟此操作抛出 OidcInteractionException 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises OidcInteractionException: 模拟交互状态的比较交换失败
+ """
raise OidcInteractionException(created.interaction_id, 'CAS failed', error='server_error', status_code=503)
async def compensate() -> None:
+ """记录失败处理是否触发补偿。"""
nonlocal compensated
compensated = True
@@ -551,16 +673,31 @@ async def test_consent_commit_then_redis_cas_failure_compensates_persisted_grant
compensated = False
async def revoke(*_args: object, **_kwargs: object) -> bool:
+ """
+ 在此测试分支返回 True。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 此分支的固定值 ``True``
+ """
return True
monkeypatch.setattr(OAuthGrantDao, 'revoke_snapshot', revoke)
async def compensate() -> None:
+ """记录失败处理是否触发补偿。"""
nonlocal compensated
compensated = True
await ConsentService.compensate_persisted_grant(db, result)
async def cas_failure(*_args: object, **_kwargs: object) -> None:
+ """
+ 模拟此操作抛出 OidcInteractionException 的情形。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :raises OidcInteractionException: 模拟交互状态的比较交换失败
+ """
raise OidcInteractionException(created.interaction_id, 'CAS failed', error='server_error', status_code=503)
monkeypatch.setattr(InteractionService, 'transition', cas_failure)
@@ -632,15 +769,34 @@ async def test_password_change_cas_failure_runs_full_security_saga(monkeypatch:
)
async def revoke(*_args: object, **_kwargs: object) -> None:
+ """
+ 在请求处理中撤销测试凭据。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ """
revoked.append(session.sid)
async def record_independent(*args: object, **_kwargs: object) -> None:
+ """
+ 记录独立事务写入的审计事件。
+
+ :param args: 传给被调用对象的位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ """
audit_events.append(str(args[1]))
monkeypatch.setattr(SsoSessionService, 'revoke', revoke)
monkeypatch.setattr(AuditService, 'record_independent', record_independent)
async def cas_fail(*args: object, **kwargs: object) -> None:
+ """
+ 模拟此操作抛出 OidcInteractionException 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises OidcInteractionException: 模拟交互状态的比较交换失败
+ """
raise OidcInteractionException(created.interaction_id, 'CAS failed', error='server_error', status_code=503)
monkeypatch.setattr(InteractionService, 'transition', cas_fail)
@@ -696,6 +852,13 @@ async def test_password_change_saga_continues_when_interaction_delete_fails(
audits: list[str] = []
async def delete_failure(*_args: object, **_kwargs: object) -> int:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :raises RuntimeError: 模拟删除 Redis 记录失败
+ """
raise RuntimeError('redis unavailable')
monkeypatch.setattr(redis, 'delete', delete_failure)
@@ -712,6 +875,13 @@ async def delete_failure(*_args: object, **_kwargs: object) -> int:
monkeypatch.setattr(AuditService, 'record_independent', lambda *args, **kwargs: _append_async(audits, str(args[1])))
async def cas_fail(*_args: object, **_kwargs: object) -> None:
+ """
+ 模拟此操作抛出 OidcInteractionException 的情形。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :raises OidcInteractionException: 模拟交互状态的比较交换失败
+ """
raise OidcInteractionException(created.interaction_id, 'CAS failed', error='server_error', status_code=503)
monkeypatch.setattr(InteractionService, 'transition', cas_fail)
@@ -730,23 +900,58 @@ async def cas_fail(*_args: object, **_kwargs: object) -> None:
class _ScalarDb(_Db):
- """支持改密测试查询用户的最小数据库替身。"""
+ """
+ 支持改密测试查询用户的最小数据库替身。
+
+ :ivar value: 待处理的输入值
+ """
def __init__(self, value: object) -> None:
+ """
+ 初始化测试夹具的 ``value``。
+
+ :param value: 待处理的输入值
+ """
super().__init__()
self.value = value
async def scalar(self, *_args: object, **_kwargs: object) -> object:
+ """
+ 向调用方返回 ``self.value``。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 测试对象保存的值
+ """
return self.value
async def execute(self, *_args: object, **_kwargs: object) -> object:
+ """
+ 按测试场景处理数据库查询并提供结果。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 包含预设记录的查询结果
+ """
value = self.value
class _Result:
+ """模拟数据库查询结果。"""
+
def scalars(self) -> object:
+ """
+ 向调用方返回 ``self``。
+
+ :return: 当前测试对象
+ """
return self
def first(self) -> object:
+ """
+ 向调用方返回 ``value``。
+
+ :return: 为此调用预设的值
+ """
return value
return _Result()
@@ -760,9 +965,15 @@ async def test_cache_callback_failure_does_not_compensate_committed_session() ->
compensated = False
async def cache_failure() -> None:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :raises RuntimeError: 模拟缓存服务不可用
+ """
raise RuntimeError('cache unavailable')
async def compensate() -> None:
+ """记录失败处理是否触发补偿。"""
nonlocal compensated
compensated = True
@@ -807,6 +1018,13 @@ async def test_code_audit_failure_invalidates_code_and_marker(monkeypatch: pytes
)
async def audit_failure(*_args: object, **_kwargs: object) -> None:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :raises RuntimeError: 模拟审计服务不可用
+ """
raise RuntimeError('audit unavailable')
monkeypatch.setattr(AuditService, 'record', audit_failure)
@@ -860,18 +1078,35 @@ async def test_code_invalidate_failure_still_cleans_marker_and_rolls_back(monkey
def _async(value: object) -> Any:
- """构造异步测试结果。"""
+ """
+ 构造异步测试结果。
+
+ :param value: 待处理的输入值
+ :return: 异步测试结果
+ """
async def result() -> object:
+ """
+ 向调用方返回 ``value``。
+
+ :return: 为此调用预设的值
+ """
return value
return result()
def _append_async(values: list[Any], value: Any) -> Any:
- """构造追加测试值的异步结果。"""
+ """
+ 构造追加测试值的异步结果。
+
+ :param values: 当前处理的值集合
+ :param value: 待处理的输入值
+ :return: 追加测试值的异步结果
+ """
async def result() -> None:
+ """记录调用方收到的异步结果。"""
values.append(value)
return result()
@@ -904,6 +1139,11 @@ async def test_interaction_http_response_matches_frontend_data_contract(
app.include_router(interaction_controller)
async def db_override() -> Any:
+ """
+ 为请求提供替代数据库会话。
+
+ :yield: 本次请求使用的模拟数据库会话
+ """
yield _Db()
app.dependency_overrides[get_db_session_provider(None)] = db_override
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_logout_confirmation.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_logout_confirmation.py
index f13225da5..3c1c733d1 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_logout_confirmation.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_logout_confirmation.py
@@ -20,22 +20,52 @@
class ConfirmationRedis:
+ """
+ 模拟带过期时间的注销确认记录。
+
+ :ivar values: 当前处理的值集合
+ """
+
def __init__(self) -> None:
+ """初始化测试夹具的 ``values``。"""
self.values: dict[str, tuple[str, float]] = {}
async def set(self, key: str, value: str, *, ex: int, nx: bool = False) -> bool:
+ """
+ 写入测试缓存键并设置过期时间。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :param ex: 捕获到的异常实例
+ :param nx: 是否只在键尚不存在时写入
+ :return: 是否写入测试缓存键并设置过期时间
+ """
if nx and key in self.values:
return False
self.values[key] = (value, monotonic() + ex)
return True
async def eval(self, _script: str, _count: int, key: str) -> str | None:
+ """
+ 按测试约定模拟 Redis 脚本的执行。
+
+ :param _script: 测试替身接收的 Redis 脚本
+ :param _count: 调用方传入的计数
+ :param key: 查找数据时使用的键
+ :return: 模拟脚本读取或更新后的值
+ """
value, expires = self.values.pop(key, (None, 0))
return value if expires > monotonic() else None
@pytest.fixture
def logout_client(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[TestClient, AsyncMock]]:
+ """
+ 创建启用认证中心的注销测试客户端。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :yield: 依次为 ``client``、``execute`` 的元组
+ """
monkeypatch.setattr(OidcConfig, 'oidc_enabled', True)
monkeypatch.setattr(OidcConfig, 'oidc_issuer', 'https://auth.example')
monkeypatch.setattr(OidcConfig, 'oidc_token_hash_pepper', 'logout-confirmation-test-' + 'x' * 32)
@@ -48,6 +78,11 @@ def logout_client(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[TestClient,
db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
async def get_db() -> AsyncIterator[SimpleNamespace]:
+ """
+ 为请求提供数据库会话。
+
+ :yield: 当前操作使用的数据库会话
+ """
yield db
app.dependency_overrides[get_db_session_provider(None)] = get_db
@@ -62,6 +97,7 @@ async def get_db() -> AsyncIterator[SimpleNamespace]:
def test_standard_logout_requires_confirmation_then_redirects(
logout_client: tuple[TestClient, AsyncMock], method: str
) -> None:
+ """标准注销先确认再重定向。"""
client, execute = logout_client
parameters = {
'id_token_hint': 'private-hint',
@@ -100,6 +136,7 @@ def test_standard_logout_requires_confirmation_then_redirects(
def test_cancel_keeps_sso_cookie_and_never_calls_revocation(logout_client: tuple[TestClient, AsyncMock]) -> None:
+ """取消注销时保留单点登录 Cookie 且不撤销会话。"""
client, execute = logout_client
client.cookies.set(OidcConfig.oidc_sso_cookie_name, 'current-sso', domain='auth.example', path='/')
page = client.get('/oauth2/logout')
@@ -119,6 +156,7 @@ def test_cancel_keeps_sso_cookie_and_never_calls_revocation(logout_client: tuple
def test_confirmation_rejects_wrong_origin_browser_or_expiry(
logout_client: tuple[TestClient, AsyncMock], attack: str
) -> None:
+ """注销确认时拒绝来源、浏览器或有效期不符的请求。"""
client, execute = logout_client
page = client.get('/oauth2/logout')
token = re.search(r'name="confirmation" value="([^"]+)"', page.text).group(1)
@@ -156,6 +194,7 @@ def test_cross_site_post_may_omit_lax_sso_cookie_until_confirmation(
def test_changing_an_initially_bound_sso_cookie_rejects_confirmation(
logout_client: tuple[TestClient, AsyncMock],
) -> None:
+ """最初绑定的单点登录 Cookie 变化后拒绝确认。"""
client, execute = logout_client
client.cookies.set(OidcConfig.oidc_sso_cookie_name, 'first-sso', domain='auth.example', path='/')
page = client.get('/oauth2/logout')
@@ -175,6 +214,7 @@ def test_changing_an_initially_bound_sso_cookie_rejects_confirmation(
async def test_confirmation_csp_allows_only_verified_registered_redirect(
monkeypatch: pytest.MonkeyPatch, registered: bool
) -> None:
+ """确认页的 CSP 仅允许已验证的注册重定向地址。"""
monkeypatch.setattr(
LogoutService, '_validate_id_token_hint', AsyncMock(return_value=({}, SimpleNamespace(client_pk=1)))
)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_audit_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_audit_controller.py
index b07f05e73..1e9df1a6a 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_audit_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_audit_controller.py
@@ -21,12 +21,18 @@
class _Session:
- """提供只读回滚边界。"""
+ """
+ 提供只读回滚边界。
+
+ :ivar rollbacks: 测试中记录的回滚次数
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``rollbacks``。"""
self.rollbacks = 0
async def rollback(self) -> None:
+ """累加 ``rollbacks`` 供后续断言检查。"""
self.rollbacks += 1
@@ -92,9 +98,23 @@ async def test_audit_list_uses_real_total_and_safe_projection(monkeypatch: pytes
]
async def list_page(*args: object, **kwargs: object) -> list[object]:
+ """
+ 向调用方返回 ``rows``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 查询得到的记录列表
+ """
return rows
async def count(*args: object, **kwargs: object) -> int:
+ """
+ 返回固定值 ``37``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``37``
+ """
return 37
monkeypatch.setattr(OAuthAuditDao, 'list_admin_page', list_page)
@@ -108,7 +128,6 @@ async def count(*args: object, **kwargs: object) -> int:
@pytest.mark.asyncio
async def test_audit_export_runs_rate_limit_and_operation_log(monkeypatch: pytest.MonkeyPatch) -> None:
"""HTTP 审计导出经过完整装饰器链,保留文件响应并记录操作日志。"""
-
query = AuditPageQueryModel()
db = _Session()
user = SimpleNamespace(user=SimpleNamespace(user_id=1, user_name='admin', dept=None))
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_client_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_client_controller.py
index 2b2775aa9..ee7d82f21 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_client_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_client_controller.py
@@ -22,37 +22,63 @@
class _FakeSession:
- """记录 Controller 的 commit/rollback 边界。"""
+ """
+ 记录 Controller 的 commit/rollback 边界。
+
+ :ivar commits: 测试中记录的提交次数
+ :ivar rollbacks: 测试中记录的回滚次数
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``commits``, ``rollbacks``。"""
self.commits = 0
self.rollbacks = 0
async def commit(self) -> None:
+ """累加 ``commits`` 供后续断言检查。"""
self.commits += 1
async def rollback(self) -> None:
+ """累加 ``rollbacks`` 供后续断言检查。"""
self.rollbacks += 1
@pytest.fixture(autouse=True)
def _request_context(monkeypatch: pytest.MonkeyPatch) -> None:
- """为日志装饰器提供当前用户上下文。"""
+ """
+ 为日志装饰器提供当前用户上下文。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
monkeypatch.setattr(RequestContext, 'get_current_user', staticmethod(_user))
async def enqueue_operation_log(*args: object, **kwargs: object) -> None:
- return None
+ """
+ 完成无需返回值的回调。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
+ return
monkeypatch.setattr(LogQueueService, 'enqueue_operation_log', enqueue_operation_log)
def _user() -> SimpleNamespace:
- """构造最小当前用户对象。"""
+ """
+ 构造最小当前用户对象。
+
+ :return: 最小当前用户对象
+ """
return SimpleNamespace(user=SimpleNamespace(user_name='admin', dept=SimpleNamespace(dept_name='测试部门')))
def _client_payload() -> dict[str, object]:
- """构造通过请求模型校验的客户端创建参数。"""
+ """
+ 构造通过请求模型校验的客户端创建参数。
+
+ :return: 通过请求模型校验的客户端创建参数
+ """
return {
'clientName': '测试客户端',
'clientType': 'public',
@@ -62,10 +88,19 @@ def _client_payload() -> dict[str, object]:
def _request() -> Request:
- """构造带可观察 CORS 快照的请求。"""
+ """
+ 构造带可观察 CORS 快照的请求。
+
+ :return: 带可观察 CORS 快照的请求
+ """
app = SimpleNamespace(state=SimpleNamespace(oidc_registered_cors_origins=('https://old.example',)))
async def receive() -> dict[str, object]:
+ """
+ 提供下游 ASGI 应用读取的 HTTP 请求体消息。
+
+ :return: 下游 ASGI 应用读取的 HTTP 请求体消息
+ """
return {'type': 'http.request', 'body': b'', 'more_body': False}
return Request(
@@ -82,7 +117,11 @@ async def receive() -> dict[str, object]:
def _routes() -> list[APIRoute]:
- """返回 Client Router 的 HTTP 路由。"""
+ """
+ 返回 Client Router 的 HTTP 路由。
+
+ :return: Client Router 的 HTTP 路由
+ """
return [route for route in oauth_client_controller.routes if isinstance(route, APIRoute)]
@@ -118,6 +157,13 @@ async def test_client_create_commits_and_secret_is_only_in_rotation_response(
session = _FakeSession()
async def fake_create(*args: object, **kwargs: object) -> object:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(model_dump=lambda **_: {'clientId': 'cli_test'})
monkeypatch.setattr(OAuthClientManagementService, 'create_client', fake_create)
@@ -137,6 +183,13 @@ async def fake_create(*args: object, **kwargs: object) -> object:
)
async def fake_rotate(*args: object, **kwargs: object) -> ClientSecretResponseModel:
+ """
+ 向调用方返回 ``secret``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 测试使用的密钥
+ """
return secret
monkeypatch.setattr(OAuthClientManagementService, 'rotate_secret', fake_rotate)
@@ -148,6 +201,13 @@ async def fake_rotate(*args: object, **kwargs: object) -> ClientSecretResponseMo
assert session.commits == 0
async def fake_fail(*args: object, **kwargs: object) -> object:
+ """
+ 模拟此操作抛出 OAuthClientManagementError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises OAuthClientManagementError: 模拟客户端管理请求被拒绝
+ """
raise OAuthClientManagementError('OAuth Client request rejected')
monkeypatch.setattr(OAuthClientManagementService, 'create_client', fake_fail)
@@ -171,6 +231,14 @@ async def test_client_batch_failure_rolls_back_all_items(
calls: list[str] = []
async def fake_disable(*args: object, **kwargs: object) -> object:
+ """
+ 模拟批量禁用客户端时的逐项结果。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises OAuthClientManagementError: 模拟待停用的客户端不存在
+ :return: ``SimpleNamespace`` 实例
+ """
client_id = args[1]
calls.append(client_id)
if client_id == 'cli_bad':
@@ -194,6 +262,13 @@ async def test_cors_snapshot_refresh_failure_fails_closed(monkeypatch: pytest.Mo
request = _request()
async def fail_refresh(*args: object, **kwargs: object) -> tuple[str, ...]:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RuntimeError: 模拟刷新数据时数据库不可用
+ """
raise RuntimeError('database unavailable')
monkeypatch.setattr(OidcRuntimeService, 'refresh_cors_snapshot', fail_refresh)
@@ -210,9 +285,23 @@ async def test_client_list_uses_real_total_and_actor_failure_is_mapped(
session = _FakeSession()
async def fake_rows(*args: object, **kwargs: object) -> list[str]:
+ """
+ 返回查询使用的固定测试行。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 查询使用的固定测试行
+ """
return ['row-1', 'row-2']
async def fake_count(*args: object, **kwargs: object) -> int:
+ """
+ 返回固定值 ``37``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``37``
+ """
return 37
monkeypatch.setattr(OAuthClientManagementService, 'list_clients', fake_rows)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_resource_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_resource_controller.py
index da131c182..b2a0b4ea4 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_resource_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_resource_controller.py
@@ -23,43 +23,75 @@
class _FakeSession:
- """记录 Controller 提交和回滚次数。"""
+ """
+ 记录 Controller 提交和回滚次数。
+
+ :ivar commits: 测试中记录的提交次数
+ :ivar rollbacks: 测试中记录的回滚次数
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``commits``, ``rollbacks``。"""
self.commits = 0
self.rollbacks = 0
async def commit(self) -> None:
+ """累加 ``commits`` 供后续断言检查。"""
self.commits += 1
async def rollback(self) -> None:
+ """累加 ``rollbacks`` 供后续断言检查。"""
self.rollbacks += 1
@pytest.fixture(autouse=True)
def _request_context(monkeypatch: pytest.MonkeyPatch) -> None:
- """为日志装饰器提供当前用户上下文。"""
+ """
+ 为日志装饰器提供当前用户上下文。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
monkeypatch.setattr(RequestContext, 'get_current_user', staticmethod(_user))
async def enqueue_operation_log(*args: object, **kwargs: object) -> None:
- return None
+ """
+ 完成无需返回值的回调。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
+ return
monkeypatch.setattr(LogQueueService, 'enqueue_operation_log', enqueue_operation_log)
def _user() -> SimpleNamespace:
- """构造最小当前用户对象。"""
+ """
+ 构造最小当前用户对象。
+
+ :return: 最小当前用户对象
+ """
return SimpleNamespace(user=SimpleNamespace(user_name='admin', dept=SimpleNamespace(dept_name='测试部门')))
def _route_map(router: object) -> dict[tuple[str, str], APIRoute]:
- """构造路由路径和方法索引。"""
+ """
+ 构造路由路径和方法索引。
+
+ :param router: 注册端点所用的路由器
+ :return: 路由路径和方法索引
+ """
routes = [route for route in router.routes if isinstance(route, APIRoute)]
return {(route.path, method): route for route in routes for method in route.methods}
def _assert_routes(router: object, expected: dict[tuple[str, str], str]) -> None:
- """断言路由路径、方法和权限依赖。"""
+ """
+ 断言路由路径、方法和权限依赖。
+
+ :param router: 注册端点所用的路由器
+ :param expected: 断言使用的预期结果
+ """
routes = _route_map(router)
assert set(routes) == set(expected)
for key, permission in expected.items():
@@ -105,6 +137,14 @@ async def test_resource_batch_failure_rolls_back_without_partial_commit(
calls: list[str] = []
async def fake_disable(*args: object, **kwargs: object) -> object:
+ """
+ 模拟批量禁用客户端时的逐项结果。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises OAuthClientManagementError: 模拟待停用的资源不存在
+ :return: ``SimpleNamespace`` 实例
+ """
resource_id = args[1]
calls.append(resource_id)
if resource_id == 'resource-bad':
@@ -153,9 +193,23 @@ async def test_resource_scope_lists_use_real_total_and_actor_failure_is_mapped(
session = _FakeSession()
async def fake_rows(*args: object, **kwargs: object) -> list[str]:
+ """
+ 返回查询使用的固定测试行。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 查询使用的固定测试行
+ """
return ['row-1', 'row-2']
async def fake_count(*args: object, **kwargs: object) -> int:
+ """
+ 返回固定值 ``37``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``37``
+ """
return 37
monkeypatch.setattr(OAuthResourceManagementService, 'list_resources', fake_rows)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_session_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_session_controller.py
index 9e5586c58..37a339f99 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_session_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_session_controller.py
@@ -28,29 +28,50 @@
class _Session:
- """记录 Controller 事务边界。"""
+ """
+ 记录 Controller 事务边界。
+
+ :ivar commits: 测试中记录的提交次数
+ :ivar rollbacks: 测试中记录的回滚次数
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``commits``, ``rollbacks``。"""
self.commits = 0
self.rollbacks = 0
async def commit(self) -> None:
+ """累加 ``commits`` 供后续断言检查。"""
self.commits += 1
async def rollback(self) -> None:
+ """累加 ``rollbacks`` 供后续断言检查。"""
self.rollbacks += 1
def _user() -> SimpleNamespace:
- """构造最小管理用户。"""
+ """
+ 构造最小管理用户。
+
+ :return: 最小管理用户
+ """
return SimpleNamespace(user=SimpleNamespace(user_name='admin', user_id=1, dept=None))
def _request() -> Request:
- """构造含最小 Redis 状态的管理请求。"""
+ """
+ 构造含最小 Redis 状态的管理请求。
+
+ :return: 含最小 Redis 状态的管理请求
+ """
app = SimpleNamespace(state=SimpleNamespace(redis=SimpleNamespace()))
async def receive() -> dict[str, object]:
+ """
+ 提供下游 ASGI 应用读取的 HTTP 请求体消息。
+
+ :return: 下游 ASGI 应用读取的 HTTP 请求体消息
+ """
return {'type': 'http.request', 'body': b'', 'more_body': False}
return Request(
@@ -59,7 +80,12 @@ async def receive() -> dict[str, object]:
def _route_map(router: object) -> dict[tuple[str, str], APIRoute]:
- """索引路由路径、方法。"""
+ """
+ 索引路由路径、方法。
+
+ :param router: 注册端点所用的路由器
+ :return: 按路径和 HTTP 方法索引的路由
+ """
return {
(route.path, method): route
for route in router.routes
@@ -101,16 +127,36 @@ async def test_batch_revoke_is_atomic_and_reason_does_not_leak(
db = _Session()
async def audit(*args: object, **kwargs: object) -> None:
- return None
+ """
+ 完成无需返回值的回调。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
+ return
monkeypatch.setattr(AuditService, 'record', audit)
async def enqueue(*args: object, **kwargs: object) -> None:
- return None
+ """
+ 完成无需返回值的回调。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
+ return
monkeypatch.setattr(LogQueueService, 'enqueue_operation_log', enqueue)
async def revoke(*args: object, **kwargs: object) -> bool:
+ """
+ 在请求处理中撤销测试凭据。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises ValueError: 模拟撤销操作产生含敏感信息的错误
+ :return: 此分支的固定值 ``True``
+ """
if args[2] == 'bad':
raise ValueError('refresh_token_hash=do-not-leak')
return True
@@ -129,6 +175,13 @@ async def revoke(*args: object, **kwargs: object) -> bool:
assert db.commits == 0 and db.rollbacks == 1
async def grant_revoke(*args: object, **kwargs: object) -> bool:
+ """
+ 在此测试分支返回 True。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``True``
+ """
return True
monkeypatch.setattr(OAuthGrantDao, 'targets', AsyncMock(return_value=[(2, 1)]))
@@ -156,6 +209,13 @@ async def test_session_controller_injects_redis_without_passing_request_to_servi
captured: dict[str, object] = {}
async def revoke_sessions(*args: object, **kwargs: object) -> int:
+ """
+ 记录批量撤销的参数并返回影响数量。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``1``
+ """
captured['args'] = args
captured['kwargs'] = kwargs
return 1
@@ -163,7 +223,13 @@ async def revoke_sessions(*args: object, **kwargs: object) -> int:
monkeypatch.setattr(OAuthSessionManagementService, 'revoke_sessions', revoke_sessions)
async def enqueue_operation_log(*args: object, **kwargs: object) -> None:
- return None
+ """
+ 完成无需返回值的回调。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
+ return
monkeypatch.setattr(LogQueueService, 'enqueue_operation_log', enqueue_operation_log)
token = RequestContext.set_current_user(_user())
@@ -195,14 +261,35 @@ async def test_grant_detail_never_returns_refresh_hash(monkeypatch: pytest.Monke
)
async def get_grant(*args: object, **kwargs: object) -> object:
+ """
+ 向调用方返回 ``row``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 与查询匹配的记录
+ """
return row
async def execute(*args: object, **kwargs: object) -> object:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(all=list, scalars=lambda: SimpleNamespace(all=list, first=lambda: None))
monkeypatch.setattr(OAuthGrantDao, 'get_by_grant_id', get_grant)
async def client_id(*args: object, **kwargs: object) -> str:
+ """
+ 返回固定值 ``client-2``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``'client-2'``
+ """
return 'client-2'
monkeypatch.setattr(OAuthClientDao, 'id_for_pk', client_id)
@@ -216,7 +303,6 @@ async def client_id(*args: object, **kwargs: object) -> str:
@pytest.mark.parametrize('grant_ids', ['grant-1', 'grant-1,grant-2'])
async def test_grant_revoke_runs_rate_limit_and_operation_log(monkeypatch: pytest.MonkeyPatch, grant_ids: str) -> None:
"""HTTP 撤销请求经过完整装饰器链并记录实际请求和撤销结果。"""
-
db = _Session()
user = _user()
path = f'/system/oauth/grant/{grant_ids}'
@@ -270,7 +356,6 @@ async def test_grant_revoke_runs_rate_limit_and_operation_log(monkeypatch: pytes
@pytest.mark.parametrize('blocked', [True, False])
async def test_access_policy_runs_rate_limit_and_operation_log(monkeypatch: pytest.MonkeyPatch, blocked: bool) -> None:
"""禁止及解除访问通过真实 HTTP 装饰器链,准确传递用户、应用和原因。"""
-
db, user = _Session(), _user()
path = '/system/oauth/grant/user/7/client/business-app/access'
route = _route_map(oauth_grant_controller)[('/system/oauth/grant/user/{user_id}/client/{client_id}/access', 'PUT')]
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oidc_key_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oidc_key_controller.py
index 12093645d..0e3cfac7f 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oidc_key_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oidc_key_controller.py
@@ -18,26 +18,42 @@
class _Session:
- """记录提交和回滚。"""
+ """
+ 记录提交和回滚。
+
+ :ivar commits: 测试中记录的提交次数
+ :ivar rollbacks: 测试中记录的回滚次数
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``commits``, ``rollbacks``。"""
self.commits = 0
self.rollbacks = 0
async def commit(self) -> None:
+ """累加 ``commits`` 供后续断言检查。"""
self.commits += 1
async def rollback(self) -> None:
+ """累加 ``rollbacks`` 供后续断言检查。"""
self.rollbacks += 1
def _user() -> SimpleNamespace:
- """构造管理用户。"""
+ """
+ 构造管理用户。
+
+ :return: 管理用户
+ """
return SimpleNamespace(user=SimpleNamespace(user_name='admin'))
def _request() -> Request:
- """构造密钥管理写请求。"""
+ """
+ 构造密钥管理写请求。
+
+ :return: 密钥管理写请求
+ """
app = SimpleNamespace(state=SimpleNamespace())
return Request({'type': 'http', 'method': 'PUT', 'path': '/', 'headers': [], 'app': app})
@@ -68,6 +84,13 @@ async def test_key_write_failures_rollback_and_never_return_private_fields(monke
db = _Session()
async def fail(*args: object, **kwargs: object) -> bool:
+ """
+ 模拟此操作抛出 ValueError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises ValueError: 模拟密钥操作产生含敏感信息的错误
+ """
raise ValueError('private_key_ciphertext=secret')
monkeypatch.setattr(KeyService, 'activate_key', fail)
@@ -77,6 +100,13 @@ async def fail(*args: object, **kwargs: object) -> bool:
assert db.rollbacks == 1 and db.commits == 0
async def retire(*args: object, **kwargs: object) -> bool:
+ """
+ 在此测试分支返回 True。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``True``
+ """
return True
monkeypatch.setattr(KeyService, 'retire_key', retire)
@@ -95,6 +125,13 @@ async def test_key_activation_returns_clear_message_before_publication(monkeypat
db = _Session()
async def unpublished(*args: object, **kwargs: object) -> bool:
+ """
+ 在调用时报告预期的测试失败:目标签名密钥尚未发布。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises KeyServiceError: 目标签名密钥尚未发布
+ """
raise KeyServiceError('目标签名密钥尚未发布')
monkeypatch.setattr(KeyService, 'activate_key', unpublished)
@@ -109,10 +146,19 @@ async def test_key_list_exposes_only_safe_enabled_capability(monkeypatch: pytest
"""密钥列表向管理页暴露启用能力,但不阻断 OIDC 关闭时的引导。"""
class _Db:
+ """模拟当前测试所需的数据库操作。"""
+
async def rollback(self) -> None:
- pass
+ """在测试会话中处理事务回滚。"""
async def list_page(*args: object, **kwargs: object) -> tuple[list[object], int]:
+ """
+ 提供分页查询的测试结果。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 分页查询的测试结果
+ """
return [], 0
monkeypatch.setattr(OidcKeyManagementService, 'list_page', list_page)
@@ -128,5 +174,10 @@ async def list_page(*args: object, **kwargs: object) -> tuple[list[object], int]
async def _async_readiness(value: OidcReadiness) -> OidcReadiness:
- """返回可注入控制器的异步就绪状态。"""
+ """
+ 返回可注入控制器的异步就绪状态。
+
+ :param value: OIDC 协议运行时就绪快照
+ :return: OIDC 协议运行时就绪快照
+ """
return value
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_token_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_token_controller.py
index d40453583..3afcce133 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_token_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_token_controller.py
@@ -24,25 +24,43 @@
@pytest.fixture(autouse=True)
def _disable_rate_limit_for_controller_unit_tests(monkeypatch: pytest.MonkeyPatch) -> None:
- """Controller 单元测试隔离 Redis 限流实现;限流器另行测试。"""
+ """
+ 隔离控制器单元测试中的 Redis 限流实现。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
async def allow(*_args: object, **_kwargs: object) -> None:
- return None
+ """
+ 完成无需返回值的回调。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ """
+ return
monkeypatch.setattr(controller.OidcRateLimiter, 'enforce', allow)
class _Db:
- """记录 Controller 事务边界的最小异步会话替身。"""
+ """
+ 记录 Controller 事务边界的最小异步会话替身。
+
+ :ivar commits: 测试中记录的提交次数
+ :ivar rollbacks: 测试中记录的回滚次数
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``commits``, ``rollbacks``。"""
self.commits = 0
self.rollbacks = 0
async def commit(self) -> None:
+ """累加 ``commits`` 供后续断言检查。"""
self.commits += 1
async def rollback(self) -> None:
+ """累加 ``rollbacks`` 供后续断言检查。"""
self.rollbacks += 1
@@ -50,12 +68,21 @@ class _FailCommitDb(_Db):
"""提交失败并允许回滚的会话替身。"""
async def commit(self) -> None:
+ """
+ 在测试会话中处理事务提交。
+
+ :raises RuntimeError: 模拟提交事务失败
+ """
self.commits += 1
raise RuntimeError('commit failed')
def _request() -> SimpleNamespace:
- """构造携带应用 Redis 状态的请求替身。"""
+ """
+ 构造携带应用 Redis 状态的请求替身。
+
+ :return: 携带应用 Redis 状态的请求替身
+ """
return SimpleNamespace(
headers={'authorization': 'Basic test'},
app=SimpleNamespace(state=SimpleNamespace(redis=object())),
@@ -91,6 +118,13 @@ async def test_token_invalid_client_has_basic_challenge(monkeypatch: pytest.Monk
monkeypatch.setattr(controller, 'read_form', lambda request: _async(_form()))
async def invalid(*args: object, **kwargs: object) -> object:
+ """
+ 模拟此操作抛出 OAuthProtocolException 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises OAuthProtocolException: 模拟客户端认证失败
+ """
raise OAuthProtocolException('invalid_client', 'Client authentication failed', 401)
monkeypatch.setattr(TokenService, 'authenticate_client', invalid)
@@ -152,6 +186,13 @@ async def test_refresh_reuse_commits_family_before_invalid_grant(monkeypatch: py
)
async def reuse(*args: object, **kwargs: object) -> TokenResult:
+ """
+ 模拟此操作抛出 RefreshTokenReuseDetected 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RefreshTokenReuseDetected: 模拟检测到刷新令牌被重复使用
+ """
raise RefreshTokenReuseDetected
monkeypatch.setattr(TokenService, 'issue_token', reuse)
@@ -174,6 +215,13 @@ async def test_refresh_reuse_commit_failure_is_server_error_and_rolls_back(monke
)
async def reuse(*args: object, **kwargs: object) -> TokenResult:
+ """
+ 模拟此操作抛出 RefreshTokenReuseDetected 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RefreshTokenReuseDetected: 模拟检测到刷新令牌被重复使用
+ """
raise RefreshTokenReuseDetected
monkeypatch.setattr(TokenService, 'issue_token', reuse)
@@ -208,6 +256,12 @@ async def test_introspect_form_boundary_preserves_http_error(monkeypatch: pytest
db = _Db()
async def invalid_form(request: object) -> dict[str, str]:
+ """
+ 模拟此操作抛出 HTTPException 的情形。
+
+ :param request: 当前 HTTP 请求
+ :raises HTTPException: 模拟表单输入无效
+ """
raise HTTPException(status_code=status_code, detail='invalid input')
monkeypatch.setattr(controller, 'read_form', invalid_form)
@@ -231,7 +285,15 @@ async def test_revoke_and_introspect_receive_database_rsa_verification_key(monke
)
class KeyDb(_Db):
+ """提供令牌校验时的密钥查询结果。"""
+
async def scalar(self, statement: object) -> object:
+ """
+ 向调用方返回 ``record``。
+
+ :param statement: 即将执行的数据库语句
+ :return: 与当前标识匹配的记录
+ """
return record
token = jwt.encode(
@@ -265,6 +327,12 @@ async def scalar(self, statement: object) -> object:
)
async def revoke_service(*args: object, **kwargs: object) -> None:
+ """
+ 捕获撤销操作使用的验证密钥。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
captured.append(kwargs['verification_key'])
monkeypatch.setattr(controller.RevocationService, 'revoke', revoke_service)
@@ -274,6 +342,13 @@ async def revoke_service(*args: object, **kwargs: object) -> None:
captured.clear()
async def introspect_service(*args: object, **kwargs: object) -> dict[str, bool]:
+ """
+ 捕获令牌内省使用的验证密钥。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 包含 ``active`` 的数据
+ """
captured.append(kwargs['verification_key'])
return {'active': False}
@@ -284,14 +359,28 @@ async def introspect_service(*args: object, **kwargs: object) -> dict[str, bool]
def _form() -> dict[str, str]:
- """构造 Controller 测试表单。"""
+ """
+ 构造 Controller 测试表单。
+
+ :return: Controller 测试表单
+ """
return {'grant_type': 'client_credentials', 'client_id': 'c'}
def _async(value: object) -> Any:
- """构造异步测试结果。"""
+ """
+ 构造异步测试结果。
+
+ :param value: 待处理的输入值
+ :return: 异步测试结果
+ """
async def result() -> object:
+ """
+ 向调用方返回 ``value``。
+
+ :return: 为此调用预设的值
+ """
return value
return result()
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_userinfo_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_userinfo_controller.py
index 4ccb55468..4d380fe56 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_userinfo_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_userinfo_controller.py
@@ -14,7 +14,12 @@
def _request(redis: object | None = None) -> SimpleNamespace:
- """构造 UserInfo 请求替身。"""
+ """
+ 构造 UserInfo 请求替身。
+
+ :param redis: 用于缓存或发布消息的 Redis 客户端
+ :return: UserInfo 请求替身
+ """
return SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis or object())))
@@ -22,13 +27,22 @@ class _ActiveRedis:
"""模拟未命中撤销列表的 Redis。"""
async def exists(self, key: str) -> bool:
+ """
+ 在此测试分支返回 False。
+
+ :param key: 查找数据时使用的键
+ :return: 此分支的固定值 ``False``
+ """
return False
@pytest.fixture(autouse=True)
def _active_authorization(monkeypatch: pytest.MonkeyPatch) -> None:
- """为 Claims 输出测试提供明确有效的授权,撤销链路由真实数据库回归覆盖。"""
+ """
+ 为 Claims 输出测试提供明确有效的授权,撤销链路由真实数据库回归覆盖。
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
grant = SimpleNamespace(
user_id=2,
subject_id='subject-1',
@@ -203,7 +217,16 @@ async def test_userinfo_live_state_failures_are_bearer_401(monkeypatch: pytest.M
monkeypatch.setattr(service.IdentityUserDao, 'get_user', lambda *args, **kwargs: _async(user))
class _Redis:
+ """模拟测试所需的 Redis 命令。"""
+
async def exists(self, key: str) -> bool:
+ """
+ 按测试场景报告撤销记录是否存在。
+
+ :param key: 查找数据时使用的键
+ :raises RuntimeError: 模拟查询 Redis 键时连接失败
+ :return: 是否按测试场景报告撤销记录是否存在
+ """
if failure == 'redis':
raise RuntimeError('redis unavailable')
return failure == 'revoked'
@@ -239,9 +262,19 @@ async def test_userinfo_disabled_is_local_not_found(monkeypatch: pytest.MonkeyPa
def _async(value: object) -> Any:
- """构造异步测试结果。"""
+ """
+ 构造异步测试结果。
+
+ :param value: 待处理的输入值
+ :return: 异步测试结果
+ """
async def result() -> object:
+ """
+ 向调用方返回 ``value``。
+
+ :return: 为此调用预设的值
+ """
return value
return result()
diff --git a/ruoyi-fastapi-backend/tests/module_identity/dao/test_oidc_key_dao.py b/ruoyi-fastapi-backend/tests/module_identity/dao/test_oidc_key_dao.py
index 2693e02d0..4b9d80b76 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/dao/test_oidc_key_dao.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/dao/test_oidc_key_dao.py
@@ -10,7 +10,13 @@
def _key(kid: str, status: str = 'pending') -> SysOidcSigningKey:
- """构造带引用私钥材料的测试密钥。"""
+ """
+ 构造带引用私钥材料的测试密钥。
+
+ :param kid: 用于定位签名密钥的标识
+ :param status: 操作或记录所处的状态
+ :return: 带引用私钥材料的测试密钥
+ """
now = datetime.now(UTC)
return SysOidcSigningKey(
kid=kid,
@@ -38,6 +44,16 @@ def capture(
_context: Any,
_executemany: bool,
) -> None:
+ """
+ 保存调用参数供断言使用。
+
+ :param _connection: SQLAlchemy 事件传入的数据库连接
+ :param _cursor: SQLAlchemy 事件传入的游标
+ :param statement: 即将执行的数据库语句
+ :param _parameters: SQL 执行时绑定的参数
+ :param _context: 执行当前语句的上下文
+ :param _executemany: 是否执行批量 SQL
+ """
if statement.lstrip().upper().startswith(('UPDATE', 'SELECT')):
statements.append(statement.upper())
diff --git a/ruoyi-fastapi-backend/tests/module_identity/dao/test_refresh_token_dao.py b/ruoyi-fastapi-backend/tests/module_identity/dao/test_refresh_token_dao.py
index 5a92cdc3c..974c0756d 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/dao/test_refresh_token_dao.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/dao/test_refresh_token_dao.py
@@ -12,7 +12,15 @@
def _token(token_id: str, status: str, now: datetime, idle_expires_at: datetime) -> SysOAuthRefreshToken:
- """构造测试用 Refresh Token 元数据。"""
+ """
+ 构造测试用 Refresh Token 元数据。
+
+ :param token_id: 会话编号
+ :param status: 操作或记录所处的状态
+ :param now: 用于设置签发和过期时间的基准时刻
+ :param idle_expires_at: 闲置过期时间
+ :return: 测试用 Refresh Token 元数据
+ """
return SysOAuthRefreshToken(
token_id=token_id,
token_hash=f'{token_id:0<64}',
diff --git a/ruoyi-fastapi-backend/tests/module_identity/models/test_oidc_key_vo.py b/ruoyi-fastapi-backend/tests/module_identity/models/test_oidc_key_vo.py
index 4c57bb003..e860a6e22 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/models/test_oidc_key_vo.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/models/test_oidc_key_vo.py
@@ -7,6 +7,7 @@
def test_public_jwk_rejects_private_rsa_parameters() -> None:
+ """公开 JWK 拒绝 RSA 私钥参数。"""
with pytest.raises(ValidationError):
OidcKeyViewModel(
kid='key-1',
@@ -26,11 +27,13 @@ def test_public_jwk_rejects_private_rsa_parameters() -> None:
@pytest.mark.parametrize('value', ['2026-08-28 10:00:00', datetime(2026, 8, 28, 10, 0)])
def test_rotation_request_rejects_missing_timezone(value: object) -> None:
+ """轮换请求拒绝缺少时区的时间。"""
with pytest.raises(ValidationError):
OidcKeyRotateModel(kid='key-1', publishAt=value)
def test_rotation_request_normalizes_offset_to_utc() -> None:
+ """轮换请求将带偏移的时刻转换为 UTC。"""
model = OidcKeyRotateModel(kid='key-1', publishAt='2026-08-28T10:00:00+08:00')
assert model.publish_at == datetime(2026, 8, 28, 2, 0, tzinfo=UTC)
assert model.model_dump(mode='json', by_alias=True)['publishAt'] == '2026-08-28T02:00:00.000Z'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/models/test_protocol_vo.py b/ruoyi-fastapi-backend/tests/module_identity/models/test_protocol_vo.py
index de5ad6e61..d20682aa9 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/models/test_protocol_vo.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/models/test_protocol_vo.py
@@ -15,6 +15,7 @@
def test_protocol_models_emit_snake_case_and_require_oidc_nonce() -> None:
+ """协议模型使用蛇形字段名且要求 OIDC nonce。"""
challenge = generate_code_challenge(generate_code_verifier())
with pytest.raises(ValidationError):
AuthorizeRequest(
@@ -57,6 +58,7 @@ def test_protocol_enum_values_are_preserved_for_business_error_mapping() -> None
def test_token_request_code_requires_redirect_uri_and_userinfo_claims_are_allowed() -> None:
+ """授权码令牌请求必须提供重定向地址并允许用户信息声明。"""
with pytest.raises(ValidationError):
TokenRequest(grant_type='authorization_code', code='ac1.code.secret', code_verifier='a' * 43)
with pytest.raises(ValidationError):
@@ -98,6 +100,7 @@ def test_token_request_limits_untrusted_form_string_lengths() -> None:
def test_audit_query_supports_owner_and_time_filters() -> None:
+ """审计查询支持按所有者和时间过滤。"""
query = AuditPageQueryModel(
clientId='external-client',
userId=_AUDIT_USER_ID,
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_client_auth.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_client_auth.py
index 7deb08a40..9a98dbdc9 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_client_auth.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_client_auth.py
@@ -13,6 +13,7 @@
@pytest.mark.parametrize('scheme', ['Basic', 'basic', 'BASIC', 'bAsIc'])
def test_basic_credentials_decode_both_form_sides_and_colon(scheme: str) -> None:
+ """解析 Basic 凭据时解码两侧表单及冒号。"""
raw = 'client+id:secret%2Bvalue%3A2'
header = scheme + ' ' + base64.b64encode(raw.encode()).decode()
@@ -20,12 +21,14 @@ def test_basic_credentials_decode_both_form_sides_and_colon(scheme: str) -> None
def test_basic_requires_strict_standard_base64() -> None:
+ """Basic 凭据必须使用严格的标准 Base64 编码。"""
with pytest.raises(ValueError):
OidcUtil.parse_basic_credentials('Basic !!!not-base64!!!')
@pytest.mark.parametrize('prefix', ['', 'Bearer ', 'BasicX ', ' Basic ', 'Basic\t'])
def test_basic_rejects_other_schemes_and_missing_space(prefix: str) -> None:
+ """Basic 认证拒绝其他方案及缺少空格的格式。"""
header = prefix + base64.b64encode(b'client:SecretCase').decode()
with pytest.raises(ValueError):
OidcUtil.parse_basic_credentials(header)
@@ -40,6 +43,7 @@ def test_authentication_preserves_domain_error_for_malformed_basic(authorization
def test_public_and_confidential_client_policy() -> None:
+ """验证公开和机密客户端的访问策略。"""
public = {
'client_id': 'public-app',
'client_type': 'public',
@@ -71,6 +75,7 @@ def test_public_and_confidential_client_policy() -> None:
def test_client_pkce_grant_and_uri_policy() -> None:
+ """验证客户端的 PKCE、授权类型及 URI 策略。"""
with pytest.raises(ValueError):
ClientCreateModel(
client_name='public',
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_identity_dependencies.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_identity_dependencies.py
index 7d8d65b89..3283cd8aa 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_identity_dependencies.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_identity_dependencies.py
@@ -26,10 +26,23 @@ def _request(
declared_length: int | None = None,
include_content_length: bool = True,
) -> Request:
- """构造最小 URL encoded 请求。"""
+ """
+ 构造最小 URL encoded 请求。
+
+ :param body: 请求或测试样例的正文
+ :param content_type: 内容类型
+ :param declared_length: 请求头声明的内容字节数
+ :param include_content_length: 是否添加 Content-Length 请求头
+ :return: 最小 URL encoded 请求
+ """
sent = False
async def receive() -> dict[str, object]:
+ """
+ 为下游 ASGI 应用提供待接收的测试消息。
+
+ :return: 下游 ASGI 应用接收的请求消息
+ """
nonlocal sent
if sent:
return {'type': 'http.disconnect'}
@@ -95,7 +108,7 @@ async def test_read_form_rejects_malformed_percent_escape(monkeypatch: pytest.Mo
@pytest.mark.asyncio
async def test_access_key_helper_rejects_remote_key_header(monkeypatch: pytest.MonkeyPatch) -> None:
- """kid 验证只允许本地公钥,拒绝 jku/x5u/jwk/x5c。"""
+ """验证 kid 时只允许本地公钥,拒绝 jku/x5u/jwk/x5c。"""
monkeypatch.setattr(dependencies.OidcConfig, 'oidc_enabled', True)
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
token = jwt.encode(
@@ -156,6 +169,7 @@ async def test_userinfo_accepts_case_insensitive_scheme_without_changing_token(
@pytest.mark.asyncio
@pytest.mark.parametrize('prefix', ['', 'Basic ', 'BearerX ', ' Bearer ', 'Bearer\t'])
async def test_userinfo_rejects_other_schemes_and_missing_space(monkeypatch: pytest.MonkeyPatch, prefix: str) -> None:
+ """用户信息接口拒绝其他认证方案及缺少空格的格式。"""
monkeypatch.setattr(dependencies.OidcConfig, 'oidc_enabled', True)
request = Request(
{
@@ -177,6 +191,13 @@ async def test_client_dependency_invalid_client_has_basic_challenge(monkeypatch:
monkeypatch.setattr(dependencies, 'read_form', lambda request: _async({'client_id': 'client-1'}))
async def invalid(*args: object, **kwargs: object) -> object:
+ """
+ 模拟此操作抛出 OAuthProtocolException 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises OAuthProtocolException: 模拟客户端认证失败
+ """
raise OAuthProtocolException('invalid_client', 'Client authentication failed', 401)
monkeypatch.setattr(dependencies.TokenService, 'authenticate_client', invalid)
@@ -225,9 +246,19 @@ def test_invalid_token_challenge_is_standard_bearer() -> None:
def _async(value: object) -> Any:
- """构造异步测试结果。"""
+ """
+ 构造异步测试结果。
+
+ :param value: 待处理的输入值
+ :return: 异步测试结果
+ """
async def result() -> object:
+ """
+ 向调用方返回 ``value``。
+
+ :return: 为此调用预设的值
+ """
return value
return result()
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_jwt_profile.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_jwt_profile.py
index 45ec5eb05..58035a692 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_jwt_profile.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_jwt_profile.py
@@ -19,15 +19,26 @@
@pytest.fixture()
def key_pair() -> tuple[object, object]:
+ """
+ 生成用于令牌测试的临时 RSA 密钥对。
+
+ :return: 用于令牌测试的临时 RSA 密钥对
+ """
private = rsa.generate_private_key(public_exponent=65537, key_size=2048)
return private, private.public_key()
def _now() -> int:
+ """
+ 返回当前 UTC 时间戳。
+
+ :return: 当前 UTC 时间戳
+ """
return int(datetime.now(UTC).timestamp())
def test_access_profile_requires_at_jwt_and_checks_audience(key_pair: tuple[object, object]) -> None:
+ """访问令牌校验要求 at+jwt 并检查受众。"""
private, public = key_pair
now = _now()
claims = {
@@ -59,6 +70,7 @@ def test_access_profile_requires_at_jwt_and_checks_audience(key_pair: tuple[obje
def test_id_token_cannot_be_used_as_access_token_and_leeway_is_forwarded(key_pair: tuple[object, object]) -> None:
+ """拒绝将身份令牌当作访问令牌并传递允许的时间偏差。"""
private, public = key_pair
now = _now()
claims = {
@@ -87,6 +99,7 @@ def test_id_token_cannot_be_used_as_access_token_and_leeway_is_forwarded(key_pai
def test_wrong_algorithm_kid_and_numeric_types_are_rejected(key_pair: tuple[object, object]) -> None:
+ """拒绝错误的算法、密钥标识及数值类型。"""
private, public = key_pair
now = _now()
claims = {
@@ -130,6 +143,7 @@ def test_wrong_algorithm_kid_and_numeric_types_are_rejected(key_pair: tuple[obje
def test_signed_non_finite_numeric_date_is_rejected(key_pair: tuple[object, object]) -> None:
+ """拒绝签名中非有限的数值日期。"""
private, public = key_pair
now = _now()
claims = {
@@ -189,6 +203,7 @@ def test_access_profile_requires_gty_and_rejects_machine_user_field_confusion(
def test_logout_profile_requires_event_and_non_empty_sid_or_sub(key_pair: tuple[object, object]) -> None:
+ """注销令牌必须含注销事件及非空的会话或主体标识。"""
private, public = key_pair
now = _now()
claims = {
@@ -254,7 +269,6 @@ def test_logout_profile_rejects_invalid_signed_claims(
@pytest.mark.parametrize('expiry', [None, 'future', True, 0, -1])
def test_logout_profile_rejects_missing_invalid_or_expired_exp(key_pair: tuple[object, object], expiry: object) -> None:
"""接收方拒绝缺失、类型错误或过期的退出令牌。"""
-
private, public = key_pair
claims = {
'iss': 'https://issuer.example',
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_oauth_rate_limit_metadata.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_oauth_rate_limit_metadata.py
index 996a5a366..bfd585f51 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_oauth_rate_limit_metadata.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_oauth_rate_limit_metadata.py
@@ -13,7 +13,15 @@
def _route(router: Any, path: str, method: str) -> APIRoute:
- """查找指定方法的路由。"""
+ """
+ 查找指定方法的路由。
+
+ :param router: 注册端点所用的路由器
+ :param path: 要读取或处理的路径
+ :param method: 当前请求的 HTTP 方法
+ :return: 指定方法的路由
+ :raises AssertionError: 未找到给定方法和路径的路由
+ """
for route in router.routes:
if isinstance(route, APIRoute) and route.path == path and method in route.methods:
return route
@@ -21,7 +29,13 @@ def _route(router: Any, path: str, method: str) -> APIRoute:
def _rate_limit(endpoint: Callable[..., Any]) -> ApiRateLimit:
- """从 ``functools.wraps`` 生成的限流包装器闭包读取配置。"""
+ """
+ 从 ``functools.wraps`` 生成的限流包装器闭包读取配置。
+
+ :param endpoint: 接收该请求的端点
+ :return: 待处理的输入值
+ :raises AssertionError: 端点缺少限流装饰器
+ """
pending: list[Callable[..., Any]] = [endpoint]
visited: set[int] = set()
while pending:
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_oidc_messages.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_oidc_messages.py
index 432a114de..c0f266c2d 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_oidc_messages.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_oidc_messages.py
@@ -21,6 +21,7 @@
def test_protocol_exception_has_chinese_diagnostics_and_compatible_wire_description(
error: str, description: str, message: str
) -> None:
+ """协议异常提供中文诊断并保留兼容的协议描述。"""
exception = OAuthProtocolException(error, description)
assert str(exception) == exception.message == message
@@ -28,6 +29,7 @@ def test_protocol_exception_has_chinese_diagnostics_and_compatible_wire_descript
def test_code_only_exception_keeps_optional_protocol_description_absent() -> None:
+ """只有错误码的异常省略可选的协议描述。"""
exception = OAuthProtocolException('invalid_scope')
assert str(exception) == '请求的权限范围无效'
@@ -35,6 +37,7 @@ def test_code_only_exception_keeps_optional_protocol_description_absent() -> Non
def test_chinese_interaction_message_keeps_redirect_protocol_ascii_and_state_unchanged() -> None:
+ """中文交互消息保留跳转参数的 ASCII 编码和原始状态。"""
app = FastAPI()
handle_exception(app)
interaction = OidcInteractionException(
@@ -46,7 +49,9 @@ def test_chinese_interaction_message_keeps_redirect_protocol_ascii_and_state_unc
redirect_uri_verified=True,
)
- @app.get('/authorize')
+ @app.get(
+ '/authorize', summary='模拟需要交互的授权', description='返回认证交互的协议错误,用于验证跳转参数与状态编码。'
+ )
async def authorize() -> None:
raise interaction.as_protocol_exception()
@@ -68,10 +73,11 @@ async def authorize() -> None:
@pytest.mark.parametrize('description', ['内部诊断:private-marker', 'dependency\nprivate-marker'])
def test_unknown_diagnostic_is_not_exposed_as_protocol_description(description: str) -> None:
+ """未知诊断信息不会作为协议描述公开。"""
app = FastAPI()
handle_exception(app)
- @app.get('/token')
+ @app.get('/token', summary='模拟令牌服务错误', description='触发服务端协议错误,用于验证对外返回的诊断信息。')
async def token() -> None:
raise OAuthProtocolException('server_error', description, status_code=503)
@@ -85,6 +91,7 @@ async def token() -> None:
def test_revocation_exception_localizes_diagnostics_without_changing_protocol_fields() -> None:
+ """撤销异常本地化诊断并保留协议字段。"""
exception = RevocationError('invalid_client', 'Client authentication failed')
assert str(exception) == exception.message == '客户端认证失败'
@@ -93,6 +100,7 @@ def test_revocation_exception_localizes_diagnostics_without_changing_protocol_fi
def test_backchannel_exception_keeps_audit_code_independent_from_chinese_diagnostics() -> None:
+ """后通道异常的审计码独立于中文诊断。"""
exception = PermanentBackchannelError('invalid retry payload', '后端退出通知重试载荷无效')
assert str(exception) == exception.message == '后端退出通知重试载荷无效'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_opaque_token.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_opaque_token.py
index 10aba6124..434321bca 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_opaque_token.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_opaque_token.py
@@ -18,6 +18,7 @@
((generate_authorization_code, 'ac1'), (generate_refresh_token, 'rt1'), (generate_sso_cookie, 'ss1')),
)
def test_typed_tokens_are_random_and_verifiable(factory: Callable[[], str], prefix: str) -> None:
+ """按类型签发的令牌具有随机性且可验证。"""
pepper = 'p' * 32
token = factory()
parsed = parse_opaque_token(token, expected_prefix=prefix)
@@ -29,6 +30,7 @@ def test_typed_tokens_are_random_and_verifiable(factory: Callable[[], str], pref
def test_token_id_alone_is_not_a_credential() -> None:
+ """仅凭令牌标识不能进行认证。"""
token = generate_refresh_token()
parsed = parse_opaque_token(token)
pepper = 'p' * 32
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_pkce.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_pkce.py
index 98aa429a0..90e37d9cd 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_pkce.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_pkce.py
@@ -12,6 +12,7 @@
def test_s256_round_trip_and_mismatch() -> None:
+ """验证 S256 的匹配和不匹配情形。"""
verifier = generate_code_verifier()
challenge = generate_code_challenge(verifier)
@@ -22,6 +23,7 @@ def test_s256_round_trip_and_mismatch() -> None:
def test_plain_and_invalid_lengths_are_rejected() -> None:
+ """拒绝明文挑战和无效长度。"""
with pytest.raises(PkceError):
verify_code_challenge('a' * 43, 'a' * 43, method='plain')
with pytest.raises(ValueError):
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_protocol_exception_handler.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_protocol_exception_handler.py
index e7a37005c..cc81928e3 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_protocol_exception_handler.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_protocol_exception_handler.py
@@ -6,10 +6,17 @@
def _client() -> TestClient:
+ """
+ 创建启用了测试配置的请求客户端。
+
+ :return: 启用了测试配置的请求客户端
+ """
app = FastAPI()
handle_exception(app)
- @app.get('/invalid-client')
+ @app.get(
+ '/invalid-client', summary='模拟客户端认证失败', description='返回 OAuth 客户端认证失败的错误和认证响应头。'
+ )
async def invalid_client() -> None:
raise OAuthProtocolException(
'invalid_client',
@@ -18,7 +25,7 @@ async def invalid_client() -> None:
headers={'Cache-Control': 'public, max-age=3600', 'Pragma': 'cache'},
)
- @app.get('/authorize-error')
+ @app.get('/authorize-error', summary='模拟授权被拒绝', description='向客户端回调地址返回授权错误并保留状态参数。')
async def authorize_error() -> None:
raise OAuthProtocolException(
'access_denied',
@@ -31,7 +38,11 @@ async def authorize_error() -> None:
issuer='https://auth.example.com',
)
- @app.get('/invalid-redirect')
+ @app.get(
+ '/invalid-redirect',
+ summary='验证无效回调地址',
+ description='对含片段的回调地址触发授权错误,检查错误响应的去向。',
+ )
async def invalid_redirect() -> None:
raise OAuthProtocolException(
'access_denied',
@@ -39,7 +50,7 @@ async def invalid_redirect() -> None:
redirect_uri_verified=True,
)
- @app.get('/interaction')
+ @app.get('/interaction', summary='模拟认证交互过期', description='触发交互过期错误,用于核对协议错误响应。')
async def interaction() -> None:
raise OidcInteractionException('interaction-1', 'Interaction expired')
@@ -47,6 +58,7 @@ async def interaction() -> None:
def test_invalid_client_uses_standard_oauth_json() -> None:
+ """无效客户端按标准 OAuth JSON 返回。"""
response = _client().get('/invalid-client')
assert response.status_code == status.HTTP_401_UNAUTHORIZED
@@ -58,6 +70,7 @@ def test_invalid_client_uses_standard_oauth_json() -> None:
def test_verified_redirect_replaces_protocol_parameters_and_preserves_application_query() -> None:
+ """已验证的重定向替换协议参数并保留业务查询。"""
response = _client().get('/authorize-error', follow_redirects=False)
assert response.status_code == status.HTTP_303_SEE_OTHER
@@ -70,6 +83,7 @@ def test_verified_redirect_replaces_protocol_parameters_and_preserves_applicatio
def test_invalid_validated_redirect_fails_closed_locally() -> None:
+ """已验证的重定向失效时在本地拒绝请求。"""
response = _client().get('/invalid-redirect', follow_redirects=False)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@@ -78,6 +92,7 @@ def test_invalid_validated_redirect_fails_closed_locally() -> None:
def test_interaction_exception_keeps_business_response_boundary() -> None:
+ """交互异常使用业务响应约定。"""
response = _client().get('/interaction')
assert response.status_code == status.HTTP_200_OK
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_redis_keys.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_redis_keys.py
index 29b62aa34..2e0e66ce3 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_redis_keys.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_redis_keys.py
@@ -7,6 +7,7 @@
def test_oidc_keys_are_isolated_from_legacy_access_token_namespace() -> None:
+ """OIDC 密钥与旧访问令牌的命名空间隔离。"""
keys = [
OidcRedisKey.interaction('interaction-id'),
OidcRedisKey.authorization_code('code-id'),
@@ -19,6 +20,7 @@ def test_oidc_keys_are_isolated_from_legacy_access_token_namespace() -> None:
def test_sensitive_identifiers_use_independent_32_byte_pepper() -> None:
+ """敏感标识使用独立的 32 字节 pepper。"""
pepper = 'independent-pepper-value-' + 'x' * 8
digest = OidcUtil.hash_sensitive_identifier('user@example.com', pepper)
@@ -34,11 +36,13 @@ def test_sensitive_identifiers_use_independent_32_byte_pepper() -> None:
@pytest.mark.parametrize('value', ['../escape', 'space value', 'a' * 129])
def test_unsafe_key_components_are_rejected(value: str) -> None:
+ """拒绝不安全的键组成部分。"""
with pytest.raises(ValueError):
OidcRedisKey.interaction(value)
def test_digest_components_must_be_sha256_hex() -> None:
+ """摘要组件必须使用 SHA-256 十六进制格式。"""
with pytest.raises(ValueError):
OidcRedisKey.sso_cookie('not-a-digest')
with pytest.raises(TypeError):
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_audit_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_audit_service.py
index 920cb424c..dc574ed56 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_audit_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_audit_service.py
@@ -27,7 +27,11 @@
@pytest_asyncio.fixture
async def audit_session() -> AsyncSession:
- """创建只包含审计表的真实 SQLite 会话。"""
+ """
+ 创建只包含审计表的真实 SQLite 会话。
+
+ :yield: 只包含审计表的真实 SQLite 会话
+ """
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
async with engine.begin() as connection:
await connection.run_sync(
@@ -149,10 +153,24 @@ async def test_audit_admin_reads_project_safe_models_and_export(monkeypatch: pyt
calls: list[dict[str, object]] = []
async def list_admin_page(*args: object, **kwargs: object) -> list[object]:
+ """
+ 记录审计分页查询参数并返回样例记录。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 样例记录
+ """
calls.append(kwargs)
return [row]
async def count_admin(*args: object, **kwargs: object) -> int:
+ """
+ 返回固定值 ``1``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``1``
+ """
return 1
monkeypatch.setattr(OAuthAuditDao, 'list_admin_page', list_admin_page)
@@ -213,13 +231,28 @@ async def test_interaction_failure_audit_rolls_back_and_wraps_failure(monkeypatc
"""交互失败审计保持双重回滚和统一异常包装语义。"""
class _Db:
+ """
+ 模拟当前测试所需的数据库操作。
+
+ :ivar rollbacks: 测试中记录的回滚次数
+ """
+
def __init__(self) -> None:
+ """初始化测试夹具的 ``rollbacks``。"""
self.rollbacks = 0
async def rollback(self) -> None:
+ """累加 ``rollbacks`` 供后续断言检查。"""
self.rollbacks += 1
async def fail(*args: object, **kwargs: object) -> object:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RuntimeError: 模拟审计服务不可用
+ """
raise RuntimeError('audit unavailable')
monkeypatch.setattr(AuditService, 'record_independent', fail)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_authentication_regressions.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_authentication_regressions.py
index ee5cd9809..145d4c135 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_authentication_regressions.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_authentication_regressions.py
@@ -67,8 +67,13 @@
@pytest_asyncio.fixture
async def auth_flow(data_session: AsyncSession, monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
- """配置一个业务客户端、机器客户端、资源服务和真实用户会话。"""
+ """
+ 配置一个业务客户端、机器客户端、资源服务和真实用户会话。
+ :param data_session: 测试使用的数据库会话
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: ``SimpleNamespace`` 实例
+ """
now = TimezoneUtil.utc_now().replace(microsecond=0)
monkeypatch.setattr(TimezoneUtil, 'utc_now', staticmethod(lambda: now))
for name, value in {
@@ -217,8 +222,13 @@ async def auth_flow(data_session: AsyncSession, monkeypatch: pytest.MonkeyPatch)
def _authorize_request(flow: SimpleNamespace, *, offline: bool = False) -> dict[str, str]:
- """构造携带 PKCE 和 Resource 的授权请求。"""
+ """
+ 构造携带 PKCE 和 Resource 的授权请求。
+ :param flow: 驱动当前场景的业务流程
+ :param offline: 是否使用离线资源
+ :return: 携带 PKCE 和 Resource 的授权请求
+ """
return {
'client_id': flow.app.client_id,
'redirect_uri': 'https://app.example.com/callback',
@@ -234,8 +244,14 @@ def _authorize_request(flow: SimpleNamespace, *, offline: bool = False) -> dict[
async def _user_token(
flow: SimpleNamespace, *, remember: bool = False, offline: bool = False
) -> tuple[TokenResult, SysOAuthGrant | None]:
- """通过真实同意和授权码流程签发用户令牌。"""
-
+ """
+ 通过真实同意和授权码流程签发用户令牌。
+
+ :param flow: 驱动当前场景的业务流程
+ :param remember: 是否记住本次选择
+ :param offline: 是否使用离线资源
+ :return: 已签发的用户令牌与对应的授权记录
+ """
request = AuthorizeRequest(**_authorize_request(flow, offline=offline))
context = await AuthorizationService.validate_request(flow.db, request)
consent = await ConsentService.submit_consent(
@@ -284,8 +300,12 @@ async def _user_token(
async def _machine_token(flow: SimpleNamespace) -> TokenResult:
- """为已认证的机器 Client 签发 Resource 访问令牌。"""
+ """
+ 为已认证的机器 Client 签发 Resource 访问令牌。
+ :param flow: 驱动当前场景的业务流程
+ :return: 机器客户端凭据换取的资源访问令牌
+ """
return await TokenService.client_credentials(
flow.db,
{'grant_type': 'client_credentials', 'scope': 'api.read', 'resource': flow.resource.audience},
@@ -297,8 +317,13 @@ async def _machine_token(flow: SimpleNamespace) -> TokenResult:
async def _introspect(flow: SimpleNamespace, token: str) -> dict[str, object]:
- """使用独立 Resource Client 查询令牌的实时状态。"""
+ """
+ 使用独立 Resource Client 查询令牌的实时状态。
+ :param flow: 驱动当前场景的业务流程
+ :param token: 用于身份验证或授权的令牌
+ :return: 资源客户端读取的令牌内省结果
+ """
return await IntrospectionService.introspect(
flow.db,
flow.redis,
@@ -310,8 +335,13 @@ async def _introspect(flow: SimpleNamespace, token: str) -> dict[str, object]:
def _claims(flow: SimpleNamespace, token: str) -> dict[str, object]:
- """验证 Access Token 的签名、Issuer 和 Resource Audience。"""
+ """
+ 验证 Access Token 的签名、Issuer 和 Resource Audience。
+ :param flow: 驱动当前场景的业务流程
+ :param token: 用于身份验证或授权的令牌
+ :return: 通过签名、签发者和受众校验的声明
+ """
return decode_access_token(
token,
verification_key=flow.signer.public_key(),
@@ -321,8 +351,13 @@ def _claims(flow: SimpleNamespace, token: str) -> dict[str, object]:
def _sign(flow: SimpleNamespace, claims: dict[str, object]) -> str:
- """签署指定 Claims,用于验证内省对授权来源的校验。"""
+ """
+ 签署指定 Claims,用于验证内省对授权来源的校验。
+ :param flow: 驱动当前场景的业务流程
+ :param claims: 令牌携带的身份声明
+ :return: 使用测试私钥签名的 JWT
+ """
return jwt.encode(
claims,
flow.signer,
@@ -334,7 +369,6 @@ def _sign(flow: SimpleNamespace, claims: dict[str, object]) -> str:
@pytest.mark.asyncio
async def test_one_time_consent_has_revocable_grant_without_remembering_consent(auth_flow: SimpleNamespace) -> None:
"""一次性同意有可撤销记录,但不授予离线续期和后续免确认资格。"""
-
token, grant = await _user_token(auth_flow)
assert grant is not None and token.refresh_token is None
assert grant.remembered_scopes == [] and grant.remembered_resources == []
@@ -356,7 +390,6 @@ async def test_one_time_consent_still_checks_current_security_state(
invalid_state: str,
) -> None:
"""一次性同意的 Access Token 仍受当前授权策略和用户安全状态约束。"""
-
token, _ = await _user_token(auth_flow)
assert (await _introspect(auth_flow, token.access_token))['active'] is True
if invalid_state == 'policy':
@@ -383,7 +416,6 @@ async def test_saved_grant_revocation_cannot_be_bypassed_by_a_later_grant(
offline: bool,
) -> None:
"""管理端撤销各类授权后,新授权不能恢复旧令牌,其他用户会话不受影响。"""
-
token, grant = await _user_token(auth_flow, remember=remember, offline=offline)
assert grant is not None
if offline:
@@ -438,7 +470,6 @@ async def test_legacy_user_tokens_without_grant_binding_require_reauthorization(
auth_flow: SimpleNamespace, remember: bool
) -> None:
"""旧令牌没有具体 Grant 绑定时拒绝访问,即使用户有其他有效授权。"""
-
token, _ = await _user_token(auth_flow, remember=remember)
claims = _claims(auth_flow, token.access_token)
claims.pop('grant_id', None)
@@ -456,7 +487,6 @@ async def test_incomplete_or_invalid_authorization_context_is_inactive(
invalid_context: str,
) -> None:
"""授权来源 Claims 缺失或不合法时,内省返回 inactive。"""
-
token, _ = await _user_token(auth_flow)
claims = _claims(auth_flow, token.access_token)
claims.update(grant_id=None, client_policy_version=auth_flow.app.policy_version)
@@ -487,7 +517,6 @@ async def test_machine_token_honours_client_resource_and_platform_ttl(
expected: int,
) -> None:
"""机器令牌的响应有效期和 JWT 有效期均遵守 Client、Resource 及平台上限。"""
-
auth_flow.machine.access_token_ttl_seconds = client_ttl
auth_flow.resource.access_token_ttl_seconds = resource_ttl
await auth_flow.db.commit()
@@ -501,7 +530,6 @@ async def test_machine_token_honours_client_resource_and_platform_ttl(
@pytest.mark.parametrize('legacy', [False, True])
async def test_scope_disable_immediately_invalidates_machine_tokens(auth_flow: SimpleNamespace, legacy: bool) -> None:
"""Scope 禁用立即使机器令牌失效,新版令牌在 Scope 恢复后仍受策略版本约束。"""
-
token = (await _machine_token(auth_flow)).access_token
if legacy:
claims = _claims(auth_flow, token)
@@ -531,7 +559,6 @@ async def test_scope_disable_immediately_invalidates_machine_tokens(auth_flow: S
@pytest.mark.parametrize('change', ['unbind', 'identity_scope', 'different_resource'])
async def test_machine_tokens_recheck_current_scope_bindings(auth_flow: SimpleNamespace, change: str) -> None:
"""机器令牌内省重新检查 Scope 的 Client 绑定、类型和所属 Resource。"""
-
token = await _machine_token(auth_flow)
assert (await _introspect(auth_flow, token.access_token))['active'] is True
if change == 'unbind':
@@ -552,7 +579,6 @@ async def test_authorize_slides_idle_timeout_but_never_extends_absolute_expiry(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""授权请求更新 SSO 空闲期限,并保留 Session 的绝对过期上限。"""
-
flow = auth_flow
absolute = flow.now + timedelta(minutes=40)
flow.session.absolute_expires_at = absolute
@@ -587,7 +613,6 @@ async def test_login_cookie_persistence_survives_forced_password_change(
force_password_change: bool,
) -> None:
"""普通登录及强制改密后的 Cookie 持久化行为均遵守保持登录选项。"""
-
flow = auth_flow
context = await AuthorizationService.validate_request(flow.db, AuthorizeRequest(**_authorize_request(flow)))
created = await InteractionService.create(flow.redis, context.to_internal_payload('cookie-test'), pepper=_PEPPER)
@@ -650,7 +675,6 @@ async def test_login_cookie_persistence_survives_forced_password_change(
@pytest.mark.parametrize('offline', [False, True])
async def test_block_and_unblock_require_new_authorization(auth_flow: SimpleNamespace, offline: bool) -> None:
"""禁止访问阻断当前令牌和授权确认,解除后只有新授权可以访问。"""
-
flow = auth_flow
token, grant = await _user_token(flow, offline=offline)
client_id, user_id, grant_id = flow.app.client_id, flow.user.user_id, grant.grant_id
@@ -724,7 +748,6 @@ async def test_block_and_unblock_require_new_authorization(auth_flow: SimpleName
@pytest.mark.asyncio
async def test_block_rejects_authorize_before_showing_consent(auth_flow: SimpleNamespace) -> None:
"""已有 SSO 时,禁止访问在授权入口直接拒绝,不依赖同意页或令牌端点兜底。"""
-
flow = auth_flow
raw, cookie = _authorize_request(flow), flow.cookie
await OAuthSessionManagementService.set_access(
@@ -738,7 +761,6 @@ async def test_block_rejects_authorize_before_showing_consent(auth_flow: SimpleN
@pytest.mark.asyncio
async def test_pre_authorized_flow_also_creates_revocable_grant(auth_flow: SimpleNamespace) -> None:
"""可信应用跳过确认页面时,授权码仍绑定后台可撤销的具体 Grant。"""
-
flow = auth_flow
flow.app.require_consent = 0
await flow.db.commit()
@@ -758,7 +780,6 @@ async def test_pre_authorized_flow_also_creates_revocable_grant(auth_flow: Simpl
@pytest.mark.asyncio
async def test_batch_revoke_covers_all_grants_for_selected_user_client(auth_flow: SimpleNamespace) -> None:
"""同一用户应用的重复历史有效记录一并撤销,其他用户及机器访问不受影响。"""
-
flow = auth_flow
token, grant = await _user_token(flow, remember=True)
duplicate = SysOAuthGrant(
@@ -803,7 +824,6 @@ async def test_failed_access_policy_audit_rolls_back_revocation(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""禁止操作的审计失败时,访问策略与令牌撤销必须同时回滚。"""
-
flow = auth_flow
token, grant = await _user_token(flow)
user_id, client_pk, client_id = flow.user.user_id, flow.app.client_pk, flow.app.client_id
@@ -821,7 +841,6 @@ async def test_failed_access_policy_audit_rolls_back_revocation(
@pytest.mark.parametrize('confirm', [False, True])
async def test_interactive_completion_binds_a_grant(auth_flow: SimpleNamespace, confirm: bool) -> None:
"""登录后直接完成与确认后完成两条交互路径都绑定可撤销授权。"""
-
flow = auth_flow
flow.app.require_consent = int(confirm)
await flow.db.commit()
@@ -854,7 +873,6 @@ async def test_interactive_completion_binds_a_grant(auth_flow: SimpleNamespace,
@pytest.mark.asyncio
async def test_expired_grant_is_not_reactivated_by_new_consent(auth_flow: SimpleNamespace) -> None:
"""授权先于 Access Token 过期后,再次同意也不能恢复旧令牌。"""
-
flow = auth_flow
old_token, old_grant = await _user_token(flow)
old_grant.expires_at = flow.now - timedelta(seconds=1)
@@ -874,7 +892,6 @@ async def test_revocation_between_consent_and_completion_prevents_code(
blocked: bool,
) -> None:
"""同意后、签码前发生撤销或禁止,不得继续发码或复用授权记录。"""
-
flow = auth_flow
context = await AuthorizationService.validate_request(flow.db, AuthorizeRequest(**_authorize_request(flow)))
payload = context.to_internal_payload('pending')
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_code_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_code_service.py
index d0b3939ae..9af7b23d8 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_code_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_code_service.py
@@ -15,7 +15,12 @@
def _payload(**overrides: object) -> dict[str, object]:
- """构造服务端授权码白名单载荷。"""
+ """
+ 构造服务端授权码白名单载荷。
+
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 服务端授权码白名单载荷
+ """
value: dict[str, object] = {
'clientPk': 1001,
'redirectUri': 'https://portal.example/callback',
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_service.py
index 710e638df..8aa1cbfc3 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_service.py
@@ -24,7 +24,12 @@
def _request(**overrides: object) -> AuthorizeRequest:
- """构造最小有效授权请求。"""
+ """
+ 构造最小有效授权请求。
+
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 最小有效授权请求
+ """
values: dict[str, object] = {
'response_type': 'code',
'client_id': 'authorization-client',
@@ -40,7 +45,12 @@ def _request(**overrides: object) -> AuthorizeRequest:
async def _seed_authorization_data(db: AsyncSession, *, second_resource_scope: bool = False) -> None:
- """写入授权服务测试所需的 Client、URI、Scope 和 Resource。"""
+ """
+ 写入授权服务测试所需的 Client、URI、Scope 和 Resource。
+
+ :param db: 当前操作使用的数据库会话
+ :param second_resource_scope: 第二个资源要求的权限范围
+ """
client = SysOAuthClient(
client_pk=_CLIENT_PK,
client_id='authorization-client',
@@ -151,7 +161,11 @@ async def _seed_authorization_data(db: AsyncSession, *, second_resource_scope: b
@pytest.fixture
def oidc_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
- """为服务测试开启安全的 OIDC 配置。"""
+ """
+ 为服务测试开启安全的 OIDC 配置。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
monkeypatch.setattr(OidcConfig, 'oidc_enabled', True)
monkeypatch.setattr(OidcConfig, 'oidc_pkce_methods', 'S256')
monkeypatch.setattr(OidcConfig, 'oidc_issuer', 'https://auth.example.com')
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_claim_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_claim_service.py
index 4dfa0cef0..9dea65987 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_claim_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_claim_service.py
@@ -56,7 +56,7 @@ def test_claim_builder_does_not_leak_local_identity_or_unapproved_contact() -> N
def test_openid_fails_closed_when_subject_or_sub_policy_is_missing(
user: dict[str, object], policy: dict[str, object], resource: list[str]
) -> None:
- """openid 请求缺少稳定 Subject 或 sub 策略时不得静默生成 Claims。"""
+ """验证 openid 请求缺少稳定 Subject 或 sub 策略时不得静默生成 Claims。"""
with pytest.raises(OAuthProtocolException):
ClaimService.build_claims(user, {'openid'}, policy, resource)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_consent_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_consent_service.py
index 0f8ab3b76..3b84327f9 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_consent_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_consent_service.py
@@ -21,7 +21,13 @@
def _context(*, prompt: str | None = None, trusted_client: int = 0) -> AuthorizationContext:
- """构造同意服务所需的已验证上下文。"""
+ """
+ 构造同意服务所需的已验证上下文。
+
+ :param prompt: 客户端要求的登录或授权交互方式
+ :param trusted_client: 是否为受信任客户端
+ :return: 同意服务所需的已验证上下文
+ """
client = ClientSnapshot(
client_pk=8001,
client_id='consent-client',
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_credential_authentication_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_credential_authentication_service.py
index 97fde5bc4..c996bb422 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_credential_authentication_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_credential_authentication_service.py
@@ -22,9 +22,24 @@
class _Redis:
- """记录认证服务访问的 Redis 最小异步替身。"""
+ """
+ 记录认证服务访问的 Redis 最小异步替身。
+
+ :ivar values: 当前处理的值集合
+ :ivar eval_values: 用于模拟 Redis 脚本结果的值
+ :ivar get_calls: 记录 ``get`` 的调用情况
+ :ivar set_calls: 记录 ``set`` 的调用情况
+ :ivar delete_calls: 记录 ``delete`` 的调用情况
+ :ivar eval_calls: 记录 ``eval`` 的调用情况
+ """
def __init__(self, values: dict[str, object] | None = None, eval_values: list[object] | None = None) -> None:
+ """
+ 初始化测试夹具的 ``values``, ``eval_values``, ``get_calls``, ``set_calls``。
+
+ :param values: 当前处理的值集合
+ :param eval_values: 用于模拟 Redis 脚本结果的值
+ """
self.values = values or {}
self.eval_values = list(eval_values or [])
self.get_calls: list[str] = []
@@ -33,18 +48,44 @@ def __init__(self, values: dict[str, object] | None = None, eval_values: list[ob
self.eval_calls: list[tuple[str, int, tuple[object, ...]]] = []
async def get(self, key: str) -> object:
+ """
+ 读取测试存储中的指定键。
+
+ :param key: 查找数据时使用的键
+ :return: 测试存储中的指定键
+ """
self.get_calls.append(key)
return self.values.get(key)
async def set(self, key: str, value: object, *, ex: object) -> None:
+ """
+ 写入测试缓存键并设置过期时间。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :param ex: 捕获到的异常实例
+ """
self.values[key] = value
self.set_calls.append((key, value, ex))
async def delete(self, key: str) -> None:
+ """
+ 删除测试缓存项及其过期状态。
+
+ :param key: 查找数据时使用的键
+ """
self.values.pop(key, None)
self.delete_calls.append(key)
async def eval(self, script: str, count: int, *keys_and_args: object) -> object:
+ """
+ 按测试约定模拟 Redis 脚本的执行。
+
+ :param script: 需要运行的脚本
+ :param count: 本次处理或预期的数量
+ :param keys_and_args: 调用方传入的其余位置参数
+ :return: 预设 Redis 脚本结果,队列为空时返回空值
+ """
self.eval_calls.append((script, count, keys_and_args))
return self.eval_values.pop(0) if self.eval_values else None
@@ -53,6 +94,14 @@ class _AtomicFailureRedis(_Redis):
"""按 OIDC 错误 Lua 脚本语义执行 INCR、锁定和锁前检查。"""
async def eval(self, script: str, count: int, *keys_and_args: object) -> object:
+ """
+ 按测试约定模拟 Redis 脚本的执行。
+
+ :param script: 需要运行的脚本
+ :param count: 本次处理或预期的数量
+ :param keys_and_args: 调用方传入的其余位置参数
+ :return: 脚本的预设结果或对应的错误状态码
+ """
self.eval_calls.append((script, count, keys_and_args))
if "redis.call('incr'" not in script:
return self.eval_values.pop(0) if self.eval_values else None
@@ -69,6 +118,13 @@ async def eval(self, script: str, count: int, *keys_and_args: object) -> object:
def _request(redis: _Redis, *, host: str = '127.0.0.1') -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param redis: 模拟测试所需的 Redis 命令
+ :param host: 连接目标或插件宿主上下文
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(
app=SimpleNamespace(state=SimpleNamespace(redis=redis)),
client=SimpleNamespace(host=host),
@@ -77,6 +133,14 @@ def _request(redis: _Redis, *, host: str = '127.0.0.1') -> SimpleNamespace:
def _user(user_name: str = 'alice', *, status: str = '0', update_date: object = None) -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param user_name: 当前用户的账号名称
+ :param status: 操作或记录所处的状态
+ :param update_date: 记录最近一次更新的时间
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(
user_id=7,
user_name=user_name,
@@ -88,6 +152,7 @@ def _user(user_name: str = 'alice', *, status: str = '0', update_date: object =
@pytest.mark.asyncio
async def test_oidc_unknown_user_and_wrong_password_are_equivalent_and_dummy_verify_runs() -> None:
+ """OIDC 对未知用户和错误密码给出相同响应并执行虚拟校验。"""
redis = _Redis()
with (
patch.object(OidcConfig, 'oidc_token_hash_pepper', 'p' * 32),
@@ -121,6 +186,7 @@ async def test_oidc_unknown_user_and_wrong_password_are_equivalent_and_dummy_ver
@pytest.mark.asyncio
async def test_oidc_captcha_is_atomically_consumed_and_success_does_not_write_legacy_token_key() -> None:
+ """OIDC 原子消费验证码且成功时不写旧令牌键。"""
redis = _Redis(eval_values=['1234', None])
user = _user()
with (
@@ -160,6 +226,7 @@ async def test_oidc_captcha_is_atomically_consumed_and_success_does_not_write_le
@pytest.mark.asyncio
async def test_oidc_disabled_user_is_rejected() -> None:
+ """OIDC 拒绝已禁用用户。"""
status, expected_reason = '1', 'user_disabled'
redis = _Redis()
with (
@@ -177,6 +244,7 @@ async def test_oidc_disabled_user_is_rejected() -> None:
@pytest.mark.asyncio
async def test_oidc_initial_and_expired_password_flags_handle_naive_and_aware_dates() -> None:
+ """OIDC 的初始和过期密码标志兼容有无时区的日期。"""
redis = _Redis(
{
'sys_config:sys.account.initPasswordModify': '1',
@@ -200,6 +268,7 @@ async def test_oidc_initial_and_expired_password_flags_handle_naive_and_aware_da
@pytest.mark.asyncio
async def test_oidc_expired_aware_password_is_reported_without_datetime_error() -> None:
+ """OIDC 能识别带时区的过期密码。"""
redis = _Redis({'sys_config:sys.account.passwordValidateDays': '30'})
old_date = datetime.now(UTC) - timedelta(days=31)
with (
@@ -219,6 +288,7 @@ async def test_oidc_expired_aware_password_is_reported_without_datetime_error()
@pytest.mark.asyncio
async def test_oidc_hashed_error_state_locks_without_plain_username() -> None:
+ """OIDC 使用哈希错误状态锁定账号而不保留明文用户名。"""
redis = _Redis(eval_values=[-1])
with (
patch.object(OidcConfig, 'oidc_token_hash_pepper', 'p' * 32),
@@ -238,6 +308,7 @@ async def test_oidc_hashed_error_state_locks_without_plain_username() -> None:
@pytest.mark.asyncio
async def test_oidc_error_counter_uses_atomic_incr_expire_and_lock_script() -> None:
+ """OIDC 错误计数通过原子脚本递增、设置过期并加锁。"""
redis = _Redis(eval_values=[1])
with (
patch.object(OidcConfig, 'oidc_token_hash_pepper', 'p' * 32),
@@ -277,6 +348,7 @@ async def test_oidc_failure_script_stays_locked_after_atomic_lock_transition() -
@pytest.mark.asyncio
async def test_legacy_success_and_wrong_password_keep_legacy_keys_and_messages() -> None:
+ """旧版成功和密码错误的流程保留原有键和消息。"""
user = _user()
redis = _Redis()
with (
@@ -311,6 +383,7 @@ async def test_legacy_success_and_wrong_password_keep_legacy_keys_and_messages()
@pytest.mark.asyncio
async def test_legacy_unknown_user_keeps_message_and_does_not_create_error_key() -> None:
+ """旧版未知用户保留原提示且不创建错误键。"""
redis = _Redis()
with (
patch(
@@ -328,6 +401,7 @@ async def test_legacy_unknown_user_keeps_message_and_does_not_create_error_key()
@pytest.mark.asyncio
async def test_legacy_lock_captcha_and_blacklist_keep_original_messages_and_keys() -> None:
+ """旧版锁定、验证码和黑名单流程保留原消息及键。"""
lock_redis = _Redis({'account_lock:alice': 'alice'})
with (
patch(
@@ -377,6 +451,7 @@ async def test_legacy_lock_captcha_and_blacklist_keep_original_messages_and_keys
@pytest.mark.asyncio
async def test_legacy_service_delegates_and_maps_original_login_exception() -> None:
+ """旧版服务委托登录并映射原有登录异常。"""
login_user = UserLogin(userName='alice', password='wrong', captchaEnabled=False)
request = _request(_Redis())
with (
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_security_event_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_security_event_service.py
index 12b4c6b62..807f5bb6c 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_security_event_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_security_event_service.py
@@ -24,7 +24,11 @@
@pytest_asyncio.fixture
async def security_session() -> AsyncSession:
- """创建身份安全事件涉及表的真实异步数据库会话。"""
+ """
+ 创建身份安全事件涉及表的真实异步数据库会话。
+
+ :yield: 身份安全事件涉及表的真实异步数据库会话
+ """
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
tables = [
SysUser.__table__,
@@ -43,7 +47,13 @@ async def security_session() -> AsyncSession:
async def _seed_user(session: AsyncSession, user_id: int, *, with_subject: bool = True) -> None:
- """写入一个用户及其可撤销的 Session、Refresh。"""
+ """
+ 写入一个用户及其可撤销的 Session、Refresh。
+
+ :param session: 当前操作共用的会话
+ :param user_id: 用户的唯一标识
+ :param with_subject: 是否为样例关联身份主体
+ """
session.add(SysUser(user_id=user_id, user_name=f'user-{user_id}', nick_name='User'))
if with_subject:
session.add(
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_subject_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_subject_service.py
index dbf0bd3c6..af6ef094e 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_subject_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_subject_service.py
@@ -22,7 +22,12 @@
@pytest_asyncio.fixture
async def service_session(tmp_path: Path) -> AsyncSession:
- """创建只包含主体服务所需表的真实 SQLite 会话。"""
+ """
+ 创建只包含主体服务所需表的真实 SQLite 会话。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :yield: 只包含主体服务所需表的真实 SQLite 会话
+ """
engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "subject-service.sqlite3"}')
tables = [SysUser.__table__, SysIdentitySubject.__table__, SysOAuthAuditLog.__table__]
async with engine.begin() as connection:
@@ -99,6 +104,11 @@ async def test_independent_audit_writer_survives_main_transaction_rollback(servi
factory = async_sessionmaker(service_session.info['service_engine'], expire_on_commit=False)
async def audit_writer(user_id: int) -> None:
+ """
+ 为测试事务写入审计事件。
+
+ :param user_id: 用户的唯一标识
+ """
async with factory() as audit_session:
await AuditService.record(
audit_session,
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_interaction_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_interaction_service.py
index 8d6c54e26..f3443d088 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_interaction_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_interaction_service.py
@@ -16,7 +16,12 @@
def _payload(**overrides: object) -> dict[str, object]:
- """构造 AuthorizationContext 的内部白名单载荷。"""
+ """
+ 构造 AuthorizationContext 的内部白名单载荷。
+
+ :param overrides: 调用方按名称传入的附加选项
+ :return: AuthorizationContext 的内部白名单载荷
+ """
value: dict[str, object] = {
'interactionId': 'context-id',
'clientPk': 1001,
@@ -191,6 +196,13 @@ async def test_transition_rejects_interaction_without_ttl(monkeypatch: pytest.Mo
redis.values[key] = (value, None)
async def get_record(*_args: object, **_kwargs: object) -> dict[str, object]:
+ """
+ 将存储值解码为交互记录。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 从缓存中解码的交互记录
+ """
return json.loads(value)
monkeypatch.setattr(InteractionService, '_get_record', classmethod(get_record))
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_introspection_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_introspection_service.py
index 29092617b..a02cda946 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_introspection_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_introspection_service.py
@@ -16,8 +16,11 @@
def _config() -> SimpleNamespace:
- """构造内省所需的最小配置。"""
+ """
+ 构造内省所需的最小配置。
+ :return: 内省所需的最小配置
+ """
return SimpleNamespace(
oidc_issuer='https://auth.example.com',
oidc_allowed_clock_skew_seconds=60,
@@ -27,16 +30,23 @@ def _config() -> SimpleNamespace:
@pytest.fixture(autouse=True)
def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
- """将全局 OIDC 配置固定为本文件测试所需的协议值。"""
+ """
+ 将全局 OIDC 配置固定为本文件测试所需的协议值。
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
monkeypatch.setattr(OidcConfig, 'oidc_issuer', 'https://auth.example.com')
monkeypatch.setattr(OidcConfig, 'oidc_allowed_clock_skew_seconds', 60)
monkeypatch.setattr(OidcConfig, 'oidc_token_hash_pepper', _PEPPER)
def _client(client_type: str = 'confidential') -> SimpleNamespace:
- """构造已启用的 Client 数据快照。"""
+ """
+ 构造已启用的 Client 数据快照。
+ :param client_type: 客户端类型(public公开客户端 confidential机密客户端)
+ :return: 已启用的 Client 数据快照
+ """
return SimpleNamespace(
client_pk=10,
client_id='introspector',
@@ -49,15 +59,18 @@ def _client(client_type: str = 'confidential') -> SimpleNamespace:
def _principal(client_type: str = 'confidential') -> OAuthClientPrincipal:
- """构造完成认证的 Client Principal。"""
+ """
+ 构造完成认证的 Client Principal。
+ :param client_type: 客户端类型(public公开客户端 confidential机密客户端)
+ :return: 完成认证的 Client Principal
+ """
return OAuthClientPrincipal('introspector', client_type, 'client_secret_basic')
@pytest.mark.asyncio
async def test_introspection_rejects_non_client_principal(monkeypatch: pytest.MonkeyPatch) -> None:
"""任意用户主体或普通对象都不能调用内省端点。"""
-
result = await IntrospectionService.introspect(object(), FakeRedis(), 'not-a-token', object())
assert result == {'active': False}
@@ -68,6 +81,13 @@ async def test_introspection_rejects_public_or_inactive_client(monkeypatch: pyte
"""内省调用方必须是数据库事实中的启用 Confidential Client。"""
async def client_lookup(*_args: object, **_kwargs: object) -> SimpleNamespace:
+ """
+ 根据客户端标识提供测试使用的 OAuth 客户端。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 与标识匹配的测试 OAuth 客户端
+ """
return _client('public')
monkeypatch.setattr('module_identity.service.token_protocol_service.OAuthClientDao.get_by_client_id', client_lookup)
@@ -96,7 +116,6 @@ async def test_introspection_auth_method_pair_is_exact(
expected: bool,
) -> None:
"""Introspection 仅接受数据库与 Principal 同时为 Confidential/Basic。"""
-
client = _client(client_type)
client.token_endpoint_auth_method = db_method
monkeypatch.setattr(
@@ -115,10 +134,16 @@ async def test_access_introspection_honours_revoked_jti_and_resource_owner(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Access JWT 必须通过签名 Profile、撤销键和 Resource 内省授权。"""
-
client = _client()
async def client_lookup(*_args: object, **_kwargs: object) -> SimpleNamespace:
+ """
+ 向调用方返回 ``client``。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 为当前请求选择的客户端
+ """
return client
monkeypatch.setattr('module_identity.service.token_protocol_service.OAuthClientDao.get_by_client_id', client_lookup)
@@ -155,7 +180,6 @@ async def test_business_client_a_is_introspected_by_independent_resource_client_
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""业务 Client A 签发的 Token 可由 Resource 专用 Client B 内省。"""
-
caller = _client()
issuer = _client()
issuer.client_pk = 20
@@ -163,6 +187,14 @@ async def test_business_client_a_is_introspected_by_independent_resource_client_
issuer.grant_types = ['authorization_code', 'refresh_token']
async def client_lookup(_db: object, client_id: str, active_only: bool = True) -> SimpleNamespace:
+ """
+ 根据客户端标识提供测试使用的 OAuth 客户端。
+
+ :param _db: 回调签名接收的数据库会话
+ :param client_id: 客户端标识
+ :param active_only: 是否仅查询启用记录
+ :return: 与标识匹配的测试 OAuth 客户端
+ """
return caller if client_id == 'introspector' else issuer
monkeypatch.setattr('module_identity.service.token_protocol_service.OAuthClientDao.get_by_client_id', client_lookup)
@@ -198,13 +230,20 @@ async def test_independent_resource_client_b_is_rejected_for_wrong_audience(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Resource 不属于调用方 B 时,即使 Token 签名正确也必须拒绝。"""
-
caller = _client()
issuer = _client()
issuer.client_pk = 20
issuer.client_id = 'business-a'
async def client_lookup(_db: object, client_id: str, active_only: bool = True) -> SimpleNamespace:
+ """
+ 根据客户端标识提供测试使用的 OAuth 客户端。
+
+ :param _db: 回调签名接收的数据库会话
+ :param client_id: 客户端标识
+ :param active_only: 是否仅查询启用记录
+ :return: 与标识匹配的测试 OAuth 客户端
+ """
return caller if client_id == 'introspector' else issuer
monkeypatch.setattr('module_identity.service.token_protocol_service.OAuthClientDao.get_by_client_id', client_lookup)
@@ -234,7 +273,6 @@ async def test_access_user_state_rejects_each_real_time_failure(
monkeypatch: pytest.MonkeyPatch, invalid_state: str
) -> None:
"""用户 Access Token 的 Subject、用户、版本、Session、Grant 任一失效都拒绝。"""
-
subject = SimpleNamespace(subject_id='subject-a', user_id=7, auth_version=3)
user = SimpleNamespace(status='0', del_flag='0', user_name='alice')
session = SimpleNamespace(user_id=7, subject_id='subject-a', auth_version=3)
@@ -270,7 +308,6 @@ async def test_machine_access_token_uses_client_binding_without_user_state(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""client_credentials Token 校验机器 Subject/Grant 能力,不读取用户状态。"""
-
caller = _client()
issuer = _client()
issuer.client_pk = 20
@@ -278,6 +315,14 @@ async def test_machine_access_token_uses_client_binding_without_user_state(
issuer.grant_types = ['client_credentials']
async def client_lookup(_db: object, client_id: str, active_only: bool = True) -> SimpleNamespace:
+ """
+ 根据客户端标识提供测试使用的 OAuth 客户端。
+
+ :param _db: 回调签名接收的数据库会话
+ :param client_id: 客户端标识
+ :param active_only: 是否仅查询启用记录
+ :return: 与标识匹配的测试 OAuth 客户端
+ """
return caller if client_id == 'introspector' else issuer
monkeypatch.setattr('module_identity.service.token_protocol_service.OAuthClientDao.get_by_client_id', client_lookup)
@@ -312,6 +357,13 @@ async def test_invalid_refresh_shape_is_inactive(monkeypatch: pytest.MonkeyPatch
"""Refresh Token 内省必须验证完整 typed opaque token。"""
async def client_lookup(*_args: object, **_kwargs: object) -> SimpleNamespace:
+ """
+ 根据客户端标识提供测试使用的 OAuth 客户端。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 与标识匹配的测试 OAuth 客户端
+ """
return _client()
monkeypatch.setattr('module_identity.service.token_protocol_service.OAuthClientDao.get_by_client_id', client_lookup)
@@ -398,27 +450,48 @@ async def test_refresh_introspection_rechecks_identity_session_grant_and_resourc
def _lookup(value: object) -> object:
- """返回固定值的异步查询桩。"""
+ """
+ 返回固定值的异步查询桩。
+
+ :param value: 待处理的输入值
+ :return: 固定值的异步查询桩
+ """
async def lookup(*_args: object, **_kwargs: object) -> object:
+ """
+ 向调用方返回 ``value``。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 为此调用预设的值
+ """
return value
return lookup
async def _async_true() -> bool:
- """返回异步 True,供类方法 monkeypatch 使用。"""
+ """
+ 返回异步 True,供类方法 monkeypatch 使用。
+ :return: 此分支的固定值 ``True``
+ """
return True
async def _async_user() -> SimpleNamespace:
- """返回带当前用户名的已验证用户快照。"""
+ """
+ 返回带当前用户名的已验证用户快照。
+ :return: 带当前用户名的已验证用户快照
+ """
return SimpleNamespace(user_name='alice')
async def _async_false() -> bool:
- """返回异步 False,供失败路径 monkeypatch 使用。"""
+ """
+ 返回异步 False,供失败路径 monkeypatch 使用。
+ :return: 此分支的固定值 ``False``
+ """
return False
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_key_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_key_service.py
index 6ae13984d..638cc6a24 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_key_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_key_service.py
@@ -25,7 +25,11 @@
@pytest_asyncio.fixture
async def data_session() -> AsyncSession:
- """仅创建密钥和审计表,隔离项目其他 ORM 的 SQLite 方言差异。"""
+ """
+ 仅创建密钥和审计表,隔离项目其他 ORM 的 SQLite 方言差异。
+
+ :yield: 当前操作共用的会话
+ """
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
tables = [SysOidcSigningKey.__table__, SysOAuthAuditLog.__table__]
async with engine.begin() as connection:
@@ -38,8 +42,11 @@ async def data_session() -> AsyncSession:
@pytest.fixture(autouse=True)
def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
- """将全局 OIDC 配置固定为密钥服务测试所需的基线。"""
+ """
+ 将全局 OIDC 配置固定为密钥服务测试所需的基线。
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
values = {
'oidc_enabled': True,
'oidc_active_kid': 'k1',
@@ -58,13 +65,23 @@ def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
def _config() -> OidcConfig:
- """返回当前测试使用的全局 OIDC 配置。"""
+ """
+ 返回当前测试使用的全局 OIDC 配置。
+ :return: 当前测试使用的全局 OIDC 配置
+ """
return OidcConfig
def _record(tmp_path: Path, *, status: str = 'active', matching: bool = True) -> SimpleNamespace:
- """生成带文件私钥和公开 JWK 的内存记录。"""
+ """
+ 生成带文件私钥和公开 JWK 的内存记录。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param status: 操作或记录所处的状态
+ :param matching: 是否提供与当前记录匹配的值
+ :return: 带文件私钥和公开 JWK 的内存记录
+ """
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
numbers = key.public_key().public_numbers()
n = base64url_encode(numbers.n.to_bytes((numbers.n.bit_length() + 7) // 8, 'big')).decode()
@@ -109,13 +126,22 @@ async def test_activate_due_processes_only_scheduled_keys_and_rolls_back_failure
"""后台只处理到期 pending,并在单项失败时回滚该项事务。"""
class _Session:
+ """
+ 模拟测试事务的会话生命周期。
+
+ :cvar commits: 测试中记录的提交次数
+ :cvar rollbacks: 测试中记录的回滚次数
+ """
+
commits = 0
rollbacks = 0
async def commit(self) -> None:
+ """累加 ``commits`` 供后续断言检查。"""
self.commits += 1
async def rollback(self) -> None:
+ """累加 ``rollbacks`` 供后续断言检查。"""
self.rollbacks += 1
session = _Session()
@@ -123,9 +149,23 @@ async def rollback(self) -> None:
scheduled: list[str] = []
async def due_keys(*args: object, **kwargs: object) -> list[SimpleNamespace]:
+ """
+ 返回到期可处理的测试密钥。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 到期可处理的测试密钥
+ """
return [due]
async def activate(*args: object, **kwargs: object) -> bool:
+ """
+ 记录目标密钥的激活调用。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``True``
+ """
scheduled.append(args[1])
return True
@@ -137,11 +177,24 @@ async def activate(*args: object, **kwargs: object) -> bool:
assert session.rollbacks == 0
async def fail(*args: object, **kwargs: object) -> bool:
+ """
+ 模拟此操作抛出 KeyServiceError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises KeyServiceError: 模拟私钥与公开 JWK 不匹配
+ """
raise KeyServiceError('private key does not match public JWK')
audit_events: list[tuple[object, ...]] = []
async def audit_writer(*args: object, **kwargs: object) -> None:
+ """
+ 为测试事务写入审计事件。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
audit_events.append(args)
monkeypatch.setattr(KeyService, 'activate_key', fail)
@@ -155,13 +208,22 @@ async def test_activate_due_audits_first_failure_and_continues_next_key(monkeypa
"""首把激活失败必须独立审计,且不得阻断后续到期密钥。"""
class _Session:
+ """
+ 模拟测试事务的会话生命周期。
+
+ :cvar commits: 测试中记录的提交次数
+ :cvar rollbacks: 测试中记录的回滚次数
+ """
+
commits = 0
rollbacks = 0
async def commit(self) -> None:
+ """累加 ``commits`` 供后续断言检查。"""
self.commits += 1
async def rollback(self) -> None:
+ """累加 ``rollbacks`` 供后续断言检查。"""
self.rollbacks += 1
session = _Session()
@@ -169,14 +231,36 @@ async def rollback(self) -> None:
audit_events: list[dict[str, object]] = []
async def due_keys(*args: object, **kwargs: object) -> list[SimpleNamespace]:
+ """
+ 向调用方返回 ``pending``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 仍在等待处理的记录
+ """
return pending
async def activate(db: object, kid: str, **kwargs: object) -> bool:
+ """
+ 记录目标密钥的激活调用。
+
+ :param db: 当前操作使用的数据库会话
+ :param kid: 用于定位签名密钥的标识
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises KeyServiceError: 模拟激活时私钥与公开 JWK 不匹配
+ :return: 此分支的固定值 ``True``
+ """
if kid == 'first':
raise KeyServiceError('private key does not match public JWK')
return True
async def audit_writer(*args: object, **kwargs: object) -> None:
+ """
+ 为测试事务写入审计事件。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
audit_events.append(kwargs)
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.list_due_pending', due_keys)
@@ -193,22 +277,47 @@ async def test_activate_due_continues_when_failure_audit_writer_fails(monkeypatc
activated: list[str] = []
class _Session:
+ """模拟测试事务的会话生命周期。"""
+
async def commit(self) -> None:
- pass
+ """在测试会话中处理事务提交。"""
async def rollback(self) -> None:
- pass
+ """在测试会话中处理事务回滚。"""
async def due_keys(*args: object, **kwargs: object) -> list[SimpleNamespace]:
+ """
+ 向调用方返回 ``pending``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 仍在等待处理的记录
+ """
return pending
async def activate(db: object, kid: str, **kwargs: object) -> bool:
+ """
+ 记录目标密钥的激活调用。
+
+ :param db: 当前操作使用的数据库会话
+ :param kid: 用于定位签名密钥的标识
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises KeyServiceError: 模拟激活时私钥与公开 JWK 不匹配
+ :return: 此分支的固定值 ``True``
+ """
if kid == 'first':
raise KeyServiceError('activation failed')
activated.append(kid)
return True
async def failed_audit(*args: object, **kwargs: object) -> None:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RuntimeError: 模拟审计数据库不可用
+ """
raise RuntimeError('audit database unavailable')
warnings: list[str] = []
@@ -293,15 +402,39 @@ async def test_rotation_lock_is_cross_instance_exclusive_and_releases_atomically
"""轮换锁在 Redis 中互斥,并只允许持有者删除自己的锁。"""
class _Redis:
+ """
+ 模拟测试所需的 Redis 命令。
+
+ :cvar value: 待处理的输入值
+ """
+
value: str | None = None
async def set(self, key: str, value: str, *, nx: bool, ex: int) -> bool:
+ """
+ 写入测试缓存键并设置过期时间。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :param nx: 是否只在键尚不存在时写入
+ :param ex: 捕获到的异常实例
+ :return: 是否写入测试缓存键并设置过期时间
+ """
if nx and self.value is not None:
return False
self.value = value
return True
async def eval(self, script: str, count: int, key: str, token: str) -> int:
+ """
+ 按测试约定模拟 Redis 脚本的执行。
+
+ :param script: 需要运行的脚本
+ :param count: 本次处理或预期的数量
+ :param key: 查找数据时使用的键
+ :param token: 用于身份验证或授权的令牌
+ :return: 表示模拟脚本执行状态的整数
+ """
if self.value == token:
self.value = None
return 1
@@ -326,7 +459,7 @@ async def test_private_key_must_match_public_jwk(tmp_path: Path) -> None:
@pytest.mark.asyncio
async def test_private_key_requires_active_signing_window(tmp_path: Path) -> None:
- """pending 或已停止签名的密钥不能用于签名。"""
+ """验证处于 pending 状态或已停止签名的密钥不能用于签名。"""
with pytest.raises(KeyServiceError, match='预期状态为 active'):
await KeyService.load_private_key_async(_record(tmp_path, status='pending'))
@@ -346,6 +479,13 @@ async def test_imported_database_kid_is_validated_before_jwks_and_signing(
OidcUtil.normalize_public_jwk(record)
async def published(*args: object, **kwargs: object) -> list[SimpleNamespace]:
+ """
+ 返回已发布的测试密钥记录。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 已发布的测试密钥记录
+ """
return [record]
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.list_published', published)
@@ -436,7 +576,13 @@ async def test_runtime_active_key_uses_database_state_not_bootstrap_kid(tmp_path
def _orm_key(record: SimpleNamespace, status: str) -> SysOidcSigningKey:
- """把内存密钥记录转换为真实 ORM 密钥。"""
+ """
+ 把内存密钥记录转换为真实 ORM 密钥。
+
+ :param record: 当前操作使用的记录
+ :param status: 操作或记录所处的状态
+ :return: ``SysOidcSigningKey`` 实例
+ """
return SysOidcSigningKey(
kid=record.kid,
alg=record.alg,
@@ -540,6 +686,13 @@ async def test_jwks_filters_private_jwk_fields(monkeypatch: pytest.MonkeyPatch,
record.public_jwk['d'] = 'secret'
async def published(*args: object, **kwargs: object) -> list[SimpleNamespace]:
+ """
+ 返回已发布的测试密钥记录。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 已发布的测试密钥记录
+ """
return [record]
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.list_published', published)
@@ -592,6 +745,13 @@ async def test_jwks_excludes_keys_outside_publish_window(monkeypatch: pytest.Mon
]
async def published(*args: object, **kwargs: object) -> list[SimpleNamespace]:
+ """
+ 向调用方返回 ``records``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 匹配查询的记录集合
+ """
return records
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.list_published', published)
@@ -607,6 +767,13 @@ async def test_jwks_rejects_malformed_rsa_jwk(monkeypatch: pytest.MonkeyPatch, t
record.public_jwk['n'] = 'not-a-rsa-modulus'
async def published(*args: object, **kwargs: object) -> list[SimpleNamespace]:
+ """
+ 返回已发布的测试密钥记录。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 已发布的测试密钥记录
+ """
return [record]
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.list_published', published)
@@ -625,15 +792,43 @@ async def test_activation_validates_pending_private_key_before_state_change(
changed = False
async def lock_algorithm(*args: object, **kwargs: object) -> list[SimpleNamespace]:
+ """
+ 返回已锁定的旧密钥与目标密钥。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 已锁定的旧密钥与目标密钥
+ """
return [old, target]
async def get_target(*args: object, **kwargs: object) -> SimpleNamespace:
+ """
+ 向调用方返回 ``target``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 当前操作的目标记录
+ """
return target
async def get_old(*args: object, **kwargs: object) -> SimpleNamespace:
+ """
+ 向调用方返回 ``old``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 更新前的记录
+ """
return old
async def activate(*args: object, **kwargs: object) -> bool:
+ """
+ 记录目标密钥的激活调用。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``True``
+ """
nonlocal changed
changed = True
return True
@@ -662,20 +857,54 @@ async def test_activation_retains_old_key_for_max_overlap_window(
config.oidc_allowed_clock_skew_seconds = 60
async def audit(*args: object, **kwargs: object) -> None:
- return None
+ """
+ 完成无需返回值的回调。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
+ return
monkeypatch.setattr('module_identity.service.key_service.AuditService.record', audit)
async def lock_algorithm(*args: object, **kwargs: object) -> list[SimpleNamespace]:
+ """
+ 返回已锁定的旧密钥与目标密钥。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 已锁定的旧密钥与目标密钥
+ """
return [old, target]
async def get_target(*args: object, **kwargs: object) -> SimpleNamespace:
+ """
+ 向调用方返回 ``target``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 当前操作的目标记录
+ """
return target
async def get_old(*args: object, **kwargs: object) -> SimpleNamespace:
+ """
+ 向调用方返回 ``old``。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 更新前的记录
+ """
return old
async def activate(*args: object, **kwargs: object) -> bool:
+ """
+ 在此测试分支返回 True。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``True``
+ """
return True
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.lock_algorithm_for_update', lock_algorithm)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_logout.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_logout.py
index ef0f16abf..09be42a42 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_logout.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_logout.py
@@ -41,23 +41,40 @@
@pytest.fixture
def now() -> datetime:
- """每个用例执行时获取时间,避免等待前序测试期间令牌过期。"""
+ """
+ 每个用例执行时获取时间,避免等待前序测试期间令牌过期。
+
+ :return: 测试执行时的 UTC 时刻
+ """
return datetime.now(UTC)
@pytest.fixture(autouse=True)
def _disable_logout_rate_limit(monkeypatch: pytest.MonkeyPatch) -> None:
- """Logout Controller 单元测试隔离 Redis 限流器。"""
+ """
+ Logout Controller 单元测试隔离 Redis 限流器。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
async def allow(*_args: object, **_kwargs: object) -> None:
- return None
+ """
+ 完成无需返回值的回调。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ """
+ return
monkeypatch.setattr(OidcRateLimiter, 'enforce', allow)
def _config() -> SimpleNamespace:
- """构造 Logout 测试配置。"""
+ """
+ 构造 Logout 测试配置。
+ :return: Logout 测试配置
+ """
return SimpleNamespace(
oidc_enabled=True,
oidc_issuer=_ISSUER,
@@ -68,8 +85,11 @@ def _config() -> SimpleNamespace:
@pytest.fixture(autouse=True)
def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
- """将全局 OIDC 配置固定为 Logout 测试所需的协议值。"""
+ """
+ 将全局 OIDC 配置固定为 Logout 测试所需的协议值。
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
monkeypatch.setattr(OidcConfig, 'oidc_enabled', True)
monkeypatch.setattr(OidcConfig, 'oidc_issuer', _ISSUER)
monkeypatch.setattr(OidcConfig, 'oidc_allowed_clock_skew_seconds', 60)
@@ -77,8 +97,14 @@ def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
def _key_record(private_key: object, now: datetime, kid: str = 'key-1') -> SimpleNamespace:
- """构造本地数据库公开 JWK 记录。"""
-
+ """
+ 构造本地数据库公开 JWK 记录。
+
+ :param private_key: 仅在当前构建进程内使用的 Ed25519 签名私钥
+ :param now: 用于设置签发和过期时间的基准时刻
+ :param kid: 用于定位签名密钥的标识
+ :return: 本地数据库公开 JWK 记录
+ """
numbers = private_key.public_key().public_numbers()
public_jwk = {
'kty': 'RSA',
@@ -100,8 +126,15 @@ def _key_record(private_key: object, now: datetime, kid: str = 'key-1') -> Simpl
def _id_token(private_key: object, *, now: datetime, kid: str = 'key-1', aud: str = 'portal') -> str:
- """签发用于测试的真实 ID Token。"""
-
+ """
+ 签发用于测试的真实 ID Token。
+
+ :param private_key: 仅在当前构建进程内使用的 Ed25519 签名私钥
+ :param now: 用于设置签发和过期时间的基准时刻
+ :param kid: 用于定位签名密钥的标识
+ :param aud: 令牌声明的受众
+ :return: 使用测试签名密钥签发的身份令牌
+ """
return encode_id_token(
{
'iss': _ISSUER,
@@ -125,7 +158,6 @@ async def test_id_token_hint_uses_local_rsa_kid_and_rejects_remote_header(
monkeypatch: pytest.MonkeyPatch, now: datetime
) -> None:
"""ID Token Hint 仅使用本地 DB JWK,远程 header 参数直接拒绝。"""
-
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
client = SimpleNamespace(client_pk=20, client_id='portal', status='0')
monkeypatch.setattr(
@@ -157,7 +189,6 @@ async def test_pending_signing_key_cannot_validate_id_token_hint(
monkeypatch: pytest.MonkeyPatch, now: datetime
) -> None:
"""待激活签名密钥只能发布,不能用于验证 ID Token Hint。"""
-
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
client = SimpleNamespace(client_pk=20, client_id='portal', status='0')
monkeypatch.setattr(
@@ -176,7 +207,6 @@ async def test_pending_signing_key_cannot_validate_id_token_hint(
@pytest.mark.asyncio
async def test_logout_redirect_and_backchannel_are_after_commit(monkeypatch: pytest.MonkeyPatch, now: datetime) -> None:
"""已注册 Redirect 安全附加 state,通知只在 commit 后执行。"""
-
client = SimpleNamespace(client_pk=20, client_id='portal', status='0')
session = SimpleNamespace(sid='sid-1', status='active', subject_id='subject-1')
monkeypatch.setattr(
@@ -192,9 +222,16 @@ async def test_logout_redirect_and_backchannel_are_after_commit(monkeypatch: pyt
sent: list[tuple[str, str]] = []
async def register_backchannel(*args: object, **kwargs: object) -> None:
+ """
+ 注册提交后触发的注销通知回调。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
coordinator = kwargs['coordinator']
async def notify() -> None:
+ """记录待发送的后通道注销通知。"""
sent.append(('https://portal.example/oidc/backchannel-logout', 'logout-token'))
await coordinator.register(notify)
@@ -244,10 +281,16 @@ async def test_invalid_hint_with_valid_cookie_still_revokes_server_session(
monkeypatch: pytest.MonkeyPatch, now: datetime
) -> None:
"""无效 Hint 不得重定向,但有效 Cookie 仍必须撤销服务端 Session。"""
-
session = SimpleNamespace(sid='sid-1', status='active', subject_id='subject-1')
async def invalid_hint(*_args: object, **_kwargs: object) -> object:
+ """
+ 模拟此操作抛出 LogoutServiceError 的情形。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :raises LogoutServiceError: 模拟注销请求中的身份令牌提示无效
+ """
raise LogoutServiceError('invalid id_token_hint')
monkeypatch.setattr(LogoutService, '_validate_id_token_hint', invalid_hint)
@@ -284,7 +327,6 @@ async def test_unsafe_or_unregistered_redirect_falls_back_to_local_and_logout_to
monkeypatch: pytest.MonkeyPatch, now: datetime
) -> None:
"""未注册 URI 不开放重定向;生成的 Logout Token 使用专用 Profile。"""
-
client = SimpleNamespace(client_pk=20, client_id='portal', status='0')
session = SimpleNamespace(sid='sid-1', status='active', subject_id='subject-1')
monkeypatch.setattr(
@@ -355,7 +397,6 @@ async def test_backchannel_dns_private_and_ipv6_addresses_are_rejected(
monkeypatch: pytest.MonkeyPatch, address: str
) -> None:
"""Back-Channel DNS 解析到内网、IPv6 回环或 metadata 地址时拒绝发送。"""
-
monkeypatch.setattr(
'module_identity.security.uri_validator.socket.getaddrinfo',
lambda *_args, **_kwargs: [(2, 1, 6, '', (address, 443))],
@@ -369,12 +410,18 @@ async def test_backchannel_retry_queue_and_structured_audit_exclude_token(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Back-Channel 失败有限重试、入队和审计均不携带 Logout Token。"""
-
attempts = 0
queued: list[tuple[str, str, str]] = []
audited: list[tuple[str, str, str, str]] = []
async def fail(_uri: str, _token: str) -> None:
+ """
+ 记录操作尝试并触发预期故障。
+
+ :param _uri: 回调签名接收的 URI
+ :param _token: 回调签名接收的令牌
+ :raises RuntimeError: 模拟网络不可用
+ """
nonlocal attempts
attempts += 1
raise RuntimeError('network down')
@@ -388,10 +435,29 @@ async def queue(
subject_id: str | None = None,
include_sid: bool = True,
) -> None:
+ """
+ 记录加入重试队列的注销通知。
+
+ :param uri: 请求对应的资源标识符
+ :param client_id: 客户端标识
+ :param sid: 关联的单点登录会话标识
+ :param event_jti: 事件 JTI
+ :param subject_id: 身份主体的唯一标识
+ :param include_sid: 是否包含 Session 标识
+ """
del event_jti, subject_id, include_sid
queued.append((uri, client_id, sid))
async def audit(event: str, uri: str, client_id: str, sid: str, *, failure_code: str | None = None) -> None:
+ """
+ 记录测试操作产生的审计事件。
+
+ :param event: 待处理的事件
+ :param uri: 请求对应的资源标识符
+ :param client_id: 客户端标识
+ :param sid: 关联的单点登录会话标识
+ :param failure_code: 失败原因代码
+ """
del failure_code
audited.append((event, uri, client_id, sid))
@@ -421,6 +487,13 @@ async def test_backchannel_retry_metadata_reuses_event_jti_without_token(
metadata: list[dict[str, object]] = []
async def fail(_uri: str, _token: str) -> None:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param _uri: 回调签名接收的 URI
+ :param _token: 回调签名接收的令牌
+ :raises RuntimeError: 模拟网络不可用
+ """
raise RuntimeError('network down')
async def queue(
@@ -429,6 +502,14 @@ async def queue(
_sid: str,
**kwargs: object,
) -> None:
+ """
+ 记录加入重试队列的注销通知。
+
+ :param _uri: 回调签名接收的 URI
+ :param _client_id: 回调签名接收的客户端标识
+ :param _sid: 回调签名接收的会话标识
+ :param kwargs: 传给被调用对象的关键字参数
+ """
metadata.append(kwargs)
monkeypatch.setattr('module_identity.service.session_service._BACKCHANNEL_RETRY_DELAY_SECONDS', 0)
@@ -454,12 +535,28 @@ async def test_backchannel_permanent_http_4xx_is_not_retried(monkeypatch: pytest
audited: list[str] = []
async def permanent(_uri: str, _token: str) -> None:
+ """
+ 模拟注销通知发生不可重试的错误。
+
+ :param _uri: 回调签名接收的 URI
+ :param _token: 回调签名接收的令牌
+ :raises httpx.HTTPStatusError: 模拟对端返回不可重试的 HTTP 400
+ """
nonlocal attempts
attempts += 1
request = httpx.Request('POST', 'https://client.example/logout')
raise httpx.HTTPStatusError('bad request', request=request, response=httpx.Response(400, request=request))
async def audit(event: str, _uri: str, _client_id: str, _sid: str, **kwargs: object) -> None:
+ """
+ 记录测试操作产生的审计事件。
+
+ :param event: 待处理的事件
+ :param _uri: 回调签名接收的 URI
+ :param _client_id: 回调签名接收的客户端标识
+ :param _sid: 回调签名接收的会话标识
+ :param kwargs: 传给被调用对象的关键字参数
+ """
audited.append(f'{event}:{kwargs.get("failure_code")}')
monkeypatch.setattr('module_identity.service.session_service._BACKCHANNEL_RETRY_DELAY_SECONDS', 0)
@@ -487,6 +584,15 @@ async def test_malformed_retry_payload_goes_to_safe_dead_letter_and_audit(
audited: list[str] = []
async def audit(event: str, _uri: str, _client_id: str, _sid: str, **kwargs: object) -> None:
+ """
+ 记录测试操作产生的审计事件。
+
+ :param event: 待处理的事件
+ :param _uri: 回调签名接收的 URI
+ :param _client_id: 回调签名接收的客户端标识
+ :param _sid: 回调签名接收的会话标识
+ :param kwargs: 传给被调用对象的关键字参数
+ """
audited.append(f'{event}:{kwargs.get("failure_code")}')
monkeypatch.setattr(LogoutService, '_audit_writer', lambda _db: audit)
@@ -499,7 +605,6 @@ async def audit(event: str, _uri: str, _client_id: str, _sid: str, **kwargs: obj
@pytest.mark.asyncio
async def test_pinned_transport_uses_approved_ip_and_preserves_origin_host(monkeypatch: pytest.MonkeyPatch) -> None:
"""Pinned transport 只拨批准 IP,同时保留注册域名的 Host 和 TLS SNI。"""
-
stream = create_autospec(httpcore.AsyncNetworkStream, instance=True)
stream.read.side_effect = [b'HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK', b'']
stream.start_tls.return_value = stream
@@ -524,11 +629,19 @@ async def test_pinned_transport_stops_oversized_response_stream() -> None:
"""远端超大响应在流读取时主动中止,不在内存中无限累积。"""
class Stream:
+ """提供可异步迭代和关闭的响应流。"""
+
async def __aiter__(self) -> Any:
+ """
+ 提供测试数据的异步迭代器。
+
+ :yield: 测试数据的异步迭代器
+ """
yield b'x' * (70 * 1024)
async def aclose(self) -> None:
- return None
+ """完成无需返回值的回调。"""
+ return
response = SimpleNamespace(status=200, headers=[], stream=Stream(), extensions={}, aclose=AsyncMock())
transport = PinnedHttpxTransport('client.example', {'203.0.113.7'})
@@ -565,6 +678,12 @@ async def test_backchannel_retry_consumer_revalidates_uri_and_reissues_short_liv
sent: list[tuple[str, str]] = []
async def notify(uri: str, token: str) -> None:
+ """
+ 记录待发送的后通道注销通知。
+
+ :param uri: 请求对应的资源标识符
+ :param token: 用于身份验证或授权的令牌
+ """
sent.append((uri, token))
result = await LogoutService.consume_backchannel_retry(object(), redis, notifier=notify)
@@ -579,7 +698,6 @@ async def test_logout_endpoint_disabled_is_local_404_without_legacy_pre_auth(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""OIDC 关闭时直接返回裸 404,不执行数据库或 Legacy PreAuth。"""
-
config = SimpleNamespace(oidc_enabled=False)
monkeypatch.setattr(controller, 'OidcConfig', config)
response = await controller.logout(_request(), object())
@@ -592,7 +710,6 @@ async def test_logout_endpoint_prepares_confirmation_without_clearing_sso_cookie
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""初次退出只建立确认,不清理 SSO Cookie 或撤销登录。"""
-
config = SimpleNamespace(
oidc_enabled=True,
oidc_sso_cookie_name='__Host-ruoyi-sso',
@@ -603,6 +720,13 @@ async def test_logout_endpoint_prepares_confirmation_without_clearing_sso_cookie
monkeypatch.setattr(controller, 'OidcConfig', config)
async def fake_logout(*_args: object, **_kwargs: object) -> LogoutResult:
+ """
+ 创建测试使用的 ``LogoutResult`` 实例。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 测试使用的 ``LogoutResult`` 实例
+ """
return LogoutResult('https://portal.example/logged-out', 'state-1', True)
monkeypatch.setattr(controller.LogoutService, 'execute_logout', fake_logout)
@@ -627,7 +751,6 @@ async def test_logout_endpoint_unexpected_service_error_returns_503_without_clea
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Logout Service 异常时返回 503,避免清理仍有效的认证 Cookie。"""
-
config = SimpleNamespace(
oidc_enabled=True,
oidc_sso_cookie_name='__Host-ruoyi-sso',
@@ -638,6 +761,13 @@ async def test_logout_endpoint_unexpected_service_error_returns_503_without_clea
monkeypatch.setattr(controller, 'OidcConfig', config)
async def fail(*_args: object, **_kwargs: object) -> LogoutResult:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :raises RuntimeError: 模拟网络不可用
+ """
raise RuntimeError('unexpected failure')
monkeypatch.setattr(controller.LogoutConfirmationService, 'issue', fail)
@@ -653,7 +783,6 @@ async def test_logout_endpoint_post_form_forwards_logout_parameters(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""POST application/x-www-form-urlencoded 正确解析并转发 Logout 参数。"""
-
config = SimpleNamespace(
oidc_enabled=True,
oidc_sso_cookie_name='__Host-ruoyi-sso',
@@ -666,6 +795,14 @@ async def test_logout_endpoint_post_form_forwards_logout_parameters(
captured: dict[str, object] = {}
async def prepare(_redis: object, parameters: dict[str, str], _cookie: str | None) -> tuple[str, str]:
+ """
+ 捕获注销确认参数并提供固定测试值。
+
+ :param _redis: 回调签名接收的 Redis 客户端
+ :param parameters: 分派给目标命令的参数
+ :param _cookie: 回调签名接收的 Cookie 值
+ :return: 固定的注销确认令牌和随机数
+ """
captured.update(parameters)
return 't' * 43, 'n' * 43
@@ -694,11 +831,22 @@ def _request(
headers: list[tuple[bytes, bytes]] | None = None,
body: bytes = b'',
) -> Request:
- """构造带最小 Redis 状态的 Starlette Request。"""
-
+ """
+ 构造带最小 Redis 状态的 Starlette Request。
+
+ :param method: 当前请求的 HTTP 方法
+ :param headers: 响应或请求携带的 HTTP 头
+ :param body: 请求或测试样例的正文
+ :return: 带最小 Redis 状态的 Starlette Request
+ """
app = SimpleNamespace(state=SimpleNamespace(redis=object()))
async def receive() -> dict[str, object]:
+ """
+ 提供下游 ASGI 应用读取的 HTTP 请求体消息。
+
+ :return: 下游 ASGI 应用读取的 HTTP 请求体消息
+ """
return {'type': 'http.request', 'body': body, 'more_body': False}
return Request(
@@ -715,20 +863,38 @@ async def receive() -> dict[str, object]:
def _async_return(value: object) -> object:
- """构造固定值异步桩。"""
+ """
+ 构造固定值异步桩。
+
+ :param value: 待处理的输入值
+ :return: 固定值异步桩
+ """
async def return_value(*_args: object, **_kwargs: object) -> object:
+ """
+ 向调用方返回 ``value``。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 为此调用预设的值
+ """
return value
return return_value
async def _async_noop(*_args: object, **_kwargs: object) -> None:
- """构造无副作用异步桩。"""
+ """
+ 构造无副作用异步桩。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ """
@pytest.mark.asyncio
async def test_expired_id_token_is_accepted_only_as_logout_hint(monkeypatch: pytest.MonkeyPatch, now: datetime) -> None:
+ """过期身份令牌仅可用于注销提示。"""
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
payload = jwt.decode(_id_token(private_key, now=now), options={'verify_signature': False})
payload.update(iat=int(now.timestamp()) - 1200, exp=int(now.timestamp()) - 600)
@@ -751,6 +917,7 @@ async def test_expired_id_token_is_accepted_only_as_logout_hint(monkeypatch: pyt
async def test_confirmed_logout_does_not_revoke_another_accounts_hint_session(
monkeypatch: pytest.MonkeyPatch, now: datetime
) -> None:
+ """确认注销不能撤销另一账号的提示会话。"""
client = SimpleNamespace(client_pk=20, client_id='portal', status='0')
other = SimpleNamespace(sid='other-sid', subject_id='other-subject', status='active')
current = SimpleNamespace(sid='current-sid', subject_id='current-subject', status='active')
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_management_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_management_service.py
index 12aaa5c34..5e5ad659b 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_management_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_management_service.py
@@ -39,7 +39,11 @@
@pytest_asyncio.fixture
async def management_session() -> AsyncSession:
- """创建只包含 OAuth 管理表的真实 SQLite 异步会话。"""
+ """
+ 创建只包含 OAuth 管理表的真实 SQLite 异步会话。
+
+ :yield: 只包含 OAuth 管理表的真实 SQLite 异步会话
+ """
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
tables = [
SysOAuthClient.__table__,
@@ -63,7 +67,11 @@ async def management_session() -> AsyncSession:
async def _seed_definitions(session: AsyncSession) -> None:
- """写入用于绑定校验的启用 Resource 和 Scope。"""
+ """
+ 写入用于绑定校验的启用 Resource 和 Scope。
+
+ :param session: 当前操作共用的会话
+ """
resource = SysOAuthResource(
resource_id='resource-a',
resource_name='Resource A',
@@ -104,7 +112,12 @@ async def _seed_definitions(session: AsyncSession) -> None:
def _confidential_payload(**changes: object) -> ClientCreateModel:
- """构造一个需要授权码、PKCE 和回调地址的机密 Client。"""
+ """
+ 构造一个需要授权码、PKCE 和回调地址的机密 Client。
+
+ :param changes: 调用方按名称传入的附加选项
+ :return: 一个需要授权码、PKCE 和回调地址的机密 Client
+ """
values: dict[str, object] = {
'client_name': '管理测试 Client',
'client_type': 'confidential',
@@ -128,21 +141,40 @@ async def test_after_commit_failure_does_not_rollback_committed_management_chang
"""提交后的运行时回调失败不得回滚已提交的管理事务。"""
class _Db:
+ """
+ 模拟当前测试所需的数据库操作。
+
+ :cvar commits: 测试中记录的提交次数
+ :cvar rollbacks: 测试中记录的回滚次数
+ """
+
commits = 0
rollbacks = 0
async def commit(self) -> None:
+ """累加 ``commits`` 供后续断言检查。"""
self.commits += 1
async def rollback(self) -> None:
+ """累加 ``rollbacks`` 供后续断言检查。"""
self.rollbacks += 1
db = _Db()
async def operation() -> str:
+ """
+ 返回固定值 ``done``。
+
+ :return: 此分支的固定值 ``'done'``
+ """
return 'done'
async def after_commit() -> None:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :raises RuntimeError: 模拟提交后刷新运行时失败
+ """
raise RuntimeError('runtime refresh failed')
with pytest.raises(RuntimeError, match='runtime refresh failed'):
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_resource_scope_management.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_resource_scope_management.py
index d8a4e73cd..8ee51a5b4 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_resource_scope_management.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_resource_scope_management.py
@@ -42,7 +42,11 @@
@pytest_asyncio.fixture
async def resource_session() -> AsyncSession:
- """创建只包含 Resource/Scope/Client 管理表的真实 SQLite 会话。"""
+ """
+ 创建只包含 Resource/Scope/Client 管理表的真实 SQLite 会话。
+
+ :yield: 只包含 Resource/Scope/Client 管理表的真实 SQLite 会话
+ """
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
tables = [
SysOAuthClient.__table__,
@@ -66,7 +70,12 @@ async def resource_session() -> AsyncSession:
def _resource_payload(**changes: object) -> ResourceCreateModel:
- """构造一个合法 Resource DTO。"""
+ """
+ 构造一个合法 Resource DTO。
+
+ :param changes: 调用方按名称传入的附加选项
+ :return: 一个合法 Resource DTO
+ """
values: dict[str, object] = {
'resource_id': 'orders-api',
'resource_name': '订单 API',
@@ -89,7 +98,13 @@ def test_management_identifiers_are_safe_path_segments(value: str) -> None:
def _client_payload(resource_id: str = 'orders-api', scope_code: str | None = None) -> ClientCreateModel:
- """构造授权码机密 Client。"""
+ """
+ 构造授权码机密 Client。
+
+ :param resource_id: 资源标识
+ :param scope_code: Scope 编码
+ :return: 授权码机密 Client
+ """
return ClientCreateModel.model_validate(
{
'client_name': 'Resource 管理测试 Client',
@@ -105,7 +120,13 @@ def _client_payload(resource_id: str = 'orders-api', scope_code: str | None = No
async def _create_resource(session: AsyncSession, resource_id: str = 'orders-api') -> object:
- """创建一个基础启用 Resource。"""
+ """
+ 创建一个基础启用 Resource。
+
+ :param session: 当前操作共用的会话
+ :param resource_id: 资源标识
+ :return: 一个基础启用 Resource
+ """
return await OAuthResourceManagementService.create_resource(
session,
_resource_payload(resource_id=resource_id, audience=f'https://{resource_id}.example/api'),
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_review_completion.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_review_completion.py
index 0ca3fd46f..d22329b25 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_review_completion.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_review_completion.py
@@ -50,14 +50,23 @@
def _basic(client_id: str, secret: str) -> str:
- """生成符合协议编码要求的机密客户端认证头。"""
+ """
+ 生成符合协议编码要求的机密客户端认证头。
+ :param client_id: 客户端标识
+ :param secret: 用于验证身份或令牌的秘密值
+ :return: 符合协议编码要求的机密客户端认证头
+ """
return 'Basic ' + base64.b64encode(f'{quote_plus(client_id)}:{quote_plus(secret)}'.encode()).decode()
async def _confidential_token(flow: SimpleNamespace) -> tuple:
- """通过机密客户端的真实授权码流程签发离线令牌。"""
+ """
+ 通过机密客户端的真实授权码流程签发离线令牌。
+ :param flow: 驱动当前场景的业务流程
+ :return: 依次为 ``token``、``secret``、``authorization`` 的元组
+ """
flow.app.client_type = 'confidential'
flow.app.token_endpoint_auth_method = 'client_secret_basic'
secret = await OAuthClientManagementService._new_secret(flow.db, flow.app, 'admin', flow.now, not_before=flow.now)
@@ -113,7 +122,6 @@ async def _confidential_token(flow: SimpleNamespace) -> tuple:
@pytest.mark.parametrize('stored_status', ['active', 'expired'])
async def test_revoke_user_terminates_expired_offline_sessions(auth_flow: SimpleNamespace, stored_status: str) -> None:
"""自然过期不影响离线续期,但管理员按用户撤销必须终止该能力。"""
-
flow = auth_flow
token, _ = await _user_token(flow, offline=True)
flow.session.idle_expires_at = flow.now - timedelta(seconds=1)
@@ -146,7 +154,6 @@ async def test_revoke_user_terminates_expired_offline_sessions(auth_flow: Simple
@pytest.mark.asyncio
async def test_secret_rotation_and_revocation_preserve_existing_authorization(auth_flow: SimpleNamespace) -> None:
"""凭据轮换只改变客户端认证,旧授权可通过新凭据继续续期。"""
-
flow = auth_flow
token, old_secret, old_header = await _confidential_token(flow)
policy_version = flow.app.policy_version
@@ -193,7 +200,6 @@ async def test_token_hint_does_not_override_real_token_type(
auth_flow: SimpleNamespace, kind: str, hint: str | None
) -> None:
"""内省和撤销均忽略不匹配或未知的可选令牌类型提示。"""
-
flow = auth_flow
token, _ = await _user_token(flow, offline=True)
value = getattr(token, kind)
@@ -224,7 +230,6 @@ async def test_effective_expiry_matches_list_count_detail_without_mutating_state
auth_flow: SimpleNamespace, expiry: str
) -> None:
"""列表筛选、总数和详情采用相同有效状态,读取不改变离线凭据语义。"""
-
flow = auth_flow
_, grant = await _user_token(flow)
setattr(flow.session, f'{expiry}_expires_at', flow.now - timedelta(seconds=1))
@@ -258,7 +263,6 @@ async def test_online_authorization_records_exact_session_participation(
auth_flow: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
"""没有刷新令牌的授权也记录应用,其他设备的参与应用不混入当前登出。"""
-
flow = auth_flow
token, _ = await _user_token(flow)
await _user_token(flow)
@@ -301,7 +305,6 @@ async def test_online_authorization_records_exact_session_participation(
@pytest.mark.asyncio
async def test_legacy_refresh_binding_is_an_exact_session_fallback(auth_flow: SimpleNamespace) -> None:
"""升级前的离线凭据仍可恢复精确会话参与者,不依赖同用户授权时间推断。"""
-
flow = auth_flow
await _user_token(flow, offline=True)
await flow.db.execute(delete(SysSsoSessionClient))
@@ -314,10 +317,19 @@ async def test_failed_token_transaction_rolls_back_session_participation(
auth_flow: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
"""令牌签发事务失败时不能残留成功登录关联记录。"""
-
record = AuditService.record
async def fail_token_audit(db: AsyncSession, event_type: str, *args: object, **kwargs: object) -> object:
+ """
+ 在令牌签发审计时模拟写入失败。
+
+ :param db: 当前操作使用的数据库会话
+ :param event_type: 审计事件类型
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RuntimeError: 模拟写入令牌审计时服务不可用
+ :return: 未注入故障时原审计函数的结果
+ """
if event_type == OidcAuditEvent.TOKEN_ISSUED:
raise RuntimeError('audit unavailable')
return await record(db, event_type, *args, **kwargs)
@@ -333,7 +345,6 @@ async def test_access_policy_without_grant_is_queryable_and_unblocking_does_not_
auth_flow: SimpleNamespace,
) -> None:
"""首次授权前的禁止策略独立可见,解除后也不凭空恢复授权。"""
-
flow = auth_flow
await OAuthSessionManagementService.set_access(
flow.db, flow.user.user_id, 'business-app', True, 'admin', '预先禁止'
@@ -359,8 +370,13 @@ async def test_access_policy_without_grant_is_queryable_and_unblocking_does_not_
def _http_app(flow: SimpleNamespace, router: APIRouter) -> FastAPI:
- """挂载真实路由并将数据库依赖定向到隔离测试库。"""
+ """
+ 挂载真实路由并将数据库依赖定向到隔离测试库。
+ :param flow: 驱动当前场景的业务流程
+ :param router: 注册端点所用的路由器
+ :return: 正在配置或处理请求的 ASGI 应用
+ """
app = FastAPI()
app.state.redis = flow.redis
app.include_router(router)
@@ -381,7 +397,6 @@ async def test_authorize_accepts_query_response_mode_on_both_methods(
auth_flow: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, method: str
) -> None:
"""标准授权方法均进入真实交互流程,未登录时保持 prompt=none 的标准错误。"""
-
monkeypatch.setattr(OidcRateLimiter, 'enforce', AsyncMock())
values = {**_authorize_request(auth_flow), 'response_mode': 'query', 'prompt': 'none', 'state': 'test-state'}
app = _http_app(auth_flow, authorization_controller)
@@ -401,7 +416,6 @@ async def test_authorize_accepts_query_response_mode_on_both_methods(
@pytest.mark.parametrize('case', ['duplicate', 'query_and_body', 'json', 'bad_escape', 'oversize'])
async def test_authorize_post_rejects_ambiguous_or_invalid_forms(auth_flow: SimpleNamespace, case: str) -> None:
"""支持 POST 不放宽重复参数、编码、媒体类型和体积限制。"""
-
body = urlencode(_authorize_request(auth_flow))
url = '/oauth2/authorize'
media_type = 'application/x-www-form-urlencoded'
@@ -429,7 +443,6 @@ async def test_authorize_post_rejects_ambiguous_or_invalid_forms(auth_flow: Simp
@pytest.mark.asyncio
async def test_unsupported_response_mode_is_only_redirected_to_verified_client(auth_flow: SimpleNamespace) -> None:
"""不支持的响应模式只能向已登记回调返回错误。"""
-
values = {**_authorize_request(auth_flow), 'response_mode': 'fragment'}
with pytest.raises(OAuthProtocolException) as error:
await AuthorizationService._parse_request(auth_flow.db, values)
@@ -443,7 +456,6 @@ async def test_unsupported_response_mode_is_only_redirected_to_verified_client(a
@pytest.mark.asyncio
async def test_access_policy_list_route_returns_camel_case_without_grants(auth_flow: SimpleNamespace) -> None:
"""独立策略列表路由返回规范字段,不被授权详情路径截获。"""
-
flow = auth_flow
await OAuthSessionManagementService.set_access(
flow.db, flow.user.user_id, 'business-app', True, 'admin', '预先禁止'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_review_regressions.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_review_regressions.py
index 915b9dfb7..fa22a9099 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_review_regressions.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_review_regressions.py
@@ -30,6 +30,14 @@
async def seed_refresh(db: AsyncSession, monkeypatch: pytest.MonkeyPatch, *, expired: bool = False) -> str:
+ """
+ 准备具有关联约束的刷新令牌数据。
+
+ :param db: 当前操作使用的数据库会话
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :param expired: 当前记录是否已过期
+ :return: 用于身份验证或授权的令牌
+ """
# 显式确认外键校验已启用,避免SQLite默认配置掩盖原有问题
await db.execute(text('PRAGMA foreign_keys=ON'))
assert await db.scalar(text('PRAGMA foreign_keys')) == 1
@@ -116,6 +124,13 @@ async def seed_refresh(db: AsyncSession, monkeypatch: pytest.MonkeyPatch, *, exp
async def refresh(db: AsyncSession, token: str) -> TokenResult:
+ """
+ 使用测试授权参数请求刷新令牌。
+
+ :param db: 当前操作使用的数据库会话
+ :param token: 用于身份验证或授权的令牌
+ :return: 刷新令牌换取的新令牌响应
+ """
return await TokenService.refresh_token(
db,
{'grant_type': 'refresh_token', 'client_id': 'refresh-regression', 'refresh_token': token},
@@ -130,6 +145,7 @@ async def refresh(db: AsyncSession, token: str) -> TokenResult:
async def test_rotation_with_real_foreign_keys_and_replay_revocation(
data_session: AsyncSession, monkeypatch: pytest.MonkeyPatch, expired: bool
) -> None:
+ """有真实外键约束时支持令牌轮换和重放撤销。"""
old = await seed_refresh(data_session, monkeypatch, expired=expired)
result = await refresh(data_session, old)
await data_session.commit()
@@ -150,6 +166,7 @@ async def test_rotation_with_real_foreign_keys_and_replay_revocation(
async def test_failed_signing_rolls_back_both_rotation_rows(
data_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """签名失败时回滚两条轮换记录。"""
old = await seed_refresh(data_session, monkeypatch)
monkeypatch.setattr(TokenService, '_issue_access_token', AsyncMock(side_effect=RuntimeError('signer unavailable')))
with pytest.raises(RuntimeError, match='signer unavailable'):
@@ -165,6 +182,7 @@ async def test_failed_signing_rolls_back_both_rotation_rows(
async def test_explicit_revocation_still_blocks_offline_refresh(
data_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """显式撤销后禁止离线刷新。"""
old = await seed_refresh(data_session, monkeypatch, expired=True)
assert await SsoSessionDao.revoke(
data_session, '99010000-0000-4000-8000-000000000001', reason='rp_initiated_logout', now=NOW
@@ -176,6 +194,7 @@ async def test_explicit_revocation_still_blocks_offline_refresh(
@pytest.mark.asyncio
async def test_real_key_list_readiness_and_client_response_are_rfc3339(monkeypatch: pytest.MonkeyPatch) -> None:
+ """真实密钥列表的就绪时间和客户端响应采用 RFC 3339。"""
monkeypatch.setattr(OidcConfig, 'oidc_enabled', False)
monkeypatch.setattr(
'module_identity.controller.oidc_key_controller.OidcKeyManagementService.list_page',
@@ -195,6 +214,7 @@ async def test_real_key_list_readiness_and_client_response_are_rfc3339(monkeypat
def test_role_values_require_an_explicit_client_allowlist() -> None:
+ """角色声明必须由客户端显式列入允许清单。"""
user = {'subject_id': 'sub-1'}
for policy, expected in [
({'roles': True}, []),
@@ -214,6 +234,7 @@ def test_role_values_require_an_explicit_client_allowlist() -> None:
async def test_confirmed_logout_revokes_offline_grant_with_expired_owned_cookie(
data_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """已过期的自有 Cookie 仍可在确认注销时撤销离线授权。"""
old = await seed_refresh(data_session, monkeypatch, expired=True)
monkeypatch.setattr(OidcConfig, 'oidc_enabled', True)
sid = '99010000-0000-4000-8000-000000000001'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_revocation_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_revocation_service.py
index 355dfd5f0..c9f05557a 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_revocation_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_revocation_service.py
@@ -15,8 +15,11 @@
def _config() -> SimpleNamespace:
- """构造撤销所需的最小配置。"""
+ """
+ 构造撤销所需的最小配置。
+ :return: 撤销所需的最小配置
+ """
return SimpleNamespace(
oidc_issuer='https://auth.example.com',
oidc_allowed_clock_skew_seconds=60,
@@ -26,16 +29,23 @@ def _config() -> SimpleNamespace:
@pytest.fixture(autouse=True)
def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
- """将全局 OIDC 配置固定为本文件测试所需的协议值。"""
+ """
+ 将全局 OIDC 配置固定为本文件测试所需的协议值。
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
monkeypatch.setattr(OidcConfig, 'oidc_issuer', 'https://auth.example.com')
monkeypatch.setattr(OidcConfig, 'oidc_allowed_clock_skew_seconds', 60)
monkeypatch.setattr(OidcConfig, 'oidc_token_hash_pepper', _PEPPER)
def _client(client_type: str = 'public') -> SimpleNamespace:
- """构造启用的撤销 Client。"""
+ """
+ 构造启用的撤销 Client。
+ :param client_type: 客户端类型(public公开客户端 confidential机密客户端)
+ :return: 启用的撤销 Client
+ """
return SimpleNamespace(
client_pk=10,
client_id='client-a',
@@ -48,7 +58,6 @@ def _client(client_type: str = 'public') -> SimpleNamespace:
@pytest.mark.asyncio
async def test_public_client_can_revoke_only_its_own_refresh_family(monkeypatch: pytest.MonkeyPatch) -> None:
"""Public Client 只能撤销自己签发的 Refresh Token Family。"""
-
monkeypatch.setattr('module_identity.service.token_protocol_service.AuditService.record', AsyncMock())
client = _client()
token = generate_refresh_token('token-0001')
@@ -99,7 +108,6 @@ async def test_revocation_auth_method_pair_is_exact(
expected: bool,
) -> None:
"""Revocation 对 Public/none 与 Confidential/Basic 组合逐项 fail closed。"""
-
client = _client(client_type)
client.token_endpoint_auth_method = db_method
monkeypatch.setattr(
@@ -116,7 +124,6 @@ async def test_revocation_auth_method_pair_is_exact(
@pytest.mark.asyncio
async def test_unknown_refresh_is_idempotent_success(monkeypatch: pytest.MonkeyPatch) -> None:
"""未知或错误 Secret 不得暴露存在性,且 RFC7009 仍返回成功。"""
-
client = _client()
monkeypatch.setattr(
'module_identity.service.token_protocol_service.OAuthClientDao.get_by_client_id', _client_lookup(client)
@@ -138,7 +145,6 @@ async def test_unknown_refresh_is_idempotent_success(monkeypatch: pytest.MonkeyP
@pytest.mark.asyncio
async def test_access_revocation_is_written_only_after_commit(monkeypatch: pytest.MonkeyPatch) -> None:
"""Access JTI 撤销必须在数据库提交成功后写入 Redis。"""
-
client = _client('confidential')
monkeypatch.setattr(
'module_identity.service.token_protocol_service.OAuthClientDao.get_by_client_id', _client_lookup(client)
@@ -177,7 +183,6 @@ async def test_access_revocation_is_written_only_after_commit(monkeypatch: pytes
@pytest.mark.asyncio
async def test_public_client_can_revoke_its_own_access_after_commit(monkeypatch: pytest.MonkeyPatch) -> None:
"""Public Client 可撤销自己通过 PKCE 获得的 Access JWT。"""
-
client = _client('public')
monkeypatch.setattr(
'module_identity.service.token_protocol_service.OAuthClientDao.get_by_client_id', _client_lookup(client)
@@ -216,7 +221,6 @@ async def test_public_client_can_revoke_its_own_access_after_commit(monkeypatch:
@pytest.mark.asyncio
async def test_public_client_cannot_revoke_other_client_access(monkeypatch: pytest.MonkeyPatch) -> None:
"""Public Client 不能撤销其他业务 Client 的 Access JWT。"""
-
client = _client('public')
monkeypatch.setattr(
'module_identity.service.token_protocol_service.OAuthClientDao.get_by_client_id', _client_lookup(client)
@@ -244,9 +248,21 @@ async def test_public_client_cannot_revoke_other_client_access(monkeypatch: pyte
def _client_lookup(client: SimpleNamespace) -> object:
- """返回指定 Client 的异步 DAO 查询桩。"""
+ """
+ 返回指定 Client 的异步 DAO 查询桩。
+
+ :param client: 发起当前调用的客户端
+ :return: 指定 Client 的异步 DAO 查询桩
+ """
async def lookup(*_args: object, **_kwargs: object) -> SimpleNamespace:
+ """
+ 向调用方返回 ``client``。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 为当前请求选择的客户端
+ """
return client
return lookup
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_sso_session_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_sso_session_service.py
index fd2ada8ec..0f1902a28 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_sso_session_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_sso_session_service.py
@@ -26,9 +26,19 @@
class SessionFakeRedis:
- """覆盖 Session 服务所需字符串、Set 和 publish 语义的 FakeRedis。"""
+ """
+ 覆盖 Session 服务所需字符串、Set 和 publish 语义的 FakeRedis。
+
+ :ivar values: 当前处理的值集合
+ :ivar sets: 模拟 Redis 保存的集合数据
+ :ivar set_expiries: 为模拟键设置的到期时间
+ :ivar expire_seconds: 有效期(秒)
+ :ivar published: 记录已发布的消息
+ :ivar lock: 用于串行访问共享资源的锁
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``values``, ``sets``, ``set_expiries``, ``expire_seconds``。"""
self.values: dict[str, tuple[str, float | None]] = {}
self.sets: dict[str, set[str]] = {}
self.set_expiries: dict[str, float] = {}
@@ -37,11 +47,26 @@ def __init__(self) -> None:
self.lock = asyncio.Lock()
async def set(self, key: str, value: str, ex: int | None = None, **kwargs: object) -> bool:
+ """
+ 写入测试缓存键并设置过期时间。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :param ex: 捕获到的异常实例
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``True``
+ """
async with self.lock:
self.values[key] = (value, None if ex is None else asyncio.get_running_loop().time() + ex)
return True
async def get(self, key: str) -> str | None:
+ """
+ 读取测试存储中的指定键。
+
+ :param key: 查找数据时使用的键
+ :return: 测试存储中的指定键
+ """
async with self.lock:
value = self.values.get(key)
if value is not None and value[1] is not None and value[1] <= asyncio.get_running_loop().time():
@@ -50,10 +75,23 @@ async def get(self, key: str) -> str | None:
return value[0] if value else None
async def delete(self, *keys: str) -> int:
+ """
+ 删除测试缓存项及其过期状态。
+
+ :param keys: 调用方传入的其余位置参数
+ :return: 实际删除的键数
+ """
async with self.lock:
return sum(self.values.pop(key, None) is not None for key in keys)
async def sadd(self, key: str, *members: str) -> int:
+ """
+ 向测试 Redis 集合添加成员。
+
+ :param key: 查找数据时使用的键
+ :param members: 调用方传入的其余位置参数
+ :return: 新添加的集合成员数
+ """
self._expire_set_if_needed(key)
current = self.sets.setdefault(key, set())
before = len(current)
@@ -61,6 +99,13 @@ async def sadd(self, key: str, *members: str) -> int:
return len(current) - before
async def srem(self, key: str, *members: str) -> int:
+ """
+ 从测试 Redis 集合中删除成员。
+
+ :param key: 查找数据时使用的键
+ :param members: 调用方传入的其余位置参数
+ :return: 供调用方使用的 ``removed``
+ """
self._expire_set_if_needed(key)
current = self.sets.setdefault(key, set())
removed = sum(member in current for member in members)
@@ -68,11 +113,23 @@ async def srem(self, key: str, *members: str) -> int:
return removed
async def smembers(self, key: str) -> builtins.set[str]:
+ """
+ 返回测试 Redis 集合中的成员。
+
+ :param key: 查找数据时使用的键
+ :return: 测试 Redis 集合中的成员
+ """
self._expire_set_if_needed(key)
return builtins.set(self.sets.get(key, builtins.set()))
async def expire(self, key: str, seconds: int) -> bool:
- """设置 Set 的剩余 TTL。"""
+ """
+ 设置 Set 的剩余 TTL。
+
+ :param key: 查找数据时使用的键
+ :param seconds: 以秒计的时间值
+ :return: 是否设置 Set 的剩余 TTL
+ """
if key not in self.sets:
return False
self.set_expiries[key] = asyncio.get_running_loop().time() + seconds
@@ -80,7 +137,12 @@ async def expire(self, key: str, seconds: int) -> bool:
return True
async def ttl(self, key: str) -> int:
- """返回 Set 的 Redis 风格剩余 TTL。"""
+ """
+ 返回 Set 的 Redis 风格剩余 TTL。
+
+ :param key: 查找数据时使用的键
+ :return: Set 的 Redis 风格剩余 TTL
+ """
self._expire_set_if_needed(key)
expiry = self.set_expiries.get(key)
if key not in self.sets:
@@ -90,20 +152,35 @@ async def ttl(self, key: str) -> int:
return max(0, int(expiry - asyncio.get_running_loop().time()))
def _expire_set_if_needed(self, key: str) -> None:
+ """
+ 清除测试时钟下已经过期的集合。
+
+ :param key: 查找数据时使用的键
+ """
expiry = self.set_expiries.get(key)
if expiry is not None and expiry <= asyncio.get_running_loop().time():
self.sets.pop(key, None)
self.set_expiries.pop(key, None)
async def publish(self, channel: str, message: str) -> int:
+ """
+ 记录发布的频道及消息。
+
+ :param channel: Redis 发布或订阅使用的频道
+ :param message: 与当前结果一起返回的说明
+ :return: 此分支的固定值 ``1``
+ """
self.published.append((channel, message))
return 1
@pytest.fixture(autouse=True)
def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
- """将全局 OIDC 配置固定为 Session 测试所需的基线。"""
+ """
+ 将全局 OIDC 配置固定为 Session 测试所需的基线。
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
values = {
'oidc_enabled': True,
'oidc_sso_absolute_seconds': 8 * 60 * 60,
@@ -119,27 +196,46 @@ def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
def _config() -> OidcConfig:
- """返回当前测试使用的全局 OIDC 配置。"""
+ """
+ 返回当前测试使用的全局 OIDC 配置。
+ :return: 当前测试使用的全局 OIDC 配置
+ """
return OidcConfig
def _config_with_long_remember() -> OidcConfig:
- """创建超过协议上限的 remember-me 配置。"""
+ """
+ 创建超过协议上限的 remember-me 配置。
+
+ :return: 超过协议上限的 remember-me 配置
+ """
config = _config()
config.oidc_sso_remember_absolute_seconds = 8 * 24 * 60 * 60
return config
async def _seed_identity(db: AsyncSession, *, auth_version: int = 2) -> None:
- """写入真实用户和 Subject 事实。"""
+ """
+ 写入真实用户和 Subject 事实。
+
+ :param db: 当前操作使用的数据库会话
+ :param auth_version: 用户认证安全版本
+ """
db.add(SysUser(user_id=1, user_name='session-user', nick_name='Session User', status='0', del_flag='0'))
db.add(SysIdentitySubject(user_id=1, subject_id=_SUBJECT_ID, auth_version=auth_version, create_by='test'))
await db.flush()
async def _create(db: AsyncSession, redis: SessionFakeRedis, *, remember: bool = False) -> tuple[str, SysSsoSession]:
- """创建测试 Session。"""
+ """
+ 创建测试 Session。
+
+ :param db: 当前操作使用的数据库会话
+ :param redis: 覆盖 Session 服务所需字符串、Set 和 publish 语义的 FakeRedis
+ :param remember: 是否记住本次选择
+ :return: 测试 Session
+ """
queue = AfterCommitCoordinator()
result = await SsoSessionService.create(
db,
@@ -240,10 +336,16 @@ async def test_coordinator_runs_all_callbacks_after_first_failure(data_session:
called: list[str] = []
async def fail() -> None:
+ """
+ 记录操作尝试并触发预期故障。
+
+ :raises RuntimeError: 副作用失败
+ """
called.append('first')
raise RuntimeError('副作用失败')
async def succeed() -> None:
+ """记录后续回调已成功执行。"""
called.append('second')
await coordinator.register(fail)
@@ -370,6 +472,13 @@ async def test_revoke_db_failure_does_not_clear_cache(
_, row = await _create(data_session, redis)
async def fail(*args: object, **kwargs: object) -> bool:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RuntimeError: 模拟数据库不可用
+ """
raise RuntimeError('database unavailable')
monkeypatch.setattr(SsoSessionDao, 'revoke', fail)
@@ -409,6 +518,11 @@ async def test_commit_failure_does_not_run_registered_cleanup(
assert await SsoSessionService.revoke(data_session, redis, row.sid, now=_NOW, coordinator=queue)
async def fail_commit() -> None:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :raises RuntimeError: 模拟事务提交失败
+ """
raise RuntimeError('commit failed')
monkeypatch.setattr(data_session, 'commit', fail_commit)
@@ -503,7 +617,7 @@ async def test_create_rotate_touch_cache_writes_wait_for_commit(data_session: As
@pytest.mark.asyncio
async def test_touch_cache_write_waits_for_commit(data_session: AsyncSession) -> None:
- """touch 的缓存刷新在事务回滚时不执行。"""
+ """验证事务回滚时不会执行 touch 的缓存刷新。"""
await _seed_identity(data_session)
redis = SessionFakeRedis()
cookie, _ = await _create(data_session, redis)
@@ -542,6 +656,13 @@ async def test_after_commit_uses_snapshot_and_publishes_when_cache_clear_fails(
snapshot = SsoSessionService._snapshot(row)
async def fail_clear(*args: object, **kwargs: object) -> None:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RuntimeError: 模拟清除 Redis 缓存失败
+ """
raise RuntimeError('redis clear failed')
monkeypatch.setattr(SsoSessionService, '_clear_cache', fail_clear)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_token_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_token_service.py
index 85d42ae7c..9123e575c 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_token_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_token_service.py
@@ -73,7 +73,11 @@ async def test_confidential_auth_marks_only_matching_secret_used(monkeypatch: py
def _config() -> SimpleNamespace:
- """构造最小 JWT/TTL 配置快照。"""
+ """
+ 构造最小 JWT/TTL 配置快照。
+
+ :return: 最小 JWT/TTL 配置快照
+ """
return SimpleNamespace(
oidc_issuer='https://auth.example.com',
oidc_access_token_ttl_seconds=600,
@@ -87,8 +91,11 @@ def _config() -> SimpleNamespace:
@pytest.fixture(autouse=True)
def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
- """将全局 OIDC 配置固定为本文件测试所需的协议值。"""
+ """
+ 将全局 OIDC 配置固定为本文件测试所需的协议值。
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
values = {
'oidc_issuer': 'https://auth.example.com',
'oidc_access_token_ttl_seconds': _DEFAULT_TTL,
@@ -103,7 +110,12 @@ def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
def _client(**overrides: object) -> SimpleNamespace:
- """构造 Token 流程所需的 Client 标量快照。"""
+ """
+ 构造 Token 流程所需的 Client 标量快照。
+
+ :param overrides: 调用方按名称传入的附加选项
+ :return: Token 流程所需的 Client 标量快照
+ """
value: dict[str, object] = {
'client_pk': 1001,
'client_id': 'portal-client',
@@ -120,7 +132,12 @@ def _client(**overrides: object) -> SimpleNamespace:
def _code_payload(**overrides: object) -> dict[str, object]:
- """构造已由 AuthorizationCodeService 验证的 Code 绑定。"""
+ """
+ 构造已由 AuthorizationCodeService 验证的 Code 绑定。
+
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 已由 AuthorizationCodeService 验证的 Code 绑定
+ """
value: dict[str, object] = {
'clientPk': 1001,
'redirectUri': 'https://portal.example/callback',
@@ -157,11 +174,25 @@ async def test_authorization_code_binds_client_redirect_and_pkce(
)
async def identity(*args: object, **kwargs: object) -> tuple[object, object]:
+ """
+ 返回认证依赖解析出的用户标识。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 认证依赖解析出的用户标识
+ """
return SimpleNamespace(user_id=2001, status='0', del_flag='0'), SimpleNamespace(
subject_id='subject-2001', auth_version=4
)
async def session(*args: object, **kwargs: object) -> SimpleNamespace:
+ """
+ 创建测试使用的 ``SimpleNamespace`` 实例。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 测试使用的 ``SimpleNamespace`` 实例
+ """
return SimpleNamespace(
sid='sid-2001',
user_id=2001,
@@ -566,6 +597,13 @@ async def test_signer_loads_private_key_from_same_active_record(monkeypatch: pyt
calls: list[object] = []
async def load(value: object, **kwargs: object) -> object:
+ """
+ 捕获加载请求并提供测试密钥。
+
+ :param value: 待处理的输入值
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 供调用方使用的 ``private_key``
+ """
calls.append(value)
return private_key
@@ -695,6 +733,13 @@ async def test_refresh_concurrent_rotation_has_one_success_and_reuse_revoke(monk
)
async def mark_used(*args: object, **kwargs: object) -> bool:
+ """
+ 记录授权凭据被使用的时间。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 是否记录授权凭据被使用的时间
+ """
state['mark_now'] = kwargs.get('now')
async with lock:
if state['rotated']:
@@ -703,6 +748,13 @@ async def mark_used(*args: object, **kwargs: object) -> bool:
return True
async def reuse(*args: object, **kwargs: object) -> int:
+ """
+ 统计刷新凭据的重复使用次数。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``1``
+ """
state['reuse'] += 1
return 1
@@ -733,9 +785,19 @@ async def reuse(*args: object, **kwargs: object) -> int:
def _async_value(value: object) -> Any:
- """返回异步测试桩。"""
+ """
+ 返回异步测试桩。
+
+ :param value: 待处理的输入值
+ :return: 异步测试桩
+ """
async def result() -> object:
+ """
+ 向调用方返回 ``value``。
+
+ :return: 为此调用预设的值
+ """
return value
return result()
diff --git a/ruoyi-fastapi-backend/tests/module_identity/support/redis_fakes.py b/ruoyi-fastapi-backend/tests/module_identity/support/redis_fakes.py
index 862b0ccc4..ec2e0a0f1 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/support/redis_fakes.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/support/redis_fakes.py
@@ -5,9 +5,18 @@
class FakeRedis:
- """实现本轮服务所用 SET NX、TTL、GET/DEL 和 Lua 等效语义的 FakeRedis。"""
+ """
+ 实现本轮服务所用 SET NX、TTL、GET/DEL 和 Lua 等效语义的 FakeRedis。
+
+ :ivar values: 当前处理的值集合
+ :ivar lists: 模拟 Redis 保存的列表数据
+ :ivar lock: 用于串行访问共享资源的锁
+ :ivar set_calls: 记录 ``set`` 的调用情况
+ :ivar eval_calls: 记录 ``eval`` 的调用情况
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``values``, ``lists``, ``lock``, ``set_calls``。"""
self.values: dict[str, tuple[str, float | None]] = {}
self.lists: dict[str, list[str]] = {}
self.lock = asyncio.Lock()
@@ -15,11 +24,26 @@ def __init__(self) -> None:
self.eval_calls: list[tuple[str, tuple[Any, ...]]] = []
def _purge(self, key: str) -> None:
+ """
+ 清除到期的测试缓存值。
+
+ :param key: 查找数据时使用的键
+ """
item = self.values.get(key)
if item is not None and item[1] is not None and item[1] <= time.monotonic():
self.values.pop(key, None)
async def set(self, key: str, value: str, ex: int | None = None, nx: bool = False, **kwargs: Any) -> bool:
+ """
+ 写入测试缓存键并设置过期时间。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :param ex: 捕获到的异常实例
+ :param nx: 是否只在键尚不存在时写入
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 是否写入测试缓存键并设置过期时间
+ """
async with self.lock:
self._purge(key)
self.set_calls.append((key, {'ex': ex, 'nx': nx, **kwargs}))
@@ -29,36 +53,71 @@ async def set(self, key: str, value: str, ex: int | None = None, nx: bool = Fals
return True
async def get(self, key: str) -> str | None:
+ """
+ 读取测试存储中的指定键。
+
+ :param key: 查找数据时使用的键
+ :return: 测试存储中的指定键
+ """
async with self.lock:
self._purge(key)
value = self.values.get(key)
return value[0] if value else None
async def exists(self, key: str) -> int:
- """按 Redis EXISTS 语义返回键数量。"""
+ """
+ 按 Redis EXISTS 语义返回键数量。
+
+ :param key: 查找数据时使用的键
+ :return: 键存在时为一,否则为零
+ """
async with self.lock:
self._purge(key)
return int(key in self.values)
async def delete(self, key: str) -> int:
+ """
+ 删除测试缓存项及其过期状态。
+
+ :param key: 查找数据时使用的键
+ :return: 实际删除的键数
+ """
async with self.lock:
self._purge(key)
return int(self.values.pop(key, None) is not None)
async def rpush(self, key: str, value: str) -> int:
- """追加队列元素。"""
+ """
+ 追加队列元素。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :return: 追加后的队列长度
+ """
async with self.lock:
self.lists.setdefault(key, []).append(value)
return len(self.lists[key])
async def lpop(self, key: str) -> str | None:
- """原子弹出队首元素。"""
+ """
+ 原子弹出队首元素。
+
+ :param key: 查找数据时使用的键
+ :return: 队首元素,队列为空时返回空值
+ """
async with self.lock:
values = self.lists.get(key, [])
return values.pop(0) if values else None
async def ltrim(self, key: str, start: int, end: int) -> bool:
- """按 Redis 负索引语义裁剪列表。"""
+ """
+ 按 Redis 负索引语义裁剪列表。
+
+ :param key: 查找数据时使用的键
+ :param start: 选取范围的起始位置
+ :param end: 选取范围的结束位置
+ :return: 此分支的固定值 ``True``
+ """
async with self.lock:
values = self.lists.get(key, [])
size = len(values)
@@ -68,6 +127,12 @@ async def ltrim(self, key: str, start: int, end: int) -> bool:
return True
async def ttl(self, key: str) -> int:
+ """
+ 查询测试缓存键的剩余生存时间。
+
+ :param key: 查找数据时使用的键
+ :return: 测试缓存键的剩余生存时间
+ """
async with self.lock:
self._purge(key)
value = self.values.get(key)
@@ -76,6 +141,14 @@ async def ttl(self, key: str) -> int:
return max(0, int(value[1] - time.monotonic()))
async def eval(self, script: str, numkeys: int, *args: Any) -> Any: # noqa: PLR0911, PLR0912
+ """
+ 按测试约定模拟 Redis 脚本的执行。
+
+ :param script: 需要运行的脚本
+ :param numkeys: 传给 Redis 脚本的键数量
+ :param args: 传给被调用对象的位置参数
+ :return: 对应脚本分支的记录、有效期或状态码
+ """
async with self.lock:
self.eval_calls.append((script, args))
key = args[0]
diff --git a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py
index 7caaddfc9..adf64fb96 100644
--- a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py
@@ -25,10 +25,20 @@
def build_request(path: str = '/system/plugin/batch', method: str = 'POST') -> object:
- """构造测试用请求对象。"""
+ """
+ 构造测试用请求对象。
+
+ :param path: 要读取或处理的路径
+ :param method: 当前请求的 HTTP 方法
+ :return: 测试用请求对象
+ """
async def empty_body() -> bytes:
- """返回测试用空请求体。"""
+ """
+ 返回测试用空请求体。
+
+ :return: 此分支的固定值 ``b''``
+ """
return b''
return SimpleNamespace(
@@ -43,7 +53,12 @@ async def empty_body() -> bytes:
def load_response_body(response: object) -> dict:
- """解析测试响应体。"""
+ """
+ 解析测试响应体。
+
+ :param response: 当前调用产生的响应
+ :return: 从响应体解码的 JSON 数据
+ """
return json.loads(response.body.decode())
@@ -68,6 +83,8 @@ def test_plugin_operation_response_hides_exit_code_from_web_payload() -> None:
class FakeAsyncSession:
"""
测试用异步数据库会话。
+
+ :ivar committed: 是否已经提交事务
"""
def __init__(self) -> None:
@@ -81,7 +98,12 @@ async def commit(self) -> None:
@pytest.fixture(autouse=True)
def fake_request_context(monkeypatch: pytest.MonkeyPatch) -> Generator[CurrentUserModel, None, None]:
- """构造日志装饰器所需的最小请求上下文。"""
+ """
+ 构造日志装饰器所需的最小请求上下文。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :yield: 日志装饰器所需的最小请求上下文
+ """
user = CurrentUserModel(
permissions=['*:*:*'],
roles=[],
@@ -91,7 +113,12 @@ def fake_request_context(monkeypatch: pytest.MonkeyPatch) -> Generator[CurrentUs
pattern_token = RequestContext.set_current_exclude_patterns([])
async def fake_enqueue_operation_log(*args: object, **kwargs: object) -> None:
- """记录测试中的操作日志入队请求。"""
+ """
+ 记录测试中的操作日志入队请求。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
monkeypatch.setattr(log_annotation.LogQueueService, 'enqueue_operation_log', fake_enqueue_operation_log)
try:
@@ -107,9 +134,7 @@ async def test_batch_system_plugins_accepts_json_body(monkeypatch: pytest.Monkey
recorded: dict[str, object] = {}
class FakePluginRuntimeService:
- """
- 测试用插件运行时服务。
- """
+ """测试用插件运行时服务。"""
async def batch_plugins(
self,
@@ -119,7 +144,15 @@ async def batch_plugins(
dry_run: bool = True,
continue_on_error: bool = False,
) -> dict[str, object]:
- """记录批量操作参数。"""
+ """
+ 记录批量操作参数。
+
+ :param operation: 操作类型
+ :param plugin_ids: 插件ID列表
+ :param dry_run: 是否只预览操作结果
+ :param continue_on_error: 单项操作失败后是否继续执行
+ :return: 包含 ``ok``、``message`` 的数据
+ """
recorded.update(
{
'operation': operation,
@@ -160,9 +193,7 @@ async def test_install_system_plugin_accepts_dry_run_query_param(
recorded: dict[str, object] = {}
class FakePluginRuntimeService:
- """
- 测试用插件运行时服务。
- """
+ """测试用插件运行时服务。"""
async def install_plugin(
self,
@@ -171,7 +202,14 @@ async def install_plugin(
dry_run: bool = False,
operated_by: str | None = None,
) -> dict[str, object]:
- """记录安装参数。"""
+ """
+ 记录安装参数。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param dry_run: 是否只预览操作结果
+ :param operated_by: 操作者用户名,非预演时写入审计日志
+ :return: 包含 ``ok``、``message`` 的数据
+ """
recorded.update({'plugin_id': plugin_id, 'dry_run': dry_run})
return {'ok': True, 'message': '安装完成'}
@@ -196,9 +234,7 @@ async def test_install_system_plugin_returns_failure_when_runtime_payload_is_not
"""校验安装运行时返回失败时接口返回失败响应。"""
class FakePluginRuntimeService:
- """
- 测试用插件运行时服务。
- """
+ """测试用插件运行时服务。"""
async def install_plugin(
self,
@@ -207,7 +243,14 @@ async def install_plugin(
dry_run: bool = False,
operated_by: str | None = None,
) -> dict[str, object]:
- """返回失败安装结果。"""
+ """
+ 返回失败安装结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param dry_run: 是否只预览操作结果
+ :param operated_by: 操作者用户名,非预演时写入审计日志
+ :return: 失败安装结果
+ """
return {'ok': False, 'message': '插件安装失败', 'pluginId': plugin_id}
monkeypatch.setattr(plugin_controller, 'get_plugin_runtime_service', FakePluginRuntimeService)
@@ -232,9 +275,7 @@ async def test_install_system_plugin_dependencies_forces_dry_run(monkeypatch: py
recorded: dict[str, object] = {}
class FakePluginRuntimeService:
- """
- 测试用插件运行时服务。
- """
+ """测试用插件运行时服务。"""
def install_plugin_dependencies(
self,
@@ -243,7 +284,14 @@ def install_plugin_dependencies(
dry_run: bool = True,
policy_config: object | None = None,
) -> dict[str, object]:
- """记录依赖安装参数。"""
+ """
+ 记录依赖安装参数。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param dry_run: 是否只预览操作结果
+ :param policy_config: 依赖安装策略配置
+ :return: 包含 ``ok``、``message``、``pluginId`` 的数据
+ """
recorded.update({'plugin_id': plugin_id, 'dry_run': dry_run, 'policy_mode': policy_config.mode})
return {'ok': True, 'message': '插件依赖安装演练完成', 'pluginId': plugin_id}
@@ -266,12 +314,17 @@ async def test_enable_system_plugin_returns_runtime_payload_when_not_ok(monkeypa
"""校验启用插件失败时接口透传运行时失败负载。"""
class FakePluginRuntimeService:
- """
- 测试用插件运行时服务。
- """
+ """测试用插件运行时服务。"""
async def set_plugin_enabled(self, plugin_id: str, *, enabled: bool, dry_run: bool = False) -> dict:
- """返回失败启用结果。"""
+ """
+ 返回失败启用结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param enabled: 是否启用该项功能
+ :param dry_run: 是否只预览操作结果
+ :return: 失败启用结果
+ """
return {'ok': False, 'message': '启用失败', 'pluginId': plugin_id, 'enabled': enabled}
monkeypatch.setattr(plugin_controller, 'get_plugin_runtime_service', FakePluginRuntimeService)
@@ -296,12 +349,17 @@ async def test_disable_system_plugin_delegates_runtime_service(monkeypatch: pyte
recorded: dict[str, object] = {}
class FakePluginRuntimeService:
- """
- 测试用插件运行时服务。
- """
+ """测试用插件运行时服务。"""
async def set_plugin_enabled(self, plugin_id: str, *, enabled: bool, dry_run: bool = False) -> dict:
- """记录插件启停参数。"""
+ """
+ 记录插件启停参数。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param enabled: 是否启用该项功能
+ :param dry_run: 是否只预览操作结果
+ :return: 包含 ``ok``、``message``、``pluginId``、``enabled`` 的数据
+ """
recorded.update({'plugin_id': plugin_id, 'enabled': enabled, 'dry_run': dry_run})
return {'ok': True, 'message': '停用成功', 'pluginId': plugin_id, 'enabled': enabled}
@@ -345,9 +403,7 @@ async def test_get_system_plugin_operation_log_list_returns_page_payload(monkeyp
)
class FakePluginService:
- """
- 测试用插件管理服务。
- """
+ """测试用插件管理服务。"""
@classmethod
async def get_plugin_operation_log_page_list_services(
@@ -356,7 +412,14 @@ async def get_plugin_operation_log_page_list_services(
query_object: PluginOperationLogPageQueryModel,
is_page: bool = True,
) -> PageModel[PluginOperationLogDetailModel]:
- """记录审计列表查询参数。"""
+ """
+ 记录审计列表查询参数。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param query_object: 插件批量操作审计日志分页查询模型
+ :param is_page: 是否开启分页
+ :return: 供调用方使用的 ``page_result``
+ """
recorded.update(
{
'query_db': query_db,
@@ -415,9 +478,7 @@ async def test_query_detail_system_plugin_operation_log_returns_payload(monkeypa
)
class FakePluginService:
- """
- 测试用插件管理服务。
- """
+ """测试用插件管理服务。"""
@classmethod
async def plugin_operation_log_detail_services(
@@ -425,7 +486,13 @@ async def plugin_operation_log_detail_services(
query_db: object,
operation_id: int,
) -> PluginOperationLogDetailModel:
- """记录审计详情查询参数。"""
+ """
+ 记录审计详情查询参数。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param operation_id: 操作日志ID
+ :return: 供调用方使用的 ``operation_log``
+ """
recorded.update({'query_db': query_db, 'operation_id': operation_id})
return operation_log
@@ -453,13 +520,16 @@ async def test_query_detail_system_plugin_operation_log_returns_failure_when_mis
"""校验审计详情不存在时返回失败响应。"""
class FakePluginService:
- """
- 测试用插件管理服务。
- """
+ """测试用插件管理服务。"""
@classmethod
async def plugin_operation_log_detail_services(cls, query_db: object, operation_id: int) -> None:
- """返回空审计详情。"""
+ """
+ 返回空审计详情。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param operation_id: 操作日志ID
+ """
return
monkeypatch.setattr(plugin_controller, 'PluginService', FakePluginService)
@@ -489,9 +559,7 @@ async def test_retain_system_plugin_operation_log_commits_session(monkeypatch: p
)
class FakePluginService:
- """
- 测试用插件管理服务。
- """
+ """测试用插件管理服务。"""
@classmethod
async def retain_plugin_operation_log_services(
@@ -499,7 +567,13 @@ async def retain_plugin_operation_log_services(
query_db: object,
retention_model: PluginOperationLogRetentionModel,
) -> PluginOperationLogRetentionResultModel:
- """记录审计保留策略调用参数。"""
+ """
+ 记录审计保留策略调用参数。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param retention_model: 插件批量操作审计日志保留策略模型
+ :return: 供调用方使用的 ``retention_result``
+ """
recorded.update({'query_db': query_db, 'retention_days': retention_model.retention_days})
return retention_result
@@ -540,9 +614,7 @@ async def test_export_system_plugin_operation_log_uses_operation_dict(
)
class FakePluginService:
- """
- 测试用插件管理服务。
- """
+ """测试用插件管理服务。"""
@classmethod
async def get_plugin_operation_log_export_list_services(
@@ -550,7 +622,13 @@ async def get_plugin_operation_log_export_list_services(
query_db: object,
query_object: PluginOperationLogExportQueryModel,
) -> list[PluginOperationLogDetailModel]:
- """记录审计导出查询参数。"""
+ """
+ 记录审计导出查询参数。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param query_object: 插件批量操作审计日志导出查询模型
+ :return: 供导出使用的审计记录列表
+ """
recorded.update({'query_db': query_db, 'export_limit': query_object.export_limit})
return [operation_log]
@@ -560,7 +638,13 @@ def export_plugin_operation_log_list_services(
operation_log_list: list[PluginOperationLogDetailModel],
operation_dict: dict[str, str],
) -> bytes:
- """记录审计导出字典映射。"""
+ """
+ 记录审计导出字典映射。
+
+ :param operation_log_list: 要处理的操作日志记录
+ :param operation_dict: 插件操作类型字典
+ :return: 此分支的固定值 ``b'plugin audit export'``
+ """
recorded.update(
{
'operation_count': len(operation_log_list),
@@ -570,13 +654,16 @@ def export_plugin_operation_log_list_services(
return b'plugin audit export'
class FakePluginOperationService:
- """
- 测试用插件操作服务。
- """
+ """测试用插件操作服务。"""
@classmethod
async def get_plugin_operation_dict_services(cls, query_db: object) -> dict[str, str]:
- """返回测试用操作类型字典。"""
+ """
+ 返回测试用操作类型字典。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :return: 测试用操作类型字典
+ """
recorded['dict_query_db'] = query_db
return {'config_set': '配置保存'}
diff --git a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_diagnostics_controller.py b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_diagnostics_controller.py
index a2516f07c..1251ef49c 100644
--- a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_diagnostics_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_diagnostics_controller.py
@@ -12,6 +12,7 @@
@pytest.mark.asyncio
async def test_diagnose_api_attaches_runtime_without_changing_static_ok(monkeypatch: pytest.MonkeyPatch) -> None:
+ """诊断接口追加运行信息并保留静态检查状态。"""
app = FastAPI()
reporter = object()
app.state.plugin_diagnostics_reporter = reporter
@@ -53,6 +54,7 @@ async def test_diagnose_api_attaches_runtime_without_changing_static_ok(monkeypa
async def test_failed_check_remains_visible_but_generation_failure_keeps_error_envelope(
monkeypatch: pytest.MonkeyPatch, complete: bool
) -> None:
+ """保留失败检查且生成失败时使用标准错误响应。"""
payload = {'ok': False, 'message': '插件诊断包生成完成,发现问题', 'info': {'pluginId': 'demo'}}
if complete:
payload.update(check={'ok': False}, config={}, menuPlan={}, audit={})
diff --git a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_release_controller.py b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_release_controller.py
index 7a3057d29..96b41744a 100644
--- a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_release_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_release_controller.py
@@ -52,6 +52,11 @@ async def test_disabled_feature_returns_clear_blocked_response(monkeypatch: pyte
"""验证功能关闭时返回明确的受限响应。"""
def unavailable() -> None:
+ """
+ 在调用时报告预期的测试失败:签名制品发布功能未启用。
+
+ :raises ValueError: 签名制品发布功能未启用
+ """
raise ValueError('签名制品发布功能未启用')
monkeypatch.setattr(controller, 'get_plugin_deployment_service', unavailable)
@@ -66,6 +71,11 @@ async def test_unexpected_database_error_does_not_expose_connection_details(monk
"""验证意外数据库异常不会将连接细节返回客户端。"""
def unavailable() -> None:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :raises RuntimeError: 模拟含有敏感连接信息的数据库故障
+ """
raise RuntimeError('mysql://secret-user:secret-password@host')
monkeypatch.setattr(controller, 'get_plugin_deployment_service', unavailable)
diff --git a/ruoyi-fastapi-backend/tests/module_plugin/service/test_plugin_service.py b/ruoyi-fastapi-backend/tests/module_plugin/service/test_plugin_service.py
index d57e0072d..186329bca 100644
--- a/ruoyi-fastapi-backend/tests/module_plugin/service/test_plugin_service.py
+++ b/ruoyi-fastapi-backend/tests/module_plugin/service/test_plugin_service.py
@@ -69,12 +69,15 @@ async def test_plugin_diagnose_with_audit_filters_recent_logs(tmp_path: Path) ->
await session.commit()
class FakeRuntimeService:
- """
- 测试用插件运行时服务。
- """
+ """测试用插件运行时服务。"""
async def diagnose_plugin(self, plugin_id: str) -> dict[str, object]:
- """返回测试用插件诊断结果。"""
+ """
+ 返回测试用插件诊断结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 测试用插件诊断结果
+ """
return {
'ok': True,
'message': '插件诊断包生成完成',
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/artifacts/conftest.py b/ruoyi-fastapi-backend/tests/plugins/core/artifacts/conftest.py
index 7002fa1f4..1e89b1bee 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/artifacts/conftest.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/artifacts/conftest.py
@@ -8,7 +8,12 @@
@pytest.fixture
def artifact_source(tmp_path: Path) -> Path:
- """构造包含部署文件和禁止导入哨兵的临时插件目录。"""
+ """
+ 构造包含部署文件和禁止导入哨兵的临时插件目录。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :return: 包含部署文件和禁止导入哨兵的临时插件目录
+ """
source = tmp_path / 'artifact_demo'
source.mkdir()
(source / 'plugin.yaml').write_text(
@@ -35,19 +40,35 @@ def artifact_source(tmp_path: Path) -> Path:
@pytest.fixture
def signing_key() -> Ed25519PrivateKey:
- """生成仅用于当前测试的临时 Ed25519 私钥。"""
+ """
+ 生成仅用于当前测试的临时 Ed25519 私钥。
+
+ :return: 仅用于当前测试的临时 Ed25519 私钥
+ """
return Ed25519PrivateKey.generate()
@pytest.fixture
def trusted_keys(signing_key: Ed25519PrivateKey) -> dict[str, Ed25519PublicKey]:
- """提供与临时签名私钥对应的宿主可信公钥映射。"""
+ """
+ 提供与临时签名私钥对应的宿主可信公钥映射。
+
+ :param signing_key: 生成仅用于当前测试的临时 Ed25519 私钥
+ :return: 与临时签名私钥对应的宿主可信公钥映射
+ """
return {'publisher': signing_key.public_key()}
@pytest.fixture
def artifact_path(tmp_path: Path, artifact_source: Path, signing_key: Ed25519PrivateKey) -> Path:
- """构建供验证和存储测试使用的签名制品。"""
+ """
+ 构建供验证和存储测试使用的签名制品。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param artifact_source: 构造包含部署文件和禁止导入哨兵的临时插件目录
+ :param signing_key: 生成仅用于当前测试的临时 Ed25519 私钥
+ :return: 供验证和存储测试使用的签名制品
+ """
output = tmp_path / 'sample.rpk'
build_artifact(artifact_source, output, signing_key, 'publisher')
return output
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/artifacts/test_package.py b/ruoyi-fastapi-backend/tests/plugins/core/artifacts/test_package.py
index ffe13065d..e5bfef2cd 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/artifacts/test_package.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/artifacts/test_package.py
@@ -22,13 +22,25 @@
def archive_files(path: Path) -> dict[str, bytes]:
- """读取测试容器中的全部文件,供定向篡改用例使用。"""
+ """
+ 读取测试容器中的全部文件,供定向篡改用例使用。
+
+ :param path: 要读取或处理的路径
+ :return: 测试容器中的全部文件
+ """
with ZipFile(path) as archive:
return {name: archive.read(name) for name in archive.namelist()}
def write_archive(path: Path, files: dict[str, bytes], compression: int = ZIP_STORED) -> Path:
- """按测试给定内容重建 ZIP 容器。"""
+ """
+ 按测试给定内容重建 ZIP 容器。
+
+ :param path: 要读取或处理的路径
+ :param files: 此次操作涉及的文件
+ :param compression: 写入归档时采用的压缩方式
+ :return: 要读取或处理的路径
+ """
with ZipFile(path, 'w', compression=compression) as archive:
for name, data in files.items():
archive.writestr(name, data)
@@ -36,7 +48,14 @@ def write_archive(path: Path, files: dict[str, bytes], compression: int = ZIP_ST
def signed_files(artifact_path: Path, signing_key: Ed25519PrivateKey, *, manifest: bytes) -> dict[str, bytes]:
- """生成测试所需的规范元数据及有效签名文档。"""
+ """
+ 生成测试所需的规范元数据及有效签名文档。
+
+ :param artifact_path: 插件制品在文件系统中的路径
+ :param signing_key: 生成仅用于当前测试的临时 Ed25519 私钥
+ :param manifest: 用于生成签名制品的插件清单
+ :return: 测试所需的规范元数据及有效签名文档
+ """
files = archive_files(artifact_path)
name = 'payload/artifact_demo/plugin.yaml'
files[name] = manifest
@@ -368,6 +387,12 @@ def test_central_directory_is_bounded_before_zipfile_allocates(
artifact_path.write_bytes(data)
def allocation_forbidden(*args: object, **kwargs: object) -> None:
+ """
+ 若执行到此操作则立即使测试失败。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
pytest.fail('ZipFile must not allocate an unbounded inventory before preflight')
monkeypatch.setattr(artifact_package, 'ZipFile', allocation_forbidden)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/artifacts/test_store.py b/ruoyi-fastapi-backend/tests/plugins/core/artifacts/test_store.py
index e94d79dee..ddbe29b44 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/artifacts/test_store.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/artifacts/test_store.py
@@ -15,10 +15,23 @@
def _parallel_import(root: str, artifact_path: str, public_key: bytes, gate: Any) -> tuple[str, str]:
- """在独立进程中同步校验起点,使并发导入争用同一制品目标。"""
+ """
+ 在独立进程中同步校验起点,使并发导入争用同一制品目标。
+
+ :param root: 路径解析的基准目录
+ :param artifact_path: 插件制品在文件系统中的路径
+ :param public_key: RSA 公钥
+ :param gate: 控制操作何时继续的同步信号
+ :return: 制品存储路径及摘要
+ """
checked = False
def check_candidate(candidate: StoredArtifact) -> None:
+ """
+ 检查插件候选目录和清单的状态。
+
+ :param candidate: 完成验证的不可变存储信息,供平台预检与发布服务读取
+ """
nonlocal checked
assert (candidate.plugin_path / 'plugin.yaml').is_file()
if not checked:
@@ -32,14 +45,23 @@ def check_candidate(candidate: StoredArtifact) -> None:
def _assert_staging_empty(root: Path) -> None:
- """检查本次导入没有遗留暂存目录。"""
+ """
+ 检查本次导入没有遗留暂存目录。
+
+ :param root: 路径解析的基准目录
+ """
staging = root / '.staging'
assert staging.is_dir()
assert list(staging.iterdir()) == []
def _file_snapshot(root: Path) -> dict[str, tuple[bytes, int]]:
- """记录存储文件内容和修改时间以比较幂等导入结果。"""
+ """
+ 记录存储文件内容和修改时间以比较幂等导入结果。
+
+ :param root: 路径解析的基准目录
+ :return: 相对路径到文件内容和修改时间的映射
+ """
return {
path.relative_to(root).as_posix(): (path.read_bytes(), path.stat().st_mtime_ns)
for path in root.rglob('*')
@@ -86,6 +108,11 @@ def test_repeated_import_keeps_existing_bytes_and_modification_times(
checked_paths: list[Path] = []
def check_candidate(candidate: StoredArtifact) -> None:
+ """
+ 检查插件候选目录和清单的状态。
+
+ :param candidate: 完成验证的不可变存储信息,供平台预检与发布服务读取
+ """
checked_paths.append(candidate.root_path)
second = store.import_artifact(artifact_path, trusted_keys, validate_candidate=check_candidate)
@@ -148,6 +175,13 @@ def test_candidate_failure_never_publishes_or_removes_unrelated_staging(
expected = verify_artifact(artifact_path, trusted_keys)
def check_candidate(candidate: StoredArtifact) -> bool:
+ """
+ 检查插件候选目录和清单的状态。
+
+ :param candidate: 完成验证的不可变存储信息,供平台预检与发布服务读取
+ :raises RuntimeError: 模拟候选制品未通过平台校验
+ :return: 是否插件候选目录和清单的状态
+ """
if failure == 'raise':
raise RuntimeError('platform validation failed')
if failure == 'mutate':
@@ -175,6 +209,12 @@ def test_async_candidate_validation_is_rejected_instead_of_being_skipped(
executed = False
async def check_candidate(candidate: StoredArtifact) -> bool:
+ """
+ 检查插件候选目录和清单的状态。
+
+ :param candidate: 完成验证的不可变存储信息,供平台预检与发布服务读取
+ :return: 此分支的固定值 ``False``
+ """
nonlocal executed
executed = True
return False
@@ -200,6 +240,14 @@ def test_extraction_failure_cleans_only_its_private_directory(
sentinel.write_text('keep', encoding='utf-8')
def fail_extract(snapshot: Path, candidate: Path, verified: VerifiedArtifact) -> None:
+ """
+ 在候选目录留下部分内容后模拟解包失败。
+
+ :param snapshot: 用于比较状态的快照
+ :param candidate: 待校验的候选项
+ :param verified: 完成静态校验的容器信息,不替代文件变化后的重新验证
+ :raises OSError: 模拟磁盘已满而无法解包
+ """
assert snapshot.is_file()
assert verified.plugin_id
candidate.mkdir()
@@ -269,6 +317,12 @@ def test_import_verifies_the_private_snapshot_after_source_is_replaced(
snapshot = store._snapshot
def snapshot_then_replace_source(source: Path, target: Path) -> None:
+ """
+ 创建交付物快照后替换原始文件。
+
+ :param source: 本次文件操作的源路径
+ :param target: 本次操作的目标
+ """
snapshot(source, target)
source.write_bytes(b'original upload was replaced after snapshot')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/conftest.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/conftest.py
index 2c49863fe..0b9e08dc9 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/conftest.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/conftest.py
@@ -31,14 +31,18 @@ def isolate_catalog_lifecycle_lock(monkeypatch: pytest.MonkeyPatch) -> None:
为临时数据库测试显式替换导入锁,避免连接开发环境 Redis。
:param monkeypatch: pytest 替换工具
- :return: None
"""
monkeypatch.setattr('plugins.core.deployment.catalog.RedisPluginLifecycleLock', NoopPluginLifecycleLock)
@pytest_asyncio.fixture
async def deployment_sessions(tmp_path: Path) -> AsyncIterator[async_sessionmaker[AsyncSession]]:
- """创建包含发布及必要宿主表的临时 SQLite 会话工厂。"""
+ """
+ 创建包含发布及必要宿主表的临时 SQLite 会话工厂。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :yield: 包含发布及必要宿主表的临时 SQLite 会话工厂
+ """
engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "deployment.sqlite"}')
async with engine.begin() as connection:
await connection.run_sync(
@@ -67,13 +71,23 @@ async def deployment_sessions(tmp_path: Path) -> AsyncIterator[async_sessionmake
@pytest.fixture
def deployment_key() -> Ed25519PrivateKey:
- """生成发布测试使用的临时签名私钥。"""
+ """
+ 生成发布测试使用的临时签名私钥。
+
+ :return: 发布测试使用的临时签名私钥
+ """
return Ed25519PrivateKey.generate()
@pytest.fixture
def deployment_config(tmp_path: Path, deployment_key: Ed25519PrivateKey) -> PluginDeploymentConfig:
- """构造独立存储目录与受限发布者公钥配置。"""
+ """
+ 构造独立存储目录与受限发布者公钥配置。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param deployment_key: 生成发布测试使用的临时签名私钥
+ :return: 独立存储目录与受限发布者公钥配置
+ """
backend = tmp_path / 'host'
(backend / 'plugins').mkdir(parents=True)
trust_file = tmp_path / 'trusted-publishers.json'
@@ -98,7 +112,12 @@ def deployment_config(tmp_path: Path, deployment_key: Ed25519PrivateKey) -> Plug
@pytest.fixture
def deployment_source(tmp_path: Path) -> Path:
- """创建用于验证静态维护边界的临时部署目录。"""
+ """
+ 创建用于验证静态维护边界的临时部署目录。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :return: 用于验证静态维护边界的临时部署目录
+ """
source = tmp_path / 'artifact_demo'
source.mkdir()
(source / 'plugin.yaml').write_text(
@@ -125,7 +144,14 @@ def deployment_source(tmp_path: Path) -> Path:
@pytest.fixture
def deployment_archive(tmp_path: Path, deployment_source: Path, deployment_key: Ed25519PrivateKey) -> Path:
- """构建发布服务测试使用的签名制品。"""
+ """
+ 构建发布服务测试使用的签名制品。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param deployment_source: 创建用于验证静态维护边界的临时部署目录
+ :param deployment_key: 生成发布测试使用的临时签名私钥
+ :return: 发布服务测试使用的签名制品
+ """
path = tmp_path / 'deployment.rpk'
build_artifact(deployment_source, path, deployment_key, 'publisher')
return path
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py
index 11d8fd148..ab454b148 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py
@@ -19,7 +19,14 @@
def worker(worker_id: str, plugin_id: str = '__runtime__', **changes: object) -> dict:
- """创建与数据库只读 status 一致的宿主或插件报告。"""
+ """
+ 创建与数据库只读 status 一致的宿主或插件报告。
+
+ :param worker_id: 工作进程的标识
+ :param plugin_id: 插件清单中的唯一标识
+ :param changes: 调用方按名称传入的附加选项
+ :return: 与数据库只读 status 一致的宿主或插件报告
+ """
return {
'workerId': worker_id,
'pluginId': plugin_id,
@@ -34,7 +41,12 @@ def worker(worker_id: str, plugin_id: str = '__runtime__', **changes: object) ->
def ready(*worker_ids: str) -> list[dict]:
- """生成指定 worker 的宿主与插件配对就绪报告。"""
+ """
+ 生成指定 worker 的宿主与插件配对就绪报告。
+
+ :param worker_ids: 调用方传入的其余位置参数
+ :return: 指定 worker 的宿主与插件配对就绪报告
+ """
return [worker(worker_id, plugin_id) for worker_id in worker_ids for plugin_id in ('__runtime__', PLUGIN_ID)]
@@ -46,7 +58,16 @@ def payload(
expected: int = 2,
enabled: bool = True,
) -> dict:
- """使用既有聚合器生成读取时刻的摘要,后续测试单独推进返回时刻。"""
+ """
+ 使用既有聚合器生成读取时刻的摘要,后续测试单独推进返回时刻。
+
+ :param reports: 保存各工作进程报告的集合
+ :param digest: 用于验证内容完整性的摘要
+ :param generation: 当前发布或部署的代次
+ :param expected: 断言使用的预期结果
+ :param enabled: 是否启用该项功能
+ :return: 包含 ``ok``、``releases``、``workers`` 的数据
+ """
reports = reports or []
summary = aggregate_release(
{
@@ -75,23 +96,44 @@ def payload(
class Clock:
- """推进轮询时钟而不执行真实等待,不替换 asyncio 事件循环自身时钟。"""
+ """
+ 推进轮询时钟而不执行真实等待,不替换 asyncio 事件循环自身时钟。
+
+ :ivar now: 当前场景使用的基准时间
+ :ivar delays: 延迟执行时记录的等待时间
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``now``, ``delays``。"""
self.now = 0.0
self.delays: list[float] = []
def monotonic(self) -> float:
+ """
+ 向调用方返回 ``self.now``。
+
+ :return: 测试时钟记录的当前时刻
+ """
return self.now
async def sleep(self, delay: float) -> None:
+ """
+ 在事务关闭后记录重试等待时间。
+
+ :param delay: 延迟时长
+ """
self.delays.append(delay)
self.now += delay
@pytest.fixture(autouse=True)
def clock(monkeypatch: pytest.MonkeyPatch) -> Clock:
- """隔离单调时钟与返回时刻,确保超时测试不消耗真实秒数。"""
+ """
+ 隔离单调时钟与返回时刻,确保超时测试不消耗真实秒数。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: 待处理的输入值
+ """
value = Clock()
monkeypatch.setattr(convergence, 'monotonic', value.monotonic)
monkeypatch.setattr(convergence, 'sleep', value.sleep)
@@ -100,7 +142,13 @@ def clock(monkeypatch: pytest.MonkeyPatch) -> Clock:
async def wait(reader: object, **changes: object) -> dict:
- """使用固定身份调用被测等待器,同时允许单项参数边界覆盖。"""
+ """
+ 使用固定身份调用被测等待器,同时允许单项参数边界覆盖。
+
+ :param reader: 读取输入内容的对象
+ :param changes: 调用方按名称传入的附加选项
+ :return: 目标发布的收敛状态
+ """
options = {
'plugin_id': PLUGIN_ID,
'digest': DIGEST,
@@ -116,6 +164,7 @@ async def wait(reader: object, **changes: object) -> dict:
@pytest.mark.asyncio
async def test_assertion_accepts_every_live_worker_and_capacity_lower_bound_without_writing(clock: Clock) -> None:
+ """只读验收全部在线工作进程及最低容量。"""
state = payload(ready(WORKER, OTHER, EXTRA))
state['releases'][0].update(prepareStatus='failed', preparedDigest='f' * 64, lastError='private-password')
state['workers'][0]['error'] = 'private-worker-error'
@@ -147,6 +196,7 @@ async def test_assertion_accepts_every_live_worker_and_capacity_lower_bound_with
@pytest.mark.asyncio
async def test_wait_reads_new_snapshots_until_all_workers_converge(clock: Clock) -> None:
+ """持续读取新快照直到全部工作进程收敛。"""
reader = AsyncMock(side_effect=[payload(), payload(ready(WORKER)), payload(ready(WORKER, OTHER))])
result = await wait(reader)
expected_attempts = 3
@@ -167,6 +217,7 @@ async def test_wait_reads_new_snapshots_until_all_workers_converge(clock: Clock)
],
)
async def test_assertion_rejects_short_capacity_orphans_and_extra_mismatched_live_worker(reports: list[dict]) -> None:
+ """验收拒绝容量不足、孤立进程及不匹配的额外进程。"""
result = await wait(AsyncMock(return_value=payload(reports)), timeout_seconds=0)
assert result['reason'] == 'not_converged' and result['ok'] is False
@@ -181,6 +232,7 @@ async def test_assertion_rejects_short_capacity_orphans_and_extra_mismatched_liv
],
)
async def test_changed_target_generation_or_recorded_capacity_is_never_followed(changes: dict, clock: Clock) -> None:
+ """目标代次或记录容量改变时不追随新值。"""
reader = AsyncMock(side_effect=[payload(**changes), payload(ready(WORKER, OTHER))])
result = await wait(reader)
assert result['reason'] == 'target_changed' and result['ok'] is False
@@ -192,12 +244,14 @@ async def test_changed_target_generation_or_recorded_capacity_is_never_followed(
@pytest.mark.asyncio
@pytest.mark.parametrize('state', [{'ok': True, 'releases': [], 'workers': []}, payload(digest=None)])
async def test_missing_release_or_target_stops_immediately(state: dict) -> None:
+ """发布或目标缺失时立即停止。"""
result = await wait(AsyncMock(return_value=state))
assert result['reason'] == 'target_missing' and result['attempts'] == 1
@pytest.mark.asyncio
async def test_disabled_target_cannot_pass_active_acceptance() -> None:
+ """已停用的目标无法通过启用状态验收。"""
reports = ready(WORKER, OTHER)
for row in reports:
if row['pluginId'] == PLUGIN_ID:
@@ -210,6 +264,7 @@ async def test_disabled_target_cannot_pass_active_acceptance() -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('failed_plugin_id', ['__runtime__', PLUGIN_ID])
async def test_any_live_worker_failure_stops_even_when_summary_is_partial(failed_plugin_id: str) -> None:
+ """即使摘要不完整也会因在线进程失败而停止。"""
reports = ready(WORKER, OTHER)
next(row for row in reports if row['workerId'] == OTHER and row['pluginId'] == failed_plugin_id)['state'] = 'failed'
result = await wait(AsyncMock(return_value=payload(reports)))
@@ -219,6 +274,7 @@ async def test_any_live_worker_failure_stops_even_when_summary_is_partial(failed
@pytest.mark.asyncio
async def test_historical_stale_and_stopped_hosts_do_not_block_replaced_cluster() -> None:
+ """已替换集群不受过期或已停止的历史主机阻塞。"""
reports = [
*ready(WORKER, OTHER),
worker(EXTRA, heartbeatTime=(NOW - timedelta(seconds=61)).isoformat()),
@@ -230,6 +286,7 @@ async def test_historical_stale_and_stopped_hosts_do_not_block_replaced_cluster(
@pytest.mark.asyncio
async def test_status_that_expires_before_return_cannot_pass(monkeypatch: pytest.MonkeyPatch) -> None:
+ """返回前已过期的状态无法通过验收。"""
reports = ready(WORKER, OTHER)
for row in reports:
row['heartbeatTime'] = (NOW - timedelta(seconds=59)).isoformat()
@@ -245,6 +302,7 @@ async def test_status_that_expires_before_return_cannot_pass(monkeypatch: pytest
@pytest.mark.asyncio
async def test_future_heartbeat_is_excluded_from_ready_capacity() -> None:
+ """未来心跳不计入就绪容量。"""
reports = ready(WORKER, OTHER)
for row in reports:
row['heartbeatTime'] = (NOW + timedelta(seconds=1)).isoformat()
@@ -255,6 +313,7 @@ async def test_future_heartbeat_is_excluded_from_ready_capacity() -> None:
@pytest.mark.asyncio
async def test_database_failure_stops_with_last_observation_without_private_exception() -> None:
+ """数据库失败时返回最后观测且不泄露内部异常。"""
reader = AsyncMock(side_effect=[payload(ready(WORKER)), ConnectionError('private-db-password')])
result = await wait(reader)
assert result['reason'] == 'unavailable' and result['attempts'] == len(reader.await_args_list)
@@ -264,6 +323,7 @@ async def test_database_failure_stops_with_last_observation_without_private_exce
@pytest.mark.asyncio
async def test_polling_stops_on_total_deadline_and_sleep_never_overshoots(clock: Clock) -> None:
+ """轮询遵守总截止时间且休眠不超过剩余时间。"""
result = await wait(AsyncMock(return_value=payload()), timeout_seconds=5)
expected_attempts = 3
expected_elapsed = 5
@@ -274,7 +334,15 @@ async def test_polling_stops_on_total_deadline_and_sleep_never_overshoots(clock:
@pytest.mark.asyncio
async def test_active_result_returned_after_deadline_is_still_timeout(clock: Clock) -> None:
+ """超过截止时间才返回的启用结果仍视为超时。"""
+
async def reader(plugin_id: str) -> dict:
+ """
+ 推进测试时钟并返回工作进程状态。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 工作进程状态
+ """
clock.now = 6
return payload(ready(WORKER, OTHER))
@@ -294,7 +362,16 @@ async def test_read_timeout_is_bounded_and_classified_by_budget_source(
read_timeout: float,
reason: str,
) -> None:
+ """按预算来源限制并归类读取超时。"""
+
def time_out(tasks: set, *, timeout: float) -> tuple[set, set]:
+ """
+ 推进测试时钟以模拟读取超时。
+
+ :param tasks: 当前场景中正在跟踪的任务
+ :param timeout: 等待操作完成的超时限制
+ :return: 空的已完成集合及仍待处理的任务
+ """
assert timeout == read_timeout
clock.now += timeout
return set(), tasks
@@ -309,9 +386,17 @@ def time_out(tasks: set, *, timeout: float) -> tuple[set, set]:
async def test_timer_before_monotonic_deadline_cannot_become_unavailable_or_late_success(
clock: Clock, swallow_cancel: bool
) -> None:
+ """单调时钟截止前触发计时器不会误报不可用或迟到成功。"""
cleaned = asyncio.Event()
async def reader(plugin_id: str) -> dict:
+ """
+ 推进测试时钟并返回工作进程状态。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 工作进程状态
+ :raises asyncio.CancelledError: 异步操作被取消时
+ """
try:
await asyncio.Future()
except asyncio.CancelledError:
@@ -330,6 +415,7 @@ async def reader(plugin_id: str) -> dict:
@pytest.mark.asyncio
async def test_reader_own_timeout_is_unavailable_even_when_total_budget_limits_read() -> None:
+ """即使总预算限制读取也将读取器自身超时记为不可用。"""
reader = AsyncMock(side_effect=TimeoutError('private-query-timeout'))
result = await wait(reader, timeout_seconds=0.01)
assert result['reason'] == 'unavailable' and result['ok'] is False
@@ -341,10 +427,16 @@ async def test_reader_own_timeout_is_unavailable_even_when_total_budget_limits_r
async def test_cancellation_propagates_and_does_not_continue_polling(
monkeypatch: pytest.MonkeyPatch, phase: str
) -> None:
+ """取消信号向上传播并终止轮询。"""
entered = asyncio.Event()
finished = asyncio.Event()
async def blocked(value: object) -> dict:
+ """
+ 将调用保持在等待状态以验证取消行为。
+
+ :param value: 待处理的输入值
+ """
entered.set()
try:
await asyncio.Future()
@@ -381,6 +473,7 @@ async def blocked(value: object) -> dict:
],
)
async def test_invalid_pins_or_time_limits_do_not_query(changes: dict) -> None:
+ """无效的固定目标或时间限制不会触发查询。"""
reader = AsyncMock()
with pytest.raises(ValueError):
await wait(reader, **changes)
@@ -405,6 +498,7 @@ async def test_invalid_pins_or_time_limits_do_not_query(changes: dict) -> None:
],
)
async def test_contradictory_or_malformed_summary_never_becomes_success(changes: dict) -> None:
+ """矛盾或格式错误的摘要无法通过验收。"""
state = payload(ready(WORKER, OTHER))
state['releases'][0].update(changes)
result = await wait(AsyncMock(return_value=state))
@@ -414,6 +508,7 @@ async def test_contradictory_or_malformed_summary_never_becomes_success(changes:
@pytest.mark.asyncio
@pytest.mark.parametrize('field', ['targetDigest', 'generation', 'liveWorkers', 'enabled'])
async def test_missing_summary_field_returns_structured_failure(field: str) -> None:
+ """缺少摘要字段时返回结构化错误。"""
state = payload(ready(WORKER, OTHER))
state['releases'][0].pop(field)
result = await wait(AsyncMock(return_value=state))
@@ -423,6 +518,7 @@ async def test_missing_summary_field_returns_structured_failure(field: str) -> N
@pytest.mark.asyncio
@pytest.mark.parametrize('collection', ['releases', 'workers'])
async def test_duplicate_summary_or_worker_rows_are_rejected(collection: str) -> None:
+ """拒绝重复摘要或工作进程记录。"""
state = payload(ready(WORKER, OTHER))
state[collection].append(deepcopy(state[collection][0]))
result = await wait(AsyncMock(return_value=state))
@@ -432,6 +528,7 @@ async def test_duplicate_summary_or_worker_rows_are_rejected(collection: str) ->
@pytest.mark.asyncio
@pytest.mark.parametrize('field', ['digest', 'generation', 'version', 'heartbeatTime', 'state', 'workerId'])
async def test_missing_raw_worker_fields_cannot_pass_via_summary(field: str) -> None:
+ """缺少进程原始字段时不能仅凭摘要通过。"""
state = payload(ready(WORKER, OTHER))
state['workers'][0].pop(field)
result = await wait(AsyncMock(return_value=state))
@@ -450,6 +547,7 @@ async def test_missing_raw_worker_fields_cannot_pass_via_summary(field: str) ->
],
)
async def test_invalid_worker_state_identity_or_naive_time_is_fail_closed(changes: dict) -> None:
+ """无效进程状态、身份或无时区时刻导致验收失败。"""
state = payload(ready(WORKER, OTHER))
state['workers'][0].update(changes)
result = await wait(AsyncMock(return_value=state))
@@ -458,6 +556,7 @@ async def test_invalid_worker_state_identity_or_naive_time_is_fail_closed(change
@pytest.mark.asyncio
async def test_target_change_after_pending_observation_keeps_original_pin() -> None:
+ """待定观测后的目标变更保留原固定目标。"""
reader = AsyncMock(side_effect=[payload(), payload(generation='f' * 32), payload(ready(WORKER, OTHER))])
result = await wait(reader)
expected_attempts = 2
@@ -476,6 +575,7 @@ async def test_target_change_after_pending_observation_keeps_original_pin() -> N
],
)
async def test_unavailable_or_malformed_payload_is_structured_and_redacted(state: object, reason: str) -> None:
+ """不可用或格式错误的响应返回脱敏的结构化信息。"""
result = await wait(AsyncMock(return_value=state))
assert result['reason'] == reason and result['lastObserved'] is None
assert 'private-error' not in str(result)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_deployment_catalog.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_deployment_catalog.py
index f56cabbbc..a4deb1d3a 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_deployment_catalog.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_deployment_catalog.py
@@ -127,8 +127,17 @@ async def test_database_failure_leaves_valid_object_for_idempotent_retry(
"""验证索引写入失败后保留完整对象以支持幂等重试。"""
class FailingDao(PluginReleaseDao):
+ """在制品登记流程中模拟数据访问失败。"""
+
@classmethod
async def register_artifact(cls, db: AsyncSession, **kwargs: Any) -> SysPluginArtifact:
+ """
+ 在制品登记后注入索引事务故障。
+
+ :param db: 当前操作使用的数据库会话
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RuntimeError: 模拟制品索引事务失败
+ """
await super().register_artifact(db, **kwargs)
raise RuntimeError('index transaction failed')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_enablement.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_enablement.py
index ab227cfdf..10376d3bb 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_enablement.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_enablement.py
@@ -41,7 +41,14 @@ class EnablementRuntime(MaintenanceRuntime):
"""模拟启停预检结果及并发状态变化的维护运行时。"""
async def set_plugin_enabled(self, plugin_id: str, *, enabled: bool, dry_run: bool) -> dict[str, Any]:
- """返回测试指定的启停预检结果。"""
+ """
+ 返回测试指定的启停预检结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param enabled: 是否启用该项功能
+ :param dry_run: 是否只预览操作结果
+ :return: 测试指定的启停预检结果
+ """
owner: EnablementFactory = self.owner
owner.checks.append((plugin_id, enabled, dry_run))
if owner.before_check is not None:
@@ -50,23 +57,44 @@ async def set_plugin_enabled(self, plugin_id: str, *, enabled: bool, dry_run: bo
class EnablementFactory(MaintenanceFactory):
- """记录启停运行时创建信息的测试工厂。"""
+ """
+ 记录启停运行时创建信息的测试工厂。
+
+ :ivar checks: 已执行检查的记录
+ :ivar before_check: 在执行检查之前调用的回调
+ :ivar reject: 测试是否模拟拒绝当前请求
+ """
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
- """初始化预检结果与回调记录。"""
+ """
+ 初始化预检结果与回调记录。
+
+ :param sessions: 创建当前测试的数据库会话的工厂
+ """
super().__init__(sessions)
self.checks: list[tuple[str, bool, bool]] = []
self.before_check: Callable[[], Awaitable[None]] | None = None
self.reject = False
def __call__(self, config: PluginDeploymentConfig, plugins: list[DiscoveredPlugin]) -> EnablementRuntime:
- """根据测试配置创建启停维护运行时。"""
+ """
+ 根据测试配置创建启停维护运行时。
+
+ :param config: 制品发布配置快照,支持为测试和维护实例注入独立目录
+ :param plugins: 参与当前操作的插件集合
+ :return: ``EnablementRuntime`` 实例
+ """
return EnablementRuntime(self, plugins)
@pytest.fixture
def enablement_factory(deployment_sessions: async_sessionmaker[AsyncSession]) -> EnablementFactory:
- """提供可注入预检行为的维护运行时工厂。"""
+ """
+ 提供可注入预检行为的维护运行时工厂。
+
+ :param deployment_sessions: 部署流程使用的会话工厂
+ :return: 可注入预检行为的维护运行时工厂
+ """
return EnablementFactory(deployment_sessions)
@@ -77,7 +105,15 @@ def enablement_service(
enablement_factory: EnablementFactory,
monkeypatch: pytest.MonkeyPatch,
) -> PluginArtifactEnablementService:
- """创建使用临时数据库和测试维护运行时的启停服务。"""
+ """
+ 创建使用临时数据库和测试维护运行时的启停服务。
+
+ :param deployment_sessions: 部署流程使用的会话工厂
+ :param deployment_config: 构造独立存储目录与受限发布者公钥配置
+ :param enablement_factory: 提供可注入预检行为的维护运行时工厂
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: 使用临时数据库和测试维护运行时的启停服务
+ """
monkeypatch.setattr(sys, 'dont_write_bytecode', sys.dont_write_bytecode)
return PluginArtifactEnablementService(
deployment_config,
@@ -89,7 +125,14 @@ def enablement_service(
@pytest.fixture
def resource_archive(deployment_source: Path, deployment_key: Ed25519PrivateKey, tmp_path: Path) -> Path:
- """构建带菜单与任务声明的签名测试制品。"""
+ """
+ 构建带菜单与任务声明的签名测试制品。
+
+ :param deployment_source: 创建用于验证静态维护边界的临时部署目录
+ :param deployment_key: 生成发布测试使用的临时签名私钥
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :return: 带菜单与任务声明的签名测试制品
+ """
manifest = yaml.safe_load((deployment_source / 'plugin.yaml').read_text(encoding='utf-8'))
manifest['backend']['jobs'] = [
{
@@ -108,7 +151,12 @@ def resource_archive(deployment_source: Path, deployment_key: Ed25519PrivateKey,
async def _seed_resources(sessions: async_sessionmaker[AsyncSession], *, disabled: bool = False) -> None:
- """在临时数据库中写入启停测试需要的声明资源。"""
+ """
+ 在临时数据库中写入启停测试需要的声明资源。
+
+ :param sessions: 创建当前测试的数据库会话的工厂
+ :param disabled: 是否将目标标记为停用
+ """
status = '1' if disabled else '0'
async with sessions() as db:
plugin = await db.get(SysPlugin, PLUGIN_ID)
@@ -147,14 +195,26 @@ async def selected_release(
resource_archive: Path,
deployment_sessions: async_sessionmaker[AsyncSession],
) -> dict[str, Any]:
- """准备已完成维护且已选择目标的发布记录。"""
+ """
+ 准备已完成维护且已选择目标的发布记录。
+
+ :param enablement_service: 创建使用临时数据库和测试维护运行时的启停服务
+ :param resource_archive: 构建带菜单与任务声明的签名测试制品
+ :param deployment_sessions: 部署流程使用的会话工厂
+ :return: 供调用方使用的 ``selected``
+ """
selected = await import_prepare_select(enablement_service, resource_archive)
await _seed_resources(deployment_sessions)
return selected
async def _snapshot(sessions: async_sessionmaker[AsyncSession]) -> dict[str, Any]:
- """读取发布状态、插件状态及声明资源的完整比较快照。"""
+ """
+ 读取发布状态、插件状态及声明资源的完整比较快照。
+
+ :param sessions: 创建当前测试的数据库会话的工厂
+ :return: 发布状态、插件状态及声明资源的完整比较快照
+ """
async with sessions() as db:
plugin = await db.get(SysPlugin, PLUGIN_ID)
release = await db.get(SysPluginRelease, PLUGIN_ID)
@@ -274,6 +334,14 @@ async def test_audit_failure_rolls_back_generation_plugin_menu_and_job_updates(
before = await _snapshot(deployment_sessions)
async def failed_audit(db: AsyncSession, payload: dict[str, Any], actor: str | None) -> None:
+ """
+ 模拟审计写入失败以检验事务处理。
+
+ :param db: 当前操作使用的数据库会话
+ :param payload: 随调用传入或返回的结构化数据
+ :param actor: 发起操作的主体
+ :raises RuntimeError: 模拟审计服务不可用
+ """
assert (await db.get(SysPlugin, PLUGIN_ID)).enabled == '1'
assert (await db.get(SysMenu, PLUGIN_MENU_ID)).status == '1'
assert (await db.get(SysJob, FIRST_JOB_ID)).status == '1'
@@ -324,6 +392,7 @@ async def test_precheck_race_cannot_apply_enablement_against_changed_preparation
after_concurrent_change: dict[str, Any] = {}
async def concurrent_change() -> None:
+ """在独立事务中写入并发更改。"""
async with deployment_sessions() as db:
if changed_field == 'installed_version':
await db.execute(
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_maintenance.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_maintenance.py
index 5c187144a..fcb8c0709 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_maintenance.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_maintenance.py
@@ -70,12 +70,7 @@ def rotated_archive(deployment_config: Any, deployment_source: Path, tmp_path: P
@pytest.mark.asyncio
async def test_prune_defaults_are_readonly_and_keep_recent(maintenance: Any) -> None:
- """
- 验证默认预演保留最近导入对象。
-
- :param maintenance: 维护服务与制品
- :return: None
- """
+ """验证默认预演保留最近导入对象。"""
service, stored = maintenance
plan = await service.prune()
assert plan['dryRun'] and not plan['candidates']
@@ -86,13 +81,7 @@ async def test_prune_defaults_are_readonly_and_keep_recent(maintenance: Any) ->
@pytest.mark.asyncio
@pytest.mark.parametrize('reference', ['target_digest', 'previous_digest', 'prepared_digest', 'worker'])
async def test_prune_protects_release_and_stale_worker_references(maintenance: Any, reference: str) -> None:
- """
- 验证发布、回滚和过期但未停止的进程引用均阻止清理。
-
- :param maintenance: 维护服务与制品
- :param reference: 受保护引用类型
- :return: None
- """
+ """验证发布、回滚和过期但未停止的进程引用均阻止清理。"""
service, stored = maintenance
async with service.session_factory() as db:
if reference == 'worker':
@@ -116,13 +105,7 @@ async def test_prune_protects_release_and_stale_worker_references(maintenance: A
@pytest.mark.asyncio
@pytest.mark.parametrize('orphan', [False, True])
async def test_prune_removes_only_reviewed_objects_and_audits(maintenance: Any, orphan: bool) -> None:
- """
- 验证已登记和孤儿对象均须按计划清理,并写入审计。
-
- :param maintenance: 维护服务与制品
- :param orphan: 是否模拟索引未提交的孤儿对象
- :return: None
- """
+ """验证已登记和孤儿对象均须按计划清理,并写入审计。"""
service, stored = maintenance
if orphan:
async with service.session_factory() as db:
@@ -143,13 +126,7 @@ async def test_prune_removes_only_reviewed_objects_and_audits(maintenance: Any,
@pytest.mark.asyncio
@pytest.mark.parametrize('failure', ['changed-plan', 'missing-maintenance', 'live-worker'])
async def test_prune_guards_before_mutating(maintenance: Any, failure: str) -> None:
- """
- 验证计划、维护确认和存活进程检查均早于文件变更。
-
- :param maintenance: 维护服务与制品
- :param failure: 待验证的拒绝原因
- :return: None
- """
+ """验证计划、维护确认和存活进程检查均早于文件变更。"""
service, stored = maintenance
plan = await service.prune(keep_last=0, min_age_days=0)
if failure == 'live-worker':
@@ -173,12 +150,7 @@ async def test_prune_guards_before_mutating(maintenance: Any, failure: str) -> N
@pytest.mark.asyncio
async def test_tampered_objects_are_reported_and_never_pruned(maintenance: Any) -> None:
- """
- 验证损坏内容不会自动获得删除资格。
-
- :param maintenance: 维护服务与制品
- :return: None
- """
+ """验证损坏内容不会自动获得删除资格。"""
service, stored = maintenance
(stored.plugin_path / '__init__.py').write_text('tampered')
plan = await service.prune(keep_last=0, min_age_days=0)
@@ -191,13 +163,7 @@ async def test_interrupted_prune_restores_before_commit_and_finishes_after_commi
maintenance: Any,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """
- 验证事务失败后恢复原目录,提交成功后恢复继续清理。
-
- :param maintenance: 维护服务与制品
- :param monkeypatch: 故障注入工具
- :return: None
- """
+ """验证事务失败后恢复原目录,提交成功后恢复继续清理。"""
service, stored = maintenance
plan = await service.prune(keep_last=0, min_age_days=0)
with monkeypatch.context() as patcher:
@@ -230,14 +196,7 @@ async def test_rotation_preserves_content_digest_and_accepts_revoked_old_key(
rotated_archive: Path,
revoke_old: bool,
) -> None:
- """
- 验证新签名可独立证明现有内容,旧密钥撤销不阻止恢复可信签名。
-
- :param maintenance: 维护服务与制品
- :param rotated_archive: 新密钥签名制品
- :param revoke_old: 是否撤销旧密钥
- :return: None
- """
+ """验证新签名可独立证明现有内容,旧密钥撤销不阻止恢复可信签名。"""
service, stored = maintenance
original = (stored.plugin_path / '__init__.py').read_bytes()
if revoke_old:
@@ -256,14 +215,7 @@ async def test_rotation_preserves_content_digest_and_accepts_revoked_old_key(
async def test_rotation_refuses_invalid_content_or_identity(
maintenance: Any, rotated_archive: Path, failure: str
) -> None:
- """
- 验证内容、索引 CAS 和发布者授权均在签名替换前检查。
-
- :param maintenance: 维护服务与制品
- :param rotated_archive: 新签名制品
- :param failure: 故障类型
- :return: None
- """
+ """验证内容、索引 CAS 和发布者授权均在签名替换前检查。"""
service, stored = maintenance
signature = (stored.root_path / 'signature.json').read_bytes()
if failure == 'tampered':
@@ -286,14 +238,7 @@ async def test_failed_rotation_reconciles_to_committed_key(
rotated_archive: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """
- 验证签名替换后事务失败可恢复旧签名并再次成功轮换。
-
- :param maintenance: 维护服务与制品
- :param rotated_archive: 新签名制品
- :param monkeypatch: 故障注入工具
- :return: None
- """
+ """验证签名替换后事务失败可恢复旧签名并再次成功轮换。"""
service, stored = maintenance
with monkeypatch.context() as patcher:
patcher.setattr(service, '_audit', AsyncMock(side_effect=RuntimeError('audit failed')))
@@ -308,12 +253,7 @@ async def test_failed_rotation_reconciles_to_committed_key(
@pytest.mark.asyncio
async def test_reconcile_rejects_path_escape(maintenance: Any) -> None:
- """
- 验证篡改维护日志不能指向存储外路径。
-
- :param maintenance: 维护服务与制品
- :return: None
- """
+ """验证篡改维护日志不能指向存储外路径。"""
service, stored = maintenance
service._write_journal({'digest': stored.digest, 'relativePath': '../outside', 'action': 'prune'})
with pytest.raises(ValueError, match='路径'):
@@ -323,20 +263,12 @@ async def test_reconcile_rejects_path_escape(maintenance: Any) -> None:
@pytest.mark.asyncio
async def test_import_holds_lifecycle_lock_until_index_commit(maintenance: Any, deployment_archive: Path) -> None:
- """
- 验证导入在写索引和提交完成前不会释放与清理共用的生命周期锁。
-
- :param maintenance: 维护服务与制品
- :param deployment_archive: 已验证测试制品
- :return: None
- """
+ """验证导入在写索引和提交完成前不会释放与清理共用的生命周期锁。"""
service, stored = maintenance
events = []
class TrackingLock:
- """
- 记录文件发布和索引写入是否在同一锁范围内。
- """
+ """记录文件发布和索引写入是否在同一锁范围内。"""
@asynccontextmanager
async def lock(self, plugin_id: str, operation: str) -> AsyncIterator[PluginLifecycleLockResult]:
@@ -345,7 +277,7 @@ async def lock(self, plugin_id: str, operation: str) -> AsyncIterator[PluginLife
:param plugin_id: 生命周期操作命名空间
:param operation: 操作类型
- :return: 已获取锁的上下文
+ :yield: 已获取锁的上下文
"""
assert (plugin_id, operation) == ('__artifacts__', 'artifact_import')
events.append('locked')
@@ -355,9 +287,7 @@ async def lock(self, plugin_id: str, operation: str) -> AsyncIterator[PluginLife
events.append('released')
class TrackingDao(PluginReleaseDao):
- """
- 记录索引登记时锁仍有效。
- """
+ """记录索引登记时锁仍有效。"""
@classmethod
async def register_artifact(cls, db: Any, **values: Any) -> SysPluginArtifact:
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_release_state.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_release_state.py
index bdefbdf08..3e56a1d4e 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_release_state.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_release_state.py
@@ -11,7 +11,13 @@
def release(expected_workers: int = 1, **overrides: object) -> SimpleNamespace:
- """构造发布目标及预期进程数量的测试记录。"""
+ """
+ 构造发布目标及预期进程数量的测试记录。
+
+ :param expected_workers: 预期参与部署的工作进程
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 发布目标及预期进程数量的测试记录
+ """
return SimpleNamespace(
**{
'plugin_id': 'demo',
@@ -25,14 +31,26 @@ def release(expected_workers: int = 1, **overrides: object) -> SimpleNamespace:
def host(worker_id: str, **overrides: object) -> SimpleNamespace:
- """构造宿主进程存活报告。"""
+ """
+ 构造宿主进程存活报告。
+
+ :param worker_id: 工作进程的标识
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 宿主进程存活报告
+ """
return SimpleNamespace(
**{'worker_id': worker_id, 'plugin_id': '__runtime__', 'state': 'ready', 'heartbeat_time': NOW, **overrides}
)
def plugin(worker_id: str, **overrides: object) -> SimpleNamespace:
- """构造插件实际加载状态报告。"""
+ """
+ 构造插件实际加载状态报告。
+
+ :param worker_id: 工作进程的标识
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 插件实际加载状态报告
+ """
return SimpleNamespace(
**{
'worker_id': worker_id,
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_service.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_service.py
index 06655fa75..17995139b 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_service.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_service.py
@@ -26,30 +26,66 @@
class MaintenanceRuntime:
- """模拟安装、升级及预检结果的维护运行时。"""
+ """
+ 模拟安装、升级及预检结果的维护运行时。
+
+ :ivar owner: 负责当前操作的对象
+ :ivar plugins: 参与当前操作的插件集合
+ """
def __init__(self, owner: 'MaintenanceFactory', plugins: list[DiscoveredPlugin]) -> None:
- """保存测试制品快照、数据库工厂及故障配置。"""
+ """
+ 保存测试制品快照、数据库工厂及故障配置。
+
+ :param owner: 负责当前操作的对象
+ :param plugins: 参与当前操作的插件集合
+ """
self.owner = owner
self.plugins = {plugin.manifest.id: plugin for plugin in plugins}
async def install_plugin(self, plugin_id: str, **kwargs: Any) -> dict[str, Any]:
- """按测试配置模拟插件安装。"""
+ """
+ 按测试配置模拟插件安装。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 模拟插件安装的执行结果
+ """
return await self.execute('install', plugin_id, **kwargs)
async def upgrade_plugin(self, plugin_id: str, **kwargs: Any) -> dict[str, Any]:
- """按测试配置模拟插件升级。"""
+ """
+ 按测试配置模拟插件升级。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 模拟插件升级的执行结果
+ """
return await self.execute('upgrade', plugin_id, **kwargs)
async def check_plugin_async(self, plugin_id: str) -> dict[str, Any]:
- """返回当前测试指定的静态预检结果。"""
+ """
+ 返回当前测试指定的静态预检结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 当前测试指定的静态预检结果
+ """
self.owner.calls.append(('check', True, self.plugins[plugin_id].manifest.version))
return {'ok': self.owner.failure != 'check', 'message': 'static dependency check'}
async def execute(
self, operation: str, plugin_id: str, *, dry_run: bool = False, operated_by: str | None = None
) -> dict[str, Any]:
- """模拟维护写入及失败场景,更新临时安装状态。"""
+ """
+ 模拟维护写入及失败场景,更新临时安装状态。
+
+ :param operation: 当前处理的操作
+ :param plugin_id: 插件清单中的唯一标识
+ :param dry_run: 是否只预览操作结果
+ :param operated_by: 操作者用户名,非预演时写入审计日志
+ :return: 包含维护操作状态及提示的响应
+ :raises RuntimeError: 模拟执行迁移时注入的数据库故障
+ """
plugin = self.plugins[plugin_id]
self.owner.calls.append((operation, dry_run, plugin.manifest.version))
if dry_run:
@@ -75,22 +111,43 @@ async def execute(
class MaintenanceFactory:
- """记录维护运行时创建情况并提供可控故障的测试工厂。"""
+ """
+ 记录维护运行时创建情况并提供可控故障的测试工厂。
+
+ :ivar sessions: 测试创建的数据库会话或会话工厂
+ :ivar calls: 测试替身记录的调用信息
+ :ivar failure: 用于模拟失败的异常或状态
+ """
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
- """初始化测试数据库和维护故障配置。"""
+ """
+ 初始化测试数据库和维护故障配置。
+
+ :param sessions: 创建当前测试的数据库会话的工厂
+ """
self.sessions = sessions
self.calls: list[tuple[str, bool, str]] = []
self.failure: str | None = None
def __call__(self, config: PluginDeploymentConfig, plugins: list[DiscoveredPlugin]) -> MaintenanceRuntime:
- """为当前候选制品创建测试维护运行时。"""
+ """
+ 为当前候选制品创建测试维护运行时。
+
+ :param config: 制品发布配置快照,支持为测试和维护实例注入独立目录
+ :param plugins: 参与当前操作的插件集合
+ :return: ``MaintenanceRuntime`` 实例
+ """
return MaintenanceRuntime(self, plugins)
@pytest.fixture
def maintenance_factory(deployment_sessions: async_sessionmaker[AsyncSession]) -> MaintenanceFactory:
- """提供可记录维护操作的运行时工厂。"""
+ """
+ 提供可记录维护操作的运行时工厂。
+
+ :param deployment_sessions: 部署流程使用的会话工厂
+ :return: 可记录维护操作的运行时工厂
+ """
return MaintenanceFactory(deployment_sessions)
@@ -101,7 +158,15 @@ def service(
maintenance_factory: MaintenanceFactory,
monkeypatch: pytest.MonkeyPatch,
) -> PluginDeploymentService:
- """创建使用临时数据库与测试生命周期锁的发布服务。"""
+ """
+ 创建使用临时数据库与测试生命周期锁的发布服务。
+
+ :param deployment_sessions: 部署流程使用的会话工厂
+ :param deployment_config: 构造独立存储目录与受限发布者公钥配置
+ :param maintenance_factory: 提供可记录维护操作的运行时工厂
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: 使用临时数据库与测试生命周期锁的发布服务
+ """
monkeypatch.setattr(sys, 'dont_write_bytecode', sys.dont_write_bytecode)
return PluginDeploymentService(
deployment_config,
@@ -112,7 +177,13 @@ def service(
async def import_prepare_select(service: PluginDeploymentService, archive: Path) -> dict[str, Any]:
- """依次导入、维护准备并选择测试制品。"""
+ """
+ 依次导入、维护准备并选择测试制品。
+
+ :param service: 创建使用临时数据库与测试生命周期锁的发布服务
+ :param archive: 包含待安装资源的归档
+ :return: 维护模式下选定制品后的发布信息
+ """
imported = await service.catalog.import_artifact(archive)
prepared = await service.prepare(PLUGIN_ID, imported['digest'], maintenance=True, actor='operator')
return await service.select(
@@ -125,7 +196,15 @@ async def import_prepare_select(service: PluginDeploymentService, archive: Path)
def new_archive(source: Path, destination: Path, key: Ed25519PrivateKey, version: str) -> Path:
- """为指定版本创建新的签名测试制品。"""
+ """
+ 为指定版本创建新的签名测试制品。
+
+ :param source: 包含插件清单和待打包资源的目录
+ :param destination: 复制或移动操作的目标位置
+ :param key: 为新制品签名的 Ed25519 私钥
+ :param version: 当前记录的版本
+ :return: 复制或移动操作的目标位置
+ """
manifest = yaml.safe_load((source / 'plugin.yaml').read_text())
manifest['version'] = version
(source / 'plugin.yaml').write_text(yaml.safe_dump(manifest), encoding='utf-8')
@@ -366,6 +445,13 @@ async def test_generation_conflict_and_audit_failure_cannot_commit_target_change
await service.select(PLUGIN_ID, imported['digest'], maintenance=True, expected_generation='f' * 32)
async def failed_audit(*args: Any, **kwargs: Any) -> None:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RuntimeError: 模拟审计事务失败
+ """
raise RuntimeError('audit transaction failed')
monkeypatch.setattr(service, '_audit', failed_audit)
@@ -395,6 +481,13 @@ async def test_rollback_resource_and_target_changes_share_a_transaction(
second = await import_prepare_select(service, upgrade)
async def failed_audit(*args: Any, **kwargs: Any) -> None:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RuntimeError: 模拟审计事务失败
+ """
raise RuntimeError('rollback audit failed')
monkeypatch.setattr(service, '_audit', failed_audit)
@@ -431,8 +524,17 @@ async def test_lifecycle_lock_denial_is_not_bypassed(
"""验证无法取得生命周期锁时不执行维护操作。"""
class DeniedLock:
+ """模拟未能获取插件操作锁。"""
+
@asynccontextmanager
async def lock(self, plugin_id: str, operation: str) -> AsyncGenerator[PluginLifecycleLockResult, None]:
+ """
+ 模拟获取插件维护锁的结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param operation: 当前处理的操作
+ :yield: ``PluginLifecycleLockResult`` 实例
+ """
yield PluginLifecycleLockResult(False, 'maintenance already running')
imported = await service.catalog.import_artifact(deployment_archive)
@@ -547,7 +649,16 @@ async def test_wait_assertion_uses_existing_release_reports_without_database_wri
def record_statement(
connection: object, cursor: object, statement: str, parameters: object, context: object, executemany: bool
) -> None:
- """记录验收阶段 SQL,不修改当前数据库连接。"""
+ """
+ 记录验收阶段 SQL,不修改当前数据库连接。
+
+ :param connection: 当前操作使用的连接
+ :param cursor: 执行当前 SQL 的数据库游标
+ :param statement: 即将执行的数据库语句
+ :param parameters: 分派给目标命令的参数
+ :param context: 当前操作所需的上下文
+ :param executemany: 是否批量执行同一条语句
+ """
statements.append(statement)
event.listen(engine, 'before_cursor_execute', record_statement)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_task_delivery.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_task_delivery.py
index 1b5ac377c..1b49d379c 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_task_delivery.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_task_delivery.py
@@ -24,15 +24,7 @@ async def test_task_signed_delivery_preserves_data_and_exercises_crud(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """
- 在 SQLite 中适配时间类型后执行 DDL,验证真实维护流程及交付包业务接口。
-
- :param deployment_sessions: 临时宿主表的数据库会话工厂
- :param deployment_config: 临时制品存储和信任配置
- :param tmp_path: 本次测试的独立目录
- :param monkeypatch: pytest 环境隔离工具
- :return: None
- """
+ """在 SQLite 中适配时间类型后执行 DDL,验证真实维护流程及交付包业务接口。"""
import shutil # noqa: PLC0415
# SQLite 只有 INTEGER PRIMARY KEY 才会生成自增值,宿主生产表使用 BIGINT。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_worker.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_worker.py
index 05a800b8b..d4535e5cb 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_worker.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_worker.py
@@ -41,7 +41,13 @@
@pytest_asyncio.fixture
async def deployment(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[SimpleNamespace]:
- """构造真实签名目录与临时 SQLite 发布数据库。"""
+ """
+ 构造真实签名目录与临时 SQLite 发布数据库。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :yield: 真实签名目录与临时 SQLite 发布数据库
+ """
backend = tmp_path / 'backend'
(backend / 'plugins').mkdir(parents=True)
key = Ed25519PrivateKey.generate()
@@ -80,7 +86,14 @@ async def deployment(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncIt
async def publish(deployment: SimpleNamespace, version: str = '1.0.0', *, fail: bool = False) -> str:
- """登记指定版本制品并建立测试需要的目标发布记录。"""
+ """
+ 登记指定版本制品并建立测试需要的目标发布记录。
+
+ :param deployment: 构造真实签名目录与临时 SQLite 发布数据库
+ :param version: 当前记录的版本
+ :param fail: 是否模拟操作失败
+ :return: 已发布制品的摘要
+ """
source = deployment.root / f'source-{version}' / 'release_demo'
source.mkdir(parents=True)
(source / 'plugin.yaml').write_text(
@@ -142,7 +155,13 @@ async def publish(deployment: SimpleNamespace, version: str = '1.0.0', *, fail:
async def activate_worker(config: PluginDeploymentConfig, sessions: Any) -> tuple[Any, Any]:
- """创建进程发布快照并实际准备和激活插件入口。"""
+ """
+ 创建进程发布快照并实际准备和激活插件入口。
+
+ :param config: 制品发布配置快照,支持为测试和维护实例注入独立目录
+ :param sessions: 创建当前测试的数据库会话的工厂
+ :return: 依次为 ``worker``、``runtime`` 的元组
+ """
app = FastAPI()
builder = PluginRuntimeBuilder(config.backend_root)
app.state.plugin_runtime_builder = builder
@@ -164,7 +183,13 @@ async def activate_worker(config: PluginDeploymentConfig, sessions: Any) -> tupl
async def summary(deployment: SimpleNamespace, plugin_id: str = 'release_demo') -> dict[str, Any]:
- """读取发布记录和宿主报告并汇总当前集群状态。"""
+ """
+ 读取发布记录和宿主报告并汇总当前集群状态。
+
+ :param deployment: 构造真实签名目录与临时 SQLite 发布数据库
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 发布记录和宿主报告并汇总当前集群状态
+ """
async with deployment.sessions() as db:
release = await PluginReleaseDao.get_release(db, plugin_id)
reports = await PluginReleaseDao.list_worker_reports(db)
@@ -173,8 +198,17 @@ async def summary(deployment: SimpleNamespace, plugin_id: str = 'release_demo')
@pytest.mark.asyncio
async def test_lock_deadline_only_limits_acquisition(deployment: SimpleNamespace) -> None:
+ """锁截止时间仅限制获取锁。"""
+
@asynccontextmanager
async def busy_lock(_plugin_id: str, _operation: str) -> AsyncIterator[SimpleNamespace]:
+ """
+ 提供未能取得的插件生命周期锁。
+
+ :param _plugin_id: 回调接收的插件标识
+ :param _operation: 回调接收的操作名称
+ :yield: 未能取得的插件生命周期锁
+ """
yield SimpleNamespace(acquired=False)
worker = PluginReleaseWorker(deployment.config, session_factory=deployment.sessions)
@@ -372,6 +406,14 @@ async def test_real_application_startup_does_not_run_artifact_install_or_resourc
monkeypatch.setattr('config.database.DataSourceRegistry.session', deployment.sessions)
class ReadOnlyGateway:
+ """
+ 提供只读工作进程使用的插件查询接口。
+
+ :cvar list_plugins: 模拟查询插件列表的操作
+ :cvar install_plugin_resources: 模拟安装插件资源的操作
+ :cvar upsert_discovered_plugin: 模拟写入已发现插件记录的操作
+ """
+
list_plugins = staticmethod(PluginDao.get_plugin_list)
install_plugin_resources = AsyncMock(
side_effect=AssertionError('startup must not reinstall artifact resources')
@@ -473,9 +515,21 @@ async def test_failed_artifact_stays_disabled_after_source_failure_reloads_regis
def _run_process(config: PluginDeploymentConfig, database: str, ready: Any, stop: Any) -> None:
- """在独立进程中实际激活制品并报告加载路径和版本。"""
+ """
+ 在独立进程中实际激活制品并报告加载路径和版本。
+
+ :param config: 制品发布配置快照,支持为测试和维护实例注入独立目录
+ :param database: 测试所使用的数据库
+ :param ready: 依赖检查是否已就绪
+ :param stop: 通知正在运行的任务停止的信号
+ """
async def run() -> None:
+ """
+ 记录测试命令的运行参数。
+
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
+ """
engine = create_async_engine(f'sqlite+aiosqlite:///{database}')
sessions = async_sessionmaker(engine, expire_on_commit=False)
worker = runtime = None
@@ -509,7 +563,13 @@ async def run() -> None:
@asynccontextmanager
async def running_processes(deployment: SimpleNamespace, count: int = 1) -> AsyncGenerator[list[dict[str, Any]], None]:
- """启动指定数量的独立测试进程并在退出时完整回收。"""
+ """
+ 启动指定数量的独立测试进程并在退出时完整回收。
+
+ :param deployment: 构造真实签名目录与临时 SQLite 发布数据库
+ :param count: 本次处理或预期的数量
+ :yield: 保存各工作进程报告的集合
+ """
context = multiprocessing.get_context('spawn')
ready = context.Queue()
stop = context.Event()
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/discovery/test_registry.py b/ruoyi-fastapi-backend/tests/plugins/core/discovery/test_registry.py
index c7089edf6..ef615e1c2 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/discovery/test_registry.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/discovery/test_registry.py
@@ -12,7 +12,15 @@ def build_discovered_plugin(
auto_scan: bool = True,
version: str = '1.0.0',
) -> DiscoveredPlugin:
- """构造测试用已发现插件。"""
+ """
+ 构造测试用已发现插件。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param plugin_id: 插件清单中的唯一标识
+ :param auto_scan: 是否自动扫描插件控制器
+ :param version: 当前记录的版本
+ :return: 测试用已发现插件
+ """
backend_path = tmp_path / plugin_id
backend_path.mkdir(parents=True)
manifest_path = backend_path / 'plugin.yaml'
@@ -30,7 +38,14 @@ def build_discovered_plugin(
def build_database_plugin(plugin_id: str = 'demo', *, enabled: str = '0', status: str = 'installed') -> PluginModel:
- """构造测试用数据库插件状态。"""
+ """
+ 构造测试用数据库插件状态。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param enabled: 是否启用该项功能
+ :param status: 操作或记录所处的状态
+ :return: 测试用数据库插件状态
+ """
return PluginModel(
pluginId=plugin_id,
pluginName='演示插件',
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/discovery/test_scanner.py b/ruoyi-fastapi-backend/tests/plugins/core/discovery/test_scanner.py
index 55d3118ea..fe8a1d07c 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/discovery/test_scanner.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/discovery/test_scanner.py
@@ -9,7 +9,13 @@
def write_manifest(plugin_dir: Path, content: str) -> Path:
- """写入测试插件清单。"""
+ """
+ 写入测试插件清单。
+
+ :param plugin_dir: 保存插件清单和资源的目录
+ :param content: 需要读取或写入的内容
+ :return: 供调用方使用的 ``manifest_path``
+ """
plugin_dir.mkdir(parents=True)
manifest_path = plugin_dir / 'plugin.yaml'
manifest_path.write_text(content, encoding='utf-8')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/lifecycle/test_migration.py b/ruoyi-fastapi-backend/tests/plugins/core/lifecycle/test_migration.py
index 12c241918..197a24197 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/lifecycle/test_migration.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/lifecycle/test_migration.py
@@ -16,6 +16,9 @@
class FakeManagedMigrationSession(list):
"""
测试用托管 migration 执行 session。
+
+ :ivar committed: 是否已经提交事务
+ :ivar rolled_back: 是否已经回滚事务
"""
def __init__(self) -> None:
@@ -36,6 +39,11 @@ async def rollback(self) -> None:
class FakeMigrationHistoryStore(PluginMigrationHistoryStore):
"""
测试用 migration 历史存储。
+
+ :ivar history_records: 已保存的历史执行记录
+ :ivar records: 当前测试保存的记录
+ :ivar running_records: 当前处于运行状态的记录
+ :ivar failure_records: 记录执行失败的条目
"""
def __init__(
@@ -43,7 +51,12 @@ def __init__(
checksums: dict[tuple[str, str], str] | None = None,
records: dict[tuple[str, str], PluginMigrationHistoryRecord] | None = None,
) -> None:
- """初始化测试用 migration 历史存储。"""
+ """
+ 初始化测试用 migration 历史存储。
+
+ :param checksums: 按资源名索引的校验和
+ :param records: 当前测试保存的记录
+ """
self.history_records = records or {
key: PluginMigrationHistoryRecord(checksum=value) for key, value in (checksums or {}).items()
}
@@ -57,7 +70,14 @@ async def get_record(
plugin_id: str,
migration_path: str,
) -> PluginMigrationHistoryRecord | None:
- """获取已执行 migration 记录。"""
+ """
+ 获取已执行 migration 记录。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :return: 已执行 migration 记录
+ """
return self.history_records.get((plugin_id, migration_path))
async def record_running(
@@ -69,7 +89,16 @@ async def record_running(
version: str,
statement_count: int,
) -> None:
- """记录 migration 开始执行。"""
+ """
+ 记录 migration 开始执行。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :param checksum: 校验内容完整性使用的校验和
+ :param version: 当前记录的版本
+ :param statement_count: SQL 语句数量
+ """
self.running_records.append((plugin_id, migration_path, checksum, version, statement_count))
async def record_success(
@@ -81,7 +110,16 @@ async def record_success(
version: str,
statement_count: int,
) -> None:
- """记录 migration 成功执行历史。"""
+ """
+ 记录 migration 成功执行历史。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :param checksum: 校验内容完整性使用的校验和
+ :param version: 当前记录的版本
+ :param statement_count: SQL 语句数量
+ """
self.records.append((plugin_id, migration_path, checksum, version, statement_count))
async def record_failure(
@@ -94,7 +132,17 @@ async def record_failure(
statement_count: int,
error_message: str,
) -> None:
- """记录 migration 失败历史。"""
+ """
+ 记录 migration 失败历史。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :param checksum: 校验内容完整性使用的校验和
+ :param version: 当前记录的版本
+ :param statement_count: SQL 语句数量
+ :param error_message: 记录到结果或审计日志中的错误详情
+ """
self.failure_records.append((plugin_id, migration_path, checksum, version, statement_count, error_message))
@@ -103,7 +151,13 @@ def write_plugin_with_migration(
migration_content: str,
migration_name: str = '001_demo.py',
) -> None:
- """写入带 migration 的测试插件。"""
+ """
+ 写入带 migration 的测试插件。
+
+ :param plugin_root: 插件的根目录
+ :param migration_content: 测试迁移脚本的内容
+ :param migration_name: 迁移脚本的文件名
+ """
(plugin_root / 'migrations').mkdir(parents=True)
(plugin_root / 'migrations' / migration_name).write_text(migration_content, encoding='utf-8')
(plugin_root / 'plugin.yaml').write_text(
@@ -121,7 +175,11 @@ def write_plugin_with_migration(
def write_plugin_with_database_migrations(plugin_root: Path) -> None:
- """写入带数据库方言 migration 的测试插件。"""
+ """
+ 写入带数据库方言 migration 的测试插件。
+
+ :param plugin_root: 插件的根目录
+ """
(plugin_root / 'migrations' / 'mysql').mkdir(parents=True)
(plugin_root / 'migrations' / 'postgresql').mkdir(parents=True)
(plugin_root / 'migrations' / 'mysql' / '001_demo.sql').write_text(
@@ -292,7 +350,13 @@ async def test_plugin_migration_runner_reports_recovery_when_success_history_wri
query_db = FakeManagedMigrationSession()
async def fail_record_success(*_args: object, **_kwargs: object) -> None:
- """模拟 success 历史写入失败。"""
+ """
+ 模拟 success 历史写入失败。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :raises RuntimeError: 模拟记录迁移历史时服务不可用
+ """
raise RuntimeError('history down')
history_store.record_success = fail_record_success # type: ignore[method-assign]
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/lifecycle/test_seed.py b/ruoyi-fastapi-backend/tests/plugins/core/lifecycle/test_seed.py
index 961c088ac..383a430a5 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/lifecycle/test_seed.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/lifecycle/test_seed.py
@@ -9,7 +9,13 @@
def write_plugin_with_seed(plugin_root: Path, seed_content: str, seed_name: str = 'demo_seed.py') -> None:
- """写入带 seed 的测试插件。"""
+ """
+ 写入带 seed 的测试插件。
+
+ :param plugin_root: 插件的根目录
+ :param seed_content: 测试种子脚本的内容
+ :param seed_name: 种子脚本的文件名
+ """
(plugin_root / 'seeds').mkdir(parents=True)
(plugin_root / 'seeds' / seed_name).write_text(seed_content, encoding='utf-8')
(plugin_root / 'plugin.yaml').write_text(
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/management/test_artifact_views.py b/ruoyi-fastapi-backend/tests/plugins/core/management/test_artifact_views.py
index ef4a4591c..a544fdfc2 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/management/test_artifact_views.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/management/test_artifact_views.py
@@ -18,7 +18,11 @@
def artifact_record() -> SysPlugin:
- """构造管理视图使用的制品来源插件记录。"""
+ """
+ 构造管理视图使用的制品来源插件记录。
+
+ :return: 管理视图使用的制品来源插件记录
+ """
return SysPlugin(
plugin_id='demo',
plugin_name='Demo',
@@ -99,15 +103,33 @@ async def test_release_view_separates_selected_code_schema_and_worker_activation
)
class Catalog:
+ """提供插件制品目录的测试替身。"""
+
def __init__(self, config: object) -> None:
- pass
+ """
+ 无需外部依赖即可创建该测试替身。
+
+ :param config: 当前对象使用的配置
+ """
@staticmethod
def reject_source_conflict(plugin_id: str) -> None:
+ """
+ 校验测试传入的插件来源。
+
+ :param plugin_id: 插件清单中的唯一标识
+ """
assert plugin_id == 'demo'
@staticmethod
async def get(digest: str) -> object:
+ """
+ 读取测试存储中的指定键。
+
+ :param digest: 用于验证内容完整性的摘要
+ :raises ValueError: 制品摘要校验失败
+ :return: 测试存储中的指定键
+ """
assert digest == DIGEST
if not verified:
raise ValueError('制品摘要校验失败')
@@ -115,6 +137,13 @@ async def get(digest: str) -> object:
@staticmethod
def discovered(artifact: object, generation: str) -> DiscoveredPlugin:
+ """
+ 校验部署代次并返回发现的插件。
+
+ :param artifact: 当前验证或交付的插件制品
+ :param generation: 当前发布或部署的代次
+ :return: 发现的插件
+ """
assert generation == GENERATION
return discovered
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/management/test_config_manager.py b/ruoyi-fastapi-backend/tests/plugins/core/management/test_config_manager.py
index 571a0e2f1..d3b8ba0f8 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/management/test_config_manager.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/management/test_config_manager.py
@@ -5,7 +5,12 @@
def _build_item(**overrides: object) -> PluginConfigItemManifest:
- """构造指定类型和值的测试配置项。"""
+ """
+ 构造指定类型和值的测试配置项。
+
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 指定类型和值的测试配置项
+ """
data: dict[str, object] = {'key': 'limit', 'type': 'number', 'default': 5}
data.update(overrides)
return PluginConfigItemManifest.model_validate(data)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/management/test_menu_installer.py b/ruoyi-fastapi-backend/tests/plugins/core/management/test_menu_installer.py
index 36875ae09..4f6507316 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/management/test_menu_installer.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/management/test_menu_installer.py
@@ -16,6 +16,10 @@
class FakePluginDao:
"""
测试用插件 DAO。
+
+ :cvar plugin_menus: 测试中由插件注册的菜单
+ :cvar menus: 测试仓储中保存的菜单
+ :cvar next_menu_id: 分配给下一条测试菜单的标识
"""
plugin_menus: dict[tuple[str, str], SimpleNamespace] = {}
@@ -36,17 +40,36 @@ async def get_plugin_menu_by_key(
plugin_id: str,
menu_key: str,
) -> SimpleNamespace | None:
- """根据插件菜单自然键查询关联。"""
+ """
+ 根据插件菜单自然键查询关联。
+
+ :param db: 当前操作使用的数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param menu_key: 插件内菜单自然键
+ :return: 与插件和菜单键匹配的归属记录
+ """
return cls.plugin_menus.get((plugin_id, menu_key))
@classmethod
async def get_plugin_menu_list(cls, db: object, plugin_id: str) -> list[SimpleNamespace]:
- """查询插件菜单关联列表。"""
+ """
+ 查询插件菜单关联列表。
+
+ :param db: 当前操作使用的数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 插件菜单关联列表
+ """
return [plugin_menu for key, plugin_menu in cls.plugin_menus.items() if key[0] == plugin_id]
@classmethod
async def get_plugin_menu_by_menu_id(cls, db: object, menu_id: int) -> SimpleNamespace | None:
- """根据菜单 ID 查询插件 ownership。"""
+ """
+ 根据菜单 ID 查询插件 ownership。
+
+ :param db: 当前操作使用的数据库会话
+ :param menu_id: 菜单ID
+ :return: 给定菜单标识对应的插件归属记录
+ """
return next(
(plugin_menu for plugin_menu in cls.plugin_menus.values() if plugin_menu.menu_id == menu_id),
None,
@@ -54,12 +77,24 @@ async def get_plugin_menu_by_menu_id(cls, db: object, menu_id: int) -> SimpleNam
@classmethod
async def get_sys_menu_by_id(cls, db: object, menu_id: int) -> SimpleNamespace | None:
- """根据菜单 ID 查询系统菜单。"""
+ """
+ 根据菜单 ID 查询系统菜单。
+
+ :param db: 当前操作使用的数据库会话
+ :param menu_id: 菜单ID
+ :return: 对应的系统菜单,未命中时为空值
+ """
return cls.menus.get(menu_id)
@classmethod
async def get_sys_menu_by_perms(cls, db: object, perms: str) -> SimpleNamespace | None:
- """根据权限标识查询系统菜单。"""
+ """
+ 根据权限标识查询系统菜单。
+
+ :param db: 当前操作使用的数据库会话
+ :param perms: 调用主体所拥有的权限集合
+ :return: 当前要安装或操作的菜单项
+ """
for menu in cls.menus.values():
if menu.perms == perms:
return menu
@@ -73,7 +108,15 @@ async def get_sys_menu_by_route(
path: str,
component: str,
) -> SimpleNamespace | None:
- """根据路由自然键查询系统菜单。"""
+ """
+ 根据路由自然键查询系统菜单。
+
+ :param db: 当前操作使用的数据库会话
+ :param parent_id: 父菜单ID
+ :param path: 要读取或处理的路径
+ :param component: 当前检查或渲染的组件
+ :return: 当前要安装或操作的菜单项
+ """
for menu in cls.menus.values():
if menu.parent_id == parent_id and menu.path == path and menu.component == component:
return menu
@@ -87,7 +130,15 @@ async def get_sys_menu_by_name_path(
menu_name: str,
path: str,
) -> SimpleNamespace | None:
- """根据菜单名称和路径查询系统菜单。"""
+ """
+ 根据菜单名称和路径查询系统菜单。
+
+ :param db: 当前操作使用的数据库会话
+ :param parent_id: 父菜单ID
+ :param menu_name: 菜单名称
+ :param path: 要读取或处理的路径
+ :return: 当前要安装或操作的菜单项
+ """
for menu in cls.menus.values():
if menu.parent_id == parent_id and menu.menu_name == menu_name and menu.path == path:
return menu
@@ -95,7 +146,13 @@ async def get_sys_menu_by_name_path(
@classmethod
async def add_sys_menu(cls, db: object, menu: object) -> SimpleNamespace:
- """新增系统菜单。"""
+ """
+ 新增系统菜单。
+
+ :param db: 当前操作使用的数据库会话
+ :param menu: 当前要安装或操作的菜单项
+ :return: 供调用方使用的 ``sys_menu``
+ """
menu_data = menu.model_dump(exclude_unset=True)
menu_id = cls.next_menu_id
cls.next_menu_id += 1
@@ -107,20 +164,37 @@ async def add_sys_menu(cls, db: object, menu: object) -> SimpleNamespace:
@classmethod
async def update_sys_menu(cls, db: object, menu: dict) -> None:
- """更新系统菜单。"""
+ """
+ 更新系统菜单。
+
+ :param db: 当前操作使用的数据库会话
+ :param menu: 当前要安装或操作的菜单项
+ """
sys_menu = cls.menus[menu['menu_id']]
for key, value in menu.items():
setattr(sys_menu, key, value)
@classmethod
async def update_sys_menu_status_by_ids(cls, db: object, menu_ids: list[int], status: str) -> None:
- """批量更新系统菜单状态。"""
+ """
+ 批量更新系统菜单状态。
+
+ :param db: 当前操作使用的数据库会话
+ :param menu_ids: 菜单ID列表
+ :param status: 操作或记录所处的状态
+ """
for menu_id in menu_ids:
cls.menus[menu_id].status = status
@classmethod
async def add_plugin_menu(cls, db: object, plugin_menu: object) -> SimpleNamespace:
- """新增插件菜单关联。"""
+ """
+ 新增插件菜单关联。
+
+ :param db: 当前操作使用的数据库会话
+ :param plugin_menu: 插件菜单关联对象
+ :return: 供调用方使用的 ``plugin_menu_model``
+ """
plugin_menu_data = plugin_menu.model_dump(exclude_unset=True)
plugin_menu_model = SimpleNamespace(**plugin_menu_data)
cls.plugin_menus[(plugin_menu_model.plugin_id, plugin_menu_model.menu_key)] = plugin_menu_model
@@ -129,7 +203,12 @@ async def add_plugin_menu(cls, db: object, plugin_menu: object) -> SimpleNamespa
@classmethod
async def update_plugin_menu_by_key(cls, db: object, plugin_menu: object) -> None:
- """根据插件菜单自然键更新插件菜单关联。"""
+ """
+ 根据插件菜单自然键更新插件菜单关联。
+
+ :param db: 当前操作使用的数据库会话
+ :param plugin_menu: 插件菜单关联对象
+ """
plugin_menu_data = plugin_menu.model_dump(exclude_unset=True)
cls.plugin_menus[(plugin_menu_data['plugin_id'], plugin_menu_data['menu_key'])].menu_id = plugin_menu_data[
'menu_id'
@@ -137,7 +216,12 @@ async def update_plugin_menu_by_key(cls, db: object, plugin_menu: object) -> Non
@classmethod
async def update_plugin_menu_key_by_menu_id(cls, db: object, plugin_menu: object) -> None:
- """根据菜单 ID 更新插件菜单自然键。"""
+ """
+ 根据菜单 ID 更新插件菜单自然键。
+
+ :param db: 当前操作使用的数据库会话
+ :param plugin_menu: 插件菜单关联对象
+ """
plugin_menu_data = plugin_menu.model_dump(exclude_unset=True)
old_key = next(
key
@@ -150,7 +234,13 @@ async def update_plugin_menu_key_by_menu_id(cls, db: object, plugin_menu: object
@classmethod
async def delete_plugin_menus_by_ids(cls, db: object, plugin_id: str, menu_ids: list[int]) -> None:
- """删除指定插件菜单 ownership。"""
+ """
+ 删除指定插件菜单 ownership。
+
+ :param db: 当前操作使用的数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param menu_ids: 菜单ID列表
+ """
cls.plugin_menus = {
key: plugin_menu
for key, plugin_menu in cls.plugin_menus.items()
@@ -159,13 +249,22 @@ async def delete_plugin_menus_by_ids(cls, db: object, plugin_id: str, menu_ids:
@classmethod
async def delete_sys_menus_by_ids(cls, db: object, menu_ids: list[int]) -> None:
- """删除系统菜单。"""
+ """
+ 删除系统菜单。
+
+ :param db: 当前操作使用的数据库会话
+ :param menu_ids: 菜单ID列表
+ """
for menu_id in menu_ids:
cls.menus.pop(menu_id, None)
def build_manifest() -> PluginManifest:
- """构造测试插件清单。"""
+ """
+ 构造测试插件清单。
+
+ :return: 测试插件清单
+ """
return PluginManifest.model_validate(
{
'id': 'demo',
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/management/test_plugin_state.py b/ruoyi-fastapi-backend/tests/plugins/core/management/test_plugin_state.py
index 4f1a60118..6ba551999 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/management/test_plugin_state.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/management/test_plugin_state.py
@@ -89,7 +89,11 @@ async def test_plugin_table_rejects_invalid_state_domains() -> None:
async def create_sqlite_sys_job_table(connection: object) -> None:
- """创建适配 SQLite 的测试用 sys_job 表。"""
+ """
+ 创建适配 SQLite 的测试用 sys_job 表。
+
+ :param connection: 当前操作使用的连接
+ """
await connection.execute(
text(
"""
@@ -120,7 +124,11 @@ async def create_sqlite_sys_job_table(connection: object) -> None:
async def create_sqlite_sys_menu_table(connection: object) -> None:
- """创建适配 SQLite 的测试用 sys_menu 表。"""
+ """
+ 创建适配 SQLite 的测试用 sys_menu 表。
+
+ :param connection: 当前操作使用的连接
+ """
await connection.execute(
text(
"""
@@ -153,7 +161,14 @@ async def create_sqlite_sys_menu_table(connection: object) -> None:
def build_discovered_plugin(tmp_path: Path, enabled: bool = True, version: str = '1.0.0') -> DiscoveredPlugin:
- """构造测试用已发现插件对象。"""
+ """
+ 构造测试用已发现插件对象。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param enabled: 是否启用该项功能
+ :param version: 当前记录的版本
+ :return: 测试用已发现插件对象
+ """
backend_path = tmp_path / 'plugins' / 'demo'
manifest_path = backend_path / 'plugin.yaml'
backend_path.mkdir(parents=True)
@@ -182,7 +197,13 @@ def build_discovered_plugin(tmp_path: Path, enabled: bool = True, version: str =
def build_discovered_plugin_with_menu(tmp_path: Path, perms: str) -> DiscoveredPlugin:
- """构造带菜单权限声明的测试插件。"""
+ """
+ 构造带菜单权限声明的测试插件。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param perms: 调用主体所拥有的权限集合
+ :return: 带菜单权限声明的测试插件
+ """
backend_path = tmp_path / 'plugins' / 'demo'
manifest_path = backend_path / 'plugin.yaml'
backend_path.mkdir(parents=True, exist_ok=True)
@@ -211,7 +232,12 @@ def build_discovered_plugin_with_menu(tmp_path: Path, perms: str) -> DiscoveredP
def build_discovered_plugin_with_permission_buttons(tmp_path: Path) -> DiscoveredPlugin:
- """构造带页面菜单和顶层按钮权限声明的测试插件。"""
+ """
+ 构造带页面菜单和顶层按钮权限声明的测试插件。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :return: 带页面菜单和顶层按钮权限声明的测试插件
+ """
backend_path = tmp_path / 'plugins' / 'demo'
manifest_path = backend_path / 'plugin.yaml'
backend_path.mkdir(parents=True, exist_ok=True)
@@ -248,7 +274,12 @@ def build_discovered_plugin_with_permission_buttons(tmp_path: Path) -> Discovere
def build_discovered_plugin_with_config(tmp_path: Path) -> DiscoveredPlugin:
- """构造带配置声明的测试插件。"""
+ """
+ 构造带配置声明的测试插件。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :return: 带配置声明的测试插件
+ """
backend_path = tmp_path / 'plugins' / 'demo'
manifest_path = backend_path / 'plugin.yaml'
backend_path.mkdir(parents=True, exist_ok=True)
@@ -300,7 +331,12 @@ def build_discovered_plugin_with_config(tmp_path: Path) -> DiscoveredPlugin:
def build_discovered_plugin_with_job(tmp_path: Path) -> DiscoveredPlugin:
- """构造带定时任务声明的测试插件。"""
+ """
+ 构造带定时任务声明的测试插件。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :return: 带定时任务声明的测试插件
+ """
backend_path = tmp_path / 'plugins' / 'demo'
manifest_path = backend_path / 'plugin.yaml'
backend_path.mkdir(parents=True, exist_ok=True)
@@ -1693,7 +1729,13 @@ async def test_get_plugin_config_services_reuses_bulk_config_lookup(
await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.__table__])
async def fail_get_config_by_key(*_args: object, **_kwargs: object) -> None:
- """模拟读取插件配置失败。"""
+ """
+ 模拟读取插件配置失败。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :raises AssertionError: 计算默认配置差异时意外执行了逐键查询
+ """
raise AssertionError('get_plugin_config_by_key should not be used for default config diff')
try:
@@ -1726,7 +1768,11 @@ class TestPluginManagementRuntimeGateway(PluginManagementRuntimeGateway):
@staticmethod
def get_async_session_local() -> object:
- """获取测试数据库会话工厂。"""
+ """
+ 获取测试数据库会话工厂。
+
+ :return: 测试数据库会话工厂
+ """
return session_maker
try:
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/management/test_release_dao.py b/ruoyi-fastapi-backend/tests/plugins/core/management/test_release_dao.py
index 5b05db9df..af595236b 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/management/test_release_dao.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/management/test_release_dao.py
@@ -22,7 +22,12 @@
@pytest_asyncio.fixture
async def sessions(tmp_path: Path) -> AsyncIterator[async_sessionmaker[AsyncSession]]:
- """创建仅含发布相关表的临时数据库会话工厂。"""
+ """
+ 创建仅含发布相关表的临时数据库会话工厂。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :yield: 仅含发布相关表的临时数据库会话工厂
+ """
engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "releases.sqlite"}')
async with engine.begin() as connection:
await connection.run_sync(
@@ -41,7 +46,14 @@ async def sessions(tmp_path: Path) -> AsyncIterator[async_sessionmaker[AsyncSess
async def register(db: AsyncSession, digest: str = DIGEST_A, version: str = '1.0.0') -> SysPluginArtifact:
- """为测试登记指定摘要与版本的制品索引。"""
+ """
+ 为测试登记指定摘要与版本的制品索引。
+
+ :param db: 当前操作使用的数据库会话
+ :param digest: 用于验证内容完整性的摘要
+ :param version: 当前记录的版本
+ :return: 已登记的制品索引记录
+ """
return await PluginReleaseDao.register_artifact(
db,
digest=digest,
@@ -55,7 +67,12 @@ async def register(db: AsyncSession, digest: str = DIGEST_A, version: str = '1.0
async def prepare(db: AsyncSession) -> SysPluginRelease:
- """为测试建立制品与已安装版本匹配的准备证据。"""
+ """
+ 为测试建立制品与已安装版本匹配的准备证据。
+
+ :param db: 当前操作使用的数据库会话
+ :return: 准备状态更新后的记录
+ """
await register(db)
db.add(SysPlugin(plugin_id='demo', plugin_name='Demo', version='1.0.0', installed_version='1.0.0'))
await db.flush()
@@ -190,6 +207,11 @@ async def test_competing_target_selections_only_one_generation_wins(sessions: as
await db.commit()
async def select_once() -> str:
+ """
+ 在独立会话中完成一次制品查询。
+
+ :return: 选中的发布代次或并发冲突标记
+ """
async with sessions() as db:
try:
row = await PluginReleaseDao.select_target(
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/native/test_wheel.py b/ruoyi-fastapi-backend/tests/plugins/core/native/test_wheel.py
index 2b28ecc92..c34805756 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/native/test_wheel.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/native/test_wheel.py
@@ -23,7 +23,11 @@
@pytest.fixture
def manifest() -> PluginManifest:
- """创建原生 wheel 测试使用的插件清单。"""
+ """
+ 创建原生 wheel 测试使用的插件清单。
+
+ :return: 原生 wheel 测试使用的插件清单
+ """
return PluginManifestFactory.create(
{
'manifestVersion': 2,
@@ -41,7 +45,14 @@ def manifest() -> PluginManifest:
def make_wheel(root: Path, *, extra: dict[str, bytes] | None = None, tag: str | None = None) -> Path:
- """构造包含可控元数据、文件内容和 RECORD 的原生测试 wheel。"""
+ """
+ 构造包含可控元数据、文件内容和 RECORD 的原生测试 wheel。
+
+ :param root: 路径解析的基准目录
+ :param extra: 添加到默认数据上的额外字段
+ :param tag: 用于区分测试数据的标签
+ :return: 包含可控元数据、文件内容和 RECORD 的原生测试 wheel
+ """
selected_tag = tag or str(next(sys_tags()))
path = root / f'{MODULE}-1.0.0-{selected_tag}.whl'
files = {
@@ -172,6 +183,13 @@ def test_extract_failure_cleans_only_new_directory(
sentinel.touch()
def fail_copy(*args: object, **kwargs: object) -> None:
+ """
+ 模拟此操作抛出 OSError 的情形。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises OSError: 模拟磁盘已满而无法复制文件
+ """
raise OSError('disk full')
monkeypatch.setattr(wheel_tools.shutil, 'copyfileobj', fail_copy)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/conftest.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/conftest.py
index 9d5da72ed..6166fbb19 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/conftest.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/conftest.py
@@ -7,7 +7,11 @@
@pytest.fixture(autouse=True)
def isolate_fake_plugin_service() -> Generator[None, None, None]:
- """在每个运行时测试前后重置共享 fake 状态。"""
+ """
+ 在每个运行时测试前后重置共享 fake 状态。
+
+ :yield: 上下文就绪后将控制权交给调用方
+ """
FakePluginService.reset()
yield
FakePluginService.reset()
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/environment.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/environment.py
index cef322bbc..dd0fdb8d3 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/environment.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/environment.py
@@ -8,10 +8,20 @@
class FakeRuntimeEnvironment:
"""
测试用运行时环境服务。
+
+ :ivar backend_dir: 后端项目目录
+ :ivar frontend_dir: 前端项目目录
+ :ivar frontend_mode: 当前使用的前端集成模式
+ :ivar backend_runtime_mode: 后端运行模式
"""
def __init__(self, backend_dir: Path, frontend_dir: Path | None = None) -> None:
- """初始化测试用运行时环境服务。"""
+ """
+ 初始化测试用运行时环境服务。
+
+ :param backend_dir: 后端项目目录
+ :param frontend_dir: 前端项目目录
+ """
self.backend_dir = backend_dir
self.frontend_dir = frontend_dir or Path(
PluginRuntimeEnvironmentService(backend_root=backend_dir).get_frontend_dir()
@@ -20,35 +30,68 @@ def __init__(self, backend_dir: Path, frontend_dir: Path | None = None) -> None:
self.backend_runtime_mode = 'dev'
def get_backend_dir(self) -> str:
- """获取后端项目根目录。"""
+ """
+ 获取后端项目根目录。
+
+ :return: 后端项目根目录
+ """
return str(self.backend_dir)
def get_backend_plugins_dir(self) -> str:
- """获取后端插件根目录。"""
+ """
+ 获取后端插件根目录。
+
+ :return: 后端插件根目录
+ """
return str(self.backend_dir / 'plugins')
def get_frontend_dir(self) -> str:
- """获取前端项目根目录。"""
+ """
+ 获取前端项目根目录。
+
+ :return: 前端项目根目录
+ """
return str(self.frontend_dir)
def get_frontend_framework(self, frontend_root: Path | str | None = None) -> str:
- """获取测试用前端工程的框架标识。"""
+ """
+ 获取测试用前端工程的框架标识。
+
+ :param frontend_root: 前端项目的根目录
+ :return: 测试用前端工程的框架标识
+ """
root = Path(frontend_root) if frontend_root is not None else self.frontend_dir
return PluginFrontendFrameworkResolver.resolve(root)
def get_frontend_plugins_dir(self) -> str:
- """获取前端插件根目录。"""
+ """
+ 获取前端插件根目录。
+
+ :return: 前端插件根目录
+ """
return str(self.frontend_dir / 'plugins')
@staticmethod
def get_python_executable() -> str:
- """获取测试用 Python 解释器。"""
+ """
+ 获取测试用 Python 解释器。
+
+ :return: 测试用 Python 解释器
+ """
return sys.executable
def get_frontend_mode(self) -> str:
- """获取测试用前端模式。"""
+ """
+ 获取测试用前端模式。
+
+ :return: 测试用前端模式
+ """
return self.frontend_mode
def get_backend_runtime_mode(self) -> str:
- """获取测试用后端运行模式。"""
+ """
+ 获取测试用后端运行模式。
+
+ :return: 测试用后端运行模式
+ """
return self.backend_runtime_mode
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/factory.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/factory.py
index 80f382a4c..2f6518de7 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/factory.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/factory.py
@@ -15,13 +15,24 @@
def write_manifest(plugin_dir: Path, content: str) -> None:
- """写入测试插件清单。"""
+ """
+ 写入测试插件清单。
+
+ :param plugin_dir: 保存插件清单和资源的目录
+ :param content: 需要读取或写入的内容
+ """
plugin_dir.mkdir(parents=True)
(plugin_dir / 'plugin.yaml').write_text(content, encoding='utf-8')
def build_runtime(backend_root: Path, frontend_root: Path | None = None) -> PluginRuntimeService:
- """构建测试用插件运行时服务。"""
+ """
+ 构建测试用插件运行时服务。
+
+ :param backend_root: 后端项目的根目录
+ :param frontend_root: 前端项目的根目录
+ :return: 测试用插件运行时服务
+ """
return PluginRuntimeService(
runtime_environment=FakeRuntimeEnvironment(backend_root, frontend_root),
dependency_checker=PluginDependencyChecker(
@@ -32,7 +43,12 @@ def build_runtime(backend_root: Path, frontend_root: Path | None = None) -> Plug
def build_gateway_overrides(gateway: object) -> PluginRuntimeGatewayOverrides:
- """构建测试用插件运行时窄端口覆盖项。"""
+ """
+ 构建测试用插件运行时窄端口覆盖项。
+
+ :param gateway: 代理底层操作的网关
+ :return: 测试用插件运行时窄端口覆盖项
+ """
return PluginRuntimeGatewayOverrides(
config_gateway=gateway,
audit_gateway=gateway,
@@ -46,7 +62,12 @@ def build_gateway_overrides(gateway: object) -> PluginRuntimeGatewayOverrides:
def build_fake_lifecycle_precheck(ok: bool = True) -> SimpleNamespace:
- """构建测试用插件生命周期预检上下文。"""
+ """
+ 构建测试用插件生命周期预检上下文。
+
+ :param ok: 操作或检查是否成功
+ :return: 测试用插件生命周期预检上下文
+ """
return SimpleNamespace(
ok=ok,
manifest_result=SimpleNamespace(ok=ok),
@@ -64,7 +85,14 @@ def build_runtime_with_gateway(
gateway: FakePluginRuntimeGateway,
frontend_root: Path | None = None,
) -> PluginRuntimeService:
- """构建带测试运行时适配器的插件运行时服务。"""
+ """
+ 构建带测试运行时适配器的插件运行时服务。
+
+ :param backend_root: 后端项目的根目录
+ :param gateway: 测试用插件运行时适配器
+ :param frontend_root: 前端项目的根目录
+ :return: 带测试运行时适配器的插件运行时服务
+ """
return PluginRuntimeService(
runtime_environment=FakeRuntimeEnvironment(backend_root, frontend_root),
dependency_checker=PluginDependencyChecker(
@@ -78,7 +106,11 @@ def build_runtime_with_gateway(
def create_controller_dir(plugin_root: Path) -> None:
- """创建测试插件 controller 目录。"""
+ """
+ 创建测试插件 controller 目录。
+
+ :param plugin_root: 插件的根目录
+ """
(plugin_root / 'controller').mkdir(parents=True)
@@ -88,7 +120,14 @@ def create_frontend_view(
view_path: str = 'index.vue',
frontend_root: Path | None = None,
) -> None:
- """创建测试插件前端视图文件。"""
+ """
+ 创建测试插件前端视图文件。
+
+ :param backend_root: 后端项目的根目录
+ :param plugin_id: 插件清单中的唯一标识
+ :param view_path: 需要加载的视图路径
+ :param frontend_root: 前端项目的根目录
+ """
resolved_frontend_root = frontend_root or Path(
PluginRuntimeEnvironmentService(backend_root=backend_root).get_frontend_dir()
)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/gateway.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/gateway.py
index 2e77162d7..d75c50485 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/gateway.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/gateway.py
@@ -17,22 +17,40 @@
class FakePluginLifecycleUnitOfWork:
"""
测试用插件生命周期主事务工作单元。
+
+ :ivar gateway: 代理底层操作的网关
+ :ivar session_context: 当前会话的上下文
+ :ivar session: 当前操作共用的会话
"""
def __init__(self, gateway: 'FakePluginRuntimeGateway') -> None:
- """初始化测试生命周期 UoW。"""
+ """
+ 初始化测试生命周期 UoW。
+
+ :param gateway: 代理底层操作的网关
+ """
self.gateway = gateway
self.session_context: FakeSession | None = None
self.session: FakeSession | None = None
async def __aenter__(self) -> 'FakePluginLifecycleUnitOfWork':
- """打开测试生命周期主事务会话。"""
+ """
+ 打开测试生命周期主事务会话。
+
+ :return: 当前实例
+ """
self.session_context = self.gateway.session_local()
self.session = await self.session_context.__aenter__()
return self
async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> None:
- """关闭测试生命周期主事务会话。"""
+ """
+ 关闭测试生命周期主事务会话。
+
+ :param exc_type: 退出上下文时的异常类型
+ :param exc: 捕获到的异常实例
+ :param traceback: 异常的调用栈
+ """
if self.session_context is None:
return
await self.session_context.__aexit__(exc_type, exc, traceback)
@@ -40,7 +58,12 @@ async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> N
self.session = None
async def check_installed_menu_conflicts(self, discovered_plugin: object) -> list[SimpleNamespace]:
- """检查已安装菜单冲突。"""
+ """
+ 检查已安装菜单冲突。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 安装菜单的冲突检查结果
+ """
return await FakePluginService.check_installed_menu_conflict_services(self.session, discovered_plugin)
async def upsert_discovered_plugin(
@@ -49,7 +72,14 @@ async def upsert_discovered_plugin(
backend_root: Path,
frontend_root: Path | None = None,
) -> SimpleNamespace:
- """写入或更新已发现插件。"""
+ """
+ 写入或更新已发现插件。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param backend_root: 后端项目的根目录
+ :param frontend_root: 前端项目的根目录
+ :return: 保存后的插件状态
+ """
return await FakePluginService.upsert_discovered_plugin_services(
self.session,
discovered_plugin,
@@ -58,35 +88,75 @@ async def upsert_discovered_plugin(
)
async def install_plugin_menu(self, discovered_plugin: object, *, enabled: bool) -> None:
- """安装插件菜单。"""
+ """
+ 安装插件菜单。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param enabled: 是否启用该项功能
+ """
await FakePluginService.install_plugin_menu_services(self.session, discovered_plugin, enabled=enabled)
async def install_plugin_default_config(self, discovered_plugin: object) -> list[SimpleNamespace]:
- """安装插件默认配置。"""
+ """
+ 安装插件默认配置。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 默认配置的安装结果
+ """
return await FakePluginService.install_plugin_default_config_services(self.session, discovered_plugin)
async def install_plugin_jobs(self, discovered_plugin: object, *, enabled: bool) -> None:
- """同步插件任务。"""
+ """
+ 同步插件任务。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param enabled: 是否启用该项功能
+ """
await FakePluginService.install_plugin_job_services(self.session, discovered_plugin, enabled=enabled)
async def mark_plugin_installed(self, discovered_plugin: object) -> SimpleNamespace:
- """标记插件已安装。"""
+ """
+ 标记插件已安装。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 更新后的安装标记
+ """
return await FakePluginService.mark_plugin_installed_services(self.session, discovered_plugin)
async def build_plugin_purge_plan(self, discovered_plugin: object) -> object:
- """构建插件物理清理计划。"""
+ """
+ 构建插件物理清理计划。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 插件物理清理计划
+ """
return await FakePluginService.build_plugin_purge_plan_services(self.session, discovered_plugin)
async def purge_plugin_metadata(self, discovered_plugin: object) -> object:
- """清理插件平台元数据。"""
+ """
+ 清理插件平台元数据。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 插件元数据的清理结果
+ """
return await FakePluginService.purge_plugin_services(self.session, discovered_plugin)
async def build_plugin_purge_plan_by_id(self, plugin_id: str) -> object:
- """按插件 ID 构建孤儿元数据清理计划。"""
+ """
+ 按插件 ID 构建孤儿元数据清理计划。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 按插件标识生成的清理计划
+ """
return await FakePluginService.build_plugin_purge_plan_by_id_services(self.session, plugin_id)
async def purge_plugin_metadata_by_id(self, plugin_id: str) -> object:
- """按插件 ID 清理孤儿元数据。"""
+ """
+ 按插件 ID 清理孤儿元数据。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 按插件标识执行的清理结果
+ """
return await FakePluginService.purge_plugin_metadata_by_id_services(self.session, plugin_id)
async def commit(self) -> None:
@@ -97,6 +167,11 @@ async def commit(self) -> None:
class FakePluginRuntimeGateway:
"""
测试用插件运行时适配器。
+
+ :ivar session_local: 为测试创建本地数据库会话的工厂
+ :ivar lifecycle_uows: 已创建的生命周期事务工作单元
+ :ivar completed_process: 用于模拟子进程执行结果的对象
+ :ivar commands: 测试替身收到的命令
"""
def __init__(self) -> None:
@@ -107,36 +182,67 @@ def __init__(self) -> None:
self.commands: list[tuple[list[str], str, int | None]] = []
def open_lifecycle_unit_of_work(self) -> FakePluginLifecycleUnitOfWork:
- """打开测试生命周期主事务工作单元。"""
+ """
+ 打开测试生命周期主事务工作单元。
+
+ :return: 供调用方使用的 ``unit_of_work``
+ """
unit_of_work = FakePluginLifecycleUnitOfWork(self)
self.lifecycle_uows.append(unit_of_work)
return unit_of_work
def get_async_session_local(self) -> FakeSessionLocal:
- """获取测试会话工厂。"""
+ """
+ 获取测试会话工厂。
+
+ :return: 测试会话工厂
+ """
return self.session_local
def get_plugin_service(self) -> type[FakePluginService]:
- """获取测试插件服务。"""
+ """
+ 获取测试插件服务。
+
+ :return: 测试插件服务
+ """
return FakePluginService
async def list_plugin_states(self) -> list[SimpleNamespace]:
- """获取测试插件状态列表。"""
+ """
+ 获取测试插件状态列表。
+
+ :return: 测试插件状态列表
+ """
async with self.session_local() as session:
return await FakePluginService.get_plugin_list_services(session)
async def get_plugin_state(self, plugin_id: str) -> SimpleNamespace | None:
- """读取内存状态,不在生命周期事务记录中创建只读会话。"""
+ """
+ 读取内存状态,不在生命周期事务记录中创建只读会话。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 内存状态
+ """
return await FakePluginService.plugin_detail_services(None, plugin_id)
@staticmethod
def build_operation_log_export_query(export_limit: int) -> SimpleNamespace:
- """构建测试用插件操作日志导出查询对象。"""
+ """
+ 构建测试用插件操作日志导出查询对象。
+
+ :param export_limit: 导出数量上限
+ :return: 测试用插件操作日志导出查询对象
+ """
return SimpleNamespace(export_limit=export_limit, exportLimit=export_limit)
@staticmethod
def build_config_update(values: dict[str, object]) -> SimpleNamespace:
- """构建测试用插件配置更新对象。"""
+ """
+ 构建测试用插件配置更新对象。
+
+ :param values: 当前处理的值集合
+ :return: 测试用插件配置更新对象
+ """
return SimpleNamespace(values=values)
async def get_plugin_config(
@@ -145,7 +251,13 @@ async def get_plugin_config(
*,
reveal_secret: bool = False,
) -> list[SimpleNamespace]:
- """获取测试插件配置。"""
+ """
+ 获取测试插件配置。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param reveal_secret: 是否在返回结果中显示敏感值
+ :return: 测试插件配置
+ """
async with self.session_local() as session:
configs = await FakePluginService.get_plugin_config_services(
session,
@@ -159,7 +271,13 @@ async def update_plugin_config(
discovered_plugin: object,
values: dict[str, object],
) -> list[SimpleNamespace]:
- """更新测试插件配置。"""
+ """
+ 更新测试插件配置。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param values: 当前处理的值集合
+ :return: 供调用方使用的 ``configs``
+ """
async with self.session_local() as session:
configs = await FakePluginService.update_plugin_config_services(
session,
@@ -177,7 +295,15 @@ async def set_plugin_config(
audit_operation: str,
success_message: str,
) -> list[SimpleNamespace]:
- """在同一事务中更新测试插件配置并记录审计日志。"""
+ """
+ 在同一事务中更新测试插件配置并记录审计日志。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param values: 当前处理的值集合
+ :param audit_operation: 审计操作类型
+ :param success_message: 操作成功提示
+ :return: 供调用方使用的 ``configs``
+ """
async with self.session_local() as session:
before_configs = await FakePluginService.get_plugin_config_services(
session,
@@ -213,7 +339,13 @@ async def add_plugin_operation_log(
dry_run: bool,
continue_on_error: bool,
) -> None:
- """记录测试插件操作日志。"""
+ """
+ 记录测试插件操作日志。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :param dry_run: 是否只预览操作结果
+ :param continue_on_error: 单项操作失败后是否继续执行
+ """
async with self.session_local() as session:
await FakePluginService.add_plugin_operation_log_services(
session,
@@ -224,7 +356,12 @@ async def add_plugin_operation_log(
await session.commit()
async def list_plugin_operation_logs(self, *, export_limit: int) -> list[SimpleNamespace]:
- """获取测试插件操作审计日志列表。"""
+ """
+ 获取测试插件操作审计日志列表。
+
+ :param export_limit: 导出数量上限
+ :return: 测试插件操作审计日志列表
+ """
async with self.session_local() as session:
return await FakePluginService.get_plugin_operation_log_export_list_services(
session,
@@ -232,7 +369,13 @@ async def list_plugin_operation_logs(self, *, export_limit: int) -> list[SimpleN
)
async def mark_plugin_error(self, plugin_id: str, error_message: str) -> bool:
- """标记测试插件错误状态。"""
+ """
+ 标记测试插件错误状态。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param error_message: 记录到结果或审计日志中的错误详情
+ :return: 是否标记测试插件错误状态
+ """
async with self.session_local() as session:
result = await FakePluginService.mark_plugin_error_services(session, plugin_id, error_message)
if getattr(result, 'is_success', False):
@@ -245,12 +388,24 @@ async def list_plugin_migrations(
plugin_id: str,
status: str | None = None,
) -> list[SimpleNamespace]:
- """查询测试插件 migration 历史。"""
+ """
+ 查询测试插件 migration 历史。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param status: 操作或记录所处的状态
+ :return: 测试插件 migration 历史
+ """
async with self.session_local() as session:
return await FakePluginService.get_plugin_migration_list_services(session, plugin_id, status)
async def get_plugin_migration(self, plugin_id: str, migration_path: str) -> SimpleNamespace | None:
- """获取测试插件 migration 历史。"""
+ """
+ 获取测试插件 migration 历史。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :return: 测试插件 migration 历史
+ """
async with self.session_local() as session:
return await FakePluginService.get_plugin_migration_services(session, plugin_id, migration_path)
@@ -261,7 +416,15 @@ async def mark_plugin_migration_status(
status: str,
error_message: str | None = None,
) -> SimpleNamespace | None:
- """人工标记测试插件 migration 历史状态。"""
+ """
+ 人工标记测试插件 migration 历史状态。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :param status: 操作或记录所处的状态
+ :param error_message: 记录到结果或审计日志中的错误详情
+ :return: 插件的数据迁移配置
+ """
async with self.session_local() as session:
migration = await FakePluginService.mark_plugin_migration_status_services(
session,
@@ -275,12 +438,22 @@ async def mark_plugin_migration_status(
return migration
async def build_plugin_purge_plan(self, discovered_plugin: object) -> object:
- """构建测试插件物理清理计划。"""
+ """
+ 构建测试插件物理清理计划。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 测试插件物理清理计划
+ """
async with self.session_local() as session:
return await FakePluginService.build_plugin_purge_plan_services(session, discovered_plugin)
async def run_plugin_migrations(self, discovered_plugin: object) -> list[object]:
- """使用独立测试 session 执行插件 migration。"""
+ """
+ 使用独立测试 session 执行插件 migration。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 独立会话中执行迁移得到的结果
+ """
async with self.session_local() as migration_session:
return await PluginMigrationRunner(
discovered_plugin,
@@ -298,7 +471,14 @@ async def set_plugin_enabled_state(
enabled: bool,
discovered_plugin: object | None = None,
) -> SimpleNamespace:
- """更新测试插件启停状态,并在启用时同步菜单。"""
+ """
+ 更新测试插件启停状态,并在启用时同步菜单。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param enabled: 是否启用该项功能
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 当前调用产生的响应
+ """
async with self.session_local() as session:
response = await FakePluginService.update_plugin_enabled_services(
session,
@@ -313,7 +493,12 @@ async def set_plugin_enabled_state(
return response
async def mark_plugin_uninstalled_state(self, plugin_id: str) -> SimpleNamespace:
- """标记测试插件安全卸载。"""
+ """
+ 标记测试插件安全卸载。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 当前调用产生的响应
+ """
async with self.session_local() as session:
response = await FakePluginService.mark_plugin_uninstalled_services(session, plugin_id)
if getattr(response, 'is_success', False):
@@ -330,7 +515,18 @@ def build_migration_record(
status: str = 'success',
error_message: str | None = None,
) -> SimpleNamespace:
- """构建测试用插件 migration 执行历史对象。"""
+ """
+ 构建测试用插件 migration 执行历史对象。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :param checksum: 校验内容完整性使用的校验和
+ :param version: 当前记录的版本
+ :param statement_count: SQL 语句数量
+ :param status: 操作或记录所处的状态
+ :param error_message: 记录到结果或审计日志中的错误详情
+ :return: 测试用插件 migration 执行历史对象
+ """
return SimpleNamespace(
plugin_id=plugin_id,
migration_path=migration_path,
@@ -354,7 +550,15 @@ def run_command(
timeout: int | None = None,
output_callback: PluginCommandOutputCallback | None = None,
) -> CompletedProcess[str]:
- """记录测试用系统命令。"""
+ """
+ 记录测试用系统命令。
+
+ :param command: 执行的命令及其参数
+ :param workdir: 命令执行时使用的工作目录
+ :param timeout: 等待操作完成的超时限制
+ :param output_callback: 依赖安装实时输出回调
+ :return: 供调用方使用的 ``self.completed_process``
+ """
self.commands.append((command, workdir, timeout))
self._simulate_npm_package_json_update(command, workdir)
if output_callback is not None:
@@ -365,7 +569,12 @@ def run_command(
return self.completed_process
def _simulate_npm_package_json_update(self, command: list[str], workdir: str) -> None:
- """模拟 npm install 对 package.json 根依赖声明的改写。"""
+ """
+ 模拟 npm install 对 package.json 根依赖声明的改写。
+
+ :param command: 执行的命令及其参数
+ :param workdir: 命令执行时使用的工作目录
+ """
if (
self.completed_process.returncode != 0
or len(command) < MIN_NPM_INSTALL_COMMAND_LENGTH
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/management.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/management.py
index 2b549c147..1c84484ba 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/management.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/management.py
@@ -7,6 +7,26 @@
class FakePluginService:
"""
测试用插件服务。
+
+ :cvar upsert_called: 记录 ``upsert`` 的调用情况
+ :cvar upsert_backend_root: 最近一次更新插件时记录的后端目录
+ :cvar upsert_frontend_root: 最近一次更新插件时记录的前端目录
+ :cvar install_plugin_menu_called_with: 调用 ``install_plugin_menu`` 时记录的参数
+ :cvar install_plugin_job_called_with: 调用 ``install_plugin_job`` 时记录的参数
+ :cvar install_config_called: 记录 ``install_config`` 的调用情况
+ :cvar mark_installed_called: 记录 ``mark_installed`` 的调用情况
+ :cvar mark_uninstalled_called_with: 调用 ``mark_uninstalled`` 时记录的参数
+ :cvar purge_called: 记录 ``purge`` 的调用情况
+ :cvar purge_by_id_called_with: 调用 ``purge_by_id`` 时记录的参数
+ :cvar update_enabled_called_with: 调用 ``update_enabled`` 时记录的参数
+ :cvar detail_plugin: 查询详情时返回的测试插件
+ :cvar upsert_plugin: 最近一次插入或更新的插件
+ :cvar installed_menu_conflicts: 已安装菜单冲突列表
+ :cvar migration_checksums: 按迁移名称记录的校验和
+ :cvar migration_records: 测试中保存的迁移执行记录
+ :cvar operation_logs: 审计记录列表
+ :cvar plugin_list: 测试仓储返回的插件列表
+ :cvar marked_errors: 已标记为失败的记录及原因
"""
upsert_called = False
@@ -54,12 +74,23 @@ def reset(cls) -> None:
@classmethod
async def get_plugin_list_services(cls, query_db: object) -> list[SimpleNamespace]:
- """读取测试用插件列表。"""
+ """
+ 读取测试用插件列表。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :return: 测试用插件列表
+ """
return cls.plugin_list
@classmethod
async def plugin_detail_services(cls, query_db: object, plugin_id: str) -> SimpleNamespace | None:
- """读取测试插件详情。"""
+ """
+ 读取测试插件详情。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 测试插件详情
+ """
return cls.detail_plugin
@classmethod
@@ -70,7 +101,15 @@ async def upsert_discovered_plugin_services(
backend_root: Path,
frontend_root: Path,
) -> SimpleNamespace:
- """记录插件写入调用。"""
+ """
+ 记录插件写入调用。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param backend_root: 后端项目的根目录
+ :param frontend_root: 前端项目的根目录
+ :return: 测试服务记录的插件写入结果
+ """
cls.upsert_called = True
cls.upsert_backend_root = backend_root
cls.upsert_frontend_root = frontend_root
@@ -90,7 +129,13 @@ async def check_installed_menu_conflict_services(
query_db: object,
discovered_plugin: object,
) -> list[SimpleNamespace]:
- """读取测试用已安装菜单冲突。"""
+ """
+ 读取测试用已安装菜单冲突。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 测试用已安装菜单冲突
+ """
return cls.installed_menu_conflicts
@classmethod
@@ -100,7 +145,14 @@ async def get_plugin_migration_services(
plugin_id: str,
migration_path: str,
) -> SimpleNamespace | None:
- """读取测试用插件 migration 执行历史。"""
+ """
+ 读取测试用插件 migration 执行历史。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :return: 测试用插件 migration 执行历史
+ """
for migration in reversed(cls.migration_records):
if (
getattr(migration, 'plugin_id', None) == plugin_id
@@ -121,7 +173,14 @@ async def get_plugin_migration_list_services(
plugin_id: str,
status: str | None = None,
) -> list[SimpleNamespace]:
- """读取测试用插件 migration 执行历史列表。"""
+ """
+ 读取测试用插件 migration 执行历史列表。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param status: 操作或记录所处的状态
+ :return: 测试用插件 migration 执行历史列表
+ """
return [
migration
for migration in cls.migration_records
@@ -135,7 +194,13 @@ async def add_plugin_migration_services(
query_db: object,
plugin_migration: object,
) -> object:
- """记录插件 migration 执行历史。"""
+ """
+ 记录插件 migration 执行历史。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_migration: 插件清单中的迁移声明
+ :return: 插件清单中的迁移声明
+ """
cls.migration_records.append(plugin_migration)
return plugin_migration
@@ -148,7 +213,16 @@ async def mark_plugin_migration_status_services(
status: str,
error_message: str | None = None,
) -> object | None:
- """人工标记测试用插件 migration 执行历史状态。"""
+ """
+ 人工标记测试用插件 migration 执行历史状态。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :param status: 操作或记录所处的状态
+ :param error_message: 记录到结果或审计日志中的错误详情
+ :return: 插件的数据迁移配置
+ """
for migration in reversed(cls.migration_records):
if (
getattr(migration, 'plugin_id', None) == plugin_id
@@ -169,7 +243,15 @@ async def add_plugin_operation_log_services(
dry_run: bool,
continue_on_error: bool,
) -> SimpleNamespace:
- """记录测试用插件批量操作审计日志。"""
+ """
+ 记录测试用插件批量操作审计日志。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param payload: 随调用传入或返回的结构化数据
+ :param dry_run: 是否只预览操作结果
+ :param continue_on_error: 单项操作失败后是否继续执行
+ :return: 供调用方使用的 ``operation_log``
+ """
operation_log = SimpleNamespace(
payload=payload,
dry_run=dry_run,
@@ -185,7 +267,13 @@ async def get_plugin_operation_log_export_list_services(
query_db: object,
query_object: object,
) -> list[SimpleNamespace]:
- """读取测试用插件操作审计导出列表。"""
+ """
+ 读取测试用插件操作审计导出列表。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param query_object: 用于过滤记录的查询模型
+ :return: 测试用插件操作审计导出列表
+ """
return [
SimpleNamespace(
operation_id=index + 1,
@@ -209,7 +297,13 @@ async def install_plugin_menu_services(
*,
enabled: bool,
) -> None:
- """记录指定插件菜单安装调用。"""
+ """
+ 记录指定插件菜单安装调用。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param enabled: 是否启用该项功能
+ """
cls.install_plugin_menu_called_with = (discovered_plugin.manifest.id, enabled)
@classmethod
@@ -218,7 +312,13 @@ async def install_plugin_default_config_services(
query_db: object,
discovered_plugin: object,
) -> list[SimpleNamespace]:
- """记录插件默认配置安装调用。"""
+ """
+ 记录插件默认配置安装调用。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 供调用方使用的 ``configs``
+ """
cls.install_config_called = True
configs = []
for item in discovered_plugin.manifest.config.items:
@@ -238,7 +338,13 @@ async def install_plugin_job_services(
*,
enabled: bool,
) -> None:
- """记录插件任务同步调用。"""
+ """
+ 记录插件任务同步调用。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param enabled: 是否启用该项功能
+ """
cls.install_plugin_job_called_with = (discovered_plugin.manifest.id, enabled)
@classmethod
@@ -249,7 +355,14 @@ async def get_plugin_config_services(
*,
reveal_secret: bool = False,
) -> list[SimpleNamespace]:
- """读取测试用插件配置。"""
+ """
+ 读取测试用插件配置。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param reveal_secret: 是否在返回结果中显示敏感值
+ :return: 测试用插件配置
+ """
configs = []
for item in discovered_plugin.manifest.config.items:
value = '******' if item.secret and not reveal_secret else item.default
@@ -277,7 +390,14 @@ async def update_plugin_config_services(
discovered_plugin: object,
update_model: object,
) -> list[SimpleNamespace]:
- """更新测试用插件配置。"""
+ """
+ 更新测试用插件配置。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param update_model: 包含待更新字段的模型
+ :return: 供调用方使用的 ``configs``
+ """
configs = []
for key, value in update_model.values.items():
payload = {
@@ -295,7 +415,13 @@ async def mark_plugin_installed_services(
query_db: object,
discovered_plugin: object,
) -> SimpleNamespace:
- """记录插件安装完成标记调用。"""
+ """
+ 记录插件安装完成标记调用。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: ``SimpleNamespace`` 实例
+ """
cls.mark_installed_called = True
cls.plugin_list = [
plugin for plugin in cls.plugin_list if getattr(plugin, 'plugin_id', None) != discovered_plugin.manifest.id
@@ -324,13 +450,27 @@ async def update_plugin_enabled_services(
enabled: bool,
discovered_plugin: object | None = None,
) -> SimpleNamespace:
- """记录插件启停调用。"""
+ """
+ 记录插件启停调用。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param enabled: 是否启用该项功能
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: ``SimpleNamespace`` 实例
+ """
cls.update_enabled_called_with = (plugin_id, enabled, discovered_plugin)
return SimpleNamespace(is_success=True, message='启用成功' if enabled else '停用成功')
@classmethod
async def mark_plugin_uninstalled_services(cls, query_db: object, plugin_id: str) -> SimpleNamespace:
- """记录插件卸载标记调用。"""
+ """
+ 记录插件卸载标记调用。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :return: ``SimpleNamespace`` 实例
+ """
cls.mark_uninstalled_called_with = plugin_id
return SimpleNamespace(is_success=True, message='卸载成功')
@@ -341,14 +481,27 @@ async def mark_plugin_error_services(
plugin_id: str,
error_message: str,
) -> SimpleNamespace:
- """记录插件错误状态标记调用。"""
+ """
+ 记录插件错误状态标记调用。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param error_message: 记录到结果或审计日志中的错误详情
+ :return: ``SimpleNamespace`` 实例
+ """
cls.marked_errors.append((plugin_id, error_message))
return SimpleNamespace(is_success=True, message='插件状态已标记为异常')
@classmethod
async def build_plugin_purge_plan_services(cls, query_db: object, discovered_plugin: object) -> object:
- """构建测试用插件物理清理计划。"""
+ """
+ 构建测试用插件物理清理计划。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 测试用插件物理清理计划
+ """
return PluginPurgePlanner.build_plan(
discovered_plugin,
menu_count=1,
@@ -359,13 +512,25 @@ async def build_plugin_purge_plan_services(cls, query_db: object, discovered_plu
@classmethod
async def purge_plugin_services(cls, query_db: object, discovered_plugin: object) -> object:
- """记录插件物理清理调用。"""
+ """
+ 记录插件物理清理调用。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 供断言比对的插件清理计划
+ """
cls.purge_called = True
return await cls.build_plugin_purge_plan_services(query_db, discovered_plugin)
@classmethod
async def build_plugin_purge_plan_by_id_services(cls, query_db: object, plugin_id: str) -> object:
- """构建测试用孤儿插件元数据清理计划。"""
+ """
+ 构建测试用孤儿插件元数据清理计划。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 测试用孤儿插件元数据清理计划
+ """
return PluginPurgePlanner.build_metadata_plan(
plugin_id,
state_count=1,
@@ -377,6 +542,12 @@ async def build_plugin_purge_plan_by_id_services(cls, query_db: object, plugin_i
@classmethod
async def purge_plugin_metadata_by_id_services(cls, query_db: object, plugin_id: str) -> object:
- """记录按插件 ID 清理孤儿元数据调用。"""
+ """
+ 记录按插件 ID 清理孤儿元数据调用。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 供断言比对的孤立元数据清理计划
+ """
cls.purge_by_id_called_with = plugin_id
return await cls.build_plugin_purge_plan_by_id_services(query_db, plugin_id)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/session.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/session.py
index 62b1fd66f..0712608ec 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/session.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/session.py
@@ -1,6 +1,10 @@
class FakeSession:
"""
测试用异步数据库会话。
+
+ :ivar committed: 是否已经提交事务
+ :ivar rolled_back: 是否已经回滚事务
+ :ivar executed_statements: 测试替身收到的 SQL 语句
"""
def __init__(self) -> None:
@@ -10,11 +14,21 @@ def __init__(self) -> None:
self.executed_statements = []
async def __aenter__(self) -> 'FakeSession':
- """进入异步上下文。"""
+ """
+ 进入异步上下文。
+
+ :return: 当前实例
+ """
return self
async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> None:
- """退出异步上下文。"""
+ """
+ 退出异步上下文。
+
+ :param exc_type: 退出上下文时的异常类型
+ :param exc: 捕获到的异常实例
+ :param traceback: 异常的调用栈
+ """
async def commit(self) -> None:
"""记录提交动作。"""
@@ -25,13 +39,20 @@ async def rollback(self) -> None:
self.rolled_back = True
async def execute(self, statement: object) -> None:
- """记录 SQL 执行动作。"""
+ """
+ 记录 SQL 执行动作。
+
+ :param statement: 即将执行的数据库语句
+ """
self.executed_statements.append(str(statement))
class FakeSessionLocal:
"""
测试用异步数据库会话工厂。
+
+ :ivar last_session: 最近一次创建或使用的会话
+ :ivar sessions: 测试创建的数据库会话或会话工厂
"""
def __init__(self) -> None:
@@ -40,24 +61,40 @@ def __init__(self) -> None:
self.sessions: list[FakeSession] = []
def __call__(self) -> FakeSession:
- """创建测试会话。"""
+ """
+ 创建测试会话。
+
+ :return: 测试会话
+ """
self.last_session = FakeSession()
self.sessions.append(self.last_session)
return self.last_session
@property
def audit_session(self) -> FakeSession | None:
- """获取最后一个审计会话。"""
+ """
+ 获取最后一个审计会话。
+
+ :return: 最后一个审计会话
+ """
return self.sessions[-1] if self.sessions else None
@property
def committed_session(self) -> FakeSession | None:
- """获取最后一个已提交会话。"""
+ """
+ 获取最后一个已提交会话。
+
+ :return: 最后一个已提交会话
+ """
committed_sessions = [session for session in self.sessions if session.committed]
return committed_sessions[-1] if committed_sessions else None
@property
def executed_session(self) -> FakeSession | None:
- """获取最后一个执行过 SQL 的会话。"""
+ """
+ 获取最后一个执行过 SQL 的会话。
+
+ :return: 最后一个执行过 SQL 的会话
+ """
executed_sessions = [session for session in self.sessions if session.executed_statements]
return executed_sessions[-1] if executed_sessions else None
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_artifact_guards.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_artifact_guards.py
index 2af5b8b7a..017c3ba31 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_artifact_guards.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_artifact_guards.py
@@ -21,6 +21,7 @@
async def test_database_artifact_source_blocks_legacy_lifecycle_without_source_directory(
tmp_path: Path, operation: str, dry_run: bool
) -> None:
+ """数据库中的产物来源即使没有源码目录也阻止旧生命周期操作。"""
gateway = FakePluginRuntimeGateway()
FakePluginService.detail_plugin = SimpleNamespace(plugin_id='demo', source='artifact')
runtime = build_runtime_with_gateway(tmp_path / 'backend', gateway)
@@ -41,8 +42,18 @@ async def test_database_artifact_source_blocks_legacy_lifecycle_without_source_d
@pytest.mark.asyncio
async def test_state_query_failure_cannot_authorize_orphan_purge(tmp_path: Path) -> None:
+ """状态查询失败时拒绝清理孤立产物。"""
+
class FailingGateway(FakePluginRuntimeGateway):
+ """在插件状态查询时模拟失败。"""
+
async def get_plugin_state(self, plugin_id: str) -> None:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :raises RuntimeError: 模拟插件状态数据库不可用
+ """
raise RuntimeError('state database unavailable')
gateway = FailingGateway()
@@ -54,20 +65,45 @@ async def get_plugin_state(self, plugin_id: str) -> None:
@pytest.mark.asyncio
async def test_config_read_resolves_selected_artifact_without_source_directory(tmp_path: Path) -> None:
+ """无源码目录时仍可按配置读取选中产物。"""
selected = object()
class ArtifactGateway(FakePluginRuntimeGateway):
+ """提供测试所选制品对应的插件记录。"""
+
async def get_selected_artifact_plugin(self, plugin_id: str, backend_root: Path) -> object:
+ """
+ 校验插件来源并返回所选交付物。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param backend_root: 后端项目的根目录
+ :return: 所选交付物
+ """
assert plugin_id == 'demo'
assert backend_root == tmp_path / 'backend'
return selected
async def get_plugin_config(self, discovered_plugin: object, *, reveal_secret: bool = False) -> list:
+ """
+ 检查插件选择和配置读取参数。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param reveal_secret: 是否在返回结果中显示敏感值
+ :return: 模拟的插件配置条目列表
+ """
assert discovered_plugin is selected
assert reveal_secret is False
return []
async def set_plugin_config(self, discovered_plugin: object, values: dict, **kwargs: object) -> list:
+ """
+ 校验写入配置的目标插件及字段值。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param values: 当前处理的值集合
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 模拟写入后的配置条目列表
+ """
assert discovered_plugin is selected
assert values == {'provider': 'local'}
return []
@@ -83,6 +119,7 @@ async def set_plugin_config(self, discovered_plugin: object, values: dict, **kwa
@pytest.mark.parametrize('method', ['install_plugin_dependencies', 'install_plugin_dependencies_from_cli'])
def test_artifact_source_blocks_dependency_install_even_when_same_id_source_exists(tmp_path: Path, method: str) -> None:
+ """同标识源码存在时产物来源仍阻止安装依赖。"""
backend = tmp_path / 'backend'
write_manifest(
backend / 'plugins' / 'demo',
@@ -98,8 +135,18 @@ def test_artifact_source_blocks_dependency_install_even_when_same_id_source_exis
def test_dependency_install_fails_closed_when_source_query_fails(tmp_path: Path) -> None:
+ """依赖来源查询失败时拒绝安装。"""
+
class FailingGateway(FakePluginRuntimeGateway):
+ """在插件状态查询时模拟失败。"""
+
async def get_plugin_state(self, plugin_id: str) -> None:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :raises RuntimeError: 模拟插件状态数据库不可用
+ """
raise RuntimeError('database unavailable')
gateway = FailingGateway()
@@ -110,8 +157,17 @@ async def get_plugin_state(self, plugin_id: str) -> None:
@pytest.mark.asyncio
async def test_sync_dependency_install_never_runs_nested_event_loop(tmp_path: Path) -> None:
+ """同步依赖安装不会嵌套启动事件循环。"""
+
class UnexpectedQueryGateway(FakePluginRuntimeGateway):
+ """在不应查询插件状态时触发测试失败。"""
+
async def get_plugin_state(self, plugin_id: str) -> None:
+ """
+ 若执行到此操作则立即使测试失败。
+
+ :param plugin_id: 插件清单中的唯一标识
+ """
pytest.fail('synchronous wrapper must not query within the running loop')
gateway = UnexpectedQueryGateway()
@@ -123,6 +179,7 @@ async def get_plugin_state(self, plugin_id: str) -> None:
@pytest.mark.asyncio
async def test_configuration_never_falls_back_to_conflicting_source(tmp_path: Path) -> None:
+ """配置读取不会回退到冲突的源码。"""
backend = tmp_path / 'backend'
write_manifest(
backend / 'plugins' / 'demo',
@@ -130,7 +187,16 @@ async def test_configuration_never_falls_back_to_conflicting_source(tmp_path: Pa
)
class ConflictingGateway(FakePluginRuntimeGateway):
+ """模拟插件制品选择冲突。"""
+
async def get_selected_artifact_plugin(self, plugin_id: str, backend_root: Path) -> None:
+ """
+ 在调用时报告预期的测试失败:制品与源码目录冲突。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param backend_root: 后端项目的根目录
+ :raises ValueError: 制品与源码目录冲突
+ """
raise ValueError('制品与源码目录冲突')
FakePluginService.detail_plugin = SimpleNamespace(plugin_id='demo', source='artifact')
@@ -144,6 +210,7 @@ async def get_selected_artifact_plugin(self, plugin_id: str, backend_root: Path)
@pytest.mark.parametrize('method', ['install_plugin_dependencies', 'install_plugin_dependencies_from_cli'])
def test_dependency_source_check_and_audit_share_one_event_loop(tmp_path: Path, method: str) -> None:
+ """依赖来源校验和审计共用事件循环。"""
backend = tmp_path / 'backend'
write_manifest(
backend / 'plugins' / 'demo',
@@ -153,10 +220,25 @@ def test_dependency_source_check_and_audit_share_one_event_loop(tmp_path: Path,
loops: list[asyncio.AbstractEventLoop] = []
class LoopAffineGateway(FakePluginRuntimeGateway):
+ """检查插件操作是否使用同一个事件循环。"""
+
async def get_plugin_state(self, plugin_id: str) -> None:
+ """
+ 提供插件状态查询的观测点。
+
+ :param plugin_id: 插件清单中的唯一标识
+ """
loops.append(asyncio.get_running_loop())
async def add_plugin_operation_log(self, payload: dict, *, dry_run: bool, continue_on_error: bool) -> None:
+ """
+ 记录插件日志调用及其事件循环。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :param dry_run: 是否只预览操作结果
+ :param continue_on_error: 单项操作失败后是否继续执行
+ :raises RuntimeError: 检测到跨事件循环复用异步数据库连接池
+ """
current_loop = asyncio.get_running_loop()
if loops[0] is not current_loop:
raise RuntimeError('shared async database pool was reused from a different event loop')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_batch_dependencies.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_batch_dependencies.py
index 72e4d475c..df3eb261d 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_batch_dependencies.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_batch_dependencies.py
@@ -156,17 +156,26 @@ def test_record_plugin_failure_state_logs_and_swallows_persistence_error(monkeyp
logged_messages = []
class BrokenAuditGateway:
- """
- 测试用异常审计网关。
- """
+ """测试用异常审计网关。"""
@staticmethod
async def mark_plugin_error(plugin_id: str, error_message: str) -> None:
- """模拟标记插件异常失败。"""
+ """
+ 模拟标记插件异常失败。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param error_message: 记录到结果或审计日志中的错误详情
+ :raises RuntimeError: 模拟更新插件错误状态时数据库不可用
+ """
raise RuntimeError('db unavailable')
def fake_exception(message: str, *args: object) -> None:
- """构造测试用批量操作异常。"""
+ """
+ 构造测试用批量操作异常。
+
+ :param message: 与当前结果一起返回的说明
+ :param args: 传给被调用对象的位置参数
+ """
logged_messages.append(message % args)
monkeypatch.setattr(audit_module.logger, 'exception', fake_exception)
@@ -331,7 +340,13 @@ def test_plugin_runtime_batch_plugins_continue_on_error_runs_remaining_items(tmp
executed_plugin_ids = []
async def fake_execute(operation: str, plugin_id: str) -> dict[str, object]:
- """测试用单插件执行函数。"""
+ """
+ 测试用单插件执行函数。
+
+ :param operation: 当前处理的操作
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 包含 ``ok``、``message``、``pluginId`` 的数据
+ """
executed_plugin_ids.append(plugin_id)
return {
'ok': plugin_id != 'beta',
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_catalog.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_catalog.py
index 70a08eb4d..d671b5221 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_catalog.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_catalog.py
@@ -29,26 +29,47 @@
class QueryOnlyStateGateway:
"""
仅提供插件状态查询能力的测试网关。
+
+ :ivar plugin_state: 当前记录的插件状态
+ :ivar detail_calls: 记录 ``detail`` 的调用情况
+ :ivar list_called: 记录 ``list`` 的调用情况
"""
def __init__(self, plugin_state: object | None = None) -> None:
- """初始化查询网关。"""
+ """
+ 初始化查询网关。
+
+ :param plugin_state: 当前记录的插件状态
+ """
self.plugin_state = plugin_state
self.detail_calls: list[str] = []
self.list_called = False
async def get_plugin_state(self, plugin_id: str) -> object | None:
- """获取插件状态。"""
+ """
+ 获取插件状态。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 插件状态
+ """
self.detail_calls.append(plugin_id)
return self.plugin_state
async def list_plugin_states(self) -> list[object]:
- """获取插件状态列表。"""
+ """
+ 获取插件状态列表。
+
+ :return: 插件状态列表
+ """
self.list_called = True
return [self.plugin_state] if self.plugin_state is not None else []
def get_plugin_service(self) -> object:
- """禁止查询链路回退到管理服务胖接口。"""
+ """
+ 禁止查询链路回退到管理服务胖接口。
+
+ :raises AssertionError: 状态查询不应依赖 PluginManagementServiceProtocol
+ """
raise AssertionError('状态查询不应依赖 PluginManagementServiceProtocol')
@@ -173,13 +194,21 @@ def test_plugin_runtime_context_sync_state_loader_warns_inside_running_loop(
warnings = []
def fake_warning(message: str) -> None:
- """记录 warning 日志。"""
+ """
+ 记录 warning 日志。
+
+ :param message: 与当前结果一起返回的说明
+ """
warnings.append(message)
monkeypatch.setattr(runtime_context_module.logger, 'warning', fake_warning)
async def load_states_sync_in_loop() -> tuple[list[object], str | None]:
- """在事件循环内调用同步状态读取。"""
+ """
+ 在事件循环内调用同步状态读取。
+
+ :return: 事件循环中读取的插件状态
+ """
return runtime.context.load_database_plugin_states_sync_with_error()
result, database_error = asyncio.run(load_states_sync_in_loop())
@@ -198,22 +227,32 @@ def test_plugin_runtime_context_caches_discovered_plugins(
scanner_roots = []
class FakePluginScanner:
- """
- 测试用插件扫描器。
- """
+ """测试用插件扫描器。"""
def __init__(self, plugins_root: Path) -> None:
- """记录插件扫描根目录。"""
+ """
+ 记录插件扫描根目录。
+
+ :param plugins_root: 后端插件根目录
+ """
scanner_roots.append(plugins_root)
@staticmethod
def discover() -> list:
- """返回测试插件列表。"""
+ """
+ 返回测试插件列表。
+
+ :return: 测试插件列表
+ """
return []
@staticmethod
def discover_with_errors() -> 'PluginDiscoveryResult':
- """返回包含发现错误的测试结果。"""
+ """
+ 返回包含发现错误的测试结果。
+
+ :return: 包含发现错误的测试结果
+ """
return PluginDiscoveryResult()
monkeypatch.setattr(runtime_context_module, 'PluginScanner', FakePluginScanner)
@@ -352,6 +391,9 @@ def test_plugin_runtime_query_entrypoints_delegate_to_query_use_case(
class FakeQueryUseCase:
"""
测试用插件查询 use case。
+
+ :ivar called_entrypoint: 实际调用的插件入口
+ :ivar plugin_id: 插件清单中的唯一标识
"""
def __init__(self) -> None:
@@ -360,18 +402,32 @@ def __init__(self) -> None:
self.plugin_id: str | None = None
def list_plugins(self) -> dict:
- """记录插件列表查询调用。"""
+ """
+ 记录插件列表查询调用。
+
+ :return: 包含 ``ok``、``plugins`` 的数据
+ """
self.called_entrypoint = 'list_plugins'
return {'ok': True, 'plugins': [{'pluginId': 'delegated'}]}
def get_plugin_info(self, plugin_id: str) -> dict:
- """记录插件详情查询调用。"""
+ """
+ 记录插件详情查询调用。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 包含 ``ok``、``plugin`` 的数据
+ """
self.called_entrypoint = 'get_plugin_info'
self.plugin_id = plugin_id
return {'ok': True, 'plugin': {'pluginId': plugin_id}}
async def get_plugin_info_with_state(self, plugin_id: str) -> dict:
- """记录带状态插件详情查询调用。"""
+ """
+ 记录带状态插件详情查询调用。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 包含 ``ok``、``plugin`` 的数据
+ """
self.called_entrypoint = 'get_plugin_info_with_state'
self.plugin_id = plugin_id
return {'ok': True, 'plugin': {'pluginId': plugin_id, 'database': {'available': True}}}
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_check_docs.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_check_docs.py
index 40c4a0426..281f0e5be 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_check_docs.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_check_docs.py
@@ -20,26 +20,38 @@
class PrecheckStateQueryGateway:
- """
- 仅提供预检所需插件状态查询能力的测试网关。
- """
+ """仅提供预检所需插件状态查询能力的测试网关。"""
async def get_plugin_state(self, plugin_id: str) -> object | None:
- """获取插件状态。"""
+ """
+ 获取插件状态。
+
+ :param plugin_id: 插件清单中的唯一标识
+ """
return None
async def list_plugin_states(self) -> list[object]:
- """获取插件状态列表。"""
+ """
+ 获取插件状态列表。
+
+ :return: 插件状态列表
+ """
return []
def get_plugin_service(self) -> object:
- """禁止预检状态读取回退到管理服务胖接口。"""
+ """
+ 禁止预检状态读取回退到管理服务胖接口。
+
+ :raises AssertionError: 预检状态读取不应依赖 PluginManagementServiceProtocol
+ """
raise AssertionError('预检状态读取不应依赖 PluginManagementServiceProtocol')
class PurgePlanOnlyGateway:
"""
仅提供插件清理计划能力的测试网关。
+
+ :ivar calls: 测试替身记录的调用信息
"""
def __init__(self) -> None:
@@ -47,7 +59,12 @@ def __init__(self) -> None:
self.calls: list[str] = []
async def build_plugin_purge_plan(self, discovered_plugin: object) -> object:
- """构建测试清理计划。"""
+ """
+ 构建测试清理计划。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 测试清理计划
+ """
self.calls.append(discovered_plugin.manifest.id)
return PluginPurgePlanner.build_plan(
discovered_plugin,
@@ -58,7 +75,11 @@ async def build_plugin_purge_plan(self, discovered_plugin: object) -> object:
)
def get_plugin_service(self) -> object:
- """禁止清理计划链路回退到管理服务胖接口。"""
+ """
+ 禁止清理计划链路回退到管理服务胖接口。
+
+ :raises AssertionError: 清理计划不应依赖 PluginManagementServiceProtocol
+ """
raise AssertionError('清理计划不应依赖 PluginManagementServiceProtocol')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_install_config_health.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_install_config_health.py
index 398abee15..2977866fe 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_install_config_health.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_install_config_health.py
@@ -29,6 +29,10 @@
class ConfigOnlyGateway:
"""
仅提供插件配置读写能力的测试网关。
+
+ :ivar get_calls: 记录 ``get`` 的调用情况
+ :ivar update_calls: 记录 ``update`` 的调用情况
+ :ivar audit_payloads: 测试中已记录的审计数据
"""
def __init__(self) -> None:
@@ -38,7 +42,13 @@ def __init__(self) -> None:
self.audit_payloads: list[dict[str, object]] = []
async def get_plugin_config(self, discovered_plugin: object, *, reveal_secret: bool = False) -> list[object]:
- """获取插件配置。"""
+ """
+ 获取插件配置。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param reveal_secret: 是否在返回结果中显示敏感值
+ :return: 插件配置
+ """
plugin_id = discovered_plugin.manifest.id
self.get_calls.append((plugin_id, reveal_secret))
value = 'openai-key' if reveal_secret else '******'
@@ -54,7 +64,13 @@ async def get_plugin_config(self, discovered_plugin: object, *, reveal_secret: b
]
async def update_plugin_config(self, discovered_plugin: object, values: dict[str, object]) -> list[object]:
- """更新插件配置。"""
+ """
+ 更新插件配置。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param values: 当前处理的值集合
+ :return: 保存后的模拟配置项
+ """
plugin_id = discovered_plugin.manifest.id
self.update_calls.append((plugin_id, values))
return [
@@ -76,7 +92,15 @@ async def set_plugin_config(
audit_operation: str,
success_message: str,
) -> list[object]:
- """在同一事务语义中更新插件配置并记录审计负载。"""
+ """
+ 在同一事务语义中更新插件配置并记录审计负载。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param values: 当前处理的值集合
+ :param audit_operation: 审计操作类型
+ :param success_message: 操作成功提示
+ :return: 供调用方使用的 ``configs``
+ """
before_configs = await self.get_plugin_config(discovered_plugin, reveal_secret=True)
configs = await self.update_plugin_config(discovered_plugin, values)
self.audit_payloads.append(
@@ -92,7 +116,11 @@ async def set_plugin_config(
return configs
def get_plugin_service(self) -> object:
- """禁止配置链路回退到管理服务胖接口。"""
+ """
+ 禁止配置链路回退到管理服务胖接口。
+
+ :raises AssertionError: 配置读写不应依赖 PluginManagementServiceProtocol
+ """
raise AssertionError('配置读写不应依赖 PluginManagementServiceProtocol')
@@ -182,26 +210,49 @@ def test_plugin_runtime_install_plugin_uses_lifecycle_uow_and_migration_gateway_
class InstallLifecycleUnitOfWork:
"""
测试用插件安装生命周期 UoW。
+
+ :ivar gateway: 代理底层操作的网关
+ :ivar session: 当前操作共用的会话
+ :ivar session_context: 当前会话的上下文
"""
def __init__(self, gateway: 'NoFatInstallGateway') -> None:
- """初始化测试 UoW。"""
+ """
+ 初始化测试 UoW。
+
+ :param gateway: 代理底层操作的网关
+ """
self.gateway = gateway
self.session: FakeSession | None = None
self.session_context: FakeSession | None = None
async def __aenter__(self) -> 'InstallLifecycleUnitOfWork':
- """打开测试 UoW 会话。"""
+ """
+ 打开测试 UoW 会话。
+
+ :return: 当前实例
+ """
self.session_context = self.gateway.session_local()
self.session = await self.session_context.__aenter__()
return self
async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> None:
- """关闭测试 UoW 会话。"""
+ """
+ 关闭测试 UoW 会话。
+
+ :param exc_type: 退出上下文时的异常类型
+ :param exc: 捕获到的异常实例
+ :param traceback: 异常的调用栈
+ """
await self.session_context.__aexit__(exc_type, exc, traceback)
async def check_installed_menu_conflicts(self, discovered_plugin: object) -> list[object]:
- """检查已安装菜单冲突。"""
+ """
+ 检查已安装菜单冲突。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 安装菜单的冲突检查结果
+ """
return await FakePluginService.check_installed_menu_conflict_services(self.session, discovered_plugin)
async def upsert_discovered_plugin(
@@ -210,7 +261,14 @@ async def upsert_discovered_plugin(
backend_root: Path,
frontend_root: Path,
) -> object:
- """写入插件基础状态。"""
+ """
+ 写入插件基础状态。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param backend_root: 后端项目的根目录
+ :param frontend_root: 前端项目的根目录
+ :return: 写入后的插件状态
+ """
return await FakePluginService.upsert_discovered_plugin_services(
self.session,
discovered_plugin,
@@ -219,19 +277,39 @@ async def upsert_discovered_plugin(
)
async def install_plugin_menu(self, discovered_plugin: object, *, enabled: bool) -> None:
- """安装插件菜单。"""
+ """
+ 安装插件菜单。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param enabled: 是否启用该项功能
+ """
await FakePluginService.install_plugin_menu_services(self.session, discovered_plugin, enabled=enabled)
async def install_plugin_default_config(self, discovered_plugin: object) -> list[object]:
- """安装插件默认配置。"""
+ """
+ 安装插件默认配置。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 默认配置的安装结果
+ """
return await FakePluginService.install_plugin_default_config_services(self.session, discovered_plugin)
async def install_plugin_jobs(self, discovered_plugin: object, *, enabled: bool) -> None:
- """同步插件任务。"""
+ """
+ 同步插件任务。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :param enabled: 是否启用该项功能
+ """
await FakePluginService.install_plugin_job_services(self.session, discovered_plugin, enabled=enabled)
async def mark_plugin_installed(self, discovered_plugin: object) -> object:
- """标记插件已安装。"""
+ """
+ 标记插件已安装。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 更新后的安装标记
+ """
return await FakePluginService.mark_plugin_installed_services(self.session, discovered_plugin)
async def commit(self) -> None:
@@ -239,24 +317,39 @@ async def commit(self) -> None:
await self.session.commit()
class NoFatInstallGateway(FakePluginRuntimeGateway):
- """
- 禁止安装流程读取 fat state gateway 的测试适配器。
- """
+ """禁止安装流程读取 fat state gateway 的测试适配器。"""
def get_async_session_local(self) -> object:
- """禁止通过 state gateway 打开数据库会话。"""
+ """
+ 禁止通过 state gateway 打开数据库会话。
+
+ :raises AssertionError: 安装流程不应通过 state gateway 打开数据库会话
+ """
raise AssertionError('安装流程不应通过 state gateway 打开数据库会话')
def get_plugin_service(self) -> object:
- """禁止通过 state gateway 获取管理服务。"""
+ """
+ 禁止通过 state gateway 获取管理服务。
+
+ :raises AssertionError: 安装流程不应通过 state gateway 获取管理服务
+ """
raise AssertionError('安装流程不应通过 state gateway 获取管理服务')
def open_lifecycle_unit_of_work(self) -> InstallLifecycleUnitOfWork:
- """打开测试生命周期 UoW。"""
+ """
+ 打开测试生命周期 UoW。
+
+ :return: ``InstallLifecycleUnitOfWork`` 实例
+ """
return InstallLifecycleUnitOfWork(self)
async def run_plugin_migrations(self, discovered_plugin: object) -> list[object]:
- """通过独立 migration session 执行插件 migration。"""
+ """
+ 通过独立 migration session 执行插件 migration。
+
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 独立迁移会话的执行结果
+ """
async with self.session_local() as migration_session:
return await PluginMigrationRunner(
discovered_plugin,
@@ -504,16 +597,22 @@ def test_plugin_runtime_lifecycle_precheck_uses_migration_history_gateway(tmp_pa
(plugin_root / 'migrations' / '001_demo.sql').write_text('select 1;\n', encoding='utf-8')
class NoFatStateGateway(FakePluginRuntimeGateway):
- """
- 禁止生命周期预检读取 fat state gateway 的测试适配器。
- """
+ """禁止生命周期预检读取 fat state gateway 的测试适配器。"""
def get_async_session_local(self) -> object:
- """禁止通过 state gateway 打开数据库会话。"""
+ """
+ 禁止通过 state gateway 打开数据库会话。
+
+ :raises AssertionError: 生命周期脚本预检不应通过 state gateway 打开数据库会话
+ """
raise AssertionError('生命周期脚本预检不应通过 state gateway 打开数据库会话')
def get_plugin_service(self) -> object:
- """禁止通过 state gateway 获取管理服务。"""
+ """
+ 禁止通过 state gateway 获取管理服务。
+
+ :raises AssertionError: 生命周期脚本预检不应通过 state gateway 获取管理服务
+ """
raise AssertionError('生命周期脚本预检不应通过 state gateway 获取管理服务')
gateway = NoFatStateGateway()
@@ -833,7 +932,16 @@ async def fail_add_plugin_operation_log_services(
dry_run: bool,
continue_on_error: bool,
) -> None:
- """模拟管理服务审计日志写入失败。"""
+ """
+ 模拟管理服务审计日志写入失败。
+
+ :param cls: 调用类方法时使用的类对象
+ :param query_db: 当前操作使用的异步数据库会话
+ :param payload: 随调用传入或返回的结构化数据
+ :param dry_run: 是否只预览操作结果
+ :param continue_on_error: 单项操作失败后是否继续执行
+ :raises RuntimeError: 模拟写入插件操作日志失败
+ """
raise RuntimeError('audit failed')
gateway = FakePluginRuntimeGateway()
@@ -1091,16 +1199,22 @@ def test_plugin_runtime_diagnose_plugin_uses_audit_gateway_for_snapshot(tmp_path
]
class NoFatStateGateway(FakePluginRuntimeGateway):
- """
- 禁止诊断审计快照读取 fat state gateway 的测试适配器。
- """
+ """禁止诊断审计快照读取 fat state gateway 的测试适配器。"""
def get_async_session_local(self) -> object:
- """禁止通过 state gateway 打开数据库会话。"""
+ """
+ 禁止通过 state gateway 打开数据库会话。
+
+ :raises AssertionError: 诊断审计快照不应通过 state gateway 打开数据库会话
+ """
raise AssertionError('诊断审计快照不应通过 state gateway 打开数据库会话')
def get_plugin_service(self) -> object:
- """禁止通过 state gateway 获取管理服务。"""
+ """
+ 禁止通过 state gateway 获取管理服务。
+
+ :raises AssertionError: 诊断审计快照不应通过 state gateway 获取管理服务
+ """
raise AssertionError('诊断审计快照不应通过 state gateway 获取管理服务')
result = asyncio.run(build_runtime_with_gateway(backend_root, NoFatStateGateway()).diagnose_plugin('demo'))
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_lifecycle_lock.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_lifecycle_lock.py
index ab0c33b4a..c9c8694e0 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_lifecycle_lock.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_lifecycle_lock.py
@@ -17,6 +17,8 @@
class DeniedLifecycleLock:
"""
测试用拒绝插件生命周期锁。
+
+ :ivar calls: 测试替身记录的调用信息
"""
def __init__(self) -> None:
@@ -25,19 +27,30 @@ def __init__(self) -> None:
@asynccontextmanager
async def lock(self, plugin_id: str, operation: str) -> AsyncGenerator[PluginLifecycleLockResult, None]:
- """返回未获取锁结果。"""
+ """
+ 返回未获取锁结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param operation: 当前处理的操作
+ :yield: 未获取锁结果
+ """
self.calls.append((plugin_id, operation))
yield PluginLifecycleLockResult(acquired=False, message='插件正在操作中')
class FailingLifecycleLock:
- """
- 测试用失败插件生命周期锁。
- """
+ """测试用失败插件生命周期锁。"""
@asynccontextmanager
async def lock(self, plugin_id: str, operation: str) -> AsyncGenerator[PluginLifecycleLockResult, None]:
- """不应被调用的锁。"""
+ """
+ 不应被调用的锁。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param operation: 当前处理的操作
+ :raises AssertionError: dry_run 不应获取生命周期锁
+ :yield: ``PluginLifecycleLockResult`` 实例
+ """
raise AssertionError('dry_run 不应获取生命周期锁')
yield PluginLifecycleLockResult(acquired=True)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_lifecycle_runner.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_lifecycle_runner.py
index 72992ce4e..398305f6f 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_lifecycle_runner.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_lifecycle_runner.py
@@ -14,12 +14,20 @@ async def test_lifecycle_step_runner_runs_steps_in_order() -> None:
calls = []
async def first(context: dict[str, object]) -> None:
- """记录第一个生命周期步骤执行。"""
+ """
+ 记录第一个生命周期步骤执行。
+
+ :param context: 当前操作所需的上下文
+ """
context['first'] = True
calls.append('first')
async def second(context: dict[str, object]) -> None:
- """记录第二个生命周期步骤执行。"""
+ """
+ 记录第二个生命周期步骤执行。
+
+ :param context: 当前操作所需的上下文
+ """
context['second'] = bool(context['first'])
calls.append('second')
@@ -38,12 +46,21 @@ async def test_lifecycle_step_runner_stops_when_step_returns_payload() -> None:
calls = []
async def stop(context: dict[str, object]) -> dict[str, object]:
- """返回负载并终止后续生命周期步骤。"""
+ """
+ 返回负载并终止后续生命周期步骤。
+
+ :param context: 当前操作所需的上下文
+ :return: 负载并终止后续生命周期步骤
+ """
calls.append('stop')
return {'ok': False, 'message': 'blocked'}
async def skipped(context: dict[str, object]) -> None:
- """标记不应执行的后续生命周期步骤。"""
+ """
+ 标记不应执行的后续生命周期步骤。
+
+ :param context: 当前操作所需的上下文
+ """
calls.append('skipped')
result = await PluginLifecycleStepRunner(
@@ -60,7 +77,12 @@ async def test_lifecycle_step_runner_records_failed_step() -> None:
"""校验生命周期步骤异常时记录失败步骤。"""
async def broken(context: dict[str, object]) -> None:
- """抛出测试用生命周期步骤异常。"""
+ """
+ 抛出测试用生命周期步骤异常。
+
+ :param context: 当前操作所需的上下文
+ :raises RuntimeError: 模拟生命周期步骤执行失败
+ """
raise RuntimeError('broken step')
with pytest.raises(PluginLifecycleStepFailed) as exc_info:
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_upgrade_enable_purge.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_upgrade_enable_purge.py
index 92443e84c..248b7489c 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_upgrade_enable_purge.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_upgrade_enable_purge.py
@@ -21,6 +21,10 @@
class MigrationOnlyGateway:
"""
仅提供插件 migration 历史能力的测试网关。
+
+ :ivar records: 当前测试保存的记录
+ :ivar list_calls: 记录 ``list`` 的调用情况
+ :ivar mark_calls: 记录 ``mark`` 的调用情况
"""
def __init__(self) -> None:
@@ -59,7 +63,13 @@ def __init__(self) -> None:
self.mark_calls: list[tuple[str, str, str, str | None]] = []
async def list_plugin_migrations(self, plugin_id: str, status: str | None = None) -> list[object]:
- """查询测试 migration 历史。"""
+ """
+ 查询测试 migration 历史。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param status: 操作或记录所处的状态
+ :return: 测试 migration 历史
+ """
self.list_calls.append((plugin_id, status))
return [
record
@@ -68,7 +78,13 @@ async def list_plugin_migrations(self, plugin_id: str, status: str | None = None
]
async def get_plugin_migration(self, plugin_id: str, migration_path: str) -> object | None:
- """获取测试 migration 历史。"""
+ """
+ 获取测试 migration 历史。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :return: 测试 migration 历史
+ """
for record in reversed(self.records):
if record.plugin_id == plugin_id and record.migration_path == migration_path:
return record
@@ -81,7 +97,15 @@ async def mark_plugin_migration_status(
status: str,
error_message: str | None = None,
) -> object | None:
- """标记测试 migration 历史状态。"""
+ """
+ 标记测试 migration 历史状态。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :param status: 操作或记录所处的状态
+ :param error_message: 记录到结果或审计日志中的错误详情
+ :return: 当前操作使用的记录
+ """
self.mark_calls.append((plugin_id, migration_path, status, error_message))
record = await self.get_plugin_migration(plugin_id, migration_path)
if record:
@@ -90,7 +114,11 @@ async def mark_plugin_migration_status(
return record
def get_plugin_service(self) -> object:
- """禁止 migration 链路回退到管理服务胖接口。"""
+ """
+ 禁止 migration 链路回退到管理服务胖接口。
+
+ :raises AssertionError: migration 历史不应依赖 PluginManagementServiceProtocol
+ """
raise AssertionError('migration 历史不应依赖 PluginManagementServiceProtocol')
@@ -742,6 +770,8 @@ def test_plugin_runtime_set_plugin_enabled_uses_lifecycle_state_gateway_without_
class NoFatLifecycleStateGateway(FakePluginRuntimeGateway):
"""
禁止启用流程读取 fat state gateway 的测试适配器。
+
+ :ivar enabled_state_calls: 记录 ``enabled_state`` 的调用情况
"""
def __init__(self) -> None:
@@ -750,11 +780,19 @@ def __init__(self) -> None:
self.enabled_state_calls: list[tuple[str, bool, object | None]] = []
def get_async_session_local(self) -> object:
- """禁止通过 state gateway 打开数据库会话。"""
+ """
+ 禁止通过 state gateway 打开数据库会话。
+
+ :raises AssertionError: 启用流程不应通过 state gateway 打开数据库会话
+ """
raise AssertionError('启用流程不应通过 state gateway 打开数据库会话')
def get_plugin_service(self) -> object:
- """禁止通过 state gateway 获取管理服务。"""
+ """
+ 禁止通过 state gateway 获取管理服务。
+
+ :raises AssertionError: 启用流程不应通过 state gateway 获取管理服务
+ """
raise AssertionError('启用流程不应通过 state gateway 获取管理服务')
async def set_plugin_enabled_state(
@@ -763,7 +801,14 @@ async def set_plugin_enabled_state(
enabled: bool,
discovered_plugin: object | None = None,
) -> object:
- """通过窄端口更新插件启停状态。"""
+ """
+ 通过窄端口更新插件启停状态。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param enabled: 是否启用该项功能
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :return: 当前调用产生的响应
+ """
self.enabled_state_calls.append((plugin_id, enabled, discovered_plugin))
async with self.session_local() as session:
response = await FakePluginService.update_plugin_enabled_services(
@@ -811,7 +856,15 @@ async def raise_enable_failure(
enabled: bool,
discovered_plugin: object | None = None,
) -> object:
- """模拟启用插件失败。"""
+ """
+ 模拟启用插件失败。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param enabled: 是否启用该项功能
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :raises RuntimeError: 模拟写入启用状态失败
+ """
raise RuntimeError('enable update failed')
original_update_enabled = FakePluginService.update_plugin_enabled_services
@@ -1093,7 +1146,15 @@ async def raise_disable_failure(
enabled: bool,
discovered_plugin: object | None = None,
) -> object:
- """模拟禁用插件失败。"""
+ """
+ 模拟禁用插件失败。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param enabled: 是否启用该项功能
+ :param discovered_plugin: 扫描插件目录后得到的插件描述
+ :raises RuntimeError: 模拟写入停用状态失败
+ """
raise RuntimeError('disable update failed')
original_update_enabled = FakePluginService.update_plugin_enabled_services
@@ -1237,7 +1298,13 @@ def test_plugin_runtime_uninstall_plugin_reports_failed_lifecycle_step(tmp_path:
gateway = FakePluginRuntimeGateway()
async def raise_uninstall_failure(query_db: object, plugin_id: str) -> object:
- """模拟卸载插件失败。"""
+ """
+ 模拟卸载插件失败。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :raises RuntimeError: 模拟写入卸载状态失败
+ """
raise RuntimeError('uninstall update failed')
original_mark_uninstalled = FakePluginService.mark_plugin_uninstalled_services
@@ -1539,16 +1606,22 @@ def test_plugin_runtime_purge_plugin_uses_lifecycle_uow_without_fat_service(tmp_
)
class NoFatPurgeGateway(FakePluginRuntimeGateway):
- """
- 禁止物理清理流程读取 fat state gateway 的测试适配器。
- """
+ """禁止物理清理流程读取 fat state gateway 的测试适配器。"""
def get_async_session_local(self) -> object:
- """禁止通过 state gateway 打开数据库会话。"""
+ """
+ 禁止通过 state gateway 打开数据库会话。
+
+ :raises AssertionError: 物理清理流程不应通过 state gateway 打开数据库会话
+ """
raise AssertionError('物理清理流程不应通过 state gateway 打开数据库会话')
def get_plugin_service(self) -> object:
- """禁止通过 state gateway 获取管理服务。"""
+ """
+ 禁止通过 state gateway 获取管理服务。
+
+ :raises AssertionError: 物理清理流程不应通过 state gateway 获取管理服务
+ """
raise AssertionError('物理清理流程不应通过 state gateway 获取管理服务')
gateway = NoFatPurgeGateway()
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/support/test_dependency_payloads.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/support/test_dependency_payloads.py
index 6ee12b678..c6c386711 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/support/test_dependency_payloads.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/support/test_dependency_payloads.py
@@ -13,7 +13,15 @@ def build_npm_plan_item(
requirement: str,
name: str,
) -> DependencyInstallPlanItem:
- """构造测试用 npm 依赖安装计划项。"""
+ """
+ 构造测试用 npm 依赖安装计划项。
+
+ :param workdir: 命令执行时使用的工作目录
+ :param kind: 当前条目的类别
+ :param requirement: 依赖声明,包括包名和版本约束
+ :param name: 用于查找或标识当前对象的名称
+ :return: 测试用 npm 依赖安装计划项
+ """
command = ['npm', 'install']
if kind == 'npmDev':
command.append('--save-dev')
@@ -123,7 +131,7 @@ def test_npm_package_json_synchronizer_uses_star_without_version(tmp_path: Path)
def test_pnpm_keeps_manifest_and_lockfile_in_sync(tmp_path: Path) -> None:
- """pnpm 安装后不回写单个 manifest,保留与锁文件匹配的实际保存约束。"""
+ """验证 pnpm 安装后不回写单个 manifest,保留与锁文件匹配的实际保存约束。"""
package_json_path = tmp_path / 'package.json'
package_content = '{"dependencies":{"plain-npm":"1.2.3"}}\n'
package_json_path.write_text(package_content, encoding='utf-8')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_application.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_application.py
index aebea953e..379959a4c 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_application.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_application.py
@@ -26,26 +26,49 @@
class FakeRedis:
"""
测试用 Redis。
+
+ :ivar values: 当前处理的值集合
+ :ivar deleted_keys: 从模拟缓存中删除的键
+ :ivar expires: 记录的到期时间
"""
def __init__(self, values: dict[str, str] | None = None) -> None:
- """初始化测试 Redis。"""
+ """
+ 初始化测试 Redis。
+
+ :param values: 当前处理的值集合
+ """
self.values = values or {}
self.deleted_keys: list[str] = []
self.expires: dict[str, int] = {}
async def get(self, key: str) -> str | None:
- """获取 Redis 值。"""
+ """
+ 获取 Redis 值。
+
+ :param key: 查找数据时使用的键
+ :return: Redis 值
+ """
return self.values.get(key)
async def set(self, key: str, value: str, ex: int | None = None) -> None:
- """写入 Redis 值。"""
+ """
+ 写入 Redis 值。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :param ex: 捕获到的异常实例
+ """
self.values[key] = value
if ex is not None:
self.expires[key] = ex
async def delete(self, key: str) -> None:
- """删除 Redis key。"""
+ """
+ 删除 Redis key。
+
+ :param key: 查找数据时使用的键
+ """
self.deleted_keys.append(key)
self.values.pop(key, None)
@@ -53,22 +76,40 @@ async def delete(self, key: str) -> None:
class FakeLifecycleLock:
"""
测试用插件生命周期锁。
+
+ :ivar acquired: 是否成功取得锁或租约
+ :ivar calls: 测试替身记录的调用信息
"""
def __init__(self, *, acquired: bool) -> None:
- """初始化测试锁。"""
+ """
+ 初始化测试锁。
+
+ :param acquired: 是否成功取得锁或租约
+ """
self.acquired = acquired
self.calls: list[tuple[str, str]] = []
@asynccontextmanager
async def lock(self, plugin_id: str, operation: str) -> AsyncGenerator[PluginLifecycleLockResult, None]:
- """返回预设锁结果。"""
+ """
+ 返回预设锁结果。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param operation: 当前处理的操作
+ :yield: 预设锁结果
+ """
self.calls.append((plugin_id, operation))
yield PluginLifecycleLockResult(acquired=self.acquired)
def build_app(redis: FakeRedis) -> FastAPI:
- """构建测试 FastAPI app。"""
+ """
+ 构建测试 FastAPI app。
+
+ :param redis: 测试用 Redis
+ :return: 测试 FastAPI app
+ """
app = FastAPI()
app.state.redis = redis
return app
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_asgi.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_asgi.py
index 03b41e607..2f27bfafa 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_asgi.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_asgi.py
@@ -15,17 +15,24 @@
@pytest.mark.asyncio
async def test_mounted_app_lifespan_state_root_path_and_shutdown(tmp_path: Path) -> None:
+ """挂载应用保留生命周期状态、根路径和关闭处理。"""
events = []
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[dict[str, str], None]:
+ """
+ 记录下游应用的启动和关闭过程。
+
+ :param app: 正在配置或处理请求的 ASGI 应用
+ :yield: 包含 ``resource`` 的数据
+ """
events.append('start')
yield {'resource': 'ready'}
events.append('stop')
child = FastAPI(lifespan=lifespan)
- @child.get('/api/state')
+ @child.get('/api/state', summary='查询插件应用状态', description='返回插件应用的资源状态、标识及挂载信息。')
async def state(request: Request) -> dict[str, str]:
return {
'resource': request.state.resource,
@@ -34,6 +41,12 @@ async def state(request: Request) -> dict[str, str]:
}
async def authorize(scope: Scope) -> PluginRequestContext:
+ """
+ 创建测试使用的 ``PluginRequestContext`` 实例。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :return: 测试使用的 ``PluginRequestContext`` 实例
+ """
return PluginRequestContext(PluginHostContext('demo', tmp_path), user=None)
manager = PluginLifespanManager(child)
@@ -54,12 +67,26 @@ async def authorize(scope: Scope) -> PluginRequestContext:
@pytest.mark.asyncio
@pytest.mark.parametrize('failure', [PermissionError, LookupError])
async def test_gateway_rejects_http_and_websocket_without_invoking_plugin(failure: type[Exception]) -> None:
+ """网关拒绝 HTTP 或 WebSocket 后不调用插件。"""
reached = []
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟接收宿主消息的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
reached.append(scope)
async def authorize(scope: Scope) -> PluginRequestContext:
+ """
+ 模拟此操作抛出 failure 的情形。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :raises Exception: 底层操作失败时向调用方传播异常
+ """
raise failure()
manager = PluginLifespanManager(child, managed=False)
@@ -71,6 +98,11 @@ async def authorize(scope: Scope) -> PluginRequestContext:
messages = []
async def send(message: Message) -> None:
+ """
+ 收集应用发送的 ASGI 消息。
+
+ :param message: 与当前结果一起返回的说明
+ """
messages.append(message)
await gateway({'type': 'websocket', 'path': '/ws'}, None, send)
@@ -80,9 +112,17 @@ async def send(message: Message) -> None:
@pytest.mark.asyncio
async def test_failed_or_unsupported_lifespan_cleans_up() -> None:
+ """生命周期失败或不受支持时清理资源。"""
stopped = asyncio.Event()
async def failed(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟子应用未完成其生命周期操作。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
try:
await receive()
await send({'type': 'lifespan.startup.failed', 'message': 'broken resource'})
@@ -97,6 +137,13 @@ async def failed(scope: Scope, receive: Receive, send: Send) -> None:
assert not manager.started
async def unsupported(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟直接结束的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
return
with pytest.raises(RuntimeError, match='确认前退出'):
@@ -105,9 +152,17 @@ async def unsupported(scope: Scope, receive: Receive, send: Send) -> None:
@pytest.mark.asyncio
async def test_lifespan_timeout_cancels_task() -> None:
+ """生命周期超时后取消任务。"""
stopped = asyncio.Event()
async def hangs(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 保持异步任务等待以触发超时处理。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
try:
await asyncio.Event().wait()
finally:
@@ -127,6 +182,13 @@ async def test_lifespan_timeout_is_bounded_and_retry_uses_fresh_protocol_state(p
attempts = []
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟接收宿主消息的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
attempts.append(scope['state'])
await receive()
if len(attempts) > 1:
@@ -172,7 +234,17 @@ async def child(scope: Scope, receive: Receive, send: Send) -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('phase', ['startup', 'shutdown'])
async def test_lifespan_self_cancellation_is_protocol_error(phase: str) -> None:
+ """生命周期主动取消被识别为协议错误。"""
+
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟接收宿主消息的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ :raises asyncio.CancelledError: 异步操作被取消时
+ """
await receive()
if phase == 'shutdown':
await send({'type': 'lifespan.startup.complete'})
@@ -190,13 +262,30 @@ async def child(scope: Scope, receive: Receive, send: Send) -> None:
@pytest.mark.asyncio
async def test_lifespan_accepts_callable_returning_future() -> None:
+ """生命周期接受返回 Future 的可调用对象。"""
+
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟接收宿主消息的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
await receive()
await send({'type': 'lifespan.startup.complete'})
await receive()
await send({'type': 'lifespan.shutdown.complete'})
def app(scope: Scope, receive: Receive, send: Send) -> asyncio.Future[None]:
+ """
+ 将测试请求交给下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ :return: 运行下游 ASGI 应用的异步任务
+ """
return asyncio.create_task(child(scope, receive, send))
manager = PluginLifespanManager(app)
@@ -208,9 +297,17 @@ def app(scope: Scope, receive: Receive, send: Send) -> asyncio.Future[None]:
@pytest.mark.asyncio
async def test_host_cancellation_propagates_and_releases_lifespan_task() -> None:
+ """宿主取消时传播取消信号并释放生命周期任务。"""
opened, stopped = asyncio.Event(), asyncio.Event()
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟接收宿主消息的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
opened.set()
try:
await asyncio.Event().wait()
@@ -228,6 +325,7 @@ async def child(scope: Scope, receive: Receive, send: Send) -> None:
@pytest.mark.parametrize('timeout', [0, -1, float('inf'), float('nan')])
def test_lifespan_rejects_invalid_time_limits(timeout: float) -> None:
+ """生命周期拒绝无效的时间限制。"""
with pytest.raises(ValueError, match='大于零'):
PluginLifespanManager(None, timeout=timeout)
with pytest.raises(ValueError, match='大于零'):
@@ -236,10 +334,18 @@ def test_lifespan_rejects_invalid_time_limits(timeout: float) -> None:
@pytest.mark.asyncio
async def test_concurrent_shutdown_waits_for_startup_and_sends_one_shutdown() -> None:
+ """并发关闭等待启动完成并只发送一次关闭事件。"""
opened, release = asyncio.Event(), asyncio.Event()
messages = []
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟接收宿主消息的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
messages.append((await receive())['type'])
opened.set()
await release.wait()
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_browser_session.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_browser_session.py
index 31f007c5a..06f175693 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_browser_session.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_browser_session.py
@@ -28,25 +28,46 @@
from module_admin.service.login_service import LoginService, oauth2_scheme
from module_plugin.controller.plugin_browser_controller import plugin_browser_controller
from plugins.core.discovery.registry import RegisteredPlugin
-from plugins.core.discovery.scanner import PluginScanner
+from plugins.core.discovery.scanner import DiscoveredPlugin, PluginScanner
from plugins.core.runtime.browser_session import COOKIE_NAME_PREFIX, SESSION_KEY_PREFIX
from plugins.core.runtime.explicit import ExplicitPluginRuntime
from utils.jwt_util import JwtUtil
class MemoryRedis:
- """实现本协议使用的原子 NX/expire,并允许明确模拟到期。"""
+ """
+ 实现本协议使用的原子 NX/expire,并允许明确模拟到期。
+
+ :ivar values: 当前处理的值集合
+ :ivar deadlines: 各操作的截止时间
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``values``, ``deadlines``。"""
self.values: dict[str, str] = {}
self.deadlines: dict[str, float] = {}
async def get(self, key: str) -> str | None:
+ """
+ 读取测试存储中的指定键。
+
+ :param key: 查找数据时使用的键
+ :return: 测试存储中的指定键
+ """
if self.deadlines.get(key, float('inf')) <= time.time():
self.values.pop(key, None)
return self.values.get(key)
async def set(self, key: str, value: str, *, ex: int = 300, nx: bool = False) -> bool:
+ """
+ 写入测试缓存键并设置过期时间。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :param ex: 捕获到的异常实例
+ :param nx: 是否只在键尚不存在时写入
+ :return: 是否写入测试缓存键并设置过期时间
+ """
if nx and await self.get(key) is not None:
return False
self.values[key] = value
@@ -54,6 +75,13 @@ async def set(self, key: str, value: str, *, ex: int = 300, nx: bool = False) ->
return True
async def expire(self, key: str, seconds: int) -> bool:
+ """
+ 为测试缓存键设置过期时间。
+
+ :param key: 查找数据时使用的键
+ :param seconds: 以秒计的时间值
+ :return: 是否为测试缓存键设置过期时间
+ """
if await self.get(key) is None:
return False
self.deadlines[key] = time.time() + seconds
@@ -80,8 +108,13 @@ async def echo(request: Request):
"""
-@pytest_asyncio.fixture
-async def browser(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[SimpleNamespace]:
+def _write_browser_plugin(tmp_path: Path) -> DiscoveredPlugin:
+ """
+ 写入测试插件的前端资源和清单,并返回扫描结果。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :return: 扫描结果
+ """
directory = tmp_path / 'plugins' / 'browser_test'
(directory / 'web' / 'dist' / 'assets').mkdir(parents=True)
(directory / 'web' / 'dist' / 'index.html').write_text('Bundle')
@@ -101,7 +134,19 @@ async def browser(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncItera
'permissions': ['browser_test:view'],
}
(directory / 'plugin.yaml').write_text(yaml.safe_dump(data))
- plugin = PluginScanner(directory.parent).load_manifest(directory / 'plugin.yaml')
+ return PluginScanner(directory.parent).load_manifest(directory / 'plugin.yaml')
+
+
+@pytest_asyncio.fixture
+async def browser(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[SimpleNamespace]:
+ """
+ 装配可通过浏览器访问的测试插件。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :yield: ``SimpleNamespace`` 实例
+ """
+ plugin = _write_browser_plugin(tmp_path)
app = FastAPI()
app.state.redis = redis = MemoryRedis()
runtime = ExplicitPluginRuntime(SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True)))
@@ -115,15 +160,32 @@ async def browser(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncItera
monkeypatch.setattr(TransportCryptoConfig, 'transport_crypto_enabled', False)
async def current_user(token_value: str = Depends(oauth2_scheme)) -> object:
+ """
+ 在令牌匹配时提供测试用户。
+
+ :param token_value: 测试令牌的实际值
+ :raises HTTPException: 模拟请求未获得身份认证
+ :return: 当前操作对应的用户
+ """
if token_value != token:
raise HTTPException(status_code=401)
return user
async def session_dependency() -> AsyncIterator[object]:
+ """
+ 为当前请求提供测试数据库会话。
+
+ :yield: 当前请求借用的测试数据库会话
+ """
yield object()
@asynccontextmanager
async def session() -> AsyncGenerator[object, None]:
+ """
+ 为当前测试操作提供数据库会话。
+
+ :yield: 数据库会话
+ """
yield object()
app.dependency_overrides[LoginService.get_current_user] = current_user
@@ -134,7 +196,7 @@ async def session() -> AsyncGenerator[object, None]:
monkeypatch.setattr('plugins.core.runtime.explicit.DataSourceRegistry.session', session)
app.include_router(plugin_browser_controller)
- @app.get('/system/private')
+ @app.get('/system/private', summary='检查宿主私有端点', description='检查请求携带的令牌并返回认证状态。')
async def private(token_value: Annotated[str, Depends(oauth2_scheme)]) -> dict:
return {'authenticated': bool(token_value)}
@@ -165,6 +227,12 @@ async def private(token_value: Annotated[str, Depends(oauth2_scheme)]) -> dict:
async def issue(browser: SimpleNamespace) -> httpx.Response:
+ """
+ 通过插件接口申请测试浏览器会话。
+
+ :param browser: 执行页面操作的浏览器实例
+ :return: 插件浏览器会话的签发响应
+ """
return await browser.client.post(
'/plugin/runtime/browser_test/session',
headers={
@@ -216,6 +284,7 @@ async def test_plugin_session_error_status_and_language(browser: SimpleNamespace
@pytest.mark.asyncio
async def test_issued_cookie_loads_ui_and_api_but_never_host_api(browser: SimpleNamespace) -> None:
+ """签发的 Cookie 可访问插件界面和接口且不能访问宿主接口。"""
client = browser.client
assert (await client.get('/apps/browser_test/ui/')).status_code == status.HTTP_401_UNAUTHORIZED
response = await issue(browser)
@@ -245,6 +314,7 @@ async def test_issued_cookie_loads_ui_and_api_but_never_host_api(browser: Simple
@pytest.mark.asyncio
async def test_multitab_renewal_reuses_cookie_and_csrf(browser: SimpleNamespace) -> None:
+ """多标签页续期复用 Cookie 和 CSRF 令牌。"""
first, second = await asyncio.gather(issue(browser), issue(browser))
assert first.json()['data']['csrfToken'] == second.json()['data']['csrfToken']
assert first.cookies == second.cookies
@@ -253,6 +323,7 @@ async def test_multitab_renewal_reuses_cookie_and_csrf(browser: SimpleNamespace)
@pytest.mark.asyncio
async def test_cookie_writes_require_origin_and_csrf(browser: SimpleNamespace) -> None:
+ """写入 Cookie 需要验证来源和 CSRF。"""
response = await issue(browser)
csrf = response.json()['data']['csrfToken']
for headers in (
@@ -272,6 +343,7 @@ async def test_cookie_writes_require_origin_and_csrf(browser: SimpleNamespace) -
@pytest.mark.asyncio
@pytest.mark.parametrize('reason', ['logout', 'replaced', 'expired', 'disabled', 'permission', 'version', 'nonce'])
async def test_session_fails_closed_after_binding_or_access_changes(browser: SimpleNamespace, reason: str) -> None:
+ """绑定或访问权限变化后拒绝已有会话。"""
await issue(browser)
key = next(key for key in browser.redis.values if key.startswith(SESSION_KEY_PREFIX))
if reason == 'logout':
@@ -298,6 +370,7 @@ async def test_session_fails_closed_after_binding_or_access_changes(browser: Sim
@pytest.mark.asyncio
async def test_cross_origin_issuance_and_unknown_plugin_rejected(browser: SimpleNamespace) -> None:
+ """拒绝跨域签发和未知插件。"""
headers = {'Authorization': f'Bearer {browser.token}', 'Origin': 'https://evil.test'}
assert (
await browser.client.post('/plugin/runtime/browser_test/session', headers=headers)
@@ -312,6 +385,7 @@ async def test_cross_origin_issuance_and_unknown_plugin_rejected(browser: Simple
async def test_required_encryption_bypasses_only_readonly_registered_ui(
browser: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """强制加密时仅放行已注册的只读界面。"""
await issue(browser)
monkeypatch.setattr(TransportCryptoConfig, 'transport_crypto_enabled', True)
monkeypatch.setattr(TransportCryptoConfig, 'transport_crypto_mode', 'required')
@@ -338,6 +412,7 @@ async def test_required_encryption_bypasses_only_readonly_registered_ui(
async def test_renewal_retries_if_record_expires_and_another_tab_replaces_it(
browser: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """记录过期且被其他标签页替换后重试续期。"""
first = await issue(browser)
key = next(key for key in browser.redis.values if key.startswith(SESSION_KEY_PREFIX))
replacement = json.loads(browser.redis.values[key])
@@ -346,6 +421,13 @@ async def test_renewal_retries_if_record_expires_and_another_tab_replaces_it(
replaced = False
async def replace_before_expire(record_key: str, seconds: int) -> bool:
+ """
+ 在设置有效期前替换缓存值。
+
+ :param record_key: 定位目标记录的键
+ :param seconds: 以秒计的时间值
+ :return: 是否在设置有效期前替换缓存值
+ """
nonlocal replaced
if not replaced:
replaced = True
@@ -370,6 +452,7 @@ async def replace_before_expire(record_key: str, seconds: int) -> bool:
async def test_real_plugin_login_resolution_does_not_refresh_or_restore_main_session(
monkeypatch: pytest.MonkeyPatch, same_time_login: bool, logout_after_read: bool
) -> None:
+ """解析真实插件登录时不刷新或恢复主会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
redis = MemoryRedis()
app = FastAPI()
@@ -384,6 +467,12 @@ async def test_real_plugin_login_resolution_does_not_refresh_or_restore_main_ses
original_get = redis.get
async def get_with_concurrent_logout(record_key: str) -> str | None:
+ """
+ 模拟读取浏览器会话期间发生注销。
+
+ :param record_key: 定位目标记录的键
+ :return: 待处理的输入值
+ """
value = await original_get(record_key)
if record_key == key and logout_after_read:
redis.values.pop(key, None)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle.py
index 9c3e80379..cc80365f2 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle.py
@@ -20,6 +20,12 @@
@pytest.fixture
def bundle_root(tmp_path: Path) -> Path:
+ """
+ 准备包含静态资源及空目录的插件前端目录。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :return: 路径解析的基准目录
+ """
root = tmp_path / 'web' / 'dist'
(root / 'assets').mkdir(parents=True)
(root / 'empty').mkdir()
@@ -36,9 +42,16 @@ def bundle_root(tmp_path: Path) -> Path:
def _mount_bundle(plugin_root: Path, *, spa_fallback: bool = True) -> FastAPI:
+ """
+ 将插件前端资源包挂载到测试应用。
+
+ :param plugin_root: 插件的根目录
+ :param spa_fallback: 找不到静态资源时是否返回单页应用入口
+ :return: 用于判断路径从属关系的父目录
+ """
child = FastAPI()
- @child.get('/api/ping')
+ @child.get('/api/ping', summary='探测插件后端', description='返回子应用标识,用于区分插件 API 与静态资源。')
async def ping() -> dict[str, str]:
return {'source': 'child-api'}
@@ -52,6 +65,7 @@ async def ping() -> dict[str, str]:
@pytest.mark.asyncio
async def test_entry_deep_link_and_head_have_safe_injected_proxy_configuration(bundle_root: Path) -> None:
+ """入口、深层链接及 HEAD 请求安全注入代理配置。"""
app = _mount_bundle(bundle_root.parents[1])
transport = httpx.ASGITransport(app=app, root_path='/gateway')
async with httpx.AsyncClient(transport=transport, base_url='https://test') as client:
@@ -83,6 +97,7 @@ async def test_entry_deep_link_and_head_have_safe_injected_proxy_configuration(b
@pytest.mark.asyncio
async def test_ui_redirect_retains_effective_mount_prefix_and_query(bundle_root: Path) -> None:
+ """界面重定向保留实际挂载前缀和查询参数。"""
transport = httpx.ASGITransport(app=_mount_bundle(bundle_root.parents[1]), root_path='/gateway')
async with httpx.AsyncClient(transport=transport, base_url='https://test') as client:
response = await client.get('/gateway/apps/demo/ui?view=reports%2Fmonthly')
@@ -98,6 +113,7 @@ async def test_ui_redirect_retains_effective_mount_prefix_and_query(bundle_root:
async def test_static_resources_have_explicit_mime_and_head_support(
bundle_root: Path, path: str, media_type: str
) -> None:
+ """静态资源声明 MIME 类型并支持 HEAD。"""
transport = httpx.ASGITransport(app=_mount_bundle(bundle_root.parents[1]))
async with httpx.AsyncClient(transport=transport, base_url='https://test') as client:
response = await client.get('/apps/demo/ui/' + path)
@@ -134,6 +150,7 @@ async def test_static_resources_have_explicit_mime_and_head_support(
],
)
async def test_missing_resources_directories_and_unsafe_paths_never_fall_back(bundle_root: Path, path: str) -> None:
+ """资源缺失、目录请求及不安全路径不会触发回退。"""
transport = httpx.ASGITransport(app=_mount_bundle(bundle_root.parents[1]))
async with httpx.AsyncClient(transport=transport, base_url='https://test') as client:
response = await client.get('/apps/demo/ui/' + path, headers=_HTML_HEADERS)
@@ -145,6 +162,7 @@ async def test_missing_resources_directories_and_unsafe_paths_never_fall_back(bu
@pytest.mark.asyncio
@pytest.mark.parametrize('accept', ['*/*', 'application/json', 'text/html;q=0', 'text/html;q=invalid'])
async def test_html_navigation_requires_explicit_acceptable_html(bundle_root: Path, accept: str) -> None:
+ """HTML 导航需要显式接受 HTML。"""
transport = httpx.ASGITransport(app=_mount_bundle(bundle_root.parents[1]))
async with httpx.AsyncClient(transport=transport, base_url='https://test') as client:
entry = await client.get('/apps/demo/ui/', headers={'Accept': accept})
@@ -155,6 +173,7 @@ async def test_html_navigation_requires_explicit_acceptable_html(bundle_root: Pa
@pytest.mark.asyncio
async def test_no_fallback_mode_and_unsupported_methods_do_not_return_html(bundle_root: Path) -> None:
+ """禁用回退或请求方法不受支持时不返回 HTML。"""
transport = httpx.ASGITransport(app=_mount_bundle(bundle_root.parents[1], spa_fallback=False))
async with httpx.AsyncClient(transport=transport, base_url='https://test') as client:
missing = await client.get('/apps/demo/ui/reports', headers=_HTML_HEADERS)
@@ -168,6 +187,7 @@ async def test_no_fallback_mode_and_unsupported_methods_do_not_return_html(bundl
@pytest.mark.asyncio
async def test_api_unknown_routes_and_non_http_scopes_are_delegated(bundle_root: Path) -> None:
+ """未知 API 路由和非 HTTP 作用域交给下游。"""
transport = httpx.ASGITransport(app=_mount_bundle(bundle_root.parents[1]))
async with httpx.AsyncClient(transport=transport, base_url='https://test') as client:
response = await client.get('/apps/demo/api/ping', headers=_HTML_HEADERS)
@@ -178,6 +198,13 @@ async def test_api_unknown_routes_and_non_http_scopes_are_delegated(bundle_root:
reached = []
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟接收宿主消息的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
reached.append(scope)
bundle = PluginBundleASGI(child, 'demo', bundle_root.parents[1], FrontendBundleManifest())
@@ -188,10 +215,25 @@ async def child(scope: Scope, receive: Receive, send: Send) -> None:
@pytest.mark.asyncio
async def test_outer_gateway_authentication_covers_ui_and_assets(bundle_root: Path) -> None:
+ """外层网关认证覆盖界面及静态资源。"""
+
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 若执行到此操作则立即使测试失败。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
pytest.fail('unauthorized request reached the child')
async def deny(scope: Scope) -> PluginRequestContext:
+ """
+ 模拟此操作抛出 LookupError 的情形。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :raises LookupError: 模拟无法解析已认证的会话
+ """
raise LookupError('unauthenticated')
manager = PluginLifespanManager(child, managed=False)
@@ -209,6 +251,7 @@ async def deny(scope: Scope) -> PluginRequestContext:
@pytest.mark.asyncio
async def test_symlink_escape_is_rejected_at_configuration_and_request_time(bundle_root: Path) -> None:
+ """在配置和请求阶段均拒绝通过符号链接越界。"""
outside = bundle_root.parents[1] / 'private.txt'
try:
(bundle_root / 'leak.txt').symlink_to(outside)
@@ -227,6 +270,7 @@ async def test_symlink_escape_is_rejected_at_configuration_and_request_time(bund
@pytest.mark.asyncio
async def test_configuration_json_cannot_close_script_and_has_no_request_secrets(bundle_root: Path) -> None:
+ """注入的配置 JSON 不能闭合脚本且不含请求密钥。"""
child = FastAPI()
bundle = PluginBundleASGI(
child, 'demo', bundle_root.parents[1], FrontendBundleManifest()
@@ -234,6 +278,11 @@ async def test_configuration_json_cannot_close_script_and_has_no_request_secrets
messages = []
async def send(message: Message) -> None:
+ """
+ 收集应用发送的 ASGI 消息。
+
+ :param message: 与当前结果一起返回的说明
+ """
messages.append(message)
scope = {
@@ -264,6 +313,7 @@ async def send(message: Message) -> None:
],
)
async def test_runtime_base_is_first_and_preserves_doctype(bundle_root: Path, html: str) -> None:
+ """运行时基址优先且保留文档类型声明。"""
(bundle_root / 'index.html').write_text(html, encoding='utf-8')
transport = httpx.ASGITransport(app=_mount_bundle(bundle_root.parents[1]))
async with httpx.AsyncClient(transport=transport, base_url='https://test') as client:
@@ -274,6 +324,7 @@ async def test_runtime_base_is_first_and_preserves_doctype(bundle_root: Path, ht
def test_missing_bundle_or_entry_is_rejected_before_activation(tmp_path: Path) -> None:
+ """激活前拒绝缺失的资源包或入口。"""
with pytest.raises(ValueError, match='目录不存在'):
PluginBundleASGI(FastAPI(), 'demo', tmp_path, FrontendBundleManifest())
(tmp_path / 'web' / 'dist').mkdir(parents=True)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_events.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_events.py
index ce786207e..e1171bf8e 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_events.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_events.py
@@ -35,7 +35,6 @@ async def send(message: dict) -> None:
保存实际 ASGI 响应片段并通知首条事件已到达。
:param message: ASGI 响应消息
- :return: None
"""
if message['type'] == 'http.response.body' and message.get('body'):
chunks.append(message['body'])
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_transport.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_transport.py
index 8086416c4..ab5eebfe8 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_transport.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_transport.py
@@ -18,20 +18,44 @@
def _encode(value: bytes) -> str:
+ """
+ 生成省略填充的 URL 安全 Base64 数据。
+
+ :param value: 待处理的输入值
+ :return: 省略填充的 URL 安全 Base64 数据
+ """
return base64.urlsafe_b64encode(value).decode().rstrip('=')
def _decode(value: str) -> bytes:
+ """
+ 解码省略填充的 URL 安全 Base64 数据。
+
+ :param value: 待处理的输入值
+ :return: 解码后的原始字节
+ """
return base64.urlsafe_b64decode(value + '=' * (-len(value) % 4))
def _json_bytes(value: object) -> bytes:
+ """
+ 将测试数据编码为紧凑的 UTF-8 JSON。
+
+ :param value: 待处理的输入值
+ :return: 紧凑 JSON 的 UTF-8 字节
+ """
return json.dumps(value, ensure_ascii=False, separators=(',', ':')).encode()
@pytest.fixture
def crypto(browser: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: # noqa: F811
- """只替换配置密钥和监控存储;保留真实解密、重放校验、Cookie 认证和加密响应。"""
+ """
+ 只替换配置密钥和监控存储;保留真实解密、重放校验、Cookie 认证和加密响应。
+
+ :param browser: 执行页面操作的浏览器实例
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :return: ``SimpleNamespace`` 实例
+ """
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
private_pem = private_key.private_bytes(
serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()
@@ -62,7 +86,15 @@ def crypto(browser: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> SimpleN
def _envelope(crypto: SimpleNamespace, method: str, path: str, payload: object) -> tuple[dict, bytes]:
- """按浏览器协议构造信封,每个请求使用独立 AES key、IV 和防重放 nonce。"""
+ """
+ 按浏览器协议构造信封,每个请求使用独立 AES key、IV 和防重放 nonce。
+
+ :param crypto: 测试传输加密使用的密钥和配置
+ :param method: 当前请求的 HTTP 方法
+ :param path: 要读取或处理的路径
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 加密信封及验证响应所需的密钥材料
+ """
aes_key = os.urandom(32)
iv = os.urandom(12)
aad = {'method': method, 'path': path}
@@ -83,6 +115,15 @@ def _envelope(crypto: SimpleNamespace, method: str, path: str, payload: object)
def _decrypt_response(response: httpx.Response, aes_key: bytes, *, method: str, path: str) -> dict:
+ """
+ 校验并解密测试响应的传输信封。
+
+ :param response: 当前调用产生的响应
+ :param aes_key: 请求协商出的AES会话密钥
+ :param method: 当前请求的 HTTP 方法
+ :param path: 要读取或处理的路径
+ :return: 解密并解析后的业务响应数据
+ """
assert response.headers['x-body-encrypted'] == '1', response.text
envelope = response.json()
expected_aad = {'method': method, 'path': path, 'direction': 'response'}
@@ -92,6 +133,19 @@ def _decrypt_response(response: httpx.Response, aes_key: bytes, *, method: str,
return json.loads(plaintext)
+def _assert_session_cookie(issued: httpx.Response, root_path: str) -> None:
+ """
+ 检查插件会话 Cookie 的作用路径和浏览器安全属性。
+
+ :param issued: 已签发的令牌或凭证
+ :param root_path: 应用或制品使用的根路径
+ """
+ cookies = issued.headers.get_list('set-cookie')
+ assert len(cookies) == 1
+ assert f'Path={root_path}/apps/browser_test/' in cookies[0]
+ assert all(attribute in cookies[0] for attribute in ('HttpOnly', 'Secure', 'SameSite=strict'))
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize('root_path', ['', '/prefix'])
async def test_encrypted_session_cookie_and_plugin_api_keep_outer_aad(
@@ -100,6 +154,7 @@ async def test_encrypted_session_cookie_and_plugin_api_keep_outer_aad(
monkeypatch: pytest.MonkeyPatch,
root_path: str,
) -> None:
+ """加密会话 Cookie 和插件接口保留外层关联数据。"""
monkeypatch.setattr(AppConfig, 'app_root_path', root_path)
transport = httpx.ASGITransport(app=browser.app, root_path=root_path)
async with httpx.AsyncClient(transport=transport, base_url='https://test') as client:
@@ -120,10 +175,7 @@ async def test_encrypted_session_cookie_and_plugin_api_keep_outer_aad(
assert data['apiBase'] == f'{root_path}/apps/browser_test/api/'
assert browser.token not in issued.text
assert issued.headers['cache-control'] == 'no-store'
- cookies = issued.headers.get_list('set-cookie')
- assert len(cookies) == 1
- assert f'Path={root_path}/apps/browser_test/' in cookies[0]
- assert all(attribute in cookies[0] for attribute in ('HttpOnly', 'Secure', 'SameSite=strict'))
+ _assert_session_cookie(issued, root_path)
info_path = '/apps/browser_test/api/info'
envelope, aes_key = _envelope(crypto, 'GET', info_path, {'query': '仅存在于密文'})
@@ -193,6 +245,7 @@ async def test_plugin_api_rejects_aad_without_its_full_namespace(
crypto: SimpleNamespace,
wrong_path: str,
) -> None:
+ """插件接口拒绝缺少完整命名空间的关联数据。"""
envelope, _ = _envelope(crypto, 'GET', wrong_path, {})
response = await browser.client.get(
'/apps/browser_test/api/info',
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_configuration.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_configuration.py
index 6ad8a0a57..976be294e 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_configuration.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_configuration.py
@@ -33,7 +33,12 @@
@pytest_asyncio.fixture
async def config_sessions(tmp_path: Path) -> AsyncIterator[async_sessionmaker[AsyncSession]]:
- """使用独立 SQLite 验证配置落库、解密和重启读取。"""
+ """
+ 使用独立 SQLite 验证配置落库、解密和重启读取。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :yield: 连接临时配置库的会话工厂
+ """
engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "config.sqlite"}')
async with engine.begin() as db:
await db.run_sync(SysPluginConfig.__table__.create)
@@ -186,12 +191,24 @@ async def test_failed_or_cancelled_read_keeps_previous_observation(
@asynccontextmanager
async def session() -> AsyncIterator[object]:
+ """
+ 为当前测试操作提供数据库会话。
+
+ :yield: 数据库会话
+ """
try:
yield object()
finally:
closed.append(True)
async def read(*args: object, **kwargs: object) -> list:
+ """
+ 控制测试读取操作的完成或失败。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RuntimeError: 模拟读取数据时数据库不可用
+ """
entered.set()
if cancelled:
await asyncio.Event().wait()
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py
index e0baeb36e..e5c7dfaac 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py
@@ -36,7 +36,11 @@ async def start_stream(runtime_browser: SimpleNamespace, *, bearer: bool = False
await result.incoming.put({'type': 'http.request', 'body': b'', 'more_body': False})
async def send(message: Message) -> None:
- """保留流输出并在首个响应片段到达时继续测试。"""
+ """
+ 保留流输出并在首个响应片段到达时继续测试。
+
+ :param message: 与当前结果一起返回的说明
+ """
result.messages.append(message)
if message['type'] == 'http.response.body' and message.get('body'):
result.chunks.append(message['body'])
@@ -68,7 +72,11 @@ async def send(message: Message) -> None:
async def finish_stream(stream: SimpleNamespace) -> None:
- """回收测试连接,保证失败分支也不会遗留请求任务。"""
+ """
+ 回收测试连接,保证失败分支也不会遗留请求任务。
+
+ :param stream: 需要逐块读取的流
+ """
await stream.incoming.put({'type': 'http.disconnect'})
if not stream.task.done():
stream.task.cancel()
@@ -90,6 +98,11 @@ async def test_websocket_cookie_origin_and_live_login_revocation(
@loaded.lifespan.app.websocket('/ws/events')
async def events(websocket: WebSocket) -> None:
+ """
+ 接受插件事件连接并处理测试消息。
+
+ :param websocket: 当前 WebSocket 连接
+ """
websocket.state.plugin_context.require_permission('browser_test:view')
await websocket.accept()
opened.set()
@@ -100,7 +113,11 @@ async def events(websocket: WebSocket) -> None:
await incoming.put({'type': 'websocket.connect'})
async def send(message: Message) -> None:
- """保留 WebSocket 接受及关闭消息。"""
+ """
+ 保留 WebSocket 接受及关闭消息。
+
+ :param message: 与当前结果一起返回的说明
+ """
messages.append(message)
task = asyncio.create_task(
@@ -208,7 +225,11 @@ async def test_recheck_uses_fresh_closed_db_sessions_and_does_not_refresh_bearer
@asynccontextmanager
async def session() -> AsyncIterator[object]:
- """统计独立数据库会话在复核之间全部关闭。"""
+ """
+ 统计独立数据库会话在复核之间全部关闭。
+
+ :yield: 用于本次复核的独立会话
+ """
sessions.active += 1
sessions.opened += 1
try:
@@ -217,7 +238,12 @@ async def session() -> AsyncIterator[object]:
sessions.active -= 1
async def read_user(**kwargs: object) -> object:
- """记录只读登录验证并返回固定账号。"""
+ """
+ 记录只读登录验证并返回固定账号。
+
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 固定账号
+ """
checked.set()
return browser.user
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connections.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connections.py
index 96cfb76b3..5e4b236bc 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connections.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connections.py
@@ -39,7 +39,13 @@ async def open_connection(tmp_path: Path, *, kind: str = 'http', listen: bool =
host = PluginHostContext('demo', tmp_path)
async def authorize(scope: Scope) -> PluginRequestContext:
- """按当前测试状态返回权限快照或触发指定失败。"""
+ """
+ 按当前测试状态返回权限快照或触发指定失败。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :raises Exception: 触发当前用例预设的授权异常
+ :return: ``PluginRequestContext`` 实例
+ """
case.calls.append(dict(scope))
if case.delay:
await asyncio.sleep(case.delay)
@@ -50,7 +56,13 @@ async def authorize(scope: Scope) -> PluginRequestContext:
)
async def child(scope: Scope, receive: Receive, send: Send) -> None:
- """发送首条业务消息,并在退出时记录清理结果。"""
+ """
+ 发送首条业务消息,并在退出时记录清理结果。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
case.context = scope['state']['plugin_context']
try:
if kind == 'websocket':
@@ -76,7 +88,11 @@ async def child(scope: Scope, receive: Receive, send: Send) -> None:
case.released.set()
async def send(message: Message) -> None:
- """保留协议输出以验证单次关闭及敏感字段不外泄。"""
+ """
+ 保留协议输出以验证单次关闭及敏感字段不外泄。
+
+ :param message: 与当前结果一起返回的说明
+ """
case.messages.append(message)
manager = PluginLifespanManager(child, managed=False)
@@ -95,7 +111,11 @@ async def send(message: Message) -> None:
async def finish_case(case: SimpleNamespace) -> None:
- """回收用例中的连接和生命周期任务。"""
+ """
+ 回收用例中的连接和生命周期任务。
+
+ :param case: 当前参数化场景的数据
+ """
await case.gateway.drain()
if not case.task.done():
case.task.cancel()
@@ -236,10 +256,23 @@ async def test_regular_json_response_never_creates_revalidation_task(tmp_path: P
calls = []
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟接收宿主消息的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
await asyncio.sleep(0.03)
await JSONResponse({'ok': True})(scope, receive, send)
async def authorize(scope: Scope) -> PluginRequestContext:
+ """
+ 记录授权请求并按测试场景提供插件上下文。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :return: ``PluginRequestContext`` 实例
+ """
calls.append(scope)
return PluginRequestContext(PluginHostContext('demo', tmp_path), None)
@@ -253,6 +286,23 @@ async def authorize(scope: Scope) -> PluginRequestContext:
await manager.shutdown()
+async def _cancel_or_drain_request(task: asyncio.Task, gateway: PluginGatewayASGI, external_cancel: bool) -> None:
+ """
+ 触发外部取消或网关排空,并等待请求任务结束。
+
+ :param task: 在后台执行当前工作的异步任务
+ :param gateway: HTTP、静态资源和 WebSocket 共用的宿主门禁
+ :param external_cancel: 是否由外部任务发起取消
+ """
+ if external_cancel:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ else:
+ await asyncio.wait_for(gateway.drain(), timeout=1)
+ await task
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize('external_cancel', [False, True])
async def test_cancel_resistant_application_cannot_send_late_events(tmp_path: Path, external_cancel: bool) -> None:
@@ -261,6 +311,13 @@ async def test_cancel_resistant_application_cannot_send_late_events(tmp_path: Pa
messages = []
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟接收宿主消息的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
try:
await send(
{'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'text/event-stream')]}
@@ -278,9 +335,20 @@ async def child(scope: Scope, receive: Receive, send: Send) -> None:
released.set()
async def authorize(scope: Scope) -> PluginRequestContext:
+ """
+ 创建测试使用的 ``PluginRequestContext`` 实例。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :return: 测试使用的 ``PluginRequestContext`` 实例
+ """
return PluginRequestContext(PluginHostContext('demo', tmp_path), None)
async def send(message: Message) -> None:
+ """
+ 收集应用发送的 ASGI 消息。
+
+ :param message: 与当前结果一起返回的说明
+ """
messages.append(message)
manager = PluginLifespanManager(child, managed=False)
@@ -289,13 +357,7 @@ async def send(message: Message) -> None:
task = asyncio.create_task(gateway({'type': 'http', 'headers': []}, None, send))
try:
await asyncio.wait_for(opened.wait(), timeout=1)
- if external_cancel:
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
- else:
- await asyncio.wait_for(gateway.drain(), timeout=1)
- await task
+ await _cancel_or_drain_request(task, gateway, external_cancel)
assert gateway.connections._unfinished
assert 'secret' not in str(messages)
release.set()
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py
index d98edb383..d03a2b769 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py
@@ -158,6 +158,13 @@ async def test_real_lifespan_exit_changes_readiness_without_marking_pending_canc
release = asyncio.Event()
async def application(scope: dict, receive: object, send: object) -> None:
+ """
+ 模拟应用的生命周期消息交换。
+
+ :param scope: 当前操作使用的作用域
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
await receive()
await send({'type': 'lifespan.startup.complete'})
await release.wait()
@@ -192,9 +199,22 @@ async def test_live_connection_counts_do_not_include_ordinary_http_or_auth_data(
release = asyncio.Event()
async def authorize(scope: dict) -> PluginRequestContext:
+ """
+ 创建测试使用的 ``PluginRequestContext`` 实例。
+
+ :param scope: 当前操作使用的作用域
+ :return: 测试使用的 ``PluginRequestContext`` 实例
+ """
return PluginRequestContext(loaded.host, user=SimpleNamespace(private='private-user'))
async def application(scope: dict, receive: object, send: object) -> None:
+ """
+ 模拟应用的生命周期消息交换。
+
+ :param scope: 当前操作使用的作用域
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
if scope['path'] == '/ordinary':
await send({'type': 'http.response.start', 'status': 200, 'headers': []})
await send({'type': 'http.response.body', 'body': b'private-response'})
@@ -209,11 +229,21 @@ async def application(scope: dict, receive: object, send: object) -> None:
await release.wait()
async def receive() -> dict:
+ """
+ 为下游 ASGI 应用提供待接收的测试消息。
+
+ :return: 下游应用接收的模拟消息
+ """
await asyncio.Event().wait()
return {}
async def send(message: dict) -> None:
- return None
+ """
+ 完成无需返回值的回调。
+
+ :param message: 与当前结果一起返回的说明
+ """
+ return
loaded.lifespan = PluginLifespanManager(application, managed=False)
await loaded.lifespan.startup()
@@ -249,6 +279,7 @@ async def test_pending_cleanup_is_deduplicated_and_late_completion_disappears(tm
cancellation_count = 0
async def resistant() -> None:
+ """模拟延迟响应取消信号的任务。"""
nonlocal cancellation_count
started.set()
try:
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_query.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_query.py
index 1b31a763e..c0c65575c 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_query.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_query.py
@@ -14,7 +14,13 @@
def snapshot(worker_id: str = WORKER, **overrides: object) -> dict:
- """构造真正加载但尚无请求的运行快照。"""
+ """
+ 构造真正加载但尚无请求的运行快照。
+
+ :param worker_id: 工作进程的标识
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 真正加载但尚无请求的运行快照
+ """
return {
'workerId': worker_id,
'collectedAt': NOW,
@@ -40,7 +46,13 @@ def snapshot(worker_id: str = WORKER, **overrides: object) -> dict:
def report(*workers: dict, **overrides: object) -> dict:
- """构造已通过报告器校验的集群观测结果。"""
+ """
+ 构造已通过报告器校验的集群观测结果。
+
+ :param workers: 调用方传入的其余位置参数
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 已通过报告器校验的集群观测结果
+ """
return {
'scope': 'reporting_workers',
'clusterAvailable': True,
@@ -56,7 +68,13 @@ def report(*workers: dict, **overrides: object) -> dict:
def release(*worker_ids: str, expected: int = 1) -> dict:
- """构造当前发布目标,故意与实际运行摘要不同以检验身份边界。"""
+ """
+ 构造当前发布目标,故意与实际运行摘要不同以检验身份边界。
+
+ :param worker_ids: 调用方传入的其余位置参数
+ :param expected: 断言使用的预期结果
+ :return: 当前发布目标
+ """
return {
'available': True,
'supported': True,
@@ -78,6 +96,7 @@ def release(*worker_ids: str, expected: int = 1) -> dict:
def test_diagnostics_preserves_actual_identity_and_marks_missing_worker_unknown() -> None:
+ """诊断保留实际身份并将缺失进程标记为未知。"""
result = query.build_runtime_diagnostics('demo', report(snapshot()), release(WORKER, OTHER, expected=2), now=NOW)
first, second = result['workers']
assert result['state'] == 'partial'
@@ -92,6 +111,7 @@ def test_diagnostics_preserves_actual_identity_and_marks_missing_worker_unknown(
def test_stale_and_invalid_workers_never_contribute_zero_or_old_actual_values() -> None:
+ """过期或无效进程不贡献旧值或虚构的零值。"""
result = query.build_runtime_diagnostics(
'demo',
report(staleWorkerIds=[WORKER], staleSnapshots=1, invalidWorkerIds=[OTHER], invalidSnapshots=1),
@@ -105,6 +125,7 @@ def test_stale_and_invalid_workers_never_contribute_zero_or_old_actual_values()
def test_empty_fresh_worker_and_truncated_worker_are_distinct() -> None:
+ """区分新鲜的空进程快照和被截断的快照。"""
result = query.build_runtime_diagnostics('demo', report(snapshot(plugins=[])), release(WORKER), now=NOW)
assert result['workers'][0]['observation'] == 'not_loaded'
assert result['workers'][0]['actual'] is None
@@ -117,6 +138,7 @@ def test_empty_fresh_worker_and_truncated_worker_are_distinct() -> None:
def test_replaced_stale_host_does_not_make_current_coverage_incomplete() -> None:
+ """已被替换的过期主机不会使当前覆盖统计不完整。"""
deployment = release(WORKER, OTHER)
for row in deployment['workers']:
if row['workerId'] == OTHER:
@@ -128,6 +150,7 @@ def test_replaced_stale_host_does_not_make_current_coverage_incomplete() -> None
@pytest.mark.asyncio
async def test_unavailable_runtime_and_release_keep_independent_failure_states(monkeypatch: pytest.MonkeyPatch) -> None:
+ """运行时与发布分别保留各自的不可用状态。"""
monkeypatch.setattr(query, '_read_release_status', AsyncMock(return_value={'supported': True, 'available': False}))
reporter = SimpleNamespace(read=AsyncMock(side_effect=RuntimeError('private-password')))
result = await query.read_plugin_runtime_diagnostics('demo', reporter=reporter)
@@ -139,6 +162,7 @@ async def test_unavailable_runtime_and_release_keep_independent_failure_states(m
@pytest.mark.asyncio
async def test_cli_reads_and_closes_redis_without_publishing_local_snapshot(monkeypatch: pytest.MonkeyPatch) -> None:
+ """命令行只读取并关闭 Redis 且不发布本地快照。"""
redis = SimpleNamespace(aclose=AsyncMock())
create = AsyncMock(return_value=redis)
read = AsyncMock(return_value={'state': 'unobserved'})
@@ -151,6 +175,7 @@ async def test_cli_reads_and_closes_redis_without_publishing_local_snapshot(monk
def test_current_worker_scope_is_explicitly_partial() -> None:
+ """明确标记当前进程的数据范围为局部。"""
result = query.build_runtime_diagnostics(
'demo', report(snapshot(), scope='current_worker', clusterAvailable=False), release(WORKER), now=NOW
)
@@ -159,6 +184,7 @@ def test_current_worker_scope_is_explicitly_partial() -> None:
def test_release_errors_are_not_copied_into_runtime_diagnostics() -> None:
+ """发布错误不会混入运行时诊断。"""
deployment = release(WORKER)
deployment['releases'][0].update(prepareStatus='failed', lastError='fake-secret-in-preparation')
for row in deployment['workers']:
@@ -170,6 +196,7 @@ def test_release_errors_are_not_copied_into_runtime_diagnostics() -> None:
def test_fresh_runtime_cache_of_stale_host_does_not_fill_expected_capacity() -> None:
+ """过期主机的新缓存无法补足预期容量。"""
deployment = release(WORKER, OTHER, expected=2)
deployment['workerTtlSeconds'] = 15
for row in deployment['workers']:
@@ -185,12 +212,14 @@ def test_fresh_runtime_cache_of_stale_host_does_not_fill_expected_capacity() ->
def test_no_expected_baseline_does_not_claim_zero_missing_workers() -> None:
+ """无预期基线时不宣称缺失进程数为零。"""
result = query.build_runtime_diagnostics('demo', report(), {'supported': True, 'available': True}, now=NOW)
assert result['missingWorkers'] is None
assert result['observedTotals'] is None
def test_snapshot_expiring_during_release_query_is_not_counted_as_fresh() -> None:
+ """发布查询期间过期的快照不计入新鲜快照。"""
cached = snapshot(collectedAt=NOW - 59)
cached['plugins'][0]['activeJobs'] = 7
incoming = report(cached)
@@ -214,6 +243,7 @@ def test_snapshot_expiring_during_release_query_is_not_counted_as_fresh() -> Non
@pytest.mark.parametrize('already_stale', [True, False])
def test_new_expiration_updates_stale_count_without_counting_existing_ids_twice(already_stale: bool) -> None:
+ """重新计数过期快照时不重复计算已有标识。"""
old_stale_ids = [WORKER, OTHER] if already_stale else [OTHER]
result = query.build_runtime_diagnostics(
'demo',
@@ -231,6 +261,7 @@ def test_new_expiration_updates_stale_count_without_counting_existing_ids_twice(
('age', 'ttl', 'fresh'), [(60, 60, True), (60.001, 60, False), (31, 30, False), (-5, 60, True), (-5.001, 60, False)]
)
def test_aggregation_rechecks_report_ttl_and_future_clock_skew(age: float, ttl: float, fresh: bool) -> None:
+ """聚合时复核报告有效期和未来时钟偏差。"""
result = query.build_runtime_diagnostics(
'demo', report(snapshot(collectedAt=NOW - age), sampleTtlSeconds=ttl), release(WORKER), now=NOW
)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_store.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_store.py
index e0c0cfa0a..c9da0d833 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_store.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_store.py
@@ -29,9 +29,18 @@
class DiagnosticsRedis:
- """提供隔离的快照读写,并记录查询过程中是否出现写入。"""
+ """
+ 提供隔离的快照读写,并记录查询过程中是否出现写入。
+
+ :ivar values: 当前处理的值集合
+ :ivar expirations: 按键记录的失效时间
+ :ivar writes: 已执行写入操作的记录
+ :ivar fail: 是否模拟操作失败
+ :ivar encoder: 将输入值转换为编码表示的对象
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``values``, ``expirations``, ``writes``, ``fail``。"""
self.values: dict[str | bytes, bytes] = {}
self.expirations: dict[str, int] = {}
self.writes = 0
@@ -39,6 +48,14 @@ def __init__(self) -> None:
self.encoder = Encoder('utf-8', 'strict', decode_responses=True)
async def set(self, key: str, value: bytes, *, ex: int) -> None:
+ """
+ 写入测试缓存键并设置过期时间。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :param ex: 捕获到的异常实例
+ :raises ConnectionError: 模拟写入诊断缓存时 Redis 连接失败
+ """
if self.fail:
raise ConnectionError('private-diagnostic-password')
self.writes += 1
@@ -46,9 +63,23 @@ async def set(self, key: str, value: bytes, *, ex: int) -> None:
self.expirations[key] = ex
async def delete(self, key: str) -> None:
+ """
+ 删除测试缓存项及其过期状态。
+
+ :param key: 查找数据时使用的键
+ """
self.values.pop(key, None)
async def scan_iter(self, *, match: str, count: int, **options: object) -> AsyncIterator[str | bytes]:
+ """
+ 逐个返回匹配模式的缓存键。
+
+ :param match: 是否采用匹配当前条件的输入
+ :param count: 本次处理或预期的数量
+ :param options: 调用方按名称传入的附加选项
+ :raises ConnectionError: 模拟扫描诊断缓存时 Redis 连接失败
+ :yield: 匹配模式的缓存键
+ """
if self.fail:
raise ConnectionError('private-diagnostic-password')
for key in self.values:
@@ -57,16 +88,37 @@ async def scan_iter(self, *, match: str, count: int, **options: object) -> Async
yield raw_key if NEVER_DECODE in options else self.encoder.decode(raw_key)
async def mget(self, keys: list[str]) -> list[bytes | None]:
+ """
+ 批量读取测试缓存键。
+
+ :param keys: 当前操作涉及的键集合
+ :return: 按请求键顺序排列的缓存值
+ """
return [self.values.get(key) for key in keys]
async def execute_command(self, command: str, *keys: str, **options: object) -> list[bytes | str | None]:
+ """
+ 调度并验证测试存储支持的批量读取命令。
+
+ :param command: 执行的命令及其参数
+ :param keys: 调用方传入的其余位置参数
+ :param options: 调用方按名称传入的附加选项
+ :return: 模拟批量读取命令的结果
+ """
assert command == 'MGET'
values = await self.mget(list(keys))
return [value if value is None or NEVER_DECODE in options else self.encoder.decode(value) for value in values]
def snapshot(worker_id: str, *, pending: int = 0, collected_at: float | None = None) -> PluginRuntimeDiagnosticSnapshot:
- """构造真正观测到零插件的宿主快照,不添加虚假的插件计数。"""
+ """
+ 构造真正观测到零插件的宿主快照,不添加虚假的插件计数。
+
+ :param worker_id: 工作进程的标识
+ :param pending: 等待处理的条目
+ :param collected_at: 采集状态的时间
+ :return: 真正观测到零插件的宿主快照
+ """
return PluginRuntimeDiagnosticSnapshot(
worker_id=worker_id,
collected_at=time.time() if collected_at is None else collected_at,
@@ -77,12 +129,19 @@ def snapshot(worker_id: str, *, pending: int = 0, collected_at: float | None = N
def store(redis: DiagnosticsRedis, value: PluginRuntimeDiagnosticSnapshot, namespace: str = NAMESPACE) -> None:
- """放入独立序列化快照以模拟另一个 worker 的定期发布。"""
+ """
+ 放入独立序列化快照以模拟另一个 worker 的定期发布。
+
+ :param redis: 提供隔离的快照读写,并记录查询过程中是否出现写入
+ :param value: 当前进程的只读诊断快照,与已有运行指标协议独立
+ :param namespace: 隔离当前资源的命名空间
+ """
redis.values[f'{namespace}:{value.worker_id}'] = value.model_dump_json(by_alias=True).encode()
@pytest.mark.asyncio
async def test_reader_never_fabricates_local_worker_or_writes_and_isolates_namespace() -> None:
+ """读取器隔离命名空间且不虚构本地进程或写入数据。"""
redis = DiagnosticsRedis()
store(redis, snapshot('a' * 32))
store(redis, snapshot('b' * 32), diagnostics_namespace('other-environment'))
@@ -102,6 +161,7 @@ async def test_reader_never_fabricates_local_worker_or_writes_and_isolates_names
@pytest.mark.asyncio
async def test_plugin_filter_retains_worker_scope_without_other_plugin_details() -> None:
+ """按插件筛选时保留进程范围并隐藏其他插件详情。"""
redis = DiagnosticsRedis()
value = snapshot('a' * 32, pending=3)
value.plugins = [
@@ -118,6 +178,7 @@ async def test_plugin_filter_retains_worker_scope_without_other_plugin_details()
@pytest.mark.asyncio
async def test_local_real_snapshot_replaces_own_redis_copy_and_failure_is_explicit() -> None:
+ """本地真实快照替换自身的 Redis 副本并明确报告失败。"""
redis = DiagnosticsRedis()
store(redis, snapshot('a' * 32, pending=9))
store(redis, snapshot('b' * 32, pending=2))
@@ -139,6 +200,7 @@ async def test_local_real_snapshot_replaces_own_redis_copy_and_failure_is_explic
@pytest.mark.asyncio
async def test_stale_future_invalid_and_identity_conflicts_never_supply_counters() -> None:
+ """过期、未来、无效或身份冲突的快照不贡献计数。"""
redis = DiagnosticsRedis()
store(redis, snapshot('a' * 32, collected_at=time.time() - DIAGNOSTICS_TTL_SECONDS - 1))
store(redis, snapshot('b' * 32, collected_at=time.time() + 100))
@@ -156,6 +218,7 @@ async def test_stale_future_invalid_and_identity_conflicts_never_supply_counters
@pytest.mark.asyncio
async def test_invalid_utf8_key_and_value_do_not_hide_healthy_workers() -> None:
+ """键值包含无效 UTF-8 时仍能看到健康进程。"""
redis = DiagnosticsRedis()
store(redis, snapshot('a' * 32))
redis.values[f'{NAMESPACE}:{"b" * 32}'] = b'\xff'
@@ -183,6 +246,7 @@ async def test_invalid_utf8_key_and_value_do_not_hide_healthy_workers() -> None:
],
)
async def test_incomplete_remote_snapshot_cannot_supply_default_zero_counters(missing_field: str) -> None:
+ """不完整的远端快照不能用零值补齐计数。"""
redis = DiagnosticsRedis()
store(redis, snapshot('a' * 32))
incomplete = snapshot('b' * 32)
@@ -205,6 +269,7 @@ async def test_incomplete_remote_snapshot_cannot_supply_default_zero_counters(mi
@pytest.mark.asyncio
async def test_size_and_worker_limits_are_reported(monkeypatch: pytest.MonkeyPatch) -> None:
+ """报告快照大小和工作进程数量限制。"""
redis = DiagnosticsRedis()
monkeypatch.setattr(module, 'MAX_DIAGNOSTICS_SNAPSHOT_BYTES', 10)
store(redis, snapshot('a' * 32))
@@ -219,6 +284,7 @@ async def test_size_and_worker_limits_are_reported(monkeypatch: pytest.MonkeyPat
@pytest.mark.asyncio
async def test_expired_during_read_is_unknown_and_io_timeout_is_bounded(monkeypatch: pytest.MonkeyPatch) -> None:
+ """读取中到期的快照标为未知并限制 I/O 超时。"""
redis = DiagnosticsRedis()
store(redis, snapshot('a' * 32))
with patch.object(redis, 'mget', AsyncMock(return_value=[None])):
@@ -228,6 +294,12 @@ async def test_expired_during_read_is_unknown_and_io_timeout_is_bounded(monkeypa
monkeypatch.setattr(module, 'DIAGNOSTICS_IO_TIMEOUT_SECONDS', 0.01)
async def blocked_read(keys: list[str]) -> list[bytes | None]:
+ """
+ 阻塞读取以测试超时处理。
+
+ :param keys: 当前操作涉及的键集合
+ :return: 解除阻塞后返回的空结果列表
+ """
await asyncio.Event().wait()
return []
@@ -239,6 +311,7 @@ async def blocked_read(keys: list[str]) -> list[bytes | None]:
@pytest.mark.asyncio
async def test_publication_failure_recovers_and_stop_only_deletes_owned_snapshot() -> None:
+ """发布失败后可恢复且停止时只删除自有快照。"""
redis = DiagnosticsRedis()
reporter = PluginDiagnosticsReporter(lambda: snapshot('a' * 32), 'a' * 32)
reporter.start(redis, NAMESPACE)
@@ -260,6 +333,7 @@ async def test_publication_failure_recovers_and_stop_only_deletes_owned_snapshot
@pytest.mark.asyncio
async def test_wrong_local_identity_cannot_be_published_or_appear_as_current_worker() -> None:
+ """错误本地身份不可发布也不显示为当前进程。"""
redis = DiagnosticsRedis()
reporter = PluginDiagnosticsReporter(lambda: snapshot('b' * 32), 'a' * 32)
reporter.redis, reporter.namespace = redis, NAMESPACE
@@ -273,6 +347,7 @@ async def test_wrong_local_identity_cannot_be_published_or_appear_as_current_wor
@pytest.mark.asyncio
async def test_application_owns_diagnostics_lifecycle_even_when_shutdown_fails() -> None:
+ """即使关闭失败应用仍负责诊断资源的生命周期。"""
redis = DiagnosticsRedis()
app = FastAPI()
app.state.redis = redis
@@ -299,6 +374,7 @@ async def test_application_owns_diagnostics_lifecycle_even_when_shutdown_fails()
@pytest.mark.asyncio
async def test_empty_runtime_uses_release_worker_identity_without_fabricating_missing_worker() -> None:
+ """运行时为空时使用发布进程身份且不虚构缺失进程。"""
app = FastAPI()
explicit = ExplicitPluginRuntime(UnavailablePluginRouteStateGateway())
app.state.plugin_explicit_runtime = explicit
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_entities.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_entities.py
index 6174e5ede..7621e5028 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_entities.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_entities.py
@@ -13,7 +13,13 @@ def test_entity_module_importer_defaults_to_backend_root() -> None:
def write_python_file(file_path: Path, content: str = '') -> Path:
- """写入 Python 测试文件。"""
+ """
+ 写入 Python 测试文件。
+
+ :param file_path: 文件路径
+ :param content: 需要读取或写入的内容
+ :return: 文件路径
+ """
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.write_text(content, encoding='utf-8')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_entrypoint.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_entrypoint.py
index 9a2c9f73a..d02b64651 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_entrypoint.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_entrypoint.py
@@ -16,7 +16,11 @@
@pytest.fixture(autouse=True)
def isolate_modules() -> Generator[None, None, None]:
- """测试模块使用独立 ID,避免影响现有插件测试。"""
+ """
+ 测试模块使用独立 ID,避免影响现有插件测试。
+
+ :yield: 上下文就绪后将控制权交给调用方
+ """
yield
for name in list(sys.modules):
if name == 'plugins.entry_test' or name.startswith('plugins.entry_test.'):
@@ -26,6 +30,14 @@ def isolate_modules() -> Generator[None, None, None]:
def make_plugin(tmp_path: Path, source: str, *, native: bool = False) -> DiscoveredPlugin:
+ """
+ 组装测试所需的插件描述。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param source: 写入测试插件入口模块的 Python 源码
+ :param native: 是否使用原生插件
+ :return: 测试所需的插件描述
+ """
root = tmp_path / 'plugins' / 'entry_test'
root.mkdir(parents=True, exist_ok=True)
module = 'ruoyi_plugin_entry_test' if native else 'plugins.entry_test'
@@ -41,6 +53,7 @@ def make_plugin(tmp_path: Path, source: str, *, native: bool = False) -> Discove
def test_python_factory_can_call_host_service(tmp_path: Path) -> None:
+ """Python 工厂可调用宿主服务。"""
calls = []
plugin = make_plugin(
tmp_path,
@@ -56,6 +69,7 @@ def test_python_factory_can_call_host_service(tmp_path: Path) -> None:
def test_loader_rejects_other_version_in_module_cache(tmp_path: Path) -> None:
+ """加载器拒绝模块缓存中的其他版本。"""
source = 'from plugins.core.sdk import PluginDefinition\ndef create_plugin(host): return PluginDefinition()\n'
first = make_plugin(tmp_path / 'first', source)
second = make_plugin(tmp_path / 'second', source)
@@ -65,6 +79,7 @@ def test_loader_rejects_other_version_in_module_cache(tmp_path: Path) -> None:
def test_failed_import_removes_new_modules(tmp_path: Path) -> None:
+ """导入失败时清理新增模块。"""
plugin = make_plugin(tmp_path, 'raise RuntimeError("broken import")\n')
with pytest.raises(RuntimeError, match='broken import'):
PluginEntrypointLoader(plugin).load(PluginHostContext(plugin.manifest.id, plugin.backend_path))
@@ -81,12 +96,14 @@ def test_failed_import_removes_new_modules(tmp_path: Path) -> None:
],
)
def test_factory_protocol_is_checked(tmp_path: Path, source: str) -> None:
+ """校验插件工厂协议。"""
plugin = make_plugin(tmp_path, source)
with pytest.raises((ValueError, TypeError)):
PluginEntrypointLoader(plugin).load(PluginHostContext(plugin.manifest.id, plugin.backend_path))
def test_native_precheck_validates_tags_record_and_hash_without_importing(tmp_path: Path) -> None:
+ """原生预检在不导入模块时校验标签、记录和哈希。"""
plugin = make_plugin(tmp_path, '', native=True)
native_root = plugin.backend_path / 'native'
package = native_root / 'ruoyi_plugin_entry_test'
@@ -114,11 +131,27 @@ def test_native_precheck_validates_tags_record_and_hash_without_importing(tmp_pa
@pytest.mark.asyncio
async def test_native_style_callable_returns_awaitable() -> None:
+ """原生可调用对象可返回可等待的结果。"""
+
async def calculate(value: int) -> int:
+ """
+ 返回输入值加一的回调结果。
+
+ :param value: 待处理的输入值
+ :return: 输入值加一的回调结果
+ """
return value + 1
class NativeStyleCallback:
+ """用同步调用入口模拟原生插件回调。"""
+
def __call__(self, value: int) -> object:
+ """
+ 执行测试替身的回调。
+
+ :param value: 待处理的输入值
+ :return: 传入数值经回调计算后的结果
+ """
return calculate(value)
result = await await_plugin_callback(NativeStyleCallback(), 4)
@@ -128,6 +161,7 @@ def __call__(self, value: int) -> object:
def test_context_rejects_resource_escape_and_unknown_service(tmp_path: Path) -> None:
+ """上下文拒绝资源越界及未知服务。"""
host = PluginHostContext('entry_test', tmp_path)
with pytest.raises(ValueError, match='根目录'):
host.resource('../outside')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_explicit.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_explicit.py
index c19cc5775..e578ef6d3 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_explicit.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_explicit.py
@@ -54,6 +54,11 @@ async def info(request: Request):
@pytest.fixture(autouse=True)
def clear_modules() -> Generator[None, None, None]:
+ """
+ 在测试结束时清理动态导入的插件模块。
+
+ :yield: 上下文就绪后将控制权交给调用方
+ """
yield
for name in list(sys.modules):
if name.startswith('plugins.runtime_test'):
@@ -73,6 +78,16 @@ def write_plugin(
dependencies: list[str] | None = None,
integration: str = 'asgi',
) -> RegisteredPlugin:
+ """
+ 在临时插件目录写入测试用的清单及文件。
+
+ :param root: 路径解析的基准目录
+ :param plugin_id: 插件清单中的唯一标识
+ :param source: 写入测试插件入口模块的 Python 源码
+ :param dependencies: 执行当前步骤所需的依赖
+ :param integration: 插件与宿主的集成方式
+ :return: ``RegisteredPlugin`` 实例
+ """
directory = root / 'plugins' / plugin_id
directory.mkdir(parents=True, exist_ok=True)
manifest = {
@@ -96,11 +111,17 @@ def write_plugin(
@asynccontextmanager
async def fake_session() -> AsyncGenerator[object, None]:
+ """
+ 为上下文提供受控的测试会话。
+
+ :yield: 上下文中借用的测试会话
+ """
yield object()
@pytest.mark.asyncio
async def test_main_runtime_mounts_authenticates_and_stops_subapplication(tmp_path: Path) -> None:
+ """主运行时挂载、认证并停止子应用。"""
plugin = write_plugin(tmp_path)
app = FastAPI()
app.state.plugin_registry = PluginRegistry([plugin])
@@ -174,6 +195,7 @@ async def denied():
async def test_router_and_endpoint_share_current_user_dependency(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, override_dependency: bool
) -> None:
+ """路由和端点共享当前用户依赖。"""
source = """
from fastapi import APIRouter, Depends, Request
from common.aspect.pre_auth import CurrentUserDependency, PreAuthDependency
@@ -207,6 +229,11 @@ async def info(
override_calls = []
async def current_user() -> CurrentUserModel:
+ """
+ 在令牌匹配时提供测试用户。
+
+ :return: 当前操作对应的用户
+ """
override_calls.append(user)
return user
@@ -236,6 +263,7 @@ async def current_user() -> CurrentUserModel:
def test_dependency_cycle_and_missing_dependency_do_not_block_independent_plugin(tmp_path: Path) -> None:
+ """依赖循环或缺失不阻塞独立插件。"""
first = write_plugin(tmp_path, plugin_id='runtime_test_a', dependencies=['runtime_test_b'])
second = write_plugin(tmp_path, plugin_id='runtime_test_b', dependencies=['runtime_test_a'])
missing = write_plugin(tmp_path, plugin_id='runtime_test_missing', dependencies=['absent'])
@@ -246,6 +274,7 @@ def test_dependency_cycle_and_missing_dependency_do_not_block_independent_plugin
def test_dependency_order_starts_dependencies_first(tmp_path: Path) -> None:
+ """先启动被依赖的插件。"""
consumer = write_plugin(tmp_path, plugin_id='runtime_test_consumer', dependencies=['runtime_test_base'])
base = write_plugin(tmp_path, plugin_id='runtime_test_base')
ordered, errors = ExplicitPluginRuntime.dependency_order(PluginRegistry([consumer, base]))
@@ -255,6 +284,7 @@ def test_dependency_order_starts_dependencies_first(tmp_path: Path) -> None:
@pytest.mark.asyncio
async def test_failed_startup_leaves_no_mount_and_isolates_plugin(tmp_path: Path) -> None:
+ """启动失败时清理挂载并隔离插件。"""
plugin = write_plugin(
tmp_path, source=ASGI_SOURCE.replace("events.append('start')", "raise RuntimeError('broken')")
)
@@ -270,6 +300,7 @@ async def test_failed_startup_leaves_no_mount_and_isolates_plugin(tmp_path: Path
@pytest.mark.asyncio
async def test_health_failure_after_startup_shuts_down_child(tmp_path: Path) -> None:
+ """启动后健康检查失败则关闭子应用。"""
plugin = write_plugin(tmp_path, source=ASGI_SOURCE + '\nasync def check(context): return False\n')
plugin.discovered_plugin.manifest.backend.health.checker = 'plugins.runtime_test:check'
app = FastAPI()
@@ -295,6 +326,13 @@ async def test_shutdown_isolates_cleanup_failures_and_closes_in_reverse_order(
order = []
async def step(name: str, *, fails: bool = False) -> None:
+ """
+ 检查插件关闭过程的步骤顺序。
+
+ :param name: 用于查找或标识当前对象的名称
+ :param fails: 是否模拟执行失败
+ :raises RuntimeError: 模拟执行清理步骤失败
+ """
assert all(not loaded.active for loaded in runtime.loaded.values())
with pytest.raises(RuntimeError, match='关闭阶段'):
await runtime.activate('runtime_test_base', app)
@@ -310,13 +348,20 @@ async def step(name: str, *, fails: bool = False) -> None:
actual_shutdown = consumer.lifespan.shutdown
async def consumer_lifespan() -> None:
+ """关闭消费端生命周期并记录结果。"""
await actual_shutdown()
await step('consumer:lifespan', fails=failure_at == 'lifespan')
async def consumer_connection() -> None:
+ """记录消费端连接的关闭步骤。"""
await step('consumer:connection', fails=failure_at == 'connection')
async def consumer_jobs(binding: object) -> None:
+ """
+ 记录消费端任务的关闭步骤。
+
+ :param binding: 关联资源和运行时的绑定信息
+ """
await step('consumer:job', fails=failure_at == 'job')
monkeypatch.setattr(consumer.lifespan, 'shutdown', consumer_lifespan)
@@ -360,6 +405,11 @@ async def test_shutdown_during_health_check_cannot_publish_late_plugin(
entered, release = asyncio.Event(), asyncio.Event()
async def check(*args: object) -> None:
+ """
+ 为源码样例提供共享的 Sphinx 检查环境。
+
+ :param args: 传给被调用对象的位置参数
+ """
entered.set()
await release.wait()
@@ -393,6 +443,14 @@ async def test_failed_activation_cannot_replace_pending_lifespan(
attempts = []
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟接收宿主消息的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ :raises RuntimeError: 模拟使用已经停止的旧资源
+ """
attempts.append(scope)
await receive()
if len(attempts) == 1:
@@ -436,6 +494,7 @@ async def child(scope: Scope, receive: Receive, send: Send) -> None:
async def test_activation_cleanup_failure_preserves_original_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """激活清理失败时保留原始错误。"""
runtime = ExplicitPluginRuntime(SimpleNamespace())
app = FastAPI()
plugin = write_plugin(tmp_path, source=ASGI_SOURCE.replace("events.append('stop')", "raise ValueError('cleanup')"))
@@ -448,6 +507,7 @@ async def test_activation_cleanup_failure_preserves_original_error(
@pytest.mark.asyncio
async def test_cancelled_activation_closes_previously_started_children(tmp_path: Path) -> None:
+ """取消激活时关闭已启动的子应用。"""
first = write_plugin(tmp_path, plugin_id='runtime_test_first')
second = write_plugin(tmp_path, plugin_id='runtime_test_second')
app = FastAPI()
@@ -458,6 +518,13 @@ async def test_cancelled_activation_closes_previously_started_children(tmp_path:
activate = runtime.activate
async def cancel_second(plugin_id: str, target: FastAPI) -> None:
+ """
+ 在处理第二个插件时触发取消。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param target: 本次操作的目标
+ :raises asyncio.CancelledError: 模拟第二次操作被取消
+ """
if plugin_id == second.plugin_id:
raise asyncio.CancelledError
await activate(plugin_id, target)
@@ -472,6 +539,7 @@ async def cancel_second(plugin_id: str, target: FastAPI) -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('failure', [ConnectionError('ready write failed'), asyncio.CancelledError()])
async def test_ready_publication_failure_closes_started_children(tmp_path: Path, failure: BaseException) -> None:
+ """发布就绪状态失败时关闭已启动的子应用。"""
plugin = write_plugin(tmp_path)
app = FastAPI()
app.state.plugin_registry = PluginRegistry([plugin])
@@ -493,6 +561,7 @@ async def test_ready_publication_failure_closes_started_children(tmp_path: Path,
@pytest.mark.asyncio
async def test_router_namespace_validation_is_atomic(tmp_path: Path) -> None:
+ """路由命名空间校验具有原子性。"""
source = """
from fastapi import APIRouter
from plugins.core.sdk import PluginDefinition
@@ -513,6 +582,7 @@ def create_plugin(host):
def test_generation_covers_native_and_bundle_content(tmp_path: Path) -> None:
+ """生成标识覆盖原生模块和资源包内容。"""
plugin = write_plugin(tmp_path)
root = plugin.backend_path
resolver = PluginStartupGenerationResolver(tmp_path, release_id='')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_health.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_health.py
index 6711cee3e..c091ee465 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_health.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_health.py
@@ -15,7 +15,11 @@
@pytest.fixture(autouse=True)
def isolate_health_plugin_modules() -> Generator[None, None, None]:
- """隔离测试插件模块,避免 v2 加载器复用其他临时目录的旧模块。"""
+ """
+ 隔离测试插件模块,避免 v2 加载器复用其他临时目录的旧模块。
+
+ :yield: 上下文就绪后将控制权交给调用方
+ """
for name in list(sys.modules):
if name == 'plugins.demo_health' or name.startswith('plugins.demo_health.'):
sys.modules.pop(name, None)
@@ -35,7 +39,14 @@ def write_plugin_with_health(
*,
manifest_version: int = 1,
) -> None:
- """写入带健康检查的测试插件。"""
+ """
+ 写入带健康检查的测试插件。
+
+ :param plugin_root: 插件的根目录
+ :param health_content: 测试健康检查模块的源码
+ :param checker_path: 健康检查声明路径
+ :param manifest_version: 插件清单版本
+ """
plugin_root.mkdir(parents=True)
(plugin_root / '__init__.py').write_text('', encoding='utf-8')
(plugin_root / 'health.py').write_text(health_content, encoding='utf-8')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_hooks.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_hooks.py
index 35b8e9b92..1dc12eefb 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_hooks.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_hooks.py
@@ -9,7 +9,13 @@
def write_plugin_with_hook(plugin_root: Path, hook_content: str, hook_path: str = 'hooks:on_startup') -> None:
- """写入带生命周期钩子的测试插件。"""
+ """
+ 写入带生命周期钩子的测试插件。
+
+ :param plugin_root: 插件的根目录
+ :param hook_content: 测试生命周期回调的源码
+ :param hook_path: 回调代码所在的路径
+ """
plugin_root.mkdir(parents=True)
(plugin_root / 'hooks.py').write_text(hook_content, encoding='utf-8')
(plugin_root / 'plugin.yaml').write_text(
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_service_extensions.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_service_extensions.py
index 91fe8ad2c..ffcb03ebb 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_service_extensions.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_service_extensions.py
@@ -13,7 +13,14 @@
def context_for(tmp_path: Path, plugin_id: str = 'sdk_demo', *, permissions: bool = True) -> PluginRequestContext:
- """为字典与缓存服务提供绑定插件的请求身份。"""
+ """
+ 为字典与缓存服务提供绑定插件的请求身份。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param plugin_id: 插件清单中的唯一标识
+ :param permissions: 当前调用允许使用的权限
+ :return: ``PluginRequestContext`` 实例
+ """
return PluginRequestContext(
PluginHostContext(plugin_id, tmp_path),
SimpleNamespace(user=SimpleNamespace(user_id=7)),
@@ -28,6 +35,11 @@ async def test_dictionary_service_returns_only_public_enabled_options(tmp_path:
@asynccontextmanager
async def session() -> AsyncIterator[object]:
+ """
+ 为当前测试操作提供数据库会话。
+
+ :yield: 数据库会话
+ """
yield db
row = SimpleNamespace(
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_services.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_services.py
index c83821e5f..834ff89a5 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_services.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_services.py
@@ -16,11 +16,17 @@
@pytest.mark.asyncio
async def test_profile_facade_calls_existing_service_for_own_user_and_limits_fields(tmp_path: Path) -> None:
+ """资料接口调用现有服务,仅访问当前用户并限制返回字段。"""
events = []
db = object()
@asynccontextmanager
async def session() -> AsyncGenerator[object, None]:
+ """
+ 为当前测试操作提供数据库会话。
+
+ :yield: 数据库会话
+ """
events.append('open')
try:
yield db
@@ -54,6 +60,7 @@ async def session() -> AsyncGenerator[object, None]:
@pytest.mark.asyncio
@pytest.mark.parametrize('invalid', ['foreign_plugin', 'permission', 'identity'])
async def test_profile_facade_rejects_invalid_context_before_database(tmp_path: Path, invalid: str) -> None:
+ """资料接口在访问数据库前拒绝无效上下文。"""
session = AsyncMock()
service = build_host_services('demo', session)['users.current_profile.v1']
host = PluginHostContext('other' if invalid == 'foreign_plugin' else 'demo', tmp_path)
@@ -68,10 +75,17 @@ async def test_profile_facade_rejects_invalid_context_before_database(tmp_path:
@pytest.mark.asyncio
async def test_endpoint_adapter_enforces_permission_and_waits_native_style_result(tmp_path: Path) -> None:
+ """端点适配器校验权限并等待原生实现的异步结果。"""
host = PluginHostContext('demo', tmp_path)
callback = AsyncMock(return_value={'ok': True})
def native_callback(context: PluginRequestContext) -> object:
+ """
+ 将宿主上下文传给原生样式回调。
+
+ :param context: 由宿主鉴权层建立的请求身份,不能由客户端字段直接构造
+ :return: 原生样式回调提供的异步结果
+ """
return callback(context)
endpoint = plugin_endpoint(native_callback, permission='demo:view')
@@ -104,9 +118,15 @@ def native_callback(context: PluginRequestContext) -> object:
@pytest.mark.asyncio
async def test_endpoint_timeout_cancels_python_service(tmp_path: Path) -> None:
+ """端点超时后取消 Python 服务。"""
closed = asyncio.Event()
async def slow(context: PluginRequestContext) -> None:
+ """
+ 模拟延迟完成的服务调用。
+
+ :param context: 由宿主鉴权层建立的请求身份,不能由客户端字段直接构造
+ """
try:
await asyncio.Event().wait()
finally:
@@ -134,6 +154,7 @@ async def slow(context: PluginRequestContext) -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('startup_failure', [False, True])
async def test_lifespan_adapter_closes_even_partial_startup(tmp_path: Path, startup_failure: bool) -> None:
+ """生命周期适配器清理部分启动的资源。"""
host = PluginHostContext('demo', tmp_path)
startup = AsyncMock(return_value={'ready': True}, side_effect=RuntimeError('failed') if startup_failure else None)
shutdown = AsyncMock()
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_job_dispatcher.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_job_dispatcher.py
index 8b308b370..2b136f817 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_job_dispatcher.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_job_dispatcher.py
@@ -32,6 +32,12 @@
@pytest.fixture
def setup_plugin(tmp_path: Path) -> Iterator[SimpleNamespace]:
+ """
+ 在临时目录中创建可调度的测试插件。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :yield: ``SimpleNamespace`` 实例
+ """
directory = tmp_path / 'plugins' / 'dispatch_test'
directory.mkdir(parents=True)
data = {
@@ -69,6 +75,11 @@ def setup_plugin(tmp_path: Path) -> Iterator[SimpleNamespace]:
@asynccontextmanager
async def session() -> AsyncGenerator[object, None]:
+ """
+ 为当前测试操作提供数据库会话。
+
+ :yield: 数据库会话
+ """
sessions.append('open')
try:
yield object()
@@ -94,6 +105,7 @@ async def session() -> AsyncGenerator[object, None]:
@pytest.mark.asyncio
async def test_persistent_reference_restores_and_dispatches_on_host_loop(setup_plugin: SimpleNamespace) -> None:
+ """持久化引用恢复后在宿主事件循环中分发。"""
state = setup_plugin
manifest = state.plugin.manifest
job = PluginJobModelBuilder.build(manifest.id, manifest.backend.jobs[0], manifest=manifest)
@@ -125,6 +137,7 @@ async def test_persistent_reference_restores_and_dispatches_on_host_loop(setup_p
@pytest.mark.asyncio
async def test_gates_reject_before_call_and_shutdown_unbinds(setup_plugin: SimpleNamespace) -> None:
+ """调用前检查访问条件并在关闭时解除绑定。"""
state = setup_plugin
with pytest.raises(RuntimeError, match='未就绪'):
await dispatch_plugin_job('dispatch_test', 'tick', '1.0.0')
@@ -152,10 +165,17 @@ async def test_gates_reject_before_call_and_shutdown_unbinds(setup_plugin: Simpl
async def test_shutdown_cancels_running_task_before_child_resources_close(
setup_plugin: SimpleNamespace, during_gate: bool
) -> None:
+ """关闭子应用资源前先取消运行中的任务。"""
state = setup_plugin
started, closed = asyncio.Event(), asyncio.Event()
async def block(*args: object, **kwargs: object) -> None:
+ """
+ 通知调用方任务已开始并等待测试释放。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
started.set()
try:
await asyncio.Event().wait()
@@ -170,6 +190,7 @@ async def block(*args: object, **kwargs: object) -> None:
loaded = state.runtime.loaded['dispatch_test']
async def stop_child() -> None:
+ """确认资源释放后停止子任务。"""
assert closed.is_set()
assert state.sessions == ['open', 'close']
@@ -187,11 +208,18 @@ async def stop_child() -> None:
@pytest.mark.asyncio
async def test_job_timeout_and_host_exception_propagate(setup_plugin: SimpleNamespace) -> None:
+ """传播任务超时及宿主异常。"""
state = setup_plugin
state.plugin.manifest.backend.jobs[0].timeout_seconds = 0.01
closed = asyncio.Event()
async def wait(*args: object, **kwargs: object) -> None:
+ """
+ 等待测试控制的任务状态变更。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
try:
await asyncio.Event().wait()
finally:
@@ -215,6 +243,7 @@ async def wait(*args: object, **kwargs: object) -> None:
@pytest.mark.asyncio
async def test_failed_activation_releases_binding_for_retry(setup_plugin: SimpleNamespace) -> None:
+ """激活失败后释放绑定以供重试。"""
runtime = setup_plugin.runtime
with (
patch.object(runtime, '_check_health', new=AsyncMock(side_effect=ValueError('unhealthy'))),
@@ -228,6 +257,7 @@ async def test_failed_activation_releases_binding_for_retry(setup_plugin: Simple
def test_job_preflight_does_not_import_and_rejects_invalid_settings(setup_plugin: SimpleNamespace) -> None:
+ """任务预检无需导入模块即可拒绝无效设置。"""
state = setup_plugin
with patch('importlib.import_module', side_effect=AssertionError('预检不能导入插件')):
checked = PluginStructureChecker(state.plugin.backend_path.parents[1]).check(
@@ -253,6 +283,13 @@ async def test_unbind_is_bounded_and_blocks_new_binding_until_old_jobs_exit(
opened, release = asyncio.Event(), asyncio.Event()
async def resistant(*args: object, **kwargs: object) -> bool:
+ """
+ 模拟延迟响应取消信号的任务。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``True``
+ """
opened.set()
while not release.is_set():
with suppress(asyncio.CancelledError):
@@ -300,6 +337,13 @@ async def test_shutdown_keeps_pending_job_diagnostics_until_callback_exits(
opened, release = asyncio.Event(), asyncio.Event()
async def resistant(*args: object, **kwargs: object) -> bool:
+ """
+ 模拟延迟响应取消信号的任务。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 此分支的固定值 ``True``
+ """
opened.set()
while not release.is_set():
with suppress(asyncio.CancelledError):
@@ -307,6 +351,11 @@ async def resistant(*args: object, **kwargs: object) -> bool:
return True
async def bounded_unbind(binding: object) -> None:
+ """
+ 以较短的宽限期解除插件任务绑定。
+
+ :param binding: 关联资源和运行时的绑定信息
+ """
await unbind_plugin_jobs(binding, grace_seconds=0.01)
state.service.side_effect = resistant
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics.py
index 775193f88..f99a2afbe 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics.py
@@ -19,7 +19,14 @@
def collector(worker_id: str = 'a' * 32, version: str = '1.0.0', generation: str | None = None) -> PluginRuntimeMetrics:
- """构建包含固定插件身份的指标收集器。"""
+ """
+ 构建包含固定插件身份的指标收集器。
+
+ :param worker_id: 工作进程的标识
+ :param version: 当前记录的版本
+ :param generation: 当前发布或部署的代次
+ :return: 包含固定插件身份的指标收集器
+ """
metrics = PluginRuntimeMetrics(worker_id=worker_id)
metrics.register('metric_demo', version, 'c' * 64, generation)
return metrics
@@ -84,7 +91,9 @@ async def test_http_observer_tracks_responses_without_recording_paths_or_content
child = FastAPI()
seen = []
- @child.get('/items/{item_id}')
+ @child.get(
+ '/items/{item_id}', summary='访问插件条目', description='回显路径中的条目标识,用于验证按路由模板聚合指标。'
+ )
async def item(item_id: str) -> dict[str, str]:
seen.append(TraceCtx.get_request_id())
if item_id == 'denied':
@@ -132,6 +141,13 @@ async def test_cancelled_asgi_request_removes_active_count() -> None:
metrics = collector()
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟接收宿主消息的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
entered.set()
await asyncio.Event().wait()
@@ -156,11 +172,23 @@ async def test_websocket_observation_covers_handshake_and_close(accepted: bool,
messages: list[Message] = []
async def child(scope: Scope, receive: Receive, send: Send) -> None:
+ """
+ 模拟接收宿主消息的下游 ASGI 应用。
+
+ :param scope: 该 ASGI 连接的类型、路径和请求头等信息
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
if accepted:
await send({'type': 'websocket.accept'})
await send({'type': 'websocket.close', 'code': code})
async def send(message: Message) -> None:
+ """
+ 收集应用发送的 ASGI 消息。
+
+ :param message: 与当前结果一起返回的说明
+ """
messages.append(message)
await PluginObservedASGI(child, metrics, 'metric_demo')({'type': 'websocket'}, AsyncMock(), send)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics_store.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics_store.py
index eb6663c6c..0ca7d6203 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics_store.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics_store.py
@@ -12,23 +12,52 @@
class MetricsRedis:
- """提供测试所需的键空间隔离和有限指标读写,不连接外部服务。"""
+ """
+ 提供测试所需的键空间隔离和有限指标读写,不连接外部服务。
+
+ :ivar values: 当前处理的值集合
+ :ivar expirations: 按键记录的失效时间
+ :ivar fail: 是否模拟操作失败
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``values``, ``expirations``, ``fail``。"""
self.values: dict[str, bytes] = {}
self.expirations: dict[str, int] = {}
self.fail = False
async def set(self, key: str, value: bytes, *, ex: int) -> None:
+ """
+ 写入测试缓存键并设置过期时间。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :param ex: 捕获到的异常实例
+ :raises ConnectionError: 模拟 Redis 写入连接中断
+ """
if self.fail:
raise ConnectionError('private-redis-password')
self.values[key] = value
self.expirations[key] = ex
async def delete(self, key: str) -> int:
+ """
+ 删除测试缓存项及其过期状态。
+
+ :param key: 查找数据时使用的键
+ :return: 实际删除的键数
+ """
return int(self.values.pop(key, None) is not None)
async def scan_iter(self, *, match: str, count: int) -> AsyncIterator[str]:
+ """
+ 逐个返回匹配模式的缓存键。
+
+ :param match: 是否采用匹配当前条件的输入
+ :param count: 本次处理或预期的数量
+ :raises ConnectionError: 模拟扫描 Redis 时连接中断
+ :yield: 匹配模式的缓存键
+ """
if self.fail:
raise ConnectionError('private-redis-password')
for key in sorted(self.values):
@@ -36,11 +65,22 @@ async def scan_iter(self, *, match: str, count: int) -> AsyncIterator[str]:
yield key
async def mget(self, keys: list[str]) -> list[bytes | None]:
+ """
+ 批量读取测试缓存键。
+
+ :param keys: 当前操作涉及的键集合
+ :return: 按键顺序排列的缓存值
+ """
return [self.values.get(key) for key in keys]
def reporter(worker_id: str) -> PluginMetricsReporter:
- """构造加载了固定插件的进程报告器。"""
+ """
+ 构造加载了固定插件的进程报告器。
+
+ :param worker_id: 工作进程的标识
+ :return: 加载了固定插件的进程报告器
+ """
metrics = PluginRuntimeMetrics(worker_id=worker_id)
metrics.register('metric_demo', '1.0.0', None, None)
metrics.begin('metric_demo', 'http', f'trace-{worker_id}').finish('succeeded')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_plugin_bootstrap.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_plugin_bootstrap.py
index d48982ed5..85638e67b 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_plugin_bootstrap.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_plugin_bootstrap.py
@@ -26,7 +26,12 @@ def test_plugin_runtime_builder_resolves_frontend_plugins_root_from_backend_root
def write_manifest(plugin_dir: Path, content: str) -> None:
- """写入测试插件清单。"""
+ """
+ 写入测试插件清单。
+
+ :param plugin_dir: 保存插件清单和资源的目录
+ :param content: 需要读取或写入的内容
+ """
plugin_dir.mkdir(parents=True)
(plugin_dir / 'plugin.yaml').write_text(content, encoding='utf-8')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_route_guard.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_route_guard.py
index 9a0c2a4e4..4b91d4b60 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_route_guard.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_route_guard.py
@@ -7,15 +7,28 @@
class FakePluginRouteStateGateway:
"""
测试用插件路由状态网关。
+
+ :ivar enabled: 是否启用该项功能
+ :ivar calls: 测试替身记录的调用信息
"""
def __init__(self, *, enabled: bool) -> None:
- """初始化测试网关。"""
+ """
+ 初始化测试网关。
+
+ :param enabled: 是否启用该项功能
+ """
self.enabled = enabled
self.calls: list[tuple[object, str]] = []
async def is_plugin_enabled(self, db: object, plugin_id: str) -> bool:
- """判断插件是否启用。"""
+ """
+ 判断插件是否启用。
+
+ :param db: 当前操作使用的数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 是否插件是否启用
+ """
self.calls.append((db, plugin_id))
return self.enabled
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_sdk_requests.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_sdk_requests.py
index 32c4fa7a7..3af528402 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_sdk_requests.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_sdk_requests.py
@@ -17,23 +17,39 @@
class ReportBody(BaseModel):
"""验证原生和 Python 回调共享的业务输入数据。"""
- name: str = Field(min_length=2)
- count: int = Field(ge=1)
+ name: str = Field(min_length=2, description='报表名称')
+ count: int = Field(ge=1, description='报表记录数')
def endpoint_app(tmp_path: Path, callback: Any, **options: Any) -> FastAPI:
- """创建只使用宿主签发身份的 SDK 接口测试应用。"""
+ """
+ 创建只使用宿主签发身份的 SDK 接口测试应用。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param callback: 需要在相应阶段调用的函数
+ :param options: 调用方按名称传入的附加选项
+ :return: 只使用宿主签发身份的 SDK 接口测试应用
+ """
app = FastAPI()
context = PluginRequestContext(PluginHostContext('sdk_demo', tmp_path), object(), frozenset({'sdk_demo:view'}))
@app.middleware('http')
async def inject(request: Request, call_next: Any) -> Any:
+ """
+ 将查询替身注入待测试的组件。
+
+ :param request: 当前 HTTP 请求
+ :param call_next: 调用下一层请求处理器的异步回调
+ :return: 注入查询替身后的下游响应
+ """
request.state.plugin_context = context
return await call_next(request)
app.add_api_route(
'/reports/{report_id}',
plugin_endpoint(callback, permission='sdk_demo:view', **options),
+ summary='处理插件报表请求',
+ description='通过插件 SDK 校验权限,并将报表请求交给当前测试的回调。',
methods=['GET', 'POST'],
)
return app
@@ -96,6 +112,11 @@ async def test_endpoint_limits_streamed_body_without_trusting_content_length(tmp
app = endpoint_app(tmp_path, callback, json_body=True, max_body_bytes=8)
async def chunks() -> AsyncIterator[bytes]:
+ """
+ 分块提供用于流式读取测试的数据。
+
+ :yield: 按发送顺序切分的 JSON 字节块
+ """
yield b'{"a":'
yield b'"too large"}'
@@ -178,6 +199,11 @@ async def test_request_cancellation_reaches_callback(tmp_path: Path) -> None:
stopped = asyncio.Event()
async def callback(context: PluginRequestContext) -> None:
+ """
+ 为并发测试提供可观测的回调执行点。
+
+ :param context: 由宿主鉴权层建立的请求身份,不能由客户端字段直接构造
+ """
entered.set()
try:
await asyncio.Event().wait()
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_sdk_transactions.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_sdk_transactions.py
index f0dc2da5d..eddafe362 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_sdk_transactions.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_sdk_transactions.py
@@ -16,7 +16,12 @@
@pytest_asyncio.fixture
async def sdk_sessions(tmp_path: Path) -> AsyncIterator[async_sessionmaker[AsyncSession]]:
- """使用独立 SQLite 验证提交、回滚和会话所有权。"""
+ """
+ 使用独立 SQLite 验证提交、回滚和会话所有权。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :yield: 连接独立 SQLite 数据库的会话工厂
+ """
engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "sdk.sqlite"}')
async with engine.begin() as db:
await db.execute(text('CREATE TABLE sdk_effect (value INTEGER NOT NULL)'))
@@ -27,7 +32,13 @@ async def sdk_sessions(tmp_path: Path) -> AsyncIterator[async_sessionmaker[Async
def request_context(tmp_path: Path, sessions: async_sessionmaker[AsyncSession]) -> PluginRequestContext:
- """构建只授予示例业务权限的宿主身份。"""
+ """
+ 构建只授予示例业务权限的宿主身份。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param sessions: 创建当前测试的数据库会话的工厂
+ :return: 只授予示例业务权限的宿主身份
+ """
host = PluginHostContext('sdk_demo', tmp_path, session_factory=sessions)
return PluginRequestContext(host, SimpleNamespace(user=SimpleNamespace(user_id=7)), frozenset({'sdk_demo:profile'}))
@@ -71,6 +82,11 @@ async def test_failed_or_cancelled_transaction_rolls_back(
captured = []
async def write() -> None:
+ """
+ 在插件事务中执行测试写入。
+
+ :raises ValueError: 模拟业务写入失败
+ """
async with context.transaction() as transaction:
captured.append(transaction)
await transaction.query_db.execute(text('INSERT INTO sdk_effect VALUES (2)'))
@@ -99,6 +115,11 @@ async def test_transaction_rejects_nested_and_parallel_session_use(
context = request_context(tmp_path, sdk_sessions)
async def foreign_task(transaction: PluginRequestContext) -> None:
+ """
+ 从另一个异步任务访问事务会话。
+
+ :param transaction: 由宿主鉴权层建立的请求身份,不能由客户端字段直接构造
+ """
transaction.transaction_session()
async with context.transaction() as transaction:
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_startup.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_startup.py
index a4bb61464..8e8cc8f80 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_startup.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_startup.py
@@ -16,7 +16,12 @@
def patch_startup_get_db(fake_get_db: Any) -> object:
- """patch 启动管理器方法实际使用的默认数据源Session。"""
+ """
+ 替换启动管理器方法使用的默认数据源会话。
+
+ :param fake_get_db: 为测试提供数据库连接的依赖替身
+ :return: 替换默认数据源依赖的补丁上下文
+ """
registry = SimpleNamespace(session=asynccontextmanager(fake_get_db))
return patch.dict(
PluginRuntimeStartupManager.load_registry_from_database.__globals__,
@@ -25,7 +30,13 @@ def patch_startup_get_db(fake_get_db: Any) -> object:
def patch_startup_global(name: str, value: object) -> object:
- """patch 启动管理器方法实际使用的模块全局引用。"""
+ """
+ 替换启动管理器方法使用的模块全局引用。
+
+ :param name: 用于查找或标识当前对象的名称
+ :param value: 待处理的输入值
+ :return: 临时替换启动模块引用的补丁上下文
+ """
return patch.dict(PluginRuntimeStartupManager.load_registry_from_database.__globals__, {name: value})
@@ -180,7 +191,11 @@ async def test_sync_enabled_plugin_install_states_marks_missing_database_plugin_
fake_session = AsyncMock()
async def fake_get_db() -> object:
- """生成测试数据库会话。"""
+ """
+ 生成测试数据库会话。
+
+ :yield: 测试数据库会话
+ """
yield fake_session
discovered_plugin = MagicMock()
@@ -254,7 +269,11 @@ async def test_sync_default_enabled_builtin_plugin_install_states_installs_missi
fake_session = AsyncMock()
async def fake_get_db() -> object:
- """生成测试数据库会话。"""
+ """
+ 生成测试数据库会话。
+
+ :yield: 测试数据库会话
+ """
yield fake_session
discovered_plugin = MagicMock()
@@ -303,7 +322,11 @@ async def test_sync_default_enabled_builtin_checks_dependencies_before_install_s
fake_session = AsyncMock()
async def fake_get_db() -> object:
- """提供测试用数据库会话生成器。"""
+ """
+ 提供测试用数据库会话生成器。
+
+ :yield: 测试用数据库会话生成器
+ """
yield fake_session
discovered_plugin = MagicMock()
@@ -355,7 +378,11 @@ async def test_sync_default_enabled_builtin_plugin_install_states_respects_unins
fake_session = AsyncMock()
async def fake_get_db() -> object:
- """生成测试数据库会话。"""
+ """
+ 生成测试数据库会话。
+
+ :yield: 测试数据库会话
+ """
yield fake_session
discovered_plugin = MagicMock()
@@ -384,7 +411,11 @@ async def test_startup_write_is_required_when_default_builtin_state_is_missing()
fake_session = AsyncMock()
async def fake_get_db() -> object:
- """生成测试数据库会话。"""
+ """
+ 生成测试数据库会话。
+
+ :yield: 测试数据库会话
+ """
yield fake_session
discovered_plugin = MagicMock()
@@ -418,7 +449,11 @@ async def test_startup_write_respects_installed_or_explicitly_uninstalled_builti
fake_session = AsyncMock()
async def fake_get_db() -> object:
- """生成测试数据库会话。"""
+ """
+ 生成测试数据库会话。
+
+ :yield: 测试数据库会话
+ """
yield fake_session
discovered_plugin = MagicMock()
@@ -494,7 +529,11 @@ async def test_load_registry_from_database_rebuilds_registry() -> None:
fake_session = object()
async def fake_get_db() -> object:
- """生成测试数据库会话。"""
+ """
+ 生成测试数据库会话。
+
+ :yield: 测试数据库会话
+ """
yield fake_session
fake_registry = PluginRegistry.build([])
@@ -743,7 +782,11 @@ async def test_recover_plugin_dependency_errors_commits_and_reloads_registry() -
fake_session = AsyncMock()
async def fake_get_db() -> object:
- """生成测试数据库会话。"""
+ """
+ 生成测试数据库会话。
+
+ :yield: 测试数据库会话
+ """
yield fake_session
app = FastAPI()
@@ -877,12 +920,14 @@ def test_register_enabled_plugin_routers_uses_enabled_plugin_ids(tmp_path: Path)
)
class FakePluginRegistry:
- """
- 测试用插件运行时注册表。
- """
+ """测试用插件运行时注册表。"""
def list_enabled_plugins(self) -> list[MagicMock]:
- """获取启用插件列表。"""
+ """
+ 获取启用插件列表。
+
+ :return: 启用插件列表
+ """
return [
MagicMock(
plugin_id='demo',
@@ -938,12 +983,14 @@ def test_register_enabled_plugin_routers_skips_invalid_route_prefix(tmp_path: Pa
)
class FakePluginRegistry:
- """
- 测试用插件运行时注册表。
- """
+ """测试用插件运行时注册表。"""
def list_enabled_plugins(self) -> list[MagicMock]:
- """获取启用插件列表。"""
+ """
+ 获取启用插件列表。
+
+ :return: 启用插件列表
+ """
return [
MagicMock(
plugin_id='demo',
@@ -986,12 +1033,14 @@ def test_register_enabled_plugin_routers_skips_unrecognized_router_factory(tmp_p
)
class FakePluginRegistry:
- """
- 测试用插件运行时注册表。
- """
+ """测试用插件运行时注册表。"""
def list_enabled_plugins(self) -> list[MagicMock]:
- """获取启用插件列表。"""
+ """
+ 获取启用插件列表。
+
+ :return: 启用插件列表
+ """
return [
MagicMock(
plugin_id='demo',
@@ -1038,7 +1087,11 @@ async def test_install_enabled_plugin_resources_isolates_failed_plugin() -> None
fake_session = AsyncMock()
async def fake_get_db() -> object:
- """提供测试数据库会话生成器。"""
+ """
+ 提供测试数据库会话生成器。
+
+ :yield: 测试数据库会话生成器
+ """
yield fake_session
broken_plugin = MagicMock()
@@ -1077,7 +1130,11 @@ async def test_sync_default_enabled_builtin_plugins_isolates_install_failure() -
fake_session = AsyncMock()
async def fake_get_db() -> object:
- """提供测试数据库会话生成器。"""
+ """
+ 提供测试数据库会话生成器。
+
+ :yield: 测试数据库会话生成器
+ """
yield fake_session
broken_plugin = MagicMock()
@@ -1142,7 +1199,11 @@ async def test_mark_plugin_runtime_error_updates_database_and_rebuilds_registry(
fake_session = AsyncMock()
async def fake_get_db() -> object:
- """生成测试数据库会话。"""
+ """
+ 生成测试数据库会话。
+
+ :yield: 测试数据库会话
+ """
yield fake_session
app = FastAPI()
@@ -1169,7 +1230,11 @@ async def test_mark_plugin_runtime_error_upserts_discovered_plugin_when_missing(
fake_session = AsyncMock()
async def fake_get_db() -> object:
- """生成测试数据库会话。"""
+ """
+ 生成测试数据库会话。
+
+ :yield: 测试数据库会话
+ """
yield fake_session
app = FastAPI()
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_task_cleanup.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_task_cleanup.py
index bc47e3f56..f6b37055c 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_task_cleanup.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_task_cleanup.py
@@ -7,9 +7,11 @@
@pytest.mark.asyncio
async def test_batch_cancellation_releases_cooperative_tasks_and_ignores_caller() -> None:
+ """批量取消释放可协作的任务并跳过调用方。"""
stopped = []
async def work() -> None:
+ """模拟受清理流程管理的异步工作。"""
try:
await asyncio.Event().wait()
finally:
@@ -25,9 +27,15 @@ async def work() -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('cancel_waiter', [False, True])
async def test_uncooperative_task_is_retained_even_when_waiter_is_cancelled(cancel_waiter: bool) -> None:
+ """等待方被取消后仍跟踪未响应取消的任务。"""
opened, interrupted, release = (asyncio.Event() for _ in range(3))
async def work() -> None:
+ """
+ 模拟受清理流程管理的异步工作。
+
+ :raises ValueError: 模拟任务延迟报告失败
+ """
opened.set()
try:
await asyncio.Event().wait()
@@ -61,6 +69,7 @@ async def work() -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('grace_seconds', [0, -1, float('inf'), float('nan')])
async def test_invalid_timeout_is_rejected_before_any_cancellation(grace_seconds: float) -> None:
+ """取消任何任务前先拒绝无效超时。"""
task = asyncio.create_task(asyncio.sleep(10))
try:
with pytest.raises(ValueError, match='大于零'):
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/test_capability.py b/ruoyi-fastapi-backend/tests/plugins/core/test_capability.py
index e868482f7..00ad208ee 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/test_capability.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/test_capability.py
@@ -6,7 +6,12 @@
def build_discovered_plugin(*, with_frontend: bool = True) -> DiscoveredPlugin:
- """构建能力测试使用的已发现插件。"""
+ """
+ 构建能力测试使用的已发现插件。
+
+ :param with_frontend: 是否生成前端资源
+ :return: 能力测试使用的已发现插件
+ """
manifest_data: dict[str, object] = {
'id': 'demo',
'name': 'Demo',
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/test_frontend_layout.py b/ruoyi-fastapi-backend/tests/plugins/core/test_frontend_layout.py
index fcae9f574..b616b9053 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/test_frontend_layout.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/test_frontend_layout.py
@@ -18,7 +18,6 @@ def clear_frontend_environment(monkeypatch: pytest.MonkeyPatch) -> None:
清除前端路径与框架环境变量,避免本机配置影响测试。
:param monkeypatch: pytest 环境变量替换工具
- :return: None
"""
for name in (
'RUOYI_PLUGIN_FRONTEND_ROOT',
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_dependency_policy.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_dependency_policy.py
index dc67acbd5..7122039f9 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_dependency_policy.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_dependency_policy.py
@@ -15,12 +15,22 @@
def build_plan(*items: DependencyInstallPlanItem) -> DependencyInstallPlan:
- """构建测试用依赖安装计划。"""
+ """
+ 构建测试用依赖安装计划。
+
+ :param items: 调用方传入的其余位置参数
+ :return: 测试用依赖安装计划
+ """
return DependencyInstallPlan(plugin_id='demo', items=list(items))
def build_python_item(requirement: str = 'openai>=2.0.0') -> DependencyInstallPlanItem:
- """构建测试用 Python 安装计划项。"""
+ """
+ 构建测试用 Python 安装计划项。
+
+ :param requirement: 依赖声明,包括包名和版本约束
+ :return: 测试用 Python 安装计划项
+ """
return DependencyInstallPlanItem(
kind='python',
requirement=requirement,
@@ -37,7 +47,14 @@ def build_npm_item(
kind: str = 'npm',
name: str = 'dayjs',
) -> DependencyInstallPlanItem:
- """构建测试用 npm 安装计划项。"""
+ """
+ 构建测试用 npm 安装计划项。
+
+ :param requirement: 依赖声明,包括包名和版本约束
+ :param kind: 当前条目的类别
+ :param name: 用于查找或标识当前对象的名称
+ :return: 测试用 npm 安装计划项
+ """
return DependencyInstallPlanItem(
kind=kind,
requirement=requirement,
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest.py
index f78e83d0d..b112abca0 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest.py
@@ -9,7 +9,12 @@
def write_project_versions(backend_root: Path, frontend_root: Path) -> None:
- """写入测试项目版本文件。"""
+ """
+ 写入测试项目版本文件。
+
+ :param backend_root: 后端项目的根目录
+ :param frontend_root: 前端项目的根目录
+ """
backend_root.mkdir(parents=True)
frontend_root.mkdir(parents=True)
(backend_root / 'pyproject.toml').write_text('[project]\nversion = "1.10.0"\n', encoding='utf-8')
@@ -253,7 +258,13 @@ def test_manifest_checker_caches_resolved_node_version(tmp_path: Path, monkeypat
calls = []
def fake_run(*args: object, **kwargs: object) -> SimpleNamespace:
- """记录 node 版本命令调用。"""
+ """
+ 记录 node 版本命令调用。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: ``SimpleNamespace`` 实例
+ """
calls.append((args, kwargs))
return SimpleNamespace(returncode=0, stdout='v20.0.0\n')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest_v2.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest_v2.py
index d0a080d68..e41e90a69 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest_v2.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest_v2.py
@@ -13,6 +13,14 @@
def manifest_data(*, native: bool = False, asgi: bool = False, bundle: bool = False) -> dict:
+ """
+ 按后端类型准备插件清单字段。
+
+ :param native: 是否使用原生插件
+ :param asgi: 测试使用的 ASGI 应用
+ :param bundle: 打包后的前端资源
+ :return: 随调用传入或返回的结构化数据
+ """
module = 'ruoyi_plugin_demo' if native else 'plugins.demo'
backend = {'module': module, 'entrypoint': f'{module}.entry:create_plugin'}
if native:
@@ -32,6 +40,7 @@ def manifest_data(*, native: bool = False, asgi: bool = False, bundle: bool = Fa
@pytest.mark.parametrize('native', [False, True])
@pytest.mark.parametrize('asgi', [False, True])
def test_runtime_and_integration_are_independent(native: bool, asgi: bool) -> None:
+ """运行时配置与集成模式相互独立。"""
manifest = PluginManifestFactory.create(manifest_data(native=native, asgi=asgi))
assert isinstance(manifest, PluginManifestV2)
assert manifest.runtime_kind == ('native' if native else 'python')
@@ -42,6 +51,7 @@ def test_runtime_and_integration_are_independent(native: bool, asgi: bool) -> No
def test_v1_keeps_defaults_and_rejects_v2_fields() -> None:
+ """第一版配置保留默认值并拒绝第二版字段。"""
data = {'id': 'demo', 'name': 'Demo', 'version': '1', 'backend': {'module': 'plugins.demo'}}
manifest = PluginManifestFactory.create(data)
assert type(manifest) is PluginManifest
@@ -64,6 +74,7 @@ def test_v1_keeps_defaults_and_rejects_v2_fields() -> None:
],
)
def test_rejects_unsafe_or_conflicting_backend(field: str, value: object) -> None:
+ """拒绝不安全或冲突的后端配置。"""
payload = manifest_data(asgi=True)
payload['backend'][field] = value
with pytest.raises(ValueError):
@@ -71,6 +82,7 @@ def test_rejects_unsafe_or_conflicting_backend(field: str, value: object) -> Non
def test_asgi_cannot_start_resources_twice() -> None:
+ """ASGI 不能重复启动资源。"""
payload = manifest_data(asgi=True)
payload['backend']['hooks'] = {'onStartup': 'plugins.demo.entry:startup'}
with pytest.raises(ValueError, match='lifespan'):
@@ -79,6 +91,7 @@ def test_asgi_cannot_start_resources_twice() -> None:
@pytest.mark.parametrize('path', ['../dist', '/dist', 'C:/dist', 'web\\dist', 'web/../dist', 'web/./dist'])
def test_bundle_rejects_nonportable_or_escaping_paths(path: str) -> None:
+ """资源包拒绝不可移植或越界的路径。"""
payload = manifest_data(asgi=True, bundle=True)
payload['frontend']['bundle']['directory'] = path
with pytest.raises(ValueError, match='安全相对路径'):
@@ -86,6 +99,7 @@ def test_bundle_rejects_nonportable_or_escaping_paths(path: str) -> None:
def test_bundle_does_not_request_host_build_or_npm() -> None:
+ """资源包无需宿主构建或调用 npm。"""
payload = manifest_data(asgi=True, bundle=True)
manifest = PluginManifestFactory.create(payload)
assert manifest.frontend.delivery.type == 'bundle'
@@ -102,6 +116,7 @@ def test_bundle_does_not_request_host_build_or_npm() -> None:
def test_host_api_compatibility_is_enforced() -> None:
+ """执行宿主 API 的兼容性检查。"""
payload = manifest_data()
payload['compatibility'] = {'hostApiVersion': '>=2.0.0'}
result = PluginManifestChecker().check(PluginManifestFactory.create(payload))
@@ -110,6 +125,7 @@ def test_host_api_compatibility_is_enforced() -> None:
def test_discovery_and_structure_do_not_execute_entrypoint(tmp_path: Path) -> None:
+ """发现和结构校验均不执行插件入口。"""
root = tmp_path / 'plugins' / 'demo'
root.mkdir(parents=True)
(root / 'plugin.yaml').write_text(yaml.safe_dump(manifest_data()), encoding='utf-8')
@@ -122,6 +138,7 @@ def test_discovery_and_structure_do_not_execute_entrypoint(tmp_path: Path) -> No
def test_bundle_resources_are_checked_in_production(tmp_path: Path) -> None:
+ """生产环境检查资源包中的资源。"""
root = tmp_path / 'plugins' / 'demo'
root.mkdir(parents=True)
(root / 'plugin.yaml').write_text(yaml.safe_dump(manifest_data(asgi=True, bundle=True)), encoding='utf-8')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_menus.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_menus.py
index 56df1acb5..2daf9d33b 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_menus.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_menus.py
@@ -5,7 +5,13 @@
def write_manifest(plugin_dir: Path, content: str) -> Path:
- """写入测试插件清单。"""
+ """
+ 写入测试插件清单。
+
+ :param plugin_dir: 保存插件清单和资源的目录
+ :param content: 需要读取或写入的内容
+ :return: 供调用方使用的 ``manifest_path``
+ """
plugin_dir.mkdir(parents=True)
manifest_path = plugin_dir / 'plugin.yaml'
manifest_path.write_text(content, encoding='utf-8')
@@ -13,7 +19,13 @@ def write_manifest(plugin_dir: Path, content: str) -> Path:
def load_plugin(backend_root: Path, plugin_id: str) -> DiscoveredPlugin:
- """加载测试插件。"""
+ """
+ 加载测试插件。
+
+ :param backend_root: 后端项目的根目录
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 测试插件
+ """
return PluginScanner(backend_root / 'plugins').load_manifest(backend_root / 'plugins' / plugin_id / 'plugin.yaml')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_plugin_deps.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_plugin_deps.py
index befbfffe8..1dd98fe2b 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_plugin_deps.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_plugin_deps.py
@@ -15,7 +15,15 @@ def build_discovered_plugin(
version: str = '1.0.0',
dependencies: list[object] | None = None,
) -> DiscoveredPlugin:
- """构造测试用已发现插件。"""
+ """
+ 构造测试用已发现插件。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param plugin_id: 插件清单中的唯一标识
+ :param version: 当前记录的版本
+ :param dependencies: 执行当前步骤所需的依赖
+ :return: 测试用已发现插件
+ """
backend_path = tmp_path / 'plugins' / plugin_id
manifest_path = backend_path / 'plugin.yaml'
backend_path.mkdir(parents=True, exist_ok=True)
@@ -36,7 +44,15 @@ def build_discovered_plugin(
def build_database_plugin(
plugin_id: str, version: str, *, enabled: str = '0', status: str = 'installed'
) -> PluginModel:
- """构造测试用数据库插件状态。"""
+ """
+ 构造测试用数据库插件状态。
+
+ :param plugin_id: 插件清单中的唯一标识
+ :param version: 当前记录的版本
+ :param enabled: 是否启用该项功能
+ :param status: 操作或记录所处的状态
+ :return: 测试用数据库插件状态
+ """
return PluginModel(
pluginId=plugin_id,
pluginName=plugin_id,
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_structure.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_structure.py
index c7f24408c..23230f88f 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_structure.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_structure.py
@@ -8,7 +8,13 @@
def write_manifest(plugin_dir: Path, content: str) -> Path:
- """写入测试插件清单。"""
+ """
+ 写入测试插件清单。
+
+ :param plugin_dir: 保存插件清单和资源的目录
+ :param content: 需要读取或写入的内容
+ :return: 供调用方使用的 ``manifest_path``
+ """
plugin_dir.mkdir(parents=True)
manifest_path = plugin_dir / 'plugin.yaml'
manifest_path.write_text(content, encoding='utf-8')
@@ -16,7 +22,13 @@ def write_manifest(plugin_dir: Path, content: str) -> Path:
def load_discovered_plugin(backend_root: Path, plugin_id: str) -> DiscoveredPlugin:
- """加载测试插件。"""
+ """
+ 加载测试插件。
+
+ :param backend_root: 后端项目的根目录
+ :param plugin_id: 插件清单中的唯一标识
+ :return: 测试插件
+ """
return PluginScanner(backend_root / 'plugins').load_manifest(backend_root / 'plugins' / plugin_id / 'plugin.yaml')
@@ -348,6 +360,7 @@ def test_structure_checker_reports_missing_migration_and_unsupported_type(tmp_pa
def test_structure_checker_validates_plugin_migration_time_types(
tmp_path: Path, sql: str, expected_failures: list[str]
) -> None:
+ """结构检查器验证插件迁移的时间类型。"""
backend_root = tmp_path / 'ruoyi-fastapi-backend'
plugin_root = backend_root / 'plugins' / 'demo'
write_manifest(
diff --git a/ruoyi-fastapi-backend/tests/plugins/examples/test_task_demo.py b/ruoyi-fastapi-backend/tests/plugins/examples/test_task_demo.py
index 145b699ed..0fadccd89 100644
--- a/ruoyi-fastapi-backend/tests/plugins/examples/test_task_demo.py
+++ b/ruoyi-fastapi-backend/tests/plugins/examples/test_task_demo.py
@@ -32,13 +32,22 @@
@pytest.fixture(autouse=True)
def isolated_runtime(monkeypatch: pytest.MonkeyPatch) -> None:
- """每个用例恢复插件自身的工厂引用,不共享测试连接池。"""
+ """
+ 每个用例恢复插件自身的工厂引用,不共享测试连接池。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ """
monkeypatch.setattr(task_demo._runtime, 'session_factory', None)
@pytest_asyncio.fixture
async def task_host(tmp_path: Path) -> AsyncIterator[PluginHostContext]:
- """仅适配迁移中的时间类型后在 SQLite 执行,不代表 PostgreSQL 方言实测。"""
+ """
+ 仅适配迁移中的时间类型后在 SQLite 执行,不代表 PostgreSQL 方言实测。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :yield: ``PluginHostContext`` 实例
+ """
engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "tasks.db"}')
sessions = async_sessionmaker(engine, expire_on_commit=False)
try:
@@ -52,15 +61,34 @@ async def task_host(tmp_path: Path) -> AsyncIterator[PluginHostContext]:
def _context(host: PluginHostContext, permissions: frozenset[str] = frozenset({'*:*:*'})) -> PluginRequestContext:
- """构造测试专用可信身份;生产身份由宿主网关注入。"""
+ """
+ 构造测试专用可信身份;生产身份由宿主网关注入。
+
+ :param host: 宿主注入的能力集合;不保存当前用户或请求数据库会话
+ :param permissions: 当前调用允许使用的权限
+ :return: 测试专用可信身份
+ """
return PluginRequestContext(host=host, user=SimpleNamespace(user_id=1), permissions=permissions)
def _client(host: PluginHostContext, permissions: frozenset[str] = frozenset({'*:*:*'})) -> httpx.AsyncClient:
- """将可信上下文注入插件子应用,使用真实 SDK HTTP 适配器检查权限与输入。"""
+ """
+ 将可信上下文注入插件子应用,使用真实 SDK HTTP 适配器检查权限与输入。
+
+ :param host: 宿主注入的能力集合;不保存当前用户或请求数据库会话
+ :param permissions: 当前调用允许使用的权限
+ :return: ``httpx.AsyncClient`` 实例
+ """
child = create_plugin(host).app_factory(host)
async def authenticated_app(scope: dict[str, Any], receive: Any, send: Any) -> None:
+ """
+ 为插件请求注入已认证上下文后调用下游应用。
+
+ :param scope: 当前操作使用的作用域
+ :param receive: 读取下一条 ASGI 消息的异步回调
+ :param send: 发送 ASGI 消息的异步回调
+ """
scope.setdefault('state', {})['plugin_context'] = _context(host, permissions)
await child(scope, receive, send)
@@ -202,6 +230,12 @@ async def test_exception_after_insert_rolls_back(task_host: PluginHostContext, m
"""即使 SQL 已写入,响应构造失败也会回滚该次事务。"""
def broken_payload(row: Any) -> dict[str, Any]:
+ """
+ 模拟此操作抛出 RuntimeError 的情形。
+
+ :param row: 当前读取或写入的数据行
+ :raises RuntimeError: 模拟构造响应失败
+ """
raise RuntimeError('response construction failed')
monkeypatch.setattr(service, '_task_payload', broken_payload)
@@ -218,7 +252,17 @@ async def test_cancel_after_insert_rolls_back_and_closes_owned_session(task_host
closed = asyncio.Event()
class PausedSession(AsyncSession):
+ """在执行 SQL 时暂停以控制测试并发顺序。"""
+
async def execute(self, statement: Any, *args: Any, **kwargs: Any) -> Any:
+ """
+ 按测试场景处理数据库查询并提供结果。
+
+ :param statement: 即将执行的数据库语句
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 执行当前操作得到的结果
+ """
result = await super().execute(statement, *args, **kwargs)
if getattr(statement, 'is_insert', False):
inserted.set()
@@ -226,6 +270,7 @@ async def execute(self, statement: Any, *args: Any, **kwargs: Any) -> Any:
return result
async def close(self) -> None:
+ """记录测试资源的关闭过程。"""
await super().close()
closed.set()
@@ -248,25 +293,59 @@ async def close(self) -> None:
class MemoryMigrationHistory(PluginMigrationHistoryStore):
- """保留各次调用结果的测试历史存储,数据库 DDL 仍在真实 SQLite 执行。"""
+ """
+ 保留各次调用结果的测试历史存储,数据库 DDL 仍在真实 SQLite 执行。
+
+ :ivar records: 当前测试保存的记录
+ :ivar successes: 成功完成的操作记录
+ """
def __init__(self) -> None:
+ """初始化测试夹具的 ``records``, ``successes``。"""
self.records: dict[tuple[str, str], PluginMigrationHistoryRecord] = {}
self.successes: list[tuple[str, str, str]] = []
async def get_record(
self, query_db: Any, plugin_id: str, migration_path: str
) -> PluginMigrationHistoryRecord | None:
+ """
+ 将存储值解码为交互记录。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :return: 与交互标识对应的记录
+ """
return self.records.get((plugin_id, migration_path))
async def record_running(
self, query_db: Any, plugin_id: str, migration_path: str, checksum: str, version: str, statement_count: int
) -> None:
+ """
+ 保存正在运行的迁移记录。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :param checksum: 校验内容完整性使用的校验和
+ :param version: 当前记录的版本
+ :param statement_count: SQL 语句数量
+ """
self.records[plugin_id, migration_path] = PluginMigrationHistoryRecord(checksum=checksum, status='running')
async def record_success(
self, query_db: Any, plugin_id: str, migration_path: str, checksum: str, version: str, statement_count: int
) -> None:
+ """
+ 保存成功完成的迁移记录。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :param checksum: 校验内容完整性使用的校验和
+ :param version: 当前记录的版本
+ :param statement_count: SQL 语句数量
+ """
self.records[plugin_id, migration_path] = PluginMigrationHistoryRecord(checksum=checksum)
self.successes.append((plugin_id, migration_path, version))
@@ -280,6 +359,17 @@ async def record_failure(
statement_count: int,
error_message: str,
) -> None:
+ """
+ 保存迁移失败的测试记录。
+
+ :param query_db: 当前操作使用的异步数据库会话
+ :param plugin_id: 插件清单中的唯一标识
+ :param migration_path: migration 相对路径
+ :param checksum: 校验内容完整性使用的校验和
+ :param version: 当前记录的版本
+ :param statement_count: SQL 语句数量
+ :param error_message: 记录到结果或审计日志中的错误详情
+ """
self.records[plugin_id, migration_path] = PluginMigrationHistoryRecord(
checksum=checksum, status='failed', error_message=error_message
)
@@ -289,6 +379,14 @@ class SqliteMigrationSession(AsyncSession):
"""仅在 SQL 执行边界适配 SQLite 时间类型,runner 校验的原始文件内容保持不变。"""
async def execute(self, statement: Any, *args: Any, **kwargs: Any) -> Any:
+ """
+ 按测试场景处理数据库查询并提供结果。
+
+ :param statement: 即将执行的数据库语句
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 底层模拟会话的查询结果
+ """
if isinstance(statement, TextClause) and 'TIMESTAMP(3) WITH TIME ZONE' in statement.text:
statement = text(statement.text.replace('TIMESTAMP(3) WITH TIME ZONE', 'DATETIME'))
return await super().execute(statement, *args, **kwargs)
@@ -302,6 +400,15 @@ def test_time_columns_compile_to_repository_database_contract() -> None:
assert column.type.compile(dialect=postgresql.dialect()) == 'TIMESTAMP(3) WITH TIME ZONE'
+def _unavailable_sessions() -> None:
+ """
+ 在调用时报告预期的测试失败:query_db 应优先于插件保存的会话工厂。
+
+ :raises AssertionError: query_db 应优先于插件保存的会话工厂
+ """
+ raise AssertionError('query_db 应优先于插件保存的会话工厂')
+
+
@pytest.mark.asyncio
async def test_migration_upgrade_preserves_old_rows_and_history_skips_replay(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
@@ -356,10 +463,7 @@ async def test_migration_upgrade_preserves_old_rows_and_history_skips_replay(
assert len(history.successes) == expected_migrations
assert (await health(health_context))['ok'] is True
- def unavailable_sessions() -> None:
- raise AssertionError('query_db 应优先于插件保存的会话工厂')
-
- monkeypatch.setattr(task_demo._runtime, 'session_factory', unavailable_sessions)
+ monkeypatch.setattr(task_demo._runtime, 'session_factory', _unavailable_sessions)
async with sessions() as db:
assert (await health(replace(health_context, query_db=db)))['ok'] is True
async with _client(host) as client:
diff --git a/ruoyi-fastapi-backend/tests/plugins/integration/test_harness_safety.py b/ruoyi-fastapi-backend/tests/plugins/integration/test_harness_safety.py
index 2dacaca0d..20f2cfb81 100644
--- a/ruoyi-fastapi-backend/tests/plugins/integration/test_harness_safety.py
+++ b/ruoyi-fastapi-backend/tests/plugins/integration/test_harness_safety.py
@@ -18,6 +18,12 @@
@pytest.fixture
def run_spec(tmp_path: Path) -> harness.RunSpec:
+ """
+ 生成当前测试目录对应的运行配置。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :return: 当前测试目录对应的运行配置
+ """
return harness.RunSpec('mysql', '0123456789abcdef' * 2, str(tmp_path))
@@ -28,7 +34,6 @@ def built_task_bundle(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
:param tmp_path: pytest 临时目录
:param monkeypatch: 测试内属性替换工具
- :return: None
"""
backend = tmp_path / 'backend'
entry = backend / 'plugins' / 'examples' / 'python' / 'task_demo' / 'web' / 'dist' / 'index.html'
@@ -41,6 +46,7 @@ def built_task_bundle(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
def test_main_without_opt_in_never_opens_database_or_redis(
engine: str, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
+ """未显式启用时主程序不连接数据库或 Redis。"""
monkeypatch.delenv(harness.OPT_IN, raising=False)
database_engine = Mock(side_effect=AssertionError('Database access is forbidden'))
redis_client = Mock(side_effect=AssertionError('Redis access is forbidden'))
@@ -61,6 +67,7 @@ def test_main_without_opt_in_never_opens_database_or_redis(
def test_opt_in_requires_explicit_password_environment(
engine: str, password: str, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """显式启用时必须通过环境变量提供密码。"""
monkeypatch.setenv(harness.OPT_IN, '1')
monkeypatch.delenv(password, raising=False)
monkeypatch.delenv('RUOYI_IT_REDIS_PASSWORD', raising=False)
@@ -77,6 +84,7 @@ def test_opt_in_requires_explicit_password_environment(
def test_cli_wait_environment_targets_only_the_isolated_database_without_mutating_parent(
engine: str, run_spec: harness.RunSpec, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """等待命令仅使用隔离数据库且不修改父进程环境。"""
spec = harness.RunSpec(engine, run_spec.run_id, run_spec.root)
prefix = 'RUOYI_IT_MYSQL' if engine == 'mysql' else 'RUOYI_IT_PG'
monkeypatch.setenv(harness.OPT_IN, '1')
@@ -106,11 +114,13 @@ def test_cli_wait_environment_targets_only_the_isolated_database_without_mutatin
['', 'a' * 31, 'a' * 33, 'A' * 32, 'g' * 32, '../production', 'a' * 31 + ';', 'a' * 31 + "'", 'a' * 32 + '\n'],
)
def test_run_spec_rejects_unsafe_database_and_redis_identity(run_id: str, tmp_path: Path) -> None:
+ """运行规格拒绝不安全的数据库或 Redis 标识。"""
with pytest.raises(ValueError, match='identity'):
harness.RunSpec('mysql', run_id, str(tmp_path)).validate()
def test_run_spec_rejects_other_engine_or_relative_root(tmp_path: Path, run_spec: harness.RunSpec) -> None:
+ """运行规格拒绝其他引擎或相对根路径。"""
with pytest.raises(ValueError, match='identity'):
harness.RunSpec('sqlite', run_spec.run_id, str(tmp_path)).validate()
with pytest.raises(ValueError, match='absolute'):
@@ -124,11 +134,17 @@ def test_run_spec_rejects_other_engine_or_relative_root(tmp_path: Path, run_spec
async def test_prepare_schema_uses_initial_sql_without_drop_or_seed_data(
engine: str, initial_filename: str, run_spec: harness.RunSpec
) -> None:
+ """使用初始 SQL 准备结构且不删库或导入种子数据。"""
spec = harness.RunSpec(engine, run_spec.run_id, run_spec.root)
connection = SimpleNamespace(exec_driver_sql=AsyncMock(), execute=AsyncMock(return_value=SimpleNamespace(all=list)))
@asynccontextmanager
async def begin() -> AsyncGenerator[Any, None]:
+ """
+ 提供受测试状态控制的事务上下文。
+
+ :yield: 受测试状态控制的事务上下文
+ """
yield connection
await harness.prepare_schema(spec, SimpleNamespace(begin=begin))
@@ -174,6 +190,7 @@ async def begin() -> AsyncGenerator[Any, None]:
async def test_prepare_schema_rejects_incomplete_or_duplicate_host_ddl_before_execution(
invalid_schema: str, table_name: str, run_spec: harness.RunSpec, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """执行前拒绝不完整或重复的宿主建表语句。"""
initial_sql = (harness.BACKEND_ROOT / 'sql' / 'ruoyi-fastapi.sql').read_text('utf-8')
if invalid_schema == 'missing':
initial_sql = initial_sql.replace(f'{table_name} (', f'unused_{table_name} (')
@@ -196,11 +213,17 @@ async def test_prepare_schema_rejects_incomplete_or_duplicate_host_ddl_before_ex
async def test_database_ddl_only_addresses_validated_run_database(
engine: str, quote: str, run_spec: harness.RunSpec
) -> None:
+ """数据库 DDL 仅操作已校验的本次运行数据库。"""
spec = harness.RunSpec(engine, run_spec.run_id, run_spec.root)
connection = SimpleNamespace(exec_driver_sql=AsyncMock())
@asynccontextmanager
async def connect() -> AsyncGenerator[Any, None]:
+ """
+ 在上下文内提供测试连接。
+
+ :yield: 当前操作使用的连接
+ """
yield connection
admin = SimpleNamespace(connect=Mock(side_effect=connect))
@@ -225,6 +248,7 @@ async def connect() -> AsyncGenerator[Any, None]:
async def test_run_drops_database_only_after_successful_create(
created: bool, run_spec: harness.RunSpec, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """仅清理本次成功创建的数据库。"""
admin = SimpleNamespace(dispose=AsyncMock())
engine = SimpleNamespace(dispose=AsyncMock())
factory = Mock(side_effect=[admin, engine])
@@ -260,6 +284,7 @@ async def test_run_drops_database_only_after_successful_create(
async def test_run_continues_owned_cleanup_after_engine_dispose_error(
run_spec: harness.RunSpec, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """释放引擎失败后仍继续清理自有资源。"""
admin = SimpleNamespace(dispose=AsyncMock())
engine = SimpleNamespace(dispose=AsyncMock(side_effect=RuntimeError('engine disposal failed')))
clear = AsyncMock(return_value=0)
@@ -290,18 +315,31 @@ async def test_run_continues_owned_cleanup_after_engine_dispose_error(
async def test_redis_cleanup_scans_and_deletes_only_its_run_prefix(
run_spec: harness.RunSpec, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """Redis 清理只扫描和删除本次运行前缀。"""
own_keys = {f'{run_spec.redis_prefix}ready:generation', f'{run_spec.redis_prefix}lifecycle:global'}
foreign_keys = {'plugin:lifecycle:lock:global', f'ruoyi_plugin_it:{"f" * 32}:ready:generation'}
keys = own_keys | foreign_keys
scans = []
async def scan_iter(**kwargs: Any) -> AsyncIterator[str]:
+ """
+ 逐个返回匹配模式的缓存键。
+
+ :param kwargs: 传给被调用对象的关键字参数
+ :yield: 匹配模式的缓存键
+ """
scans.append(kwargs['match'])
for key in sorted(keys):
if fnmatchcase(key, kwargs['match']):
yield key
async def delete(key: str) -> int:
+ """
+ 删除测试缓存项及其过期状态。
+
+ :param key: 查找数据时使用的键
+ :return: 此分支的固定值 ``1``
+ """
keys.remove(key)
return 1
@@ -319,7 +357,15 @@ async def delete(key: str) -> int:
async def test_redis_cleanup_refuses_foreign_key_even_if_scan_returns_it(
run_spec: harness.RunSpec, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """即使扫描返回其他键也拒绝删除。"""
+
async def scan_iter(**kwargs: Any) -> AsyncIterator[str]:
+ """
+ 逐个返回匹配模式的缓存键。
+
+ :param kwargs: 传给被调用对象的关键字参数
+ :yield: 此分支的固定值 ``'plugin:lifecycle:lock:global'``
+ """
yield 'plugin:lifecycle:lock:global'
client = SimpleNamespace(scan_iter=scan_iter, delete=AsyncMock(), aclose=AsyncMock())
@@ -331,6 +377,7 @@ async def scan_iter(**kwargs: Any) -> AsyncIterator[str]:
def test_safe_error_redacts_explicit_credentials_and_bounds_output(monkeypatch: pytest.MonkeyPatch) -> None:
+ """错误输出隐藏显式凭据并限制长度。"""
password = 'db-password-unique-92ab'
secret = 'redis-secret-unique-57ef'
monkeypatch.setenv('RUOYI_IT_MYSQL_PASSWORD', password)
@@ -347,6 +394,7 @@ def test_safe_error_redacts_explicit_credentials_and_bounds_output(monkeypatch:
def test_workers_pass_independent_stop_events_to_spawned_processes(
run_spec: harness.RunSpec, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """每个派生工作进程使用独立的停止事件。"""
events = [SimpleNamespace(set=Mock()), SimpleNamespace(set=Mock())]
queue = SimpleNamespace(close=Mock(), join_thread=Mock())
context = SimpleNamespace(
@@ -373,6 +421,7 @@ def test_workers_pass_independent_stop_events_to_spawned_processes(
@pytest.mark.asyncio
@pytest.mark.parametrize('second_state', ['killed', 'dead'])
async def test_workers_close_skips_killed_or_dead_stop_event_but_stops_healthy_worker(second_state: str) -> None:
+ """关闭时跳过已终止进程的事件并停止健康进程。"""
healthy_stop = SimpleNamespace(set=Mock())
unusable_stop = SimpleNamespace(set=Mock(side_effect=AssertionError('Terminated waiter poisoned this event')))
healthy = SimpleNamespace(pid=101, exitcode=0, is_alive=Mock(return_value=True), terminate=Mock())
@@ -384,10 +433,20 @@ async def test_workers_close_skips_killed_or_dead_stop_event_but_stops_healthy_w
)
def join_healthy(timeout: float) -> None:
+ """
+ 模拟健康工作线程正常停止。
+
+ :param timeout: 等待操作完成的超时限制
+ """
healthy_stop.set.assert_called_once()
healthy.is_alive.return_value = False
def join_second(timeout: float) -> None:
+ """
+ 标记第二个工作线程已退出。
+
+ :param timeout: 等待操作完成的超时限制
+ """
second.is_alive.return_value = False
healthy.join = Mock(side_effect=join_healthy)
@@ -411,13 +470,21 @@ def join_second(timeout: float) -> None:
def _wait_for_isolated_stop(stop: Any, ready: Any, index: int) -> None:
- """子进程入口不导入应用模块,也不访问外部服务。"""
+ """
+ 子进程入口不导入应用模块,也不访问外部服务。
+
+ :param stop: 通知正在运行的任务停止的信号
+ :param ready: 依赖检查是否已就绪
+ :param index: 当前条目在序列中的位置
+ :raises RuntimeError: 隔离的停止事件等待超过安全时限
+ """
ready.put(index)
if not stop.wait(30):
raise RuntimeError('Offline event waiter exceeded its safety timeout')
def test_real_spawn_terminated_waiter_does_not_block_other_worker_shutdown() -> None:
+ """实际派生的等待进程被终止后不阻塞其他进程关闭。"""
context = harness.multiprocessing.get_context('spawn')
workers = harness.Workers.__new__(harness.Workers)
workers.stops = [context.Event(), context.Event()]
@@ -430,10 +497,12 @@ def test_real_spawn_terminated_waiter_does_not_block_other_worker_shutdown() ->
failures: list[BaseException] = []
async def stop_group() -> None:
+ """停止工作进程组并等待清理。"""
await workers.kill_failed_worker()
await workers.close()
def close_in_guarded_thread() -> None:
+ """在线程内执行关闭操作并记录结果。"""
try:
asyncio.run(stop_group())
except BaseException as exc:
@@ -472,6 +541,7 @@ def close_in_guarded_thread() -> None:
async def test_run_requires_built_bundle_before_opening_any_resource(
tmp_path: Path, run_spec: harness.RunSpec, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """运行前确认资源包已构建才打开外部资源。"""
monkeypatch.setattr(harness, 'BACKEND_ROOT', tmp_path / 'unbuilt-backend')
configure = Mock(side_effect=AssertionError('Configuration must remain untouched'))
factory = Mock(side_effect=AssertionError('Database access is forbidden'))
diff --git a/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py b/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py
index cc05ffac4..85572d4e4 100644
--- a/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py
+++ b/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py
@@ -37,7 +37,12 @@
def frontend_root() -> Path:
- """选择本次验收的真实 Web 工程,明确拒绝尚无对应宿主的框架。"""
+ """
+ 选择本次验收的真实 Web 工程,明确拒绝尚无对应宿主的框架。
+
+ :raises ValueError: 插件网络验收仅支持 RUOYI_PLUGIN_FRONTEND_FRAMEWORK=vue2、vue3 或 react
+ :return: 当前框架的真实前端工程目录
+ """
framework = os.environ.get('RUOYI_PLUGIN_FRONTEND_FRAMEWORK', 'vue3').strip().lower()
if framework not in {'vue2', 'vue3', 'react'}:
raise ValueError('插件网络验收仅支持 RUOYI_PLUGIN_FRONTEND_FRAMEWORK=vue2、vue3 或 react')
@@ -50,7 +55,7 @@ async def wait_until(predicate: Callable[[], bool], wait_seconds: float = 15) ->
:param predicate: 待满足的状态条件
:param wait_seconds: 最长等待秒数
- :return: None
+ :raises TimeoutError: 网络验收等待状态超时
"""
loop = asyncio.get_running_loop()
deadline = loop.time() + wait_seconds
@@ -95,7 +100,6 @@ def prepare_network_host(fixture: SimpleNamespace) -> None:
为现有隔离鉴权夹具添加宿主导航与真实插件流端点。
:param fixture: 使用生产门禁及会话协议的隔离运行时
- :return: None
"""
app = fixture.app
loaded = fixture.runtime.loaded['browser_test']
@@ -107,13 +111,23 @@ def prepare_network_host(fixture: SimpleNamespace) -> None:
@loaded.lifespan.app.websocket('/ws/events')
async def events(websocket: WebSocket) -> None:
+ """
+ 接受插件事件连接并处理测试消息。
+
+ :param websocket: 当前 WebSocket 连接
+ """
websocket.state.plugin_context.require_permission('browser_test:view')
await websocket.accept()
await websocket.send_text('connected')
await websocket.receive_text()
- @app.get('/getInfo')
+ @app.get('/getInfo', summary='读取验收用户资料', description='返回网络验收账号的用户资料及权限。')
async def info() -> dict[str, Any]:
+ """
+ 返回含 ``code``, ``user``, ``roles``, ``permissions`` 等字段 的测试数据。
+
+ :return: 含 ``code``, ``user``, ``roles``, ``permissions`` 等字段 的测试数据
+ """
return {
'code': 200,
'user': {
@@ -129,8 +143,13 @@ async def info() -> dict[str, Any]:
'appTimezone': 'Asia/Shanghai',
}
- @app.get('/getRouters')
+ @app.get('/getRouters', summary='读取验收导航菜单', description='返回用于验证插件页面访问的宿主路由树。')
async def routers() -> dict[str, Any]:
+ """
+ 返回含 ``code``, ``data`` 的测试数据。
+
+ :return: 含 ``code``, ``data`` 的测试数据
+ """
return {
'code': 200,
'data': [
@@ -149,8 +168,17 @@ async def routers() -> dict[str, Any]:
],
}
- @app.get('/transport/crypto/frontend-config')
+ @app.get(
+ '/transport/crypto/frontend-config',
+ summary='读取前端传输加密策略',
+ description='返回验收环境使用的传输加密配置。',
+ )
async def crypto_policy() -> dict[str, Any]:
+ """
+ 返回含 ``code``, ``data`` 的测试数据。
+
+ :return: 含 ``code``, ``data`` 的测试数据
+ """
return {
'code': 200,
'data': {
@@ -161,12 +189,25 @@ async def crypto_policy() -> dict[str, Any]:
},
}
- @app.get('/system/config/configKey/{key}')
+ @app.get(
+ '/system/config/configKey/{key}', summary='按键读取验收配置', description='模拟按配置键查询系统参数的响应。'
+ )
async def config(key: str) -> dict[str, Any]:
+ """
+ 返回含 ``code``, ``msg`` 的测试数据。
+
+ :param key: 查找数据时使用的键
+ :return: 含 ``code``, ``msg`` 的测试数据
+ """
return {'code': 200, 'msg': '30'}
- @app.get('/system/notice/listTop')
+ @app.get('/system/notice/listTop', summary='读取置顶通知', description='返回验收环境的置顶通知列表。')
async def notices() -> dict[str, Any]:
+ """
+ 返回含 ``code``, ``data`` 的测试数据。
+
+ :return: 含 ``code``, ``data`` 的测试数据
+ """
return {'code': 200, 'data': []}
@@ -178,7 +219,8 @@ async def network_servers(fixture: SimpleNamespace, directory: Path, output: Pat
:param fixture: 隔离宿主应用
:param directory: 证书及就绪文件目录
:param output: 诊断日志目录
- :return: 代理 HTTPS 来源地址
+ :yield: 代理 HTTPS 来源地址
+ :raises AssertionError: 前端代理服务启动失败
"""
frontend = frontend_root()
cert_path, key_path = certificate_files(directory)
@@ -256,7 +298,6 @@ async def open_socket(page: Any, origin: str) -> None:
:param page: 宿主浏览器页面
:param origin: HTTPS 代理来源
- :return: None
"""
await page.evaluate(
"""url => new Promise((resolve, reject) => {
@@ -327,7 +368,6 @@ async def start_browser_streams(page: Any, frame: Any, origin: str) -> None:
:param page: 宿主浏览器页面
:param frame: 已连接的插件 iframe 定位器
:param origin: HTTPS 代理地址
- :return: None
"""
await frame.locator('#reset').click()
await frame.locator('#start').click()
@@ -343,7 +383,6 @@ async def verify_browser_streams(fixture: SimpleNamespace, page: Any, frame: Any
:param page: 宿主浏览器页面
:param frame: 已连接的插件 iframe 定位器
:param origin: HTTPS 代理地址
- :return: None
"""
loaded = fixture.runtime.loaded['browser_test']
connections = loaded.gateway.connections.connections
@@ -393,7 +432,7 @@ async def verify_browser(fixture: SimpleNamespace, origin: str, output: Path) ->
:param fixture: 隔离宿主运行时和可控账号状态
:param origin: HTTPS 代理地址
:param output: 失败截图与 Playwright trace 目录
- :return: None
+ :raises BaseException: 执行中断,清理后向调用方传播原异常
"""
async with async_playwright() as playwright:
executable = os.environ.get('RUOYI_SMOKE_BROWSER_EXECUTABLE')
diff --git a/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke_runner.py b/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke_runner.py
index d6d6031af..947ccce3e 100644
--- a/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke_runner.py
+++ b/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke_runner.py
@@ -19,6 +19,11 @@ async def test_network_cleanup_preserves_original_failure(
stopping = asyncio.Event()
async def serve(**kwargs: object) -> None:
+ """
+ 将测试服务标记为就绪并等待停止。
+
+ :param kwargs: 传给被调用对象的关键字参数
+ """
server.started = True
await stopping.wait()
@@ -26,6 +31,13 @@ async def serve(**kwargs: object) -> None:
monkeypatch.setattr(smoke.uvicorn, 'Server', lambda config: server)
async def start_frontend(*args: object, **kwargs: object) -> SimpleNamespace:
+ """
+ 按测试场景模拟前端启动结果。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: ``SimpleNamespace`` 实例
+ """
if failure == 'startup':
kwargs['stdout'].write("Cannot find module 'memory-fs'\n")
else:
diff --git a/ruoyi-fastapi-backend/tests/plugins/native/test_native_bundle_build.py b/ruoyi-fastapi-backend/tests/plugins/native/test_native_bundle_build.py
index e39299dc1..b33d3a970 100644
--- a/ruoyi-fastapi-backend/tests/plugins/native/test_native_bundle_build.py
+++ b/ruoyi-fastapi-backend/tests/plugins/native/test_native_bundle_build.py
@@ -13,6 +13,12 @@
@pytest.fixture
def source(tmp_path: Path) -> Path:
+ """
+ 创建构建原生插件所需的源目录。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :return: 构建原生插件所需的源目录
+ """
root = tmp_path / 'native_bundle'
(root / 'web' / 'dist' / 'assets').mkdir(parents=True)
(root / 'web' / 'dist' / 'index.html').write_text('', encoding='utf-8')
@@ -25,6 +31,12 @@ def source(tmp_path: Path) -> Path:
def manifest(**overrides: object) -> PluginManifest:
+ """
+ 构建原生插件包使用的测试清单。
+
+ :param overrides: 调用方按名称传入的附加选项
+ :return: 原生插件包使用的测试清单
+ """
data = {
'manifestVersion': 2,
'id': 'native_bundle',
@@ -44,6 +56,7 @@ def manifest(**overrides: object) -> PluginManifest:
def test_collects_only_built_bundle_and_declared_resource_directories(source: Path, tmp_path: Path) -> None:
+ """仅收集构建后的包及声明的资源目录。"""
migrations = source / 'migrations' / 'mysql'
migrations.mkdir(parents=True)
(migrations / '001_init.sql').write_text('SELECT 1;', encoding='utf-8')
@@ -62,6 +75,7 @@ def test_collects_only_built_bundle_and_declared_resource_directories(source: Pa
def test_missing_bundle_entry_fails_before_compilation(
source: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """编译前报告缺失的资源包入口。"""
(source / 'web' / 'dist' / 'index.html').unlink()
(source / 'plugin.yaml').write_text(yaml.safe_dump(manifest().model_dump(by_alias=True)), encoding='utf-8')
output = tmp_path / 'output'
@@ -76,6 +90,7 @@ def test_missing_bundle_entry_fails_before_compilation(
@pytest.mark.parametrize('name', ['.env.production', 'package.json', 'secret.rs', 'src/private.ts'])
def test_rejects_development_or_secret_files_in_dist(source: Path, tmp_path: Path, name: str) -> None:
+ """发行目录拒绝开发文件和秘密文件。"""
path = source / 'web' / 'dist' / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('not a deployment asset', encoding='utf-8')
@@ -84,11 +99,13 @@ def test_rejects_development_or_secret_files_in_dist(source: Path, tmp_path: Pat
def test_rejects_output_inside_bundle(source: Path) -> None:
+ """拒绝将输出目录置于资源包内。"""
with pytest.raises(ValueError, match='输出目录'):
build_native_plugin.collect_deployment_resources(source, manifest(), source / 'web' / 'dist' / 'package')
def test_rejects_hardlinked_assets(source: Path, tmp_path: Path) -> None:
+ """拒绝带硬链接的资源。"""
external = tmp_path / 'private.txt'
external.write_text('private', encoding='utf-8')
os.link(external, source / 'web' / 'dist' / 'private.txt')
@@ -99,6 +116,7 @@ def test_rejects_hardlinked_assets(source: Path, tmp_path: Path) -> None:
def test_rejects_reparse_points_before_descending(
source: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """遍历子目录前拒绝重解析点。"""
original = package.is_link_or_reparse
resource = source / 'web' / 'dist' / 'assets'
inode = resource.lstat().st_ino
@@ -109,6 +127,7 @@ def test_rejects_reparse_points_before_descending(
@pytest.mark.parametrize('relative', ['plugin.yaml', 'native/data.json'])
def test_resources_cannot_overwrite_manifest_or_native_package(source: Path, tmp_path: Path, relative: str) -> None:
+ """资源不能覆盖清单或原生包。"""
path = source / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('reserved', encoding='utf-8')
diff --git a/ruoyi-fastapi-backend/tests/plugins/native/test_rust_demo.py b/ruoyi-fastapi-backend/tests/plugins/native/test_rust_demo.py
index 53f7faf56..ed54cce95 100644
--- a/ruoyi-fastapi-backend/tests/plugins/native/test_rust_demo.py
+++ b/ruoyi-fastapi-backend/tests/plugins/native/test_rust_demo.py
@@ -43,12 +43,18 @@
@pytest.fixture(scope='module')
def plugin() -> DiscoveredPlugin:
+ """
+ 加载测试所需的插件及其清单。
+
+ :return: 测试所需的插件及其清单
+ """
root = Path(PLUGIN_DIRECTORY).resolve()
assert (root / 'plugin.yaml').is_file(), '指定的 Rust 交付目录不存在'
return PluginScanner(root.parent).load_manifest(root / 'plugin.yaml')
def test_distribution_contains_native_business_code_and_passes_static_discovery(plugin: DiscoveredPlugin) -> None:
+ """发行包包含原生业务代码并通过静态发现。"""
check = PluginStructureChecker(plugin.backend_path.parents[1]).check(plugin, include_frontend=False)
assert check.ok, check.failed_items
files = [path for path in plugin.backend_path.rglob('*') if path.is_file()]
@@ -64,6 +70,7 @@ def test_distribution_contains_native_business_code_and_passes_static_discovery(
@pytest.mark.asyncio
async def test_compiled_native_health_returns_rust_future(plugin: DiscoveredPlugin) -> None:
+ """编译后的原生健康检查返回 Rust Future。"""
loader = PluginEntrypointLoader(plugin)
callback = loader.load_callable(plugin.manifest.backend.health.checker)
assert not inspect.iscoroutinefunction(callback)
@@ -73,11 +80,17 @@ async def test_compiled_native_health_returns_rust_future(plugin: DiscoveredPlug
@asynccontextmanager
async def fake_session() -> AsyncGenerator[object, None]:
+ """
+ 为上下文提供受控的测试会话。
+
+ :yield: 上下文内使用的受控测试会话
+ """
yield object()
@pytest.mark.asyncio
async def test_real_native_subapp_uses_host_auth_lifespan_and_python_service(plugin: DiscoveredPlugin) -> None:
+ """真实原生子应用使用宿主认证、生命周期和 Python 服务。"""
app = FastAPI()
gateway = SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True))
runtime = ExplicitPluginRuntime(gateway)
@@ -136,12 +149,18 @@ async def test_real_native_subapp_uses_host_auth_lifespan_and_python_service(plu
@pytest.mark.asyncio
async def test_native_python_coroutine_bridge_keeps_context_and_cancellation(plugin: DiscoveredPlugin) -> None:
+ """原生与 Python 协程桥接保留上下文及取消语义。"""
trace = ContextVar('native_test_trace', default='missing')
started = asyncio.Event()
closed = asyncio.Event()
loop = asyncio.get_running_loop()
async def service(context: PluginRequestContext) -> None:
+ """
+ 检查宿主服务回调的事件循环及请求上下文。
+
+ :param context: 由宿主鉴权层建立的请求身份,不能由客户端字段直接构造
+ """
assert asyncio.get_running_loop() is loop
assert trace.get() == 'current-request'
started.set()
@@ -167,7 +186,15 @@ async def service(context: PluginRequestContext) -> None:
@pytest.mark.asyncio
async def test_native_python_service_exception_propagates(plugin: DiscoveredPlugin) -> None:
+ """原生调用传播 Python 服务异常。"""
+
async def failed_service(context: PluginRequestContext) -> None:
+ """
+ 模拟此操作抛出 ValueError 的情形。
+
+ :param context: 由宿主鉴权层建立的请求身份,不能由客户端字段直接构造
+ :raises ValueError: 模拟宿主服务调用失败
+ """
raise ValueError('host-service-failed')
host = PluginHostContext('rust_demo', plugin.backend_path, services={'users.current_profile.v1': failed_service})
@@ -179,6 +206,7 @@ async def failed_service(context: PluginRequestContext) -> None:
@pytest.mark.asyncio
async def test_real_native_router_gets_host_context_and_permissions(plugin: DiscoveredPlugin) -> None:
+ """真实原生路由获取宿主上下文及权限。"""
manifest = plugin.manifest.model_copy(deep=True)
manifest.backend.integration = 'router'
manifest.backend.asgi = None
@@ -190,10 +218,21 @@ async def test_real_native_router_gets_host_context_and_permissions(plugin: Disc
user = SimpleNamespace(user=SimpleNamespace(user_id=7), permissions=['rust_demo:view', 'rust_demo:profile'])
async def login(token: str = Depends(oauth2_scheme)) -> object:
+ """
+ 校验测试令牌并提供已登录用户。
+
+ :param token: 用于身份验证或授权的令牌
+ :return: 当前操作对应的用户
+ """
assert token == 'test-token'
return user
async def session() -> AsyncIterator[object]:
+ """
+ 为当前测试操作提供数据库会话。
+
+ :yield: 数据库会话
+ """
yield object()
app.dependency_overrides[LoginService.get_current_user] = login
@@ -201,6 +240,13 @@ async def session() -> AsyncIterator[object]:
@app.exception_handler(PermissionException)
async def permission_error(request: object, exc: PermissionException) -> JSONResponse:
+ """
+ 创建测试使用的 ``JSONResponse`` 实例。
+
+ :param request: 当前 HTTP 请求
+ :param exc: 捕获到的异常实例
+ :return: 测试使用的 ``JSONResponse`` 实例
+ """
return JSONResponse({'detail': exc.message}, status_code=status.HTTP_403_FORBIDDEN)
with patch('plugins.core.runtime.explicit.DataSourceRegistry.session', fake_session):
@@ -231,6 +277,7 @@ async def permission_error(request: object, exc: PermissionException) -> JSONRes
@pytest.mark.asyncio
async def test_real_scheduler_invokes_rust_awaitable_through_persistent_dispatcher(plugin: DiscoveredPlugin) -> None:
+ """真实调度器通过持久化分派器等待 Rust 结果。"""
app = FastAPI()
gateway = SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True))
runtime = ExplicitPluginRuntime(gateway)
@@ -238,6 +285,11 @@ async def test_real_scheduler_invokes_rust_awaitable_through_persistent_dispatch
completed = asyncio.get_running_loop().create_future()
def on_execution(event: object) -> None:
+ """
+ 将任务执行结果交给等待的测试。
+
+ :param event: 待处理的事件
+ """
if not completed.done():
completed.set_result(event)
diff --git a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/conftest.py b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/conftest.py
index 00c02bbab..02c88d143 100644
--- a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/conftest.py
+++ b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/conftest.py
@@ -9,7 +9,11 @@
@pytest.fixture
def ai_catalog() -> Iterator[None]:
- """为直接调用 AI 服务的测试加载与已启用插件相同的词库。"""
+ """
+ 为直接调用 AI 服务的测试加载与已启用插件相同的词库。
+
+ :yield: 上下文就绪后将控制权交给调用方
+ """
compile_catalogs()
CatalogRegistry.register_plugin('ai', Path(__file__).resolve().parents[3] / 'plugins/ai')
try:
diff --git a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_i18n.py b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_i18n.py
index f85607be9..80bf122e4 100644
--- a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_i18n.py
+++ b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_i18n.py
@@ -42,6 +42,14 @@ async def test_stream_error_uses_captured_locale_after_request_context_changes()
"""验证请求语言改变后,流式错误仍使用创建时的快照。"""
async def broken_stream(*args: object, **kwargs: object) -> AsyncIterator[object]:
+ """
+ 模拟读取模型响应流期间发生错误。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :raises RuntimeError: 模型提供方内部错误
+ :yield: 上下文就绪后将控制权交给调用方
+ """
raise RuntimeError('模型提供方内部错误')
yield
diff --git a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_plugin.py b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_plugin.py
index 90ae4291a..90cd6c0f7 100644
--- a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_plugin.py
+++ b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_plugin.py
@@ -149,7 +149,12 @@ async def test_ai_chat_config_detail_returns_vo_when_config_missing(monkeypatch:
"""校验 AI 对话配置不存在时服务返回 VO 默认模型,而不是 DO 对象。"""
async def fake_get_chat_config_detail_by_user_id(*_args: object, **_kwargs: object) -> None:
- """返回测试用 AI 聊天配置。"""
+ """
+ 返回测试用 AI 聊天配置。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ """
monkeypatch.setattr(
AiChatConfigDao,
@@ -169,7 +174,12 @@ async def test_ai_chat_services_rejects_missing_model(monkeypatch: pytest.Monkey
"""校验 AI 对话在模型不存在时返回带消息标识的错误事件。"""
async def fake_get_ai_model_detail_by_id(*_args: object, **_kwargs: object) -> None:
- """返回测试用 AI 模型配置。"""
+ """
+ 返回测试用 AI 模型配置。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ """
monkeypatch.setattr(AiModelDao, 'get_ai_model_detail_by_id', fake_get_ai_model_detail_by_id)
@@ -196,7 +206,13 @@ async def test_ai_chat_services_rejects_disabled_model(monkeypatch: pytest.Monke
"""校验 AI 对话不能使用已停用模型。"""
async def fake_get_ai_model_detail_by_id(*_args: object, **_kwargs: object) -> dict[str, object]:
- """返回测试用 AI 模型配置。"""
+ """
+ 返回测试用 AI 模型配置。
+
+ :param _args: 调用方传入的其余位置参数
+ :param _kwargs: 调用方按名称传入的附加选项
+ :return: 测试用 AI 模型配置
+ """
return {
'model_id': 1,
'model_code': 'gpt-4o-mini',
@@ -233,14 +249,26 @@ def test_ai_model_factory_rejects_unknown_provider(monkeypatch: pytest.MonkeyPat
class FakeModel:
"""
测试用模型类。
+
+ :ivar kwargs: 传给被调用对象的关键字参数
"""
def __init__(self, **kwargs: object) -> None:
- """初始化测试用 AI 模型提供者。"""
+ """
+ 初始化测试用 AI 模型提供者。
+
+ :param kwargs: 传给被调用对象的关键字参数
+ """
self.kwargs = kwargs
def fake_resolve_provider_class(cls: type[AiUtil], provider: str) -> type[FakeModel] | None:
- """返回测试用 AI 模型提供者类。"""
+ """
+ 返回测试用 AI 模型提供者类。
+
+ :param cls: 调用类方法时使用的类对象
+ :param provider: 提供当前服务的实现
+ :return: 测试用 AI 模型提供者类
+ """
return FakeModel if provider == 'OpenAI' else None
monkeypatch.setattr(AiUtil, '_resolve_provider_class', classmethod(fake_resolve_provider_class))
diff --git a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_react_integration.py b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_react_integration.py
index 5769906f9..f0f2e6ca2 100644
--- a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_react_integration.py
+++ b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_react_integration.py
@@ -28,7 +28,11 @@
def load_ai_manifest() -> 'PluginManifest':
- """加载实际 AI 插件清单,避免用测试清单掩盖发布遗漏。"""
+ """
+ 加载实际 AI 插件清单,避免用测试清单掩盖发布遗漏。
+
+ :return: 实际 AI 插件清单
+ """
return (
PluginScanner(BACKEND_ROOT / 'plugins').load_manifest(BACKEND_ROOT / 'plugins' / 'ai' / 'plugin.yaml').manifest
)
@@ -86,7 +90,13 @@ class FakeAgent:
"""离线流式 Agent,不请求模型或数据库。"""
async def arun(self, message: str, **kwargs) -> 'AsyncIterator[SimpleNamespace]':
- """逐段返回测试模型事件。"""
+ """
+ 逐段返回测试模型事件。
+
+ :param message: 与当前结果一起返回的说明
+ :param kwargs: 传给被调用对象的关键字参数
+ :yield: 逐项产生的 ``chunk``
+ """
assert message == '你好'
assert kwargs == {'stream': True, 'stream_events': True}
for chunk in chunks:
diff --git a/ruoyi-fastapi-backend/tests/redis_helpers.py b/ruoyi-fastapi-backend/tests/redis_helpers.py
index c49e4e7f9..54156076b 100644
--- a/ruoyi-fastapi-backend/tests/redis_helpers.py
+++ b/ruoyi-fastapi-backend/tests/redis_helpers.py
@@ -1,7 +1,3 @@
-"""
-供测试使用的独立 Redis 进程和跨版本到期时间查询
-"""
-
import os
import secrets
import shutil
@@ -32,7 +28,11 @@
@dataclass(frozen=True)
class IsolatedRedisServer:
"""
- 保存测试子进程和 Redis 标识,防止清空其他实例
+ 保存测试子进程和 Redis 标识,防止清空其他实例。
+
+ :ivar process: 本次测试创建的子进程
+ :ivar connection: 当前操作使用的连接
+ :ivar run_id: 任务ID
"""
process: subprocess.Popen
@@ -41,10 +41,10 @@ class IsolatedRedisServer:
async def reset_database(self, client: Redis) -> None:
"""
- 确认测试子进程存活且实例标识一致后清空测试库
+ 确认测试子进程存活且实例标识一致后清空测试库。
:param client: 测试实例的 Redis 客户端
- :return: None
+ :raises RuntimeError: 隔离进程已退出或实例身份改变,无法安全重置数据库
"""
if self.process.poll() is not None:
raise RuntimeError('Isolated Redis process has exited; refusing to clear a database')
@@ -56,9 +56,10 @@ async def reset_database(self, client: Redis) -> None:
def redis_server_executable() -> str | None:
"""
- 查找显式指定或 PATH 中的测试 Redis 程序,不读取应用配置
+ 查找显式指定或 PATH 中的测试 Redis 程序,不读取应用配置。
:return: Redis 程序路径,未找到时返回 None
+ :raises ValueError: 环境变量指定的 Redis 服务端文件不可执行
"""
configured = os.environ.get('RUOYI_TEST_REDIS_SERVER')
executable = shutil.which(configured or 'redis-server')
@@ -69,9 +70,10 @@ def redis_server_executable() -> str | None:
def available_loopback_port() -> int:
"""
- 由操作系统分配空闲 TCP 端口,排除 Redis 默认端口
+ 由操作系统分配空闲 TCP 端口,排除 Redis 默认端口。
:return: 可用于回环连接的端口
+ :raises RuntimeError: 为隔离测试分配到了 Redis 默认端口
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
listener.bind(('127.0.0.1', 0))
@@ -83,10 +85,9 @@ def available_loopback_port() -> int:
def stop_redis_process(process: subprocess.Popen) -> None:
"""
- 回收测试子进程,超时后强制结束并等待退出
+ 回收测试子进程,超时后强制结束并等待退出。
:param process: 本次测试创建的子进程
- :return: None
"""
if process.poll() is not None:
return
@@ -101,10 +102,11 @@ def stop_redis_process(process: subprocess.Popen) -> None:
@contextmanager
def isolated_redis_server(executable: str) -> Iterator[IsolatedRedisServer]:
"""
- 启动隔离 Redis,Linux 使用临时套接字,Windows 使用动态回环端口
+ 启动隔离 Redis,Linux 使用临时套接字,Windows 使用动态回环端口。
:param executable: Redis 程序路径
- :return: 使用随机密码的测试实例
+ :yield: 使用随机密码的测试实例
+ :raises RuntimeError: 隔离的 Redis 服务未启动、未提供身份或未及时就绪
"""
windows = os.name == 'nt'
with tempfile.TemporaryDirectory(prefix='user-cache-', dir=None if windows else '/tmp') as directory:
@@ -168,7 +170,7 @@ def isolated_redis_server(executable: str) -> Iterator[IsolatedRedisServer]:
async def absolute_expiry_ms(client: Redis, key: str) -> int:
"""
- 原子读取绝对到期时刻,兼容 Redis 6.2
+ 原子读取绝对到期时刻,兼容 Redis 6.2。
:param client: Redis 客户端
:param key: 待查询的缓存键
diff --git a/ruoyi-fastapi-backend/tests/scheduler_helpers.py b/ruoyi-fastapi-backend/tests/scheduler_helpers.py
index 3c0258be5..b3533acca 100644
--- a/ruoyi-fastapi-backend/tests/scheduler_helpers.py
+++ b/ruoyi-fastapi-backend/tests/scheduler_helpers.py
@@ -41,10 +41,9 @@
def init_execution_process(database_url: str) -> None:
"""
- 子进程只使用测试库,禁止回退到项目开发数据源
+ 子进程只使用测试库,禁止回退到项目开发数据源。
:param database_url: 隔离测试数据库连接地址
- :return: None
"""
engine = create_engine(database_url)
JobExecutionStore.session = staticmethod(lambda: Session(engine, expire_on_commit=False))
@@ -52,10 +51,11 @@ def init_execution_process(database_url: str) -> None:
def held_process_job(directory: str) -> int:
"""
- 通过临时文件协调真实进程任务,带超时避免失败后遗留任务
+ 通过临时文件协调真实进程任务,带超时避免失败后遗留任务。
:param directory: 进程测试使用的临时目录
:return: 执行任务的进程ID
+ :raises TimeoutError: 等待测试释放进程任务超时
"""
Path(directory, 'started.json').write_text(json.dumps({'pid': os.getpid()}), encoding='utf-8')
deadline = time.monotonic() + 20
@@ -68,7 +68,7 @@ def held_process_job(directory: str) -> int:
def claim_in_process(execution_id: str, job: dict) -> bool:
"""
- 不同进程同时尝试占用同一任务,保留占用供父进程断言
+ 不同进程同时尝试占用同一任务,保留占用供父进程断言。
:param execution_id: 执行ID
:param job: 任务对象信息
@@ -79,7 +79,7 @@ def claim_in_process(execution_id: str, job: dict) -> bool:
def harmless_job(value: str = 'done') -> str:
"""
- 隔离测试任务,只记录调用并返回参数
+ 隔离测试任务,只记录调用并返回参数。
:param value: 用于记录调用和返回的测试参数
:return: 任务输入参数
@@ -89,11 +89,7 @@ def harmless_job(value: str = 'done') -> str:
async def held_job() -> None:
- """
- 保持一次异步执行,用于验证手动与 Cron 共享并发上限
-
- :return: None
- """
+ """保持一次异步执行,用于验证手动与 Cron 共享并发上限。"""
CALLS.append('held')
STARTED.set()
await RELEASE.wait()
@@ -101,7 +97,7 @@ async def held_job() -> None:
def job_info(**changes) -> JobModel:
"""
- 构造使用未来 Cron 的无业务副作用任务
+ 构造使用未来 Cron 的无业务副作用任务。
:param changes: 需要覆盖的任务字段
:return: 测试任务对象
@@ -127,7 +123,13 @@ def job_info(**changes) -> JobModel:
@dataclass
class Runtime:
"""
- 使用文件 SQLite 和真实 APScheduler 的隔离测试环境
+ 使用文件 SQLite 和真实 APScheduler 的隔离测试环境。
+
+ :ivar engine: 隔离测试数据库引擎
+ :ivar sessions: 异步数据库会话工厂
+ :ivar scheduler: 隔离测试调度器
+ :ivar started: 是否已经完成启动
+ :ivar release: 释放资源或同步等待的信号
"""
engine: Engine
@@ -138,7 +140,7 @@ class Runtime:
async def save(self, job: JobModel | None = None) -> JobModel:
"""
- 保存测试定义和初始同步状态
+ 保存测试定义和初始同步状态。
:param job: 任务对象信息
:return: 已保存的任务对象
@@ -152,7 +154,7 @@ async def save(self, job: JobModel | None = None) -> JobModel:
async def execution(self, execution_id: str) -> dict:
"""
- 读取当前执行状态
+ 读取当前执行状态。
:param execution_id: 执行ID
:return: 当前执行状态
@@ -163,11 +165,12 @@ async def execution(self, execution_id: str) -> dict:
async def wait_execution(self, execution_id: str, expected: set[str]) -> dict:
"""
- 等待执行进入预期状态,失败时打印最后观察到的状态
+ 等待执行进入预期状态,失败时打印最后观察到的状态。
:param execution_id: 执行ID
:param expected: 预期的执行状态集合
:return: 符合预期的执行状态
+ :raises AssertionError: 截止时间内没有观察到预期执行状态
"""
deadline = asyncio.get_running_loop().time() + 5
while asyncio.get_running_loop().time() < deadline:
@@ -181,11 +184,11 @@ async def wait_execution(self, execution_id: str, expected: set[str]) -> dict:
@pytest_asyncio.fixture
async def runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[Runtime]:
"""
- 只访问临时 SQLite,调度器执行日志不会连接开发数据库
+ 只访问临时 SQLite,调度器执行日志不会连接开发数据库。
:param tmp_path: 临时目录
:param monkeypatch: 测试替换对象
- :return: 隔离测试运行环境
+ :yield: 隔离测试运行环境
"""
global STARTED, RELEASE
STARTED, RELEASE = asyncio.Event(), asyncio.Event()
@@ -202,12 +205,11 @@ async def runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncItera
def assign_sqlite_id(_mapper: object, connection: object, target: SysJob) -> None:
"""
- 为 SQLite 测试模拟真实 MySQL/PostgreSQL 的数据库任务 ID 分配
+ 为 SQLite 测试模拟真实 MySQL/PostgreSQL 的数据库任务 ID 分配。
:param _mapper: 任务模型映射器
:param connection: 数据库连接
:param target: 任务模型实例
- :return: None
"""
if target.job_id is None:
target.job_id = connection.scalar(select(func.coalesce(func.max(SysJob.job_id), 0) + 1))
@@ -242,11 +244,10 @@ def assign_sqlite_id(_mapper: object, connection: object, target: SysJob) -> Non
def patch_scheduler_components(monkeypatch: pytest.MonkeyPatch, scheduler: AsyncIOScheduler) -> None:
"""
- 为隔离调度器创建完整的功能类实例及依赖关系
+ 为隔离调度器创建完整的功能类实例及依赖关系。
:param monkeypatch: 测试替换对象
:param scheduler: 隔离测试调度器
- :return: None
"""
resources = SchedulerResources()
jobs = SchedulerJobs(scheduler)
@@ -268,13 +269,12 @@ def patch_runtime_globals(
engine: Engine,
) -> None:
"""
- 隔离调度器单例和数据库工厂,测试结束由 monkeypatch 逐项恢复
+ 隔离调度器单例和数据库工厂,测试结束由 monkeypatch 逐项恢复。
:param monkeypatch: 测试替换对象
:param scheduler: 隔离测试调度器
:param sessions: 异步数据库会话工厂
:param engine: 隔离测试数据库引擎
- :return: None
"""
monkeypatch.setattr(task_module, 'runtime_harmless', harmless_job, raising=False)
monkeypatch.setattr(task_module, 'runtime_held', held_job, raising=False)
diff --git a/ruoyi-fastapi-backend/tests/scripts/test_check_docstrings.py b/ruoyi-fastapi-backend/tests/scripts/test_check_docstrings.py
new file mode 100644
index 000000000..f94c4e237
--- /dev/null
+++ b/ruoyi-fastapi-backend/tests/scripts/test_check_docstrings.py
@@ -0,0 +1,537 @@
+import ast
+import json
+import subprocess
+import sys
+from collections.abc import Callable, Iterator
+from pathlib import Path
+from textwrap import indent
+
+import pytest
+
+from scripts.check_docstrings import (
+ ALEMBIC_ENV,
+ ROUTER_MODULE,
+ comment_language,
+ header_comments,
+ sphinx_settings,
+ violations,
+)
+
+
+@pytest.fixture(scope='module')
+def check() -> Iterator[Callable[..., list[tuple[int, str]]]]:
+ """
+ 为源码样例提供共享的 Sphinx 检查环境。
+
+ :yield: 逐项产生的 ``parse``
+ """
+ with sphinx_settings() as settings:
+
+ def parse(source: str, path: Path = Path('sample.py')) -> list[tuple[int, str]]:
+ """
+ 收集样例源码的文件头与 docstring 诊断。
+
+ :param source: 要检查的 Python 源码
+ :param path: 源文件的位置,用于匹配路径规则和解析本地导入
+ :return: 样例源码的文件头与 docstring 诊断
+ """
+ tree = ast.parse(source)
+ return [*header_comments(source), *comment_language(source, tree, path), *violations(tree, settings, path)]
+
+ yield parse
+
+
+@pytest.mark.parametrize(
+ 'body',
+ [
+ 'Args:\n value: 输入值',
+ 'Parameters\n----------\nvalue : int\n 输入值',
+ ':param value: 输入值\n\nReturns:\n int',
+ ':parma value: 输入值',
+ ':param typo: 输入值',
+ ':param value 缺少结束冒号',
+ ':param : 缺少参数名',
+ ':raises: 缺少异常类型',
+ '@param value: 输入值',
+ '## 示例',
+ '```python\nprint(1)\n```',
+ '[说明](https://example.com)',
+ ':yield value: 数据块',
+ ':ytype: bytes',
+ ':return:',
+ ':param value:',
+ ':type int value: int',
+ ':param int or str value: 输入值',
+ '.. invalid-directive::',
+ '.. code-block:: python\n :unknown-option:\n\n print(1)',
+ '调用 :py:met:`str.strip`。',
+ '未闭合的 **strong 标记。',
+ '请使用``convert``转换。',
+ ],
+)
+def test_rejects_non_rest_and_invalid_fields(body: str, check: Callable) -> None:
+ """拒绝非 reST 标记和无效字段。"""
+ source = 'async def convert(value):\n """\n 转换输入。\n\n' + indent(body, ' ') + '\n """'
+ assert any('缺少 :param 描述' not in error for _, error in check(source))
+
+
+@pytest.mark.parametrize('prefix', ['class Example:\n', 'def example():\n', 'async def example():\n'])
+def test_checks_each_docstring_owner(prefix: str, check: Callable) -> None:
+ """逐一校验类、同步函数和异步函数的文档。"""
+ doc = '"""示例。\n\nArgs:\n value: 输入值\n"""'
+ source = prefix + indent(doc, ' ')
+ assert (4, '章节 Args: 请改用 reST 字段或指令') in check(source)
+
+
+@pytest.mark.parametrize(
+ ('body', 'line'),
+ [
+ ('Parameters\n----------\nvalue : int\n 输入值', 4),
+ ('.. note::\n\n Args:\n value: 输入值', 6),
+ (':param value: 输入值\n未缩进的说明。\n:return: 转换结果', 6),
+ ],
+)
+def test_reports_source_line_for_misplaced_markup(body: str, line: int, check: Callable) -> None:
+ """标记放错位置时报告实际源码行号。"""
+ source = 'def example(value):\n' + indent('"""说明。\n\n' + body + '\n"""', ' ')
+ assert line in [lineno for lineno, _ in check(source)]
+
+
+def test_allows_rest_fields_roles_and_examples(check: Callable) -> None:
+ """接受合法的 reST 字段、角色和示例。"""
+ source = '''
+def convert(value, /, *items, flag=True, **options):
+ """
+ 转换输入。
+
+ :param int value: 输入值
+ 此行继续说明该参数。
+ :param items: 其余输入值
+ :param flag: 转换开关
+ :param options: 扩展选项
+ :keyword mode: 通过 options 传入的模式
+ :type mode: str or None
+ :return: 转换结果
+ :rtype: str
+ :raises ValueError: 输入无效
+ :meta private:
+
+ :py:meth:`str.strip` 处理的示例::
+
+ Args:
+ :parma name: 示例文本
+
+ .. code-block:: python
+ :linenos:
+
+ print("Parameters")
+
+ >>> print("Args:")
+ Args:
+
+ 链接写法见 `说明 `_。字面文本为 ``[说明](https://example.com)``。
+ """
+ template = """Args:
+ value: 普通字符串
+ """
+'''
+ assert not check(source)
+
+
+def test_checks_summary_punctuation_and_constructor_signature(check: Callable) -> None:
+ """校验摘要标点和构造函数签名。"""
+ assert check('def example():\n """缺少句号"""') == [(2, '请以句末标点结束文档摘要')]
+ source = 'class Example:\n """示例。\n\n :param typo: 输入\n """\n def __init__(self, value):\n """保存输入值。"""'
+ assert check(source) == [(4, '文档参数 typo 不在函数签名中'), (7, '参数 value 缺少 :param 描述')]
+
+
+def test_file_header_boundary(check: Callable) -> None:
+ """验证文件头边界,并保留解释器声明和代码内部注释。"""
+ assert [line for line, _ in check('\n# 说明\n"""模块文档。"""\n')] == [2, 3]
+ assert check('#!/usr/bin/env python3\n# coding: utf-8\nimport os # 行尾注释\n# 内部注释') == []
+ assert check('# 说明') and check('#!/usr/bin/env python3\n\n# coding: utf-8')
+ assert check('description = """普通字符串。"""') == []
+
+
+def test_missing_private_nested_and_async_docs(check: Callable) -> None:
+ """检查类、特殊方法、私有函数和嵌套异步函数的覆盖范围。"""
+ source = 'class _Type:\n def __init__(self):\n async def _inner(): pass\n\ndef _helper(): pass'
+ assert sorted(line for line, _ in check(source)) == [1, 2, 3, 5]
+
+
+def test_overload_uses_implementation_documentation(check: Callable) -> None:
+ """验证类型重载共用实现文档,并要求实现存在。"""
+ stub = 'from typing import overload as signature\n@signature\ndef f(x: int) -> int: ...\n'
+ assert check(stub)
+ assert check(stub + 'def f(x): pass') == [(4, 'f 缺少 Sphinx/reST docstring')]
+ assert not check(
+ stub + 'def f(x):\n """\n 返回输入值。\n\n :param x: 输入值\n :return: 原值\n """\n return x'
+ )
+
+
+def test_requires_parameter_descriptions(check: Callable) -> None:
+ """验证各类显式参数必须有描述,类型字段和代码块不能代替参数说明。"""
+ source = '''
+class Factory:
+ """示例工厂。"""
+
+ @staticmethod
+ async def create(self, /, *items, mode, **options):
+ """
+ 创建示例。
+
+ :type self: str
+ :param items: 位置参数
+ :keyword mode: 创建模式
+ :keyword timeout: 超时秒数
+
+ 示例::
+
+ :param options: 仅用于展示
+ """
+'''
+ assert {message for _, message in check(source)} == {'参数 self 缺少 :param 描述', '参数 options 缺少 :param 描述'}
+
+
+def test_requires_class_and_instance_attribute_descriptions(check: Callable) -> None:
+ """验证声明、解包赋值和实例属性的覆盖,排除局部变量与其他对象的属性。"""
+ source = '''
+class Result:
+ """结果。
+
+ :cvar version: 格式版本
+ :ivar count: 记录数
+ :vartype _active: bool
+ """
+
+ version = 1
+ count: int
+ def __init__(self):
+ """初始化状态。"""
+ self.count, self._active = 0, True
+ local = self
+ local.foreign = 1
+'''
+ assert [message for _, message in check(source)] == ['属性 _active 缺少 :ivar 或 :cvar 描述']
+ slots = 'class Record:\n """一条记录。\n\n :ivar name: 名称\n """\n __slots__ = ("name", "count")'
+ assert [message for _, message in check(slots)] == ['属性 count 缺少 :ivar 或 :cvar 描述']
+
+
+def test_model_exemption_follows_imports_without_running_model_code(tmp_path: Path, check: Callable) -> None:
+ """验证单文件检查能沿导入和别名识别模型,同时检查普通类和模型方法。"""
+ (tmp_path / 'base_types.py').write_text(
+ 'from pydantic import BaseModel as Schema\nfrom sqlalchemy.orm import registry\n'
+ 'mapper = registry()\nOrm = mapper.generate_base()\nclass Payload(Schema): pass\n'
+ 'raise RuntimeError("source only")\n',
+ encoding='utf-8',
+ )
+ source = '''
+import base_types as bases
+from base_types import Orm
+class Child(bases.Payload):
+ """载荷。"""
+ value: int
+ def normalize(self, scale):
+ """转换数值。"""
+class Table(Orm):
+ """数据表。"""
+ field = 1
+class BaseModel:
+ """普通同名类。"""
+ flag: bool
+'''
+ errors = check(source, tmp_path / 'models.py')
+ assert {message for _, message in errors} == {
+ '属性 flag 缺少 :ivar 或 :cvar 描述',
+ '参数 scale 缺少 :param 描述',
+ 'Child.value 必须填写含中文的 description',
+ }
+
+
+def test_pydantic_fields_require_descriptions(check: Callable) -> None:
+ """校验有效的字段说明,覆盖别名、类型元数据、计算字段及类变量。"""
+ source = '''
+from typing import Annotated, ClassVar as Shared
+from pydantic import BaseModel, Field as F, computed_field
+from pydantic_settings import BaseSettings
+LABEL = '项目名称'
+EMPTY = ' '
+Label = Annotated[str, F(description=LABEL)]
+class Options(BaseSettings):
+ """应用配置。"""
+ model_config = {}
+ _private: str
+ shared: 'Shared[int]' = 1
+ label: Label
+ deferred: 'Label'
+ limited: Label = F(min_length=1)
+ bare: int
+ blank: str = F(description=EMPTY)
+ english: str = F(description='English only')
+ cleared: Label = F(description=None)
+ items: list[Annotated[str, F(description=LABEL)]]
+class Payload(BaseModel):
+ """模型载荷。"""
+ @computed_field
+ @property
+ def total(self):
+ """统计总量。"""
+ @computed_field(description='有效数量')
+ @property
+ def count(self):
+ """统计有效数量。"""
+'''
+ errors = {msg for _, msg in check(source)}
+ assert errors == {
+ *(f'Options.{name} 必须填写含中文的 description' for name in ('bare', 'blank', 'english', 'cleared', 'items')),
+ 'Payload.total 必须填写含中文的 description',
+ }
+
+
+def test_sqlalchemy_columns_require_comments(check: Callable) -> None:
+ """检查实际映射列、复用类型和显式表定义,仅对关系属性免除列说明。"""
+ source = '''
+import sqlalchemy as sa
+from sqlalchemy.orm import DeclarativeBase, Mapped, declared_attr, mapped_column as col, relationship
+from typing import Annotated
+Key = Annotated[int, col(comment='记录标识')]
+standalone = sa.Table('log', metadata, sa.Column('event', sa.String))
+class Record(DeclarativeBase):
+ """映射记录。"""
+ id: Mapped[Key] = col(primary_key=True)
+ name = sa.Column(sa.String, doc='名称')
+ score: Mapped[int]
+ parent: Mapped['Record'] = relationship()
+ size: Mapped[int] = col(comment='')
+class Other(DeclarativeBase):
+ """显式数据表。"""
+ __table__ = sa.Table('other', metadata, sa.Column('id', sa.Integer))
+class Mix:
+ """声明列的混入类。"""
+ @declared_attr
+ def stamp(cls):
+ """
+ 创建时间列。
+
+ :return: 时间列
+ """
+ return col()
+'''
+ messages = {msg for _, msg in check(source)}
+ assert messages == {
+ *(f'Record.{name} 必须填写含中文的 comment' for name in ('name', 'score', 'size')),
+ 'other.id 必须填写含中文的 comment',
+ 'log.event 必须填写含中文的 comment',
+ 'Mix.stamp 必须填写含中文的 comment',
+ }
+
+
+def test_routes_and_test_functions_have_distinct_requirements(tmp_path: Path, check: Callable) -> None:
+ """验证装饰器、显式注册及 pytest 例外的边界。"""
+ source = '''
+from fastapi import APIRouter as Router
+api = Router()
+@api.get('/items', summary='查询条目', description='按条件列出匹配的条目。')
+def items(value): pass
+def detail(key): pass
+api.add_api_route('/detail', endpoint=detail, summary='查询详情', description='按键返回条目详情。')
+def test_items(client):
+ """测试列表路由。"""
+def test_detail(client): pass
+def build(key):
+ """生成测试数据。"""
+@cache.get('/else')
+def ordinary(key): pass
+'''
+ errors = check(source, tmp_path / 'test_routes.py')
+ assert {message for _, message in errors} == {
+ 'test_detail 缺少 Sphinx/reST docstring',
+ 'ordinary 缺少 Sphinx/reST docstring',
+ '参数 key 缺少 :param 描述',
+ }
+
+
+def test_every_http_registration_requires_chinese_summary_and_description(check: Callable) -> None:
+ """验证同一端点的每次注册、隐藏操作和外部回调各自声明中文元数据。"""
+ source = '''
+from fastapi import APIRouter as Router
+from elsewhere import handler
+router = Router()
+api = router
+EMPTY = ' '
+DOCS = {'summary': '查询事项', 'description': '返回全部事项。'}
+@api.get('/ok', **DOCS)
+@api.post('/other', summary='新增事项')
+def items():
+ """处理事项。"""
+@router.api_route('/hidden', methods=['GET'], include_in_schema=False, summary=None, description=EMPTY)
+def hidden(): pass
+router.add_api_route('/external', endpoint=handler, summary='English only', description='返回状态。')
+router.add_api_route('/wrapped', plugin_endpoint(handler), summary='查询状态')
+@api.websocket('/ws')
+def events(socket): pass
+api.add_route('/docs', handler, include_in_schema=False)
+'''
+ assert check(source) == [
+ (9, 'HTTP 路由必须填写含中文的 description'),
+ (12, 'HTTP 路由必须填写含中文的 summary'),
+ (12, 'HTTP 路由必须填写含中文的 description'),
+ (14, 'HTTP 路由必须填写含中文的 summary'),
+ (15, 'HTTP 路由必须填写含中文的 description'),
+ ]
+
+
+def test_programmatic_routes_and_factory_router_share_the_http_rules(check: Callable) -> None:
+ """验证直接注册路径操作对象及通过工厂取得的路由器都逐条检查。"""
+ source = '''
+from fastapi import APIRouter
+from fastapi.routing import APIRoute as Operation
+def make_router() -> APIRouter:
+ """
+ 创建路由器。
+
+ :return: 应用路由器
+ """
+ return APIRouter()
+router = make_router()
+def handler(): pass
+routes = [Operation('/one', handler, summary='读取记录')]
+router.get('/two', description='读取单条记录。')(handler)
+'''
+ assert [message for _, message in check(source)] == [
+ 'HTTP 路由必须填写含中文的 description',
+ 'HTTP 路由必须填写含中文的 summary',
+ ]
+
+
+def test_preserves_alembic_and_only_the_original_router_class(check: Callable) -> None:
+ """验证特例按源文件和类定位,同一文件的其他定义继续受检。"""
+ source = 'class APIRouterPro:\n def __init__(self): pass\nclass RouterRegister: pass'
+ assert not check(source, ALEMBIC_ENV)
+ assert check(source, ROUTER_MODULE) == [(3, 'RouterRegister 缺少 Sphinx/reST docstring')]
+
+
+def test_generator_documents_each_observable_outcome(check: Callable) -> None:
+ """生成器应分别说明生成值、最终返回值和传给调用方的异常。"""
+ source = '''
+def stream(value):
+ """
+ 生成输入项。
+
+ :param value: 待处理的值
+ """
+ try:
+ if value is None:
+ raise KeyError()
+ except LookupError:
+ return
+ if value < 0:
+ raise ValueError()
+ yield value
+ return value + 1
+'''
+ assert {message for _, message in check(source)} == {
+ '缺少 :yield: 描述',
+ '缺少 :return: 描述',
+ '缺少 :raises ValueError: 描述',
+ }
+ documented = source.replace(
+ '待处理的值', '待处理的值\n :yields: 输入项\n :returns: 下一项\n :raises ValueError: 输入为负数'
+ )
+ assert not check(documented)
+
+
+def test_async_generator_and_reraised_exception(check: Callable) -> None:
+ """异步生成器记录生成值及重新抛出的异常,嵌套函数单独校验。"""
+ source = '''
+async def stream():
+ """提供数据。"""
+ def helper():
+ """返回输入值。
+
+ :return: 固定的整数
+ """
+ return 1
+ try:
+ yield helper()
+ except OSError as exc:
+ raise exc
+'''
+ assert {message for _, message in check(source)} == {'缺少 :yield: 描述', '缺少 :raises OSError: 描述'}
+ assert not check('def finish():\n """结束会话。"""\n return None')
+
+
+def test_test_functions_only_describe_intent(check: Callable) -> None:
+ """测试用例拒绝普通函数可用的参数字段和返回值字段。"""
+ source = (
+ 'def test_value(x):\n """\n 检查数值。\n\n :param x: 输入值\n :return: 数值\n """\n return x'
+ )
+ assert not check(source)
+ assert check(source, Path('test_value.py')) == [(3, '测试函数只写测试意图,请移除接口字段')]
+ assert not check('def test_value(x):\n """检查数值。"""', Path('test_value.py'))
+ fixture = 'from pytest import fixture as resource\n@resource()\n' + source
+ assert not check(fixture, Path('test_value.py'))
+
+
+def test_chinese_prose_and_class_field_overlap(check: Callable) -> None:
+ """中英文可混用,英文段落、字段描述、普通注释及重复属性说明会被识别。"""
+ source = 'class Item:\n """保存 ID。\n\n :param id: 标识\n :ivar id: Identifier\n """\n id: int'
+ errors = [message for _, message in check(source)]
+ assert any('字段须用中文' in message for message in errors)
+ assert any('重复使用参数和属性字段' in message for message in errors)
+ assert check('def read():\n """Read ID."""')
+ assert check('def read():\n """读取 ID。\n\n English prose.\n """')
+ assert check('value = 1 # Accept input.')
+ assert not check('value = 1 # 接受 ID\nvalue = 2 # noqa: F841')
+
+
+@pytest.mark.parametrize('directory', ['ruoyi-fastapi-backend', 'ruoyi-fastapi-test', '.github'])
+def test_ruff_requires_all_multiline_summaries_on_second_line(directory: str) -> None:
+ """三处 Ruff 配置均拒绝多行摘要紧接引号,并接受单行摘要及正确换行的文档。"""
+ config = ROUTER_MODULE.parents[2] / directory / 'ruff.toml'
+ source = '''
+class Example:
+ """类说明。
+
+ 更多说明。
+ """
+
+ def read(self) -> int:
+ """读取条数。
+
+ :return: 条数
+ """
+ return 1
+
+async def stream():
+ """生成数据。
+
+ :yield: 数据块
+ """
+ yield 1
+
+def test_value():
+ """验证输入。
+
+ 说明测试场景。
+ """
+
+def single():
+ """单行摘要。"""
+
+def correctly_wrapped():
+ """
+ 正确的多行摘要。
+
+ 附加说明。
+ """
+'''
+ run = subprocess.run(
+ [sys.executable, '-m', 'ruff', 'check', '--config', str(config), '--output-format=json', '--no-cache', '-'],
+ input=source,
+ capture_output=True,
+ encoding='utf-8',
+ check=False,
+ )
+ diagnostics = json.loads(run.stdout)
+ assert [item['location']['row'] for item in diagnostics if item['code'] == 'D213'] == [3, 9, 16, 23]
diff --git a/ruoyi-fastapi-backend/tests/scripts/test_migrate_job_fields.py b/ruoyi-fastapi-backend/tests/scripts/test_migrate_job_fields.py
index 2e29b484e..de379730c 100644
--- a/ruoyi-fastapi-backend/tests/scripts/test_migrate_job_fields.py
+++ b/ruoyi-fastapi-backend/tests/scripts/test_migrate_job_fields.py
@@ -27,6 +27,7 @@
],
)
def test_legacy_args_keep_the_old_execution_meaning(value: str | None, expected: list) -> None:
+ """旧版参数保留原执行语义。"""
assert parse_legacy_args(value) == expected
@@ -39,6 +40,7 @@ def test_policy_migration_fixes_discard_and_preserves_other_choices(
concurrent: str,
limit: int,
) -> None:
+ """策略迁移修正丢弃策略并保留其他选择。"""
values = convert_configuration({'misfire_policy': policy, 'concurrent': concurrent, 'job_group': 'redis'})
assert values['misfire_grace_time'] == grace
assert values['coalesce'] is coalesce
@@ -48,11 +50,13 @@ def test_policy_migration_fixes_discard_and_preserves_other_choices(
@pytest.mark.parametrize('kwargs', ['[1]', '{broken', 'null', 'true', '{"value": NaN}'])
def test_invalid_definition_parameters_require_repair_before_migration(kwargs: str) -> None:
+ """迁移前必须修复无效定义参数。"""
with pytest.raises(ValueError):
convert_configuration({'job_kwargs': kwargs})
def test_preflight_rejects_duplicate_identity_or_names_without_mutating() -> None:
+ """预检拒绝重复身份或名称且不修改数据。"""
engine = create_engine('sqlite://')
with engine.begin() as connection:
connection.exec_driver_sql(
@@ -76,6 +80,7 @@ def test_preflight_rejects_duplicate_identity_or_names_without_mutating() -> Non
def test_pending_snapshot_is_converted_without_changing_original_data() -> None:
+ """转换待处理快照时保留原数据。"""
original = {
'jobId': 42,
'jobGroup': 'sqlalchemy',
@@ -96,6 +101,11 @@ def test_pending_snapshot_is_converted_without_changing_original_data() -> None:
@pytest.fixture
def dictionary_db() -> Generator[Connection, None, None]:
+ """
+ 构建供任务字段迁移测试使用的 SQLite 数据库。
+
+ :yield: 供任务字段迁移测试使用的 SQLite 数据库
+ """
engine = create_engine('sqlite://')
with engine.begin() as connection:
connection.exec_driver_sql(
@@ -114,6 +124,7 @@ def dictionary_db() -> Generator[Connection, None, None]:
def test_store_dictionary_reuses_ids_and_keeps_custom_labels_and_status(dictionary_db: Connection) -> None:
+ """存储字典复用标识并保留自定义标签和状态。"""
dictionary_db.exec_driver_sql(
"INSERT INTO sys_dict_type (dict_id, dict_name, dict_type) VALUES (5, '任务分组', 'sys_job_group')"
)
@@ -145,6 +156,7 @@ def test_store_dictionary_reuses_ids_and_keeps_custom_labels_and_status(dictiona
def test_store_dictionary_fills_old_missing_options_and_does_not_reset_later_edits(dictionary_db: Connection) -> None:
+ """存储字典补全旧版本缺失选项且保留后续编辑。"""
dictionary_db.exec_driver_sql(
"INSERT INTO sys_dict_type (dict_id, dict_name, dict_type) VALUES (5, '任务分组', 'sys_job_group')"
)
@@ -178,6 +190,7 @@ def test_store_dictionary_fills_old_missing_options_and_does_not_reset_later_edi
def test_store_dictionary_conflict_stops_before_mutation(dictionary_db: Connection) -> None:
+ """检测到存储字典冲突时在写入前停止。"""
dictionary_db.exec_driver_sql(
'INSERT INTO sys_dict_type (dict_id, dict_name, dict_type) VALUES '
"(5, '任务分组', 'sys_job_group'), (8, '已有字典', 'sys_job_store')"
@@ -188,6 +201,7 @@ def test_store_dictionary_conflict_stops_before_mutation(dictionary_db: Connecti
def test_store_dictionary_can_initialize_when_type_is_missing(dictionary_db: Connection) -> None:
+ """字典类型缺失时可初始化存储字典。"""
assert migrate_store_dictionary(dictionary_db, plan_store_dictionary(dictionary_db)) == {
'current': False,
'added': 3,
diff --git a/ruoyi-fastapi-backend/tests/scripts/test_migrate_legacy_files.py b/ruoyi-fastapi-backend/tests/scripts/test_migrate_legacy_files.py
index c26345db6..88a2d74c9 100644
--- a/ruoyi-fastapi-backend/tests/scripts/test_migrate_legacy_files.py
+++ b/ruoyi-fastapi-backend/tests/scripts/test_migrate_legacy_files.py
@@ -18,25 +18,50 @@
class AsyncSessionContext:
"""
- 测试用异步数据库会话上下文
+ 测试用异步数据库会话上下文。
+
+ :ivar session: 当前操作共用的会话
"""
def __init__(self, session: SimpleNamespace) -> None:
+ """
+ 初始化测试夹具的 ``session``。
+
+ :param session: 当前操作共用的会话
+ """
self.session = session
async def __aenter__(self) -> SimpleNamespace:
+ """
+ 向调用方返回 ``self.session``。
+
+ :return: 当前测试上下文持有的数据库会话
+ """
return self.session
async def __aexit__(self, exc_type: type | None, exc_value: BaseException | None, traceback: object) -> None:
- return None
+ """
+ 完成无需返回值的回调。
+
+ :param exc_type: 退出上下文时的异常类型
+ :param exc_value: 退出上下文时的异常实例
+ :param traceback: 异常的调用栈
+ """
+ return
def make_database_registry(session: SimpleNamespace) -> SimpleNamespace:
- """构造使用测试会话的数据库注册表。"""
+ """
+ 构造使用测试会话的数据库注册表。
+
+ :param session: 当前操作共用的会话
+ :return: 使用测试会话的数据库注册表
+ """
return SimpleNamespace(session=lambda: AsyncSessionContext(session))
def test_collect_legacy_files_filters_disallowed_extensions(tmp_path: Path) -> None:
+ """收集旧文件时过滤未许可扩展名。"""
allowed_file = tmp_path / 'upload' / 'report.txt'
allowed_file.parent.mkdir()
allowed_file.write_bytes(b'report-content')
@@ -55,6 +80,7 @@ def test_collect_legacy_files_filters_disallowed_extensions(tmp_path: Path) -> N
def test_collect_legacy_files_filters_oversized_files(tmp_path: Path) -> None:
+ """收集旧文件时排除超大文件。"""
(tmp_path / 'small.txt').write_bytes(b'ok')
(tmp_path / 'large.txt').write_bytes(b'too-large')
@@ -69,6 +95,7 @@ def test_collect_legacy_files_filters_oversized_files(tmp_path: Path) -> None:
def test_calculate_file_hash_rejects_changed_file(tmp_path: Path) -> None:
+ """计算哈希时拒绝内容已变化的文件。"""
filepath = tmp_path / 'report.txt'
filepath.write_bytes(b'old-content')
with patch.object(UploadConfig, 'UPLOAD_PATH', str(tmp_path)):
@@ -82,6 +109,7 @@ def test_calculate_file_hash_rejects_changed_file(tmp_path: Path) -> None:
def test_migrate_legacy_files_dry_run_performs_full_validation_without_commit(tmp_path: Path) -> None:
+ """旧文件迁移预演完成全部校验且无需提交事务。"""
(tmp_path / 'report.txt').write_bytes(b'report-content')
session = SimpleNamespace(commit=AsyncMock())
@@ -100,6 +128,7 @@ def test_migrate_legacy_files_dry_run_performs_full_validation_without_commit(tm
def test_migrate_legacy_files_writes_file_info_model_and_commits(tmp_path: Path) -> None:
+ """旧文件迁移写入文件信息并提交。"""
(tmp_path / 'report.txt').write_bytes(b'report-content')
session = SimpleNamespace(commit=AsyncMock())
@@ -125,6 +154,7 @@ def test_migrate_legacy_files_writes_file_info_model_and_commits(tmp_path: Path)
def test_migrate_legacy_files_skips_existing_storage_location(tmp_path: Path) -> None:
+ """旧文件迁移跳过已有存储位置。"""
(tmp_path / 'report.txt').write_bytes(b'report-content')
session = SimpleNamespace(commit=AsyncMock())
@@ -146,6 +176,7 @@ def test_migrate_legacy_files_skips_existing_storage_location(tmp_path: Path) ->
def test_migrate_legacy_files_commits_by_batch(tmp_path: Path) -> None:
+ """旧文件迁移按批次提交。"""
for index in range(3):
(tmp_path / f'report-{index}.txt').write_bytes(f'content-{index}'.encode())
session = SimpleNamespace(commit=AsyncMock())
@@ -164,6 +195,7 @@ def test_migrate_legacy_files_commits_by_batch(tmp_path: Path) -> None:
def test_migrate_legacy_files_requires_valid_execution_options() -> None:
+ """旧文件迁移要求有效的执行选项。"""
with pytest.raises(ValueError, match='每批提交数量必须大于0'):
asyncio.run(migrate_legacy_files(dry_run=True, batch_size=0))
with pytest.raises(ValueError, match='必须停止公开文件上传'):
diff --git a/ruoyi-fastapi-backend/tests/server/test_oidc_cors_refresh.py b/ruoyi-fastapi-backend/tests/server/test_oidc_cors_refresh.py
index c9bd54925..b7314198e 100644
--- a/ruoyi-fastapi-backend/tests/server/test_oidc_cors_refresh.py
+++ b/ruoyi-fastapi-backend/tests/server/test_oidc_cors_refresh.py
@@ -9,16 +9,33 @@
@pytest.mark.asyncio
async def test_registered_cors_changes_reach_other_workers_and_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """注册的跨域规则变更传达到其他进程且失败时拒绝访问。"""
monkeypatch.setattr(OidcConfig, 'oidc_enabled', True)
state = {'version': '0', 'origins': ('https://old.example',)}
async def get(_key: str) -> str:
+ """
+ 读取测试存储中的指定键。
+
+ :param _key: 回调接收的查找键
+ :return: 测试存储中的指定键
+ """
return state['version']
async def incr(_key: str) -> None:
+ """
+ 增加测试缓存键的计数。
+
+ :param _key: 回调接收的查找键
+ """
state['version'] = str(int(state['version']) + 1)
async def load() -> tuple[str, ...]:
+ """
+ 捕获加载请求并提供测试密钥。
+
+ :return: 为当前测试准备的密钥
+ """
return state['origins']
redis = SimpleNamespace(get=get, incr=incr)
diff --git a/ruoyi-fastapi-backend/tests/server/test_oidc_runtime.py b/ruoyi-fastapi-backend/tests/server/test_oidc_runtime.py
index c64b7fdec..504b76ca1 100644
--- a/ruoyi-fastapi-backend/tests/server/test_oidc_runtime.py
+++ b/ruoyi-fastapi-backend/tests/server/test_oidc_runtime.py
@@ -44,6 +44,11 @@ async def test_oidc_runtime_validation_loads_database_active_key() -> None:
@asynccontextmanager
async def session() -> AsyncGenerator[object, None]:
+ """
+ 为当前测试操作提供数据库会话。
+
+ :yield: 数据库会话
+ """
yield db
with (
@@ -62,10 +67,15 @@ async def session() -> AsyncGenerator[object, None]:
@pytest.mark.asyncio
async def test_oidc_runtime_validation_fails_closed_without_usable_key() -> None:
- """active 元数据或私钥不可用时后台继续启动,但 OIDC 标记为未就绪。"""
+ """验证 active 元数据或私钥不可用时后台继续启动,但 OIDC 标记为未就绪。"""
@asynccontextmanager
async def session() -> AsyncGenerator[object, None]:
+ """
+ 为当前测试操作提供数据库会话。
+
+ :yield: 数据库会话
+ """
yield object()
with (
@@ -92,6 +102,12 @@ async def test_background_loops_wait_in_both_leader_and_follower() -> None:
created: list[object] = []
def create_task(coro: object) -> object:
+ """
+ 创建测试任务并将其交给调用方。
+
+ :param coro: 需要执行的协程对象
+ :return: 测试任务并将其交给调用方
+ """
created.append(coro)
coro.close()
return (fake_key_task, fake_retry_task)[len(created) - 1]
@@ -120,10 +136,16 @@ def create_task(coro: object) -> object:
@pytest.mark.asyncio
@pytest.mark.parametrize('loop', ['key', 'retry'])
async def test_background_loops_resume_after_lease_reacquisition(loop: str) -> None:
+ """重新获得租约后恢复后台循环。"""
db = SimpleNamespace(commit=AsyncMock())
@asynccontextmanager
async def session() -> AsyncGenerator[SimpleNamespace, None]:
+ """
+ 为当前测试操作提供数据库会话。
+
+ :yield: 数据库会话
+ """
yield db
with (
@@ -162,6 +184,12 @@ async def test_server_background_task_setup_delegates_oidc_runtime() -> None:
log_task = object()
def create_task(coro: object) -> object:
+ """
+ 创建测试任务并将其交给调用方。
+
+ :param coro: 需要执行的协程对象
+ :return: 测试任务并将其交给调用方
+ """
coro.close()
return log_task
diff --git a/ruoyi-fastapi-backend/tests/server/test_plugin_runtime.py b/ruoyi-fastapi-backend/tests/server/test_plugin_runtime.py
index 1fcaf7956..77b328a94 100644
--- a/ruoyi-fastapi-backend/tests/server/test_plugin_runtime.py
+++ b/ruoyi-fastapi-backend/tests/server/test_plugin_runtime.py
@@ -98,7 +98,12 @@ async def run_as_plugin_writer(
*,
create_tables: Callable[[], Awaitable[None]],
) -> None:
- """模拟当前非leader worker获得插件生命周期锁。"""
+ """
+ 模拟当前非leader worker获得插件生命周期锁。
+
+ :param _app: 回调接收的应用实例
+ :param create_tables: 数据库建表回调
+ """
await create_tables()
fake_plugin_runtime.startup = AsyncMock(side_effect=run_as_plugin_writer)
@@ -299,19 +304,32 @@ async def test_shutdown_application_runtime_preserves_cleanup_order() -> None:
plugin_runtime = MagicMock()
async def record_plugin_shutdown(_app: object) -> None:
+ """
+ 记录插件关闭阶段。
+
+ :param _app: 回调接收的应用实例
+ """
events.append('plugin')
async def record_scheduler_shutdown() -> None:
+ """记录调度器关闭阶段。"""
events.append('scheduler')
async def record_redis_shutdown(_app: object) -> None:
+ """
+ 记录 Redis 连接释放的顺序。
+
+ :param _app: 回调接收的应用实例
+ """
assert DataSourceRegistry._cache_redis is None
events.append('redis')
async def record_database_shutdown() -> None:
+ """记录数据库资源的关闭顺序。"""
events.append('database')
async def record_log_complete() -> None:
+ """记录日志刷写完成的时机。"""
events.append('logs')
plugin_runtime.shutdown = AsyncMock(side_effect=record_plugin_shutdown)
diff --git a/ruoyi-fastapi-backend/tests/sql/test_plugin_release_schema.py b/ruoyi-fastapi-backend/tests/sql/test_plugin_release_schema.py
index aa5a3d55b..8ac39b857 100644
--- a/ruoyi-fastapi-backend/tests/sql/test_plugin_release_schema.py
+++ b/ruoyi-fastapi-backend/tests/sql/test_plugin_release_schema.py
@@ -20,6 +20,7 @@
],
)
def test_initial_release_schema_matches_models(initial: str, time_type: str) -> None:
+ """初始发布表结构与模型一致。"""
initialization = (SQL_ROOT / initial).read_text(encoding='utf-8')
statements = PluginLifecycleScriptHelper.split_sql_statements(initialization)
for table in (SysPluginArtifact.__table__, SysPluginRelease.__table__, SysPluginWorker.__table__):
@@ -49,6 +50,7 @@ def test_initial_release_schema_matches_models(initial: str, time_type: str) ->
@pytest.mark.parametrize('dialect', [mysql.dialect(), postgresql.dialect()])
def test_release_orm_schema_compiles_for_supported_database_dialects(dialect: object) -> None:
+ """发布 ORM 结构可在支持的数据库方言中编译。"""
for model in (SysPluginArtifact, SysPluginRelease, SysPluginWorker):
ddl = str(CreateTable(model.__table__).compile(dialect=dialect))
assert model.__tablename__ in ddl
diff --git a/ruoyi-fastapi-backend/tests/sql/test_plugin_schema.py b/ruoyi-fastapi-backend/tests/sql/test_plugin_schema.py
index 0416bebf6..688926704 100644
--- a/ruoyi-fastapi-backend/tests/sql/test_plugin_schema.py
+++ b/ruoyi-fastapi-backend/tests/sql/test_plugin_schema.py
@@ -8,7 +8,12 @@
def read_sql(sql_path: Path) -> str:
- """读取初始化 SQL 文件内容。"""
+ """
+ 读取初始化 SQL 文件内容。
+
+ :param sql_path: 需要读取的 SQL 文件路径
+ :return: 初始化 SQL 文件内容
+ """
return sql_path.read_text(encoding='utf-8')
diff --git a/ruoyi-fastapi-backend/tests/test_api_docs_auth.py b/ruoyi-fastapi-backend/tests/test_api_docs_auth.py
index 7f806f3ea..b02f00faf 100644
--- a/ruoyi-fastapi-backend/tests/test_api_docs_auth.py
+++ b/ruoyi-fastapi-backend/tests/test_api_docs_auth.py
@@ -28,6 +28,12 @@
@pytest.fixture
def docs_app(monkeypatch: pytest.MonkeyPatch) -> Iterator[SimpleNamespace]:
+ """
+ 构建启用文档端点的测试应用。
+
+ :param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
+ :yield: 启用文档端点的测试应用
+ """
monkeypatch.setattr(AppConfig, 'app_disable_swagger', False)
monkeypatch.setattr(AppConfig, 'app_disable_redoc', False)
monkeypatch.setattr(AppConfig, 'app_root_path', '')
@@ -40,9 +46,24 @@ def docs_app(monkeypatch: pytest.MonkeyPatch) -> Iterator[SimpleNamespace]:
add_context_cleanup_middleware(app)
async def database() -> AsyncIterator[object]:
+ """
+ 提供依赖注入使用的数据库替身。
+
+ :yield: 依赖注入使用的数据库替身
+ """
yield object()
async def authenticate(request: Request, token: str, db: object, *, refresh_session: bool) -> CurrentUserModel:
+ """
+ 按测试场景提供请求认证结果。
+
+ :param request: 当前 HTTP 请求
+ :param token: 用于身份验证或授权的令牌
+ :param db: 当前操作使用的数据库会话
+ :param refresh_session: 是否续期宿主主登录会话
+ :raises AuthException: 用户token已失效,请重新登录
+ :return: 当前登录用户及其权限信息
+ """
assert refresh_session
if token != 'valid':
raise AuthException(message='用户token已失效,请重新登录')
@@ -58,34 +79,58 @@ async def authenticate(request: Request, token: str, db: object, *, refresh_sess
monkeypatch.setattr(LoginService, '_resolve_current_user', resolver)
app.dependency_overrides[get_db_session_provider(None)] = database
- @app.get('/public', dependencies=[PreAuthDependency([{'path': '/public'}])])
+ @app.get(
+ '/public',
+ summary='访问公开资源',
+ description='返回公开状态,用于核对匿名接口的 OpenAPI 安全声明。',
+ dependencies=[PreAuthDependency([{'path': '/public'}])],
+ )
async def public() -> dict:
return {'public': True}
- @app.get('/protected', dependencies=[PreAuthDependency()])
+ @app.get(
+ '/protected',
+ summary='读取已认证用户',
+ description='从预认证上下文读取并返回用户标识。',
+ dependencies=[PreAuthDependency()],
+ )
async def protected() -> dict:
return {'userId': RequestContext.get_current_user().user.user_id}
@app.api_route(
'/method',
+ summary='检查按方法匹配的认证',
+ description='在同一路径处理多种请求方法,用于核对各方法的安全声明。',
methods=['GET', 'POST'],
dependencies=[PreAuthDependency([{'path': '/method', 'methods': ['GET']}])],
)
async def method() -> dict:
return {'ok': True}
- @app.get('/items/{name}', dependencies=[PreAuthDependency([{'path': '/items/{name}'}])])
+ @app.get(
+ '/items/{name}',
+ summary='按名称查询条目',
+ description='回显条目名称,用于核对路径参数对应的认证规则。',
+ dependencies=[PreAuthDependency([{'path': '/items/{name}'}])],
+ )
async def items(name: str) -> dict:
return {'name': name}
@app.get(
'/mixed/{name}',
+ summary='读取混合认证资源',
+ description='回显路径参数,用于核对部分名称可匿名访问时的文档说明。',
dependencies=[PreAuthDependency([{'path': '/mixed/{name}', 'ignore_paths': ['/mixed/private']}])],
)
async def mixed(name: str) -> dict:
return {'name': name}
- @app.get('/partial/{name}', dependencies=[PreAuthDependency([{'path': '/partial/free'}])])
+ @app.get(
+ '/partial/{name}',
+ summary='读取部分公开资源',
+ description='回显名称,用于验证带例外路径的匿名访问规则。',
+ dependencies=[PreAuthDependency([{'path': '/partial/free'}])],
+ )
async def partial(name: str) -> dict:
return {'name': name}
@@ -96,6 +141,14 @@ async def partial(name: str) -> dict:
def _security(app: FastAPI, path: str, method: str = 'get') -> list[dict]:
+ """
+ 读取指定 OpenAPI 操作的安全要求。
+
+ :param app: 正在配置或处理请求的 ASGI 应用
+ :param path: 要读取或处理的路径
+ :param method: 当前请求的 HTTP 方法
+ :return: 指定 OpenAPI 操作的安全要求
+ """
return app.openapi()['paths'][path][method].get('security', [])
@@ -104,6 +157,7 @@ def _security(app: FastAPI, path: str, method: str = 'get') -> list[dict]:
async def test_proxy_schema_does_not_add_deployment_prefix_to_direct_schema(
docs_app: SimpleNamespace, server_urls: list[str]
) -> None:
+ """代理文档的部署前缀不会写入直连文档。"""
servers = [{'url': url} for url in server_urls]
docs_app.app.servers = deepcopy(servers)
transport = httpx.ASGITransport(app=docs_app.app, root_path='/gateway')
@@ -122,6 +176,7 @@ async def test_proxy_schema_does_not_add_deployment_prefix_to_direct_schema(
@pytest.mark.asyncio
@pytest.mark.parametrize('path', ['/public', '/items/{name}'])
async def test_fully_excluded_route_has_no_login_security(docs_app: SimpleNamespace, path: str) -> None:
+ """完全排除的路由无需在文档中声明登录认证。"""
assert _security(docs_app.app, path) == []
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=docs_app.app), base_url='http://test') as client:
response = await client.get(path.replace('{name}', 'free'), headers={'Authorization': 'Bearer invalid'})
@@ -132,6 +187,7 @@ async def test_fully_excluded_route_has_no_login_security(docs_app: SimpleNamesp
@pytest.mark.asyncio
async def test_protected_route_keeps_login_security(docs_app: SimpleNamespace) -> None:
+ """受保护路由保留登录安全要求。"""
assert _security(docs_app.app, '/protected') == [LOGIN_SECURITY]
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=docs_app.app), base_url='http://test') as client:
denied = await client.get('/protected')
@@ -143,6 +199,7 @@ async def test_protected_route_keeps_login_security(docs_app: SimpleNamespace) -
@pytest.mark.asyncio
async def test_security_is_classified_per_http_method(docs_app: SimpleNamespace) -> None:
+ """按 HTTP 方法分别判定安全要求。"""
assert _security(docs_app.app, '/method', 'get') == []
assert _security(docs_app.app, '/method', 'post') == [LOGIN_SECURITY]
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=docs_app.app), base_url='http://test') as client:
@@ -163,6 +220,7 @@ async def test_security_is_classified_per_http_method(docs_app: SimpleNamespace)
async def test_parameter_dependent_authentication_is_documented_as_conditional(
docs_app: SimpleNamespace, path: str, public_path: str, protected_path: str, documented_rule: str
) -> None:
+ """依赖参数的认证在文档中标为有条件。"""
operation = docs_app.app.openapi()['paths'][path]['get']
assert LOGIN_SECURITY in operation['security']
assert {} in operation['security']
@@ -181,34 +239,76 @@ async def test_parameter_dependent_authentication_is_documented_as_conditional(
async def test_explicit_authentication_cannot_be_removed_from_public_route_schema(
docs_app: SimpleNamespace, declaration: str
) -> None:
+ """公开路由中显式声明的认证仍保留在文档中。"""
path = f'/explicit-{declaration}'
dependencies = [PreAuthDependency([{'path': path}])]
async def identity(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> int:
+ """
+ 返回认证依赖解析出的用户标识。
+
+ :param user: 当前已认证用户及其权限信息
+ :return: 认证依赖解析出的用户标识
+ """
return user.user.user_id
if declaration == 'current':
- @docs_app.app.get(path, dependencies=dependencies)
+ @docs_app.app.get(
+ path,
+ summary='读取显式认证的用户',
+ description='返回当前用户标识,用于验证公开路径上显式声明的认证依赖。',
+ dependencies=dependencies,
+ )
async def current(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict:
+ """
+ 返回含 ``userId`` 的测试数据。
+
+ :param user: 当前已认证用户及其权限信息
+ :return: 含 ``userId`` 的测试数据
+ """
return {'userId': user.user.user_id}
elif declaration == 'nested':
- @docs_app.app.get(path, dependencies=dependencies)
+ @docs_app.app.get(
+ path,
+ summary='读取嵌套认证的用户',
+ description='从嵌套依赖获取用户标识,用于核对公开路径的安全声明。',
+ dependencies=dependencies,
+ )
async def nested(user_id: Annotated[int, Depends(identity)]) -> dict:
+ """
+ 返回含 ``userId`` 的测试数据。
+
+ :param user_id: 用户的唯一标识
+ :return: 含 ``userId`` 的测试数据
+ """
return {'userId': user_id}
elif declaration == 'token':
- @docs_app.app.get(path, dependencies=dependencies)
+ @docs_app.app.get(
+ path,
+ summary='读取显式 OAuth 令牌',
+ description='从 OAuth 依赖读取令牌,用于核对公开路径的认证要求。',
+ dependencies=dependencies,
+ )
async def token(value: Annotated[str, Depends(oauth2_scheme)]) -> dict:
+ """
+ 返回含 ``token`` 的测试数据。
+
+ :param value: 待处理的输入值
+ :return: 含 ``token`` 的测试数据
+ """
return {'token': value}
else:
router = APIRouter(dependencies=dependencies)
- @router.get(path)
+ @router.get(
+ path, summary='访问有认证要求的插件路由', description='返回插件状态,用于验证挂载路由显式声明的认证要求。'
+ )
async def plugin() -> dict:
return {'ok': True}
@@ -227,14 +327,25 @@ async def plugin() -> dict:
@pytest.mark.asyncio
@pytest.mark.parametrize('required', [False, True])
async def test_all_pre_auth_dependencies_must_exclude_the_route(docs_app: SimpleNamespace, required: bool) -> None:
+ """全部预认证依赖均排除时才放行路由。"""
path = '/multiple'
dependencies = [
PreAuthDependency([{'path': path}]),
PreAuthDependency([] if required else [{'path': path}]),
]
- @docs_app.app.get(path, dependencies=dependencies)
+ @docs_app.app.get(
+ path,
+ summary='检查多个预认证依赖',
+ description='组合排除规则并返回成功状态,用于验证匿名访问范围。',
+ dependencies=dependencies,
+ )
async def multiple() -> dict:
+ """
+ 返回含 ``ok`` 的测试数据。
+
+ :return: 含 ``ok`` 的测试数据
+ """
return {'ok': True}
assert _security(docs_app.app, path) == ([LOGIN_SECURITY] if required else [])
@@ -248,14 +359,24 @@ async def multiple() -> dict:
@pytest.mark.asyncio
async def test_disjoint_exclusions_do_not_make_a_parameterized_route_public(docs_app: SimpleNamespace) -> None:
+ """不相交的排除范围不会使参数化路由公开。"""
+
@docs_app.app.get(
'/disjoint/{name}',
+ summary='检查不相交的排除规则',
+ description='回显名称,用于验证多个依赖的公开范围是否重叠。',
dependencies=[
PreAuthDependency([{'path': '/disjoint/first'}]),
PreAuthDependency([{'path': '/disjoint/second'}]),
],
)
async def disjoint(name: str) -> dict:
+ """
+ 返回含 ``name`` 的测试数据。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 含 ``name`` 的测试数据
+ """
return {'name': name}
assert _security(docs_app.app, '/disjoint/{name}') == [LOGIN_SECURITY]
@@ -267,13 +388,21 @@ async def disjoint(name: str) -> dict:
@pytest.mark.parametrize('name', ['public', 'private'])
def test_fixed_route_honors_wildcard_exclusion_and_ignore_paths(docs_app: SimpleNamespace, name: str) -> None:
+ """固定路由遵循通配符和忽略路径。"""
path = f'/fixed/{name}'
@docs_app.app.get(
path,
+ summary='检查固定路径认证',
+ description='在固定路径返回成功状态,用于核对通配规则及例外路径。',
dependencies=[PreAuthDependency([{'path': '/fixed/{name}', 'ignore_paths': ['/fixed/private']}])],
)
async def fixed() -> dict:
+ """
+ 返回含 ``ok`` 的测试数据。
+
+ :return: 含 ``ok`` 的测试数据
+ """
return {'ok': True}
assert _security(docs_app.app, path) == ([LOGIN_SECURITY] if name == 'private' else [])
@@ -283,8 +412,12 @@ async def fixed() -> dict:
def test_irrelevant_or_reallowed_exceptions_do_not_make_fully_public_routes_conditional(
docs_app: SimpleNamespace, ignore_path: str
) -> None:
+ """无关或已重新放行的例外不会让公开路由变为有条件认证。"""
+
@docs_app.app.get(
'/reallowed/{name}',
+ summary='检查重新放行的路径',
+ description='回显名称,用于核对排除规则中的例外处理。',
dependencies=[
PreAuthDependency(
[
@@ -295,6 +428,12 @@ def test_irrelevant_or_reallowed_exceptions_do_not_make_fully_public_routes_cond
],
)
async def reallowed(name: str) -> dict:
+ """
+ 返回含 ``name`` 的测试数据。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 含 ``name`` 的测试数据
+ """
return {'name': name}
assert _security(docs_app.app, '/reallowed/{name}') == []
@@ -305,12 +444,24 @@ async def reallowed(name: str) -> dict:
async def test_public_login_exclusion_preserves_other_required_security(
docs_app: SimpleNamespace, conditional: bool
) -> None:
+ """排除登录要求时保留其他安全要求。"""
path = '/key/{name}' if conditional else '/key'
rule = {'path': '/key/free' if conditional else path}
api_key = APIKeyHeader(name='X-API-Key', scheme_name='ServiceKey')
- @docs_app.app.get(path, dependencies=[PreAuthDependency([rule])])
+ @docs_app.app.get(
+ path,
+ summary='读取独立安全凭证',
+ description='返回依赖解析的凭证,用于确认登录排除后仍保留其他安全要求。',
+ dependencies=[PreAuthDependency([rule])],
+ )
async def key(value: Annotated[str, Depends(api_key)]) -> dict:
+ """
+ 返回含 ``key`` 的测试数据。
+
+ :param value: 待处理的输入值
+ :return: 含 ``key`` 的测试数据
+ """
return {'key': value}
security = _security(docs_app.app, path)
@@ -329,10 +480,22 @@ async def key(value: Annotated[str, Depends(api_key)]) -> dict:
@pytest.mark.asyncio
async def test_independent_oauth_scheme_with_the_same_name_remains_required(docs_app: SimpleNamespace) -> None:
+ """同名的独立 OAuth 方案仍是必需项。"""
independent = OAuth2PasswordBearer(tokenUrl='independent-login', scheme_name='OAuth2PasswordBearer')
- @docs_app.app.get('/independent', dependencies=[PreAuthDependency([{'path': '/independent'}])])
+ @docs_app.app.get(
+ '/independent',
+ summary='读取独立 OAuth 令牌',
+ description='返回独立 OAuth 方案解析的令牌,用于核对安全声明。',
+ dependencies=[PreAuthDependency([{'path': '/independent'}])],
+ )
async def independent_token(token: Annotated[str, Depends(independent)]) -> dict:
+ """
+ 返回含 ``token`` 的测试数据。
+
+ :param token: 用于身份验证或授权的令牌
+ :return: 含 ``token`` 的测试数据
+ """
return {'token': token}
assert _security(docs_app.app, '/independent') == [LOGIN_SECURITY]
@@ -348,11 +511,14 @@ async def independent_token(token: Annotated[str, Depends(independent)]) -> dict
async def test_nested_router_prefix_and_root_path_match_runtime_rules(
docs_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, root_path: str
) -> None:
+ """嵌套路由前缀及根路径遵循运行时规则。"""
monkeypatch.setattr(AppConfig, 'app_root_path', root_path)
docs_app.app.root_path = root_path
child = APIRouter(prefix='/child', dependencies=[PreAuthDependency([{'path': '/api/child/public'}])])
- @child.get('/public')
+ @child.get(
+ '/public', summary='访问嵌套的公开路由', description='返回成功状态,用于核对嵌套前缀与部署路径的认证规则。'
+ )
async def public() -> dict:
return {'ok': True}
@@ -368,6 +534,7 @@ async def public() -> dict:
@pytest.mark.asyncio
async def test_schema_urls_and_direct_schema_share_security_and_servers(docs_app: SimpleNamespace) -> None:
+ """代理文档与直连文档共享安全要求和服务器信息。"""
direct = docs_app.app.openapi()
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=docs_app.app), base_url='http://test') as client:
custom = await client.get('/openapi.json')
@@ -381,15 +548,22 @@ async def test_schema_urls_and_direct_schema_share_security_and_servers(docs_app
def test_schema_adjustment_is_idempotent_and_tracks_late_router_registration(docs_app: SimpleNamespace) -> None:
+ """重复调整文档结果一致且能跟踪后注册的路由。"""
initial = deepcopy(docs_app.app.openapi())
assert docs_app.app.openapi() == initial
router = APIRouter(prefix='/late', dependencies=[PreAuthDependency([{'path': '/late/public'}])])
- @router.get('/public')
+ @router.get(
+ '/public', summary='访问后注册的公开路由', description='在初次生成文档后注册公开接口,用于检查文档刷新。'
+ )
async def public() -> dict:
return {'ok': True}
- @router.get('/protected')
+ @router.get(
+ '/protected',
+ summary='访问后注册的受保护路由',
+ description='在初次生成文档后注册受保护接口,用于检查安全声明刷新。',
+ )
async def protected() -> dict:
return {'ok': True}
@@ -410,18 +584,36 @@ async def protected() -> dict:
async def test_duplicate_route_preserves_native_security(
docs_app: SimpleNamespace, public_first: bool, include_first: bool
) -> None:
+ """重复路由保留原生安全要求。"""
path = '/duplicate'
@docs_app.app.get(
path,
+ summary='访问首个同路径注册',
+ description='返回首个处理函数的标记,用于比对重复路径的文档与运行行为。',
dependencies=[PreAuthDependency([{'path': path}] if public_first else [])],
include_in_schema=include_first,
)
async def first() -> dict:
+ """
+ 返回含 ``route`` 的测试数据。
+
+ :return: 含 ``route`` 的测试数据
+ """
return {'route': 'first'}
- @docs_app.app.get(path, dependencies=[PreAuthDependency([] if public_first else [{'path': path}])])
+ @docs_app.app.get(
+ path,
+ summary='访问第二个同路径注册',
+ description='声明第二个处理函数,用于验证重复注册时保留的安全要求。',
+ dependencies=[PreAuthDependency([] if public_first else [{'path': path}])],
+ )
async def second() -> dict:
+ """
+ 返回含 ``route`` 的测试数据。
+
+ :return: 含 ``route`` 的测试数据
+ """
return {'route': 'second'}
operation = docs_app.app.openapi()['paths'][path]['get']
@@ -443,18 +635,38 @@ async def second() -> dict:
async def test_duplicate_path_with_different_convertors_preserves_native_security(
docs_app: SimpleNamespace, public_first: bool, include_first: bool
) -> None:
+ """同一路径使用不同转换器时保留原生安全要求。"""
rule = {'path': '/duplicate-convertor/{value}'}
@docs_app.app.get(
'/duplicate-convertor/{value:int}',
+ summary='通过整数转换器访问',
+ description='返回通过整数路径转换器解析的值。',
dependencies=[PreAuthDependency([rule] if public_first else [])],
include_in_schema=include_first,
)
async def integer(value: int) -> dict:
+ """
+ 返回含 ``route``, ``value`` 的测试数据。
+
+ :param value: 待处理的输入值
+ :return: 含 ``route``, ``value`` 的测试数据
+ """
return {'route': 'integer', 'value': value}
- @docs_app.app.get('/duplicate-convertor/{value}', dependencies=[PreAuthDependency([] if public_first else [rule])])
+ @docs_app.app.get(
+ '/duplicate-convertor/{value}',
+ summary='通过字符串转换器访问',
+ description='返回通过字符串路径转换器解析的值。',
+ dependencies=[PreAuthDependency([] if public_first else [rule])],
+ )
async def string(value: str) -> dict:
+ """
+ 返回含 ``route``, ``value`` 的测试数据。
+
+ :param value: 待处理的输入值
+ :return: 含 ``route``, ``value`` 的测试数据
+ """
return {'route': 'string', 'value': value}
path = '/duplicate-convertor/{value}'
@@ -489,6 +701,7 @@ async def string(value: str) -> dict:
async def test_duplicate_route_with_other_authentication_preserves_native_security(
docs_app: SimpleNamespace, first_auth: str, second_auth: str
) -> None:
+ """重复路由带有其他认证时保留原生安全要求。"""
path = '/duplicate-security'
api_key = APIKeyHeader(name='X-API-Key', scheme_name='DuplicateKey')
dependencies = {
@@ -499,12 +712,32 @@ async def test_duplicate_route_with_other_authentication_preserves_native_securi
'public_key': [PreAuthDependency([{'path': path}]), Depends(api_key)],
}
- @docs_app.app.get(path, dependencies=dependencies[first_auth])
+ @docs_app.app.get(
+ path,
+ summary='访问第一组认证依赖',
+ description='返回首个处理函数的标记,用于比对同路径上的不同认证方案。',
+ dependencies=dependencies[first_auth],
+ )
async def first() -> dict:
+ """
+ 返回含 ``route`` 的测试数据。
+
+ :return: 含 ``route`` 的测试数据
+ """
return {'route': 'first'}
- @docs_app.app.get(path, dependencies=dependencies[second_auth])
+ @docs_app.app.get(
+ path,
+ summary='访问第二组认证依赖',
+ description='返回后注册处理函数的标记,用于比对同路径上的不同认证方案。',
+ dependencies=dependencies[second_auth],
+ )
async def second() -> dict:
+ """
+ 返回含 ``route`` 的测试数据。
+
+ :return: 含 ``route`` 的测试数据
+ """
return {'route': 'second'}
operation = docs_app.app.openapi()['paths'][path]['get']
@@ -522,6 +755,7 @@ async def second() -> dict:
def test_unrelated_schema_details_and_security_schemes_are_preserved(docs_app: SimpleNamespace) -> None:
+ """保留无关的文档细节和安全方案。"""
api_key = APIKeyHeader(name='X-External-Key', scheme_name='ExternalKey')
@docs_app.app.get(
@@ -532,10 +766,23 @@ def test_unrelated_schema_details_and_security_schemes_are_preserved(docs_app: S
openapi_extra={'x-external': {'enabled': True}},
)
async def external(key: Annotated[str, Depends(api_key)]) -> dict:
+ """
+ 返回含 ``key`` 的测试数据。
+
+ :param key: 查找数据时使用的键
+ :return: 含 ``key`` 的测试数据
+ """
return {'key': key}
- @docs_app.app.get('/plain-public')
+ @docs_app.app.get(
+ '/plain-public', summary='访问无认证的公开路由', description='返回成功状态,用于确认公开接口的安全要求为空。'
+ )
async def plain_public() -> dict:
+ """
+ 返回含 ``ok`` 的测试数据。
+
+ :return: 含 ``ok`` 的测试数据
+ """
return {'ok': True}
schema = docs_app.app.openapi()
@@ -574,11 +821,21 @@ async def plain_public() -> dict:
async def test_parameter_convertors_exclude_impossible_public_values(
docs_app: SimpleNamespace, converter: str, first_value: str, second_value: str, excluded_value: str
) -> None:
+ """路径转换器排除不可能公开的值。"""
+
@docs_app.app.get(
f'/converted/{{value:{converter}}}',
+ summary='查询转换后的路径参数',
+ description='回显转换后的值,用于排除无法由路径转换器匹配的公开规则。',
dependencies=[PreAuthDependency([{'path': f'/converted/{excluded_value}'}])],
)
async def converted(value: int | UUID) -> dict:
+ """
+ 返回含 ``value`` 的测试数据。
+
+ :param value: 待处理的输入值
+ :return: 含 ``value`` 的测试数据
+ """
return {'value': str(value)}
security = _security(docs_app.app, '/converted/{value}')
@@ -600,15 +857,24 @@ async def converted(value: int | UUID) -> dict:
async def test_overlapping_public_values_respect_each_pre_auth_exception(
docs_app: SimpleNamespace, reallow: bool
) -> None:
+ """公开值重叠时遵循每个预认证依赖的例外。"""
rules = [{'path': '/overlap/{name}', 'ignore_paths': ['/overlap/free']}]
if reallow:
rules.append({'path': '/overlap/free'})
@docs_app.app.get(
'/overlap/{name}',
+ summary='查询公开范围重叠的资源',
+ description='回显名称,用于核对多组公开规则和例外的交集。',
dependencies=[PreAuthDependency(rules), PreAuthDependency([{'path': '/overlap/free'}])],
)
async def overlap(name: str) -> dict:
+ """
+ 返回含 ``name`` 的测试数据。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 含 ``name`` 的测试数据
+ """
return {'name': name}
security = _security(docs_app.app, '/overlap/{name}')
@@ -625,6 +891,7 @@ async def overlap(name: str) -> dict:
def test_adjusted_schema_never_mutates_the_native_cache(docs_app: SimpleNamespace) -> None:
+ """调整文档不会修改原生缓存。"""
adjusted = docs_app.app.openapi()
native = docs_app.app.openapi_schema
assert native is not adjusted
@@ -641,6 +908,7 @@ def test_adjusted_schema_never_mutates_the_native_cache(docs_app: SimpleNamespac
def test_registering_docs_again_does_not_duplicate_conditional_authentication_notes(docs_app: SimpleNamespace) -> None:
+ """重复注册文档不会重复追加条件认证说明。"""
before = deepcopy(docs_app.app.openapi())
APIDocsUtil.custom_api_docs_router(docs_app.app)
assert docs_app.app.openapi() == before
@@ -648,11 +916,18 @@ def test_registering_docs_again_does_not_duplicate_conditional_authentication_no
@pytest.mark.asyncio
async def test_changed_exclusion_rules_restore_native_security_and_description(docs_app: SimpleNamespace) -> None:
+ """更改排除规则后恢复原生安全要求和说明。"""
pre_auth = PreAuthDependency([{'path': '/mutable/free'}])
description = '原有接口描述必须保留。'
- @docs_app.app.get('/mutable/{name}', dependencies=[pre_auth], description=description)
+ @docs_app.app.get('/mutable/{name}', summary='验证可变的认证规则', dependencies=[pre_auth], description=description)
async def mutable(name: str) -> dict:
+ """
+ 返回含 ``name`` 的测试数据。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 含 ``name`` 的测试数据
+ """
return {'name': name}
before = docs_app.app.openapi()['paths']['/mutable/{name}']['get']
@@ -673,13 +948,23 @@ async def mutable(name: str) -> dict:
@pytest.mark.parametrize('conditional', [False, True])
def test_compound_security_from_openapi_extra_is_preserved(docs_app: SimpleNamespace, conditional: bool) -> None:
+ """保留 OpenAPI 扩展声明的组合安全要求。"""
gateway = APIKeyHeader(name='X-Gateway-Key', scheme_name='GatewayKey')
audit = APIKeyHeader(name='X-Audit-Key', scheme_name='AuditKey')
- @docs_app.app.get('/security-definitions')
+ @docs_app.app.get(
+ '/security-definitions', summary='读取网关和审计凭证', description='返回两种独立安全依赖解析的键值。'
+ )
async def security_definitions(
gateway_key: Annotated[str, Depends(gateway)], audit_key: Annotated[str, Depends(audit)]
) -> dict:
+ """
+ 返回含 ``gateway``, ``audit`` 的测试数据。
+
+ :param gateway_key: 在网关配置中选择目标的键
+ :param audit_key: 对应审计记录的键
+ :return: 含 ``gateway``, ``audit`` 的测试数据
+ """
return {'gateway': gateway_key, 'audit': audit_key}
path = '/compound/{name}' if conditional else '/compound'
@@ -688,11 +973,17 @@ async def security_definitions(
@docs_app.app.get(
path,
+ summary='检查组合安全声明',
dependencies=[PreAuthDependency([{'path': '/compound/free' if conditional else path}])],
description=description,
openapi_extra={'security': [{**LOGIN_SECURITY, **additional_security}], 'x-gateway': {'required': True}},
)
async def compound() -> dict:
+ """
+ 返回含 ``ok`` 的测试数据。
+
+ :return: 含 ``ok`` 的测试数据
+ """
return {'ok': True}
operation = docs_app.app.openapi()['paths'][path]['get']
@@ -719,10 +1010,22 @@ async def compound() -> dict:
async def test_embedded_parameters_and_literal_dots_preserve_full_exclusion(
docs_app: SimpleNamespace, path: str, public_path: str, private_path: str, unmatched_ignore: str, ignore: str
) -> None:
+ """嵌入路径参数及字面点号保留完全排除效果。"""
ignored_paths = [] if ignore == 'none' else [private_path if ignore == 'matching' else unmatched_ignore]
- @docs_app.app.get(path, dependencies=[PreAuthDependency([{'path': path, 'ignore_paths': ignored_paths}])])
+ @docs_app.app.get(
+ path,
+ summary='验证嵌入式路径参数',
+ description='回显路径中的名称,用于核对嵌入参数和字面点号的匹配。',
+ dependencies=[PreAuthDependency([{'path': path, 'ignore_paths': ignored_paths}])],
+ )
async def embedded(name: str) -> dict:
+ """
+ 返回含 ``name`` 的测试数据。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 含 ``name`` 的测试数据
+ """
return {'name': name}
security = _security(docs_app.app, path)
@@ -743,8 +1046,12 @@ async def embedded(name: str) -> dict:
@pytest.mark.asyncio
async def test_modifying_documented_rules_cannot_change_runtime_authentication(docs_app: SimpleNamespace) -> None:
+ """修改文档规则不能改变运行时认证。"""
+
@docs_app.app.api_route(
'/documented/{name}',
+ summary='验证文档与实际认证的独立性',
+ description='回显路径参数,用于检查修改公开文档后的运行时认证行为。',
methods=['GET', 'POST'],
dependencies=[
PreAuthDependency(
@@ -753,6 +1060,12 @@ async def test_modifying_documented_rules_cannot_change_runtime_authentication(d
],
)
async def documented(name: str) -> dict:
+ """
+ 返回含 ``name`` 的测试数据。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 含 ``name`` 的测试数据
+ """
return {'name': name}
schema = docs_app.app.openapi()
@@ -773,14 +1086,23 @@ async def documented(name: str) -> dict:
@pytest.mark.asyncio
async def test_explicit_anonymous_security_for_optional_api_key_is_preserved(docs_app: SimpleNamespace) -> None:
+ """可选 API 密钥保留显式匿名访问声明。"""
optional_key = APIKeyHeader(name='X-Optional-Key', scheme_name='OptionalKey', auto_error=False)
@docs_app.app.get(
'/optional-key',
+ summary='读取可选 API 密钥',
+ description='返回可选凭证,用于检查显式匿名访问的安全声明。',
dependencies=[PreAuthDependency([{'path': '/optional-key'}])],
openapi_extra={'security': [{}]},
)
async def optional(key: Annotated[str | None, Depends(optional_key)]) -> dict:
+ """
+ 返回含 ``key`` 的测试数据。
+
+ :param key: 查找数据时使用的键
+ :return: 含 ``key`` 的测试数据
+ """
return {'key': key}
security = _security(docs_app.app, '/optional-key')
@@ -794,14 +1116,24 @@ async def optional(key: Annotated[str | None, Depends(optional_key)]) -> dict:
@pytest.mark.asyncio
async def test_complex_rule_cannot_override_a_proven_empty_public_intersection(docs_app: SimpleNamespace) -> None:
+ """复杂规则无法覆盖已证明为空的公开范围交集。"""
+
@docs_app.app.get(
'/complex/{name}',
+ summary='检查复杂路径规则',
+ description='回显名称,用于核对复杂规则与已知公开范围的交集。',
dependencies=[
PreAuthDependency([{'path': '/complex/(a|b)'}]),
PreAuthDependency([{'path': '/complex/c'}]),
],
)
async def complex_rule(name: str) -> dict:
+ """
+ 返回含 ``name`` 的测试数据。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 含 ``name`` 的测试数据
+ """
return {'name': name}
assert _security(docs_app.app, '/complex/{name}') == [LOGIN_SECURITY]
@@ -813,8 +1145,21 @@ async def complex_rule(name: str) -> dict:
@pytest.mark.asyncio
async def test_unresolved_complex_rules_do_not_add_an_unproven_anonymous_alternative(docs_app: SimpleNamespace) -> None:
- @docs_app.app.get('/unresolved/{name}', dependencies=[PreAuthDependency([{'path': '/unresolved/(a|b)'}])])
+ """未能解析的复杂规则不会引入未经确认的匿名选项。"""
+
+ @docs_app.app.get(
+ '/unresolved/{name}',
+ summary='检查未解析的路径规则',
+ description='回显路径参数,用于验证复杂匹配规则的认证声明。',
+ dependencies=[PreAuthDependency([{'path': '/unresolved/(a|b)'}])],
+ )
async def unresolved(name: str) -> dict:
+ """
+ 返回含 ``name`` 的测试数据。
+
+ :param name: 用于查找或标识当前对象的名称
+ :return: 含 ``name`` 的测试数据
+ """
return {'name': name}
operation = docs_app.app.openapi()['paths']['/unresolved/{name}']['get']
diff --git a/ruoyi-fastapi-backend/tests/test_api_docs_switches.py b/ruoyi-fastapi-backend/tests/test_api_docs_switches.py
index 70d2de244..12c8bfcf3 100644
--- a/ruoyi-fastapi-backend/tests/test_api_docs_switches.py
+++ b/ruoyi-fastapi-backend/tests/test_api_docs_switches.py
@@ -11,6 +11,7 @@
def test_custom_schema_respects_docs_switches(
monkeypatch: pytest.MonkeyPatch, disable_swagger: bool, disable_redoc: bool
) -> None:
+ """自定义文档遵循文档开关。"""
monkeypatch.setattr(AppConfig, 'app_disable_swagger', disable_swagger)
monkeypatch.setattr(AppConfig, 'app_disable_redoc', disable_redoc)
app = FastAPI(openapi_url=None)
@@ -26,6 +27,7 @@ def test_custom_schema_respects_docs_switches(
def test_proxy_schema_and_enabled_ui_are_available(
monkeypatch: pytest.MonkeyPatch, disable_swagger: bool, disable_redoc: bool
) -> None:
+ """代理文档和已启用的文档界面可访问。"""
monkeypatch.setattr(AppConfig, 'app_disable_swagger', disable_swagger)
monkeypatch.setattr(AppConfig, 'app_disable_redoc', disable_redoc)
app = FastAPI(
diff --git a/ruoyi-fastapi-backend/tests/test_audit_time_delegation.py b/ruoyi-fastapi-backend/tests/test_audit_time_delegation.py
index 2f0e9919c..333c838cc 100644
--- a/ruoyi-fastapi-backend/tests/test_audit_time_delegation.py
+++ b/ruoyi-fastapi-backend/tests/test_audit_time_delegation.py
@@ -6,6 +6,7 @@
def test_plugin_persistence_payload_ignores_client_audit_times() -> None:
+ """插件持久化数据忽略客户端提交的审计时间。"""
now = datetime(2026, 8, 21, 12, 0, 0, tzinfo=UTC)
payload = PluginDao.dump_plugin_persistence_payload(
PluginModel(
@@ -22,6 +23,7 @@ def test_plugin_persistence_payload_ignores_client_audit_times() -> None:
def test_existing_migration_update_uses_onupdate_not_external_time() -> None:
+ """迁移更新通过 onupdate 生成时间。"""
now = datetime(2026, 8, 21, 12, 0, 0, tzinfo=UTC)
payload = PluginMigrationModel(
pluginId='demo',
diff --git a/ruoyi-fastapi-backend/tests/test_entity_time_columns.py b/ruoyi-fastapi-backend/tests/test_entity_time_columns.py
index 925f5c8f4..66527bd87 100644
--- a/ruoyi-fastapi-backend/tests/test_entity_time_columns.py
+++ b/ruoyi-fastapi-backend/tests/test_entity_time_columns.py
@@ -135,6 +135,14 @@
def _column_default(model: type, field_name: str, attribute: str) -> object | None:
+ """
+ 读取指定 ORM 列的默认值。
+
+ :param model: 当前处理的数据模型
+ :param field_name: 需要读取或校验的字段名
+ :param attribute: 要读取或替换的属性名
+ :return: 指定 ORM 列的默认值
+ """
column = model.__table__.c[field_name]
value = getattr(column, attribute)
return None if value is None else value.arg
diff --git a/ruoyi-fastapi-backend/tests/utils/test_application_leader_lease.py b/ruoyi-fastapi-backend/tests/utils/test_application_leader_lease.py
index 2300340f9..945dddf60 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_application_leader_lease.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_application_leader_lease.py
@@ -9,7 +9,12 @@
class FakeLeaseRedis:
- """支持Application leader租约语义的内存Redis。"""
+ """
+ 支持Application leader租约语义的内存Redis。
+
+ :ivar values: 当前处理的值集合
+ :ivar expires: 记录的到期时间
+ """
def __init__(self) -> None:
"""初始化内存锁状态。"""
@@ -17,7 +22,15 @@ def __init__(self) -> None:
self.expires: dict[str, int] = {}
async def set(self, key: str, value: str, *, nx: bool, ex: int) -> bool:
- """模拟SET NX EX。"""
+ """
+ 模拟SET NX EX。
+
+ :param key: 查找数据时使用的键
+ :param value: 待处理的输入值
+ :param nx: 是否只在键尚不存在时写入
+ :param ex: 捕获到的异常实例
+ :return: 是否模拟SET NX EX
+ """
if nx and key in self.values:
return False
self.values[key] = value
@@ -25,11 +38,25 @@ async def set(self, key: str, value: str, *, nx: bool, ex: int) -> bool:
return True
async def get(self, key: str) -> str | None:
- """读取锁值。"""
+ """
+ 读取锁值。
+
+ :param key: 查找数据时使用的键
+ :return: 锁值
+ """
return self.values.get(key)
async def eval(self, script: str, _key_count: int, key: str, *args: object) -> int:
- """模拟compare-and-expire和compare-and-delete脚本。"""
+ """
+ 模拟compare-and-expire和compare-and-delete脚本。
+
+ :param script: 需要运行的脚本
+ :param _key_count: Redis 脚本接收的键数
+ :param key: 查找数据时使用的键
+ :param args: 传给被调用对象的位置参数
+ :return: 比较并续期或删除操作的成功标志
+ :raises AssertionError: 执行了测试未预期的租约脚本
+ """
owner_token = str(args[0])
if self.values.get(key) != owner_token:
return 0
diff --git a/ruoyi-fastapi-backend/tests/utils/test_cron_util.py b/ruoyi-fastapi-backend/tests/utils/test_cron_util.py
index 7fcdaad4b..87a906906 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_cron_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_cron_util.py
@@ -33,6 +33,7 @@
ids=['before-gap', 'before-fold', 'on-gap', 'on-fold'],
)
def test_preview_matches_persisted_trigger_across_dst(expression: str, start: str, expected: list[str]) -> None:
+ """跨夏令时的预览与持久化触发器一致。"""
start_time = datetime.fromisoformat(start)
preview = CronUtil.next_run_times(expression, 'America/New_York', start_time, 3)
trigger = pickle.loads(pickle.dumps(MyCronTrigger.from_crontab(expression, 'America/New_York')))
@@ -54,11 +55,13 @@ def test_preview_matches_persisted_trigger_across_dst(expression: str, start: st
],
)
def test_quartz_week_and_workday_semantics(expression: str, expected: list[str]) -> None:
+ """验证 Quartz 对星期和工作日的解释。"""
times = CronUtil.next_run_times(expression, 'UTC', datetime(2026, 2, 1, tzinfo=UTC), 2)
assert [value.date().isoformat() for value in times] == expected
def test_cron_trigger_uses_explicit_business_timezone() -> None:
+ """Cron 触发器使用显式指定的业务时区。"""
trigger = MyCronTrigger.from_crontab('0 0 9 * * ?', 'Asia/Shanghai')
fire_time = trigger.get_next_fire_time(None, datetime(2026, 1, 1, tzinfo=UTC))
diff --git a/ruoyi-fastapi-backend/tests/utils/test_current_user_cache_util.py b/ruoyi-fastapi-backend/tests/utils/test_current_user_cache_util.py
index b31258f08..57ef06a9f 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_current_user_cache_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_current_user_cache_util.py
@@ -33,7 +33,11 @@
@pytest.fixture(scope='module')
def redis_socket() -> Iterator[IsolatedRedisServer]:
- """启动隔离 Redis;保留 fixture 名称供现有缓存与会话测试复用。"""
+ """
+ 启动隔离 Redis;保留 fixture 名称供现有缓存与会话测试复用。
+
+ :yield: 逐项产生的 ``server``
+ """
executable = redis_server_executable()
if executable is None:
pytest.skip('真实缓存脚本测试需要 redis-server,可通过 RUOYI_TEST_REDIS_SERVER 指定')
@@ -43,7 +47,12 @@ def redis_socket() -> Iterator[IsolatedRedisServer]:
@pytest_asyncio.fixture
async def cache_redis(redis_socket: IsolatedRedisServer) -> AsyncIterator[Redis]:
- """每项测试使用独立客户端并清空专属测试实例。"""
+ """
+ 每项测试使用独立客户端并清空专属测试实例。
+
+ :param redis_socket: 启动隔离 Redis;保留 fixture 名称供现有缓存与会话测试复用
+ :yield: 用于缓存或发布消息的 Redis 客户端
+ """
redis = Redis(**redis_socket.connection)
try:
for _attempt in range(10):
@@ -61,6 +70,13 @@ async def cache_redis(redis_socket: IsolatedRedisServer) -> AsyncIterator[Redis]
def user_model(user_id: int = USER_ID, permission: str = 'demo:read') -> CurrentUserModel:
+ """
+ 创建测试使用的 ``CurrentUserModel`` 实例。
+
+ :param user_id: 用户的唯一标识
+ :param permission: 当前请求需要的权限标识
+ :return: 测试使用的 ``CurrentUserModel`` 实例
+ """
return CurrentUserModel(
permissions=[permission],
roles=['reader'],
@@ -73,6 +89,13 @@ def user_model(user_id: int = USER_ID, permission: str = 'demo:read') -> Current
async def prime_cache(redis: Redis, user_id: int = USER_ID) -> CurrentUserModel:
+ """
+ 为指定用户预先填充测试缓存。
+
+ :param redis: 用于缓存或发布消息的 Redis 客户端
+ :param user_id: 用户的唯一标识
+ :return: 当前操作对应的用户
+ """
user = user_model(user_id)
cached, ticket = await CurrentUserCacheUtil.read(redis, NAMESPACE, user_id, TTL_SECONDS)
assert cached is None
@@ -83,6 +106,7 @@ async def prime_cache(redis: Redis, user_id: int = USER_ID) -> CurrentUserModel:
@pytest.mark.asyncio
async def test_round_trip_isolates_models_and_omits_password_and_dynamic_fields(cache_redis: Redis) -> None:
+ """缓存读写隔离模型并排除密码和动态字段。"""
original = await prime_cache(cache_redis)
cached, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
assert cached is not None
@@ -105,6 +129,7 @@ async def test_round_trip_isolates_models_and_omits_password_and_dynamic_fields(
@pytest.mark.asyncio
async def test_password_hash_is_never_serialized(cache_redis: Redis) -> None:
+ """密码哈希不参与序列化。"""
_, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
user = user_model()
user.user.password = 'secret-hash'
@@ -119,6 +144,7 @@ async def test_password_hash_is_never_serialized(cache_redis: Redis) -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('shared', [False, True])
async def test_invalidation_rejects_old_query_results(cache_redis: Redis, shared: bool) -> None:
+ """缓存失效后拒绝旧查询结果。"""
_, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
assert await CurrentUserCacheUtil.invalidate(cache_redis, NAMESPACE, None if shared else {USER_ID})
assert not await CurrentUserCacheUtil.write(cache_redis, NAMESPACE, USER_ID, user_model(), ticket)
@@ -129,12 +155,18 @@ async def test_invalidation_rejects_old_query_results(cache_redis: Redis, shared
@pytest.mark.asyncio
async def test_concurrent_queries_cannot_repopulate_after_invalidation(cache_redis: Redis) -> None:
+ """缓存失效后并发查询不能重新填入旧数据。"""
query_count = 8
prepared = []
all_started = asyncio.Event()
complete_queries = asyncio.Event()
async def query_and_fill() -> bool:
+ """
+ 使用读取票据回填用户缓存。
+
+ :return: 是否使用读取票据回填用户缓存
+ """
_, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
prepared.append(ticket)
if len(prepared) == query_count:
@@ -157,6 +189,7 @@ async def query_and_fill() -> bool:
@pytest.mark.asyncio
async def test_user_invalidation_preserves_other_users_and_global_invalidates_all(cache_redis: Redis) -> None:
+ """单用户失效保留其他用户数据,全局失效清除所有用户。"""
await prime_cache(cache_redis, USER_ID)
await prime_cache(cache_redis, OTHER_USER_ID)
assert await CurrentUserCacheUtil.invalidate(cache_redis, NAMESPACE, {USER_ID})
@@ -169,6 +202,7 @@ async def test_user_invalidation_preserves_other_users_and_global_invalidates_al
@pytest.mark.asyncio
@pytest.mark.parametrize('key_index', [0, 1])
async def test_missing_epoch_never_restores_existing_snapshot(cache_redis: Redis, key_index: int) -> None:
+ """缺少版本标识时不会恢复已有快照。"""
await prime_cache(cache_redis)
keys = CurrentUserCacheUtil._keys(NAMESPACE, USER_ID)
previous = await cache_redis.get(keys[key_index])
@@ -181,6 +215,7 @@ async def test_missing_epoch_never_restores_existing_snapshot(cache_redis: Redis
@pytest.mark.asyncio
async def test_fixed_deadline_is_not_extended_by_slow_fill_or_reads(cache_redis: Redis) -> None:
+ """慢速写入或读取不会延长固定截止时间。"""
_, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
await asyncio.sleep(0.03)
assert await CurrentUserCacheUtil.write(cache_redis, NAMESPACE, USER_ID, user_model(), ticket)
@@ -195,6 +230,7 @@ async def test_fixed_deadline_is_not_extended_by_slow_fill_or_reads(cache_redis:
@pytest.mark.asyncio
async def test_user_epoch_has_idle_expiry_without_extending_snapshot_deadline(cache_redis: Redis) -> None:
+ """用户版本可按空闲时间过期且不延长快照寿命。"""
await prime_cache(cache_redis)
global_key, user_key, snapshot_key = CurrentUserCacheUtil._keys(NAMESPACE, USER_ID)
epoch_ttl_ms = CurrentUserCacheUtil._USER_EPOCH_TTL_SECONDS * 1000
@@ -209,6 +245,7 @@ async def test_user_epoch_has_idle_expiry_without_extending_snapshot_deadline(ca
@pytest.mark.asyncio
async def test_invalidation_expires_user_epochs_but_keeps_global_epoch(cache_redis: Redis) -> None:
+ """失效操作使用户版本过期并保留全局版本。"""
assert await CurrentUserCacheUtil.invalidate(cache_redis, NAMESPACE, {USER_ID, OTHER_USER_ID})
for user_id in (USER_ID, OTHER_USER_ID):
user_key = CurrentUserCacheUtil._keys(NAMESPACE, user_id)[1]
@@ -219,6 +256,7 @@ async def test_invalidation_expires_user_epochs_but_keeps_global_epoch(cache_red
@pytest.mark.asyncio
async def test_query_past_its_original_deadline_cannot_fill(cache_redis: Redis) -> None:
+ """查询超过初始截止时间后不能回填。"""
_, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
expired = replace(ticket, created_at_ms=ticket.created_at_ms - TTL_MS, deadline_ms=ticket.created_at_ms - 1)
assert not await CurrentUserCacheUtil.write(cache_redis, NAMESPACE, USER_ID, user_model(), expired)
@@ -227,6 +265,7 @@ async def test_query_past_its_original_deadline_cannot_fill(cache_redis: Redis)
@pytest.mark.asyncio
async def test_late_older_query_cannot_replace_newer_snapshot(cache_redis: Redis) -> None:
+ """迟到的旧查询不能替换较新的快照。"""
_, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
older = replace(ticket, created_at_ms=ticket.created_at_ms - 100)
assert await CurrentUserCacheUtil.write(cache_redis, NAMESPACE, USER_ID, user_model(permission='new'), ticket)
@@ -237,6 +276,7 @@ async def test_late_older_query_cannot_replace_newer_snapshot(cache_redis: Redis
@pytest.mark.asyncio
async def test_shorter_configured_ttl_does_not_accept_previously_longer_snapshot(cache_redis: Redis) -> None:
+ """缩短配置有效期后拒绝原先寿命更长的快照。"""
_, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
old = replace(ticket, created_at_ms=ticket.created_at_ms - TTL_MS)
assert await CurrentUserCacheUtil.write(cache_redis, NAMESPACE, USER_ID, user_model(), old)
@@ -246,6 +286,7 @@ async def test_shorter_configured_ttl_does_not_accept_previously_longer_snapshot
@pytest.mark.asyncio
async def test_restored_expired_payload_is_not_accepted_even_if_redis_key_has_new_ttl(cache_redis: Redis) -> None:
+ """即使 Redis 键获得新有效期也拒绝已过期的内容。"""
await prime_cache(cache_redis)
snapshot_key = CurrentUserCacheUtil._keys(NAMESPACE, USER_ID)[2]
await cache_redis.hset(snapshot_key, 'deadline', 1)
@@ -256,6 +297,7 @@ async def test_restored_expired_payload_is_not_accepted_even_if_redis_key_has_ne
@pytest.mark.asyncio
@pytest.mark.parametrize('damage', ['json', 'user_id', 'password', 'disabled', 'deleted', 'null'])
async def test_damaged_snapshot_is_not_used(cache_redis: Redis, damage: str) -> None:
+ """损坏的快照不可使用。"""
await prime_cache(cache_redis)
key = CurrentUserCacheUtil._keys(NAMESPACE, USER_ID)[2]
payload = json.loads(await cache_redis.hget(key, 'payload'))
@@ -282,6 +324,7 @@ async def test_damaged_snapshot_is_not_used(cache_redis: Redis, damage: str) ->
@pytest.mark.asyncio
async def test_namespaces_and_users_do_not_share_snapshots(cache_redis: Redis) -> None:
+ """不同命名空间和用户不共享快照。"""
await prime_cache(cache_redis)
assert (await CurrentUserCacheUtil.read(cache_redis, 'another-database', USER_ID, TTL_SECONDS))[0] is None
assert (await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, OTHER_USER_ID, TTL_SECONDS))[0] is None
@@ -289,6 +332,7 @@ async def test_namespaces_and_users_do_not_share_snapshots(cache_redis: Redis) -
@pytest.mark.asyncio
async def test_empty_invalidation_does_not_invalidate_other_users(cache_redis: Redis) -> None:
+ """空的失效请求不影响其他用户。"""
await prime_cache(cache_redis)
assert await CurrentUserCacheUtil.invalidate(cache_redis, NAMESPACE, set())
assert (await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS))[0] is not None
@@ -297,6 +341,7 @@ async def test_empty_invalidation_does_not_invalidate_other_users(cache_redis: R
@pytest.mark.asyncio
@pytest.mark.parametrize('error_type', [RedisConnectionError, RedisTimeoutError, ResponseError])
async def test_cache_failure_returns_to_database_without_claiming_success(error_type: type[Exception]) -> None:
+ """缓存故障时回退到数据库且不报告缓存成功。"""
redis = AsyncMock(spec=Redis)
redis.eval.side_effect = error_type('unavailable')
assert await CurrentUserCacheUtil.read(redis, NAMESPACE, USER_ID, TTL_SECONDS) == (None, None)
@@ -308,6 +353,7 @@ async def test_cache_failure_returns_to_database_without_claiming_success(error_
@pytest.mark.asyncio
@pytest.mark.parametrize('result', [None, 1, [], ['global', 'user', '1', '2'], ['global', 'user', None, '2', '']])
async def test_malformed_redis_response_falls_back_to_database(result: object) -> None:
+ """Redis 返回格式错误时回退到数据库。"""
redis = AsyncMock(spec=Redis)
redis.eval.return_value = result
assert await CurrentUserCacheUtil.read(redis, NAMESPACE, USER_ID, TTL_SECONDS) == (None, None)
@@ -318,10 +364,16 @@ async def test_malformed_redis_response_falls_back_to_database(result: object) -
async def test_slow_cache_operation_is_bounded_and_cancelled(
cache_redis: Redis, operation: str, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """限制慢缓存操作的等待时间并取消操作。"""
_, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
stopped = asyncio.Event()
async def slow_eval(*args: object) -> None:
+ """
+ 模拟迟迟未完成的缓存脚本。
+
+ :param args: 传给被调用对象的位置参数
+ """
try:
await asyncio.Event().wait()
finally:
@@ -342,6 +394,7 @@ async def slow_eval(*args: object) -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('operation', ['read', 'write', 'invalidate'])
async def test_cancellation_is_propagated(cache_redis: Redis, operation: str) -> None:
+ """取消信号向调用方传播。"""
_, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
redis = AsyncMock(spec=Redis)
redis.eval.side_effect = asyncio.CancelledError
@@ -356,10 +409,16 @@ async def test_cancellation_is_propagated(cache_redis: Redis, operation: str) ->
@pytest.mark.asyncio
async def test_cancelling_caller_stops_pending_redis_operation() -> None:
+ """调用方取消后停止待处理的 Redis 操作。"""
started = asyncio.Event()
stopped = asyncio.Event()
async def blocking_eval(*args: object) -> None:
+ """
+ 在执行缓存脚本时等待测试控制信号。
+
+ :param args: 传给被调用对象的位置参数
+ """
started.set()
try:
await asyncio.Event().wait()
@@ -380,11 +439,17 @@ async def blocking_eval(*args: object) -> None:
@pytest.mark.parametrize('operation', ['read', 'write', 'invalidate'])
@pytest.mark.parametrize('cancellation', ['task_group', 'deadline'])
async def test_anyio_parent_cancellation_is_not_converted_to_cache_fallback(operation: str, cancellation: str) -> None:
+ """AnyIO 父级取消信号不会被转换为缓存回退。"""
started = anyio.Event()
stopped = anyio.Event()
results = []
async def blocking_eval(*args: object) -> None:
+ """
+ 在执行缓存脚本时等待测试控制信号。
+
+ :param args: 传给被调用对象的位置参数
+ """
started.set()
try:
await anyio.sleep_forever()
@@ -396,6 +461,7 @@ async def blocking_eval(*args: object) -> None:
ticket = CurrentUserCacheTicket('global', 'user', 0, TTL_MS)
async def run_operation() -> None:
+ """执行指定的用户缓存操作并收集结果。"""
if operation == 'read':
result = await CurrentUserCacheUtil.read(redis, NAMESPACE, USER_ID, TTL_SECONDS)
elif operation == 'write':
@@ -436,6 +502,12 @@ async def test_cancellation_waits_for_redis_connection_release( # noqa: PLR0915
monkeypatch.setattr(CurrentUserCacheUtil, '_OPERATION_TIMEOUT_SECONDS', 0.02 if timed_out else 1)
async def blocking_command(*args: object, **kwargs: object) -> None:
+ """
+ 等待测试控制信号后完成命令。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ """
started.set()
try:
await asyncio.Event().wait()
@@ -446,6 +518,11 @@ async def blocking_command(*args: object, **kwargs: object) -> None:
ticket = CurrentUserCacheTicket('global', 'user', 0, TTL_MS)
async def run_operation() -> None:
+ """
+ 执行指定的用户缓存操作并收集结果。
+
+ :raises asyncio.CancelledError: 异步操作被取消时
+ """
with request_scope:
try:
if operation == 'read':
@@ -504,9 +581,16 @@ async def run_operation() -> None:
async def test_redis_cleanup_error_does_not_replace_timeout_or_cancellation(
cancellation: str, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """Redis 清理错误不会覆盖超时或取消。"""
started = asyncio.Event()
async def failing_cleanup(*args: object) -> None:
+ """
+ 模拟资源清理过程中发生故障。
+
+ :param args: 传给被调用对象的位置参数
+ :raises RuntimeError: 模拟清理失败
+ """
started.set()
try:
await asyncio.Event().wait()
@@ -528,12 +612,14 @@ async def failing_cleanup(*args: object) -> None:
@pytest.mark.asyncio
async def test_disabled_cache_never_accesses_redis() -> None:
+ """禁用缓存时不访问 Redis。"""
redis = AsyncMock(spec=Redis)
assert await CurrentUserCacheUtil.read(redis, NAMESPACE, USER_ID, 0) == (None, None)
redis.eval.assert_not_called()
def test_namespace_is_stable_for_engine_and_connection_and_unknown_bind_bypasses() -> None:
+ """引擎与连接使用稳定命名空间,未知绑定绕过缓存。"""
engine = create_engine('sqlite://')
try:
with engine.connect() as connection:
@@ -548,6 +634,7 @@ def test_namespace_is_stable_for_engine_and_connection_and_unknown_bind_bypasses
@pytest.mark.asyncio
async def test_async_and_sync_bind_share_namespace() -> None:
+ """异步与同步绑定共享命名空间。"""
engine = create_async_engine('sqlite+aiosqlite://')
try:
async with engine.connect() as connection:
diff --git a/ruoyi-fastapi-backend/tests/utils/test_jwt_util.py b/ruoyi-fastapi-backend/tests/utils/test_jwt_util.py
index 94bcf0ee0..1ee163a66 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_jwt_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_jwt_util.py
@@ -9,6 +9,7 @@
@pytest.mark.parametrize('jwt_error', [DecodeError(), InvalidAlgorithmError(), InvalidKeyError()])
def test_decode_converts_pyjwt_errors_to_auth_exception(jwt_error: Exception) -> None:
+ """解码时将 PyJWT 错误转换为认证异常。"""
with (
patch('utils.jwt_util.jwt.decode', side_effect=jwt_error),
pytest.raises(AuthException) as exc_info,
@@ -20,6 +21,7 @@ def test_decode_converts_pyjwt_errors_to_auth_exception(jwt_error: Exception) ->
@pytest.mark.parametrize('jwt_error', [InvalidAlgorithmError(), InvalidKeyError()])
def test_encode_converts_pyjwt_errors_to_auth_exception(jwt_error: Exception) -> None:
+ """编码时将 PyJWT 错误转换为认证异常。"""
with (
patch('utils.jwt_util.jwt.encode', side_effect=jwt_error),
pytest.raises(AuthException) as exc_info,
diff --git a/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py b/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py
index 53f9fb248..16d70ee53 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py
@@ -17,11 +17,17 @@
@pytest.fixture(autouse=True)
def enable_log_mask_for_tests() -> Iterator[None]:
+ """
+ 在测试期间启用日志脱敏。
+
+ :yield: 上下文就绪后将控制权交给调用方
+ """
with patch.object(LogConfig, 'log_mask_enabled', True):
yield
def test_sanitize_nested_log_payload() -> None:
+ """对嵌套日志数据脱敏。"""
payload = {
'jsonBody': {
'password': 'plain-password',
@@ -44,6 +50,7 @@ def test_sanitize_nested_log_payload() -> None:
def test_ip_masking_can_be_enabled_by_partial_mask_field_configuration() -> None:
+ """可通过部分掩码字段配置启用 IP 脱敏。"""
payload = {
'jsonBody': {
'ipaddr': '192.168.1.10',
@@ -63,6 +70,7 @@ def test_ip_masking_can_be_enabled_by_partial_mask_field_configuration() -> None
def test_sanitize_config_value_by_config_key() -> None:
+ """按配置键对配置值脱敏。"""
payload = {
'configKey': 'sys.transport.privateKey',
'configValue': '-----BEGIN PRIVATE KEY-----abc',
@@ -74,6 +82,7 @@ def test_sanitize_config_value_by_config_key() -> None:
def test_sanitize_text_message() -> None:
+ """对文本日志消息脱敏。"""
text = 'Authorization=Bearer abc.def password=123456 api_key=sk-test'
expected_mask_count = 3
@@ -86,6 +95,7 @@ def test_sanitize_text_message() -> None:
def test_sanitize_text_masks_configured_secret_fields() -> None:
+ """对文本中配置为敏感的字段脱敏。"""
text = (
'secret_key=my-secret private_key="-----BEGIN PRIVATE KEY-----abc" '
"credential='cred-123' credentials=cred-list"
@@ -102,6 +112,7 @@ def test_sanitize_text_masks_configured_secret_fields() -> None:
def test_sanitize_text_key_pattern_does_not_cross_lines() -> None:
+ """文本脱敏的键匹配不会跨行。"""
text = 'header\nprivate\n key=value\nfooter'
sanitized = LogSanitizer.sanitize_text(text)
@@ -110,6 +121,7 @@ def test_sanitize_text_key_pattern_does_not_cross_lines() -> None:
def test_sanitize_stringified_json_preserves_newlines_after_masking() -> None:
+ """字符串形式的 JSON 脱敏后保留换行。"""
text = '{\n "password": "123456",\n "userName": "admin"\n}'
sanitized = LogSanitizer.sanitize_data({'operParam': text})
@@ -118,6 +130,7 @@ def test_sanitize_stringified_json_preserves_newlines_after_masking() -> None:
def test_sanitize_text_masks_configured_partial_fields() -> None:
+ """文本脱敏支持配置部分掩码字段。"""
text = 'email=admin@example.com phonenumber=13812345678 mobile="13812345679"'
sanitized = LogSanitizer.sanitize_text(text)
@@ -131,6 +144,7 @@ def test_sanitize_text_masks_configured_partial_fields() -> None:
def test_sanitize_text_can_enable_ip_masking_by_partial_mask_field_configuration() -> None:
+ """文本中的 IP 可通过部分掩码配置脱敏。"""
text = 'login_ip=192.168.1.10 ipaddr="192.168.1.11"'
ip_fields = LogSanitizer._PARTIAL_MASK_FIELDS | {'ip', 'ipaddr', 'operip', 'loginip'}
ip_key_pattern = '|'.join(
@@ -156,6 +170,7 @@ def test_sanitize_text_can_enable_ip_masking_by_partial_mask_field_configuration
def test_sanitize_text_masks_python_repr_like_payload() -> None:
+ """对类似 Python repr 的文本脱敏。"""
text = "ValueError({'secret_key': 'abc', 'password': '123456', 'api_key': 'sk-123'})"
expected_mask_count = 3
@@ -168,6 +183,7 @@ def test_sanitize_text_masks_python_repr_like_payload() -> None:
def test_sanitize_text_masks_alphanumeric_verification_code() -> None:
+ """对字母数字组合的验证码脱敏。"""
text = '短信验证码为A1B2'
sanitized = LogSanitizer.sanitize_text(text)
@@ -177,6 +193,7 @@ def test_sanitize_text_masks_alphanumeric_verification_code() -> None:
def test_sanitize_text_returns_original_when_mask_disabled() -> None:
+ """关闭脱敏时保留原始文本。"""
text = 'Authorization=Bearer abc.def password=123456 api_key=sk-test'
with patch.object(LogConfig, 'log_mask_enabled', False):
@@ -186,6 +203,7 @@ def test_sanitize_text_returns_original_when_mask_disabled() -> None:
def test_build_json_payload_sanitizes_exception_and_extra() -> None:
+ """构造 JSON 日志时对异常和附加字段脱敏。"""
initializer = LoggerInitializer()
try:
raise ValueError('token=abc.def')
@@ -219,6 +237,7 @@ def test_build_json_payload_sanitizes_exception_and_extra() -> None:
def test_json_log_formatter_emits_valid_json_record() -> None:
+ """JSON 日志格式化器输出有效的 JSON 记录。"""
initializer = LoggerInitializer()
outputs = []
test_logger = _logger.patch(initializer._patch_record)
@@ -238,6 +257,7 @@ def test_json_log_formatter_emits_valid_json_record() -> None:
def test_json_log_formatter_does_not_leak_internal_payload_between_handlers() -> None:
+ """不同处理器间不泄露 JSON 日志内部数据。"""
initializer = LoggerInitializer()
first_outputs = []
second_outputs = []
@@ -261,6 +281,7 @@ def test_json_log_formatter_does_not_leak_internal_payload_between_handlers() ->
def test_plain_log_formatter_sanitizes_exception_traceback() -> None:
+ """纯文本日志对异常堆栈脱敏。"""
initializer = LoggerInitializer()
outputs = []
test_logger = _logger.patch(initializer._patch_record)
@@ -287,6 +308,7 @@ def test_plain_log_formatter_sanitizes_exception_traceback() -> None:
def test_plain_log_formatter_separates_consecutive_records() -> None:
+ """纯文本日志分隔连续记录。"""
initializer = LoggerInitializer()
outputs = []
expected_output_count = 2
@@ -307,7 +329,14 @@ def test_plain_log_formatter_separates_consecutive_records() -> None:
def test_get_request_params_returns_structured_payload() -> None:
+ """读取请求参数时返回结构化数据。"""
+
async def receive() -> dict:
+ """
+ 提供下游 ASGI 应用读取的 HTTP 请求体消息。
+
+ :return: 下游 ASGI 应用读取的 HTTP 请求体消息
+ """
return {
'type': 'http.request',
'body': b'{"password":"plain-password","phonenumber":"13812345678"}',
@@ -334,7 +363,14 @@ async def receive() -> dict:
def test_get_request_params_falls_back_to_raw_body_when_json_invalid() -> None:
+ """无效 JSON 请求体回退为原始内容。"""
+
async def receive() -> dict:
+ """
+ 提供下游 ASGI 应用读取的 HTTP 请求体消息。
+
+ :return: 下游 ASGI 应用读取的 HTTP 请求体消息
+ """
return {
'type': 'http.request',
'body': b'{bad json',
@@ -364,7 +400,14 @@ async def receive() -> dict:
def test_get_request_params_decodes_non_utf8_body_without_raising() -> None:
+ """非 UTF-8 请求体可以安全解码。"""
+
async def receive() -> dict:
+ """
+ 提供下游 ASGI 应用读取的 HTTP 请求体消息。
+
+ :return: 下游 ASGI 应用读取的 HTTP 请求体消息
+ """
return {
'type': 'http.request',
'body': b'\xff\xfeabc',
@@ -391,6 +434,7 @@ async def receive() -> dict:
def test_log_handles_missing_user_agent_without_error() -> None:
+ """缺少用户代理时仍能记录日志。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER, log_type='login')
assert log_decorator._get_oper_type(None) == 0
@@ -410,6 +454,7 @@ def test_log_handles_missing_user_agent_without_error() -> None:
def test_build_log_text_with_summary_mode() -> None:
+ """摘要模式下生成日志文本。"""
log_decorator = Log(
title='测试日志',
business_type=BusinessType.OTHER,
@@ -436,6 +481,7 @@ def test_build_log_text_with_summary_mode() -> None:
def test_build_log_text_with_include_mode() -> None:
+ """包含模式下生成日志文本。"""
log_decorator = Log(
title='测试日志',
business_type=BusinessType.OTHER,
@@ -465,6 +511,7 @@ def test_build_log_text_with_include_mode() -> None:
def test_include_fields_support_snake_case_matching_camel_case_payload() -> None:
+ """蛇形包含规则可匹配驼峰字段。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
log_text = log_decorator._build_log_text(
@@ -488,6 +535,7 @@ def test_include_fields_support_snake_case_matching_camel_case_payload() -> None
def test_include_fields_support_camel_case_matching_snake_case_payload() -> None:
+ """驼峰包含规则可匹配蛇形字段。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
log_text = log_decorator._build_log_text(
@@ -511,11 +559,13 @@ def test_include_fields_support_camel_case_matching_snake_case_payload() -> None
def test_request_field_helper_builds_canonical_path() -> None:
+ """请求字段辅助函数生成规范路径。"""
assert RequestLogFieldRoot.JSON_BODY.field('model_code') == 'json_body.model_code'
assert ResponseLogFieldRoot.DATA.field('userName') == 'data.userName'
def test_code_field_masking_only_applies_to_login_like_verification_code() -> None:
+ """仅对登录验证码等相应的 code 字段脱敏。"""
login_payload = {
'uuid': 'captcha-session',
'code': 'A1B2',
@@ -534,6 +584,7 @@ def test_code_field_masking_only_applies_to_login_like_verification_code() -> No
def test_build_log_text_with_exclude_mode() -> None:
+ """排除模式下生成日志文本。"""
log_decorator = Log(
title='测试日志',
business_type=BusinessType.OTHER,
@@ -564,6 +615,7 @@ def test_build_log_text_with_exclude_mode() -> None:
def test_exclude_fields_support_snake_case_matching_camel_case_payload() -> None:
+ """蛇形排除规则可匹配驼峰字段。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
log_text = log_decorator._build_log_text(
@@ -587,6 +639,7 @@ def test_exclude_fields_support_snake_case_matching_camel_case_payload() -> None
def test_exclude_fields_remove_multiple_list_indexes_without_shift() -> None:
+ """排除多个列表索引时避免位置偏移。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
log_text = log_decorator._build_log_text(
@@ -610,6 +663,7 @@ def test_exclude_fields_remove_multiple_list_indexes_without_shift() -> None:
def test_collect_field_path_warnings_for_invalid_root() -> None:
+ """字段路径根无效时收集警告。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
warnings = log_decorator._collect_field_path_warnings(
@@ -625,6 +679,7 @@ def test_collect_field_path_warnings_for_invalid_root() -> None:
def test_collect_field_path_warnings_accepts_normalized_root() -> None:
+ """字段路径检查接受规范化的根名称。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
warnings = log_decorator._collect_field_path_warnings(
@@ -638,6 +693,7 @@ def test_collect_field_path_warnings_accepts_normalized_root() -> None:
def test_collect_field_path_warnings_for_missing_include_fields() -> None:
+ """包含字段缺失时收集路径警告。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
warnings = log_decorator._collect_field_path_warnings(
@@ -653,6 +709,7 @@ def test_collect_field_path_warnings_for_missing_include_fields() -> None:
def test_collect_field_path_warnings_for_missing_exclude_fields() -> None:
+ """排除字段缺失时收集路径警告。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
warnings = log_decorator._collect_field_path_warnings(
@@ -668,6 +725,7 @@ def test_collect_field_path_warnings_for_missing_exclude_fields() -> None:
def test_log_warns_when_include_fields_do_not_match_mode() -> None:
+ """包含字段与日志模式不符时记录警告。"""
with patch('common.annotation.log_annotation.logger.warning') as mock_warning:
Log(
title='测试日志',
@@ -681,6 +739,7 @@ def test_log_warns_when_include_fields_do_not_match_mode() -> None:
def test_request_include_fields_invalid_root_raises_value_error() -> None:
+ """请求包含字段的根无效时引发 ValueError。"""
try:
Log(
title='测试日志',
@@ -695,6 +754,7 @@ def test_request_include_fields_invalid_root_raises_value_error() -> None:
def test_request_exclude_fields_invalid_root_raises_value_error() -> None:
+ """请求排除字段的根无效时引发 ValueError。"""
try:
Log(
title='测试日志',
@@ -709,6 +769,7 @@ def test_request_exclude_fields_invalid_root_raises_value_error() -> None:
def test_build_log_text_warns_for_missing_include_field() -> None:
+ """构造日志时提示缺少包含字段。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
with patch('common.annotation.log_annotation.logger.warning') as mock_warning:
@@ -735,6 +796,7 @@ def test_build_log_text_warns_for_missing_include_field() -> None:
def test_missing_include_field_warning_only_emitted_once() -> None:
+ """同一缺失包含字段只提示一次。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
payload = LogSanitizer.sanitize_data({'data': {'userName': 'admin'}})
@@ -758,6 +820,7 @@ def test_missing_include_field_warning_only_emitted_once() -> None:
def test_include_fields_keep_explicit_none_value() -> None:
+ """包含规则保留显式空值。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
with patch('common.annotation.log_annotation.logger.warning') as mock_warning:
@@ -783,6 +846,7 @@ def test_include_fields_keep_explicit_none_value() -> None:
def test_include_field_warning_reports_ambiguous_normalized_match() -> None:
+ """规范化后匹配有歧义时报告包含字段警告。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
with patch('common.annotation.log_annotation.logger.warning') as mock_warning:
@@ -811,6 +875,7 @@ def test_include_field_warning_reports_ambiguous_normalized_match() -> None:
def test_build_log_text_warns_for_missing_exclude_field() -> None:
+ """构造日志时提示缺少排除字段。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
with patch('common.annotation.log_annotation.logger.warning') as mock_warning:
@@ -836,6 +901,7 @@ def test_build_log_text_warns_for_missing_exclude_field() -> None:
def test_build_summary_payload_supports_message_field_fallback() -> None:
+ """摘要数据支持回退使用消息字段。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
summary_payload = log_decorator._build_summary_payload({'code': 200, 'message': '获取成功'}, 'response')
@@ -847,6 +913,7 @@ def test_build_summary_payload_supports_message_field_fallback() -> None:
def test_log_decorator_truncates_oversized_json_result() -> None:
+ """日志装饰器截断超大 JSON 结果。"""
log_decorator = Log(title='测试日志', business_type=BusinessType.OTHER)
json_result = log_decorator._build_log_text(
{'code': 200, 'data': {'content': 'x' * 2100}},
diff --git a/ruoyi-fastapi-backend/tests/utils/test_oidc_util.py b/ruoyi-fastapi-backend/tests/utils/test_oidc_util.py
index 35b5c9d22..50097a154 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_oidc_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_oidc_util.py
@@ -18,6 +18,7 @@
def test_query_replacement_preserves_unrelated_duplicates_blank_values_and_fragment() -> None:
+ """替换查询参数时保留无关重复项、空值和片段。"""
location = OidcUtil.replace_query_parameters(
'https://rp.example/cb?keep=one&keep=two&empty=&state=old&error=old#part',
[('code', 'a+/='), ('state', '中文 +&')],
@@ -29,12 +30,14 @@ def test_query_replacement_preserves_unrelated_duplicates_blank_values_and_fragm
def test_logout_state_distinguishes_missing_and_empty_state() -> None:
+ """注销流程区分缺少状态和空状态。"""
uri = 'https://rp.example/cb?state=old&keep=1&state=older'
assert OidcUtil.append_state(uri, None) == uri
assert OidcUtil.append_state(uri, '') == 'https://rp.example/cb?keep=1&state='
def test_interaction_csrf_is_only_in_fragment() -> None:
+ """交互 CSRF 令牌仅出现在 URL 片段中。"""
assert OidcUtil.interaction_url('https://id.example/login?lang=zh#old', 'i-1', 's+/=') == (
'https://id.example/login?lang=zh&interaction=i-1#csrf=s+/='
)
@@ -42,17 +45,20 @@ def test_interaction_csrf_is_only_in_fragment() -> None:
@pytest.mark.parametrize(('validate_all_first', 'message'), [(False, '参数重复'), (True, '参数无效')])
def test_batch_validation_preserves_each_callers_error_precedence(validate_all_first: bool, message: str) -> None:
+ """批量校验保留各调用方的错误优先级。"""
with pytest.raises(ValueError, match=message):
OidcUtil.split_batch('one,one,bad/path', 'ids', max_size=100, validate_all_first=validate_all_first)
@pytest.mark.parametrize('value', ['one,,two', 'one,%2Ftwo', 'one,t wo', 'one,t\\wo'])
def test_batch_rejects_ambiguous_path_identifiers(value: str) -> None:
+ """批量请求拒绝有歧义的路径标识。"""
with pytest.raises(ValueError, match='参数无效'):
OidcUtil.split_batch(value, 'ids', max_size=100)
def test_json_keeps_unicode_and_key_order_without_accepting_duplicate_input_keys() -> None:
+ """JSON 保留 Unicode 和键顺序并拒绝重复输入键。"""
assert OidcUtil.serialize_json({'z': [1], 'a': '中文'}, error_message='载荷无效') == '{"a":"中文","z":[1]}'
with pytest.raises(ValueError, match='重复字段'):
json.loads('{"nested":{"scope":"openid","scope":"admin"}}', object_pairs_hook=OidcUtil.json_object_pairs)
@@ -60,11 +66,13 @@ def test_json_keeps_unicode_and_key_order_without_accepting_duplicate_input_keys
@pytest.mark.parametrize('value', [float('nan'), float('inf'), float('-inf'), object()])
def test_cache_json_rejects_nonfinite_numbers_and_nonserializable_objects(value: object) -> None:
+ """缓存 JSON 拒绝非有限数值及不可序列化对象。"""
with pytest.raises(ValueError, match='载荷无效'):
OidcUtil.serialize_json({'value': value}, error_message='载荷无效')
def test_digest_vectors_preserve_existing_wire_and_browser_binding_formats() -> None:
+ """摘要测试向量与原传输及浏览器绑定格式一致。"""
assert OidcUtil.sha256_digest('abc') == 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'
assert OidcUtil.hmac_sha256('Hi There', b'\x0b' * 20) == (
'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7'
@@ -78,10 +86,12 @@ def test_digest_vectors_preserve_existing_wire_and_browser_binding_formats() ->
@pytest.mark.parametrize('ciphertext', [_V1_CIPHERTEXT, _V2_CIPHERTEXT], ids=['legacy-v1', 'salted-v2'])
def test_decrypt_accepts_persisted_private_key_formats(ciphertext: str) -> None:
+ """解密支持已持久化的私钥格式。"""
assert OidcUtil.decrypt_signing_private_key(ciphertext, b'm' * 32) == b'private-key-regression-fixture'
def test_encrypt_preserves_v2_envelope_and_rejects_wrong_decryption_key() -> None:
+ """加密保留第二版封装并拒绝错误解密密钥。"""
ciphertext = OidcUtil.encrypt_signing_private_key(
b'private-key-regression-fixture', b'm' * 32, salt=bytes(range(16)), nonce=bytes(range(12))
)
@@ -92,11 +102,17 @@ def test_encrypt_preserves_v2_envelope_and_rejects_wrong_decryption_key() -> Non
@pytest.fixture(scope='module')
def public_jwk() -> dict[str, str]:
+ """
+ 生成测试使用的 RSA 公钥 JWK。
+
+ :return: 测试使用的 RSA 公钥 JWK
+ """
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
return OidcUtil.rsa_public_jwk(key.public_key(), 'k1')
def test_public_jwk_strips_private_fields_without_mutating_input(public_jwk: dict[str, str]) -> None:
+ """公开 JWK 移除私有字段且保留原输入。"""
record = SimpleNamespace(kid='k1', public_jwk={**public_jwk, 'd': 'private-material'})
actual = OidcUtil.normalize_public_jwk(record, min_rsa_bits=2048, min_exponent=3, max_exponent=2**32)
assert actual == public_jwk
@@ -108,6 +124,7 @@ def test_public_jwk_strips_private_fields_without_mutating_input(public_jwk: dic
@pytest.mark.parametrize(('field', 'value'), [('n', 'AQ'), ('e', 'Ag'), ('e', 'AQAB=')])
def test_public_jwk_rejects_weak_or_noncanonical_parameters(public_jwk: dict[str, str], field: str, value: str) -> None:
+ """公开 JWK 拒绝弱参数及非规范参数。"""
with pytest.raises(ValueError):
OidcUtil.normalize_public_jwk(
{**public_jwk, field: value}, min_rsa_bits=2048, min_exponent=3, max_exponent=2**32
@@ -127,10 +144,12 @@ def test_public_jwk_rejects_weak_or_noncanonical_parameters(public_jwk: dict[str
],
)
def test_backchannel_parser_rejects_unsafe_structures_and_literal_private_ips(uri: str) -> None:
+ """后通道解析器拒绝不安全结构及字面私有 IP。"""
assert OidcUtil.parse_backchannel_uri(uri) is None
def test_uri_helpers_preserve_different_registration_policies() -> None:
+ """URI 工具分别保留不同注册策略。"""
localhost = 'http://localhost:5173/callback'
assert OidcUtil.validate_registered_uri('redirect', localhost) == localhost
assert OidcUtil.is_safe_post_logout_uri(localhost)
@@ -148,6 +167,7 @@ def test_uri_helpers_preserve_different_registration_policies() -> None:
],
)
def test_utilities_and_exceptions_import_without_cycles_or_loading_application_state(modules: list[str]) -> None:
+ """导入工具和异常模块无需加载应用状态且无循环依赖。"""
script = (
'import importlib, sys\n'
f'for name in {modules!r}: importlib.import_module(name)\n'
diff --git a/ruoyi-fastapi-backend/tests/utils/test_response_timezone.py b/ruoyi-fastapi-backend/tests/utils/test_response_timezone.py
index 828b3168a..fff3c0a61 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_response_timezone.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_response_timezone.py
@@ -7,6 +7,7 @@
def test_response_util_serializes_nested_datetimes_as_fixed_utc_rfc3339() -> None:
+ """响应中的嵌套日期时间统一序列化为 UTC 的 RFC 3339 格式。"""
response = ResponseUtil.success(data={'createdAt': datetime(2026, 8, 28, 10, 30, 0, 123456, tzinfo=UTC)})
payload = json.loads(response.body)
@@ -16,5 +17,6 @@ def test_response_util_serializes_nested_datetimes_as_fixed_utc_rfc3339() -> Non
def test_response_util_rejects_naive_datetime_output() -> None:
+ """响应拒绝无时区日期时间。"""
with pytest.raises(ValueError, match='必须携带时区'):
ResponseUtil.success(data={'createdAt': datetime(2026, 8, 28, 10, 30)})
diff --git a/ruoyi-fastapi-backend/tests/utils/test_startup_log_filter.py b/ruoyi-fastapi-backend/tests/utils/test_startup_log_filter.py
index e56f344da..a94c3f3da 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_startup_log_filter.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_startup_log_filter.py
@@ -8,7 +8,14 @@
def build_log_record(*, level: str, level_no: int, extra: dict[str, object]) -> dict[str, object]:
- """构建 Logger filter 所需的最小日志记录。"""
+ """
+ 构建 Logger filter 所需的最小日志记录。
+
+ :param level: 日志或结果使用的级别
+ :param level_no: 日志级别的数值
+ :param extra: 添加到默认数据上的额外字段
+ :return: Logger filter 所需的最小日志记录
+ """
return {
'level': SimpleNamespace(name=level, no=level_no),
'extra': dict(extra),
diff --git a/ruoyi-fastapi-backend/tests/utils/test_template_util.py b/ruoyi-fastapi-backend/tests/utils/test_template_util.py
index af1e22ce6..0994ec916 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_template_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_template_util.py
@@ -17,6 +17,14 @@ def _gen_table(
tpl_web_type: str = 'element-ui',
tpl_category: str = 'crud',
) -> GenTableModel:
+ """
+ 构造含主键及样例字段的生成表。
+
+ :param gen_view: 是否生成详情页
+ :param tpl_web_type: 前端模板类型(element-ui、element-plus、react-antd)
+ :param tpl_category: 使用的模板(crud单表操作 tree树表操作)
+ :return: 含主键及样例字段的生成表
+ """
columns = [
GenTableColumnModel(
columnName='item_id',
@@ -89,6 +97,7 @@ def _gen_table(
],
)
def test_get_gen_view_supports_stored_option_formats(value: object, expected: bool) -> None:
+ """生成视图设置支持已存储的选项格式。"""
params = {'genView': value} if value is not None else None
assert TemplateUtils.get_gen_view(params) is expected
@@ -96,6 +105,7 @@ def test_get_gen_view_supports_stored_option_formats(value: object, expected: bo
@pytest.mark.parametrize(('value', 'expected'), [('1', True), ('0', False)])
def test_gen_table_params_accepts_frontend_string_switch(value: str, expected: bool) -> None:
+ """生成表参数接受前端字符串开关。"""
assert GenTableParamsModel(genView=value).gen_view is expected
@@ -107,6 +117,7 @@ def test_gen_table_params_accepts_frontend_string_switch(value: str, expected: b
],
)
def test_template_list_and_context_include_optional_view(tpl_web_type: str, view_template: str) -> None:
+ """模板清单和上下文包含可选视图。"""
gen_table = _gen_table(gen_view=True, tpl_web_type=tpl_web_type)
templates = TemplateUtils.get_template_list(gen_table)
@@ -118,6 +129,7 @@ def test_template_list_and_context_include_optional_view(tpl_web_type: str, view
def test_template_list_omits_view_when_disabled() -> None:
+ """关闭视图后模板清单省略该项。"""
gen_table = _gen_table(gen_view=False)
templates = TemplateUtils.get_template_list(gen_table)
@@ -130,6 +142,7 @@ def test_template_list_omits_view_when_disabled() -> None:
@pytest.mark.parametrize('tpl_web_type', ['element-ui', 'element-plus'])
@pytest.mark.parametrize('tpl_category', ['crud', 'tree'])
def test_detail_templates_render_with_list_integration(tpl_web_type: str, tpl_category: str) -> None:
+ """详情模板渲染时集成列表入口。"""
gen_table = _gen_table(gen_view=True, tpl_web_type=tpl_web_type, tpl_category=tpl_category)
context = TemplateUtils.prepare_context(gen_table)
env = TemplateInitializer.init_jinja2()
@@ -150,6 +163,7 @@ def test_detail_templates_render_with_list_integration(tpl_web_type: str, tpl_ca
@pytest.mark.asyncio
async def test_set_table_from_options_restores_view_flag() -> None:
+ """从表选项恢复视图开关。"""
gen_table = _gen_table(gen_view=True)
gen_table.view = False
@@ -161,6 +175,7 @@ async def test_set_table_from_options_restores_view_flag() -> None:
def test_secondary_source_templates_use_named_dependency_and_isolated_metadata(
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """辅助数据源模板使用具名依赖及独立元数据。"""
gen_table = _gen_table(gen_view=False)
gen_table.data_source_name = 'reporting'
monkeypatch.setattr(
@@ -189,6 +204,7 @@ def test_secondary_source_templates_use_named_dependency_and_isolated_metadata(
def test_python_templates_handle_audit_timestamps_by_exact_column_name() -> None:
+ """Python 模板按确切列名处理审计时间。"""
columns = [
GenTableColumnModel(
columnName='item_id',
@@ -278,6 +294,7 @@ def test_python_templates_handle_audit_timestamps_by_exact_column_name() -> None
def test_dao_audit_filter_uses_a_set_for_a_single_timestamp() -> None:
+ """DAO 过滤单一审计时间时仍使用集合。"""
columns = [
GenTableColumnModel(
columnName='item_id',
@@ -315,6 +332,7 @@ def test_dao_audit_filter_uses_a_set_for_a_single_timestamp() -> None:
def test_do_template_supports_required_update_time_only_mixin() -> None:
+ """数据对象模板支持仅要求更新时间的混入类。"""
columns = [
GenTableColumnModel(
columnName='item_id',
@@ -349,6 +367,7 @@ def test_do_template_supports_required_update_time_only_mixin() -> None:
def test_sub_table_entity_template_uses_required_nullable_semantics() -> None:
+ """子表实体模板区分必填字段和可空字段。"""
gen_table = _gen_table(gen_view=False, tpl_category='sub')
gen_table.sub_table_name = 'gen_item_detail'
gen_table.sub_table_fk_name = 'item_id'
@@ -413,6 +432,7 @@ def test_sub_table_entity_template_uses_required_nullable_semantics() -> None:
def test_named_data_source_bases_are_cached_and_isolated(monkeypatch: pytest.MonkeyPatch) -> None:
+ """按名称分别缓存并隔离数据源基类。"""
database.get_data_source_base.cache_clear()
monkeypatch.setattr(type(database.DataBaseConfig), 'get_source', lambda _self, _name: object())
@@ -438,6 +458,7 @@ def test_named_data_source_bases_are_cached_and_isolated(monkeypatch: pytest.Mon
def test_sqlalchemy_type_mapping_uses_target_source(
monkeypatch: pytest.MonkeyPatch, db_type: str, column_type: str, expected: str
) -> None:
+ """SQLAlchemy 类型映射使用目标数据源。"""
monkeypatch.setattr(
type(database.DataBaseConfig),
'get_source',
diff --git a/ruoyi-fastapi-backend/tests/utils/test_time_util.py b/ruoyi-fastapi-backend/tests/utils/test_time_util.py
index 08d2be162..8d4c66ec6 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_time_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_time_util.py
@@ -7,6 +7,7 @@
def test_utc_now_returns_aware_utc_datetime() -> None:
+ """获取当前 UTC 时间时返回带时区对象。"""
now = TimezoneUtil.utc_now()
assert now.tzinfo is UTC
@@ -14,11 +15,13 @@ def test_utc_now_returns_aware_utc_datetime() -> None:
def test_naive_datetime_is_rejected() -> None:
+ """拒绝未带时区的日期时间。"""
with pytest.raises(ValueError, match='必须携带时区信息'):
TimezoneUtil.ensure_aware(datetime(2026, 8, 28, 10, 0, 0))
def test_datetime_is_normalized_to_utc_and_business_timezone() -> None:
+ """日期时间可转换为 UTC 和业务时区。"""
shanghai_time = datetime.fromisoformat('2026-08-28T10:30:00+08:00')
assert TimezoneUtil.to_utc(shanghai_time) == datetime(2026, 8, 28, 2, 30, tzinfo=UTC)
@@ -26,6 +29,7 @@ def test_datetime_is_normalized_to_utc_and_business_timezone() -> None:
def test_optional_utc_preserves_none_and_rejects_naive_datetime() -> None:
+ """可选 UTC 转换保留空值并拒绝无时区时间。"""
assert TimezoneUtil.to_optional_utc(None) is None
value = datetime.fromisoformat('2026-08-28T10:30:00+08:00')
assert TimezoneUtil.to_optional_utc(value) == datetime(2026, 8, 28, 2, 30, tzinfo=UTC)
@@ -34,6 +38,7 @@ def test_optional_utc_preserves_none_and_rejects_naive_datetime() -> None:
def test_to_utc_milliseconds_truncates_sub_millisecond_precision() -> None:
+ """转换 UTC 毫秒时间时截去亚毫秒精度。"""
value = datetime.fromisoformat('2026-08-28T10:30:00.123999+08:00')
assert TimezoneUtil.to_utc_milliseconds(value) == datetime(2026, 8, 28, 2, 30, 0, 123000, tzinfo=UTC)
@@ -51,6 +56,7 @@ def test_to_utc_milliseconds_truncates_sub_millisecond_precision() -> None:
def test_local_date_range_uses_utc_half_open_interval(
day: date, zone: str, expected_start: str, expected_end: str
) -> None:
+ """本地日期范围转换为左闭右开的 UTC 区间。"""
start, end = TimezoneUtil.local_date_range_to_utc(day, day, zone)
assert start == datetime.fromisoformat(expected_start)
@@ -58,6 +64,7 @@ def test_local_date_range_uses_utc_half_open_interval(
def test_format_rfc3339_uses_utc_and_millisecond_precision() -> None:
+ """RFC 3339 输出采用 UTC 并保留毫秒精度。"""
value = datetime.fromisoformat('2026-08-28T10:30:00.123456+08:00')
assert TimezoneUtil.format_rfc3339(value) == '2026-08-28T02:30:00.123Z'
@@ -76,10 +83,12 @@ class TestGenTimeUtil:
],
)
def test_normalization_preserves_timezone_qualifiers(self, column_type: str, expected: str) -> None:
+ """规范化时间类型时保留时区限定。"""
assert GenTimeUtil.normalize_db_type(column_type) == expected
@pytest.mark.parametrize('column_type', ['TIME(3) WITH TIME ZONE', 'timetz'])
def test_time_with_timezone_requires_an_explicit_storage_decision(self, column_type: str) -> None:
+ """带时区的时间类型必须明确存储方式。"""
with pytest.raises(ServiceWarning) as error:
GenTimeUtil.get_time_semantics(column_type, 'postgresql')
@@ -87,4 +96,5 @@ def test_time_with_timezone_requires_an_explicit_storage_decision(self, column_t
@pytest.mark.parametrize('db_type', ['mysql', 'postgresql'])
def test_non_time_columns_do_not_receive_time_semantics(self, db_type: str) -> None:
+ """非时间列不附加时间语义。"""
assert GenTimeUtil.get_time_semantics('varchar(64)', db_type) is None
diff --git a/ruoyi-fastapi-backend/utils/api_annotation_util.py b/ruoyi-fastapi-backend/utils/api_annotation_util.py
index 27a1433ac..7cfa36283 100644
--- a/ruoyi-fastapi-backend/utils/api_annotation_util.py
+++ b/ruoyi-fastapi-backend/utils/api_annotation_util.py
@@ -13,14 +13,12 @@
class ApiAnnotationUtil:
- """
- 接口装饰器通用工具类
- """
+ """接口装饰器通用工具类。"""
@classmethod
def get_request(cls, func: Callable[P, Awaitable[R]], *args: P.args, **kwargs: P.kwargs) -> Request | None:
"""
- 从被装饰函数的入参中提取Request对象
+ 从被装饰函数的入参中提取Request对象。
:param func: 被装饰的异步接口函数
:param args: 位置参数
@@ -38,7 +36,7 @@ def get_request(cls, func: Callable[P, Awaitable[R]], *args: P.args, **kwargs: P
@classmethod
def get_redis_client(cls, request: Request, skip_message: str) -> aioredis.Redis | None:
"""
- 从应用状态中获取Redis连接
+ 从应用状态中获取Redis连接。
:param request: 当前请求对象
:param skip_message: 未初始化Redis连接时的日志信息
@@ -59,7 +57,7 @@ def resolve_request_redis(
**kwargs: P.kwargs,
) -> tuple[Request | None, aioredis.Redis | None]:
"""
- 从被装饰函数入参中同时解析Request与Redis连接
+ 从被装饰函数入参中同时解析Request与Redis连接。
:param func: 被装饰的异步接口函数
:param skip_message: 未初始化Redis连接时的日志信息
@@ -80,11 +78,12 @@ def normalize_http_methods(
default_methods: Sequence[HttpMethod] | None = None,
) -> tuple[str, ...]:
"""
- 标准化HTTP请求方法配置
+ 标准化HTTP请求方法配置。
:param methods: 显式配置的HTTP请求方法
:param default_methods: methods为空时使用的默认HTTP请求方法
:return: 去重且标准化后的HTTP请求方法元组
+ :raises TypeError: methods参数仅支持HttpMethod枚举
"""
target_methods = methods if methods is not None else default_methods
if not target_methods:
diff --git a/ruoyi-fastapi-backend/utils/api_response_header_util.py b/ruoyi-fastapi-backend/utils/api_response_header_util.py
index 40824e3b6..9e95ba0c9 100644
--- a/ruoyi-fastapi-backend/utils/api_response_header_util.py
+++ b/ruoyi-fastapi-backend/utils/api_response_header_util.py
@@ -4,18 +4,15 @@
class ApiResponseHeaderUtil:
- """
- 接口响应头通用工具类
- """
+ """接口响应头通用工具类。"""
@classmethod
def merge_headers(cls, request: Request, headers: Mapping[str, str] | None) -> None:
"""
- 将响应头暂存到请求上下文中,供出站中间件统一追加
+ 将响应头暂存到请求上下文中,供出站中间件统一追加。
:param request: 当前请求对象
:param headers: 需要追加的响应头
- :return: None
"""
if not headers:
return
diff --git a/ruoyi-fastapi-backend/utils/cache_util.py b/ruoyi-fastapi-backend/utils/cache_util.py
index 5f7db94d4..1645e9fc8 100644
--- a/ruoyi-fastapi-backend/utils/cache_util.py
+++ b/ruoyi-fastapi-backend/utils/cache_util.py
@@ -17,7 +17,12 @@
@dataclass(frozen=True, slots=True)
class CurrentUserCacheTicket:
"""
- 当前用户查询开始时的缓存版本和固定有效期
+ 当前用户查询开始时的缓存版本和固定有效期。
+
+ :ivar global_epoch: 全局缓存的失效版本号
+ :ivar user_epoch: 当前用户缓存的失效版本号
+ :ivar created_at_ms: 创建缓存票据的时间戳(毫秒)
+ :ivar deadline_ms: 允许写回缓存的截止时间戳(毫秒)
"""
global_epoch: str
@@ -28,9 +33,16 @@ class CurrentUserCacheTicket:
class CurrentUserCacheUtil:
"""
- 当前用户快照缓存工具类
+ 当前用户快照缓存工具类。
数据库提交后主动失效,硬过期限制失效遗漏时的缓存复用时间。
+
+ :cvar _OPERATION_TIMEOUT_SECONDS: 操作超时时间(秒)
+ :cvar _READ_RESULT_SIZE: 预期从 Redis 读脚本返回的字段数量
+ :cvar _USER_EPOCH_TTL_SECONDS: 用户缓存版本的有效期(秒)
+ :cvar _READ_SCRIPT: 原子读取用户缓存和版本信息的 Redis 脚本
+ :cvar _WRITE_SCRIPT: 仅在版本仍有效时写入缓存的 Redis 脚本
+ :cvar _INVALIDATE_SCRIPT: 推进缓存版本并使旧数据失效的 Redis 脚本
"""
_OPERATION_TIMEOUT_SECONDS = 1
@@ -93,7 +105,7 @@ class CurrentUserCacheUtil:
@staticmethod
def namespace_for_bind(bind: object) -> str | None:
"""
- 根据数据库连接目标生成缓存命名空间,不访问数据库
+ 根据数据库连接目标生成缓存命名空间,不访问数据库。
:param bind: 数据库引擎或连接
:return: 隐藏密码后的连接目标摘要,未知绑定返回None
@@ -107,7 +119,7 @@ def namespace_for_bind(bind: object) -> str | None:
@staticmethod
def _keys(namespace: str, user_id: int) -> tuple[str, str, str]:
"""
- 获取同一数据源下的版本和用户快照键
+ 获取同一数据源下的版本和用户快照键。
:param namespace: 数据源缓存命名空间
:param user_id: 用户id
@@ -122,7 +134,7 @@ async def read(
cls, redis: Redis, namespace: str, user_id: int, ttl_seconds: int
) -> tuple[CurrentUserModel | None, CurrentUserCacheTicket | None]:
"""
- 原子读取用户快照,未命中时返回用于安全回填的查询凭据
+ 原子读取用户快照,未命中时返回用于安全回填的查询凭据。
:param redis: Redis连接对象
:param namespace: 数据源缓存命名空间
@@ -181,7 +193,7 @@ async def write(
ticket: CurrentUserCacheTicket,
) -> bool:
"""
- 版本未变化时回填用户快照,不延长查询开始时的有效期
+ 版本未变化时回填用户快照,不延长查询开始时的有效期。
:param redis: Redis连接对象
:param namespace: 数据源缓存命名空间
@@ -219,7 +231,7 @@ async def write(
@classmethod
async def invalidate(cls, redis: Redis, namespace: str, user_ids: set[int] | None = None) -> bool:
"""
- 轮换用户或共享信息版本,使已有快照和并发查询凭据失效
+ 轮换用户或共享信息版本,使已有快照和并发查询凭据失效。
:param redis: Redis连接对象
:param namespace: 数据源缓存命名空间
@@ -249,13 +261,14 @@ async def invalidate(cls, redis: Redis, namespace: str, user_ids: set[int] | Non
@classmethod
async def _eval(cls, redis: Redis, script: str, key_count: int, *args: object) -> Any:
"""
- 限时执行Redis脚本,取消后等待连接归还
+ 限时执行Redis脚本,取消后等待连接归还。
:param redis: Redis连接对象
:param script: Lua脚本
:param key_count: 脚本键数量
:param args: 脚本键和参数
:return: Redis响应值
+ :raises asyncio.CancelledError: 等待 Redis 脚本执行时操作被取消
"""
task = asyncio.ensure_future(redis.eval(script, key_count, *args))
try:
@@ -283,7 +296,7 @@ async def _eval(cls, redis: Redis, script: str, key_count: int, *args: object) -
@staticmethod
def _text(value: str | bytes) -> str:
"""
- 兼容Redis字符串和字节响应
+ 兼容Redis字符串和字节响应。
:param value: Redis响应值
:return: 字符串
diff --git a/ruoyi-fastapi-backend/utils/client_ip_util.py b/ruoyi-fastapi-backend/utils/client_ip_util.py
index 34b7fdcfd..6db0dbd3a 100644
--- a/ruoyi-fastapi-backend/utils/client_ip_util.py
+++ b/ruoyi-fastapi-backend/utils/client_ip_util.py
@@ -4,14 +4,12 @@
class ClientIPUtil:
- """
- 客户端IP提取工具
- """
+ """客户端IP提取工具。"""
@classmethod
def get_client_ip(cls, request: Request) -> str:
"""
- 获取客户端真实IP
+ 获取客户端真实IP。
仅当请求来源命中可信代理列表,且可信代理跳数大于0时,才会解析
X-Forwarded-For / X-Real-IP 请求头;否则回退到直接连接来源地址。
@@ -42,7 +40,7 @@ def get_client_ip(cls, request: Request) -> str:
@classmethod
def _should_trust_proxy_headers(cls, remote_addr: str) -> bool:
"""
- 判断当前连接来源是否属于可信代理
+ 判断当前连接来源是否属于可信代理。
:param remote_addr: 与应用直接建立连接的来源IP
:return: 是否信任代理头
@@ -53,7 +51,7 @@ def _should_trust_proxy_headers(cls, remote_addr: str) -> bool:
@classmethod
def _get_trusted_proxy_ips(cls) -> set[str]:
"""
- 获取可信代理IP集合
+ 获取可信代理IP集合。
:return: 可信代理IP集合
"""
diff --git a/ruoyi-fastapi-backend/utils/common_util.py b/ruoyi-fastapi-backend/utils/common_util.py
index eb6ff35c9..f63a02ffc 100644
--- a/ruoyi-fastapi-backend/utils/common_util.py
+++ b/ruoyi-fastapi-backend/utils/common_util.py
@@ -19,6 +19,7 @@
def worship() -> None:
+ """将启动时的佛像字符画写入日志。"""
logger.info(r"""
////////////////////////////////////////////////////////////////////
// _ooOoo_ //
@@ -46,16 +47,14 @@ def worship() -> None:
class SqlalchemyUtil:
- """
- sqlalchemy工具类
- """
+ """sqlalchemy工具类。"""
@classmethod
def base_to_dict(
cls, obj: Base | dict, transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case'
) -> dict:
"""
- 将sqlalchemy模型对象转换为字典
+ 将sqlalchemy模型对象转换为字典。
:param obj: sqlalchemy模型对象或普通字典
:param transform_case: 转换得到的结果形式,可选的有'no_case'(不转换)、'snake_to_camel'(下划线转小驼峰)、'camel_to_snake'(小驼峰转下划线),默认为'no_case'
@@ -129,7 +128,7 @@ def serialize_result(
cls, result: Any, transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case'
) -> Any:
"""
- 将sqlalchemy查询结果序列化
+ 将sqlalchemy查询结果序列化。
:param result: sqlalchemy查询结果
:param transform_case: 转换得到的结果形式,可选的有'no_case'(不转换)、'snake_to_camel'(下划线转小驼峰)、'camel_to_snake'(小驼峰转下划线),默认为'no_case'
@@ -155,7 +154,7 @@ def serialize_result(
@classmethod
def get_server_default_null(cls, dialect_name: str, need_explicit_null: bool = True) -> TextClause | None:
"""
- 根据数据库方言动态返回值为null的server_default
+ 根据数据库方言动态返回值为null的server_default。
:param dialect_name: 数据库方言名称
:param need_explicit_null: 是否需要显式DEFAULT NULL
@@ -167,14 +166,12 @@ def get_server_default_null(cls, dialect_name: str, need_explicit_null: bool = T
class CamelCaseUtil:
- """
- 下划线形式(snake_case)转小驼峰形式(camelCase)工具方法
- """
+ """下划线形式(snake_case)转小驼峰形式(camelCase)工具方法。"""
@classmethod
def snake_to_camel(cls, snake_str: str) -> str:
"""
- 下划线形式字符串(snake_case)转换为小驼峰形式字符串(camelCase)
+ 下划线形式字符串(snake_case)转换为小驼峰形式字符串(camelCase)。
:param snake_str: 下划线形式字符串
:return: 小驼峰形式字符串
@@ -219,7 +216,7 @@ def transform_result(cls, result: Any) -> Any: ...
@classmethod
def transform_result(cls, result: Any) -> Any:
"""
- 针对不同类型将下划线形式(snake_case)批量转换为小驼峰形式(camelCase)方法
+ 针对不同类型将下划线形式(snake_case)批量转换为小驼峰形式(camelCase)方法。
:param result: 输入数据
:return: 小驼峰形式结果
@@ -228,14 +225,12 @@ def transform_result(cls, result: Any) -> Any:
class SnakeCaseUtil:
- """
- 小驼峰形式(camelCase)转下划线形式(snake_case)工具方法
- """
+ """小驼峰形式(camelCase)转下划线形式(snake_case)工具方法。"""
@classmethod
def camel_to_snake(cls, camel_str: str) -> str:
"""
- 小驼峰形式字符串(camelCase)转换为下划线形式字符串(snake_case)
+ 小驼峰形式字符串(camelCase)转换为下划线形式字符串(snake_case)。
:param camel_str: 小驼峰形式字符串
:return: 下划线形式字符串
@@ -279,7 +274,7 @@ def transform_result(cls, result: Any) -> Any: ...
@classmethod
def transform_result(cls, result: Any) -> Any:
"""
- 针对不同类型将小驼峰形式(camelCase)批量转换为下划线形式(snake_case)方法
+ 针对不同类型将小驼峰形式(camelCase)批量转换为下划线形式(snake_case)方法。
:param result: 输入数据
:return: 下划线形式结果
@@ -288,13 +283,19 @@ def transform_result(cls, result: Any) -> Any:
def bytes2human(n: int, format_str: str = '%(value).1f%(symbol)s') -> str:
- """Used by various scripts. See:
- http://goo.gl/zeJZl
+ """
+ 将字节数格式化为易读的容量单位。
+
+ 原始实现见 http://goo.gl/zeJZl 。
>>> bytes2human(10000)
'9.8K'
>>> bytes2human(100001221)
'95.4M'
+
+ :param n: 待格式化的字节数
+ :param format_str: 插入大小和单位的输出格式
+ :return: 附带容量单位的字节数文本
"""
symbols = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
prefix = {}
@@ -308,12 +309,18 @@ def bytes2human(n: int, format_str: str = '%(value).1f%(symbol)s') -> str:
def bytes2file_response(bytes_info: bytes) -> Generator[bytes]:
+ """
+ 将内存中的文件内容作为响应数据块输出。
+
+ :param bytes_info: 作为下载响应发送的二进制内容
+ :yield: 供下载响应发送的二进制内容
+ """
yield bytes_info
def export_list2excel(list_data: list) -> bytes:
"""
- 工具方法:将需要导出的list数据转化为对应excel的二进制数据
+ 工具方法:将需要导出的list数据转化为对应excel的二进制数据。
:param list_data: 数据列表
:return: 字典信息对应excel的二进制数据
@@ -328,7 +335,7 @@ def export_list2excel(list_data: list) -> bytes:
def get_excel_template(header_list: list, selector_header_list: list, option_list: list[dict]) -> bytes:
"""
- 工具方法:将需要导出的list数据转化为对应excel的二进制数据
+ 工具方法:将需要导出的list数据转化为对应excel的二进制数据。
:param header_list: 表头数据列表
:param selector_header_list: 需要设置为选择器格式的表头数据列表
@@ -389,7 +396,7 @@ def get_excel_template(header_list: list, selector_header_list: list, option_lis
def get_filepath_from_url(url: str) -> str:
"""
- 工具方法:根据请求参数获取文件路径
+ 工具方法:根据请求参数获取文件路径。
:param url: 请求参数中的url参数
:return: 文件路径
diff --git a/ruoyi-fastapi-backend/utils/cron_util.py b/ruoyi-fastapi-backend/utils/cron_util.py
index 124cb12de..3674db57d 100644
--- a/ruoyi-fastapi-backend/utils/cron_util.py
+++ b/ruoyi-fastapi-backend/utils/cron_util.py
@@ -11,7 +11,12 @@
class NearestWeekdayExpression(AllExpression):
"""
- 支持Quartz最近工作日语法的日期表达式
+ 支持Quartz最近工作日语法的日期表达式。
+
+ :cvar SATURDAY: 周六对应的星期编号
+ :cvar SUNDAY: 周日对应的星期编号
+ :cvar value_re: 解析工作日表达式的正则表达式
+ :ivar day: W前指定的日序号,取值为1至31
"""
SATURDAY = 5
@@ -21,7 +26,7 @@ class NearestWeekdayExpression(AllExpression):
def __init__(self, day: str) -> None:
"""
- 初始化最近工作日表达式
+ 初始化最近工作日表达式。
:param day: W前指定的日序号,取值为1至31
"""
@@ -30,7 +35,7 @@ def __init__(self, day: str) -> None:
def get_next_value(self, date: datetime, field: DayOfMonthField) -> int | None:
"""
- 计算当前月份中满足条件的最近工作日
+ 计算当前月份中满足条件的最近工作日。
:param date: 当前查找的日期
:param field: APScheduler传入的日期字段
@@ -49,7 +54,7 @@ def get_next_value(self, date: datetime, field: DayOfMonthField) -> int | None:
def __str__(self) -> str:
"""
- 返回Quartz最近工作日表达式
+ 返回Quartz最近工作日表达式。
:return: 日序号和W组成的表达式
"""
@@ -58,7 +63,9 @@ def __str__(self) -> str:
class QuartzDayOfMonthField(DayOfMonthField):
"""
- 注册最近工作日表达式的Quartz日期字段
+ 注册最近工作日表达式的Quartz日期字段。
+
+ :cvar COMPILERS: 当前 Cron 字段支持的表达式编译器
"""
COMPILERS = [NearestWeekdayExpression, *DayOfMonthField.COMPILERS]
@@ -66,7 +73,13 @@ class QuartzDayOfMonthField(DayOfMonthField):
class MyCronTrigger(CronTrigger):
"""
- 统一任务注册和预览行为的Quartz触发器
+ 统一任务注册和预览行为的Quartz触发器。
+
+ :cvar CRON_FIELDS_WITH_YEAR: 包含年份的 Cron 表达式应有的字段数
+ :cvar FIELDS_MAP: Cron 字段名称到解析器的映射
+ :cvar WEEKDAYS: 工作日选择器识别的星期名称
+ :cvar NUMERIC_FIELD: 用于识别数值 Cron 字段的模式
+ :ivar task_job_group: 业务分组快照
"""
CRON_FIELDS_WITH_YEAR = 7
@@ -77,7 +90,7 @@ class MyCronTrigger(CronTrigger):
def __getstate__(self) -> dict:
"""
- 序列化Cron规则及业务分组快照
+ 序列化Cron规则及业务分组快照。
:return: 触发器持久化状态
"""
@@ -85,17 +98,16 @@ def __getstate__(self) -> dict:
def __setstate__(self, state: dict) -> None:
"""
- 恢复Cron规则及业务分组快照
+ 恢复Cron规则及业务分组快照。
:param state: 触发器持久化状态
- :return: None
"""
super().__setstate__(state)
self.task_job_group = state.get('task_job_group', 'default')
def get_next_fire_time(self, previous_fire_time: datetime | None, now: datetime) -> datetime | None:
"""
- 计算下一次有效执行时刻
+ 计算下一次有效执行时刻。
夏令时跳转中不存在的当地时间跳过,重复时间仅取第一次。
@@ -114,11 +126,12 @@ def get_next_fire_time(self, previous_fire_time: datetime | None, now: datetime)
@classmethod
def from_crontab(cls, expr: str, timezone: str) -> 'MyCronTrigger':
"""
- 根据Quartz表达式和任务时区创建触发器
+ 根据Quartz表达式和任务时区创建触发器。
:param expr: 包含6或7个字段的Quartz表达式
:param timezone: 任务IANA时区名称
:return: 配置完成的Cron触发器
+ :raises ValueError: 字段数不为六或七,或按周指定日期时日字段未使用问号或星号
"""
values = expr.split()
if len(values) not in (6, 7):
@@ -161,12 +174,13 @@ def from_crontab(cls, expr: str, timezone: str) -> 'MyCronTrigger':
@classmethod
def _weekday_names(cls, expression: str) -> str:
"""
- 将Quartz星期编号转换为APScheduler星期名称
+ 将Quartz星期编号转换为APScheduler星期名称。
Quartz的1表示星期日;APScheduler的数字0表示星期一。
:param expression: Quartz周字段表达式
:return: 逗号分隔的星期名称
+ :raises ValueError: Cron 周范围的结束值不能早于开始值
"""
weekdays = set()
for part in expression.split(','):
@@ -182,7 +196,13 @@ def _weekday_names(cls, expression: str) -> str:
class CronUtil:
"""
- Cron表达式工具类
+ Cron表达式工具类。
+
+ :cvar MAX_PREVIEW_COUNT: 最多返回的触发时间预览数
+ :cvar ONE_YEAR_LENGTH: 单个四位年份的字符数
+ :cvar MAX_YEAR: 可参与调度计算的最大年份
+ :cvar CRON_EXPRESSION_LENGTH_MIN: Cron 表达式允许的最少字段数
+ :cvar CRON_EXPRESSION_LENGTH_MAX: Cron 表达式允许的最多字段数
"""
MAX_PREVIEW_COUNT = 20
@@ -193,6 +213,14 @@ class CronUtil:
@classmethod
def __valid_range(cls, search_str: str, start_range: int, end_range: int) -> bool:
+ """
+ 校验 Cron 字段中的数值范围表达式。
+
+ :param search_str: 查找的字符串
+ :param start_range: 请求范围的起始字节位置
+ :param end_range: 请求范围的结束字节位置
+ :return: 是否校验 Cron 字段中的数值范围表达式
+ """
match = re.match(r'^(\d+)-(\d+)$', search_str)
if match:
start, end = int(match.group(1)), int(match.group(2))
@@ -203,6 +231,17 @@ def __valid_range(cls, search_str: str, start_range: int, end_range: int) -> boo
def __valid_sum(
cls, search_str: str, start_range_a: int, start_range_b: int, end_range_a: int, end_range_b: int, sum_range: int
) -> bool:
+ """
+ 校验 Cron 字段中的步长表达式。
+
+ :param search_str: 查找的字符串
+ :param start_range_a: 第一个范围的起始字节位置
+ :param start_range_b: 第二个范围的起始字节位置
+ :param end_range_a: 第一个范围的结束字节位置
+ :param end_range_b: 第二个范围的结束字节位置
+ :param sum_range: 参与校验的数值范围
+ :return: 是否校验 Cron 字段中的步长表达式
+ """
match = re.match(r'^(\d+)/(\d+)$', search_str)
if match:
start, end = int(match.group(1)), int(match.group(2))
@@ -216,7 +255,7 @@ def __valid_sum(
@classmethod
def validate_second_or_minute(cls, second_or_minute: str) -> bool:
"""
- 校验秒或分钟值是否正确
+ 校验秒或分钟值是否正确。
:param second_or_minute: 秒或分钟值
:return: 校验结果
@@ -231,7 +270,7 @@ def validate_second_or_minute(cls, second_or_minute: str) -> bool:
@classmethod
def validate_hour(cls, hour: str) -> bool:
"""
- 校验小时值是否正确
+ 校验小时值是否正确。
:param hour: 小时值
:return: 校验结果
@@ -246,7 +285,7 @@ def validate_hour(cls, hour: str) -> bool:
@classmethod
def validate_day(cls, day: str) -> bool:
"""
- 校验日值是否正确
+ 校验日值是否正确。
:param day: 日值
:return: 校验结果
@@ -262,7 +301,7 @@ def validate_day(cls, day: str) -> bool:
@classmethod
def validate_month(cls, month: str) -> bool:
"""
- 校验月值是否正确
+ 校验月值是否正确。
:param month: 月值
:return: 校验结果
@@ -277,7 +316,7 @@ def validate_month(cls, month: str) -> bool:
@classmethod
def validate_week(cls, week: str) -> bool:
"""
- 校验周值是否正确
+ 校验周值是否正确。
:param week: 周值
:return: 校验结果
@@ -293,7 +332,7 @@ def validate_week(cls, week: str) -> bool:
@classmethod
def validate_year(cls, year: str, timezone: str) -> bool:
"""
- 校验年值是否正确
+ 校验年值是否正确。
:param year: 年值
:param timezone: 任务IANA时区名称,用于确定当前业务年份
@@ -318,7 +357,7 @@ def validate_year(cls, year: str, timezone: str) -> bool:
@classmethod
def validate_cron_expression(cls, cron_expression: str, timezone: str) -> bool:
"""
- 校验Cron表达式是否正确
+ 校验Cron表达式是否正确。
:param cron_expression: Cron表达式
:param timezone: 任务IANA时区名称
@@ -335,13 +374,14 @@ def next_run_times(
cls, cron_expression: str, time_zone: str, start_time: datetime, count: int = 5
) -> list[datetime]:
"""
- 从指定时刻开始枚举未来UTC执行时刻
+ 从指定时刻开始枚举未来UTC执行时刻。
:param cron_expression: Quartz表达式
:param time_zone: 任务IANA时区名称
:param start_time: 查找起算时刻,包含该时刻
:param count: 最多返回的执行时刻数量,取值为1至20
:return: 按时间排序的UTC时刻列表,无未来结果时返回空列表
+ :raises ValueError: 预览数量必须在 1 至 20 之间
"""
if not 1 <= count <= cls.MAX_PREVIEW_COUNT:
raise ValueError('预览数量必须在 1 至 20 之间')
diff --git a/ruoyi-fastapi-backend/utils/crypto_util.py b/ruoyi-fastapi-backend/utils/crypto_util.py
index 8dc12290b..886f9329c 100644
--- a/ruoyi-fastapi-backend/utils/crypto_util.py
+++ b/ruoyi-fastapi-backend/utils/crypto_util.py
@@ -9,16 +9,23 @@
class CryptoUtil:
"""
- 加解密工具类
+ 加解密工具类。
+
+ :cvar _cipher_suite: 对配置内容执行加解密的密码套件
"""
_cipher_suite = None
@classmethod
def _get_cipher_suite(cls) -> Fernet:
+ """
+ 构建用于配置数据加解密的密码套件。
+
+ :return: 用于配置数据加解密的密码套件
+ """
if cls._cipher_suite is None:
# 使用 JWT secret key 派生 Fernet key
- # SHA256 hash (32 bytes) -> Base64 encoded (44 bytes) -> Fernet key
+ # 将 32 字节的 SHA-256 摘要编码为 44 字节的 Base64,作为 Fernet 密钥。
key = base64.urlsafe_b64encode(hashlib.sha256(JwtConfig.jwt_secret_key.encode()).digest())
cls._cipher_suite = Fernet(key)
return cls._cipher_suite
@@ -26,10 +33,11 @@ def _get_cipher_suite(cls) -> Fernet:
@classmethod
def encrypt(cls, data: str) -> str:
"""
- 加密字符串
+ 加密字符串。
:param data: 明文
:return: 密文
+ :raises ServiceException: 加密失败
"""
if not data:
return data
@@ -43,10 +51,11 @@ def encrypt(cls, data: str) -> str:
@classmethod
def decrypt(cls, token: str) -> str:
"""
- 解密字符串
+ 解密字符串。
:param token: 密文
:return: 明文
+ :raises ServiceException: 解密失败
"""
if not token:
return token
diff --git a/ruoyi-fastapi-backend/utils/dependency_util.py b/ruoyi-fastapi-backend/utils/dependency_util.py
index 7a719660c..a8825499e 100644
--- a/ruoyi-fastapi-backend/utils/dependency_util.py
+++ b/ruoyi-fastapi-backend/utils/dependency_util.py
@@ -6,14 +6,12 @@
class DependencyUtil:
- """
- 依赖项工具类
- """
+ """依赖项工具类。"""
@classmethod
def get_request_path(cls, request: Request) -> str:
"""
- 获取不含部署前缀的应用内请求路径
+ 获取不含部署前缀的应用内请求路径。
:param request: 当前请求对象
:return: 应用内请求路径
@@ -34,11 +32,11 @@ def get_request_path(cls, request: Request) -> str:
@classmethod
def check_exclude_routes(cls, request: Request, err_msg: str = '当前路由不在认证规则内,不可使用该依赖项') -> None:
"""
- 检查路径和方法是否匹配排除路由模式
+ 检查路径和方法是否匹配排除路由模式。
:param request: 请求对象
:param err_msg: 错误信息
- :return: None
+ :raises PermissionException: 当前路径和 HTTP 方法命中需要拒绝的路由规则
"""
# 获取当前请求路径和方法
path = cls.get_request_path(request)
diff --git a/ruoyi-fastapi-backend/utils/excel_util.py b/ruoyi-fastapi-backend/utils/excel_util.py
index 096bd8cd7..82eaadea1 100644
--- a/ruoyi-fastapi-backend/utils/excel_util.py
+++ b/ruoyi-fastapi-backend/utils/excel_util.py
@@ -14,16 +14,14 @@
class ExcelUtil:
- """
- Excel操作类
- """
+ """Excel操作类。"""
@classmethod
def __mapping_list(
cls, list_data: list, mapping_dict: dict, timezone_name: str, locale_context: LocaleContext
) -> list[dict]:
"""
- 按导出语言生成表头和单元格文本,并按导出时区转换日期时间
+ 按导出语言生成表头和单元格文本,并按导出时区转换日期时间。
:param list_data: 数据列表
:param mapping_dict: 映射字典
@@ -60,7 +58,7 @@ def export_list2excel(
locale_context: LocaleContext | None = None,
) -> bytes:
"""
- 工具方法:将需要导出的list数据转化为对应excel的二进制数据
+ 工具方法:将需要导出的list数据转化为对应excel的二进制数据。
:param list_data: 数据列表
:param mapping_dict: 映射字典
@@ -87,7 +85,7 @@ def get_excel_template(
locale_context: LocaleContext | None = None,
) -> bytes:
"""
- 生成包含本地化表头和下拉选项的 Excel 模板
+ 生成包含本地化表头和下拉选项的 Excel 模板。
:param header_list: 表头数据列表
:param selector_header_list: 需要设置为选择器格式的表头数据列表
@@ -159,7 +157,7 @@ def get_excel_template(
@staticmethod
def _display_value(value: object, context: LocaleContext) -> object:
"""
- 仅翻译声明了消息标识的固定文本,保留业务内容
+ 仅翻译声明了消息标识的固定文本,保留业务内容。
:param value: 表头、固定枚举或业务数据
:param context: 导出语言快照
diff --git a/ruoyi-fastapi-backend/utils/exception_util.py b/ruoyi-fastapi-backend/utils/exception_util.py
index 8255cdf49..aa804542f 100644
--- a/ruoyi-fastapi-backend/utils/exception_util.py
+++ b/ruoyi-fastapi-backend/utils/exception_util.py
@@ -7,9 +7,7 @@
class ExceptionUtil:
- """
- 未知异常的安全响应与诊断工具类。
- """
+ """未知异常的安全响应与诊断工具类。"""
@staticmethod
def handle_unexpected_exception(exc: Exception) -> Response:
diff --git a/ruoyi-fastapi-backend/utils/file_util.py b/ruoyi-fastapi-backend/utils/file_util.py
index f490b0447..aae3be9dd 100644
--- a/ruoyi-fastapi-backend/utils/file_util.py
+++ b/ruoyi-fastapi-backend/utils/file_util.py
@@ -17,7 +17,13 @@
class FileStorageInfo(Protocol):
"""
- 文件存储信息协议
+ 文件存储信息协议。
+
+ :ivar file_id: 文件ID
+ :ivar storage_type: 文件存储类型
+ :ivar access_type: 文件访问类型
+ :ivar storage_key: 存储相对路径
+ :ivar stored_name: 存储文件名
"""
file_id: str
@@ -30,7 +36,12 @@ class FileStorageInfo(Protocol):
@dataclass(frozen=True)
class FileByteRange:
"""
- 文件字节范围
+ 文件字节范围。
+
+ :ivar start: 响应包含的第一个字节偏移
+ :ivar end: 响应包含的最后一个字节偏移
+ :ivar file_size: 文件总大小
+ :ivar is_partial: 是否按客户端请求只返回部分字节
"""
start: int
@@ -41,7 +52,7 @@ class FileByteRange:
@property
def length(self) -> int:
"""
- 获取范围字节数
+ 获取范围字节数。
:return: 范围字节数
"""
@@ -51,7 +62,12 @@ def length(self) -> int:
@dataclass(frozen=True)
class FileDownloadResult:
"""
- 文件下载结果
+ 文件下载结果。
+
+ :ivar data: 要写入下载响应的文件内容
+ :ivar filename: 浏览器下载时使用的文件名
+ :ivar byte_range: 文件字节范围
+ :ivar accept_ranges: 是否支持Range请求
"""
data: AsyncGenerator[bytes, None]
@@ -63,7 +79,10 @@ class FileDownloadResult:
@dataclass(frozen=True)
class StagedFile:
"""
- 待删除文件暂存信息
+ 待删除文件暂存信息。
+
+ :ivar source_path: 操作前文件所在的路径
+ :ivar trash_path: 文件移入回收区后的路径
"""
source_path: Path
@@ -73,7 +92,23 @@ class StagedFile:
@dataclass(frozen=True)
class FileReconcileFinding:
"""
- 文件存储对账异常
+ 文件存储对账异常。
+
+ :ivar issue_key: 异常唯一标识
+ :ivar issue_type: 异常类型
+ :ivar severity: 问题的严重程度
+ :ivar detail: 用于说明当前结果的详细信息
+ :ivar file_id: 文件ID
+ :ivar storage_type: 文件存储类型
+ :ivar access_type: 文件访问类型
+ :ivar expected_root: 记录声明的存储根目录
+ :ivar expected_key: 记录声明的存储对象键
+ :ivar actual_root: 实际存储根目录
+ :ivar actual_key: 扫描到的存储对象键
+ :ivar expected_size: 预期文件大小
+ :ivar actual_size: 实际文件大小
+ :ivar expected_hash: 预期SHA-256
+ :ivar actual_hash: 实际SHA-256
"""
issue_key: str
@@ -96,7 +131,11 @@ class FileReconcileFinding:
@dataclass(frozen=True)
class FileReconcileScanResult:
"""
- 文件存储对账扫描结果
+ 文件存储对账扫描结果。
+
+ :ivar findings: 本次扫描发现的对账问题
+ :ivar scanned_file_count: 已检查的文件记录数量
+ :ivar scanned_storage_count: 已扫描的存储对象数量
"""
findings: list[FileReconcileFinding]
@@ -107,7 +146,14 @@ class FileReconcileScanResult:
@dataclass(frozen=True)
class _FileReconcileContext:
"""
- 文件存储对账内部上下文
+ 文件存储对账内部上下文。
+
+ :ivar file_info: 文件信息
+ :ivar source_root: 来源存储区域
+ :ivar source_key: 来源相对路径
+ :ivar source_path: 操作前文件所在的路径
+ :ivar trash_key: 文件在回收区中的存储键
+ :ivar trash_path: 文件移入回收区后的路径
"""
file_info: dict[str, Any]
@@ -120,7 +166,9 @@ class _FileReconcileContext:
class FileUtil:
"""
- 文件工具类
+ 文件工具类。
+
+ :cvar FILE_RANGE_PATTERN: 解析 HTTP 字节范围请求头的正则表达式
"""
FILE_RANGE_PATTERN = re.compile(r'^bytes=(\d*)-(\d*)$', re.IGNORECASE)
@@ -128,11 +176,13 @@ class FileUtil:
@classmethod
def parse_byte_range(cls, range_header: str | None, file_size: int) -> FileByteRange:
"""
- 解析HTTP单区间Range请求头
+ 解析HTTP单区间Range请求头。
:param range_header: Range请求头
:param file_size: 文件总大小
:return: 文件字节范围
+ :raises ValueError: 文件大小不能小于0
+ :raises FileRangeNotSatisfiableException: 字节范围格式无效、包含多段或无法满足
"""
if file_size < 0:
raise ValueError('文件大小不能小于0')
@@ -176,10 +226,11 @@ def parse_byte_range(cls, range_header: str | None, file_size: int) -> FileByteR
@classmethod
def parse_file_ids(cls, file_ids: str) -> list[str]:
"""
- 解析并校验文件ID
+ 解析并校验文件ID。
:param file_ids: 文件ID字符串
:return: 文件ID列表
+ :raises ServiceException: 文件ID不能为空;文件ID格式不正确
"""
if not file_ids:
raise ServiceException(message='文件ID不能为空', msg_key='file.idRequired')
@@ -196,10 +247,9 @@ def parse_file_ids(cls, file_ids: str) -> list[str]:
@classmethod
def enrich_storage_status(cls, file_rows: list[dict[str, Any]]) -> None:
"""
- 补充文件物理存储状态
+ 补充文件物理存储状态。
:param file_rows: 文件信息列表
- :return: None
"""
for file_row in file_rows:
file_row['storageStatus'] = cls.get_storage_status(file_row)
@@ -207,13 +257,20 @@ def enrich_storage_status(cls, file_rows: list[dict[str, Any]]) -> None:
@classmethod
def get_storage_status(cls, file_info: dict[str, Any]) -> str:
"""
- 获取文件物理存储状态
+ 获取文件物理存储状态。
:param file_info: 文件信息
:return: 文件物理存储状态
"""
def get_value(snake_name: str, camel_name: str) -> Any:
+ """
+ 兼容蛇形和驼峰字段名读取文件状态。
+
+ :param snake_name: 字段的下划线形式
+ :param camel_name: 字段的驼峰形式
+ :return: 从蛇形或驼峰字段读取的值
+ """
return file_info.get(snake_name) if snake_name in file_info else file_info.get(camel_name)
try:
@@ -252,10 +309,11 @@ def get_value(snake_name: str, camel_name: str) -> Any:
@classmethod
def stage_file_deletions(cls, file_infos: list[FileStorageInfo]) -> list[StagedFile]:
"""
- 将待删除文件移入回收区
+ 将待删除文件移入回收区。
:param file_infos: 文件信息列表
:return: 暂存文件列表
+ :raises Exception: 底层操作失败时向调用方传播异常
"""
staged_files = []
try:
@@ -281,10 +339,11 @@ def stage_file_deletions(cls, file_infos: list[FileStorageInfo]) -> list[StagedF
@classmethod
def _get_staged_file_paths(cls, file_info: FileStorageInfo) -> StagedFile:
"""
- 获取文件原路径和回收区路径
+ 获取文件原路径和回收区路径。
:param file_info: 文件信息
:return: 文件暂存信息
+ :raises ValueError: 文件存储类型或访问类型异常
"""
if file_info.storage_type != 'local' or file_info.access_type not in {'public', 'private'}:
raise ValueError('文件存储类型或访问类型异常')
@@ -301,10 +360,9 @@ def _get_staged_file_paths(cls, file_info: FileStorageInfo) -> StagedFile:
@classmethod
def restore_staged_files(cls, staged_files: list[StagedFile]) -> None:
"""
- 将隔离区文件恢复到原路径
+ 将隔离区文件恢复到原路径。
:param staged_files: 暂存文件列表
- :return: None
"""
for staged_file in reversed(staged_files):
try:
@@ -320,10 +378,12 @@ def restore_staged_files(cls, staged_files: list[StagedFile]) -> None:
@classmethod
def prepare_deleted_files_for_restore(cls, file_infos: list[FileStorageInfo]) -> list[StagedFile]:
"""
- 校验待恢复文件并生成暂存信息
+ 校验待恢复文件并生成暂存信息。
:param file_infos: 文件信息列表
:return: 暂存文件列表
+ :raises FileNotFoundError: 回收区文件不存在
+ :raises FileExistsError: 文件原路径已存在
"""
staged_files = []
for file_info in file_infos:
@@ -338,10 +398,12 @@ def prepare_deleted_files_for_restore(cls, file_infos: list[FileStorageInfo]) ->
@classmethod
def prepare_deleted_files_for_purge(cls, file_infos: list[FileStorageInfo]) -> list[StagedFile]:
"""
- 校验待永久清理文件并生成暂存信息
+ 校验待永久清理文件并生成暂存信息。
:param file_infos: 文件信息列表
:return: 暂存文件列表
+ :raises FileExistsError: 待清理文件仍存在于正式存储目录
+ :raises ValueError: 回收区路径不是普通文件
"""
staged_files = []
for file_info in file_infos:
@@ -356,10 +418,11 @@ def prepare_deleted_files_for_purge(cls, file_infos: list[FileStorageInfo]) -> l
@classmethod
def purge_deleted_files(cls, staged_files: list[StagedFile]) -> None:
"""
- 永久删除回收区文件
+ 永久删除回收区文件。
:param staged_files: 暂存文件列表
- :return: None
+ :raises FileExistsError: 待清理文件仍存在于正式存储目录
+ :raises ValueError: 回收区路径不是普通文件
"""
for staged_file in staged_files:
if staged_file.source_path.exists():
@@ -373,10 +436,10 @@ def purge_deleted_files(cls, staged_files: list[StagedFile]) -> None:
@classmethod
def restore_deleted_files(cls, staged_files: list[StagedFile]) -> None:
"""
- 将已删除文件从回收区恢复到原路径
+ 将已删除文件从回收区恢复到原路径。
:param staged_files: 暂存文件列表
- :return: None
+ :raises Exception: 底层操作失败时向调用方传播异常
"""
restored_files = []
try:
@@ -394,10 +457,9 @@ def restore_deleted_files(cls, staged_files: list[StagedFile]) -> None:
@classmethod
def _restage_restored_files(cls, staged_files: list[StagedFile]) -> None:
"""
- 将恢复失败的文件重新移入回收区
+ 将恢复失败的文件重新移入回收区。
:param staged_files: 暂存文件列表
- :return: None
"""
for staged_file in reversed(staged_files):
try:
@@ -412,10 +474,9 @@ def _restage_restored_files(cls, staged_files: list[StagedFile]) -> None:
@classmethod
def cleanup_trash_directories(cls, staged_files: list[StagedFile]) -> None:
"""
- 清理恢复后留下的空回收区目录
+ 清理恢复后留下的空回收区目录。
:param staged_files: 暂存文件列表
- :return: None
"""
for staged_file in staged_files:
UploadUtil.remove_empty_directory(staged_file.trash_path.parent)
@@ -423,7 +484,11 @@ def cleanup_trash_directories(cls, staged_files: list[StagedFile]) -> None:
class FileReconcileUtil:
"""
- 文件存储对账工具类
+ 文件存储对账工具类。
+
+ :cvar MAX_SCAN_ENTRIES: 单次对账允许遍历的最大条目数
+ :cvar HASH_CHUNK_SIZE: 计算文件哈希时每次读取的字节数
+ :cvar ORPHAN_GRACE_SECONDS: 将未引用文件判定为孤立文件前等待的秒数
"""
MAX_SCAN_ENTRIES = 1_000_000
@@ -433,11 +498,12 @@ class FileReconcileUtil:
@classmethod
def scan_storage(cls, file_infos: list[dict[str, Any]], check_hash: bool = False) -> FileReconcileScanResult:
"""
- 执行数据库和本地文件系统双向对账
+ 执行数据库和本地文件系统双向对账。
:param file_infos: 文件信息列表
:param check_hash: 是否校验文件SHA-256
:return: 对账扫描结果
+ :raises RuntimeError: 被扫描的物理文件数超过上限
"""
roots = cls.get_storage_roots()
cls._validate_storage_roots(roots)
@@ -524,7 +590,7 @@ def scan_storage(cls, file_infos: list[dict[str, Any]], check_hash: bool = False
@classmethod
def get_storage_roots(cls) -> dict[str, Path]:
"""
- 获取对账使用的本地存储根目录
+ 获取对账使用的本地存储根目录。
:return: 存储区域和绝对根目录映射
"""
@@ -538,11 +604,12 @@ def get_storage_roots(cls) -> dict[str, Path]:
@classmethod
def resolve_location(cls, root_name: str, relative_key: str) -> Path:
"""
- 安全解析指定存储区域内的相对路径
+ 安全解析指定存储区域内的相对路径。
:param root_name: 存储区域
:param relative_key: 相对路径
:return: 安全文件路径
+ :raises ValueError: 存储区域不合法
"""
roots = cls.get_storage_roots()
if root_name not in roots:
@@ -553,20 +620,21 @@ def resolve_location(cls, root_name: str, relative_key: str) -> Path:
@classmethod
def calculate_file_hash(cls, filepath: Path) -> str:
"""
- 计算普通文件SHA-256
+ 计算普通文件SHA-256。
:param filepath: 文件路径
- :return: SHA-256
+ :return: 内容的 SHA-256 摘要
"""
return cls.calculate_file_integrity(filepath)[1]
@classmethod
def calculate_file_integrity(cls, filepath: Path) -> tuple[int, str]:
"""
- 稳定计算普通文件大小和SHA-256
+ 稳定计算普通文件大小和SHA-256。
:param filepath: 文件路径
:return: 文件大小和SHA-256
+ :raises ValueError: 目标路径不是普通文件;文件在摘要计算期间发生变化
"""
if filepath.is_symlink() or not filepath.is_file():
raise ValueError('目标路径不是普通文件')
@@ -601,13 +669,16 @@ def move_regular_file(
target_key: str,
) -> tuple[Path, Path]:
"""
- 在受控存储区域之间移动普通文件
+ 在受控存储区域之间移动普通文件。
:param source_root: 来源存储区域
:param source_key: 来源相对路径
:param target_root: 目标存储区域
:param target_key: 目标相对路径
:return: 来源和目标文件路径
+ :raises ValueError: 来源路径不是普通文件
+ :raises FileExistsError: 目标路径已存在
+ :raises OSError: 文件移动结果校验失败
"""
source_path = cls.resolve_location(source_root, source_key)
target_path = cls.resolve_location(target_root, target_key)
@@ -625,10 +696,11 @@ def move_regular_file(
@classmethod
def delete_quarantine_file(cls, quarantine_key: str) -> Path:
"""
- 永久删除隔离区普通文件
+ 永久删除隔离区普通文件。
:param quarantine_key: 隔离区相对路径
:return: 已删除文件路径
+ :raises ValueError: 隔离区目标不是普通文件
"""
quarantine_path = cls.resolve_location('quarantine', quarantine_key)
if quarantine_path.is_symlink() or not quarantine_path.is_file():
@@ -646,8 +718,12 @@ def build_finding(
**metadata: Any,
) -> FileReconcileFinding:
"""
- 构造包含稳定唯一标识的对账异常
+ 构造包含稳定唯一标识的对账异常。
+ :param issue_type: 异常类型
+ :param severity: 问题的严重程度
+ :param detail: 用于说明当前结果的详细信息
+ :param metadata: 调用方按名称传入的附加选项
:return: 对账异常
"""
identity = '|'.join(
@@ -684,6 +760,14 @@ def _build_file_context(
file_info: dict[str, Any],
roots: dict[str, Path],
) -> _FileReconcileContext:
+ """
+ 构建对账检查使用的文件信息及路径上下文。
+
+ :param file_info: 文件信息
+ :param roots: 需要检查的文件存储根目录集合
+ :raises ValueError: 文件ID为空;暂不支持非本地存储类型;访问类型不合法;存储路径或存储文件名为空;存储文件名包含路径信息;存储路径和存储文件名不一致;文件状态和删除标志不一致;文件状态不合法
+ :return: 对账检查使用的文件信息及路径上下文
+ """
file_id = cls._get_text_value(file_info, 'file_id')
storage_type = cls._get_text_value(file_info, 'storage_type')
access_type = cls._get_text_value(file_info, 'access_type')
@@ -729,6 +813,15 @@ def _inspect_file_context(
expected_locations: set[tuple[str, str]],
check_hash: bool,
) -> tuple[list[FileReconcileFinding], set[tuple[str, str]]]:
+ """
+ 检查文件记录与磁盘文件状态的一致性。
+
+ :param context: 文件存储对账内部上下文
+ :param roots: 需要检查的文件存储根目录集合
+ :param expected_locations: 记录声明的存储位置
+ :param check_hash: 是否校验文件SHA-256
+ :return: 发现的问题与已识别的存储位置
+ """
file_info = context.file_info
file_id = cls._get_text_value(file_info, 'file_id')
storage_type = cls._get_text_value(file_info, 'storage_type')
@@ -899,7 +992,18 @@ def _build_integrity_findings(
expected_key: str,
check_hash: bool,
) -> list[FileReconcileFinding]:
- """构造文件大小和摘要一致性异常。"""
+ """
+ 构造文件大小和摘要一致性异常。
+
+ :param file_info: 文件信息
+ :param actual_path: 扫描到的文件路径
+ :param actual_root: 实际存储根目录
+ :param actual_key: 扫描到的存储对象键
+ :param expected_root: 记录声明的存储根目录
+ :param expected_key: 记录声明的存储对象键
+ :param check_hash: 是否校验文件SHA-256
+ :return: 文件大小和摘要一致性异常
+ """
file_id = cls._get_text_value(file_info, 'file_id')
storage_type = cls._get_text_value(file_info, 'storage_type')
access_type = cls._get_text_value(file_info, 'access_type')
@@ -950,7 +1054,12 @@ def _build_integrity_findings(
@classmethod
def _iter_storage_entries(cls, root: Path) -> Iterator[tuple[str, Path, bool]]:
- """逐项遍历存储目录,避免大目录扫描时一次性占用过多内存。"""
+ """
+ 逐项遍历存储目录,避免大目录扫描时一次性占用过多内存。
+
+ :param root: 路径解析的基准目录
+ :yield: 相对存储键、磁盘路径及条目状态标志
+ """
stack = [root]
while stack:
directory = stack.pop()
@@ -969,6 +1078,14 @@ def _iter_storage_entries(cls, root: Path) -> Iterator[tuple[str, Path, bool]]:
@classmethod
def _resolve_lexical_path(cls, root: Path, relative_key: str) -> Path:
+ """
+ 解析路径的词法位置。
+
+ :param root: 路径解析的基准目录
+ :param relative_key: 相对路径
+ :raises ValueError: 存储路径包含符号链接
+ :return: 供调用方使用的 ``candidate_path``
+ """
FilePathUtil.resolve_path_within_root(root, relative_key)
normalized_key = relative_key.replace('\\', '/')
candidate_path = root.joinpath(*normalized_key.split('/'))
@@ -981,6 +1098,12 @@ def _resolve_lexical_path(cls, root: Path, relative_key: str) -> Path:
@classmethod
def _validate_storage_roots(cls, roots: dict[str, Path]) -> None:
+ """
+ 校验对账可访问的存储根目录。
+
+ :param roots: 需要检查的文件存储根目录集合
+ :raises ValueError: 存储根目录重合或互相嵌套
+ """
root_items = list(roots.items())
for index, (root_name, root_path) in enumerate(root_items):
root_path.mkdir(parents=True, exist_ok=True)
@@ -994,6 +1117,13 @@ def _validate_storage_roots(cls, roots: dict[str, Path]) -> None:
@staticmethod
def _is_relative_to(path: Path, parent: Path) -> bool:
+ """
+ 判断候选路径是否位于指定目录之下。
+
+ :param path: 要读取或处理的路径
+ :param parent: 用于判断路径从属关系的父目录
+ :return: 是否候选路径是否位于指定目录之下
+ """
try:
path.relative_to(parent)
return True
@@ -1002,6 +1132,12 @@ def _is_relative_to(path: Path, parent: Path) -> bool:
@staticmethod
def _get_path_state(path: Path) -> str:
+ """
+ 读取对账路径的文件系统状态。
+
+ :param path: 要读取或处理的路径
+ :return: 对账路径的文件系统状态
+ """
if path.is_symlink():
return 'unsafe'
if not path.exists():
@@ -1010,10 +1146,24 @@ def _get_path_state(path: Path) -> str:
@staticmethod
def _get_text_value(file_info: dict[str, Any], field_name: str) -> str | None:
+ """
+ 从文件记录中提取文本字段。
+
+ :param file_info: 文件信息
+ :param field_name: 需要读取或校验的字段名
+ :return: 文本字段值,缺失时为空值
+ """
value = file_info.get(field_name)
return str(value) if value is not None else None
@staticmethod
def _get_int_value(file_info: dict[str, Any], field_name: str) -> int | None:
+ """
+ 从文件记录中提取整数字段。
+
+ :param file_info: 文件信息
+ :param field_name: 需要读取或校验的字段名
+ :return: 整数字段值,缺失时为空值
+ """
value = file_info.get(field_name)
return int(value) if value is not None else None
diff --git a/ruoyi-fastapi-backend/utils/gen_i18n_util.py b/ruoyi-fastapi-backend/utils/gen_i18n_util.py
index 4c82843af..fee47aa7c 100644
--- a/ruoyi-fastapi-backend/utils/gen_i18n_util.py
+++ b/ruoyi-fastapi-backend/utils/gen_i18n_util.py
@@ -15,7 +15,21 @@
class GenI18nUtil:
"""
- 生成模块的独立语言资源与增量合并工具
+ 生成模块的独立语言资源与增量合并工具。
+
+ :cvar PROJECT_ROOT: 用于定位项目资源的根目录
+ :cvar FRAMEWORKS: 支持生成翻译资源的前端框架
+ :cvar KEY_PATTERN: 检查消息键格式的正则表达式
+ :cvar PO_LINE_PATTERN: 校验 PO 消息行语法的正则表达式
+ :ivar framework: 目标前端框架
+ :ivar app_root: 生成翻译资源时使用的应用根目录
+ :ivar source_locale: 源消息使用的语言标识
+ :ivar locales: 生成翻译资源的目标语言列表
+ :ivar translations: 按语言和消息键索引的译文
+ :ivar namespace: 隔离当前资源的命名空间
+ :ivar frontend: 前端部分的配置
+ :ivar backend: 后端部分的配置或处理对象
+ :ivar field_prefixes: 生成字段消息键时识别的前缀
"""
PROJECT_ROOT = Path(__file__).resolve().parents[2]
@@ -25,9 +39,10 @@ class GenI18nUtil:
def __init__(self, table: GenTableModel) -> None:
"""
- 从目标应用配置确定语言,保留表注释作为基准文案
+ 从目标应用配置确定语言,保留表注释作为基准文案。
:param table: 本次生成使用的业务表副本
+ :raises ServiceWarning: 生成基准语言与目标应用或后端配置不一致
"""
self.framework = self.FRAMEWORKS.get(table.tpl_web_type, 'vue2')
self.app_root = self.PROJECT_ROOT / 'ruoyi-fastapi-frontend' / self.framework / 'web'
@@ -100,7 +115,9 @@ def __init__(self, table: GenTableModel) -> None:
@staticmethod
def invalid_configuration() -> None:
"""
- 拒绝无法安全注册或插值的生成参数
+ 拒绝无法安全注册或插值的生成参数。
+
+ :raises ServiceWarning: 国际化生成配置无效,请检查语言列表与译文占位符
"""
raise ServiceWarning(
message='国际化生成配置无效,请检查语言列表与译文占位符',
@@ -109,7 +126,7 @@ def invalid_configuration() -> None:
def key(self, suffix: str) -> str:
"""
- 生成可由静态扫描识别的完整前端消息标识
+ 生成可由静态扫描识别的完整前端消息标识。
:param suffix: 模块内稳定语义路径
:return: 完整命名空间和消息标识
@@ -120,7 +137,7 @@ def key(self, suffix: str) -> str:
def text(self, suffix: str, source: str, english: str | None = None) -> str:
"""
- 登记模板文案,未提供的目标语言译文保持为空
+ 登记模板文案,未提供的目标语言译文保持为空。
:param suffix: 模块内稳定语义路径
:param source: 基准文案
@@ -140,7 +157,7 @@ def text(self, suffix: str, source: str, english: str | None = None) -> str:
def field_key(self, column: GenTableColumnModel, suffix: str = 'label') -> str:
"""
- 根据代码字段生成标签、占位符或必填提示
+ 根据代码字段生成标签、占位符或必填提示。
:param column: 主表或子表字段
:param suffix: label、input、select 或 required
@@ -155,7 +172,7 @@ def field_key(self, column: GenTableColumnModel, suffix: str = 'label') -> str:
def backend_text(self, suffix: str, source: str, english: str | None = None) -> str:
"""
- 登记后端 gettext 消息,使用与前端独立的语义路径
+ 登记后端 gettext 消息,使用与前端独立的语义路径。
:param suffix: 模块内稳定消息路径
:param source: 基准文案,插值使用命名百分号形式
@@ -176,7 +193,7 @@ def backend_text(self, suffix: str, source: str, english: str | None = None) ->
def backend_field_key(self, column: GenTableColumnModel, suffix: str = 'label') -> str:
"""
- 生成后端校验与导出字段消息
+ 生成后端校验与导出字段消息。
:param column: 主表或子表字段
:param suffix: label 或 required
@@ -192,7 +209,7 @@ def backend_field_key(self, column: GenTableColumnModel, suffix: str = 'label')
@staticmethod
def nest(values: dict[str, str]) -> dict:
"""
- 将稳定点路径转换为独立命名空间内的嵌套字典
+ 将稳定点路径转换为独立命名空间内的嵌套字典。
:param values: 点路径及文案
:return: 嵌套资源字典
@@ -209,7 +226,7 @@ def nest(values: dict[str, str]) -> dict:
@classmethod
def merge_json(cls, existing: dict, generated: dict) -> dict:
"""
- 只补充缺失键,不覆盖已有人工文案或删除旧键
+ 只补充缺失键,不覆盖已有人工文案或删除旧键。
:param existing: 已有语言资源
:param generated: 本次生成资源
@@ -226,7 +243,7 @@ def merge_json(cls, existing: dict, generated: dict) -> dict:
@staticmethod
def po_content(entries: dict[str, str], locale: str) -> str:
"""
- 生成可合并到 core 域的 gettext 文本
+ 生成可合并到 core 域的 gettext 文本。
:param entries: 稳定消息标识和译文
:param locale: 目标语言
@@ -245,10 +262,11 @@ def po_content(entries: dict[str, str], locale: str) -> str:
@classmethod
def read_catalog(cls, content: str) -> Catalog:
"""
- 严格解析词库,避免宽松解析器静默截断未加引号的人工译文
+ 严格解析词库,避免宽松解析器静默截断未加引号的人工译文。
:param content: PO 文件内容
:return: 已校验的词库
+ :raises ValueError: 输入包含不受支持的 PO 语句
"""
for raw_line in content.lstrip('\ufeff').splitlines():
line = raw_line.strip()
@@ -259,7 +277,7 @@ def read_catalog(cls, content: str) -> Catalog:
@classmethod
def merge_po(cls, existing: str, generated: str) -> str:
"""
- 合并模块消息,保留已有 gettext 译文和消息标志
+ 合并模块消息,保留已有 gettext 译文和消息标志。
:param existing: 目标目录已有 PO 内容
:param generated: 新增模块 PO 内容
@@ -275,18 +293,24 @@ def merge_po(cls, existing: str, generated: str) -> str:
return output.getvalue().decode('utf-8')
def backend_catalog_path(self, locale: str) -> str:
- """获取当前业务模块在生成包中的后端 PO 路径。"""
+ """
+ 获取当前业务模块在生成包中的后端 PO 路径。
+
+ :param locale: 目标语言
+ :return: 当前业务模块在生成包中的后端 PO 路径
+ """
return f'backend/i18n/catalogs/{locale}/LC_MESSAGES/core/{self.namespace}.po'
@classmethod
def merge_content(cls, relative_path: str, existing: str, generated: str) -> str:
"""
- 按资源类型保留已有人工翻译
+ 按资源类型保留已有人工翻译。
:param relative_path: 生成包内相对路径
:param existing: 已有内容
:param generated: 本次生成内容
:return: 合并后的内容,非词库文件按原有规则更新
+ :raises ServiceWarning: 已有语言资源格式无效,生成已停止以保留原文件
"""
try:
if relative_path.startswith('frontend/src/i18n/locales/') and relative_path.endswith('.json'):
@@ -306,7 +330,7 @@ def merge_content(cls, relative_path: str, existing: str, generated: str) -> str
def refresh_pending(self, artifacts: dict[str, str]) -> None:
"""
- 按合并后的实际词库更新待补译清单
+ 按合并后的实际词库更新待补译清单。
:param artifacts: 已渲染并完成增量合并的生成文件
"""
@@ -333,7 +357,7 @@ def refresh_pending(self, artifacts: dict[str, str]) -> None:
def artifacts(self) -> dict[str, str]:
"""
- 生成独立语言资源、待补译清单和接入说明
+ 生成独立语言资源、待补译清单和接入说明。
:return: 生成包内相对路径和文本内容
"""
diff --git a/ruoyi-fastapi-backend/utils/gen_util.py b/ruoyi-fastapi-backend/utils/gen_util.py
index c3a762183..7e9686b28 100644
--- a/ruoyi-fastapi-backend/utils/gen_util.py
+++ b/ruoyi-fastapi-backend/utils/gen_util.py
@@ -9,7 +9,9 @@
class GenUtils:
"""
- 代码生成器工具类
+ 代码生成器工具类。
+
+ :cvar TEXTAREA_COLUMN_LENGTH: 选择多行输入框时使用的列长度阈值
"""
TEXTAREA_COLUMN_LENGTH = 500
@@ -17,7 +19,7 @@ class GenUtils:
@classmethod
def init_table(cls, gen_table: GenTableModel, oper_name: str) -> None:
"""
- 初始化表信息
+ 初始化表信息。
:param gen_table: 业务表对象
:param oper_name: 操作人
@@ -34,7 +36,7 @@ def init_table(cls, gen_table: GenTableModel, oper_name: str) -> None:
@classmethod
def init_column_field(cls, column: GenTableColumnModel, table: GenTableModel) -> None:
"""
- 初始化列属性字段
+ 初始化列属性字段。
:param column: 业务表字段对象
:param table: 业务表对象
@@ -114,7 +116,7 @@ def init_column_field(cls, column: GenTableColumnModel, table: GenTableModel) ->
@classmethod
def arrays_contains(cls, arr: list[str], target_value: str) -> bool:
"""
- 校验数组是否包含指定值
+ 校验数组是否包含指定值。
:param arr: 数组
:param target_value: 需要校验的值
@@ -125,7 +127,7 @@ def arrays_contains(cls, arr: list[str], target_value: str) -> bool:
@classmethod
def get_module_name(cls, package_name: str) -> str:
"""
- 获取模块名
+ 获取模块名。
:param package_name: 包名
:return: 模块名
@@ -135,7 +137,7 @@ def get_module_name(cls, package_name: str) -> str:
@classmethod
def get_business_name(cls, table_name: str) -> str:
"""
- 获取业务名
+ 获取业务名。
:param table_name: 业务表名
:return: 业务名
@@ -145,7 +147,7 @@ def get_business_name(cls, table_name: str) -> str:
@classmethod
def convert_class_name(cls, table_name: str) -> str:
"""
- 表名转换成Python类名
+ 表名转换成Python类名。
:param table_name: 业务表名
:return: Python类名
@@ -160,7 +162,7 @@ def convert_class_name(cls, table_name: str) -> str:
@classmethod
def replace_first(cls, replacement: str, search_list: list[str]) -> str:
"""
- 批量替换前缀
+ 批量替换前缀。
:param replacement: 需要被替换的字符串
:param search_list: 可替换的字符串列表
@@ -174,7 +176,7 @@ def replace_first(cls, replacement: str, search_list: list[str]) -> str:
@classmethod
def replace_text(cls, text: str) -> str:
"""
- 关键字替换
+ 关键字替换。
:param text: 需要被替换的字符串
:return: 替换后的字符串
@@ -184,7 +186,7 @@ def replace_text(cls, text: str) -> str:
@classmethod
def get_db_type(cls, column_type: str) -> str:
"""
- 获取数据库类型字段
+ 获取数据库类型字段。
:param column_type: 字段类型
:return: 数据库类型
@@ -194,7 +196,7 @@ def get_db_type(cls, column_type: str) -> str:
@classmethod
def get_column_length(cls, column_type: str) -> int:
"""
- 获取字段长度
+ 获取字段长度。
:param column_type: 字段类型
:return: 字段长度
@@ -207,7 +209,7 @@ def get_column_length(cls, column_type: str) -> int:
@classmethod
def split_column_type(cls, column_type: str) -> list[str]:
"""
- 拆分列类型
+ 拆分列类型。
:param column_type: 字段类型
:return: 拆分结果
@@ -219,7 +221,7 @@ def split_column_type(cls, column_type: str) -> list[str]:
@classmethod
def to_camel_case(cls, text: str) -> str:
"""
- 将字符串转换为驼峰命名
+ 将字符串转换为驼峰命名。
:param text: 需要转换的字符串
:return: 驼峰命名
diff --git a/ruoyi-fastapi-backend/utils/import_util.py b/ruoyi-fastapi-backend/utils/import_util.py
index c349e9c58..154fd290f 100644
--- a/ruoyi-fastapi-backend/utils/import_util.py
+++ b/ruoyi-fastapi-backend/utils/import_util.py
@@ -12,10 +12,12 @@
class ImportUtil:
+ """加载可选模块和指定的 Python 对象。"""
+
@classmethod
def find_project_root(cls) -> Path:
"""
- 查找项目根目录
+ 查找项目根目录。
:return: 项目根目录路径
"""
@@ -29,7 +31,7 @@ def find_project_root(cls) -> Path:
@classmethod
def is_valid_model(cls, obj: Any, base_class: Base) -> bool:
"""
- 验证是否为有效的SQLAlchemy模型类
+ 验证是否为有效的SQLAlchemy模型类。
:param obj: 待验证的对象
:param base_class: SQLAlchemy的Base类
@@ -53,7 +55,7 @@ def is_valid_model(cls, obj: Any, base_class: Base) -> bool:
@lru_cache(maxsize=256)
def find_models(cls, base_class: Base) -> list[Base]:
"""
- 查找并过滤有效的模型类,避免重复和无效定义
+ 查找并过滤有效的模型类,避免重复和无效定义。
:param base_class: SQLAlchemy的Base类,用于验证模型类
:return: 有效模型类列表
diff --git a/ruoyi-fastapi-backend/utils/jwt_util.py b/ruoyi-fastapi-backend/utils/jwt_util.py
index 9a52f9aff..dbe114b8c 100644
--- a/ruoyi-fastapi-backend/utils/jwt_util.py
+++ b/ruoyi-fastapi-backend/utils/jwt_util.py
@@ -9,9 +9,7 @@
class JwtUtil:
- """
- JWT编解码工具类。
- """
+ """JWT编解码工具类。"""
@classmethod
def encode(cls, payload: dict[str, Any]) -> str:
@@ -20,6 +18,7 @@ def encode(cls, payload: dict[str, Any]) -> str:
:param payload: JWT载荷
:return: 编码后的JWT
+ :raises AuthException: 用户token生成失败
"""
try:
return jwt.encode(payload, JwtConfig.jwt_secret_key, algorithm=JwtConfig.jwt_algorithm)
@@ -35,6 +34,7 @@ def decode(cls, token: str | bytes, options: dict[str, Any] | None = None) -> di
:param token: 待解析的JWT
:param options: PyJWT解析选项
:return: JWT载荷
+ :raises AuthException: 用户token已失效,请重新登录
"""
try:
return jwt.decode(
diff --git a/ruoyi-fastapi-backend/utils/log_util.py b/ruoyi-fastapi-backend/utils/log_util.py
index 22fb58142..3d77fb491 100644
--- a/ruoyi-fastapi-backend/utils/log_util.py
+++ b/ruoyi-fastapi-backend/utils/log_util.py
@@ -19,7 +19,7 @@
def _split_field_tokens(field_name: str) -> tuple[str, ...]:
"""
- 拆分字段名为文本匹配用的 token
+ 拆分字段名为文本匹配用的 token。
:param field_name: 原始字段名
:return: token 元组
@@ -31,7 +31,7 @@ def _split_field_tokens(field_name: str) -> tuple[str, ...]:
def _build_text_key_pattern(field_name: str) -> str:
"""
- 构建文本日志中的字段名匹配正则,自动兼容 snake_case / camelCase / kebab-case / dot.case
+ 构建文本日志中的字段名匹配正则,自动兼容 snake_case / camelCase / kebab-case / dot.case。
:param field_name: 原始字段名
:return: 正则片段
@@ -44,7 +44,7 @@ def _build_text_key_pattern(field_name: str) -> str:
def _build_text_assignment_patterns(key_pattern: str) -> list[re.Pattern[str]]:
"""
- 构建文本日志中的键值对匹配正则
+ 构建文本日志中的键值对匹配正则。
:param key_pattern: 字段名正则片段
:return: 正则列表
@@ -67,7 +67,27 @@ def _build_text_assignment_patterns(key_pattern: str) -> list[re.Pattern[str]]:
class LogSanitizer:
"""
- 日志脱敏工具
+ 日志脱敏工具。
+
+ :cvar _MASK: 替换敏感内容的脱敏文本
+ :cvar _PHONE_MIN_LENGTH: 启用手机号局部脱敏的最小字符数
+ :cvar _PHONE_PREFIX_LENGTH: 手机号脱敏后保留的前缀位数
+ :cvar _PHONE_SUFFIX_LENGTH: 手机号脱敏后保留的后缀位数
+ :cvar _EMAIL_SHORT_LOCAL_LENGTH: 短邮箱用户名采用专用脱敏方式的长度阈值
+ :cvar _IPV4_PARTS: IPv4 地址预期包含的段数
+ :cvar _IPV4_VISIBLE_PARTS: 脱敏后仍显示的 IPv4 地址段数
+ :cvar _IPV6_MASK_THRESHOLD: 启用 IPv6 局部掩码的长度阈值
+ :cvar _IPV6_VISIBLE_PARTS: 脱敏后仍显示的 IPv6 地址段数
+ :cvar _SENSITIVE_FIELDS: 日志中需要完全隐藏的字段集合
+ :cvar _TEXT_SENSITIVE_FIELDS: 从非结构化文本中识别的敏感字段
+ :cvar _TEXT_SENSITIVE_KEY_PATTERN: 从文本中匹配敏感字段名的模式
+ :cvar _PARTIAL_MASK_FIELDS: 仅保留部分字符的字段集合
+ :cvar _TEXT_PARTIAL_FIELDS: 文本中需要局部脱敏的字段
+ :cvar _TEXT_PARTIAL_KEY_PATTERN: 从文本中定位局部脱敏字段的模式
+ :cvar _CONFIG_SECRET_PATTERNS: 用于识别配置项秘密值的匹配规则
+ :cvar _KV_PATTERNS: 用于识别文本中键值对的匹配规则
+ :cvar _PARTIAL_KV_PATTERNS: 匹配需要局部脱敏的键值对的模式
+ :cvar _LOGIN_CODE_PATTERN: 匹配日志中登录验证码的模式
"""
_MASK = LogConfig.log_mask_placeholder
@@ -118,7 +138,7 @@ class LogSanitizer:
@classmethod
def sanitize_data(cls, data: Any, field_name: str | None = None) -> Any:
"""
- 对日志数据进行脱敏
+ 对日志数据进行脱敏。
:param data: 原始日志数据
:param field_name: 当前字段名
@@ -143,7 +163,7 @@ def sanitize_data(cls, data: Any, field_name: str | None = None) -> Any:
@classmethod
def sanitize_text(cls, text: str) -> str:
"""
- 对普通文本日志进行脱敏
+ 对普通文本日志进行脱敏。
:param text: 原始文本
:return: 脱敏后的文本
@@ -158,7 +178,7 @@ def sanitize_text(cls, text: str) -> str:
@classmethod
def _sanitize_mapping(cls, data: Mapping[Any, Any]) -> dict[Any, Any]:
"""
- 对字典类型数据进行脱敏
+ 对字典类型数据进行脱敏。
:param data: 字典数据
:return: 脱敏后的字典
@@ -187,7 +207,7 @@ def _sanitize_mapping(cls, data: Mapping[Any, Any]) -> dict[Any, Any]:
@classmethod
def _sanitize_string(cls, value: str, field_name: str | None = None) -> Any:
"""
- 对字符串数据进行脱敏
+ 对字符串数据进行脱敏。
:param value: 字符串值
:param field_name: 当前字段名
@@ -233,7 +253,7 @@ def _sanitize_string(cls, value: str, field_name: str | None = None) -> Any:
@classmethod
def _replace_text_secret(cls, match: re.Match[str]) -> str:
"""
- 替换文本中的敏感值
+ 替换文本中的敏感值。
:param match: 正则匹配对象
:return: 脱敏后的文本
@@ -247,7 +267,7 @@ def _replace_text_secret(cls, match: re.Match[str]) -> str:
@classmethod
def _replace_text_partial_secret(cls, match: re.Match[str]) -> str:
"""
- 替换文本中的部分脱敏字段值
+ 替换文本中的部分脱敏字段值。
:param match: 正则匹配对象
:return: 脱敏后的文本
@@ -263,7 +283,7 @@ def _replace_text_partial_secret(cls, match: re.Match[str]) -> str:
@staticmethod
def _dump_sanitized_structured_text(sanitized_value: Any, original_text: str) -> Any:
"""
- 将脱敏后的结构化数据恢复为文本,并尽量保持原始换行风格
+ 将脱敏后的结构化数据恢复为文本,并尽量保持原始换行风格。
:param sanitized_value: 脱敏后的结构化数据
:param original_text: 原始文本
@@ -279,7 +299,7 @@ def _should_fully_mask_field(
cls, normalized_key: str, value: Any, full_mapping: Mapping[str, Any] | None = None
) -> bool:
"""
- 判断字段是否需要全量脱敏
+ 判断字段是否需要全量脱敏。
:param normalized_key: 标准化后的字段名
:param value: 字段值
@@ -299,7 +319,7 @@ def _should_fully_mask_field(
@classmethod
def _is_secret_config_key(cls, config_key: str) -> bool:
"""
- 判断参数键是否属于敏感配置
+ 判断参数键是否属于敏感配置。
:param config_key: 参数键
:return: 是否敏感
@@ -309,7 +329,7 @@ def _is_secret_config_key(cls, config_key: str) -> bool:
@classmethod
def _mask_partial_value(cls, value: str, normalized_field: str) -> str:
"""
- 对部分字段进行部分脱敏
+ 对部分字段进行部分脱敏。
:param value: 原始值
:param normalized_field: 标准化后的字段名
@@ -326,7 +346,7 @@ def _mask_partial_value(cls, value: str, normalized_field: str) -> str:
@staticmethod
def _normalize_key(field_name: str) -> str:
"""
- 标准化字段名
+ 标准化字段名。
:param field_name: 原始字段名
:return: 标准化字段名
@@ -336,7 +356,7 @@ def _normalize_key(field_name: str) -> str:
@classmethod
def _mask_phone(cls, value: str) -> str:
"""
- 手机号脱敏
+ 手机号脱敏。
:param value: 原始手机号
:return: 脱敏后的手机号
@@ -349,7 +369,7 @@ def _mask_phone(cls, value: str) -> str:
@classmethod
def _mask_email(cls, value: str) -> str:
"""
- 邮箱脱敏
+ 邮箱脱敏。
:param value: 原始邮箱
:return: 脱敏后的邮箱
@@ -367,7 +387,7 @@ def _mask_email(cls, value: str) -> str:
@classmethod
def _mask_ip(cls, value: str) -> str:
"""
- IP地址脱敏
+ IP地址脱敏。
:param value: 原始IP
:return: 脱敏后的IP
@@ -384,14 +404,19 @@ def _mask_ip(cls, value: str) -> str:
class InterceptHandler(logging.Handler):
+ """
+ 将标准库日志转发给应用日志处理器。
+
+ :cvar target_logger: 接收转发日志记录的记录器
+ """
+
target_logger = _logger
def emit(self, record: logging.LogRecord) -> None:
"""
- 拦截标准 logging 记录并转发到 Loguru
+ 拦截标准 logging 记录并转发到 Loguru。
:param record: 原生 logging 日志记录
- :return: None
"""
try:
level = self.target_logger.level(record.levelname).name
@@ -405,12 +430,18 @@ def emit(self, record: logging.LogRecord) -> None:
class LoggerInitializer:
- def __init__(self) -> None:
- """
- 初始化日志基础配置与运行时标识
+ """
+ 初始化应用的日志输出目标和格式。
- :return: None
- """
+ :ivar worker_id: 工作进程的标识
+ :ivar instance_id: 写入日志的服务实例标识
+ :ivar service_name: 写入日志的服务名称
+ :ivar _log_file_enabled: 是否将日志写入文件
+ :ivar _log_base_dir: 日志文件所在的目录
+ """
+
+ def __init__(self) -> None:
+ """初始化日志基础配置与运行时标识。"""
self.worker_id = WorkerIdUtil.get_worker_id(LogConfig.log_worker_id)
self.instance_id = LogConfig.log_instance_id
self.service_name = LogConfig.log_service_name or AppConfig.app_name
@@ -419,11 +450,7 @@ def __init__(self) -> None:
self._ensure_log_directory_exists()
def _ensure_log_directory_exists(self) -> None:
- """
- 确保日志目录存在
-
- :return: None
- """
+ """确保日志目录存在。"""
if not self._log_file_enabled:
return
if self._log_base_dir and not os.path.exists(self._log_base_dir):
@@ -454,7 +481,7 @@ def _filter(self, record: dict) -> bool:
@staticmethod
def _get_exception_value_text(exception: Any) -> str | None:
"""
- 获取脱敏后的异常值文本
+ 获取脱敏后的异常值文本。
:param exception: Loguru 异常对象
:return: 脱敏后的异常值文本
@@ -465,7 +492,7 @@ def _get_exception_value_text(exception: Any) -> str | None:
def _get_exception_traceback_text(self, exception: Any) -> str | None:
"""
- 获取脱敏后的异常堆栈文本
+ 获取脱敏后的异常堆栈文本。
:param exception: Loguru 异常对象
:return: 脱敏后的异常堆栈文本
@@ -482,7 +509,7 @@ def _get_exception_traceback_text(self, exception: Any) -> str | None:
def _build_plain_exception_suffix(self, record: dict) -> str:
"""
- 构建普通文本日志使用的异常后缀
+ 构建普通文本日志使用的异常后缀。
:param record: Loguru 日志记录字典
:return: 异常后缀文本
@@ -492,7 +519,7 @@ def _build_plain_exception_suffix(self, record: dict) -> str:
def _build_json_payload(self, record: dict) -> dict:
"""
- 构建统一的 JSON 日志结构
+ 构建统一的 JSON 日志结构。
:param record: Loguru 日志记录字典
:return: JSON 日志结构
@@ -526,7 +553,7 @@ def _build_json_payload(self, record: dict) -> dict:
def _json_log_formatter(self, record: dict) -> str:
"""
- 将 Loguru 日志记录格式化为 JSON 文本
+ 将 Loguru 日志记录格式化为 JSON 文本。
:param record: Loguru 日志记录字典
:return: JSON 格式文本
@@ -536,7 +563,7 @@ def _json_log_formatter(self, record: dict) -> str:
def _plain_log_formatter(self, record: dict) -> str:
"""
- 将 Loguru 日志记录格式化为普通文本,并追加脱敏后的异常堆栈
+ 将 Loguru 日志记录格式化为普通文本,并追加脱敏后的异常堆栈。
:param record: Loguru 日志记录字典
:return: 普通文本格式模板
@@ -555,7 +582,7 @@ def _plain_log_formatter(self, record: dict) -> str:
def _patch_record(self, record: dict) -> dict:
"""
- 在日志落地前统一脱敏
+ 在日志落地前统一脱敏。
:param record: Loguru 日志记录字典
:return: 脱敏后的日志记录字典
@@ -566,7 +593,7 @@ def _patch_record(self, record: dict) -> dict:
def _info_file_filter(self, record: dict) -> bool:
"""
- 仅输出 INFO 级别日志到 info 文件
+ 仅输出 INFO 级别日志到 info 文件。
:param record: Loguru 日志记录字典
:return: 是否允许输出日志
@@ -575,7 +602,7 @@ def _info_file_filter(self, record: dict) -> bool:
def _error_file_filter(self, record: dict) -> bool:
"""
- 输出 WARNING 及以上日志到 error 文件
+ 输出 WARNING 及以上日志到 error 文件。
:param record: Loguru 日志记录字典
:return: 是否允许输出日志
@@ -583,11 +610,7 @@ def _error_file_filter(self, record: dict) -> bool:
return self._filter(record) and record['level'].no >= logging.WARNING
def _configure_logging(self) -> None:
- """
- 统一接管标准 logging 与第三方日志输出
-
- :return: None
- """
+ """统一接管标准 logging 与第三方日志输出。"""
logging.basicConfig(handlers=[InterceptHandler()], level=0, force=True)
for logger_name in ('uvicorn', 'uvicorn.error', 'uvicorn.access', 'fastapi'):
logging.getLogger(logger_name).handlers = [InterceptHandler()]
@@ -597,7 +620,7 @@ def _configure_logging(self) -> None:
def init_log(self) -> Logger:
"""
- 初始化 Loguru 输出与标准 logging 配置
+ 初始化 Loguru 输出与标准 logging 配置。
:return: 已配置的 Loguru Logger 实例
"""
diff --git a/ruoyi-fastapi-backend/utils/message_util.py b/ruoyi-fastapi-backend/utils/message_util.py
index b425d3b57..7d27a7c41 100644
--- a/ruoyi-fastapi-backend/utils/message_util.py
+++ b/ruoyi-fastapi-backend/utils/message_util.py
@@ -2,4 +2,9 @@
def message_service(sms_code: str) -> None:
+ """
+ 将短信验证码写入日志。
+
+ :param sms_code: 短信验证码
+ """
logger.info(f'短信验证码为{sms_code}')
diff --git a/ruoyi-fastapi-backend/utils/oidc_util.py b/ruoyi-fastapi-backend/utils/oidc_util.py
index af67be352..495d181d7 100644
--- a/ruoyi-fastapi-backend/utils/oidc_util.py
+++ b/ruoyi-fastapi-backend/utils/oidc_util.py
@@ -22,6 +22,33 @@
class OidcUtil:
"""
统一认证公共工具类。
+
+ :cvar _PROTOCOL_DESCRIPTION_PATTERN: 校验协议错误描述允许字符的正则表达式
+ :cvar _ERROR_MESSAGES: 按错误类型查找的提示文本
+ :cvar _DEFAULT_PROTOCOL_DESCRIPTIONS: 按协议错误码选择的默认英文说明
+ :cvar _DESCRIPTION_MESSAGES: 协议错误描述到本地化消息的映射
+ :cvar _PROTOCOL_DESCRIPTIONS: 本地化消息到协议错误描述的反向映射
+ :cvar _SENSITIVE_KEY: 匹配需要隐藏的敏感字段名的规则
+ :cvar _SENSITIVE_VALUE: 匹配可能包含凭证的字段值的规则
+ :cvar _OPAQUE_CAPABILITY: 匹配不透明凭证格式的正则表达式
+ :cvar _JWT_PART_COUNT: 识别 JWT 时要求的片段数
+ :cvar _JWT_PART_MIN_LENGTH: 识别 JWT 片段时允许的最小长度
+ :cvar _JWT_PART_MAX_LENGTH: 识别 JWT 片段时允许的最大长度
+ :cvar _COMPONENT_PATTERN: 校验标识组件格式的正则表达式
+ :cvar _SHA256_HEX_LENGTH: SHA-256 摘要的十六进制字符数
+ :cvar _ENCRYPTION_KDF_ITERATIONS: 密钥派生使用的迭代次数
+ :cvar _SAFE_KID_PATTERN: 校验密钥标识格式的正则表达式
+ :cvar _MIN_PEPPER_BYTES: 服务端摘要密钥要求的最少字节数
+ :cvar _MAX_URI_LENGTH: 允许注册或处理的 URI 长度上限
+ :cvar _DEVELOPMENT_HTTP_HOSTS: 在开发环境允许使用 HTTP 的主机名
+ :cvar _USERINFO_AUDIENCE_SUFFIX: 构造用户信息接口受众标识的后缀
+ :cvar _ASCII_CONTROL_LIMIT: ASCII 控制字符范围的上界
+ :cvar _MAX_USER_AGENT_LENGTH: 保存客户端标识字符串时的长度上限
+ :cvar _COOKIE_PARTS: 解析会话 Cookie 时预期的组成段数
+ :cvar _COOKIE_PREFIX: 标识会话 Cookie 格式的前缀
+ :cvar _COOKIE_SECRET_TEXT_LENGTH: Cookie 密钥编码后的字符长度
+ :cvar _COOKIE_SECRET_BYTES: 生成 Cookie 密钥时使用的随机字节数
+ :cvar _S256_CHALLENGE: 校验 PKCE S256 挑战值的正则表达式
"""
_PROTOCOL_DESCRIPTION_PATTERN = re.compile(r'[\x20-\x21\x23-\x5B\x5D-\x7E]+')
@@ -238,14 +265,13 @@ def protocol_error_description(cls, error: str, description: str | None) -> str
@staticmethod
def read_field(user: Any, name: str, default: Any = None) -> Any:
"""
- 从 ORM 用户对象或字典读取字段
+ 从 ORM 用户对象或字典读取字段。
:param user: SysUser ORM 记录或用户 Claim 字段映射
:param name: 字段名称
:param default: 字段缺省值
:return: 读取的字段值
"""
-
if isinstance(user, Mapping):
return user.get(name, default)
return getattr(user, name, default)
@@ -253,13 +279,13 @@ def read_field(user: Any, name: str, default: Any = None) -> Any:
@staticmethod
def positive_int(value: Any, field: str) -> int:
"""
- 校验正整数标量
+ 校验正整数标量。
:param value: 待校验的正整数
:param field: 字段名称
:return: 校验后的正整数
+ :raises ValueError: 字段值不是正整数
"""
-
if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
raise ValueError(f'{field} 必须为正整数')
return value
@@ -267,13 +293,13 @@ def positive_int(value: Any, field: str) -> int:
@staticmethod
def nonnegative_int(value: Any, field: str) -> int:
"""
- 校验非负整数标量
+ 校验非负整数标量。
:param value: 待校验的非负整数
:param field: 字段名称
:return: 校验后的非负整数
+ :raises ValueError: 字段值不是非负整数
"""
-
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
raise ValueError(f'{field} 必须为非负整数')
return value
@@ -281,14 +307,14 @@ def nonnegative_int(value: Any, field: str) -> int:
@staticmethod
def nonempty_string(value: Any, field: str, limit: int) -> str:
"""
- 校验非空字符串及长度
+ 校验非空字符串及长度。
:param value: 待校验的字符串
:param field: 字段名称
:param limit: 字符串的最大长度
:return: 校验后的字符串
+ :raises ValueError: 值不是非空字符串或超过长度上限
"""
-
if not isinstance(value, str) or not value or len(value) > limit:
raise ValueError(f'{field} 必须为非空字符串')
return value
@@ -296,14 +322,14 @@ def nonempty_string(value: Any, field: str, limit: int) -> str:
@classmethod
def string_list(cls, value: Any, field: str, limit: int) -> list[str]:
"""
- 校验字符串列表并复制为 JSON 安全列表
+ 校验字符串列表并复制为 JSON 安全列表。
:param value: 待校验的字符串列表
:param field: 字段名称
:param limit: 字符串列表的最大长度
:return: 校验后的字符串列表
+ :raises ValueError: 值不是满足长度要求的字符串序列
"""
-
if not isinstance(value, (list, tuple)) or len(value) > limit:
raise ValueError(f'{field} 必须为符合长度限制的字符串列表')
return [cls.nonempty_string(item, field, 500) for item in value]
@@ -311,24 +337,22 @@ def string_list(cls, value: Any, field: str, limit: int) -> list[str]:
@staticmethod
def json_list(value: Any) -> list[Any]:
"""
- 将 Scope 或 Resource 字段规范化为列表
+ 将 Scope 或 Resource 字段规范化为列表。
:param value: JSON 编码的 Scope 或 Resource 列表值
:return: Scope 或 Resource 元素列表;输入不是 JSON 数组时返回空列表
"""
-
return list(value) if isinstance(value, (list, tuple)) else []
@staticmethod
def json_object_pairs(items: list[tuple[str, object]]) -> dict[str, object]:
"""
- 构造拒绝重复字段的 JSON 对象
+ 构造拒绝重复字段的 JSON 对象。
:param items: JSON 对象字段
:return: 唯一字段组成的对象
:raises ValueError: JSON 对象包含重复字段
"""
-
result: dict[str, object] = {}
for key, value in items:
# 拒绝重复字段,避免不同解析器产生歧义
@@ -345,6 +369,7 @@ def serialize_json(record: Mapping[str, Any], *, error_message: str) -> str:
:param record: 需要缓存的标量载荷
:param error_message: 调用场景的中文错误说明
:return: 按键排序的 JSON 字符串
+ :raises ValueError: 数据不能序列化为有效的 JSON
"""
try:
return json.dumps(record, ensure_ascii=False, separators=(',', ':'), sort_keys=True, allow_nan=False)
@@ -354,12 +379,11 @@ def serialize_json(record: Mapping[str, Any], *, error_message: str) -> str:
@staticmethod
def json_etag(payload: Mapping[str, Any]) -> str:
"""
- 为 JWKS 响应计算稳定的强 ETag
+ 为 JWKS 响应计算稳定的强 ETag。
:param payload: 公开响应 JSON 映射
:return: 带双引号的 SHA-256 ETag
"""
-
canonical = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode()
return '"' + hashlib.sha256(canonical).hexdigest() + '"'
@@ -372,6 +396,7 @@ def actor_name(value: Any, *, error_message: str = '操作者不能为空') -> s
:param value: 待校验的操作者名称
:param error_message: 名称不可用时的中文说明
:return: 最多 64 个字符的操作者名称
+ :raises ValueError: 操作人名称为空或格式无效
"""
if not isinstance(value, str) or not value.strip():
raise ValueError(error_message)
@@ -387,6 +412,7 @@ def split_batch(value: str, field_name: str, *, max_size: int, validate_all_firs
:param max_size: 允许的最大项目数量
:param validate_all_first: 是否先校验全部格式再检查重复,保留调用场景的报错顺序
:return: 去除首尾空白后的标识列表
+ :raises ValueError: 批次为空、超出大小限制或含有重复参数
"""
items = value.split(',') if isinstance(value, str) else []
if not items or len(items) > max_size:
@@ -394,6 +420,12 @@ def split_batch(value: str, field_name: str, *, max_size: int, validate_all_firs
values = [item.strip() for item in items]
def invalid(item: str) -> bool:
+ """
+ 判断批量标识是否包含不可接受的路径字符。
+
+ :param item: 当前要处理的条目
+ :return: 是否批量标识是否包含不可接受的路径字符
+ """
return not item or '%' in item or '/' in item or '\\' in item or any(char.isspace() for char in item)
if validate_all_first and any(invalid(item) for item in values):
@@ -415,6 +447,7 @@ def unique_codes(values: Iterable[str], field_name: str) -> list[str]:
:param values: 待校验的编码集合
:param field_name: 中文错误说明中的字段名称
:return: 保持原序的编码列表
+ :raises ValueError: 标识为空、带有多余空白或包含重复项
"""
result: list[str] = []
for value in values:
@@ -428,13 +461,13 @@ def unique_codes(values: Iterable[str], field_name: str) -> list[str]:
@staticmethod
def normalize_user_ids(values: Iterable[int], *, max_size: int) -> tuple[int, ...]:
"""
- 校验、去重并排序用户 ID,确保批量锁顺序稳定
+ 校验、去重并排序用户 ID,确保批量锁顺序稳定。
:param values: 待校验的用户 ID 可迭代集合
:param max_size: 去重后允许的最大用户数量
:return: 排序去重后的用户 ID 元组
+ :raises ValueError: 用户编号列表必须全部为整数;用户编号列表数量无效;用户编号列表必须全部为正整数
"""
-
if isinstance(values, (str, bytes)):
raise ValueError('用户编号列表必须全部为整数')
result = tuple(sorted(set(values)))
@@ -453,18 +486,16 @@ def is_trimmed_identifier(value: str, *, max_length: int) -> bool:
:param max_length: 标识最大长度
:return: Session ID 是否有效
"""
-
return isinstance(value, str) and 1 <= len(value) <= max_length and value.strip() == value
@staticmethod
def scope_set(scopes: str | Iterable[str] | None) -> set[str]:
"""
- 将空格分隔或集合形式的 Scope 规范化
+ 将空格分隔或集合形式的 Scope 规范化。
:param scopes: 请求的 Scope 集合
:return: 规范化 Scope 集合
"""
-
if scopes is None:
return set()
if isinstance(scopes, str):
@@ -474,12 +505,11 @@ def scope_set(scopes: str | Iterable[str] | None) -> set[str]:
@staticmethod
def normalize_audiences(value: Any) -> list[str]:
"""
- 将 aud 声明规范化为去重列表
+ 将 aud 声明规范化为去重列表。
:param value: OAuth Token 的 Audience 声明值
:return: 去重后的 Audience 列表;格式非法时返回空列表
"""
-
values = [value] if isinstance(value, str) else value
if not isinstance(values, list) or not values or any(not isinstance(item, str) or not item for item in values):
return []
@@ -488,13 +518,12 @@ def normalize_audiences(value: Any) -> list[str]:
@staticmethod
def token_audiences(issuer: str, resources: Sequence[str]) -> list[str]:
"""
- 将 aud 声明规范化为去重列表
+ 将 aud 声明规范化为去重列表。
- :param issuer: OIDC issuer URL
+ :param issuer: OIDC 签发者地址
:param resources: 已校验的 Resource audience 字符串序列
:return: 包含 userinfo audience 和 Resource audience 的去重列表
"""
-
result = [f'{issuer.rstrip("/")}{OidcUtil._USERINFO_AUDIENCE_SUFFIX}']
result.extend(resources)
@@ -503,12 +532,11 @@ def token_audiences(issuer: str, resources: Sequence[str]) -> list[str]:
@staticmethod
def claim_numeric_date(value: Any) -> int | float | None:
"""
- 将用户更新时间转换为 NumericDate
+ 将用户更新时间转换为 NumericDate。
:param value: 用户更新时间
:return: NumericDate 时间戳或 None
"""
-
if value is None or isinstance(value, (int, float)):
return value
timestamp = getattr(value, 'timestamp', None)
@@ -518,12 +546,11 @@ def claim_numeric_date(value: Any) -> int | float | None:
@staticmethod
def numeric_date(value: datetime | None) -> int | None:
"""
- 将 datetime 转换为有限的 Unix 时间戳
+ 将 datetime 转换为有限的 Unix 时间戳。
:param value: 可选的 Token 签发时间或过期时间
:return: 有限的 Unix 时间戳;输入为空或时间戳非有限时返回 None
"""
-
if value is None:
return None
timestamp = value.timestamp()
@@ -533,14 +560,14 @@ def numeric_date(value: datetime | None) -> int | None:
@staticmethod
def requires_reauthentication(auth_time: datetime, max_age: int | None, now: datetime | None = None) -> bool:
"""
- 纯函数判断 SSO 认证是否超过 max_age
+ 纯函数判断 SSO 认证是否超过 max_age。
:param auth_time: SSO 认证时间
:param max_age: 请求的最大认证年龄
:param now: 可选当前时间
:return: 超过 max_age 时为 True
+ :raises ValueError: max_age 必须为非负整数
"""
-
# 时间工具依赖基础异常,延迟导入避免异常模块初始化时形成循环。
from utils.time_util import TimezoneUtil # noqa: PLC0415
@@ -558,13 +585,13 @@ def requires_reauthentication(auth_time: datetime, max_age: int | None, now: dat
@staticmethod
def validate_path_identifier(value: str, field_name: str) -> str:
"""
- 校验可安全放入单一路径段的管理标识
+ 校验可安全放入单一路径段的管理标识。
:param value: 待校验的资源或权限标识
:param field_name: 校验失败时展示的字段名称
:return: 校验通过的管理标识
+ :raises ValueError: 标识含有不能用于单一路径段的字符
"""
-
if (
not isinstance(value, str)
or not value
@@ -587,13 +614,13 @@ def is_valid_kid(cls, value: Any) -> bool:
@staticmethod
def validate_registered_uri(uri_type: str, value: str) -> str:
"""
- 校验注册 URI
+ 校验注册 URI。
:param uri_type: 注册地址类型
:param value: 待校验的完整注册地址
:return: 校验通过的原始注册地址
+ :raises ValueError: 地址不得包含通配符;地址必须使用 HTTP 或 HTTPS 协议并包含主机名;地址不得包含用户名或密码;地址不得包含片段标识 fragment;后端退出通知地址不得包含查询参数;地址中的主机名或端口无效;地址必须包含主机名;HTTP 地址仅允许用于本机开发环境;跨域来源只能包含协议、主机名和可选端口
"""
-
if '*' in value:
raise ValueError('地址不得包含通配符')
parsed = urlsplit(value)
@@ -621,14 +648,13 @@ def validate_registered_uri(uri_type: str, value: str) -> str:
@staticmethod
def validate_resource_audience(audience: str, *, max_length: int) -> str:
"""
- 校验 Resource audience URI
+ 校验 Resource audience URI。
- :param audience: Resource audience
+ :param audience: 目标资源的受众标识
:param max_length: URI 最大长度
:return: 校验后的 Resource audience URI
:raises ValueError: audience 不是无用户信息的绝对 HTTPS URI 时抛出
"""
-
if not isinstance(audience, str) or not audience or len(audience) > max_length:
raise ValueError('资源受众必须为非空地址')
parsed = urlsplit(audience)
@@ -648,12 +674,11 @@ def validate_resource_audience(audience: str, *, max_length: int) -> str:
@staticmethod
def is_safe_post_logout_uri(uri: Any) -> bool:
"""
- 验证退出后重定向 URI 的安全格式
+ 验证退出后重定向 URI 的安全格式。
:param uri: 回调 URI
:return: URI 是否满足退出后重定向安全约束
"""
-
if not isinstance(uri, str) or not uri or len(uri) > OidcUtil._MAX_URI_LENGTH or '*' in uri:
return False
try:
@@ -675,12 +700,11 @@ def is_safe_post_logout_uri(uri: Any) -> bool:
@staticmethod
def is_public_ip(value: str) -> bool:
"""
- 判断地址是否不属于回环、内网、链路本地或保留网段
+ 判断地址是否不属于回环、内网、链路本地或保留网段。
:param value: IPv4 或 IPv6 文本地址
:return: 仅当地址可作为公网目标时返回 ``True``
"""
-
try:
address = ipaddress.ip_address(value)
except ValueError:
@@ -697,12 +721,11 @@ def is_public_ip(value: str) -> bool:
@staticmethod
def parse_backchannel_uri(uri: object) -> tuple[str, int] | None:
"""
- 解析并校验 Back-Channel URI 的非网络安全边界
+ 解析并校验 Back-Channel URI 的非网络安全边界。
:param uri: 待校验的 URI
:return: 合法时返回主机名和端口,否则返回 ``None``
"""
-
if not isinstance(uri, str) or not uri or len(uri) > OidcUtil._MAX_URI_LENGTH or '*' in uri:
return None
try:
@@ -770,13 +793,12 @@ def replace_query_parameters(
@staticmethod
def append_state(redirect_uri: str, state: str | None) -> str:
"""
- 为已验证的退出回调地址附加状态参数
+ 为已验证的退出回调地址附加状态参数。
:param redirect_uri: 服务端已验证的退出回调地址
:param state: 原始退出状态参数
:return: 附加状态参数后的回调地址
"""
-
if state is None:
return redirect_uri
return OidcUtil.replace_query_parameters(redirect_uri, [('state', state)], {'state'})
@@ -784,14 +806,13 @@ def append_state(redirect_uri: str, state: str | None) -> str:
@staticmethod
def interaction_url(base: str, interaction_id: str, csrf_token: str) -> str:
"""
- 构建只把原始 CSRF 放入 URL Fragment 的交互地址
+ 构建只把原始 CSRF 放入 URL Fragment 的交互地址。
:param base: 交互地址基址
:param interaction_id: 交互流程标识
- :param csrf_token: CSRF Token
+ :param csrf_token: 防止跨站请求伪造的令牌
:return: 交互页面 URL
"""
-
parsed = urlsplit(base)
query = dict(parse_qsl(parsed.query, keep_blank_values=True))
query['interaction'] = interaction_id
@@ -805,6 +826,7 @@ def normalize_prompt(value: str | None) -> str | None:
:param value: 空格分隔的 prompt 参数
:return: 保持原顺序的规范化参数或 None
+ :raises ValueError: prompt 只能包含支持的值,且 none 不能与其他值组合
"""
if value is None:
return None
@@ -833,12 +855,11 @@ def is_s256_challenge(cls, value: Any) -> bool:
@staticmethod
def base64url_encode(value: bytes) -> str:
"""
- 将字节编码为无填充的 Base64URL 文本
+ 将字节编码为无填充的 Base64URL 文本。
:param value: 待编码字节
:return: 无填充的 Base64URL 文本
"""
-
return base64.urlsafe_b64encode(value).rstrip(b'=').decode('ascii')
@staticmethod
@@ -855,14 +876,13 @@ def sha256_digest(value: str | bytes) -> str:
@staticmethod
def sha256_hex_digest(value: str | bytes) -> str:
"""
- 校验已生成的 SHA-256 十六进制摘要
+ 校验已生成的 SHA-256 十六进制摘要。
:param value: 摘要文本或 ASCII 字节
:return: 小写十六进制摘要
:raises TypeError: 输入不是 str 或 bytes
:raises ValueError: 摘要长度或字符集不正确
"""
-
if not isinstance(value, (str, bytes)):
raise TypeError('摘要必须为字符串或字节数据')
if isinstance(value, bytes):
@@ -894,12 +914,11 @@ def hmac_sha256(value: str | bytes, key: str | bytes) -> str:
@staticmethod
def access_token_hash(access_token: str) -> str:
"""
- 计算 OIDC at_hash 值
+ 计算 OIDC at_hash 值。
:param access_token: 待计算 OIDC at_hash 的 ASCII JWT Access Token 文本
:return: SHA-256 前 128 bit 摘要的无填充 Base64URL 字符串
"""
-
digest = hashlib.sha256(access_token.encode('ascii')).digest()[:16]
return base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')
@@ -907,13 +926,13 @@ def access_token_hash(access_token: str) -> str:
@staticmethod
def csrf_digest(token: str, pepper: str) -> str:
"""
- 使用独立 Pepper 生成 CSRF HMAC 摘要
+ 使用独立 Pepper 生成 CSRF HMAC 摘要。
:param token: 原始 CSRF Token
:param pepper: Token 摘要 Pepper
:return: CSRF 摘要
+ :raises ValueError: CSRF 摘要密钥至少需要 32 字节
"""
-
if (
not isinstance(token, str)
or not isinstance(pepper, str)
@@ -967,14 +986,13 @@ def logout_rate_scope(cls, address: Any, pepper: str | bytes) -> str:
@classmethod
def redis_key_component(cls, value: str | int, *, name: str = 'Redis Key 组件') -> str:
"""
- 校验可作为 Key 路径组件的标识符
+ 校验可作为 Key 路径组件的标识符。
:param value: 待校验的标识符
:param name: 错误信息中的字段名称
:return: 原样返回的安全组件
:raises ValueError: 组件为空或包含路径/控制字符
"""
-
component = str(value)
if not cls._COMPONENT_PATTERN.fullmatch(component):
raise ValueError(f'{name} 包含不允许的字符')
@@ -983,7 +1001,7 @@ def redis_key_component(cls, value: str | int, *, name: str = 'Redis Key 组件'
@classmethod
def hash_sensitive_identifier(cls, value: str | bytes, pepper: str | bytes) -> str:
"""
- 使用独立 Pepper 对敏感标识生成 HMAC-SHA256 摘要
+ 使用独立 Pepper 对敏感标识生成 HMAC-SHA256 摘要。
:param value: 用户名、IP 等敏感标识
:param pepper: 独立于 JWT/传输加密密钥的 Pepper,至少 32 bytes
@@ -991,7 +1009,6 @@ def hash_sensitive_identifier(cls, value: str | bytes, pepper: str | bytes) -> s
:raises TypeError: 标识或 Pepper 类型错误
:raises ValueError: Pepper 为空或长度不足
"""
-
if not isinstance(value, (str, bytes)) or not isinstance(pepper, (str, bytes)):
raise TypeError('敏感标识和摘要密钥必须为字符串或字节数据')
raw_value = value.encode('utf-8') if isinstance(value, str) else value
@@ -1003,13 +1020,12 @@ def hash_sensitive_identifier(cls, value: str | bytes, pepper: str | bytes) -> s
@staticmethod
def parse_basic_credentials(authorization: str) -> tuple[str, str]:
"""
- 解析 RFC 7617 Basic Header,不接受请求体 Secret 回退
+ 解析 RFC 7617 Basic Header,不接受请求体 Secret 回退。
- :param authorization: Authorization Header
+ :param authorization: 请求中的 Authorization 头
:return: 解码后的 client_id 与 client_secret
:raises ValueError: Header、Base64 或凭据格式不合法
"""
-
if not isinstance(authorization, str) or authorization[:6].lower() != 'basic ':
raise ValueError('客户端认证信息无效')
encoded = authorization[6:].strip()
@@ -1044,23 +1060,21 @@ def generate_client_id() -> str:
@staticmethod
def generate_client_secret() -> str:
"""
- 生成仅应展示一次的高熵 Client Secret
+ 生成仅应展示一次的高熵 Client Secret。
:return: 带 cs1 类型前缀的随机 Secret
"""
-
return f'cs1.{secrets.token_urlsafe(32)}'
@staticmethod
def client_secret_hashes(client: Any, explicit: Iterable[str] | None = None) -> list[str]:
"""
- 收集 Client 当前可用的 Secret 哈希
+ 收集 Client 当前可用的 Secret 哈希。
:param client: Client 映射或对象
:param explicit: 调用方显式提供的 Secret 哈希集合
:return: 规范化后的 Secret 哈希列表
"""
-
values = explicit
if values is None:
values = OidcUtil.read_field(client, 'secret_hashes')
@@ -1084,12 +1098,11 @@ def client_secret_hashes(client: Any, explicit: Iterable[str] | None = None) ->
@staticmethod
def is_rfc4122_uuid(value: str) -> bool:
"""
- 判断字符串是否为规范的 RFC 4122 UUID
+ 判断字符串是否为规范的 RFC 4122 UUID。
:param value: 待检查的 UUID 字符串
:return: 是否为规范的 RFC 4122 UUID 字符串
"""
-
try:
parsed = UUID(value)
except (TypeError, ValueError, AttributeError):
@@ -1099,13 +1112,12 @@ def is_rfc4122_uuid(value: str) -> bool:
@staticmethod
def parse_sso_cookie(cookie: str) -> tuple[str, str]:
"""
- 拆分并验证 SSO Cookie 中的 Session 标识和随机 Secret
+ 拆分并验证 SSO Cookie 中的 Session 标识和随机 Secret。
:param cookie: Cookie 原文
- :return: ``(sid, secret)``
+ :return: 会话标识和密钥组成的二元组
:raises ValueError: Cookie 格式、UUID 或 Secret 长度不合法
"""
-
if not isinstance(cookie, str):
raise ValueError('会话 Cookie 必须为字符串')
parts = cookie.split('.')
@@ -1129,13 +1141,12 @@ def parse_sso_cookie(cookie: str) -> tuple[str, str]:
@staticmethod
def session_pepper_bytes(pepper: str | bytes) -> bytes:
"""
- 验证并转换 Token Pepper 字节串
+ 验证并转换 Token Pepper 字节串。
- :param pepper: OIDC Token Pepper
+ :param pepper: 用于 OIDC 令牌摘要的独立密钥
:return: Pepper 字节
:raises ValueError: Pepper 类型或长度不合法
"""
-
if not isinstance(pepper, (str, bytes)):
raise ValueError('会话摘要密钥必须为字符串或字节数据')
raw = pepper.encode() if isinstance(pepper, str) else pepper
@@ -1146,14 +1157,13 @@ def session_pepper_bytes(pepper: str | bytes) -> bytes:
@classmethod
def session_secret_digest(cls, secret: str | bytes, pepper: str | bytes) -> str:
"""
- 使用 Pepper 计算 Cookie Secret 的 HMAC 摘要
+ 使用 Pepper 计算 Cookie Secret 的 HMAC 摘要。
:param secret: Cookie Secret 原文,仅在请求内存中存在
- :param pepper: OIDC Token Pepper
+ :param pepper: 用于 OIDC 令牌摘要的独立密钥
:return: 十六进制 HMAC 摘要
:raises ValueError: secret 不是 str/bytes,或 pepper 不是 str/bytes、编码后少于 32 字节
"""
-
raw_secret = secret.encode() if isinstance(secret, str) else secret
if not isinstance(raw_secret, bytes):
raise ValueError('会话密钥必须为字节数据或字符串')
@@ -1162,14 +1172,13 @@ def session_secret_digest(cls, secret: str | bytes, pepper: str | bytes) -> str:
@classmethod
def session_user_agent_digest(cls, user_agent: str | None, pepper: str | bytes) -> str | None:
"""
- 使用 Pepper 计算 User-Agent 的 HMAC 摘要
+ 使用 Pepper 计算 User-Agent 的 HMAC 摘要。
:param user_agent: 请求 User-Agent
- :param pepper: OIDC Token Pepper
+ :param pepper: 用于 OIDC 令牌摘要的独立密钥
:return: User-Agent 摘要或 None
:raises ValueError: User-Agent 不是字符串、超过 500 个字符,或 pepper 编码后少于 32 字节
"""
-
if user_agent is None:
return None
if not isinstance(user_agent, str) or len(user_agent) > OidcUtil._MAX_USER_AGENT_LENGTH:
@@ -1179,12 +1188,11 @@ def session_user_agent_digest(cls, user_agent: str | None, pepper: str | bytes)
@staticmethod
def looks_like_jwt(value: str) -> bool:
"""
- 判断字符串是否具有 JWT 三段式秘密外观
+ 判断字符串是否具有 JWT 三段式秘密外观。
:param value: 待检测的字符串
:return: 是否符合 JWT 外形
"""
-
parts = value.split('.')
return len(parts) == OidcUtil._JWT_PART_COUNT and all(
@@ -1194,12 +1202,11 @@ def looks_like_jwt(value: str) -> bool:
@classmethod
def sanitize_audit_detail(cls, detail: Any) -> Any:
"""
- 递归删除审计详情中的敏感字段
+ 递归删除审计详情中的敏感字段。
:param detail: 待记录的任意可序列化值
:return: 只包含安全字段的可序列化值
"""
-
if isinstance(detail, Mapping):
return {
str(key): cls.sanitize_audit_detail(value)
@@ -1248,7 +1255,7 @@ def normalize_public_jwk(
cls, record: Any, *, min_rsa_bits: int = 2048, min_exponent: int = 3, max_exponent: int = 2**32
) -> dict[str, str]:
"""
- 提取并校验公开 RSA JWK
+ 提取并校验公开 RSA JWK。
:param record: 数据库签名密钥记录或包含 public_jwk 字段的映射
:param min_rsa_bits: 最小 RSA 模数位数
@@ -1257,7 +1264,6 @@ def normalize_public_jwk(
:return: 只包含公开字段的 JWK
:raises ValueError: JWK 结构或算法不合法
"""
-
value = getattr(record, 'public_jwk', record)
if not isinstance(value, Mapping):
raise ValueError('公开 JWK 必须为对象')
@@ -1315,13 +1321,12 @@ def normalize_public_jwk(
@staticmethod
def derive_signing_encryption_key(material: bytes, salt: bytes) -> bytes:
"""
- 使用随机盐派生私钥加密密钥
+ 使用随机盐派生私钥加密密钥。
:param material: 部署配置中的加密主密钥
:param salt: 单条密钥记录的随机盐
:return: AES-GCM 使用的 256 位密钥
"""
-
return PBKDF2HMAC(
algorithm=SHA256(),
length=32,
@@ -1351,6 +1356,7 @@ def decrypt_signing_private_key(cls, ciphertext: str, material: bytes) -> bytes:
:param ciphertext: 带版本前缀的私钥密文
:param material: 部署加密主密钥
:return: 已解密的私钥 PEM 字节
+ :raises ValueError: 不支持当前签名私钥密文格式
"""
if ciphertext.startswith('v2.'):
envelope = base64.urlsafe_b64decode(ciphertext.removeprefix('v2.'))
diff --git a/ruoyi-fastapi-backend/utils/openapi_util.py b/ruoyi-fastapi-backend/utils/openapi_util.py
index 56e52dba4..4f93e8e49 100644
--- a/ruoyi-fastapi-backend/utils/openapi_util.py
+++ b/ruoyi-fastapi-backend/utils/openapi_util.py
@@ -14,7 +14,11 @@
class OpenAPIUtil:
"""
- OpenAPI认证声明工具类
+ OpenAPI认证声明工具类。
+
+ :cvar _MAX_PATH_STATES: 展开路由认证条件时允许探索的最大状态数
+ :cvar _CONDITIONAL_DESCRIPTION: 路由认证取决于路径条件时显示的说明
+ :cvar _UNRESOLVED_DESCRIPTION: 无法完全展开认证条件时使用的文档说明
"""
_MAX_PATH_STATES = 4096
@@ -27,7 +31,7 @@ class OpenAPIUtil:
@classmethod
def adjust_security(cls, schema: dict[str, Any], routes: Sequence[BaseRoute]) -> dict[str, Any]:
"""
- 根据前置认证规则调整各接口的登录安全声明
+ 根据前置认证规则调整各接口的登录安全声明。
:param schema: 可修改的OpenAPI文档副本
:param routes: 应用路由列表
@@ -79,10 +83,10 @@ def adjust_security(cls, schema: dict[str, Any], routes: Sequence[BaseRoute]) ->
@staticmethod
def _iter_auth_routes(routes: Sequence[BaseRoute]) -> Iterator[tuple[Any, str]]:
"""
- 获取不存在重复声明的路由
+ 获取不存在重复声明的路由。
:param routes: 应用路由列表
- :return: 唯一路由及HTTP方法
+ :yield: 唯一路由及HTTP方法
"""
first_routes = {}
conflicting_operations = set()
@@ -104,7 +108,7 @@ def _iter_auth_routes(routes: Sequence[BaseRoute]) -> Iterator[tuple[Any, str]]:
@classmethod
def _has_external_login_scheme(cls, dependency: Any) -> bool:
"""
- 判断是否存在与宿主登录同名的其他安全依赖
+ 判断是否存在与宿主登录同名的其他安全依赖。
:param dependency: 路由依赖声明
:return: 是否需要保留同名安全声明
@@ -121,11 +125,10 @@ def _has_external_login_scheme(cls, dependency: Any) -> bool:
@classmethod
def _adjust_operation_security(cls, operation: dict[str, Any], *, conditional: bool) -> None:
"""
- 调整宿主登录要求并保留其他安全方案
+ 调整宿主登录要求并保留其他安全方案。
:param operation: 接口文档
:param conditional: 是否仅部分路径需要登录
- :return: None
"""
security = operation.get('security', [])
scheme = oauth2_scheme.scheme_name
@@ -153,7 +156,7 @@ def _adjust_operation_security(cls, operation: dict[str, Any], *, conditional: b
@classmethod
def _get_auth_mode(cls, route: Any, method: str, requirements: list[AuthRule]) -> str:
"""
- 判断接口是否始终、从不或按路径参数要求登录
+ 判断接口是否始终、从不或按路径参数要求登录。
:param route: 包含最终路径和依赖的路由
:param method: HTTP方法
@@ -202,7 +205,7 @@ def _get_auth_mode(cls, route: Any, method: str, requirements: list[AuthRule]) -
@classmethod
def _has_template_coverage(cls, route: Any, method: str, pre_auth: AuthRule) -> bool:
"""
- 判断同一模板的排除规则是否覆盖全部参数值
+ 判断同一模板的排除规则是否覆盖全部参数值。
:param route: 接口路由
:param method: HTTP方法
@@ -225,7 +228,7 @@ def _has_template_coverage(cls, route: Any, method: str, pre_auth: AuthRule) ->
@staticmethod
def _method_rules(pre_auth: AuthRule, method: str) -> list[dict[str, Any]]:
"""
- 获取适用于当前HTTP方法的排除规则
+ 获取适用于当前HTTP方法的排除规则。
:param pre_auth: 前置认证依赖
:param method: HTTP方法
@@ -236,7 +239,7 @@ def _method_rules(pre_auth: AuthRule, method: str) -> list[dict[str, Any]]:
@staticmethod
def _get_path_shape(route: Any) -> tuple[tuple[str | None, ...], dict[int, Convertor]] | None:
"""
- 将普通路径模板拆分为固定段和单段参数
+ 将普通路径模板拆分为固定段和单段参数。
:param route: 接口路由
:return: 路径段及参数转换器,复杂模板返回None
@@ -267,7 +270,7 @@ def _get_rule_constraints(
convertors: dict[int, Convertor],
) -> tuple[list[tuple[str | None, ...]], bool]:
"""
- 将排除规则转换为路径参数的取值约束
+ 将排除规则转换为路径参数的取值约束。
:param pre_auth: 前置认证依赖
:param method: HTTP方法
@@ -312,7 +315,7 @@ def _has_public_path(
method: str,
) -> bool | None:
"""
- 判断各前置认证分支的公开路径是否存在交集
+ 判断各前置认证分支的公开路径是否存在交集。
:param segments: 路径模板
:param convertors: 参数转换器
@@ -329,6 +332,13 @@ def _has_public_path(
has_unknown_rules = any(unknown for _, unknown in groups)
def visit(index: int, values: tuple[str | None, ...]) -> bool:
+ """
+ 在路由约束中搜索无需认证的路径组合。
+
+ :param index: 当前条目在序列中的位置
+ :param values: 当前处理的值集合
+ :return: 是否在路由约束中搜索无需认证的路径组合
+ """
nonlocal limited, unresolved
state = (index, values)
if state in visited:
@@ -365,7 +375,7 @@ def _get_candidate_path(
segments: tuple[str | None, ...], convertors: dict[int, Convertor], ignored_paths: set[str]
) -> str:
"""
- 为未固定的参数选择不落入有限例外列表的值
+ 为未固定的参数选择不落入有限例外列表的值。
:param segments: 已合并的路径参数约束
:param convertors: 参数转换器
diff --git a/ruoyi-fastapi-backend/utils/page_util.py b/ruoyi-fastapi-backend/utils/page_util.py
index 3c5059033..a4c2ded14 100644
--- a/ruoyi-fastapi-backend/utils/page_util.py
+++ b/ruoyi-fastapi-backend/utils/page_util.py
@@ -9,14 +9,12 @@
class PageUtil:
- """
- 分页工具类
- """
+ """分页工具类。"""
@classmethod
def get_page_obj(cls, data_list: list, page_num: int, page_size: int) -> PageModel:
"""
- 输入数据列表data_list和分页信息,返回分页数据列表结果
+ 输入数据列表data_list和分页信息,返回分页数据列表结果。
:param data_list: 原始数据列表
:param page_num: 当前页码
@@ -42,7 +40,7 @@ async def paginate(
cls, db: AsyncSession, query: Select, page_num: int, page_size: int, is_page: bool = False
) -> PageModel | list[dict[str, Any] | list[dict[Any, Any]]]:
"""
- 输入查询语句和分页信息,返回分页数据列表结果
+ 输入查询语句和分页信息,返回分页数据列表结果。
:param db: orm对象
:param query: sqlalchemy查询语句
@@ -83,7 +81,7 @@ async def paginate(
def get_page_obj(data_list: list, page_num: int, page_size: int) -> PageModel:
"""
- 输入数据列表data_list和分页信息,返回分页数据列表结果
+ 输入数据列表data_list和分页信息,返回分页数据列表结果。
:param data_list: 原始数据列表
:param page_num: 当前页码
diff --git a/ruoyi-fastapi-backend/utils/pwd_util.py b/ruoyi-fastapi-backend/utils/pwd_util.py
index 9fa592f44..00c0e8405 100644
--- a/ruoyi-fastapi-backend/utils/pwd_util.py
+++ b/ruoyi-fastapi-backend/utils/pwd_util.py
@@ -2,14 +2,12 @@
class PwdUtil:
- """
- 密码工具类
- """
+ """密码工具类。"""
@classmethod
def verify_password(cls, plain_password: str, hashed_password: str) -> bool:
"""
- 工具方法:校验当前输入的密码与数据库存储的密码是否一致
+ 工具方法:校验当前输入的密码与数据库存储的密码是否一致。
:param plain_password: 当前输入的密码
:param hashed_password: 数据库存储的密码
@@ -22,7 +20,7 @@ def verify_password(cls, plain_password: str, hashed_password: str) -> bool:
@classmethod
def get_password_hash(cls, input_password: str) -> str:
"""
- 工具方法:对当前输入的密码进行加密
+ 工具方法:对当前输入的密码进行加密。
:param input_password: 输入的密码
:return: 加密成功的密码
diff --git a/ruoyi-fastapi-backend/utils/response_util.py b/ruoyi-fastapi-backend/utils/response_util.py
index c4757bee2..127866616 100644
--- a/ruoyi-fastapi-backend/utils/response_util.py
+++ b/ruoyi-fastapi-backend/utils/response_util.py
@@ -16,14 +16,12 @@
class ResponseUtil:
- """
- 响应工具类
- """
+ """响应工具类。"""
@staticmethod
def _json_content(result: dict[str, Any]) -> Any:
"""
- 序列化响应时刻及显式标记的国际化消息
+ 序列化响应时刻及显式标记的国际化消息。
:param result: 待返回的响应内容
:return: 可供JSON响应使用的数据
@@ -56,7 +54,7 @@ def success( # noqa: PLR0913 - 保留已有位置参数,扩展语义仅允许
plural_key: str | None = None,
) -> Response:
"""
- 成功响应方法
+ 成功响应方法。
:param msg: 可选,自定义成功响应信息
:param data: 可选,成功响应结果中属性为data的值
@@ -125,7 +123,7 @@ def failure( # noqa: PLR0913 - 保留已有位置参数,扩展语义仅允许
plural_key: str | None = None,
) -> Response:
"""
- 失败响应方法
+ 失败响应方法。
:param msg: 可选,自定义失败响应信息
:param data: 可选,失败响应结果中属性为data的值
@@ -194,7 +192,7 @@ def unauthorized( # noqa: PLR0913 - 保留已有位置参数,扩展语义仅
plural_key: str | None = None,
) -> Response:
"""
- 未认证响应方法
+ 未认证响应方法。
:param msg: 可选,自定义未认证响应信息
:param data: 可选,未认证响应结果中属性为data的值
@@ -263,7 +261,7 @@ def forbidden( # noqa: PLR0913 - 保留已有位置参数,扩展语义仅允
plural_key: str | None = None,
) -> Response:
"""
- 未授权响应方法
+ 未授权响应方法。
:param msg: 可选,自定义未授权响应信息
:param data: 可选,未授权响应结果中属性为data的值
@@ -332,7 +330,7 @@ def error( # noqa: PLR0913 - 保留已有位置参数,扩展语义仅允许
plural_key: str | None = None,
) -> Response:
"""
- 错误响应方法
+ 错误响应方法。
:param msg: 可选,自定义错误响应信息
:param data: 可选,错误响应结果中属性为data的值
@@ -401,7 +399,7 @@ def too_many_requests( # noqa: PLR0913 - 保留已有位置参数,扩展语
plural_key: str | None = None,
) -> Response:
"""
- 接口限流响应方法
+ 接口限流响应方法。
:param msg: 可选,自定义限流响应信息
:param data: 可选,限流响应结果中属性为data的值
@@ -462,7 +460,7 @@ def streaming(
status_code: int = status.HTTP_200_OK,
) -> Response:
"""
- 流式响应方法
+ 流式响应方法。
:param data: 流式传输的内容
:param headers: 可选,响应头信息
diff --git a/ruoyi-fastapi-backend/utils/security_util.py b/ruoyi-fastapi-backend/utils/security_util.py
index d2b9e670e..c9db67b94 100644
--- a/ruoyi-fastapi-backend/utils/security_util.py
+++ b/ruoyi-fastapi-backend/utils/security_util.py
@@ -6,7 +6,10 @@
class SecurityUtil:
"""
- 安全工具类
+ 安全工具类。
+
+ :cvar HTML_TAGS: 清理 HTML 时允许的标签
+ :cvar HTML_ATTRIBUTES: 清理 HTML 时允许保留的属性
"""
# 仅允许文档型富文本;仅保留文本样式,不接受表单或可执行内容,视频嵌入强制使用沙箱。
diff --git a/ruoyi-fastapi-backend/utils/server_util.py b/ruoyi-fastapi-backend/utils/server_util.py
index a3455a217..94a2e8ef5 100644
--- a/ruoyi-fastapi-backend/utils/server_util.py
+++ b/ruoyi-fastapi-backend/utils/server_util.py
@@ -18,7 +18,21 @@
class APIDocsUtil:
"""
- API文档工具类
+ API文档工具类。
+
+ :cvar _OPENAPI_URL: 提供 OpenAPI 描述的路由路径
+ :cvar _PROXY_OPENAPI_URL: 经过反向代理时使用的 OpenAPI 路径
+ :cvar _DOCS_URL: Swagger UI 的路由路径
+ :cvar _PROXY_DOCS_URL: 经过反向代理时使用的 Swagger UI 路径
+ :cvar _REDOC_URL: ReDoc 的路由路径
+ :cvar _PROXY_REDOC_URL: 经过反向代理时使用的 ReDoc 路径
+ :cvar _OAUTH2_REDIRECT_URL: Swagger UI 完成 OAuth 认证的回调路径
+ :cvar _PROXY_OAUTH2_REDIRECT_URL: 经过反向代理时的 OAuth 回调路径
+ :cvar DEFAULT_REDOC_JS_URL: ReDoc 默认加载的 JavaScript 资源地址
+ :cvar DEFAULT_REDOC_FAVICON_URL: ReDoc 默认加载的站点图标地址
+ :cvar DEFAULT_SWAGGER_JS_URL: Swagger UI 默认加载的 JavaScript 资源地址
+ :cvar DEFAULT_SWAGGER_CSS_URL: Swagger UI 默认加载的样式表地址
+ :cvar DEFAULT_SWAGGER_FAVICON_URL: Swagger UI 默认使用的站点图标地址
"""
# API文档URLs
@@ -41,42 +55,54 @@ class APIDocsUtil:
@classmethod
def proxy_openapi_url(cls) -> str | None:
"""
- 代理OpenAPI文档URL
+ 代理OpenAPI文档URL。
+
+ :return: 代理环境下 OpenAPI 描述的访问地址
"""
return cls._PROXY_OPENAPI_URL if not (AppConfig.app_disable_swagger and AppConfig.app_disable_redoc) else None
@classmethod
def docs_url(cls) -> str:
"""
- 文档URL
+ 文档URL。
+
+ :return: 供调用方使用的 ``cls._DOCS_URL``
"""
return cls._DOCS_URL
@classmethod
def proxy_docs_url(cls) -> str:
"""
- 代理文档URL
+ 代理文档URL。
+
+ :return: 代理环境下交互文档的访问地址
"""
return cls._PROXY_DOCS_URL if not AppConfig.app_disable_swagger else None
@classmethod
def redoc_url(cls) -> str:
"""
- ReDoc文档URL
+ ReDoc文档URL。
+
+ :return: 供调用方使用的 ``cls._REDOC_URL``
"""
return cls._REDOC_URL
@classmethod
def proxy_redoc_url(cls) -> str:
"""
- 代理ReDoc文档URL
+ 代理ReDoc文档URL。
+
+ :return: 代理环境下 ReDoc 的访问地址
"""
return cls._PROXY_REDOC_URL if not AppConfig.app_disable_redoc else None
@classmethod
def proxy_oauth2_redirect_url(cls) -> str:
"""
- 代理OAuth2重定向URL
+ 代理OAuth2重定向URL。
+
+ :return: 代理环境下 OAuth2 回调地址
"""
return cls._PROXY_OAUTH2_REDIRECT_URL if not AppConfig.app_disable_swagger else None
@@ -90,17 +116,23 @@ def setup_docs_static_resources(
swagger_favicon_url: str = DEFAULT_SWAGGER_FAVICON_URL,
) -> None:
"""
- 配置文档静态资源
+ 配置文档静态资源。
:param redoc_js_url: 用于加载ReDoc JavaScript的URL
:param redoc_favicon_url: ReDoc要使用的favicon的URL
:param swagger_js_url: 用于加载Swagger UI JavaScript的URL
:param swagger_css_url: 用于加载Swagger UI CSS的URL
:param swagger_favicon_url: Swagger UI要使用的favicon的URL
- :return:
"""
def redoc_monkey_patch(*args, **kwargs) -> HTMLResponse:
+ """
+ 使用本地静态资源生成 ReDoc 页面。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 引用本地静态资源的 ReDoc 响应
+ """
return get_redoc_html(
*args,
**kwargs,
@@ -109,6 +141,13 @@ def redoc_monkey_patch(*args, **kwargs) -> HTMLResponse:
)
def swagger_ui_monkey_patch(*args, **kwargs) -> HTMLResponse:
+ """
+ 使用本地静态资源生成 Swagger UI 页面。
+
+ :param args: 传给被调用对象的位置参数
+ :param kwargs: 传给被调用对象的关键字参数
+ :return: 引用本地静态资源的 Swagger UI 响应
+ """
return get_swagger_ui_html(
*args,
**kwargs,
@@ -131,7 +170,7 @@ def custom_api_docs_router(
swagger_favicon_url: str = DEFAULT_SWAGGER_FAVICON_URL,
) -> None:
"""
- 自定义API文档路由
+ 自定义API文档路由。
:param app: FastAPI对象
:param redoc_js_url: 用于加载ReDoc JavaScript的URL
@@ -139,11 +178,15 @@ def custom_api_docs_router(
:param swagger_js_url: 用于加载Swagger UI JavaScript的URL
:param swagger_css_url: 用于加载Swagger UI CSS的URL
:param swagger_favicon_url: Swagger UI要使用的favicon的URL
- :return:
"""
original_openapi = app.openapi
def openapi() -> dict[str, Any]:
+ """
+ 提供应用的 OpenAPI 描述。
+
+ :return: 应用的 OpenAPI 描述
+ """
# 生成文档时再加载认证规则,避免服务器工具与登录服务循环引用。
from utils.openapi_util import OpenAPIUtil # noqa: PLC0415
@@ -158,12 +201,30 @@ async def custom_openapi(request: Request) -> JSONResponse:
return await cls._custom_openapi(app)
async def custom_redoc(request: Request) -> HTMLResponse:
+ """
+ 返回自定义 ReDoc 文档页面。
+
+ :param request: 当前 HTTP 请求
+ :return: 自定义 ReDoc 文档页面
+ """
return await cls._custom_redoc(app, redoc_js_url, redoc_favicon_url)
async def custom_swagger(request: Request) -> HTMLResponse:
+ """
+ 返回自定义 Swagger UI 文档页面。
+
+ :param request: 当前 HTTP 请求
+ :return: 自定义 Swagger UI 文档页面
+ """
return await cls._custom_swagger(app, swagger_js_url, swagger_css_url, swagger_favicon_url)
async def custom_swagger_ui_redirect(request: Request) -> HTMLResponse:
+ """
+ 返回 Swagger UI 的 OAuth 重定向页面。
+
+ :param request: 当前 HTTP 请求
+ :return: Swagger UI 的 OAuth 重定向页面
+ """
return await cls._custom_swagger_ui_redirect(app, swagger_favicon_url)
# 注册路由
@@ -174,7 +235,7 @@ async def custom_swagger_ui_redirect(request: Request) -> HTMLResponse:
@classmethod
async def _custom_openapi(cls, app: FastAPI) -> JSONResponse:
"""
- 自定义 OpenAPI 路由处理函数
+ 自定义 OpenAPI 路由处理函数。
:param app: FastAPI对象
:return: openapi的json响应
@@ -189,7 +250,7 @@ async def _custom_redoc(
redoc_favicon_url: str,
) -> HTMLResponse:
"""
- 自定义 ReDoc 路由处理函数
+ 自定义 ReDoc 路由处理函数。
:param app: FastAPI对象
:param redoc_js_url: 用于加载ReDoc JavaScript的URL
@@ -218,7 +279,7 @@ async def _custom_swagger(
swagger_favicon_url: str,
) -> HTMLResponse:
"""
- 自定义 Swagger UI 路由处理函数
+ 自定义 Swagger UI 路由处理函数。
:param app: FastAPI对象
:param swagger_js_url: 用于加载Swagger UI JavaScript的URL
@@ -250,7 +311,7 @@ async def _custom_swagger_ui_redirect(
swagger_favicon_url: str,
) -> HTMLResponse:
"""
- 自定义 Swagger UI OAuth2 重定向路由处理函数
+ 自定义 Swagger UI OAuth2 重定向路由处理函数。
:param app: FastAPI对象
:param swagger_favicon_url: Swagger UI要使用的favicon的URL
@@ -267,7 +328,7 @@ async def _custom_swagger_ui_redirect(
@staticmethod
def _get_disabled_html_content(title: str, name: str, favicon_url: str) -> HTMLResponse:
"""
- 生成禁用文档的HTML内容
+ 生成禁用文档的HTML内容。
:param title: 页面标题
:param name: 文档名称
@@ -308,13 +369,12 @@ def _register_docs_routes(
cls, app: FastAPI, swagger_handler: Callable, redirect_handler: Callable, redoc_handler: Callable
) -> None:
"""
- 注册文档路由
+ 注册文档路由。
:param app: FastAPI对象
:param swagger_handler: Swagger UI 路由处理函数
:param redirect_handler: Swagger UI OAuth2 重定向路由处理函数
:param redoc_handler: ReDoc 路由处理函数
- :return:
"""
swagger_urls: list[str] = (
[cls._DOCS_URL] if not AppConfig.app_disable_swagger else [cls._DOCS_URL, cls._PROXY_DOCS_URL]
@@ -342,6 +402,11 @@ class StartupUtil:
worker_id 仅用于日志展示,租约所有权使用进程唯一 owner token,避免多个
worker 配置相同展示 ID 时同时误判为 leader。
+
+ :cvar _RENEW_SCRIPT: 验证锁所有权并延长有效期的 Redis 脚本
+ :cvar _RELEASE_SCRIPT: 仅在令牌匹配时释放 Redis 锁的脚本
+ :cvar _application_lock_owner_token: 用于验证应用锁所有权的令牌
+ :cvar _application_lock_owner_pid: 持有应用启动锁的进程编号
"""
_RENEW_SCRIPT = """
@@ -467,6 +532,11 @@ def start_application_leader_renewal(
"""
async def _loop() -> None:
+ """
+ 定期续约应用启动时取得的主节点租约。
+
+ :raises asyncio.CancelledError: 异步操作被取消时
+ """
while True:
try:
renewed = await cls.renew_application_leader(
@@ -494,7 +564,9 @@ async def _loop() -> None:
class WorkerIdUtil:
"""
- Worker标识生成工具类
+ Worker标识生成工具类。
+
+ :cvar _worker_id: 当前工作进程的标识
"""
_worker_id: str | None = None
@@ -502,7 +574,7 @@ class WorkerIdUtil:
@classmethod
def get_worker_id(cls, configured_worker_id: str | None) -> str:
"""
- 获取当前worker标识
+ 获取当前worker标识。
:param configured_worker_id: 配置的worker标识
:return: 当前worker标识
@@ -518,7 +590,10 @@ def get_worker_id(cls, configured_worker_id: str | None) -> str:
class IPUtil:
"""
- IP工具类
+ IP工具类。
+
+ :cvar _PREFERRED_DNS_HOSTS: 探测出站网络地址时优先尝试的 DNS 主机
+ :cvar _DNS_CONNECT_TIMEOUT: 探测 DNS 主机时允许的连接等待时间
"""
_PREFERRED_DNS_HOSTS: tuple[str, str] = ('223.5.5.5', '8.8.8.8')
@@ -527,7 +602,9 @@ class IPUtil:
@classmethod
def get_local_ip(cls) -> str:
"""
- 获取本机Local IP
+ 获取本机Local IP。
+
+ :return: 本机Local IP
"""
try:
for snics in psutil.net_if_addrs().values():
@@ -542,7 +619,9 @@ def get_local_ip(cls) -> str:
@classmethod
def get_network_ips(cls) -> list[str]:
"""
- 获取本机Network IP列表
+ 获取本机Network IP列表。
+
+ :return: 本机Network IP列表
"""
network_ips = []
try:
diff --git a/ruoyi-fastapi-backend/utils/string_util.py b/ruoyi-fastapi-backend/utils/string_util.py
index 55f3d8f76..ac18f3d73 100644
--- a/ruoyi-fastapi-backend/utils/string_util.py
+++ b/ruoyi-fastapi-backend/utils/string_util.py
@@ -2,14 +2,12 @@
class StringUtil:
- """
- 字符串工具类
- """
+ """字符串工具类。"""
@classmethod
def is_blank(cls, string: str | None) -> bool:
"""
- 校验字符串是否为''或全空格
+ 校验字符串是否为''或全空格。
:param string: 需要校验的字符串
:return: 校验结果
@@ -24,7 +22,7 @@ def is_blank(cls, string: str | None) -> bool:
@classmethod
def is_empty(cls, string: str) -> bool:
"""
- 校验字符串是否为''或None
+ 校验字符串是否为''或None。
:param string: 需要校验的字符串
:return: 校验结果
@@ -34,7 +32,7 @@ def is_empty(cls, string: str) -> bool:
@classmethod
def is_not_empty(cls, string: str) -> bool:
"""
- 校验字符串是否不是''和None
+ 校验字符串是否不是''和None。
:param string: 需要校验的字符串
:return: 校验结果
@@ -44,7 +42,7 @@ def is_not_empty(cls, string: str) -> bool:
@classmethod
def is_http(cls, link: str) -> bool:
"""
- 判断是否为http(s)://开头
+ 判断是否为http(s)://开头。
:param link: 链接
:return: 是否为http(s)://开头
@@ -54,7 +52,7 @@ def is_http(cls, link: str) -> bool:
@classmethod
def contains_ignore_case(cls, search_str: str, compare_str: str) -> bool:
"""
- 查找指定字符串是否包含指定字符串同时忽略大小写
+ 查找指定字符串是否包含指定字符串同时忽略大小写。
:param search_str: 查找的字符串
:param compare_str: 比对的字符串
@@ -67,7 +65,7 @@ def contains_ignore_case(cls, search_str: str, compare_str: str) -> bool:
@classmethod
def contains_any_ignore_case(cls, search_str: str, compare_str_list: list[str]) -> bool:
"""
- 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时忽略大小写
+ 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时忽略大小写。
:param search_str: 查找的字符串
:param compare_str_list: 比对的字符串列表
@@ -80,7 +78,7 @@ def contains_any_ignore_case(cls, search_str: str, compare_str_list: list[str])
@classmethod
def equals_ignore_case(cls, search_str: str, compare_str: str) -> bool:
"""
- 比较两个字符串是否相等同时忽略大小写
+ 比较两个字符串是否相等同时忽略大小写。
:param search_str: 查找的字符串
:param compare_str: 比对的字符串
@@ -93,7 +91,7 @@ def equals_ignore_case(cls, search_str: str, compare_str: str) -> bool:
@classmethod
def equals_any_ignore_case(cls, search_str: str, compare_str_list: list[str]) -> bool:
"""
- 比较指定字符串是否与指定字符串列表中的任意一个字符串相等同时忽略大小写
+ 比较指定字符串是否与指定字符串列表中的任意一个字符串相等同时忽略大小写。
:param search_str: 查找的字符串
:param compare_str_list: 比对的字符串列表
@@ -106,7 +104,7 @@ def equals_any_ignore_case(cls, search_str: str, compare_str_list: list[str]) ->
@classmethod
def startswith_case(cls, search_str: str, compare_str: str) -> bool:
"""
- 查找指定字符串是否以指定字符串开头
+ 查找指定字符串是否以指定字符串开头。
:param search_str: 查找的字符串
:param compare_str: 比对的字符串
@@ -119,7 +117,7 @@ def startswith_case(cls, search_str: str, compare_str: str) -> bool:
@classmethod
def startswith_any_case(cls, search_str: str, compare_str_list: list[str]) -> bool:
"""
- 查找指定字符串是否以指定字符串列表中的任意一个字符串开头
+ 查找指定字符串是否以指定字符串列表中的任意一个字符串开头。
:param search_str: 查找的字符串
:param compare_str_list: 比对的字符串列表
@@ -132,7 +130,7 @@ def startswith_any_case(cls, search_str: str, compare_str_list: list[str]) -> bo
@classmethod
def convert_to_camel_case(cls, name: str) -> str:
"""
- 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串
+ 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。
:param name: 转换前的下划线大写方式命名的字符串
:return: 转换后的驼峰式命名的字符串
@@ -152,10 +150,10 @@ def convert_to_camel_case(cls, name: str) -> str:
@classmethod
def get_mapping_value_by_key_ignore_case(cls, mapping: dict[str, str], key: str) -> str:
"""
- 根据忽略大小写的键获取字典中的对应的值
+ 根据忽略大小写的键获取字典中的对应的值。
- param mapping: 字典
- param key: 字典的键
+ :param mapping: 字典
+ :param key: 字典的键
:return: 字典键对应的值
"""
for k, v in mapping.items():
diff --git a/ruoyi-fastapi-backend/utils/template_util.py b/ruoyi-fastapi-backend/utils/template_util.py
index 6780f363e..943462694 100644
--- a/ruoyi-fastapi-backend/utils/template_util.py
+++ b/ruoyi-fastapi-backend/utils/template_util.py
@@ -16,16 +16,15 @@
class TemplateInitializer:
- """
- 模板引擎初始化类
- """
+ """模板引擎初始化类。"""
@classmethod
def init_jinja2(cls) -> Environment:
"""
- 初始化 Jinja2 模板引擎
+ 初始化 Jinja2 模板引擎。
:return: Jinja2 环境对象
+ :raises RuntimeError: Jinja2 环境初始化失败
"""
try:
template_dir = os.path.join(os.getcwd(), 'module_generator', 'templates')
@@ -35,14 +34,16 @@ def init_jinja2(cls) -> Environment:
trim_blocks=True,
lstrip_blocks=True,
)
- # Generated source and previews should keep readable Unicode labels.
- # tojson still escapes quotes, backslashes and HTML-sensitive characters.
+ # 生成源码和预览时保留可读的 Unicode 标签。
+ # tojson 仍会转义引号、反斜杠及 HTML 敏感字符。
env.policies['json.dumps_kwargs'] = {**env.policies['json.dumps_kwargs'], 'ensure_ascii': False}
env.filters.update(
{
'camel_to_snake': SnakeCaseUtil.camel_to_snake,
'snake_to_camel': CamelCaseUtil.snake_to_camel,
'get_sqlalchemy_type': TemplateUtils.get_sqlalchemy_type,
+ 'model_field_label': TemplateUtils.model_field_label,
+ 'python_literal': repr,
}
)
return env
@@ -52,7 +53,12 @@ def init_jinja2(cls) -> Environment:
class TemplateUtils:
"""
- 模板工具类
+ 模板工具类。
+
+ :cvar FRONTEND_PROJECT_PATH: 生成器定位前端资源使用的项目路径
+ :cvar BACKEND_PROJECT_PATH: 生成器定位后端资源使用的项目路径
+ :cvar DEFAULT_PARENT_MENU_ID: 生成菜单时使用的默认上级菜单标识
+ :cvar FORM_COL_SPAN_MAP: 表单列数到栅格宽度的映射
"""
# 项目路径
@@ -64,14 +70,23 @@ class TemplateUtils:
@classmethod
def prepare_context(cls, gen_table: GenTableModel) -> dict[str, Any]:
"""
- 准备模板变量
+ 准备模板变量。
:param gen_table: 生成表的配置信息
:return: 模板上下文字典
+ :raises ServiceWarning: 请先完善生成配置信息
"""
if not gen_table.options:
raise ServiceWarning(message='请先完善生成配置信息', msg_key='generator.configurationRequired')
gen_table = gen_table.model_copy(deep=True)
+ for table in (gen_table, gen_table.sub_table):
+ if table is None:
+ continue
+ for column in [*(table.columns or []), table.pk_column]:
+ if column and not (column.column_comment or '').strip():
+ column.column_comment = {'create_time': '创建时间', 'update_time': '更新时间'}.get(
+ column.column_name, f'字段 {column.column_name}'
+ )
cls.prepare_time_columns(gen_table)
class_name = gen_table.class_name
module_name = gen_table.module_name
@@ -155,14 +170,25 @@ def prepare_context(cls, gen_table: GenTableModel) -> dict[str, Any]:
return context
+ @staticmethod
+ def model_field_label(comment: str) -> str:
+ """
+ 保留列的原始说明,并为外语标签补充中文字段标识。
+
+ :param comment: 生成配置中的列说明
+ :return: 写入数据库模型和接口模型的字段说明
+ """
+ return comment if re.search(r'[\u3400-\u9fff\U00020000-\U0002fa1f]', comment) else f'字段 {comment}'
+
@classmethod
def prepare_time_columns(cls, gen_table: GenTableModel) -> None:
"""
- 规范化模板副本中的主表和子表时间字段
+ 规范化模板副本中的主表和子表时间字段。
只处理模板副本,不改写数据库中保存的生成配置。
:param gen_table: 用于渲染的生成表配置副本
+ :raises ServiceWarning: 生成表的时间列不能映射为明确的时间语义
"""
db_type = DataBaseConfig.get_source(gen_table.data_source_name).db_type
for table in [gen_table, gen_table.sub_table]:
@@ -184,7 +210,7 @@ def prepare_time_columns(cls, gen_table: GenTableModel) -> None:
@classmethod
def set_extensions_context(cls, context: dict, gen_table: GenTableModel) -> None:
"""
- 设置扩展功能上下文
+ 设置扩展功能上下文。
:param context: 模板上下文字典
:param gen_table: 生成表的配置信息
@@ -195,11 +221,10 @@ def set_extensions_context(cls, context: dict, gen_table: GenTableModel) -> None
@classmethod
def set_menu_context(cls, context: dict, gen_table: GenTableModel) -> None:
"""
- 设置菜单上下文
+ 设置菜单上下文。
:param context: 模板上下文字典
:param gen_table: 生成表的配置信息
- :return: 新的模板上下文字典
"""
options = gen_table.options
params_obj = json.loads(options)
@@ -208,11 +233,10 @@ def set_menu_context(cls, context: dict, gen_table: GenTableModel) -> None:
@classmethod
def set_tree_context(cls, context: dict, gen_table: GenTableModel) -> None:
"""
- 设置树形结构上下文
+ 设置树形结构上下文。
:param context: 模板上下文字典
:param gen_table: 生成表的配置信息
- :return: 新的模板上下文字典
"""
options = gen_table.options
params_obj = json.loads(options)
@@ -224,11 +248,10 @@ def set_tree_context(cls, context: dict, gen_table: GenTableModel) -> None:
@classmethod
def set_sub_context(cls, context: dict, gen_table: GenTableModel) -> None:
"""
- 设置子表上下文
+ 设置子表上下文。
:param context: 模板上下文字典
:param gen_table: 生成表的配置信息
- :return: 新的模板上下文字典
"""
sub_table = gen_table.sub_table
sub_table_name = gen_table.sub_table_name
@@ -246,7 +269,7 @@ def set_sub_context(cls, context: dict, gen_table: GenTableModel) -> None:
@classmethod
def get_template_list(cls, gen_table: GenTableModel) -> list[str]:
"""
- 获取模板列表
+ 获取模板列表。
:param gen_table: 生成表的配置信息
:return: 模板列表
@@ -275,7 +298,7 @@ def get_template_list(cls, gen_table: GenTableModel) -> list[str]:
templates.append(f'{use_web_type}/index-tree.{extension}.jinja2')
elif tpl_category == GenConstant.TPL_SUB:
templates.append(f'{use_web_type}/index.{extension}.jinja2')
- # templates.append('python/sub-domain.python.jinja2')
+
if cls.get_gen_view(params_obj):
templates.append(f'{use_web_type}/view.{extension}.jinja2')
return templates
@@ -283,7 +306,7 @@ def get_template_list(cls, gen_table: GenTableModel) -> list[str]:
@classmethod
def get_file_name(cls, template: str, gen_table: GenTableModel) -> str:
"""
- 根据模板生成文件名
+ 根据模板生成文件名。
:param template: 模板路径
:param gen_table: 生成表的配置信息
@@ -320,7 +343,7 @@ def get_file_name(cls, template: str, gen_table: GenTableModel) -> str:
@classmethod
def get_package_prefix(cls, package_name: str) -> str:
"""
- 获取包前缀
+ 获取包前缀。
:param package_name: 包名
:return: 包前缀
@@ -330,7 +353,7 @@ def get_package_prefix(cls, package_name: str) -> str:
@classmethod
def get_vo_import_list(cls, gen_table: GenTableModel) -> list[str]:
"""
- 获取vo模板导入包列表
+ 获取vo模板导入包列表。
:param gen_table: 生成表的配置信息
:return: 导入包列表
@@ -356,7 +379,7 @@ def get_vo_import_list(cls, gen_table: GenTableModel) -> list[str]:
@classmethod
def get_do_import_list(cls, gen_table: GenTableModel) -> list[str]:
"""
- 根据实际ORM列类型构建生成模型的导入列表
+ 根据实际ORM列类型构建生成模型的导入列表。
:param gen_table: 生成表配置信息
:return: 已合并同源导入的语句列表
@@ -386,7 +409,7 @@ def get_do_import_list(cls, gen_table: GenTableModel) -> list[str]:
@classmethod
def get_db_type(cls, column_type: str) -> str:
"""
- 获取规范化的数据库列类型
+ 获取规范化的数据库列类型。
:param column_type: 数据库列类型
:return: 保留时区限定的规范化类型名称
@@ -396,7 +419,7 @@ def get_db_type(cls, column_type: str) -> str:
@classmethod
def merge_same_imports(cls, imports: list[str], import_start: str) -> list[str]:
"""
- 合并相同的导入语句
+ 合并相同的导入语句。
:param imports: 导入语句列表
:param import_start: 导入语句的起始字符串
@@ -420,7 +443,7 @@ def merge_same_imports(cls, imports: list[str], import_start: str) -> list[str]:
@classmethod
def get_dicts(cls, gen_table: GenTableModel) -> str:
"""
- 获取字典列表
+ 获取字典列表。
:param gen_table: 生成表的配置信息
:return: 字典列表
@@ -435,11 +458,10 @@ def get_dicts(cls, gen_table: GenTableModel) -> str:
@classmethod
def add_dicts(cls, dicts: set[str], columns: list[GenTableColumnModel]) -> None:
"""
- 添加字典列表
+ 添加字典列表。
:param dicts: 字典列表
:param columns: 字段列表
- :return: 新的字典列表
"""
for column in columns:
if (
@@ -454,7 +476,7 @@ def add_dicts(cls, dicts: set[str], columns: list[GenTableColumnModel]) -> None:
@classmethod
def get_permission_prefix(cls, module_name: str, business_name: str) -> str:
"""
- 获取权限前缀
+ 获取权限前缀。
:param module_name: 模块名
:param business_name: 业务名
@@ -465,7 +487,7 @@ def get_permission_prefix(cls, module_name: str, business_name: str) -> str:
@classmethod
def get_col_span(cls, form_col_num: int | None) -> str:
"""
- 根据表单列数获取栅格跨度
+ 根据表单列数获取栅格跨度。
:param form_col_num: 表单列数
:return: 栅格跨度
@@ -475,7 +497,7 @@ def get_col_span(cls, form_col_num: int | None) -> str:
@classmethod
def get_parent_menu_id(cls, params_obj: dict) -> str:
"""
- 获取上级菜单ID
+ 获取上级菜单ID。
:param params_obj: 菜单参数字典
:return: 上级菜单ID
@@ -487,7 +509,7 @@ def get_parent_menu_id(cls, params_obj: dict) -> str:
@classmethod
def get_gen_view(cls, params_obj: dict | None) -> bool:
"""
- 获取是否生成详情页
+ 获取是否生成详情页。
:param params_obj: 生成选项
:return: 是否生成详情页
@@ -504,7 +526,7 @@ def get_gen_view(cls, params_obj: dict | None) -> bool:
@classmethod
def get_tree_code(cls, params_obj: dict) -> str:
"""
- 获取树编码
+ 获取树编码。
:param params_obj: 菜单参数字典
:return: 树编码
@@ -516,7 +538,7 @@ def get_tree_code(cls, params_obj: dict) -> str:
@classmethod
def get_tree_parent_code(cls, params_obj: dict) -> str:
"""
- 获取树父编码
+ 获取树父编码。
:param params_obj: 菜单参数字典
:return: 树父编码
@@ -528,7 +550,7 @@ def get_tree_parent_code(cls, params_obj: dict) -> str:
@classmethod
def get_tree_name(cls, params_obj: dict) -> str:
"""
- 获取树名称
+ 获取树名称。
:param params_obj: 菜单参数字典
:return: 树名称
@@ -540,7 +562,7 @@ def get_tree_name(cls, params_obj: dict) -> str:
@classmethod
def get_expand_column(cls, gen_table: GenTableModel) -> int:
"""
- 获取展开列
+ 获取展开列。
:param gen_table: 生成表的配置信息
:return: 展开列
@@ -559,7 +581,7 @@ def get_expand_column(cls, gen_table: GenTableModel) -> int:
@classmethod
def to_camel_case(cls, text: str) -> str:
"""
- 将字符串转换为驼峰命名
+ 将字符串转换为驼峰命名。
:param text: 待转换的字符串
:return: 转换后的驼峰命名字符串
@@ -570,7 +592,7 @@ def to_camel_case(cls, text: str) -> str:
@classmethod
def get_sqlalchemy_type(cls, column_type: str, source_name: str | None = None) -> str:
"""
- 获取SQLAlchemy类型
+ 获取SQLAlchemy类型。
:param column_type: 列类型
:param source_name: 数据源名称
diff --git a/ruoyi-fastapi-backend/utils/time_util.py b/ruoyi-fastapi-backend/utils/time_util.py
index 6969c0842..3dac1ff37 100644
--- a/ruoyi-fastapi-backend/utils/time_util.py
+++ b/ruoyi-fastapi-backend/utils/time_util.py
@@ -9,7 +9,10 @@
class TimezoneUtil:
"""
- 时区工具类
+ 时区工具类。
+
+ :cvar RFC3339_PATTERN: 匹配 RFC 3339 时间戳的模式
+ :cvar ISO_DATE_PATTERN: 匹配 ISO 日历日期的模式
"""
RFC3339_PATTERN = re.compile(
@@ -21,10 +24,11 @@ class TimezoneUtil:
@classmethod
def get_timezone(cls, timezone_name: str) -> ZoneInfo:
"""
- 获取并缓存有效的IANA时区对象
+ 获取并缓存有效的IANA时区对象。
:param timezone_name: IANA时区名称
:return: 时区对象
+ :raises ValueError: IANA时区不能为空
"""
if not isinstance(timezone_name, str) or not timezone_name.strip():
raise ValueError('IANA时区不能为空')
@@ -34,10 +38,11 @@ def get_timezone(cls, timezone_name: str) -> ZoneInfo:
@cache
def _load_timezone(cls, timezone_name: str) -> ZoneInfo:
"""
- 加载时区对象,仅缓存校验成功的名称
+ 加载时区对象,仅缓存校验成功的名称。
:param timezone_name: IANA时区名称
:return: 时区对象
+ :raises ValueError: 名称不能解析为有效的 IANA 时区
"""
try:
return ZoneInfo(timezone_name)
@@ -47,7 +52,7 @@ def _load_timezone(cls, timezone_name: str) -> ZoneInfo:
@classmethod
def validate_timezone_name(cls, timezone_name: str) -> str:
"""
- 校验并返回规范化的IANA时区名称
+ 校验并返回规范化的IANA时区名称。
:param timezone_name: IANA时区名称
:return: 去除首尾空白后的有效时区名称
@@ -57,7 +62,7 @@ def validate_timezone_name(cls, timezone_name: str) -> str:
@classmethod
def validate_timezone_preference(cls, value: str) -> str:
"""
- 校验账号时区偏好,auto表示由客户端提供设备时区
+ 校验账号时区偏好,auto表示由客户端提供设备时区。
:param value: auto或IANA时区名称
:return: 校验后的账号偏好
@@ -67,7 +72,7 @@ def validate_timezone_preference(cls, value: str) -> str:
@classmethod
def get_request_timezone(cls) -> str:
"""
- 获取当前请求的显示时区,未指定时回退到业务时区
+ 获取当前请求的显示时区,未指定时回退到业务时区。
:return: 当前请求使用的IANA时区名称
"""
@@ -78,12 +83,13 @@ def get_request_timezone(cls) -> str:
@classmethod
def parse_business_date(cls, value: str | date) -> date:
"""
- 解析纯业务日期
+ 解析纯业务日期。
仅接受date对象或YYYY-MM-DD字符串,拒绝日期时间和数字。
:param value: 待校验的输入值
:return: 不含时间和时区的日期对象
+ :raises ValueError: 业务日期必须是有效的YYYY-MM-DD
"""
if isinstance(value, date) and not isinstance(value, datetime):
return value
@@ -97,12 +103,13 @@ def parse_business_date(cls, value: str | date) -> date:
@classmethod
def parse_rfc3339(cls, value: str | datetime) -> datetime:
"""
- 解析带时区的RFC 3339时刻并归一化为UTC毫秒
+ 解析带时区的RFC 3339时刻并归一化为UTC毫秒。
接受带 UTC 标记或数字偏移量的日期时间。
:param value: 待校验的输入值
:return: 携带UTC时区的毫秒精度时刻
+ :raises ValueError: 时刻必须是有效的带offset的RFC 3339字符串或aware datetime
"""
if isinstance(value, datetime):
return cls.to_utc_milliseconds(value)
@@ -116,7 +123,7 @@ def parse_rfc3339(cls, value: str | datetime) -> datetime:
@classmethod
def get_app_timezone(cls) -> ZoneInfo:
"""
- 获取应用配置的业务时区
+ 获取应用配置的业务时区。
:return: APP_TIMEZONE对应的时区对象
"""
@@ -128,7 +135,7 @@ def get_app_timezone(cls) -> ZoneInfo:
@classmethod
def utc_now(cls) -> datetime:
"""
- 获取当前UTC时刻
+ 获取当前UTC时刻。
:return: 携带UTC时区的当前时刻
"""
@@ -137,11 +144,12 @@ def utc_now(cls) -> datetime:
@classmethod
def ensure_aware(cls, value: datetime, *, field_name: str = 'datetime') -> datetime:
"""
- 校验时刻是否携带有效时区信息
+ 校验时刻是否携带有效时区信息。
:param value: 待校验时刻
:param field_name: 校验错误中使用的字段名称
:return: 校验通过的原时刻
+ :raises ValueError: 日期时间没有可用的时区偏移
"""
if value.tzinfo is None or value.utcoffset() is None:
raise ValueError(f'{field_name}必须携带时区信息')
@@ -150,7 +158,7 @@ def ensure_aware(cls, value: datetime, *, field_name: str = 'datetime') -> datet
@classmethod
def to_utc(cls, value: datetime) -> datetime:
"""
- 将带时区的时刻转换为UTC
+ 将带时区的时刻转换为UTC。
:param value: 携带时区信息的时刻
:return: 携带UTC时区的时刻
@@ -170,7 +178,7 @@ def to_optional_utc(cls, value: datetime | None) -> datetime | None:
@classmethod
def to_utc_milliseconds(cls, value: datetime) -> datetime:
"""
- 将带时区的时刻转换为毫秒精度UTC
+ 将带时区的时刻转换为毫秒精度UTC。
:param value: 携带时区信息的时刻
:return: 截断微秒尾数后的UTC时刻
@@ -181,7 +189,7 @@ def to_utc_milliseconds(cls, value: datetime) -> datetime:
@classmethod
def to_business_time(cls, value: datetime, timezone_name: str | None = None) -> datetime:
"""
- 将时刻转换为指定业务时区
+ 将时刻转换为指定业务时区。
:param value: 携带时区信息的时刻
:param timezone_name: 目标IANA时区名称,省略时使用APP_TIMEZONE
@@ -198,12 +206,13 @@ def local_date_range_to_utc(
timezone_name: str | None = None,
) -> tuple[datetime, datetime]:
"""
- 将包含首尾日期的业务日期范围转换为UTC半开区间
+ 将包含首尾日期的业务日期范围转换为UTC半开区间。
:param begin_date: 起始业务日期
:param end_date: 结束业务日期,包含当天
:param timezone_name: 业务IANA时区名称,省略时使用APP_TIMEZONE
:return: UTC半开区间[start, end)
+ :raises ValueError: 结束日期不能早于开始日期
"""
if end_date < begin_date:
raise ValueError('结束日期不能早于开始日期')
@@ -220,12 +229,13 @@ def local_date_strings_to_utc(
timezone_name: str | None = None,
) -> tuple[datetime | None, datetime | None] | None:
"""
- 将可选业务日期边界转换为UTC半开区间
+ 将可选业务日期边界转换为UTC半开区间。
:param begin_date: 起始业务日期,为空时不限制下界
:param end_date: 结束业务日期,包含当天,为空时不限制上界
:param timezone_name: 业务IANA时区名称,省略时使用APP_TIMEZONE
:return: UTC起止边界;缺失的边界为None,两边均缺失时返回None
+ :raises ValueError: 结束日期不能早于开始日期;结束日期必须早于9999-12-31
"""
if not begin_date and not end_date:
return None
@@ -251,11 +261,12 @@ def rfc3339_range_to_utc(
end_time: str | datetime | None,
) -> tuple[datetime | None, datetime | None] | None:
"""
- 解析可选的RFC 3339时刻范围
+ 解析可选的RFC 3339时刻范围。
:param begin_time: 起始时刻,为空时不限制下界
:param end_time: 结束时刻,为空时不限制上界
:return: UTC起止时刻;缺失的边界为None,两边均缺失时返回None
+ :raises ValueError: 结束时间不能早于开始时间
"""
if not begin_time and not end_time:
return None
@@ -268,7 +279,7 @@ def rfc3339_range_to_utc(
@classmethod
def format_rfc3339(cls, value: datetime) -> str:
"""
- 将时刻格式化为固定毫秒精度的UTC字符串
+ 将时刻格式化为固定毫秒精度的UTC字符串。
:param value: 携带时区信息的时刻
:return: 以Z结尾的RFC 3339字符串
@@ -280,7 +291,13 @@ def format_rfc3339(cls, value: datetime) -> str:
@dataclass(frozen=True)
class TimeSemantics:
"""
- 时间字段在Python、ORM、API和页面控件间的类型映射
+ 时间字段在Python、ORM、API和页面控件间的类型映射。
+
+ :ivar kind: 当前条目的类别
+ :ivar python_type: PYTHON类型
+ :ivar sqlalchemy_type: 生成数据库列时使用的 SQLAlchemy 类型
+ :ivar vo_type: 生成 Pydantic 字段时使用的类型
+ :ivar control: 代码生成器配置的显示类型
"""
kind: str
@@ -292,7 +309,11 @@ class TimeSemantics:
class GenTimeUtil:
"""
- 代码生成器时间字段工具类
+ 代码生成器时间字段工具类。
+
+ :cvar DATE: 表示日历日期的生成器类型
+ :cvar TIME: 表示一天内时刻的生成器类型
+ :cvar INSTANT: 表示 UTC 时间点的生成器类型
"""
DATE = TimeSemantics(
@@ -312,7 +333,7 @@ class GenTimeUtil:
@classmethod
def normalize_db_type(cls, column_type: str) -> str:
"""
- 规范化数据库类型名称,保留PostgreSQL时区限定
+ 规范化数据库类型名称,保留PostgreSQL时区限定。
:param column_type: 包含精度等修饰的数据库列类型
:return: 去除精度和unsigned修饰后的类型名称
@@ -323,11 +344,12 @@ def normalize_db_type(cls, column_type: str) -> str:
@classmethod
def get_time_semantics(cls, column_type: str, db_type: str) -> TimeSemantics | None:
"""
- 根据数据库列类型获取时间字段语义
+ 根据数据库列类型获取时间字段语义。
:param column_type: 数据库列类型
:param db_type: 数据源类型
:return: 时间字段的类型映射,非时间字段返回None
+ :raises ServiceWarning: PostgreSQL 无时区 timestamp 含义不明确,请将真实时刻列改为 TIMESTAMP(3) WITH TIME ZONE 后重新导入生成配置;带时区的 time 不能作为一天内时间生成,请使用 TIME WITHOUT TIME ZONE;真实时刻请使用 TIMESTAMP(3) WITH TIME ZONE
"""
data_type = cls.normalize_db_type(column_type)
if data_type == 'date':
@@ -354,11 +376,12 @@ def get_time_semantics(cls, column_type: str, db_type: str) -> TimeSemantics | N
@classmethod
def validate_time_control(cls, column_type: str, db_type: str, control: str | None) -> None:
"""
- 校验MySQL TIME字段是否已确认表示一天内时间
+ 校验MySQL TIME字段是否已确认表示一天内时间。
:param column_type: 数据库列类型
:param db_type: 数据源类型
:param control: 代码生成器配置的显示类型
+ :raises ServiceWarning: MySQL TIME 也可表示时长。确认字段表示一天内时间后,将显示类型设为“时间(一天内)”;时长请使用明确单位的数值列后重新导入
"""
if db_type == 'mysql' and cls.normalize_db_type(column_type) == 'time' and control != 'time':
raise ServiceWarning(
diff --git a/ruoyi-fastapi-backend/utils/transport_crypto_util.py b/ruoyi-fastapi-backend/utils/transport_crypto_util.py
index d17134a36..327afef66 100644
--- a/ruoyi-fastapi-backend/utils/transport_crypto_util.py
+++ b/ruoyi-fastapi-backend/utils/transport_crypto_util.py
@@ -22,7 +22,7 @@
# 通用编码辅助
def _urlsafe_b64encode(data: bytes) -> str:
"""
- 将字节串编码为URL安全的Base64字符串
+ 将字节串编码为URL安全的Base64字符串。
:param data: 原始字节串
:return: URL安全的Base64字符串
@@ -32,7 +32,7 @@ def _urlsafe_b64encode(data: bytes) -> str:
def _urlsafe_b64decode(data: str) -> bytes:
"""
- 将URL安全的Base64字符串解码为字节串
+ 将URL安全的Base64字符串解码为字节串。
:param data: URL安全的Base64字符串
:return: 解码后的字节串
@@ -42,11 +42,15 @@ def _urlsafe_b64decode(data: str) -> bytes:
class TransportKeyError(ValueError):
- """可通过刷新公钥重试的传输层密钥错误。"""
+ """
+ 可通过刷新公钥重试的传输层密钥错误。
+
+ :ivar msg_key: 对外响应使用的语义标识
+ """
def __init__(self, message: str, *, msg_key: str) -> None:
"""
- 保存诊断原文和客户端用于判断重试的消息标识
+ 保存诊断原文和客户端用于判断重试的消息标识。
:param message: 内部诊断使用的错误原文
:param msg_key: 对外响应使用的语义标识
@@ -58,11 +62,11 @@ def __init__(self, message: str, *, msg_key: str) -> None:
@dataclass(frozen=True)
class TransportKeyPair:
"""
- 传输层密钥对载体
+ 传输层密钥对载体。
- kid: 密钥版本标识
- private_key_pem: PEM格式私钥
- public_key_pem: PEM格式公钥
+ :ivar kid: 密钥版本标识
+ :ivar private_key_pem: PEM格式私钥
+ :ivar public_key_pem: PEM格式公钥
"""
kid: str
@@ -74,14 +78,14 @@ class TransportKeyPair:
@dataclass(frozen=True)
class DecryptedTransportEnvelope:
"""
- 请求信封解密结果
-
- kid: 请求使用的密钥版本标识
- nonce: 请求随机数
- timestamp: 请求时间戳
- aes_key: 当前请求协商出的AES会话密钥
- aad: 通过校验后的AAD上下文
- plaintext: 解密得到的原始请求载荷
+ 请求信封解密结果。
+
+ :ivar kid: 请求使用的密钥版本标识
+ :ivar nonce: 请求随机数
+ :ivar timestamp: 请求时间戳
+ :ivar aes_key: 当前请求协商出的AES会话密钥
+ :ivar aad: 通过校验后的AAD上下文
+ :ivar plaintext: 解密得到的原始请求载荷
"""
kid: str
@@ -95,7 +99,12 @@ class DecryptedTransportEnvelope:
# 传输层密钥管理
class TransportKeyProvider:
"""
- 传输层密钥提供者
+ 传输层密钥提供者。
+
+ :cvar _lock: 协调并发访问共享状态的锁
+ :cvar _key_pairs: 按密钥标识索引的加解密密钥对
+ :cvar _MIN_RSA_KEY_SIZE: 接受的 RSA 密钥最小位数
+ :cvar _RSA_KEY_SIZE_STEP: 支持的相邻 RSA 密钥长度间隔
"""
_lock = Lock()
@@ -106,9 +115,9 @@ class TransportKeyProvider:
@classmethod
def validate_runtime_configuration(cls) -> None:
"""
- 校验传输层加解密运行配置,确保启用时显式配置密钥对
+ 校验传输层加解密运行配置,确保启用时显式配置密钥对。
- :return: None
+ :raises ValueError: TRANSPORT_CRYPTO_RSA_KEY_SIZE必须大于等于2048,且为256的整数倍;启用传输层加解密时,必须显式配置TRANSPORT_CRYPTO_PUBLIC_KEY和TRANSPORT_CRYPTO_PRIVATE_KEY;TRANSPORT_CRYPTO_PUBLIC_KEY与TRANSPORT_CRYPTO_PRIVATE_KEY不匹配
"""
if not TransportCryptoConfig.transport_crypto_enabled or TransportCryptoConfig.transport_crypto_mode == 'off':
return
@@ -143,7 +152,7 @@ def validate_runtime_configuration(cls) -> None:
@classmethod
def get_current_key_pair(cls) -> TransportKeyPair:
"""
- 获取当前启用的密钥对
+ 获取当前启用的密钥对。
:return: 当前启用的密钥对
"""
@@ -157,7 +166,7 @@ def get_current_key_pair(cls) -> TransportKeyPair:
@classmethod
def get_current_kid(cls) -> str:
"""
- 获取当前启用的密钥标识
+ 获取当前启用的密钥标识。
:return: 当前启用的密钥标识
"""
@@ -166,7 +175,7 @@ def get_current_kid(cls) -> str:
@classmethod
def get_public_key_pem(cls, kid: str | None = None) -> str:
"""
- 获取公钥PEM
+ 获取公钥PEM。
:param kid: 密钥版本标识,未传入时默认使用当前版本
:return: PEM格式公钥字符串
@@ -176,7 +185,7 @@ def get_public_key_pem(cls, kid: str | None = None) -> str:
@classmethod
def get_private_key_pem(cls, kid: str | None = None) -> str:
"""
- 获取私钥PEM
+ 获取私钥PEM。
:param kid: 密钥版本标识,未传入时默认使用当前版本
:return: PEM格式私钥字符串
@@ -186,10 +195,11 @@ def get_private_key_pem(cls, kid: str | None = None) -> str:
@classmethod
def get_key_pair(cls, kid: str | None = None) -> TransportKeyPair:
"""
- 根据kid获取密钥对,未传入时返回当前密钥对
+ 根据kid获取密钥对,未传入时返回当前密钥对。
:param kid: 密钥版本标识,未传入时默认使用当前版本
:return: 匹配到的密钥对
+ :raises TransportKeyError: 密钥版本不存在
"""
target_kid = kid or cls.get_current_kid()
if cls._key_pairs is None:
@@ -204,7 +214,7 @@ def get_key_pair(cls, kid: str | None = None) -> TransportKeyPair:
@classmethod
def get_supported_kids(cls) -> tuple[str, ...]:
"""
- 获取当前支持解密的全部密钥版本
+ 获取当前支持解密的全部密钥版本。
:return: 当前支持解密的密钥版本元组
"""
@@ -215,9 +225,10 @@ def get_supported_kids(cls) -> tuple[str, ...]:
@classmethod
def _build_key_pairs(cls) -> dict[str, TransportKeyPair]:
"""
- 构建当前进程可用的全部密钥对映射
+ 构建当前进程可用的全部密钥对映射。
:return: 以kid为键的密钥对映射
+ :raises ValueError: 启用传输层加解密时,必须显式配置TRANSPORT_CRYPTO_PUBLIC_KEY和TRANSPORT_CRYPTO_PRIVATE_KEY
"""
configured_private_key = cls._normalize_pem(TransportCryptoConfig.transport_crypto_private_key)
configured_public_key = cls._normalize_pem(TransportCryptoConfig.transport_crypto_public_key)
@@ -237,9 +248,10 @@ def _build_key_pairs(cls) -> dict[str, TransportKeyPair]:
@classmethod
def _build_legacy_key_pairs(cls) -> dict[str, TransportKeyPair]:
"""
- 构建历史密钥对映射,用于密钥轮换窗口内的兼容解密
+ 构建历史密钥对映射,用于密钥轮换窗口内的兼容解密。
:return: 以kid为键的历史密钥对映射
+ :raises ValueError: 传输层历史密钥配置不是合法JSON;传输层历史密钥配置必须是JSON数组;传输层历史密钥项必须是JSON对象;传输层历史密钥项必须包含kid和privateKey
"""
legacy_key_pairs: dict[str, TransportKeyPair] = {}
configured_legacy_key_pairs = TransportCryptoConfig.transport_crypto_legacy_key_pairs
@@ -283,7 +295,7 @@ def _build_legacy_key_pairs(cls) -> dict[str, TransportKeyPair]:
@staticmethod
def _normalize_pem(pem_value: str) -> str:
"""
- 兼容环境变量中的换行转义
+ 兼容环境变量中的换行转义。
:param pem_value: 原始PEM字符串
:return: 标准化后的PEM字符串
@@ -293,17 +305,15 @@ def _normalize_pem(pem_value: str) -> str:
# 传输层安全校验
class TransportSecurityUtil:
- """
- 传输层安全校验工具
- """
+ """传输层安全校验工具。"""
@classmethod
def validate_timestamp(cls, timestamp: int) -> None:
"""
- 校验请求时间窗
+ 校验请求时间窗。
:param timestamp: 请求信封中的时间戳
- :return: None
+ :raises ValueError: 加密请求已过期,请刷新页面后重试
"""
now_timestamp = int(time.time())
if abs(now_timestamp - timestamp) > TransportCryptoConfig.transport_crypto_clock_skew_seconds:
@@ -318,12 +328,12 @@ def validate_timestamp(cls, timestamp: int) -> None:
@classmethod
async def validate_replay(cls, request: Request, kid: str, nonce: str) -> None:
"""
- 使用Redis进行防重放校验
+ 使用Redis进行防重放校验。
:param request: 当前请求对象
:param kid: 当前密钥版本标识
:param nonce: 当前请求随机数
- :return: None
+ :raises ValueError: 服务端防重放校验不可用,请稍后重试;检测到重复请求,请勿重放加密报文
"""
redis = getattr(request.app.state, 'redis', None)
if redis is None:
@@ -351,7 +361,7 @@ async def validate_replay(cls, request: Request, kid: str, nonce: str) -> None:
@classmethod
def _should_fail_closed_when_replay_check_unavailable(cls, request: Request) -> bool:
"""
- 判断当前请求在防重放能力不可用时是否需要直接拒绝
+ 判断当前请求在防重放能力不可用时是否需要直接拒绝。
:param request: 当前请求对象
:return: 是否需要失败关闭
@@ -364,7 +374,7 @@ def _should_fail_closed_when_replay_check_unavailable(cls, request: Request) ->
@staticmethod
def _normalize_path(path: str) -> str:
"""
- 标准化请求路径,剥离应用根路径前缀
+ 标准化请求路径,剥离应用根路径前缀。
:param path: 原始请求路径
:return: 标准化后的业务路径
@@ -378,7 +388,7 @@ def _normalize_path(path: str) -> str:
@staticmethod
def _is_required_path(path: str) -> bool:
"""
- 判断当前路径是否命中强制加密路径配置
+ 判断当前路径是否命中强制加密路径配置。
:param path: 当前请求路径
:return: 是否命中强制加密路径
@@ -396,7 +406,11 @@ def _is_required_path(path: str) -> bool:
# 传输层加解密核心能力
class TransportCryptoUtil:
"""
- 传输层加解密工具
+ 传输层加解密工具。
+
+ :cvar _ENVELOPE_VERSION: 加密信封使用的协议版本
+ :cvar _RESPONSE_ENVELOPE_ALGORITHM: 响应加密信封使用的算法标识
+ :cvar _REQUIRED_ENVELOPE_FIELDS: 解包加密信封时必须存在的字段
"""
_ENVELOPE_VERSION = '1'
@@ -406,7 +420,7 @@ class TransportCryptoUtil:
@classmethod
def get_response_envelope_algorithm(cls) -> str:
"""
- 获取响应信封算法标识
+ 获取响应信封算法标识。
:return: 响应信封算法标识
"""
@@ -420,7 +434,7 @@ def decrypt_envelope(
expected_path: str,
) -> DecryptedTransportEnvelope:
"""
- 解密请求信封
+ 解密请求信封。
:param envelope: 请求加密信封
:param expected_method: 当前请求预期HTTP方法
@@ -447,10 +461,11 @@ def decrypt_envelope(
@classmethod
def decrypt_request_key(cls, envelope: dict[str, Any]) -> bytes:
"""
- 仅解出请求中的AES会话密钥,用于异常场景构造加密错误响应
+ 仅解出请求中的AES会话密钥,用于异常场景构造加密错误响应。
:param envelope: 请求加密信封
:return: 请求协商出的AES会话密钥
+ :raises TransportKeyError: 请求密钥解密失败
"""
kid = str(envelope['kid'])
private_key_pem = TransportKeyProvider.get_private_key_pem(kid)
@@ -474,7 +489,7 @@ def encrypt_response_body(
path: str,
) -> bytes:
"""
- 使用请求协商出的AES密钥加密响应体
+ 使用请求协商出的AES密钥加密响应体。
:param aes_key: 请求协商出的AES会话密钥
:param payload: 需要加密的响应体字节串
@@ -499,7 +514,7 @@ def encrypt_response_body(
@classmethod
def decode_query_envelope(cls, encrypted_query: str) -> dict[str, Any]:
"""
- 解码查询参数中的加密信封
+ 解码查询参数中的加密信封。
:param encrypted_query: 查询参数中的加密信封字符串
:return: 解码后的信封字典
@@ -510,7 +525,7 @@ def decode_query_envelope(cls, encrypted_query: str) -> dict[str, Any]:
@classmethod
def build_public_key_payload(cls) -> dict[str, Any]:
"""
- 构建公钥下发载荷
+ 构建公钥下发载荷。
:return: 公钥下发载荷字典
"""
@@ -526,7 +541,7 @@ def build_public_key_payload(cls) -> dict[str, Any]:
@classmethod
def build_frontend_config_payload(cls) -> dict[str, Any]:
"""
- 构建前端传输层加解密运行配置载荷
+ 构建前端传输层加解密运行配置载荷。
:return: 前端传输层加解密运行配置载荷字典
"""
@@ -551,10 +566,10 @@ def build_frontend_config_payload(cls) -> dict[str, Any]:
@classmethod
def _validate_envelope(cls, envelope: dict[str, Any]) -> None:
"""
- 校验请求加密信封的结构、协议版本与算法是否有效
+ 校验请求加密信封的结构、协议版本与算法是否有效。
:param envelope: 请求加密信封
- :return: None
+ :raises ValueError: 加密请求信封格式不合法;加密请求协议版本不受支持;加密请求算法不受支持
"""
if not isinstance(envelope, dict):
raise ValueError('加密请求信封格式不合法')
@@ -577,12 +592,13 @@ def _extract_and_validate_aad(
expected_path: str,
) -> dict[str, str]:
"""
- 提取并校验请求AAD,确保密文与当前接口绑定
+ 提取并校验请求AAD,确保密文与当前接口绑定。
:param envelope: 请求加密信封
:param expected_method: 当前请求预期HTTP方法
:param expected_path: 当前请求预期路径
:return: 归一化后的AAD字典
+ :raises ValueError: 加密请求缺少合法的aad;加密请求的method/path与当前接口不匹配
"""
aad = envelope.get('aad')
if not isinstance(aad, dict):
@@ -598,7 +614,7 @@ def _extract_and_validate_aad(
@staticmethod
def _build_aad_bytes(aad: dict[str, str]) -> bytes:
"""
- 将AAD字典序列化为AES-GCM additionalData所需字节串
+ 将AAD字典序列化为AES-GCM additionalData所需字节串。
:param aad: AAD字典
:return: 序列化后的AAD字节串
@@ -608,7 +624,7 @@ def _build_aad_bytes(aad: dict[str, str]) -> bytes:
@staticmethod
def _split_paths(path_value: str) -> list[str]:
"""
- 将逗号分隔的路径配置拆分为列表
+ 将逗号分隔的路径配置拆分为列表。
:param path_value: 原始路径配置
:return: 路径列表
@@ -619,7 +635,23 @@ def _split_paths(path_value: str) -> list[str]:
# 传输层监控读写与聚合
class TransportCryptoMonitorUtil:
"""
- 传输层加解密监控工具
+ 传输层加解密监控工具。
+
+ :cvar _REDIS_KEY_PREFIX: 加密监控数据使用的 Redis 键前缀
+ :cvar _META_STARTED_AT_KEY: 记录监控启动时间的 Redis 键
+ :cvar _COUNTERS_KEY: 保存加密操作计数的 Redis 键
+ :cvar _FAILURE_REASONS_KEY: 保存失败原因计数的 Redis 键
+ :cvar _KIDS_KEY: 保存各密钥使用计数的 Redis 键
+ :cvar _RECENT_FAILURES_KEY: 保存最近失败记录的 Redis 键
+ :cvar _RECENT_FAILURE_LIMIT: 最多保留的最近失败记录数
+ :cvar _REDIS_WARNING_INTERVAL_SECONDS: Redis 告警的最小间隔(秒)
+ :cvar _lock: 协调并发访问共享状态的锁
+ :cvar _started_at: 当前监控实例的启动时间
+ :cvar _counters: 按事件累计的计数器
+ :cvar _failure_reasons: 各类失败原因的累计次数
+ :cvar _kid_counters: 按密钥标识记录的使用次数
+ :cvar _recent_failures: 最近发生的失败记录
+ :cvar _last_redis_warning_at: 上次记录 Redis 异常警告的时间
"""
_REDIS_KEY_PREFIX = 'transport:monitor'
@@ -642,10 +674,9 @@ class TransportCryptoMonitorUtil:
@classmethod
async def record_plain_request(cls, app: FastAPI | None = None) -> None:
"""
- 记录明文请求
+ 记录明文请求。
:param app: FastAPI应用对象
- :return: None
"""
if await cls._write_redis_counters(
app,
@@ -660,11 +691,10 @@ async def record_plain_request(cls, app: FastAPI | None = None) -> None:
@classmethod
async def record_encrypted_request(cls, app: FastAPI | None = None, kid: str | None = None) -> None:
"""
- 记录加密请求
+ 记录加密请求。
:param app: FastAPI应用对象
:param kid: 当前请求使用的密钥版本
- :return: None
"""
if await cls._write_redis_counters(
app,
@@ -681,12 +711,11 @@ async def record_encrypted_request(cls, app: FastAPI | None = None, kid: str | N
@classmethod
async def record_required_rejected(cls, app: FastAPI | None = None, method: str = '', path: str = '') -> None:
"""
- 记录强制加密接口被明文访问的拒绝事件
+ 记录强制加密接口被明文访问的拒绝事件。
:param app: FastAPI应用对象
:param method: 请求方法
:param path: 请求路径
- :return: None
"""
if await cls._write_redis_failure(
app,
@@ -701,11 +730,10 @@ async def record_required_rejected(cls, app: FastAPI | None = None, method: str
@classmethod
async def record_decrypt_success(cls, app: FastAPI | None = None, kid: str | None = None) -> None:
"""
- 记录请求解密成功事件
+ 记录请求解密成功事件。
:param app: FastAPI应用对象
:param kid: 当前请求使用的密钥版本
- :return: None
"""
if await cls._write_redis_counters(
app,
@@ -726,14 +754,13 @@ async def record_decrypt_failure(
kid: str | None = None,
) -> None:
"""
- 记录请求解密失败事件
+ 记录请求解密失败事件。
:param app: FastAPI应用对象
:param method: 请求方法
:param path: 请求路径
:param reason: 失败原因分类
:param kid: 当前请求使用的密钥版本
- :return: None
"""
if await cls._write_redis_failure(app, method=method, path=path, reason=reason, kid=kid):
return
@@ -742,10 +769,9 @@ async def record_decrypt_failure(
@classmethod
async def record_plain_response(cls, app: FastAPI | None = None) -> None:
"""
- 记录明文响应
+ 记录明文响应。
:param app: FastAPI应用对象
- :return: None
"""
if await cls._write_redis_counters(app, counter_updates={'plain_responses_total': 1}):
return
@@ -759,12 +785,11 @@ async def record_encrypted_response(
is_error: bool = False,
) -> None:
"""
- 记录加密响应
+ 记录加密响应。
:param app: FastAPI应用对象
:param kid: 当前响应使用的密钥版本
:param is_error: 是否为错误响应
- :return: None
"""
counter_updates = {'encrypted_responses_total': 1}
if is_error:
@@ -781,7 +806,7 @@ async def record_encrypted_response(
@classmethod
async def get_snapshot(cls, app: FastAPI | None = None) -> dict[str, Any]:
"""
- 获取传输层加解密监控快照
+ 获取传输层加解密监控快照。
:param app: FastAPI应用对象
:return: 监控快照字典
@@ -801,7 +826,7 @@ async def _write_redis_counters(
kid_counter_updates: dict[str, int] | None = None,
) -> bool:
"""
- 将监控计数写入Redis
+ 将监控计数写入Redis。
:param app: FastAPI应用对象
:param counter_updates: 全局计数增量
@@ -839,7 +864,7 @@ async def _write_redis_failure(
include_decrypt_failure: bool = True,
) -> bool:
"""
- 将失败事件写入Redis
+ 将失败事件写入Redis。
:param app: FastAPI应用对象
:param method: 请求方法
@@ -884,7 +909,7 @@ async def _write_redis_failure(
@classmethod
async def _get_redis_snapshot(cls, app: FastAPI | None) -> dict[str, Any]:
"""
- 从Redis中读取监控快照
+ 从Redis中读取监控快照。
:param app: FastAPI应用对象
:return: Redis监控快照字典
@@ -931,7 +956,7 @@ async def _get_redis_snapshot(cls, app: FastAPI | None) -> dict[str, Any]:
@classmethod
async def _get_redis_kid_stats(cls, redis: aioredis.Redis, kids: list[str]) -> list[dict[str, Any]]:
"""
- 获取Redis中的按密钥版本聚合统计
+ 获取Redis中的按密钥版本聚合统计。
:param redis: Redis客户端
:param kids: 密钥版本列表
@@ -957,11 +982,7 @@ async def _get_redis_kid_stats(cls, redis: aioredis.Redis, kids: list[str]) -> l
# 进程内回退统计
@classmethod
def _record_plain_request_local(cls) -> None:
- """
- 在本地内存中记录明文请求
-
- :return: None
- """
+ """在本地内存中记录明文请求。"""
with cls._lock:
cls._counters['requests_total'] += 1
cls._counters['plain_requests_total'] += 1
@@ -969,10 +990,9 @@ def _record_plain_request_local(cls) -> None:
@classmethod
def _record_encrypted_request_local(cls, kid: str | None = None) -> None:
"""
- 在本地内存中记录加密请求
+ 在本地内存中记录加密请求。
:param kid: 当前请求使用的密钥版本
- :return: None
"""
with cls._lock:
cls._counters['requests_total'] += 1
@@ -982,10 +1002,9 @@ def _record_encrypted_request_local(cls, kid: str | None = None) -> None:
@classmethod
def _record_decrypt_success_local(cls, kid: str | None = None) -> None:
"""
- 在本地内存中记录解密成功事件
+ 在本地内存中记录解密成功事件。
:param kid: 当前请求使用的密钥版本
- :return: None
"""
with cls._lock:
cls._counters['decrypt_success_total'] += 1
@@ -993,22 +1012,17 @@ def _record_decrypt_success_local(cls, kid: str | None = None) -> None:
@classmethod
def _record_plain_response_local(cls) -> None:
- """
- 在本地内存中记录明文响应
-
- :return: None
- """
+ """在本地内存中记录明文响应。"""
with cls._lock:
cls._counters['plain_responses_total'] += 1
@classmethod
def _record_encrypted_response_local(cls, kid: str | None = None, is_error: bool = False) -> None:
"""
- 在本地内存中记录加密响应
+ 在本地内存中记录加密响应。
:param kid: 当前响应使用的密钥版本
:param is_error: 是否为错误响应
- :return: None
"""
with cls._lock:
cls._counters['encrypted_responses_total'] += 1
@@ -1026,14 +1040,13 @@ def _record_failure_local(
include_decrypt_failure: bool = True,
) -> None:
"""
- 在本地内存中记录失败事件
+ 在本地内存中记录失败事件。
:param method: 请求方法
:param path: 请求路径
:param reason: 失败原因分类
:param kid: 当前请求使用的密钥版本
:param include_decrypt_failure: 是否计入解密失败次数
- :return: None
"""
with cls._lock:
if include_decrypt_failure:
@@ -1055,7 +1068,7 @@ def _record_failure_local(
@classmethod
def _get_local_snapshot_parts(cls) -> dict[str, Any]:
"""
- 获取本地内存中的监控快照片段
+ 获取本地内存中的监控快照片段。
:return: 本地监控快照片段
"""
@@ -1081,7 +1094,7 @@ def _get_local_snapshot_parts(cls) -> dict[str, Any]:
@classmethod
def _merge_snapshot_parts(cls, redis_snapshot: dict[str, Any], local_snapshot: dict[str, Any]) -> dict[str, Any]:
"""
- 合并Redis统计与本地回退统计
+ 合并Redis统计与本地回退统计。
:param redis_snapshot: Redis监控快照片段
:param local_snapshot: 本地监控快照片段
@@ -1136,7 +1149,7 @@ def _merge_snapshot_parts(cls, redis_snapshot: dict[str, Any], local_snapshot: d
@classmethod
def _build_snapshot(cls, snapshot_parts: dict[str, Any]) -> dict[str, Any]:
"""
- 基于监控片段构建最终快照
+ 基于监控片段构建最终快照。
:param snapshot_parts: 监控快照片段
:return: 最终监控快照
@@ -1177,7 +1190,7 @@ def _build_snapshot(cls, snapshot_parts: dict[str, Any]) -> dict[str, Any]:
@classmethod
def _get_redis_client(cls, app: FastAPI | None) -> aioredis.Redis | None:
"""
- 获取当前应用中的Redis客户端
+ 获取当前应用中的Redis客户端。
:param app: FastAPI应用对象
:return: Redis客户端,不存在时返回None
@@ -1189,11 +1202,10 @@ def _get_redis_client(cls, app: FastAPI | None) -> aioredis.Redis | None:
@classmethod
def _increase_kid_counter_local(cls, kid: str | None, counter_name: str) -> None:
"""
- 在本地内存中按密钥版本累加统计值
+ 在本地内存中按密钥版本累加统计值。
:param kid: 当前密钥版本
:param counter_name: 统计项名称
- :return: None
"""
if not kid:
return
@@ -1202,11 +1214,10 @@ def _increase_kid_counter_local(cls, kid: str | None, counter_name: str) -> None
@classmethod
def _log_redis_warning(cls, action: str, exc: Exception) -> None:
"""
- 记录Redis监控降级日志,并限制日志频率
+ 记录Redis监控降级日志,并限制日志频率。
:param action: 当前执行动作
:param exc: 异常对象
- :return: None
"""
now = time.monotonic()
with cls._lock:
@@ -1218,7 +1229,7 @@ def _log_redis_warning(cls, action: str, exc: Exception) -> None:
@classmethod
def _has_local_fallback_data(cls, local_snapshot: dict[str, Any]) -> bool:
"""
- 判断本地回退统计中是否存在有效数据
+ 判断本地回退统计中是否存在有效数据。
:param local_snapshot: 本地监控快照片段
:return: 是否存在有效数据
@@ -1234,7 +1245,7 @@ def _has_local_fallback_data(cls, local_snapshot: dict[str, Any]) -> bool:
@classmethod
def _build_kid_counter_key(cls, kid: str) -> str:
"""
- 构建按密钥版本统计的Redis键名
+ 构建按密钥版本统计的Redis键名。
:param kid: 密钥版本
:return: Redis键名
@@ -1244,7 +1255,7 @@ def _build_kid_counter_key(cls, kid: str) -> str:
@classmethod
def _parse_recent_failures(cls, recent_failures: list[str]) -> list[dict[str, Any]]:
"""
- 解析Redis中的最近失败记录
+ 解析Redis中的最近失败记录。
:param recent_failures: Redis中存储的失败记录列表
:return: 失败记录对象列表
@@ -1264,7 +1275,7 @@ def _parse_recent_failures(cls, recent_failures: list[str]) -> list[dict[str, An
@staticmethod
def _to_int_mapping(mapping: dict[str, Any]) -> dict[str, int]:
"""
- 将Redis返回的字符串字典转换为整数字典
+ 将Redis返回的字符串字典转换为整数字典。
:param mapping: Redis原始字典
:return: 转换后的整数字典
@@ -1274,7 +1285,7 @@ def _to_int_mapping(mapping: dict[str, Any]) -> dict[str, int]:
@staticmethod
def _parse_datetime(value: Any) -> datetime | None:
"""
- 将字符串时间解析为datetime对象
+ 将字符串时间解析为datetime对象。
:param value: 原始时间值
:return: datetime对象,解析失败时返回None
@@ -1294,7 +1305,7 @@ def _parse_datetime(value: Any) -> datetime | None:
@classmethod
def _coerce_datetime_for_sort(cls, value: Any) -> datetime:
"""
- 将任意时间值转换为可排序的datetime对象
+ 将任意时间值转换为可排序的datetime对象。
:param value: 原始时间值
:return: datetime对象
diff --git a/ruoyi-fastapi-backend/utils/upload_util.py b/ruoyi-fastapi-backend/utils/upload_util.py
index 1a8806e0a..949636212 100644
--- a/ruoyi-fastapi-backend/utils/upload_util.py
+++ b/ruoyi-fastapi-backend/utils/upload_util.py
@@ -17,18 +17,17 @@
class FilePathUtil:
- """
- 文件路径安全校验工具类
- """
+ """文件路径安全校验工具类。"""
@classmethod
def resolve_path_within_root(cls, root: str | os.PathLike[str], untrusted_path: str) -> Path:
"""
- 将不可信相对路径解析为根目录内路径
+ 将不可信相对路径解析为根目录内路径。
:param root: 文件根目录
:param untrusted_path: 不可信文件路径
:return: 根目录内的路径
+ :raises ValueError: 文件路径不能为空;文件路径不合法;文件路径超出允许目录
"""
if not untrusted_path or '\x00' in untrusted_path:
raise ValueError('文件路径不能为空')
@@ -58,11 +57,12 @@ def resolve_path_within_root(cls, root: str | os.PathLike[str], untrusted_path:
@classmethod
def resolve_file_within_root(cls, root: str | os.PathLike[str], untrusted_path: str) -> Path:
"""
- 将不可信相对路径解析为根目录内已存在的普通文件
+ 将不可信相对路径解析为根目录内已存在的普通文件。
:param root: 文件根目录
:param untrusted_path: 不可信文件路径
:return: 根目录内的文件路径
+ :raises FileNotFoundError: 文件不存在
"""
candidate_path = cls.resolve_path_within_root(root, untrusted_path)
@@ -73,7 +73,10 @@ def resolve_file_within_root(cls, root: str | os.PathLike[str], untrusted_path:
class UploadUtil:
"""
- 上传工具类
+ 上传工具类。
+
+ :cvar GENERATED_FILE_INFO_LENGTH: 上传文件名中生成信息片段的字符数
+ :cvar MAX_RANDOM_CODE: 文件名随机编码允许的最大值
"""
GENERATED_FILE_INFO_LENGTH = 18
@@ -82,7 +85,7 @@ class UploadUtil:
@classmethod
def generate_random_number(cls) -> str:
"""
- 生成3位数字构成的字符串
+ 生成3位数字构成的字符串。
:return: 3位数字构成的字符串
"""
@@ -93,7 +96,7 @@ def generate_random_number(cls) -> str:
@classmethod
def check_file_exists(cls, filepath: str | os.PathLike[str]) -> bool:
"""
- 检查文件是否存在
+ 检查文件是否存在。
:param filepath: 文件路径
:return: 校验结果
@@ -103,7 +106,7 @@ def check_file_exists(cls, filepath: str | os.PathLike[str]) -> bool:
@classmethod
def ensure_directory(cls, directory: str | os.PathLike[str]) -> None:
"""
- 创建文件目录
+ 创建文件目录。
:param directory: 文件目录
"""
@@ -112,7 +115,7 @@ def ensure_directory(cls, directory: str | os.PathLike[str]) -> None:
@classmethod
def check_file_extension(cls, file: UploadFile) -> bool:
"""
- 检查文件后缀是否合法
+ 检查文件后缀是否合法。
:param file: 文件对象
:return: 校验结果
@@ -124,7 +127,7 @@ def check_file_extension(cls, file: UploadFile) -> bool:
@classmethod
def get_file_extension(cls, filename: str | None) -> str:
"""
- 获取文件名的小写扩展名
+ 获取文件名的小写扩展名。
:param filename: 文件名称
:return: 小写文件扩展名
@@ -137,7 +140,7 @@ def get_file_extension(cls, filename: str | None) -> str:
@classmethod
def get_original_filename(cls, filename: str | None) -> str:
"""
- 获取移除目录信息后的原始文件名
+ 获取移除目录信息后的原始文件名。
:param filename: 文件名称
:return: 原始文件名
@@ -149,7 +152,7 @@ def get_original_filename(cls, filename: str | None) -> str:
@classmethod
def get_safe_file_stem(cls, filename: str | None) -> str:
"""
- 获取移除路径和非法字符后的文件名前缀
+ 获取移除路径和非法字符后的文件名前缀。
:param filename: 文件名称
:return: 安全文件名前缀
@@ -170,7 +173,7 @@ def build_download_headers(
accept_ranges: bool = True,
) -> dict[str, str]:
"""
- 构造文件下载响应头
+ 构造文件下载响应头。
:param filename: 文件名称
:param byte_range: 文件字节范围
@@ -198,7 +201,7 @@ def build_download_headers(
@classmethod
def check_file_timestamp(cls, filename: str) -> bool:
"""
- 校验文件时间戳是否合法
+ 校验文件时间戳是否合法。
:param filename: 文件名称
:return: 校验结果
@@ -216,7 +219,7 @@ def check_file_timestamp(cls, filename: str) -> bool:
@classmethod
def check_file_machine(cls, filename: str) -> bool:
"""
- 校验文件机器码是否合法
+ 校验文件机器码是否合法。
:param filename: 文件名称
:return: 校验结果
@@ -230,7 +233,7 @@ def check_file_machine(cls, filename: str) -> bool:
@classmethod
def check_file_random_code(cls, filename: str) -> bool:
"""
- 校验文件随机码是否合法
+ 校验文件随机码是否合法。
:param filename: 文件名称
:return: 校验结果
@@ -251,12 +254,13 @@ async def generate_file(
length: int | None = None,
) -> AsyncGenerator[bytes, None]:
"""
- 根据文件生成二进制数据
+ 根据文件生成二进制数据。
:param filepath: 文件路径
:param start: 读取起始字节位置
:param length: 读取字节数
- :yield: 二进制数据
+ :yield: 按读取顺序逐块产生二进制数据的异步迭代器
+ :raises ValueError: 文件读取范围不合法
"""
if start < 0 or (length is not None and length < 0):
raise ValueError('文件读取范围不合法')
@@ -275,7 +279,7 @@ async def generate_file(
@classmethod
def delete_file(cls, filepath: str | os.PathLike[str]) -> None:
"""
- 根据文件路径删除对应文件
+ 根据文件路径删除对应文件。
:param filepath: 文件路径
"""
@@ -284,7 +288,7 @@ def delete_file(cls, filepath: str | os.PathLike[str]) -> None:
@classmethod
def move_file(cls, source: str | os.PathLike[str], target: str | os.PathLike[str]) -> None:
"""
- 移动文件到目标路径
+ 移动文件到目标路径。
:param source: 原文件路径
:param target: 目标文件路径
@@ -295,7 +299,7 @@ def move_file(cls, source: str | os.PathLike[str], target: str | os.PathLike[str
@classmethod
def remove_empty_directory(cls, directory: str | os.PathLike[str]) -> None:
"""
- 删除空目录
+ 删除空目录。
:param directory: 目录路径
"""
diff --git a/ruoyi-fastapi-backend/utils/user_import_util.py b/ruoyi-fastapi-backend/utils/user_import_util.py
index a46e49f60..c545e4c5e 100644
--- a/ruoyi-fastapi-backend/utils/user_import_util.py
+++ b/ruoyi-fastapi-backend/utils/user_import_util.py
@@ -5,7 +5,10 @@
class UserImportUtil:
"""
- 用户导入格式注册与归一化工具类
+ 用户导入格式注册与归一化工具类。
+
+ :cvar HEADER_ALIASES: 导入表头到模型字段的别名映射
+ :cvar VALUE_ALIASES: 导入单元格文本到字段值的别名映射
"""
# 已发布模板的别名独立于当前启用语言,新增语言时追加别名,保留旧模板兼容性。
@@ -26,10 +29,12 @@ class UserImportUtil:
@classmethod
def normalize_headers(cls, headers: list[object]) -> list[str]:
"""
- 独立于界面语言识别已发布模板,拒绝歧义或缺失的必需列
+ 独立于界面语言识别已发布模板,拒绝歧义或缺失的必需列。
:param headers: 表格原始表头
:return: 对应的稳定字段名,额外列保留原名
+ :raises ValueError: 同一导入表头别名映射到多个字段
+ :raises ServiceException: 导入表头含重复列或缺少必需列
"""
aliases = {}
for field, names in cls.HEADER_ALIASES.items():
@@ -64,11 +69,12 @@ def normalize_headers(cls, headers: list[object]) -> list[str]:
@classmethod
def normalize_value(cls, field: str, value: object) -> str:
"""
- 将模板固定枚举名称或原始码值映射回稳定码值
+ 将模板固定枚举名称或原始码值映射回稳定码值。
:param field: 导入字段名
:param value: 单元格内容
:return: 稳定码值
+ :raises ServiceException: 导入字段的显示名称或枚举码值无效
"""
if isinstance(value, Real) and not isinstance(value, bool) and float(value).is_integer():
value = int(value)
diff --git a/ruoyi-fastapi-test/common/base_page_test.py b/ruoyi-fastapi-test/common/base_page_test.py
index e9631916d..ae5a76b00 100644
--- a/ruoyi-fastapi-test/common/base_page_test.py
+++ b/ruoyi-fastapi-test/common/base_page_test.py
@@ -6,24 +6,47 @@
class BasePageTest:
+ """
+ 为页面端到端测试提供通用的浏览器和登录操作。
+
+ :cvar harness: 为端到端测试管理资源的夹具
+ :cvar context: 当前操作所需的上下文
+ :cvar page: 浏览器页面或要查询的页码
+ :cvar token: 用于身份验证或授权的令牌
+ """
+
harness = None
context = None
page = None
token = None
async def setup(self, harness: BrowserHarness) -> None:
- """创建独立上下文,浏览器和诊断资源由会话 fixture 管理。"""
+ """
+ 创建独立上下文,浏览器和诊断资源由会话 fixture 管理。
+
+ :param harness: 复用会话浏览器,每个用例独立管理上下文及失败诊断
+ """
self.harness = harness
self.token = await harness.login()
self.context = await harness.new_context(token=self.token)
self.page = await self.context.new_page()
async def goto_page(self, url: str) -> None:
- """访问指定页面"""
+ """
+ 访问指定页面。
+
+ :param url: 当前请求的目标地址
+ """
await self.page.goto(url)
async def select_department(self, dialog: Locator, label: str, department: str) -> None:
- """兼容 Element Plus 树选择器与 Vue2 的 vue-treeselect。"""
+ """
+ 兼容 Element Plus 树选择器与 Vue2 的 vue-treeselect。
+
+ :param dialog: 测试正在操作的对话框
+ :param label: 显示给用户的标签
+ :param department: 测试操作对应的部门
+ """
field = dialog.locator('.el-form-item').filter(has_text=label)
await field.locator('.el-select__wrapper, .vue-treeselect__control').click()
choices = self.page.locator(
@@ -33,37 +56,70 @@ async def select_department(self, dialog: Locator, label: str, department: str)
await choices.filter(has_text=re.compile(rf'^\s*{re.escape(department)}(?:\s*\(\d+\))?\s*$')).click()
async def wait_for_page_title(self, title_text: str, timeout_ms: int = 10000) -> None:
- """等待页面标题出现"""
+ """
+ 等待页面标题出现。
+
+ :param title_text: 标题主体文本
+ :param timeout_ms: 等待超时的毫秒数
+ """
await self.page.wait_for_selector(f'div:has-text("{title_text}")', timeout=timeout_ms)
page_title = await self.page.inner_text(f'div:has-text("{title_text}")')
assert title_text in page_title
async def wait_for_selector(self, selector: str, timeout_ms: int = 10000) -> None:
- """等待选择器出现"""
+ """
+ 等待选择器出现。
+
+ :param selector: 定位页面元素的选择器
+ :param timeout_ms: 等待超时的毫秒数
+ """
await self.page.wait_for_selector(selector, timeout=timeout_ms)
async def query_selector(self, selector: str) -> any:
- """查询选择器元素"""
+ """
+ 查询选择器元素。
+
+ :param selector: 定位页面元素的选择器
+ :return: 选择器元素
+ """
return await self.page.query_selector(selector)
async def click_button(self, button_text: str) -> None:
- """点击按钮"""
+ """
+ 点击按钮。
+
+ :param button_text: 目标按钮显示的文字
+ """
button = await self.page.wait_for_selector(f'text="{button_text}"', timeout=5000)
await button.click()
async def fill_input(self, selector: str, value: str) -> None:
- """填充输入框"""
+ """
+ 填充输入框。
+
+ :param selector: 定位页面元素的选择器
+ :param value: 待处理的输入值
+ """
await self.page.fill(selector, value)
async def get_text_content(self, selector: str) -> str:
- """获取元素文本内容"""
+ """
+ 获取元素文本内容。
+
+ :param selector: 定位页面元素的选择器
+ :return: 元素文本内容
+ """
element = await self.page.query_selector(selector)
if element:
return await element.text_content()
return None
async def get_table_total_rows(self) -> int:
- """获取表格总行数"""
+ """
+ 获取表格总行数。
+
+ :return: 表格总行数
+ """
element = self.page.locator('span.el-pagination__total').first
text = await element.text_content()
diff --git a/ruoyi-fastapi-test/common/browser_harness.py b/ruoyi-fastapi-test/common/browser_harness.py
index 7e2eff09f..2225ab707 100644
--- a/ruoyi-fastapi-test/common/browser_harness.py
+++ b/ruoyi-fastapi-test/common/browser_harness.py
@@ -21,7 +21,14 @@
async def _wait_for_login_retry(response: APIResponse | Response, attempt: int, waited: int) -> int:
- """API 与表单登录共用同一等待预算,仅使用后端实际返回的秒数。"""
+ """
+ 为 API 和表单登录共用等待预算,使用后端返回的秒数。
+
+ :param response: 当前调用产生的响应
+ :param attempt: 当前尝试的次数
+ :param waited: 已经等待的时长
+ :return: 本次重试后累计等待的秒数
+ """
assert attempt + 1 < _LOGIN_MAX_ATTEMPTS, '登录 HTTP 429:已达到最大尝试次数'
retry_after = response.headers.get('retry-after', '').strip()
assert retry_after.isascii() and retry_after.isdecimal(), f'登录 HTTP 429:Retry-After 无效:{retry_after!r}'
@@ -32,7 +39,12 @@ async def _wait_for_login_retry(response: APIResponse | Response, attempt: int,
async def _login_token(response: APIResponse | Response) -> str:
- """非限流错误必须失败,成功响应必须携带有效令牌。"""
+ """
+ 非限流错误必须失败,成功响应必须携带有效令牌。
+
+ :param response: 当前调用产生的响应
+ :return: 用于身份验证或授权的令牌
+ """
assert response.ok, f'登录 HTTP 状态异常:{response.status}'
payload = await response.json()
token = payload.get('token') or (payload.get('data') or {}).get('token')
@@ -41,16 +53,39 @@ async def _login_token(response: APIResponse | Response) -> str:
def artifact_directory(root: Path, node_id: str) -> Path:
- """为每个用例生成稳定、无路径跳转且适合 Windows 的诊断目录。"""
+ """
+ 为每个用例生成稳定、无路径跳转且适合 Windows 的诊断目录。
+
+ :param root: 路径解析的基准目录
+ :param node_id: pytest 标识当前测试节点的字符串
+ :return: 当前用例的诊断产物目录
+ """
label = re.sub(r'[^a-zA-Z0-9_.-]+', '-', node_id).strip('-')[-80:] or 'test'
digest = hashlib.sha256(node_id.encode()).hexdigest()[:12]
return root / f'{label}-{digest}'
class BrowserHarness:
- """复用会话浏览器,每个用例独立管理上下文及失败诊断。"""
+ """
+ 复用会话浏览器,每个用例独立管理上下文及失败诊断。
+
+ :ivar playwright: 管理浏览器实例的 Playwright 对象
+ :ivar browser: 执行页面操作的浏览器实例
+ :ivar output: 命令或操作的输出
+ :ivar contexts: 当前测试创建的浏览器上下文
+ :ivar api_contexts: 当前测试使用的 API 请求上下文
+ :ivar events: 保存已发出事件的序列
+ :ivar token: 用于身份验证或授权的令牌
+ """
def __init__(self, playwright: Playwright, browser: Browser, output: Path) -> None:
+ """
+ 保存浏览器实例、测试产物目录和事件记录。
+
+ :param playwright: 管理浏览器实例的 Playwright 对象
+ :param browser: 执行页面操作的浏览器实例
+ :param output: 命令或操作的输出
+ """
self.playwright = playwright
self.browser = browser
self.output = output
@@ -60,7 +95,12 @@ def __init__(self, playwright: Playwright, browser: Browser, output: Path) -> No
self.token: str | None = None
async def api_context(self, token: str | None = None) -> APIRequestContext:
- """创建随用例回收的 API 客户端。"""
+ """
+ 创建随用例回收的 API 客户端。
+
+ :param token: 用于身份验证或授权的令牌
+ :return: 随用例回收的 API 客户端
+ """
# UI 操作之间可能长于后端的 keep-alive 超时。直连 API 的测试请求各自关闭连接。
headers = {'Connection': 'close'}
if token:
@@ -74,7 +114,11 @@ async def api_context(self, token: str | None = None) -> APIRequestContext:
return context
async def login(self) -> str:
- """用例内复用令牌;429 最多重试两次,总等待不超过 60 秒。"""
+ """
+ 用例内复用令牌;429 最多重试两次,总等待不超过 60 秒。
+
+ :return: 用于身份验证或授权的令牌
+ """
if self.token:
return self.token
api = await self.api_context()
@@ -89,7 +133,14 @@ async def login(self) -> str:
return self.token
async def login_through_page(self, page: Page, username: str = 'admin', password: str = 'admin123') -> str:
- """真实填写并提交登录表单,仅对 429 有界重试,不替换夹具的管理员令牌。"""
+ """
+ 真实填写并提交登录表单,仅对 429 有界重试,不替换夹具的管理员令牌。
+
+ :param page: 浏览器页面或要查询的页码
+ :param username: 登录账号名称
+ :param password: 认证使用的密码
+ :return: 用于身份验证或授权的令牌
+ """
await page.get_by_placeholder('账号').fill(username)
await page.get_by_placeholder('密码').fill(password)
waited = 0
@@ -108,7 +159,13 @@ async def login_through_page(self, page: Page, username: str = 'admin', password
return token
async def new_context(self, *, token: str | None = None, **options) -> BrowserContext:
- """每次调用均创建隔离上下文,不继承前一用例 Cookie 或本地存储。"""
+ """
+ 每次调用均创建隔离上下文,不继承前一用例 Cookie 或本地存储。
+
+ :param token: 用于身份验证或授权的令牌
+ :param options: 调用方按名称传入的附加选项
+ :return: 当前操作所需的上下文
+ """
context = await self.browser.new_context(
**{'base_url': Config.frontend_url, 'viewport': {'width': 1440, 'height': 1000}, **options}
)
@@ -124,12 +181,23 @@ async def new_context(self, *, token: str | None = None, **options) -> BrowserCo
return context
async def new_page(self, *, authenticated: bool = False, **options) -> Page:
- """创建可选已认证页面。"""
+ """
+ 创建可选已认证页面。
+
+ :param authenticated: 是否以登录状态打开页面
+ :param options: 调用方按名称传入的附加选项
+ :return: 可选已认证页面
+ """
token = await self.login() if authenticated else None
context = await self.new_context(token=token, **options)
return await context.new_page()
def _record_page(self, page: Page) -> None:
+ """
+ 为新页面注册浏览器事件采集。
+
+ :param page: 浏览器页面或要查询的页码
+ """
page.on('pageerror', lambda error: self.events.append({'kind': 'pageerror', 'message': str(error)}))
page.on(
'console',
@@ -141,6 +209,13 @@ def _record_page(self, page: Page) -> None:
)
async def _save_screenshot(self, page: Page, context_index: int, page_index: int) -> None:
+ """
+ 保存浏览器页面截图用于诊断测试失败。
+
+ :param page: 浏览器页面或要查询的页码
+ :param context_index: 要操作的浏览器上下文索引
+ :param page_index: 目标页面在上下文中的索引
+ """
if page.is_closed():
return
try:
@@ -153,6 +228,13 @@ async def _save_screenshot(self, page: Page, context_index: int, page_index: int
self.events.append({'kind': 'screenshot-error', 'message': str(exc)})
async def _finish_context(self, context: BrowserContext, index: int, *, failed: bool) -> None:
+ """
+ 结束浏览器上下文并收集测试产物。
+
+ :param context: 当前操作所需的上下文
+ :param index: 当前条目在序列中的位置
+ :param failed: 当前尝试是否失败
+ """
try:
if failed:
for page_index, page in enumerate(context.pages):
@@ -169,13 +251,22 @@ async def _finish_context(self, context: BrowserContext, index: int, *, failed:
self.events.append({'kind': 'context-close-error', 'message': str(exc)})
async def _dispose_api(self, api: APIRequestContext) -> None:
+ """
+ 释放浏览器测试使用的 API 请求上下文。
+
+ :param api: 发起 API 请求的客户端
+ """
try:
await api.dispose()
except Exception as exc:
self.events.append({'kind': 'api-dispose-error', 'message': str(exc)})
async def finish(self, *, failed: bool) -> None:
- """失败时保留页面截图、trace 和控制台日志,再回收全部上下文。"""
+ """
+ 失败时保留页面截图、trace 和控制台日志,再回收全部上下文。
+
+ :param failed: 当前尝试是否失败
+ """
if failed:
await asyncio.to_thread(self.output.mkdir, parents=True, exist_ok=True)
for index, context in enumerate(self.contexts):
diff --git a/ruoyi-fastapi-test/common/config.py b/ruoyi-fastapi-test/common/config.py
index 09e885a49..c11349758 100644
--- a/ruoyi-fastapi-test/common/config.py
+++ b/ruoyi-fastapi-test/common/config.py
@@ -2,6 +2,16 @@
class Config:
+ """
+ 保存端到端测试使用的环境配置。
+
+ :cvar frontend_url: 被测前端服务的根地址
+ :cvar backend_url: 被测后端服务的根地址
+ :cvar browser_channel: 启动浏览器时使用的发行通道
+ :cvar swagger_disabled: 是否停用了 Swagger UI
+ :cvar frontend_framework: 用于生成或构建前端的框架
+ """
+
frontend_url = os.environ.get('TEST_FRONTEND_URL', 'http://localhost:80')
backend_url = os.environ.get('TEST_BACKEND_URL', 'http://localhost:9099')
browser_channel = os.environ.get('TEST_BROWSER_CHANNEL') or None
diff --git a/ruoyi-fastapi-test/common/login_helper.py b/ruoyi-fastapi-test/common/login_helper.py
index 9a0b48be3..6b6b8f1a1 100644
--- a/ruoyi-fastapi-test/common/login_helper.py
+++ b/ruoyi-fastapi-test/common/login_helper.py
@@ -5,16 +5,29 @@
class LoginHelper:
"""
- 登录辅助类
+ 登录辅助类。
+
+ :ivar base_url: 基础URL
+ :ivar session: 当前操作共用的会话
"""
def __init__(self, base_url: str = Config.frontend_url) -> None:
+ """
+ 为目标站点创建登录测试使用的 HTTP 会话。
+
+ :param base_url: 基础URL
+ """
self.base_url = base_url
self.session = requests.Session()
def login(self, username: str = 'admin', password: str = 'admin123', max_retries: int = 3) -> str | None:
"""
- 执行登录操作(在测试环境中,验证码已禁用)
+ 执行登录操作(在测试环境中,验证码已禁用)。
+
+ :param username: 登录账号名称
+ :param password: 认证使用的密码
+ :param max_retries: 允许重试的最大次数
+ :return: 用于身份验证或授权的令牌
"""
for _attempt in range(max_retries):
# 在测试环境中,验证码已禁用,所以直接登录
diff --git a/ruoyi-fastapi-test/common/page_catalog.py b/ruoyi-fastapi-test/common/page_catalog.py
index b1785f705..b294d07f1 100644
--- a/ruoyi-fastapi-test/common/page_catalog.py
+++ b/ruoyi-fastapi-test/common/page_catalog.py
@@ -3,7 +3,15 @@
@dataclass(frozen=True)
class PageCase:
- """三套 Web 工程共有的内置菜单、实际页面内容与首屏业务请求。"""
+ """
+ 三套 Web 工程共有的内置菜单、实际页面内容与首屏业务请求。
+
+ :ivar path: 要读取或处理的路径
+ :ivar title: 当前界面或记录显示的标题
+ :ivar content: 需要读取或写入的内容
+ :ivar api: 发起 API 请求的客户端
+ :ivar selector: 定位页面元素的选择器
+ """
path: str
title: str
@@ -12,7 +20,12 @@ class PageCase:
selector: str = '.el-table'
def selector_for(self, framework: str) -> str:
- """按组件库选择实际业务内容,保持页面与接口覆盖相同。"""
+ """
+ 按组件库选择实际业务内容,保持页面与接口覆盖相同。
+
+ :param framework: 目标前端框架
+ :return: 当前组件库对应的内容选择器
+ """
if framework != 'react':
return self.selector
overrides = {
diff --git a/ruoyi-fastapi-test/common/ui.py b/ruoyi-fastapi-test/common/ui.py
index ef5a64ec5..12f47be77 100644
--- a/ruoyi-fastapi-test/common/ui.py
+++ b/ruoyi-fastapi-test/common/ui.py
@@ -2,6 +2,11 @@
def button_name(label: str) -> re.Pattern[str]:
- """保留 Vue 字体图标前缀,同时兼容 Ant Design 双字按钮插入的空格。"""
+ """
+ 保留 Vue 字体图标前缀,同时兼容 Ant Design 双字按钮插入的空格。
+
+ :param label: 显示给用户的标签
+ :return: 可匹配实际按钮文本的名称模式
+ """
text = r'\s*'.join(re.escape(character) for character in label)
return re.compile(rf'{text}\s*$')
diff --git a/ruoyi-fastapi-test/conftest.py b/ruoyi-fastapi-test/conftest.py
index 000c705b1..ba6a1e63b 100644
--- a/ruoyi-fastapi-test/conftest.py
+++ b/ruoyi-fastapi-test/conftest.py
@@ -21,7 +21,13 @@
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item: pytest.Item, call: pytest.CallInfo) -> Generator:
- """在浏览器 fixture 回收前保存调用结果,确保断言失败仍能导出诊断。"""
+ """
+ 在浏览器 fixture 回收前保存调用结果,确保断言失败仍能导出诊断。
+
+ :param item: 当前要处理的条目
+ :param call: 需要执行或验证的调用
+ :yield: 上下文就绪后将控制权交给调用方
+ """
result = yield
report = result.get_result()
setattr(item, f'rep_{report.when}', report)
@@ -29,7 +35,11 @@ def pytest_runtest_makereport(item: pytest.Item, call: pytest.CallInfo) -> Gener
@pytest_asyncio.fixture(scope='session', loop_scope='session')
async def e2e_browser() -> AsyncIterator[tuple[Playwright, Browser]]:
- """一次 pytest 会话只启动一个 Chromium 进程。"""
+ """
+ 一次 pytest 会话只启动一个 Chromium 进程。
+
+ :yield: 依次为 ``playwright``、``browser`` 的元组
+ """
async with async_playwright() as playwright:
browser = await playwright.chromium.launch(
headless=True,
@@ -46,7 +56,13 @@ async def e2e_browser() -> AsyncIterator[tuple[Playwright, Browser]]:
async def browser_harness(
e2e_browser: tuple[Playwright, Browser], request: pytest.FixtureRequest
) -> AsyncIterator[BrowserHarness]:
- """每个用例有自己的上下文、诊断目录和 API 客户端。"""
+ """
+ 每个用例有自己的上下文、诊断目录和 API 客户端。
+
+ :param e2e_browser: 执行端到端流程的浏览器
+ :param request: pytest 当前用例的请求上下文
+ :yield: 为端到端测试管理资源的夹具
+ """
harness = BrowserHarness(*e2e_browser, artifact_directory(E2E_OUTPUT_ROOT, request.node.nodeid))
try:
yield harness
diff --git a/ruoyi-fastapi-test/monitor/test_job_management.py b/ruoyi-fastapi-test/monitor/test_job_management.py
index 024f0e1ae..ec35eb1c5 100644
--- a/ruoyi-fastapi-test/monitor/test_job_management.py
+++ b/ruoyi-fastapi-test/monitor/test_job_management.py
@@ -18,15 +18,30 @@
class JobManagementTest(SystemPage):
- """通过真实界面验证任务配置、异步同步和手动执行。"""
+ """
+ 通过真实界面验证任务配置、异步同步和手动执行。
+
+ :cvar job_id: 任务ID
+ """
job_id: int | None = None
def job_row(self, job_name: str) -> Locator:
+ """
+ 定位指定名称的调度任务行。
+
+ :param job_name: 任务名称过滤条件
+ :return: 匹配指定任务名称的行定位器
+ """
return self.row(job_name)
def job_actions(self, job_name: str) -> Locator:
- """Element UI 固定列有隐藏副本,仅返回操作列中实际可见的按钮。"""
+ """
+ Element UI 固定列有隐藏副本,仅返回操作列中实际可见的按钮。
+
+ :param job_name: 任务名称过滤条件
+ :return: 当前任务行可点击的操作控件
+ """
rows = self.page.locator('.app-container:visible > .el-table tbody tr').filter(
has=self.page.get_by_text(job_name, exact=True)
)
@@ -35,7 +50,14 @@ def job_actions(self, job_name: str) -> Locator:
return rows.locator('td:last-child').get_by_role('button')
async def submit(self, action: Callable[[], Awaitable], method: str, path: str) -> dict:
- """等待本次操作的响应,不依赖短暂提示或固定延时。"""
+ """
+ 等待本次操作的响应,不依赖短暂提示或固定延时。
+
+ :param action: 当前要记录或执行的动作
+ :param method: 当前请求的 HTTP 方法
+ :param path: 要读取或处理的路径
+ :return: 提交成功后响应中的业务数据
+ """
async with self.page.expect_response(
lambda response: response.request.method == method and urlparse(response.url).path.endswith(path)
) as response_info:
@@ -47,7 +69,14 @@ async def submit(self, action: Callable[[], Awaitable], method: str, path: str)
return payload['data']
async def poll_api(self, path: str, ready: Callable[[dict], bool], **params) -> dict:
- """轮询异步结果,超时时保留最后一次响应以便诊断。"""
+ """
+ 轮询异步结果,超时时保留最后一次响应以便诊断。
+
+ :param path: 要读取或处理的路径
+ :param ready: 依赖检查是否已就绪
+ :param params: 调用方按名称传入的附加选项
+ :return: 随调用传入或返回的结构化数据
+ """
deadline = monotonic() + 30
while True:
response = await self.context.request.get(
@@ -64,7 +93,11 @@ async def poll_api(self, path: str, ready: Callable[[dict], bool], **params) ->
await asyncio.sleep(0.25)
async def wait_for_sync(self, mutation: dict) -> None:
- """已保存后,还要确认本次配置版本已由调度器应用。"""
+ """
+ 已保存后,还要确认本次配置版本已由调度器应用。
+
+ :param mutation: 应用到初始状态的修改
+ """
assert mutation['saved'] is True, mutation
assert len(mutation['jobs']) == 1, mutation
changed = mutation['jobs'][0]
@@ -81,6 +114,11 @@ async def wait_for_sync(self, mutation: dict) -> None:
)
async def search_job(self, job_name: str) -> None:
+ """
+ 在管理页面按任务名称筛选列表。
+
+ :param job_name: 任务名称过滤条件
+ """
form = self.page.locator('form').first
await form.get_by_placeholder('请输入任务名称', exact=True).fill(job_name)
async with self.page.expect_response(
@@ -98,6 +136,11 @@ async def search_job(self, job_name: str) -> None:
)
async def create_job(self, job_name: str) -> None:
+ """
+ 通过管理页面创建调度任务。
+
+ :param job_name: 任务名称过滤条件
+ """
await self.page.get_by_role('button', name=button_name('新增')).click()
dialog = self.page.get_by_role('dialog', name='添加任务', exact=True)
await (
@@ -123,6 +166,12 @@ async def create_job(self, job_name: str) -> None:
await expect(self.job_row(job_name)).to_have_count(1)
async def edit_job(self, job_name: str, new_job_name: str) -> None:
+ """
+ 通过管理页面修改调度任务。
+
+ :param job_name: 任务名称过滤条件
+ :param new_job_name: 新建定时任务的名称
+ """
# 同步状态列也包含按钮,操作按钮仅在最后一列定位。
await self.job_actions(job_name).nth(0).click()
dialog = self.page.get_by_role('dialog', name='修改任务', exact=True)
@@ -141,6 +190,12 @@ async def edit_job(self, job_name: str, new_job_name: str) -> None:
await expect(self.job_row(new_job_name)).to_have_count(1)
async def toggle_job_status(self, job_name: str, enabled: bool) -> None:
+ """
+ 通过管理页面切换调度任务状态。
+
+ :param job_name: 任务名称过滤条件
+ :param enabled: 是否启用该项功能
+ """
switch = self.job_row(job_name).locator('.ant-switch' if self.is_react else '.el-switch')
await switch.click()
action = '启用' if enabled else '暂停|停用'
@@ -158,6 +213,12 @@ async def toggle_job_status(self, job_name: str, enabled: bool) -> None:
await expect(switch).not_to_have_class(re.compile(r'is-checked|ant-switch-checked'))
async def run_job_once(self, job_name: str) -> str:
+ """
+ 通过管理页面手动执行一次调度任务。
+
+ :param job_name: 任务名称过滤条件
+ :return: 供调用方使用的 ``execution_id``
+ """
direct_run = (
self.button(self.job_row(job_name), '执行一次')
if self.is_react
@@ -196,6 +257,12 @@ async def run_job_once(self, job_name: str) -> str:
return execution_id
async def view_job_log(self, job_name: str, execution_id: str) -> None:
+ """
+ 打开并校验指定执行记录的任务日志。
+
+ :param job_name: 任务名称过滤条件
+ :param execution_id: 执行ID
+ """
# 执行状态和日志分别落库,先等待本次执行的日志出现。
await self.poll_api('/monitor/jobLog/list', lambda payload: len(payload['rows']) == 1, executionId=execution_id)
direct_log = self.job_actions(job_name).nth(3)
@@ -221,6 +288,11 @@ async def view_job_log(self, job_name: str, execution_id: str) -> None:
await self.page.wait_for_url('**/monitor/job')
async def delete_job(self, job_name: str) -> None:
+ """
+ 通过管理页面搜索并删除调度任务。
+
+ :param job_name: 任务名称过滤条件
+ """
await self.search_job(job_name)
await self.job_actions(job_name).nth(1).click()
confirm = self.page.get_by_role('dialog').get_by_role('button', name=button_name('确定'))
@@ -241,6 +313,7 @@ async def cleanup_job(self) -> None:
assert (await response.json())['code'] == HTTPStatus.OK
async def test_job_crud_operations(self) -> None:
+ """验证调度任务的增删改查。"""
job_name = f'测试任务_{uuid4().hex[:12]}'
edited_name = job_name + '_edit'
await self.goto_page(Config.frontend_url + '/monitor/job')
diff --git a/ruoyi-fastapi-test/monitor/test_transport_crypto.py b/ruoyi-fastapi-test/monitor/test_transport_crypto.py
index 63029b44d..aee0da9df 100644
--- a/ruoyi-fastapi-test/monitor/test_transport_crypto.py
+++ b/ruoyi-fastapi-test/monitor/test_transport_crypto.py
@@ -13,7 +13,12 @@
async def assert_monitor_snapshot(page: Page, payload: dict) -> None:
- """核对同一响应中的启用状态、计数及环境配置。"""
+ """
+ 核对同一响应中的启用状态、计数及环境配置。
+
+ :param page: 浏览器页面或要查询的页码
+ :param payload: 随调用传入或返回的结构化数据
+ """
assert payload['code'] == HTTPStatus.OK, payload
data = payload['data']
cards = page.locator('.summary-card, .crypto-summary')
diff --git a/ruoyi-fastapi-test/prepare_e2e_compose.py b/ruoyi-fastapi-test/prepare_e2e_compose.py
index c6467899c..575c15e72 100644
--- a/ruoyi-fastapi-test/prepare_e2e_compose.py
+++ b/ruoyi-fastapi-test/prepare_e2e_compose.py
@@ -10,7 +10,15 @@
def isolate_compose(config: dict, project: str, python_version: str) -> dict:
- """从已解析的测试配置生成独立项目,保留应用和数据库的真实配置。"""
+ """
+ 从已解析的测试配置生成独立项目,保留应用和数据库的真实配置。
+
+ :param config: 当前对象使用的配置
+ :param project: 选中的项目或工作目录
+ :param python_version: 当前 Python 版本
+ :raises ValueError: 测试项目名必须以 ruoyi-ci- 开头且仅包含小写字母、数字、下划线或连字符
+ :return: 当前对象使用的配置
+ """
if not re.fullmatch(r'ruoyi-ci-[a-z0-9][a-z0-9_-]*', project):
raise ValueError('测试项目名必须以 ruoyi-ci- 开头且仅包含小写字母、数字、下划线或连字符')
config = copy.deepcopy(config)
@@ -76,6 +84,7 @@ def isolate_compose(config: dict, project: str, python_version: str) -> dict:
def main() -> None:
+ """生成 CI 专用的独立 Compose 配置。"""
parser = argparse.ArgumentParser(description='生成 CI 专用的独立 Compose 项目,不修改开发配置。')
parser.add_argument('--database', choices=['mysql', 'postgresql'], required=True)
parser.add_argument('--framework', choices=['vue2', 'vue3', 'react'], required=True)
diff --git a/ruoyi-fastapi-test/ruff.toml b/ruoyi-fastapi-test/ruff.toml
index 5d6399b8c..7d0ab2b85 100644
--- a/ruoyi-fastapi-test/ruff.toml
+++ b/ruoyi-fastapi-test/ruff.toml
@@ -12,6 +12,8 @@ select = [
"A", # flake8-builtins
"COM", # flake8-commas
"C4", # flake8-comprehensions
+ "D", # pydocstyle
+ "D213", # 多行文档字符串的摘要从第二行开始
"ISC", # flake8-implicit-str-concat
"ICN", # flake8-import-conventions
"PIE", # flake8-pie
@@ -37,6 +39,9 @@ ignore = [
"ANN401", # dynamically typed expressions (typing.Any) are disallowed in {name}
"B008", # do not perform function calls in argument defaults
"COM812", # trailing comma missing
+ "D100", # dev lint forbids module docstrings
+ "D104", # the same file-header rule applies to packages
+ "D400", # dev lint checks terminal punctuation in both Chinese and English
"RET504", # unnecessary assignment to {name} before return statement
"SIM105", # use contextlib.suppress({exception}) instead of try-except-pass
"C901", # too complex
@@ -55,6 +60,10 @@ runtime-evaluated-base-classes = ["pydantic.BaseModel", "sqlalchemy.orm.Declarat
[lint.isort]
known-third-party = ["alembic"]
+[lint.pydocstyle]
+# Use general layout rules; parameters and return values use reST fields.
+convention = "pep257"
+
[lint.pylint]
max-args = 10
max-returns = 10
@@ -65,4 +74,4 @@ keep-runtime-typing = true
[format]
docstring-code-format = true
-quote-style = "single"
\ No newline at end of file
+quote-style = "single"
diff --git a/ruoyi-fastapi-test/system/page.py b/ruoyi-fastapi-test/system/page.py
index 87e1f109a..c178c90b5 100644
--- a/ruoyi-fastapi-test/system/page.py
+++ b/ruoyi-fastapi-test/system/page.py
@@ -20,35 +20,60 @@
class SystemPage(BasePageTest):
- """通过真实界面操作与真实接口结果同步系统管理测试。"""
+ """
+ 通过真实界面操作与真实接口结果同步系统管理测试。
+
+ :ivar api: 发起 API 请求的客户端
+ :ivar list_path: 显示记录列表的页面路径
+ """
api: APIRequestContext
list_path: str
@property
def is_react(self) -> bool:
- """根据本轮框架使用真实组件选择器,不改变业务断言。"""
+ """
+ 根据本轮框架使用真实组件选择器,不改变业务断言。
+
+ :return: 是否根据本轮框架使用真实组件选择器
+ """
return Config.frontend_framework == 'react'
async def setup(self, harness: BrowserHarness) -> None:
- """复用浏览器登录,并保留仅用于持久化核验和失败清理的 API 客户端。"""
+ """
+ 复用浏览器登录,并保留仅用于持久化核验和失败清理的 API 客户端。
+
+ :param harness: 复用会话浏览器,每个用例独立管理上下文及失败诊断
+ """
await super().setup(harness)
self.api = await harness.api_context(self.token)
@property
def form(self) -> Locator:
- """当前页面可见的查询表单。"""
+ """
+ 当前页面可见的查询表单。
+
+ :return: 供调用方使用的 ``self.page.locator(f'.app-main .app-container {selector}:visible').first``
+ """
selector = '.ant-form' if self.is_react else '.el-form'
return self.page.locator(f'.app-main .app-container {selector}:visible').first
@property
def dialog(self) -> Locator:
- """当前组件库的可见编辑弹窗。"""
+ """
+ 当前组件库的可见编辑弹窗。
+
+ :return: 当前可见的编辑弹窗定位器
+ """
return self.page.locator('.ant-modal:visible' if self.is_react else '.el-dialog:visible')
@property
def rows(self) -> Locator:
- """主表格数据行,不重复计算 Element UI 固定列的镜像表格。"""
+ """
+ 主表格数据行,不重复计算 Element UI 固定列的镜像表格。
+
+ :return: 主表格中的数据行定位器
+ """
selector = (
'.app-main .ant-table-tbody > .ant-table-row:visible'
if self.is_react
@@ -57,17 +82,34 @@ def rows(self) -> Locator:
return self.page.locator(selector)
def row(self, identity: str) -> Locator:
- """按当前测试记录的精确文本定位,避免误操作列表第一条业务数据。"""
+ """
+ 按当前测试记录的精确文本定位,避免误操作列表第一条业务数据。
+
+ :param identity: 用于请求的身份信息
+ :return: 精确匹配测试记录的数据行定位器
+ """
return self.rows.filter(has=self.page.get_by_text(identity, exact=True))
@staticmethod
def button(scope: Locator | Page, label: str) -> Locator:
- """图标字体可能进入 Vue2 可访问名称,因此按完整文字后缀匹配。"""
+ """
+ 图标字体可能进入 Vue2 可访问名称,因此按完整文字后缀匹配。
+
+ :param scope: 当前操作使用的作用域
+ :param label: 显示给用户的标签
+ :return: 按可访问名称匹配的按钮定位器
+ """
# Ant Design 的双字按钮可能在两字之间加入空格。
return scope.get_by_role('button', name=button_name(label))
def field(self, scope: Locator, label: str) -> Locator:
- """两种组件库都按真实表单标签定位,不依赖 Vue3 自动生成的 input id。"""
+ """
+ 两种组件库都按真实表单标签定位,不依赖 Vue3 自动生成的 input id。
+
+ :param scope: 当前操作使用的作用域
+ :param label: 显示给用户的标签
+ :return: 给定表单标签对应的字段定位器
+ """
suffix = r'(?: · 原文:简体中文)?' if self.is_react and label in {'菜单名称', '字典名称', '数据标签'} else ''
label_selector = '.ant-form-item-label' if self.is_react else '.el-form-item__label'
field_selector = '.ant-form-item' if self.is_react else '.el-form-item'
@@ -77,11 +119,23 @@ def field(self, scope: Locator, label: str) -> Locator:
return scope.locator(f'{field_selector}:visible').filter(has=labels)
def input(self, scope: Locator, label: str) -> Locator:
- """返回字段内的文本、密码或数字输入框。"""
+ """
+ 返回字段内的文本、密码或数字输入框。
+
+ :param scope: 当前操作使用的作用域
+ :param label: 显示给用户的标签
+ :return: 字段内的文本、密码或数字输入框
+ """
return self.field(scope, label).locator('input:not([type=radio]):not([type=checkbox]), textarea').first
async def open_translation_input(self, scope: Locator, source_label: str) -> Locator:
- """展开当前表单的译名区域,按可访问名称定位英文输入框。"""
+ """
+ 展开当前表单的译名区域,按可访问名称定位英文输入框。
+
+ :param scope: 当前操作使用的作用域
+ :param source_label: 在界面中显示的数据来源标签
+ :return: 展开后的英文译名输入框定位器
+ """
fields = scope.locator('.translation-fields')
toggle = fields.locator('button[aria-expanded]')
if await toggle.get_attribute('aria-expanded') == 'false':
@@ -94,11 +148,23 @@ async def open_translation_input(self, scope: Locator, source_label: str) -> Loc
return fields.get_by_role('textbox', name=label, exact=True)
async def fill(self, scope: Locator, label: str, value: str) -> None:
- """填写真实输入控件,触发框架正常的输入事件。"""
+ """
+ 填写真实输入控件,触发框架正常的输入事件。
+
+ :param scope: 当前操作使用的作用域
+ :param label: 显示给用户的标签
+ :param value: 待处理的输入值
+ """
await self.input(scope, label).fill(value)
async def choose(self, scope: Locator, label: str, option: str) -> None:
- """选择两种 Element 组件库中的下拉选项。"""
+ """
+ 选择两种 Element 组件库中的下拉选项。
+
+ :param scope: 当前操作使用的作用域
+ :param label: 显示给用户的标签
+ :param option: 当前选择或待选择的选项
+ """
await self.field(scope, label).locator('.ant-select' if self.is_react else '.el-select').click()
selector = (
'.ant-select-dropdown:visible .ant-select-item-option'
@@ -109,7 +175,13 @@ async def choose(self, scope: Locator, label: str, option: str) -> None:
await choices.click()
async def radio(self, scope: Locator, label: str, option: str) -> None:
- """选择并核对单选项。"""
+ """
+ 选择并核对单选项。
+
+ :param scope: 当前操作使用的作用域
+ :param label: 显示给用户的标签
+ :param option: 当前选择或待选择的选项
+ """
choice = (
self.field(scope, label)
.locator('.ant-radio-wrapper' if self.is_react else '.el-radio')
@@ -119,7 +191,13 @@ async def radio(self, scope: Locator, label: str, option: str) -> None:
await expect(choice.locator('input[type=radio]')).to_be_checked()
async def choose_department(self, scope: Locator, label: str, department: str) -> None:
- """覆盖 Element、vue-treeselect 和 Ant Design 的真实树节点。"""
+ """
+ 覆盖 Element、vue-treeselect 和 Ant Design 的真实树节点。
+
+ :param scope: 当前操作使用的作用域
+ :param label: 显示给用户的标签
+ :param department: 测试操作对应的部门
+ """
if self.is_react:
await self.field(scope, label).locator('.ant-select').click()
await (
@@ -137,19 +215,38 @@ async def choose_department(self, scope: Locator, label: str, department: str) -
@staticmethod
def matches(response: Response, path: str, method: str) -> bool:
- """同时匹配请求方法和 API 路径,兼容两套开发代理前缀。"""
+ """
+ 同时匹配请求方法和 API 路径,兼容两套开发代理前缀。
+
+ :param response: 当前调用产生的响应
+ :param path: 要读取或处理的路径
+ :param method: 当前请求的 HTTP 方法
+ :return: 是否同时匹配请求方法和 API 路径
+ """
return response.request.method == method and urlsplit(response.url).path.rstrip('/').endswith(path)
@staticmethod
async def payload(response: Response) -> dict:
- """HTTP 与应用状态都必须成功,不让 200 包装的业务错误通过测试。"""
+ """
+ HTTP 与应用状态都必须成功,不让 200 包装的业务错误通过测试。
+
+ :param response: 当前调用产生的响应
+ :return: 随调用传入或返回的结构化数据
+ """
assert response.ok, f'{response.request.method} {response.url}: HTTP {response.status}'
payload = await response.json()
assert payload.get('code') == HTTPStatus.OK, f'{response.url}: {payload}'
return payload
async def action(self, trigger: Callable[[], Awaitable[None]], path: str, method: str = 'GET') -> dict:
- """先监听目标响应,再执行点击,避免固定睡眠和遗漏快速响应。"""
+ """
+ 先监听目标响应,再执行点击,避免固定睡眠和遗漏快速响应。
+
+ :param trigger: 计算任务下次执行时间的触发器
+ :param path: 要读取或处理的路径
+ :param method: 当前请求的 HTTP 方法
+ :return: 本次点击触发的接口响应
+ """
async with self.page.expect_response(lambda response: self.matches(response, path, method)) as response_info:
await trigger()
return await self.payload(await response_info.value)
@@ -164,14 +261,25 @@ async def rendered(self) -> None:
await expect(self.page.locator(f'.app-main {table}:visible').first).to_be_visible()
async def open(self, route: str, list_path: str) -> dict:
- """打开真实管理页面并核对首个列表响应。"""
+ """
+ 打开真实管理页面并核对首个列表响应。
+
+ :param route: 当前请求匹配的路由
+ :param list_path: 显示记录列表的页面路径
+ :return: 随调用传入或返回的结构化数据
+ """
self.list_path = list_path
payload = await self.action(lambda: self.page.goto(Config.frontend_url + route), list_path)
await self.rendered()
return payload
async def search(self, fields: dict[str, str] | None = None) -> dict:
- """按界面查询并返回真实响应。"""
+ """
+ 按界面查询并返回真实响应。
+
+ :param fields: 当前场景涉及的字段
+ :return: 真实响应
+ """
await self.rendered()
for label, value in (fields or {}).items():
await self.fill(self.form, label, value)
@@ -180,13 +288,21 @@ async def search(self, fields: dict[str, str] | None = None) -> dict:
return payload
async def reset(self) -> dict:
- """通过重置按钮恢复查询条件。"""
+ """
+ 通过重置按钮恢复查询条件。
+
+ :return: 随调用传入或返回的结构化数据
+ """
payload = await self.action(self.button(self.form, '重置').click, self.list_path)
await self.rendered()
return payload
async def add(self) -> Locator:
- """打开新增弹窗。"""
+ """
+ 打开新增弹窗。
+
+ :return: 测试正在操作的对话框
+ """
await self.button(self.page, '新增').first.click()
await expect(self.dialog).to_be_visible()
return self.dialog
@@ -197,13 +313,26 @@ async def close_dialog(self) -> None:
await expect(self.dialog).to_have_count(0)
async def edit(self, identity: str, resource: str, record_id: int) -> Locator:
- """从目标记录打开编辑弹窗,并等待详情加载。"""
+ """
+ 从目标记录打开编辑弹窗,并等待详情加载。
+
+ :param identity: 用于请求的身份信息
+ :param resource: 当前授权或管理的资源
+ :param record_id: 要查询或修改的记录标识
+ :return: 测试正在操作的对话框
+ """
await self.action(lambda: self.row_action(identity, '修改'), f'{resource}/{record_id}')
await expect(self.dialog).to_be_visible()
return self.dialog
async def save(self, resource: str, method: str) -> dict:
- """保存表单,要求写请求、列表刷新和弹窗关闭全部完成。"""
+ """
+ 保存表单,要求写请求、列表刷新和弹窗关闭全部完成。
+
+ :param resource: 当前授权或管理的资源
+ :param method: 当前请求的 HTTP 方法
+ :return: 随调用传入或返回的结构化数据
+ """
dialog = self.dialog
async with self.page.expect_response(lambda response: self.matches(response, self.list_path, 'GET')) as listed:
await self.action(self.button(dialog, '确定').click, resource, method)
@@ -213,14 +342,26 @@ async def save(self, resource: str, method: str) -> dict:
return payload
async def delete(self, identity: str, resource: str, record_id: int) -> dict:
- """删除本用例创建的目标行,并核对其消失。"""
+ """
+ 删除本用例创建的目标行,并核对其消失。
+
+ :param identity: 用于请求的身份信息
+ :param resource: 当前授权或管理的资源
+ :param record_id: 要查询或修改的记录标识
+ :return: 随调用传入或返回的结构化数据
+ """
await self.row_action(identity, '删除')
payload = await self.confirm_refresh(f'{resource}/{record_id}')
await expect(self.row(identity)).to_have_count(0)
return payload
async def row_action(self, identity: str, action: str) -> None:
- """兼容 Vue2 文本/更多菜单和 Vue3 用户角色页的图标按钮。"""
+ """
+ 兼容 Vue2 文本/更多菜单和 Vue3 用户角色页的图标按钮。
+
+ :param identity: 用于请求的身份信息
+ :param action: 当前要记录或执行的动作
+ """
row = self.row(identity)
named = self.button(row, action)
if await named.count():
@@ -244,7 +385,13 @@ async def row_action(self, identity: str, action: str) -> None:
await row.get_by_role('button').nth(positions[action]).click()
async def toggle_status(self, identity: str, resource: str, record_id: int) -> None:
- """停用再启用,并逐次重读保存状态,不依赖成功 toast。"""
+ """
+ 停用再启用,并逐次重读保存状态,不依赖成功 toast。
+
+ :param identity: 用于请求的身份信息
+ :param resource: 当前授权或管理的资源
+ :param record_id: 要查询或修改的记录标识
+ """
for status in ('1', '0'):
await self.row(identity).locator('.ant-switch' if self.is_react else '.el-switch').click()
confirmation = self.page.locator(
@@ -259,7 +406,13 @@ async def toggle_status(self, identity: str, resource: str, record_id: int) -> N
await self.persisted(resource, record_id, {'status': status})
async def confirm_refresh(self, path: str, method: str = 'DELETE') -> dict:
- """确认危险操作,并等待操作及其列表刷新均成功。"""
+ """
+ 确认危险操作,并等待操作及其列表刷新均成功。
+
+ :param path: 要读取或处理的路径
+ :param method: 当前请求的 HTTP 方法
+ :return: 随调用传入或返回的结构化数据
+ """
confirmation = self.page.locator('.ant-modal-confirm:visible' if self.is_react else '.el-message-box:visible')
await expect(confirmation).to_be_visible()
async with self.page.expect_response(lambda response: self.matches(response, self.list_path, 'GET')) as listed:
@@ -270,7 +423,14 @@ async def confirm_refresh(self, path: str, method: str = 'DELETE') -> dict:
return payload
async def persisted(self, resource: str, record_id: int, expected: dict) -> dict:
- """从真实后端重读已保存数据,防止仅验证成功提示或前端本地状态。"""
+ """
+ 从真实后端重读已保存数据,防止仅验证成功提示或前端本地状态。
+
+ :param resource: 当前授权或管理的资源
+ :param record_id: 要查询或修改的记录标识
+ :param expected: 断言使用的预期结果
+ :return: 当前操作使用的记录
+ """
response = await self.api.get(f'{resource}/{record_id}')
assert response.ok
payload = await response.json()
@@ -282,20 +442,39 @@ async def persisted(self, resource: str, record_id: int, expected: dict) -> dict
@staticmethod
def records(payload: dict) -> list[dict]:
- """兼容分页 rows 与树形列表 data 的真实响应格式。"""
+ """
+ 兼容分页 rows 与树形列表 data 的真实响应格式。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 需要处理的各行记录
+ """
rows = payload.get('rows', payload.get('data', []))
assert isinstance(rows, list), payload
return rows
@classmethod
def record(cls, payload: dict, field: str, value: str) -> dict:
- """查询必须返回且仅返回一个目标记录。"""
+ """
+ 查询必须返回且仅返回一个目标记录。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :param field: 需要读取或修改的字段
+ :param value: 待处理的输入值
+ :return: 必须返回且仅返回一个目标记录
+ """
records = [row for row in cls.records(payload) if row[field] == value]
assert len(records) == 1, f'未找到唯一的 {field}={value!r}: {payload}'
return records[0]
async def cleanup(self, resource: str, field: str, values: Sequence[str], id_key: str) -> None:
- """失败时只清理精确匹配本用例唯一标识的数据,不触碰预置记录。"""
+ """
+ 失败时只清理精确匹配本用例唯一标识的数据,不触碰预置记录。
+
+ :param resource: 当前授权或管理的资源
+ :param field: 需要读取或修改的字段
+ :param values: 当前处理的值集合
+ :param id_key: 从响应中读取记录标识的键
+ """
for value in values:
response = await self.api.get(f'{resource}/list', params={field: value, 'pageSize': 1000, 'pageNum': 1})
assert response.ok
diff --git a/ruoyi-fastapi-test/system/test_dict_management.py b/ruoyi-fastapi-test/system/test_dict_management.py
index 01b249e0d..6e9d11ef3 100644
--- a/ruoyi-fastapi-test/system/test_dict_management.py
+++ b/ruoyi-fastapi-test/system/test_dict_management.py
@@ -11,7 +11,13 @@
async def verify_dictionary_data(view: SystemPage, resource: str, kind: str) -> None:
- """创建两条数据,修改英文译文,并逐条核对原文、业务值及回显样式。"""
+ """
+ 创建两条数据,修改英文译文,并逐条核对原文、业务值及回显样式。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param resource: 当前授权或管理的资源
+ :param kind: 当前条目的类别
+ """
label_field, value_field = ('标签', '键值') if Config.frontend_framework == 'vue2' else ('数据标签', '数据键值')
entries = []
for label, english_label, value, style, style_value in [
diff --git a/ruoyi-fastapi-test/system/test_file_management.py b/ruoyi-fastapi-test/system/test_file_management.py
index 1002b71d5..359a0ce60 100644
--- a/ruoyi-fastapi-test/system/test_file_management.py
+++ b/ruoyi-fastapi-test/system/test_file_management.py
@@ -14,7 +14,13 @@
async def file_action_row(view: SystemPage, name: str) -> Locator:
- """Element UI 的固定操作列另有一张可见表格。"""
+ """
+ Element UI 的固定操作列另有一张可见表格。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param name: 用于查找或标识当前对象的名称
+ :return: 带可见文件操作按钮的表格行
+ """
fixed = view.page.locator('.el-table__fixed-right:visible .el-table__row').filter(
has=view.page.get_by_text(name, exact=True)
)
@@ -22,14 +28,25 @@ async def file_action_row(view: SystemPage, name: str) -> Locator:
async def select_file(view: SystemPage, name: str) -> None:
- """点击可见复选框外层,核验隐藏原生控件的选择状态。"""
+ """
+ 点击可见复选框外层,核验隐藏原生控件的选择状态。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param name: 用于查找或标识当前对象的名称
+ """
selection = view.row(name).locator('.el-checkbox, .ant-checkbox-wrapper')
await selection.click()
await expect(selection.locator('input')).to_be_checked()
async def cleanup_file(view: SystemPage, file_id: str, name: str) -> None:
- """只清理本次上传文件,兼容用例已将其永久删除的情况。"""
+ """
+ 只清理本次上传文件,兼容用例已将其永久删除的情况。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param file_id: 文件ID
+ :param name: 用于查找或标识当前对象的名称
+ """
response = await view.api.get('/system/file/list', params={'originalName': name, 'pageNum': 1, 'pageSize': 1000})
assert response.ok
payload = await response.json()
@@ -46,7 +63,14 @@ async def cleanup_file(view: SystemPage, file_id: str, name: str) -> None:
async def verify_file_details_and_download(view: SystemPage, name: str, file_id: str, contents: bytes) -> None:
- """详情校验持久化摘要,浏览器下载校验原始文件名和真实字节。"""
+ """
+ 详情校验持久化摘要,浏览器下载校验原始文件名和真实字节。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param name: 用于查找或标识当前对象的名称
+ :param file_id: 文件ID
+ :param contents: 需要写入或校验的文件内容
+ """
action_row = await file_action_row(view, name)
detail = await view.action(action_row.get_by_role('button').nth(0).click, f'/system/file/{file_id}')
assert detail['data']['fileHash'] == hashlib.sha256(contents).hexdigest()
@@ -66,7 +90,13 @@ async def verify_file_details_and_download(view: SystemPage, name: str, file_id:
async def upload_fixture(view: SystemPage, access_type: str) -> tuple[dict, str, bytes]:
- """文件管理页没有上传控件,使用真实公共上传接口准备唯一文件。"""
+ """
+ 文件管理页没有上传控件,使用真实公共上传接口准备唯一文件。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param access_type: 文件访问类型
+ :return: 依次为 ``payload``、``name``、``contents`` 的元组
+ """
name = f'e2e_{access_type}_{uuid4().hex[:8]}.txt'
contents = f'{name}\n真实文件下载与恢复校验\n'.encode()
upload_path = '/common/upload' if access_type == 'public' else '/common/files/upload'
diff --git a/ruoyi-fastapi-test/system/test_log_management.py b/ruoyi-fastapi-test/system/test_log_management.py
index 2fdafa2ae..5eecdfb52 100644
--- a/ruoyi-fastapi-test/system/test_log_management.py
+++ b/ruoyi-fastapi-test/system/test_log_management.py
@@ -12,7 +12,14 @@
async def wait_for_audit(view: SystemPage, path: str) -> dict:
- """日志经 Redis Stream 异步入库,轮询真实查询直到目标事件可见。"""
+ """
+ 日志经 Redis Stream 异步入库,轮询真实查询直到目标事件可见。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param path: 要读取或处理的路径
+ :return: 随调用传入或返回的结构化数据
+ :raises AssertionError: 目标操作日志未在时限内写入
+ """
for _ in range(30):
payload = await view.search()
if any(record['operUrl'].endswith(path) for record in payload['rows']):
diff --git a/ruoyi-fastapi-test/system/test_menu_management.py b/ruoyi-fastapi-test/system/test_menu_management.py
index eb0117a71..fdbc350aa 100644
--- a/ruoyi-fastapi-test/system/test_menu_management.py
+++ b/ruoyi-fastapi-test/system/test_menu_management.py
@@ -10,7 +10,14 @@
async def add_menu_button(view: SystemPage, parent_name: str, expected: dict) -> dict:
- """在真实父菜单下创建按钮,并校验其原文、译文与权限的保存结果。"""
+ """
+ 在真实父菜单下创建按钮,并校验其原文、译文与权限的保存结果。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param parent_name: 父级记录的显示名称
+ :param expected: 断言使用的预期结果
+ :return: 供调用方使用的 ``leaf``
+ """
resource = '/system/menu'
await view.button(view.row(parent_name), '新增').click()
dialog = view.dialog
diff --git a/ruoyi-fastapi-test/system/test_oauth_management.py b/ruoyi-fastapi-test/system/test_oauth_management.py
index 7ea6f7e36..0a63de5e9 100644
--- a/ruoyi-fastapi-test/system/test_oauth_management.py
+++ b/ruoyi-fastapi-test/system/test_oauth_management.py
@@ -19,7 +19,12 @@
async def successful_json(response: APIResponse | Response) -> dict[str, Any]:
- """同时验证 HTTP 与真实业务响应,不将错误页当成空列表。"""
+ """
+ 同时验证 HTTP 与真实业务响应,不将错误页当成空列表。
+
+ :param response: 当前调用产生的响应
+ :return: 随调用传入或返回的结构化数据
+ """
assert response.ok, f'OAuth API HTTP 状态异常:{response.status}'
payload = await response.json()
assert payload['code'] == SUCCESS_CODE, payload.get('msg')
@@ -27,7 +32,15 @@ async def successful_json(response: APIResponse | Response) -> dict[str, Any]:
async def click_response(page: Page, button: Locator, path: str, method: str) -> dict[str, Any]:
- """点击操作后等待对应业务请求完成,兼容两个框架的 API 前缀。"""
+ """
+ 点击操作后等待对应业务请求完成,兼容两个框架的 API 前缀。
+
+ :param page: 浏览器页面或要查询的页码
+ :param button: 触发当前动作的按钮
+ :param path: 要读取或处理的路径
+ :param method: 当前请求的 HTTP 方法
+ :return: 业务请求完成后捕获的响应
+ """
async with page.expect_response(
lambda response: urlparse(response.url).path.endswith(path) and response.request.method == method
) as pending:
@@ -36,7 +49,15 @@ async def click_response(page: Page, button: Locator, path: str, method: str) ->
async def find_record(page: Page, kind: str, placeholder: str, name: str) -> Locator:
- """按唯一名称查询当前用例的记录,避开分页和其他测试的数据。"""
+ """
+ 按唯一名称查询当前用例的记录,避开分页和其他测试的数据。
+
+ :param page: 浏览器页面或要查询的页码
+ :param kind: 当前条目的类别
+ :param placeholder: 输入框用于定位或提示的占位文本
+ :param name: 用于查找或标识当前对象的名称
+ :return: 需要处理的各行记录
+ """
await page.get_by_placeholder(placeholder, exact=True).fill(name)
await click_response(
page, page.get_by_role('button', name=button_name('查找')), f'/system/oauth/{kind}/list', 'GET'
@@ -47,7 +68,15 @@ async def find_record(page: Page, kind: str, placeholder: str, name: str) -> Loc
async def change_record_status(page: Page, rows: Locator, kind: str, identifier: str, *, enable: bool) -> None:
- """从实际行菜单停用或启用,再确认弹窗提交的接口成功。"""
+ """
+ 从实际行菜单停用或启用,再确认弹窗提交的接口成功。
+
+ :param page: 浏览器页面或要查询的页码
+ :param rows: 需要处理的各行记录
+ :param kind: 当前条目的类别
+ :param identifier: 在当前流程中定位记录的标识
+ :param enable: 是否启用目标功能
+ """
await rows.get_by_role('button', name=button_name('更多')).click()
label = '重新启用' if enable else {'client': '停用应用', 'resource': '停用服务', 'scope': '停用权限'}[kind]
await page.locator('.el-dropdown-menu:visible, .ant-dropdown:visible').get_by_text(label, exact=True).click()
@@ -63,7 +92,14 @@ async def change_record_status(page: Page, rows: Locator, kind: str, identifier:
async def assert_record_status(api: APIRequestContext, kind: str, identifier: str, status: str) -> None:
- """直接读取持久化记录,验证 UI 操作确实改变后端状态。"""
+ """
+ 直接读取持久化记录,验证 UI 操作确实改变后端状态。
+
+ :param api: 发起 API 请求的客户端
+ :param kind: 当前条目的类别
+ :param identifier: 在当前流程中定位记录的标识
+ :param status: 操作或记录所处的状态
+ """
payload = await successful_json(await api.get(f'/system/oauth/{kind}/{identifier}'))
assert payload['data']['status'] == status
diff --git a/ruoyi-fastapi-test/system/test_plugin_management.py b/ruoyi-fastapi-test/system/test_plugin_management.py
index 1fc0e1fdb..81e97a364 100644
--- a/ruoyi-fastapi-test/system/test_plugin_management.py
+++ b/ruoyi-fastapi-test/system/test_plugin_management.py
@@ -24,7 +24,12 @@
def validate_operation_envelope(payload: dict) -> dict:
- """601 是明确的业务阻断;异常状态、缺失数据和不一致的成功标志均不能通过。"""
+ """
+ 601 是明确的业务阻断;异常状态、缺失数据和不一致的成功标志均不能通过。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 当前调用处理的业务数据
+ """
data = payload['data']
assert isinstance(data, dict) and isinstance(data['ok'], bool), payload
assert payload['code'] == (HTTPStatus.OK if data['ok'] else PLUGIN_WARNING), payload
@@ -35,13 +40,24 @@ def validate_operation_envelope(payload: dict) -> dict:
async def plugin_payload(response: Response) -> dict:
- """业务成功和业务阻断都必须是 HTTP 200,并进一步验证具体操作契约。"""
+ """
+ 业务成功和业务阻断都必须是 HTTP 200,并进一步验证具体操作契约。
+
+ :param response: 当前调用产生的响应
+ :return: 通过 HTTP 状态和业务状态检查的插件响应
+ """
assert response.status == HTTPStatus.OK, f'{response.url}: HTTP {response.status}'
return validate_operation_envelope(await response.json())
def validate_capability(capability: dict, operation: str) -> bool:
- """以源码 AI 插件的运行模式验证阻断来源,不能把任意失败当作生产模式限制。"""
+ """
+ 以源码 AI 插件的运行模式验证阻断来源,不能把任意失败当作生产模式限制。
+
+ :param capability: 当前检查的能力
+ :param operation: 当前处理的操作
+ :return: 是否以源码 AI 插件的运行模式验证阻断来源
+ """
assert capability['pluginId'] == PLUGIN_ID
assert capability['frontendMode'] in {'dev', 'built'}
assert capability['backendRuntimeMode'] in {'dev', 'service', 'maintenance'}
@@ -64,7 +80,11 @@ def validate_capability(capability: dict, operation: str) -> bool:
def validate_dependency_report(report: dict) -> None:
- """失败必须由实际缺失或版本不满足的依赖解释,而不是接口异常或空数据。"""
+ """
+ 失败必须由实际缺失或版本不满足的依赖解释,而不是接口异常或空数据。
+
+ :param report: 记录操作结果的报告
+ """
assert report['pluginId'] == PLUGIN_ID
dependencies = report['dependencies']
assert isinstance(dependencies, list) and dependencies
@@ -84,7 +104,13 @@ def validate_dependency_report(report: dict) -> None:
def validate_install_plan(payload: dict, capability: dict) -> bool:
- """AI 无插件间依赖;只有明确的环境能力限制可以阻断其拓扑计划。"""
+ """
+ AI 无插件间依赖;只有明确的环境能力限制可以阻断其拓扑计划。
+
+ :param payload: 随调用传入或返回的结构化数据
+ :param capability: 当前检查的能力
+ :return: 是否AI 无插件间依赖;只有明确的环境能力限制可以阻断其拓扑计划
+ """
blocked = validate_capability(capability, 'batch_install')
assert payload['operation'] == 'install'
assert payload['databaseAvailable'] is True and payload['databaseError'] is None
@@ -108,7 +134,12 @@ def validate_install_plan(payload: dict, capability: dict) -> bool:
def record_plugin_writes(view: SystemPage) -> list[Request]:
- """记录浏览器真实请求,最终只允许显式 dry-run 的依赖计划请求。"""
+ """
+ 记录浏览器真实请求,最终只允许显式 dry-run 的依赖计划请求。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :return: 已执行写入操作的记录
+ """
writes: list[Request] = []
view.page.on(
'request',
@@ -120,12 +151,22 @@ def record_plugin_writes(view: SystemPage) -> list[Request]:
def table_rows(scope: Locator) -> Locator:
- """只计当前可见主表格,避免 Vue2 固定列镜像被重复计算。"""
+ """
+ 只计当前可见主表格,避免 Vue2 固定列镜像被重复计算。
+
+ :param scope: 当前操作使用的作用域
+ :return: 当前可见主表格中的数据行
+ """
return scope.locator('.el-table__body-wrapper:visible .el-table__row, .ant-table-row:visible')
async def open_plugins(browser_harness: BrowserHarness) -> tuple[SystemPage, dict]:
- """使用真实登录和列表,定位项目自带的 AI 插件。"""
+ """
+ 使用真实登录和列表,定位项目自带的 AI 插件。
+
+ :param browser_harness: 管理浏览器上下文、页面和登录状态的端到端测试夹具
+ :return: 依次为 ``view``、``plugin`` 的元组
+ """
view = SystemPage()
await view.setup(browser_harness)
payload = await view.open('/system/plugin', f'{RESOURCE}/list')
@@ -135,7 +176,12 @@ async def open_plugins(browser_harness: BrowserHarness) -> tuple[SystemPage, dic
async def plugin_row(view: SystemPage) -> Locator:
- """Vue2 横向溢出时点击固定操作列,Vue3 点击主表格操作。"""
+ """
+ Vue2 横向溢出时点击固定操作列,Vue3 点击主表格操作。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :return: 包含可见操作控件的插件行
+ """
fixed = view.page.locator('.app-main .el-table__fixed-right:visible .el-table__row').filter(
has=view.page.get_by_text(PLUGIN_ID, exact=True)
)
@@ -143,17 +189,31 @@ async def plugin_row(view: SystemPage) -> Locator:
async def plugin_action(view: SystemPage, label: str) -> None:
- """操作插件所在行,兼容两套组件库的固定列。"""
+ """
+ 操作插件所在行,兼容两套组件库的固定列。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param label: 显示给用户的标签
+ """
await view.button(await plugin_row(view), label).click()
async def close_dialog(view: SystemPage) -> None:
- """等待弹窗关闭,确保后续请求来自主页面。"""
+ """
+ 等待弹窗关闭,确保后续请求来自主页面。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ """
await view.close_dialog()
async def assert_unchanged(view: SystemPage, before: dict) -> None:
- """计划查看不能修改插件的安装版本、启用设置或状态。"""
+ """
+ 计划查看不能修改插件的安装版本、启用设置或状态。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param before: 变更前取得的状态
+ """
# 只读核验允许连接被重置后重建一次;HTTP 和业务错误仍由下方断言报告。
response = await view.api.get(f'{RESOURCE}/{PLUGIN_ID}', max_retries=1)
assert response.ok
@@ -164,7 +224,12 @@ async def assert_unchanged(view: SystemPage, before: dict) -> None:
async def verify_manifest_tabs(view: SystemPage, detail: dict) -> None:
- """逐项核对清单声明,不能只验证标签页标题存在。"""
+ """
+ 逐项核对清单声明,不能只验证标签页标题存在。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param detail: 用于说明当前结果的详细信息
+ """
dialog = view.dialog
for tab, records, field in (
('菜单', detail.get('frontend', {}).get('menus', []), 'name'),
@@ -183,7 +248,11 @@ async def verify_manifest_tabs(view: SystemPage, detail: dict) -> None:
async def verify_metrics(view: SystemPage) -> None:
- """运行观测的条数和空态都与当前进程真实响应一致。"""
+ """
+ 运行观测的条数和空态都与当前进程真实响应一致。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ """
dialog = view.dialog
metrics = dialog.locator('.plugin-metrics')
for trigger in (
@@ -231,7 +300,13 @@ async def test_plugin_search_detail_and_metrics(browser_harness: BrowserHarness)
async def request_dependency_preview(view: SystemPage, endpoint: str) -> dict:
- """只点击生成计划,并强制核对实际请求携带 dryRun=true。"""
+ """
+ 只点击生成计划,并强制核对实际请求携带 dryRun=true。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param endpoint: 接收该请求的端点
+ :return: 经过预演参数校验的依赖计划响应
+ """
async with view.page.expect_response(
lambda result: view.matches(result, f'{endpoint}/install', 'POST')
) as preview_response:
@@ -242,7 +317,12 @@ async def request_dependency_preview(view: SystemPage, endpoint: str) -> dict:
def validate_blocked_preview(preview: dict, capability: dict) -> None:
- """服务模式的预演拒绝也必须有结构化能力依据,不接受普通 601 异常。"""
+ """
+ 服务模式的预演拒绝也必须有结构化能力依据,不接受普通 601 异常。
+
+ :param preview: 提交前生成的预览
+ :param capability: 当前检查的能力
+ """
assert validate_capability(capability, 'dependency_install') is True
assert preview['ok'] is False and preview['status'] == 'blocked'
assert preview['pluginId'] == PLUGIN_ID and preview['operation'] == 'dependency_install'
@@ -254,7 +334,13 @@ def validate_blocked_preview(preview: dict, capability: dict) -> None:
async def verify_dependency_preview(view: SystemPage, preview: dict, report: dict) -> None:
- """开发模式必须完整展示真实预演报告,并且保持实际安装不可执行。"""
+ """
+ 开发模式必须完整展示真实预演报告,并且保持实际安装不可执行。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param preview: 提交前生成的预览
+ :param report: 记录操作结果的报告
+ """
assert preview['ok'] is True and preview['dryRun'] is True
assert preview['pluginId'] == PLUGIN_ID and preview['operation'] == 'dependency_install'
assert preview['message'] == '插件依赖安装演练完成,未执行实际安装'
@@ -279,7 +365,12 @@ async def verify_dependency_preview(view: SystemPage, preview: dict, report: dic
async def verify_dependency_report_dialog(view: SystemPage, report: dict) -> None:
- """Vue2 的 601 拒绝值是 error,但警告 toast 必须展示真实依赖异常信息。"""
+ """
+ Vue2 的 601 拒绝值是 error,但警告 toast 必须展示真实依赖异常信息。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param report: 记录操作结果的报告
+ """
assert Config.frontend_framework in {'vue2', 'vue3', 'react'}
if not report['ok']:
await expect(
@@ -373,7 +464,12 @@ async def test_plugin_install_plan(browser_harness: BrowserHarness) -> None:
async def verify_install_plan_dialog(view: SystemPage, payload: dict) -> None:
- """可操作环境展示拓扑细节,但用例始终不点击实际执行入口。"""
+ """
+ 可操作环境展示拓扑细节,但用例始终不点击实际执行入口。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param payload: 随调用传入或返回的结构化数据
+ """
plan = payload['plan']
await expect(view.dialog).to_contain_text('插件安装计划')
await expect(view.button(view.dialog, '执行计划:安装')).to_be_enabled()
diff --git a/ruoyi-fastapi-test/system/test_role_management.py b/ruoyi-fastapi-test/system/test_role_management.py
index 168f7be15..9340ba0e1 100644
--- a/ruoyi-fastapi-test/system/test_role_management.py
+++ b/ruoyi-fastapi-test/system/test_role_management.py
@@ -13,7 +13,14 @@
async def check_assigned_user(view: SystemPage, role_id: int, name: str, *, assigned: bool) -> None:
- """重新读取已授权用户,验证新增和取消授权确实保存。"""
+ """
+ 重新读取已授权用户,验证新增和取消授权确实保存。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param role_id: 角色id
+ :param name: 用于查找或标识当前对象的名称
+ :param assigned: 分配给目标的记录或权限
+ """
response = await view.api.get('/system/role/authUser/allocatedList', params={'roleId': role_id, 'userName': name})
payload = await response.json()
assert response.ok and payload['code'] == HTTPStatus.OK, payload
@@ -22,7 +29,13 @@ async def check_assigned_user(view: SystemPage, role_id: int, name: str, *, assi
async def assign_and_cancel(view: SystemPage, role_id: int, user_name: str) -> None:
- """先后验证单条取消和批量取消授权。"""
+ """
+ 先后验证单条取消和批量取消授权。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param role_id: 角色id
+ :param user_name: 当前用户的账号名称
+ """
resource = '/system/role'
for bulk in (False, True):
await view.action(view.button(view.page, '添加用户').click, f'{resource}/authUser/unallocatedList')
@@ -63,7 +76,12 @@ async def assign_and_cancel(view: SystemPage, role_id: int, user_name: str) -> N
async def select_system_menu(view: SystemPage, dialog: Locator) -> None:
- """选中系统管理根节点,并核对组件实际的选中状态。"""
+ """
+ 选中系统管理根节点,并核对组件实际的选中状态。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param dialog: 测试正在操作的对话框
+ """
menu_node = (
dialog.locator('.ant-tree-treenode' if view.is_react else '.el-tree-node__content')
.filter(has=view.page.get_by_text('系统管理', exact=True))
diff --git a/ruoyi-fastapi-test/system/test_user_management.py b/ruoyi-fastapi-test/system/test_user_management.py
index 9190e3dd2..55fd8b604 100644
--- a/ruoyi-fastapi-test/system/test_user_management.py
+++ b/ruoyi-fastapi-test/system/test_user_management.py
@@ -12,7 +12,13 @@
async def verify_auth_role(view: SystemPage, user_id: int, *, assigned: bool) -> None:
- """每次授权变更后重读真实后端,普通角色选中状态必须一致。"""
+ """
+ 每次授权变更后重读真实后端,普通角色选中状态必须一致。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param user_id: 用户的唯一标识
+ :param assigned: 分配给目标的记录或权限
+ """
response = await view.api.get(f'/system/user/authRole/{user_id}')
payload = await response.json()
assert response.ok and payload['code'] == HTTPStatus.OK, payload
@@ -22,7 +28,13 @@ async def verify_auth_role(view: SystemPage, user_id: int, *, assigned: bool) ->
async def reset_password(view: SystemPage, name: str, browser_harness: BrowserHarness) -> None:
- """通过界面重置密码,并使用新密码实际登录验证。"""
+ """
+ 通过界面重置密码,并使用新密码实际登录验证。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param name: 用于查找或标识当前对象的名称
+ :param browser_harness: 管理浏览器上下文、页面和登录状态的端到端测试夹具
+ """
await view.row_action(name, '重置密码')
prompt = view.page.locator('.el-message-box:visible, .ant-modal:visible')
await prompt.locator('input').fill('Updated123456!')
@@ -40,7 +52,11 @@ async def reset_password(view: SystemPage, name: str, browser_harness: BrowserHa
async def verify_optional_date_keyboard(view: SystemPage) -> None:
- """验证用户管理的空日期筛选支持双向 Tab 导航和键盘开闭日历。"""
+ """
+ 验证用户管理的空日期筛选支持双向 Tab 导航和键盘开闭日历。
+
+ :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ """
start = view.page.get_by_placeholder('开始日期', exact=True)
end = view.page.get_by_placeholder('结束日期', exact=True)
await start.focus()
diff --git a/ruoyi-fastapi-test/test_account_pages.py b/ruoyi-fastapi-test/test_account_pages.py
index f11bbd4e7..2095be2c3 100644
--- a/ruoyi-fastapi-test/test_account_pages.py
+++ b/ruoyi-fastapi-test/test_account_pages.py
@@ -21,7 +21,12 @@
async def successful_payload(response: APIResponse | Response) -> dict[str, Any]:
- """验证真实接口的 HTTP 与业务状态,避免仅凭成功提示判断保存结果。"""
+ """
+ 验证真实接口的 HTTP 与业务状态,避免仅凭成功提示判断保存结果。
+
+ :param response: 当前调用产生的响应
+ :return: 随调用传入或返回的结构化数据
+ """
assert response.ok, f'账户 API HTTP 状态异常:{response.status}'
payload = await response.json()
assert payload['code'] == HTTPStatus.OK, payload.get('msg')
@@ -29,7 +34,13 @@ async def successful_payload(response: APIResponse | Response) -> dict[str, Any]
def profile_input(form: Locator, label: str) -> Locator:
- """用用户看到的表单标签兼容 Element UI 和 Element Plus。"""
+ """
+ 用用户看到的表单标签兼容 Element UI 和 Element Plus。
+
+ :param form: 当前正在填充的表单
+ :param label: 显示给用户的标签
+ :return: 用户资料中指定标签的输入框定位器
+ """
return form.locator('.el-form-item, .ant-form-item').filter(has_text=label).locator('input')
diff --git a/ruoyi-fastapi-test/test_browser_harness.py b/ruoyi-fastapi-test/test_browser_harness.py
index 999c906ad..8afca80bd 100644
--- a/ruoyi-fastapi-test/test_browser_harness.py
+++ b/ruoyi-fastapi-test/test_browser_harness.py
@@ -21,7 +21,14 @@
def login_response(status: HTTPStatus, *, retry_after: str | None = None, payload: dict | None = None) -> MagicMock:
- """构造登录协议响应,保留 HTTP 状态、响应头和异步 JSON 读取语义。"""
+ """
+ 构造登录协议响应,保留 HTTP 状态、响应头和异步 JSON 读取语义。
+
+ :param status: 操作或记录所处的状态
+ :param retry_after: 建议重试等待秒数
+ :param payload: 随调用传入或返回的结构化数据
+ :return: 登录协议响应
+ """
return MagicMock(
status=status,
ok=status == HTTPStatus.OK,
@@ -31,7 +38,13 @@ def login_response(status: HTTPStatus, *, retry_after: str | None = None, payloa
def login_harness(tmp_path: Path, responses: list[object]) -> tuple[BrowserHarness, AsyncMock]:
- """仅替换网络边界,直接运行实际登录重试逻辑。"""
+ """
+ 仅替换网络边界,直接运行实际登录重试逻辑。
+
+ :param tmp_path: pytest 为当前用例创建的临时目录
+ :param responses: 按 HTTP 状态码声明的响应信息
+ :return: 模拟浏览器和被测登录重试环境
+ """
api = AsyncMock()
api.post.side_effect = responses
playwright = MagicMock()
@@ -40,7 +53,12 @@ def login_harness(tmp_path: Path, responses: list[object]) -> tuple[BrowserHarne
def login_page(responses: list[MagicMock]) -> MagicMock:
- """模拟浏览器响应事件边界,实际运行表单提交及跳转校验逻辑。"""
+ """
+ 模拟浏览器响应事件边界,实际运行表单提交及跳转校验逻辑。
+
+ :param responses: 按 HTTP 状态码声明的响应信息
+ :return: 浏览器页面或要查询的页码
+ """
page = MagicMock()
page.get_by_placeholder.return_value.fill = AsyncMock()
page.get_by_role.return_value.click = AsyncMock()
@@ -202,6 +220,7 @@ async def test_login_bounds_cumulative_wait(tmp_path: Path, monkeypatch: pytest.
def test_artifact_paths_cannot_escape_output(tmp_path: Path) -> None:
+ """产物路径不能越出输出目录。"""
first = artifact_directory(tmp_path, '../../a/test_login.py::test_a[UTC]')
second = artifact_directory(tmp_path, '../../b/test_login.py::test_a[UTC]')
assert first.parent == second.parent == tmp_path
@@ -212,6 +231,7 @@ def test_artifact_paths_cannot_escape_output(tmp_path: Path) -> None:
async def test_contexts_share_browser_but_not_authentication(
e2e_browser: tuple[Playwright, Browser], tmp_path: Path
) -> None:
+ """浏览器上下文共享浏览器并隔离认证状态。"""
first = BrowserHarness(*e2e_browser, tmp_path / 'first')
second = BrowserHarness(*e2e_browser, tmp_path / 'second')
try:
@@ -229,6 +249,7 @@ async def test_contexts_share_browser_but_not_authentication(
async def test_failed_case_keeps_trace_screenshot_and_console(
e2e_browser: tuple[Playwright, Browser], tmp_path: Path
) -> None:
+ """失败用例保留跟踪、截图和控制台记录。"""
harness = BrowserHarness(*e2e_browser, tmp_path)
page = await harness.new_page()
await page.set_content('Failure diagnostics ')
@@ -242,6 +263,7 @@ async def test_failed_case_keeps_trace_screenshot_and_console(
def test_compose_isolation_removes_shared_resources() -> None:
+ """Compose 隔离配置移除共享资源。"""
config = {
'services': {
'ruoyi-frontend': {'build': {'context': '/frontend'}, 'container_name': 'shared', 'ports': ['80:80']},
@@ -262,5 +284,6 @@ def test_compose_isolation_removes_shared_resources() -> None:
def test_compose_requires_dedicated_project_prefix() -> None:
+ """Compose 要求独立的项目前缀。"""
with pytest.raises(ValueError, match='ruoyi-ci-'):
isolate_compose({'services': {}}, 'production', '3.12')
diff --git a/ruoyi-fastapi-test/test_code_gen_harness.py b/ruoyi-fastapi-test/test_code_gen_harness.py
index e0fe77f00..b056d0dba 100644
--- a/ruoyi-fastapi-test/test_code_gen_harness.py
+++ b/ruoyi-fastapi-test/test_code_gen_harness.py
@@ -80,6 +80,11 @@ async def test_edit_table_waits_for_details_and_ignores_departing_search_form(
""".replace('RENDER_DELAY', '500' if delayed == 'render' else '0')
async def respond(route: Route) -> None:
+ """
+ 按请求方法提供浏览器测试响应。
+
+ :param route: 当前请求匹配的路由
+ """
if route.request.method == 'PUT':
saved.update(route.request.post_data_json)
await route.fulfill(json={'code': 200})
diff --git a/ruoyi-fastapi-test/test_login.py b/ruoyi-fastapi-test/test_login.py
index 0a80b3ef2..661a1145c 100644
--- a/ruoyi-fastapi-test/test_login.py
+++ b/ruoyi-fastapi-test/test_login.py
@@ -47,6 +47,11 @@ async def test_loading_message_before_app_starts(browser_harness: BrowserHarness
assert entries
async def delay_scripts(route: Route) -> None:
+ """
+ 暂停页面脚本请求直到测试允许继续。
+
+ :param route: 当前请求匹配的路由
+ """
await resume.wait()
await route.continue_()
diff --git a/ruoyi-fastapi-test/test_pages.py b/ruoyi-fastapi-test/test_pages.py
index 195428ebd..7b0d28479 100644
--- a/ruoyi-fastapi-test/test_pages.py
+++ b/ruoyi-fastapi-test/test_pages.py
@@ -17,7 +17,13 @@
def builtin_routes(routes: list[dict[str, Any]], parent: str = '') -> set[str]:
- """列出服务端真实返回的内置页面,忽略外链和独立插件路由。"""
+ """
+ 列出服务端真实返回的内置页面,忽略外链和独立插件路由。
+
+ :param routes: 已配置的路由条目
+ :param parent: 用于判断路径从属关系的父目录
+ :return: 服务端真实返回的内置页面
+ """
paths = set()
for route in routes:
segment = route['path']
diff --git a/ruoyi-fastapi-test/test_plugin_network_harness.py b/ruoyi-fastapi-test/test_plugin_network_harness.py
index 620085034..dc87c2d20 100644
--- a/ruoyi-fastapi-test/test_plugin_network_harness.py
+++ b/ruoyi-fastapi-test/test_plugin_network_harness.py
@@ -25,6 +25,12 @@ async def test_plugin_read_recovers_only_one_connection_reset(
requests = []
async def respond(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ """
+ 按请求方法提供浏览器测试响应。
+
+ :param reader: 读取输入内容的对象
+ :param writer: 负责写入测试结果的对象
+ """
try:
request = await reader.readuntil(b'\r\n\r\n')
requests.append(request.split(b'\r\n')[0])
diff --git a/ruoyi-fastapi-test/test_plugin_response_contract.py b/ruoyi-fastapi-test/test_plugin_response_contract.py
index f4bec3e3f..e9a7c1ab5 100644
--- a/ruoyi-fastapi-test/test_plugin_response_contract.py
+++ b/ruoyi-fastapi-test/test_plugin_response_contract.py
@@ -21,7 +21,13 @@
def capability(frontend: str = 'built', backend: str = 'service') -> dict:
- """构造与 CI 中源码 AI 插件一致的能力报告。"""
+ """
+ 构造与 CI 中源码 AI 插件一致的能力报告。
+
+ :param frontend: 前端部分的配置
+ :param backend: 后端部分的配置或处理对象
+ :return: 与 CI 中源码 AI 插件一致的能力报告
+ """
warnings = []
if backend == 'service':
warnings.append('当前为服务运行模式,请在维护窗口执行插件变更。')
@@ -44,7 +50,14 @@ def capability(frontend: str = 'built', backend: str = 'service') -> dict:
def dependency_report(*, installed: bool, satisfied: bool, skipped: bool = False) -> dict:
- """缺失、版本不满足与 built 模式跳过检查有不同且可验证的语义。"""
+ """
+ 缺失、版本不满足与 built 模式跳过检查有不同且可验证的语义。
+
+ :param installed: 当前环境中已安装的版本
+ :param satisfied: 预期条件是否已经满足
+ :param skipped: 是否跳过当前步骤
+ :return: 包含 ``pluginId``、``ok``、``dependencyOk``、``message``、``dependencies`` 等字段的数据
+ """
ok = skipped or (installed and satisfied)
return {
'pluginId': PLUGIN_ID,
@@ -68,7 +81,12 @@ def dependency_report(*, installed: bool, satisfied: bool, skipped: bool = False
def install_plan(runtime: dict) -> dict:
- """有效拓扑与生产环境阻断分别保留,模拟已观测到的 CI 响应结构。"""
+ """
+ 有效拓扑与生产环境阻断分别保留,模拟已观测到的 CI 响应结构。
+
+ :param runtime: 只访问临时 SQLite,调度器执行日志不会连接开发数据库
+ :return: 包含 ``ok``、``message``、``operation``、``databaseAvailable``、``databaseError`` 等字段的数据
+ """
blocked = not runtime['runtimeManageable']
return {
'ok': not blocked,
@@ -99,7 +117,12 @@ def install_plan(runtime: dict) -> dict:
def envelope(data: dict) -> dict:
- """响应封装的成功字段必须与业务结果对应。"""
+ """
+ 响应封装的成功字段必须与业务结果对应。
+
+ :param data: 当前调用处理的业务数据
+ :return: 包含 ``code``、``success``、``msg``、``data`` 的数据
+ """
return {
'code': HTTPStatus.OK if data['ok'] else PLUGIN_WARNING,
'success': data['ok'],
@@ -113,12 +136,14 @@ def envelope(data: dict) -> dict:
[(True, True, False), (False, False, False), (True, False, False), (False, False, True)],
)
def test_dependency_contract_accepts_only_explained_results(installed: bool, satisfied: bool, skipped: bool) -> None:
+ """依赖检查只接受有原因说明的结果。"""
report = dependency_report(installed=installed, satisfied=satisfied, skipped=skipped)
validate_dependency_report(validate_operation_envelope(envelope(report)))
@pytest.mark.parametrize('field', ['missingDependencies', 'unsatisfiedDependencies', 'dependencyOk', 'message'])
def test_dependency_contract_rejects_unexplained_failure(field: str) -> None:
+ """依赖检查拒绝没有说明原因的失败。"""
report = dependency_report(installed=False, satisfied=False)
report[field] = {
'missingDependencies': [],
@@ -135,6 +160,7 @@ def test_dependency_contract_rejects_unexplained_failure(field: str) -> None:
[('dev', 'dev'), ('dev', 'maintenance'), ('built', 'dev'), ('dev', 'service'), ('built', 'service')],
)
def test_plan_contract_distinguishes_runtime_capability(frontend: str, backend: str) -> None:
+ """计划响应区分运行时能力。"""
runtime = capability(frontend, backend)
payload = validate_operation_envelope(envelope(install_plan(runtime)))
assert validate_install_plan(payload, runtime) is (not runtime['runtimeManageable'])
@@ -145,6 +171,7 @@ def test_plan_contract_distinguishes_runtime_capability(frontend: str, backend:
['no_blocker', 'wrong_operation', 'wrong_plugin', 'wrong_mode', 'database_error', 'unexpected_success'],
)
def test_plan_contract_rejects_unrelated_or_inconsistent_failure(corruption: str) -> None:
+ """计划响应拒绝无关或前后不一致的失败。"""
runtime = capability()
payload = install_plan(runtime)
if corruption == 'no_blocker':
@@ -166,6 +193,7 @@ def test_plan_contract_rejects_unrelated_or_inconsistent_failure(corruption: str
@pytest.mark.parametrize('corruption', ['server_error', 'success_flag', 'missing_payload', 'wrong_message'])
def test_operation_envelope_does_not_hide_errors(corruption: str) -> None:
+ """操作响应封装不能隐藏错误。"""
payload = envelope(install_plan(capability()))
if corruption == 'server_error':
payload['code'] = HTTPStatus.INTERNAL_SERVER_ERROR
@@ -180,6 +208,7 @@ def test_operation_envelope_does_not_hide_errors(corruption: str) -> None:
async def test_operation_payload_rejects_http_failure_even_with_valid_business_data() -> None:
+ """即使业务数据有效也拒绝 HTTP 层失败的响应。"""
response = MagicMock(
status=HTTPStatus.INTERNAL_SERVER_ERROR, json=AsyncMock(return_value=envelope(install_plan(capability())))
)
@@ -189,6 +218,7 @@ async def test_operation_payload_rejects_http_failure_even_with_valid_business_d
def test_capability_rejects_unexplained_blocked_operations_in_development() -> None:
+ """开发环境中的能力检查拒绝无原因的受阻操作。"""
runtime = capability('dev', 'dev')
runtime['blockedOperations'] = ['batch_install']
with pytest.raises(AssertionError):
@@ -197,6 +227,7 @@ def test_capability_rejects_unexplained_blocked_operations_in_development() -> N
@pytest.mark.parametrize('unsafe_field', [None, 'dryRun', 'results'])
def test_dependency_preview_requires_explicit_safe_environment_block(unsafe_field: str | None) -> None:
+ """依赖预览要求显式声明安全环境限制。"""
runtime = capability()
preview = {
'ok': False,
diff --git a/ruoyi-fastapi-test/tool/test_code_gen.py b/ruoyi-fastapi-test/tool/test_code_gen.py
index c5d8f8134..901e2ecee 100644
--- a/ruoyi-fastapi-test/tool/test_code_gen.py
+++ b/ruoyi-fastapi-test/tool/test_code_gen.py
@@ -19,17 +19,32 @@
class GenTableTest(SystemPage):
- """只操作本用例导入的生成配置,验证编辑、代码预览及下载。"""
+ """
+ 只操作本用例导入的生成配置,验证编辑、代码预览及下载。
+
+ :cvar table_id: 代码生成表的记录标识
+ :cvar table_name: 表名称
+ :cvar table_comment: 表描述过滤条件
+ """
table_id: int | None = None
table_name: str = ''
table_comment: str = ''
def table_row(self) -> Locator:
+ """
+ 定位代码生成列表中的目标表。
+
+ :return: 匹配目标表名的数据行定位器
+ """
return self.row(self.table_name)
async def search_table(self) -> dict:
- """等待搜索接口与表格完成,避免初始响应覆盖查询结果。"""
+ """
+ 等待搜索接口与表格完成,避免初始响应覆盖查询结果。
+
+ :return: 随调用传入或返回的结构化数据
+ """
form = self.page.locator('form').first
await (
form.locator('.el-form-item, .ant-form-item')
@@ -112,7 +127,12 @@ async def edit_table(self) -> None:
await expect(self.table_row()).to_contain_text(self.table_comment)
async def select_preview_file(self, dialog: Locator, name: str) -> None:
- """通过预览标签或弹窗内的溢出菜单切换到指定文件。"""
+ """
+ 通过预览标签或弹窗内的溢出菜单切换到指定文件。
+
+ :param dialog: 测试正在操作的对话框
+ :param name: 用于查找或标识当前对象的名称
+ """
tab = dialog.get_by_role('tab', name=name, exact=True)
target = tab
menu = dialog.get_by_role('listbox')
@@ -166,6 +186,11 @@ async def preview_and_download(self) -> None:
zip_path = Path(await download.path())
def read_generated_code() -> tuple[list[str], str]:
+ """
+ 从导出压缩包读取生成的源码。
+
+ :return: 压缩包内的文件名及拼接后的源码
+ """
with ZipFile(zip_path) as archive:
names = archive.namelist()
return names, '\n'.join(archive.read(name).decode('utf-8') for name in names if name.endswith('.py'))
From eb93c91900ba242dd1808b0d1526bfbb3f358ac3 Mon Sep 17 00:00:00 2001
From: insistence <3055204202@qq.com>
Date: Thu, 26 Nov 2026 10:57:28 +0800
Subject: [PATCH 4/9] =?UTF-8?q?feat:=20=E5=BC=95=E5=85=A5=20ty=20=E6=A3=80?=
=?UTF-8?q?=E6=9F=A5=E5=B9=B6=E6=94=B6=E7=B4=A7=20Python=20=E7=B1=BB?=
=?UTF-8?q?=E5=9E=8B=E5=A3=B0=E6=98=8E?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.github/scripts/mobile_smoke.py | 9 +-
.github/tests/test_ci_contracts.py | 1 +
.github/tests/test_ci_plan.py | 6 +-
.github/tests/test_ci_python_matrix.py | 14 +
.github/ty.toml | 15 +
.github/workflows/ci-backend.yml | 5 +
.github/workflows/ci-quality.yml | 25 +-
.../.x18n/scan_python_domains.py | 2 +
ruoyi-fastapi-backend/alembic/env.py | 8 +-
.../cli/completion/controller.py | 5 +-
.../cli/completion/installers.py | 20 +-
.../cli/completion/providers.py | 62 ++--
.../cli/completion/shells.py | 31 ++
ruoyi-fastapi-backend/cli/context.py | 8 +-
ruoyi-fastapi-backend/cli/core/app_builder.py | 11 +-
.../cli/core/completion_dispatcher.py | 9 +-
.../cli/core/context_factory.py | 8 +-
.../cli/groups/app/controller.py | 9 +-
.../cli/groups/cache/controller.py | 13 +-
.../cli/groups/config/command.py | 3 +-
.../cli/groups/config/controller.py | 11 +-
.../cli/groups/config/presenter.py | 2 +-
.../cli/groups/crypto/controller.py | 9 +-
.../cli/groups/db/controller.py | 17 +-
.../cli/groups/dev/command.py | 4 +-
.../cli/groups/dev/controller.py | 7 +-
.../cli/groups/dev/presenter.py | 4 +-
.../cli/groups/gen/controller.py | 17 +-
.../cli/groups/job/controller.py | 15 +-
.../cli/groups/oidc/controller.py | 3 +-
.../cli/groups/ops/controller.py | 11 +-
.../cli/groups/ops/presenter.py | 2 +-
.../cli/groups/plugin/artifact_controller.py | 30 +-
.../cli/groups/plugin/commands/dependency.py | 5 +-
.../cli/groups/plugin/commands/lifecycle.py | 4 +-
.../cli/groups/plugin/commands/sdk.py | 2 +-
.../cli/groups/plugin/controller.py | 88 ++---
.../cli/groups/plugin/options.py | 9 +-
.../cli/groups/plugin/presenter.py | 38 +-
ruoyi-fastapi-backend/cli/main.py | 10 +-
ruoyi-fastapi-backend/cli/output.py | 2 +-
.../cli/runtime/config/service.py | 21 +-
.../cli/runtime/config/support.py | 32 +-
.../cli/runtime/crypto/support.py | 8 +-
.../cli/runtime/dev/service.py | 7 +
.../cli/runtime/gen/service.py | 16 +-
.../cli/runtime/job/service.py | 24 +-
.../cli/runtime/ops/support.py | 8 +-
.../cli/runtime/plugin/gateway.py | 21 +-
.../cli/runtime/plugin/scaffold/payload.py | 10 +-
.../cli/runtime/plugin/scaffold/v2.py | 6 +-
.../cli/runtime/plugin/sdk.py | 13 +-
.../cli/runtime/plugin/service.py | 71 ++--
.../cli/runtime/plugin/support.py | 33 +-
.../cli/tui/actions/builders.py | 3 +-
.../cli/tui/actions/execution.py | 13 +-
.../cli/tui/actions/factories/cache.py | 3 +-
.../cli/tui/actions/factories/gen.py | 5 +-
.../cli/tui/actions/factories/jobs.py | 5 +-
.../cli/tui/actions/factories/static.py | 25 +-
.../cli/tui/actions/models.py | 7 +-
.../cli/tui/actions/presentation.py | 3 +-
.../cli/tui/actions/registry.py | 3 +-
ruoyi-fastapi-backend/cli/tui/adapters/app.py | 41 +--
.../cli/tui/adapters/base.py | 30 +-
.../cli/tui/adapters/cache.py | 12 +-
.../cli/tui/adapters/crypto.py | 9 +-
ruoyi-fastapi-backend/cli/tui/adapters/gen.py | 28 +-
.../cli/tui/adapters/health.py | 27 +-
.../cli/tui/adapters/jobs.py | 6 +-
.../cli/tui/adapters/models.py | 8 +-
ruoyi-fastapi-backend/cli/tui/adapters/ops.py | 36 +-
ruoyi-fastapi-backend/cli/tui/app.py | 4 +-
ruoyi-fastapi-backend/cli/tui/capabilities.py | 7 +-
ruoyi-fastapi-backend/cli/tui/copy/actions.py | 11 +-
.../cli/tui/copy/fragments.py | 44 +--
.../cli/tui/copy/workspace.py | 4 +-
.../cli/tui/screens/browser.py | 47 +--
.../cli/tui/screens/dashboard.py | 39 +-
.../cli/tui/screens/detail.py | 45 +--
.../cli/tui/screens/focus.py | 64 +++-
.../cli/tui/screens/interactions.py | 17 +-
.../cli/tui/screens/summary.py | 11 +-
ruoyi-fastapi-backend/cli/tui/search.py | 7 +-
ruoyi-fastapi-backend/cli/wizard/base.py | 20 +-
ruoyi-fastapi-backend/cli/wizard/prompts.py | 11 +-
.../common/annotation/cache_annotation.py | 14 +-
.../common/annotation/log_annotation.py | 78 ++--
.../common/annotation/pydantic_annotation.py | 130 +++----
.../annotation/rate_limit_annotation.py | 12 +-
.../common/aspect/data_scope.py | 94 ++---
.../common/aspect/db_session.py | 4 +-
.../common/aspect/interface_auth.py | 9 +-
.../common/aspect/pre_auth.py | 4 +-
ruoyi-fastapi-backend/common/auth_policy.py | 19 +-
ruoyi-fastapi-backend/common/context.py | 33 +-
ruoyi-fastapi-backend/common/enums.py | 3 +
ruoyi-fastapi-backend/common/mixin.py | 71 ++--
ruoyi-fastapi-backend/common/vo.py | 79 ++--
ruoyi-fastapi-backend/config/database.py | 180 ++++++----
ruoyi-fastapi-backend/config/env.py | 2 +-
ruoyi-fastapi-backend/config/get_redis.py | 5 +-
.../config/scheduler/dispatcher.py | 5 +-
.../config/scheduler/events.py | 13 +-
.../config/scheduler/executors.py | 10 +-
.../config/scheduler/job_adapter.py | 6 +-
.../config/scheduler/job_execution.py | 17 +-
.../config/scheduler/jobs.py | 9 +-
.../config/scheduler/listener.py | 36 +-
.../config/scheduler/triggers.py | 4 +-
ruoyi-fastapi-backend/docs/cli_usage.md | 24 +-
.../docs/file_management_usage_guide.md | 9 +-
ruoyi-fastapi-backend/i18n/message.py | 17 +-
ruoyi-fastapi-backend/i18n/registry.py | 20 +-
ruoyi-fastapi-backend/i18n/translation.py | 2 +-
ruoyi-fastapi-backend/i18n/translator.py | 8 +-
.../transport_crypto_middleware.py | 58 +--
.../controller/captcha_controller.py | 2 +-
.../controller/config_controller.py | 2 +-
.../controller/dept_controller.py | 4 +-
.../controller/dict_controller.py | 4 +-
.../controller/file_controller.py | 2 +-
.../module_admin/controller/job_controller.py | 14 +-
.../module_admin/controller/log_controller.py | 6 +-
.../controller/login_controller.py | 27 +-
.../controller/menu_controller.py | 2 +-
.../controller/notice_controller.py | 2 +-
.../controller/online_controller.py | 2 +-
.../controller/post_controller.py | 2 +-
.../controller/role_controller.py | 25 +-
.../controller/user_controller.py | 63 ++--
.../module_admin/dao/config_dao.py | 16 +-
.../module_admin/dao/dept_dao.py | 33 +-
.../module_admin/dao/dict_dao.py | 28 +-
.../module_admin/dao/file_access_dao.py | 39 +-
.../module_admin/dao/file_business_dao.py | 14 +-
.../module_admin/dao/file_info_dao.py | 57 +--
.../module_admin/dao/job_dao.py | 8 +-
.../module_admin/dao/job_log_dao.py | 16 +-
.../module_admin/dao/job_runtime_dao.py | 16 +-
.../module_admin/dao/log_dao.py | 64 ++--
.../module_admin/dao/login_dao.py | 29 +-
.../module_admin/dao/menu_dao.py | 40 ++-
.../module_admin/dao/notice_dao.py | 18 +-
.../module_admin/dao/post_dao.py | 18 +-
.../module_admin/dao/role_dao.py | 30 +-
.../module_admin/dao/user_dao.py | 74 ++--
.../module_admin/entity/do/config_do.py | 25 +-
.../module_admin/entity/do/dept_do.py | 31 +-
.../module_admin/entity/do/dict_do.py | 61 ++--
.../module_admin/entity/do/file_do.py | 264 ++++++++------
.../module_admin/entity/do/job_do.py | 93 +++--
.../module_admin/entity/do/job_runtime_do.py | 56 +--
.../module_admin/entity/do/log_do.py | 79 ++--
.../module_admin/entity/do/menu_do.py | 55 +--
.../module_admin/entity/do/notice_do.py | 35 +-
.../module_admin/entity/do/post_do.py | 21 +-
.../module_admin/entity/do/role_do.py | 39 +-
.../module_admin/entity/do/user_do.py | 67 ++--
.../module_admin/entity/vo/cache_vo.py | 13 +-
.../module_admin/entity/vo/common_vo.py | 9 +-
.../module_admin/entity/vo/config_vo.py | 12 +-
.../module_admin/entity/vo/dept_vo.py | 22 +-
.../module_admin/entity/vo/dict_vo.py | 20 +-
.../module_admin/entity/vo/file_vo.py | 116 +++---
.../module_admin/entity/vo/job_runtime_vo.py | 24 +-
.../module_admin/entity/vo/job_vo.py | 49 +--
.../module_admin/entity/vo/log_vo.py | 24 +-
.../module_admin/entity/vo/login_vo.py | 34 +-
.../module_admin/entity/vo/menu_vo.py | 20 +-
.../module_admin/entity/vo/notice_vo.py | 28 +-
.../module_admin/entity/vo/online_vo.py | 16 +-
.../module_admin/entity/vo/post_vo.py | 12 +-
.../module_admin/entity/vo/role_vo.py | 28 +-
.../module_admin/entity/vo/server_vo.py | 26 +-
.../entity/vo/transport_crypto_vo.py | 24 +-
.../module_admin/entity/vo/user_vo.py | 93 +++--
.../module_admin/service/cache_service.py | 10 +-
.../module_admin/service/captcha_service.py | 4 +-
.../module_admin/service/common_service.py | 62 ++--
.../module_admin/service/config_service.py | 26 +-
.../module_admin/service/dept_service.py | 44 ++-
.../module_admin/service/dict_service.py | 75 ++--
.../service/file_access_service.py | 70 ++--
.../service/file_business_service.py | 42 ++-
.../module_admin/service/file_service.py | 120 ++++++-
.../module_admin/service/job_log_service.py | 36 +-
.../module_admin/service/job_service.py | 32 +-
.../module_admin/service/log_service.py | 90 ++++-
.../module_admin/service/login_service.py | 104 +++---
.../module_admin/service/menu_service.py | 35 +-
.../module_admin/service/notice_service.py | 34 +-
.../module_admin/service/online_service.py | 21 +-
.../module_admin/service/post_service.py | 24 +-
.../module_admin/service/role_service.py | 126 +++++--
.../module_admin/service/server_service.py | 16 +-
.../module_admin/service/user_service.py | 191 ++++++----
.../controller/gen_controller.py | 2 +-
.../module_generator/dao/gen_dao.py | 34 +-
.../module_generator/entity/do/gen_do.py | 106 +++---
.../module_generator/entity/vo/gen_vo.py | 40 +--
.../module_generator/service/gen_service.py | 158 ++++----
.../templates/python/service.py.jinja2 | 5 +-
.../templates/python/vo.py.jinja2 | 25 +-
.../controller/interaction_controller.py | 4 +-
.../controller/token_controller.py | 6 +-
.../dao/identity_subject_dao.py | 19 +-
.../module_identity/dao/oauth_audit_dao.py | 86 ++---
.../module_identity/dao/oauth_client_dao.py | 14 +-
.../module_identity/dao/oauth_grant_dao.py | 18 +-
.../module_identity/dao/oauth_token_dao.py | 55 +--
.../module_identity/dao/oidc_key_dao.py | 33 +-
.../module_identity/dao/sso_session_dao.py | 50 +--
.../module_identity/dependencies.py | 27 +-
.../entity/do/identity_subject_do.py | 25 +-
.../entity/do/oauth_audit_do.py | 84 +++--
.../entity/do/oauth_client_do.py | 117 +++---
.../entity/do/oauth_grant_do.py | 158 ++++----
.../entity/do/oauth_resource_do.py | 96 ++---
.../module_identity/entity/do/oidc_key_do.py | 41 ++-
.../module_identity/entity/types.py | 74 ++++
.../entity/vo/interaction_vo.py | 14 +-
.../entity/vo/oauth_client_vo.py | 17 +-
.../entity/vo/oauth_resource_vo.py | 8 +-
.../entity/vo/oauth_session_vo.py | 41 +--
.../module_identity/entity/vo/oidc_key_vo.py | 8 +-
.../module_identity/entity/vo/protocol_vo.py | 59 +--
.../security/backchannel_transport.py | 26 +-
.../module_identity/security/jwt_profile.py | 2 +
.../module_identity/security/uri_validator.py | 10 +-
.../module_identity/service/audit_service.py | 11 +-
.../service/authorization_service.py | 41 +--
.../service/consent_service.py | 5 +-
.../service/identity_service.py | 8 +-
.../service/interaction_service.py | 16 +-
.../module_identity/service/key_service.py | 36 +-
.../service/logout_confirmation_service.py | 14 +-
.../service/oauth_management_service.py | 7 +-
.../service/runtime_service.py | 3 +-
.../service/session_service.py | 89 +++--
.../service/token_protocol_service.py | 21 +-
.../module_identity/service/token_service.py | 26 +-
.../controller/plugin_browser_controller.py | 7 +-
.../controller/plugin_controller.py | 10 +-
.../controller/plugin_metrics_controller.py | 5 +-
.../module_plugin/service/plugin_service.py | 10 +-
.../ai/controller/ai_model_controller.py | 2 +-
.../plugins/ai/dao/ai_model_dao.py | 12 +-
.../plugins/ai/entity/do/ai_chat_do.py | 27 +-
.../plugins/ai/entity/do/ai_model_do.py | 41 ++-
.../plugins/ai/entity/vo/ai_chat_vo.py | 42 +--
.../plugins/ai/entity/vo/ai_model_vo.py | 12 +-
.../plugins/ai/service/ai_chat_service.py | 137 ++++---
.../plugins/ai/service/ai_model_service.py | 32 +-
.../plugins/ai/utils/ai_util.py | 21 +-
.../plugins/core/artifacts/package.py | 13 +-
.../plugins/core/artifacts/schema.py | 6 +-
.../plugins/core/artifacts/store.py | 4 +-
.../plugins/core/deployment/config.py | 4 +-
.../plugins/core/deployment/convergence.py | 2 +-
.../plugins/core/deployment/enablement.py | 4 +-
.../plugins/core/deployment/maintenance.py | 4 +-
.../plugins/core/discovery/registry.py | 3 +-
.../plugins/core/discovery/scanner.py | 7 +-
.../plugins/core/lifecycle/jobs.py | 41 ++-
.../plugins/core/management/dao/dao.py | 30 +-
.../core/management/dao/release_dao.py | 9 +-
.../core/management/entity/do/models.py | 101 +++---
.../management/entity/do/release_models.py | 63 ++--
.../core/management/entity/vo/schemas.py | 64 ++--
.../plugins/core/management/service/config.py | 27 +-
.../core/management/service/gateway.py | 143 +++++---
.../plugins/core/management/service/logs.py | 26 +-
.../plugins/core/management/service/menus.py | 31 +-
.../core/management/service/service.py | 91 +++--
.../plugins/core/manifest/__init__.py | 1 +
.../plugins/core/manifest/menu_tree.py | 5 +-
.../plugins/core/manifest/schema.py | 129 ++++---
.../plugins/core/manifest/v2.py | 26 +-
.../plugins/core/native/wheel.py | 50 ++-
.../plugins/core/runtime/application.py | 8 +-
.../plugins/core/runtime/asgi.py | 34 +-
.../plugins/core/runtime/configuration.py | 8 +-
.../plugins/core/runtime/connections.py | 16 +-
.../plugins/core/runtime/diagnostics.py | 32 +-
.../plugins/core/runtime/diagnostics_query.py | 10 +-
.../plugins/core/runtime/entrypoint.py | 19 +-
.../plugins/core/runtime/explicit.py | 50 ++-
.../plugins/core/runtime/host_services.py | 4 +-
.../plugins/core/runtime/job_dispatcher.py | 47 ++-
.../plugins/core/runtime/metrics.py | 12 +-
.../plugins/core/runtime/route_guard.py | 10 +-
.../plugins/core/runtime/service/batch.py | 44 +--
.../plugins/core/runtime/service/config.py | 23 +-
.../plugins/core/runtime/service/context.py | 9 +-
.../core/runtime/service/dependencies.py | 66 +---
.../plugins/core/runtime/service/facade.py | 148 ++++----
.../plugins/core/runtime/service/gateway.py | 15 +-
.../core/runtime/service/lifecycle/common.py | 97 ++++-
.../core/runtime/service/lifecycle/enable.py | 43 +--
.../core/runtime/service/lifecycle/install.py | 85 ++---
.../runtime/service/lifecycle/operations.py | 11 +-
.../core/runtime/service/lifecycle/purge.py | 52 +--
.../core/runtime/service/lifecycle/upgrade.py | 90 ++---
.../plugins/core/runtime/service/migration.py | 4 +-
.../core/runtime/service/migration_store.py | 4 +-
.../plugins/core/runtime/service/precheck.py | 8 +-
.../plugins/core/runtime/service/query.py | 57 ++-
.../plugins/core/runtime/service/responses.py | 3 +-
.../plugins/core/runtime/startup.py | 15 +-
.../core/runtime/startup_coordination.py | 12 +-
.../core/runtime/support/batch_report.py | 15 +-
.../core/runtime/support/npm_package.py | 5 +-
.../core/runtime/support/payload/audit.py | 4 +-
.../core/runtime/support/payload/base.py | 8 +-
.../core/runtime/support/payload/catalog.py | 13 +-
.../core/runtime/support/payload/config.py | 20 +-
.../core/runtime/support/payload/lifecycle.py | 64 ++--
.../core/runtime/support/payload/plan.py | 90 +++--
.../core/runtime/support/payload/runtime.py | 100 ++----
.../runtime/support/payload/validation.py | 77 +++-
.../plugins/core/runtime/support/precheck.py | 38 +-
.../plugins/core/sdk/context.py | 16 +-
ruoyi-fastapi-backend/plugins/core/state.py | 2 +-
ruoyi-fastapi-backend/plugins/core/types.py | 94 +++--
.../plugins/core/validation/dependencies.py | 7 +-
.../plugins/core/validation/manifest.py | 37 +-
.../plugins/core/validation/plugin_deps.py | 11 +-
.../plugins/core/validation/structure.py | 20 +-
.../examples/python/asgi_demo/__init__.py | 2 +-
.../examples/python/task_demo/__init__.py | 17 +-
ruoyi-fastapi-backend/requirements-pg.txt | 1 +
ruoyi-fastapi-backend/requirements.txt | 1 +
.../scripts/build_native_plugin.py | 19 +-
.../scripts/check_docstrings.py | 94 ++---
ruoyi-fastapi-backend/scripts/check_types.py | 56 +++
ruoyi-fastapi-backend/scripts/compile_i18n.py | 8 +-
.../scripts/migrate_job_fields.py | 11 +-
.../scripts/migrate_legacy_files.py | 24 +-
.../scripts/plugin_release_integration.py | 340 +++++++++---------
.../scripts/plugin_task_integration.py | 3 +
.../scripts/verify_timezone_database.py | 33 +-
.../tests/cli/completion/test_installers.py | 21 +-
.../tests/cli/completion/test_providers.py | 14 +-
.../tests/cli/completion/test_shells.py | 32 ++
.../cli/root/test_plugin_artifact_commands.py | 15 +-
.../root/test_plugin_command_controller.py | 189 +++-------
.../tests/cli/root/test_plugin_diagnostics.py | 14 +-
.../tests/cli/root/test_plugin_lazy_import.py | 3 +-
.../cli/root/test_plugin_release_wait.py | 7 +-
.../tests/cli/root/test_utils.py | 2 +-
.../tests/cli/runtime/plugin/conftest.py | 96 +----
.../test_runtime_dependency_allowlist.py | 1 +
.../plugin/test_runtime_dependency_lock.py | 3 +
.../runtime/plugin/test_runtime_gateway.py | 23 +-
.../plugin/test_runtime_react_scaffold.py | 12 +-
.../runtime/plugin/test_runtime_scaffold.py | 8 +-
.../plugin/test_runtime_scaffold_v2.py | 18 +-
.../runtime/plugin/test_runtime_testing.py | 9 +-
.../tests/cli/runtime/test_config.py | 33 +-
.../tests/cli/runtime/test_dev.py | 23 ++
.../tests/cli/runtime/test_job.py | 2 +-
.../cli/tui/actions/test_action_execution.py | 6 +-
.../tests/cli/tui/adapters/conftest.py | 17 +-
.../tui/adapters/test_app_ops_snapshots.py | 17 +-
.../test_cache_db_crypto_snapshots.py | 12 +-
.../test_configs_dashboard_snapshots.py | 16 +-
.../tui/adapters/test_jobs_gen_snapshots.py | 12 +-
.../tests/cli/tui/test_tui_command_app.py | 7 +
.../tests/cli/tui/test_tui_detail_screen.py | 9 +-
.../tests/cli/wizard/test_cache_clear.py | 13 +-
.../tests/cli/wizard/test_db_upgrade.py | 21 +-
.../tests/cli/wizard/test_gen_export.py | 23 +-
.../tests/cli/wizard/test_gen_import.py | 37 +-
.../tests/cli/wizard/test_prod_check.py | 17 +-
.../tests/common/test_auth_policy.py | 29 +-
.../tests/common/test_data_scope.py | 38 +-
.../tests/common/test_exception_responses.py | 8 +-
.../tests/common/test_model_aliases.py | 25 ++
.../tests/common/test_pre_auth.py | 66 +++-
.../tests/common/test_pydantic_annotation.py | 42 +++
.../tests/common/test_query_time.py | 31 +-
.../tests/common/test_request_timezone.py | 16 +-
.../tests/common/test_router_register.py | 15 +-
.../tests/common/test_types.py | 6 +-
.../test_current_user_cache_resources.py | 9 +-
.../test_current_user_cache_settings.py | 2 +-
.../test_current_user_cache_transactions.py | 36 +-
.../test_database_exception_handlers.py | 8 +-
.../tests/config/test_database_registry.py | 143 +++-----
.../tests/config/test_database_settings.py | 12 +-
.../tests/config/test_oidc_settings.py | 20 +-
.../test_scheduler_execution_coordination.py | 16 +-
.../config/test_scheduler_execution_retry.py | 10 +-
.../tests/config/test_scheduler_executor.py | 16 +-
.../tests/config/test_scheduler_fields.py | 31 +-
.../config/test_scheduler_job_persistence.py | 33 +-
.../tests/config/test_scheduler_job_sync.py | 17 +-
.../config/test_scheduler_leader_lease.py | 5 +-
.../tests/config/test_scheduler_runtime.py | 27 +-
.../config/test_scheduler_sql_logging.py | 11 +-
.../tests/i18n/test_catalog_domains.py | 100 +++---
.../i18n/test_database_initialization.py | 9 +-
.../tests/i18n/test_dict_cache_publication.py | 43 +--
.../tests/i18n/test_excel_i18n.py | 12 +-
.../tests/i18n/test_locale.py | 12 +-
.../tests/i18n/test_locale_revision.py | 36 +-
.../tests/i18n/test_plugin_messages.py | 6 +-
.../tests/i18n/test_response_completion.py | 20 +-
.../tests/i18n/test_translations.py | 41 ++-
.../controller/test_dept_controller.py | 12 +-
.../controller/test_user_controller.py | 35 +-
.../tests/module_admin/dao/test_log_sort.py | 38 ++
.../dao/test_user_auth_queries.py | 2 +-
.../module_admin/service/file_helpers.py | 25 ++
.../tests/module_admin/service/helpers.py | 66 ++++
.../service/test_cached_session_races.py | 3 +-
.../service/test_common_file_security.py | 159 ++++----
.../test_current_user_cache_integration.py | 13 +-
.../test_current_user_cache_mutations.py | 25 +-
.../service/test_current_user_resolution.py | 2 +-
.../module_admin/service/test_dept_service.py | 54 ++-
.../service/test_file_access_log.py | 74 ++--
.../module_admin/service/test_file_acl.py | 129 +++----
...test_file_lifecycle_retention_execution.py | 50 +--
.../service/test_file_management.py | 144 ++++----
.../service/test_file_reconcile.py | 36 +-
.../service/test_file_reference.py | 36 +-
.../service/test_file_retention_policy.py | 22 +-
.../test_identity_security_integration.py | 59 +--
.../module_admin/service/test_job_service.py | 56 +--
.../service/test_login_plugin_routes.py | 8 +-
.../service/test_login_service.py | 87 +++--
.../service/test_login_session_renewal.py | 113 ++++--
.../module_admin/service/test_menu_service.py | 51 +--
.../service/test_notice_html_security.py | 29 +-
.../service/test_notice_service.py | 8 +-
.../service/test_online_service.py | 3 +-
.../service/test_server_service.py | 6 +
.../module_admin/service/test_user_service.py | 83 ++++-
.../service/test_user_timezone.py | 23 +-
.../module_generator/dao/test_gen_dao.py | 45 +--
.../module_generator/test_gen_service.py | 74 +++-
.../module_generator/test_generated_i18n.py | 38 +-
.../test_generated_time_contract.py | 87 +++--
.../module_generator/test_react_templates.py | 5 +-
.../test_architecture_boundaries.py | 6 +-
.../tests/module_identity/conftest.py | 3 +-
.../module_identity/controllers/conftest.py | 2 +
.../test_authorization_controller.py | 102 ++----
.../controllers/test_client_ip_resolution.py | 12 +-
.../controllers/test_discovery_controller.py | 121 ++-----
.../test_interaction_controller.py | 320 ++++++-----------
.../controllers/test_logout_confirmation.py | 40 ++-
.../test_oauth_audit_controller.py | 30 +-
.../test_oauth_client_controller.py | 36 +-
.../test_oauth_resource_controller.py | 41 +--
.../test_oauth_session_controller.py | 64 ++--
.../controllers/test_oidc_key_controller.py | 48 +--
.../controllers/test_token_controller.py | 81 ++---
.../controllers/test_userinfo_controller.py | 15 +-
.../dao/test_grant_policy_dao.py | 1 +
.../module_identity/dao/test_oidc_key_dao.py | 8 +-
.../dao/test_refresh_token_dao.py | 8 +-
.../models/test_identity_models.py | 24 +-
.../models/test_oidc_key_vo.py | 10 +-
.../models/test_protocol_vo.py | 10 +-
.../security/test_client_auth.py | 4 +-
.../security/test_identity_dependencies.py | 20 +-
.../security/test_jwt_profile.py | 28 +-
.../security/test_redis_keys.py | 14 +-
.../services/test_audit_service.py | 27 +-
.../test_authentication_regressions.py | 54 +--
.../test_authorization_code_service.py | 50 +--
.../services/test_authorization_service.py | 2 +-
.../services/test_consent_service.py | 4 +-
.../test_credential_authentication_service.py | 80 +++--
.../test_identity_security_event_service.py | 20 +-
.../services/test_identity_subject_service.py | 5 +-
.../services/test_interaction_service.py | 72 ++--
.../services/test_introspection_service.py | 27 +-
.../services/test_key_service.py | 83 +----
.../module_identity/services/test_logout.py | 67 ++--
.../services/test_oauth_management_service.py | 66 ++--
.../test_oauth_resource_scope_management.py | 41 ++-
.../services/test_review_completion.py | 28 +-
.../services/test_review_regressions.py | 23 +-
.../services/test_revocation_service.py | 21 +-
.../services/test_sso_session_service.py | 78 ++--
.../services/test_token_service.py | 93 ++---
.../tests/module_identity/support/http.py | 36 ++
.../module_identity/support/redis_fakes.py | 11 +-
.../tests/module_identity/support/sessions.py | 24 ++
.../controller/test_plugin_controller.py | 111 +++---
.../test_plugin_diagnostics_controller.py | 9 +-
.../test_plugin_metrics_controller.py | 18 +-
.../test_plugin_release_controller.py | 23 +-
.../service/test_plugin_service.py | 36 +-
.../tests/plugins/core/deployment/conftest.py | 2 +-
.../core/deployment/test_convergence.py | 9 +-
.../deployment/test_deployment_catalog.py | 1 +
.../core/deployment/test_enablement.py | 23 +-
.../core/deployment/test_maintenance.py | 4 +-
.../plugins/core/deployment/test_service.py | 18 +-
.../core/deployment/test_task_delivery.py | 4 +-
.../plugins/core/deployment/test_worker.py | 62 ++--
.../plugins/core/discovery/test_registry.py | 31 +-
.../core/management/test_artifact_views.py | 15 +-
.../core/management/test_menu_installer.py | 27 +-
.../core/management/test_plugin_state.py | 273 ++++++++------
.../core/management/test_release_dao.py | 18 +-
.../tests/plugins/core/native/test_wheel.py | 23 +-
.../plugins/core/runtime/fakes/environment.py | 80 +----
.../plugins/core/runtime/fakes/factory.py | 2 +-
.../plugins/core/runtime/fakes/gateway.py | 222 +++---------
.../plugins/core/runtime/fakes/management.py | 254 ++++++-------
.../plugins/core/runtime/fakes/session.py | 33 +-
.../runtime/service/test_artifact_guards.py | 23 +-
.../service/test_batch_dependencies.py | 42 ++-
.../core/runtime/service/test_catalog.py | 85 ++---
.../core/runtime/service/test_check_docs.py | 28 +-
.../runtime/service/test_gateway_ports.py | 15 +-
.../service/test_install_config_health.py | 249 ++++---------
.../runtime/service/test_structure_checks.py | 6 +
.../service/test_upgrade_enable_purge.py | 177 +++++----
.../support/test_dependency_payloads.py | 3 +-
.../tests/plugins/core/runtime/test_asgi.py | 8 +-
.../core/runtime/test_browser_session.py | 19 +-
.../tests/plugins/core/runtime/test_bundle.py | 11 +-
.../core/runtime/test_configuration.py | 22 +-
.../core/runtime/test_connection_sessions.py | 6 +-
.../plugins/core/runtime/test_connections.py | 13 +-
.../plugins/core/runtime/test_diagnostics.py | 54 ++-
.../core/runtime/test_diagnostics_store.py | 12 +-
.../plugins/core/runtime/test_explicit.py | 43 ++-
.../tests/plugins/core/runtime/test_health.py | 4 +-
.../runtime/test_host_service_extensions.py | 4 +-
.../core/runtime/test_host_services.py | 2 +-
.../core/runtime/test_job_dispatcher.py | 8 +-
.../plugins/core/runtime/test_metrics.py | 10 +-
.../core/runtime/test_metrics_store.py | 8 +-
.../core/runtime/test_plugin_bootstrap.py | 18 +-
.../plugins/core/runtime/test_route_guard.py | 5 +-
.../plugins/core/runtime/test_sdk_requests.py | 6 +-
.../plugins/core/runtime/test_startup.py | 11 +-
.../plugins/core/runtime/test_task_cleanup.py | 4 +-
.../tests/plugins/core/test_state.py | 12 +-
.../core/validation/test_dependency_policy.py | 4 +-
.../validation/test_frontend_dependencies.py | 8 +-
.../plugins/core/validation/test_manifest.py | 7 +-
.../core/validation/test_manifest_v2.py | 33 ++
.../core/validation/test_plugin_deps.py | 10 +-
.../tests/plugins/examples/test_task_demo.py | 15 +-
.../integration/test_harness_safety.py | 60 +++-
.../plugins/integration/test_network_smoke.py | 4 +-
.../integration/test_network_smoke_runner.py | 6 +-
.../native/test_native_bundle_build.py | 9 +-
.../tests/plugins/native/test_rust_demo.py | 23 +-
.../plugins/sample_plugins/test_ai_i18n.py | 11 +-
.../plugins/sample_plugins/test_ai_plugin.py | 48 +--
.../test_ai_react_integration.py | 33 +-
ruoyi-fastapi-backend/tests/redis_helpers.py | 23 +-
.../tests/scheduler_helpers.py | 61 ++--
.../scripts/test_migrate_legacy_files.py | 1 +
.../tests/server/test_oidc_cors_refresh.py | 23 +-
.../tests/server/test_oidc_runtime.py | 25 +-
.../tests/server/test_plugin_runtime.py | 28 +-
.../tests/sql/test_plugin_release_schema.py | 7 +-
.../tests/test_api_docs_auth.py | 16 +-
.../tests/test_audit_time_delegation.py | 16 +-
.../tests/test_entity_time_columns.py | 8 +-
.../utils/test_application_leader_lease.py | 22 +-
.../utils/test_current_user_cache_util.py | 62 ++--
.../tests/utils/test_log_sanitize_util.py | 33 +-
.../tests/utils/test_page_util.py | 55 +++
.../tests/utils/test_response_timezone.py | 2 +-
.../tests/utils/test_startup_log_filter.py | 39 +-
.../tests/utils/test_template_util.py | 263 +++++++-------
.../tests/utils/test_time_util.py | 5 +-
ruoyi-fastapi-backend/ty.toml | 15 +
.../utils/api_annotation_util.py | 6 +-
ruoyi-fastapi-backend/utils/cache_util.py | 14 +-
ruoyi-fastapi-backend/utils/common_util.py | 8 +-
ruoyi-fastapi-backend/utils/cron_util.py | 14 +-
ruoyi-fastapi-backend/utils/crypto_util.py | 2 +-
.../utils/dependency_util.py | 4 +-
ruoyi-fastapi-backend/utils/excel_util.py | 4 +-
ruoyi-fastapi-backend/utils/file_util.py | 8 +-
ruoyi-fastapi-backend/utils/gen_i18n_util.py | 22 +-
ruoyi-fastapi-backend/utils/gen_util.py | 28 +-
ruoyi-fastapi-backend/utils/import_util.py | 6 +-
ruoyi-fastapi-backend/utils/jwt_util.py | 3 +-
ruoyi-fastapi-backend/utils/log_util.py | 29 +-
ruoyi-fastapi-backend/utils/oidc_util.py | 16 +-
ruoyi-fastapi-backend/utils/openapi_util.py | 29 +-
ruoyi-fastapi-backend/utils/page_util.py | 118 ++++--
ruoyi-fastapi-backend/utils/pwd_util.py | 2 +-
ruoyi-fastapi-backend/utils/server_util.py | 54 +--
ruoyi-fastapi-backend/utils/string_util.py | 6 +-
ruoyi-fastapi-backend/utils/template_util.py | 83 +++--
.../utils/transport_crypto_util.py | 38 +-
ruoyi-fastapi-backend/utils/upload_util.py | 4 +-
.../utils/user_import_util.py | 7 +-
ruoyi-fastapi-test/common/base_page_test.py | 39 +-
ruoyi-fastapi-test/common/browser_harness.py | 20 +-
ruoyi-fastapi-test/common/login_helper.py | 2 +-
ruoyi-fastapi-test/conftest.py | 15 +-
.../monitor/test_job_management.py | 1 +
ruoyi-fastapi-test/requirements.txt | 1 +
ruoyi-fastapi-test/system/page.py | 2 +-
.../system/test_plugin_management.py | 14 +-
ruoyi-fastapi-test/test_browser_harness.py | 3 +-
ruoyi-fastapi-test/test_code_gen_harness.py | 4 +-
ruoyi-fastapi-test/test_pages.py | 7 +-
.../test_plugin_network_harness.py | 6 +-
ruoyi-fastapi-test/tool/test_code_gen.py | 5 +-
ruoyi-fastapi-test/ty.toml | 15 +
ty.toml | 16 +
618 files changed, 11011 insertions(+), 9024 deletions(-)
create mode 100644 .github/ty.toml
create mode 100644 ruoyi-fastapi-backend/module_identity/entity/types.py
create mode 100644 ruoyi-fastapi-backend/scripts/check_types.py
create mode 100644 ruoyi-fastapi-backend/tests/common/test_model_aliases.py
create mode 100644 ruoyi-fastapi-backend/tests/common/test_pydantic_annotation.py
create mode 100644 ruoyi-fastapi-backend/tests/module_admin/dao/test_log_sort.py
create mode 100644 ruoyi-fastapi-backend/tests/module_admin/service/file_helpers.py
create mode 100644 ruoyi-fastapi-backend/tests/module_admin/service/helpers.py
create mode 100644 ruoyi-fastapi-backend/tests/module_identity/support/http.py
create mode 100644 ruoyi-fastapi-backend/tests/module_identity/support/sessions.py
create mode 100644 ruoyi-fastapi-backend/tests/utils/test_page_util.py
create mode 100644 ruoyi-fastapi-backend/ty.toml
create mode 100644 ruoyi-fastapi-test/ty.toml
create mode 100644 ty.toml
diff --git a/.github/scripts/mobile_smoke.py b/.github/scripts/mobile_smoke.py
index 27b2d60d4..d9f6d934e 100644
--- a/.github/scripts/mobile_smoke.py
+++ b/.github/scripts/mobile_smoke.py
@@ -20,10 +20,11 @@
TOKEN = 'isolated-mobile-smoke-token'
LOGIN_BUTTON_MIN_WIDTH = 250
LOGIN_BUTTON_MIN_HEIGHT = 44
+NICKNAME = '移动端 CI'
USER = {
'userId': 7,
'userName': 'ci-user',
- 'nickName': '移动端 CI',
+ 'nickName': NICKNAME,
'avatar': '',
'phonenumber': '13800000000',
'email': 'mobile-ci@example.test',
@@ -179,9 +180,7 @@ async def run_smoke(framework: str, base_url: str, output: Path) -> None:
async with async_playwright() as playwright:
executable = os.environ.get('RUOYI_SMOKE_BROWSER_EXECUTABLE')
- browser = await playwright.chromium.launch(
- headless=True, **({'executable_path': executable} if executable else {})
- )
+ browser = await playwright.chromium.launch(headless=True, executable_path=executable or None)
context = await browser.new_context(viewport={'width': 390, 'height': 844}, timezone_id='UTC')
await context.tracing.start(screenshots=True, snapshots=True, sources=True)
await context.route('http://localhost:9099/**', api)
@@ -203,7 +202,7 @@ async def run_smoke(framework: str, base_url: str, output: Path) -> None:
await login_button.click()
await expect(page).to_have_url(re.compile(r'/pages/index'), timeout=30000)
await page.goto(f'{base_url}/#/pages/mine/info/index')
- await expect(page.get_by_text(USER['nickName'], exact=True)).to_be_visible(timeout=30000)
+ await expect(page.get_by_text(NICKNAME, exact=True)).to_be_visible(timeout=30000)
await expect(page.get_by_text('Nickname', exact=True)).to_be_visible(timeout=15000)
created_at = await page.evaluate(
"""({locale, timeZone, createTime}) => new Intl.DateTimeFormat(locale, {
diff --git a/.github/tests/test_ci_contracts.py b/.github/tests/test_ci_contracts.py
index f08a75974..cd3544384 100644
--- a/.github/tests/test_ci_contracts.py
+++ b/.github/tests/test_ci_contracts.py
@@ -18,6 +18,7 @@ def load_script(name: str) -> ModuleType:
:return: 已执行模块顶层定义的脚本模块
"""
spec = importlib.util.spec_from_file_location(name, ROOT / '.github/scripts' / f'{name}.py')
+ assert spec is not None and spec.loader is not None, name
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
diff --git a/.github/tests/test_ci_plan.py b/.github/tests/test_ci_plan.py
index 5e0988800..dc3af1b2d 100644
--- a/.github/tests/test_ci_plan.py
+++ b/.github/tests/test_ci_plan.py
@@ -5,6 +5,7 @@
SCRIPT = Path(__file__).resolve().parents[1] / 'scripts' / 'ci_plan.py'
SPEC = importlib.util.spec_from_file_location('ci_plan', SCRIPT)
+assert SPEC is not None and SPEC.loader is not None, SCRIPT
ci = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(ci)
FRONTEND_PROJECT_COUNT = 6
@@ -167,7 +168,10 @@ def test_full_run_preserves_python_database_and_framework_combinations() -> None
def test_gate_rejects_unsuccessful_required_job(result: str | None) -> None:
"""必跑任务失败、取消、跳过或缺失均不能通过门禁。"""
plan = ci.build_plan(['README.md'])
- needs = {'plan': {'result': 'success'}, **{name: {'result': 'skipped'} for name in ci.CATEGORIES}}
+ needs: dict[str, dict[str, str | None]] = {
+ 'plan': {'result': 'success'},
+ **{name: {'result': 'skipped'} for name in ci.CATEGORIES},
+ }
needs['quality']['result'] = result
assert ci.check_results(plan, needs)
diff --git a/.github/tests/test_ci_python_matrix.py b/.github/tests/test_ci_python_matrix.py
index 1ba3c1991..11fc1bd5c 100644
--- a/.github/tests/test_ci_python_matrix.py
+++ b/.github/tests/test_ci_python_matrix.py
@@ -21,6 +21,7 @@ def load_module(name: str, path: Path) -> ModuleType:
:return: 提供被测功能的模块
"""
spec = importlib.util.spec_from_file_location(name, path)
+ assert spec is not None and spec.loader is not None, path
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@@ -37,6 +38,19 @@ def test_backend_and_native_cover_full_e2e_python_versions(workflow: str, job: s
assert config['jobs'][job]['strategy']['matrix']['python'] == list(ci.PYTHON_VERSIONS)
+@pytest.mark.parametrize('workflow,job', [('ci-backend.yml', 'unit-contract'), ('ci-quality.yml', 'type-check')])
+def test_type_checks_run_on_every_supported_python(workflow: str, job: str) -> None:
+ """后端、浏览器测试和 CI 脚本的类型检查应在每个受支持版本运行。"""
+ config = yaml.safe_load((ROOT / '.github/workflows' / workflow).read_text(encoding='utf-8'))
+ matrix_job = config['jobs'][job]
+ assert matrix_job['strategy']['matrix']['python'] == list(ci.PYTHON_VERSIONS)
+ (setup,) = (step for step in matrix_job['steps'] if step.get('uses', '').startswith('actions/setup-python@'))
+ assert setup['with']['python-version'] == '${{ matrix.python }}'
+ (check,) = (step for step in matrix_job['steps'] if 'scripts/check_types.py' in step.get('run', ''))
+ assert 'if' not in check
+ assert '--python-version ${{ matrix.python }}' in check['run']
+
+
def test_release_covers_full_matrix_and_preserves_pr_baseline() -> None:
"""插件发布的完整矩阵跟随 E2E,PR 仍使用单版本基线。"""
config = yaml.safe_load((ROOT / '.github/workflows/ci-integration.yml').read_text(encoding='utf-8'))
diff --git a/.github/ty.toml b/.github/ty.toml
new file mode 100644
index 000000000..8198b1807
--- /dev/null
+++ b/.github/ty.toml
@@ -0,0 +1,15 @@
+[environment]
+python-platform = "all"
+python-version = "3.11"
+
+[rules]
+blanket-ignore-comment = "error"
+disjoint-cast = "error"
+mismatched-enum-name = "error"
+mismatched-namedtuple-name = "error"
+mismatched-sentinel-name = "error"
+unsound-return = "error"
+unsound-yield = "error"
+
+[terminal]
+error-on-warning = true
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index b7f41ae3c..25c523481 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -31,6 +31,7 @@ jobs:
cache-dependency-path: |
ruoyi-fastapi-backend/requirements*.txt
ruoyi-fastapi-backend/plugins/ai/plugin.yaml
+ ruoyi-fastapi-test/requirements.txt
- name: Install MySQL, PostgreSQL and test dependencies
run: python -m pip install -r requirements.txt -r requirements-pg.txt -r requirements-test.txt
- name: Compile and validate gettext catalogs
@@ -64,6 +65,10 @@ jobs:
run: python ../.github/scripts/install_ai_test_dependencies.py
- name: Check dependency consistency
run: python -m pip check
+ - name: Type-check backend, plugins and tests
+ run: |
+ python -m pip install -c ../ruoyi-fastapi-test/requirements.txt playwright
+ python scripts/check_types.py --python-version ${{ matrix.python }} .
- name: Run backend unit and contract tests
run: python -m pytest tests -q -m 'not browser and not native and not integration' --strict-markers --durations=20 --junitxml=target/ci/backend.xml
- name: Verify tests were executed
diff --git a/.github/workflows/ci-quality.yml b/.github/workflows/ci-quality.yml
index 2d607529b..72544875e 100644
--- a/.github/workflows/ci-quality.yml
+++ b/.github/workflows/ci-quality.yml
@@ -7,6 +7,25 @@ permissions:
contents: read
jobs:
+ type-check:
+ name: Browser and CI types on Python ${{ matrix.python }}
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ python: ['3.11', '3.12', '3.13', '3.14', '3.15']
+ steps:
+ - uses: actions/checkout@v5
+ - uses: actions/setup-python@v6
+ with:
+ python-version: ${{ matrix.python }}
+ cache: pip
+ cache-dependency-path: |
+ .github/requirements.txt
+ ruoyi-fastapi-test/requirements.txt
+ - run: python -m pip install -r .github/requirements.txt -r ruoyi-fastapi-test/requirements.txt
+ - run: python ruoyi-fastapi-backend/scripts/check_types.py --python-version ${{ matrix.python }} ruoyi-fastapi-test .github
+
checks:
name: Code and CI contracts
runs-on: ubuntu-latest
@@ -17,8 +36,10 @@ jobs:
with:
python-version: '3.12'
cache: pip
- cache-dependency-path: .github/requirements.txt
- - run: python -m pip install -r .github/requirements.txt
+ cache-dependency-path: |
+ .github/requirements.txt
+ ruoyi-fastapi-test/requirements.txt
+ - run: python -m pip install -r .github/requirements.txt -r ruoyi-fastapi-test/requirements.txt
- name: Python lint and format
run: |
ruff check ruoyi-fastapi-backend ruoyi-fastapi-test .github/scripts .github/tests
diff --git a/ruoyi-fastapi-backend/.x18n/scan_python_domains.py b/ruoyi-fastapi-backend/.x18n/scan_python_domains.py
index 7aad60097..d8d3ab948 100644
--- a/ruoyi-fastapi-backend/.x18n/scan_python_domains.py
+++ b/ruoyi-fastapi-backend/.x18n/scan_python_domains.py
@@ -64,6 +64,8 @@ def position(line: int, column: int) -> int:
raise ValueError(
f'{source["path"]}:{node.lineno}: static message requires a literal or module constant domain'
)
+ if key.end_lineno is None or key.end_col_offset is None:
+ raise ValueError(f'{source["path"]}:{key.lineno}: missing end position for message key')
usages.append(
{
'domain': domain.value,
diff --git a/ruoyi-fastapi-backend/alembic/env.py b/ruoyi-fastapi-backend/alembic/env.py
index 5ddb69120..a643e14b2 100644
--- a/ruoyi-fastapi-backend/alembic/env.py
+++ b/ruoyi-fastapi-backend/alembic/env.py
@@ -1,12 +1,12 @@
import asyncio
import os
-from collections.abc import Iterable, MutableMapping
+from collections.abc import Iterable
from logging.config import fileConfig
-from typing import Literal
from alembic import context
from alembic.migration import MigrationContext
from alembic.operations.ops import MigrationScript
+from alembic.runtime.environment import NameFilterParentNames, NameFilterType
from sqlalchemy.engine import Connection
from config.database import Base, DataSourceRegistry, build_async_sqlalchemy_database_url
@@ -79,8 +79,8 @@ def run_migrations_offline() -> None:
def do_run_migrations(connection: Connection) -> None:
def include_name(
name: str | None,
- type_: Literal['schema', 'table', 'column', 'index', 'unique_constraint', 'foreign_key_constraint'],
- parent_names: MutableMapping[Literal['schema_name', 'table_name', 'schema_qualified_table_name'], str | None],
+ type_: NameFilterType,
+ parent_names: NameFilterParentNames,
) -> bool:
if type_ == 'table':
return name in target_metadata.tables
diff --git a/ruoyi-fastapi-backend/cli/completion/controller.py b/ruoyi-fastapi-backend/cli/completion/controller.py
index 1fc1f45dc..b09c69687 100644
--- a/ruoyi-fastapi-backend/cli/completion/controller.py
+++ b/ruoyi-fastapi-backend/cli/completion/controller.py
@@ -5,6 +5,7 @@
from cli.completion.doctor import COMPLETION_DOCTOR, CompletionDoctorService
from cli.completion.installers import COMPLETION_INSTALLER, CompletionInstallerService
from cli.completion.presenter import CompletionCommandPresenter
+from cli.context import OutputFormat
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
@@ -64,7 +65,7 @@ def show(self, shell: str) -> None:
def install(
self,
- output: str,
+ output: OutputFormat,
*,
shell: str | None,
target_file: Path | None,
@@ -97,7 +98,7 @@ def install(
text_builder=self.presenter.build_completion_install_text,
)
- def doctor(self, output: str) -> None:
+ def doctor(self, output: OutputFormat) -> None:
"""
检查当前 completion 配置状态。
diff --git a/ruoyi-fastapi-backend/cli/completion/installers.py b/ruoyi-fastapi-backend/cli/completion/installers.py
index d67c1f7bf..02fc5f9db 100644
--- a/ruoyi-fastapi-backend/cli/completion/installers.py
+++ b/ruoyi-fastapi-backend/cli/completion/installers.py
@@ -1,5 +1,6 @@
import io
import os
+from collections.abc import Callable
from contextlib import redirect_stderr
from dataclasses import dataclass
from pathlib import Path
@@ -9,6 +10,7 @@
import typer
import typer.main
from click.shell_completion import BashComplete, FishComplete, ShellComplete, ZshComplete
+from typer._click import Command as TyperClickCommand
from cli.completion.providers import COMPLETION_PROVIDER_GATEWAY, CompletionProviderGateway
from cli.completion.shells import PowerShellComplete, ensure_custom_completion_classes_registered
@@ -104,7 +106,7 @@ def make_bash_completion_script_compatible(script_text: str) -> str:
return '\n'.join(compatible_lines) + '\n'
@staticmethod
- def build_posix_source_command(target_file: Path) -> str:
+ def build_posix_source_command(target_file: Path | str) -> str:
"""
构建 POSIX shell 使用的 source 命令。
@@ -114,7 +116,7 @@ def build_posix_source_command(target_file: Path) -> str:
return f'source {target_file}'
@staticmethod
- def build_fish_source_command(target_file: Path) -> str:
+ def build_fish_source_command(target_file: Path | str) -> str:
"""
构建 Fish shell 使用的 source 命令。
@@ -124,7 +126,7 @@ def build_fish_source_command(target_file: Path) -> str:
return f'status --is-interactive; and source {target_file}'
@staticmethod
- def build_powershell_source_command(target_file: Path) -> str:
+ def build_powershell_source_command(target_file: Path | str) -> str:
"""
构建 PowerShell 使用的 source 命令。
@@ -146,9 +148,9 @@ class CompletionShellRuntimePolicy:
"""
name: str
- click_completion_class: type[Any]
- script_transformer: Any
- source_command_builder: Any
+ click_completion_class: type[ShellComplete]
+ script_transformer: Callable[[str], str]
+ source_command_builder: Callable[[str], str]
@dataclass(frozen=True)
@@ -262,9 +264,9 @@ def resolve_shell_runtime_policy(self, shell: str) -> CompletionShellRuntimePoli
return runtime_policy
@staticmethod
- def build_completion_click_command(root_cli: typer.Typer) -> click.Command:
+ def build_completion_click_command(root_cli: typer.Typer) -> TyperClickCommand:
"""
- 将 Typer 根应用转换为 Click 命令对象,供 shell completion 生成使用。
+ 将 Typer 根应用转换为其可执行的 Click 命令。
:param root_cli: Typer 根应用
:return: Click 命令对象
@@ -289,7 +291,7 @@ def render_completion_script(self, root_cli: typer.Typer, shell: str) -> str:
stderr_buffer = io.StringIO()
with redirect_stderr(stderr_buffer):
script_text = runtime_policy.click_completion_class(
- click_command,
+ click.Command(click_command.name),
{},
'ruoyi',
CLICK_COMPLETE_ENV_VAR,
diff --git a/ruoyi-fastapi-backend/cli/completion/providers.py b/ruoyi-fastapi-backend/cli/completion/providers.py
index 2d6912aba..fe4ed050a 100644
--- a/ruoyi-fastapi-backend/cli/completion/providers.py
+++ b/ruoyi-fastapi-backend/cli/completion/providers.py
@@ -5,7 +5,7 @@
from pathlib import Path
from typing import Any
-import click
+from typer._click import Context
from cli.metadata import (
COMPLETION_SHELL_SPEC_REGISTRY,
@@ -28,7 +28,7 @@ class CompletionContextResolver:
将原本散落的参数与环境变量解析逻辑收口到单一职责对象中。
"""
- def resolve_completion_env(self, ctx: click.Context | None) -> str:
+ def resolve_completion_env(self, ctx: Context | None) -> str:
"""
解析当前 completion 场景使用的环境名称。
@@ -36,7 +36,7 @@ def resolve_completion_env(self, ctx: click.Context | None) -> str:
:return: 环境名称,默认返回 ``dev``
"""
if ctx is not None:
- env_value = getattr(ctx, 'params', {}).get('env')
+ env_value: object = ctx.params.get('env')
if isinstance(env_value, str) and env_value.strip():
return env_value.strip()
@@ -55,7 +55,7 @@ def resolve_completion_env(self, ctx: click.Context | None) -> str:
return 'dev'
- def resolve_cache_name_for_completion(self, ctx: click.Context | None) -> str:
+ def resolve_cache_name_for_completion(self, ctx: Context | None) -> str:
"""
解析当前 cache key 补全场景使用的缓存名称。
@@ -63,7 +63,7 @@ def resolve_cache_name_for_completion(self, ctx: click.Context | None) -> str:
:return: 缓存名称,缺失时返回空字符串
"""
if ctx is not None:
- cache_name = getattr(ctx, 'params', {}).get('cache_name')
+ cache_name: object = ctx.params.get('cache_name')
if isinstance(cache_name, str) and cache_name.strip():
return cache_name.strip()
@@ -299,7 +299,7 @@ def filter_candidates(candidates: list[str], incomplete: str) -> list[str]:
def complete_dynamic_items(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
incomplete: str,
*,
runtime_module_name: str,
@@ -339,7 +339,7 @@ def complete_dynamic_items(
def complete_dynamic_list(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
incomplete: str,
*,
runtime_module_name: str,
@@ -421,7 +421,7 @@ def list_static_cache_names(self) -> list[str]:
def complete_env_values(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -443,7 +443,7 @@ def complete_env_values(
def complete_shell_names(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -463,7 +463,7 @@ def complete_shell_names(
def complete_cache_names(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -485,7 +485,7 @@ def complete_cache_names(
def complete_alembic_revisions(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -524,7 +524,7 @@ class PathCompletionProvider:
def complete_sql_files(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -550,7 +550,7 @@ def complete_sql_files(
def complete_output_paths(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -617,7 +617,7 @@ def __post_init__(self) -> None:
def complete_config_keys(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -642,7 +642,7 @@ def complete_config_keys(
def complete_gen_table_names(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -667,7 +667,7 @@ def complete_gen_table_names(
def complete_gen_db_table_names(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -692,7 +692,7 @@ def complete_gen_db_table_names(
def complete_cache_keys(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -720,7 +720,7 @@ def complete_cache_keys(
def complete_job_names(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -745,7 +745,7 @@ def complete_job_names(
def complete_job_ids(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -834,7 +834,7 @@ def list_static_cache_names(self) -> list[str]:
def complete_env_values(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -850,7 +850,7 @@ def complete_env_values(
def complete_shell_names(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -866,7 +866,7 @@ def complete_shell_names(
def complete_cache_names(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -882,7 +882,7 @@ def complete_cache_names(
def complete_alembic_revisions(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -898,7 +898,7 @@ def complete_alembic_revisions(
def complete_sql_files(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -914,7 +914,7 @@ def complete_sql_files(
def complete_output_paths(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -930,7 +930,7 @@ def complete_output_paths(
def complete_config_keys(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -946,7 +946,7 @@ def complete_config_keys(
def complete_gen_table_names(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -962,7 +962,7 @@ def complete_gen_table_names(
def complete_gen_db_table_names(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -978,7 +978,7 @@ def complete_gen_db_table_names(
def complete_cache_keys(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -994,7 +994,7 @@ def complete_cache_keys(
def complete_job_names(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
@@ -1010,7 +1010,7 @@ def complete_job_names(
def complete_job_ids(
self,
- ctx: click.Context | None,
+ ctx: Context | None,
args: list[str] | None,
incomplete: str,
) -> list[str]:
diff --git a/ruoyi-fastapi-backend/cli/completion/shells.py b/ruoyi-fastapi-backend/cli/completion/shells.py
index 0ce38f0f8..d690a827f 100644
--- a/ruoyi-fastapi-backend/cli/completion/shells.py
+++ b/ruoyi-fastapi-backend/cli/completion/shells.py
@@ -1,5 +1,6 @@
import os
+import click
from click.shell_completion import (
CompletionItem,
ShellComplete,
@@ -7,6 +8,8 @@
get_completion_class,
split_arg_string,
)
+from typer._click import Command
+from typer.completion import shell_completion
_SOURCE_POWERSHELL = """\
$%(complete_func)s = {
@@ -111,3 +114,31 @@ def ensure_custom_completion_classes_registered() -> None:
# Click 8.5 新增同名实现,但其数字索引协议与本项目脚本的文本参数协议不同。
if get_completion_class(PowerShellComplete.name) is not PowerShellComplete:
add_completion_class(PowerShellComplete)
+
+
+def dispatch_click_completion(command: Command, instruction: str, complete_var: str) -> int:
+ """
+ 按 Click 脚本的协议为 Typer 命令树提供补全。
+
+ :param command: Typer 创建的根命令
+ :param instruction: 包含 shell 名称和动作的 Click 指令
+ :param complete_var: 脚本使用的补全环境变量名
+ :return: 补全进程退出码
+ """
+ shell, _, action = instruction.partition('_')
+ formatter_class = get_completion_class(shell)
+ if formatter_class is None:
+ return 1
+ formatter = formatter_class(click.Command(command.name), {}, 'ruoyi', complete_var)
+ if action == 'source':
+ click.echo(formatter.source().encode(), nl=False)
+ return 0
+
+ resolver_class = shell_completion.get_completion_class(shell)
+ if action != 'complete' or resolver_class is None:
+ return 1
+ resolver = resolver_class(command, {}, 'ruoyi', complete_var)
+ items = resolver.get_completions(*formatter.get_completion_args())
+ lines = (formatter.format_completion(CompletionItem(item.value, type=item.type, help=item.help)) for item in items)
+ click.echo('\n'.join(lines).encode())
+ return 0
diff --git a/ruoyi-fastapi-backend/cli/context.py b/ruoyi-fastapi-backend/cli/context.py
index 2749b398f..4fe08c4b0 100644
--- a/ruoyi-fastapi-backend/cli/context.py
+++ b/ruoyi-fastapi-backend/cli/context.py
@@ -5,6 +5,8 @@
from cli.completion.providers import COMPLETION_PROVIDER_GATEWAY
+OutputFormat = Literal['text', 'json']
+
@dataclass
class CliContext:
@@ -21,7 +23,7 @@ class CliContext:
"""
env: str = 'dev'
- output: Literal['text', 'json'] = 'text'
+ output: OutputFormat = 'text'
operator: str | None = None
allow_prod: bool = False
yes: bool = False
@@ -40,7 +42,7 @@ class CliContextBuilder:
@staticmethod
def build(
env: str,
- output: Literal['text', 'json'],
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
@@ -79,7 +81,7 @@ def build(
autocompletion=COMPLETION_PROVIDER_GATEWAY.complete_env_values,
),
]
-OutputOption = Annotated[Literal['text', 'json'], typer.Option('--output', help='输出格式,支持 text 或 json')]
+OutputOption = Annotated[OutputFormat, typer.Option('--output', help='输出格式,支持 text 或 json')]
AllowProdOption = Annotated[bool, typer.Option('--allow-prod', help='允许在生产环境中执行危险命令')]
YesOption = Annotated[bool, typer.Option('--yes', help='跳过危险命令确认')]
DryRunOption = Annotated[bool, typer.Option('--dry-run', help='仅执行预演,不落地实际变更')]
diff --git a/ruoyi-fastapi-backend/cli/core/app_builder.py b/ruoyi-fastapi-backend/cli/core/app_builder.py
index 3a91cbda1..62987cc39 100644
--- a/ruoyi-fastapi-backend/cli/core/app_builder.py
+++ b/ruoyi-fastapi-backend/cli/core/app_builder.py
@@ -3,6 +3,7 @@
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
+from types import ModuleType
from typing import Annotated, Literal
import typer
@@ -97,7 +98,7 @@ class CliExtensionRegistration:
"""
module_path: str
- attach: Callable[[typer.Typer, object], None]
+ attach: Callable[[typer.Typer, ModuleType], None]
@dataclass(frozen=True)
@@ -148,7 +149,7 @@ class CliExtensionMountSupport:
"""
@staticmethod
- def attach_completion(cli: typer.Typer, module: object) -> None:
+ def attach_completion(cli: typer.Typer, module: ModuleType) -> None:
"""
挂载 completion 扩展入口。
@@ -158,7 +159,7 @@ def attach_completion(cli: typer.Typer, module: object) -> None:
cli.add_typer(module.COMPLETION_COMMAND_BUILDER.build(cli), name='completion')
@staticmethod
- def attach_wizard(cli: typer.Typer, module: object) -> None:
+ def attach_wizard(cli: typer.Typer, module: ModuleType) -> None:
"""
挂载 wizard 扩展入口。
@@ -168,7 +169,7 @@ def attach_wizard(cli: typer.Typer, module: object) -> None:
cli.add_typer(module.WIZARD_COMMAND_BUILDER.build(), name='wizard')
@staticmethod
- def attach_tui(cli: typer.Typer, module: object) -> None:
+ def attach_tui(cli: typer.Typer, module: ModuleType) -> None:
"""
挂载 TUI 扩展入口。
@@ -278,7 +279,7 @@ class CliModuleLoader:
"""
@staticmethod
- def load(module_path: str) -> object:
+ def load(module_path: str) -> ModuleType:
"""
按模块路径加载模块对象。
diff --git a/ruoyi-fastapi-backend/cli/core/completion_dispatcher.py b/ruoyi-fastapi-backend/cli/core/completion_dispatcher.py
index 741005548..174a2d604 100644
--- a/ruoyi-fastapi-backend/cli/core/completion_dispatcher.py
+++ b/ruoyi-fastapi-backend/cli/core/completion_dispatcher.py
@@ -2,10 +2,10 @@
from dataclasses import dataclass, field
import typer
-from click.shell_completion import shell_complete as click_shell_complete
+from typer.completion import completion_init
from typer.completion import shell_complete as typer_shell_complete
-from cli.completion.shells import ensure_custom_completion_classes_registered
+from cli.completion.shells import dispatch_click_completion, ensure_custom_completion_classes_registered
@dataclass(frozen=True)
@@ -101,11 +101,10 @@ def dispatch(self, cli: typer.Typer) -> None:
if not instruction:
return
+ completion_init()
click_command = typer.main.get_command(cli)
if self.support.is_click_style_instruction(instruction):
- raise SystemExit(
- click_shell_complete(click_command, {}, 'ruoyi', self.support.complete_env_var, instruction)
- )
+ raise SystemExit(dispatch_click_completion(click_command, instruction, self.support.complete_env_var))
if self.support.is_typer_style_instruction(instruction):
raise SystemExit(
typer_shell_complete(click_command, {}, 'ruoyi', self.support.complete_env_var, instruction)
diff --git a/ruoyi-fastapi-backend/cli/core/context_factory.py b/ruoyi-fastapi-backend/cli/core/context_factory.py
index e3210ac1a..ae1d770a0 100644
--- a/ruoyi-fastapi-backend/cli/core/context_factory.py
+++ b/ruoyi-fastapi-backend/cli/core/context_factory.py
@@ -3,7 +3,7 @@
from importlib import import_module
from typing import Any
-from cli.context import CLI_CONTEXT_BUILDER, CliContext, CliContextBuilder
+from cli.context import CLI_CONTEXT_BUILDER, CliContext, CliContextBuilder, OutputFormat
from cli.guards import (
DEFAULT_DANGEROUS_COMMAND_GUARD,
DEFAULT_DANGEROUS_COMMAND_RULE_REGISTRY,
@@ -175,7 +175,7 @@ def get_dangerous_command_support(self) -> DangerousCommandContextSupport:
def build_regular(
self,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
@@ -196,7 +196,7 @@ def build_regular(
def build_readonly(
self,
env: str,
- output: str,
+ output: OutputFormat,
) -> CliContext:
"""
构建只读命令上下文。
@@ -210,7 +210,7 @@ def build_readonly(
def build_dangerous(
self,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
diff --git a/ruoyi-fastapi-backend/cli/groups/app/controller.py b/ruoyi-fastapi-backend/cli/groups/app/controller.py
index 84940b75e..0bd5f17cf 100644
--- a/ruoyi-fastapi-backend/cli/groups/app/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/app/controller.py
@@ -4,6 +4,7 @@
from fastapi.routing import APIRoute, iter_route_contexts
from cli.bootstrap import APP_BOOTSTRAP, AppBootstrapService
+from cli.context import OutputFormat
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
@@ -81,7 +82,7 @@ def run_app(self, env: str) -> None:
"""
self.bootstrap_service.exec_app_run_command(env)
- def doctor(self, env: str, output: str) -> None:
+ def doctor(self, env: str, output: OutputFormat) -> None:
"""
执行应用启动前检查。
@@ -109,7 +110,7 @@ def doctor(self, env: str, output: str) -> None:
default_exit_code=exit_code,
)
- def show_config(self, env: str, output: str) -> None:
+ def show_config(self, env: str, output: OutputFormat) -> None:
"""
输出当前应用配置快照。
@@ -124,7 +125,7 @@ def show_config(self, env: str, output: str) -> None:
default_exit_code=SUCCESS,
)
- def show_env(self, env: str, output: str) -> None:
+ def show_env(self, env: str, output: OutputFormat) -> None:
"""
输出当前 CLI 解析到的应用环境信息。
@@ -142,7 +143,7 @@ def show_env(self, env: str, output: str) -> None:
def show_routes(
self,
env: str,
- output: str,
+ output: OutputFormat,
*,
path_prefix: str,
method: str,
diff --git a/ruoyi-fastapi-backend/cli/groups/cache/controller.py b/ruoyi-fastapi-backend/cli/groups/cache/controller.py
index 16e0019ba..9d0c70ec3 100644
--- a/ruoyi-fastapi-backend/cli/groups/cache/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/cache/controller.py
@@ -1,3 +1,4 @@
+from cli.context import OutputFormat
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
@@ -42,7 +43,7 @@ def __init__(
self.presenter = presenter or CacheCommandPresenter()
self.runtime_service = runtime_service or CACHE_RUNTIME
- def stats(self, env: str, output: str) -> None:
+ def stats(self, env: str, output: OutputFormat) -> None:
"""
查看缓存统计信息。
@@ -58,7 +59,7 @@ def stats(self, env: str, output: str) -> None:
text_condition=lambda result_data: bool(result_data.get('ok', False)),
)
- def keys(self, cache_name: str, env: str, output: str) -> None:
+ def keys(self, cache_name: str, env: str, output: OutputFormat) -> None:
"""
查看指定缓存名称下的键名列表。
@@ -75,7 +76,7 @@ def keys(self, cache_name: str, env: str, output: str) -> None:
text_condition=lambda result_data: bool(result_data.get('ok', False)),
)
- def get(self, cache_name: str, cache_key: str, env: str, output: str) -> None:
+ def get(self, cache_name: str, cache_key: str, env: str, output: OutputFormat) -> None:
"""
查看指定缓存内容。
@@ -96,7 +97,7 @@ def get(self, cache_name: str, cache_key: str, env: str, output: str) -> None:
def clear(
self,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
@@ -137,7 +138,7 @@ def clear(
),
)
- def ttl(self, cache_name: str, cache_key: str, env: str, output: str) -> None:
+ def ttl(self, cache_name: str, cache_key: str, env: str, output: OutputFormat) -> None:
"""
查看指定缓存键的剩余过期时间。
@@ -155,7 +156,7 @@ def ttl(self, cache_name: str, cache_key: str, env: str, output: str) -> None:
text_condition=lambda result_data: 'error' not in result_data,
)
- def warmup(self, env: str, output: str, allow_prod: bool, yes: bool) -> None:
+ def warmup(self, env: str, output: OutputFormat, allow_prod: bool, yes: bool) -> None:
"""
执行系统缓存预热。
diff --git a/ruoyi-fastapi-backend/cli/groups/config/command.py b/ruoyi-fastapi-backend/cli/groups/config/command.py
index 94cb911be..05c3b410f 100644
--- a/ruoyi-fastapi-backend/cli/groups/config/command.py
+++ b/ruoyi-fastapi-backend/cli/groups/config/command.py
@@ -101,7 +101,8 @@ def set_command(
allow_prod: AllowProdOption = False,
yes: YesOption = False,
dry_run: DryRunOption = False,
- value: Annotated[str, typer.Option('--value', help='参数键值')] = ...,
+ *,
+ value: Annotated[str, typer.Option('--value', help='参数键值')],
name: Annotated[str | None, typer.Option('--name', help='参数名称,新增时必填')] = None,
config_type: Annotated[Literal['Y', 'N'] | None, typer.Option('--config-type', help='系统内置标记')] = None,
remark: Annotated[str | None, typer.Option('--remark', help='参数备注')] = None,
diff --git a/ruoyi-fastapi-backend/cli/groups/config/controller.py b/ruoyi-fastapi-backend/cli/groups/config/controller.py
index 0ad56af30..85ab08f0e 100644
--- a/ruoyi-fastapi-backend/cli/groups/config/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/config/controller.py
@@ -1,5 +1,6 @@
from typing import Literal
+from cli.context import OutputFormat
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
@@ -47,7 +48,7 @@ def __init__(
def list_configs(
self,
env: str,
- output: str,
+ output: OutputFormat,
*,
config_name: str,
config_key: str,
@@ -97,7 +98,7 @@ def get_config(
self,
config_key: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
source: Literal['db', 'cache', 'both'],
) -> None:
@@ -123,7 +124,7 @@ def set_config(
self,
config_key: str,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
@@ -171,7 +172,7 @@ def set_config(
def sync_cache(
self,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
) -> None:
@@ -198,7 +199,7 @@ def sync_cache(
def doctor(
self,
env: str,
- output: str,
+ output: OutputFormat,
*,
sample_limit: int,
) -> None:
diff --git a/ruoyi-fastapi-backend/cli/groups/config/presenter.py b/ruoyi-fastapi-backend/cli/groups/config/presenter.py
index a1c617c5b..1670ec3b7 100644
--- a/ruoyi-fastapi-backend/cli/groups/config/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/config/presenter.py
@@ -139,7 +139,7 @@ def _build_config_item_lines(config_item: dict[str, object]) -> list[str]:
]
@staticmethod
- def _build_config_detail_section(title: str, config_item: dict[str, object] | None) -> list[str]:
+ def _build_config_detail_section(title: str, config_item: object) -> list[str]:
"""
构建单个配置来源的详情文本段落。
diff --git a/ruoyi-fastapi-backend/cli/groups/crypto/controller.py b/ruoyi-fastapi-backend/cli/groups/crypto/controller.py
index fcb2688ab..647149e0f 100644
--- a/ruoyi-fastapi-backend/cli/groups/crypto/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/crypto/controller.py
@@ -1,3 +1,4 @@
+from cli.context import OutputFormat
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
@@ -42,7 +43,7 @@ def __init__(
self.presenter = presenter or CryptoCommandPresenter()
self.runtime_service = runtime_service or CRYPTO_RUNTIME
- def validate(self, env: str, output: str) -> None:
+ def validate(self, env: str, output: OutputFormat) -> None:
"""
校验传输加密配置。
@@ -52,7 +53,7 @@ def validate(self, env: str, output: str) -> None:
ctx = self.context_factory.build_readonly(env, output)
self.execution_service.complete_payload(ctx, self.runtime_service.validate_crypto_config())
- def keygen(self, env: str, output: str, *, kid: str, key_size: int) -> None:
+ def keygen(self, env: str, output: OutputFormat, *, kid: str, key_size: int) -> None:
"""
生成新的传输加密密钥对。
@@ -74,7 +75,7 @@ def keygen(self, env: str, output: str, *, kid: str, key_size: int) -> None:
def rotate(
self,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
@@ -103,7 +104,7 @@ def rotate(
)
self.execution_service.complete_payload(ctx, self.runtime_service.build_rotation_payload(next_kid, key_size))
- def export_public(self, env: str, output: str) -> None:
+ def export_public(self, env: str, output: OutputFormat) -> None:
"""
导出当前运行环境的公钥信息。
diff --git a/ruoyi-fastapi-backend/cli/groups/db/controller.py b/ruoyi-fastapi-backend/cli/groups/db/controller.py
index 0a45300d4..32ac620e3 100644
--- a/ruoyi-fastapi-backend/cli/groups/db/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/db/controller.py
@@ -1,3 +1,4 @@
+from cli.context import OutputFormat
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
@@ -42,7 +43,7 @@ def __init__(
self.presenter = presenter or DbCommandPresenter()
self.runtime_service = runtime_service or DATABASE_RUNTIME
- def check(self, env: str, output: str) -> None:
+ def check(self, env: str, output: OutputFormat) -> None:
"""
检查数据库连接状态。
@@ -54,7 +55,7 @@ def check(self, env: str, output: str) -> None:
ctx, self.execution_service.run_async(self.runtime_service.ping_database())
)
- def current(self, env: str, output: str) -> None:
+ def current(self, env: str, output: OutputFormat) -> None:
"""
查看数据库当前迁移版本。
@@ -74,7 +75,7 @@ def current(self, env: str, output: str) -> None:
def upgrade(
self,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
@@ -104,7 +105,7 @@ def upgrade(
def init(
self,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
@@ -131,7 +132,7 @@ def init(
def downgrade(
self,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
@@ -162,7 +163,7 @@ def revision(
self,
message: str,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
@@ -193,7 +194,7 @@ def revision(
self.runtime_service.create_revision(message, autogenerate=autogenerate, dry_run=dry_run),
)
- def heads(self, env: str, output: str) -> None:
+ def heads(self, env: str, output: OutputFormat) -> None:
"""
查看当前代码仓库中的 Alembic heads。
@@ -210,7 +211,7 @@ def heads(self, env: str, output: str) -> None:
text_condition=lambda result_data: 'error' not in result_data,
)
- def history(self, env: str, output: str, *, limit: int) -> None:
+ def history(self, env: str, output: OutputFormat, *, limit: int) -> None:
"""
查看当前代码仓库中的 Alembic 历史版本。
diff --git a/ruoyi-fastapi-backend/cli/groups/dev/command.py b/ruoyi-fastapi-backend/cli/groups/dev/command.py
index 1b3794f1f..a45b4f94a 100644
--- a/ruoyi-fastapi-backend/cli/groups/dev/command.py
+++ b/ruoyi-fastapi-backend/cli/groups/dev/command.py
@@ -14,7 +14,7 @@
_DEV_COMMAND_CONTROLLER = DevCommandController()
-@app.command('lint', help='执行 Ruff 检查、格式化和 reST 文档字符串检查')
+@app.command('lint', help='执行 Ruff 格式化、静态检查、文档规范和 ty 类型检查')
def lint(
targets: Annotated[list[str] | None, typer.Argument(help='待检查路径,可传多个')] = None,
env: EnvOption = 'dev',
@@ -24,7 +24,7 @@ def lint(
unsafe_fixes: bool = typer.Option(False, '--unsafe-fixes', help='允许 Ruff 不安全修复'),
) -> None:
"""
- 执行 Ruff 检查、格式化和 reST 文档字符串检查。
+ 执行 Ruff 格式化、静态检查、文档规范和 ty 类型检查。
:param targets: 待检查路径列表
:param env: 当前命令运行环境
diff --git a/ruoyi-fastapi-backend/cli/groups/dev/controller.py b/ruoyi-fastapi-backend/cli/groups/dev/controller.py
index 470d12d3a..c6fa49683 100644
--- a/ruoyi-fastapi-backend/cli/groups/dev/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/dev/controller.py
@@ -1,3 +1,4 @@
+from cli.context import OutputFormat
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
@@ -46,14 +47,14 @@ def lint(
self,
targets: list[str] | None,
env: str,
- output: str,
+ output: OutputFormat,
*,
check_only: bool,
fix: bool,
unsafe_fixes: bool,
) -> None:
"""
- 执行 Ruff 检查、格式化和 reST 文档字符串检查。
+ 执行 Ruff 格式化、静态检查、文档规范和 ty 类型检查。
:param targets: 待检查路径列表
:param env: 当前命令运行环境
@@ -75,7 +76,7 @@ def test(
self,
targets: list[str] | None,
env: str,
- output: str,
+ output: OutputFormat,
*,
keyword: str,
maxfail: int,
diff --git a/ruoyi-fastapi-backend/cli/groups/dev/presenter.py b/ruoyi-fastapi-backend/cli/groups/dev/presenter.py
index 4a8929bd5..c6a47089b 100644
--- a/ruoyi-fastapi-backend/cli/groups/dev/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/dev/presenter.py
@@ -30,6 +30,8 @@ def build_dev_lint_text(self, payload: dict[str, object]) -> str:
lines.extend(self._build_command_result_section('check', payload.get('check')))
if 'docstrings' in payload:
lines.extend(self._build_command_result_section('docstrings', payload['docstrings']))
+ if 'ty' in payload:
+ lines.extend(self._build_command_result_section('ty', payload['ty']))
return '\n'.join(lines)
def build_dev_test_text(self, payload: dict[str, object]) -> str:
@@ -56,7 +58,7 @@ def build_dev_test_text(self, payload: dict[str, object]) -> str:
return '\n'.join(lines)
@staticmethod
- def _build_command_result_section(title: str, payload: dict[str, object] | None) -> list[str]:
+ def _build_command_result_section(title: str, payload: object) -> list[str]:
"""
构建单个子命令执行结果段落。
diff --git a/ruoyi-fastapi-backend/cli/groups/gen/controller.py b/ruoyi-fastapi-backend/cli/groups/gen/controller.py
index 35d3f7ce1..40d7403f9 100644
--- a/ruoyi-fastapi-backend/cli/groups/gen/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/gen/controller.py
@@ -1,3 +1,4 @@
+from cli.context import OutputFormat
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
@@ -46,7 +47,7 @@ def import_table(
self,
table_names: list[str],
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
@@ -76,7 +77,7 @@ def import_table(
def list_tables(
self,
env: str,
- output: str,
+ output: OutputFormat,
*,
table_name: str,
table_comment: str,
@@ -116,7 +117,7 @@ def list_tables(
def list_db_tables(
self,
env: str,
- output: str,
+ output: OutputFormat,
*,
table_name: str,
table_comment: str,
@@ -153,7 +154,7 @@ def list_db_tables(
text_condition=lambda data: data.get('ok', False),
)
- def show_detail(self, table_id: int, env: str, output: str) -> None:
+ def show_detail(self, table_id: int, env: str, output: OutputFormat) -> None:
"""
查看单个代码生成业务表详情。
@@ -174,7 +175,7 @@ def show_detail(self, table_id: int, env: str, output: str) -> None:
def create_table(
self,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
@@ -205,7 +206,7 @@ def create_table(
payload['env'] = ctx.env
self.execution_service.complete_payload(ctx, payload)
- def preview(self, table_id: int, env: str, output: str) -> None:
+ def preview(self, table_id: int, env: str, output: OutputFormat) -> None:
"""
预览指定业务表的代码生成结果。
@@ -227,7 +228,7 @@ def export(
self,
table_names: list[str],
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
@@ -270,7 +271,7 @@ def sync_db(
self,
table_name: str,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
) -> None:
diff --git a/ruoyi-fastapi-backend/cli/groups/job/controller.py b/ruoyi-fastapi-backend/cli/groups/job/controller.py
index ef2e1d174..1439244f8 100644
--- a/ruoyi-fastapi-backend/cli/groups/job/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/job/controller.py
@@ -1,3 +1,4 @@
+from cli.context import OutputFormat
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
@@ -50,7 +51,7 @@ def __init__(
def list(
self,
env: str,
- output: str,
+ output: OutputFormat,
*,
job_name: str,
job_group: str,
@@ -89,7 +90,7 @@ def list(
text_condition=lambda result_data: bool(result_data.get('ok', False)),
)
- def run_once(self, job_id: int, env: str, output: str, allow_prod: bool, yes: bool) -> None:
+ def run_once(self, job_id: int, env: str, output: OutputFormat, allow_prod: bool, yes: bool) -> None:
"""
执行一次定时任务。
@@ -104,7 +105,7 @@ def run_once(self, job_id: int, env: str, output: str, allow_prod: bool, yes: bo
ctx, self.execution_service.run_async(self.job_runtime.run_job_once(job_id))
)
- def detail(self, job_id: int, env: str, output: str) -> None:
+ def detail(self, job_id: int, env: str, output: OutputFormat) -> None:
"""
查看单个定时任务详情。
@@ -124,7 +125,7 @@ def detail(self, job_id: int, env: str, output: str) -> None:
def logs(
self,
env: str,
- output: str,
+ output: OutputFormat,
*,
job_name: str,
job_group: str,
@@ -169,7 +170,7 @@ def logs(
text_condition=lambda result_data: bool(result_data.get('ok', False)),
)
- def pause(self, job_id: int, env: str, output: str, allow_prod: bool, yes: bool) -> None:
+ def pause(self, job_id: int, env: str, output: OutputFormat, allow_prod: bool, yes: bool) -> None:
"""
暂停定时任务。
@@ -184,7 +185,7 @@ def pause(self, job_id: int, env: str, output: str, allow_prod: bool, yes: bool)
ctx, self.execution_service.run_async(self.job_runtime.pause_job(job_id))
)
- def resume(self, job_id: int, env: str, output: str, allow_prod: bool, yes: bool) -> None:
+ def resume(self, job_id: int, env: str, output: OutputFormat, allow_prod: bool, yes: bool) -> None:
"""
恢复定时任务。
@@ -199,7 +200,7 @@ def resume(self, job_id: int, env: str, output: str, allow_prod: bool, yes: bool
ctx, self.execution_service.run_async(self.job_runtime.resume_job(job_id))
)
- def sync(self, env: str, output: str, allow_prod: bool, yes: bool) -> None:
+ def sync(self, env: str, output: OutputFormat, allow_prod: bool, yes: bool) -> None:
"""
同步调度任务配置。
diff --git a/ruoyi-fastapi-backend/cli/groups/oidc/controller.py b/ruoyi-fastapi-backend/cli/groups/oidc/controller.py
index b3a560aee..4ecbbc1b6 100644
--- a/ruoyi-fastapi-backend/cli/groups/oidc/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/oidc/controller.py
@@ -1,3 +1,4 @@
+from cli.context import OutputFormat
from cli.core import DEFAULT_CORE_SERVICES, CliContextFactory, CliExecutionService
from cli.runtime.oidc import OIDC_RUNTIME, OidcRuntimeCliService
@@ -35,7 +36,7 @@ def __init__(
def bootstrap_key(
self,
env: str,
- output: str,
+ output: OutputFormat,
allow_prod: bool,
yes: bool,
dry_run: bool,
diff --git a/ruoyi-fastapi-backend/cli/groups/ops/controller.py b/ruoyi-fastapi-backend/cli/groups/ops/controller.py
index f5e7f897c..ae2badb6a 100644
--- a/ruoyi-fastapi-backend/cli/groups/ops/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/ops/controller.py
@@ -1,3 +1,4 @@
+from cli.context import OutputFormat
from cli.core import (
DEFAULT_CORE_SERVICES,
CliContextFactory,
@@ -48,7 +49,7 @@ def __init__(
self.database_runtime = database_runtime or DATABASE_RUNTIME
self.operations_runtime = operations_runtime or OPERATIONS_RUNTIME
- def ping_db(self, env: str, output: str) -> None:
+ def ping_db(self, env: str, output: OutputFormat) -> None:
"""
检查数据库连接。
@@ -60,7 +61,7 @@ def ping_db(self, env: str, output: str) -> None:
ctx, self.execution_service.run_async(self.database_runtime.ping_database())
)
- def ping_redis(self, env: str, output: str) -> None:
+ def ping_redis(self, env: str, output: OutputFormat) -> None:
"""
检查 Redis 连接。
@@ -73,7 +74,7 @@ def ping_redis(self, env: str, output: str) -> None:
self.execution_service.run_async(self.operations_runtime.ping_redis()),
)
- def health(self, env: str, output: str) -> None:
+ def health(self, env: str, output: OutputFormat) -> None:
"""
输出基础健康检查结果。
@@ -97,7 +98,7 @@ def health(self, env: str, output: str) -> None:
default_exit_code=exit_code,
)
- def deps(self, env: str, output: str, *, include_dev: bool) -> None:
+ def deps(self, env: str, output: OutputFormat, *, include_dev: bool) -> None:
"""
检查当前 CLI 和后端运行依赖版本。
@@ -115,7 +116,7 @@ def deps(self, env: str, output: str, *, include_dev: bool) -> None:
default_exit_code=exit_code,
)
- def server_info(self, env: str, output: str) -> None:
+ def server_info(self, env: str, output: OutputFormat) -> None:
"""
输出服务器运行时信息。
diff --git a/ruoyi-fastapi-backend/cli/groups/ops/presenter.py b/ruoyi-fastapi-backend/cli/groups/ops/presenter.py
index a271aebd8..2851d4e2b 100644
--- a/ruoyi-fastapi-backend/cli/groups/ops/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/ops/presenter.py
@@ -140,7 +140,7 @@ def build_dependencies_text(self, payload: dict[str, object]) -> str:
return '\n'.join(lines)
@staticmethod
- def _build_check_status_line(name: str, status_payload: dict[str, object] | None) -> str:
+ def _build_check_status_line(name: str, status_payload: object) -> str:
"""
构建单项检查结果摘要行。
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/artifact_controller.py b/ruoyi-fastapi-backend/cli/groups/plugin/artifact_controller.py
index b1cb34efd..d4ea8a147 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/artifact_controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/artifact_controller.py
@@ -8,7 +8,7 @@
from pathlib import Path
from typing import Any
-from cli.context import CliContext
+from cli.context import CliContext, OutputOption
from cli.core import DEFAULT_CORE_SERVICES, CliContextFactory, CliExecutionService
from cli.exit_codes import ARGUMENT_ERROR
from cli.runtime.base import RUNTIME_OPERATOR
@@ -75,7 +75,7 @@ def maintain_artifacts(
self,
operation: str,
env: str,
- output: str,
+ output: OutputOption,
*,
options: dict[str, Any],
allow_prod: bool = False,
@@ -165,7 +165,7 @@ def _default_enablement(config: Any) -> Any:
def _context(
self,
env: str,
- output: str,
+ output: OutputOption,
*,
command_name: str | None = None,
allow_prod: bool = False,
@@ -258,7 +258,7 @@ def build_artifact(
source: Path,
destination: Path,
env: str,
- output: str,
+ output: OutputOption,
*,
key_file: Path,
key_id: str,
@@ -291,7 +291,7 @@ def build() -> dict[str, Any]:
self._execute(ctx, build)
- def verify_artifact(self, path: Path, env: str, output: str) -> None:
+ def verify_artifact(self, path: Path, env: str, output: OutputOption) -> None:
"""
校验制品签名、完整摘要与发布者授权范围。
@@ -314,7 +314,9 @@ def verify() -> dict[str, Any]:
self._execute(ctx, verify)
- def import_artifact(self, path: Path, env: str, output: str, *, allow_prod: bool, yes: bool, dry_run: bool) -> None:
+ def import_artifact(
+ self, path: Path, env: str, output: OutputOption, *, allow_prod: bool, yes: bool, dry_run: bool
+ ) -> None:
"""
导入已验证制品及其索引,预演时只执行检查。
@@ -335,7 +337,7 @@ def import_artifact(self, path: Path, env: str, output: str, *, allow_prod: bool
),
)
- def list_artifacts(self, env: str, output: str, *, plugin_id: str | None = None) -> None:
+ def list_artifacts(self, env: str, output: OutputOption, *, plugin_id: str | None = None) -> None:
"""
查询已导入制品,可按插件 ID 筛选。
@@ -351,7 +353,7 @@ def list_artifacts(self, env: str, output: str, *, plugin_id: str | None = None)
),
)
- def plan_release(self, plugin_id: str, digest: str, env: str, output: str) -> None:
+ def plan_release(self, plugin_id: str, digest: str, env: str, output: OutputOption) -> None:
"""
静态检查目标制品并输出维护计划。
@@ -373,7 +375,7 @@ def prepare_release(
plugin_id: str,
digest: str,
env: str,
- output: str,
+ output: OutputOption,
*,
maintenance: bool,
allow_prod: bool,
@@ -409,7 +411,7 @@ def select_release(
plugin_id: str,
digest: str,
env: str,
- output: str,
+ output: OutputOption,
*,
expected_generation: str,
expected_workers: int,
@@ -445,7 +447,7 @@ def select_release(
),
)
- def release_status(self, env: str, output: str, *, plugin_id: str | None = None) -> None:
+ def release_status(self, env: str, output: OutputOption, *, plugin_id: str | None = None) -> None:
"""
查询目标制品、数据准备状态和 worker 加载结果。
@@ -505,7 +507,7 @@ def wait_release(
plugin_id: str,
digest: str,
env: str,
- output: str,
+ output: OutputOption,
*,
expected_generation: str,
expected_workers: int,
@@ -575,7 +577,7 @@ def rollback_release(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputOption,
*,
expected_generation: str,
schema_compatible: bool,
@@ -613,7 +615,7 @@ def set_release_enabled(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputOption,
*,
enabled: bool,
expected_generation: str,
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/commands/dependency.py b/ruoyi-fastapi-backend/cli/groups/plugin/commands/dependency.py
index e06dc764a..fe3df5d35 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/commands/dependency.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/commands/dependency.py
@@ -8,11 +8,10 @@
PluginDependencyAllowlistExampleCommandOptions,
PluginDependencyInstallCommandOptions,
PluginDependencyLockCommandOptions,
+ PluginPlanOperation,
+ PluginPrecheckOperation,
)
-PluginPrecheckOperation = Literal['install', 'enable', 'upgrade', 'uninstall', 'purge']
-PluginPlanOperation = Literal['install', 'enable', 'upgrade']
-
def register_dependency_commands(app: typer.Typer, get_controller: Callable[[], Any]) -> None:
"""
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/commands/lifecycle.py b/ruoyi-fastapi-backend/cli/groups/plugin/commands/lifecycle.py
index 422b7ece3..4a8f1102c 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/commands/lifecycle.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/commands/lifecycle.py
@@ -4,8 +4,8 @@
import typer
from cli.context import AllowProdOption, DryRunOption, EnvOption, OutputOption, YesOption
+from cli.groups.plugin.options import PluginPlanOperation
-PluginBatchOperation = Literal['install', 'enable', 'upgrade']
PluginMigrationStatus = Literal['running', 'success', 'failed', 'unknown']
@@ -19,7 +19,7 @@ def register_lifecycle_commands(app: typer.Typer, get_controller: Callable[[], A
@app.command('batch', help='按拓扑顺序批量执行插件操作')
def batch_command(
- operation: Annotated[PluginBatchOperation, typer.Argument(help='批量操作类型:install、enable 或 upgrade')],
+ operation: Annotated[PluginPlanOperation, typer.Argument(help='批量操作类型:install、enable 或 upgrade')],
plugin_ids: Annotated[list[str] | None, typer.Argument(help='插件ID列表,不传则执行全部插件')] = None,
env: EnvOption = 'dev',
output: OutputOption = 'text',
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/commands/sdk.py b/ruoyi-fastapi-backend/cli/groups/plugin/commands/sdk.py
index b939f3ca9..e03f62f58 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/commands/sdk.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/commands/sdk.py
@@ -51,7 +51,7 @@ def _execute_sdk(
operation: str,
project: Path,
frontend_root: Path | None,
- output: str,
+ output: OutputOption,
*,
dry_run: bool = False,
force: bool = False,
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/controller.py b/ruoyi-fastapi-backend/cli/groups/plugin/controller.py
index 2e87acbd1..2e2dacf55 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/controller.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/controller.py
@@ -1,12 +1,13 @@
import importlib
import json
import sys
-from collections.abc import Callable
+from collections.abc import Callable, Mapping
from typing import TYPE_CHECKING
import click
import typer
+from cli.context import CliContext, OutputFormat
from cli.core import DEFAULT_CORE_SERVICES, CliContextFactory, CliExecutionService
from cli.exit_codes import ARGUMENT_ERROR, DEPENDENCY_ERROR, RUNTIME_ERROR, SUCCESS
from plugins.core.validation.dependency_policy import DependencyInstallPolicyConfig
@@ -17,6 +18,8 @@
PluginDependencyAllowlistExampleCommandOptions,
PluginDependencyInstallCommandOptions,
PluginDependencyLockCommandOptions,
+ PluginPlanOperation,
+ PluginPrecheckOperation,
)
from .payload import PluginCommandPayloadAdapter
from .presenter import PluginCommandPresenter
@@ -24,6 +27,7 @@
if TYPE_CHECKING:
from cli.runtime.plugin.service import CliPluginRuntimeService
from plugins.core.runtime.service import PluginRuntimeService
+ from plugins.core.types import PluginConfigValue
PluginDependencyOutputCallback = Callable[[str, str], None]
@@ -79,7 +83,7 @@ def core_runtime(self) -> 'PluginRuntimeService':
"""
return self.plugin_runtime.core_runtime
- def list_plugins(self, env: str, output: str) -> None:
+ def list_plugins(self, env: str, output: OutputFormat) -> None:
"""
查看插件列表。
@@ -97,10 +101,10 @@ def list_plugins(self, env: str, output: str) -> None:
def _complete_plugin_payload(
self,
- ctx: object,
+ ctx: CliContext,
payload: dict[str, object],
*,
- text_builder: object,
+ text_builder: Callable[[dict[str, object]], str],
success_exit_code: int = SUCCESS,
failure_exit_code: int = DEPENDENCY_ERROR,
) -> None:
@@ -127,7 +131,7 @@ def _complete_plugin_payload(
@staticmethod
def _resolve_plugin_exit_code(
- payload: dict[str, object],
+ payload: Mapping[str, object],
*,
success_exit_code: int,
failure_exit_code: int,
@@ -147,7 +151,7 @@ def _resolve_plugin_exit_code(
return failure_exit_code
- def plugin_info(self, plugin_id: str, env: str, output: str) -> None:
+ def plugin_info(self, plugin_id: str, env: str, output: OutputFormat) -> None:
"""
查看插件详情。
@@ -164,7 +168,7 @@ def plugin_info(self, plugin_id: str, env: str, output: str) -> None:
failure_exit_code=RUNTIME_ERROR,
)
- def check_plugin(self, plugin_id: str | None, env: str, output: str) -> None:
+ def check_plugin(self, plugin_id: str | None, env: str, output: OutputFormat) -> None:
"""
检查插件依赖状态。
@@ -180,7 +184,7 @@ def check_plugin(self, plugin_id: str | None, env: str, output: str) -> None:
text_builder=self.presenter.build_check_text,
)
- def check_plugin_dependencies(self, plugin_id: str, env: str, output: str) -> None:
+ def check_plugin_dependencies(self, plugin_id: str, env: str, output: OutputFormat) -> None:
"""
检查插件依赖。
@@ -196,7 +200,9 @@ def check_plugin_dependencies(self, plugin_id: str, env: str, output: str) -> No
text_builder=self.presenter.build_dependency_text,
)
- def precheck_plugin(self, operation: str, plugin_id: str, env: str, output: str) -> None:
+ def precheck_plugin(
+ self, operation: PluginPrecheckOperation, plugin_id: str, env: str, output: OutputFormat
+ ) -> None:
"""
执行插件操作预检。
@@ -213,7 +219,7 @@ def precheck_plugin(self, operation: str, plugin_id: str, env: str, output: str)
text_builder=self.presenter.build_precheck_text,
)
- def health_plugin(self, plugin_id: str, env: str, output: str) -> None:
+ def health_plugin(self, plugin_id: str, env: str, output: OutputFormat) -> None:
"""
执行插件健康检查。
@@ -229,7 +235,7 @@ def health_plugin(self, plugin_id: str, env: str, output: str) -> None:
text_builder=self.presenter.build_health_text,
)
- def diagnose_plugin(self, plugin_id: str, env: str, output: str, *, output_file: str = '') -> None:
+ def diagnose_plugin(self, plugin_id: str, env: str, output: OutputFormat, *, output_file: str = '') -> None:
"""
生成插件诊断包。
@@ -252,7 +258,7 @@ def diagnose_plugin(self, plugin_id: str, env: str, output: str, *, output_file:
text_builder=self.presenter.build_diagnose_text,
)
- def generate_plugin_docs(self, plugin_id: str, env: str, output: str, *, output_file: str = '') -> None:
+ def generate_plugin_docs(self, plugin_id: str, env: str, output: OutputFormat, *, output_file: str = '') -> None:
"""
生成插件 Markdown 文档片段。
@@ -280,7 +286,7 @@ def test_plugin(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
keyword: str = '',
maxfail: int = 0,
@@ -312,7 +318,9 @@ def test_plugin(
text_builder=self.presenter.build_test_text,
)
- def plan_plugins(self, operation: str, plugin_ids: list[str], env: str, output: str) -> None:
+ def plan_plugins(
+ self, operation: PluginPlanOperation, plugin_ids: list[str], env: str, output: OutputFormat
+ ) -> None:
"""
生成插件批量操作拓扑计划。
@@ -331,10 +339,10 @@ def plan_plugins(self, operation: str, plugin_ids: list[str], env: str, output:
def batch_plugins(
self,
- operation: str,
+ operation: PluginPlanOperation,
plugin_ids: list[str],
env: str,
- output: str,
+ output: OutputFormat,
*,
allow_prod: bool,
yes: bool,
@@ -380,7 +388,7 @@ def install_plugin_dependencies(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
options: PluginDependencyInstallCommandOptions,
) -> None:
@@ -462,14 +470,14 @@ def install_plugin_dependencies(
)
@staticmethod
- def _build_dependency_install_output_callback(ctx: object) -> PluginDependencyOutputCallback | None:
+ def _build_dependency_install_output_callback(ctx: CliContext) -> PluginDependencyOutputCallback | None:
"""
为文本输出模式构建依赖安装实时输出回调。
:param ctx: CLI上下文
:return: 实时输出回调;非文本模式返回 None
"""
- if getattr(ctx, 'output', 'text') != 'text':
+ if ctx.output != 'text':
return None
def output_callback(kind: str, text: str) -> None:
@@ -488,7 +496,7 @@ def lock_plugin_dependencies(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
options: PluginDependencyLockCommandOptions,
) -> None:
@@ -524,7 +532,7 @@ def lock_plugin_dependencies(
def generate_plugin_dependency_allowlist_example(
self,
env: str,
- output: str,
+ output: OutputFormat,
*,
options: PluginDependencyAllowlistExampleCommandOptions,
) -> None:
@@ -556,7 +564,7 @@ def generate_plugin_dependency_allowlist_example(
@staticmethod
def _should_interactive_confirm_dependency_install(
- ctx: object,
+ ctx: CliContext,
options: PluginDependencyInstallCommandOptions,
) -> bool:
"""
@@ -566,9 +574,7 @@ def _should_interactive_confirm_dependency_install(
:param options: 依赖安装命令选项
:return: 是否进入交互确认
"""
- return (
- not options.yes and not options.dry_run and getattr(ctx, 'output', 'text') == 'text' and sys.stdin.isatty()
- )
+ return not options.yes and not options.dry_run and ctx.output == 'text' and bool(sys.stdin.isatty())
@staticmethod
def _dependency_install_policy_blocked(payload: dict[str, object]) -> bool:
@@ -621,7 +627,7 @@ def create_plugin(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputFormat,
options: PluginCreateCommandOptions,
) -> None:
"""
@@ -669,7 +675,7 @@ def install_plugin(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
allow_prod: bool,
yes: bool,
@@ -705,7 +711,7 @@ def upgrade_plugin(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
allow_prod: bool,
yes: bool,
@@ -741,7 +747,7 @@ def set_plugin_enabled(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
enabled: bool,
allow_prod: bool,
@@ -782,7 +788,7 @@ def uninstall_plugin(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
allow_prod: bool,
yes: bool,
@@ -818,7 +824,7 @@ def purge_plugin(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
allow_prod: bool,
yes: bool,
@@ -850,7 +856,7 @@ def purge_plugin(
text_builder=self.presenter.build_purge_text,
)
- def list_plugin_migrations(self, plugin_id: str, status: str | None, env: str, output: str) -> None:
+ def list_plugin_migrations(self, plugin_id: str, status: str | None, env: str, output: OutputFormat) -> None:
"""
查看插件 migration 历史。
@@ -872,7 +878,7 @@ def mark_plugin_migration_success(
plugin_id: str,
migration_path: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
note: str,
allow_prod: bool,
@@ -912,7 +918,7 @@ def mark_plugin_migration_failed(
plugin_id: str,
migration_path: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
note: str,
allow_prod: bool,
@@ -953,7 +959,7 @@ def plugin_config(
action: str,
pairs: list[str],
env: str,
- output: str,
+ output: OutputFormat,
*,
allow_prod: bool,
yes: bool,
@@ -1025,7 +1031,7 @@ def plugin_config(
yes=yes,
)
- def _get_plugin_config(self, plugin_id: str, env: str, output: str) -> None:
+ def _get_plugin_config(self, plugin_id: str, env: str, output: OutputFormat) -> None:
"""
读取插件配置。
@@ -1045,7 +1051,7 @@ def _export_plugin_config(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
allow_prod: bool,
yes: bool,
@@ -1095,7 +1101,7 @@ def _import_plugin_config(
self,
plugin_id: str,
env: str,
- output: str,
+ output: OutputFormat,
*,
allow_prod: bool,
yes: bool,
@@ -1143,7 +1149,7 @@ def _set_plugin_config(
plugin_id: str,
pairs: list[str],
env: str,
- output: str,
+ output: OutputFormat,
*,
allow_prod: bool,
yes: bool,
@@ -1185,7 +1191,7 @@ def _set_plugin_config(
)
@staticmethod
- def _parse_config_pairs(pairs: list[str]) -> dict[str, str]:
+ def _parse_config_pairs(pairs: list[str]) -> dict[str, 'PluginConfigValue']:
"""
解析配置键值参数。
@@ -1193,7 +1199,7 @@ def _parse_config_pairs(pairs: list[str]) -> dict[str, str]:
:return: 配置键值字典
:raises ValueError: 配置项未按 key=value 提供
"""
- values = {}
+ values: dict[str, PluginConfigValue] = {}
for pair in pairs:
if '=' not in pair:
raise ValueError(f'配置参数必须使用 key=value 格式:{pair}')
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/options.py b/ruoyi-fastapi-backend/cli/groups/plugin/options.py
index 3c019ad56..5615bbb18 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/options.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/options.py
@@ -1,7 +1,12 @@
from dataclasses import dataclass
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
+
+if TYPE_CHECKING:
+ from plugins.core.validation.dependency_policy import DependencyInstallPolicyMode
PluginFrontendFrameworkChoice = Literal['auto', 'vue2', 'vue3', 'react']
+PluginPlanOperation = Literal['install', 'enable', 'upgrade']
+PluginPrecheckOperation = Literal[PluginPlanOperation, 'uninstall', 'purge']
@dataclass(frozen=True)
@@ -52,7 +57,7 @@ class PluginDependencyInstallCommandOptions:
allow_prod: bool = False
yes: bool = False
dry_run: bool = False
- policy_mode: str | None = None
+ policy_mode: 'DependencyInstallPolicyMode | None' = None
allow_unlisted: bool = False
lockfile: str = ''
allowlist: str = ''
diff --git a/ruoyi-fastapi-backend/cli/groups/plugin/presenter.py b/ruoyi-fastapi-backend/cli/groups/plugin/presenter.py
index c47363259..bf382e856 100644
--- a/ruoyi-fastapi-backend/cli/groups/plugin/presenter.py
+++ b/ruoyi-fastapi-backend/cli/groups/plugin/presenter.py
@@ -607,13 +607,13 @@ def build_install_text(self, payload: dict[str, object]) -> str:
structure_errors = payload.get('structureErrors')
if isinstance(structure_errors, list) and structure_errors:
- lines.append(f'structure_errors: {len(structure_errors)}')
+ lines.append(f'structure_errors: {structure_errors}')
else:
lines.append('structure_errors: none')
menu_conflicts = payload.get('menuConflicts')
if isinstance(menu_conflicts, list) and menu_conflicts:
- lines.append(f'menu_conflicts: {len(menu_conflicts)}')
+ lines.append(f'menu_conflicts: {menu_conflicts}')
else:
lines.append('menu_conflicts: none')
@@ -651,13 +651,13 @@ def build_upgrade_text(self, payload: dict[str, object]) -> str:
structure_errors = payload.get('structureErrors')
if isinstance(structure_errors, list) and structure_errors:
- lines.append(f'structure_errors: {len(structure_errors)}')
+ lines.append(f'structure_errors: {structure_errors}')
else:
lines.append('structure_errors: none')
menu_conflicts = payload.get('menuConflicts')
if isinstance(menu_conflicts, list) and menu_conflicts:
- lines.append(f'menu_conflicts: {len(menu_conflicts)}')
+ lines.append(f'menu_conflicts: {menu_conflicts}')
else:
lines.append('menu_conflicts: none')
@@ -911,7 +911,17 @@ def _build_purge_plan_line(item: dict[str, object]) -> str:
)
@staticmethod
- def _build_plugin_plan_line(item: dict[str, object]) -> str:
+ def _list_count(value: object) -> int:
+ """
+ 统计插件响应中列表字段的条目数。
+
+ :param value: 待统计的字段值
+ :return: 条目数,字段缺失或不是列表时为零
+ """
+ return len(value) if isinstance(value, list) else 0
+
+ @classmethod
+ def _build_plugin_plan_line(cls, item: dict[str, object]) -> str:
"""
构建插件批量操作计划文本行。
@@ -922,7 +932,7 @@ def _build_plugin_plan_line(item: dict[str, object]) -> str:
f' - #{item.get("order", "-")} {item.get("pluginId", "-")} | '
f'ready: {str(item.get("ready", False)).lower()} | '
f'requested: {str(item.get("requested", False)).lower()} | '
- f'deps: {len(item.get("dependencies", []))}'
+ f'deps: {cls._list_count(item.get("dependencies"))}'
)
@staticmethod
@@ -952,22 +962,22 @@ def _build_batch_result_line(item: dict[str, object]) -> str:
f'duration_ms: {item.get("durationMs", 0)} | message: {item.get("message", "-")}'
)
- @staticmethod
- def _build_check_summary_line(check: dict[str, object]) -> str:
+ @classmethod
+ def _build_check_summary_line(cls, check: dict[str, object]) -> str:
"""
构建插件检查摘要文本行。
:param check: 插件检查负载
:return: 文本行
"""
- missing_dependencies = check.get('missingDependencies', [])
- unsatisfied_dependencies = check.get('unsatisfiedDependencies', [])
- structure_errors = check.get('structureErrors', [])
- menu_conflicts = check.get('menuConflicts', [])
+ missing_dependencies = cls._list_count(check.get('missingDependencies'))
+ unsatisfied_dependencies = cls._list_count(check.get('unsatisfiedDependencies'))
+ structure_errors = cls._list_count(check.get('structureErrors'))
+ menu_conflicts = cls._list_count(check.get('menuConflicts'))
return (
f' - {check.get("pluginId", "-")} | ok: {str(check.get("ok", False)).lower()} | '
- f'missing: {len(missing_dependencies)} | unsatisfied: {len(unsatisfied_dependencies)} | '
- f'structure_errors: {len(structure_errors)} | menu_conflicts: {len(menu_conflicts)}'
+ f'missing: {missing_dependencies} | unsatisfied: {unsatisfied_dependencies} | '
+ f'structure_errors: {structure_errors} | menu_conflicts: {menu_conflicts}'
)
@staticmethod
diff --git a/ruoyi-fastapi-backend/cli/main.py b/ruoyi-fastapi-backend/cli/main.py
index db7a156b9..a071aa1af 100644
--- a/ruoyi-fastapi-backend/cli/main.py
+++ b/ruoyi-fastapi-backend/cli/main.py
@@ -1,5 +1,9 @@
import sys
+from collections.abc import Callable
from dataclasses import dataclass
+from typing import TypeVar
+
+from typer import Typer
from cli.core import (
DEFAULT_CORE_SERVICES,
@@ -8,6 +12,8 @@
ProjectRuntimeLocator,
)
+ResultT = TypeVar('ResultT')
+
@dataclass(frozen=True)
class CliImportArgvScope:
@@ -23,7 +29,7 @@ class CliImportArgvScope:
project_runtime_locator: ProjectRuntimeLocator
- def run(self, callback: object) -> object:
+ def run(self, callback: Callable[[], ResultT]) -> ResultT:
"""
在导入期参数作用域内执行回调。
@@ -58,7 +64,7 @@ class CliMainRunner:
application_builder: CliApplicationBuilder
import_argv_scope: CliImportArgvScope
- def build_cli(self) -> object:
+ def build_cli(self) -> Typer:
"""
构建 CLI 根应用,并在导入期仅保留最小化参数集。
diff --git a/ruoyi-fastapi-backend/cli/output.py b/ruoyi-fastapi-backend/cli/output.py
index e5496ea4f..75ece7f13 100644
--- a/ruoyi-fastapi-backend/cli/output.py
+++ b/ruoyi-fastapi-backend/cli/output.py
@@ -135,7 +135,7 @@ def build_status_token(self, kind: str) -> str:
:return: 标签文本
"""
definition = self.get_status_definition(kind)
- return getattr(definition, self.settings.icon_mode, definition.none)
+ return {'emoji': definition.emoji, 'ascii': definition.ascii}.get(self.settings.icon_mode, definition.none)
def style_status_token(self, kind: str, *, fg: str | None = None) -> str:
"""
diff --git a/ruoyi-fastapi-backend/cli/runtime/config/service.py b/ruoyi-fastapi-backend/cli/runtime/config/service.py
index 699793935..e60d5bbb3 100644
--- a/ruoyi-fastapi-backend/cli/runtime/config/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/config/service.py
@@ -37,28 +37,13 @@ def build_cli_config_model(config_vo_module: Any, config_record: Any) -> Any | N
"""
将 ORM 配置记录显式转换为 CLI 可用的配置模型。
- ``ConfigModel`` 当前未统一开启 ``populate_by_name``,因此 CLI 侧在处理
- ORM 蛇形字段对象时,需要主动映射为驼峰 alias 输入,避免详情查询结果
- 被静默序列化为空。
-
:param config_vo_module: 配置 VO 模块
:param config_record: ORM 配置记录
:return: CLI 可用配置模型
"""
if config_record is None:
return None
- return config_vo_module.ConfigModel(
- configId=getattr(config_record, 'config_id', None),
- configName=getattr(config_record, 'config_name', None),
- configKey=getattr(config_record, 'config_key', None),
- configValue=getattr(config_record, 'config_value', None),
- configType=getattr(config_record, 'config_type', None),
- createBy=getattr(config_record, 'create_by', None),
- createTime=getattr(config_record, 'create_time', None),
- updateBy=getattr(config_record, 'update_by', None),
- updateTime=getattr(config_record, 'update_time', None),
- remark=getattr(config_record, 'remark', None),
- )
+ return config_vo_module.ConfigModel.model_validate(config_record)
async def load_config_from_database(
self,
@@ -77,7 +62,7 @@ async def load_config_from_database(
async with async_session_local() as session:
config_record = await config_dao.get_config_detail_by_info(
session,
- config_vo_module.ConfigModel(configKey=config_key),
+ config_vo_module.ConfigModel(config_key=config_key),
)
except Exception as exc:
return {'ok': False, 'message': '读取参数配置失败', 'error': str(exc), 'exit_code': DATABASE_ERROR}
@@ -253,7 +238,7 @@ async def set_config(
async with async_session_local() as session:
config_record = await config_dao.get_config_detail_by_info(
session,
- config_vo_module.ConfigModel(configKey=config_key),
+ config_vo_module.ConfigModel(config_key=config_key),
)
existing_config = self.build_cli_config_model(config_vo_module, config_record)
if existing_config is None and not config_name:
diff --git a/ruoyi-fastapi-backend/cli/runtime/config/support.py b/ruoyi-fastapi-backend/cli/runtime/config/support.py
index 88ef781ec..29200e302 100644
--- a/ruoyi-fastapi-backend/cli/runtime/config/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/config/support.py
@@ -103,13 +103,13 @@ def build_config_query(
"""
config_vo_module = self.infrastructure_gateway.get_config_vo_module()
return config_vo_module.ConfigPageQueryModel(
- configName=config_name or None,
- configKey=config_key or None,
- configType=config_type,
- beginTime=begin_date or None,
- endTime=end_date or None,
- pageNum=page_num,
- pageSize=page_size,
+ config_name=config_name or None,
+ config_key=config_key or None,
+ config_type=config_type,
+ begin_time=begin_date or None,
+ end_time=end_date or None,
+ page_num=page_num,
+ page_size=page_size,
)
def build_target_config_model(
@@ -138,17 +138,17 @@ def build_target_config_model(
config_vo_module = self.infrastructure_gateway.get_config_vo_module()
default_config_type = existing_config.config_type if existing_config else common_constant.NO
target_config = config_vo_module.ConfigModel(
- configId=existing_config.config_id if existing_config else None,
- configName=config_name
+ config_id=existing_config.config_id if existing_config else None,
+ config_name=config_name
if config_name is not None
else (existing_config.config_name if existing_config else None),
- configKey=config_key,
- configValue=config_value,
- configType=config_type if config_type is not None else default_config_type,
- createBy=existing_config.create_by if existing_config else operator,
- createTime=existing_config.create_time if existing_config else current_time,
- updateBy=operator,
- updateTime=current_time,
+ config_key=config_key,
+ config_value=config_value,
+ config_type=config_type if config_type is not None else default_config_type,
+ create_by=existing_config.create_by if existing_config else operator,
+ create_time=existing_config.create_time if existing_config else current_time,
+ update_by=operator,
+ update_time=current_time,
remark=remark if remark is not None else (existing_config.remark if existing_config else None),
)
target_config.validate_fields()
diff --git a/ruoyi-fastapi-backend/cli/runtime/crypto/support.py b/ruoyi-fastapi-backend/cli/runtime/crypto/support.py
index 6ba101e22..52a85236d 100644
--- a/ruoyi-fastapi-backend/cli/runtime/crypto/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/crypto/support.py
@@ -1,11 +1,15 @@
import json
from collections.abc import Callable
-from typing import Any
+from typing import TYPE_CHECKING, Any
from cli.exit_codes import ARGUMENT_ERROR, RUNTIME_ERROR
from .gateway import CryptoInfrastructureGateway
+if TYPE_CHECKING:
+ from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
+
+
MIN_RSA_KEY_SIZE = 2048
RSA_KEY_SIZE_STEP = 256
@@ -48,7 +52,7 @@ def generate_rsa_key_pair(self, key_size: int) -> tuple[str, str]:
"""
rsa_module = self.infrastructure_gateway.get_rsa_module()
serialization_module = self.infrastructure_gateway.get_serialization_module()
- private_key = rsa_module.generate_private_key(public_exponent=65537, key_size=key_size)
+ private_key: RSAPrivateKey = rsa_module.generate_private_key(public_exponent=65537, key_size=key_size)
private_key_pem = private_key.private_bytes(
encoding=serialization_module.Encoding.PEM,
format=serialization_module.PrivateFormat.PKCS8,
diff --git a/ruoyi-fastapi-backend/cli/runtime/dev/service.py b/ruoyi-fastapi-backend/cli/runtime/dev/service.py
index 17dd03b7e..3f8caec3c 100644
--- a/ruoyi-fastapi-backend/cli/runtime/dev/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/dev/service.py
@@ -103,6 +103,13 @@ def run_lint(
}
if not docstrings['ok']:
payload['exit_code'] = RUNTIME_ERROR
+ return payload
+ types = self.process_gateway.run_command(
+ [self.runtime_environment.get_python_executable(), 'scripts/check_types.py', *normalized_targets]
+ )
+ payload['ty'] = types
+ if not types['ok']:
+ payload.update(ok=False, message='ty 类型检查失败', exit_code=RUNTIME_ERROR)
return payload
def run_tests(
diff --git a/ruoyi-fastapi-backend/cli/runtime/gen/service.py b/ruoyi-fastapi-backend/cli/runtime/gen/service.py
index f5c31d4f4..338f2f05f 100644
--- a/ruoyi-fastapi-backend/cli/runtime/gen/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/gen/service.py
@@ -108,10 +108,10 @@ async def list_gen_tables(
try:
gen_vo_module = self.infrastructure_gateway.get_gen_vo_module()
query_model = gen_vo_module.GenTablePageQueryModel(
- tableName=table_name or None,
- tableComment=table_comment or None,
- pageNum=page_num,
- pageSize=page_size,
+ table_name=table_name or None,
+ table_comment=table_comment or None,
+ page_num=page_num,
+ page_size=page_size,
)
async with async_session_local() as session:
result = await gen_table_service.get_gen_table_list_services(session, query_model, is_page=paged)
@@ -156,10 +156,10 @@ async def list_gen_db_tables(
try:
gen_vo_module = self.infrastructure_gateway.get_gen_vo_module()
query_model = gen_vo_module.GenTablePageQueryModel(
- tableName=table_name or None,
- tableComment=table_comment or None,
- pageNum=page_num,
- pageSize=page_size,
+ table_name=table_name or None,
+ table_comment=table_comment or None,
+ page_num=page_num,
+ page_size=page_size,
)
async with async_session_local() as session:
result = await gen_table_service.get_gen_db_table_list_services(session, query_model, is_page=paged)
diff --git a/ruoyi-fastapi-backend/cli/runtime/job/service.py b/ruoyi-fastapi-backend/cli/runtime/job/service.py
index a49be2612..6962b8461 100644
--- a/ruoyi-fastapi-backend/cli/runtime/job/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/job/service.py
@@ -61,11 +61,11 @@ async def list_jobs(
job_vo_module = self.infrastructure_gateway.get_job_vo_module()
job_service = self.infrastructure_gateway.get_job_service()
query_model = job_vo_module.JobPageQueryModel(
- jobName=job_name or None,
- jobGroup=job_group or None,
+ job_name=job_name or None,
+ job_group=job_group or None,
status=status,
- pageNum=page_num,
- pageSize=page_size,
+ page_num=page_num,
+ page_size=page_size,
)
try:
async with async_session_local() as session:
@@ -137,13 +137,13 @@ async def list_job_logs(
job_log_service = self.infrastructure_gateway.get_job_log_service()
job_vo_module = self.infrastructure_gateway.get_job_vo_module()
query_model = job_vo_module.JobLogPageQueryModel(
- jobName=job_name or None,
- jobGroup=job_group or None,
+ job_name=job_name or None,
+ job_group=job_group or None,
status=status,
- beginTime=begin_date or None,
- endTime=end_date or None,
- pageNum=page_num,
- pageSize=page_size,
+ begin_time=begin_date or None,
+ end_time=end_date or None,
+ page_num=page_num,
+ page_size=page_size,
)
try:
async with async_session_local() as session:
@@ -191,11 +191,11 @@ async def run_with_scheduler_context(
await scheduler_manager.init_system_scheduler(redis)
if operation == 'run-once':
- result = await job_service.execute_job_once_services(session, job_vo_module.JobModel(jobId=job_id))
+ result = await job_service.execute_job_once_services(session, job_vo_module.JobModel(job_id=job_id))
elif operation in {'pause', 'resume'}:
result = await job_service.edit_job_services(
session,
- job_vo_module.EditJobModel(jobId=job_id, status=status, type='status'),
+ job_vo_module.EditJobModel(job_id=job_id, status=status, type='status'),
)
else:
raise ValueError(f'不支持的任务操作:{operation}')
diff --git a/ruoyi-fastapi-backend/cli/runtime/ops/support.py b/ruoyi-fastapi-backend/cli/runtime/ops/support.py
index cdf28204b..a51b295e5 100644
--- a/ruoyi-fastapi-backend/cli/runtime/ops/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/ops/support.py
@@ -156,12 +156,14 @@ def resolve_server_ip(self, hostname: str) -> str:
for interface_addresses in psutil.net_if_addrs().values():
for address_info in interface_addresses:
+ address: object = address_info.address
if (
address_info.family == socket.AF_INET
- and address_info.address
- and not address_info.address.startswith('127.')
+ and isinstance(address, str)
+ and address
+ and not address.startswith('127.')
):
- return address_info.address
+ return address
return '127.0.0.1'
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/gateway.py b/ruoyi-fastapi-backend/cli/runtime/plugin/gateway.py
index 5b0efb1b9..5e21605a1 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/gateway.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/gateway.py
@@ -1,5 +1,14 @@
+from __future__ import annotations
+
from importlib import import_module
-from typing import Any
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from plugins.core.environment import PluginRuntimeEnvironmentService
+ from plugins.core.management.service.gateway import PluginManagementRuntimeGateway
+ from plugins.core.runtime.service import PluginRuntimeService
+ from plugins.core.runtime.service.dependency_container import PluginRuntimeGatewayOverrides
+ from plugins.core.runtime.service.lifecycle_lock import PluginLifecycleLock
class PluginRuntimeGateway:
@@ -11,7 +20,7 @@ class PluginRuntimeGateway:
"""
@staticmethod
- def get_core_runtime_service_class() -> Any:
+ def get_core_runtime_service_class() -> type[PluginRuntimeService]:
"""
获取插件核心运行时服务类。
@@ -20,7 +29,7 @@ def get_core_runtime_service_class() -> Any:
return import_module('plugins.core.runtime.service').PluginRuntimeService
@staticmethod
- def get_core_runtime_gateway_overrides_class() -> Any:
+ def get_core_runtime_gateway_overrides_class() -> type[PluginRuntimeGatewayOverrides]:
"""
获取插件核心运行时窄端口覆盖项类。
@@ -29,7 +38,7 @@ def get_core_runtime_gateway_overrides_class() -> Any:
return import_module('plugins.core.runtime.service.dependency_container').PluginRuntimeGatewayOverrides
@staticmethod
- def get_management_runtime_gateway() -> Any:
+ def get_management_runtime_gateway() -> PluginManagementRuntimeGateway:
"""
获取插件管理运行时适配器。
@@ -39,7 +48,7 @@ def get_management_runtime_gateway() -> Any:
return gateway_class()
@staticmethod
- def get_core_runtime_environment() -> Any:
+ def get_core_runtime_environment() -> PluginRuntimeEnvironmentService:
"""
获取插件核心运行时环境服务。
@@ -48,7 +57,7 @@ def get_core_runtime_environment() -> Any:
return import_module('plugins.core.environment').PLUGIN_RUNTIME_ENVIRONMENT
@staticmethod
- def get_core_lifecycle_lock() -> Any:
+ def get_core_lifecycle_lock() -> PluginLifecycleLock:
"""
获取插件核心生命周期分布式锁。
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/payload.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/payload.py
index e50b38294..39151dddd 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/payload.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/payload.py
@@ -44,7 +44,7 @@ class PluginScaffoldPlanPayload:
files: list[tuple[Path, str]]
conflicts: list[str]
- def to_payload(self) -> dict[str, Any]:
+ def to_payload(self) -> dict[str, object]:
"""
序列化为既有 CLI payload 契约。
@@ -83,7 +83,7 @@ class PluginScaffoldSuccessPayload:
scaffold_plan: dict[str, Any]
dry_run: bool
- def to_payload(self) -> dict[str, Any]:
+ def to_payload(self) -> dict[str, object]:
"""
序列化为既有 CLI payload 契约。
@@ -114,7 +114,7 @@ class PluginScaffoldConflictPayload:
dry_run: bool
failure_code: int = RUNTIME_ERROR
- def to_payload(self) -> dict[str, Any]:
+ def to_payload(self) -> dict[str, object]:
"""
序列化为既有 CLI payload 契约。
@@ -140,7 +140,7 @@ def build_conflict_payload(
*,
dry_run: bool,
failure_code: int = RUNTIME_ERROR,
- ) -> dict[str, Any]:
+ ) -> dict[str, object]:
"""
构建插件模板目录冲突负载。
@@ -158,7 +158,7 @@ def build_conflict_payload(
).to_payload()
@staticmethod
- def build_success_payload(plugin_id: str, scaffold_plan: dict[str, Any], *, dry_run: bool) -> dict[str, Any]:
+ def build_success_payload(plugin_id: str, scaffold_plan: dict[str, Any], *, dry_run: bool) -> dict[str, object]:
"""
构建插件模板创建成功负载。
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py
index a90d94601..25482ec5c 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/v2.py
@@ -1,6 +1,7 @@
import json
from collections.abc import Callable
from importlib.resources import files
+from io import StringIO
from pathlib import Path
from typing import Any
@@ -199,7 +200,8 @@ def _manifest(plugin_id: str, *, native: bool, bundle: bool) -> str:
}
],
)
- return yaml.safe_dump(
+ stream = StringIO()
+ yaml.safe_dump(
{
'manifestVersion': 2,
'id': plugin_id,
@@ -211,9 +213,11 @@ def _manifest(plugin_id: str, *, native: bool, bundle: bool) -> str:
'permissions': [{'code': f'{plugin_id}:view', 'name': '访问插件'}],
'compatibility': {'hostApiVersion': '^1.2.0', 'pythonVersion': '>=3.11'},
},
+ stream,
allow_unicode=True,
sort_keys=False,
)
+ return stream.getvalue()
@staticmethod
def _readme(plugin_id: str, *, native: bool, bundle: bool, test: bool) -> str:
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/sdk.py b/ruoyi-fastapi-backend/cli/runtime/plugin/sdk.py
index 96384f854..1aa608b94 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/sdk.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/sdk.py
@@ -3,7 +3,7 @@
import os
import re
import stat
-from collections.abc import Iterator
+from collections.abc import Generator
from contextlib import contextmanager
from pathlib import Path
from typing import Any
@@ -298,11 +298,11 @@ def _wire_versions(content: str) -> list[str]:
:param content: JS 或类型声明内容
:return: 所有可明确识别的协议版本字面量
"""
- return re.findall(
+ pattern = re.compile(
r'^\s*export\s+(?:declare\s+)?const\s+PLUGIN_BRIDGE_VERSION\s*[:=]\s*(\d+)\s*;?\s*$',
- content,
re.MULTILINE,
)
+ return [match.group(1) for match in pattern.finditer(content)]
@classmethod
def _validate_exports(cls, contents: dict[str, str], metadata: dict[str, Any]) -> None:
@@ -455,7 +455,7 @@ def _refusal(report: dict[str, Any], *, force: bool) -> str | None:
@classmethod
@contextmanager
- def _lock(cls, root: Path) -> Iterator[None]:
+ def _lock(cls, root: Path) -> Generator[None, None, None]:
"""
用工程局部独占文件串行更新,不自动抢占可能仍被使用的旧锁。
@@ -537,10 +537,11 @@ def _apply(
for name in VENDOR_FILES:
try:
path = cls._safe_path(vendor / name)
- if originals[name] is None:
+ original = originals[name]
+ if original is None:
path.unlink(missing_ok=True)
else:
- cls._write(path, originals[name])
+ cls._write(path, original)
except (OSError, ValueError) as rollback_error:
failures.append(f'{name}: {rollback_error}')
if failures:
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/service.py b/ruoyi-fastapi-backend/cli/runtime/plugin/service.py
index 6c690a4d3..9ade5bb83 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/service.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/service.py
@@ -1,6 +1,8 @@
+from __future__ import annotations
+
from dataclasses import dataclass, replace
from pathlib import Path
-from typing import Any
+from typing import TYPE_CHECKING, Any
from cli.exit_codes import RUNTIME_ERROR, SUCCESS
@@ -16,6 +18,15 @@
PluginTestPlanBuilder,
)
+if TYPE_CHECKING:
+ from plugins.core.environment import PluginRuntimeEnvironmentService
+ from plugins.core.management.service.gateway import PluginManagementRuntimeGateway
+ from plugins.core.runtime.service import PluginRuntimeService
+ from plugins.core.runtime.service.dependency_container import PluginRuntimeGatewayOverrides
+ from plugins.core.runtime.service.gateway import PluginCommandRunnerGateway, PluginManagementModelGateway
+ from plugins.core.runtime.service.lifecycle_lock import PluginLifecycleLock
+ from plugins.core.validation.dependencies import PluginDependencyChecker
+
PYTEST_COMMAND_TIMEOUT_SECONDS = 120
@@ -32,12 +43,12 @@ class CliPluginRuntimeDependencies:
:ivar lifecycle_lock: 插件生命周期操作锁
"""
- runtime_environment: object | None = None
- dependency_checker: object | None = None
- management_gateway: object | None = None
- model_gateway: object | None = None
- command_gateway: object | None = None
- lifecycle_lock: object | None = None
+ runtime_environment: PluginRuntimeEnvironmentService | None = None
+ dependency_checker: PluginDependencyChecker | None = None
+ management_gateway: PluginManagementRuntimeGateway | None = None
+ model_gateway: PluginManagementModelGateway | None = None
+ command_gateway: PluginCommandRunnerGateway | None = None
+ lifecycle_lock: PluginLifecycleLock | None = None
class CliPluginRuntimeService:
@@ -59,12 +70,12 @@ def __init__(
*,
success_code: int = SUCCESS,
runtime_error_code: int = RUNTIME_ERROR,
- runtime_environment: object | None = None,
- dependency_checker: object | None = None,
- management_gateway: object | None = None,
- model_gateway: object | None = None,
- command_gateway: object | None = None,
- lifecycle_lock: object | None = None,
+ runtime_environment: PluginRuntimeEnvironmentService | None = None,
+ dependency_checker: PluginDependencyChecker | None = None,
+ management_gateway: PluginManagementRuntimeGateway | None = None,
+ model_gateway: PluginManagementModelGateway | None = None,
+ command_gateway: PluginCommandRunnerGateway | None = None,
+ lifecycle_lock: PluginLifecycleLock | None = None,
plugin_gateway: PluginRuntimeGateway | None = None,
) -> None:
"""
@@ -91,10 +102,10 @@ def __init__(
command_gateway=command_gateway,
lifecycle_lock=lifecycle_lock,
)
- self._core_runtime: Any | None = None
+ self._core_runtime: PluginRuntimeService | None = None
@property
- def core_runtime(self) -> Any:
+ def core_runtime(self) -> PluginRuntimeService:
"""
延迟获取插件核心运行时服务。
@@ -114,7 +125,7 @@ def core_runtime(self) -> Any:
)
return self._core_runtime
- def _resolve_runtime_environment(self) -> object:
+ def _resolve_runtime_environment(self) -> PluginRuntimeEnvironmentService:
"""
解析插件核心运行时环境服务。
@@ -126,7 +137,7 @@ def _resolve_runtime_environment(self) -> object:
self.dependencies = replace(self.dependencies, runtime_environment=runtime_environment)
return runtime_environment
- def _load_management_gateway(self) -> object:
+ def _load_management_gateway(self) -> PluginManagementRuntimeGateway:
"""
解析插件管理运行时适配器。
@@ -141,18 +152,20 @@ def _load_management_gateway(self) -> object:
)
return management_gateway
- def _resolve_management_gateway(self) -> object:
+ def _resolve_management_gateway(self) -> PluginManagementRuntimeGateway:
"""
解析插件管理运行时适配器。
:return: 插件管理运行时适配器
"""
if self.dependencies.management_gateway is None:
- self._load_management_gateway()
+ return self._load_management_gateway()
return self.dependencies.management_gateway
@staticmethod
- def _build_gateway_overrides(gateway_overrides_class: object, management_gateway: object) -> object:
+ def _build_gateway_overrides(
+ gateway_overrides_class: type[PluginRuntimeGatewayOverrides], management_gateway: PluginManagementRuntimeGateway
+ ) -> PluginRuntimeGatewayOverrides:
"""
构建插件核心运行时窄端口覆盖项。
@@ -171,27 +184,27 @@ def _build_gateway_overrides(gateway_overrides_class: object, management_gateway
migration_execution_gateway=management_gateway,
)
- def _resolve_model_gateway(self) -> object:
+ def _resolve_model_gateway(self) -> PluginManagementModelGateway:
"""
解析插件核心运行时模型工厂网关。
:return: 插件核心运行时模型工厂网关
"""
- if self.dependencies.model_gateway is None:
- self._resolve_management_gateway()
- return self.dependencies.model_gateway
+ if self.dependencies.model_gateway is not None:
+ return self.dependencies.model_gateway
+ return self._resolve_management_gateway()
- def _resolve_command_gateway(self) -> object:
+ def _resolve_command_gateway(self) -> PluginCommandRunnerGateway:
"""
解析插件核心运行时命令执行网关。
:return: 插件核心运行时命令执行网关
"""
- if self.dependencies.command_gateway is None:
- self._resolve_management_gateway()
- return self.dependencies.command_gateway
+ if self.dependencies.command_gateway is not None:
+ return self.dependencies.command_gateway
+ return self._resolve_management_gateway()
- def _resolve_lifecycle_lock(self) -> object:
+ def _resolve_lifecycle_lock(self) -> PluginLifecycleLock:
"""
解析插件核心生命周期操作锁。
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/support.py b/ruoyi-fastapi-backend/cli/runtime/plugin/support.py
index dbd068419..8c159307b 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/support.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/support.py
@@ -2,6 +2,7 @@
import hashlib
import re
from dataclasses import dataclass, field
+from io import StringIO
from pathlib import Path
from typing import Any
@@ -80,7 +81,7 @@ class PluginTestCommandResultPayload:
completed: Any
- def to_payload(self) -> dict[str, Any]:
+ def to_payload(self) -> dict[str, object]:
"""
序列化为既有 CLI payload 契约。
@@ -105,7 +106,7 @@ class PluginTestResultItemPayload:
target: PluginTestTarget
completed: Any
- def to_payload(self) -> dict[str, Any]:
+ def to_payload(self) -> dict[str, object]:
"""
序列化为既有 CLI payload 契约。
@@ -132,7 +133,7 @@ class PluginTestMissingPayload:
plugin_id: str
expected_paths: list[Path]
- def to_payload(self) -> dict[str, Any]:
+ def to_payload(self) -> dict[str, object]:
"""
序列化为既有 CLI payload 契约。
@@ -166,7 +167,7 @@ class PluginTestExecutionPayload:
frontend_build: bool
results: list[dict[str, Any]]
- def to_payload(self) -> dict[str, Any]:
+ def to_payload(self) -> dict[str, object]:
"""
序列化为既有 CLI payload 契约。
@@ -198,10 +199,10 @@ class CliPluginRuntimeExceptionPayload:
:ivar failure_code: 失败退出码
"""
- exception_payload: dict[str, Any]
+ exception_payload: dict[str, object]
failure_code: int = RUNTIME_ERROR
- def to_payload(self) -> dict[str, Any]:
+ def to_payload(self) -> dict[str, object]:
"""
序列化为既有 CLI payload 契约。
@@ -220,11 +221,11 @@ class CliPluginRuntimeExitCodePayload:
:ivar failure_code: 失败退出码
"""
- payload: dict[str, Any]
+ payload: dict[str, object]
success_code: int = SUCCESS
failure_code: int = RUNTIME_ERROR
- def to_payload(self) -> dict[str, Any]:
+ def to_payload(self) -> dict[str, object]:
"""
序列化为既有 CLI payload 契约。
@@ -290,7 +291,9 @@ def to_yaml(self) -> str:
:return: YAML 文本
"""
- return yaml.safe_dump(self.to_dict(), allow_unicode=True, sort_keys=False)
+ stream = StringIO()
+ yaml.safe_dump(self.to_dict(), stream, allow_unicode=True, sort_keys=False)
+ return stream.getvalue()
class PluginDependencyLockfileTemplateBuilder:
@@ -1010,7 +1013,7 @@ class PluginTestPayloadBuilder:
"""
@staticmethod
- def build_command_result(completed: Any) -> dict[str, Any]:
+ def build_command_result(completed: Any) -> dict[str, object]:
"""
构建 CLI 系统命令执行结果负载。
@@ -1020,7 +1023,7 @@ def build_command_result(completed: Any) -> dict[str, Any]:
return PluginTestCommandResultPayload(completed).to_payload()
@staticmethod
- def build_result_item(target: PluginTestTarget, completed: Any) -> dict[str, Any]:
+ def build_result_item(target: PluginTestTarget, completed: Any) -> dict[str, object]:
"""
构建单个插件测试结果项。
@@ -1032,11 +1035,11 @@ def build_result_item(target: PluginTestTarget, completed: Any) -> dict[str, Any
@staticmethod
def with_exit_code(
- payload: dict[str, Any],
+ payload: dict[str, object],
*,
success_code: int = SUCCESS,
failure_code: int = RUNTIME_ERROR,
- ) -> dict[str, Any]:
+ ) -> dict[str, object]:
"""
为插件测试负载补充退出码。
@@ -1052,7 +1055,7 @@ def with_exit_code(
).to_payload()
@staticmethod
- def build_missing_payload(plugin_id: str, expected_paths: list[Path]) -> dict[str, Any]:
+ def build_missing_payload(plugin_id: str, expected_paths: list[Path]) -> dict[str, object]:
"""
构建插件测试目标缺失负载。
@@ -1071,7 +1074,7 @@ def build_execution_payload(
quiet: bool,
frontend_build: bool,
results: list[dict[str, Any]],
- ) -> dict[str, Any]:
+ ) -> dict[str, object]:
"""
构建插件测试执行结果负载。
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/builders.py b/ruoyi-fastapi-backend/cli/tui/actions/builders.py
index 04e859c44..0e92fb8aa 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/builders.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/builders.py
@@ -2,6 +2,7 @@
from cli.tui.actions.models import (
ActionParameterBuilder,
+ ActionParameters,
ActionSummaryBuilder,
ActionTextBuilder,
TuiActionSpec,
@@ -70,7 +71,7 @@ def build_action(
*,
action_id: str,
label: str,
- parameters: dict[str, object],
+ parameters: ActionParameters,
env: str,
summary_lines: list[str],
preview_title: str | None = None,
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/execution.py b/ruoyi-fastapi-backend/cli/tui/actions/execution.py
index ae1aa5595..ce38428f8 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/execution.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/execution.py
@@ -13,7 +13,7 @@
from cli.runtime.gen import GEN_RUNTIME, GenRuntimeService
from cli.runtime.job import JOB_RUNTIME, JobRuntimeService
from cli.runtime.ops import OPERATIONS_RUNTIME, OperationsRuntimeService
-from cli.tui.actions.models import TuiActionResult, TuiActionSpec
+from cli.tui.actions.models import ActionParameters, TuiActionResult, TuiActionSpec
from cli.tui.copy import TUI_COPY
from cli.utils import SHELL_TEXT_FORMATTER
from utils.time_util import TimezoneUtil
@@ -59,6 +59,7 @@ async def execute(self, spec: TuiActionSpec, env: str) -> TuiActionResult:
:return: 动作执行结果
:raises asyncio.CancelledError: 异步操作被取消时
"""
+ payload: dict[str, object]
try:
payload = await asyncio.wait_for(
self._dispatch(spec, env),
@@ -118,7 +119,7 @@ async def _dispatch(self, spec: TuiActionSpec, env: str) -> dict[str, Any]:
payload = self._unsupported_action(action_id)
return payload
- async def _dispatch_job(self, action_id: str, parameters: dict[str, object]) -> dict[str, Any]:
+ async def _dispatch_job(self, action_id: str, parameters: ActionParameters) -> dict[str, Any]:
"""
执行任务领域动作。
@@ -137,7 +138,7 @@ async def _dispatch_job(self, action_id: str, parameters: dict[str, object]) ->
return await self.operations_runtime.sync_jobs()
return self._unsupported_action(action_id)
- async def _dispatch_cache(self, action_id: str, parameters: dict[str, object]) -> dict[str, Any]:
+ async def _dispatch_cache(self, action_id: str, parameters: ActionParameters) -> dict[str, Any]:
"""
执行缓存领域动作。
@@ -154,7 +155,7 @@ async def _dispatch_cache(self, action_id: str, parameters: dict[str, object]) -
)
return self._unsupported_action(action_id)
- async def _dispatch_gen(self, action_id: str, parameters: dict[str, object]) -> dict[str, Any]:
+ async def _dispatch_gen(self, action_id: str, parameters: ActionParameters) -> dict[str, Any]:
"""
执行代码生成领域动作。
@@ -169,7 +170,7 @@ async def _dispatch_gen(self, action_id: str, parameters: dict[str, object]) ->
return await self.gen_runtime.sync_gen_table_from_db(table_name)
return self._unsupported_action(action_id)
- async def _dispatch_database(self, action_id: str, parameters: dict[str, object]) -> dict[str, Any]:
+ async def _dispatch_database(self, action_id: str, parameters: ActionParameters) -> dict[str, Any]:
"""
执行数据库领域动作。
@@ -237,7 +238,7 @@ async def _install_completion(self) -> dict[str, Any]:
activate=True,
)
- async def _dispatch_crypto(self, action_id: str, parameters: dict[str, object]) -> dict[str, Any]:
+ async def _dispatch_crypto(self, action_id: str, parameters: ActionParameters) -> dict[str, Any]:
"""
执行传输加密领域动作。
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/factories/cache.py b/ruoyi-fastapi-backend/cli/tui/actions/factories/cache.py
index 097e5ca12..5dd63e378 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/factories/cache.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/factories/cache.py
@@ -1,6 +1,7 @@
from dataclasses import dataclass
from cli.tui.actions.builders import TuiActionTemplate, TuiActionTemplateSupport
+from cli.tui.actions.models import ActionParameters
from cli.tui.adapters.models import BrowserRecordSnapshot
from cli.tui.copy import TUI_COPY
@@ -18,7 +19,7 @@ class CacheActionTemplateFactory:
support: TuiActionTemplateSupport
- def build_clear_parameters(self, record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_clear_parameters(self, record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建缓存清理预演参数。
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/factories/gen.py b/ruoyi-fastapi-backend/cli/tui/actions/factories/gen.py
index 3a0b5e6ff..2d13cb531 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/factories/gen.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/factories/gen.py
@@ -1,6 +1,7 @@
from dataclasses import dataclass
from cli.tui.actions.builders import TuiActionTemplate, TuiActionTemplateSupport
+from cli.tui.actions.models import ActionParameters
from cli.tui.adapters.models import BrowserRecordSnapshot
from cli.tui.copy import TUI_COPY
@@ -20,7 +21,7 @@ class GenActionTemplateFactory:
def build_export_dry_run_parameters(
self, record: BrowserRecordSnapshot | None, env: str
- ) -> dict[str, object] | None:
+ ) -> ActionParameters | None:
"""
构建代码生成导出 dry-run 命令参数。
@@ -34,7 +35,7 @@ def build_export_dry_run_parameters(
return None
return {'table_name': table_name, 'mode': 'zip', 'dry_run': True}
- def build_sync_db_parameters(self, record: BrowserRecordSnapshot | None, env: str) -> dict[str, object] | None:
+ def build_sync_db_parameters(self, record: BrowserRecordSnapshot | None, env: str) -> ActionParameters | None:
"""
构建代码生成表结构同步命令参数。
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/factories/jobs.py b/ruoyi-fastapi-backend/cli/tui/actions/factories/jobs.py
index 2b2a994eb..715f1e175 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/factories/jobs.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/factories/jobs.py
@@ -1,6 +1,7 @@
from dataclasses import dataclass
from cli.tui.actions.builders import TuiActionTemplate, TuiActionTemplateSupport
+from cli.tui.actions.models import ActionParameters
from cli.tui.adapters.models import BrowserRecordSnapshot
from cli.tui.copy import TUI_COPY
@@ -18,7 +19,7 @@ class JobActionTemplateFactory:
support: TuiActionTemplateSupport
- def build_run_once_parameters(self, record: BrowserRecordSnapshot | None, env: str) -> dict[str, object] | None:
+ def build_run_once_parameters(self, record: BrowserRecordSnapshot | None, env: str) -> ActionParameters | None:
"""
构建任务执行一次命令参数。
@@ -53,7 +54,7 @@ def build_run_once_summary(self, record: BrowserRecordSnapshot | None, env: str)
),
]
- def build_toggle_parameters(self, record: BrowserRecordSnapshot | None, env: str) -> dict[str, object] | None:
+ def build_toggle_parameters(self, record: BrowserRecordSnapshot | None, env: str) -> ActionParameters | None:
"""
构建任务暂停或恢复命令参数。
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/factories/static.py b/ruoyi-fastapi-backend/cli/tui/actions/factories/static.py
index 62b5ce87d..304287773 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/factories/static.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/factories/static.py
@@ -1,6 +1,7 @@
from dataclasses import dataclass
from cli.tui.actions.builders import TuiActionTemplate, TuiActionTemplateSupport
+from cli.tui.actions.models import ActionParameters
from cli.tui.adapters.models import BrowserRecordSnapshot
from cli.tui.copy import TUI_COPY
@@ -19,7 +20,7 @@ class StaticActionTemplateFactory:
support: TuiActionTemplateSupport
@staticmethod
- def build_job_sync_parameters(record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_job_sync_parameters(record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建任务同步命令参数。
@@ -31,7 +32,7 @@ def build_job_sync_parameters(record: BrowserRecordSnapshot | None, env: str) ->
return {}
@staticmethod
- def build_config_sync_parameters(record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_config_sync_parameters(record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建配置同步命令参数。
@@ -43,7 +44,7 @@ def build_config_sync_parameters(record: BrowserRecordSnapshot | None, env: str)
return {}
@staticmethod
- def build_cache_warmup_parameters(record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_cache_warmup_parameters(record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建缓存预热命令参数。
@@ -55,7 +56,7 @@ def build_cache_warmup_parameters(record: BrowserRecordSnapshot | None, env: str
return {}
@staticmethod
- def build_db_upgrade_parameters(record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_db_upgrade_parameters(record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建数据库升级预演参数。
@@ -67,7 +68,7 @@ def build_db_upgrade_parameters(record: BrowserRecordSnapshot | None, env: str)
return {'revision': 'head', 'dry_run': True}
@staticmethod
- def build_db_init_dry_run_parameters(record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_db_init_dry_run_parameters(record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建数据库初始化预演命令参数。
@@ -79,7 +80,7 @@ def build_db_init_dry_run_parameters(record: BrowserRecordSnapshot | None, env:
return {'dry_run': True}
@staticmethod
- def build_app_precheck_parameters(record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_app_precheck_parameters(record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建应用启动前检查参数。
@@ -91,7 +92,7 @@ def build_app_precheck_parameters(record: BrowserRecordSnapshot | None, env: str
return {'include_config': True}
@staticmethod
- def build_completion_install_parameters(record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_completion_install_parameters(record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建补全安装命令参数。
@@ -103,7 +104,7 @@ def build_completion_install_parameters(record: BrowserRecordSnapshot | None, en
return {'activate': True}
@staticmethod
- def build_prod_check_parameters(record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_prod_check_parameters(record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建综合运行巡检参数。
@@ -115,7 +116,7 @@ def build_prod_check_parameters(record: BrowserRecordSnapshot | None, env: str)
return {'include_config': True}
@staticmethod
- def build_crypto_rotate_parameters(record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_crypto_rotate_parameters(record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建加密轮换预演命令参数。
@@ -127,7 +128,7 @@ def build_crypto_rotate_parameters(record: BrowserRecordSnapshot | None, env: st
return {'key_size': 2048}
@staticmethod
- def build_crypto_keygen_parameters(record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_crypto_keygen_parameters(record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建加密密钥生成命令参数。
@@ -139,7 +140,7 @@ def build_crypto_keygen_parameters(record: BrowserRecordSnapshot | None, env: st
return {'key_size': 2048}
@staticmethod
- def build_ops_ping_db_parameters(record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_ops_ping_db_parameters(record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建数据库探活命令参数。
@@ -151,7 +152,7 @@ def build_ops_ping_db_parameters(record: BrowserRecordSnapshot | None, env: str)
return {}
@staticmethod
- def build_ops_ping_redis_parameters(record: BrowserRecordSnapshot | None, env: str) -> dict[str, object]:
+ def build_ops_ping_redis_parameters(record: BrowserRecordSnapshot | None, env: str) -> ActionParameters:
"""
构建 Redis 探活命令参数。
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/models.py b/ruoyi-fastapi-backend/cli/tui/actions/models.py
index 3a7791fc9..6b7831323 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/models.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/models.py
@@ -1,11 +1,10 @@
from collections.abc import Callable
from dataclasses import dataclass
-from typing import Literal
from cli.tui.adapters.models import TUI_ADAPTER_MODEL_RENDERER, BrowserRecordSnapshot
-ActionSlot = Literal['primary', 'secondary', 'global', 'utility']
-ActionParameterBuilder = Callable[[BrowserRecordSnapshot | None, str], dict[str, object] | None]
+ActionParameters = dict[str, str | int]
+ActionParameterBuilder = Callable[[BrowserRecordSnapshot | None, str], ActionParameters | None]
ActionSummaryBuilder = Callable[[BrowserRecordSnapshot | None, str], list[str]]
ActionTextBuilder = Callable[[BrowserRecordSnapshot | None, str], str]
@@ -25,7 +24,7 @@ class TuiActionSpec:
action_id: str
label: str
- parameters: dict[str, object]
+ parameters: ActionParameters
preview_title: str
preview_lines: list[str]
refresh_view: bool = True
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/presentation.py b/ruoyi-fastapi-backend/cli/tui/actions/presentation.py
index 9063c4b41..83f3c6d77 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/presentation.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/presentation.py
@@ -81,10 +81,9 @@ def build_browser_action_lines(
"""
lines: list[str] = []
for capability in self.capability_registry.get_browser_capabilities(view_key):
- slot = capability.slot # type: ignore[assignment]
action = self.action_registry.resolve_browser_action(
view_key=view_key,
- slot=slot,
+ slot=capability.slot,
record=record,
env=env,
)
diff --git a/ruoyi-fastapi-backend/cli/tui/actions/registry.py b/ruoyi-fastapi-backend/cli/tui/actions/registry.py
index 1a35d99ae..a58561059 100644
--- a/ruoyi-fastapi-backend/cli/tui/actions/registry.py
+++ b/ruoyi-fastapi-backend/cli/tui/actions/registry.py
@@ -1,8 +1,9 @@
from dataclasses import dataclass
from cli.tui.actions.builders import TuiActionSpecFactory, TuiActionTemplate
-from cli.tui.actions.models import ActionSlot, TuiActionSpec
+from cli.tui.actions.models import TuiActionSpec
from cli.tui.adapters.models import BrowserRecordSnapshot
+from cli.tui.capabilities import ActionSlot
@dataclass(frozen=True)
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/app.py b/ruoyi-fastapi-backend/cli/tui/adapters/app.py
index 8a5ecc5e0..c57020783 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/app.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/app.py
@@ -2,7 +2,7 @@
from dataclasses import dataclass
from typing import Any
-from cli.tui.adapters.base import BaseDetailAdapter
+from cli.tui.adapters.base import BaseDetailAdapter, get_dict_field, get_list_field
from cli.tui.adapters.models import (
TUI_ADAPTER_MODEL_RENDERER,
DetailPageSnapshot,
@@ -110,7 +110,7 @@ def resolve_completion_preview_shell(payload: dict[str, Any] | None) -> str:
if not isinstance(payload, dict):
return 'bash'
active_shell = str(payload.get('activeShell') or '').strip().lower()
- shells = payload.get('shells') if isinstance(payload.get('shells'), dict) else {}
+ shells = get_dict_field(payload, 'shells')
if active_shell and isinstance(shells.get(active_shell), dict) and shells[active_shell].get('supported', False):
return active_shell
for shell_name in ('bash', 'zsh', 'fish', 'powershell'):
@@ -127,8 +127,7 @@ def build_env_section(payload: dict[str, Any] | None) -> DetailSectionSnapshot:
:param payload: ``app env`` JSON 负载
:return: 分区快照
"""
- runtime = payload.get('runtime') if isinstance(payload, dict) else None
- if not isinstance(runtime, dict):
+ if not isinstance(payload, dict) or not isinstance(runtime := payload.get('runtime'), dict):
return DetailSectionSnapshot(
title='环境解析',
status='fail',
@@ -161,8 +160,7 @@ def build_config_section(payload: dict[str, Any] | None) -> DetailSectionSnapsho
:param payload: ``app config`` JSON 负载
:return: 分区快照
"""
- config = payload.get('config') if isinstance(payload, dict) else None
- if not isinstance(config, dict):
+ if not isinstance(payload, dict) or not isinstance(config := payload.get('config'), dict):
return DetailSectionSnapshot(
title='应用配置',
status='fail',
@@ -196,8 +194,7 @@ def build_dependency_section(payload: dict[str, Any] | None) -> DetailSectionSna
:param payload: ``app config`` JSON 负载
:return: 分区快照
"""
- config = payload.get('config') if isinstance(payload, dict) else None
- if not isinstance(config, dict):
+ if not isinstance(payload, dict) or not isinstance(config := payload.get('config'), dict):
return DetailSectionSnapshot(
title='依赖配置',
status='fail',
@@ -236,8 +233,8 @@ def build_routes_section(self, payload: dict[str, Any] | None) -> DetailSectionS
)
count = payload.get('count', 0)
- routes = payload.get('routes') if isinstance(payload.get('routes'), list) else []
- grouped_routes = payload.get('groupedRoutes') if isinstance(payload.get('groupedRoutes'), dict) else {}
+ routes = get_list_field(payload, 'routes')
+ grouped_routes = get_dict_field(payload, 'groupedRoutes')
group_items = sorted(
((str(tag), len(items) if isinstance(items, list) else 0) for tag, items in grouped_routes.items()),
key=lambda item: (-item[1], item[0]),
@@ -303,10 +300,10 @@ def build_completion_section(payload: dict[str, Any] | None) -> DetailSectionSna
),
)
- shells = payload.get('shells') if isinstance(payload.get('shells'), dict) else {}
+ shells = get_dict_field(payload, 'shells')
active_shell = str(payload.get('activeShell') or '-')
- env_choices = payload.get('envChoices') if isinstance(payload.get('envChoices'), list) else []
- active_shell_payload = shells.get(active_shell) if isinstance(shells.get(active_shell), dict) else None
+ env_choices = get_list_field(payload, 'envChoices')
+ active_shell_payload = shells.get(active_shell)
target_file = active_shell_payload.get('targetFile', '-') if isinstance(active_shell_payload, dict) else '-'
source_command = (
active_shell_payload.get('sourceCommand', '-') if isinstance(active_shell_payload, dict) else '-'
@@ -417,9 +414,9 @@ def build_doctor_section(payload: dict[str, Any] | None) -> DetailSectionSnapsho
),
)
- database = payload.get('database') if isinstance(payload.get('database'), dict) else {}
- redis = payload.get('redis') if isinstance(payload.get('redis'), dict) else {}
- crypto = payload.get('crypto') if isinstance(payload.get('crypto'), dict) else {}
+ database = get_dict_field(payload, 'database')
+ redis = get_dict_field(payload, 'redis')
+ crypto = get_dict_field(payload, 'crypto')
return DetailSectionSnapshot(
title='启动前检查',
status='ok' if payload.get('ok', False) else 'fail',
@@ -493,16 +490,8 @@ def build_overview_section(
routes_ok = bool(isinstance(routes_payload, dict) and routes_payload.get('ok', False))
completion_ok = bool(isinstance(completion_payload, dict) and completion_payload.get('ok', False))
route_count = routes_payload.get('count', 0) if isinstance(routes_payload, dict) else 0
- runtime = (
- env_payload.get('runtime')
- if isinstance(env_payload, dict) and isinstance(env_payload.get('runtime'), dict)
- else {}
- )
- config = (
- config_payload.get('config')
- if isinstance(config_payload, dict) and isinstance(config_payload.get('config'), dict)
- else {}
- )
+ runtime = get_dict_field(env_payload, 'runtime')
+ config = get_dict_field(config_payload, 'config')
status = 'ok'
conclusion = '应用基线正常,可继续查看环境映射、配置摘要与路由状态'
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/base.py b/ruoyi-fastapi-backend/cli/tui/adapters/base.py
index ab3b5b616..18974930c 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/base.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/base.py
@@ -11,6 +11,30 @@
from cli.utils import SHELL_TEXT_FORMATTER
+def get_dict_field(payload: object, key: str) -> dict[str, Any]:
+ """
+ 读取命令结果中的字典字段,字段缺失或类型不符时返回空字典。
+
+ :param payload: 命令结果
+ :param key: 字段名
+ :return: 字段中的字典
+ """
+ value = payload.get(key) if isinstance(payload, dict) else None
+ return value if isinstance(value, dict) else {}
+
+
+def get_list_field(payload: object, key: str) -> list[Any]:
+ """
+ 读取命令结果中的列表字段,字段缺失或类型不符时返回空列表。
+
+ :param payload: 命令结果
+ :param key: 字段名
+ :return: 字段中的列表
+ """
+ value = payload.get(key) if isinstance(payload, dict) else None
+ return value if isinstance(value, list) else []
+
+
class BaseBrowserAdapter:
"""
TUI 浏览页适配基类。
@@ -61,7 +85,7 @@ def resolve_active_filter(self, filter_key: str) -> PageFilterOption:
"""
return TUI_SEARCH_SERVICE.resolve_filter_option(self.filter_options, filter_key) or self.filter_options[0]
- def resolve_search_context(self, query: str) -> PageSearchContext:
+ def resolve_search_context(self, query: str) -> PageSearchContext | None:
"""
解析当前页面搜索上下文。
@@ -201,9 +225,9 @@ def filter_sections(self, sections: Sequence[DetailSectionSnapshot], query: str)
:param query: 搜索词
:return: 过滤后的分区列表
"""
- return TUI_SEARCH_SERVICE.filter_detail_sections(list(sections), query) # type: ignore[arg-type]
+ return TUI_SEARCH_SERVICE.filter_detail_sections(list(sections), query)
- def resolve_search_context(self, query: str) -> PageSearchContext:
+ def resolve_search_context(self, query: str) -> PageSearchContext | None:
"""
解析当前详情页搜索上下文。
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/cache.py b/ruoyi-fastapi-backend/cli/tui/adapters/cache.py
index 0a10bdea3..e26fdd2e7 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/cache.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/cache.py
@@ -1,7 +1,7 @@
import asyncio
from typing import Any
-from cli.tui.adapters.base import BaseBrowserAdapter
+from cli.tui.adapters.base import BaseBrowserAdapter, get_dict_field, get_list_field
from cli.tui.adapters.models import (
TUI_ADAPTER_MODEL_RENDERER,
BrowserPageSnapshot,
@@ -81,7 +81,7 @@ def build_overview_section(self, payload: dict[str, Any] | None) -> DetailSectio
:param payload: ``cache stats`` JSON 负载
:return: 分区快照
"""
- info = payload.get('info') if isinstance(payload, dict) and isinstance(payload.get('info'), dict) else {}
+ info = get_dict_field(payload, 'info')
cache_rows = self.row_extractor.extract_cache_name_rows(payload)
return DetailSectionSnapshot(
title='Redis 摘要',
@@ -110,7 +110,7 @@ def build_overview_judgement_section(
:param filtered_rows: 当前筛选后的缓存名列表
:return: 分区快照
"""
- info = payload.get('info') if isinstance(payload, dict) and isinstance(payload.get('info'), dict) else {}
+ info = get_dict_field(payload, 'info')
cache_rows = self.row_extractor.extract_cache_name_rows(payload)
db_size = payload.get('dbSize', '-') if isinstance(payload, dict) else '-'
client_count = info.get('connected_clients', '-')
@@ -207,7 +207,7 @@ def build_keys_summary_section(self, payload: dict[str, Any] | None) -> DetailSe
payload, empty_label='键摘要', empty_value='不可用'
),
)
- keys = payload.get('keys') if isinstance(payload.get('keys'), list) else []
+ keys = get_list_field(payload, 'keys')
rendered_keys = [str(item).strip() for item in keys if str(item).strip()]
lines = [
'## 统计',
@@ -241,7 +241,7 @@ def build_keys_section(self, payload: dict[str, Any] | None) -> DetailSectionSna
payload, empty_label='键列表', empty_value='不可用'
),
)
- keys = payload.get('keys') if isinstance(payload.get('keys'), list) else []
+ keys = get_list_field(payload, 'keys')
lines = [
SHELL_TEXT_FORMATTER.truncate_text(item, 88) for item in keys[:12] if str(item).strip()
] or TUI_ADAPTER_MODEL_RENDERER.build_empty_lines(
@@ -360,7 +360,7 @@ async def load_cache_detail_sections(
keys_payload = await self.query_service.get_cache_keys(cache_name)
key_items: list[str] = []
if isinstance(keys_payload, dict) and keys_payload.get('ok', False):
- raw_keys = keys_payload.get('keys') if isinstance(keys_payload.get('keys'), list) else []
+ raw_keys = get_list_field(keys_payload, 'keys')
key_items = [str(item).strip() for item in raw_keys if str(item).strip()]
return [
self.build_keys_summary_section(keys_payload),
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/crypto.py b/ruoyi-fastapi-backend/cli/tui/adapters/crypto.py
index e4e6bf40d..d5eed9f34 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/crypto.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/crypto.py
@@ -107,8 +107,7 @@ def build_public_identity_section(payload: dict[str, Any] | None) -> DetailSecti
:param payload: ``crypto export-public`` JSON 负载
:return: 分区快照
"""
- public_key_payload = payload.get('publicKey') if isinstance(payload, dict) else None
- if not isinstance(public_key_payload, dict):
+ if not isinstance(payload, dict) or not isinstance(public_key_payload := payload.get('publicKey'), dict):
return DetailSectionSnapshot(
title='公钥身份',
status='fail',
@@ -134,8 +133,7 @@ def build_supported_kids_section(payload: dict[str, Any] | None) -> DetailSectio
:param payload: ``crypto export-public`` JSON 负载
:return: 分区快照
"""
- public_key_payload = payload.get('publicKey') if isinstance(payload, dict) else None
- if not isinstance(public_key_payload, dict):
+ if not isinstance(payload, dict) or not isinstance(public_key_payload := payload.get('publicKey'), dict):
return DetailSectionSnapshot(
title='兼容版本',
status='fail',
@@ -165,8 +163,7 @@ def build_public_preview_section(self, payload: dict[str, Any] | None) -> Detail
:param payload: ``crypto export-public`` JSON 负载
:return: 分区快照
"""
- public_key_payload = payload.get('publicKey') if isinstance(payload, dict) else None
- if not isinstance(public_key_payload, dict):
+ if not isinstance(payload, dict) or not isinstance(public_key_payload := payload.get('publicKey'), dict):
return DetailSectionSnapshot(
title='公钥预览',
status='fail',
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/gen.py b/ruoyi-fastapi-backend/cli/tui/adapters/gen.py
index c424c637b..c58917438 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/gen.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/gen.py
@@ -1,7 +1,7 @@
import asyncio
from typing import Any
-from cli.tui.adapters.base import BaseBrowserAdapter
+from cli.tui.adapters.base import BaseBrowserAdapter, get_dict_field, get_list_field
from cli.tui.adapters.models import (
TUI_ADAPTER_MODEL_RENDERER,
BrowserPageSnapshot,
@@ -68,9 +68,8 @@ def build_gen_focus_section(self, payload: dict[str, Any] | None) -> DetailSecti
:param payload: ``gen detail`` JSON 负载
:return: 分区快照
"""
- detail = payload.get('detail') if isinstance(payload, dict) else None
- info = detail.get('info') if isinstance(detail, dict) else None
- if not isinstance(info, dict):
+ detail = get_dict_field(payload, 'detail')
+ if not isinstance(payload, dict) or not isinstance(detail.get('info'), dict):
return DetailSectionSnapshot(
title='业务表摘要',
status='fail',
@@ -93,9 +92,8 @@ def build_gen_generation_section(self, payload: dict[str, Any] | None) -> Detail
:param payload: ``gen detail`` JSON 负载
:return: 分区快照
"""
- detail = payload.get('detail') if isinstance(payload, dict) else None
- info = detail.get('info') if isinstance(detail, dict) else None
- if not isinstance(info, dict):
+ detail = get_dict_field(payload, 'detail')
+ if not isinstance(payload, dict) or not isinstance(info := detail.get('info'), dict):
return DetailSectionSnapshot(
title='生成配置',
status='fail',
@@ -124,9 +122,8 @@ def build_gen_column_summary_section(self, payload: dict[str, Any] | None) -> De
:param payload: ``gen detail`` JSON 负载
:return: 分区快照
"""
- detail = payload.get('detail') if isinstance(payload, dict) else None
- rows = detail.get('rows') if isinstance(detail, dict) else None
- if not isinstance(rows, list):
+ detail = get_dict_field(payload, 'detail')
+ if not isinstance(payload, dict) or not isinstance(rows := detail.get('rows'), list):
return DetailSectionSnapshot(
title='字段摘要',
status='fail',
@@ -155,9 +152,8 @@ def build_gen_columns_section(self, payload: dict[str, Any] | None) -> DetailSec
:param payload: ``gen detail`` JSON 负载
:return: 分区快照
"""
- detail = payload.get('detail') if isinstance(payload, dict) else None
- rows = detail.get('rows') if isinstance(detail, dict) else None
- if not isinstance(rows, list) or not rows:
+ detail = get_dict_field(payload, 'detail')
+ if not isinstance(payload, dict) or not isinstance(rows := detail.get('rows'), list) or not rows:
return DetailSectionSnapshot(
title='字段列表',
status='fail',
@@ -204,7 +200,7 @@ def build_gen_precheck_section(
"""
detail = detail_payload.get('detail') if isinstance(detail_payload, dict) else None
info = detail.get('info') if isinstance(detail, dict) else None
- rows = detail.get('rows') if isinstance(detail, dict) and isinstance(detail.get('rows'), list) else []
+ rows = get_list_field(detail, 'rows')
preview = preview_payload.get('preview') if isinstance(preview_payload, dict) else None
preview_templates = preview if isinstance(preview, dict) else {}
row_dicts = [row for row in rows if isinstance(row, dict)]
@@ -317,7 +313,7 @@ def build_gen_preview_section(self, payload: dict[str, Any] | None) -> DetailSec
payload, empty_label='代码预览', empty_value='不可用'
),
)
- preview_payload = payload.get('preview') if isinstance(payload.get('preview'), dict) else {}
+ preview_payload = get_dict_field(payload, 'preview')
lines = [
'## 模板规模',
f'模板数量: {payload.get("templateCount", len(preview_payload))}',
@@ -365,7 +361,7 @@ def build_gen_export_preview_section(self, payload: dict[str, Any] | None) -> De
),
)
- results = payload.get('results') if isinstance(payload.get('results'), list) else []
+ results = get_list_field(payload, 'results')
lines = [
'## 预演结果',
f'执行模式: {payload.get("mode", "-")}',
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/health.py b/ruoyi-fastapi-backend/cli/tui/adapters/health.py
index 634203a2b..2a3f99c7e 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/health.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/health.py
@@ -2,6 +2,7 @@
from dataclasses import dataclass, field
from typing import Any
+from cli.tui.adapters.base import get_dict_field, get_list_field
from cli.tui.copy import TUI_COPY
from cli.tui.diagnostics import TUI_DIAGNOSTIC_SERVICE
from cli.tui.keymaps import TUI_KEYMAP_REGISTRY
@@ -392,11 +393,10 @@ def build_app_env_panel(
:param routes_payload: ``app routes`` JSON 负载
:return: 面板快照
"""
- runtime = env_payload.get('runtime') if isinstance(env_payload, dict) else None
route_count = routes_payload.get('count', 0) if isinstance(routes_payload, dict) else 0
grouped_routes = routes_payload.get('groupedRoutes') if isinstance(routes_payload, dict) else None
group_count = len(grouped_routes) if isinstance(grouped_routes, dict) else 0
- if not isinstance(runtime, dict):
+ if not isinstance(env_payload, dict) or not isinstance(runtime := env_payload.get('runtime'), dict):
return DashboardPanelSnapshot(
title='应用摘要',
status='fail',
@@ -441,9 +441,9 @@ def build_health_panel(self, payload: dict[str, Any] | None) -> DashboardPanelSn
),
)
- database = payload.get('database') if isinstance(payload.get('database'), dict) else {}
- redis = payload.get('redis') if isinstance(payload.get('redis'), dict) else {}
- crypto = payload.get('crypto') if isinstance(payload.get('crypto'), dict) else {}
+ database = get_dict_field(payload, 'database')
+ redis = get_dict_field(payload, 'redis')
+ crypto = get_dict_field(payload, 'crypto')
return DashboardPanelSnapshot(
title='系统摘要',
status='ok' if payload.get('ok', False) else 'fail',
@@ -653,8 +653,8 @@ def build_cache_panel(self, payload: dict[str, Any] | None) -> DashboardPanelSna
suggestion=TUI_COPY.build_dashboard_page_suggestion('缓存', '查看 Redis 状态'),
),
)
- info = payload.get('info') if isinstance(payload.get('info'), dict) else {}
- cache_names = payload.get('cacheNames') if isinstance(payload.get('cacheNames'), list) else []
+ info = get_dict_field(payload, 'info')
+ cache_names = get_list_field(payload, 'cacheNames')
return DashboardPanelSnapshot(
title='缓存摘要',
status='ok' if payload.get('ok', False) else 'fail',
@@ -687,8 +687,8 @@ def build_dependency_panel(self, payload: dict[str, Any] | None) -> DashboardPan
suggestion=TUI_COPY.build_dashboard_page_suggestion('运维', '检查依赖详情'),
),
)
- packages = payload.get('packages') if isinstance(payload.get('packages'), dict) else {}
- missing_required = payload.get('missingRequired') if isinstance(payload.get('missingRequired'), list) else []
+ packages = get_dict_field(payload, 'packages')
+ missing_required = get_list_field(payload, 'missingRequired')
lines = [
'## 依赖结论',
f'检查结果: {"通过" if payload.get("ok", False) else "异常"}',
@@ -715,8 +715,7 @@ def build_server_info_panel(self, payload: dict[str, Any] | None) -> DashboardPa
:param payload: ``ops server-info`` JSON 负载
:return: 面板快照
"""
- server = payload.get('server') if isinstance(payload, dict) else None
- if not isinstance(server, dict):
+ if not isinstance(payload, dict) or not isinstance(server := payload.get('server'), dict):
return DashboardPanelSnapshot(
title='服务器摘要',
status='fail',
@@ -727,9 +726,9 @@ def build_server_info_panel(self, payload: dict[str, Any] | None) -> DashboardPa
suggestion=TUI_COPY.build_dashboard_page_suggestion('运维', '重新采集服务器摘要'),
),
)
- sys_info = server.get('sys') if isinstance(server.get('sys'), dict) else {}
- cpu_info = server.get('cpu') if isinstance(server.get('cpu'), dict) else {}
- mem_info = server.get('mem') if isinstance(server.get('mem'), dict) else {}
+ sys_info = get_dict_field(server, 'sys')
+ cpu_info = get_dict_field(server, 'cpu')
+ mem_info = get_dict_field(server, 'mem')
return DashboardPanelSnapshot(
title='服务器摘要',
status='ok' if payload.get('ok', False) else 'fail',
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/jobs.py b/ruoyi-fastapi-backend/cli/tui/adapters/jobs.py
index 5ec74328a..b0ed4cd50 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/jobs.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/jobs.py
@@ -341,8 +341,7 @@ def build_job_focus_section(self, payload: dict[str, Any] | None) -> DetailSecti
:param payload: ``job detail`` JSON 负载
:return: 分区快照
"""
- job = payload.get('job') if isinstance(payload, dict) else None
- if not isinstance(job, dict):
+ if not isinstance(payload, dict) or not isinstance(job := payload.get('job'), dict):
return DetailSectionSnapshot(
title='任务摘要',
status='fail',
@@ -368,8 +367,7 @@ def build_job_schedule_section(payload: dict[str, Any] | None) -> DetailSectionS
:param payload: ``job detail`` JSON 负载
:return: 分区快照
"""
- job = payload.get('job') if isinstance(payload, dict) else None
- if not isinstance(job, dict):
+ if not isinstance(payload, dict) or not isinstance(job := payload.get('job'), dict):
return DetailSectionSnapshot(
title='调度配置',
status='fail',
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/models.py b/ruoyi-fastapi-backend/cli/tui/adapters/models.py
index 1dd99331d..14890dd9c 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/models.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/models.py
@@ -75,9 +75,11 @@ async def resolve_detail_sections(self) -> list[DetailSectionSnapshot]:
"""
if self.detail_loader is None:
return self.detail_sections
- if self._cached_detail_sections is None:
- object.__setattr__(self, '_cached_detail_sections', tuple(await self.detail_loader()))
- return list(self._cached_detail_sections)
+ cached = self._cached_detail_sections
+ if cached is None:
+ cached = tuple(await self.detail_loader())
+ object.__setattr__(self, '_cached_detail_sections', cached)
+ return list(cached)
@dataclass(frozen=True)
diff --git a/ruoyi-fastapi-backend/cli/tui/adapters/ops.py b/ruoyi-fastapi-backend/cli/tui/adapters/ops.py
index 649497e8a..b7d05ac0d 100644
--- a/ruoyi-fastapi-backend/cli/tui/adapters/ops.py
+++ b/ruoyi-fastapi-backend/cli/tui/adapters/ops.py
@@ -2,7 +2,7 @@
from dataclasses import dataclass
from typing import Any
-from cli.tui.adapters.base import BaseDetailAdapter
+from cli.tui.adapters.base import BaseDetailAdapter, get_dict_field, get_list_field
from cli.tui.adapters.models import (
TUI_ADAPTER_MODEL_RENDERER,
DetailPageSnapshot,
@@ -103,8 +103,8 @@ def build_health_section(payload: dict[str, Any] | None) -> DetailSectionSnapsho
payload, empty_label='健康检查', empty_value='不可用'
),
)
- database = payload.get('database') if isinstance(payload.get('database'), dict) else {}
- redis = payload.get('redis') if isinstance(payload.get('redis'), dict) else {}
+ database = get_dict_field(payload, 'database')
+ redis = get_dict_field(payload, 'redis')
return DetailSectionSnapshot(
title='健康检查',
status='ok' if payload.get('ok', False) else 'fail',
@@ -184,8 +184,8 @@ def build_dependency_section(payload: dict[str, Any] | None) -> DetailSectionSna
status='fail',
lines=TUI_ADAPTER_MODEL_RENDERER.build_failure_lines(payload, empty_label='依赖', empty_value='不可用'),
)
- packages = payload.get('packages') if isinstance(payload.get('packages'), dict) else {}
- missing_required = payload.get('missingRequired') if isinstance(payload.get('missingRequired'), list) else []
+ packages = get_dict_field(payload, 'packages')
+ missing_required = get_list_field(payload, 'missingRequired')
lines = [
'## 总体结论',
f'检查结果: {"通过" if payload.get("ok", False) else "异常"}',
@@ -217,8 +217,7 @@ def build_server_section(payload: dict[str, Any] | None) -> DetailSectionSnapsho
:param payload: ``ops server-info`` JSON 负载
:return: 分区快照
"""
- server = payload.get('server') if isinstance(payload, dict) else None
- if not isinstance(server, dict):
+ if not isinstance(payload, dict) or not isinstance(server := payload.get('server'), dict):
return DetailSectionSnapshot(
title='服务器摘要',
status='fail',
@@ -227,10 +226,10 @@ def build_server_section(payload: dict[str, Any] | None) -> DetailSectionSnapsho
),
)
- sys_info = server.get('sys') if isinstance(server.get('sys'), dict) else {}
- cpu_info = server.get('cpu') if isinstance(server.get('cpu'), dict) else {}
- mem_info = server.get('mem') if isinstance(server.get('mem'), dict) else {}
- py_info = server.get('py') if isinstance(server.get('py'), dict) else {}
+ sys_info = get_dict_field(server, 'sys')
+ cpu_info = get_dict_field(server, 'cpu')
+ mem_info = get_dict_field(server, 'mem')
+ py_info = get_dict_field(server, 'py')
return DetailSectionSnapshot(
title='服务器摘要',
status='ok' if payload.get('ok', False) else 'fail',
@@ -261,8 +260,7 @@ def build_disk_section(self, payload: dict[str, Any] | None) -> DetailSectionSna
:param payload: ``ops server-info`` JSON 负载
:return: 分区快照
"""
- server = payload.get('server') if isinstance(payload, dict) else None
- if not isinstance(server, dict):
+ if not isinstance(payload, dict) or not isinstance(server := payload.get('server'), dict):
return DetailSectionSnapshot(
title='磁盘样本',
status='fail',
@@ -270,7 +268,7 @@ def build_disk_section(self, payload: dict[str, Any] | None) -> DetailSectionSna
payload, empty_label='磁盘样本', empty_value='不可用'
),
)
- sys_files = server.get('sysFiles') if isinstance(server.get('sysFiles'), list) else []
+ sys_files = get_list_field(server, 'sysFiles')
lines = TUI_ADAPTER_MODEL_RENDERER.build_empty_lines(
empty_label='磁盘样本',
empty_value='0 个',
@@ -339,13 +337,9 @@ def build_overview_section(
server_ok = bool(isinstance(server_payload, dict) and server_payload.get('ok', False))
missing_required = deps_payload.get('missingRequired') if isinstance(deps_payload, dict) else None
missing_count = len(missing_required) if isinstance(missing_required, list) else 0
- server = (
- server_payload.get('server')
- if isinstance(server_payload, dict) and isinstance(server_payload.get('server'), dict)
- else {}
- )
- cpu_info = server.get('cpu') if isinstance(server.get('cpu'), dict) else {}
- mem_info = server.get('mem') if isinstance(server.get('mem'), dict) else {}
+ server = get_dict_field(server_payload, 'server')
+ cpu_info = get_dict_field(server, 'cpu')
+ mem_info = get_dict_field(server, 'mem')
status = 'ok'
conclusion = '基础探活与运行依赖正常,可继续查看服务器资源与磁盘样本'
diff --git a/ruoyi-fastapi-backend/cli/tui/app.py b/ruoyi-fastapi-backend/cli/tui/app.py
index f5ab6fb57..1521375eb 100644
--- a/ruoyi-fastapi-backend/cli/tui/app.py
+++ b/ruoyi-fastapi-backend/cli/tui/app.py
@@ -3,8 +3,10 @@
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from time import monotonic
+from typing import ClassVar
from textual.app import App
+from textual.binding import BindingType
from textual.css.query import NoMatches
from cli.tui.adapters import (
@@ -797,7 +799,7 @@ class RuoyiTuiApp(App[None]):
"""
CSS = _TUI_APP_CSS
- BINDINGS = TUI_APP_BINDINGS
+ BINDINGS: ClassVar[list[BindingType]] = list(TUI_APP_BINDINGS)
def __init__(self, env: str) -> None:
"""
diff --git a/ruoyi-fastapi-backend/cli/tui/capabilities.py b/ruoyi-fastapi-backend/cli/tui/capabilities.py
index 07cee8067..a1a9de16f 100644
--- a/ruoyi-fastapi-backend/cli/tui/capabilities.py
+++ b/ruoyi-fastapi-backend/cli/tui/capabilities.py
@@ -3,6 +3,7 @@
from cli.tui.copy import TUI_COPY
+ActionSlot = Literal['primary', 'secondary', 'global', 'utility']
CapabilityKind = Literal['read_only', 'preview', 'low_risk_action', 'command_hint']
CapabilityScope = Literal['browser', 'detail']
@@ -21,7 +22,7 @@ class TuiCapability:
"""
kind: CapabilityKind
- slot: str
+ slot: ActionSlot
key: str
label: str
hint_label: str
@@ -41,7 +42,7 @@ class TuiCapabilitySpec:
capability_key: str
kind: CapabilityKind
- slot: str
+ slot: ActionSlot
key: str
@@ -141,7 +142,7 @@ def build_capability(
*,
capability_key: str,
kind: CapabilityKind,
- slot: str,
+ slot: ActionSlot,
key: str,
scope: CapabilityScope,
) -> TuiCapability:
diff --git a/ruoyi-fastapi-backend/cli/tui/copy/actions.py b/ruoyi-fastapi-backend/cli/tui/copy/actions.py
index f40a6cbde..aae4bdd2b 100644
--- a/ruoyi-fastapi-backend/cli/tui/copy/actions.py
+++ b/ruoyi-fastapi-backend/cli/tui/copy/actions.py
@@ -1,7 +1,6 @@
from cli.tui.copy.fragments import (
ACTION_CONSEQUENCE_TEXTS,
ACTION_FEEDBACK_COPY,
- ACTION_HINT_COPY,
ACTION_LABELS,
ACTION_NOTIFICATION_COPY,
ACTION_PREVIEW_FIELD_LABELS,
@@ -9,9 +8,13 @@
ACTION_PURPOSE_LABELS,
ACTION_RESULT_FIELD_LABELS,
ACTION_SCOPE_LABELS,
+ BROWSER_ACTION_HINT_DEFAULT,
+ BROWSER_ACTION_HINT_TEMPLATES,
CAPABILITY_HINT_LABELS,
CAPABILITY_LABELS,
COMMAND_HINT_TITLES,
+ DETAIL_ACTION_HINT_DEFAULT,
+ DETAIL_ACTION_HINT_TEMPLATES,
GENERAL_COPY,
)
from cli.utils import SHELL_TEXT_FORMATTER
@@ -184,7 +187,7 @@ def build_browser_action_hint_text(view_key: str, interaction_hint: str) -> str:
:return: 动作提示文本
"""
normalized_view = str(view_key).strip().lower()
- template = ACTION_HINT_COPY['browser_templates'].get(normalized_view, ACTION_HINT_COPY['browser_default'])
+ template = BROWSER_ACTION_HINT_TEMPLATES.get(normalized_view, BROWSER_ACTION_HINT_DEFAULT)
return template.format(interaction_hint=interaction_hint)
@staticmethod
@@ -197,7 +200,7 @@ def build_detail_action_hint_text(view_key: str, interaction_hint: str) -> str:
:return: 动作提示文本
"""
normalized_view = str(view_key).strip().lower()
- template = ACTION_HINT_COPY['detail_templates'].get(normalized_view, ACTION_HINT_COPY['detail_default'])
+ template = DETAIL_ACTION_HINT_TEMPLATES.get(normalized_view, DETAIL_ACTION_HINT_DEFAULT)
return template.format(interaction_hint=interaction_hint)
@staticmethod
@@ -244,7 +247,7 @@ def build_cli_command_hint(*command_args: str) -> str:
:param command_args: CLI 命令参数
:return: 可直接复制执行的命令文本
"""
- return SHELL_TEXT_FORMATTER.format_shell_command(('ruoyi', *command_args))
+ return SHELL_TEXT_FORMATTER.format_shell_command(['ruoyi', *command_args])
@staticmethod
def build_command_hint_lines(
diff --git a/ruoyi-fastapi-backend/cli/tui/copy/fragments.py b/ruoyi-fastapi-backend/cli/tui/copy/fragments.py
index d47411e8e..eb48f9d35 100644
--- a/ruoyi-fastapi-backend/cli/tui/copy/fragments.py
+++ b/ruoyi-fastapi-backend/cli/tui/copy/fragments.py
@@ -300,29 +300,31 @@
'value_label': '数值',
}
-ACTION_HINT_COPY = {
- 'browser_default': '当前页面以浏览为主。{interaction_hint}',
- 'browser_templates': {
- 'cache': '建议先核对 Redis 概览与键值样本,再决定预热或执行清理预演。{interaction_hint}',
- 'configs': '建议先看高风险配置,再决定是否刷新参数缓存。{interaction_hint}',
- 'gen': '建议先看生成前校验、同步预检查与代码预览,再决定是否同步表结构或执行导出预演。{interaction_hint}',
- 'jobs': '建议先看失败聚合,再决定执行一次、暂停恢复或同步调度。{interaction_hint}',
- },
- 'detail_default': '当前页面以查看分区为主。{interaction_hint}',
- 'detail_templates': {
- 'app': '建议先确认环境映射、应用配置、补全诊断和路由状态,再决定是否执行启动前检查或安装补全。{interaction_hint}',
- 'crypto': '建议先确认运行校验、公钥身份和兼容版本,再决定是否生成新密钥或执行轮换预演。{interaction_hint}',
- 'database': '建议先确认 revision、Heads 和历史链路,再决定是否执行初始化预演或升级预演。{interaction_hint}',
- 'ops': '建议先确认数据库探活、Redis 探活、依赖版本和服务器资源,再决定是否执行综合运行巡检。{interaction_hint}',
- },
- 'operation_hint_lines': [
- '> [←/→] 切换焦点',
- '> [J/K] 向上/向下滚动',
- '> [PgUp/PgDn] 整页滚动',
- '> [Home/End] 跳到首尾',
- ],
+BROWSER_ACTION_HINT_DEFAULT = '当前页面以浏览为主。{interaction_hint}'
+
+BROWSER_ACTION_HINT_TEMPLATES = {
+ 'cache': '建议先核对 Redis 概览与键值样本,再决定预热或执行清理预演。{interaction_hint}',
+ 'configs': '建议先看高风险配置,再决定是否刷新参数缓存。{interaction_hint}',
+ 'gen': '建议先看生成前校验、同步预检查与代码预览,再决定是否同步表结构或执行导出预演。{interaction_hint}',
+ 'jobs': '建议先看失败聚合,再决定执行一次、暂停恢复或同步调度。{interaction_hint}',
}
+DETAIL_ACTION_HINT_DEFAULT = '当前页面以查看分区为主。{interaction_hint}'
+
+DETAIL_ACTION_HINT_TEMPLATES = {
+ 'app': '建议先确认环境映射、应用配置、补全诊断和路由状态,再决定是否执行启动前检查或安装补全。{interaction_hint}',
+ 'crypto': '建议先确认运行校验、公钥身份和兼容版本,再决定是否生成新密钥或执行轮换预演。{interaction_hint}',
+ 'database': '建议先确认 revision、Heads 和历史链路,再决定是否执行初始化预演或升级预演。{interaction_hint}',
+ 'ops': '建议先确认数据库探活、Redis 探活、依赖版本和服务器资源,再决定是否执行综合运行巡检。{interaction_hint}',
+}
+
+OPERATION_HINT_LINES = [
+ '> [←/→] 切换焦点',
+ '> [J/K] 向上/向下滚动',
+ '> [PgUp/PgDn] 整页滚动',
+ '> [Home/End] 跳到首尾',
+]
+
ACTION_FEEDBACK_COPY = {
'toast_prefix': '动作结果',
}
diff --git a/ruoyi-fastapi-backend/cli/tui/copy/workspace.py b/ruoyi-fastapi-backend/cli/tui/copy/workspace.py
index 78622a9ae..5bb8eaa2f 100644
--- a/ruoyi-fastapi-backend/cli/tui/copy/workspace.py
+++ b/ruoyi-fastapi-backend/cli/tui/copy/workspace.py
@@ -1,5 +1,4 @@
from cli.tui.copy.fragments import (
- ACTION_HINT_COPY,
BROWSER_ACTION_PANEL_COPY,
BROWSER_EMPTY_RECORD_COPY,
BROWSER_LOADING_COPY,
@@ -7,6 +6,7 @@
DETAIL_EMPTY_SECTION_COPY,
GENERAL_COPY,
METRIC_COPY,
+ OPERATION_HINT_LINES,
SIGNAL_RAIL_COPY,
STATE_SECTION_TITLES,
STATE_SUGGESTIONS,
@@ -424,7 +424,7 @@ def build_browser_action_panel_lines(action_lines: list[str], feedback_lines: li
'',
BROWSER_ACTION_PANEL_COPY['operation_section_title'],
]
- lines.extend(ACTION_HINT_COPY['operation_hint_lines'])
+ lines.extend(OPERATION_HINT_LINES)
if feedback_lines:
lines.extend(
[
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/browser.py b/ruoyi-fastapi-backend/cli/tui/screens/browser.py
index 84f37f17f..e3f87c4d4 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/browser.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/browser.py
@@ -4,7 +4,6 @@
from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, ScrollableContainer, Vertical
-from textual.screen import Screen
from textual.widgets import Footer, Static
from cli.tui.actions import (
@@ -15,8 +14,9 @@
)
from cli.tui.adapters import BrowserPageSnapshot, BrowserRecordSnapshot, DetailSectionSnapshot
from cli.tui.adapters.models import TUI_ADAPTER_MODEL_RENDERER
+from cli.tui.capabilities import ActionSlot
from cli.tui.copy import TUI_COPY
-from cli.tui.screens.focus import BaseScreenFocusService, ScreenFocusActionsMixin
+from cli.tui.screens.focus import BaseScreenFocusService, WorkspaceScreen
from cli.tui.screens.interactions import TUI_SCREEN_INTERACTION_SERVICE, ScreenInteractionActionsMixin
from cli.tui.screens.summary import STATUS_SUMMARY_BUILDER
from cli.tui.search import TUI_SEARCH_SERVICE
@@ -90,7 +90,7 @@ def current_search_query(snapshot: BrowserPageSnapshot) -> str:
def resolve_action(
*,
active_view: str,
- slot: str,
+ slot: ActionSlot,
record: BrowserRecordSnapshot,
env: str,
) -> TuiActionSpec | None:
@@ -259,7 +259,7 @@ def get_default_scroll_target(
return screen.query_one('#workspace-main', ScrollableContainer)
-class BrowserScreen(ScreenInteractionActionsMixin, ScreenFocusActionsMixin, Screen[None]):
+class BrowserScreen(ScreenInteractionActionsMixin, WorkspaceScreen):
"""
TUI 浏览型页面。
@@ -380,7 +380,7 @@ def _apply_filter_shortcut(self, shortcut: str) -> None:
remember_filter = getattr(self.app, 'remember_browser_filter', None)
if callable(remember_filter):
remember_filter(self.active_view, target.key)
- self.app.action_refresh_current_view()
+ self.workspace_app.action_refresh_current_view()
def _open_search(self) -> None:
"""打开当前浏览页搜索输入弹窗。"""
@@ -406,7 +406,7 @@ def _clear_search(self) -> None:
self._current_search_query(),
)
- def _resolve_action(self, slot: str) -> TuiActionSpec | None:
+ def _resolve_action(self, slot: ActionSlot) -> TuiActionSpec | None:
"""
解析当前页面指定槽位对应的动作。
@@ -434,7 +434,7 @@ def _build_record_action_lines(self, record: BrowserRecordSnapshot) -> list[str]
feedback_lines=self._action_feedback_lines,
)
- def _open_action_confirm(self, slot: str) -> None:
+ def _open_action_confirm(self, slot: ActionSlot) -> None:
"""
打开指定槽位动作的确认弹窗。
@@ -706,39 +706,6 @@ def action_apply_filter_4(self) -> None:
"""应用第四个浏览页筛选条件。"""
self._apply_filter_shortcut('4')
- def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSidebar.Selected) -> None:
- """
- 根据侧边栏事件打开对应视图,并避免重复打开当前页面。
-
- :param event: 侧边栏高亮或选中事件
- """
- item = getattr(event.item, 'item', None)
- if not isinstance(item, NavigationItem):
- return
- if not event.control.navigation_ready:
- return
- if item.view_key == self.active_view and self.app.requested_view == self.active_view:
- return
- self.app.open_view(item.view_key)
-
- @on(WorkspaceSidebar.Selected)
- def on_sidebar_selected(self, event: WorkspaceSidebar.Selected) -> None:
- """
- 响应左侧导航选中事件并切换视图。
-
- :param event: 导航选中事件
- """
- self._open_sidebar_item(event)
-
- @on(WorkspaceSidebar.Highlighted)
- def on_sidebar_highlighted(self, event: WorkspaceSidebar.Highlighted) -> None:
- """
- 响应左侧导航高亮变更并立即切换视图。
-
- :param event: 导航高亮事件
- """
- self._open_sidebar_item(event)
-
def compose(self) -> ComposeResult:
"""
构建浏览页界面结构。
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/dashboard.py b/ruoyi-fastapi-backend/cli/tui/screens/dashboard.py
index 0a4d931f5..82386b82c 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/dashboard.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/dashboard.py
@@ -1,14 +1,12 @@
-from textual import on
from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Grid, Horizontal, ScrollableContainer
-from textual.screen import Screen
from textual.widgets import Footer
from cli.tui.adapters import DashboardSnapshot
from cli.tui.copy import TUI_COPY
from cli.tui.keymaps import TUI_KEYMAP_REGISTRY
-from cli.tui.screens.focus import BaseScreenFocusService, ScreenFocusActionsMixin
+from cli.tui.screens.focus import BaseScreenFocusService, WorkspaceScreen
from cli.tui.screens.summary import STATUS_SUMMARY_BUILDER
from cli.tui.widgets import (
MetricPanel,
@@ -108,7 +106,7 @@ def get_default_scroll_target(self, screen: 'DashboardScreen') -> ScrollableCont
return screen.query_one('#workspace-main', ScrollableContainer)
-class DashboardScreen(ScreenFocusActionsMixin, Screen[None]):
+class DashboardScreen(WorkspaceScreen):
"""
TUI 首页巡检屏幕。
@@ -219,36 +217,3 @@ def compose(self) -> ComposeResult:
def on_mount(self) -> None:
"""首页挂载后默认将焦点停留在左侧导航。"""
self.call_after_refresh(self.query_one(WorkspaceSidebar).focus)
-
- def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSidebar.Selected) -> None:
- """
- 根据侧边栏事件打开对应视图,并避免重复打开当前页面。
-
- :param event: 侧边栏高亮或选中事件
- """
- item = getattr(event.item, 'item', None)
- if not isinstance(item, NavigationItem):
- return
- if not event.control.navigation_ready:
- return
- if item.view_key == self.active_view and self.app.requested_view == self.active_view:
- return
- self.app.open_view(item.view_key)
-
- @on(WorkspaceSidebar.Selected)
- def on_sidebar_selected(self, event: WorkspaceSidebar.Selected) -> None:
- """
- 响应左侧导航选中事件并切换视图。
-
- :param event: 导航选中事件
- """
- self._open_sidebar_item(event)
-
- @on(WorkspaceSidebar.Highlighted)
- def on_sidebar_highlighted(self, event: WorkspaceSidebar.Highlighted) -> None:
- """
- 响应左侧导航高亮变更并立即切换视图。
-
- :param event: 导航高亮事件
- """
- self._open_sidebar_item(event)
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/detail.py b/ruoyi-fastapi-backend/cli/tui/screens/detail.py
index f16c7dab5..c40657c2c 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/detail.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/detail.py
@@ -4,7 +4,6 @@
from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, ScrollableContainer
-from textual.screen import Screen
from textual.widgets import Footer
from cli.tui.actions import (
@@ -15,8 +14,9 @@
)
from cli.tui.adapters import DetailPageSnapshot, DetailSectionSnapshot
from cli.tui.adapters.models import TUI_ADAPTER_MODEL_RENDERER
+from cli.tui.capabilities import ActionSlot
from cli.tui.copy import TUI_COPY
-from cli.tui.screens.focus import BaseScreenFocusService, ScreenFocusActionsMixin
+from cli.tui.screens.focus import BaseScreenFocusService, WorkspaceScreen
from cli.tui.screens.interactions import TUI_SCREEN_INTERACTION_SERVICE, ScreenInteractionActionsMixin
from cli.tui.screens.summary import STATUS_SUMMARY_BUILDER
from cli.tui.widgets import (
@@ -86,7 +86,7 @@ def current_search_query(snapshot: DetailPageSnapshot) -> str:
return search_context.query if search_context is not None else ''
@staticmethod
- def resolve_action(*, active_view: str, slot: str, env: str) -> TuiActionSpec | None:
+ def resolve_action(*, active_view: str, slot: ActionSlot, env: str) -> TuiActionSpec | None:
"""
解析当前详情页指定槽位对应的动作。
@@ -136,7 +136,7 @@ def get_default_scroll_target(
return screen.query_one('#workspace-main', ScrollableContainer)
-class DetailScreen(ScreenInteractionActionsMixin, ScreenFocusActionsMixin, Screen[None]):
+class DetailScreen(ScreenInteractionActionsMixin, WorkspaceScreen):
"""
TUI 通用详情屏幕。
@@ -267,7 +267,7 @@ def _clear_search(self) -> None:
self._current_search_query(),
)
- def _resolve_action(self, slot: str) -> TuiActionSpec | None:
+ def _resolve_action(self, slot: ActionSlot) -> TuiActionSpec | None:
"""
解析当前详情页指定槽位对应的动作。
@@ -276,7 +276,7 @@ def _resolve_action(self, slot: str) -> TuiActionSpec | None:
"""
return self.support.resolve_action(active_view=self.active_view, slot=slot, env=self.env)
- def _open_action_confirm(self, slot: str) -> None:
+ def _open_action_confirm(self, slot: ActionSlot) -> None:
"""
打开指定槽位动作的确认弹窗。
@@ -368,39 +368,6 @@ def on_unmount(self) -> None:
"""详情页卸载时取消尚未完成的后台任务。"""
self._cancel_task(self._action_task)
- def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSidebar.Selected) -> None:
- """
- 根据侧边栏事件打开对应视图,并避免重复打开当前页面。
-
- :param event: 侧边栏高亮或选中事件
- """
- item = getattr(event.item, 'item', None)
- if not isinstance(item, NavigationItem):
- return
- if not event.control.navigation_ready:
- return
- if item.view_key == self.active_view and self.app.requested_view == self.active_view:
- return
- self.app.open_view(item.view_key)
-
- @on(WorkspaceSidebar.Selected)
- def on_sidebar_selected(self, event: WorkspaceSidebar.Selected) -> None:
- """
- 响应左侧导航选中事件并切换视图。
-
- :param event: 导航选中事件
- """
- self._open_sidebar_item(event)
-
- @on(WorkspaceSidebar.Highlighted)
- def on_sidebar_highlighted(self, event: WorkspaceSidebar.Highlighted) -> None:
- """
- 响应左侧导航高亮变更并立即切换视图。
-
- :param event: 导航高亮事件
- """
- self._open_sidebar_item(event)
-
@on(SectionNavigator.Changed)
def on_section_changed(self, event: SectionNavigator.Changed) -> None:
"""
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/focus.py b/ruoyi-fastapi-backend/cli/tui/screens/focus.py
index a722418fa..f65b65165 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/focus.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/focus.py
@@ -1,7 +1,14 @@
from abc import ABC, abstractmethod
-from typing import Any
+from typing import TYPE_CHECKING, Any, cast
+from textual import on
from textual.containers import ScrollableContainer
+from textual.screen import Screen
+
+from cli.tui.widgets import NavigationItem, WorkspaceSidebar
+
+if TYPE_CHECKING:
+ from cli.tui.app import RuoyiTuiApp
class BaseScreenFocusService(ABC):
@@ -59,25 +66,58 @@ def get_scroll_target(self, screen: Any) -> Any:
return self.get_default_scroll_target(screen)
-class ScreenFocusActionsMixin:
+class WorkspaceScreen(Screen[None]):
"""
- TUI 屏幕焦点动作混入。
-
- 该混入负责将焦点服务暴露为屏幕上的左右移动与滚动 action,避免
- 各个 Screen 类重复编写同形转发方法。
+ 工作区屏幕的焦点与侧栏导航行为。
+ :ivar active_view: 当前视图标识
:ivar focus_service: TUI 屏幕焦点服务基类
"""
+ active_view: str
focus_service: BaseScreenFocusService
- def _move_focus(self, step: int) -> None:
+ @property
+ def workspace_app(self) -> 'RuoyiTuiApp':
"""
- 按给定方向移动当前焦点。
+ 获取挂载当前工作区屏幕的应用。
- :param step: 焦点移动步长
+ :return: 管理工作区导航的应用
+ """
+ return cast('RuoyiTuiApp', self.app)
+
+ def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSidebar.Selected) -> None:
+ """
+ 根据侧边栏事件打开对应视图,并避免重复打开当前页面。
+
+ :param event: 侧边栏高亮或选中事件
+ """
+ item = getattr(event.item, 'item', None)
+ if not isinstance(item, NavigationItem):
+ return
+ if not isinstance(event.control, WorkspaceSidebar) or not event.control.navigation_ready:
+ return
+ if item.view_key == self.active_view and self.workspace_app.requested_view == self.active_view:
+ return
+ self.workspace_app.open_view(item.view_key)
+
+ @on(WorkspaceSidebar.Selected)
+ def on_sidebar_selected(self, event: WorkspaceSidebar.Selected) -> None:
+ """
+ 响应左侧导航选中事件并切换视图。
+
+ :param event: 导航选中事件
+ """
+ self._open_sidebar_item(event)
+
+ @on(WorkspaceSidebar.Highlighted)
+ def on_sidebar_highlighted(self, event: WorkspaceSidebar.Highlighted) -> None:
+ """
+ 响应左侧导航高亮变更并立即切换视图。
+
+ :param event: 导航高亮事件
"""
- self.focus_service.move_focus(self, step)
+ self._open_sidebar_item(event)
def _get_scroll_target(self) -> Any:
"""
@@ -113,8 +153,8 @@ def action_scroll_focus_end(self) -> None:
def action_focus_left(self) -> None:
"""将焦点向左移动一列。"""
- self._move_focus(-1)
+ self.focus_service.move_focus(self, -1)
def action_focus_right(self) -> None:
"""将焦点向右移动一列。"""
- self._move_focus(1)
+ self.focus_service.move_focus(self, 1)
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/interactions.py b/ruoyi-fastapi-backend/cli/tui/screens/interactions.py
index f84bdca5a..ae6f22ff0 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/interactions.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/interactions.py
@@ -1,6 +1,6 @@
import asyncio
import inspect
-from collections.abc import Awaitable, Callable
+from collections.abc import Callable, Coroutine
from typing import Any
from cli.tui.actions import (
@@ -9,11 +9,11 @@
TuiActionResult,
TuiActionSpec,
)
+from cli.tui.capabilities import ActionSlot
from cli.tui.copy import TUI_COPY
from cli.tui.screens.confirm import ActionConfirmScreen
from cli.tui.screens.search import SearchInputScreen
from cli.tui.search import PageSearchContext
-from cli.tui.widgets import WorkspaceSidebar
class TuiScreenInteractionService:
@@ -106,7 +106,7 @@ def open_action_confirm(
def schedule_action_task(
existing_task: asyncio.Task[None] | None,
action: TuiActionSpec,
- execute_callback: Callable[[TuiActionSpec], Awaitable[None]],
+ execute_callback: Callable[[TuiActionSpec], Coroutine[Any, Any, None]],
) -> asyncio.Task[None]:
"""
安排动作执行任务,并在必要时取消旧任务。
@@ -125,7 +125,7 @@ def confirm_and_schedule_action(
screen: Any,
action: TuiActionSpec | None,
existing_task: asyncio.Task[None] | None,
- execute_callback: Callable[[TuiActionSpec], Awaitable[None]],
+ execute_callback: Callable[[TuiActionSpec], Coroutine[Any, Any, None]],
) -> asyncio.Task[None] | None:
"""
统一处理动作确认结果,并在确认后调度后台执行任务。
@@ -244,20 +244,13 @@ def _open_search(self) -> None:
def _clear_search(self) -> None:
"""清空当前页面搜索词。"""
- def _open_action_confirm(self, slot: str) -> None:
+ def _open_action_confirm(self, slot: ActionSlot) -> None:
"""
打开指定槽位动作的确认弹窗。
:param slot: 动作槽位
"""
- def _open_sidebar_item(self, event: WorkspaceSidebar.Highlighted | WorkspaceSidebar.Selected) -> None:
- """
- 根据侧栏事件打开对应视图。
-
- :param event: 侧栏事件
- """
-
def action_open_search(self) -> None:
"""打开当前页面搜索输入。"""
self._open_search()
diff --git a/ruoyi-fastapi-backend/cli/tui/screens/summary.py b/ruoyi-fastapi-backend/cli/tui/screens/summary.py
index 99a3e6fcd..1620aa910 100644
--- a/ruoyi-fastapi-backend/cli/tui/screens/summary.py
+++ b/ruoyi-fastapi-backend/cli/tui/screens/summary.py
@@ -9,11 +9,16 @@ class StatusCarrier(Protocol):
该协议用于描述首页面板、详情分区和浏览记录这类具备 ``status``
属性的摘要统计对象。
-
- :ivar status: 操作或记录所处的状态
"""
- status: str
+ @property
+ def status(self) -> str:
+ """
+ 获取面板、分区或记录的状态。
+
+ :return: 当前状态
+ """
+ ...
@dataclass(frozen=True)
diff --git a/ruoyi-fastapi-backend/cli/tui/search.py b/ruoyi-fastapi-backend/cli/tui/search.py
index 1c09a44d5..f07751175 100644
--- a/ruoyi-fastapi-backend/cli/tui/search.py
+++ b/ruoyi-fastapi-backend/cli/tui/search.py
@@ -1,5 +1,8 @@
from collections.abc import Callable
from dataclasses import dataclass, field
+from typing import TypeVar
+
+SectionT = TypeVar('SectionT')
@dataclass(frozen=True)
@@ -289,7 +292,7 @@ def resolve_search_suggestions(provider_spec: SearchSuggestionProviderSpec, quer
return [str(candidate).strip() for candidate in candidates if str(candidate).strip()]
@staticmethod
- def filter_detail_sections(sections: list[object], query: str) -> list[object]:
+ def filter_detail_sections(sections: list[SectionT], query: str) -> list[SectionT]:
"""
按搜索词过滤详情页分区列表。
@@ -300,7 +303,7 @@ def filter_detail_sections(sections: list[object], query: str) -> list[object]:
normalized_query = str(query or '').strip().lower()
if not normalized_query:
return sections
- filtered_sections: list[object] = []
+ filtered_sections: list[SectionT] = []
for section in sections:
title = str(getattr(section, 'title', '') or '').strip().lower()
lines = getattr(section, 'lines', [])
diff --git a/ruoyi-fastapi-backend/cli/wizard/base.py b/ruoyi-fastapi-backend/cli/wizard/base.py
index 3d39292d7..159f576bc 100644
--- a/ruoyi-fastapi-backend/cli/wizard/base.py
+++ b/ruoyi-fastapi-backend/cli/wizard/base.py
@@ -487,6 +487,14 @@ def handle_execution_result(self, ctx: CliContext, nested_result: Any, output: O
del ctx, nested_result, output
return False
+ def get_execution_result_support(self) -> WizardExecutionResultSupport:
+ """
+ 根据向导的失败提示构建结果处理器。
+
+ :return: 向导执行结果处理器
+ """
+ return WizardExecutionResultSupport(failure_message=self.failure_message)
+
def build_failure_payload(self, nested_result: Any) -> dict[str, Any]:
"""
为内部 CLI 非 JSON 结果构建失败负载。
@@ -686,14 +694,7 @@ class BaseCliWizardFlow(BaseNestedCommandWizardFlow[SelectionT], ABC):
nested_command_runner: ClassVar[Callable[..., Any]] = staticmethod(NESTED_CLI_SUPPORT.run)
nested_live_command_runner: ClassVar[Callable[..., Any]] = staticmethod(NESTED_CLI_SUPPORT.exec)
- def __init__(self) -> None:
- """
- 初始化当前项目向导基类。
-
- 该基类通过协作者缓存稳定持有交互、结果收口和内部 CLI 调用 support,
- 避免模板方法执行过程中重复构建同类对象。
- """
- self._support_cache: WizardSupportCache | None = None
+ _support_cache: WizardSupportCache | None = None
def get_support_cache(self) -> WizardSupportCache:
"""
@@ -703,8 +704,7 @@ def get_support_cache(self) -> WizardSupportCache:
:return: 协作者缓存
"""
- support_cache = getattr(self, '_support_cache', None)
- if support_cache is None:
+ if self._support_cache is None:
self._support_cache = WizardSupportCache(self)
return self._support_cache
diff --git a/ruoyi-fastapi-backend/cli/wizard/prompts.py b/ruoyi-fastapi-backend/cli/wizard/prompts.py
index 004ae76ff..acef2f2ab 100644
--- a/ruoyi-fastapi-backend/cli/wizard/prompts.py
+++ b/ruoyi-fastapi-backend/cli/wizard/prompts.py
@@ -21,7 +21,7 @@ def prompt_env(self, default_env: str = 'dev') -> str:
env_names = ENVIRONMENT_OPTION_SERVICE.discover_env_names()
prompt_message = f'运行环境(可选值: {", ".join(env_names)})'
while True:
- env_value = typer.prompt(prompt_message, default=default_env).strip()
+ env_value = str(typer.prompt(prompt_message, default=default_env)).strip()
if env_value in env_names:
return env_value
typer.echo(f'不支持的环境名称:{env_value},请重新输入。')
@@ -37,10 +37,7 @@ def prompt_choice(prompt_text: str, choices: list[str], default_value: str) -> s
:return: 用户选择的枚举值
"""
while True:
- value = typer.prompt(
- f'{prompt_text}(可选值: {", ".join(choices)})',
- default=default_value,
- ).strip()
+ value = str(typer.prompt(f'{prompt_text}(可选值: {", ".join(choices)})', default=default_value)).strip()
if value in choices:
return value
typer.echo(f'不支持的选项:{value},请重新输入。')
@@ -55,7 +52,7 @@ def prompt_required_text(prompt_text: str, default_value: str = '') -> str:
:return: 用户输入文本
"""
while True:
- value = typer.prompt(prompt_text, default=default_value).strip()
+ value = str(typer.prompt(prompt_text, default=default_value)).strip()
if value:
return value
typer.echo('该字段不能为空,请重新输入。')
@@ -69,7 +66,7 @@ def prompt_optional_text(prompt_text: str, default_value: str = '') -> str:
:param default_value: 默认值
:return: 用户输入文本
"""
- return typer.prompt(prompt_text, default=default_value).strip()
+ return str(typer.prompt(prompt_text, default=default_value)).strip()
@staticmethod
def prompt_confirm(prompt_text: str, default_value: bool = False) -> bool:
diff --git a/ruoyi-fastapi-backend/common/annotation/cache_annotation.py b/ruoyi-fastapi-backend/common/annotation/cache_annotation.py
index f42d197d2..dca914784 100644
--- a/ruoyi-fastapi-backend/common/annotation/cache_annotation.py
+++ b/ruoyi-fastapi-backend/common/annotation/cache_annotation.py
@@ -6,7 +6,7 @@
from fastapi import Request
from fastapi.encoders import jsonable_encoder
-from fastapi.responses import JSONResponse, ORJSONResponse, Response, StreamingResponse, UJSONResponse
+from fastapi.responses import JSONResponse, Response, StreamingResponse
from redis import asyncio as aioredis
from common.constant import HttpStatusConstant
@@ -153,7 +153,7 @@ def _extract_json_response_content(self, result: Any) -> Any | None:
if result is None or isinstance(result, StreamingResponse):
return None
- if isinstance(result, (JSONResponse, ORJSONResponse, UJSONResponse)):
+ if isinstance(result, JSONResponse):
return self._load_json_content(result.body.decode('utf-8'))
if isinstance(result, Response):
@@ -229,7 +229,7 @@ def __init__(
cache_response_codes if cache_response_codes is not None else {HttpStatusConstant.SUCCESS}
)
- def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]:
+ def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R | JSONResponse]]:
"""
为目标异步接口函数增加接口缓存能力。
@@ -238,7 +238,7 @@ def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]
"""
@wraps(func)
- async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | JSONResponse:
"""
读取匹配请求的接口缓存,并在缓存未命中时执行接口。
@@ -258,7 +258,7 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
cache_key = await self._build_cache_key(request, catalog_fingerprint=catalog_fingerprint)
cached_response = await redis.get(cache_key)
if cached_response and CatalogRegistry.fingerprint() == catalog_fingerprint:
- return self._build_cached_response(cached_response) # type: ignore[return-value]
+ return self._build_cached_response(cached_response)
result = await func(*args, **kwargs)
# 业务 await 期间可能发布新词库;不能把新版译文写入旧发布仍在使用的缓存键。
@@ -352,7 +352,7 @@ def _extract_response_payload(self, result: Any) -> dict[str, Any] | None:
if isinstance(result, StreamingResponse):
return None
- if isinstance(result, (JSONResponse, ORJSONResponse, UJSONResponse)):
+ if isinstance(result, JSONResponse):
# 命中缓存时无法安全复放后台任务,因此带有后台任务的响应不参与缓存
if getattr(result, 'background', None) is not None:
return None
@@ -382,7 +382,7 @@ def _extract_response_payload(self, result: Any) -> dict[str, Any] | None:
'headers': {},
}
- def _build_cached_response(self, cached_response: str) -> JSONResponse:
+ def _build_cached_response(self, cached_response: str | bytes) -> JSONResponse:
"""
根据缓存内容重建JSON响应对象。
diff --git a/ruoyi-fastapi-backend/common/annotation/log_annotation.py b/ruoyi-fastapi-backend/common/annotation/log_annotation.py
index fb465e25a..b2f4d9b36 100644
--- a/ruoyi-fastapi-backend/common/annotation/log_annotation.py
+++ b/ruoyi-fastapi-backend/common/annotation/log_annotation.py
@@ -6,14 +6,15 @@
from datetime import datetime
from enum import StrEnum
from functools import wraps
-from typing import Any, Literal, ParamSpec, TypeVar
+from typing import Any, Final, Literal, ParamSpec, TypeVar
import httpx
from async_lru import alru_cache
-from fastapi import Request
+from fastapi import Request, Response
from fastapi.exceptions import RequestValidationError
-from fastapi.responses import JSONResponse, ORJSONResponse, UJSONResponse
+from fastapi.responses import JSONResponse
from pydantic_validation_decorator import FieldValidationError
+from starlette.datastructures import UploadFile
from starlette.exceptions import HTTPException
from starlette.status import HTTP_200_OK
from user_agents import parse
@@ -179,7 +180,7 @@ def __init__(
:param response_exclude_fields: 响应日志排除字段路径,仅在response_log_mode='exclude'时生效;推荐从code/msg/data/rows/success/time开始,字段名支持 snake_case 与 camelCase 自动兼容
"""
self.title = title
- self.business_type = business_type.value
+ self.business_type: Final = business_type.value
self.log_type = log_type
self.request_log_mode = request_log_mode
self.response_log_mode = response_log_mode
@@ -193,7 +194,7 @@ def __init__(
self._validate_request_field_paths_strict()
self._warn_invalid_field_path_config()
- def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]:
+ def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R | Response]]:
"""
为接口添加操作日志或登录日志记录。
@@ -202,7 +203,7 @@ def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]
"""
@wraps(func)
- async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | Response:
"""
执行接口并根据日志策略记录请求、响应及耗时。
@@ -291,11 +292,10 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
if self.log_type == 'login':
# 登录请求来自于api文档时不记录登录日志,其余情况则记录
if not (request_from_swagger or request_from_redoc):
- user = kwargs.get('form_data')
login_log.update(
{
'loginTime': oper_time,
- 'userName': user.username,
+ 'userName': getattr(kwargs.get('form_data'), 'username', None),
'status': str(status),
'msg': sanitized_result_dict.get('msg') or '',
}
@@ -307,21 +307,21 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
dept_name = current_user.user.dept.dept_name if current_user.user.dept else None
operation_log = OperLogModel(
title=self.title,
- businessType=self.business_type,
+ business_type=self.business_type,
method=func_path,
- requestMethod=request_method,
- operatorType=operator_type,
- operName=current_user.user.user_name,
- deptName=dept_name,
- operUrl=oper_url,
- operIp=oper_ip,
- operLocation=oper_location,
- operParam=oper_param,
- jsonResult=json_result,
+ request_method=request_method,
+ operator_type=operator_type,
+ oper_name=current_user.user.user_name,
+ dept_name=dept_name,
+ oper_url=oper_url,
+ oper_ip=oper_ip,
+ oper_location=oper_location,
+ oper_param=oper_param,
+ json_result=json_result,
status=status,
- errorMsg=error_msg,
- operTime=oper_time,
- costTime=int(cost_time),
+ error_msg=error_msg,
+ oper_time=oper_time,
+ cost_time=int(cost_time),
)
await LogQueueService.enqueue_operation_log(request, operation_log, func_path)
@@ -346,7 +346,8 @@ def _get_decorator_func_path(self, func: Callable) -> str:
# 获取完整模块路径
module_path = module.__name__ if module else ''
# 获取当前被装饰函数所在路径
- func_path = f'{module_path}.{func.__name__}()'
+ func_name = getattr(func, '__name__', type(func).__name__)
+ func_path = f'{module_path}.{func_name}()'
return func_path
@@ -362,7 +363,7 @@ def _limit_log_text(log_text: str, max_length: int, overflow_text: str) -> str:
"""
return overflow_text if len(log_text) > max_length else log_text
- def _get_oper_type(self, user_agent: Any) -> int:
+ def _get_oper_type(self, user_agent: Any) -> Literal[0, 1, 2]:
"""
获取操作类型。
@@ -370,13 +371,11 @@ def _get_oper_type(self, user_agent: Any) -> int:
:return: 操作类型
"""
user_agent_text = user_agent or ''
- operator_type = 0
- if 'Windows' in user_agent_text or 'Macintosh' in user_agent_text or 'Linux' in user_agent_text:
- operator_type = 1
if 'Mobile' in user_agent_text or 'Android' in user_agent_text or 'iPhone' in user_agent_text:
- operator_type = 2
-
- return operator_type
+ return 2
+ if 'Windows' in user_agent_text or 'Macintosh' in user_agent_text or 'Linux' in user_agent_text:
+ return 1
+ return 0
async def _get_oper_location(self, oper_ip: str) -> str:
"""
@@ -460,7 +459,7 @@ async def _get_form_request_params(self, request: Request, content_type: str) ->
return params
# 过滤掉文件对象,只保留普通表单字段
- form_dict = {key: value for key, value in form_data.items() if not hasattr(value, 'filename')}
+ form_dict = {key: value for key, value in form_data.items() if not isinstance(value, UploadFile)}
if form_dict:
params['form_data'] = form_dict
@@ -470,7 +469,7 @@ async def _get_form_request_params(self, request: Request, content_type: str) ->
file_info = {}
for key, value in form_data.items():
- if hasattr(value, 'filename'):
+ if isinstance(value, UploadFile):
file_info[key] = {
'filename': value.filename,
'content_type': value.content_type,
@@ -1011,7 +1010,7 @@ def _set_login_data(self, login_log: dict, origin_kwargs: dict) -> None:
if 'form_data' in origin_kwargs:
origin_kwargs['form_data'].login_info = login_log
- def _get_status_and_error_msg(self, result_dict: dict) -> tuple[int, str]:
+ def _get_status_and_error_msg(self, result_dict: dict) -> tuple[Literal[0, 1], str | None]:
"""
获取操作状态和错误信息。
@@ -1023,7 +1022,8 @@ def _get_status_and_error_msg(self, result_dict: dict) -> tuple[int, str]:
if result_dict.get('code') == HTTP_200_OK:
status = 0
else:
- error_msg = self._get_result_message(result_dict)
+ message = self._get_result_message(result_dict)
+ error_msg = message if isinstance(message, str) else None
return status, error_msg
@@ -1044,14 +1044,8 @@ def _is_request_from_swagger_or_redoc(self, request: Request) -> tuple[bool, boo
:param request: Request对象
:return: 是否来自swagger请求和是否来自redoc请求元组
"""
- request_from_swagger = (
- request.headers.get('referer').endswith('docs') if request.headers.get('referer') else False
- )
- request_from_redoc = (
- request.headers.get('referer').endswith('redoc') if request.headers.get('referer') else False
- )
-
- return request_from_swagger, request_from_redoc
+ referer = request.headers.get('referer', '')
+ return referer.endswith('docs'), referer.endswith('redoc')
def _get_result_dict(self, result: Any, request_from_swagger: bool, request_from_redoc: bool) -> dict:
"""
@@ -1062,7 +1056,7 @@ def _get_result_dict(self, result: Any, request_from_swagger: bool, request_from
:param request_from_redoc: 是否来自redoc请求
:return: 操作结果字典
"""
- if isinstance(result, (JSONResponse, ORJSONResponse, UJSONResponse)):
+ if isinstance(result, JSONResponse):
result_dict = json.loads(str(result.body, 'utf-8'))
elif request_from_swagger or request_from_redoc:
result_dict = {}
diff --git a/ruoyi-fastapi-backend/common/annotation/pydantic_annotation.py b/ruoyi-fastapi-backend/common/annotation/pydantic_annotation.py
index 1d4c14014..34bc0eb38 100644
--- a/ruoyi-fastapi-backend/common/annotation/pydantic_annotation.py
+++ b/ruoyi-fastapi-backend/common/annotation/pydantic_annotation.py
@@ -1,104 +1,88 @@
import inspect
-from typing import TYPE_CHECKING, TypeVar
+import keyword
+from collections.abc import Callable
+from typing import Any, Generic, TypeVar
from fastapi import Form, Query
from pydantic import BaseModel
-
-if TYPE_CHECKING:
- from pydantic.fields import FieldInfo
+from pydantic.fields import FieldInfo
BaseModelVar = TypeVar('BaseModelVar', bound=BaseModel)
-def as_query(cls: type[BaseModelVar]) -> type[BaseModelVar]:
+class _ModelDependency(Generic[BaseModelVar]):
"""
- pydantic模型查询参数装饰器,将pydantic模型用于接收查询参数。
+ 向 FastAPI 暴露模型字段的参数签名,并用请求数据构建模型。
- :param cls: 将查询参数转换到的模型类
- :return: 将查询参数转换到的模型类
+ :ivar model: 用来校验请求数据的模型类
+ :ivar __signature__: FastAPI 解析查询或表单参数时使用的签名
"""
- new_parameters = []
- for model_field in cls.model_fields.values():
- model_field: FieldInfo
+ def __init__(self, model: type[BaseModelVar], parameter: Callable[..., FieldInfo]) -> None:
+ """
+ 按模型字段声明生成依赖签名,保留外部参数名及默认值。
- if not model_field.is_required():
- new_parameters.append(
- inspect.Parameter(
- model_field.alias,
- inspect.Parameter.POSITIONAL_ONLY,
- default=Query(default=model_field.default, description=model_field.description),
- annotation=model_field.annotation,
- )
- )
- else:
- new_parameters.append(
+ :param model: 接收请求数据的模型类
+ :param parameter: 创建查询或表单参数的 FastAPI 工厂
+ """
+ self.model = model
+ parameters = []
+ for name, field in model.model_fields.items():
+ alias = field.alias or name
+ argument = alias if alias.isidentifier() and not keyword.iskeyword(alias) else name
+ parameters.append(
inspect.Parameter(
- model_field.alias,
- inspect.Parameter.POSITIONAL_ONLY,
- default=Query(..., description=model_field.description),
- annotation=model_field.annotation,
+ argument,
+ inspect.Parameter.KEYWORD_ONLY,
+ default=parameter(
+ default=field.default,
+ default_factory=field.default_factory,
+ alias=alias,
+ description=field.description,
+ ),
+ annotation=field.annotation,
)
)
+ self.__signature__ = inspect.Signature(parameters, return_annotation=model)
- async def as_query_func(**data) -> type[BaseModelVar]:
+ async def __call__(self, **data: Any) -> BaseModelVar:
"""
- 用解析出的查询参数构建模型实例。
+ 用 FastAPI 提取的字段构建并校验模型实例。
- :param data: 调用方按名称传入的附加选项
- :return: 由查询参数创建的模型实例
+ :param data: 按字段名传入的查询参数或表单值
+ :return: 通过校验的模型实例
"""
- return cls(**data)
-
- sig = inspect.signature(as_query_func)
- sig = sig.replace(parameters=new_parameters)
- as_query_func.__signature__ = sig
- cls.as_query = as_query_func
- return cls
+ return self.model.model_validate(data, by_name=True)
-def as_form(cls: type[BaseModelVar]) -> type[BaseModelVar]:
+def as_query(cls: type[BaseModelVar]) -> type[BaseModelVar]:
"""
- pydantic模型表单参数装饰器,将pydantic模型用于接收表单参数。
+ 将模型的查询参数依赖注册为类属性。
- :param cls: 将表单字段转换到的模型类
- :return: 将表单字段转换到的模型类
+ :param cls: 接收查询参数的 Pydantic 模型类
+ :return: 已注册查询参数依赖的模型类
"""
- new_parameters = []
+ return _register_dependency(cls, 'as_query', Query)
- for model_field in cls.model_fields.values():
- model_field: FieldInfo
- if not model_field.is_required():
- new_parameters.append(
- inspect.Parameter(
- model_field.alias,
- inspect.Parameter.POSITIONAL_ONLY,
- default=Form(default=model_field.default, description=model_field.description),
- annotation=model_field.annotation,
- )
- )
- else:
- new_parameters.append(
- inspect.Parameter(
- model_field.alias,
- inspect.Parameter.POSITIONAL_ONLY,
- default=Form(..., description=model_field.description),
- annotation=model_field.annotation,
- )
- )
+def as_form(cls: type[BaseModelVar]) -> type[BaseModelVar]:
+ """
+ 将模型的表单参数依赖注册为类属性。
- async def as_form_func(**data) -> type[BaseModelVar]:
- """
- 用解析出的表单字段构建模型实例。
+ :param cls: 接收表单参数的 Pydantic 模型类
+ :return: 已注册表单参数依赖的模型类
+ """
+ return _register_dependency(cls, 'as_form', Form)
- :param data: 调用方按名称传入的附加选项
- :return: 由表单字段创建的模型实例
- """
- return cls(**data)
- sig = inspect.signature(as_form_func)
- sig = sig.replace(parameters=new_parameters)
- as_form_func.__signature__ = sig
- cls.as_form = as_form_func
+def _register_dependency(cls: type[BaseModelVar], name: str, parameter: Callable[..., FieldInfo]) -> type[BaseModelVar]:
+ """
+ 将可异步调用的参数依赖绑定到模型类。
+
+ :param cls: 接收请求数据的模型类
+ :param name: 依赖在模型类上的属性名
+ :param parameter: 创建 FastAPI 参数的工厂
+ :return: 已注册依赖的模型类
+ """
+ setattr(cls, name, _ModelDependency(cls, parameter))
return cls
diff --git a/ruoyi-fastapi-backend/common/annotation/rate_limit_annotation.py b/ruoyi-fastapi-backend/common/annotation/rate_limit_annotation.py
index 69d41bdc1..3be6163d4 100644
--- a/ruoyi-fastapi-backend/common/annotation/rate_limit_annotation.py
+++ b/ruoyi-fastapi-backend/common/annotation/rate_limit_annotation.py
@@ -8,7 +8,7 @@
from functools import wraps
from typing import Literal, ParamSpec, TypeVar
-from fastapi import Request
+from fastapi import Request, Response
from redis import asyncio as aioredis
from common.context import RequestContext
@@ -340,7 +340,7 @@ def __init__(
self.methods = ApiAnnotationUtil.normalize_http_methods(resolved_methods)
self.message = resolved_message
- def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]:
+ def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R | Response]]:
"""
为目标异步接口函数增加接口限流能力。
@@ -349,7 +349,7 @@ def __call__(self, func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]
"""
@wraps(func)
- async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | Response:
"""
校验请求的限流条件后执行被装饰的接口。
@@ -390,7 +390,7 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
headers = self._build_rate_limit_headers(rate_limit_result)
if not rate_limit_result['allowed']:
self._log_rate_limit_hit(request, rate_limit_result)
- return ResponseUtil.too_many_requests(msg=self.message, headers=headers) # type: ignore[return-value]
+ return ResponseUtil.too_many_requests(msg=self.message, headers=headers)
ApiResponseHeaderUtil.merge_headers(request, headers)
result = await func(*args, **kwargs)
@@ -617,8 +617,8 @@ def _get_route_path(self, request: Request) -> str:
:return: 路由模板路径
"""
route = request.scope.get('route')
- route_path = getattr(route, 'path', None)
- return route_path or request.url.path
+ route_path: object = getattr(route, 'path', None)
+ return route_path if isinstance(route_path, str) and route_path else request.url.path
def _get_scope_value(self, request: Request) -> str | None:
"""
diff --git a/ruoyi-fastapi-backend/common/aspect/data_scope.py b/ruoyi-fastapi-backend/common/aspect/data_scope.py
index 907a80829..843194268 100644
--- a/ruoyi-fastapi-backend/common/aspect/data_scope.py
+++ b/ruoyi-fastapi-backend/common/aspect/data_scope.py
@@ -1,8 +1,7 @@
-from fastapi import Depends, Request, params
+from fastapi import Request, params
from sqlalchemy import ColumnElement, false, func, or_, select, true
from common.context import RequestContext
-from config.database import Base
from module_admin.entity.do.dept_do import SysDept
from module_admin.entity.do.role_do import SysRoleDept
from utils.dependency_util import DependencyUtil
@@ -30,7 +29,7 @@ class GetDataScope:
def __init__(
self,
- query_alias: Base,
+ query_alias: type,
user_alias: str | None = 'user_id',
dept_alias: str | None = 'dept_id',
) -> None:
@@ -45,7 +44,7 @@ def __init__(
self.user_alias = user_alias
self.dept_alias = dept_alias
- def __call__(self, request: Request) -> ColumnElement:
+ def __call__(self, request: Request) -> ColumnElement[bool]:
"""
根据当前用户和角色构建数据范围查询条件。
@@ -53,67 +52,40 @@ def __call__(self, request: Request) -> ColumnElement:
:return: 限制当前用户可见数据的 SQL 条件
"""
DependencyUtil.check_exclude_routes(request, err_msg='当前路由不在认证规则内,不可使用GetDataScope依赖项')
- current_user = RequestContext.get_current_user()
- if current_user.user.admin:
+ user = RequestContext.get_current_user().user
+ if user is None:
+ return false()
+ if user.admin:
+ return true()
+ roles = [role for role in user.role or [] if role is not None and role.status == '0' and role.del_flag == '0']
+ scopes = {role.data_scope for role in roles}
+ if self.DATA_SCOPE_ALL in scopes:
return true()
- user_id = current_user.user.user_id
- dept_id = current_user.user.dept_id
- roles = [role for role in (current_user.user.role or []) if role.status == '0' and role.del_flag == '0']
- custom_data_scope_role_id_list = [item.role_id for item in roles if item.data_scope == self.DATA_SCOPE_CUSTOM]
- param_sql_list = []
- for role in roles:
- if role.data_scope == self.DATA_SCOPE_ALL:
- param_sql_list = [True]
- break
- if role.data_scope == self.DATA_SCOPE_CUSTOM:
- if len(custom_data_scope_role_id_list) > 1:
- param_sql_list.append(
- getattr(self.query_alias, self.dept_alias).in_(
- select(SysRoleDept.dept_id).where(SysRoleDept.role_id.in_(custom_data_scope_role_id_list))
- )
- if hasattr(self.query_alias, self.dept_alias)
- else False
- )
- else:
- param_sql_list.append(
- getattr(self.query_alias, self.dept_alias).in_(
- select(SysRoleDept.dept_id).where(SysRoleDept.role_id == role.role_id)
- )
- if hasattr(self.query_alias, self.dept_alias)
- else False
- )
- elif role.data_scope == self.DATA_SCOPE_DEPT:
- param_sql_list.append(
- getattr(self.query_alias, self.dept_alias) == dept_id
- if dept_id is not None and hasattr(self.query_alias, self.dept_alias)
- else False
- )
- elif role.data_scope == self.DATA_SCOPE_DEPT_AND_CHILD:
- param_sql_list.append(
- getattr(self.query_alias, self.dept_alias).in_(
- select(SysDept.dept_id).where(
- or_(SysDept.dept_id == dept_id, func.find_in_set(dept_id, SysDept.ancestors))
- )
- )
- if dept_id is not None and hasattr(self.query_alias, self.dept_alias)
- else False
- )
- elif role.data_scope == self.DATA_SCOPE_SELF:
- param_sql_list.append(
- getattr(self.query_alias, self.user_alias) == user_id
- if hasattr(self.query_alias, self.user_alias)
- else False
- )
- else:
- param_sql_list.append(False)
- param_sql_list = list(dict.fromkeys(param_sql_list))
- param_sql = or_(false(), *param_sql_list)
- return param_sql
+ conditions: list[ColumnElement[bool]] = []
+ dept_column = getattr(self.query_alias, self.dept_alias, None) if self.dept_alias else None
+ if dept_column is not None:
+ custom_role_ids = [
+ role.role_id for role in roles if role.data_scope == self.DATA_SCOPE_CUSTOM and role.role_id is not None
+ ]
+ if custom_role_ids:
+ departments = select(SysRoleDept.dept_id).where(SysRoleDept.role_id.in_(custom_role_ids))
+ conditions.append(dept_column.in_(departments))
+ if user.dept_id is not None and self.DATA_SCOPE_DEPT in scopes:
+ conditions.append(dept_column == user.dept_id)
+ if user.dept_id is not None and self.DATA_SCOPE_DEPT_AND_CHILD in scopes:
+ departments = select(SysDept.dept_id).where(
+ or_(SysDept.dept_id == user.dept_id, func.find_in_set(user.dept_id, SysDept.ancestors))
+ )
+ conditions.append(dept_column.in_(departments))
+ user_column = getattr(self.query_alias, self.user_alias, None) if self.user_alias else None
+ if user_column is not None and user.user_id is not None and self.DATA_SCOPE_SELF in scopes:
+ conditions.append(user_column == user.user_id)
+ return or_(false(), *conditions)
def DataScopeDependency( # noqa: N802
- query_alias: Base,
+ query_alias: type,
user_alias: str | None = 'user_id',
dept_alias: str | None = 'dept_id',
) -> params.Depends:
@@ -125,4 +97,4 @@ def DataScopeDependency( # noqa: N802
:param dept_alias: 部门id字段别名,默认为'dept_id'
:return: 当前用户数据权限依赖
"""
- return Depends(GetDataScope(query_alias, user_alias, dept_alias))
+ return params.Depends(GetDataScope(query_alias, user_alias, dept_alias))
diff --git a/ruoyi-fastapi-backend/common/aspect/db_session.py b/ruoyi-fastapi-backend/common/aspect/db_session.py
index 4b27b73fb..3b0eb3a08 100644
--- a/ruoyi-fastapi-backend/common/aspect/db_session.py
+++ b/ruoyi-fastapi-backend/common/aspect/db_session.py
@@ -1,7 +1,7 @@
from collections.abc import AsyncIterator
from functools import cache
-from fastapi import Depends, params
+from fastapi import params
from sqlalchemy.ext.asyncio import AsyncSession
from config.database import DataSourceRegistry
@@ -50,4 +50,4 @@ def DBSessionDependency(source_name: str | None = None) -> params.Depends: # no
:param source_name: 数据源名称,为空时使用默认数据源
:return: 数据库会话依赖
"""
- return Depends(get_db_session_provider(source_name))
+ return params.Depends(get_db_session_provider(source_name))
diff --git a/ruoyi-fastapi-backend/common/aspect/interface_auth.py b/ruoyi-fastapi-backend/common/aspect/interface_auth.py
index 1082e92ca..45b36504e 100644
--- a/ruoyi-fastapi-backend/common/aspect/interface_auth.py
+++ b/ruoyi-fastapi-backend/common/aspect/interface_auth.py
@@ -1,4 +1,4 @@
-from fastapi import Depends, Request, params
+from fastapi import Request, params
from common.context import RequestContext
from exceptions.exception import PermissionException
@@ -79,8 +79,7 @@ def __call__(self, request: Request) -> bool:
request, err_msg='当前路由不在认证规则内,不可使用CheckRoleInterfaceAuth依赖项'
)
current_user = RequestContext.get_current_user()
- user_role_list = current_user.user.role
- user_role_key_list = [role.role_key for role in user_role_list]
+ user_role_key_list = [role.role_key for role in current_user.user.role or [] if role is not None]
if isinstance(self.role_key, str) and self.role_key in user_role_key_list:
return True
if isinstance(self.role_key, list):
@@ -100,7 +99,7 @@ def UserInterfaceAuthDependency(perm: str | list, is_strict: bool = False) -> pa
:param is_strict: 当传入的权限标识是list类型时,是否开启严格模式,开启表示会校验列表中的每一个权限标识,所有的校验结果都需要为True才会通过
:return: 根据权限标识校验当前用户接口权限依赖
"""
- return Depends(CheckUserInterfaceAuth(perm, is_strict))
+ return params.Depends(CheckUserInterfaceAuth(perm, is_strict))
def RoleInterfaceAuthDependency(role_key: str | list, is_strict: bool = False) -> params.Depends: # noqa: N802
@@ -111,4 +110,4 @@ def RoleInterfaceAuthDependency(role_key: str | list, is_strict: bool = False) -
:param is_strict: 当传入的角色标识是list类型时,是否开启严格模式,开启表示会校验列表中的每一个角色标识,所有的校验结果都需要为True才会通过
:return: 根据角色校验当前用户接口权限依赖
"""
- return Depends(CheckRoleInterfaceAuth(role_key, is_strict))
+ return params.Depends(CheckRoleInterfaceAuth(role_key, is_strict))
diff --git a/ruoyi-fastapi-backend/common/aspect/pre_auth.py b/ruoyi-fastapi-backend/common/aspect/pre_auth.py
index 0f471dc3b..b457fd725 100644
--- a/ruoyi-fastapi-backend/common/aspect/pre_auth.py
+++ b/ruoyi-fastapi-backend/common/aspect/pre_auth.py
@@ -41,7 +41,7 @@ def PreAuthDependency(exclude_routes: list[ExcludeRoute] | None = None) -> param
methods为空列表表示所有方法
:return: 登录认证前置校验依赖
"""
- return Depends(PreAuth(exclude_routes))
+ return params.Depends(PreAuth(exclude_routes))
def CurrentUserDependency() -> params.Depends: # noqa: N802
@@ -50,4 +50,4 @@ def CurrentUserDependency() -> params.Depends: # noqa: N802
:return: 当前登录用户信息依赖
"""
- return Depends(LoginService.get_current_user)
+ return params.Depends(LoginService.get_current_user)
diff --git a/ruoyi-fastapi-backend/common/auth_policy.py b/ruoyi-fastapi-backend/common/auth_policy.py
index 925089f17..6bd36805c 100644
--- a/ruoyi-fastapi-backend/common/auth_policy.py
+++ b/ruoyi-fastapi-backend/common/auth_policy.py
@@ -1,15 +1,22 @@
import re
from collections.abc import Callable, Iterator
-from typing import Literal, TypedDict
+from typing import TYPE_CHECKING, Literal, TypedDict
from fastapi import Request
from fastapi.dependencies.models import Dependant
from fastapi.dependencies.utils import get_dependant
+from pydantic import TypeAdapter
+from common.enums import ExcludeRouteMethod
from utils.dependency_util import DependencyUtil
+if TYPE_CHECKING:
+ from common.context import CompiledExcludeRoute
+
+
+_exclude_route_method = TypeAdapter(ExcludeRouteMethod)
+
-# 定义排除路由的字典结构
class ExcludeRoute(TypedDict, total=False):
"""
排除路由的字典结构。
@@ -20,7 +27,7 @@ class ExcludeRoute(TypedDict, total=False):
"""
path: str
- methods: list[Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']]
+ methods: list[ExcludeRouteMethod]
ignore_paths: list[str]
@@ -42,7 +49,7 @@ def __init__(self, exclude_routes: list[ExcludeRoute] | None = None) -> None:
"""
self.exclude_routes = exclude_routes or []
# 编译排除路径为正则表达式模式,并存储方法信息
- self.exclude_patterns = []
+ self.exclude_patterns: list[CompiledExcludeRoute] = []
for route in self.exclude_routes:
# 使用TypedDict,确保路由字典包含path字段
@@ -55,7 +62,7 @@ def __init__(self, exclude_routes: list[ExcludeRoute] | None = None) -> None:
self.exclude_patterns.append(
{
'pattern': pattern,
- 'methods': [method.upper() for method in methods],
+ 'methods': [_exclude_route_method.validate_python(method.upper()) for method in methods],
'original_path': path,
'ignore_paths': ignore_paths,
}
@@ -138,7 +145,7 @@ def visit(dependency: Dependant, rule: AuthRule | None = None) -> Iterator[AuthR
:param rule: 当前正在检查的规则
:yield: 依赖树中匹配的认证规则
"""
- if dependency.call in overrides:
+ if dependency.call is not None and dependency.call in overrides:
# 按替换函数的实际声明判断,普通依赖覆盖不会使公开接口变为必需登录。
dependency = get_dependant(
path=dependency.path or '',
diff --git a/ruoyi-fastapi-backend/common/context.py b/ruoyi-fastapi-backend/common/context.py
index 755e532ea..0bdc81df0 100644
--- a/ruoyi-fastapi-backend/common/context.py
+++ b/ruoyi-fastapi-backend/common/context.py
@@ -1,8 +1,9 @@
import re
from contextvars import ContextVar, Token
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Literal
+from typing import TYPE_CHECKING, TypedDict
+from common.enums import ExcludeRouteMethod
from config.env import I18nConfig
from exceptions.exception import LoginException
@@ -21,11 +22,27 @@ class LocaleContext:
locale: str = I18nConfig.i18n_default_locale
+class CompiledExcludeRoute(TypedDict):
+ """
+ 编译后的认证排除规则。
+
+ :ivar pattern: 匹配请求路径的正则表达式
+ :ivar original_path: 原始路由路径
+ :ivar methods: 规则适用的 HTTP 方法,空列表表示全部方法
+ :ivar ignore_paths: 不适用该规则的路径
+ """
+
+ pattern: re.Pattern[str]
+ original_path: str
+ methods: list[ExcludeRouteMethod]
+ ignore_paths: list[str]
+
+
# 定义上下文变量
# 存储当前请求的编译后的排除路由模式列表
-current_exclude_patterns: ContextVar[
- list[dict[str, str | list[Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']] | re.Pattern]] | None
-] = ContextVar('current_exclude_patterns', default=None)
+current_exclude_patterns: ContextVar[list[CompiledExcludeRoute] | None] = ContextVar(
+ 'current_exclude_patterns', default=None
+)
# 存储当前用户信息
current_user: ContextVar['CurrentUserModel | None'] = ContextVar('current_user', default=None)
current_timezone: ContextVar[str | None] = ContextVar('current_timezone', default=None)
@@ -38,9 +55,7 @@ class RequestContext:
@staticmethod
def set_current_exclude_patterns(
- exclude_patterns: list[
- dict[str, str | list[Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']] | re.Pattern]
- ],
+ exclude_patterns: list[CompiledExcludeRoute],
) -> Token:
"""
设置当前请求的编译后的排除路由模式列表。
@@ -51,9 +66,7 @@ def set_current_exclude_patterns(
return current_exclude_patterns.set(exclude_patterns)
@staticmethod
- def get_current_exclude_patterns() -> list[
- dict[str, str | list[Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']] | re.Pattern]
- ]:
+ def get_current_exclude_patterns() -> list[CompiledExcludeRoute]:
"""
获取当前请求的编译后的排除路由模式列表。
diff --git a/ruoyi-fastapi-backend/common/enums.py b/ruoyi-fastapi-backend/common/enums.py
index 7a13194e4..b89694ff9 100644
--- a/ruoyi-fastapi-backend/common/enums.py
+++ b/ruoyi-fastapi-backend/common/enums.py
@@ -1,4 +1,7 @@
from enum import Enum, StrEnum
+from typing import Literal
+
+ExcludeRouteMethod = Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']
class HttpMethod(StrEnum):
diff --git a/ruoyi-fastapi-backend/common/mixin.py b/ruoyi-fastapi-backend/common/mixin.py
index 50abc8314..d47881326 100644
--- a/ruoyi-fastapi-backend/common/mixin.py
+++ b/ruoyi-fastapi-backend/common/mixin.py
@@ -1,9 +1,8 @@
from datetime import date, datetime
-from typing import Any, ClassVar
+from typing import TYPE_CHECKING, Any, ClassVar, cast
from pydantic import field_validator, model_validator
-from sqlalchemy import Column
-from sqlalchemy.orm import Mapped, declared_attr
+from sqlalchemy.orm import Mapped, declared_attr, mapped_column
from common.types import DbUtcDateTime
from utils.time_util import TimezoneUtil
@@ -11,7 +10,7 @@
class CreateTimeMixin:
"""
- 创建时间字段Mixin。
+ 创建时间字段混入类。
:cvar __create_time_nullable__: 创建时间列是否允许空值
:cvar __create_time_comment__: 创建时间列的数据库注释
@@ -21,23 +20,26 @@ class CreateTimeMixin:
__create_time_comment__ = '创建时间'
@declared_attr
- def create_time(cls) -> Mapped[datetime]: # noqa: N805
+ def create_time(cls) -> Mapped[datetime | None]: # noqa: N805
"""
声明记录创建时间的 ORM 字段。
- :return: ``Column`` 实例
+ :return: 创建时间的映射列
"""
- return Column(
- DbUtcDateTime(),
- nullable=cls.__create_time_nullable__,
- default=TimezoneUtil.utc_now,
- comment=cls.__create_time_comment__,
+ return cast(
+ 'Mapped[datetime | None]',
+ mapped_column(
+ DbUtcDateTime(),
+ nullable=cls.__create_time_nullable__,
+ default=TimezoneUtil.utc_now,
+ comment=cls.__create_time_comment__,
+ ),
)
class UpdateTimeMixin:
"""
- 更新时间字段Mixin。
+ 更新时间字段混入类。
:cvar __update_time_nullable__: 更新时间列是否允许空值
:cvar __update_time_insert_default__: 新增记录时是否填充默认更新时间
@@ -49,27 +51,39 @@ class UpdateTimeMixin:
__update_time_comment__ = '更新时间'
@declared_attr
- def update_time(cls) -> Mapped[datetime]: # noqa: N805
+ def update_time(cls) -> Mapped[datetime | None]: # noqa: N805
"""
声明记录更新时间的 ORM 字段。
- :return: ``Column`` 实例
+ :return: 更新时间的映射列
"""
- return Column(
- DbUtcDateTime(),
- nullable=cls.__update_time_nullable__,
- default=TimezoneUtil.utc_now if cls.__update_time_insert_default__ else None,
- onupdate=TimezoneUtil.utc_now,
- comment=cls.__update_time_comment__,
+ return cast(
+ 'Mapped[datetime | None]',
+ mapped_column(
+ DbUtcDateTime(),
+ nullable=cls.__update_time_nullable__,
+ default=TimezoneUtil.utc_now if cls.__update_time_insert_default__ else None,
+ onupdate=TimezoneUtil.utc_now,
+ comment=cls.__update_time_comment__,
+ ),
)
class AuditTimeMixin(CreateTimeMixin, UpdateTimeMixin):
- """创建时间和更新时间字段Mixin。"""
+ """创建和更新时间字段混入类。"""
class DateRangeQueryMixin:
- """业务日期范围查询校验混入类。"""
+ """
+ 业务时区日期范围查询混入类。
+
+ :ivar begin_time: 查询起始日期
+ :ivar end_time: 查询结束日期
+ """
+
+ if TYPE_CHECKING:
+ begin_time: str | None
+ end_time: str | None
@field_validator('begin_time', 'end_time', mode='before', check_fields=False)
@classmethod
@@ -101,7 +115,16 @@ def validate_date_range(self) -> 'DateRangeQueryMixin':
class InstantRangeQueryMixin:
- """RFC 3339时刻范围查询校验混入类。"""
+ """
+ RFC 3339 时刻范围查询混入类。
+
+ :ivar begin_time: 带时区的查询起始时刻
+ :ivar end_time: 带时区的查询结束时刻
+ """
+
+ if TYPE_CHECKING:
+ begin_time: str | None
+ end_time: str | None
@field_validator('begin_time', 'end_time', mode='before', check_fields=False)
@classmethod
@@ -132,7 +155,7 @@ def validate_instant_range(self) -> 'InstantRangeQueryMixin':
class GeneratedTimeRangeQueryMixin:
"""
- 代码生成器命名时间范围校验混入类。
+ 代码生成器命名时间范围查询混入类。
:cvar time_range_fields: 参与区间查询的字段及其时间语义
"""
diff --git a/ruoyi-fastapi-backend/common/vo.py b/ruoyi-fastapi-backend/common/vo.py
index c580b87bb..611effe02 100644
--- a/ruoyi-fastapi-backend/common/vo.py
+++ b/ruoyi-fastapi-backend/common/vo.py
@@ -1,3 +1,4 @@
+from functools import cache
from typing import Any, Generic, Self, TypeVar
from pydantic import BaseModel, ConfigDict, Field, create_model, model_validator
@@ -11,6 +12,12 @@
T = TypeVar('T')
+class CamelModel(BaseModel):
+ """支持蛇形字段名和驼峰别名输入的 API 模型。"""
+
+ model_config = ConfigDict(alias_generator=to_camel, validate_by_name=True, validate_by_alias=True)
+
+
class CrudResponseModel(BaseModel):
"""操作响应模型。"""
@@ -42,16 +49,16 @@ def preserve_message_metadata(self) -> Self:
return self
-class ResponseBaseModel(BaseModel):
+class ResponseBaseModel(CamelModel):
"""响应模型。"""
code: int = Field(default=HttpStatusConstant.SUCCESS, description='响应码')
msg: str = Field(default='操作成功', description='响应信息')
- msg_key: str | None = Field(default=None, alias='msgKey', description='国际化消息标识')
- msg_params: dict | None = Field(default=None, alias='msgParams', description='国际化消息插值参数')
- msg_domain: str | None = Field(default=None, alias='msgDomain', description='国际化插件词库域')
- msg_count: int | None = Field(default=None, alias='msgCount', description='复数消息数量')
- msg_plural_key: str | None = Field(default=None, alias='msgPluralKey', description='复数消息标识')
+ msg_key: str | None = Field(default=None, description='国际化消息标识')
+ msg_params: dict | None = Field(default=None, description='国际化消息插值参数')
+ msg_domain: str | None = Field(default=None, description='国际化插件词库域')
+ msg_count: int | None = Field(default=None, description='复数消息数量')
+ msg_plural_key: str | None = Field(default=None, description='复数消息标识')
success: bool = Field(default=True, description='响应是否成功')
time: ApiUtcDateTime = Field(default_factory=TimezoneUtil.utc_now, description='响应时间')
@@ -59,56 +66,32 @@ class ResponseBaseModel(BaseModel):
class DynamicResponseModel(ResponseBaseModel, Generic[T]):
"""动态响应模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
- def __class_getitem__(cls, item: Any) -> Any | Self:
+ @classmethod
+ @cache
+ def __class_getitem__(cls, typevar_values: object) -> type[BaseModel]:
"""
- 当使用 DynamicResponseModel[Item] 语法时,动态创建一个包含所有字段的新模型。
+ 将业务模型的字段合并到响应模型,并复用同一模型生成的结果。
- :param item: 当前要处理的条目
- :return: 绑定给定数据类型的响应模型
- :raises TypeError: 泛型参数不是 Pydantic 模型
+ :param typevar_values: 提供业务字段的 Pydantic 模型类
+ :return: 继承响应字段和序列化配置的模型类
+ :raises TypeError: 泛型参数不是 Pydantic 模型类
"""
- # 检查是否已经为该类型创建了模型
- if not hasattr(cls, '_cached_models'):
- cls._cached_models = {}
-
- if item in cls._cached_models:
- return cls._cached_models[item]
-
- # 检查item是否为Pydantic模型
- if not hasattr(item, 'model_fields'):
- raise TypeError(f'{item} 不是一个Pydantic模型,请使用Pydantic模型作为泛型参数')
-
- # 获取ResponseBaseModel的字段
- base_fields = {}
- for field_name, field in cls.model_fields.items():
- base_fields[field_name] = (field.annotation, field)
-
- # 获取泛型类型的字段
- item_fields = {}
- for field_name, field in item.model_fields.items():
- item_fields[field_name] = (field.annotation, field)
-
- # 合并所有字段
- all_fields = {**base_fields, **item_fields}
-
- # 动态创建新模型
- new_model = create_model(
- f'DynamicResponseModel[{item.__name__}]', __base__=cls, __config__=cls.model_config, **all_fields
+ if not isinstance(typevar_values, type) or not issubclass(typevar_values, BaseModel):
+ raise TypeError(f'{typevar_values} 不是一个Pydantic模型,请使用Pydantic模型作为泛型参数')
+ fields: dict[str, Any] = {
+ name: (field.annotation, field) for name, field in typevar_values.model_fields.items()
+ }
+ return create_model(
+ f'DynamicResponseModel[{typevar_values.__name__}]',
+ __base__=cls,
+ __module__=__name__,
+ **fields,
)
- # 缓存模型
- cls._cached_models[item] = new_model
- return new_model
-
-
-class PageModel(BaseModel, Generic[T]):
+class PageModel(CamelModel, Generic[T]):
"""分页模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
rows: list[T] = Field(description='记录列表')
page_num: int = Field(description='当前页码')
page_size: int = Field(description='每页记录数')
diff --git a/ruoyi-fastapi-backend/config/database.py b/ruoyi-fastapi-backend/config/database.py
index cca47e400..7b1dfd0f8 100644
--- a/ruoyi-fastapi-backend/config/database.py
+++ b/ruoyi-fastapi-backend/config/database.py
@@ -10,7 +10,7 @@
import anyio
import anyio.lowlevel
from pydantic import SecretStr
-from sqlalchemy import URL, Engine, create_engine, event, inspect, text
+from sqlalchemy import URL, CursorResult, Delete, Engine, Table, Update, create_engine, event, inspect, text
from sqlalchemy.exc import DBAPIError
from sqlalchemy.ext.asyncio import (
AsyncAttrs,
@@ -93,6 +93,8 @@ def _error_details(exc: BaseException) -> tuple[str, int | None]:
if isinstance(exc, DataSourceException):
return exc.error_type or type(exc).__name__, exc.error_code
original = exc.orig if isinstance(exc, DBAPIError) else exc
+ if original is None:
+ return type(exc).__name__, None
error_code = original.args[0] if original.args and isinstance(original.args[0], int) else None
return type(original).__name__, error_code
@@ -408,17 +410,59 @@ def _where_user_ids(cls, clause: Any, table_name: str, parameters: Any) -> set[i
):
return None
parameter_sets = parameters if isinstance(parameters, (list, tuple)) else [parameters or {}]
- user_ids = set()
+ user_ids: set[int] = set()
for item in parameter_sets:
if not isinstance(item, Mapping):
return None
raw = item.get(value.key, value.value)
values = raw if clause.operator is operators.in_op and isinstance(raw, (list, tuple, set)) else [raw]
- if not all(isinstance(user_id, int) and not isinstance(user_id, bool) for user_id in values):
- return None
- user_ids.update(values)
+ for user_id in values:
+ if not isinstance(user_id, int) or isinstance(user_id, bool):
+ return None
+ user_ids.add(user_id)
return user_ids
+ @classmethod
+ def _dml_user_ids(cls, state: ORMExecuteState, statement: UpdateBase, table_name: str) -> set[int] | None:
+ """
+ 从写入条件或 ORM 批量更新的主键提取需要失效的用户。
+
+ :param state: 当前 SQL 执行状态
+ :param statement: 直接写入用户数据表的语句
+ :param table_name: 写入目标的表名
+ :return: 受影响的用户 ID,主键被改写或无法确定范围时返回 ``None``
+ """
+ parameters = state.parameters
+ if state.is_update:
+ assigned = list(getattr(statement, '_values', None) or {})
+ assigned.extend(column for column, _value in getattr(statement, '_ordered_values', None) or ())
+ if any(getattr(column, 'key', column) == 'user_id' for column in assigned):
+ return None
+ if (
+ state.is_orm_statement
+ and isinstance(parameters, list)
+ and state.execution_options.get('dml_strategy') in (None, 'auto', 'bulk')
+ ):
+ try:
+ entity = statement.entity_description.get('entity')
+ except (AttributeError, KeyError):
+ entity = None
+ if entity is not None:
+ # ORM 会为每组参数自动附加主键条件。
+ ids: set[int] = set()
+ for row in parameters:
+ user_id = row.get('user_id')
+ if not isinstance(user_id, int) or isinstance(user_id, bool):
+ return None
+ ids.add(user_id)
+ return ids
+ rows = parameters if isinstance(parameters, (list, tuple)) else [parameters]
+ if 'user_id' in statement.compile().params or any(
+ isinstance(row, Mapping) and 'user_id' in row for row in rows
+ ):
+ return None
+ return cls._where_user_ids(getattr(statement, 'whereclause', None), table_name, parameters)
+
async def _invalidate_cache(self, user_ids: set[int] | None) -> None:
"""
提交完成后轮换缓存版本,Redis异常由短时硬过期兜底。
@@ -462,12 +506,13 @@ def _track_current_user_statement(state: ORMExecuteState) -> Any:
:return: 原语句执行结果
"""
result = state.invoke_statement()
- if not AppConfig.app_current_user_cache_enabled:
+ session = state.session
+ if not AppConfig.app_current_user_cache_enabled or not isinstance(session, CurrentUserCacheSession):
return result
try:
statement = state.statement
if CurrentUserCacheSession._has_unscoped_write(statement):
- state.session._record_cache_change(None)
+ session._record_cache_change(None)
elif state.is_insert or state.is_update or state.is_delete:
target = getattr(statement, 'table', None)
table_names = CurrentUserCacheSession._table_names(target)
@@ -476,51 +521,14 @@ def _track_current_user_statement(state: ORMExecuteState) -> Any:
isinstance(target, (Alias, Join)) and table_names & CurrentUserCacheSession._USER_TABLES
):
# 别名及多表写入的WHERE可能引用其他表,不能据此缩小目标用户范围。
- state.session._record_cache_change(None)
+ session._record_cache_change(None)
elif table_name in CurrentUserCacheSession._USER_TABLES:
- ids = CurrentUserCacheSession._where_user_ids(
- getattr(statement, 'whereclause', None), table_name, state.parameters
- )
- bulk_entity = None
- if (
- state.is_update
- and state.is_orm_statement
- and isinstance(state.parameters, list)
- and state.execution_options.get('dml_strategy') in (None, 'auto', 'bulk')
- ):
- try:
- bulk_entity = statement.entity_description.get('entity')
- except (AttributeError, KeyError):
- pass
- assigned_columns = list(getattr(statement, '_values', None) or {})
- assigned_columns.extend(column for column, _value in getattr(statement, '_ordered_values', None) or ())
- if state.is_update and any(getattr(column, 'key', column) == 'user_id' for column in assigned_columns):
- # 用户归属变更需覆盖新旧用户,自定义绑定及表达式不能只按参数名判断。
- ids = None
- elif bulk_entity is not None:
- # ORM批量更新会自动附加主键条件,用户资料和登录时间更新走此路径。
- values = [item.get('user_id') for item in state.parameters]
- ids = (
- set(values)
- if all(isinstance(value, int) and not isinstance(value, bool) for value in values)
- else None
- )
- elif state.is_update and (
- 'user_id' in statement.compile().params
- or any(
- isinstance(parameters, Mapping) and 'user_id' in parameters
- for parameters in (
- state.parameters if isinstance(state.parameters, (list, tuple)) else [state.parameters]
- )
- )
- ):
- # 修改主键或未知用户范围时不能只失效原用户。
- ids = None
- state.session._record_cache_change(ids)
+ ids = session._dml_user_ids(state, statement, table_name) if isinstance(statement, UpdateBase) else None
+ session._record_cache_change(ids)
except Exception as exc:
# SQL已执行成功,范围分析失败不能改变业务结果。
logger.warning(f'当前用户缓存变更范围分析失败,将失效全部快照:{type(exc).__name__}')
- state.session._record_cache_change(None)
+ session._record_cache_change(None)
return result
@@ -561,7 +569,7 @@ def _invalidate_current_user_cache(session: CurrentUserCacheSession) -> None:
try:
transaction = session.get_nested_transaction() or session.get_transaction()
changes = session.info.get(session._CHANGE_KEY, {})
- if transaction not in changes:
+ if transaction is None or transaction not in changes:
return
user_ids = changes.pop(transaction)
if transaction.nested:
@@ -595,6 +603,21 @@ def _discard_current_user_changes(session: CurrentUserCacheSession, transaction:
session.info.pop(session._CHANGE_KEY, None)
+async def execute_rowcount(db: AsyncSession, statement: Update | Delete) -> int:
+ """
+ 在当前 ORM 会话中执行更新或删除,返回驱动报告的匹配行数。
+
+ :param db: 执行语句的数据库会话
+ :param statement: 无需返回数据行的更新或删除语句
+ :return: 驱动报告的匹配行数,驱动无法确定时为 -1
+ :raises TypeError: 执行结果未提供游标行数
+ """
+ result = await db.execute(statement)
+ if not isinstance(result, CursorResult):
+ raise TypeError('更新或删除语句未返回游标结果')
+ return result.rowcount
+
+
def create_async_session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
"""
创建异步Session工厂。
@@ -776,34 +799,28 @@ async def initialize(self, log_enabled: bool = True) -> None:
for name, result in zip(names, results, strict=True):
config = self._configs[name]
required = config.db_required or name == default_name
- healthy = not isinstance(result, BaseException)
- error_type = None
- error_code = None
- if not healthy:
- error_type, error_code = _error_details(result)
+ if not isinstance(result, BaseException):
+ if log_enabled:
+ timezone = self._runtime(name).session_timezone
+ logger.bind(
+ data_source=name, database_type=config.db_type, required=required, session_timezone=timezone
+ ).info(f'✅ 数据源 {name} 初始化成功,sessionTimeZone={timezone}')
+ continue
if log_enabled:
- log_context: dict[str, Any] = {
- 'data_source': name,
- 'database_type': config.db_type,
- 'required': required,
- }
- if error_type is not None:
- log_context['error_type'] = error_type
- log_context['error_code'] = error_code
- elif healthy:
- log_context['session_timezone'] = self._runtime(name).session_timezone
- source_logger = logger.bind(**log_context)
- if healthy:
- source_logger.info(
- f'✅ 数据源 {name} 初始化成功,sessionTimeZone={self._runtime(name).session_timezone}'
- )
- elif required:
- source_logger.error(f'❌ 必需数据源 {name} 连接检查失败{_error_log_suffix(error_type, error_code)}')
+ error_type, error_code = _error_details(result)
+ source_logger = logger.bind(
+ data_source=name,
+ database_type=config.db_type,
+ required=required,
+ error_type=error_type,
+ error_code=error_code,
+ )
+ suffix = _error_log_suffix(error_type, error_code)
+ if required:
+ source_logger.error(f'❌ 必需数据源 {name} 连接检查失败{suffix}')
else:
- source_logger.warning(
- f'⚠️ 非必需数据源 {name} 连接检查失败,应用将降级启动{_error_log_suffix(error_type, error_code)}'
- )
- if not healthy and required and required_failure is None:
+ source_logger.warning(f'⚠️ 非必需数据源 {name} 连接检查失败,应用将降级启动{suffix}')
+ if required and required_failure is None:
required_failure = (name, result)
if required_failure is not None:
name, result = required_failure
@@ -993,6 +1010,19 @@ async def dispose_all(self) -> None:
class Base(AsyncAttrs, DeclarativeBase):
"""默认数据源的 SQLAlchemy 声明式模型基类。"""
+ @classmethod
+ def get_table(cls) -> Table:
+ """
+ 获取建表、索引和约束操作使用的映射表。
+
+ :return: 当前 ORM 模型实际绑定的表
+ :raises TypeError: 模型映射到联接或子查询
+ """
+ table = cls.__table__
+ if not isinstance(table, Table):
+ raise TypeError(f'{cls.__name__} 未映射到数据库表')
+ return table
+
@cache
def get_data_source_base(source_name: str) -> type[DeclarativeBase]:
diff --git a/ruoyi-fastapi-backend/config/env.py b/ruoyi-fastapi-backend/config/env.py
index ba9e5173f..dc032908c 100644
--- a/ruoyi-fastapi-backend/config/env.py
+++ b/ruoyi-fastapi-backend/config/env.py
@@ -836,7 +836,7 @@ def parse_cli_args() -> str:
parser.add_argument('--env', type=str, default='', help='运行环境')
# 解析命令行参数
args, _ = parser.parse_known_args()
- run_env = args.env or run_env
+ run_env = str(args.env or run_env)
# 运行环境未指定时默认加载.env.dev
run_env = run_env.strip() or 'dev'
env_file = f'.env.{run_env}'
diff --git a/ruoyi-fastapi-backend/config/get_redis.py b/ruoyi-fastapi-backend/config/get_redis.py
index 5c94cd84a..337c1a7e7 100644
--- a/ruoyi-fastapi-backend/config/get_redis.py
+++ b/ruoyi-fastapi-backend/config/get_redis.py
@@ -22,7 +22,7 @@ async def create_redis_pool(cls, log_enabled: bool = True, log_start_enabled: bo
:param log_start_enabled: 是否输出开始连接日志
:return: Redis连接对象
"""
- redis = await aioredis.from_url(
+ redis = aioredis.Redis.from_url(
url=f'redis://{RedisConfig.redis_host}',
port=RedisConfig.redis_port,
username=RedisConfig.redis_username,
@@ -31,6 +31,7 @@ async def create_redis_pool(cls, log_enabled: bool = True, log_start_enabled: bo
encoding='utf-8',
decode_responses=True,
)
+ await redis.initialize()
if log_start_enabled is None:
log_start_enabled = log_enabled
if log_enabled or log_start_enabled:
@@ -87,7 +88,7 @@ async def close_redis_pool(cls, app: FastAPI) -> None:
logger.debug('✅️ 关闭redis连接成功')
@classmethod
- async def init_sys_dict(cls, redis: FastAPI) -> None:
+ async def init_sys_dict(cls, redis: aioredis.Redis) -> None:
"""
应用启动时缓存字典表。
diff --git a/ruoyi-fastapi-backend/config/scheduler/dispatcher.py b/ruoyi-fastapi-backend/config/scheduler/dispatcher.py
index a85c348b8..84238ce2c 100644
--- a/ruoyi-fastapi-backend/config/scheduler/dispatcher.py
+++ b/ruoyi-fastapi-backend/config/scheduler/dispatcher.py
@@ -74,6 +74,7 @@ async def dispatch_pending(self, *, is_leader: Callable[[], bool]) -> None:
分批领取待执行请求,派发只在领取事务提交后进行。
:param is_leader: 检查当前进程是否仍持有Leader租约
+ :raises ValueError: 已领取的执行请求缺少派发凭据
"""
if not is_leader() or self.lock.locked():
return
@@ -90,8 +91,10 @@ async def dispatch_pending(self, *, is_leader: Callable[[], bool]) -> None:
execution = await JobRuntimeDao.claim_request(session, execution_id, job_id)
snapshot = execution.job_snapshot if execution is not None else None
token = execution.owner_token if execution is not None else None
+ if execution is not None and token is None:
+ raise ValueError('已领取的执行请求缺少派发凭据')
await session.commit()
- if execution is None:
+ if token is None:
continue
if not is_leader():
# 尚未开始的领取租约过期后由新 Leader 重新派发。
diff --git a/ruoyi-fastapi-backend/config/scheduler/events.py b/ruoyi-fastapi-backend/config/scheduler/events.py
index 34cbded22..963abdfa5 100644
--- a/ruoyi-fastapi-backend/config/scheduler/events.py
+++ b/ruoyi-fastapi-backend/config/scheduler/events.py
@@ -32,7 +32,7 @@ class JobSnapshot:
"""
name: str
- jobstore: str
+ jobstore: str | None
executor: str
invoke_target: str
args: str
@@ -70,6 +70,17 @@ def from_job(cls, job: Job, *, managed: bool = False) -> 'JobSnapshot':
managed=managed and (job.id.isdecimal() or job.id.startswith('_manual:')),
)
+ def require_job_id(self) -> int:
+ """
+ 读取持久化执行所需的任务 ID。
+
+ :return: 关联的数据库任务 ID
+ :raises ValueError: 调度任务缺少数据库任务 ID
+ """
+ if self.job_id is None:
+ raise ValueError('调度任务缺少数据库任务 ID')
+ return self.job_id
+
def execution_snapshot(self) -> dict[str, Any]:
"""
生成跨进程执行记录需要的可序列化配置快照。
diff --git a/ruoyi-fastapi-backend/config/scheduler/executors.py b/ruoyi-fastapi-backend/config/scheduler/executors.py
index eeef4cbf6..76c7eee37 100644
--- a/ruoyi-fastapi-backend/config/scheduler/executors.py
+++ b/ruoyi-fastapi-backend/config/scheduler/executors.py
@@ -3,7 +3,7 @@
import sys
import time
import traceback
-from collections.abc import Callable, Iterator
+from collections.abc import Callable, Generator
from concurrent.futures import Future
from concurrent.futures.process import BrokenProcessPool
from contextlib import contextmanager
@@ -46,7 +46,7 @@ def _execution(
logger_name: str,
*,
event: TimedJobExecutionEvent | None = None,
-) -> Iterator[TimedJobExecutionEvent]:
+) -> Generator[TimedJobExecutionEvent, None, None]:
"""
在实际调用边界记录任务起止时刻和单调耗时。
@@ -97,7 +97,7 @@ def _claim_execution(event: TimedJobExecutionEvent) -> str | None:
try:
claim = JobExecutionStore.claim(
event.execution_id,
- snapshot.job_id,
+ snapshot.require_job_id(),
snapshot.execution_snapshot(),
event.scheduled_run_time,
dispatch_token=snapshot.dispatch_token,
@@ -123,6 +123,8 @@ def _finish_execution(event: TimedJobExecutionEvent, token: str) -> None:
:param token: 当前执行占用凭据
"""
try:
+ if event.start_time is None or event.end_time is None or event.run_duration_ms is None:
+ raise ValueError('任务执行计时信息不完整')
JobExecutionStore.finish(
event.execution_id,
token,
@@ -147,7 +149,7 @@ def _record_unstarted_execution(event: TimedJobExecutionEvent) -> None:
try:
JobExecutionStore.record_unstarted(
event.execution_id,
- event.snapshot.job_id,
+ event.snapshot.require_job_id(),
event.snapshot.execution_snapshot(),
event.scheduled_run_time,
'missed' if event.code == EVENT_JOB_MISSED else 'rejected',
diff --git a/ruoyi-fastapi-backend/config/scheduler/job_adapter.py b/ruoyi-fastapi-backend/config/scheduler/job_adapter.py
index 2cf060366..75b66ac02 100644
--- a/ruoyi-fastapi-backend/config/scheduler/job_adapter.py
+++ b/ruoyi-fastapi-backend/config/scheduler/job_adapter.py
@@ -3,7 +3,7 @@
import json
import pickle
from collections.abc import Callable
-from typing import Any
+from typing import Any, cast
from apscheduler.job import Job
from apscheduler.util import iscoroutinefunction_partial, obj_to_ref
@@ -50,7 +50,7 @@ def from_record(record: Any) -> JobModel:
:return: 任务对象信息
"""
if isinstance(record, JobModel):
- return record
+ return cast('JobModel', record)
return JobModel.model_construct(
**{name: getattr(record, name) for name in JobModel.model_fields if hasattr(record, name)}
)
@@ -168,6 +168,8 @@ def prepare(cls, job: JobModel, *, function: Callable[..., Any] | None = None) -
# 禁止非有限数值进入JSON列,避免数据库与执行器对同一参数产生不同解释。
json.dumps([job.job_args, kwargs], allow_nan=False)
executor = 'default' if iscoroutinefunction_partial(function) else job.job_executor
+ if job.cron_expression is None:
+ raise ValueError('Cron 表达式不能为空')
trigger = MyCronTrigger.from_crontab(job.cron_expression, job.time_zone)
trigger.task_job_group = job.job_group
options = {
diff --git a/ruoyi-fastapi-backend/config/scheduler/job_execution.py b/ruoyi-fastapi-backend/config/scheduler/job_execution.py
index a12ff55c4..f8626e933 100644
--- a/ruoyi-fastapi-backend/config/scheduler/job_execution.py
+++ b/ruoyi-fastapi-backend/config/scheduler/job_execution.py
@@ -81,7 +81,7 @@ def claim(
"""
with cls.session() as db, db.begin():
# 无值变更的 UPDATE 同时适用于 MySQL、PostgreSQL 和 SQLite 的写锁。
- locked = db.execute(
+ locked = db.connection().execute(
update(SysJobSync)
.where(SysJobSync.job_id == job_id)
.values(
@@ -112,14 +112,14 @@ def claim(
message = '任务已删除或已停用,取消尚未开始的定时执行' if dispatch_token is None else '任务已删除'
cls._stop(execution, 'cancelled', message)
return ExecutionClaim(False, status='cancelled', message=message)
- active = db.scalar(
+ active = db.execute(
select(func.count())
.select_from(SysJobExecution)
.where(
SysJobExecution.job_id == job_id,
SysJobExecution.status.in_(['running', 'unknown']),
)
- )
+ ).scalar_one()
limit = job.max_instances
if active >= limit:
message = f'达到任务并发上限 {limit},本次未执行'
@@ -129,8 +129,9 @@ def claim(
execution.status = 'running'
execution.owner_token = token
execution.scheduled_time = scheduled_time
- execution.start_time = TimezoneUtil.utc_now()
- execution.lease_until = execution.start_time + timedelta(seconds=cls.LEASE_SECONDS)
+ start_time = TimezoneUtil.utc_now()
+ execution.start_time = start_time
+ execution.lease_until = start_time + timedelta(seconds=cls.LEASE_SECONDS)
execution.message = None
return ExecutionClaim(True, token=token, status='running')
@@ -159,7 +160,7 @@ def renew(cls, execution_id: str, token: str) -> bool:
:return: 是否续租成功
"""
with cls.session() as db, db.begin():
- result = db.execute(
+ result = db.connection().execute(
update(SysJobExecution)
.where(
SysJobExecution.execution_id == execution_id,
@@ -229,7 +230,7 @@ def _retryable_finish_error(error: DBAPIError) -> bool:
:param error: SQLAlchemy 包装的数据库异常
:return: 是否可以重试终态更新事务
"""
- if error.connection_invalidated:
+ if error.connection_invalidated or error.orig is None:
return False
original = error.orig
sqlstate = getattr(original, 'sqlstate', None) or getattr(original, 'pgcode', None)
@@ -259,7 +260,7 @@ def record_unstarted(
:param dispatch_token: 本次派发的领取凭据
"""
with cls.session() as db, db.begin():
- locked = db.execute(
+ locked = db.connection().execute(
update(SysJobSync)
.where(SysJobSync.job_id == job_id)
.values(
diff --git a/ruoyi-fastapi-backend/config/scheduler/jobs.py b/ruoyi-fastapi-backend/config/scheduler/jobs.py
index 689a858ca..3d60ea974 100644
--- a/ruoyi-fastapi-backend/config/scheduler/jobs.py
+++ b/ruoyi-fastapi-backend/config/scheduler/jobs.py
@@ -1,7 +1,7 @@
import json
from collections.abc import Callable
from datetime import UTC, datetime
-from typing import Any
+from typing import Any, cast
from apscheduler.job import Job
from apscheduler.schedulers.asyncio import AsyncIOScheduler
@@ -70,7 +70,10 @@ def prepare_job(cls, job_info: JobModel) -> dict[str, Any]:
:param job_info: 任务对象信息
:return: 调度器任务参数
+ :raises ValueError: 未配置任务调用目标
"""
+ if not job_info.invoke_target:
+ raise ValueError('调用目标不能为空')
return JobAdapter.prepare(job_info, function=cls.import_function(job_info.invoke_target))
@classmethod
@@ -164,9 +167,7 @@ def get_job(self, job_id: str | int) -> Job | None:
:param job_id: 任务id
:return: 任务对象
"""
- query_job = self.scheduler.get_job(job_id=str(job_id))
-
- return query_job
+ return cast('Job | None', self.scheduler.get_job(job_id=str(job_id)))
def add_job(self, job_info: JobModel) -> None:
"""
diff --git a/ruoyi-fastapi-backend/config/scheduler/listener.py b/ruoyi-fastapi-backend/config/scheduler/listener.py
index b4d3011e2..366cc173a 100644
--- a/ruoyi-fastapi-backend/config/scheduler/listener.py
+++ b/ruoyi-fastapi-backend/config/scheduler/listener.py
@@ -46,25 +46,25 @@ def handle_event(self, event: SchedulerEvent) -> None:
if event.run_duration_ms is not None:
message += f', 耗时:{event.run_duration_ms}毫秒'
job_log = JobLogModel(
- jobId=info.job_id,
- executionId=event.execution_id,
- jobName=info.name,
- jobGroup=info.job_group,
- jobStore=info.jobstore,
- jobExecutor=info.executor,
- invokeTarget=info.invoke_target,
- jobArgs=json.loads(info.args) if info.args else [],
- jobKwargs=json.loads(info.kwargs),
- jobTrigger=info.trigger,
- jobMessage=message,
+ job_id=info.job_id,
+ execution_id=event.execution_id,
+ job_name=info.name,
+ job_group=info.job_group,
+ job_store=info.jobstore,
+ job_executor=info.executor,
+ invoke_target=info.invoke_target,
+ job_args=json.loads(info.args) if info.args else [],
+ job_kwargs=json.loads(info.kwargs),
+ job_trigger=info.trigger,
+ job_message=message,
status='1' if reason else '0',
- exceptionInfo=str(event.exception) if event.exception else (reason or ''),
- scheduledTime=event.scheduled_run_time,
- startTime=event.start_time,
- endTime=event.end_time,
- runDurationMs=event.run_duration_ms,
- timeZone=info.time_zone,
- createTime=TimezoneUtil.utc_now(),
+ exception_info=str(event.exception) if event.exception else (reason or ''),
+ scheduled_time=event.scheduled_run_time,
+ start_time=event.start_time,
+ end_time=event.end_time,
+ run_duration_ms=event.run_duration_ms,
+ time_zone=info.time_zone,
+ create_time=TimezoneUtil.utc_now(),
)
self.persist_log(job_log)
except Exception:
diff --git a/ruoyi-fastapi-backend/config/scheduler/triggers.py b/ruoyi-fastapi-backend/config/scheduler/triggers.py
index 57be7d94f..d3bef745b 100644
--- a/ruoyi-fastapi-backend/config/scheduler/triggers.py
+++ b/ruoyi-fastapi-backend/config/scheduler/triggers.py
@@ -77,8 +77,8 @@ def trigger_timezone(trigger: Any) -> str | None:
:param trigger: Cron、单次或组合触发器
:return: 任务时区名称,未携带时区时返回None
"""
- if hasattr(trigger, 'task_timezone'):
- return trigger.task_timezone
+ if isinstance(task_timezone := getattr(trigger, 'task_timezone', None), str):
+ return task_timezone
if hasattr(trigger, 'timezone'):
return str(trigger.timezone)
for child in getattr(trigger, 'triggers', ()):
diff --git a/ruoyi-fastapi-backend/docs/cli_usage.md b/ruoyi-fastapi-backend/docs/cli_usage.md
index 928e93660..28d2c9d98 100644
--- a/ruoyi-fastapi-backend/docs/cli_usage.md
+++ b/ruoyi-fastapi-backend/docs/cli_usage.md
@@ -543,11 +543,33 @@ ruoyi dev test tests --output=json
说明:
-- `dev lint` 依次运行 Ruff 格式化、静态检查和项目文档规范检查。CLI 和 CI 共用 `scripts/check_docstrings.py` 校验 reST 文档、模型字段和 HTTP 路由说明。在后端目录执行 `python scripts/check_docstrings.py .` 可单独运行这项检查。
+- `dev lint` 依次运行 Ruff 格式化、Ruff 静态检查、项目文档规范检查和 ty 类型检查。在后端目录执行 `python scripts/check_docstrings.py .` 可单独校验 reST 文档、模型字段和 HTTP 路由说明。
- `--check-only` 会改成只检查,不写回
- `--fix` 会执行 `ruff check --fix`
- `dev test` 通过当前环境的 `python -m pytest` 执行测试
+#### Python 类型检查
+
+在后端目录运行以下命令。后端(含插件和单元测试)、浏览器测试和 CI 脚本各自使用独立的 Python 导入根目录。ty 从当前解释器环境解析依赖,默认按项目支持的最低版本 Python 3.11 检查各平台的条件分支。在 VS Code 打开整个仓库时也使用同一版本。CI 在 Python 3.11 至 3.15 的各个环境中通过 `--python-version` 指定对应的目标版本。
+
+```bash
+# 检查后端、插件及其测试
+python scripts/check_types.py .
+# 检查三个工程
+python scripts/check_types.py ..
+# 只检查插件目录
+python scripts/check_types.py plugins
+```
+
+复现整仓检查时,在同一虚拟环境中安装两种数据库驱动、测试工具和 AI 插件依赖。
+
+```bash
+python -m pip install -r requirements.txt -r requirements-pg.txt -r requirements-test.txt -r ../ruoyi-fastapi-test/requirements.txt -r ../.github/requirements.txt
+python ../.github/scripts/install_ai_test_dependencies.py
+```
+
+三个工程均直接检查全部类型诊断。任一受支持的 Python 版本报告错误或警告时,CI 类型检查失败。
+
#### Python 文档字符串
Python 文件顶部禁止说明性 `#` 注释和模块 docstring。首行 shebang 和 Python 识别的编码声明可以保留。类、方法和函数实现使用 Sphinx/reStructuredText docstring,包括私有成员、嵌套定义和异步函数。使用 `@overload` 的函数在具体实现上统一写文档。[Ruff 重载文档规则](https://docs.astral.sh/ruff/rules/overload-with-docstring/)
diff --git a/ruoyi-fastapi-backend/docs/file_management_usage_guide.md b/ruoyi-fastapi-backend/docs/file_management_usage_guide.md
index 20297eef9..f156e867b 100644
--- a/ruoyi-fastapi-backend/docs/file_management_usage_guide.md
+++ b/ruoyi-fastapi-backend/docs/file_management_usage_guide.md
@@ -207,8 +207,13 @@ CONTRACT_FILE_BUSINESS_TYPE = 'contract'
### 4.2 请求模型接收文件 ID
```python
-class ContractModel(BaseModel):
- model_config = ConfigDict(alias_generator=to_camel)
+from pydantic import Field
+
+from common.vo import CamelModel
+
+
+class ContractModel(CamelModel):
+ """合同及其关联附件。"""
contract_id: int | None = Field(default=None, description='合同ID')
contract_name: str = Field(description='合同名称')
diff --git a/ruoyi-fastapi-backend/i18n/message.py b/ruoyi-fastapi-backend/i18n/message.py
index 58bd6ba87..7ffaf9fe9 100644
--- a/ruoyi-fastapi-backend/i18n/message.py
+++ b/ruoyi-fastapi-backend/i18n/message.py
@@ -19,14 +19,14 @@ class I18nMessage(str):
:ivar msg_key: 完整消息标识
:ivar msg_params: 消息插值参数
:ivar domain: 已注册的词库域
- :ivar count: 本次处理或预期的数量
+ :ivar plural_count: 选择复数译文时使用的数量
:ivar plural_key: 复数消息标识
"""
msg_key: str
msg_params: dict | None
domain: str
- count: int | None
+ plural_count: int | None
plural_key: str | None
def __new__(
@@ -55,10 +55,19 @@ def __new__(
instance.msg_key = msg_key
instance.msg_params = dict(msg_params) if msg_params is not None else None
instance.domain = domain
- instance.count = count
+ instance.plural_count = count
instance.plural_key = plural_key
return instance
+ def __setstate__(self, state: dict[str, object]) -> None:
+ """
+ 恢复消息属性,并移除旧格式中遮蔽字符串 count 方法的同名字段。
+
+ :param state: 复制或反序列化时取得的实例属性,复数数量已由构造参数恢复
+ """
+ self.__dict__.update(state)
+ self.__dict__.pop('count', None)
+
def __getnewargs_ex__(self) -> tuple[tuple[str], dict]:
"""
复制或序列化时保留消息元数据。
@@ -69,6 +78,6 @@ def __getnewargs_ex__(self) -> tuple[tuple[str], dict]:
'msg_key': self.msg_key,
'msg_params': self.msg_params,
'domain': self.domain,
- 'count': self.count,
+ 'count': self.plural_count,
'plural_key': self.plural_key,
}
diff --git a/ruoyi-fastapi-backend/i18n/registry.py b/ruoyi-fastapi-backend/i18n/registry.py
index 0d302742b..e0978c2f9 100644
--- a/ruoyi-fastapi-backend/i18n/registry.py
+++ b/ruoyi-fastapi-backend/i18n/registry.py
@@ -1,13 +1,29 @@
import re
from pathlib import Path
+from typing import NotRequired, TypedDict
from config.env import I18nConfig
+
+class _LocaleDefinition(TypedDict):
+ """
+ 单个语言标签的启用状态、别名和回退顺序。
+
+ :ivar enabled: 当前语言是否启用
+ :ivar aliases: 可匹配此语言的其他标签
+ :ivar fallback: 译文缺失时依次尝试的语言标签
+ """
+
+ enabled: NotRequired[bool]
+ aliases: tuple[str, ...]
+ fallback: tuple[str, ...]
+
+
MAX_LOCALE_LENGTH = 63
_SCRIPT_SUBTAG_LENGTH = 4
_REGION_SUBTAG_LENGTH = 2
CATALOG_ROOT = Path(__file__).parent / 'catalogs'
-LOCALES = {
+LOCALES: dict[str, _LocaleDefinition] = {
'zh-CN': {'enabled': True, 'aliases': ('zh', 'zh-Hans'), 'fallback': ()},
'en-US': {'enabled': True, 'aliases': ('en',), 'fallback': ('zh-CN',)},
}
@@ -109,7 +125,7 @@ def fallback_chain(code: str) -> tuple[str, ...]:
:param code: 已注册的语言标识
:return: 包含基准语言的回退链
"""
- result = []
+ result: list[str] = []
def visit(item: str, stack: tuple[str, ...] = ()) -> None:
"""
diff --git a/ruoyi-fastapi-backend/i18n/translation.py b/ruoyi-fastapi-backend/i18n/translation.py
index 4a4cc14bb..bba620f22 100644
--- a/ruoyi-fastapi-backend/i18n/translation.py
+++ b/ruoyi-fastapi-backend/i18n/translation.py
@@ -47,7 +47,7 @@ def merge(current: dict[str, str] | None, patch: dict[str, str | None]) -> dict[
:param patch: 本次提交的语言补丁
:return: 合并后的新映射,不修改输入对象
"""
- result = dict(current or {})
+ result: dict[str, str] = dict(current or {})
for locale, translation in patch.items():
if translation is None:
result.pop(locale, None)
diff --git a/ruoyi-fastapi-backend/i18n/translator.py b/ruoyi-fastapi-backend/i18n/translator.py
index 5d27853eb..c328d8d4e 100644
--- a/ruoyi-fastapi-backend/i18n/translator.py
+++ b/ruoyi-fastapi-backend/i18n/translator.py
@@ -63,7 +63,11 @@ def _translate_catalog_message(
"""
try:
catalog = cls._load_catalog(code, domain)
- value = catalog.gettext(msg_key) if count is None else catalog.ngettext(msg_key, plural_key, count)
+ value = (
+ catalog.ngettext(msg_key, plural_key, count)
+ if count is not None and plural_key is not None
+ else catalog.gettext(msg_key)
+ )
if value not in (msg_key, plural_key):
return value % ({**(params or {}), 'count': count} if count is not None else params or {})
logger.warning(
@@ -151,7 +155,7 @@ def message_fields(
msg_params = msg.msg_params if msg_params is None else msg_params
domain = msg.domain if domain is None else domain
if count is None and plural_key is None:
- count, plural_key = msg.count, msg.plural_key
+ count, plural_key = msg.plural_count, msg.plural_key
domain = domain or 'core'
validate_plural(count, plural_key)
context = context or RequestContext.get_current_locale()
diff --git a/ruoyi-fastapi-backend/middlewares/transport_crypto_middleware.py b/ruoyi-fastapi-backend/middlewares/transport_crypto_middleware.py
index 4bfaa5355..ee4d2d0c7 100644
--- a/ruoyi-fastapi-backend/middlewares/transport_crypto_middleware.py
+++ b/ruoyi-fastapi-backend/middlewares/transport_crypto_middleware.py
@@ -1,10 +1,12 @@
import json
from collections.abc import Awaitable, Callable
+from typing import TypedDict, cast
from urllib.parse import parse_qs, urlencode
from fastapi import FastAPI, Request
from fastapi.datastructures import Headers, QueryParams
from fastapi.responses import JSONResponse
+from starlette.applications import Starlette
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from common.constant import HttpStatusConstant
@@ -19,6 +21,20 @@
)
+class TransportCryptoContext(TypedDict):
+ """
+ 加密请求与响应共享的上下文。
+
+ :ivar active: 当前请求是否启用传输加密
+ :ivar kid: 请求使用的密钥版本
+ :ivar aes_key: 解密得到的 AES 会话密钥
+ """
+
+ active: bool
+ kid: str
+ aes_key: bytes
+
+
class TransportCryptoMiddleware:
"""
传输层请求解密与响应加密中间件。
@@ -127,8 +143,8 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive=self._build_receive(body))
try:
decrypted_scope, decrypted_body, crypto_context = await self._decrypt_request(scope, request, headers, body)
- await TransportCryptoMonitorUtil.record_encrypted_request(current_app, str(crypto_context['kid']))
- await TransportCryptoMonitorUtil.record_decrypt_success(current_app, str(crypto_context['kid']))
+ await TransportCryptoMonitorUtil.record_encrypted_request(current_app, crypto_context['kid'])
+ await TransportCryptoMonitorUtil.record_decrypt_success(current_app, crypto_context['kid'])
except Exception as exc:
error_crypto_context = self._build_error_crypto_context(scope, headers, body)
error_kid = (
@@ -186,7 +202,7 @@ async def _decrypt_request(
request: Request,
headers: Headers,
body: bytes,
- ) -> tuple[Scope, bytes, dict[str, str | bytes | bool]]:
+ ) -> tuple[Scope, bytes, TransportCryptoContext]:
"""
解密请求并回写解密后的headers、query和body。
@@ -208,7 +224,7 @@ async def _decrypt_request(
if query_envelope is None and body_envelope is None:
raise ValueError('未找到可解密的请求载荷')
- crypto_context: dict[str, str | bytes | bool] | None = None
+ crypto_context: TransportCryptoContext | None = None
if query_envelope is not None:
decrypted_query = await self._decrypt_envelope(request, scope, query_envelope)
query_payload = self._loads_json_mapping(decrypted_query.plaintext.decode('utf-8'))
@@ -244,7 +260,7 @@ async def _decrypt_envelope(
self,
request: Request,
scope: Scope,
- envelope: dict[str, str],
+ envelope: dict[str, object],
) -> DecryptedTransportEnvelope:
"""
解密单个请求信封并执行时间窗、防重放校验。
@@ -263,7 +279,7 @@ async def _decrypt_envelope(
await TransportSecurityUtil.validate_replay(request, decrypted_payload.kid, decrypted_payload.nonce)
return decrypted_payload
- def _extract_query_envelope(self, scope: Scope) -> dict[str, str] | None:
+ def _extract_query_envelope(self, scope: Scope) -> dict[str, object] | None:
"""
从查询参数中提取加密信封。
@@ -276,7 +292,7 @@ def _extract_query_envelope(self, scope: Scope) -> dict[str, str] | None:
return None
return TransportCryptoUtil.decode_query_envelope(encrypted_query)
- def _extract_body_envelope(self, content_type: str, body: bytes) -> dict[str, str] | None:
+ def _extract_body_envelope(self, content_type: str, body: bytes) -> dict[str, object] | None:
"""
根据内容类型从请求体中提取加密信封。
@@ -292,11 +308,11 @@ def _extract_body_envelope(self, content_type: str, body: bytes) -> dict[str, st
body_payload = json.loads(body.decode('utf-8'))
if not isinstance(body_payload, dict):
raise ValueError('加密请求体格式不合法')
- return body_payload
+ return cast('dict[str, object]', body_payload)
if 'application/x-www-form-urlencoded' in content_type:
parsed_form = parse_qs(body.decode('utf-8'), keep_blank_values=True)
- body_envelope = {
+ body_envelope: dict[str, object] = {
key: values[-1] if isinstance(values, list) else values for key, values in parsed_form.items()
}
aad = body_envelope.get('aad')
@@ -316,7 +332,7 @@ def _build_response_encryptor(
app: FastAPI | None,
scope: Scope,
send: Send,
- crypto_context: dict[str, str | bytes | bool],
+ crypto_context: TransportCryptoContext,
) -> Callable[[Message], Awaitable[None]]:
"""
构建响应加密发送器,仅对JSON响应执行加密。
@@ -355,7 +371,7 @@ async def _encrypt_response(message: Message) -> None:
request_mode='encrypted',
response_mode='plain',
crypto_status='ok',
- kid=str(crypto_context['kid']),
+ kid=crypto_context['kid'],
),
),
}
@@ -377,7 +393,7 @@ async def _encrypt_response(message: Message) -> None:
encrypted_body = TransportCryptoUtil.encrypt_response_body(
aes_key=crypto_context['aes_key'],
payload=b''.join(buffered_json_body),
- kid=str(crypto_context['kid']),
+ kid=crypto_context['kid'],
method=str(scope.get('method', '')),
path=self._normalize_path(str(scope.get('path', ''))),
)
@@ -398,7 +414,7 @@ async def _encrypt_response(message: Message) -> None:
response_headers = self._replace_header(
response_headers,
self._ENCRYPT_KID_HEADER.encode('utf-8'),
- str(crypto_context['kid']).encode('utf-8'),
+ crypto_context['kid'].encode('utf-8'),
)
response_headers = self._merge_response_headers(
response_headers,
@@ -406,10 +422,10 @@ async def _encrypt_response(message: Message) -> None:
request_mode='encrypted',
response_mode='encrypted',
crypto_status='ok',
- kid=str(crypto_context['kid']),
+ kid=crypto_context['kid'],
),
)
- await TransportCryptoMonitorUtil.record_encrypted_response(app, str(crypto_context['kid']))
+ await TransportCryptoMonitorUtil.record_encrypted_response(app, crypto_context['kid'])
await send({**response_start_message, 'headers': response_headers})
await send({'type': 'http.response.body', 'body': encrypted_body, 'more_body': False})
@@ -467,7 +483,7 @@ async def _observe_response(message: Message) -> None:
return _observe_response
- def _build_crypto_context(self, decrypted_payload: DecryptedTransportEnvelope) -> dict[str, str | bytes | bool]:
+ def _build_crypto_context(self, decrypted_payload: DecryptedTransportEnvelope) -> TransportCryptoContext:
"""
从解密结果构建请求生命周期内的加密上下文。
@@ -485,7 +501,7 @@ def _build_error_crypto_context(
scope: Scope,
headers: Headers,
body: bytes,
- ) -> dict[str, str | bytes | bool] | None:
+ ) -> TransportCryptoContext | None:
"""
尝试在解密失败场景下提取AES会话密钥,以便返回加密错误响应。
@@ -688,7 +704,7 @@ async def _send_error_response(
receive: Receive,
send: Send,
msg_key: str,
- crypto_context: dict[str, str | bytes | bool] | None = None,
+ crypto_context: TransportCryptoContext | None = None,
headers: dict[str, str] | None = None,
) -> None:
"""
@@ -711,7 +727,7 @@ async def _send_error_response(
encrypted_body = TransportCryptoUtil.encrypt_response_body(
aes_key=crypto_context['aes_key'],
payload=json.dumps(response_content, ensure_ascii=False).encode('utf-8'),
- kid=str(crypto_context['kid']),
+ kid=crypto_context['kid'],
method=str(scope.get('method', '')),
path=cls._normalize_path(str(scope.get('path', ''))),
)
@@ -719,7 +735,7 @@ async def _send_error_response(
response.init_headers()
response.headers[cls._ENCRYPT_RESPONSE_HEADER] = '1'
response.headers[cls._ENCRYPT_ALG_HEADER] = TransportCryptoUtil.get_response_envelope_algorithm()
- response.headers[cls._ENCRYPT_KID_HEADER] = str(crypto_context['kid'])
+ response.headers[cls._ENCRYPT_KID_HEADER] = crypto_context['kid']
if headers:
response.headers.update(headers)
await response(scope, receive, send)
@@ -822,7 +838,7 @@ def _is_enabled_path(cls, path: str) -> bool:
return any(path == enabled_path or path.startswith(f'{enabled_path}/') for enabled_path in enabled_paths)
-def add_transport_crypto_middleware(app: ASGIApp) -> None:
+def add_transport_crypto_middleware(app: Starlette) -> None:
"""
添加传输层加解密中间件。
diff --git a/ruoyi-fastapi-backend/module_admin/controller/captcha_controller.py b/ruoyi-fastapi-backend/module_admin/controller/captcha_controller.py
index 5e3f28ae0..4fdd5131f 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/captcha_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/captcha_controller.py
@@ -41,6 +41,6 @@ async def get_captcha_image(request: Request) -> Response:
return ResponseUtil.success(
model_content=CaptchaCode(
- captchaEnabled=captcha_enabled, registerEnabled=register_enabled, img=image, uuid=session_id
+ captcha_enabled=captcha_enabled, register_enabled=register_enabled, img=image, uuid=session_id
)
)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/config_controller.py b/ruoyi-fastapi-backend/module_admin/controller/config_controller.py
index bd4eb0316..ec28affec 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/config_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/config_controller.py
@@ -127,7 +127,7 @@ async def delete_system_config(
config_ids: Annotated[str, Path(description='需要删除的参数主键')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- delete_config = DeleteConfigModel(configIds=config_ids)
+ delete_config = DeleteConfigModel(config_ids=config_ids)
delete_config_result = await ConfigService.delete_config_services(request, query_db, delete_config)
logger.info(delete_config_result.message)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/dept_controller.py b/ruoyi-fastapi-backend/module_admin/controller/dept_controller.py
index ab5399331..58015b9b7 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/dept_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/dept_controller.py
@@ -41,7 +41,7 @@ async def get_system_dept_tree_for_edit_option(
query_db: Annotated[AsyncSession, DBSessionDependency()],
data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
) -> Response:
- dept_query = DeptModel(deptId=dept_id)
+ dept_query = DeptModel(dept_id=dept_id)
dept_query_result = await DeptService.get_dept_for_edit_option_services(query_db, dept_query, data_scope_sql)
logger.info('获取成功')
@@ -171,7 +171,7 @@ async def delete_system_dept(
for dept_id in dept_id_list:
if not current_user.user.admin:
await DeptService.check_dept_data_scope_services(query_db, int(dept_id), data_scope_sql)
- delete_dept = DeleteDeptModel(deptIds=dept_ids)
+ delete_dept = DeleteDeptModel(dept_ids=dept_ids)
delete_dept.update_by = current_user.user.user_name
delete_dept_result = await DeptService.delete_dept_services(query_db, delete_dept)
logger.info(delete_dept_result.message)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/dict_controller.py b/ruoyi-fastapi-backend/module_admin/controller/dict_controller.py
index aa097e34e..1487430c5 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/dict_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/dict_controller.py
@@ -133,7 +133,7 @@ async def delete_system_dict_type(
dict_ids: Annotated[str, Path(description='需要删除的字典主键')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- delete_dict_type = DeleteDictTypeModel(dictIds=dict_ids)
+ delete_dict_type = DeleteDictTypeModel(dict_ids=dict_ids)
delete_dict_type_result = await DictTypeService.delete_dict_type_services(request, query_db, delete_dict_type)
logger.info(delete_dict_type_result.message)
@@ -312,7 +312,7 @@ async def delete_system_dict_data(
dict_codes: Annotated[str, Path(description='需要删除的字典编码')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- delete_dict_data = DeleteDictDataModel(dictCodes=dict_codes)
+ delete_dict_data = DeleteDictDataModel(dict_codes=dict_codes)
delete_dict_data_result = await DictDataService.delete_dict_data_services(request, query_db, delete_dict_data)
logger.info(delete_dict_data_result.message)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/file_controller.py b/ruoyi-fastapi-backend/module_admin/controller/file_controller.py
index 14cf83c31..30136f9be 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/file_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/file_controller.py
@@ -822,7 +822,7 @@ async def delete_system_file(
delete_file_result = await FileLifecycleService.delete_file_services(
query_db,
current_user,
- DeleteFileModel(fileIds=file_ids),
+ DeleteFileModel(file_ids=file_ids),
file_data_scope_sql,
request=request,
)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/job_controller.py b/ruoyi-fastapi-backend/module_admin/controller/job_controller.py
index 749123d5c..2e118a07e 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/job_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/job_controller.py
@@ -63,9 +63,9 @@
async def preview_system_job(request: Request, preview: JobPreviewRequest) -> Response:
start_time = preview.start_time or TimezoneUtil.utc_now()
result = JobPreviewResult(
- timeZone=preview.time_zone,
- startTime=start_time,
- nextRunTimes=CronUtil.next_run_times(preview.cron_expression, preview.time_zone, start_time, preview.count),
+ time_zone=preview.time_zone,
+ start_time=start_time,
+ next_run_times=CronUtil.next_run_times(preview.cron_expression, preview.time_zone, start_time, preview.count),
)
return ResponseUtil.success(data=result)
@@ -152,9 +152,9 @@ async def change_system_job_status(
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
) -> Response:
edit_job = EditJobModel(
- jobId=change_job.job_id,
+ job_id=change_job.job_id,
status=change_job.status,
- updateBy=current_user.user.user_name,
+ update_by=current_user.user.user_name,
type='status',
)
edit_job_result = await JobService.edit_job_services(query_db, edit_job)
@@ -283,7 +283,7 @@ async def delete_system_job(
job_ids: Annotated[str, Path(description='需要删除的定时任务ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- delete_job = DeleteJobModel(jobIds=job_ids)
+ delete_job = DeleteJobModel(job_ids=job_ids)
delete_job_result = await JobService.delete_job_services(query_db, delete_job)
logger.info(delete_job_result.message)
@@ -392,7 +392,7 @@ async def delete_system_job_log(
job_log_ids: Annotated[str, Path(description='需要删除的定时任务日志ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- delete_job_log = DeleteJobLogModel(jobLogIds=job_log_ids)
+ delete_job_log = DeleteJobLogModel(job_log_ids=job_log_ids)
delete_job_log_result = await JobLogService.delete_job_log_services(query_db, delete_job_log)
logger.info(delete_job_log_result.message)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/log_controller.py b/ruoyi-fastapi-backend/module_admin/controller/log_controller.py
index 8eca2c23b..15156f620 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/log_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/log_controller.py
@@ -85,7 +85,7 @@ async def delete_system_operation_log(
oper_ids: Annotated[str, Path(description='需要删除的日志主键')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- delete_operation_log = DeleteOperLogModel(operIds=oper_ids)
+ delete_operation_log = DeleteOperLogModel(oper_ids=oper_ids)
delete_operation_log_result = await OperationLogService.delete_operation_log_services(
query_db, delete_operation_log
)
@@ -181,7 +181,7 @@ async def delete_system_login_log(
info_ids: Annotated[str, Path(description='需要删除的访问ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- delete_login_log = DeleteLoginLogModel(infoIds=info_ids)
+ delete_login_log = DeleteLoginLogModel(info_ids=info_ids)
delete_login_log_result = await LoginLogService.delete_login_log_services(query_db, delete_login_log)
logger.info(delete_login_log_result.message)
@@ -202,7 +202,7 @@ async def unlock_system_user(
user_name: Annotated[str, Path(description='用户名称')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- unlock_user = UnlockUser(userName=user_name)
+ unlock_user = UnlockUser(user_name=user_name)
unlock_user_result = await LoginLogService.unlock_user_services(request, unlock_user)
logger.info(unlock_user_result.message)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/login_controller.py b/ruoyi-fastapi-backend/module_admin/controller/login_controller.py
index 6072ea0f1..4c575b9b3 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/login_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/login_controller.py
@@ -3,6 +3,7 @@
from typing import Annotated
from fastapi import Depends, Request, Response
+from fastapi.responses import JSONResponse
from sqlalchemy.ext.asyncio import AsyncSession
from common.annotation.cache_annotation import ApiCache, ApiCacheEvict
@@ -15,6 +16,7 @@
from common.router import APIRouterPro
from common.vo import CrudResponseModel, DataResponseModel, DynamicResponseModel, ResponseBaseModel
from config.env import AppConfig, JwtConfig
+from exceptions.exception import AuthException
from module_admin.entity.vo.login_vo import (
LoginToken,
RouterModel,
@@ -52,12 +54,12 @@ async def login(
await request.app.state.redis.get(f'{RedisInitKeyConfig.SYS_CONFIG.key}:sys.account.captchaEnabled') == 'true'
)
user = UserLogin(
- userName=form_data.username,
+ user_name=form_data.username,
password=form_data.password,
code=form_data.code,
uuid=form_data.uuid,
- loginInfo=form_data.login_info,
- captchaEnabled=captcha_enabled,
+ login_info=form_data.login_info,
+ captcha_enabled=captcha_enabled,
)
result = await LoginService.authenticate_user(request, query_db, user)
access_token_expires = timedelta(minutes=JwtConfig.jwt_expire_minutes)
@@ -85,16 +87,14 @@ async def login(
access_token,
ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes),
)
- login_update = EditUserModel(userId=result[0].user_id, loginDate=TimezoneUtil.utc_now(), type='status')
+ login_update = EditUserModel(user_id=result[0].user_id, login_date=TimezoneUtil.utc_now(), type='status')
if form_data.locale is not None:
login_update.locale = form_data.locale
await UserService.edit_user_services(query_db, login_update)
logger.info('登录成功')
# 判断请求是否来自于api文档,如果是返回指定格式的结果,用于修复api文档认证成功后token显示undefined的bug
- request_from_swagger = request.headers.get('referer').endswith('docs') if request.headers.get('referer') else False
- request_from_redoc = request.headers.get('referer').endswith('redoc') if request.headers.get('referer') else False
- if request_from_swagger or request_from_redoc:
- return {'access_token': access_token, 'token_type': 'Bearer'}
+ if request.headers.get('referer', '').endswith(('docs', 'redoc')):
+ return JSONResponse({'access_token': access_token, 'token_type': 'Bearer'})
return ResponseUtil.success(msg_key='auth.signedIn', dict_content={'token': access_token})
@@ -176,12 +176,13 @@ async def register_user(
)
@ApiCacheEvict(namespaces=ApiGroup.LOGOUT_MUTATION)
async def logout(request: Request, token: Annotated[str | None, Depends(oauth2_scheme)]) -> Response:
+ if not token:
+ raise AuthException(data='', message='用户未登录,请先完成登录', msg_key='auth.signInRequired')
payload = JwtUtil.decode(token, options={'verify_exp': False})
- if AppConfig.app_same_time_login:
- token_id: str = payload.get('session_id')
- else:
- token_id: str = payload.get('user_id')
- await LoginService.logout_services(request, token_id, token)
+ token_id = payload.get('session_id' if AppConfig.app_same_time_login else 'user_id')
+ if not isinstance(token_id, (str, int)) or not token_id:
+ raise AuthException(data='', message='用户token不合法', msg_key='auth.invalidToken')
+ await LoginService.logout_services(request, str(token_id), token)
logger.info('退出成功')
return ResponseUtil.success(msg_key='auth.signedOut')
diff --git a/ruoyi-fastapi-backend/module_admin/controller/menu_controller.py b/ruoyi-fastapi-backend/module_admin/controller/menu_controller.py
index 23e3ca047..3d4a2fdd7 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/menu_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/menu_controller.py
@@ -163,7 +163,7 @@ async def delete_system_menu(
menu_ids: Annotated[str, Path(description='需要删除的菜单ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- delete_menu = DeleteMenuModel(menuIds=menu_ids)
+ delete_menu = DeleteMenuModel(menu_ids=menu_ids)
delete_menu_result = await MenuService.delete_menu_services(query_db, delete_menu)
logger.info(delete_menu_result.message)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/notice_controller.py b/ruoyi-fastapi-backend/module_admin/controller/notice_controller.py
index 69c18c19a..09f877646 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/notice_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/notice_controller.py
@@ -186,7 +186,7 @@ async def delete_system_notice(
notice_ids: Annotated[str, Path(description='需要删除的公告ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- delete_notice = DeleteNoticeModel(noticeIds=notice_ids)
+ delete_notice = DeleteNoticeModel(notice_ids=notice_ids)
delete_notice_result = await NoticeService.delete_notice_services(query_db, delete_notice)
logger.info(delete_notice_result.message)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/online_controller.py b/ruoyi-fastapi-backend/module_admin/controller/online_controller.py
index 2fe9102fc..2a82320bf 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/online_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/online_controller.py
@@ -56,7 +56,7 @@ async def delete_monitor_online(
token_ids: Annotated[str, Path(description='需要强退的会话编号')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- delete_online = DeleteOnlineModel(tokenIds=token_ids)
+ delete_online = DeleteOnlineModel(token_ids=token_ids)
delete_online_result = await OnlineService.delete_online_services(request, delete_online)
logger.info(delete_online_result.message)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/post_controller.py b/ruoyi-fastapi-backend/module_admin/controller/post_controller.py
index 5195b9246..c0790e3ad 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/post_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/post_controller.py
@@ -108,7 +108,7 @@ async def delete_system_post(
post_ids: Annotated[str, Path(description='需要删除的岗位ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- delete_post = DeletePostModel(postIds=post_ids)
+ delete_post = DeletePostModel(post_ids=post_ids)
delete_post_result = await PostService.delete_post_services(query_db, delete_post)
logger.info(delete_post_result.message)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/role_controller.py b/ruoyi-fastapi-backend/module_admin/controller/role_controller.py
index 6f1b2509c..36fe10c80 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/role_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/role_controller.py
@@ -27,7 +27,12 @@
RoleModel,
RolePageQueryModel,
)
-from module_admin.entity.vo.user_vo import CrudUserRoleModel, CurrentUserModel, UserInfoModel, UserRolePageQueryModel
+from module_admin.entity.vo.user_vo import (
+ CrudUserRoleModel,
+ CurrentUserModel,
+ UserInfoModel,
+ UserRolePageQueryModel,
+)
from module_admin.service.dept_service import DeptService
from module_admin.service.role_service import RoleService
from module_admin.service.user_service import UserService
@@ -155,11 +160,11 @@ async def edit_system_role_datascope(
if not current_user.user.admin:
await RoleService.check_role_data_scope_services(query_db, str(role_data_scope.role_id), data_scope_sql)
edit_role = AddRoleModel(
- roleId=role_data_scope.role_id,
- dataScope=role_data_scope.data_scope,
- deptIds=role_data_scope.dept_ids,
- deptCheckStrictly=role_data_scope.dept_check_strictly,
- updateBy=current_user.user.user_name,
+ role_id=role_data_scope.role_id,
+ data_scope=role_data_scope.data_scope,
+ dept_ids=role_data_scope.dept_ids,
+ dept_check_strictly=role_data_scope.dept_check_strictly,
+ update_by=current_user.user.user_name,
)
role_data_scope_result = await RoleService.role_datascope_services(query_db, edit_role)
logger.info(role_data_scope_result.message)
@@ -186,10 +191,10 @@ async def delete_system_role(
role_id_list = role_ids.split(',') if role_ids else []
if role_id_list:
for role_id in role_id_list:
- await RoleService.check_role_allowed_services(RoleModel(roleId=int(role_id)))
+ await RoleService.check_role_allowed_services(RoleModel(role_id=int(role_id)))
if not current_user.user.admin:
await RoleService.check_role_data_scope_services(query_db, role_id, data_scope_sql)
- delete_role = DeleteRoleModel(roleIds=role_ids, updateBy=current_user.user.user_name)
+ delete_role = DeleteRoleModel(role_ids=role_ids, update_by=current_user.user.user_name)
delete_role_result = await RoleService.delete_role_services(query_db, delete_role)
logger.info(delete_role_result.message)
@@ -272,9 +277,9 @@ async def reset_system_role_status(
if not current_user.user.admin:
await RoleService.check_role_data_scope_services(query_db, str(change_role.role_id), data_scope_sql)
edit_role = AddRoleModel(
- roleId=change_role.role_id,
+ role_id=change_role.role_id,
status=change_role.status,
- updateBy=current_user.user.user_name,
+ update_by=current_user.user.user_name,
type='status',
)
edit_role_result = await RoleService.edit_role_services(query_db, edit_role)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/user_controller.py b/ruoyi-fastapi-backend/module_admin/controller/user_controller.py
index e43c362fa..45bf6de38 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/user_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/user_controller.py
@@ -122,10 +122,10 @@ async def add_system_user(
if not current_user.user.admin:
await DeptService.check_dept_data_scope_services(query_db, add_user.dept_id, dept_data_scope_sql)
await RoleService.check_role_data_scope_services(
- query_db, ','.join([str(item) for item in add_user.role_ids]), role_data_scope_sql
+ query_db, ','.join(str(item) for item in add_user.role_ids or []), role_data_scope_sql
)
- await UserService.validate_password_services(request.app.state.redis, add_user.password)
- add_user.password = PwdUtil.get_password_hash(add_user.password)
+ password = await UserService.validate_password_services(request.app.state.redis, add_user.password)
+ add_user.password = PwdUtil.get_password_hash(password)
add_user.create_by = current_user.user.user_name
add_user.update_by = current_user.user.user_name
add_user_result = await UserService.add_user_services(query_db, add_user)
@@ -156,7 +156,6 @@ async def edit_system_user(
# 普通编辑只接收管理表单字段,密码与内部操作类型由专用接口处理。
edit_user = EditUserModel(
**edit_user.model_dump(
- by_alias=True,
exclude_unset=True,
include={
'user_id',
@@ -170,15 +169,15 @@ async def edit_system_user(
'remark',
},
),
- roleIds=edit_user.role_ids or [],
- postIds=edit_user.post_ids or [],
+ role_ids=edit_user.role_ids or [],
+ post_ids=edit_user.post_ids or [],
)
await UserService.check_user_allowed_services(edit_user)
if not current_user.user.admin:
await UserService.check_user_data_scope_services(query_db, edit_user.user_id, user_data_scope_sql)
await DeptService.check_dept_data_scope_services(query_db, edit_user.dept_id, dept_data_scope_sql)
await RoleService.check_role_data_scope_services(
- query_db, ','.join([str(item) for item in edit_user.role_ids]), role_data_scope_sql
+ query_db, ','.join(str(item) for item in edit_user.role_ids or []), role_data_scope_sql
)
edit_user.update_by = current_user.user.user_name
edit_user_result = await UserService.edit_user_services(query_db, edit_user)
@@ -210,10 +209,10 @@ async def delete_system_user(
return ResponseUtil.failure(msg_key='user.deleteCurrentUser')
for user_id in user_id_list:
- await UserService.check_user_allowed_services(UserModel(userId=int(user_id)))
+ await UserService.check_user_allowed_services(UserModel(user_id=int(user_id)))
if not current_user.user.admin:
await UserService.check_user_data_scope_services(query_db, int(user_id), data_scope_sql)
- delete_user = DeleteUserModel(userIds=user_ids, updateBy=current_user.user.user_name)
+ delete_user = DeleteUserModel(user_ids=user_ids, update_by=current_user.user.user_name)
delete_user_result = await UserService.delete_user_services(query_db, delete_user)
logger.info(delete_user_result.message)
@@ -239,14 +238,14 @@ async def reset_system_user_pwd(
await UserService.check_user_allowed_services(reset_user)
if not current_user.user.admin:
await UserService.check_user_data_scope_services(query_db, reset_user.user_id, data_scope_sql)
- await UserService.validate_password_services(
+ password = await UserService.validate_password_services(
request.app.state.redis, reset_user.password, PasswordCharacterType.DEFAULT
)
edit_user = EditUserModel(
- userId=reset_user.user_id,
- password=PwdUtil.get_password_hash(reset_user.password),
- pwdUpdateDate=TimezoneUtil.utc_now(),
- updateBy=current_user.user.user_name,
+ user_id=reset_user.user_id,
+ password=PwdUtil.get_password_hash(password),
+ pwd_update_date=TimezoneUtil.utc_now(),
+ update_by=current_user.user.user_name,
type='pwd',
)
edit_user_result = await UserService.edit_user_services(query_db, edit_user)
@@ -275,9 +274,9 @@ async def change_system_user_status(
if not current_user.user.admin:
await UserService.check_user_data_scope_services(query_db, change_user.user_id, data_scope_sql)
edit_user = EditUserModel(
- userId=change_user.user_id,
+ user_id=change_user.user_id,
status=change_user.status,
- updateBy=current_user.user.user_name,
+ update_by=current_user.user.user_name,
type='status',
)
edit_user_result = await UserService.edit_user_services(query_db, edit_user)
@@ -363,16 +362,17 @@ async def change_system_user_profile_avatar(
avatar_path = os.path.join(dir_path, avatar_name)
async with aiofiles.open(avatar_path, 'wb') as f:
await f.write(avatarfile)
+ avatar_url = f'{UploadConfig.UPLOAD_PREFIX}/{relative_path}/{avatar_name}'
edit_user = EditUserModel(
- userId=current_user.user.user_id,
- avatar=f'{UploadConfig.UPLOAD_PREFIX}/{relative_path}/{avatar_name}',
- updateBy=current_user.user.user_name,
+ user_id=current_user.user.user_id,
+ avatar=avatar_url,
+ update_by=current_user.user.user_name,
type='avatar',
)
edit_user_result = await UserService.edit_user_services(query_db, edit_user)
logger.info(edit_user_result.message)
- return ResponseUtil.success(model_content=AvatarModel(imgUrl=edit_user.avatar), msg=edit_user_result.message)
+ return ResponseUtil.success(model_content=AvatarModel(img_url=avatar_url), msg=edit_user_result.message)
return ResponseUtil.failure(msg_key='user.avatar.uploadFailed')
@@ -393,14 +393,13 @@ async def change_system_user_profile_info(
edit_user = EditUserModel(
**user_info.model_dump(
exclude_unset=True,
- by_alias=True,
include={'nick_name', 'email', 'phonenumber', 'sex'},
),
- userId=current_user.user.user_id,
- userName=current_user.user.user_name,
- updateBy=current_user.user.user_name,
- roleIds=current_user.user.role_ids.split(',') if current_user.user.role_ids else [],
- postIds=current_user.user.post_ids.split(',') if current_user.user.post_ids else [],
+ user_id=current_user.user.user_id,
+ user_name=current_user.user.user_name,
+ update_by=current_user.user.user_name,
+ role_ids=current_user.user.role_ids.split(',') if current_user.user.role_ids else [],
+ post_ids=current_user.user.post_ids.split(',') if current_user.user.post_ids else [],
role=current_user.user.role,
)
edit_user_result = await UserService.edit_user_services(query_db, edit_user)
@@ -481,11 +480,11 @@ async def reset_system_user_password(
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
) -> Response:
reset_user = ResetUserModel(
- userId=current_user.user.user_id,
- oldPassword=reset_password.old_password,
+ user_id=current_user.user.user_id,
+ old_password=reset_password.old_password,
password=reset_password.new_password,
- pwdUpdateDate=TimezoneUtil.utc_now(),
- updateBy=current_user.user.user_name,
+ pwd_update_date=TimezoneUtil.utc_now(),
+ update_by=current_user.user.user_name,
)
await UserService.validate_password_services(request.app.state.redis, reset_user.password)
reset_user_result = await UserService.reset_user_services(query_db, reset_user)
@@ -594,7 +593,7 @@ async def get_system_allocated_role_list(
user_id: Annotated[int, Path(description='用户ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- user_role_query = UserRoleQueryModel(userId=user_id)
+ user_role_query = UserRoleQueryModel(user_id=user_id)
user_role_allocated_query_result = await UserService.get_user_role_allocated_list_services(
query_db, user_role_query
)
@@ -626,7 +625,7 @@ async def update_system_role_user(
await RoleService.check_role_data_scope_services(query_db, role_ids, role_data_scope_sql)
add_user_role_result = await UserService.add_user_role_services(
query_db,
- CrudUserRoleModel(userId=user_id, roleIds=role_ids),
+ CrudUserRoleModel(user_id=user_id, role_ids=role_ids),
current_user.user.user_name,
)
logger.info(add_user_role_result.message)
diff --git a/ruoyi-fastapi-backend/module_admin/dao/config_dao.py b/ruoyi-fastapi-backend/module_admin/dao/config_dao.py
index 4cabfc661..7a5021624 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/config_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/config_dao.py
@@ -1,6 +1,6 @@
from typing import Any
-from sqlalchemy import delete, select, update
+from sqlalchemy import delete, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
@@ -39,8 +39,8 @@ async def get_config_detail_by_info(cls, db: AsyncSession, config: ConfigModel)
(
await db.execute(
select(SysConfig).where(
- SysConfig.config_key == config.config_key if config.config_key else True,
- SysConfig.config_value == config.config_value if config.config_value else True,
+ SysConfig.config_key == config.config_key if config.config_key else true(),
+ SysConfig.config_value == config.config_value if config.config_value else true(),
)
)
)
@@ -68,11 +68,11 @@ async def get_config_list(
query = (
select(SysConfig)
.where(
- SysConfig.config_name.like(f'%{query_object.config_name}%') if query_object.config_name else True,
- SysConfig.config_key.like(f'%{query_object.config_key}%') if query_object.config_key else True,
- SysConfig.config_type == query_object.config_type if query_object.config_type else True,
- SysConfig.create_time >= time_range[0] if time_range and time_range[0] is not None else True,
- SysConfig.create_time < time_range[1] if time_range and time_range[1] is not None else True,
+ SysConfig.config_name.like(f'%{query_object.config_name}%') if query_object.config_name else true(),
+ SysConfig.config_key.like(f'%{query_object.config_key}%') if query_object.config_key else true(),
+ SysConfig.config_type == query_object.config_type if query_object.config_type else true(),
+ SysConfig.create_time >= time_range[0] if time_range and time_range[0] is not None else true(),
+ SysConfig.create_time < time_range[1] if time_range and time_range[1] is not None else true(),
)
.order_by(SysConfig.config_id)
.distinct()
diff --git a/ruoyi-fastapi-backend/module_admin/dao/dept_dao.py b/ruoyi-fastapi-backend/module_admin/dao/dept_dao.py
index 9b7e1e7a6..cf0f940c3 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/dept_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/dept_dao.py
@@ -1,6 +1,6 @@
from collections.abc import Sequence
-from sqlalchemy import ColumnElement, bindparam, func, select, update
+from sqlalchemy import ColumnElement, bindparam, func, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.util import immutabledict
@@ -26,7 +26,7 @@ async def get_dept_by_id(cls, db: AsyncSession, dept_id: int) -> SysDept | None:
return dept_info
@classmethod
- async def get_dept_detail_by_id(cls, db: AsyncSession, dept_id: int) -> SysDept | None:
+ async def get_dept_detail_by_id(cls, db: AsyncSession, dept_id: int | None) -> SysDept | None:
"""
根据部门id获取部门详细信息。
@@ -34,6 +34,8 @@ async def get_dept_detail_by_id(cls, db: AsyncSession, dept_id: int) -> SysDept
:param dept_id: 部门id
:return: 部门信息对象
"""
+ if dept_id is None:
+ return None
dept_info = (
(await db.execute(select(SysDept).where(SysDept.dept_id == dept_id, SysDept.del_flag == '0')))
.scalars()
@@ -55,8 +57,8 @@ async def get_dept_detail_by_info(cls, db: AsyncSession, dept: DeptModel) -> Sys
(
await db.execute(
select(SysDept).where(
- SysDept.parent_id == dept.parent_id if dept.parent_id else True,
- SysDept.dept_name == dept.dept_name if dept.dept_name else True,
+ SysDept.parent_id == dept.parent_id if dept.parent_id else true(),
+ SysDept.dept_name == dept.dept_name if dept.dept_name else true(),
SysDept.del_flag == '0',
)
)
@@ -136,7 +138,7 @@ async def get_dept_list_for_tree(
.where(
SysDept.status == '0',
SysDept.del_flag == '0',
- SysDept.dept_name.like(f'%{dept_info.dept_name}%') if dept_info.dept_name else True,
+ SysDept.dept_name.like(f'%{dept_info.dept_name}%') if dept_info.dept_name else true(),
data_scope_sql,
)
.order_by(SysDept.order_num)
@@ -167,9 +169,9 @@ async def get_dept_list(
select(SysDept)
.where(
SysDept.del_flag == '0',
- SysDept.dept_id == page_object.dept_id if page_object.dept_id is not None else True,
- SysDept.status == page_object.status if page_object.status else True,
- SysDept.dept_name.like(f'%{page_object.dept_name}%') if page_object.dept_name else True,
+ SysDept.dept_id == page_object.dept_id if page_object.dept_id is not None else true(),
+ SysDept.status == page_object.status if page_object.status else true(),
+ SysDept.dept_name.like(f'%{page_object.dept_name}%') if page_object.dept_name else true(),
data_scope_sql,
)
.order_by(SysDept.order_num)
@@ -240,7 +242,8 @@ async def update_dept_sort_dao(cls, db: AsyncSession, dept_sort_list: list[dict[
:param dept_sort_list: 部门id与显示顺序列表
"""
await db.execute(
- update(SysDept.__table__)
+ SysDept.get_table()
+ .update()
.where(SysDept.dept_id == bindparam('_dept_id'))
.values(order_num=bindparam('_order_num')),
[{'_dept_id': item['dept_id'], '_order_num': item['order_num']} for item in dept_sort_list],
@@ -269,7 +272,7 @@ async def delete_dept_dao(cls, db: AsyncSession, dept: DeptModel) -> None:
)
@classmethod
- async def count_normal_children_dept_dao(cls, db: AsyncSession, dept_id: int) -> int | None:
+ async def count_normal_children_dept_dao(cls, db: AsyncSession, dept_id: int) -> int:
"""
根据部门id查询查询所有子部门(正常状态)的数量。
@@ -283,12 +286,12 @@ async def count_normal_children_dept_dao(cls, db: AsyncSession, dept_id: int) ->
.select_from(SysDept)
.where(SysDept.status == '0', SysDept.del_flag == '0', func.find_in_set(dept_id, SysDept.ancestors))
)
- ).scalar()
+ ).scalar_one()
return normal_children_dept_count
@classmethod
- async def count_children_dept_dao(cls, db: AsyncSession, dept_id: int) -> int | None:
+ async def count_children_dept_dao(cls, db: AsyncSession, dept_id: int) -> int:
"""
根据部门id查询查询所有子部门(所有状态)的数量。
@@ -303,12 +306,12 @@ async def count_children_dept_dao(cls, db: AsyncSession, dept_id: int) -> int |
.where(SysDept.del_flag == '0', SysDept.parent_id == dept_id)
.limit(1)
)
- ).scalar()
+ ).scalar_one()
return children_dept_count
@classmethod
- async def count_dept_user_dao(cls, db: AsyncSession, dept_id: int) -> int | None:
+ async def count_dept_user_dao(cls, db: AsyncSession, dept_id: int) -> int:
"""
根据部门id查询查询部门下的用户数量。
@@ -320,6 +323,6 @@ async def count_dept_user_dao(cls, db: AsyncSession, dept_id: int) -> int | None
await db.execute(
select(func.count('*')).select_from(SysUser).where(SysUser.dept_id == dept_id, SysUser.del_flag == '0')
)
- ).scalar()
+ ).scalar_one()
return dept_user_count
diff --git a/ruoyi-fastapi-backend/module_admin/dao/dict_dao.py b/ruoyi-fastapi-backend/module_admin/dao/dict_dao.py
index e896e0fd0..b5acc5ecd 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/dict_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/dict_dao.py
@@ -1,7 +1,7 @@
from collections.abc import Sequence
from typing import Any
-from sqlalchemy import and_, delete, func, select, update
+from sqlalchemy import and_, delete, func, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
@@ -41,8 +41,8 @@ async def get_dict_type_detail_by_info(cls, db: AsyncSession, dict_type: DictTyp
(
await db.execute(
select(SysDictType).where(
- SysDictType.dict_type == dict_type.dict_type if dict_type.dict_type else True,
- SysDictType.dict_name == dict_type.dict_name if dict_type.dict_name else True,
+ SysDictType.dict_type == dict_type.dict_type if dict_type.dict_type else true(),
+ SysDictType.dict_name == dict_type.dict_name if dict_type.dict_name else true(),
)
)
)
@@ -82,11 +82,11 @@ async def get_dict_type_list(
query = (
select(SysDictType)
.where(
- SysDictType.dict_name.like(f'%{query_object.dict_name}%') if query_object.dict_name else True,
- SysDictType.dict_type.like(f'%{query_object.dict_type}%') if query_object.dict_type else True,
- SysDictType.status == query_object.status if query_object.status else True,
- SysDictType.create_time >= time_range[0] if time_range and time_range[0] is not None else True,
- SysDictType.create_time < time_range[1] if time_range and time_range[1] is not None else True,
+ SysDictType.dict_name.like(f'%{query_object.dict_name}%') if query_object.dict_name else true(),
+ SysDictType.dict_type.like(f'%{query_object.dict_type}%') if query_object.dict_type else true(),
+ SysDictType.status == query_object.status if query_object.status else true(),
+ SysDictType.create_time >= time_range[0] if time_range and time_range[0] is not None else true(),
+ SysDictType.create_time < time_range[1] if time_range and time_range[1] is not None else true(),
)
.order_by(SysDictType.dict_id)
.distinct()
@@ -200,9 +200,9 @@ async def get_dict_data_list(
query = (
select(SysDictData)
.where(
- SysDictData.dict_type == query_object.dict_type if query_object.dict_type else True,
- SysDictData.dict_label.like(f'%{query_object.dict_label}%') if query_object.dict_label else True,
- SysDictData.status == query_object.status if query_object.status else True,
+ SysDictData.dict_type == query_object.dict_type if query_object.dict_type else true(),
+ SysDictData.dict_label.like(f'%{query_object.dict_label}%') if query_object.dict_label else true(),
+ SysDictData.status == query_object.status if query_object.status else true(),
)
.order_by(SysDictData.dict_sort)
.distinct()
@@ -227,7 +227,7 @@ async def query_dict_data_list(cls, db: AsyncSession, dict_type: str) -> Sequenc
await db.execute(
select(SysDictData)
.select_from(SysDictType)
- .where(SysDictType.dict_type == dict_type if dict_type else True, SysDictType.status == '0')
+ .where(SysDictType.dict_type == dict_type if dict_type else true(), SysDictType.status == '0')
.join(
SysDictData,
and_(SysDictType.dict_type == SysDictData.dict_type, SysDictData.status == '0'),
@@ -290,7 +290,7 @@ async def delete_dict_data_dao(cls, db: AsyncSession, dict_data: DictDataModel)
await db.execute(delete(SysDictData).where(SysDictData.dict_code.in_([dict_data.dict_code])))
@classmethod
- async def count_dict_data_dao(cls, db: AsyncSession, dict_type: str) -> int | None:
+ async def count_dict_data_dao(cls, db: AsyncSession, dict_type: str) -> int:
"""
根据字典类型查询字典类型关联的字典数据数量。
@@ -300,6 +300,6 @@ async def count_dict_data_dao(cls, db: AsyncSession, dict_type: str) -> int | No
"""
dict_data_count = (
await db.execute(select(func.count('*')).select_from(SysDictData).where(SysDictData.dict_type == dict_type))
- ).scalar()
+ ).scalar_one()
return dict_data_count
diff --git a/ruoyi-fastapi-backend/module_admin/dao/file_access_dao.py b/ruoyi-fastapi-backend/module_admin/dao/file_access_dao.py
index 32eb7d7a2..edabdbaf3 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/file_access_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/file_access_dao.py
@@ -1,7 +1,8 @@
+from collections.abc import Sequence
from datetime import datetime
from typing import Any
-from sqlalchemy import ColumnElement, delete, or_, select
+from sqlalchemy import ColumnElement, Row, delete, or_, select, true
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
@@ -142,7 +143,7 @@ async def get_acl_subject_name_map(
:param dept_data_scope_sql: 部门数据权限对应的查询sql语句
:return: 主体名称映射
"""
- subject_name_map = {}
+ subject_name_map: dict[tuple[str, int], str] = {}
user_ids = subject_ids.get('user', set())
if user_ids:
user_rows = (
@@ -186,7 +187,9 @@ async def get_acl_subject_name_map(
)
)
).all()
- subject_name_map.update({('dept', dept_id): dept_name for dept_id, dept_name in dept_rows})
+ subject_name_map.update(
+ {('dept', dept_id): dept_name or f'部门({dept_id})' for dept_id, dept_name in dept_rows}
+ )
return subject_name_map
@@ -219,7 +222,7 @@ async def search_acl_subjects(
user_data_scope_sql,
or_(SysUser.user_name.like(keyword_pattern), SysUser.nick_name.like(keyword_pattern))
if keyword
- else True,
+ else true(),
)
rows = (await db.execute(query.order_by(SysUser.user_id).limit(limit))).all()
return [
@@ -237,7 +240,7 @@ async def search_acl_subjects(
SysRole.role_id != 1,
SysRole.status == '0',
SysRole.del_flag == '0',
- SysRole.role_name.like(keyword_pattern) if keyword else True,
+ SysRole.role_name.like(keyword_pattern) if keyword else true(),
)
rows = (await db.execute(query.order_by(SysRole.role_id))).all()
rows = await cls._filter_role_rows_by_data_scope(db, rows, user_data_scope_sql)
@@ -248,18 +251,20 @@ async def search_acl_subjects(
SysDept.status == '0',
SysDept.del_flag == '0',
dept_data_scope_sql,
- SysDept.dept_name.like(keyword_pattern) if keyword else True,
+ SysDept.dept_name.like(keyword_pattern) if keyword else true(),
)
rows = (await db.execute(query.order_by(SysDept.order_num, SysDept.dept_id).limit(limit))).all()
- return [{'subject_id': dept_id, 'subject_name': dept_name} for dept_id, dept_name in rows]
+ return [
+ {'subject_id': dept_id, 'subject_name': dept_name or f'部门({dept_id})'} for dept_id, dept_name in rows
+ ]
@classmethod
async def _filter_role_rows_by_data_scope(
cls,
db: AsyncSession,
- role_rows: list[Any],
+ role_rows: Sequence[Row[int, str] | tuple[int, str]],
user_data_scope_sql: ColumnElement,
- ) -> list[Any]:
+ ) -> list[tuple[int, str]]:
"""
过滤包含数据权限范围外成员的角色。
@@ -302,9 +307,9 @@ async def _filter_role_rows_by_data_scope(
visible_member_ids.setdefault(role_id, set()).add(user_id)
return [
- role_row
- for role_row in role_rows
- if all_member_ids.get(role_row[0], set()).issubset(visible_member_ids.get(role_row[0], set()))
+ (role_id, role_name)
+ for role_id, role_name in role_rows
+ if all_member_ids.get(role_id, set()).issubset(visible_member_ids.get(role_id, set()))
]
@@ -347,11 +352,11 @@ async def get_file_access_log_list(
select(SysFileAccessLog)
.where(
SysFileAccessLog.file_id == file_id,
- SysFileAccessLog.action == query_object.action if query_object.action else True,
- SysFileAccessLog.result == query_object.result if query_object.result else True,
- SysFileAccessLog.actor_name.like(f'%{query_object.actor_name}%') if query_object.actor_name else True,
- SysFileAccessLog.access_time >= time_range[0] if time_range and time_range[0] is not None else True,
- SysFileAccessLog.access_time <= time_range[1] if time_range and time_range[1] is not None else True,
+ SysFileAccessLog.action == query_object.action if query_object.action else true(),
+ SysFileAccessLog.result == query_object.result if query_object.result else true(),
+ SysFileAccessLog.actor_name.like(f'%{query_object.actor_name}%') if query_object.actor_name else true(),
+ SysFileAccessLog.access_time >= time_range[0] if time_range and time_range[0] is not None else true(),
+ SysFileAccessLog.access_time <= time_range[1] if time_range and time_range[1] is not None else true(),
)
.order_by(SysFileAccessLog.access_time.desc(), SysFileAccessLog.audit_id.desc())
)
diff --git a/ruoyi-fastapi-backend/module_admin/dao/file_business_dao.py b/ruoyi-fastapi-backend/module_admin/dao/file_business_dao.py
index 1232badd2..26decc269 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/file_business_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/file_business_dao.py
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import Any, Literal
-from sqlalchemy import ColumnElement, and_, delete, exists, func, or_, select, update
+from sqlalchemy import ColumnElement, and_, delete, exists, func, literal, or_, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
@@ -275,7 +275,7 @@ async def get_file_retention_policy_by_business_type(
await db.execute(
select(SysFileRetentionPolicy).where(
SysFileRetentionPolicy.business_type == business_type,
- SysFileRetentionPolicy.status == '0' if enabled_only else True,
+ SysFileRetentionPolicy.status == '0' if enabled_only else true(),
)
)
)
@@ -380,7 +380,7 @@ async def get_missing_notice_candidates(
SysFileInfo.expire_time.is_not(None),
expire_condition,
~current_notice_exists,
- file_data_scope_sql,
+ literal(file_data_scope_sql) if isinstance(file_data_scope_sql, bool) else file_data_scope_sql,
)
.order_by(SysFileInfo.expire_time, SysFileInfo.file_id)
.limit(batch_size)
@@ -442,7 +442,7 @@ async def invalidate_changed_expire_time_notices(
:param expire_time: 文件当前到期时间
"""
expire_condition = (
- True
+ true()
if expire_time is None
else or_(
SysFileRetentionNotice.expire_time != expire_time,
@@ -518,9 +518,9 @@ async def get_file_retention_notice_list(
file_data_scope_sql,
SysFileInfo.original_name.like(f'%{query_object.original_name}%')
if query_object.original_name
- else True,
- SysFileRetentionNotice.notice_type == query_object.notice_type if query_object.notice_type else True,
- SysFileRetentionNotice.status == query_object.status if query_object.status else True,
+ else true(),
+ SysFileRetentionNotice.notice_type == query_object.notice_type if query_object.notice_type else true(),
+ SysFileRetentionNotice.status == query_object.status if query_object.status else true(),
)
.order_by(
SysFileRetentionNotice.status,
diff --git a/ruoyi-fastapi-backend/module_admin/dao/file_info_dao.py b/ruoyi-fastapi-backend/module_admin/dao/file_info_dao.py
index ead1999c5..60d3e925d 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/file_info_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/file_info_dao.py
@@ -1,10 +1,11 @@
from datetime import datetime, timedelta
from typing import Any
-from sqlalchemy import ColumnElement, case, delete, exists, func, or_, select, update
+from sqlalchemy import ColumnElement, case, delete, exists, func, or_, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
+from config.database import execute_rowcount
from module_admin.entity.do.dept_do import SysDept
from module_admin.entity.do.file_do import (
SysFileAcl,
@@ -73,7 +74,7 @@ async def get_file_info_by_id(
SysFileInfo.file_id == file_id,
SysFileInfo.status == 'active',
SysFileInfo.del_flag == '0',
- file_data_scope_sql if file_data_scope_sql is not None else True,
+ file_data_scope_sql if file_data_scope_sql is not None else true(),
)
)
)
@@ -172,12 +173,14 @@ async def get_reconcile_run_list(
SysFileReconcileRun.error_message,
)
.where(
- SysFileReconcileRun.status == query_object.status if query_object.status else True,
- SysFileReconcileRun.trigger_type == query_object.trigger_type if query_object.trigger_type else True,
+ SysFileReconcileRun.status == query_object.status if query_object.status else true(),
+ SysFileReconcileRun.trigger_type == query_object.trigger_type if query_object.trigger_type else true(),
)
.order_by(SysFileReconcileRun.started_time.desc(), SysFileReconcileRun.run_id.desc())
)
- return await PageUtil.paginate(db, query, query_object.page_num, query_object.page_size, is_page)
+ return await PageUtil.paginate(
+ db, query, query_object.page_num, query_object.page_size, is_page, as_mappings=True
+ )
@classmethod
async def get_all_local_file_infos(cls, db: AsyncSession) -> list[dict[str, Any]]:
@@ -291,7 +294,8 @@ async def resolve_disappeared_issues(
:param current_time: 当前时间
:return: 自动关闭数量
"""
- result = await db.execute(
+ return await execute_rowcount(
+ db,
update(SysFileReconcileIssue)
.where(
SysFileReconcileIssue.status.in_(['open', 'ignored']),
@@ -303,9 +307,8 @@ async def resolve_disappeared_issues(
handle_reason='异常在后续完整扫描中未再次出现',
handled_by='system',
handled_time=current_time,
- )
+ ),
)
- return int(result.rowcount or 0)
@classmethod
async def finish_reconcile_run(
@@ -367,7 +370,7 @@ async def get_reconcile_issue_list(
:param is_page: 是否分页
:return: 对账异常列表
"""
- keyword_condition: ColumnElement | bool = True
+ keyword_condition: ColumnElement[bool] = true()
if query_object.keyword:
keyword = f'%{query_object.keyword}%'
keyword_condition = or_(
@@ -383,9 +386,9 @@ async def get_reconcile_issue_list(
)
.outerjoin(SysFileInfo, SysFileInfo.file_id == SysFileReconcileIssue.file_id)
.where(
- SysFileReconcileIssue.issue_type == query_object.issue_type if query_object.issue_type else True,
- SysFileReconcileIssue.severity == query_object.severity if query_object.severity else True,
- SysFileReconcileIssue.status == query_object.status if query_object.status else True,
+ SysFileReconcileIssue.issue_type == query_object.issue_type if query_object.issue_type else true(),
+ SysFileReconcileIssue.severity == query_object.severity if query_object.severity else true(),
+ SysFileReconcileIssue.status == query_object.status if query_object.status else true(),
keyword_condition,
)
.order_by(
@@ -561,7 +564,7 @@ async def get_file_info_detail_by_id(
await db.execute(
select(SysFileInfo).where(
SysFileInfo.file_id == file_id,
- file_data_scope_sql if file_data_scope_sql is not None else True,
+ file_data_scope_sql if file_data_scope_sql is not None else true(),
)
)
)
@@ -592,7 +595,7 @@ async def get_file_info_by_id_for_update(
SysFileInfo.file_id == file_id,
SysFileInfo.status == 'active',
SysFileInfo.del_flag == '0',
- file_data_scope_sql if file_data_scope_sql is not None else True,
+ file_data_scope_sql if file_data_scope_sql is not None else true(),
)
.with_for_update()
)
@@ -624,7 +627,7 @@ async def get_file_infos_by_ids_for_update(
SysFileInfo.file_id.in_(file_ids),
SysFileInfo.status == 'active',
SysFileInfo.del_flag == '0',
- file_data_scope_sql if file_data_scope_sql is not None else True,
+ file_data_scope_sql if file_data_scope_sql is not None else true(),
)
.order_by(SysFileInfo.file_id)
.with_for_update()
@@ -657,7 +660,7 @@ async def get_deleted_file_infos_by_ids_for_update(
SysFileInfo.file_id.in_(file_ids),
SysFileInfo.status == 'deleted',
SysFileInfo.del_flag == '1',
- file_data_scope_sql if file_data_scope_sql is not None else True,
+ file_data_scope_sql if file_data_scope_sql is not None else true(),
)
.order_by(SysFileInfo.file_id)
.with_for_update()
@@ -690,7 +693,7 @@ async def get_purgeable_file_infos_by_ids_for_update(
SysFileInfo.file_id.in_(file_ids),
SysFileInfo.status.in_(['deleted', 'purging']),
SysFileInfo.del_flag == '1',
- file_data_scope_sql if file_data_scope_sql is not None else True,
+ file_data_scope_sql if file_data_scope_sql is not None else true(),
)
.order_by(SysFileInfo.file_id)
.with_for_update()
@@ -944,7 +947,7 @@ def _get_file_info_query_conditions(
cls,
query_object: FileInfoPageQueryModel,
current_time: datetime,
- ) -> list[ColumnElement | bool]:
+ ) -> list[ColumnElement[bool]]:
"""
构建文件管理查询条件。
@@ -954,7 +957,7 @@ def _get_file_info_query_conditions(
"""
expiring_time = current_time + timedelta(days=cls.FILE_EXPIRING_DAYS)
time_range = TimezoneUtil.rfc3339_range_to_utc(query_object.begin_time, query_object.end_time)
- expiration_condition: ColumnElement | bool = True
+ expiration_condition: ColumnElement[bool] = true()
if query_object.expiration_status == 'permanent':
expiration_condition = SysFileInfo.expire_time.is_(None)
elif query_object.expiration_status == 'expired':
@@ -964,20 +967,20 @@ def _get_file_info_query_conditions(
elif query_object.expiration_status == 'valid':
expiration_condition = SysFileInfo.expire_time > expiring_time
return [
- SysFileInfo.original_name.like(f'%{query_object.original_name}%') if query_object.original_name else True,
- SysFileInfo.access_type == query_object.access_type if query_object.access_type else True,
- SysFileInfo.status == query_object.status if query_object.status else True,
- SysFileInfo.create_by.like(f'%{query_object.create_by}%') if query_object.create_by else True,
+ SysFileInfo.original_name.like(f'%{query_object.original_name}%') if query_object.original_name else true(),
+ SysFileInfo.access_type == query_object.access_type if query_object.access_type else true(),
+ SysFileInfo.status == query_object.status if query_object.status else true(),
+ SysFileInfo.create_by.like(f'%{query_object.create_by}%') if query_object.create_by else true(),
or_(
SysUser.user_name.like(f'%{query_object.owner_name}%'),
SysUser.nick_name.like(f'%{query_object.owner_name}%'),
)
if query_object.owner_name
- else True,
- SysFileInfo.dept_id == query_object.dept_id if query_object.dept_id else True,
+ else true(),
+ SysFileInfo.dept_id == query_object.dept_id if query_object.dept_id else true(),
expiration_condition,
- SysFileInfo.create_time >= time_range[0] if time_range and time_range[0] is not None else True,
- SysFileInfo.create_time <= time_range[1] if time_range and time_range[1] is not None else True,
+ SysFileInfo.create_time >= time_range[0] if time_range and time_range[0] is not None else true(),
+ SysFileInfo.create_time <= time_range[1] if time_range and time_range[1] is not None else true(),
]
@classmethod
diff --git a/ruoyi-fastapi-backend/module_admin/dao/job_dao.py b/ruoyi-fastapi-backend/module_admin/dao/job_dao.py
index 47484b748..570db4879 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/job_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/job_dao.py
@@ -1,7 +1,7 @@
from collections.abc import Sequence
from typing import Any
-from sqlalchemy import delete, select, update
+from sqlalchemy import delete, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
@@ -65,9 +65,9 @@ async def get_job_list(
query = (
select(SysJob)
.where(
- SysJob.job_name.like(f'%{query_object.job_name}%') if query_object.job_name else True,
- SysJob.job_group == query_object.job_group if query_object.job_group else True,
- SysJob.status == query_object.status if query_object.status else True,
+ SysJob.job_name.like(f'%{query_object.job_name}%') if query_object.job_name else true(),
+ SysJob.job_group == query_object.job_group if query_object.job_group else true(),
+ SysJob.status == query_object.status if query_object.status else true(),
)
.order_by(SysJob.job_id)
)
diff --git a/ruoyi-fastapi-backend/module_admin/dao/job_log_dao.py b/ruoyi-fastapi-backend/module_admin/dao/job_log_dao.py
index ccc71ff95..59b87f0af 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/job_log_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/job_log_dao.py
@@ -1,6 +1,6 @@
from typing import Any
-from sqlalchemy import delete, desc, select
+from sqlalchemy import delete, desc, select, true
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Session
@@ -32,13 +32,13 @@ async def get_job_log_list(
query = (
select(SysJobLog)
.where(
- SysJobLog.job_id == query_object.job_id if query_object.job_id is not None else True,
- SysJobLog.execution_id == query_object.execution_id if query_object.execution_id else True,
- SysJobLog.job_name.like(f'%{query_object.job_name}%') if query_object.job_name else True,
- SysJobLog.job_group == query_object.job_group if query_object.job_group else True,
- SysJobLog.status == query_object.status if query_object.status else True,
- SysJobLog.create_time >= time_range[0] if time_range and time_range[0] is not None else True,
- SysJobLog.create_time < time_range[1] if time_range and time_range[1] is not None else True,
+ SysJobLog.job_id == query_object.job_id if query_object.job_id is not None else true(),
+ SysJobLog.execution_id == query_object.execution_id if query_object.execution_id else true(),
+ SysJobLog.job_name.like(f'%{query_object.job_name}%') if query_object.job_name else true(),
+ SysJobLog.job_group == query_object.job_group if query_object.job_group else true(),
+ SysJobLog.status == query_object.status if query_object.status else true(),
+ SysJobLog.create_time >= time_range[0] if time_range and time_range[0] is not None else true(),
+ SysJobLog.create_time < time_range[1] if time_range and time_range[1] is not None else true(),
)
.order_by(desc(SysJobLog.create_time))
)
diff --git a/ruoyi-fastapi-backend/module_admin/dao/job_runtime_dao.py b/ruoyi-fastapi-backend/module_admin/dao/job_runtime_dao.py
index e7428329e..95c39712b 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/job_runtime_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/job_runtime_dao.py
@@ -2,7 +2,7 @@
from typing import Any
from uuid import uuid4
-from sqlalchemy import select, update
+from sqlalchemy import select, true, update
from sqlalchemy.dialects.mysql import insert as mysql_insert
from sqlalchemy.dialects.postgresql import insert as postgres_insert
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
@@ -56,7 +56,7 @@ async def ensure_state(db: AsyncSession, job_id: int) -> None:
await db.execute(statement)
@classmethod
- async def lock_job(cls, db: AsyncSession, job_id: int) -> tuple[SysJob | None, SysJobSync | None]:
+ async def lock_job(cls, db: AsyncSession, job_id: int) -> tuple[SysJob | None, SysJobSync]:
"""
按同步状态、任务记录的固定顺序加锁,并为已有任务建立初始状态。
@@ -257,10 +257,10 @@ async def execution_page(db: AsyncSession, query: JobExecutionQueryModel) -> Pag
statement = (
select(*fields, SysJobExecution.job_snapshot['jobName'].as_string().label('job_name'))
.where(
- SysJobExecution.job_id == query.job_id if query.job_id is not None else True,
- SysJobExecution.execution_id == query.execution_id if query.execution_id else True,
- SysJobExecution.status == query.status if query.status else True,
- SysJobExecution.source == query.source if query.source else True,
+ SysJobExecution.job_id == query.job_id if query.job_id is not None else true(),
+ SysJobExecution.execution_id == query.execution_id if query.execution_id else true(),
+ SysJobExecution.status == query.status if query.status else true(),
+ SysJobExecution.source == query.source if query.source else true(),
)
.order_by(SysJobExecution.create_time.desc(), SysJobExecution.execution_id.desc())
)
@@ -291,8 +291,8 @@ async def sync_page(db: AsyncSession, query: JobSyncQueryModel) -> PageModel:
statement = (
select(*fields)
.where(
- SysJobSync.job_id == query.job_id if query.job_id is not None else True,
- SysJobSync.sync_status == query.sync_status if query.sync_status else True,
+ SysJobSync.job_id == query.job_id if query.job_id is not None else true(),
+ SysJobSync.sync_status == query.sync_status if query.sync_status else true(),
)
.order_by(SysJobSync.update_time.desc(), SysJobSync.job_id.desc())
)
diff --git a/ruoyi-fastapi-backend/module_admin/dao/log_dao.py b/ruoyi-fastapi-backend/module_admin/dao/log_dao.py
index 2c7a20441..23751b59d 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/log_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/log_dao.py
@@ -1,6 +1,6 @@
from typing import Any
-from sqlalchemy import asc, delete, desc, select
+from sqlalchemy import ColumnElement, Table, delete, select, true
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
@@ -11,6 +11,26 @@
from utils.time_util import TimezoneUtil
+def _log_order(
+ table: Table,
+ query: OperLogPageQueryModel | LoginLogPageQueryModel,
+ time_column: str,
+) -> ColumnElement:
+ """
+ 根据查询参数选择日志排序列,缺少有效排序条件时按日志时间倒序。
+
+ :param table: 日志表
+ :param query: 含排序字段和方向的日志查询参数
+ :param time_column: 日志时间列名
+ :return: SQL 排序表达式
+ """
+ if query.order_by_column and query.is_asc:
+ column = table.c.get(SnakeCaseUtil.camel_to_snake(query.order_by_column))
+ if column is not None:
+ return column.asc() if query.is_asc == 'ascending' else column.desc()
+ return table.c[time_column].desc()
+
+
class OperationLogDao:
"""操作日志管理模块数据库操作层。"""
@@ -26,26 +46,19 @@ async def get_operation_log_list(
:param is_page: 是否开启分页
:return: 操作日志列表信息对象
"""
- if query_object.is_asc == 'ascending':
- order_by_column = asc(getattr(SysOperLog, SnakeCaseUtil.camel_to_snake(query_object.order_by_column), None))
- elif query_object.is_asc == 'descending':
- order_by_column = desc(
- getattr(SysOperLog, SnakeCaseUtil.camel_to_snake(query_object.order_by_column), None)
- )
- else:
- order_by_column = desc(SysOperLog.oper_time)
+ order_by_column = _log_order(SysOperLog.get_table(), query_object, 'oper_time')
time_range = TimezoneUtil.local_date_strings_to_utc(
query_object.begin_time, query_object.end_time, timezone_name=TimezoneUtil.get_request_timezone()
)
query = (
select(SysOperLog)
.where(
- SysOperLog.title.like(f'%{query_object.title}%') if query_object.title else True,
- SysOperLog.oper_name.like(f'%{query_object.oper_name}%') if query_object.oper_name else True,
- SysOperLog.business_type == query_object.business_type if query_object.business_type else True,
- SysOperLog.status == query_object.status if query_object.status else True,
- SysOperLog.oper_time >= time_range[0] if time_range and time_range[0] is not None else True,
- SysOperLog.oper_time < time_range[1] if time_range and time_range[1] is not None else True,
+ SysOperLog.title.like(f'%{query_object.title}%') if query_object.title else true(),
+ SysOperLog.oper_name.like(f'%{query_object.oper_name}%') if query_object.oper_name else true(),
+ SysOperLog.business_type == query_object.business_type if query_object.business_type else true(),
+ SysOperLog.status == query_object.status if query_object.status else true(),
+ SysOperLog.oper_time >= time_range[0] if time_range and time_range[0] is not None else true(),
+ SysOperLog.oper_time < time_range[1] if time_range and time_range[1] is not None else true(),
)
.distinct()
.order_by(order_by_column)
@@ -106,27 +119,18 @@ async def get_login_log_list(
:param is_page: 是否开启分页
:return: 登录日志列表信息对象
"""
- if query_object.is_asc == 'ascending':
- order_by_column = asc(
- getattr(SysLogininfor, SnakeCaseUtil.camel_to_snake(query_object.order_by_column), None)
- )
- elif query_object.is_asc == 'descending':
- order_by_column = desc(
- getattr(SysLogininfor, SnakeCaseUtil.camel_to_snake(query_object.order_by_column), None)
- )
- else:
- order_by_column = desc(SysLogininfor.login_time)
+ order_by_column = _log_order(SysLogininfor.get_table(), query_object, 'login_time')
time_range = TimezoneUtil.local_date_strings_to_utc(
query_object.begin_time, query_object.end_time, timezone_name=TimezoneUtil.get_request_timezone()
)
query = (
select(SysLogininfor)
.where(
- SysLogininfor.ipaddr.like(f'%{query_object.ipaddr}%') if query_object.ipaddr else True,
- SysLogininfor.user_name.like(f'%{query_object.user_name}%') if query_object.user_name else True,
- SysLogininfor.status == query_object.status if query_object.status else True,
- SysLogininfor.login_time >= time_range[0] if time_range and time_range[0] is not None else True,
- SysLogininfor.login_time < time_range[1] if time_range and time_range[1] is not None else True,
+ SysLogininfor.ipaddr.like(f'%{query_object.ipaddr}%') if query_object.ipaddr else true(),
+ SysLogininfor.user_name.like(f'%{query_object.user_name}%') if query_object.user_name else true(),
+ SysLogininfor.status == query_object.status if query_object.status else true(),
+ SysLogininfor.login_time >= time_range[0] if time_range and time_range[0] is not None else true(),
+ SysLogininfor.login_time < time_range[1] if time_range and time_range[1] is not None else true(),
)
.distinct()
.order_by(order_by_column)
diff --git a/ruoyi-fastapi-backend/module_admin/dao/login_dao.py b/ruoyi-fastapi-backend/module_admin/dao/login_dao.py
index 70417beab..4d8dc5f2b 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/login_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/login_dao.py
@@ -1,29 +1,26 @@
-from sqlalchemy import Row, and_, select
+from sqlalchemy import Nullable, Row, Select, and_, select
from sqlalchemy.ext.asyncio import AsyncSession
from module_admin.entity.do.dept_do import SysDept
from module_admin.entity.do.user_do import SysUser
-async def login_by_account(db: AsyncSession, user_name: str) -> Row[tuple[SysUser, SysDept]] | None:
+async def login_by_account(db: AsyncSession, user_name: str) -> Row[SysUser, SysDept | None] | None:
"""
根据用户名查询用户信息。
:param db: orm对象
:param user_name: 用户名
- :return: 用户对象
+ :return: 用户及其有效部门,未匹配用户时返回 None
"""
- user = (
- await db.execute(
- select(SysUser, SysDept)
- .where(SysUser.user_name == user_name, SysUser.del_flag == '0')
- .join(
- SysDept,
- and_(SysUser.dept_id == SysDept.dept_id, SysDept.status == '0', SysDept.del_flag == '0'),
- isouter=True,
- )
- .distinct()
+ statement: Select[SysUser, SysDept | None] = (
+ select(SysUser, Nullable(SysDept))
+ .where(SysUser.user_name == user_name, SysUser.del_flag == '0')
+ .join(
+ SysDept,
+ and_(SysUser.dept_id == SysDept.dept_id, SysDept.status == '0', SysDept.del_flag == '0'),
+ isouter=True,
)
- ).first()
-
- return user
+ .distinct()
+ )
+ return (await db.execute(statement)).first()
diff --git a/ruoyi-fastapi-backend/module_admin/dao/menu_dao.py b/ruoyi-fastapi-backend/module_admin/dao/menu_dao.py
index 9e8c9d564..27d485e5c 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/menu_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/menu_dao.py
@@ -1,6 +1,6 @@
from collections.abc import Sequence
-from sqlalchemy import and_, bindparam, delete, func, or_, select, update
+from sqlalchemy import and_, bindparam, delete, func, or_, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.constant import MenuConstant
@@ -9,6 +9,7 @@
from module_admin.entity.do.role_do import SysRole, SysRoleMenu
from module_admin.entity.do.user_do import SysUser, SysUserRole
from module_admin.entity.vo.menu_vo import MenuModel, MenuQueryModel
+from module_admin.entity.vo.role_vo import RoleModel
class MenuDao:
@@ -40,9 +41,9 @@ async def get_menu_detail_by_info(cls, db: AsyncSession, menu: MenuModel) -> Sys
(
await db.execute(
select(SysMenu).where(
- SysMenu.parent_id == menu.parent_id if menu.parent_id else True,
- SysMenu.menu_name == menu.menu_name if menu.menu_name else True,
- SysMenu.menu_type == menu.menu_type if menu.menu_type else True,
+ SysMenu.parent_id == menu.parent_id if menu.parent_id else true(),
+ SysMenu.menu_name == menu.menu_name if menu.menu_name else true(),
+ SysMenu.menu_type == menu.menu_type if menu.menu_type else true(),
)
)
)
@@ -82,7 +83,9 @@ async def get_menus_by_path_or_route_name(cls, db: AsyncSession, path: str, rout
return menu_list
@classmethod
- async def get_menu_list_for_tree(cls, db: AsyncSession, user_id: int, role: list) -> Sequence[SysMenu]:
+ async def get_menu_list_for_tree(
+ cls, db: AsyncSession, user_id: int, role: Sequence[RoleModel | None] | None
+ ) -> Sequence[SysMenu]:
"""
根据角色信息获取所有在用菜单列表信息。
@@ -91,7 +94,7 @@ async def get_menu_list_for_tree(cls, db: AsyncSession, user_id: int, role: list
:param role: 用户角色列表信息
:return: 菜单列表信息
"""
- role_id_list = [item.role_id for item in role]
+ role_id_list = [item.role_id for item in role or () if item is not None]
if 1 in role_id_list:
menu_query_all = (
(await db.execute(select(SysMenu).where(SysMenu.status == '0').order_by(SysMenu.order_num).distinct()))
@@ -127,7 +130,7 @@ async def get_menu_list_for_tree(cls, db: AsyncSession, user_id: int, role: list
@classmethod
async def get_menu_list(
- cls, db: AsyncSession, page_object: MenuQueryModel, user_id: int, role: list
+ cls, db: AsyncSession, page_object: MenuQueryModel, user_id: int, role: Sequence[RoleModel | None] | None
) -> Sequence[SysMenu]:
"""
根据查询参数获取菜单列表信息。
@@ -138,15 +141,15 @@ async def get_menu_list(
:param role: 用户角色列表
:return: 菜单列表信息对象
"""
- role_id_list = [item.role_id for item in role]
+ role_id_list = [item.role_id for item in role or () if item is not None]
if 1 in role_id_list:
menu_query_all = (
(
await db.execute(
select(SysMenu)
.where(
- SysMenu.status == page_object.status if page_object.status else True,
- SysMenu.menu_name.like(f'%{page_object.menu_name}%') if page_object.menu_name else True,
+ SysMenu.status == page_object.status if page_object.status else true(),
+ SysMenu.menu_name.like(f'%{page_object.menu_name}%') if page_object.menu_name else true(),
)
.order_by(SysMenu.order_num)
.distinct()
@@ -175,8 +178,10 @@ async def get_menu_list(
SysMenu,
and_(
SysRoleMenu.menu_id == SysMenu.menu_id,
- SysMenu.status == page_object.status if page_object.status else True,
- SysMenu.menu_name.like(f'%{page_object.menu_name}%') if page_object.menu_name else True,
+ SysMenu.status == page_object.status if page_object.status else true(),
+ SysMenu.menu_name.like(f'%{page_object.menu_name}%')
+ if page_object.menu_name
+ else true(),
),
)
.order_by(SysMenu.order_num)
@@ -232,7 +237,8 @@ async def update_menu_sort_dao(cls, db: AsyncSession, menu_sort_list: list[dict[
:param menu_sort_list: 菜单ID与显示顺序列表
"""
await db.execute(
- update(SysMenu.__table__)
+ SysMenu.get_table()
+ .update()
.where(SysMenu.menu_id == bindparam('_menu_id'))
.values(order_num=bindparam('_order_num')),
[{'_menu_id': item['menu_id'], '_order_num': item['order_num']} for item in menu_sort_list],
@@ -249,7 +255,7 @@ async def delete_menu_dao(cls, db: AsyncSession, menu: MenuModel) -> None:
await db.execute(delete(SysMenu).where(SysMenu.menu_id.in_([menu.menu_id])))
@classmethod
- async def has_child_by_menu_id_dao(cls, db: AsyncSession, menu_id: int) -> int | None:
+ async def has_child_by_menu_id_dao(cls, db: AsyncSession, menu_id: int) -> int:
"""
根据菜单id查询菜单关联子菜单的数量。
@@ -259,12 +265,12 @@ async def has_child_by_menu_id_dao(cls, db: AsyncSession, menu_id: int) -> int |
"""
menu_count = (
await db.execute(select(func.count('*')).select_from(SysMenu).where(SysMenu.parent_id == menu_id))
- ).scalar()
+ ).scalar_one()
return menu_count
@classmethod
- async def check_menu_exist_role_dao(cls, db: AsyncSession, menu_id: int) -> int | None:
+ async def check_menu_exist_role_dao(cls, db: AsyncSession, menu_id: int) -> int:
"""
根据菜单id查询菜单关联角色数量。
@@ -274,6 +280,6 @@ async def check_menu_exist_role_dao(cls, db: AsyncSession, menu_id: int) -> int
"""
role_count = (
await db.execute(select(func.count('*')).select_from(SysRoleMenu).where(SysRoleMenu.menu_id == menu_id))
- ).scalar()
+ ).scalar_one()
return role_count
diff --git a/ruoyi-fastapi-backend/module_admin/dao/notice_dao.py b/ruoyi-fastapi-backend/module_admin/dao/notice_dao.py
index e1088b5a0..1be505bf8 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/notice_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/notice_dao.py
@@ -1,6 +1,6 @@
from typing import Any
-from sqlalchemy import and_, case, delete, func, or_, select, update
+from sqlalchemy import and_, case, delete, func, or_, select, true, update
from sqlalchemy.dialects.mysql import insert as mysql_insert
from sqlalchemy.dialects.postgresql import insert as postgresql_insert
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
@@ -74,11 +74,11 @@ async def get_notice_list(
query = (
select(SysNotice)
.where(
- SysNotice.notice_title.like(f'%{query_object.notice_title}%') if query_object.notice_title else True,
- SysNotice.create_by.like(f'%{query_object.create_by}%') if query_object.create_by else True,
- SysNotice.notice_type == query_object.notice_type if query_object.notice_type else True,
- SysNotice.create_time >= time_range[0] if time_range and time_range[0] is not None else True,
- SysNotice.create_time < time_range[1] if time_range and time_range[1] is not None else True,
+ SysNotice.notice_title.like(f'%{query_object.notice_title}%') if query_object.notice_title else true(),
+ SysNotice.create_by.like(f'%{query_object.create_by}%') if query_object.create_by else true(),
+ SysNotice.notice_type == query_object.notice_type if query_object.notice_type else true(),
+ SysNotice.create_time >= time_range[0] if time_range and time_range[0] is not None else true(),
+ SysNotice.create_time < time_range[1] if time_range and time_range[1] is not None else true(),
)
.order_by(SysNotice.notice_id.desc())
.distinct()
@@ -172,12 +172,14 @@ async def get_notice_read_user_list(
SysUser.nick_name.like(f'%{search_value}%'),
)
if search_value
- else True,
+ else true(),
)
.order_by(SysNoticeRead.read_time.desc())
)
- return await PageUtil.paginate(db, query, query_object.page_num, query_object.page_size, is_page)
+ return await PageUtil.paginate(
+ db, query, query_object.page_num, query_object.page_size, is_page, as_mappings=True
+ )
@classmethod
async def add_notice_reads(cls, db: AsyncSession, user_id: int, notice_ids: list[int]) -> None:
diff --git a/ruoyi-fastapi-backend/module_admin/dao/post_dao.py b/ruoyi-fastapi-backend/module_admin/dao/post_dao.py
index df9aa933c..bc3b500f3 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/post_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/post_dao.py
@@ -1,6 +1,6 @@
from typing import Any
-from sqlalchemy import delete, func, select, update
+from sqlalchemy import delete, func, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
@@ -56,9 +56,9 @@ async def get_post_detail_by_info(cls, db: AsyncSession, post: PostModel) -> Sys
(
await db.execute(
select(SysPost).where(
- SysPost.post_name == post.post_name if post.post_name else True,
- SysPost.post_code == post.post_code if post.post_code else True,
- SysPost.post_sort == post.post_sort if post.post_sort else True,
+ SysPost.post_name == post.post_name if post.post_name else true(),
+ SysPost.post_code == post.post_code if post.post_code else true(),
+ SysPost.post_sort == post.post_sort if post.post_sort else true(),
)
)
)
@@ -83,9 +83,9 @@ async def get_post_list(
query = (
select(SysPost)
.where(
- SysPost.post_code.like(f'%{query_object.post_code}%') if query_object.post_code else True,
- SysPost.post_name.like(f'%{query_object.post_name}%') if query_object.post_name else True,
- SysPost.status == query_object.status if query_object.status else True,
+ SysPost.post_code.like(f'%{query_object.post_code}%') if query_object.post_code else true(),
+ SysPost.post_name.like(f'%{query_object.post_name}%') if query_object.post_name else true(),
+ SysPost.status == query_object.status if query_object.status else true(),
)
.order_by(SysPost.post_sort)
.distinct()
@@ -135,7 +135,7 @@ async def delete_post_dao(cls, db: AsyncSession, post: PostModel) -> None:
await db.execute(delete(SysPost).where(SysPost.post_id.in_([post.post_id])))
@classmethod
- async def count_user_post_dao(cls, db: AsyncSession, post_id: int) -> int | None:
+ async def count_user_post_dao(cls, db: AsyncSession, post_id: int) -> int:
"""
根据岗位id查询岗位关联的用户数量。
@@ -145,6 +145,6 @@ async def count_user_post_dao(cls, db: AsyncSession, post_id: int) -> int | None
"""
user_post_count = (
await db.execute(select(func.count('*')).select_from(SysUserPost).where(SysUserPost.post_id == post_id))
- ).scalar()
+ ).scalar_one()
return user_post_count
diff --git a/ruoyi-fastapi-backend/module_admin/dao/role_dao.py b/ruoyi-fastapi-backend/module_admin/dao/role_dao.py
index a311a5308..786844b40 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/role_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/role_dao.py
@@ -1,7 +1,7 @@
from collections.abc import Sequence
from typing import Any
-from sqlalchemy import ColumnElement, and_, delete, desc, func, select, update
+from sqlalchemy import ColumnElement, and_, delete, desc, func, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
@@ -56,8 +56,8 @@ async def get_role_by_info(cls, db: AsyncSession, role: RoleModel) -> SysRole |
select(SysRole)
.where(
SysRole.del_flag == '0',
- SysRole.role_name == role.role_name if role.role_name else True,
- SysRole.role_key == role.role_key if role.role_key else True,
+ SysRole.role_name == role.role_name if role.role_name else true(),
+ SysRole.role_key == role.role_key if role.role_key else true(),
)
.order_by(desc(SysRole.create_time))
.distinct()
@@ -150,12 +150,12 @@ async def get_role_list(
.join(SysDept, SysDept.dept_id == SysUser.dept_id, isouter=True)
.where(
SysRole.del_flag == '0',
- SysRole.role_id == query_object.role_id if query_object.role_id is not None else True,
- SysRole.role_name.like(f'%{query_object.role_name}%') if query_object.role_name else True,
- SysRole.role_key.like(f'%{query_object.role_key}%') if query_object.role_key else True,
- SysRole.status == query_object.status if query_object.status else True,
- SysRole.create_time >= time_range[0] if time_range and time_range[0] is not None else True,
- SysRole.create_time < time_range[1] if time_range and time_range[1] is not None else True,
+ SysRole.role_id == query_object.role_id if query_object.role_id is not None else true(),
+ SysRole.role_name.like(f'%{query_object.role_name}%') if query_object.role_name else true(),
+ SysRole.role_key.like(f'%{query_object.role_key}%') if query_object.role_key else true(),
+ SysRole.status == query_object.status if query_object.status else true(),
+ SysRole.create_time >= time_range[0] if time_range and time_range[0] is not None else true(),
+ SysRole.create_time < time_range[1] if time_range and time_range[1] is not None else true(),
data_scope_sql,
)
.order_by(SysRole.role_sort)
@@ -208,7 +208,7 @@ async def delete_role_dao(cls, db: AsyncSession, role: RoleModel) -> None:
)
@classmethod
- async def get_role_menu_dao(cls, db: AsyncSession, role: RoleModel) -> Sequence[SysMenu]:
+ async def get_role_menu_dao(cls, db: AsyncSession, role: SysRole | RoleModel) -> Sequence[SysMenu]:
"""
根据角色id获取角色菜单关联列表信息。
@@ -232,7 +232,7 @@ async def get_role_menu_dao(cls, db: AsyncSession, role: RoleModel) -> Sequence[
)
)
if role.menu_check_strictly
- else True,
+ else true(),
)
.order_by(SysMenu.parent_id, SysMenu.order_num)
)
@@ -301,7 +301,7 @@ async def get_role_dept_dao(cls, db: AsyncSession, role: RoleModel) -> Sequence[
)
)
if role.dept_check_strictly
- else True,
+ else true(),
)
.order_by(SysDept.parent_id, SysDept.order_num)
)
@@ -320,7 +320,7 @@ async def add_role_dept_dao(cls, db: AsyncSession, role_dept: RoleDeptModel) ->
:param db: orm对象
:param role_dept: 用户角色部门关联对象
"""
- db_role_dept = SysRoleDept(**role_dept.dict())
+ db_role_dept = SysRoleDept(**role_dept.model_dump())
db.add(db_role_dept)
@classmethod
@@ -334,7 +334,7 @@ async def delete_role_dept_dao(cls, db: AsyncSession, role_dept: RoleDeptModel)
await db.execute(delete(SysRoleDept).where(SysRoleDept.role_id.in_([role_dept.role_id])))
@classmethod
- async def count_user_role_dao(cls, db: AsyncSession, role_id: int) -> int | None:
+ async def count_user_role_dao(cls, db: AsyncSession, role_id: int) -> int:
"""
根据角色id查询角色关联用户数量。
@@ -344,6 +344,6 @@ async def count_user_role_dao(cls, db: AsyncSession, role_id: int) -> int | None
"""
user_count = (
await db.execute(select(func.count('*')).select_from(SysUserRole).where(SysUserRole.role_id == role_id))
- ).scalar()
+ ).scalar_one()
return user_count
diff --git a/ruoyi-fastapi-backend/module_admin/dao/user_dao.py b/ruoyi-fastapi-backend/module_admin/dao/user_dao.py
index e9fb55071..e18c0593a 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/user_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/user_dao.py
@@ -1,7 +1,7 @@
from collections.abc import Sequence
-from typing import Any
+from typing import Any, TypedDict
-from sqlalchemy import ColumnElement, and_, delete, desc, func, or_, select, update
+from sqlalchemy import ColumnElement, and_, delete, desc, func, or_, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
@@ -24,6 +24,24 @@
from utils.time_util import TimezoneUtil
+class UserDetailRecord(TypedDict):
+ """
+ 用户详情查询返回的资料和关联记录。
+
+ :ivar user_basic_info: 用户基本资料,未找到时为空
+ :ivar user_dept_info: 用户所属部门
+ :ivar user_role_info: 用户角色
+ :ivar user_post_info: 用户岗位
+ :ivar user_menu_info: 用户可访问的菜单
+ """
+
+ user_basic_info: SysUser | None
+ user_dept_info: SysDept | None
+ user_role_info: Sequence[SysRole]
+ user_post_info: Sequence[SysPost]
+ user_menu_info: Sequence[SysMenu]
+
+
class UserDao:
"""用户管理模块数据库操作层。"""
@@ -78,9 +96,9 @@ async def get_user_by_info(cls, db: AsyncSession, user: UserModel) -> SysUser |
select(SysUser)
.where(
SysUser.del_flag == '0',
- SysUser.user_name == user.user_name if user.user_name else True,
- SysUser.phonenumber == user.phonenumber if user.phonenumber else True,
- SysUser.email == user.email if user.email else True,
+ SysUser.user_name == user.user_name if user.user_name else true(),
+ SysUser.phonenumber == user.phonenumber if user.phonenumber else true(),
+ SysUser.email == user.email if user.email else true(),
)
.order_by(desc(SysUser.create_time))
.distinct()
@@ -190,7 +208,7 @@ async def get_user_by_id(cls, db: AsyncSession, user_id: int, *, for_auth: bool
return results
@classmethod
- async def get_user_detail_by_id(cls, db: AsyncSession, user_id: int) -> dict[str, Any]:
+ async def get_user_detail_by_id(cls, db: AsyncSession, user_id: int) -> UserDetailRecord:
"""
根据user_id获取用户详细信息。
@@ -270,7 +288,7 @@ async def get_user_detail_by_id(cls, db: AsyncSession, user_id: int) -> dict[str
.scalars()
.all()
)
- results = {
+ return {
'user_basic_info': query_user_basic_info,
'user_dept_info': query_user_dept_info,
'user_role_info': query_user_role_info,
@@ -278,12 +296,10 @@ async def get_user_detail_by_id(cls, db: AsyncSession, user_id: int) -> dict[str
'user_menu_info': query_user_menu_info,
}
- return results
-
@classmethod
async def get_user_list(
cls, db: AsyncSession, query_object: UserPageQueryModel, data_scope_sql: ColumnElement, is_page: bool = False
- ) -> PageModel | list[list[dict[str, Any]]]:
+ ) -> PageModel | list[list[dict[str, Any] | None]]:
"""
根据查询参数获取用户列表信息。
@@ -307,16 +323,16 @@ async def get_user_list(
),
)
if query_object.dept_id
- else True,
- SysUser.user_id == query_object.user_id if query_object.user_id is not None else True,
- SysUser.user_name.like(f'%{query_object.user_name}%') if query_object.user_name else True,
- SysUser.nick_name.like(f'%{query_object.nick_name}%') if query_object.nick_name else True,
- SysUser.email.like(f'%{query_object.email}%') if query_object.email else True,
- SysUser.phonenumber.like(f'%{query_object.phonenumber}%') if query_object.phonenumber else True,
- SysUser.status == query_object.status if query_object.status else True,
- SysUser.sex == query_object.sex if query_object.sex else True,
- SysUser.create_time >= time_range[0] if time_range and time_range[0] is not None else True,
- SysUser.create_time < time_range[1] if time_range and time_range[1] is not None else True,
+ else true(),
+ SysUser.user_id == query_object.user_id if query_object.user_id is not None else true(),
+ SysUser.user_name.like(f'%{query_object.user_name}%') if query_object.user_name else true(),
+ SysUser.nick_name.like(f'%{query_object.nick_name}%') if query_object.nick_name else true(),
+ SysUser.email.like(f'%{query_object.email}%') if query_object.email else true(),
+ SysUser.phonenumber.like(f'%{query_object.phonenumber}%') if query_object.phonenumber else true(),
+ SysUser.status == query_object.status if query_object.status else true(),
+ SysUser.sex == query_object.sex if query_object.sex else true(),
+ SysUser.create_time >= time_range[0] if time_range and time_range[0] is not None else true(),
+ SysUser.create_time < time_range[1] if time_range and time_range[1] is not None else true(),
data_scope_sql,
)
.join(
@@ -327,7 +343,7 @@ async def get_user_list(
.order_by(SysUser.user_id)
.distinct()
)
- user_list: PageModel | list[list[dict[str, Any]]] = await PageUtil.paginate(
+ user_list: PageModel | list[list[dict[str, Any] | None]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -408,8 +424,8 @@ async def get_user_role_allocated_list_by_user_id(
.where(
SysRole.del_flag == '0',
SysRole.role_id != 1,
- SysRole.role_name == query_object.role_name if query_object.role_name else True,
- SysRole.role_key == query_object.role_key if query_object.role_key else True,
+ SysRole.role_name == query_object.role_name if query_object.role_name else true(),
+ SysRole.role_key == query_object.role_key if query_object.role_key else true(),
SysRole.role_id.in_(
select(SysUserRole.role_id).where(SysUserRole.user_id == query_object.user_id)
),
@@ -447,8 +463,8 @@ async def get_user_role_allocated_list_by_role_id(
.join(SysRole, SysRole.role_id == SysUserRole.role_id, isouter=True)
.where(
SysUser.del_flag == '0',
- SysUser.user_name == query_object.user_name if query_object.user_name else True,
- SysUser.phonenumber == query_object.phonenumber if query_object.phonenumber else True,
+ SysUser.user_name == query_object.user_name if query_object.user_name else true(),
+ SysUser.phonenumber == query_object.phonenumber if query_object.phonenumber else true(),
SysRole.role_id == query_object.role_id,
data_scope_sql,
)
@@ -484,8 +500,8 @@ async def get_user_role_unallocated_list_by_role_id(
.join(SysRole, SysRole.role_id == SysUserRole.role_id, isouter=True)
.where(
SysUser.del_flag == '0',
- SysUser.user_name == query_object.user_name if query_object.user_name else True,
- SysUser.phonenumber == query_object.phonenumber if query_object.phonenumber else True,
+ SysUser.user_name == query_object.user_name if query_object.user_name else true(),
+ SysUser.phonenumber == query_object.phonenumber if query_object.phonenumber else true(),
or_(SysRole.role_id != query_object.role_id, SysRole.role_id.is_(None)),
~SysUser.user_id.in_(
select(SysUser.user_id)
@@ -536,8 +552,8 @@ async def delete_user_role_by_user_and_role_dao(cls, db: AsyncSession, user_role
"""
await db.execute(
delete(SysUserRole).where(
- SysUserRole.user_id == user_role.user_id if user_role.user_id else True,
- SysUserRole.role_id == user_role.role_id if user_role.role_id else True,
+ SysUserRole.user_id == user_role.user_id if user_role.user_id else true(),
+ SysUserRole.role_id == user_role.role_id if user_role.role_id else true(),
)
)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/config_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/config_do.py
index c5f21e58f..e05d63f6e 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/config_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/config_do.py
@@ -1,4 +1,5 @@
-from sqlalchemy import CHAR, Column, Integer, String
+from sqlalchemy import CHAR, Integer, String
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin
from config.database import Base
@@ -12,14 +13,20 @@ class SysConfig(AuditTimeMixin, Base):
__tablename__ = 'sys_config'
__table_args__ = {'comment': '参数配置表'}
- config_id = Column(Integer, primary_key=True, nullable=False, autoincrement=True, comment='参数主键')
- config_name = Column(String(100), nullable=True, server_default="''", comment='参数名称')
- config_key = Column(String(100), nullable=True, server_default="''", comment='参数键名')
- config_value = Column(String(500), nullable=True, server_default="''", comment='参数键值')
- config_type = Column(CHAR(1), nullable=True, server_default='N', comment='系统内置(Y是 N否)')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- remark = Column(
+ config_id: Mapped[int] = mapped_column(
+ Integer, primary_key=True, nullable=False, autoincrement=True, comment='参数主键'
+ )
+ config_name: Mapped[str | None] = mapped_column(String(100), nullable=True, server_default="''", comment='参数名称')
+ config_key: Mapped[str | None] = mapped_column(String(100), nullable=True, server_default="''", comment='参数键名')
+ config_value: Mapped[str | None] = mapped_column(
+ String(500), nullable=True, server_default="''", comment='参数键值'
+ )
+ config_type: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='N', comment='系统内置(Y是 N否)'
+ )
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ remark: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/dept_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/dept_do.py
index 81d28d205..036e2a636 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/dept_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/dept_do.py
@@ -1,4 +1,5 @@
-from sqlalchemy import CHAR, BigInteger, Column, Integer, String
+from sqlalchemy import CHAR, BigInteger, Integer, String
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin
from config.database import Base
@@ -12,30 +13,34 @@ class SysDept(AuditTimeMixin, Base):
__tablename__ = 'sys_dept'
__table_args__ = {'comment': '部门表'}
- dept_id = Column(BigInteger, primary_key=True, autoincrement=True, comment='部门id')
- parent_id = Column(BigInteger, server_default='0', comment='父部门id')
- ancestors = Column(String(50), nullable=True, server_default="''", comment='祖级列表')
- dept_name = Column(String(30), nullable=True, server_default="''", comment='部门名称')
- order_num = Column(Integer, server_default='0', comment='显示顺序')
- leader = Column(
+ dept_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True, comment='部门id')
+ parent_id: Mapped[int | None] = mapped_column(BigInteger, server_default='0', comment='父部门id')
+ ancestors: Mapped[str | None] = mapped_column(String(50), nullable=True, server_default="''", comment='祖级列表')
+ dept_name: Mapped[str | None] = mapped_column(String(30), nullable=True, server_default="''", comment='部门名称')
+ order_num: Mapped[int | None] = mapped_column(Integer, server_default='0', comment='显示顺序')
+ leader: Mapped[str | None] = mapped_column(
String(20),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='负责人',
)
- phone = Column(
+ phone: Mapped[str | None] = mapped_column(
String(11),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='联系电话',
)
- email = Column(
+ email: Mapped[str | None] = mapped_column(
String(50),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='邮箱',
)
- status = Column(CHAR(1), nullable=True, server_default='0', comment='部门状态(0正常 1停用)')
- del_flag = Column(CHAR(1), nullable=True, server_default='0', comment='删除标志(0代表存在 2代表删除)')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
+ status: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='部门状态(0正常 1停用)'
+ )
+ del_flag: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='删除标志(0代表存在 2代表删除)'
+ )
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/dict_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/dict_do.py
index 7d0f35f3e..4456acdfe 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/dict_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/dict_do.py
@@ -1,5 +1,6 @@
-from sqlalchemy import CHAR, JSON, BigInteger, Column, Integer, String
+from sqlalchemy import CHAR, JSON, BigInteger, Integer, String
from sqlalchemy.dialects.postgresql import JSONB
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin
from config.database import Base
@@ -13,14 +14,22 @@ class SysDictType(AuditTimeMixin, Base):
__tablename__ = 'sys_dict_type'
__table_args__ = {'comment': '字典类型表'}
- dict_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='字典主键')
- dict_name = Column(String(100), nullable=True, server_default="''", comment='字典名称')
- dict_name_i18n = Column(JSON().with_variant(JSONB(), 'postgresql'), nullable=True, comment='多语言译文')
- dict_type = Column(String(100), unique=True, nullable=True, server_default="''", comment='字典类型')
- status = Column(CHAR(1), nullable=True, server_default='0', comment='状态(0正常 1停用)')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- remark = Column(
+ dict_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='字典主键'
+ )
+ dict_name: Mapped[str | None] = mapped_column(String(100), nullable=True, server_default="''", comment='字典名称')
+ dict_name_i18n: Mapped[dict[str, str] | None] = mapped_column(
+ JSON().with_variant(JSONB(), 'postgresql'), nullable=True, comment='多语言译文'
+ )
+ dict_type: Mapped[str | None] = mapped_column(
+ String(100), unique=True, nullable=True, server_default="''", comment='字典类型'
+ )
+ status: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='状态(0正常 1停用)'
+ )
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ remark: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
@@ -34,29 +43,37 @@ class SysDictData(AuditTimeMixin, Base):
__tablename__ = 'sys_dict_data'
__table_args__ = {'comment': '字典数据表'}
- dict_code = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='字典编码')
- dict_sort = Column(Integer, nullable=True, server_default='0', comment='字典排序')
- dict_label = Column(String(100), nullable=True, server_default="''", comment='字典标签')
- dict_label_i18n = Column(JSON().with_variant(JSONB(), 'postgresql'), nullable=True, comment='多语言译文')
- dict_value = Column(String(100), nullable=True, server_default="''", comment='字典键值')
- dict_type = Column(String(100), nullable=True, server_default="''", comment='字典类型')
- css_class = Column(
+ dict_code: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='字典编码'
+ )
+ dict_sort: Mapped[int | None] = mapped_column(Integer, nullable=True, server_default='0', comment='字典排序')
+ dict_label: Mapped[str | None] = mapped_column(String(100), nullable=True, server_default="''", comment='字典标签')
+ dict_label_i18n: Mapped[dict[str, str] | None] = mapped_column(
+ JSON().with_variant(JSONB(), 'postgresql'), nullable=True, comment='多语言译文'
+ )
+ dict_value: Mapped[str | None] = mapped_column(String(100), nullable=True, server_default="''", comment='字典键值')
+ dict_type: Mapped[str | None] = mapped_column(String(100), nullable=True, server_default="''", comment='字典类型')
+ css_class: Mapped[str | None] = mapped_column(
String(100),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='样式属性(其他样式扩展)',
)
- list_class = Column(
+ list_class: Mapped[str | None] = mapped_column(
String(100),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='表格回显样式',
)
- is_default = Column(CHAR(1), nullable=True, server_default='N', comment='是否默认(Y是 N否)')
- status = Column(CHAR(1), nullable=True, server_default='0', comment='状态(0正常 1停用)')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- remark = Column(
+ is_default: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='N', comment='是否默认(Y是 N否)'
+ )
+ status: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='状态(0正常 1停用)'
+ )
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ remark: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/file_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/file_do.py
index efded5bca..e61fada4e 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/file_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/file_do.py
@@ -1,4 +1,8 @@
-from sqlalchemy import CHAR, BigInteger, Column, Index, Integer, String, Text, UniqueConstraint
+from datetime import datetime
+from typing import Literal
+
+from sqlalchemy import CHAR, BigInteger, Index, Integer, String, Text, UniqueConstraint
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin, CreateTimeMixin
from common.types import DbUtcDateTime
@@ -26,34 +30,34 @@ class SysFileInfo(AuditTimeMixin, Base):
{'comment': '文件信息表'},
)
- file_id = Column(String(36), primary_key=True, nullable=False, comment='文件ID')
- original_name = Column(String(255), nullable=False, comment='原始文件名')
- stored_name = Column(String(255), nullable=False, comment='存储文件名')
- storage_key = Column(String(500), nullable=False, comment='存储相对路径')
- storage_type = Column(String(20), nullable=False, server_default='local', comment='存储类型')
- access_type = Column(String(20), nullable=False, server_default='public', comment='访问类型')
- upload_user_id = Column(BigInteger, nullable=True, comment='上传用户ID')
- uploader_access_enabled = Column(
+ file_id: Mapped[str] = mapped_column(String(36), primary_key=True, nullable=False, comment='文件ID')
+ original_name: Mapped[str] = mapped_column(String(255), nullable=False, comment='原始文件名')
+ stored_name: Mapped[str] = mapped_column(String(255), nullable=False, comment='存储文件名')
+ storage_key: Mapped[str] = mapped_column(String(500), nullable=False, comment='存储相对路径')
+ storage_type: Mapped[str] = mapped_column(String(20), nullable=False, server_default='local', comment='存储类型')
+ access_type: Mapped[str] = mapped_column(String(20), nullable=False, server_default='public', comment='访问类型')
+ upload_user_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='上传用户ID')
+ uploader_access_enabled: Mapped[str] = mapped_column(
CHAR(1),
nullable=False,
server_default='1',
comment='是否保留上传人访问权限',
)
- owner_user_id = Column(BigInteger, nullable=True, comment='所有者用户ID')
- dept_id = Column(BigInteger, nullable=True, comment='所属部门ID')
- acl_version = Column(Integer, nullable=False, server_default='0', comment='访问控制版本')
- business_type = Column(String(50), nullable=True, comment='业务类型')
- business_id = Column(String(64), nullable=True, comment='业务ID')
- extension = Column(String(20), nullable=False, server_default="''", comment='文件扩展名')
- content_type = Column(String(255), nullable=True, comment='内容类型')
- file_size = Column(BigInteger, nullable=False, server_default='0', comment='文件大小')
- file_hash = Column(String(64), nullable=False, comment='文件SHA-256')
- status = Column(String(20), nullable=False, server_default='active', comment='文件状态')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- expire_time = Column(DbUtcDateTime(), nullable=True, comment='过期时间')
- deleted_time = Column(DbUtcDateTime(), nullable=True, comment='移入回收站时间')
- del_flag = Column(CHAR(1), nullable=False, server_default='0', comment='删除标志')
+ owner_user_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='所有者用户ID')
+ dept_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='所属部门ID')
+ acl_version: Mapped[int] = mapped_column(Integer, nullable=False, server_default='0', comment='访问控制版本')
+ business_type: Mapped[str | None] = mapped_column(String(50), nullable=True, comment='业务类型')
+ business_id: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='业务ID')
+ extension: Mapped[str] = mapped_column(String(20), nullable=False, server_default="''", comment='文件扩展名')
+ content_type: Mapped[str | None] = mapped_column(String(255), nullable=True, comment='内容类型')
+ file_size: Mapped[int] = mapped_column(BigInteger, nullable=False, server_default='0', comment='文件大小')
+ file_hash: Mapped[str] = mapped_column(String(64), nullable=False, comment='文件SHA-256')
+ status: Mapped[str] = mapped_column(String(20), nullable=False, server_default='active', comment='文件状态')
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ expire_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='过期时间')
+ deleted_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='移入回收站时间')
+ del_flag: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='0', comment='删除标志')
class SysFileReference(CreateTimeMixin, Base):
@@ -73,13 +77,17 @@ class SysFileReference(CreateTimeMixin, Base):
{'comment': '文件业务引用表'},
)
- reference_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='引用ID')
- file_id = Column(String(36), nullable=False, comment='文件ID')
- business_type = Column(String(50), nullable=False, comment='业务类型')
- business_id = Column(String(64), nullable=False, comment='业务ID')
- business_name = Column(String(255), nullable=True, comment='业务名称')
- retention_expire_time = Column(DbUtcDateTime(), nullable=True, comment='保留期限到期时间')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
+ reference_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='引用ID'
+ )
+ file_id: Mapped[str] = mapped_column(String(36), nullable=False, comment='文件ID')
+ business_type: Mapped[str] = mapped_column(String(50), nullable=False, comment='业务类型')
+ business_id: Mapped[str] = mapped_column(String(64), nullable=False, comment='业务ID')
+ business_name: Mapped[str | None] = mapped_column(String(255), nullable=True, comment='业务名称')
+ retention_expire_time: Mapped[datetime | None] = mapped_column(
+ DbUtcDateTime(), nullable=True, comment='保留期限到期时间'
+ )
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
class SysFileRetentionPolicy(AuditTimeMixin, Base):
@@ -90,12 +98,12 @@ class SysFileRetentionPolicy(AuditTimeMixin, Base):
__update_time_nullable__ = False
__table_args__ = {'comment': '文件业务保留策略表'}
- business_type = Column(String(50), primary_key=True, nullable=False, comment='业务类型')
- retention_days = Column(Integer, nullable=False, comment='保留天数')
- status = Column(CHAR(1), nullable=False, server_default='0', comment='状态(0启用 1停用)')
- remark = Column(String(500), nullable=True, comment='备注')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
+ business_type: Mapped[str] = mapped_column(String(50), primary_key=True, nullable=False, comment='业务类型')
+ retention_days: Mapped[int] = mapped_column(Integer, nullable=False, comment='保留天数')
+ status: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='0', comment='状态(0启用 1停用)')
+ remark: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='备注')
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
class SysFileRetentionNotice(CreateTimeMixin, Base):
@@ -115,13 +123,17 @@ class SysFileRetentionNotice(CreateTimeMixin, Base):
{'comment': '文件保留期限提醒表'},
)
- notice_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='提醒ID')
- file_id = Column(String(36), nullable=False, comment='文件ID')
- notice_type = Column(String(20), nullable=False, comment='提醒类型')
- expire_time = Column(DbUtcDateTime(), nullable=False, comment='文件过期时间')
- status = Column(CHAR(1), nullable=False, server_default='0', comment='状态(0未读 1已读 2已失效)')
- read_by = Column(String(64), nullable=True, server_default="''", comment='读取者')
- read_time = Column(DbUtcDateTime(), nullable=True, comment='读取时间')
+ notice_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='提醒ID'
+ )
+ file_id: Mapped[str] = mapped_column(String(36), nullable=False, comment='文件ID')
+ notice_type: Mapped[str] = mapped_column(String(20), nullable=False, comment='提醒类型')
+ expire_time: Mapped[datetime] = mapped_column(DbUtcDateTime(), nullable=False, comment='文件过期时间')
+ status: Mapped[str] = mapped_column(
+ CHAR(1), nullable=False, server_default='0', comment='状态(0未读 1已读 2已失效)'
+ )
+ read_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='读取者')
+ read_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='读取时间')
class SysFileAcl(CreateTimeMixin, Base):
@@ -142,16 +154,26 @@ class SysFileAcl(CreateTimeMixin, Base):
{'comment': '文件访问控制表'},
)
- acl_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='访问控制ID')
- file_id = Column(String(36), nullable=False, comment='文件ID')
- subject_type = Column(String(20), nullable=False, comment='主体类型')
- subject_id = Column(BigInteger, nullable=False, comment='主体ID')
- permission = Column(String(20), nullable=False, server_default='download', comment='权限类型')
- effect = Column(String(10), nullable=False, server_default='allow', comment='授权效果')
- include_children = Column(CHAR(1), nullable=False, server_default='0', comment='部门是否包含下级')
- expire_time = Column(DbUtcDateTime(), nullable=True, comment='授权过期时间')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- del_flag = Column(CHAR(1), nullable=False, server_default='0', comment='删除标志')
+ acl_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='访问控制ID'
+ )
+ file_id: Mapped[str] = mapped_column(String(36), nullable=False, comment='文件ID')
+ subject_type: Mapped[Literal['user', 'role', 'dept']] = mapped_column(
+ String(20), nullable=False, comment='主体类型'
+ )
+ subject_id: Mapped[int] = mapped_column(BigInteger, nullable=False, comment='主体ID')
+ permission: Mapped[Literal['download']] = mapped_column(
+ String(20), nullable=False, server_default='download', comment='权限类型'
+ )
+ effect: Mapped[Literal['allow', 'deny']] = mapped_column(
+ String(10), nullable=False, server_default='allow', comment='授权效果'
+ )
+ include_children: Mapped[str] = mapped_column(
+ CHAR(1), nullable=False, server_default='0', comment='部门是否包含下级'
+ )
+ expire_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='授权过期时间')
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ del_flag: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='0', comment='删除标志')
class SysFileAccessLog(Base):
@@ -164,20 +186,30 @@ class SysFileAccessLog(Base):
{'comment': '文件访问审计表'},
)
- audit_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='审计ID')
- file_id = Column(String(36), nullable=False, comment='文件ID')
- action = Column(String(20), nullable=False, comment='操作类型')
- actor_user_id = Column(BigInteger, nullable=True, comment='操作用户ID')
- actor_name = Column(String(64), nullable=True, server_default="''", comment='操作用户名称')
- result = Column(String(20), nullable=False, comment='操作结果')
- request_id = Column(String(64), nullable=True, server_default="''", comment='请求ID')
- trace_id = Column(String(64), nullable=True, server_default="''", comment='链路ID')
- ip_address = Column(String(128), nullable=True, server_default="''", comment='客户端地址')
- user_agent = Column(String(500), nullable=True, server_default="''", comment='用户代理')
- bytes_sent = Column(BigInteger, nullable=False, server_default='0', comment='发送字节数')
- error_message = Column(String(500), nullable=True, server_default="''", comment='失败原因')
- operation_detail = Column(Text, nullable=True, comment='操作详情')
- access_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='访问时间')
+ audit_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='审计ID'
+ )
+ file_id: Mapped[str] = mapped_column(String(36), nullable=False, comment='文件ID')
+ action: Mapped[str] = mapped_column(String(20), nullable=False, comment='操作类型')
+ actor_user_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='操作用户ID')
+ actor_name: Mapped[str | None] = mapped_column(
+ String(64), nullable=True, server_default="''", comment='操作用户名称'
+ )
+ result: Mapped[str] = mapped_column(String(20), nullable=False, comment='操作结果')
+ request_id: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='请求ID')
+ trace_id: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='链路ID')
+ ip_address: Mapped[str | None] = mapped_column(
+ String(128), nullable=True, server_default="''", comment='客户端地址'
+ )
+ user_agent: Mapped[str | None] = mapped_column(String(500), nullable=True, server_default="''", comment='用户代理')
+ bytes_sent: Mapped[int] = mapped_column(BigInteger, nullable=False, server_default='0', comment='发送字节数')
+ error_message: Mapped[str | None] = mapped_column(
+ String(500), nullable=True, server_default="''", comment='失败原因'
+ )
+ operation_detail: Mapped[str | None] = mapped_column(Text, nullable=True, comment='操作详情')
+ access_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='访问时间'
+ )
class SysFileReconcileRun(Base):
@@ -190,20 +222,30 @@ class SysFileReconcileRun(Base):
{'comment': '文件存储对账任务表'},
)
- run_id = Column(String(36), primary_key=True, nullable=False, comment='任务ID')
- trigger_type = Column(String(20), nullable=False, comment='触发类型')
- status = Column(String(20), nullable=False, comment='任务状态')
- check_hash = Column(CHAR(1), nullable=False, server_default='0', comment='是否校验文件摘要')
- lock_name = Column(String(32), nullable=True, comment='运行锁名称')
- scanned_file_count = Column(BigInteger, nullable=False, server_default='0', comment='扫描文件记录数')
- scanned_storage_count = Column(BigInteger, nullable=False, server_default='0', comment='扫描物理文件数')
- issue_count = Column(BigInteger, nullable=False, server_default='0', comment='发现异常数')
- new_issue_count = Column(BigInteger, nullable=False, server_default='0', comment='新增或重新出现异常数')
- resolved_issue_count = Column(BigInteger, nullable=False, server_default='0', comment='自动恢复异常数')
- started_by = Column(String(64), nullable=True, server_default="''", comment='发起人')
- started_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='开始时间')
- finished_time = Column(DbUtcDateTime(), nullable=True, comment='完成时间')
- error_message = Column(Text, nullable=True, comment='失败原因')
+ run_id: Mapped[str] = mapped_column(String(36), primary_key=True, nullable=False, comment='任务ID')
+ trigger_type: Mapped[str] = mapped_column(String(20), nullable=False, comment='触发类型')
+ status: Mapped[str] = mapped_column(String(20), nullable=False, comment='任务状态')
+ check_hash: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='0', comment='是否校验文件摘要')
+ lock_name: Mapped[str | None] = mapped_column(String(32), nullable=True, comment='运行锁名称')
+ scanned_file_count: Mapped[int] = mapped_column(
+ BigInteger, nullable=False, server_default='0', comment='扫描文件记录数'
+ )
+ scanned_storage_count: Mapped[int] = mapped_column(
+ BigInteger, nullable=False, server_default='0', comment='扫描物理文件数'
+ )
+ issue_count: Mapped[int] = mapped_column(BigInteger, nullable=False, server_default='0', comment='发现异常数')
+ new_issue_count: Mapped[int] = mapped_column(
+ BigInteger, nullable=False, server_default='0', comment='新增或重新出现异常数'
+ )
+ resolved_issue_count: Mapped[int] = mapped_column(
+ BigInteger, nullable=False, server_default='0', comment='自动恢复异常数'
+ )
+ started_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='发起人')
+ started_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='开始时间'
+ )
+ finished_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='完成时间')
+ error_message: Mapped[str | None] = mapped_column(Text, nullable=True, comment='失败原因')
class SysFileReconcileIssue(Base):
@@ -218,29 +260,35 @@ class SysFileReconcileIssue(Base):
{'comment': '文件存储对账异常表'},
)
- issue_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='异常ID')
- issue_key = Column(String(64), nullable=False, comment='异常唯一标识')
- last_run_id = Column(String(36), nullable=False, comment='最近发现任务ID')
- issue_type = Column(String(32), nullable=False, comment='异常类型')
- severity = Column(String(10), nullable=False, comment='严重级别')
- file_id = Column(String(36), nullable=True, comment='文件ID')
- storage_type = Column(String(20), nullable=True, comment='存储类型')
- access_type = Column(String(20), nullable=True, comment='访问类型')
- expected_root = Column(String(20), nullable=True, comment='预期存储区域')
- expected_key = Column(String(500), nullable=True, comment='预期相对路径')
- actual_root = Column(String(20), nullable=True, comment='实际存储区域')
- actual_key = Column(String(500), nullable=True, comment='实际相对路径')
- expected_size = Column(BigInteger, nullable=True, comment='预期文件大小')
- actual_size = Column(BigInteger, nullable=True, comment='实际文件大小')
- expected_hash = Column(String(64), nullable=True, comment='预期SHA-256')
- actual_hash = Column(String(64), nullable=True, comment='实际SHA-256')
- status = Column(String(20), nullable=False, server_default='open', comment='处理状态')
- detail = Column(Text, nullable=True, comment='异常说明')
- occurrence_count = Column(Integer, nullable=False, server_default='1', comment='发现次数')
- first_seen_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='首次发现时间')
- last_seen_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='最近发现时间')
- handle_action = Column(String(32), nullable=True, comment='处理动作')
- handle_reason = Column(String(500), nullable=True, comment='处理原因')
- handled_by = Column(String(64), nullable=True, comment='处理人')
- handled_time = Column(DbUtcDateTime(), nullable=True, comment='处理时间')
- quarantine_key = Column(String(500), nullable=True, comment='隔离区相对路径')
+ issue_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='异常ID'
+ )
+ issue_key: Mapped[str] = mapped_column(String(64), nullable=False, comment='异常唯一标识')
+ last_run_id: Mapped[str] = mapped_column(String(36), nullable=False, comment='最近发现任务ID')
+ issue_type: Mapped[str] = mapped_column(String(32), nullable=False, comment='异常类型')
+ severity: Mapped[str] = mapped_column(String(10), nullable=False, comment='严重级别')
+ file_id: Mapped[str | None] = mapped_column(String(36), nullable=True, comment='文件ID')
+ storage_type: Mapped[str | None] = mapped_column(String(20), nullable=True, comment='存储类型')
+ access_type: Mapped[str | None] = mapped_column(String(20), nullable=True, comment='访问类型')
+ expected_root: Mapped[str | None] = mapped_column(String(20), nullable=True, comment='预期存储区域')
+ expected_key: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='预期相对路径')
+ actual_root: Mapped[str | None] = mapped_column(String(20), nullable=True, comment='实际存储区域')
+ actual_key: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='实际相对路径')
+ expected_size: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='预期文件大小')
+ actual_size: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='实际文件大小')
+ expected_hash: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='预期SHA-256')
+ actual_hash: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='实际SHA-256')
+ status: Mapped[str] = mapped_column(String(20), nullable=False, server_default='open', comment='处理状态')
+ detail: Mapped[str | None] = mapped_column(Text, nullable=True, comment='异常说明')
+ occurrence_count: Mapped[int] = mapped_column(Integer, nullable=False, server_default='1', comment='发现次数')
+ first_seen_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='首次发现时间'
+ )
+ last_seen_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='最近发现时间'
+ )
+ handle_action: Mapped[str | None] = mapped_column(String(32), nullable=True, comment='处理动作')
+ handle_reason: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='处理原因')
+ handled_by: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='处理人')
+ handled_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='处理时间')
+ quarantine_key: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='隔离区相对路径')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/job_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/job_do.py
index 9cd62f838..cdfcf78f9 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/job_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/job_do.py
@@ -1,15 +1,18 @@
+from datetime import datetime
+from typing import Any
+
from sqlalchemy import (
CHAR,
JSON,
BigInteger,
Boolean,
CheckConstraint,
- Column,
Index,
Integer,
String,
UniqueConstraint,
)
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin, CreateTimeMixin
from common.types import DbUtcDateTime
@@ -27,25 +30,33 @@ class SysJob(AuditTimeMixin, Base):
{'comment': '定时任务调度表'},
)
- job_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='任务ID')
- job_name = Column(String(64), nullable=False, comment='任务名称(同一业务分组内唯一)')
- job_group = Column(String(64), nullable=False, server_default='default', comment='业务分组')
- job_store = Column(String(64), nullable=False, server_default='default', comment='调度存储')
- job_executor = Column(String(64), nullable=True, server_default='default', comment='任务执行器')
- invoke_target = Column(String(500), nullable=False, comment='调用目标字符串')
- job_args = Column(JSON, nullable=False, default=list, comment='位置参数(JSON数组)')
- job_kwargs = Column(JSON, nullable=False, default=dict, comment='关键字参数(JSON对象)')
- cron_expression = Column(String(255), nullable=True, server_default="''", comment='cron执行表达式')
- time_zone = Column(String(64), nullable=False, comment='cron时区(IANA)')
- misfire_grace_time = Column(
+ job_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='任务ID'
+ )
+ job_name: Mapped[str] = mapped_column(String(64), nullable=False, comment='任务名称(同一业务分组内唯一)')
+ job_group: Mapped[str] = mapped_column(String(64), nullable=False, server_default='default', comment='业务分组')
+ job_store: Mapped[str] = mapped_column(String(64), nullable=False, server_default='default', comment='调度存储')
+ job_executor: Mapped[str | None] = mapped_column(
+ String(64), nullable=True, server_default='default', comment='任务执行器'
+ )
+ invoke_target: Mapped[str] = mapped_column(String(500), nullable=False, comment='调用目标字符串')
+ job_args: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list, comment='位置参数(JSON数组)')
+ job_kwargs: Mapped[dict[str, Any]] = mapped_column(
+ JSON, nullable=False, default=dict, comment='关键字参数(JSON对象)'
+ )
+ cron_expression: Mapped[str | None] = mapped_column(
+ String(255), nullable=True, server_default="''", comment='cron执行表达式'
+ )
+ time_zone: Mapped[str] = mapped_column(String(64), nullable=False, comment='cron时区(IANA)')
+ misfire_grace_time: Mapped[int | None] = mapped_column(
Integer().evaluates_none(), nullable=True, default=1, comment='允许延迟秒数,NULL表示不限'
)
- coalesce = Column(Boolean, nullable=False, default=False, comment='积压时是否只执行最近一次')
- max_instances = Column(Integer, nullable=False, server_default='1', comment='任务最大并发数')
- status = Column(CHAR(1), nullable=False, server_default='1', comment='状态(0正常 1暂停)')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- remark = Column(String(500), nullable=True, server_default="''", comment='备注信息')
+ coalesce: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, comment='积压时是否只执行最近一次')
+ max_instances: Mapped[int] = mapped_column(Integer, nullable=False, server_default='1', comment='任务最大并发数')
+ status: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='1', comment='状态(0正常 1暂停)')
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ remark: Mapped[str | None] = mapped_column(String(500), nullable=True, server_default="''", comment='备注信息')
class SysJobLog(CreateTimeMixin, Base):
@@ -58,22 +69,30 @@ class SysJobLog(CreateTimeMixin, Base):
{'comment': '定时任务调度日志表'},
)
- job_log_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='任务日志ID')
- job_id = Column(BigInteger, nullable=True, comment='逻辑任务ID,历史未关联日志可为空')
- execution_id = Column(String(32), nullable=True, comment='执行ID,历史未关联日志可为空')
- job_name = Column(String(64), nullable=False, comment='任务名称')
- job_group = Column(String(64), nullable=False, comment='任务组名')
- job_store = Column(String(64), nullable=True, comment='调度存储快照')
- job_executor = Column(String(64), nullable=False, comment='任务执行器')
- invoke_target = Column(String(500), nullable=False, comment='调用目标字符串')
- job_args = Column(JSON, nullable=True, comment='位置参数快照(JSON数组)')
- job_kwargs = Column(JSON, nullable=True, comment='关键字参数快照(JSON对象)')
- job_trigger = Column(String(255), nullable=True, server_default="''", comment='任务触发器')
- time_zone = Column(String(64), nullable=True, comment='任务时区快照(IANA)')
- job_message = Column(String(500), nullable=True, comment='日志信息')
- status = Column(CHAR(1), nullable=True, server_default='0', comment='执行状态(0正常 1失败)')
- exception_info = Column(String(2000), nullable=True, server_default="''", comment='异常信息')
- scheduled_time = Column(DbUtcDateTime(), nullable=True, comment='计划执行时刻')
- start_time = Column(DbUtcDateTime(), nullable=True, comment='执行开始时间')
- end_time = Column(DbUtcDateTime(), nullable=True, comment='执行结束时间')
- run_duration_ms = Column(BigInteger, nullable=True, comment='实际执行耗时(毫秒)')
+ job_log_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='任务日志ID'
+ )
+ job_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='逻辑任务ID,历史未关联日志可为空')
+ execution_id: Mapped[str | None] = mapped_column(String(32), nullable=True, comment='执行ID,历史未关联日志可为空')
+ job_name: Mapped[str] = mapped_column(String(64), nullable=False, comment='任务名称')
+ job_group: Mapped[str] = mapped_column(String(64), nullable=False, comment='任务组名')
+ job_store: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='调度存储快照')
+ job_executor: Mapped[str] = mapped_column(String(64), nullable=False, comment='任务执行器')
+ invoke_target: Mapped[str] = mapped_column(String(500), nullable=False, comment='调用目标字符串')
+ job_args: Mapped[list[Any] | None] = mapped_column(JSON, nullable=True, comment='位置参数快照(JSON数组)')
+ job_kwargs: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True, comment='关键字参数快照(JSON对象)')
+ job_trigger: Mapped[str | None] = mapped_column(
+ String(255), nullable=True, server_default="''", comment='任务触发器'
+ )
+ time_zone: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='任务时区快照(IANA)')
+ job_message: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='日志信息')
+ status: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='执行状态(0正常 1失败)'
+ )
+ exception_info: Mapped[str | None] = mapped_column(
+ String(2000), nullable=True, server_default="''", comment='异常信息'
+ )
+ scheduled_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='计划执行时刻')
+ start_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='执行开始时间')
+ end_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='执行结束时间')
+ run_duration_ms: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='实际执行耗时(毫秒)')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/job_runtime_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/job_runtime_do.py
index 7e6ee4b2b..2fd475cb0 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/job_runtime_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/job_runtime_do.py
@@ -1,4 +1,8 @@
-from sqlalchemy import JSON, BigInteger, Boolean, Column, Index, String, Text
+from datetime import datetime
+from typing import Any
+
+from sqlalchemy import JSON, BigInteger, Boolean, Index, String, Text
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin
from common.types import DbUtcDateTime
@@ -14,18 +18,22 @@ class SysJobSync(AuditTimeMixin, Base):
{'comment': '任务调度同步状态'},
)
- job_id = Column(BigInteger, primary_key=True, autoincrement=False, comment='逻辑任务ID')
- config_version = Column(BigInteger, nullable=False, default=1, comment='最新配置版本')
- applied_version = Column(BigInteger, nullable=False, default=0, comment='已应用版本')
- config_hash = Column(String(64), nullable=False, comment='最新配置摘要')
- deleted = Column(Boolean, nullable=False, default=False, comment='任务是否已删除')
- sync_status = Column(
+ job_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=False, comment='逻辑任务ID')
+ config_version: Mapped[int] = mapped_column(BigInteger, nullable=False, default=1, comment='最新配置版本')
+ applied_version: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0, comment='已应用版本')
+ config_hash: Mapped[str] = mapped_column(String(64), nullable=False, comment='最新配置摘要')
+ deleted: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, comment='任务是否已删除')
+ sync_status: Mapped[str] = mapped_column(
String(16), nullable=False, default='pending', comment='应用状态(pending、applied 或 failed)'
)
- sync_error = Column(String(2000), nullable=True, comment='最近同步错误')
- applied_time = Column(DbUtcDateTime(), nullable=True, comment='最近应用时刻')
- next_run_time = Column(DbUtcDateTime(), nullable=True, comment='最近观测的实际下次调度时刻')
- schedule_observed_time = Column(DbUtcDateTime(), nullable=True, comment='Leader调度观测时刻')
+ sync_error: Mapped[str | None] = mapped_column(String(2000), nullable=True, comment='最近同步错误')
+ applied_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='最近应用时刻')
+ next_run_time: Mapped[datetime | None] = mapped_column(
+ DbUtcDateTime(), nullable=True, comment='最近观测的实际下次调度时刻'
+ )
+ schedule_observed_time: Mapped[datetime | None] = mapped_column(
+ DbUtcDateTime(), nullable=True, comment='Leader调度观测时刻'
+ )
class SysJobExecution(AuditTimeMixin, Base):
@@ -38,16 +46,16 @@ class SysJobExecution(AuditTimeMixin, Base):
{'comment': '任务执行请求与状态'},
)
- execution_id = Column(String(32), primary_key=True, comment='执行ID')
- job_id = Column(BigInteger, nullable=False, comment='逻辑任务ID')
- source = Column(String(10), nullable=False, comment='触发方式(手动或定时)')
- status = Column(String(16), nullable=False, default='pending', comment='执行状态')
- job_snapshot = Column(JSON, nullable=False, comment='提交时任务配置快照')
- owner_token = Column(String(64), nullable=True, comment='派发或执行占用凭据')
- lease_until = Column(DbUtcDateTime(), nullable=True, comment='执行占用租约截止时刻')
- scheduled_time = Column(DbUtcDateTime(), nullable=True, comment='计划执行时刻')
- start_time = Column(DbUtcDateTime(), nullable=True, comment='实际开始时刻')
- end_time = Column(DbUtcDateTime(), nullable=True, comment='实际结束时刻')
- run_duration_ms = Column(BigInteger, nullable=True, comment='实际执行耗时(毫秒)')
- message = Column(Text, nullable=True, comment='执行结果或未执行原因')
- requested_by = Column(String(64), nullable=True, comment='手动执行提交者')
+ execution_id: Mapped[str] = mapped_column(String(32), primary_key=True, comment='执行ID')
+ job_id: Mapped[int] = mapped_column(BigInteger, nullable=False, comment='逻辑任务ID')
+ source: Mapped[str] = mapped_column(String(10), nullable=False, comment='触发方式(手动或定时)')
+ status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', comment='执行状态')
+ job_snapshot: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, comment='提交时任务配置快照')
+ owner_token: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='派发或执行占用凭据')
+ lease_until: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='执行占用租约截止时刻')
+ scheduled_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='计划执行时刻')
+ start_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='实际开始时刻')
+ end_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='实际结束时刻')
+ run_duration_ms: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='实际执行耗时(毫秒)')
+ message: Mapped[str | None] = mapped_column(Text, nullable=True, comment='执行结果或未执行原因')
+ requested_by: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='手动执行提交者')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/log_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/log_do.py
index b02d81c0f..b19555c3f 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/log_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/log_do.py
@@ -1,4 +1,7 @@
-from sqlalchemy import CHAR, BigInteger, Column, Index, Integer, String
+from datetime import datetime
+
+from sqlalchemy import CHAR, BigInteger, Index, Integer, String
+from sqlalchemy.orm import Mapped, mapped_column
from common.types import DbUtcDateTime
from config.database import Base
@@ -11,15 +14,23 @@ class SysLogininfor(Base):
__tablename__ = 'sys_logininfor'
__table_args__ = {'comment': '系统访问记录'}
- info_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='访问ID')
- user_name = Column(String(50), nullable=True, server_default="''", comment='用户账号')
- ipaddr = Column(String(128), nullable=True, server_default="''", comment='登录IP地址')
- login_location = Column(String(255), nullable=True, server_default="''", comment='登录地点')
- browser = Column(String(50), nullable=True, server_default="''", comment='浏览器类型')
- os = Column(String(50), nullable=True, server_default="''", comment='操作系统')
- status = Column(CHAR(1), nullable=True, server_default='0', comment='登录状态(0成功 1失败)')
- msg = Column(String(255), nullable=True, server_default="''", comment='提示消息')
- login_time = Column(DbUtcDateTime(), nullable=True, default=TimezoneUtil.utc_now, comment='访问时间')
+ info_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='访问ID'
+ )
+ user_name: Mapped[str | None] = mapped_column(String(50), nullable=True, server_default="''", comment='用户账号')
+ ipaddr: Mapped[str | None] = mapped_column(String(128), nullable=True, server_default="''", comment='登录IP地址')
+ login_location: Mapped[str | None] = mapped_column(
+ String(255), nullable=True, server_default="''", comment='登录地点'
+ )
+ browser: Mapped[str | None] = mapped_column(String(50), nullable=True, server_default="''", comment='浏览器类型')
+ os: Mapped[str | None] = mapped_column(String(50), nullable=True, server_default="''", comment='操作系统')
+ status: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='登录状态(0成功 1失败)'
+ )
+ msg: Mapped[str | None] = mapped_column(String(255), nullable=True, server_default="''", comment='提示消息')
+ login_time: Mapped[datetime | None] = mapped_column(
+ DbUtcDateTime(), nullable=True, default=TimezoneUtil.utc_now, comment='访问时间'
+ )
idx_sys_logininfor_s = Index('idx_sys_logininfor_s', status)
idx_sys_logininfor_lt = Index('idx_sys_logininfor_lt', login_time)
@@ -31,25 +42,39 @@ class SysOperLog(Base):
__tablename__ = 'sys_oper_log'
__table_args__ = {'comment': '操作日志记录'}
- oper_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='日志主键')
- title = Column(String(50), nullable=True, server_default="''", comment='模块标题')
- business_type = Column(Integer, nullable=True, server_default='0', comment='业务类型(0其它 1新增 2修改 3删除)')
- method = Column(String(100), nullable=True, server_default="''", comment='方法名称')
- request_method = Column(String(10), nullable=True, server_default="''", comment='请求方式')
- operator_type = Column(
+ oper_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='日志主键'
+ )
+ title: Mapped[str | None] = mapped_column(String(50), nullable=True, server_default="''", comment='模块标题')
+ business_type: Mapped[int | None] = mapped_column(
+ Integer, nullable=True, server_default='0', comment='业务类型(0其它 1新增 2修改 3删除)'
+ )
+ method: Mapped[str | None] = mapped_column(String(100), nullable=True, server_default="''", comment='方法名称')
+ request_method: Mapped[str | None] = mapped_column(
+ String(10), nullable=True, server_default="''", comment='请求方式'
+ )
+ operator_type: Mapped[int | None] = mapped_column(
Integer, nullable=True, server_default='0', comment='操作类别(0其它 1后台用户 2手机端用户)'
)
- oper_name = Column(String(50), nullable=True, server_default="''", comment='操作人员')
- dept_name = Column(String(50), nullable=True, server_default="''", comment='部门名称')
- oper_url = Column(String(255), nullable=True, server_default="''", comment='请求URL')
- oper_ip = Column(String(128), nullable=True, server_default="''", comment='主机地址')
- oper_location = Column(String(255), nullable=True, server_default="''", comment='操作地点')
- oper_param = Column(String(2000), nullable=True, server_default="''", comment='请求参数')
- json_result = Column(String(2000), nullable=True, server_default="''", comment='返回参数')
- status = Column(Integer, nullable=True, server_default='0', comment='操作状态(0正常 1异常)')
- error_msg = Column(String(2000), nullable=True, server_default="''", comment='错误消息')
- oper_time = Column(DbUtcDateTime(), nullable=True, default=TimezoneUtil.utc_now, comment='操作时间')
- cost_time = Column(BigInteger, nullable=True, server_default='0', comment='消耗时间')
+ oper_name: Mapped[str | None] = mapped_column(String(50), nullable=True, server_default="''", comment='操作人员')
+ dept_name: Mapped[str | None] = mapped_column(String(50), nullable=True, server_default="''", comment='部门名称')
+ oper_url: Mapped[str | None] = mapped_column(String(255), nullable=True, server_default="''", comment='请求URL')
+ oper_ip: Mapped[str | None] = mapped_column(String(128), nullable=True, server_default="''", comment='主机地址')
+ oper_location: Mapped[str | None] = mapped_column(
+ String(255), nullable=True, server_default="''", comment='操作地点'
+ )
+ oper_param: Mapped[str | None] = mapped_column(String(2000), nullable=True, server_default="''", comment='请求参数')
+ json_result: Mapped[str | None] = mapped_column(
+ String(2000), nullable=True, server_default="''", comment='返回参数'
+ )
+ status: Mapped[int | None] = mapped_column(
+ Integer, nullable=True, server_default='0', comment='操作状态(0正常 1异常)'
+ )
+ error_msg: Mapped[str | None] = mapped_column(String(2000), nullable=True, server_default="''", comment='错误消息')
+ oper_time: Mapped[datetime | None] = mapped_column(
+ DbUtcDateTime(), nullable=True, default=TimezoneUtil.utc_now, comment='操作时间'
+ )
+ cost_time: Mapped[int | None] = mapped_column(BigInteger, nullable=True, server_default='0', comment='消耗时间')
idx_sys_oper_log_bt = Index('idx_sys_oper_log_bt', business_type)
idx_sys_oper_log_s = Index('idx_sys_oper_log_s', status)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/menu_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/menu_do.py
index 5731ee151..0e4e72526 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/menu_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/menu_do.py
@@ -1,5 +1,6 @@
-from sqlalchemy import CHAR, JSON, BigInteger, Column, Integer, String
+from sqlalchemy import CHAR, JSON, BigInteger, Integer, String
from sqlalchemy.dialects.postgresql import JSONB
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin
from config.database import Base
@@ -13,37 +14,51 @@ class SysMenu(AuditTimeMixin, Base):
__tablename__ = 'sys_menu'
__table_args__ = {'comment': '菜单权限表'}
- menu_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='菜单ID')
- menu_name = Column(String(50), nullable=False, comment='菜单名称')
- menu_name_i18n = Column(JSON().with_variant(JSONB(), 'postgresql'), nullable=True, comment='多语言译文')
- parent_id = Column(BigInteger, nullable=True, server_default='0', comment='父菜单ID')
- order_num = Column(Integer, server_default='0', comment='显示顺序')
- path = Column(String(200), nullable=True, server_default="''", comment='路由地址')
- component = Column(
+ menu_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='菜单ID'
+ )
+ menu_name: Mapped[str] = mapped_column(String(50), nullable=False, comment='菜单名称')
+ menu_name_i18n: Mapped[dict[str, str] | None] = mapped_column(
+ JSON().with_variant(JSONB(), 'postgresql'), nullable=True, comment='多语言译文'
+ )
+ parent_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, server_default='0', comment='父菜单ID')
+ order_num: Mapped[int | None] = mapped_column(Integer, server_default='0', comment='显示顺序')
+ path: Mapped[str | None] = mapped_column(String(200), nullable=True, server_default="''", comment='路由地址')
+ component: Mapped[str | None] = mapped_column(
String(255),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='组件路径',
)
- query = Column(
+ query: Mapped[str | None] = mapped_column(
String(255),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='路由参数',
)
- route_name = Column(String(50), nullable=True, server_default="''", comment='路由名称')
- is_frame = Column(Integer, nullable=True, server_default='1', comment='是否为外链(0是 1否)')
- is_cache = Column(Integer, nullable=True, server_default='0', comment='是否缓存(0缓存 1不缓存)')
- menu_type = Column(CHAR(1), nullable=True, server_default="''", comment='菜单类型(M目录 C菜单 F按钮)')
- visible = Column(CHAR(1), nullable=True, server_default='0', comment='菜单状态(0显示 1隐藏)')
- status = Column(CHAR(1), nullable=True, server_default='0', comment='菜单状态(0正常 1停用)')
- perms = Column(
+ route_name: Mapped[str | None] = mapped_column(String(50), nullable=True, server_default="''", comment='路由名称')
+ is_frame: Mapped[int | None] = mapped_column(
+ Integer, nullable=True, server_default='1', comment='是否为外链(0是 1否)'
+ )
+ is_cache: Mapped[int | None] = mapped_column(
+ Integer, nullable=True, server_default='0', comment='是否缓存(0缓存 1不缓存)'
+ )
+ menu_type: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default="''", comment='菜单类型(M目录 C菜单 F按钮)'
+ )
+ visible: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='菜单状态(0显示 1隐藏)'
+ )
+ status: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='菜单状态(0正常 1停用)'
+ )
+ perms: Mapped[str | None] = mapped_column(
String(100),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='权限标识',
)
- icon = Column(String(100), nullable=True, server_default='#', comment='菜单图标')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- remark = Column(String(500), nullable=True, server_default="''", comment='备注')
+ icon: Mapped[str | None] = mapped_column(String(100), nullable=True, server_default='#', comment='菜单图标')
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ remark: Mapped[str | None] = mapped_column(String(500), nullable=True, server_default="''", comment='备注')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/notice_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/notice_do.py
index e02524fa8..e71ad2e0f 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/notice_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/notice_do.py
@@ -1,5 +1,8 @@
-from sqlalchemy import CHAR, BigInteger, Column, Integer, LargeBinary, String, UniqueConstraint
+from datetime import datetime
+
+from sqlalchemy import CHAR, BigInteger, Integer, LargeBinary, String, UniqueConstraint
from sqlalchemy.dialects import mysql
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin
from common.types import DbUtcDateTime
@@ -15,19 +18,23 @@ class SysNotice(AuditTimeMixin, Base):
__tablename__ = 'sys_notice'
__table_args__ = {'comment': '通知公告表'}
- notice_id = Column(Integer, primary_key=True, nullable=False, autoincrement=True, comment='公告ID')
- notice_title = Column(String(50), nullable=False, comment='公告标题')
- notice_type = Column(CHAR(1), nullable=False, comment='公告类型(1通知 2公告)')
- notice_content = Column(
+ notice_id: Mapped[int] = mapped_column(
+ Integer, primary_key=True, nullable=False, autoincrement=True, comment='公告ID'
+ )
+ notice_title: Mapped[str] = mapped_column(String(50), nullable=False, comment='公告标题')
+ notice_type: Mapped[str] = mapped_column(CHAR(1), nullable=False, comment='公告类型(1通知 2公告)')
+ notice_content: Mapped[bytes | None] = mapped_column(
mysql.LONGBLOB if DataBaseConfig.default_source.db_type == 'mysql' else LargeBinary,
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type, False),
comment='公告内容',
)
- status = Column(CHAR(1), nullable=True, server_default='0', comment='公告状态(0正常 1关闭)')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- remark = Column(
+ status: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='公告状态(0正常 1关闭)'
+ )
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ remark: Mapped[str | None] = mapped_column(
String(255),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
@@ -44,13 +51,15 @@ class SysNoticeRead(Base):
{'comment': '公告已读记录表'},
)
- read_id = Column(
+ read_id: Mapped[int] = mapped_column(
BigInteger().with_variant(Integer, 'sqlite'),
primary_key=True,
nullable=False,
autoincrement=True,
comment='已读主键',
)
- notice_id = Column(Integer, nullable=False, comment='公告ID')
- user_id = Column(BigInteger, nullable=False, comment='用户ID')
- read_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='阅读时间')
+ notice_id: Mapped[int] = mapped_column(Integer, nullable=False, comment='公告ID')
+ user_id: Mapped[int] = mapped_column(BigInteger, nullable=False, comment='用户ID')
+ read_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='阅读时间'
+ )
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/post_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/post_do.py
index 22f0fa36a..f31b278b8 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/post_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/post_do.py
@@ -1,4 +1,5 @@
-from sqlalchemy import CHAR, BigInteger, Column, Integer, String
+from sqlalchemy import CHAR, BigInteger, Integer, String
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin
from config.database import Base
@@ -12,14 +13,16 @@ class SysPost(AuditTimeMixin, Base):
__tablename__ = 'sys_post'
__table_args__ = {'comment': '岗位信息表'}
- post_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='岗位ID')
- post_code = Column(String(64), nullable=False, comment='岗位编码')
- post_name = Column(String(50), nullable=False, comment='岗位名称')
- post_sort = Column(Integer, nullable=False, comment='显示顺序')
- status = Column(CHAR(1), nullable=False, comment='状态(0正常 1停用)')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- remark = Column(
+ post_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='岗位ID'
+ )
+ post_code: Mapped[str] = mapped_column(String(64), nullable=False, comment='岗位编码')
+ post_name: Mapped[str] = mapped_column(String(50), nullable=False, comment='岗位名称')
+ post_sort: Mapped[int] = mapped_column(Integer, nullable=False, comment='显示顺序')
+ status: Mapped[str] = mapped_column(CHAR(1), nullable=False, comment='状态(0正常 1停用)')
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ remark: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/role_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/role_do.py
index 6a4bacca1..d1ad85ad1 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/role_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/role_do.py
@@ -1,5 +1,6 @@
-from sqlalchemy import CHAR, BigInteger, Column, Integer, SmallInteger, String
+from sqlalchemy import CHAR, BigInteger, Integer, SmallInteger, String
from sqlalchemy.dialects import mysql
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin
from config.database import Base
@@ -13,33 +14,37 @@ class SysRole(AuditTimeMixin, Base):
__tablename__ = 'sys_role'
__table_args__ = {'comment': '角色信息表'}
- role_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='角色ID')
- role_name = Column(String(30), nullable=False, comment='角色名称')
- role_key = Column(String(100), nullable=False, comment='角色权限字符串')
- role_sort = Column(Integer, nullable=False, comment='显示顺序')
- data_scope = Column(
+ role_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='角色ID'
+ )
+ role_name: Mapped[str] = mapped_column(String(30), nullable=False, comment='角色名称')
+ role_key: Mapped[str] = mapped_column(String(100), nullable=False, comment='角色权限字符串')
+ role_sort: Mapped[int] = mapped_column(Integer, nullable=False, comment='显示顺序')
+ data_scope: Mapped[str | None] = mapped_column(
CHAR(1),
nullable=True,
server_default='1',
comment='数据范围(1:全部数据权限 2:自定数据权限 3:本部门数据权限 4:本部门及以下数据权限)',
)
- menu_check_strictly = Column(
+ menu_check_strictly: Mapped[int | None] = mapped_column(
mysql.TINYINT(display_width=1) if DataBaseConfig.default_source.db_type == 'mysql' else SmallInteger,
nullable=True,
server_default='1',
comment='菜单树选择项是否关联显示',
)
- dept_check_strictly = Column(
+ dept_check_strictly: Mapped[int | None] = mapped_column(
mysql.TINYINT(display_width=1) if DataBaseConfig.default_source.db_type == 'mysql' else SmallInteger,
nullable=True,
server_default='1',
comment='部门树选择项是否关联显示',
)
- status = Column(CHAR(1), nullable=False, comment='角色状态(0正常 1停用)')
- del_flag = Column(CHAR(1), nullable=True, server_default='0', comment='删除标志(0代表存在 2代表删除)')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- remark = Column(
+ status: Mapped[str] = mapped_column(CHAR(1), nullable=False, comment='角色状态(0正常 1停用)')
+ del_flag: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='删除标志(0代表存在 2代表删除)'
+ )
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ remark: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
@@ -53,8 +58,8 @@ class SysRoleDept(Base):
__tablename__ = 'sys_role_dept'
__table_args__ = {'comment': '角色和部门关联表'}
- role_id = Column(BigInteger, primary_key=True, nullable=False, comment='角色ID')
- dept_id = Column(BigInteger, primary_key=True, nullable=False, comment='部门ID')
+ role_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, nullable=False, comment='角色ID')
+ dept_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, nullable=False, comment='部门ID')
class SysRoleMenu(Base):
@@ -63,5 +68,5 @@ class SysRoleMenu(Base):
__tablename__ = 'sys_role_menu'
__table_args__ = {'comment': '角色和菜单关联表'}
- role_id = Column(BigInteger, primary_key=True, nullable=False, comment='角色ID')
- menu_id = Column(BigInteger, primary_key=True, nullable=False, comment='菜单ID')
+ role_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, nullable=False, comment='角色ID')
+ menu_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, nullable=False, comment='菜单ID')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/do/user_do.py b/ruoyi-fastapi-backend/module_admin/entity/do/user_do.py
index 16d29cd9d..514aded1d 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/do/user_do.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/do/user_do.py
@@ -1,4 +1,7 @@
-from sqlalchemy import CHAR, BigInteger, Column, String
+from datetime import datetime
+
+from sqlalchemy import CHAR, BigInteger, String
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin
from common.types import DbUtcDateTime
@@ -13,32 +16,44 @@ class SysUser(AuditTimeMixin, Base):
__tablename__ = 'sys_user'
__table_args__ = {'comment': '用户信息表'}
- user_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='用户ID')
- dept_id = Column(
+ user_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='用户ID'
+ )
+ dept_id: Mapped[int | None] = mapped_column(
BigInteger,
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type, False),
comment='部门ID',
)
- user_name = Column(String(30), nullable=False, comment='用户账号')
- nick_name = Column(String(30), nullable=False, comment='用户昵称')
- user_type = Column(String(2), nullable=True, server_default='00', comment='用户类型(00系统用户)')
- email = Column(String(50), nullable=True, server_default="''", comment='用户邮箱')
- phonenumber = Column(String(11), nullable=True, server_default="''", comment='手机号码')
- sex = Column(CHAR(1), nullable=True, server_default='0', comment='用户性别(0男 1女 2未知)')
- avatar = Column(String(100), nullable=True, server_default="''", comment='头像地址')
- locale = Column(String(63), nullable=False, server_default='zh-CN', comment='语言偏好')
- locale_revision = Column(BigInteger, nullable=False, server_default='0', comment='语言偏好版本')
- time_zone = Column(String(64), nullable=False, server_default='auto', comment='显示时区(auto跟随设备或IANA名称)')
- password = Column(String(100), nullable=True, server_default="''", comment='密码')
- status = Column(CHAR(1), nullable=True, server_default='0', comment='帐号状态(0正常 1停用)')
- del_flag = Column(CHAR(1), nullable=True, server_default='0', comment='删除标志(0代表存在 2代表删除)')
- login_ip = Column(String(128), nullable=True, server_default="''", comment='最后登录IP')
- login_date = Column(DbUtcDateTime(), nullable=True, comment='最后登录时间')
- pwd_update_date = Column(DbUtcDateTime(), nullable=True, comment='密码最后更新时间')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- remark = Column(
+ user_name: Mapped[str] = mapped_column(String(30), nullable=False, comment='用户账号')
+ nick_name: Mapped[str] = mapped_column(String(30), nullable=False, comment='用户昵称')
+ user_type: Mapped[str | None] = mapped_column(
+ String(2), nullable=True, server_default='00', comment='用户类型(00系统用户)'
+ )
+ email: Mapped[str | None] = mapped_column(String(50), nullable=True, server_default="''", comment='用户邮箱')
+ phonenumber: Mapped[str | None] = mapped_column(String(11), nullable=True, server_default="''", comment='手机号码')
+ sex: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='用户性别(0男 1女 2未知)'
+ )
+ avatar: Mapped[str | None] = mapped_column(String(100), nullable=True, server_default="''", comment='头像地址')
+ locale: Mapped[str] = mapped_column(String(63), nullable=False, server_default='zh-CN', comment='语言偏好')
+ locale_revision: Mapped[int] = mapped_column(BigInteger, nullable=False, server_default='0', comment='语言偏好版本')
+ time_zone: Mapped[str] = mapped_column(
+ String(64), nullable=False, server_default='auto', comment='显示时区(auto跟随设备或IANA名称)'
+ )
+ password: Mapped[str | None] = mapped_column(String(100), nullable=True, server_default="''", comment='密码')
+ status: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='帐号状态(0正常 1停用)'
+ )
+ del_flag: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='删除标志(0代表存在 2代表删除)'
+ )
+ login_ip: Mapped[str | None] = mapped_column(String(128), nullable=True, server_default="''", comment='最后登录IP')
+ login_date: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='最后登录时间')
+ pwd_update_date: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='密码最后更新时间')
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ remark: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
@@ -52,8 +67,8 @@ class SysUserRole(Base):
__tablename__ = 'sys_user_role'
__table_args__ = {'comment': '用户和角色关联表'}
- user_id = Column(BigInteger, primary_key=True, nullable=False, comment='用户ID')
- role_id = Column(BigInteger, primary_key=True, nullable=False, comment='角色ID')
+ user_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, nullable=False, comment='用户ID')
+ role_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, nullable=False, comment='角色ID')
class SysUserPost(Base):
@@ -62,5 +77,5 @@ class SysUserPost(Base):
__tablename__ = 'sys_user_post'
__table_args__ = {'comment': '用户与岗位关联表'}
- user_id = Column(BigInteger, primary_key=True, nullable=False, comment='用户ID')
- post_id = Column(BigInteger, primary_key=True, nullable=False, comment='岗位ID')
+ user_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, nullable=False, comment='用户ID')
+ post_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, nullable=False, comment='岗位ID')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/cache_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/cache_vo.py
index e95174a8e..5b3a14ef7 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/cache_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/cache_vo.py
@@ -1,24 +1,21 @@
from typing import Any
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import Field
+from common.vo import CamelModel
-class CacheMonitorModel(BaseModel):
- """缓存监控信息对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
+class CacheMonitorModel(CamelModel):
+ """缓存监控信息对应pydantic模型。"""
command_stats: list | None = Field(default=[], description='命令统计')
db_size: int | None = Field(default=None, description='Key数量')
info: dict | None = Field(default={}, description='Redis信息')
-class CacheInfoModel(BaseModel):
+class CacheInfoModel(CamelModel):
"""缓存监控对象对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
cache_key: str | None = Field(default=None, description='缓存键名')
cache_name: str | None = Field(default=None, description='缓存名称')
cache_value: Any | None = Field(default=None, description='缓存内容')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/common_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/common_vo.py
index 9be1c02be..0ee3ed489 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/common_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/common_vo.py
@@ -1,13 +1,12 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import Field
+from common.vo import CamelModel
-class UploadResponseModel(BaseModel):
- """上传响应模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
+class UploadResponseModel(CamelModel):
+ """上传响应模型。"""
file_name: str | None = Field(default=None, description='新文件映射路径')
new_file_name: str | None = Field(default=None, description='新文件名称')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/config_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/config_vo.py
index 597421b48..be77504f0 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/config_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/config_vo.py
@@ -1,18 +1,18 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field
from pydantic_validation_decorator import NotBlank, Size
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from i18n.message import I18nMessage
-class ConfigModel(BaseModel):
+class ConfigModel(CamelModel):
"""参数配置表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
config_id: int | None = Field(default=None, description='参数主键')
config_name: str | None = Field(default=None, description='参数名称')
@@ -93,9 +93,7 @@ class ConfigPageQueryModel(ConfigQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class DeleteConfigModel(BaseModel):
+class DeleteConfigModel(CamelModel):
"""删除参数配置模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
config_ids: str = Field(description='需要删除的参数主键')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/dept_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/dept_vo.py
index 742063b81..9ebe27d8c 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/dept_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/dept_vo.py
@@ -1,18 +1,18 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field
from pydantic_validation_decorator import Network, NotBlank, Size
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from i18n.message import I18nMessage
-class DeptModel(BaseModel):
+class DeptModel(CamelModel):
"""部门表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
dept_id: int | None = Field(default=None, description='部门id')
parent_id: int | None = Field(default=None, description='父部门id')
@@ -101,31 +101,25 @@ class DeptQueryModel(DateRangeQueryMixin, DeptModel):
end_time: str | None = Field(default=None, description='结束时间')
-class DeptTreeModel(BaseModel):
+class DeptTreeModel(CamelModel):
"""部门树模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
id: int = Field(description='部门id')
label: str = Field(description='部门名称')
parent_id: int = Field(description='父部门id')
children: list['DeptTreeModel'] | None = Field(default=None, description='子部门树')
-class DeleteDeptModel(BaseModel):
+class DeleteDeptModel(CamelModel):
"""删除部门模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
- dept_ids: str = Field(default=None, description='需要删除的部门id')
+ dept_ids: str | None = Field(default=None, description='需要删除的部门id')
update_by: str | None = Field(default=None, description='更新者')
update_time: str | None = Field(default=None, description='更新时间')
-class DeptSortModel(BaseModel):
+class DeptSortModel(CamelModel):
"""部门排序批量保存模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
dept_ids: str = Field(description='需要更新排序的部门id')
order_nums: str = Field(description='部门显示顺序')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/dict_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/dict_vo.py
index 3eea7101e..2205e559f 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/dict_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/dict_vo.py
@@ -1,19 +1,19 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field, field_validator
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field, field_validator
from pydantic_validation_decorator import NotBlank, Pattern, Size
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from i18n.message import I18nMessage
from i18n.translation import TranslationUtil
-class DictTypeBaseModel(BaseModel):
+class DictTypeBaseModel(CamelModel):
"""字典类型表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
dict_id: int | None = Field(default=None, description='字典主键')
dict_name: str | None = Field(default=None, description='字典名称')
@@ -85,10 +85,10 @@ def validate_dict_name_i18n(cls, value: object) -> dict[str, str | None]:
return TranslationUtil.validate(value, 100)
-class DictDataBaseModel(BaseModel):
+class DictDataBaseModel(CamelModel):
"""字典数据表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
dict_code: int | None = Field(default=None, description='字典编码')
dict_sort: int | None = Field(default=None, description='字典排序')
@@ -205,11 +205,9 @@ class DictTypePageQueryModel(DictTypeQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class DeleteDictTypeModel(BaseModel):
+class DeleteDictTypeModel(CamelModel):
"""删除字典类型模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
dict_ids: str = Field(description='需要删除的字典主键')
@@ -227,9 +225,7 @@ class DictDataPageQueryModel(DictDataQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class DeleteDictDataModel(BaseModel):
+class DeleteDictDataModel(CamelModel):
"""删除字典数据模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
dict_codes: str = Field(description='需要删除的字典编码')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/file_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/file_vo.py
index f1e933390..0c04472fc 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/file_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/file_vo.py
@@ -1,10 +1,10 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field
from common.mixin import InstantRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
FileReconcileAction = Literal[
'ignore',
@@ -20,10 +20,10 @@
]
-class FileInfoModel(BaseModel):
+class FileInfoModel(CamelModel):
"""文件信息表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
file_id: str = Field(max_length=36, description='文件ID')
original_name: str = Field(max_length=255, description='原始文件名')
@@ -65,10 +65,10 @@ class FileInfoDisplayModel(FileInfoModel):
)
-class FileReferenceModel(BaseModel):
+class FileReferenceModel(CamelModel):
"""文件业务引用表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
reference_id: int | None = Field(default=None, description='引用ID')
file_id: str = Field(description='文件ID')
@@ -81,10 +81,10 @@ class FileReferenceModel(BaseModel):
legacy: bool = Field(default=False, description='是否为文件主表兼容引用')
-class FileRetentionPolicyModel(BaseModel):
+class FileRetentionPolicyModel(CamelModel):
"""文件业务保留策略模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True, str_strip_whitespace=True)
+ model_config = ConfigDict(from_attributes=True, str_strip_whitespace=True)
business_type: str = Field(min_length=1, max_length=50, description='业务类型')
retention_days: int = Field(ge=1, le=36500, description='保留天数')
@@ -96,10 +96,10 @@ class FileRetentionPolicyModel(BaseModel):
update_time: ApiUtcDateTime | None = Field(default=None, description='更新时间')
-class FileRetentionNoticeModel(BaseModel):
+class FileRetentionNoticeModel(CamelModel):
"""文件保留期限提醒展示模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
notice_id: int = Field(description='提醒ID')
file_id: str = Field(description='文件ID')
@@ -116,11 +116,9 @@ class FileRetentionNoticeModel(BaseModel):
can_dispose: bool = Field(default=False, description='是否允许到期处置')
-class FileRetentionNoticeQueryModel(BaseModel):
+class FileRetentionNoticeQueryModel(CamelModel):
"""文件保留期限提醒不分页查询模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
original_name: str | None = Field(default=None, description='原始文件名')
notice_type: Literal['expiring', 'expired'] | None = Field(default=None, description='提醒类型')
status: Literal['0', '1'] | None = Field(default=None, description='提醒状态')
@@ -133,36 +131,34 @@ class FileRetentionNoticePageQueryModel(FileRetentionNoticeQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class FileRetentionScanModel(BaseModel):
+class FileRetentionScanModel(CamelModel):
"""文件保留期限提醒扫描结果模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
expiring_count: int = Field(default=0, ge=0, description='新增即将到期提醒数')
expired_count: int = Field(default=0, ge=0, description='新增已到期提醒数')
-class ExtendFileRetentionModel(BaseModel):
+class ExtendFileRetentionModel(CamelModel):
"""延长文件保留期限模型。"""
- model_config = ConfigDict(alias_generator=to_camel, str_strip_whitespace=True)
+ model_config = ConfigDict(str_strip_whitespace=True)
expire_time: ApiUtcDateTime = Field(description='新的到期时间')
reason: str = Field(min_length=1, max_length=500, description='延期原因')
-class DisposeExpiredFileModel(BaseModel):
+class DisposeExpiredFileModel(CamelModel):
"""到期文件处置模型。"""
- model_config = ConfigDict(alias_generator=to_camel, str_strip_whitespace=True)
+ model_config = ConfigDict(str_strip_whitespace=True)
reason: str = Field(min_length=1, max_length=500, description='处置原因')
-class FileAccessLogModel(BaseModel):
+class FileAccessLogModel(CamelModel):
"""文件访问审计表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
audit_id: int | None = Field(default=None, description='审计ID')
file_id: str = Field(description='文件ID')
@@ -191,10 +187,10 @@ class FileAccessLogModel(BaseModel):
access_time: ApiUtcDateTime | None = Field(default=None, description='访问时间')
-class FileAclModel(BaseModel):
+class FileAclModel(CamelModel):
"""文件访问控制表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
acl_id: int | None = Field(default=None, description='访问控制ID')
file_id: str = Field(description='文件ID')
@@ -209,11 +205,9 @@ class FileAclModel(BaseModel):
create_time: ApiUtcDateTime | None = Field(default=None, description='创建时间')
-class FileAclItemModel(BaseModel):
+class FileAclItemModel(CamelModel):
"""文件访问控制配置项模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
subject_type: Literal['user', 'role', 'dept'] = Field(description='主体类型')
subject_id: int = Field(gt=0, description='主体ID')
effect: Literal['allow', 'deny'] = Field(description='授权效果')
@@ -221,11 +215,9 @@ class FileAclItemModel(BaseModel):
expire_time: ApiUtcDateTime | None = Field(default=None, description='授权过期时间')
-class FileAclBuiltinPermissionModel(BaseModel):
+class FileAclBuiltinPermissionModel(CamelModel):
"""文件内置访问权限展示模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
source: Literal['admin', 'owner', 'uploader'] = Field(description='权限来源')
subject_id: int | None = Field(default=None, description='权限主体ID')
subject_name: str = Field(description='权限主体名称')
@@ -235,11 +227,9 @@ class FileAclBuiltinPermissionModel(BaseModel):
description: str = Field(description='权限说明')
-class FileAclListModel(BaseModel):
+class FileAclListModel(CamelModel):
"""文件访问控制列表模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
acl_version: int = Field(ge=0, description='访问控制版本')
builtin_permissions: list[FileAclBuiltinPermissionModel] = Field(
default_factory=list, description='文件内置访问权限'
@@ -247,39 +237,31 @@ class FileAclListModel(BaseModel):
entries: list[FileAclModel] = Field(default_factory=list, description='访问控制配置项')
-class SaveFileAclModel(BaseModel):
+class SaveFileAclModel(CamelModel):
"""保存文件访问控制模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
acl_version: int = Field(ge=0, description='访问控制版本')
entries: list[FileAclItemModel] = Field(default_factory=list, max_length=100, description='访问控制配置项')
-class BatchSaveFileAclModel(BaseModel):
+class BatchSaveFileAclModel(CamelModel):
"""批量保存文件访问控制模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
file_ids: str = Field(description='需要授权的文件ID')
entries: list[FileAclItemModel] = Field(default_factory=list, max_length=100, description='访问控制配置项')
-class FileAclSubjectOptionModel(BaseModel):
+class FileAclSubjectOptionModel(CamelModel):
"""文件访问控制主体选项模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
subject_id: int = Field(description='主体ID')
subject_name: str = Field(description='主体名称')
dept_id: int | None = Field(default=None, description='所属部门ID')
-class FileInfoQueryModel(InstantRangeQueryMixin, BaseModel):
+class FileInfoQueryModel(InstantRangeQueryMixin, CamelModel):
"""文件信息管理不分页查询模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
original_name: str | None = Field(default=None, description='原始文件名')
access_type: Literal['public', 'private'] | None = Field(default=None, description='访问类型')
status: Literal['active', 'deleted', 'purging'] | None = Field(default=None, description='文件状态')
@@ -300,11 +282,9 @@ class FileInfoPageQueryModel(FileInfoQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class FileStatsModel(BaseModel):
+class FileStatsModel(CamelModel):
"""文件管理统计模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
total_count: int = Field(default=0, ge=0, description='文件总数')
total_size: int = Field(default=0, ge=0, description='文件总大小')
public_size: int = Field(default=0, ge=0, description='公开文件总大小')
@@ -316,11 +296,9 @@ class FileStatsModel(BaseModel):
acl_expiring_count: int = Field(default=0, ge=0, description='ACL即将过期文件数')
-class FileAccessLogQueryModel(InstantRangeQueryMixin, BaseModel):
+class FileAccessLogQueryModel(InstantRangeQueryMixin, CamelModel):
"""文件访问审计不分页查询模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
action: (
Literal[
'upload',
@@ -349,18 +327,16 @@ class FileAccessLogPageQueryModel(FileAccessLogQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class DeleteFileModel(BaseModel):
+class DeleteFileModel(CamelModel):
"""删除文件模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
file_ids: str = Field(description='需要删除的文件ID')
-class TransferFileModel(BaseModel):
+class TransferFileModel(CamelModel):
"""转移文件模型。"""
- model_config = ConfigDict(alias_generator=to_camel, str_strip_whitespace=True)
+ model_config = ConfigDict(str_strip_whitespace=True)
owner_user_id: int = Field(gt=0, description='新所有者用户ID')
dept_id: int = Field(gt=0, description='新所属部门ID')
@@ -368,10 +344,10 @@ class TransferFileModel(BaseModel):
reason: str = Field(min_length=1, max_length=500, description='转移原因')
-class FileReconcileRunModel(BaseModel):
+class FileReconcileRunModel(CamelModel):
"""文件存储对账任务展示模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
run_id: str = Field(description='任务ID')
trigger_type: Literal['manual', 'scheduled'] = Field(description='触发类型')
@@ -388,21 +364,19 @@ class FileReconcileRunModel(BaseModel):
error_message: str | None = Field(default=None, description='失败原因')
-class FileReconcileRunPageQueryModel(BaseModel):
+class FileReconcileRunPageQueryModel(CamelModel):
"""文件存储对账任务分页查询模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
status: Literal['running', 'completed', 'failed'] | None = Field(default=None, description='任务状态')
trigger_type: Literal['manual', 'scheduled'] | None = Field(default=None, description='触发类型')
page_num: int = Field(default=1, ge=1, description='当前页码')
page_size: int = Field(default=10, ge=1, le=100, description='每页记录数')
-class FileReconcileIssueModel(BaseModel):
+class FileReconcileIssueModel(CamelModel):
"""文件存储对账异常展示模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
issue_id: int = Field(description='异常ID')
issue_key: str = Field(description='异常唯一标识')
@@ -445,11 +419,9 @@ class FileReconcileIssueModel(BaseModel):
available_actions: list[FileReconcileAction] = Field(default_factory=list, description='可用处理动作')
-class FileReconcileIssuePageQueryModel(BaseModel):
+class FileReconcileIssuePageQueryModel(CamelModel):
"""文件存储对账异常分页查询模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
issue_type: str | None = Field(default=None, max_length=32, description='异常类型')
severity: Literal['critical', 'warning', 'info'] | None = Field(default=None, description='严重级别')
status: Literal['open', 'ignored', 'quarantined', 'resolved'] | None = Field(default=None, description='处理状态')
@@ -458,29 +430,25 @@ class FileReconcileIssuePageQueryModel(BaseModel):
page_size: int = Field(default=10, ge=1, le=100, description='每页记录数')
-class FileReconcileStartModel(BaseModel):
+class FileReconcileStartModel(CamelModel):
"""启动文件存储对账模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
check_hash: bool = Field(default=False, description='是否校验文件SHA-256')
-class FileReconcileHandleModel(BaseModel):
+class FileReconcileHandleModel(CamelModel):
"""文件存储对账异常处理模型。"""
- model_config = ConfigDict(alias_generator=to_camel, str_strip_whitespace=True)
+ model_config = ConfigDict(str_strip_whitespace=True)
action: FileReconcileAction = Field(description='处理动作')
reason: str = Field(min_length=1, max_length=500, description='处理原因')
original_name: str | None = Field(default=None, min_length=1, max_length=255, description='登记原始文件名')
-class FileReconcileStatsModel(BaseModel):
+class FileReconcileStatsModel(CamelModel):
"""文件存储对账统计模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
open_count: int = Field(default=0, ge=0, description='待处理异常数')
critical_count: int = Field(default=0, ge=0, description='严重异常数')
warning_count: int = Field(default=0, ge=0, description='警告异常数')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/job_runtime_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/job_runtime_vo.py
index 12e940a6a..d643e11ce 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/job_runtime_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/job_runtime_vo.py
@@ -1,15 +1,15 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
-class JobExecutionModel(BaseModel):
+class JobExecutionModel(CamelModel):
"""可供管理界面查询的执行状态,不包含执行占用凭据。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
execution_id: str = Field(description='执行ID')
job_id: int = Field(description='任务ID')
@@ -27,11 +27,9 @@ class JobExecutionModel(BaseModel):
run_duration_ms: int | None = Field(default=None, description='实际执行耗时(毫秒)')
-class JobExecutionQueryModel(BaseModel):
+class JobExecutionQueryModel(CamelModel):
"""执行记录分页查询条件。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
job_id: int | None = Field(default=None, gt=0, description='任务ID')
execution_id: str | None = Field(
default=None, min_length=32, max_length=32, pattern='^[0-9a-f]{32}$', description='执行ID'
@@ -42,10 +40,10 @@ class JobExecutionQueryModel(BaseModel):
page_size: int = Field(default=10, ge=1, le=100, description='每页记录数')
-class JobSyncModel(BaseModel):
+class JobSyncModel(CamelModel):
"""单任务配置版本和实际应用状态。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
job_id: int = Field(description='任务ID')
config_version: int = Field(description='最新配置版本')
@@ -61,11 +59,9 @@ class JobSyncModel(BaseModel):
update_time: ApiUtcDateTime | None = Field(default=None, description='更新时间')
-class JobSyncQueryModel(BaseModel):
+class JobSyncQueryModel(CamelModel):
"""包含删除记录的同步状态分页查询条件。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
job_id: int | None = Field(default=None, gt=0, description='任务ID')
sync_status: Literal['pending', 'applied', 'failed'] | None = Field(
default=None, description='调度同步状态(pending待同步 applied已生效 failed同步失败)'
@@ -74,11 +70,9 @@ class JobSyncQueryModel(BaseModel):
page_size: int = Field(default=10, ge=1, le=100, description='每页记录数')
-class JobMutationResult(BaseModel):
+class JobMutationResult(CamelModel):
"""业务修改已保存与调度配置已生效分开表达的响应数据。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
saved: bool = Field(description='业务修改是否已提交')
sync_status: Literal['pending', 'applied', 'failed'] = Field(
description='调度同步状态(pending待同步 applied已生效 failed同步失败)'
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/job_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/job_vo.py
index 0f3bf482b..117979b6c 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/job_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/job_vo.py
@@ -1,23 +1,26 @@
-from typing import Any, Literal
+from typing import Any, Generic, Literal
-from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_validator, model_validator
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field, JsonValue, field_validator, model_validator
from pydantic_validation_decorator import NotBlank, Size
+from typing_extensions import TypeVar
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from config.env import AppConfig
from i18n.message import I18nMessage
from utils.cron_util import MyCronTrigger
from utils.time_util import TimezoneUtil
+_JobId = TypeVar('_JobId', bound=int | None, default=int | None)
-class JobModel(BaseModel):
+
+class JobModel(CamelModel, Generic[_JobId]):
"""定时任务调度表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
- job_id: int | None = Field(default=None, gt=0, description='任务ID')
+ job_id: _JobId = Field(default=None, validate_default=True, gt=0, description='任务ID')
job_name: str | None = Field(default=None, max_length=64, description='任务名称(同一业务分组内唯一)')
job_group: str = Field(default='default', min_length=1, max_length=64, description='业务分组')
job_store: Literal['default', 'sqlalchemy', 'redis'] = Field(default='default', description='调度存储')
@@ -143,11 +146,9 @@ def validate_fields(self) -> None:
self.get_cron_expression()
-class JobPreviewRequest(BaseModel):
+class JobPreviewRequest(CamelModel):
"""Cron执行时刻预览请求模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
cron_expression: str = Field(min_length=1, max_length=255, description='Cron 表达式')
time_zone: str = Field(default_factory=lambda: AppConfig.app_timezone, description='任务 IANA 时区')
start_time: ApiUtcDateTime | None = Field(default=None, description='起算时刻,省略时使用服务端当前时刻')
@@ -177,20 +178,18 @@ def validate_cron_expression(cls, value: str) -> str:
return value.strip()
-class JobPreviewResult(BaseModel):
+class JobPreviewResult(CamelModel):
"""Cron执行时刻预览结果模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
time_zone: str = Field(description='任务IANA时区名称')
start_time: ApiUtcDateTime = Field(description='本次预览的UTC起算时刻')
next_run_times: list[ApiUtcDateTime] = Field(description='未来UTC执行时刻列表')
-class JobLogModel(BaseModel):
+class JobLogModel(CamelModel):
"""定时任务调度日志表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
job_log_id: int | None = Field(default=None, description='任务日志ID')
job_id: int | None = Field(default=None, description='逻辑任务ID')
@@ -214,11 +213,9 @@ class JobLogModel(BaseModel):
create_time: ApiUtcDateTime | None = Field(default=None, description='创建时间')
-class JobQueryModel(DateRangeQueryMixin, BaseModel):
+class JobQueryModel(DateRangeQueryMixin, CamelModel):
"""定时任务管理不分页查询模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
job_name: str | None = Field(default=None, description='任务名称')
job_group: str | None = Field(default=None, description='业务分组')
status: Literal['0', '1'] | None = Field(default=None, description='任务状态')
@@ -233,18 +230,16 @@ class JobPageQueryModel(JobQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class EditJobModel(JobModel):
+class EditJobModel(JobModel[int]):
"""编辑定时任务模型。"""
job_id: int = Field(gt=0, description='任务ID')
type: str | None = Field(default=None, description='操作类型')
-class JobRunModel(BaseModel):
+class JobRunModel(CamelModel):
"""手动执行请求,仅按稳定任务ID读取已保存配置。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
job_id: int = Field(gt=0, description='任务ID')
@@ -254,19 +249,15 @@ class ChangeJobStatusModel(JobRunModel):
status: Literal['0', '1'] = Field(description='状态(0正常 1暂停)')
-class DeleteJobModel(BaseModel):
+class DeleteJobModel(CamelModel):
"""删除定时任务模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
job_ids: str = Field(description='需要删除的定时任务ID')
-class JobLogQueryModel(DateRangeQueryMixin, BaseModel):
+class JobLogQueryModel(DateRangeQueryMixin, CamelModel):
"""定时任务日志不分页查询模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
job_id: int | None = Field(default=None, gt=0, description='逻辑任务ID')
execution_id: str | None = Field(default=None, pattern='^[0-9a-f]{32}$', description='执行ID')
job_name: str | None = Field(default=None, description='任务名称快照')
@@ -283,9 +274,7 @@ class JobLogPageQueryModel(JobLogQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class DeleteJobLogModel(BaseModel):
+class DeleteJobLogModel(CamelModel):
"""删除定时任务日志模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
job_log_ids: str = Field(description='需要删除的定时任务日志ID')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/log_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/log_vo.py
index 3f3834d2c..7a577fc60 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/log_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/log_vo.py
@@ -1,16 +1,16 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
-class OperLogModel(BaseModel):
+class OperLogModel(CamelModel):
"""操作日志表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
oper_id: int | None = Field(default=None, description='日志主键')
title: str | None = Field(default=None, description='模块标题')
@@ -35,10 +35,10 @@ class OperLogModel(BaseModel):
cost_time: int | None = Field(default=None, description='消耗时间')
-class LogininforModel(BaseModel):
+class LogininforModel(CamelModel):
"""登录日志表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
info_id: int | None = Field(default=None, description='访问ID')
user_name: str | None = Field(default=None, description='用户账号')
@@ -69,11 +69,9 @@ class OperLogPageQueryModel(OperLogQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class DeleteOperLogModel(BaseModel):
+class DeleteOperLogModel(CamelModel):
"""删除操作日志模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
oper_ids: str = Field(description='需要删除的日志主键')
@@ -95,17 +93,13 @@ class LoginLogPageQueryModel(LoginLogQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class DeleteLoginLogModel(BaseModel):
+class DeleteLoginLogModel(CamelModel):
"""删除登录日志模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
info_ids: str = Field(description='需要删除的访问ID')
-class UnlockUser(BaseModel):
+class UnlockUser(CamelModel):
"""解锁用户模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
user_name: str = Field(description='用户名称')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/login_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/login_vo.py
index a438a9474..267e66837 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/login_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/login_vo.py
@@ -1,17 +1,15 @@
import re
-from pydantic import BaseModel, ConfigDict, Field, model_validator
-from pydantic.alias_generators import to_camel
+from pydantic import BaseModel, Field, model_validator
+from common.vo import CamelModel
from exceptions.exception import ModelValidatorException
from module_admin.entity.vo.menu_vo import MenuModel
-class UserLogin(BaseModel):
+class UserLogin(CamelModel):
"""用户登录所需的凭据和验证信息。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
user_name: str = Field(description='用户名称')
password: str = Field(description='用户密码')
code: str | None = Field(default=None, description='验证码')
@@ -20,19 +18,15 @@ class UserLogin(BaseModel):
captcha_enabled: bool | None = Field(default=None, description='是否启用验证码,前端无需传递')
-class UnlockScreenModel(BaseModel):
+class UnlockScreenModel(CamelModel):
"""用于验证锁屏解锁请求的凭据。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
password: str | None = Field(default=None, description='用户密码')
-class UserRegister(BaseModel):
+class UserRegister(CamelModel):
"""注册新用户时提交的账户资料。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
username: str = Field(description='用户名称')
password: str = Field(description='用户密码')
confirm_password: str = Field(description='用户二次确认密码')
@@ -60,19 +54,15 @@ class Token(BaseModel):
token_type: str = Field(description='token类型')
-class LoginToken(BaseModel):
+class LoginToken(CamelModel):
"""用户登录成功后签发的令牌。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
token: str = Field(description='token信息')
-class CaptchaCode(BaseModel):
+class CaptchaCode(CamelModel):
"""图形验证码响应。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
captcha_enabled: bool = Field(description='是否启用验证码')
register_enabled: bool = Field(description='是否启用注册')
img: str = Field(description='验证码图片')
@@ -91,14 +81,12 @@ class SmsCode(BaseModel):
class MenuTreeModel(MenuModel):
"""表示菜单树中的可选节点。"""
- children: list['MenuTreeModel'] | None | None = Field(default=None, description='子菜单')
+ children: list['MenuTreeModel'] | None = Field(default=None, description='子菜单')
-class MetaModel(BaseModel):
+class MetaModel(CamelModel):
"""描述前端路由的展示及缓存选项。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
title: str | None = Field(default=None, description='设置路由在侧边栏和面包屑中展示的名字')
title_i18n: dict[str, str] = Field(default_factory=dict, alias='titleI18n', description='路由标题译文')
icon: str | None = Field(default=None, description='设置路由的图标')
@@ -107,11 +95,9 @@ class MetaModel(BaseModel):
plugin_id: str | None = Field(default=None, description='由平台菜单归属确定的插件ID')
-class RouterModel(BaseModel):
+class RouterModel(CamelModel):
"""描述用户可访问的前端路由及其子路由。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
name: str | None = Field(default=None, description='路由名称')
path: str | None = Field(default=None, description='路由地址')
hidden: bool | None = Field(default=None, description='是否隐藏路由,当设置 true 的时候该路由不会再侧边栏出现')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/menu_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/menu_vo.py
index 3ca762a1e..4b05c09b7 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/menu_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/menu_vo.py
@@ -1,19 +1,19 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field, field_validator
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field, field_validator
from pydantic_validation_decorator import NotBlank, Size
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from i18n.message import I18nMessage
from i18n.translation import TranslationUtil
-class MenuBaseModel(BaseModel):
+class MenuBaseModel(CamelModel):
"""菜单表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
menu_id: int | None = Field(default=None, description='菜单ID')
menu_name: str | None = Field(default=None, description='菜单名称')
@@ -145,11 +145,9 @@ class MenuQueryModel(DateRangeQueryMixin, MenuBaseModel):
end_time: str | None = Field(default=None, description='结束时间')
-class MenuTreeModel(BaseModel):
+class MenuTreeModel(CamelModel):
"""菜单树模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
id: int = Field(description='菜单id')
label: str = Field(description='菜单名称')
label_i18n: dict[str, str] = Field(default_factory=dict, alias='labelI18n', description='菜单名称译文')
@@ -157,18 +155,14 @@ class MenuTreeModel(BaseModel):
children: list['MenuTreeModel'] | None = Field(default=None, description='子菜单树')
-class DeleteMenuModel(BaseModel):
+class DeleteMenuModel(CamelModel):
"""删除菜单模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
menu_ids: str = Field(description='需要删除的菜单ID')
-class MenuSortModel(BaseModel):
+class MenuSortModel(CamelModel):
"""菜单排序批量保存模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
menu_ids: str = Field(description='需要更新排序的菜单ID')
order_nums: str = Field(description='菜单显示顺序')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/notice_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/notice_vo.py
index 5f9525808..dc1b74a3e 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/notice_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/notice_vo.py
@@ -1,19 +1,19 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field, field_validator
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field, field_validator
from pydantic_validation_decorator import NotBlank, Size, Xss
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from i18n.message import I18nMessage
from utils.security_util import SecurityUtil
-class NoticeModel(BaseModel):
+class NoticeModel(CamelModel):
"""通知公告表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
notice_id: int | None = Field(default=None, description='公告ID')
notice_title: str | None = Field(default=None, description='公告标题')
@@ -78,10 +78,10 @@ class NoticePageQueryModel(NoticeQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class NoticeReadUserModel(BaseModel):
+class NoticeReadUserModel(CamelModel):
"""公告已读用户模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
user_id: int = Field(description='用户ID')
user_name: str = Field(description='用户账号')
@@ -91,30 +91,24 @@ class NoticeReadUserModel(BaseModel):
read_time: ApiUtcDateTime = Field(description='阅读时间')
-class NoticeReadUserPageQueryModel(BaseModel):
+class NoticeReadUserPageQueryModel(CamelModel):
"""公告已读用户分页查询模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
notice_id: int = Field(description='公告ID')
search_value: str | None = Field(default=None, description='登录名称或用户名称')
page_num: int = Field(default=1, description='当前页码')
page_size: int = Field(default=10, description='每页记录数')
-class DeleteNoticeModel(BaseModel):
+class DeleteNoticeModel(CamelModel):
"""删除通知公告模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
notice_ids: str = Field(description='需要删除的公告ID')
-class NoticeTopModel(BaseModel):
+class NoticeTopModel(CamelModel):
"""首页顶部通知公告模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
notice_id: int = Field(description='公告ID')
notice_title: str = Field(description='公告标题')
notice_type: Literal['1', '2'] = Field(description='公告类型(1通知 2公告)')
@@ -124,10 +118,8 @@ class NoticeTopModel(BaseModel):
is_read: bool = Field(default=False, description='是否已读')
-class NoticeTopResponseModel(BaseModel):
+class NoticeTopResponseModel(CamelModel):
"""首页顶部通知公告响应模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
data: list[NoticeTopModel] = Field(description='通知公告列表')
unread_count: int = Field(description='未读数量')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/online_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/online_vo.py
index 8d18fce49..0c3da7681 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/online_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/online_vo.py
@@ -1,15 +1,13 @@
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import Field
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
-class OnlineModel(BaseModel):
+class OnlineModel(CamelModel):
"""在线用户对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
token_id: str | None = Field(default=None, description='会话编号')
user_name: str | None = Field(default=None, description='登录名称')
dept_name: str | None = Field(default=None, description='所属部门')
@@ -27,18 +25,14 @@ class OnlineQueryModel(DateRangeQueryMixin, OnlineModel):
end_time: str | None = Field(default=None, description='结束时间')
-class OnlinePageResponseModel(BaseModel):
+class OnlinePageResponseModel(CamelModel):
"""在线用户分页响应模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
rows: list[OnlineModel] = Field(description='在线用户记录列表')
total: int = Field(description='总记录数')
-class DeleteOnlineModel(BaseModel):
+class DeleteOnlineModel(CamelModel):
"""强退在线用户模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
token_ids: str = Field(description='需要强退的会话编号')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/post_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/post_vo.py
index 37b4f51e0..72b98742a 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/post_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/post_vo.py
@@ -1,18 +1,18 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field
from pydantic_validation_decorator import NotBlank, Size
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from i18n.message import I18nMessage
-class PostModel(BaseModel):
+class PostModel(CamelModel):
"""岗位信息表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
post_id: int | None = Field(default=None, description='岗位ID')
post_code: str | None = Field(default=None, description='岗位编码')
@@ -85,9 +85,7 @@ class PostPageQueryModel(PostQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class DeletePostModel(BaseModel):
+class DeletePostModel(CamelModel):
"""删除岗位模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
post_ids: str = Field(description='需要删除的岗位ID')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/role_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/role_vo.py
index 3da6d77fe..a65a80325 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/role_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/role_vo.py
@@ -1,18 +1,18 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field, field_validator, model_validator
from pydantic_validation_decorator import NotBlank, Size
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from i18n.message import I18nMessage
-class RoleModel(BaseModel):
+class RoleModel(CamelModel):
"""角色表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
role_id: int | None = Field(default=None, description='角色ID')
role_name: str | None = Field(default=None, description='角色名称')
@@ -111,19 +111,19 @@ def validate_fields(self) -> None:
self.get_role_sort()
-class RoleMenuModel(BaseModel):
+class RoleMenuModel(CamelModel):
"""角色和菜单关联表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
role_id: int | None = Field(default=None, description='角色ID')
menu_id: int | None = Field(default=None, description='菜单ID')
-class RoleDeptModel(BaseModel):
+class RoleDeptModel(CamelModel):
"""角色和部门关联表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
role_id: int | None = Field(default=None, description='角色ID')
dept_id: int | None = Field(default=None, description='部门ID')
@@ -143,20 +143,16 @@ class RolePageQueryModel(RoleQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class RoleMenuQueryModel(BaseModel):
+class RoleMenuQueryModel(CamelModel):
"""角色菜单查询模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
menus: list = Field(default=[], description='菜单信息')
checked_keys: list[int] = Field(default=[], description='已选择的菜单ID信息')
-class RoleDeptQueryModel(BaseModel):
+class RoleDeptQueryModel(CamelModel):
"""角色部门查询模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
depts: list = Field(default=[], description='部门信息')
checked_keys: list[int] = Field(default=[], description='已选择的部门ID信息')
@@ -169,11 +165,9 @@ class AddRoleModel(RoleModel):
type: str | None = Field(default=None, description='操作类型')
-class DeleteRoleModel(BaseModel):
+class DeleteRoleModel(CamelModel):
"""删除角色模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
role_ids: str = Field(description='需要删除的角色ID')
update_by: str | None = Field(default=None, description='更新者')
update_time: ApiUtcDateTime | None = Field(default=None, description='更新时间')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/server_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/server_vo.py
index 325d36934..de882d532 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/server_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/server_vo.py
@@ -1,36 +1,30 @@
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import Field
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
-class CpuInfo(BaseModel):
+class CpuInfo(CamelModel):
"""描述处理器的核心数量和使用情况。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
cpu_num: int | None = Field(default=None, description='核心数')
used: float | None = Field(default=None, description='CPU用户使用率')
sys: float | None = Field(default=None, description='CPU系统使用率')
free: float | None = Field(default=None, description='CPU当前空闲率')
-class MemoryInfo(BaseModel):
+class MemoryInfo(CamelModel):
"""描述服务器内存的容量和占用情况。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
total: str | None = Field(default=None, description='内存总量')
used: str | None = Field(default=None, description='已用内存')
free: str | None = Field(default=None, description='剩余内存')
usage: float | None = Field(default=None, description='使用率')
-class SysInfo(BaseModel):
+class SysInfo(CamelModel):
"""描述服务器主机及操作系统信息。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
computer_ip: str | None = Field(default=None, description='服务器IP')
computer_name: str | None = Field(default=None, description='服务器名称')
os_arch: str | None = Field(default=None, description='系统架构')
@@ -41,8 +35,6 @@ class SysInfo(BaseModel):
class PyInfo(MemoryInfo):
"""描述 Python 运行环境及进程信息。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
name: str | None = Field(default=None, description='Python名称')
version: str | None = Field(default=None, description='Python版本')
start_time: ApiUtcDateTime | None = Field(default=None, description='启动时间')
@@ -50,11 +42,9 @@ class PyInfo(MemoryInfo):
home: str | None = Field(default=None, description='安装路径')
-class SysFiles(BaseModel):
+class SysFiles(CamelModel):
"""描述文件系统挂载点及磁盘空间用量。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
dir_name: str | None = Field(default=None, description='盘符路径')
sys_type_name: str | None = Field(default=None, description='盘符类型')
type_name: str | None = Field(default=None, description='文件类型')
@@ -64,11 +54,9 @@ class SysFiles(BaseModel):
usage: str | None = Field(default=None, description='资源的使用率')
-class ServerMonitorModel(BaseModel):
+class ServerMonitorModel(CamelModel):
"""服务监控对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
cpu: CpuInfo | None = Field(description='CPU相关信息')
py: PyInfo | None = Field(description='Python相关信息')
mem: MemoryInfo | None = Field(description='內存相关信息')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/transport_crypto_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/transport_crypto_vo.py
index 2071c400e..30b1453a2 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/transport_crypto_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/transport_crypto_vo.py
@@ -1,14 +1,12 @@
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import Field
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
-class TransportCryptoFrontendConfigModel(BaseModel):
+class TransportCryptoFrontendConfigModel(CamelModel):
"""传输层加解密前端运行配置模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
transport_crypto_enabled: bool = Field(description='后端是否启用传输层加解密')
transport_crypto_mode: str = Field(description='当前传输层加解密模式')
transport_crypto_active: bool = Field(description='前端当前是否应启用传输层加解密')
@@ -23,11 +21,9 @@ class TransportCryptoFrontendConfigModel(BaseModel):
config_expire_at: int = Field(description='前端配置建议刷新时间戳')
-class TransportCryptoPublicKeyModel(BaseModel):
+class TransportCryptoPublicKeyModel(CamelModel):
"""传输层加解密公钥下发模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
kid: str = Field(description='当前启用的密钥版本标识')
envelope_version: str = Field(description='当前传输层加密信封协议版本')
alg: str = Field(description='当前传输层加密算法标识')
@@ -36,11 +32,9 @@ class TransportCryptoPublicKeyModel(BaseModel):
expire_at: int = Field(description='当前公钥建议刷新时间戳')
-class TransportCryptoKidStatModel(BaseModel):
+class TransportCryptoKidStatModel(CamelModel):
"""传输层加解密按密钥版本统计模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
kid: str | None = Field(default=None, description='密钥版本标识')
encrypted_requests: int | None = Field(default=0, description='加密请求次数')
decrypt_success: int | None = Field(default=0, description='请求解密成功次数')
@@ -48,11 +42,9 @@ class TransportCryptoKidStatModel(BaseModel):
encrypted_responses: int | None = Field(default=0, description='加密响应次数')
-class TransportCryptoFailureRecordModel(BaseModel):
+class TransportCryptoFailureRecordModel(CamelModel):
"""传输层加解密最近失败记录模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
time: ApiUtcDateTime | None = Field(default=None, description='失败时间')
method: str | None = Field(default=None, description='请求方法')
path: str | None = Field(default=None, description='请求路径')
@@ -60,11 +52,9 @@ class TransportCryptoFailureRecordModel(BaseModel):
kid: str | None = Field(default=None, description='密钥版本标识')
-class TransportCryptoMonitorModel(BaseModel):
+class TransportCryptoMonitorModel(CamelModel):
"""传输层加解密监控模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
monitor_scope: str | None = Field(default=None, description='监控统计范围,默认基于Redis聚合')
started_at: ApiUtcDateTime | None = Field(default=None, description='当前监控统计起始时间')
app_env: str | None = Field(default=None, description='当前应用环境')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/user_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/user_vo.py
index 101590489..70f8b895e 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/user_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/user_vo.py
@@ -1,12 +1,12 @@
import re
-from typing import Literal
+from typing import Generic, Literal, Self, TypeVar
from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator, model_validator
-from pydantic.alias_generators import to_camel
from pydantic_validation_decorator import Network, NotBlank, Size, Xss
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from exceptions.exception import ModelValidatorException
from i18n.message import I18nMessage
from i18n.registry import LocaleRegistry
@@ -22,14 +22,18 @@ class TokenData(BaseModel):
user_id: int | None = Field(default=None, description='用户ID')
-class UserModel(BaseModel):
- """用户表对应pydantic模型。"""
+_UserId = TypeVar('_UserId', bound=int | None)
+_UserName = TypeVar('_UserName', bound=str | None)
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
- user_id: int | None = Field(default=None, description='用户ID')
+class _UserFields(CamelModel, Generic[_UserId, _UserName]):
+ """用户表字段及其校验规则。"""
+
+ model_config = ConfigDict(from_attributes=True)
+
+ user_id: _UserId = Field(description='用户ID')
dept_id: int | None = Field(default=None, description='部门ID')
- user_name: str | None = Field(default=None, description='用户账号')
+ user_name: _UserName = Field(description='用户账号')
nick_name: str | None = Field(default=None, description='用户昵称')
user_type: str | None = Field(default=None, description='用户类型(00系统用户)')
email: str | None = Field(default=None, description='用户邮箱')
@@ -85,7 +89,7 @@ def validate_time_zone(cls, value: str) -> str:
return TimezoneUtil.validate_timezone_preference(value)
@model_validator(mode='after')
- def check_password(self) -> 'UserModel':
+ def check_password(self) -> Self:
"""
校验密码中是否包含禁止使用的字符。
@@ -98,7 +102,7 @@ def check_password(self) -> 'UserModel':
raise ModelValidatorException(message='密码不能包含非法字符:< > " \' \\ |', msg_key='auth.passwordCharacters')
@model_validator(mode='after')
- def check_admin(self) -> 'UserModel':
+ def check_admin(self) -> Self:
"""
根据用户编号标记管理员用户。
@@ -182,43 +186,50 @@ def validate_fields(self) -> None:
self.get_phonenumber()
+class UserModel(_UserFields[int | None, str | None]):
+ """用户查询和编辑模型,支持按需填写字段。"""
+
+ user_id: int | None = Field(default=None, description='用户ID')
+ user_name: str | None = Field(default=None, description='用户账号')
+
+
class UserRowModel(UserModel):
"""用户列表行数据模型。"""
dept: DeptModel | None = Field(default=None, description='部门信息')
-class UserRoleModel(BaseModel):
+class UserRoleModel(CamelModel):
"""用户和角色关联表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
user_id: int | None = Field(default=None, description='用户ID')
role_id: int | None = Field(default=None, description='角色ID')
-class UserPostModel(BaseModel):
+class UserPostModel(CamelModel):
"""用户与岗位关联表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
user_id: int | None = Field(default=None, description='用户ID')
post_id: int | None = Field(default=None, description='岗位ID')
-class UserInfoModel(UserModel):
+class UserInfoModel(_UserFields[int, str]):
"""用户个人资料及其部门、角色信息。"""
- post_ids: str | None | None = Field(default=None, description='岗位ID信息')
- role_ids: str | None | None = Field(default=None, description='角色ID信息')
- dept: DeptModel | None | None = Field(default=None, description='部门信息')
+ post_ids: str | None = Field(default=None, description='岗位ID信息')
+ role_ids: str | None = Field(default=None, description='角色ID信息')
+ dept: DeptModel | None = Field(default=None, description='部门信息')
role: list[RoleModel | None] | None = Field(default=[], description='角色信息')
-class UpdateUserProfileModel(BaseModel):
+class UpdateUserProfileModel(CamelModel):
"""修改用户个人资料模型。"""
- model_config = ConfigDict(alias_generator=to_camel, extra='forbid')
+ model_config = ConfigDict(extra='forbid')
nick_name: str | None = Field(default=None, max_length=30, description='用户昵称')
email: str | None = Field(default=None, max_length=50, description='用户邮箱')
@@ -226,10 +237,10 @@ class UpdateUserProfileModel(BaseModel):
sex: Literal['0', '1', '2'] | None = Field(default=None, description='用户性别(0男 1女 2未知)')
-class UserTimezoneModel(BaseModel):
+class UserTimezoneModel(CamelModel):
"""当前用户的显示时区偏好模型。"""
- model_config = ConfigDict(alias_generator=to_camel, extra='forbid')
+ model_config = ConfigDict(extra='forbid')
time_zone: str = Field(max_length=64, description='auto跟随设备,或指定IANA时区')
@@ -263,47 +274,39 @@ def validate_locale(cls, value: str) -> str:
return LocaleRegistry.normalize_locale(value, preference=True)
-class CurrentUserModel(BaseModel):
+class CurrentUserModel(CamelModel):
"""当前已认证用户及其权限信息。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
permissions: list = Field(description='权限信息')
roles: list = Field(description='角色信息')
- user: UserInfoModel | None = Field(description='用户信息')
+ user: UserInfoModel = Field(description='用户信息')
app_timezone: str = Field(default='UTC', description='业务时区(IANA)')
pwd_chrtype: str = Field(default='0', description='密码字符范围')
is_default_modify_pwd: bool = Field(default=False, description='是否初始密码修改提醒')
is_password_expired: bool = Field(default=False, description='密码是否过期提醒')
-class UserDetailModel(BaseModel):
+class UserDetailModel(CamelModel):
"""获取用户详情信息响应模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
- data: UserInfoModel | None | None = Field(default=None, description='用户信息')
+ data: UserInfoModel | None = Field(default=None, description='用户信息')
post_ids: list | None = Field(default=None, description='岗位ID信息')
posts: list[PostModel | None] = Field(description='岗位信息')
role_ids: list | None = Field(default=None, description='角色ID信息')
roles: list[RoleModel | None] = Field(description='角色信息')
-class UserProfileModel(BaseModel):
+class UserProfileModel(CamelModel):
"""获取个人信息响应模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
data: UserInfoModel | None = Field(description='用户信息')
post_group: str | None = Field(description='岗位信息')
role_group: str | None = Field(description='角色信息')
-class AvatarModel(BaseModel):
+class AvatarModel(CamelModel):
"""上传头像响应模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
img_url: str = Field(description='头像地址')
@@ -335,11 +338,9 @@ class EditUserModel(AddUserModel):
role: list | None = Field(default=[], description='角色信息')
-class ResetPasswordModel(BaseModel):
+class ResetPasswordModel(CamelModel):
"""重置密码模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
old_password: str | None = Field(default=None, description='旧密码')
new_password: str | None = Field(default=None, description='新密码')
@@ -365,11 +366,9 @@ class ResetUserModel(UserModel):
session_id: str | None = Field(default=None, description='会话id')
-class DeleteUserModel(BaseModel):
+class DeleteUserModel(CamelModel):
"""删除用户模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
user_ids: str = Field(description='需要删除的用户ID')
update_by: str | None = Field(default=None, description='更新者')
update_time: ApiUtcDateTime | None = Field(default=None, description='更新时间')
@@ -379,6 +378,8 @@ class UserRoleQueryModel(UserModel):
"""用户角色关联管理不分页查询模型。"""
role_id: int | None = Field(default=None, description='角色ID')
+ role_name: str | None = Field(default=None, description='用于筛选已分配角色的名称')
+ role_key: str | None = Field(default=None, description='用于筛选已分配角色的权限字符')
class UserRolePageQueryModel(UserRoleQueryModel):
@@ -394,20 +395,16 @@ class SelectedRoleModel(RoleModel):
flag: bool | None = Field(default=False, description='选择标识')
-class UserRoleResponseModel(BaseModel):
+class UserRoleResponseModel(CamelModel):
"""用户角色关联管理列表返回模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
roles: list[SelectedRoleModel | None] = Field(default=[], description='角色信息')
- user: UserInfoModel = Field(description='用户信息')
+ user: UserInfoModel | None = Field(description='用户信息')
-class CrudUserRoleModel(BaseModel):
+class CrudUserRoleModel(CamelModel):
"""新增、删除用户关联角色及角色关联用户模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
user_id: int | None = Field(default=None, description='用户ID')
user_ids: str | None = Field(default=None, description='用户ID信息')
role_id: int | None = Field(default=None, description='角色ID')
diff --git a/ruoyi-fastapi-backend/module_admin/service/cache_service.py b/ruoyi-fastapi-backend/module_admin/service/cache_service.py
index 0d8a85653..5733357dc 100644
--- a/ruoyi-fastapi-backend/module_admin/service/cache_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/cache_service.py
@@ -23,7 +23,7 @@ async def get_cache_monitor_statistical_info_services(cls, request: Request) ->
command_stats = [
{'name': key.split('_')[1], 'value': str(value.get('calls'))} for key, value in command_stats_dict.items()
]
- result = CacheMonitorModel(commandStats=command_stats, dbSize=db_size, info=info)
+ result = CacheMonitorModel(command_stats=command_stats, db_size=db_size, info=info)
return result
@@ -36,9 +36,9 @@ async def get_cache_monitor_cache_name_services(cls) -> list[CacheInfoModel]:
"""
name_list = [
CacheInfoModel(
- cacheKey='',
- cacheName=key_config.key,
- cacheValue='',
+ cache_key='',
+ cache_name=key_config.key,
+ cache_value='',
remark=key_config.remark,
)
for key_config in RedisInitKeyConfig
@@ -74,7 +74,7 @@ async def get_cache_monitor_cache_value_services(
"""
cache_value = await request.app.state.redis.get(f'{cache_name}:{cache_key}')
- return CacheInfoModel(cacheKey=cache_key, cacheName=cache_name, cacheValue=cache_value, remark='')
+ return CacheInfoModel(cache_key=cache_key, cache_name=cache_name, cache_value=cache_value, remark='')
@classmethod
async def clear_cache_monitor_cache_name_services(cls, request: Request, cache_name: str) -> CrudResponseModel:
diff --git a/ruoyi-fastapi-backend/module_admin/service/captcha_service.py b/ruoyi-fastapi-backend/module_admin/service/captcha_service.py
index 3d2160d34..94d6f94da 100644
--- a/ruoyi-fastapi-backend/module_admin/service/captcha_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/captcha_service.py
@@ -10,7 +10,7 @@ class CaptchaService:
"""验证码模块服务层。"""
@classmethod
- async def create_captcha_image_service(cls) -> list[str, int]:
+ async def create_captcha_image_service(cls) -> tuple[str, int]:
"""
创建登录使用的图形验证码。
@@ -54,4 +54,4 @@ async def create_captcha_image_service(cls) -> list[str, int]:
# 将图像数据转换为base64字符串
base64_string = base64.b64encode(buffer.getvalue()).decode()
- return [base64_string, result]
+ return base64_string, result
diff --git a/ruoyi-fastapi-backend/module_admin/service/common_service.py b/ruoyi-fastapi-backend/module_admin/service/common_service.py
index 9d01aa88f..21b0f4a60 100644
--- a/ruoyi-fastapi-backend/module_admin/service/common_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/common_service.py
@@ -19,7 +19,7 @@
from module_admin.entity.do.file_do import SysFileInfo
from module_admin.entity.vo.common_vo import UploadResponseModel
from module_admin.entity.vo.file_vo import FileInfoModel
-from module_admin.entity.vo.user_vo import CurrentUserModel
+from module_admin.entity.vo.user_vo import CurrentUserModel, UserInfoModel
from module_admin.service.file_access_service import FileAuditService
from utils.file_util import FileByteRange, FileDownloadResult, FileUtil
from utils.time_util import TimezoneUtil
@@ -90,22 +90,22 @@ async def upload_service(
try:
file_info = FileInfoModel(
- fileId=file_id,
- originalName=original_filename,
- storedName=filename,
- storageKey=storage_key,
- accessType=access_type,
- uploadUserId=user.user_id,
- ownerUserId=user.user_id,
- deptId=user.dept_id,
+ file_id=file_id,
+ original_name=original_filename,
+ stored_name=filename,
+ storage_key=storage_key,
+ access_type=access_type,
+ upload_user_id=user.user_id,
+ owner_user_id=user.user_id,
+ dept_id=user.dept_id,
extension=extension,
- contentType=file.content_type,
- fileSize=total_size,
- fileHash=file_hash,
- createBy=user.user_name,
- createTime=now,
- updateBy=user.user_name,
- updateTime=now,
+ content_type=file.content_type,
+ file_size=total_size,
+ file_hash=file_hash,
+ create_by=user.user_name,
+ create_time=now,
+ update_by=user.user_name,
+ update_time=now,
)
await FileInfoDao.add_file_info_dao(query_db, file_info)
await query_db.commit()
@@ -143,13 +143,13 @@ async def upload_service(
return CrudResponseModel(
is_success=True,
result=UploadResponseModel(
- fileName=file_name,
- newFileName=filename,
- originalFilename=original_filename,
+ file_name=file_name,
+ new_file_name=filename,
+ original_filename=original_filename,
url=file_url,
- fileId=file_id,
- accessType=access_type,
- downloadUrl=download_path,
+ file_id=file_id,
+ access_type=access_type,
+ download_url=download_path,
),
message='上传成功',
msg_key='file.uploaded',
@@ -360,34 +360,30 @@ async def _has_private_file_download_permission(
return 'allow' in matched_effects
@staticmethod
- def _get_current_user_role_ids(user: object) -> set[int]:
+ def _get_current_user_role_ids(user: UserInfoModel) -> set[int]:
"""
获取当前用户角色ID集合。
:param user: 当前用户对象
:return: 角色ID集合
"""
- role_ids = {
- role.role_id
- for role in (getattr(user, 'role', None) or [])
- if role is not None and getattr(role, 'role_id', None) is not None
- }
- role_ids_text = getattr(user, 'role_ids', None)
+ role_ids = {role.role_id for role in (user.role or []) if role is not None and role.role_id is not None}
+ role_ids_text = user.role_ids
if role_ids_text:
role_ids.update(int(role_id) for role_id in role_ids_text.split(',') if role_id.strip().isdigit())
return role_ids
@staticmethod
- def _get_current_user_dept_ids(user: object) -> tuple[int | None, set[int]]:
+ def _get_current_user_dept_ids(user: UserInfoModel) -> tuple[int | None, set[int]]:
"""
获取当前用户部门及祖级部门ID。
:param user: 当前用户对象
:return: 当前部门ID和祖级部门ID集合
"""
- dept = getattr(user, 'dept', None)
- dept_id = getattr(user, 'dept_id', None) or getattr(dept, 'dept_id', None)
- ancestors = getattr(dept, 'ancestors', None) or ''
+ dept = user.dept
+ dept_id = user.dept_id or (dept.dept_id if dept else None)
+ ancestors = (dept.ancestors if dept else None) or ''
ancestor_dept_ids = {int(ancestor_id) for ancestor_id in ancestors.split(',') if ancestor_id.strip().isdigit()}
return dept_id, ancestor_dept_ids
diff --git a/ruoyi-fastapi-backend/module_admin/service/config_service.py b/ruoyi-fastapi-backend/module_admin/service/config_service.py
index 45d90e6ce..fe6b8eaf1 100644
--- a/ruoyi-fastapi-backend/module_admin/service/config_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/config_service.py
@@ -1,4 +1,4 @@
-from typing import Any
+from typing import Any, Literal, overload
from fastapi import Request
from redis import asyncio as aioredis
@@ -18,6 +18,18 @@
class ConfigService:
"""参数配置管理模块服务层。"""
+ @classmethod
+ @overload
+ async def get_config_list_services(
+ cls, query_db: AsyncSession, query_object: ConfigPageQueryModel, is_page: Literal[True]
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_config_list_services(
+ cls, query_db: AsyncSession, query_object: ConfigPageQueryModel, is_page: Literal[False] = False
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_config_list_services(
cls, query_db: AsyncSession, query_object: ConfigPageQueryModel, is_page: bool = False
@@ -47,11 +59,11 @@ async def init_cache_sys_config_services(cls, query_db: AsyncSession, redis: aio
# 删除匹配的键
if keys:
await redis.delete(*keys)
- config_all = await ConfigDao.get_config_list(query_db, ConfigPageQueryModel(), is_page=False)
+ config_all = await cls.get_config_list_services(query_db, ConfigPageQueryModel(), is_page=False)
for config_obj in config_all:
await redis.set(
f'{RedisInitKeyConfig.SYS_CONFIG.key}:{config_obj.get("configKey")}',
- config_obj.get('configValue'),
+ config_obj['configValue'],
)
@classmethod
@@ -77,7 +89,7 @@ async def check_config_key_unique_services(cls, query_db: AsyncSession, page_obj
:return: 校验结果
"""
config_id = -1 if page_object.config_id is None else page_object.config_id
- config = await ConfigDao.get_config_detail_by_info(query_db, ConfigModel(configKey=page_object.config_key))
+ config = await ConfigDao.get_config_detail_by_info(query_db, ConfigModel(config_key=page_object.config_key))
if config and config.config_id != config_id:
return CommonConstant.NOT_UNIQUE
return CommonConstant.UNIQUE
@@ -179,7 +191,7 @@ async def delete_config_services(
msg_key='config.builtInProtected',
msg_params={'config_key': str(config_info.config_key)},
)
- await ConfigDao.delete_config_dao(query_db, ConfigModel(configId=int(config_id)))
+ await ConfigDao.delete_config_dao(query_db, ConfigModel(config_id=int(config_id)))
delete_config_key_list.append(f'{RedisInitKeyConfig.SYS_CONFIG.key}:{config_info.config_key}')
await query_db.commit()
if delete_config_key_list:
@@ -192,7 +204,7 @@ async def delete_config_services(
raise ServiceException(message='传入参数配置id为空', msg_key='config.idRequired')
@classmethod
- async def config_detail_services(cls, query_db: AsyncSession, config_id: int) -> ConfigModel:
+ async def config_detail_services(cls, query_db: AsyncSession, config_id: int | None) -> ConfigModel:
"""
获取参数配置详细信息service。
@@ -200,6 +212,8 @@ async def config_detail_services(cls, query_db: AsyncSession, config_id: int) ->
:param config_id: 参数配置id
:return: 参数配置id对应的信息
"""
+ if config_id is None:
+ return ConfigModel()
config = await ConfigDao.get_config_detail_by_id(query_db, config_id=config_id)
result = ConfigModel(**CamelCaseUtil.transform_result(config)) if config else ConfigModel()
diff --git a/ruoyi-fastapi-backend/module_admin/service/dept_service.py b/ruoyi-fastapi-backend/module_admin/service/dept_service.py
index b6e0e66e8..7bd81769c 100644
--- a/ruoyi-fastapi-backend/module_admin/service/dept_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/dept_service.py
@@ -68,7 +68,7 @@ async def get_dept_list_services(
@classmethod
async def check_dept_data_scope_services(
- cls, query_db: AsyncSession, dept_id: int, data_scope_sql: ColumnElement
+ cls, query_db: AsyncSession, dept_id: int | None, data_scope_sql: ColumnElement
) -> CrudResponseModel:
"""
校验部门是否有数据权限service。
@@ -79,7 +79,9 @@ async def check_dept_data_scope_services(
:return: 校验结果
:raises ServiceException: 没有权限访问部门数据
"""
- depts = await DeptDao.get_dept_list(query_db, DeptModel(deptId=dept_id), data_scope_sql)
+ if dept_id is None:
+ raise ServiceException(message='没有权限访问部门数据', msg_key='dept.forbidden')
+ depts = await DeptDao.get_dept_list(query_db, DeptModel(dept_id=dept_id), data_scope_sql)
if depts:
return CrudResponseModel(is_success=True, message='校验通过', msg_key='common.validated')
raise ServiceException(message='没有权限访问部门数据', msg_key='dept.forbidden')
@@ -95,7 +97,7 @@ async def check_dept_name_unique_services(cls, query_db: AsyncSession, page_obje
"""
dept_id = -1 if page_object.dept_id is None else page_object.dept_id
dept = await DeptDao.get_dept_detail_by_info(
- query_db, DeptModel(deptName=page_object.dept_name, parentId=page_object.parent_id)
+ query_db, DeptModel(dept_name=page_object.dept_name, parent_id=page_object.parent_id)
)
if dept and dept.dept_id != dept_id:
return CommonConstant.NOT_UNIQUE
@@ -118,6 +120,8 @@ async def add_dept_services(cls, query_db: AsyncSession, page_object: DeptModel)
msg_key='dept.addDuplicate',
msg_params={'dept_name': str(page_object.dept_name)},
)
+ if page_object.parent_id is None:
+ raise ServiceException(message='上级部门不存在', msg_key='dept.parentNotFound')
parent_info = await DeptDao.get_dept_detail_by_id(query_db, page_object.parent_id)
if not parent_info:
raise ServiceException(message='上级部门不存在', msg_key='dept.parentNotFound')
@@ -166,7 +170,7 @@ async def edit_dept_services(cls, query_db: AsyncSession, page_object: DeptModel
)
if (
page_object.status == CommonConstant.DEPT_DISABLE
- and (await DeptDao.count_normal_children_dept_dao(query_db, page_object.dept_id)) > 0
+ and (await DeptDao.count_normal_children_dept_dao(query_db, old_dept.dept_id)) > 0
):
raise ServiceException(
message=f'修改部门{page_object.dept_name}失败,该部门包含未停用的子部门',
@@ -175,6 +179,8 @@ async def edit_dept_services(cls, query_db: AsyncSession, page_object: DeptModel
)
# 根部门使用虚拟父节点 0,其他父部门必须存在且不能是当前部门的后代。
new_ancestors = '0'
+ if page_object.parent_id is None:
+ raise ServiceException(message='上级部门不存在', msg_key='dept.parentNotFound')
if page_object.parent_id != 0:
new_parent_dept = await DeptDao.get_dept_detail_by_id(query_db, page_object.parent_id)
if not new_parent_dept:
@@ -186,7 +192,7 @@ async def edit_dept_services(cls, query_db: AsyncSession, page_object: DeptModel
page_object.ancestors = new_ancestors
try:
if new_ancestors != old_dept.ancestors:
- await cls.update_dept_children(query_db, page_object.dept_id, new_ancestors, old_dept.ancestors)
+ await cls.update_dept_children(query_db, old_dept.dept_id, new_ancestors, old_dept.ancestors)
edit_dept = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'update_time'})
await DeptDao.edit_dept_dao(query_db, edit_dept)
if (
@@ -280,7 +286,7 @@ async def delete_dept_services(cls, query_db: AsyncSession, page_object: DeleteD
if (await DeptDao.count_dept_user_dao(query_db, int(dept_id))) > 0:
raise ServiceWarning(message='部门存在用户,不允许删除', msg_key='dept.usersPreventDelete')
- await DeptDao.delete_dept_dao(query_db, DeptModel(deptId=dept_id))
+ await DeptDao.delete_dept_dao(query_db, DeptModel(dept_id=dept_id))
await query_db.commit()
return CrudResponseModel(is_success=True, message='删除成功', msg_key='common.deleted')
except Exception as e:
@@ -290,7 +296,7 @@ async def delete_dept_services(cls, query_db: AsyncSession, page_object: DeleteD
raise ServiceException(message='传入部门id为空', msg_key='dept.idRequired')
@classmethod
- async def dept_detail_services(cls, query_db: AsyncSession, dept_id: int) -> DeptModel:
+ async def dept_detail_services(cls, query_db: AsyncSession, dept_id: int | None) -> DeptModel:
"""
获取部门详细信息service。
@@ -312,10 +318,13 @@ def list_to_tree(cls, permission_list: Sequence[SysDept]) -> list[DeptTreeModel]
:return: 部门树形嵌套数据
"""
_permission_list = [
- DeptTreeModel(id=item.dept_id, label=item.dept_name, parentId=item.parent_id) for item in permission_list
+ DeptTreeModel(
+ id=item.dept_id, label=item.dept_name or f'部门({item.dept_id})', parent_id=item.parent_id or 0
+ )
+ for item in permission_list
]
# 转成id为key的字典
- mapping: dict[int, DeptTreeModel] = dict(zip([i.id for i in _permission_list], _permission_list, strict=False))
+ mapping = {node.id: node for node in _permission_list}
# 树容器
container: list[DeptTreeModel] = []
@@ -326,11 +335,9 @@ def list_to_tree(cls, permission_list: Sequence[SysDept]) -> list[DeptTreeModel]
if parent is None:
container.append(d)
else:
- children: list[DeptTreeModel] = parent.children
- if not children:
- children = []
- children.append(d)
- parent.children = children
+ if parent.children is None:
+ parent.children = []
+ parent.children.append(d)
return container
@@ -356,12 +363,14 @@ async def update_parent_dept_status_normal(cls, query_db: AsyncSession, dept: De
:param query_db: orm对象
:param dept: 部门对象
"""
+ if not dept.ancestors:
+ return
dept_id_list = dept.ancestors.split(',')
await DeptDao.update_dept_status_normal_dao(query_db, list(map(int, dept_id_list)))
@classmethod
async def update_dept_children(
- cls, query_db: AsyncSession, dept_id: int, new_ancestors: str, old_ancestors: str
+ cls, query_db: AsyncSession, dept_id: int, new_ancestors: str, old_ancestors: str | None
) -> None:
"""
更新子部门信息。
@@ -370,11 +379,14 @@ async def update_dept_children(
:param dept_id: 部门id
:param new_ancestors: 新的祖先
:param old_ancestors: 旧的祖先
+ :raises ValueError: 部门的祖级列表不完整,无法更新子树
"""
children = await DeptDao.get_children_dept_dao(query_db, dept_id)
update_children = []
for child in children:
+ if not child.ancestors or not old_ancestors:
+ raise ValueError('部门祖级列表不完整,无法更新子树')
child_ancestors = await cls.replace_first(child.ancestors, old_ancestors, new_ancestors)
update_children.append({'dept_id': child.dept_id, 'ancestors': child_ancestors})
- if children:
+ if update_children:
await DeptDao.update_dept_children_dao(query_db, update_children)
diff --git a/ruoyi-fastapi-backend/module_admin/service/dict_service.py b/ruoyi-fastapi-backend/module_admin/service/dict_service.py
index 609b953f5..28c89fc37 100644
--- a/ruoyi-fastapi-backend/module_admin/service/dict_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/dict_service.py
@@ -1,7 +1,7 @@
import json
from collections.abc import Sequence
from functools import partial
-from typing import Any
+from typing import Any, Literal, overload
from fastapi import Request
from redis import asyncio as aioredis
@@ -30,6 +30,18 @@
class DictTypeService:
"""字典类型管理模块服务层。"""
+ @classmethod
+ @overload
+ async def get_dict_type_list_services(
+ cls, query_db: AsyncSession, query_object: DictTypePageQueryModel, is_page: Literal[True]
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_dict_type_list_services(
+ cls, query_db: AsyncSession, query_object: DictTypePageQueryModel, is_page: Literal[False] = False
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_dict_type_list_services(
cls, query_db: AsyncSession, query_object: DictTypePageQueryModel, is_page: bool = False
@@ -44,7 +56,7 @@ async def get_dict_type_list_services(
"""
dict_type_list_result = await DictTypeDao.get_dict_type_list(query_db, query_object, is_page)
- rows = dict_type_list_result.rows if is_page else dict_type_list_result
+ rows = dict_type_list_result.rows if isinstance(dict_type_list_result, PageModel) else dict_type_list_result
for row in rows:
row['dictNameI18n'] = row.get('dictNameI18n') or {}
@@ -61,7 +73,7 @@ async def check_dict_type_unique_services(cls, query_db: AsyncSession, page_obje
"""
dict_id = -1 if page_object.dict_id is None else page_object.dict_id
dict_type = await DictTypeDao.get_dict_type_detail_by_info(
- query_db, DictTypeModel(dictType=page_object.dict_type)
+ query_db, DictTypeModel(dict_type=page_object.dict_type)
)
if dict_type and dict_type.dict_id != dict_id:
return CommonConstant.NOT_UNIQUE
@@ -91,12 +103,12 @@ async def add_dict_type_services(
await DictTypeDao.add_dict_type_dao(query_db, page_object)
await query_db.commit()
await DictDataService.publish_dict_cache(query_db, request.app.state.redis, page_object.dict_type)
- result = {'is_success': True, 'message': '新增成功', 'msg_key': 'common.added'}
+ result = CrudResponseModel(is_success=True, message='新增成功', msg_key='common.added')
except Exception as e:
await query_db.rollback()
raise e
- return CrudResponseModel(**result)
+ return result
@classmethod
async def edit_dict_type_services(
@@ -123,14 +135,16 @@ async def edit_dict_type_services(
)
try:
if dict_type_info.dict_type != page_object.dict_type:
- query_dict_data = DictDataPageQueryModel(dictType=dict_type_info.dict_type)
- dict_data_list = await DictDataDao.get_dict_data_list(query_db, query_dict_data, is_page=False)
+ query_dict_data = DictDataPageQueryModel(dict_type=dict_type_info.dict_type)
+ dict_data_list = await DictDataService.get_dict_data_list_services(
+ query_db, query_dict_data, is_page=False
+ )
for dict_data in dict_data_list:
edit_dict_data = DictDataModel(
- dictCode=dict_data['dictCode'],
- dictType=page_object.dict_type,
- updateBy=page_object.update_by,
- updateTime=page_object.update_time,
+ dict_code=dict_data['dictCode'],
+ dict_type=page_object.dict_type,
+ update_by=page_object.update_by,
+ update_time=page_object.update_time,
).model_dump(exclude_unset=True, exclude={'create_time', 'update_time'})
await DictDataDao.edit_dict_data_dao(query_db, edit_dict_data)
await DictTypeDao.edit_dict_type_dao(query_db, edit_dict_type)
@@ -165,13 +179,16 @@ async def delete_dict_type_services(
delete_dict_type_list = []
for dict_id in dict_id_list:
dict_type_into = await cls.dict_type_detail_services(query_db, int(dict_id))
- if (await DictDataDao.count_dict_data_dao(query_db, dict_type_into.dict_type)) > 0:
+ if (
+ dict_type_into.dict_type
+ and (await DictDataDao.count_dict_data_dao(query_db, dict_type_into.dict_type)) > 0
+ ):
raise ServiceException(
message=f'{dict_type_into.dict_name}已分配,不能删除',
msg_key='dict.assigned',
msg_params={'dict_name': str(dict_type_into.dict_name)},
)
- await DictTypeDao.delete_dict_type_dao(query_db, DictTypeModel(dictId=int(dict_id)))
+ await DictTypeDao.delete_dict_type_dao(query_db, DictTypeModel(dict_id=int(dict_id)))
delete_dict_type_list.append(dict_type_into.dict_type)
await query_db.commit()
await DictDataService.publish_dict_cache(query_db, request.app.state.redis, *delete_dict_type_list)
@@ -183,7 +200,7 @@ async def delete_dict_type_services(
raise ServiceException(message='传入字典类型id为空', msg_key='dict.typeIdRequired')
@classmethod
- async def dict_type_detail_services(cls, query_db: AsyncSession, dict_id: int) -> DictTypeModel:
+ async def dict_type_detail_services(cls, query_db: AsyncSession, dict_id: int | None) -> DictTypeModel:
"""
获取字典类型详细信息service。
@@ -191,6 +208,8 @@ async def dict_type_detail_services(cls, query_db: AsyncSession, dict_id: int) -
:param dict_id: 字典类型id
:return: 字典类型id对应的信息
"""
+ if dict_id is None:
+ return DictTypeModel()
dict_type = await DictTypeDao.get_dict_type_detail_by_id(query_db, dict_id=dict_id)
result = DictTypeModel(**CamelCaseUtil.transform_result(dict_type)) if dict_type else DictTypeModel()
@@ -237,14 +256,26 @@ async def refresh_sys_dict_services(cls, request: Request, query_db: AsyncSessio
:return: 刷新字典缓存校验结果
"""
await DictDataService.init_cache_sys_dict_services(query_db, request.app.state.redis)
- result = {'is_success': True, 'message': '刷新成功', 'msg_key': 'common.refreshed'}
+ result = CrudResponseModel(is_success=True, message='刷新成功', msg_key='common.refreshed')
- return CrudResponseModel(**result)
+ return result
class DictDataService:
"""字典数据管理模块服务层。"""
+ @classmethod
+ @overload
+ async def get_dict_data_list_services(
+ cls, query_db: AsyncSession, query_object: DictDataPageQueryModel, is_page: Literal[True]
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_dict_data_list_services(
+ cls, query_db: AsyncSession, query_object: DictDataPageQueryModel, is_page: Literal[False] = False
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_dict_data_list_services(
cls, query_db: AsyncSession, query_object: DictDataPageQueryModel, is_page: bool = False
@@ -259,7 +290,7 @@ async def get_dict_data_list_services(
"""
dict_data_list_result = await DictDataDao.get_dict_data_list(query_db, query_object, is_page)
- rows = dict_data_list_result.rows if is_page else dict_data_list_result
+ rows = dict_data_list_result.rows if isinstance(dict_data_list_result, PageModel) else dict_data_list_result
for row in rows:
row['dictLabelI18n'] = row.get('dictLabelI18n') or {}
@@ -296,7 +327,7 @@ async def init_cache_sys_dict_services(cls, query_db: AsyncSession, redis: aiore
await cls.publish_dict_cache(query_db, redis, *sorted(dict_types))
@staticmethod
- async def publish_dict_cache(query_db: AsyncSession, redis: aioredis.Redis, *dict_types: str) -> None:
+ async def publish_dict_cache(query_db: AsyncSession, redis: aioredis.Redis, *dict_types: str | None) -> None:
"""
将指定字典类型的最新数据写入缓存。
@@ -326,6 +357,8 @@ async def publish_snapshot(pipe: aioredis.client.Pipeline, *, dict_type: str, ca
pipe.delete(cache_key)
for dict_type in dict.fromkeys(dict_types):
+ if not dict_type:
+ continue
cache_key = f'{RedisInitKeyConfig.SYS_DICT.key}:{dict_type}'
await redis.transaction(partial(publish_snapshot, dict_type=dict_type, cache_key=cache_key), cache_key)
@@ -443,7 +476,7 @@ async def delete_dict_data_services(
delete_dict_type_list = []
for dict_code in dict_code_list:
dict_data = await cls.dict_data_detail_services(query_db, int(dict_code))
- await DictDataDao.delete_dict_data_dao(query_db, DictDataModel(dictCode=dict_code))
+ await DictDataDao.delete_dict_data_dao(query_db, DictDataModel(dict_code=dict_code))
delete_dict_type_list.append(dict_data.dict_type)
await query_db.commit()
await cls.publish_dict_cache(query_db, request.app.state.redis, *delete_dict_type_list)
@@ -455,7 +488,7 @@ async def delete_dict_data_services(
raise ServiceException(message='传入字典数据id为空', msg_key='dict.dataIdRequired')
@classmethod
- async def dict_data_detail_services(cls, query_db: AsyncSession, dict_code: int) -> DictDataModel:
+ async def dict_data_detail_services(cls, query_db: AsyncSession, dict_code: int | None) -> DictDataModel:
"""
获取字典数据详细信息service。
@@ -463,6 +496,8 @@ async def dict_data_detail_services(cls, query_db: AsyncSession, dict_code: int)
:param dict_code: 字典数据id
:return: 字典数据id对应的信息
"""
+ if dict_code is None:
+ return DictDataModel()
dict_data = await DictDataDao.get_dict_data_detail_by_id(query_db, dict_code=dict_code)
result = DictDataModel(**CamelCaseUtil.transform_result(dict_data)) if dict_data else DictDataModel()
diff --git a/ruoyi-fastapi-backend/module_admin/service/file_access_service.py b/ruoyi-fastapi-backend/module_admin/service/file_access_service.py
index 1608a9ee1..cc16f23c4 100644
--- a/ruoyi-fastapi-backend/module_admin/service/file_access_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/file_access_service.py
@@ -69,24 +69,24 @@ async def get_file_acl_list_services(
dept_data_scope_sql,
)
return FileAclListModel(
- aclVersion=file_info.acl_version,
- builtinPermissions=cls._build_builtin_permissions(file_info, subject_name_map),
+ acl_version=file_info.acl_version,
+ builtin_permissions=cls._build_builtin_permissions(file_info, subject_name_map),
entries=[
FileAclModel(
- aclId=file_acl.acl_id,
- fileId=file_acl.file_id,
- subjectType=file_acl.subject_type,
- subjectId=file_acl.subject_id,
- subjectName=subject_name_map.get(
+ acl_id=file_acl.acl_id,
+ file_id=file_acl.file_id,
+ subject_type=file_acl.subject_type,
+ subject_id=file_acl.subject_id,
+ subject_name=subject_name_map.get(
(file_acl.subject_type, file_acl.subject_id),
f'不可用或无权查看主体({file_acl.subject_id})',
),
permission=file_acl.permission,
effect=file_acl.effect,
- includeChildren=file_acl.include_children == '1',
- expireTime=file_acl.expire_time,
- createBy=file_acl.create_by,
- createTime=file_acl.create_time,
+ include_children=file_acl.include_children == '1',
+ expire_time=file_acl.expire_time,
+ create_by=file_acl.create_by,
+ create_time=file_acl.create_time,
)
for file_acl in file_acl_list
],
@@ -109,9 +109,9 @@ def _build_builtin_permissions(
builtin_permissions = [
FileAclBuiltinPermissionModel(
source='admin',
- subjectName='平台管理员',
+ subject_name='平台管理员',
enabled=True,
- denyOverridable=False,
+ deny_overridable=False,
description='平台管理员始终允许下载,显式拒绝不能覆盖。',
)
]
@@ -121,13 +121,13 @@ def _build_builtin_permissions(
builtin_permissions.append(
FileAclBuiltinPermissionModel(
source='owner',
- subjectId=owner_user_id,
- subjectName=subject_name_map.get(
+ subject_id=owner_user_id,
+ subject_name=subject_name_map.get(
('user', owner_user_id),
f'不可用或无权查看主体({owner_user_id})',
),
enabled=True,
- denyOverridable=False,
+ deny_overridable=False,
description='文件所有者始终允许下载,显式拒绝不能覆盖。',
)
)
@@ -137,13 +137,13 @@ def _build_builtin_permissions(
builtin_permissions.append(
FileAclBuiltinPermissionModel(
source='uploader',
- subjectId=upload_user_id,
- subjectName=subject_name_map.get(
+ subject_id=upload_user_id,
+ subject_name=subject_name_map.get(
('user', upload_user_id),
f'不可用或无权查看主体({upload_user_id})',
),
enabled=uploader_access_enabled,
- denyOverridable=uploader_access_enabled and not uploader_is_owner,
+ deny_overridable=uploader_access_enabled and not uploader_is_owner,
description=(
(
'当前上传人同时是文件所有者,显式拒绝不能覆盖;所有权转移后按上传人规则判断。'
@@ -516,19 +516,19 @@ async def enqueue_file_audit(
try:
user = current_user.user
file_access_log = FileAccessLogModel(
- fileId=file_id,
+ file_id=file_id,
action=action,
- actorUserId=user.user_id if user else None,
- actorName=user.user_name if user else '',
+ actor_user_id=user.user_id if user else None,
+ actor_name=user.user_name if user else '',
result=result,
- requestId=TraceCtx.get_request_id(),
- traceId=TraceCtx.get_trace_id(),
- ipAddress=ClientIPUtil.get_client_ip(request),
- userAgent=(request.headers.get('User-Agent') or '')[:500],
- bytesSent=bytes_sent,
- errorMessage=error_message[:500],
- operationDetail=cls._serialize_operation_detail(operation_detail),
- accessTime=TimezoneUtil.utc_now(),
+ request_id=TraceCtx.get_request_id(),
+ trace_id=TraceCtx.get_trace_id(),
+ ip_address=ClientIPUtil.get_client_ip(request),
+ user_agent=(request.headers.get('User-Agent') or '')[:500],
+ bytes_sent=bytes_sent,
+ error_message=error_message[:500],
+ operation_detail=cls._serialize_operation_detail(operation_detail),
+ access_time=TimezoneUtil.utc_now(),
)
await LogQueueService.enqueue_file_access_log(
request,
@@ -559,13 +559,13 @@ async def add_system_file_audit(
:param operation_detail: 操作详情
"""
file_access_log = FileAccessLogModel(
- fileId=file_id,
+ file_id=file_id,
action=action,
- actorName='system',
+ actor_name='system',
result=result,
- errorMessage=error_message[:500],
- operationDetail=cls._serialize_operation_detail(operation_detail),
- accessTime=TimezoneUtil.utc_now(),
+ error_message=error_message[:500],
+ operation_detail=cls._serialize_operation_detail(operation_detail),
+ access_time=TimezoneUtil.utc_now(),
)
await FileAccessLogDao.add_file_access_log_dao(query_db, file_access_log)
diff --git a/ruoyi-fastapi-backend/module_admin/service/file_business_service.py b/ruoyi-fastapi-backend/module_admin/service/file_business_service.py
index 0c01b24bb..7c4c88b41 100644
--- a/ruoyi-fastapi-backend/module_admin/service/file_business_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/file_business_service.py
@@ -1,6 +1,6 @@
import uuid
from datetime import timedelta
-from typing import Any
+from typing import Any, Literal, overload
from sqlalchemy import ColumnElement, true
from sqlalchemy.ext.asyncio import AsyncSession
@@ -66,9 +66,9 @@ async def get_file_reference_list_services(
result.insert(
0,
FileReferenceModel(
- fileId=file_id,
- businessType=business_type,
- businessId=business_id,
+ file_id=file_id,
+ business_type=business_type,
+ business_id=business_id,
legacy=True,
),
)
@@ -213,6 +213,16 @@ def _normalize_file_ids(cls, file_ids: list[str]) -> list[str]:
raise ServiceException(message='文件ID格式错误', msg_key='file.business.invalidFileId') from exc
return list(dict.fromkeys(normalized_file_ids))
+ @staticmethod
+ @overload
+ def _normalize_text(value: str | None, field_name: str, max_length: int, required: Literal[True]) -> str: ...
+
+ @staticmethod
+ @overload
+ def _normalize_text(
+ value: str | None, field_name: str, max_length: int, required: Literal[False] = False
+ ) -> str | None: ...
+
@staticmethod
def _normalize_text(value: str | None, field_name: str, max_length: int, required: bool = False) -> str | None:
"""
@@ -502,13 +512,33 @@ async def scan_file_retention_notices_services(
await FileRetentionNoticeDao.add_file_retention_notices(query_db, notice_list)
await query_db.commit()
return FileRetentionScanModel(
- expiringCount=len(expiring_files),
- expiredCount=len(expired_files),
+ expiring_count=len(expiring_files),
+ expired_count=len(expired_files),
)
except Exception:
await query_db.rollback()
raise
+ @classmethod
+ @overload
+ async def get_file_retention_notice_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: FileRetentionNoticePageQueryModel,
+ file_data_scope_sql: ColumnElement,
+ is_page: Literal[True] = True,
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_file_retention_notice_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: FileRetentionNoticePageQueryModel,
+ file_data_scope_sql: ColumnElement,
+ is_page: Literal[False],
+ ) -> list[dict]: ...
+
@classmethod
async def get_file_retention_notice_list_services(
cls,
diff --git a/ruoyi-fastapi-backend/module_admin/service/file_service.py b/ruoyi-fastapi-backend/module_admin/service/file_service.py
index 67e850d7b..605455274 100644
--- a/ruoyi-fastapi-backend/module_admin/service/file_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/file_service.py
@@ -3,7 +3,7 @@
import uuid
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta
-from typing import Any, Literal
+from typing import Any, Literal, overload
from fastapi import Request
from sqlalchemy import ColumnElement
@@ -901,7 +901,7 @@ async def _enqueue_purge_audits(
request: Request | None,
current_user: CurrentUserModel,
file_audit_snapshots: list[FileAuditSnapshot],
- result: str,
+ result: Literal['completed', 'failed'],
error_message: str = '',
) -> None:
"""
@@ -954,6 +954,26 @@ def _validate_purge_parameters(cls, retention_days: int, batch_size: int) -> Non
class FileQueryService:
"""查询文件列表、详情及管理统计。"""
+ @classmethod
+ @overload
+ async def get_file_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: FileInfoPageQueryModel,
+ file_data_scope_sql: ColumnElement,
+ is_page: Literal[True] = True,
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_file_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: FileInfoPageQueryModel,
+ file_data_scope_sql: ColumnElement,
+ is_page: Literal[False],
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_file_list_services(
cls,
@@ -1019,6 +1039,28 @@ async def file_detail_services(
file_info['storage_status'] = await asyncio.to_thread(FileUtil.get_storage_status, file_info)
return FileInfoDisplayModel.model_validate(file_info, by_name=True)
+ @classmethod
+ @overload
+ async def get_file_access_log_list_services(
+ cls,
+ query_db: AsyncSession,
+ file_id: str,
+ query_object: FileAccessLogPageQueryModel,
+ file_data_scope_sql: ColumnElement,
+ is_page: Literal[True] = True,
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_file_access_log_list_services(
+ cls,
+ query_db: AsyncSession,
+ file_id: str,
+ query_object: FileAccessLogPageQueryModel,
+ file_data_scope_sql: ColumnElement,
+ is_page: Literal[False],
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_file_access_log_list_services(
cls,
@@ -1338,6 +1380,26 @@ async def run_scheduled_reconcile_services(cls, check_hash: bool = False) -> Non
return
await cls.execute_reconcile_run_services(reconcile_run.run_id)
+ @classmethod
+ @overload
+ async def get_reconcile_run_list_services(
+ cls,
+ query_db: AsyncSession,
+ current_user: CurrentUserModel,
+ query_object: FileReconcileRunPageQueryModel,
+ is_page: Literal[True] = True,
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_reconcile_run_list_services(
+ cls,
+ query_db: AsyncSession,
+ current_user: CurrentUserModel,
+ query_object: FileReconcileRunPageQueryModel,
+ is_page: Literal[False],
+ ) -> list[FileReconcileRunModel]: ...
+
@classmethod
async def get_reconcile_run_list_services(
cls,
@@ -1370,6 +1432,26 @@ async def get_reconcile_run_list_services(
)
return [FileReconcileRunModel.model_validate(row, by_name=True) for row in run_list]
+ @classmethod
+ @overload
+ async def get_reconcile_issue_list_services(
+ cls,
+ query_db: AsyncSession,
+ current_user: CurrentUserModel,
+ query_object: FileReconcileIssuePageQueryModel,
+ is_page: Literal[True] = True,
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_reconcile_issue_list_services(
+ cls,
+ query_db: AsyncSession,
+ current_user: CurrentUserModel,
+ query_object: FileReconcileIssuePageQueryModel,
+ is_page: Literal[False],
+ ) -> list[FileReconcileIssueModel]: ...
+
@classmethod
async def get_reconcile_issue_list_services(
cls,
@@ -1739,25 +1821,25 @@ async def _register_orphan_file(
await FileInfoDao.add_file_info_dao(
query_db,
FileInfoModel(
- fileId=file_id,
- originalName=original_name,
- storedName=stored_name,
- storageKey=storage_key,
- storageType='local',
- accessType=access_type,
- uploadUserId=user.user_id,
- ownerUserId=user.user_id,
- deptId=user.dept_id,
+ file_id=file_id,
+ original_name=original_name,
+ stored_name=stored_name,
+ storage_key=storage_key,
+ storage_type='local',
+ access_type=access_type,
+ upload_user_id=user.user_id,
+ owner_user_id=user.user_id,
+ dept_id=user.dept_id,
extension=extension,
- contentType=mimetypes.guess_type(original_name)[0] or 'application/octet-stream',
- fileSize=file_size,
- fileHash=file_hash,
+ content_type=mimetypes.guess_type(original_name)[0] or 'application/octet-stream',
+ file_size=file_size,
+ file_hash=file_hash,
status='active',
- createBy=user.user_name,
- createTime=current_time,
- updateBy=user.user_name,
- updateTime=current_time,
- delFlag='0',
+ create_by=user.user_name,
+ create_time=current_time,
+ update_by=user.user_name,
+ update_time=current_time,
+ del_flag='0',
),
)
issue.file_id = file_id
diff --git a/ruoyi-fastapi-backend/module_admin/service/job_log_service.py b/ruoyi-fastapi-backend/module_admin/service/job_log_service.py
index 8056bf86b..127552f32 100644
--- a/ruoyi-fastapi-backend/module_admin/service/job_log_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/job_log_service.py
@@ -1,5 +1,5 @@
import json
-from typing import Any
+from typing import Any, Literal, overload
from fastapi import Request
from sqlalchemy.ext.asyncio import AsyncSession
@@ -17,6 +17,18 @@
class JobLogService:
"""定时任务日志管理模块服务层。"""
+ @classmethod
+ @overload
+ async def get_job_log_list_services(
+ cls, query_db: AsyncSession, query_object: JobLogPageQueryModel, is_page: Literal[True]
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_job_log_list_services(
+ cls, query_db: AsyncSession, query_object: JobLogPageQueryModel, is_page: Literal[False] = False
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_job_log_list_services(
cls, query_db: AsyncSession, query_object: JobLogPageQueryModel, is_page: bool = False
@@ -45,12 +57,12 @@ def add_job_log_services(cls, query_db: Session, page_object: JobLogModel) -> Cr
try:
JobLogDao.add_job_log_dao(query_db, page_object)
query_db.commit()
- result = {'is_success': True, 'message': '新增成功', 'msg_key': 'common.added'}
+ result = CrudResponseModel(is_success=True, message='新增成功', msg_key='common.added')
except Exception as e:
query_db.rollback()
- result = {'is_success': False, 'message': str(e)}
+ result = CrudResponseModel(is_success=False, message=str(e))
- return CrudResponseModel(**result)
+ return result
@classmethod
async def delete_job_log_services(cls, query_db: AsyncSession, page_object: DeleteJobLogModel) -> CrudResponseModel:
@@ -66,15 +78,15 @@ async def delete_job_log_services(cls, query_db: AsyncSession, page_object: Dele
job_log_id_list = page_object.job_log_ids.split(',')
try:
for job_log_id in job_log_id_list:
- await JobLogDao.delete_job_log_dao(query_db, JobLogModel(jobLogId=job_log_id))
+ await JobLogDao.delete_job_log_dao(query_db, JobLogModel(job_log_id=job_log_id))
await query_db.commit()
- result = {'is_success': True, 'message': '删除成功', 'msg_key': 'common.deleted'}
+ result = CrudResponseModel(is_success=True, message='删除成功', msg_key='common.deleted')
except Exception as e:
await query_db.rollback()
raise e
else:
- result = {'is_success': False, 'message': '传入定时任务日志id为空'}
- return CrudResponseModel(**result)
+ result = CrudResponseModel(is_success=False, message='传入定时任务日志id为空')
+ return result
@classmethod
async def clear_job_log_services(cls, query_db: AsyncSession) -> CrudResponseModel:
@@ -88,12 +100,12 @@ async def clear_job_log_services(cls, query_db: AsyncSession) -> CrudResponseMod
try:
await JobLogDao.clear_job_log_dao(query_db)
await query_db.commit()
- result = {'is_success': True, 'message': '清除成功', 'msg_key': 'common.cleared'}
+ result = CrudResponseModel(is_success=True, message='清除成功', msg_key='common.cleared')
except Exception as e:
await query_db.rollback()
raise e
- return CrudResponseModel(**result)
+ return result
@staticmethod
async def export_job_log_list_services(request: Request, job_log_list: list) -> bytes:
@@ -133,7 +145,7 @@ async def export_job_log_list_services(request: Request, job_log_list: list) ->
)
job_executor_option = [
{
- 'label': TranslationUtil.resolve(item.get('dictLabel'), item.get('dictLabelI18n')),
+ 'label': TranslationUtil.resolve(item.get('dictLabel') or '', item.get('dictLabelI18n')),
'value': item.get('dictValue'),
}
for item in job_executor_list
@@ -148,7 +160,7 @@ async def export_job_log_list_services(request: Request, job_log_list: list) ->
else:
item['status'] = I18nMessage('失败', msg_key='export.failure')
if str(item.get('jobExecutor')) in job_executor_option_dict:
- item['jobExecutor'] = job_executor_option_dict.get(str(item.get('jobExecutor'))).get('label')
+ item['jobExecutor'] = job_executor_option_dict[str(item.get('jobExecutor'))]['label']
binary_data = ExcelUtil.export_list2excel(job_log_list, mapping_dict)
return binary_data
diff --git a/ruoyi-fastapi-backend/module_admin/service/job_service.py b/ruoyi-fastapi-backend/module_admin/service/job_service.py
index d58c660be..56bb61643 100644
--- a/ruoyi-fastapi-backend/module_admin/service/job_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/job_service.py
@@ -1,6 +1,6 @@
import json
from datetime import datetime, timedelta
-from typing import Any
+from typing import Any, Literal, overload
from fastapi import Request
from sqlalchemy.ext.asyncio import AsyncSession
@@ -15,7 +15,7 @@
from module_admin.dao.job_dao import JobDao
from module_admin.dao.job_runtime_dao import JobRuntimeDao
from module_admin.entity.vo.job_runtime_vo import JobExecutionQueryModel, JobSyncQueryModel
-from module_admin.entity.vo.job_vo import DeleteJobModel, EditJobModel, JobModel, JobPageQueryModel
+from module_admin.entity.vo.job_vo import DeleteJobModel, EditJobModel, JobModel, JobPageQueryModel, JobRunModel
from module_admin.service.dict_service import DictDataService
from utils.cron_util import CronUtil
from utils.excel_util import ExcelUtil
@@ -72,6 +72,7 @@ async def _after_commit(cls, states: list[dict[str, Any]], action: str) -> CrudR
:return: 业务提交及调度同步结果
"""
job_ids = {state['jobId'] for state in states}
+ sync: dict[str, Any]
try:
sync = await SchedulerManager.request_scheduler_sync(job_ids, immediate=True)
except Exception as exc:
@@ -90,6 +91,18 @@ async def _after_commit(cls, states: list[dict[str, Any]], action: str) -> CrudR
is_success=True, message=message, result={**sync, 'saved': True, 'jobs': list(results.values())}
)
+ @classmethod
+ @overload
+ async def get_job_list_services(
+ cls, query_db: AsyncSession, query_object: JobPageQueryModel, is_page: Literal[True]
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_job_list_services(
+ cls, query_db: AsyncSession, query_object: JobPageQueryModel, is_page: Literal[False] = False
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_job_list_services(
cls, query_db: AsyncSession, query_object: JobPageQueryModel, is_page: bool = False
@@ -125,7 +138,8 @@ def _get_observed_next_run_time(row: dict[str, Any]) -> datetime | None:
return None
if TimezoneUtil.utc_now() - TimezoneUtil.to_utc(observed) > timedelta(seconds=30):
return None
- return row.get('nextRunTime')
+ next_run_time = row.get('nextRunTime')
+ return next_run_time if isinstance(next_run_time, datetime) else None
@staticmethod
def _get_next_valid_time(cron_expression: str | None, time_zone: str | None) -> datetime | None:
@@ -234,7 +248,7 @@ async def edit_job_services(cls, query_db: AsyncSession, page_object: EditJobMod
msg_params={'job_name': str(changed.job_name)},
)
await JobDao.edit_job_dao(query_db, edit_job, job_info)
- state = await JobRuntimeDao.record_configuration(query_db, job_info.job_id, changed)
+ state = await JobRuntimeDao.record_configuration(query_db, db_job.job_id, changed)
await query_db.commit()
except Exception:
await query_db.rollback()
@@ -245,7 +259,7 @@ async def edit_job_services(cls, query_db: AsyncSession, page_object: EditJobMod
async def execute_job_once_services(
cls,
query_db: AsyncSession,
- page_object: JobModel,
+ page_object: JobRunModel | JobModel,
*,
requested_by: str | None = None,
) -> CrudResponseModel:
@@ -259,6 +273,8 @@ async def execute_job_once_services(
:raises Exception: 事务失败并回滚后重新抛出原异常
"""
try:
+ if page_object.job_id is None:
+ raise ServiceException(message='定时任务不存在', msg_key='job.notFound')
db_job, _state = await JobRuntimeDao.lock_job(query_db, page_object.job_id)
if db_job is None:
raise ServiceException(message='定时任务不存在', msg_key='job.notFound')
@@ -296,7 +312,7 @@ async def delete_job_services(cls, query_db: AsyncSession, page_object: DeleteJo
try:
for job_id in job_id_list:
await JobRuntimeDao.lock_job(query_db, job_id)
- await JobDao.delete_job_dao(query_db, JobModel(jobId=job_id))
+ await JobDao.delete_job_dao(query_db, JobModel(job_id=job_id))
state = await JobRuntimeDao.record_configuration(query_db, job_id, None)
states.append(JobRuntimeDao.state_result(state))
await JobRuntimeDao.cancel_unstarted(query_db, job_id_list)
@@ -426,7 +442,7 @@ async def export_job_list_services(request: Request, job_list: list) -> bytes:
)
job_executor_option = [
{
- 'label': TranslationUtil.resolve(item.get('dictLabel'), item.get('dictLabelI18n')),
+ 'label': TranslationUtil.resolve(item.get('dictLabel') or '', item.get('dictLabelI18n')),
'value': item.get('dictValue'),
}
for item in job_executor_list
@@ -439,7 +455,7 @@ async def export_job_list_services(request: Request, job_list: list) -> bytes:
else:
item['status'] = I18nMessage('暂停', msg_key='export.paused')
if str(item.get('jobExecutor')) in job_executor_option_dict:
- item['jobExecutor'] = job_executor_option_dict.get(str(item.get('jobExecutor'))).get('label')
+ item['jobExecutor'] = job_executor_option_dict[str(item.get('jobExecutor'))]['label']
item['misfireGraceTime'] = (
item.get('misfireGraceTime')
if item.get('misfireGraceTime') is not None
diff --git a/ruoyi-fastapi-backend/module_admin/service/log_service.py b/ruoyi-fastapi-backend/module_admin/service/log_service.py
index 32b12f516..f00af99bf 100644
--- a/ruoyi-fastapi-backend/module_admin/service/log_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/log_service.py
@@ -3,10 +3,12 @@
import json
import os
import uuid
-from typing import Any
+from collections.abc import Iterator, Mapping, Sequence
+from typing import Any, Literal, overload
from fastapi import Request
from redis import asyncio as aioredis
+from redis.typing import XReadGroupResponse, XReadGroupStreamResponse
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import CrudResponseModel, PageModel
@@ -32,10 +34,24 @@
from utils.excel_util import ExcelUtil
from utils.log_util import LogSanitizer, logger
+LogStreamBatch = tuple[str | bytes, list[tuple[str | bytes, dict[str, str]]]]
+
class OperationLogService:
"""操作日志管理模块服务层。"""
+ @classmethod
+ @overload
+ async def get_operation_log_list_services(
+ cls, query_db: AsyncSession, query_object: OperLogPageQueryModel, is_page: Literal[True]
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_operation_log_list_services(
+ cls, query_db: AsyncSession, query_object: OperLogPageQueryModel, is_page: Literal[False] = False
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_operation_log_list_services(
cls, query_db: AsyncSession, query_object: OperLogPageQueryModel, is_page: bool = False
@@ -87,7 +103,7 @@ async def delete_operation_log_services(
oper_id_list = page_object.oper_ids.split(',')
try:
for oper_id in oper_id_list:
- await OperationLogDao.delete_operation_log_dao(query_db, OperLogModel(operId=oper_id))
+ await OperationLogDao.delete_operation_log_dao(query_db, OperLogModel(oper_id=oper_id))
await query_db.commit()
return CrudResponseModel(is_success=True, message='删除成功', msg_key='common.deleted')
except Exception as e:
@@ -147,7 +163,7 @@ async def export_operation_log_list_services(cls, request: Request, operation_lo
)
operation_type_option = [
{
- 'label': TranslationUtil.resolve(item.get('dictLabel'), item.get('dictLabelI18n')),
+ 'label': TranslationUtil.resolve(item.get('dictLabel') or '', item.get('dictLabelI18n')),
'value': item.get('dictValue'),
}
for item in operation_type_list
@@ -160,7 +176,7 @@ async def export_operation_log_list_services(cls, request: Request, operation_lo
else:
item['status'] = I18nMessage('失败', msg_key='export.failure')
if str(item.get('businessType')) in operation_type_option_dict:
- item['businessType'] = operation_type_option_dict.get(str(item.get('businessType'))).get('label')
+ item['businessType'] = operation_type_option_dict[str(item.get('businessType'))]['label']
binary_data = ExcelUtil.export_list2excel(operation_log_list, mapping_dict)
return binary_data
@@ -169,6 +185,18 @@ async def export_operation_log_list_services(cls, request: Request, operation_lo
class LoginLogService:
"""登录日志管理模块服务层。"""
+ @classmethod
+ @overload
+ async def get_login_log_list_services(
+ cls, query_db: AsyncSession, query_object: LoginLogPageQueryModel, is_page: Literal[True]
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_login_log_list_services(
+ cls, query_db: AsyncSession, query_object: LoginLogPageQueryModel, is_page: Literal[False] = False
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_login_log_list_services(
cls, query_db: AsyncSession, query_object: LoginLogPageQueryModel, is_page: bool = False
@@ -220,7 +248,7 @@ async def delete_login_log_services(
info_id_list = page_object.info_ids.split(',')
try:
for info_id in info_id_list:
- await LoginLogDao.delete_login_log_dao(query_db, LogininforModel(infoId=info_id))
+ await LoginLogDao.delete_login_log_dao(query_db, LogininforModel(info_id=info_id))
await query_db.commit()
return CrudResponseModel(is_success=True, message='删除成功', msg_key='common.deleted')
except Exception as e:
@@ -410,7 +438,7 @@ async def _acquire_dedup(cls, redis: aioredis.Redis, event_id: str) -> bool:
if not event_id:
return False
key = f'{LogConfig.log_stream_dedup_prefix}:{event_id}'
- return await redis.set(key, '1', nx=True, ex=LogConfig.log_stream_dedup_ttl)
+ return bool(await redis.set(key, '1', nx=True, ex=LogConfig.log_stream_dedup_ttl))
@classmethod
async def _release_dedup(cls, redis: aioredis.Redis, event_id: str) -> None:
@@ -453,6 +481,46 @@ async def _claim_pending(cls, redis: aioredis.Redis, consumer_name: str) -> None
return
start_id = next_start_id
+ @staticmethod
+ def _stream_batches(
+ response: XReadGroupResponse,
+ ) -> Iterator[LogStreamBatch]:
+ """
+ 将 Redis 的流读取响应整理成每个流一批消息,兼容 RESP2 和 RESP3。
+
+ :param response: 消费组的读取结果
+ :yield: 流名称和保留顺序的消息列表
+ """
+ streams = response.items() if isinstance(response, dict) else response
+ for stream_name, entries in streams:
+ batch = LogAggregatorService._decode_stream_batch(stream_name, entries)
+ if batch is not None:
+ yield batch
+
+ @staticmethod
+ def _decode_stream_batch(
+ stream_name: str | bytes, entries: XReadGroupStreamResponse | list[XReadGroupStreamResponse]
+ ) -> LogStreamBatch | None:
+ """
+ 解码单个日志流的消息字段,并跳过已删除的消息。
+
+ :param stream_name: Redis 返回的流名称
+ :param entries: 当前流的消息或旧版 RESP3 返回的嵌套消息列表
+ :return: 流名称与消息列表,没有有效消息时返回 None
+ """
+ messages = []
+ for item in entries:
+ for message_id, fields, *_ in item if isinstance(item, list) else (item,):
+ if message_id is not None:
+ decoded_fields = {
+ key.decode() if isinstance(key, bytes) else key: value.decode()
+ if isinstance(value, bytes)
+ else value
+ for key, value in (fields or {}).items()
+ }
+ messages.append((message_id, decoded_fields))
+ return (stream_name, messages) if messages else None
+
@classmethod
async def consume_stream(cls, redis: aioredis.Redis) -> None:
"""
@@ -479,7 +547,7 @@ async def consume_stream(cls, redis: aioredis.Redis) -> None:
)
if not result:
continue
- for stream_name, messages in result:
+ for stream_name, messages in cls._stream_batches(result):
await cls._process_messages(redis, stream_name, messages)
except asyncio.CancelledError:
raise
@@ -488,7 +556,9 @@ async def consume_stream(cls, redis: aioredis.Redis) -> None:
await asyncio.sleep(1)
@classmethod
- async def _process_messages(cls, redis: aioredis.Redis, stream_name: str, messages: list[tuple[str, dict]]) -> None:
+ async def _process_messages(
+ cls, redis: aioredis.Redis, stream_name: str | bytes, messages: Sequence[tuple[str | bytes, Mapping[str, str]]]
+ ) -> None:
"""
处理消息并落库。
@@ -500,14 +570,14 @@ async def _process_messages(cls, redis: aioredis.Redis, stream_name: str, messag
if not messages:
return
async with DataSourceRegistry.session() as session:
- ack_ids: list[str] = []
+ ack_ids: list[str | bytes] = []
dedup_event_ids: list[str] = []
try:
for message_id, data in messages:
event_type = data.get('event_type')
event_id = data.get('event_id')
payload_raw = data.get('payload') or '{}'
- if event_type not in {'login', 'operation', 'file_access'}:
+ if not isinstance(event_id, str) or event_type not in {'login', 'operation', 'file_access'}:
ack_ids.append(message_id)
continue
acquired = await cls._acquire_dedup(redis, event_id)
diff --git a/ruoyi-fastapi-backend/module_admin/service/login_service.py b/ruoyi-fastapi-backend/module_admin/service/login_service.py
index d8001419c..16e38c1e4 100644
--- a/ruoyi-fastapi-backend/module_admin/service/login_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/login_service.py
@@ -10,6 +10,7 @@
from sqlalchemy import Engine, Row
from sqlalchemy.exc import UnboundExecutionError
from sqlalchemy.ext.asyncio import AsyncSession
+from starlette.requests import HTTPConnection
from common.aspect.db_session import DBSessionDependency
from common.auth_policy import AuthPolicy
@@ -30,7 +31,6 @@
AddUserModel,
CurrentUserModel,
ResetUserModel,
- TokenData,
UserInfoModel,
UserLocaleModel,
)
@@ -53,7 +53,7 @@
class PreAuthOAuth2PasswordBearer(OAuth2PasswordBearer):
"""支持公开路由排除的登录令牌依赖。"""
- async def __call__(self, request: Request) -> str | None:
+ async def __call__(self, request: HTTPConnection) -> str | None:
"""
根据路由认证要求读取登录令牌。
@@ -62,6 +62,8 @@ async def __call__(self, request: Request) -> str | None:
:raises AuthException: 用户未登录,请先完成登录;用户token已失效,请重新登录
:raises HTTPException: 当前路由要求认证且请求未提供有效凭据
"""
+ if not isinstance(request, Request):
+ return await super().__call__(request)
mode = AuthPolicy.get_auth_mode(request, (LoginService.get_current_user, oauth2_scheme))
if mode == 'excluded':
return None
@@ -151,7 +153,7 @@ class LoginService:
@classmethod
async def authenticate_user(
cls, request: Request, query_db: AsyncSession, login_user: UserLogin
- ) -> Row[tuple[SysUser, SysDept]]:
+ ) -> Row[SysUser, SysDept | None]:
"""
根据用户名密码校验用户登录。
@@ -193,7 +195,7 @@ async def unlock_screen_services(
user = await UserDao.get_user_by_name(query_db, current_user.user.user_name)
if not user:
raise ServiceException(message='服务器超时,请重新登录', msg_key='auth.serverTimeout')
- if not PwdUtil.verify_password(password, user.password):
+ if not user.password or not PwdUtil.verify_password(password, user.password):
raise ServiceException(message='密码错误,请重新输入', msg_key='auth.incorrectPassword')
return True
@@ -217,9 +219,9 @@ async def create_access_token(cls, data: dict, expires_delta: timedelta | None =
@classmethod
async def get_current_user(
cls,
- request: Request = Request,
- token: str | None = Depends(oauth2_scheme),
- query_db: AsyncSession = DBSessionDependency(),
+ request: Request,
+ token: Annotated[str | None, Depends(oauth2_scheme)],
+ query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> CurrentUserModel | None:
"""
根据token获取当前用户信息。
@@ -268,23 +270,23 @@ async def _resolve_current_user(
if token.startswith('Bearer '):
token = token.removeprefix('Bearer ').strip()
payload = JwtUtil.decode(token)
- user_id: str = payload.get('user_id')
- session_id: str = payload.get('session_id')
- if not user_id:
+ user_id = payload.get('user_id')
+ session_id = payload.get('session_id')
+ if not user_id or (AppConfig.app_same_time_login and not session_id):
logger.warning('用户token不合法')
raise AuthException(data='', message='用户token不合法', msg_key='auth.invalidToken')
- token_data = TokenData(user_id=int(user_id))
+ authenticated_user_id = int(user_id)
except (TypeError, ValueError) as e:
logger.warning('用户token已失效,请重新登录')
raise AuthException(data='', message='用户token已失效,请重新登录', msg_key='auth.tokenExpired') from e
redis = request.app.state.redis
- token_key = f'{RedisInitKeyConfig.ACCESS_TOKEN.key}:{session_id if AppConfig.app_same_time_login else token_data.user_id}'
+ token_key = f'{RedisInitKeyConfig.ACCESS_TOKEN.key}:{session_id if AppConfig.app_same_time_login else authenticated_user_id}'
redis_token = await redis.get(token_key)
if token != redis_token:
logger.warning('用户token已失效,请重新登录')
raise AuthException(data='', message='用户token已失效,请重新登录', msg_key='auth.tokenExpired')
- current_user = await cls._get_current_user_snapshot(redis, query_db, token_data.user_id)
+ current_user = await cls._get_current_user_snapshot(redis, query_db, authenticated_user_id)
# 密码策略及过期状态在本次鉴权时计算
current_user.app_timezone = AppConfig.app_timezone
current_user.pwd_chrtype = await cls.get_sys_account_chrtype(request)
@@ -381,8 +383,8 @@ async def _get_current_user_from_db(cls, query_db: AsyncSession, user_id: int) -
roles=[role.role_key for role in roles],
user=UserInfoModel(
**user_info,
- postIds=','.join(str(post.post_id) for post in query_user.get('user_post_info') or []),
- roleIds=','.join(str(role.role_id) for role in roles),
+ post_ids=','.join(str(post.post_id) for post in query_user.get('user_post_info') or []),
+ role_ids=','.join(str(role.role_id) for role in roles),
dept=CamelCaseUtil.transform_result(query_user.get('user_dept_info')),
role=CamelCaseUtil.transform_result(roles),
),
@@ -399,10 +401,12 @@ async def get_sys_account_chrtype(cls, request: Request) -> str:
"""
pwd_chrtype = await request.app.state.redis.get(f'{RedisInitKeyConfig.SYS_CONFIG.key}:sys.account.chrtype')
- return pwd_chrtype or '0'
+ if isinstance(pwd_chrtype, bytes):
+ return pwd_chrtype.decode() or '0'
+ return pwd_chrtype if isinstance(pwd_chrtype, str) and pwd_chrtype else '0'
@classmethod
- async def __init_password_is_modify(cls, request: Request, pwd_update_date: datetime) -> bool:
+ async def __init_password_is_modify(cls, request: Request, pwd_update_date: datetime | None) -> bool:
"""
判断当前用户是否初始密码登录。
@@ -413,10 +417,10 @@ async def __init_password_is_modify(cls, request: Request, pwd_update_date: date
init_password_is_modify = await request.app.state.redis.get(
f'{RedisInitKeyConfig.SYS_CONFIG.key}:sys.account.initPasswordModify'
)
- return init_password_is_modify == '1' and pwd_update_date is None
+ return pwd_update_date is None and bool(init_password_is_modify == '1')
@classmethod
- async def __password_is_expired(cls, request: Request, pwd_update_date: datetime) -> bool:
+ async def __password_is_expired(cls, request: Request, pwd_update_date: datetime | None) -> bool:
"""
判断当前用户密码是否过期。
@@ -448,7 +452,7 @@ async def get_current_user_routers(cls, user_id: int, query_db: AsyncSession) ->
user_router_menu = sorted(
[
row
- for row in query_user.get('user_menu_info')
+ for row in query_user['user_menu_info']
if row.menu_type in [MenuConstant.TYPE_DIR, MenuConstant.TYPE_MENU]
],
key=lambda x: x.order_num,
@@ -493,6 +497,7 @@ def __generate_user_router_menu(
"""
router_list: list[RouterModel] = []
for permission in permission_list:
+ title_translations = {key: text for key, text in permission.menu_name_i18n.items() if text is not None}
router = RouterModel(
hidden=permission.visible == '1',
name=RouterUtil.get_router_name(permission),
@@ -501,9 +506,9 @@ def __generate_user_router_menu(
query=permission.query,
meta=MetaModel(
title=permission.menu_name,
- titleI18n=permission.menu_name_i18n or {},
+ title_i18n=title_translations,
icon=permission.icon,
- noCache=permission.is_cache == 1,
+ no_cache=permission.is_cache == 1,
link=permission.path if RouterUtil.is_http(permission.path) else None,
),
)
@@ -521,9 +526,9 @@ def __generate_user_router_menu(
name=RouterUtil.get_route_name(permission.route_name, permission.path),
meta=MetaModel(
title=permission.menu_name,
- titleI18n=permission.menu_name_i18n or {},
+ title_i18n=title_translations,
icon=permission.icon,
- noCache=permission.is_cache == 1,
+ no_cache=permission.is_cache == 1,
link=permission.path if RouterUtil.is_http(permission.path) else None,
),
query=permission.query,
@@ -531,19 +536,17 @@ def __generate_user_router_menu(
children_list.append(children)
router.children = children_list
elif permission.parent_id == MenuConstant.ROOT_ID and RouterUtil.is_inner_link(permission):
- router.meta = MetaModel(
- title=permission.menu_name, titleI18n=permission.menu_name_i18n or {}, icon=permission.icon
- )
+ router.meta = MetaModel(title=permission.menu_name, title_i18n=title_translations, icon=permission.icon)
router.path = '/'
children_list: list[RouterModel] = []
- router_path = RouterUtil.inner_link_replace_each(permission.path)
+ router_path = RouterUtil.inner_link_replace_each(permission.path or '')
children = RouterModel(
path=router_path,
component=MenuConstant.INNER_LINK,
name=RouterUtil.get_route_name(permission.route_name, permission.path),
meta=MetaModel(
title=permission.menu_name,
- titleI18n=permission.menu_name_i18n or {},
+ title_i18n=title_translations,
icon=permission.icon,
link=permission.path if RouterUtil.is_http(permission.path) else None,
),
@@ -596,10 +599,10 @@ async def register_user_services(
request.app.state.redis, user_register.password, PasswordCharacterType.DEFAULT
)
add_user = AddUserModel(
- userName=user_register.username,
- nickName=user_register.username,
+ user_name=user_register.username,
+ nick_name=user_register.username,
password=PwdUtil.get_password_hash(user_register.password),
- pwdUpdateDate=TimezoneUtil.utc_now(),
+ pwd_update_date=TimezoneUtil.utc_now(),
)
result = await UserService.add_user_services(query_db, add_user)
return result
@@ -619,7 +622,7 @@ async def get_sms_code_services(cls, request: Request, query_db: AsyncSession, u
redis_sms_result = await request.app.state.redis.get(f'{RedisInitKeyConfig.SMS_CODE.key}:{user.session_id}')
if redis_sms_result:
return SmsCode(is_success=False, sms_code='', session_id='', message='短信验证码仍在有效期内')
- is_user = await UserDao.get_user_by_name(query_db, user.user_name)
+ is_user = await UserDao.get_user_by_name(query_db, user.user_name) if user.user_name else None
if is_user:
sms_code = str(random.randint(100000, 999999))
session_id = str(uuid.uuid4())
@@ -648,21 +651,20 @@ async def forget_user_services(
redis_sms_result = await request.app.state.redis.get(
f'{RedisInitKeyConfig.SMS_CODE.key}:{forget_user.session_id}'
)
- if forget_user.sms_code == redis_sms_result:
- await UserService.validate_password_services(
- request.app.state.redis, forget_user.password, PasswordCharacterType.DEFAULT
- )
- forget_user.password = PwdUtil.get_password_hash(forget_user.password)
- forget_user.user_id = (await UserDao.get_user_by_name(query_db, forget_user.user_name)).user_id
- edit_result = await UserService.reset_user_services(query_db, forget_user)
- result = edit_result.dict()
- elif not redis_sms_result:
- result = {'is_success': False, 'message': '短信验证码已过期'}
- else:
+ if not redis_sms_result:
+ return CrudResponseModel(is_success=False, message='短信验证码已过期')
+ if forget_user.sms_code != redis_sms_result:
await request.app.state.redis.delete(f'{RedisInitKeyConfig.SMS_CODE.key}:{forget_user.session_id}')
- result = {'is_success': False, 'message': '短信验证码不正确'}
+ return CrudResponseModel(is_success=False, message='短信验证码不正确')
- return CrudResponseModel(**result)
+ user = await UserDao.get_user_by_name(query_db, forget_user.user_name) if forget_user.user_name else None
+ if user is None:
+ return CrudResponseModel(is_success=False, message='用户不存在', msg_key='user.notFound')
+ await UserService.validate_password_services(
+ request.app.state.redis, forget_user.password, PasswordCharacterType.DEFAULT
+ )
+ forget_user.user_id = user.user_id
+ return await UserService.reset_user_services(query_db, forget_user)
@classmethod
async def logout_services(cls, request: Request, token_id: str, token: str) -> bool:
@@ -700,7 +702,7 @@ def get_router_name(cls, menu: MenuTreeModel) -> str:
return cls.get_route_name(menu.route_name, menu.path)
@classmethod
- def get_route_name(cls, name: str, path: str) -> str:
+ def get_route_name(cls, name: str | None, path: str | None) -> str:
"""
获取路由名称,如没有配置路由名称则取路由地址。
@@ -708,7 +710,7 @@ def get_route_name(cls, name: str, path: str) -> str:
:param path: 路由地址
:return: 路由名称(驼峰格式)
"""
- router_name = name if name else path
+ router_name = name or path or ''
return router_name.capitalize()
@classmethod
@@ -722,7 +724,7 @@ def get_router_path(cls, menu: MenuTreeModel) -> str | None:
# 内链打开外网方式
router_path = menu.path
if menu.parent_id != MenuConstant.ROOT_ID and cls.is_inner_link(menu):
- router_path = cls.inner_link_replace_each(router_path)
+ router_path = cls.inner_link_replace_each(router_path or '')
# 非外链并且是一级目录(类型为目录)
if (
menu.parent_id == MenuConstant.ROOT_ID
@@ -791,14 +793,14 @@ def is_parent_view(cls, menu: MenuTreeModel) -> bool:
return menu.parent_id != MenuConstant.ROOT_ID and menu.menu_type == MenuConstant.TYPE_DIR
@classmethod
- def is_http(cls, link: str) -> bool:
+ def is_http(cls, link: str | None) -> bool:
"""
判断是否为http(s)://开头。
:param link: 链接
:return: 是否为http(s)://开头
"""
- return link.startswith((CommonConstant.HTTP, CommonConstant.HTTPS))
+ return bool(link and link.startswith((CommonConstant.HTTP, CommonConstant.HTTPS)))
@classmethod
def inner_link_replace_each(cls, path: str) -> str:
diff --git a/ruoyi-fastapi-backend/module_admin/service/menu_service.py b/ruoyi-fastapi-backend/module_admin/service/menu_service.py
index 67a5a0550..69f5f4dc6 100644
--- a/ruoyi-fastapi-backend/module_admin/service/menu_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/menu_service.py
@@ -22,7 +22,7 @@ class MenuService:
@classmethod
async def get_menu_tree_services(
- cls, query_db: AsyncSession, current_user: CurrentUserModel | None = None
+ cls, query_db: AsyncSession, current_user: CurrentUserModel
) -> list[dict[str, Any]]:
"""
获取菜单树信息service。
@@ -41,7 +41,7 @@ async def get_menu_tree_services(
@classmethod
async def get_role_menu_tree_services(
- cls, query_db: AsyncSession, role_id: int, current_user: CurrentUserModel | None = None
+ cls, query_db: AsyncSession, role_id: int, current_user: CurrentUserModel
) -> RoleMenuQueryModel:
"""
根据角色id获取菜单树信息service。
@@ -56,15 +56,15 @@ async def get_role_menu_tree_services(
)
menu_tree_result = cls.list_to_tree(menu_list_result)
role = await RoleDao.get_role_detail_by_id(query_db, role_id)
- role_menu_list = await RoleDao.get_role_menu_dao(query_db, role)
+ role_menu_list = await RoleDao.get_role_menu_dao(query_db, role) if role is not None else []
checked_keys = [row.menu_id for row in role_menu_list]
- result = RoleMenuQueryModel(menus=menu_tree_result, checkedKeys=checked_keys)
+ result = RoleMenuQueryModel(menus=menu_tree_result, checked_keys=checked_keys)
return result
@classmethod
async def get_menu_list_services(
- cls, query_db: AsyncSession, page_object: MenuQueryModel, current_user: CurrentUserModel | None = None
+ cls, query_db: AsyncSession, page_object: MenuQueryModel, current_user: CurrentUserModel
) -> list[dict[str, Any]]:
"""
获取菜单列表信息service。
@@ -92,7 +92,7 @@ async def check_menu_name_unique_services(cls, query_db: AsyncSession, page_obje
:return: 校验结果
"""
menu_id = -1 if page_object.menu_id is None else page_object.menu_id
- menu = await MenuDao.get_menu_detail_by_info(query_db, MenuModel(menuName=page_object.menu_name))
+ menu = await MenuDao.get_menu_detail_by_info(query_db, MenuModel(menu_name=page_object.menu_name))
if menu and menu.menu_id != menu_id:
return CommonConstant.NOT_UNIQUE
return CommonConstant.UNIQUE
@@ -211,6 +211,8 @@ async def edit_menu_services(cls, query_db: AsyncSession, page_object: MenuModel
if parent_id in visited_ids:
raise ServiceException(message='上级菜单存在循环关系', msg_key='menu.parentCycle')
visited_ids.add(parent_id)
+ if parent_id is None:
+ raise ServiceException(message='上级菜单不存在', msg_key='menu.parentNotFound')
parent_menu = await MenuDao.get_menu_detail_by_id(query_db, parent_id)
if not parent_menu:
raise ServiceException(message='上级菜单不存在', msg_key='menu.parentNotFound')
@@ -302,7 +304,7 @@ async def delete_menu_services(cls, query_db: AsyncSession, page_object: DeleteM
raise ServiceWarning(message='存在子菜单,不允许删除', msg_key='menu.childrenPreventDelete')
if (await MenuDao.check_menu_exist_role_dao(query_db, int(menu_id))) > 0:
raise ServiceWarning(message='菜单已分配,不允许删除', msg_key='menu.assigned')
- await MenuDao.delete_menu_dao(query_db, MenuModel(menuId=menu_id))
+ await MenuDao.delete_menu_dao(query_db, MenuModel(menu_id=menu_id))
await query_db.commit()
return CrudResponseModel(is_success=True, message='删除成功', msg_key='common.deleted')
except Exception as e:
@@ -312,7 +314,7 @@ async def delete_menu_services(cls, query_db: AsyncSession, page_object: DeleteM
raise ServiceException(message='传入菜单id为空', msg_key='menu.idRequired')
@classmethod
- async def menu_detail_services(cls, query_db: AsyncSession, menu_id: int) -> MenuModel:
+ async def menu_detail_services(cls, query_db: AsyncSession, menu_id: int | None) -> MenuModel:
"""
获取菜单详细信息service。
@@ -320,6 +322,8 @@ async def menu_detail_services(cls, query_db: AsyncSession, menu_id: int) -> Men
:param menu_id: 菜单id
:return: 菜单id对应的信息
"""
+ if menu_id is None:
+ return MenuModel()
menu = await MenuDao.get_menu_detail_by_id(query_db, menu_id=menu_id)
result = MenuModel(**CamelCaseUtil.transform_result(menu)) if menu else MenuModel()
@@ -335,12 +339,15 @@ def list_to_tree(cls, permission_list: Sequence[SysMenu]) -> list[MenuTreeModel]
"""
_permission_list = [
MenuTreeModel(
- id=item.menu_id, label=item.menu_name, labelI18n=item.menu_name_i18n or {}, parentId=item.parent_id
+ id=item.menu_id,
+ label=item.menu_name,
+ label_i18n=item.menu_name_i18n or {},
+ parent_id=item.parent_id or 0,
)
for item in permission_list
]
# 转成id为key的字典
- mapping: dict[int, MenuTreeModel] = dict(zip([i.id for i in _permission_list], _permission_list, strict=False))
+ mapping = {node.id: node for node in _permission_list}
# 树容器
container: list[MenuTreeModel] = []
@@ -351,10 +358,8 @@ def list_to_tree(cls, permission_list: Sequence[SysMenu]) -> list[MenuTreeModel]
if parent is None:
container.append(d)
else:
- children: list[MenuTreeModel] = parent.children
- if not children:
- children = []
- children.append(d)
- parent.children = children
+ if parent.children is None:
+ parent.children = []
+ parent.children.append(d)
return container
diff --git a/ruoyi-fastapi-backend/module_admin/service/notice_service.py b/ruoyi-fastapi-backend/module_admin/service/notice_service.py
index 85152a31d..ff04f3225 100644
--- a/ruoyi-fastapi-backend/module_admin/service/notice_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/notice_service.py
@@ -1,4 +1,4 @@
-from typing import Any
+from typing import Any, Literal, overload
from sqlalchemy.ext.asyncio import AsyncSession
@@ -27,6 +27,18 @@ class NoticeService:
TOP_NOTICE_LIMIT = 5
+ @classmethod
+ @overload
+ async def get_notice_list_services(
+ cls, query_db: AsyncSession, query_object: NoticePageQueryModel, is_page: Literal[True] = True
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_notice_list_services(
+ cls, query_db: AsyncSession, query_object: NoticePageQueryModel, is_page: Literal[False]
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_notice_list_services(
cls, query_db: AsyncSession, query_object: NoticePageQueryModel, is_page: bool = True
@@ -60,7 +72,19 @@ async def get_notice_top_services(cls, query_db: AsyncSession, user_id: int) ->
notice_models = [NoticeTopModel(**CamelCaseUtil.transform_result(notice)) for notice in notice_list]
unread_count = sum(not notice.is_read for notice in notice_models)
- return NoticeTopResponseModel(data=notice_models, unreadCount=unread_count)
+ return NoticeTopResponseModel(data=notice_models, unread_count=unread_count)
+
+ @classmethod
+ @overload
+ async def get_notice_read_user_list_services(
+ cls, query_db: AsyncSession, query_object: NoticeReadUserPageQueryModel, is_page: Literal[True] = True
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_notice_read_user_list_services(
+ cls, query_db: AsyncSession, query_object: NoticeReadUserPageQueryModel, is_page: Literal[False]
+ ) -> list[dict[str, Any]]: ...
@classmethod
async def get_notice_read_user_list_services(
@@ -199,7 +223,7 @@ async def delete_notice_services(cls, query_db: AsyncSession, page_object: Delet
try:
await NoticeDao.delete_notice_reads(query_db, notice_id_list)
for notice_id in notice_id_list:
- await NoticeDao.delete_notice_dao(query_db, NoticeModel(noticeId=notice_id))
+ await NoticeDao.delete_notice_dao(query_db, NoticeModel(notice_id=notice_id))
await query_db.commit()
return CrudResponseModel(is_success=True, message='删除成功', msg_key='common.deleted')
except Exception as e:
@@ -209,7 +233,7 @@ async def delete_notice_services(cls, query_db: AsyncSession, page_object: Delet
raise ServiceException(message='传入通知公告id为空', msg_key='notice.idRequired')
@classmethod
- async def notice_detail_services(cls, query_db: AsyncSession, notice_id: int) -> NoticeModel:
+ async def notice_detail_services(cls, query_db: AsyncSession, notice_id: int | None) -> NoticeModel:
"""
获取通知公告详细信息service。
@@ -217,6 +241,8 @@ async def notice_detail_services(cls, query_db: AsyncSession, notice_id: int) ->
:param notice_id: 通知公告id
:return: 通知公告id对应的信息
"""
+ if notice_id is None:
+ return NoticeModel()
notice = await NoticeDao.get_notice_detail_by_id(query_db, notice_id=notice_id)
result = NoticeModel(**CamelCaseUtil.transform_result(notice)) if notice else NoticeModel()
diff --git a/ruoyi-fastapi-backend/module_admin/service/online_service.py b/ruoyi-fastapi-backend/module_admin/service/online_service.py
index 3710e0dac..bb937a982 100644
--- a/ruoyi-fastapi-backend/module_admin/service/online_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/online_service.py
@@ -34,28 +34,31 @@ async def get_online_list_services(cls, request: Request, query_object: OnlineQu
except AuthException:
# 单个过期或损坏的会话不应影响在线用户列表中的其他会话
continue
+ login_info = payload.get('login_info')
+ if not isinstance(login_info, dict):
+ login_info = {}
online_dict = {
'token_id': payload.get('session_id') if AppConfig.app_same_time_login else payload.get('user_id'),
'user_name': payload.get('user_name'),
'dept_name': payload.get('dept_name'),
- 'ipaddr': payload.get('login_info').get('ipaddr'),
- 'login_location': payload.get('login_info').get('loginLocation'),
- 'browser': payload.get('login_info').get('browser'),
- 'os': payload.get('login_info').get('os'),
- 'login_time': payload.get('login_info').get('loginTime'),
+ 'ipaddr': login_info.get('ipaddr'),
+ 'login_location': login_info.get('loginLocation'),
+ 'browser': login_info.get('browser'),
+ 'os': login_info.get('os'),
+ 'login_time': login_info.get('loginTime'),
}
if query_object.user_name and not query_object.ipaddr:
if query_object.user_name == payload.get('user_name'):
online_info_list = [online_dict]
break
elif not query_object.user_name and query_object.ipaddr:
- if query_object.ipaddr == payload.get('login_info').get('ipaddr'):
+ if query_object.ipaddr == login_info.get('ipaddr'):
online_info_list = [online_dict]
break
elif query_object.user_name and query_object.ipaddr:
- if query_object.user_name == payload.get('user_name') and query_object.ipaddr == payload.get(
- 'login_info'
- ).get('ipaddr'):
+ if query_object.user_name == payload.get('user_name') and query_object.ipaddr == login_info.get(
+ 'ipaddr'
+ ):
online_info_list = [online_dict]
break
else:
diff --git a/ruoyi-fastapi-backend/module_admin/service/post_service.py b/ruoyi-fastapi-backend/module_admin/service/post_service.py
index 81f7f14e7..9c247bcb1 100644
--- a/ruoyi-fastapi-backend/module_admin/service/post_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/post_service.py
@@ -1,4 +1,4 @@
-from typing import Any
+from typing import Any, Literal, overload
from sqlalchemy.ext.asyncio import AsyncSession
@@ -15,6 +15,18 @@
class PostService:
"""岗位管理模块服务层。"""
+ @classmethod
+ @overload
+ async def get_post_list_services(
+ cls, query_db: AsyncSession, query_object: PostPageQueryModel, is_page: Literal[True]
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_post_list_services(
+ cls, query_db: AsyncSession, query_object: PostPageQueryModel, is_page: Literal[False] = False
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_post_list_services(
cls, query_db: AsyncSession, query_object: PostPageQueryModel, is_page: bool = False
@@ -41,7 +53,7 @@ async def check_post_name_unique_services(cls, query_db: AsyncSession, page_obje
:return: 校验结果
"""
post_id = -1 if page_object.post_id is None else page_object.post_id
- post = await PostDao.get_post_detail_by_info(query_db, PostModel(postName=page_object.post_name))
+ post = await PostDao.get_post_detail_by_info(query_db, PostModel(post_name=page_object.post_name))
if post and post.post_id != post_id:
return CommonConstant.NOT_UNIQUE
return CommonConstant.UNIQUE
@@ -56,7 +68,7 @@ async def check_post_code_unique_services(cls, query_db: AsyncSession, page_obje
:return: 校验结果
"""
post_id = -1 if page_object.post_id is None else page_object.post_id
- post = await PostDao.get_post_detail_by_info(query_db, PostModel(postCode=page_object.post_code))
+ post = await PostDao.get_post_detail_by_info(query_db, PostModel(post_code=page_object.post_code))
if post and post.post_id != post_id:
return CommonConstant.NOT_UNIQUE
return CommonConstant.UNIQUE
@@ -150,7 +162,7 @@ async def delete_post_services(cls, query_db: AsyncSession, page_object: DeleteP
msg_key='post.assigned',
msg_params={'post_name': str(post.post_name)},
)
- await PostDao.delete_post_dao(query_db, PostModel(postId=post_id))
+ await PostDao.delete_post_dao(query_db, PostModel(post_id=post_id))
await query_db.commit()
return CrudResponseModel(is_success=True, message='删除成功', msg_key='common.deleted')
except Exception as e:
@@ -160,7 +172,7 @@ async def delete_post_services(cls, query_db: AsyncSession, page_object: DeleteP
raise ServiceException(message='传入岗位id为空', msg_key='post.idRequired')
@classmethod
- async def post_detail_services(cls, query_db: AsyncSession, post_id: int) -> PostModel:
+ async def post_detail_services(cls, query_db: AsyncSession, post_id: int | None) -> PostModel:
"""
获取岗位详细信息service。
@@ -168,6 +180,8 @@ async def post_detail_services(cls, query_db: AsyncSession, post_id: int) -> Pos
:param post_id: 岗位id
:return: 岗位id对应的信息
"""
+ if post_id is None:
+ return PostModel()
post = await PostDao.get_post_detail_by_id(query_db, post_id=post_id)
result = PostModel(**CamelCaseUtil.transform_result(post)) if post else PostModel()
diff --git a/ruoyi-fastapi-backend/module_admin/service/role_service.py b/ruoyi-fastapi-backend/module_admin/service/role_service.py
index a0b86b7d5..6c9ffc01d 100644
--- a/ruoyi-fastapi-backend/module_admin/service/role_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/role_service.py
@@ -1,4 +1,4 @@
-from typing import Any
+from typing import Any, Literal, overload
from sqlalchemy import ColumnElement
from sqlalchemy.ext.asyncio import AsyncSession
@@ -51,10 +51,30 @@ async def get_role_dept_tree_services(cls, query_db: AsyncSession, role_id: int)
role = await cls.role_detail_services(query_db, role_id)
role_dept_list = await RoleDao.get_role_dept_dao(query_db, role)
checked_keys = [row.dept_id for row in role_dept_list]
- result = RoleDeptQueryModel(checkedKeys=checked_keys)
+ result = RoleDeptQueryModel(checked_keys=checked_keys)
return result
+ @classmethod
+ @overload
+ async def get_role_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: RolePageQueryModel,
+ data_scope_sql: ColumnElement,
+ is_page: Literal[True],
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_role_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: RolePageQueryModel,
+ data_scope_sql: ColumnElement,
+ is_page: Literal[False] = False,
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_role_list_services(
cls,
@@ -105,7 +125,7 @@ async def check_role_data_scope_services(
if role_id_list:
for role_id in role_id_list:
roles = await RoleDao.get_role_list(
- query_db, RolePageQueryModel(roleId=int(role_id)), data_scope_sql, is_page=False
+ query_db, RolePageQueryModel(role_id=int(role_id)), data_scope_sql, is_page=False
)
if roles:
continue
@@ -121,7 +141,7 @@ async def check_role_name_unique_services(cls, query_db: AsyncSession, page_obje
:return: 校验结果
"""
role_id = -1 if page_object.role_id is None else page_object.role_id
- role = await RoleDao.get_role_by_info(query_db, RoleModel(roleName=page_object.role_name))
+ role = await RoleDao.get_role_by_info(query_db, RoleModel(role_name=page_object.role_name))
if role and role.role_id != role_id:
return CommonConstant.NOT_UNIQUE
return CommonConstant.UNIQUE
@@ -136,7 +156,7 @@ async def check_role_key_unique_services(cls, query_db: AsyncSession, page_objec
:return: 校验结果
"""
role_id = -1 if page_object.role_id is None else page_object.role_id
- role = await RoleDao.get_role_by_info(query_db, RoleModel(roleKey=page_object.role_key))
+ role = await RoleDao.get_role_by_info(query_db, RoleModel(role_key=page_object.role_key))
if role and role.role_id != role_id:
return CommonConstant.NOT_UNIQUE
return CommonConstant.UNIQUE
@@ -152,7 +172,7 @@ async def add_role_services(cls, query_db: AsyncSession, page_object: AddRoleMod
:raises ServiceException: 角色名称或权限标识已存在
:raises Exception: 事务失败并回滚后重新抛出原异常
"""
- add_role = RoleModel(**page_object.model_dump(by_alias=True, exclude={'create_time', 'update_time'}))
+ add_role = RoleModel(**page_object.model_dump(exclude={'create_time', 'update_time'}))
if not await cls.check_role_name_unique_services(query_db, page_object):
raise ServiceException(
message=f'新增角色{page_object.role_name}失败,角色名称已存在',
@@ -170,7 +190,7 @@ async def add_role_services(cls, query_db: AsyncSession, page_object: AddRoleMod
role_id = add_result.role_id
if page_object.menu_ids:
for menu in page_object.menu_ids:
- await RoleDao.add_role_menu_dao(query_db, RoleMenuModel(roleId=role_id, menuId=menu))
+ await RoleDao.add_role_menu_dao(query_db, RoleMenuModel(role_id=role_id, menu_id=menu))
await query_db.commit()
return CrudResponseModel(is_success=True, message='新增成功', msg_key='common.added')
except Exception as e:
@@ -190,10 +210,13 @@ async def _role_menu_changed(
:param page_object: 本次角色编辑请求
:param role_info: 编辑前的角色信息
:return: 菜单集合发生变化时为 True
+ :raises ServiceException: 未找到原角色标识
"""
if 'menu_ids' not in page_object.model_fields_set:
return False
- current_ids = set(await RoleDao.list_role_menu_ids(query_db, int(role_info.role_id)))
+ if role_info.role_id is None:
+ raise ServiceException(message='角色不存在', msg_key='role.notFound')
+ current_ids = set(await RoleDao.list_role_menu_ids(query_db, role_info.role_id))
requested_ids = {int(menu_id) for menu_id in (page_object.menu_ids or [])}
return current_ids != requested_ids
@@ -209,7 +232,10 @@ async def _handle_edit_identity_event(
:param query_db: orm对象
:param page_object: 编辑角色对象
:param role_info: 当前角色信息
+ :raises ServiceException: 未提供编辑角色的标识
"""
+ if page_object.role_id is None:
+ raise ServiceException(message='角色不存在', msg_key='role.notFound')
if page_object.type == 'status':
if page_object.status == '1' and role_info.status != '1':
await IdentitySecurityEventService.handle_role_event(
@@ -249,7 +275,7 @@ async def edit_role_services(cls, query_db: AsyncSession, page_object: AddRoleMo
del edit_role['menu_ids']
if page_object.type == 'status':
del edit_role['type']
- role_info = await cls.role_detail_services(query_db, edit_role.get('role_id'))
+ role_info = await cls.role_detail_services(query_db, page_object.role_id)
if role_info:
if page_object.type != 'status':
if not await cls.check_role_name_unique_services(query_db, page_object):
@@ -268,11 +294,11 @@ async def edit_role_services(cls, query_db: AsyncSession, page_object: AddRoleMo
await cls._handle_edit_identity_event(query_db, page_object, role_info)
await RoleDao.edit_role_dao(query_db, edit_role)
if page_object.type != 'status':
- await RoleDao.delete_role_menu_dao(query_db, RoleMenuModel(roleId=page_object.role_id))
+ await RoleDao.delete_role_menu_dao(query_db, RoleMenuModel(role_id=page_object.role_id))
if page_object.menu_ids:
for menu in page_object.menu_ids:
await RoleDao.add_role_menu_dao(
- query_db, RoleMenuModel(roleId=page_object.role_id, menuId=menu)
+ query_db, RoleMenuModel(role_id=page_object.role_id, menu_id=menu)
)
await query_db.commit()
return CrudResponseModel(is_success=True, message='更新成功', msg_key='common.updated')
@@ -301,11 +327,11 @@ async def role_datascope_services(cls, query_db: AsyncSession, page_object: AddR
if role_info.role_id:
try:
await RoleDao.edit_role_dao(query_db, edit_role)
- await RoleDao.delete_role_dept_dao(query_db, RoleDeptModel(roleId=page_object.role_id))
+ await RoleDao.delete_role_dept_dao(query_db, RoleDeptModel(role_id=page_object.role_id))
if page_object.dept_ids and page_object.data_scope == '2':
for dept in page_object.dept_ids:
await RoleDao.add_role_dept_dao(
- query_db, RoleDeptModel(roleId=page_object.role_id, deptId=dept)
+ query_db, RoleDeptModel(role_id=page_object.role_id, dept_id=dept)
)
await query_db.commit()
return CrudResponseModel(is_success=True, message='分配成功', msg_key='common.assigned')
@@ -348,9 +374,9 @@ async def delete_role_services(cls, query_db: AsyncSession, page_object: DeleteR
'updateBy': page_object.update_by,
'updateTime': page_object.update_time,
}
- await RoleDao.delete_role_menu_dao(query_db, RoleMenuModel(**role_id_dict))
- await RoleDao.delete_role_dept_dao(query_db, RoleDeptModel(**role_id_dict))
- await RoleDao.delete_role_dao(query_db, RoleModel(**role_id_dict))
+ await RoleDao.delete_role_menu_dao(query_db, RoleMenuModel.model_validate(role_id_dict))
+ await RoleDao.delete_role_dept_dao(query_db, RoleDeptModel.model_validate(role_id_dict))
+ await RoleDao.delete_role_dao(query_db, RoleModel.model_validate(role_id_dict))
await query_db.commit()
return CrudResponseModel(is_success=True, message='删除成功', msg_key='common.deleted')
except Exception as e:
@@ -360,7 +386,7 @@ async def delete_role_services(cls, query_db: AsyncSession, page_object: DeleteR
raise ServiceException(message='传入角色id为空', msg_key='role.idRequired')
@classmethod
- async def role_detail_services(cls, query_db: AsyncSession, role_id: int) -> RoleModel:
+ async def role_detail_services(cls, query_db: AsyncSession, role_id: int | None) -> RoleModel:
"""
获取角色详细信息service。
@@ -368,6 +394,8 @@ async def role_detail_services(cls, query_db: AsyncSession, role_id: int) -> Rol
:param role_id: 角色id
:return: 角色id对应的信息
"""
+ if role_id is None:
+ return RoleModel()
role = await RoleDao.get_role_detail_by_id(query_db, role_id=role_id)
result = RoleModel(**CamelCaseUtil.transform_result(role)) if role else RoleModel()
@@ -404,6 +432,26 @@ async def export_role_list_services(role_list: list) -> bytes:
return binary_data
+ @classmethod
+ @overload
+ async def get_role_user_allocated_list_services(
+ cls,
+ query_db: AsyncSession,
+ page_object: UserRolePageQueryModel,
+ data_scope_sql: ColumnElement,
+ is_page: Literal[True],
+ ) -> PageModel[UserInfoModel]: ...
+
+ @classmethod
+ @overload
+ async def get_role_user_allocated_list_services(
+ cls,
+ query_db: AsyncSession,
+ page_object: UserRolePageQueryModel,
+ data_scope_sql: ColumnElement,
+ is_page: Literal[False] = False,
+ ) -> list[UserInfoModel]: ...
+
@classmethod
async def get_role_user_allocated_list_services(
cls,
@@ -411,7 +459,7 @@ async def get_role_user_allocated_list_services(
page_object: UserRolePageQueryModel,
data_scope_sql: ColumnElement,
is_page: bool = False,
- ) -> PageModel:
+ ) -> PageModel[UserInfoModel] | list[UserInfoModel]:
"""
根据角色id获取已分配用户列表。
@@ -424,14 +472,29 @@ async def get_role_user_allocated_list_services(
query_user_list = await UserDao.get_user_role_allocated_list_by_role_id(
query_db, page_object, data_scope_sql, is_page
)
- allocated_list = PageModel[UserInfoModel](
- **{
- **query_user_list.model_dump(by_alias=True),
- 'rows': [UserInfoModel(**row) for row in query_user_list.rows],
- }
- )
+ if isinstance(query_user_list, PageModel):
+ return PageModel[UserInfoModel].model_validate(query_user_list.model_dump())
+ return [UserInfoModel.model_validate(row) for row in query_user_list]
- return allocated_list
+ @classmethod
+ @overload
+ async def get_role_user_unallocated_list_services(
+ cls,
+ query_db: AsyncSession,
+ page_object: UserRolePageQueryModel,
+ data_scope_sql: ColumnElement,
+ is_page: Literal[True],
+ ) -> PageModel[UserInfoModel]: ...
+
+ @classmethod
+ @overload
+ async def get_role_user_unallocated_list_services(
+ cls,
+ query_db: AsyncSession,
+ page_object: UserRolePageQueryModel,
+ data_scope_sql: ColumnElement,
+ is_page: Literal[False] = False,
+ ) -> list[UserInfoModel]: ...
@classmethod
async def get_role_user_unallocated_list_services(
@@ -440,7 +503,7 @@ async def get_role_user_unallocated_list_services(
page_object: UserRolePageQueryModel,
data_scope_sql: ColumnElement,
is_page: bool = False,
- ) -> PageModel:
+ ) -> PageModel[UserInfoModel] | list[UserInfoModel]:
"""
根据角色id获取未分配用户列表。
@@ -453,11 +516,6 @@ async def get_role_user_unallocated_list_services(
query_user_list = await UserDao.get_user_role_unallocated_list_by_role_id(
query_db, page_object, data_scope_sql, is_page
)
- unallocated_list = PageModel[UserInfoModel](
- **{
- **query_user_list.model_dump(by_alias=True),
- 'rows': [UserInfoModel(**row) for row in query_user_list.rows],
- }
- )
-
- return unallocated_list
+ if isinstance(query_user_list, PageModel):
+ return PageModel[UserInfoModel].model_validate(query_user_list.model_dump())
+ return [UserInfoModel.model_validate(row) for row in query_user_list]
diff --git a/ruoyi-fastapi-backend/module_admin/service/server_service.py b/ruoyi-fastapi-backend/module_admin/service/server_service.py
index c2e1577e9..5be8323f0 100644
--- a/ruoyi-fastapi-backend/module_admin/service/server_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/server_service.py
@@ -29,7 +29,7 @@ async def get_server_monitor_info() -> ServerMonitorModel:
cpu_used = cpu_usage_percent.user
cpu_sys = cpu_usage_percent.system
cpu_free = cpu_usage_percent.idle
- cpu = CpuInfo(cpuNum=cpu_num, used=cpu_used, sys=cpu_sys, free=cpu_free)
+ cpu = CpuInfo(cpu_num=cpu_num, used=cpu_used, sys=cpu_sys, free=cpu_free)
# 内存信息
memory_info = psutil.virtual_memory()
@@ -49,7 +49,7 @@ async def get_server_monitor_info() -> ServerMonitorModel:
os_arch = platform.machine()
user_dir = str(await anyio.Path.cwd())
sys = SysInfo(
- computerIp=computer_ip, computerName=computer_name, osArch=os_arch, osName=os_name, userDir=user_dir
+ computer_ip=computer_ip, computer_name=computer_name, os_arch=os_arch, os_name=os_name, user_dir=user_dir
)
# python解释器信息
@@ -74,8 +74,8 @@ async def get_server_monitor_info() -> ServerMonitorModel:
py = PyInfo(
name=python_name,
version=python_version,
- startTime=start_time,
- runTime=run_time,
+ start_time=start_time,
+ run_time=run_time,
home=python_home,
total=bytes2human(memory_info.available),
used=bytes2human(current_process_memory_info.rss),
@@ -86,7 +86,7 @@ async def get_server_monitor_info() -> ServerMonitorModel:
# 磁盘信息
sys_files = ServerService._get_disk_info()
- result = ServerMonitorModel(cpu=cpu, mem=mem, sys=sys, py=py, sysFiles=sys_files)
+ result = ServerMonitorModel(cpu=cpu, mem=mem, sys=sys, py=py, sys_files=sys_files)
return result
@@ -137,9 +137,9 @@ def _read_disk_info(device: str, mountpoint: str, filesystem: str) -> SysFiles |
return None
return SysFiles(
- dirName=device,
- sysTypeName=filesystem,
- typeName='本地固定磁盘(' + mountpoint.replace('\\', '') + ')',
+ dir_name=device,
+ sys_type_name=filesystem,
+ type_name='本地固定磁盘(' + mountpoint.replace('\\', '') + ')',
total=bytes2human(disk_usage.total),
used=bytes2human(disk_usage.used),
free=bytes2human(disk_usage.free),
diff --git a/ruoyi-fastapi-backend/module_admin/service/user_service.py b/ruoyi-fastapi-backend/module_admin/service/user_service.py
index 6ba240e53..58f4b44c5 100644
--- a/ruoyi-fastapi-backend/module_admin/service/user_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/user_service.py
@@ -1,6 +1,6 @@
import io
import re
-from typing import Any
+from typing import Any, Literal, overload
import pandas as pd
from fastapi import Request, UploadFile
@@ -95,13 +95,14 @@ async def validate_password_services(
redis: aioredis.Redis,
password: str | None,
pwd_chrtype: PasswordCharacterType | str | None = None,
- ) -> None:
+ ) -> str:
"""
校验密码是否符合系统密码策略。
:param redis: redis对象
:param password: 明文密码
:param pwd_chrtype: 指定密码字符范围,未指定时读取系统配置
+ :return: 通过策略校验的密码
:raises ServiceException: 密码不能为空;密码长度必须介于 6 和 20 之间
"""
if pwd_chrtype is None:
@@ -119,6 +120,27 @@ async def validate_password_services(
if not re.fullmatch(password_character_type.pattern, password):
raise ServiceException(message=password_character_type.message)
+ return password
+
+ @classmethod
+ @overload
+ async def get_user_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: UserPageQueryModel,
+ data_scope_sql: ColumnElement,
+ is_page: Literal[True],
+ ) -> PageModel[UserRowModel]: ...
+
+ @classmethod
+ @overload
+ async def get_user_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: UserPageQueryModel,
+ data_scope_sql: ColumnElement,
+ is_page: Literal[False] = False,
+ ) -> list[dict[str, Any]]: ...
@classmethod
async def get_user_list_services(
@@ -136,21 +158,18 @@ async def get_user_list_services(
:param data_scope_sql: 数据权限对应的查询sql语句
:param is_page: 是否开启分页
:return: 用户列表信息对象
+ :raises ValueError: 用户部门关联行缺少用户记录
"""
query_result = await UserDao.get_user_list(query_db, query_object, data_scope_sql, is_page)
- if is_page:
- user_list_result = PageModel[UserRowModel](
- **{
- **query_result.model_dump(by_alias=True),
- 'rows': [{**row[0], 'dept': row[1]} for row in query_result.rows],
- }
- )
- else:
- user_list_result = []
- if query_result:
- user_list_result = [{**row[0], 'dept': row[1]} for row in query_result]
-
- return user_list_result
+ rows = query_result.rows if isinstance(query_result, PageModel) else query_result
+ users = []
+ for user, dept in rows:
+ if user is None:
+ raise ValueError('用户部门关联查询缺少用户记录')
+ users.append({**user, 'dept': dept})
+ if isinstance(query_result, PageModel):
+ return PageModel[UserRowModel].model_validate({**query_result.model_dump(), 'rows': users})
+ return users
@classmethod
async def check_user_allowed_services(cls, check_user: UserModel) -> CrudResponseModel:
@@ -167,7 +186,7 @@ async def check_user_allowed_services(cls, check_user: UserModel) -> CrudRespons
@classmethod
async def check_user_data_scope_services(
- cls, query_db: AsyncSession, user_id: int, data_scope_sql: ColumnElement
+ cls, query_db: AsyncSession, user_id: int | None, data_scope_sql: ColumnElement
) -> CrudResponseModel:
"""
校验用户数据权限service。
@@ -178,7 +197,11 @@ async def check_user_data_scope_services(
:return: 校验结果
:raises ServiceException: 没有权限访问用户数据
"""
- users = await UserDao.get_user_list(query_db, UserPageQueryModel(userId=user_id), data_scope_sql, is_page=False)
+ if user_id is None:
+ raise ServiceException(message='没有权限访问用户数据', msg_key='user.forbidden')
+ users = await UserDao.get_user_list(
+ query_db, UserPageQueryModel(user_id=user_id), data_scope_sql, is_page=False
+ )
if users:
return CrudResponseModel(is_success=True, message='校验通过', msg_key='common.validated')
raise ServiceException(message='没有权限访问用户数据', msg_key='user.forbidden')
@@ -193,7 +216,7 @@ async def check_user_name_unique_services(cls, query_db: AsyncSession, page_obje
:return: 校验结果
"""
user_id = -1 if page_object.user_id is None else page_object.user_id
- user = await UserDao.get_user_by_info(query_db, UserModel(userName=page_object.user_name))
+ user = await UserDao.get_user_by_info(query_db, UserModel(user_name=page_object.user_name))
if user and user.user_id != user_id:
return CommonConstant.NOT_UNIQUE
return CommonConstant.UNIQUE
@@ -239,7 +262,7 @@ async def add_user_services(cls, query_db: AsyncSession, page_object: AddUserMod
:raises ServiceException: 登录账号、手机号或邮箱已被使用
:raises Exception: 事务失败并回滚后重新抛出原异常
"""
- add_user = UserModel(**page_object.model_dump(by_alias=True, exclude={'create_time', 'update_time'}))
+ add_user = UserModel(**page_object.model_dump(exclude={'create_time', 'update_time'}))
if not await cls.check_user_name_unique_services(query_db, page_object):
raise ServiceException(
message=f'新增用户{page_object.user_name}失败,登录账号已存在',
@@ -268,10 +291,10 @@ async def add_user_services(cls, query_db: AsyncSession, page_object: AddUserMod
)
if page_object.role_ids:
for role in page_object.role_ids:
- await UserDao.add_user_role_dao(query_db, UserRoleModel(userId=user_id, roleId=role))
+ await UserDao.add_user_role_dao(query_db, UserRoleModel(user_id=user_id, role_id=role))
if page_object.post_ids:
for post in page_object.post_ids:
- await UserDao.add_user_post_dao(query_db, UserPostModel(userId=user_id, postId=post))
+ await UserDao.add_user_post_dao(query_db, UserPostModel(user_id=user_id, post_id=post))
await query_db.commit()
return CrudResponseModel(is_success=True, message='新增成功', msg_key='common.added')
except Exception as e:
@@ -361,7 +384,7 @@ async def edit_user_services(cls, query_db: AsyncSession, page_object: EditUserM
exclude={'admin', 'create_time', 'update_time'},
)
cls._deal_edit_user(page_object, edit_user)
- user_info = await cls.user_detail_services(query_db, edit_user.get('user_id'))
+ user_info = await cls.user_detail_services(query_db, page_object.user_id)
if user_info.data and user_info.data.user_id:
if page_object.type not in ['status', 'avatar', 'pwd']:
if not await cls.check_user_name_unique_services(query_db, page_object):
@@ -385,17 +408,17 @@ async def edit_user_services(cls, query_db: AsyncSession, page_object: EditUserM
try:
await UserDao.edit_user_dao(query_db, edit_user)
if page_object.type not in {'status', 'avatar', 'pwd'}:
- await UserDao.delete_user_role_dao(query_db, UserRoleModel(userId=page_object.user_id))
- await UserDao.delete_user_post_dao(query_db, UserPostModel(userId=page_object.user_id))
+ await UserDao.delete_user_role_dao(query_db, UserRoleModel(user_id=page_object.user_id))
+ await UserDao.delete_user_post_dao(query_db, UserPostModel(user_id=page_object.user_id))
if page_object.role_ids:
for role in page_object.role_ids:
await UserDao.add_user_role_dao(
- query_db, UserRoleModel(userId=page_object.user_id, roleId=role)
+ query_db, UserRoleModel(user_id=page_object.user_id, role_id=role)
)
if page_object.post_ids:
for post in page_object.post_ids:
await UserDao.add_user_post_dao(
- query_db, UserPostModel(userId=page_object.user_id, postId=post)
+ query_db, UserPostModel(user_id=page_object.user_id, post_id=post)
)
await cls._handle_edit_identity_security_event(query_db, page_object, user_info.data)
await query_db.commit()
@@ -426,9 +449,9 @@ async def delete_user_services(cls, query_db: AsyncSession, page_object: DeleteU
'updateBy': page_object.update_by,
'updateTime': page_object.update_time,
}
- await UserDao.delete_user_role_dao(query_db, UserRoleModel(**user_id_dict))
- await UserDao.delete_user_post_dao(query_db, UserPostModel(**user_id_dict))
- await UserDao.delete_user_dao(query_db, UserModel(**user_id_dict))
+ await UserDao.delete_user_role_dao(query_db, UserRoleModel.model_validate(user_id_dict))
+ await UserDao.delete_user_post_dao(query_db, UserPostModel.model_validate(user_id_dict))
+ await UserDao.delete_user_dao(query_db, UserModel.model_validate(user_id_dict))
await IdentitySecurityEventService.handle_user_event(
query_db,
int(user_id),
@@ -444,7 +467,7 @@ async def delete_user_services(cls, query_db: AsyncSession, page_object: DeleteU
raise ServiceException(message='传入用户id为空', msg_key='user.idRequired')
@classmethod
- async def user_detail_services(cls, query_db: AsyncSession, user_id: int | str) -> UserDetailModel:
+ async def user_detail_services(cls, query_db: AsyncSession, user_id: int | str | None) -> UserDetailModel:
"""
获取用户详细信息service。
@@ -454,8 +477,10 @@ async def user_detail_services(cls, query_db: AsyncSession, user_id: int | str)
"""
posts = await PostService.get_post_list_services(query_db, PostPageQueryModel(), is_page=False)
roles = await RoleService.get_role_select_option_services(query_db)
- if user_id != '':
- query_user = await UserDao.get_user_detail_by_id(query_db, user_id=user_id)
+ if user_id in ('', None):
+ return UserDetailModel(posts=posts, roles=roles)
+ query_user = await UserDao.get_user_detail_by_id(query_db, user_id=int(user_id))
+ if query_user['user_basic_info'] is not None:
post_ids = ','.join([str(row.post_id) for row in query_user.get('user_post_info')])
post_ids_list = [row.post_id for row in query_user.get('user_post_info')]
role_ids = ','.join([str(row.role_id) for row in query_user.get('user_role_info')])
@@ -464,14 +489,14 @@ async def user_detail_services(cls, query_db: AsyncSession, user_id: int | str)
return UserDetailModel(
data=UserInfoModel(
**CamelCaseUtil.transform_result(query_user.get('user_basic_info')),
- postIds=post_ids,
- roleIds=role_ids,
+ post_ids=post_ids,
+ role_ids=role_ids,
dept=CamelCaseUtil.transform_result(query_user.get('user_dept_info')),
role=CamelCaseUtil.transform_result(query_user.get('user_role_info')),
),
- postIds=post_ids_list,
+ post_ids=post_ids_list,
posts=posts,
- roleIds=role_ids_list,
+ role_ids=role_ids_list,
roles=roles,
)
@@ -537,6 +562,8 @@ async def user_profile_services(cls, query_db: AsyncSession, user_id: int) -> Us
:return: 用户id对应的信息
"""
query_user = await UserDao.get_user_detail_by_id(query_db, user_id=user_id)
+ if query_user['user_basic_info'] is None:
+ return UserProfileModel(data=None, post_group='', role_group='')
post_ids = ','.join([str(row.post_id) for row in query_user.get('user_post_info')])
post_group = ','.join([row.post_name for row in query_user.get('user_post_info')])
role_ids = ','.join([str(row.role_id) for row in query_user.get('user_role_info')])
@@ -545,13 +572,13 @@ async def user_profile_services(cls, query_db: AsyncSession, user_id: int) -> Us
return UserProfileModel(
data=UserInfoModel(
**CamelCaseUtil.transform_result(query_user.get('user_basic_info')),
- postIds=post_ids,
- roleIds=role_ids,
+ post_ids=post_ids,
+ role_ids=role_ids,
dept=CamelCaseUtil.transform_result(query_user.get('user_dept_info')),
role=CamelCaseUtil.transform_result(query_user.get('user_role_info')),
),
- postGroup=post_group,
- roleGroup=role_group,
+ post_group=post_group,
+ role_group=role_group,
)
@classmethod
@@ -565,13 +592,17 @@ async def reset_user_services(cls, query_db: AsyncSession, page_object: ResetUse
:raises ServiceException: 修改密码失败,旧密码错误;新密码不能与旧密码相同
:raises Exception: 事务失败并回滚后重新抛出原异常
"""
+ if page_object.user_id is None:
+ raise ServiceException(message='用户不存在', msg_key='user.notFound')
+ if not page_object.password:
+ raise ServiceException(message='密码不能为空', msg_key='auth.passwordRequired')
reset_user = page_object.model_dump(
exclude_unset=True,
exclude={'admin', 'create_time', 'update_time'},
)
if page_object.old_password:
user = (await UserDao.get_user_detail_by_id(query_db, user_id=page_object.user_id)).get('user_basic_info')
- if not PwdUtil.verify_password(page_object.old_password, user.password):
+ if not user or not user.password or not PwdUtil.verify_password(page_object.old_password, user.password):
raise ServiceException(message='修改密码失败,旧密码错误', msg_key='user.oldPasswordIncorrect')
if PwdUtil.verify_password(page_object.password, user.password):
raise ServiceException(message='新密码不能与旧密码相同', msg_key='user.passwordUnchanged')
@@ -637,6 +668,7 @@ async def batch_import_user_services(
:raises ServiceException: 导入文件为空
:raises Exception: 事务失败并回滚后重新抛出原异常
"""
+ actor = current_user.user
contents = await file.read()
await file.close()
df = pd.read_excel(io.BytesIO(contents), header=None, dtype=object)
@@ -659,34 +691,34 @@ async def batch_import_user_services(
cls._set_row_sex_value(row)
cls._set_row_status_value(row)
add_user = UserModel(
- deptId=row['dept_id'],
- userName=row['user_name'],
+ dept_id=row['dept_id'],
+ user_name=row['user_name'],
password=PwdUtil.get_password_hash(init_password),
- nickName=row['nick_name'],
+ nick_name=row['nick_name'],
email=row['email'],
phonenumber=str(row['phonenumber']) if row['phonenumber'] is not None else None,
sex=row['sex'],
status=row['status'],
- createBy=current_user.user.user_name,
- updateBy=current_user.user.user_name,
+ create_by=actor.user_name,
+ update_by=actor.user_name,
)
- user_info = await UserDao.get_user_by_info(query_db, UserModel(userName=row['user_name']))
+ user_info = await UserDao.get_user_by_info(query_db, UserModel(user_name=row['user_name']))
if user_info:
if update_support:
edit_user_model = UserModel(
- userId=user_info.user_id,
- deptId=row['dept_id'],
- userName=row['user_name'],
- nickName=row['nick_name'],
+ user_id=user_info.user_id,
+ dept_id=row['dept_id'],
+ user_name=row['user_name'],
+ nick_name=row['nick_name'],
email=row['email'],
phonenumber=str(row['phonenumber']) if row['phonenumber'] is not None else None,
sex=row['sex'],
status=row['status'],
- updateBy=current_user.user.user_name,
+ update_by=actor.user_name,
)
edit_user_model.validate_fields()
await cls.check_user_allowed_services(edit_user_model)
- if not current_user.user.admin:
+ if not actor.admin:
await cls.check_user_data_scope_services(
query_db, edit_user_model.user_id, user_data_scope_sql
)
@@ -703,21 +735,21 @@ async def batch_import_user_services(
query_db,
user_info.user_id,
'user_disabled',
- actor=current_user.user.user_name,
+ actor=actor.user_name,
)
if edit_user_model.dept_id != user_info.dept_id:
await IdentitySecurityEventService.handle_user_event(
query_db,
user_info.user_id,
'department_changed',
- actor=current_user.user.user_name,
+ actor=actor.user_name,
)
else:
add_error_result.append(f'{count}.用户账号{row["user_name"]}已存在')
duplicate_accounts.append(f'{count}. {row["user_name"]}')
else:
add_user.validate_fields()
- if not current_user.user.admin:
+ if not actor.admin:
await DeptService.check_dept_data_scope_services(
query_db, add_user.dept_id, dept_data_scope_sql
)
@@ -725,7 +757,7 @@ async def batch_import_user_services(
await IdentitySubjectService.create_for_new_user(
query_db,
user_id=added_user.user_id,
- create_by=current_user.user.user_name,
+ create_by=actor.user_name,
)
await query_db.commit()
return CrudResponseModel(
@@ -830,23 +862,28 @@ async def get_user_role_allocated_list_services(
:param query_db: orm对象
:param page_object: 用户关联角色对象
:return: 已分配角色列表
+ :raises ServiceException: 未提供用户标识
"""
+ if page_object.user_id is None:
+ raise ServiceException(message='用户不存在', msg_key='user.notFound')
query_user = await UserDao.get_user_detail_by_id(query_db, page_object.user_id)
+ query_role_list = [
+ SelectedRoleModel(**row) for row in await RoleService.get_role_select_option_services(query_db)
+ ]
+ if query_user['user_basic_info'] is None:
+ return UserRoleResponseModel(roles=query_role_list, user=None)
post_ids = ','.join([str(row.post_id) for row in query_user.get('user_post_info')])
role_ids = ','.join([str(row.role_id) for row in query_user.get('user_role_info')])
user = UserInfoModel(
**CamelCaseUtil.transform_result(query_user.get('user_basic_info')),
- postIds=post_ids,
- roleIds=role_ids,
+ post_ids=post_ids,
+ role_ids=role_ids,
dept=CamelCaseUtil.transform_result(query_user.get('user_dept_info')),
role=CamelCaseUtil.transform_result(query_user.get('user_role_info')),
)
- query_role_list = [
- SelectedRoleModel(**row) for row in await RoleService.get_role_select_option_services(query_db)
- ]
for model_a in query_role_list:
- for model_b in user.role:
- if model_a.role_id == model_b.role_id:
+ for model_b in user.role or []:
+ if model_b is not None and model_a.role_id == model_b.role_id:
model_a.flag = True
result = UserRoleResponseModel(roles=query_role_list, user=user)
@@ -873,9 +910,13 @@ async def add_user_role_services(
if await cls._current_role_ids(query_db, page_object.user_id) == requested_role_ids:
await query_db.commit()
return CrudResponseModel(is_success=True, message='分配成功', msg_key='common.assigned')
- await UserDao.delete_user_role_by_user_and_role_dao(query_db, UserRoleModel(userId=page_object.user_id))
+ await UserDao.delete_user_role_by_user_and_role_dao(
+ query_db, UserRoleModel(user_id=page_object.user_id)
+ )
for role_id in role_id_list:
- await UserDao.add_user_role_dao(query_db, UserRoleModel(userId=page_object.user_id, roleId=role_id))
+ await UserDao.add_user_role_dao(
+ query_db, UserRoleModel(user_id=page_object.user_id, role_id=role_id)
+ )
await IdentitySecurityEventService.handle_user_event(
query_db,
page_object.user_id,
@@ -892,7 +933,9 @@ async def add_user_role_services(
if not await cls._current_role_ids(query_db, page_object.user_id):
await query_db.commit()
return CrudResponseModel(is_success=True, message='分配成功', msg_key='common.assigned')
- await UserDao.delete_user_role_by_user_and_role_dao(query_db, UserRoleModel(userId=page_object.user_id))
+ await UserDao.delete_user_role_by_user_and_role_dao(
+ query_db, UserRoleModel(user_id=page_object.user_id)
+ )
await IdentitySecurityEventService.handle_user_event(
query_db,
page_object.user_id,
@@ -910,11 +953,13 @@ async def add_user_role_services(
changed_user_ids: list[int] = []
for user_id in user_id_list:
user_role = await cls.detail_user_role_services(
- query_db, UserRoleModel(userId=user_id, roleId=page_object.role_id)
+ query_db, UserRoleModel(user_id=user_id, role_id=page_object.role_id)
)
if user_role:
continue
- await UserDao.add_user_role_dao(query_db, UserRoleModel(userId=user_id, roleId=page_object.role_id))
+ await UserDao.add_user_role_dao(
+ query_db, UserRoleModel(user_id=user_id, role_id=page_object.role_id)
+ )
changed_user_ids.append(int(user_id))
await cls._handle_role_assignment_changes(query_db, changed_user_ids, actor)
await query_db.commit()
@@ -944,10 +989,10 @@ async def delete_user_role_services(
try:
existing = await cls.detail_user_role_services(
query_db,
- UserRoleModel(userId=page_object.user_id, roleId=page_object.role_id),
+ UserRoleModel(user_id=page_object.user_id, role_id=page_object.role_id),
)
await UserDao.delete_user_role_by_user_and_role_dao(
- query_db, UserRoleModel(userId=page_object.user_id, roleId=page_object.role_id)
+ query_db, UserRoleModel(user_id=page_object.user_id, role_id=page_object.role_id)
)
if existing is not None:
await IdentitySecurityEventService.handle_user_event(
@@ -968,10 +1013,10 @@ async def delete_user_role_services(
for user_id in user_id_list:
existing = await cls.detail_user_role_services(
query_db,
- UserRoleModel(userId=user_id, roleId=page_object.role_id),
+ UserRoleModel(user_id=user_id, role_id=page_object.role_id),
)
await UserDao.delete_user_role_by_user_and_role_dao(
- query_db, UserRoleModel(userId=user_id, roleId=page_object.role_id)
+ query_db, UserRoleModel(user_id=user_id, role_id=page_object.role_id)
)
if existing is not None:
changed_user_ids.append(int(user_id))
diff --git a/ruoyi-fastapi-backend/module_generator/controller/gen_controller.py b/ruoyi-fastapi-backend/module_generator/controller/gen_controller.py
index c83f66c65..cdddca3c2 100644
--- a/ruoyi-fastapi-backend/module_generator/controller/gen_controller.py
+++ b/ruoyi-fastapi-backend/module_generator/controller/gen_controller.py
@@ -154,7 +154,7 @@ async def delete_gen_table(
table_ids: Annotated[str, Path(description='需要删除的代码生成业务表ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
- delete_gen_table = DeleteGenTableModel(tableIds=table_ids)
+ delete_gen_table = DeleteGenTableModel(table_ids=table_ids)
delete_gen_table_result = await GenTableService.delete_gen_table_services(query_db, delete_gen_table)
logger.info(delete_gen_table_result.message)
diff --git a/ruoyi-fastapi-backend/module_generator/dao/gen_dao.py b/ruoyi-fastapi-backend/module_generator/dao/gen_dao.py
index 68d84e166..4bf536a41 100644
--- a/ruoyi-fastapi-backend/module_generator/dao/gen_dao.py
+++ b/ruoyi-fastapi-backend/module_generator/dao/gen_dao.py
@@ -2,10 +2,10 @@
from dataclasses import dataclass
from typing import Any
-from sqlalchemy import Row, bindparam, delete, func, select, text, update
+from sqlalchemy import Row, bindparam, delete, func, select, text, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
-from sqlglot.expressions import Expression
+from sqlglot.expressions import Expr
from common.types import DbUtcDateTime
from common.vo import PageModel
@@ -215,7 +215,7 @@ async def get_gen_table_all(cls, db: AsyncSession, source_name: str | None = Non
@classmethod
async def create_table_by_sql_dao(
- cls, db: AsyncSession, sql_statements: list[Expression], *, source_config: DataSourceSettings
+ cls, db: AsyncSession, sql_statements: list[Expr], *, source_config: DataSourceSettings
) -> None:
"""
根据sql语句创建表结构。
@@ -247,13 +247,13 @@ async def get_gen_table_list(
.where(
func.lower(GenTable.table_name).like(f'%{query_object.table_name.lower()}%')
if query_object.table_name
- else True,
+ else true(),
func.lower(GenTable.table_comment).like(f'%{query_object.table_comment.lower()}%')
if query_object.table_comment
- else True,
- GenTable.create_time >= time_range[0] if time_range and time_range[0] is not None else True,
- GenTable.create_time < time_range[1] if time_range and time_range[1] is not None else True,
- GenTable.data_source_name == query_object.data_source_name if query_object.data_source_name else True,
+ else true(),
+ GenTable.create_time >= time_range[0] if time_range and time_range[0] is not None else true(),
+ GenTable.create_time < time_range[1] if time_range and time_range[1] is not None else true(),
+ GenTable.data_source_name == query_object.data_source_name if query_object.data_source_name else true(),
)
.distinct()
)
@@ -317,10 +317,10 @@ async def get_gen_db_table_list(
message='PostgreSQL 系统目录不记录建表时间,请清除建表日期筛选',
msg_key='generator.creationDateUnsupported',
)
- if query_object.begin_time:
+ if metadata_range and metadata_range[0] is not None:
query_sql += metadata.created_after_filter
query_params['begin_time'] = metadata_range[0]
- if query_object.end_time:
+ if metadata_range and metadata_range[1] is not None:
query_sql += metadata.created_before_filter
query_params['end_time'] = metadata_range[1]
query_sql += ' order by create_time desc'
@@ -367,9 +367,9 @@ async def add_gen_table_dao(cls, db: AsyncSession, gen_table: GenTableModel) ->
:return: 新增的生成表记录
"""
db_gen_table = GenTable(
- **GenTableBaseModel(
- **gen_table.model_dump(by_alias=True, exclude={'create_time', 'update_time'})
- ).model_dump(exclude={'create_time', 'update_time'})
+ **GenTableBaseModel(**gen_table.model_dump(exclude={'create_time', 'update_time'})).model_dump(
+ exclude={'create_time', 'update_time'}
+ )
)
db.add(db_gen_table)
await db.flush()
@@ -404,7 +404,7 @@ class GenTableColumnDao:
"""代码生成业务表字段模块数据库操作层。"""
@classmethod
- async def get_gen_table_column_list_by_table_id(cls, db: AsyncSession, table_id: int) -> GenTableColumn:
+ async def get_gen_table_column_list_by_table_id(cls, db: AsyncSession, table_id: int) -> Sequence[GenTableColumn]:
"""
根据业务表id获取需要生成的业务表字段列表信息。
@@ -453,9 +453,9 @@ async def add_gen_table_column_dao(cls, db: AsyncSession, gen_table_column: GenT
:return: 新增的生成表列记录
"""
db_gen_table_column = GenTableColumn(
- **GenTableColumnBaseModel(
- **gen_table_column.model_dump(by_alias=True, exclude={'create_time', 'update_time'})
- ).model_dump(exclude={'create_time', 'update_time'})
+ **GenTableColumnBaseModel(**gen_table_column.model_dump(exclude={'create_time', 'update_time'})).model_dump(
+ exclude={'create_time', 'update_time'}
+ )
)
db.add(db_gen_table_column)
await db.flush()
diff --git a/ruoyi-fastapi-backend/module_generator/entity/do/gen_do.py b/ruoyi-fastapi-backend/module_generator/entity/do/gen_do.py
index e3386038d..3472ace67 100644
--- a/ruoyi-fastapi-backend/module_generator/entity/do/gen_do.py
+++ b/ruoyi-fastapi-backend/module_generator/entity/do/gen_do.py
@@ -1,5 +1,5 @@
-from sqlalchemy import CHAR, BigInteger, Column, Integer, String
-from sqlalchemy.orm import foreign, relationship
+from sqlalchemy import CHAR, BigInteger, Integer, String
+from sqlalchemy.orm import Mapped, foreign, mapped_column, relationship
from common.mixin import AuditTimeMixin
from config.database import Base
@@ -13,48 +13,60 @@ class GenTable(AuditTimeMixin, Base):
__tablename__ = 'gen_table'
__table_args__ = {'comment': '代码生成业务表'}
- table_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='编号')
- table_name = Column(String(200), nullable=True, server_default="''", comment='表名称')
- table_comment = Column(String(500), nullable=True, server_default="''", comment='表描述')
- data_source_name = Column(String(64), nullable=False, server_default='primary', comment='目标数据源名称')
- sub_table_name = Column(
+ table_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='编号'
+ )
+ table_name: Mapped[str | None] = mapped_column(String(200), nullable=True, server_default="''", comment='表名称')
+ table_comment: Mapped[str | None] = mapped_column(String(500), nullable=True, server_default="''", comment='表描述')
+ data_source_name: Mapped[str] = mapped_column(
+ String(64), nullable=False, server_default='primary', comment='目标数据源名称'
+ )
+ sub_table_name: Mapped[str | None] = mapped_column(
String(64),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='关联子表的表名',
)
- sub_table_fk_name = Column(
+ sub_table_fk_name: Mapped[str | None] = mapped_column(
String(64),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='子表关联的外键名',
)
- class_name = Column(String(100), nullable=True, server_default="''", comment='实体类名称')
- tpl_category = Column(
+ class_name: Mapped[str | None] = mapped_column(
+ String(100), nullable=True, server_default="''", comment='实体类名称'
+ )
+ tpl_category: Mapped[str | None] = mapped_column(
String(200), nullable=True, server_default='crud', comment='使用的模板(crud单表操作 tree树表操作)'
)
- tpl_web_type = Column(
+ tpl_web_type: Mapped[str | None] = mapped_column(
String(30), nullable=True, server_default="''", comment='前端模板类型(element-ui模版 element-plus模版)'
)
- package_name = Column(String(100), nullable=True, comment='生成包路径')
- module_name = Column(String(30), nullable=True, comment='生成模块名')
- business_name = Column(String(30), nullable=True, comment='生成业务名')
- function_name = Column(String(50), nullable=True, comment='生成功能名')
- function_author = Column(String(50), nullable=True, comment='生成功能作者')
- form_col_num = Column(Integer, nullable=True, server_default='1', comment='表单布局(单列 双列 三列)')
- gen_type = Column(CHAR(1), nullable=True, server_default='0', comment='生成代码方式(0zip压缩包 1自定义路径)')
- gen_path = Column(String(200), nullable=True, server_default='/', comment='生成路径(不填默认项目路径)')
- options = Column(String(1000), nullable=True, comment='其它生成选项')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- remark = Column(
+ package_name: Mapped[str | None] = mapped_column(String(100), nullable=True, comment='生成包路径')
+ module_name: Mapped[str | None] = mapped_column(String(30), nullable=True, comment='生成模块名')
+ business_name: Mapped[str | None] = mapped_column(String(30), nullable=True, comment='生成业务名')
+ function_name: Mapped[str | None] = mapped_column(String(50), nullable=True, comment='生成功能名')
+ function_author: Mapped[str | None] = mapped_column(String(50), nullable=True, comment='生成功能作者')
+ form_col_num: Mapped[int | None] = mapped_column(
+ Integer, nullable=True, server_default='1', comment='表单布局(单列 双列 三列)'
+ )
+ gen_type: Mapped[str | None] = mapped_column(
+ CHAR(1), nullable=True, server_default='0', comment='生成代码方式(0zip压缩包 1自定义路径)'
+ )
+ gen_path: Mapped[str | None] = mapped_column(
+ String(200), nullable=True, server_default='/', comment='生成路径(不填默认项目路径)'
+ )
+ options: Mapped[str | None] = mapped_column(String(1000), nullable=True, comment='其它生成选项')
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ remark: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='备注',
)
- columns = relationship(
+ columns: Mapped[list['GenTableColumn']] = relationship(
'GenTableColumn',
primaryjoin=lambda: GenTable.table_id == foreign(GenTableColumn.table_id),
order_by='GenTableColumn.sort',
@@ -68,32 +80,34 @@ class GenTableColumn(AuditTimeMixin, Base):
__tablename__ = 'gen_table_column'
__table_args__ = {'comment': '代码生成业务表字段'}
- column_id = Column(BigInteger, primary_key=True, autoincrement=True, nullable=False, comment='编号')
- table_id = Column(BigInteger, nullable=True, comment='归属表编号')
- column_name = Column(String(200), nullable=True, comment='列名称')
- column_comment = Column(String(500), nullable=True, comment='列描述')
- column_type = Column(String(100), nullable=True, comment='列类型')
- python_type = Column(String(500), nullable=True, comment='PYTHON类型')
- python_field = Column(String(200), nullable=True, comment='PYTHON字段名')
- is_pk = Column(CHAR(1), nullable=True, comment='是否主键(1是)')
- is_increment = Column(CHAR(1), nullable=True, comment='是否自增(1是)')
- is_required = Column(CHAR(1), nullable=True, comment='是否必填(1是)')
- is_unique = Column(CHAR(1), nullable=True, comment='是否唯一(1是)')
- is_insert = Column(CHAR(1), nullable=True, comment='是否为插入字段(1是)')
- is_edit = Column(CHAR(1), nullable=True, comment='是否编辑字段(1是)')
- is_list = Column(CHAR(1), nullable=True, comment='是否列表字段(1是)')
- is_query = Column(CHAR(1), nullable=True, comment='是否查询字段(1是)')
- query_type = Column(
+ column_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, autoincrement=True, nullable=False, comment='编号'
+ )
+ table_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='归属表编号')
+ column_name: Mapped[str | None] = mapped_column(String(200), nullable=True, comment='列名称')
+ column_comment: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='列描述')
+ column_type: Mapped[str | None] = mapped_column(String(100), nullable=True, comment='列类型')
+ python_type: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='PYTHON类型')
+ python_field: Mapped[str | None] = mapped_column(String(200), nullable=True, comment='PYTHON字段名')
+ is_pk: Mapped[str | None] = mapped_column(CHAR(1), nullable=True, comment='是否主键(1是)')
+ is_increment: Mapped[str | None] = mapped_column(CHAR(1), nullable=True, comment='是否自增(1是)')
+ is_required: Mapped[str | None] = mapped_column(CHAR(1), nullable=True, comment='是否必填(1是)')
+ is_unique: Mapped[str | None] = mapped_column(CHAR(1), nullable=True, comment='是否唯一(1是)')
+ is_insert: Mapped[str | None] = mapped_column(CHAR(1), nullable=True, comment='是否为插入字段(1是)')
+ is_edit: Mapped[str | None] = mapped_column(CHAR(1), nullable=True, comment='是否编辑字段(1是)')
+ is_list: Mapped[str | None] = mapped_column(CHAR(1), nullable=True, comment='是否列表字段(1是)')
+ is_query: Mapped[str | None] = mapped_column(CHAR(1), nullable=True, comment='是否查询字段(1是)')
+ query_type: Mapped[str | None] = mapped_column(
String(200), nullable=True, server_default='EQ', comment='查询方式(等于、不等于、大于、小于、范围)'
)
- html_type = Column(
+ html_type: Mapped[str | None] = mapped_column(
String(200), nullable=True, comment='显示类型(文本框、文本域、下拉框、复选框、单选框、日期控件)'
)
- dict_type = Column(String(200), nullable=True, server_default="''", comment='字典类型')
- sort = Column(Integer, nullable=True, comment='排序')
- create_by = Column(String(64), server_default="''", comment='创建者')
- update_by = Column(String(64), server_default="''", comment='更新者')
+ dict_type: Mapped[str | None] = mapped_column(String(200), nullable=True, server_default="''", comment='字典类型')
+ sort: Mapped[int | None] = mapped_column(Integer, nullable=True, comment='排序')
+ create_by: Mapped[str | None] = mapped_column(String(64), server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), server_default="''", comment='更新者')
- tables = relationship(
+ tables: Mapped[GenTable | None] = relationship(
'GenTable', primaryjoin=lambda: foreign(GenTableColumn.table_id) == GenTable.table_id, back_populates='columns'
)
diff --git a/ruoyi-fastapi-backend/module_generator/entity/vo/gen_vo.py b/ruoyi-fastapi-backend/module_generator/entity/vo/gen_vo.py
index b4e71b93c..7dfdd636a 100644
--- a/ruoyi-fastapi-backend/module_generator/entity/vo/gen_vo.py
+++ b/ruoyi-fastapi-backend/module_generator/entity/vo/gen_vo.py
@@ -1,20 +1,20 @@
from typing import Literal, Optional
-from pydantic import BaseModel, ConfigDict, Field, model_validator
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field, model_validator
from pydantic_validation_decorator import NotBlank
from common.constant import GenConstant
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from i18n.message import I18nMessage
from utils.string_util import StringUtil
-class GenTableBaseModel(BaseModel):
+class GenTableBaseModel(CamelModel):
"""代码生成业务表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
table_id: int | None = Field(default=None, description='编号')
table_name: str | None = Field(default=None, description='表名称')
@@ -144,22 +144,18 @@ class GenTableRowModel(GenTableBaseModel):
columns: list['GenTableColumnBaseModel'] | None = Field(default=None, description='表列信息')
-class GenTableDbRowModel(BaseModel):
+class GenTableDbRowModel(CamelModel):
"""代码生成业务表数据库行数据模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
table_name: str | None = Field(default=None, description='表名称')
table_comment: str | None = Field(default=None, description='表描述')
create_time: ApiUtcDateTime | None = Field(default=None, description='创建时间')
update_time: ApiUtcDateTime | None = Field(default=None, description='更新时间')
-class GenDataSourceModel(BaseModel):
+class GenDataSourceModel(CamelModel):
"""代码生成数据源选项模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
name: str = Field(description='数据源名称')
db_type: str = Field(description='数据库类型')
is_default: bool = Field(default=False, description='是否为默认数据源')
@@ -200,11 +196,9 @@ class EditGenTableModel(GenTableModel):
params: Optional['GenTableParamsModel'] = Field(default=None, description='业务表参数')
-class GenTableParamsModel(BaseModel):
+class GenTableParamsModel(CamelModel):
"""代码生成业务表参数模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
tree_code: str | None = Field(default=None, description='树编码字段')
tree_parent_code: str | None = Field(default=None, description='树父编码字段')
tree_name: str | None = Field(default=None, description='树名称字段')
@@ -233,28 +227,24 @@ class GenTablePageQueryModel(GenTableQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class GenTableDetailModel(BaseModel):
+class GenTableDetailModel(CamelModel):
"""代码生成业务表详情模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
info: GenTableModel | None = Field(default=None, description='业务表信息')
rows: list['GenTableColumnModel'] | None = Field(default=None, description='表列信息')
tables: list['GenTableModel'] | None = Field(default=None, description='所有业务表信息')
-class DeleteGenTableModel(BaseModel):
+class DeleteGenTableModel(CamelModel):
"""删除代码生成业务表模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
table_ids: str = Field(description='需要删除的代码生成业务表ID')
-class GenTableColumnBaseModel(BaseModel):
+class GenTableColumnBaseModel(CamelModel):
"""代码生成业务表字段对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
column_id: int | None = Field(default=None, description='编号')
table_id: int | None = Field(default=None, description='归属表编号')
@@ -316,14 +306,14 @@ class GenTableColumnModel(GenTableColumnBaseModel):
vo_type: str | None = Field(default=None, exclude=True, description='生成的 Pydantic 模型使用的字段类型')
@model_validator(mode='after')
- def check_some_is(self) -> 'GenTableModel':
+ def check_some_is(self) -> 'GenTableColumnModel':
"""
根据数据库列配置计算生成模板使用的字段标志。
:return: 当前实例
"""
self.cap_python_field = self.python_field[0].upper() + self.python_field[1:] if self.python_field else None
- self.pk = self.is_pk and self.is_pk == '1'
+ self.pk = self.is_pk == '1' if self.is_pk is not None else None
self.increment = bool(self.is_increment and self.is_increment == '1')
self.required = bool(self.is_required and self.is_required == '1')
self.unique = bool(self.is_unique and self.is_unique == '1')
@@ -354,9 +344,7 @@ class GenTableColumnPageQueryModel(GenTableColumnQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class DeleteGenTableColumnModel(BaseModel):
+class DeleteGenTableColumnModel(CamelModel):
"""删除代码生成业务表字段模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
column_ids: str = Field(description='需要删除的代码生成业务表字段ID')
diff --git a/ruoyi-fastapi-backend/module_generator/service/gen_service.py b/ruoyi-fastapi-backend/module_generator/service/gen_service.py
index 615749f2a..46b112f9e 100644
--- a/ruoyi-fastapi-backend/module_generator/service/gen_service.py
+++ b/ruoyi-fastapi-backend/module_generator/service/gen_service.py
@@ -3,12 +3,13 @@
import os
import zipfile
from pathlib import Path
-from typing import Any
+from typing import Any, Literal, overload
import aiofiles
+from jinja2 import Environment
from sqlalchemy.ext.asyncio import AsyncSession
from sqlglot import parse as sqlglot_parse
-from sqlglot.expressions import Add, Alter, Create, Delete, Drop, Expression, Insert, Table, TruncateTable, Update
+from sqlglot.expressions import Add, Alter, Create, Delete, Drop, Expr, Insert, Table, TruncateTable, Update
from common.constant import GenConstant
from common.vo import CrudResponseModel, PageModel
@@ -43,7 +44,7 @@ def get_data_source_list_services(cls) -> list[GenDataSourceModel]:
"""
default_name = DataBaseConfig.db_default_source
return [
- GenDataSourceModel(name=name, dbType=config.db_type, isDefault=name == default_name)
+ GenDataSourceModel(name=name, db_type=config.db_type, is_default=name == default_name)
for name, config in DataBaseConfig.db_sources.items()
]
@@ -57,6 +58,18 @@ def _source_name(source_name: str | None) -> str:
"""
return source_name or DataBaseConfig.db_default_source
+ @classmethod
+ @overload
+ async def get_gen_table_list_services(
+ cls, query_db: AsyncSession, query_object: GenTablePageQueryModel, is_page: Literal[True]
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_gen_table_list_services(
+ cls, query_db: AsyncSession, query_object: GenTablePageQueryModel, is_page: Literal[False] = False
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_gen_table_list_services(
cls, query_db: AsyncSession, query_object: GenTablePageQueryModel, is_page: bool = False
@@ -73,6 +86,18 @@ async def get_gen_table_list_services(
return gen_table_list_result
+ @classmethod
+ @overload
+ async def get_gen_db_table_list_services(
+ cls, query_db: AsyncSession, query_object: GenTablePageQueryModel, is_page: Literal[True]
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_gen_db_table_list_services(
+ cls, query_db: AsyncSession, query_object: GenTablePageQueryModel, is_page: Literal[False] = False
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_gen_db_table_list_services(
cls,
@@ -118,7 +143,7 @@ async def get_gen_db_table_list_by_name_services(
async with DataSourceRegistry.session(source_name) as target_db:
rows = await GenTableDao.get_gen_db_table_list_by_names(target_db, table_names, source_config)
result = [
- GenTableModel(**gen_table, dataSourceName=source_name)
+ GenTableModel(**gen_table, data_source_name=source_name)
for gen_table in CamelCaseUtil.transform_result(rows)
]
return result
@@ -144,7 +169,7 @@ async def import_gen_table_services(
try:
async with DataSourceRegistry.session(source_name) as target_db:
for table in gen_table_list:
- table_name = table.table_name
+ table_name = GenUtils.require_metadata(table.table_name)
table.data_source_name = source_name
GenUtils.init_table(table, current_user.user.user_name)
add_gen_table = await GenTableDao.add_gen_table_dao(query_db, table)
@@ -181,6 +206,8 @@ async def edit_gen_table_services(cls, query_db: AsyncSession, page_object: Edit
by_alias=True,
exclude={'create_time', 'update_time'},
)
+ if page_object.table_id is None:
+ raise ServiceException(message='业务表不存在', msg_key='generator.tableNotFound')
gen_table_info = await cls.get_gen_table_by_id_services(query_db, page_object.table_id)
if gen_table_info.table_id:
try:
@@ -190,7 +217,7 @@ async def edit_gen_table_services(cls, query_db: AsyncSession, page_object: Edit
options.update(edit_gen_table.get('params') or {})
edit_gen_table['options'] = json.dumps(options)
await GenTableDao.edit_gen_table_dao(query_db, edit_gen_table)
- for gen_table_column in page_object.columns:
+ for gen_table_column in page_object.columns or []:
gen_table_column.update_by = page_object.update_by
await GenTableColumnDao.edit_gen_table_column_dao(
query_db,
@@ -224,9 +251,9 @@ async def delete_gen_table_services(
table_id_list = page_object.table_ids.split(',')
try:
for table_id in table_id_list:
- await GenTableDao.delete_gen_table_dao(query_db, GenTableModel(tableId=table_id))
+ await GenTableDao.delete_gen_table_dao(query_db, GenTableModel(table_id=table_id))
await GenTableColumnDao.delete_gen_table_column_by_table_id_dao(
- query_db, GenTableColumnModel(tableId=table_id)
+ query_db, GenTableColumnModel(table_id=table_id)
)
await query_db.commit()
return CrudResponseModel(is_success=True, message='删除成功', msg_key='common.deleted')
@@ -282,7 +309,11 @@ async def create_table_services(
"""
source_name = cls._source_name(source_name)
target_config = DataBaseConfig.get_source(source_name)
- sql_statements = sqlglot_parse(sql, dialect=target_config.sqlglot_parse_dialect)
+ sql_statements = []
+ for statement in sqlglot_parse(sql, dialect=target_config.sqlglot_parse_dialect):
+ if statement is None:
+ raise ServiceException(message='建表语句不合法', msg_key='generator.invalidCreateStatement')
+ sql_statements.append(statement)
if cls.__is_valid_create_table(sql_statements):
try:
table_names = cls.__get_table_names(sql_statements)
@@ -303,7 +334,7 @@ async def create_table_services(
raise ServiceException(message='建表语句不合法', msg_key='generator.invalidCreateStatement')
@classmethod
- def __is_valid_create_table(cls, sql_statements: list[Expression]) -> bool:
+ def __is_valid_create_table(cls, sql_statements: list[Expr]) -> bool:
"""
校验sql语句是否为合法的建表语句。
@@ -321,17 +352,21 @@ def __is_valid_create_table(cls, sql_statements: list[Expression]) -> bool:
return not (not any(validate_create) or any(validate_forbidden_keywords))
@classmethod
- def __get_table_names(cls, sql_statements: list[Expression]) -> list[str]:
+ def __get_table_names(cls, sql_statements: list[Expr]) -> list[str]:
"""
获取sql语句中所有的建表表名。
:param sql_statements: sql语句的ast列表
:return: 建表表名列表
- """
- table_names = [
- sql_statement.find(Table).name for sql_statement in sql_statements if isinstance(sql_statement, Create)
- ]
-
+ :raises ServiceException: 建表语句缺少表名称
+ """
+ table_names = []
+ for statement in sql_statements:
+ if isinstance(statement, Create):
+ table = statement.find(Table)
+ if table is None:
+ raise ServiceException(message='建表语句不合法', msg_key='generator.invalidCreateStatement')
+ table_names.append(table.name)
return table_names
@classmethod
@@ -376,8 +411,8 @@ async def generate_code_services(
env = TemplateInitializer.init_jinja2()
render_info = await cls.__get_gen_render_info(query_db, table_name, source_name)
try:
- output_root = cls.__get_output_root(render_info[3])
- files = cls.__render_files(env, render_info)
+ output_root = cls._get_output_root(render_info[3])
+ files = cls._render_files(env, render_info)
output_paths = {name: cls.__get_output_path(output_root, name) for name in files}
# 全部词库解析、合并成功后才开始写入,避免无效资源造成半份产物。
for relative_path, content in files.items():
@@ -430,7 +465,7 @@ async def batch_gen_code_services(
for table_name in table_names:
env = TemplateInitializer.init_jinja2()
render_info = await cls.__get_gen_render_info(query_db, table_name, source_name)
- generated_files = cls.__render_files(env, render_info)
+ generated_files = cls._render_files(env, render_info)
generators.append(render_info[2]['generatedI18n'])
for path, content in generated_files.items():
files[path] = GenI18nUtil.merge_content(path, files[path], content) if path in files else content
@@ -447,7 +482,7 @@ async def batch_gen_code_services(
return zip_data
@classmethod
- def __render_files(cls, env: Any, render_info: list) -> dict[str, str]:
+ def _render_files(cls, env: Environment, render_info: list) -> dict[str, str]:
"""
渲染源码后收集模板登记的独立语言资源。
@@ -455,7 +490,7 @@ def __render_files(cls, env: Any, render_info: list) -> dict[str, str]:
:param render_info: 模板、输出路径、上下文和业务表
:return: 生成包内相对路径及内容
"""
- files = {
+ files: dict[str, str] = {
output_file: env.get_template(template).render(**render_info[2])
for template, output_file in zip(render_info[0], render_info[1], strict=True)
}
@@ -483,7 +518,7 @@ def __get_output_path(output_root: Path, relative_path: str) -> Path:
return resolved
@staticmethod
- def __get_output_root(gen_table: GenTableModel) -> Path:
+ def _get_output_root(gen_table: GenTableModel) -> Path:
"""
保持生成路径为独立生成包根,拒绝直接覆盖已知应用源码。
@@ -507,9 +542,7 @@ def __get_output_root(gen_table: GenTableModel) -> Path:
return root
@classmethod
- async def __get_gen_render_info(
- cls, query_db: AsyncSession, table_name: str, source_name: str | None = None
- ) -> list:
+ async def __get_gen_render_info(cls, query_db: AsyncSession, table_name: str, source_name: str) -> list:
"""
获取生成代码渲染模板相关信息。
@@ -535,21 +568,6 @@ async def __get_gen_render_info(
return [template_list, output_files, context, gen_table]
- @classmethod
- def __get_gen_path(cls, gen_table: GenTableModel, template: str) -> str:
- """
- 根据GenTableModel对象和模板名称生成路径。
-
- :param gen_table: GenTableModel对象
- :param template: 模板名称
- :return: 生成的路径
- """
- gen_path = gen_table.gen_path
- if gen_path == '/':
- return os.path.join(os.getcwd(), GenConfig.GEN_PATH, TemplateUtils.get_file_name(template, gen_table))
-
- return os.path.join(gen_path, TemplateUtils.get_file_name(template, gen_table))
-
@classmethod
async def sync_db_services(
cls, query_db: AsyncSession, table_name: str, source_name: str | None = None
@@ -566,8 +584,10 @@ async def sync_db_services(
"""
source_name = cls._source_name(source_name)
gen_table = await GenTableDao.get_gen_table_by_name(query_db, table_name, source_name)
+ if gen_table is None:
+ raise ServiceException(message='业务表不存在', msg_key='generator.tableNotFound')
table = GenTableModel(**CamelCaseUtil.transform_result(gen_table))
- table_columns = table.columns
+ table_columns = table.columns or []
table_column_map = {column.column_name: column for column in table_columns}
source_config = DataBaseConfig.get_source(source_name)
async with DataSourceRegistry.session(source_name) as target_db:
@@ -617,35 +637,43 @@ async def set_sub_table(cls, query_db: AsyncSession, gen_table: GenTableModel) -
:param query_db: orm对象
:param gen_table: 业务表信息
+ :raises ServiceException: 关联子表未在选中数据源登记
"""
if gen_table.sub_table_name:
+ source_name = cls._source_name(gen_table.data_source_name)
sub_table = await GenTableDao.get_gen_table_by_name(
query_db,
gen_table.sub_table_name,
- cls._source_name(gen_table.data_source_name),
+ source_name,
)
+ if sub_table is None:
+ raise ServiceException(
+ message=f'业务表不存在或不属于数据源 {source_name}:{gen_table.sub_table_name}',
+ msg_key='generator.tableOutsideSource',
+ msg_params={'source_name': source_name, 'table_name': gen_table.sub_table_name},
+ )
gen_table.sub_table = GenTableModel(**CamelCaseUtil.transform_result(sub_table))
@classmethod
async def set_pk_column(cls, gen_table: GenTableModel) -> None:
"""
- 设置主键列信息。
+ 为主表和关联子表选择主键,未标记主键时使用已有配置或首列。
:param gen_table: 业务表信息
+ :raises ServiceException: 主子表配置不完整或没有可用的字段
"""
- for column in gen_table.columns:
- if column.pk:
- gen_table.pk_column = column
- break
- if gen_table.pk_column is None:
- gen_table.pk_column = gen_table.columns[0]
+ tables = [gen_table]
if gen_table.tpl_category == GenConstant.TPL_SUB:
- for column in gen_table.sub_table.columns:
- if column.pk:
- gen_table.sub_table.pk_column = column
- break
- if gen_table.sub_table.columns is None:
- gen_table.sub_table.pk_column = gen_table.sub_table.columns[0]
+ if gen_table.sub_table is None:
+ raise ServiceException(message='关联子表的表名不能为空', msg_key='generator.childTableRequired')
+ tables.append(gen_table.sub_table)
+ for table in tables:
+ if table.columns:
+ table.pk_column = next(
+ (column for column in table.columns if column.pk), table.pk_column or table.columns[0]
+ )
+ elif table.pk_column is None:
+ raise ServiceException(message='请先完善生成配置信息', msg_key='generator.configurationRequired')
@classmethod
async def set_table_from_options(cls, gen_table: GenTableModel) -> GenTableModel:
@@ -675,21 +703,19 @@ async def validate_edit(cls, edit_gen_table: EditGenTableModel) -> None:
:raises ServiceException: 树编码字段不能为空;树父编码字段不能为空;树名称字段不能为空;关联子表的表名不能为空;子表关联的外键名不能为空
"""
if edit_gen_table.tpl_category == GenConstant.TPL_TREE:
- params_obj = edit_gen_table.params.model_dump(by_alias=True)
+ params = edit_gen_table.params
- if GenConstant.TREE_CODE not in params_obj:
+ if params is None or not params.tree_code:
raise ServiceException(message='树编码字段不能为空', msg_key='generator.treeCodeRequired')
- if GenConstant.TREE_PARENT_CODE not in params_obj:
+ if not params.tree_parent_code:
raise ServiceException(message='树父编码字段不能为空', msg_key='generator.treeParentCodeRequired')
- if GenConstant.TREE_NAME not in params_obj:
+ if not params.tree_name:
raise ServiceException(message='树名称字段不能为空', msg_key='generator.treeNameRequired')
- if edit_gen_table.tpl_category == GenConstant.TPL_SUB:
- if not edit_gen_table.sub_table_name:
- raise ServiceException(message='关联子表的表名不能为空', msg_key='generator.childTableRequired')
- if not edit_gen_table.sub_table_fk_name:
- raise ServiceException(
- message='子表关联的外键名不能为空', msg_key='generator.childForeignKeyRequired'
- )
+ if edit_gen_table.tpl_category == GenConstant.TPL_SUB:
+ if not edit_gen_table.sub_table_name:
+ raise ServiceException(message='关联子表的表名不能为空', msg_key='generator.childTableRequired')
+ if not edit_gen_table.sub_table_fk_name:
+ raise ServiceException(message='子表关联的外键名不能为空', msg_key='generator.childForeignKeyRequired')
class GenTableColumnService:
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2
index 230ade6d6..7cab9b033 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2
@@ -1,4 +1,3 @@
-{% set pkField = pkColumn.python_field %}
{% set pk_field = pkColumn.python_field | camel_to_snake %}
{% set pkParentheseIndex = pkColumn.column_comment.find("(") %}
{% set pk_field_comment = pkColumn.column_comment[:pkParentheseIndex] if pkParentheseIndex != -1 else pkColumn.column_comment %}
@@ -59,7 +58,7 @@ class {{ BusinessName }}Service:
:return: 校验结果
"""
{{ pk_field }} = -1 if page_object.{{ pk_field }} is None else page_object.{{ pk_field }}
- {{ businessName }} = await {{ BusinessName }}Dao.get_{{ businessName }}_detail_by_info(query_db, {{ BusinessName }}Model({{ column.python_field }}=page_object.{{ column.python_field | camel_to_snake }}))
+ {{ businessName }} = await {{ BusinessName }}Dao.get_{{ businessName }}_detail_by_info(query_db, {{ BusinessName }}Model({{ column.python_field | camel_to_snake }}=page_object.{{ column.python_field | camel_to_snake }}))
if {{ businessName }} and {{ businessName }}.{{ pk_field }} != {{ pk_field }}:
return CommonConstant.NOT_UNIQUE
return CommonConstant.UNIQUE
@@ -172,7 +171,7 @@ class {{ BusinessName }}Service:
for sub_table in {{ businessName }}.{{ subclassName }}_list:
await {{ BusinessName }}Dao.delete_{{ subTable.business_name }}_dao(query_db, sub_table)
{% endif %}
- await {{ BusinessName }}Dao.delete_{{ businessName }}_dao(query_db, {{ BusinessName }}Model({{ pkField }}={{ pk_field }}))
+ await {{ BusinessName }}Dao.delete_{{ businessName }}_dao(query_db, {{ BusinessName }}Model({{ pk_field }}={{ pk_field }}))
await query_db.commit()
return CrudResponseModel(is_success=True, message='删除成功', msg_key='common.deleted')
except Exception as e:
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/vo.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/vo.py.jinja2
index 092332a03..ec4588b84 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/vo.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/vo.py.jinja2
@@ -29,12 +29,9 @@
from typing import ClassVar
{% endif %}
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field
{% if vo_field_required.has_required or sub_vo_field_required.has_required %}
from pydantic_validation_decorator import NotBlank
-
-from i18n.message import I18nMessage
{% endif %}
{% if vo_field_daterange.has_daterange %}
@@ -45,13 +42,17 @@ from common.mixin import GeneratedTimeRangeQueryMixin
{{ vo_import }}
{% endif %}
{% endfor %}
+from common.vo import CamelModel
+{% if vo_field_required.has_required or sub_vo_field_required.has_required %}
+from i18n.message import I18nMessage
+{% endif %}
{% if table.sub %}
-class {{ BusinessName }}BaseModel(BaseModel):
+class {{ BusinessName }}BaseModel(CamelModel):
"""{{ functionName }}表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
{% for column in columns %}
{{ column.column_name }}: {{ column.vo_type }} | None = Field(default=None, description={{ column.column_comment | model_field_label | tojson }})
@@ -91,10 +92,10 @@ class {{ BusinessName }}BaseModel(BaseModel):
{% endif %}
-class {{ BusinessName }}Model({% if table.sub %}{{ BusinessName }}BaseModel{% else %}BaseModel{% endif %}):
+class {{ BusinessName }}Model({% if table.sub %}{{ BusinessName }}BaseModel{% else %}CamelModel{% endif %}):
"""{{ functionName }}表对应pydantic模型。"""
{% if not table.sub %}
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
{% for column in columns %}
{{ column.column_name }}: {{ column.vo_type }} | None = Field(default=None, description={{ column.column_comment | model_field_label | tojson }})
@@ -140,10 +141,10 @@ class {{ BusinessName }}Model({% if table.sub %}{{ BusinessName }}BaseModel{% el
{% if table.sub %}
-class {{ subTable.business_name | capitalize }}Model(BaseModel):
+class {{ subTable.business_name | capitalize }}Model(CamelModel):
"""{{ subTable.function_name }}表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
{% for sub_column in subTable.columns %}
{{ sub_column.column_name }}: {{ sub_column.vo_type }} | None = Field(default=None, description={{ sub_column.column_comment | model_field_label | tojson }})
@@ -212,9 +213,7 @@ class {{ BusinessName }}PageQueryModel({{ BusinessName }}QueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class Delete{{ BusinessName }}Model(BaseModel):
+class Delete{{ BusinessName }}Model(CamelModel):
"""删除{{ functionName }}模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
{{ pk_field }}s: str = Field(description={{ ('需要删除的' ~ pk_field_comment) | tojson }})
diff --git a/ruoyi-fastapi-backend/module_identity/controller/interaction_controller.py b/ruoyi-fastapi-backend/module_identity/controller/interaction_controller.py
index 418b702d1..3db176076 100644
--- a/ruoyi-fastapi-backend/module_identity/controller/interaction_controller.py
+++ b/ruoyi-fastapi-backend/module_identity/controller/interaction_controller.py
@@ -1,5 +1,5 @@
import json
-from typing import Annotated, TypeVar
+from typing import Annotated, TypeVar, cast
from fastapi import Depends, Header, Request
from fastapi.responses import Response
@@ -54,7 +54,7 @@ def _redis(request: Request) -> Redis:
value = getattr(request.app.state, 'redis', None)
if value is None:
raise OidcInteractionException(error='server_error', status_code=503, message='认证服务不可用')
- return value
+ return cast('Redis', value)
def _not_found() -> Response:
diff --git a/ruoyi-fastapi-backend/module_identity/controller/token_controller.py b/ruoyi-fastapi-backend/module_identity/controller/token_controller.py
index e5659a035..5884805a8 100644
--- a/ruoyi-fastapi-backend/module_identity/controller/token_controller.py
+++ b/ruoyi-fastapi-backend/module_identity/controller/token_controller.py
@@ -143,16 +143,16 @@ def _rate_limit_error(error: RateLimitExceeded | RateLimitUnavailable) -> JSONRe
return JSONResponse(content={'error': 'temporarily_unavailable'}, status_code=503, headers=_NO_STORE)
-async def _record_independent_audit(db: AsyncSession, event_type: str, **fields: object) -> None:
+async def _record_independent_audit(db: AsyncSession, event_type: str, *, failure_code: str) -> None:
"""
尝试记录协议失败审计,审计异常不改变标准错误响应。
:param db: 异步数据库会话
:param event_type: 审计事件类型
- :param fields: 审计字段
+ :param failure_code: 写入审计日志的协议错误码
"""
try:
- await AuditService.record_independent(db, event_type, 'failure', **fields)
+ await AuditService.record_independent(db, event_type, 'failure', failure_code=failure_code)
except Exception:
return
diff --git a/ruoyi-fastapi-backend/module_identity/dao/identity_subject_dao.py b/ruoyi-fastapi-backend/module_identity/dao/identity_subject_dao.py
index bd223f841..70da0a44e 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/identity_subject_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/identity_subject_dao.py
@@ -6,6 +6,7 @@
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
+from config.database import execute_rowcount
from module_admin.entity.do.user_do import SysUser
from module_identity.entity.do.identity_subject_do import SysIdentitySubject
from utils.time_util import TimezoneUtil
@@ -105,12 +106,12 @@ async def backfill_for_users(
:param create_by: 创建人标识
:return: 补齐后的 Identity Subject 序列
"""
+ rows: list[SysIdentitySubject] = []
ids = list(dict.fromkeys(user_ids))
if not ids:
- return []
+ return rows
result = await db.execute(select(SysIdentitySubject.user_id).where(SysIdentitySubject.user_id.in_(ids)))
existing = set(result.scalars().all())
- rows: list[SysIdentitySubject] = []
for user_id in ids:
if user_id in existing:
continue
@@ -130,13 +131,14 @@ async def increment_auth_version(cls, db: AsyncSession, user_id: int, expected_v
conditions = [SysIdentitySubject.user_id == user_id]
if expected_version is not None:
conditions.append(SysIdentitySubject.auth_version == expected_version)
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysIdentitySubject)
.where(*conditions)
- .values(auth_version=SysIdentitySubject.auth_version + 1, update_time=TimezoneUtil.utc_now())
+ .values(auth_version=SysIdentitySubject.auth_version + 1, update_time=TimezoneUtil.utc_now()),
)
- return bool(result.rowcount)
+ return bool(affected)
@classmethod
async def increment_auth_versions(
@@ -151,18 +153,19 @@ async def increment_auth_versions(
:param now: 当前时间
:return: 成功更新的 Identity Subject 数量
"""
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysIdentitySubject)
.where(SysIdentitySubject.user_id.in_(user_ids))
.values(
auth_version=SysIdentitySubject.auth_version + 1,
update_by=update_by,
update_time=now or TimezoneUtil.utc_now(),
- )
+ ),
)
await db.flush()
- return result.rowcount or 0
+ return affected
@classmethod
async def list_missing_user_ids(cls, db: AsyncSession, user_ids: Iterable[int] | None = None) -> list[int]:
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oauth_audit_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oauth_audit_dao.py
index ae0c6e33d..1278f0ca5 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oauth_audit_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oauth_audit_dao.py
@@ -1,5 +1,6 @@
from collections.abc import Iterable, Sequence
from datetime import datetime
+from typing import TypedDict, Unpack
from sqlalchemy import delete, func, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -7,6 +8,28 @@
from module_identity.entity.do.oauth_audit_do import SysOAuthAuditArchive, SysOAuthAuditLog
+class AuditFilters(TypedDict, total=False):
+ """
+ 管理端审计查询的可选筛选条件。
+
+ :ivar client_id: Client 公开标识
+ :ivar user_id: 用户编号
+ :ivar event_type: 审计事件类型
+ :ivar result: 审计结果
+ :ivar risk_level: 审计风险级别
+ :ivar start_time: 查询开始时间
+ :ivar end_time: 查询结束时间
+ """
+
+ client_id: str | None
+ user_id: int | None
+ event_type: str | None
+ result: str | None
+ risk_level: str | None
+ start_time: datetime | None
+ end_time: datetime | None
+
+
class OAuthAuditDao:
"""OAuth Audit 数据库操作层。"""
@@ -127,13 +150,7 @@ async def list_admin_page(
*,
offset: int,
limit: int,
- client_id: str | None = None,
- user_id: int | None = None,
- event_type: str | None = None,
- result: str | None = None,
- risk_level: str | None = None,
- start_time: datetime | None = None,
- end_time: datetime | None = None,
+ **filters: Unpack[AuditFilters],
) -> Sequence[SysOAuthAuditLog]:
"""
分页查询管理端 OAuth Audit 日志。
@@ -141,28 +158,12 @@ async def list_admin_page(
:param db: orm对象
:param offset: 分页偏移量
:param limit: 分页大小
- :param client_id: Client 公开标识
- :param user_id: 用户编号
- :param event_type: 审计事件类型
- :param result: 审计结果
- :param risk_level: 审计风险级别
- :param start_time: 查询开始时间
- :param end_time: 查询结束时间
+ :param filters: 审计事件筛选条件
:return: 管理端 OAuth Audit 日志序列
"""
query = (
select(SysOAuthAuditLog)
- .where(
- *cls._conditions(
- client_id=client_id,
- user_id=user_id,
- event_type=event_type,
- result=result,
- risk_level=risk_level,
- start_time=start_time,
- end_time=end_time,
- )
- )
+ .where(*cls._conditions(**filters))
.order_by(SysOAuthAuditLog.event_id.desc())
.offset(max(offset, 0))
.limit(min(max(limit, 1), 5000))
@@ -175,45 +176,18 @@ async def list_admin_page(
async def count_admin(
cls,
db: AsyncSession,
- *,
- client_id: str | None = None,
- user_id: int | None = None,
- event_type: str | None = None,
- result: str | None = None,
- risk_level: str | None = None,
- start_time: datetime | None = None,
- end_time: datetime | None = None,
+ **filters: Unpack[AuditFilters],
) -> int:
"""
统计管理端 OAuth Audit 日志数量。
:param db: orm对象
- :param client_id: Client 公开标识
- :param user_id: 用户编号
- :param event_type: 审计事件类型
- :param result: 审计结果
- :param risk_level: 审计风险级别
- :param start_time: 查询开始时间
- :param end_time: 查询结束时间
+ :param filters: 审计事件筛选条件
:return: 符合条件的 OAuth Audit 日志数量
"""
- result = await db.execute(
- select(func.count())
- .select_from(SysOAuthAuditLog)
- .where(
- *cls._conditions(
- client_id=client_id,
- user_id=user_id,
- event_type=event_type,
- result=result,
- risk_level=risk_level,
- start_time=start_time,
- end_time=end_time,
- )
- )
- )
+ rows = await db.execute(select(func.count()).select_from(SysOAuthAuditLog).where(*cls._conditions(**filters)))
- return int(result.scalar_one())
+ return rows.scalar_one()
@classmethod
async def archive_before(cls, db: AsyncSession, before: datetime, limit: int = 1000) -> int:
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oauth_client_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oauth_client_dao.py
index cf73f8b1a..03e01d212 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oauth_client_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oauth_client_dao.py
@@ -1,9 +1,10 @@
from collections.abc import Mapping, Sequence
from datetime import datetime
-from sqlalchemy import delete, func, select, update
+from sqlalchemy import Row, delete, func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
+from config.database import execute_rowcount
from module_identity.entity.do.oauth_client_do import SysOAuthClient, SysOAuthClientSecret, SysOAuthClientUri
from module_identity.entity.do.oauth_grant_do import SysOAuthGrant, SysOAuthRefreshToken
from module_identity.entity.do.oauth_resource_do import (
@@ -108,7 +109,7 @@ async def id_map(cls, db: AsyncSession, client_pks: Sequence[int]) -> Mapping[in
:return: Client 内部主键到公开标识的映射
"""
if not client_pks:
- return {}
+ return dict[int, str]()
result = await db.execute(
select(SysOAuthClient.client_pk, SysOAuthClient.client_id).where(SysOAuthClient.client_pk.in_(client_pks))
)
@@ -205,13 +206,14 @@ async def mark_secret_used(cls, db: AsyncSession, secret_id: str) -> bool:
:param secret_id: Client Secret 标识
:return: 是否更新成功
"""
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOAuthClientSecret)
.where(SysOAuthClientSecret.secret_id == secret_id)
- .values(last_used_at=TimezoneUtil.utc_now())
+ .values(last_used_at=TimezoneUtil.utc_now()),
)
- return bool(result.rowcount)
+ return bool(affected)
@classmethod
async def list_uris(
@@ -584,7 +586,7 @@ async def revoke_client_credentials(cls, db: AsyncSession, client_pk: int, now:
@classmethod
async def get_client_detail_rows(
cls, db: AsyncSession, client_id: str
- ) -> tuple[SysOAuthClient, list[tuple[SysOAuthScope, int]], list[str], Sequence[SysOAuthClientUri]] | None:
+ ) -> tuple[SysOAuthClient, Sequence[Row[SysOAuthScope, int]], list[str], Sequence[SysOAuthClientUri]] | None:
"""
查询 OAuth Client 详情及关联数据。
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oauth_grant_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oauth_grant_dao.py
index 3ab3eac85..31f6f9bbd 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oauth_grant_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oauth_grant_dao.py
@@ -6,9 +6,11 @@
from sqlalchemy import case, func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
+from config.database import execute_rowcount
from module_identity.dao.oauth_access_policy_dao import OAuthAccessPolicyDao
from module_identity.entity.do.oauth_client_do import SysOAuthClient
from module_identity.entity.do.oauth_grant_do import SysOAuthAccessPolicy, SysOAuthGrant, SysOAuthRefreshToken
+from module_identity.entity.types import AuthorizationStatus
from utils.time_util import TimezoneUtil
@@ -41,7 +43,7 @@ class OAuthGrantSnapshot:
granted_scopes: tuple[str, ...]
granted_resources: tuple[str, ...]
client_policy_version: int
- status: str
+ status: AuthorizationStatus
consented_at: datetime
expires_at: datetime | None
revoked_at: datetime | None
@@ -332,7 +334,8 @@ async def revoke(cls, db: AsyncSession, grant_id: str, reason: str | None = None
)
.values(status='revoked', revoked_at=TimezoneUtil.utc_now(), revoke_reason=reason)
)
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOAuthGrant)
.where(SysOAuthGrant.grant_id == grant_id, SysOAuthGrant.status == 'active')
.values(
@@ -341,10 +344,10 @@ async def revoke(cls, db: AsyncSession, grant_id: str, reason: str | None = None
revoke_reason=reason,
remembered_scopes=[],
remembered_resources=[],
- )
+ ),
)
- return bool(result.rowcount)
+ return bool(affected)
@staticmethod
async def targets(db: AsyncSession, grant_ids: list[str]) -> list[tuple[int, int]]:
@@ -399,13 +402,14 @@ async def revoke_for_user(cls, db: AsyncSession, user_id: int, reason: str | Non
:param reason: 撤销或标记原因
:return: 已撤销的 OAuth Grant 数量
"""
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOAuthGrant)
.where(SysOAuthGrant.user_id == user_id, SysOAuthGrant.status == 'active')
- .values(status='revoked', revoked_at=TimezoneUtil.utc_now(), revoke_reason=reason)
+ .values(status='revoked', revoked_at=TimezoneUtil.utc_now(), revoke_reason=reason),
)
- return result.rowcount or 0
+ return affected
@classmethod
async def list_for_user(cls, db: AsyncSession, user_id: int, status: str | None = None) -> Sequence[SysOAuthGrant]:
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oauth_token_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oauth_token_dao.py
index c2bad8d06..70e5dc41d 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oauth_token_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oauth_token_dao.py
@@ -4,6 +4,7 @@
from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession
+from config.database import execute_rowcount
from module_identity.entity.do.oauth_grant_do import SysOAuthRefreshToken
from utils.time_util import TimezoneUtil
@@ -128,13 +129,14 @@ async def mark_used(
values: dict[str, object] = {'status': 'used', 'last_used_at': now or TimezoneUtil.utc_now()}
if replaced_by_token_id is not None:
values['replaced_by_token_id'] = replaced_by_token_id
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOAuthRefreshToken)
.where(SysOAuthRefreshToken.token_id == token_id, SysOAuthRefreshToken.status == 'active')
- .values(**values)
+ .values(**values),
)
- return bool(result.rowcount)
+ return bool(affected)
@classmethod
async def mark_reuse_detected(cls, db: AsyncSession, token_id: str, reason: str = 'refresh_token_reuse') -> bool:
@@ -147,13 +149,14 @@ async def mark_reuse_detected(cls, db: AsyncSession, token_id: str, reason: str
:return: 是否更新成功
"""
now = TimezoneUtil.utc_now()
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOAuthRefreshToken)
.where(SysOAuthRefreshToken.token_id == token_id)
- .values(status='reuse_detected', reuse_detected_at=now, revoked_at=now, revoke_reason=reason)
+ .values(status='reuse_detected', reuse_detected_at=now, revoked_at=now, revoke_reason=reason),
)
- return bool(result.rowcount)
+ return bool(affected)
@classmethod
async def refresh_token_family_reuse(
@@ -177,22 +180,24 @@ async def refresh_token_family_reuse(
"""
await cls.lock_family(db, family_id)
current = now or TimezoneUtil.utc_now()
- other_result = await db.execute(
+ other_affected = await execute_rowcount(
+ db,
update(SysOAuthRefreshToken)
.where(
SysOAuthRefreshToken.family_id == family_id,
SysOAuthRefreshToken.token_id != offending_token_id,
SysOAuthRefreshToken.status.not_in(['revoked', 'expired', 'reuse_detected']),
)
- .values(status='revoked', revoked_at=current, revoke_reason=reason)
+ .values(status='revoked', revoked_at=current, revoke_reason=reason),
)
- offending_result = await db.execute(
+ offending_affected = await execute_rowcount(
+ db,
update(SysOAuthRefreshToken)
.where(SysOAuthRefreshToken.family_id == family_id, SysOAuthRefreshToken.token_id == offending_token_id)
- .values(status='reuse_detected', reuse_detected_at=current, revoked_at=current, revoke_reason=reason)
+ .values(status='reuse_detected', reuse_detected_at=current, revoked_at=current, revoke_reason=reason),
)
- return (other_result.rowcount or 0) + (offending_result.rowcount or 0)
+ return other_affected + offending_affected
@classmethod
async def revoke_family(cls, db: AsyncSession, family_id: str, reason: str | None = None) -> int:
@@ -204,16 +209,17 @@ async def revoke_family(cls, db: AsyncSession, family_id: str, reason: str | Non
:param reason: 撤销或标记原因
:return: 已撤销的 OAuth Refresh Token 数量
"""
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOAuthRefreshToken)
.where(
SysOAuthRefreshToken.family_id == family_id, SysOAuthRefreshToken.status.not_in(['revoked', 'expired'])
)
- .values(status='revoked', revoked_at=TimezoneUtil.utc_now(), revoke_reason=reason)
+ .values(status='revoked', revoked_at=TimezoneUtil.utc_now(), revoke_reason=reason),
)
await db.flush()
- return result.rowcount or 0
+ return affected
@classmethod
async def revoke_for_user(cls, db: AsyncSession, user_id: int, reason: str | None = None) -> int:
@@ -225,13 +231,14 @@ async def revoke_for_user(cls, db: AsyncSession, user_id: int, reason: str | Non
:param reason: 撤销或标记原因
:return: 已撤销的 OAuth Refresh Token 数量
"""
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOAuthRefreshToken)
.where(SysOAuthRefreshToken.user_id == user_id, SysOAuthRefreshToken.status.not_in(['revoked', 'expired']))
- .values(status='revoked', revoked_at=TimezoneUtil.utc_now(), revoke_reason=reason)
+ .values(status='revoked', revoked_at=TimezoneUtil.utc_now(), revoke_reason=reason),
)
- return result.rowcount or 0
+ return affected
@classmethod
async def revoke_for_users(
@@ -246,17 +253,18 @@ async def revoke_for_users(
:param now: 当前时间
:return: 已撤销的 OAuth Refresh Token 数量
"""
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOAuthRefreshToken)
.where(
SysOAuthRefreshToken.user_id.in_(user_ids),
SysOAuthRefreshToken.status.not_in(['revoked', 'expired', 'reuse_detected']),
)
- .values(status='revoked', revoked_at=now or TimezoneUtil.utc_now(), revoke_reason=reason)
+ .values(status='revoked', revoked_at=now or TimezoneUtil.utc_now(), revoke_reason=reason),
)
await db.flush()
- return result.rowcount or 0
+ return affected
@classmethod
async def expire_due(cls, db: AsyncSession) -> int:
@@ -266,14 +274,15 @@ async def expire_due(cls, db: AsyncSession) -> int:
:param db: orm对象
:return: 已过期的 OAuth Refresh Token 数量
"""
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOAuthRefreshToken)
.where(
SysOAuthRefreshToken.status == 'active',
(SysOAuthRefreshToken.idle_expires_at <= TimezoneUtil.utc_now())
| (SysOAuthRefreshToken.absolute_expires_at <= TimezoneUtil.utc_now()),
)
- .values(status='expired')
+ .values(status='expired'),
)
- return result.rowcount or 0
+ return affected
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oidc_key_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oidc_key_dao.py
index 1bf622003..69e7f8eab 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oidc_key_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oidc_key_dao.py
@@ -4,6 +4,7 @@
from sqlalchemy import delete, func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
+from config.database import execute_rowcount
from module_identity.entity.do.oidc_key_do import SysOidcSigningKey
from utils.time_util import TimezoneUtil
@@ -183,13 +184,14 @@ async def set_retiring(
:param now: 当前时间
:return: 是否更新成功
"""
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOidcSigningKey)
.where(SysOidcSigningKey.kid == kid, SysOidcSigningKey.status.in_(['active', 'retiring']))
- .values(status='retiring', signing_stop_at=now, remove_from_jwks_at=remove_from_jwks_at)
+ .values(status='retiring', signing_stop_at=now, remove_from_jwks_at=remove_from_jwks_at),
)
- return bool(result.rowcount)
+ return bool(affected)
@classmethod
async def delete_retired(cls, db: AsyncSession, kid: str) -> bool:
@@ -200,9 +202,9 @@ async def delete_retired(cls, db: AsyncSession, kid: str) -> bool:
:param kid: Signing Key 标识
:return: 是否删除成功
"""
- result = await db.execute(delete(SysOidcSigningKey).where(SysOidcSigningKey.kid == kid))
+ affected = await execute_rowcount(db, delete(SysOidcSigningKey).where(SysOidcSigningKey.kid == kid))
- return bool(result.rowcount)
+ return bool(affected)
@classmethod
async def lock_algorithm_for_update(cls, db: AsyncSession, alg: str = 'RS256') -> Sequence[SysOidcSigningKey]:
@@ -248,17 +250,18 @@ async def activate(cls, db: AsyncSession, kid: str, alg: str = 'RS256', now: dat
.where(SysOidcSigningKey.alg == alg, SysOidcSigningKey.status == 'active')
.values(status='retiring', signing_stop_at=current)
)
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOidcSigningKey)
.where(
SysOidcSigningKey.kid == kid,
SysOidcSigningKey.alg == alg,
SysOidcSigningKey.status == 'pending',
)
- .values(status='active', signing_start_at=current)
+ .values(status='active', signing_start_at=current),
)
- return bool(result.rowcount)
+ return bool(affected)
@classmethod
async def mark_compromised(cls, db: AsyncSession, kid: str) -> bool:
@@ -269,13 +272,14 @@ async def mark_compromised(cls, db: AsyncSession, kid: str) -> bool:
:param kid: Signing Key 标识
:return: 是否标记成功
"""
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOidcSigningKey)
.where(SysOidcSigningKey.kid == kid, SysOidcSigningKey.status != 'retired')
- .values(status='compromised', signing_stop_at=TimezoneUtil.utc_now())
+ .values(status='compromised', signing_stop_at=TimezoneUtil.utc_now()),
)
- return bool(result.rowcount)
+ return bool(affected)
@classmethod
async def retire_due(cls, db: AsyncSession) -> int:
@@ -285,14 +289,15 @@ async def retire_due(cls, db: AsyncSession) -> int:
:param db: orm对象
:return: 已退役的 OIDC Signing Key 数量
"""
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysOidcSigningKey)
.where(
SysOidcSigningKey.status == 'retiring',
SysOidcSigningKey.remove_from_jwks_at.is_not(None),
SysOidcSigningKey.remove_from_jwks_at <= TimezoneUtil.utc_now(),
)
- .values(status='retired')
+ .values(status='retired'),
)
- return result.rowcount or 0
+ return affected
diff --git a/ruoyi-fastapi-backend/module_identity/dao/sso_session_dao.py b/ruoyi-fastapi-backend/module_identity/dao/sso_session_dao.py
index 4af4f69b7..c07eebb9c 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/sso_session_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/sso_session_dao.py
@@ -4,6 +4,7 @@
from sqlalchemy import case, func, select, union, update
from sqlalchemy.ext.asyncio import AsyncSession
+from config.database import execute_rowcount
from module_identity.entity.do.oauth_client_do import SysOAuthClient
from module_identity.entity.do.oauth_grant_do import SysOAuthRefreshToken, SysSsoSession, SysSsoSessionClient
from utils.time_util import TimezoneUtil
@@ -108,7 +109,8 @@ async def touch(cls, db: AsyncSession, sid: str, idle_expires_at: datetime, now:
:return: 是否更新成功
"""
current = now or TimezoneUtil.utc_now()
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysSsoSession)
.where(
SysSsoSession.sid == sid,
@@ -117,11 +119,11 @@ async def touch(cls, db: AsyncSession, sid: str, idle_expires_at: datetime, now:
SysSsoSession.absolute_expires_at > current,
idle_expires_at <= SysSsoSession.absolute_expires_at,
)
- .values(last_seen_at=current, idle_expires_at=idle_expires_at)
+ .values(last_seen_at=current, idle_expires_at=idle_expires_at),
)
await db.flush()
- return bool(result.rowcount)
+ return bool(affected)
@classmethod
async def revoke(cls, db: AsyncSession, sid: str, reason: str | None = None, now: datetime | None = None) -> bool:
@@ -134,14 +136,15 @@ async def revoke(cls, db: AsyncSession, sid: str, reason: str | None = None, now
:param now: 当前时间
:return: 是否撤销成功
"""
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysSsoSession)
.where(SysSsoSession.sid == sid, SysSsoSession.status.in_(('active', 'expired')))
- .values(status='revoked', revoked_at=now or TimezoneUtil.utc_now(), revoke_reason=reason)
+ .values(status='revoked', revoked_at=now or TimezoneUtil.utc_now(), revoke_reason=reason),
)
await db.flush()
- return bool(result.rowcount)
+ return bool(affected)
@classmethod
async def revoke_for_user(
@@ -156,14 +159,15 @@ async def revoke_for_user(
:param now: 当前时间
:return: 已撤销的 SSO Session 数量
"""
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysSsoSession)
.where(SysSsoSession.user_id == user_id, SysSsoSession.status.in_(('active', 'expired')))
- .values(status='revoked', revoked_at=now or TimezoneUtil.utc_now(), revoke_reason=reason)
+ .values(status='revoked', revoked_at=now or TimezoneUtil.utc_now(), revoke_reason=reason),
)
await db.flush()
- return result.rowcount or 0
+ return affected
@classmethod
async def revoke_for_users(
@@ -187,14 +191,15 @@ async def revoke_for_users(
conditions = [SysSsoSession.user_id.in_(user_ids), SysSsoSession.status.in_(('active', 'expired'))]
if exclude_sid is not None:
conditions.append(SysSsoSession.sid != exclude_sid)
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysSsoSession)
.where(*conditions)
- .values(status='revoked', revoked_at=now or TimezoneUtil.utc_now(), revoke_reason=reason)
+ .values(status='revoked', revoked_at=now or TimezoneUtil.utc_now(), revoke_reason=reason),
)
await db.flush()
- return result.rowcount or 0
+ return affected
@classmethod
async def expire_due(cls, db: AsyncSession, now: datetime | None = None) -> int:
@@ -206,17 +211,18 @@ async def expire_due(cls, db: AsyncSession, now: datetime | None = None) -> int:
:return: 已过期的 SSO Session 数量
"""
now = now or TimezoneUtil.utc_now()
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysSsoSession)
.where(
SysSsoSession.status == 'active',
(SysSsoSession.idle_expires_at <= now) | (SysSsoSession.absolute_expires_at <= now),
)
- .values(status='expired')
+ .values(status='expired'),
)
await db.flush()
- return result.rowcount or 0
+ return affected
@classmethod
async def list_due(
@@ -252,18 +258,19 @@ async def expire(cls, db: AsyncSession, sid: str, now: datetime | None = None) -
:return: 是否过期成功
"""
current = now or TimezoneUtil.utc_now()
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysSsoSession)
.where(
SysSsoSession.sid == sid,
SysSsoSession.status == 'active',
(SysSsoSession.idle_expires_at <= current) | (SysSsoSession.absolute_expires_at <= current),
)
- .values(status='expired')
+ .values(status='expired'),
)
await db.flush()
- return bool(result.rowcount)
+ return bool(affected)
@classmethod
async def rotate_secret(
@@ -285,7 +292,8 @@ async def rotate_secret(
:return: 是否轮换成功
"""
current = now or TimezoneUtil.utc_now()
- result = await db.execute(
+ affected = await execute_rowcount(
+ db,
update(SysSsoSession)
.where(
SysSsoSession.sid == sid,
@@ -294,11 +302,11 @@ async def rotate_secret(
SysSsoSession.idle_expires_at > current,
SysSsoSession.absolute_expires_at > current,
)
- .values(session_secret_hash=new_secret_hash, last_seen_at=current)
+ .values(session_secret_hash=new_secret_hash, last_seen_at=current),
)
await db.flush()
- return bool(result.rowcount)
+ return bool(affected)
@classmethod
async def list_for_user(
diff --git a/ruoyi-fastapi-backend/module_identity/dependencies.py b/ruoyi-fastapi-backend/module_identity/dependencies.py
index 22c09b1cb..346539a9a 100644
--- a/ruoyi-fastapi-backend/module_identity/dependencies.py
+++ b/ruoyi-fastapi-backend/module_identity/dependencies.py
@@ -2,12 +2,13 @@
import re
from dataclasses import dataclass
from datetime import datetime
-from typing import Any
+from typing import Annotated, Any, cast
from urllib.parse import parse_qsl
import jwt
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
-from fastapi import Depends, HTTPException, Request, params
+from fastapi import HTTPException, Request, params
+from jwt.algorithms import RSAAlgorithm
from jwt.exceptions import PyJWTError
from redis.asyncio import Redis
from redis.exceptions import RedisError
@@ -17,6 +18,7 @@
from config.env import OidcConfig
from exceptions.exception import OAuthProtocolException, OidcInteractionException
from module_identity.dao.oidc_key_dao import OidcKeyDao
+from module_identity.entity.types import InteractionRecord
from module_identity.security.client_auth import ClientAuthenticationError
from module_identity.security.jwt_profile import JwtProfileError, decode_access_token
from module_identity.security.principal import OAuthClientPrincipal
@@ -75,7 +77,10 @@ async def load_access_verification_key(
if record is None or not isinstance(record.public_jwk, dict):
raise JwtProfileError('未知的签名密钥标识 kid')
try:
- return jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(record.public_jwk, separators=(',', ':')))
+ key = RSAAlgorithm.from_jwk(json.dumps(record.public_jwk, separators=(',', ':')))
+ if not isinstance(key, RSAPublicKey):
+ raise JwtProfileError('签名公钥无效')
+ return key
except (TypeError, ValueError, KeyError) as exc:
raise JwtProfileError('签名公钥无效') from exc
@@ -96,7 +101,7 @@ def _disabled() -> None:
async def require_oidc_protocol_ready(
request: Request,
- query_db: AsyncSession = DBSessionDependency(),
+ query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> None:
"""
在 OIDC 已启用但签名能力尚未就绪时阻断公共协议端点。
@@ -130,7 +135,7 @@ def _redis(request: Request) -> Redis:
value = getattr(request.app.state, 'redis', None)
if value is None:
raise HTTPException(status_code=503, detail='认证服务暂不可用')
- return value
+ return cast('Redis', value)
async def read_form(request: Request) -> dict[str, str]:
@@ -187,7 +192,7 @@ async def read_form(request: Request) -> dict[str, str]:
async def get_oidc_client(
request: Request,
- query_db: AsyncSession = DBSessionDependency(),
+ query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> OAuthClientPrincipal:
"""
验证 Basic 或 Public Client 表单认证。
@@ -257,7 +262,7 @@ async def _load_access_context(request: Request, query_db: AsyncSession) -> Acce
async def get_oidc_access_token(
request: Request,
- query_db: AsyncSession = DBSessionDependency(),
+ query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> AccessTokenContext:
"""
验证 UserInfo 使用的 Bearer Access Token。
@@ -272,7 +277,7 @@ async def get_oidc_access_token(
async def get_interaction_csrf(
request: Request,
interaction_id: str,
-) -> dict[str, Any]:
+) -> InteractionRecord:
"""
验证 Interaction CSRF Header,并返回内部状态记录。
@@ -312,7 +317,7 @@ def OidcClientDependency() -> params.Depends: # noqa: N802
:return: Client Authentication 依赖
"""
- return Depends(get_oidc_client)
+ return params.Depends(get_oidc_client)
def OidcAccessTokenDependency() -> params.Depends: # noqa: N802
@@ -321,7 +326,7 @@ def OidcAccessTokenDependency() -> params.Depends: # noqa: N802
:return: 严格 Access Token 依赖
"""
- return Depends(get_oidc_access_token)
+ return params.Depends(get_oidc_access_token)
def InteractionCsrfDependency() -> params.Depends: # noqa: N802
@@ -330,4 +335,4 @@ def InteractionCsrfDependency() -> params.Depends: # noqa: N802
:return: Interaction CSRF 依赖
"""
- return Depends(get_interaction_csrf)
+ return params.Depends(get_interaction_csrf)
diff --git a/ruoyi-fastapi-backend/module_identity/entity/do/identity_subject_do.py b/ruoyi-fastapi-backend/module_identity/entity/do/identity_subject_do.py
index 493d923cd..3f7696cdc 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/do/identity_subject_do.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/do/identity_subject_do.py
@@ -1,4 +1,7 @@
-from sqlalchemy import BigInteger, Column, ForeignKey, Index, Integer, String, UniqueConstraint
+from datetime import datetime
+
+from sqlalchemy import BigInteger, ForeignKey, Index, Integer, String, UniqueConstraint
+from sqlalchemy.orm import Mapped, mapped_column
from common.types import DbUtcDateTime
from config.database import Base
@@ -16,22 +19,26 @@ class SysIdentitySubject(Base):
{'comment': '统一认证主体关联表'},
)
- identity_id = Column(
+ identity_id: Mapped[int] = mapped_column(
BigInteger().with_variant(Integer, 'sqlite'),
primary_key=True,
nullable=False,
autoincrement=True,
comment='内部主键',
)
- user_id = Column(
+ user_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_user.user_id', name='fk_identity_subject_user', ondelete='RESTRICT'),
nullable=False,
comment='本地用户ID',
)
- subject_id = Column(String(36), nullable=False, comment='OIDC 主体标识')
- auth_version = Column(BigInteger, nullable=False, server_default='1', comment='认证安全版本')
- create_by = Column(String(64), nullable=True, comment='创建者')
- create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间')
- update_by = Column(String(64), nullable=True, comment='更新者')
- update_time = Column(DbUtcDateTime(), nullable=True, onupdate=TimezoneUtil.utc_now, comment='更新时间')
+ subject_id: Mapped[str] = mapped_column(String(36), nullable=False, comment='OIDC 主体标识')
+ auth_version: Mapped[int] = mapped_column(BigInteger, nullable=False, server_default='1', comment='认证安全版本')
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='创建者')
+ create_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间'
+ )
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='更新者')
+ update_time: Mapped[datetime | None] = mapped_column(
+ DbUtcDateTime(), nullable=True, onupdate=TimezoneUtil.utc_now, comment='更新时间'
+ )
diff --git a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_audit_do.py b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_audit_do.py
index 8e0dd578a..024fc56d6 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_audit_do.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_audit_do.py
@@ -1,7 +1,11 @@
-from sqlalchemy import JSON, BigInteger, Column, Index, Integer, String
+from datetime import datetime
+
+from sqlalchemy import JSON, BigInteger, Index, Integer, String
+from sqlalchemy.orm import Mapped, mapped_column
from common.types import DbUtcDateTime
from config.database import Base
+from module_identity.entity.types import AuditResult, AuditRiskLevel
from utils.time_util import TimezoneUtil
@@ -18,29 +22,33 @@ class SysOAuthAuditLog(Base):
{'comment': 'OAuth Audit Log'},
)
- event_id = Column(
+ event_id: Mapped[int] = mapped_column(
BigInteger().with_variant(Integer, 'sqlite'),
primary_key=True,
nullable=False,
autoincrement=True,
comment='事件ID',
)
- trace_id = Column(String(64), nullable=True, comment='链路追踪ID')
- event_type = Column(String(64), nullable=False, comment='事件类型')
- result = Column(String(16), nullable=False, comment='结果')
- risk_level = Column(String(16), nullable=False, server_default='normal', comment='风险等级')
- client_id = Column(String(64), nullable=True, comment='Client ID 快照')
- resource_id = Column(String(64), nullable=True, comment='Resource ID 快照')
- user_id = Column(BigInteger, nullable=True, comment='用户ID快照')
- subject_id = Column(String(36), nullable=True, comment='Subject 快照')
- sid = Column(String(36), nullable=True, comment='单点登录会话标识')
- grant_id = Column(String(36), nullable=True, comment='授权记录标识')
- token_id = Column(String(36), nullable=True, comment='令牌标识')
- ip_address = Column(String(128), nullable=True, comment='客户端 IP')
- user_agent = Column(String(500), nullable=True, comment='脱敏 User-Agent')
- failure_code = Column(String(64), nullable=True, comment='失败码')
- detail = Column(JSON, nullable=True, comment='脱敏扩展详情')
- create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='事件时间')
+ trace_id: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='链路追踪ID')
+ event_type: Mapped[str] = mapped_column(String(64), nullable=False, comment='事件类型')
+ result: Mapped[AuditResult] = mapped_column(String(16), nullable=False, comment='结果')
+ risk_level: Mapped[AuditRiskLevel] = mapped_column(
+ String(16), nullable=False, server_default='normal', comment='风险等级'
+ )
+ client_id: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='Client ID 快照')
+ resource_id: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='Resource ID 快照')
+ user_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='用户ID快照')
+ subject_id: Mapped[str | None] = mapped_column(String(36), nullable=True, comment='Subject 快照')
+ sid: Mapped[str | None] = mapped_column(String(36), nullable=True, comment='单点登录会话标识')
+ grant_id: Mapped[str | None] = mapped_column(String(36), nullable=True, comment='授权记录标识')
+ token_id: Mapped[str | None] = mapped_column(String(36), nullable=True, comment='令牌标识')
+ ip_address: Mapped[str | None] = mapped_column(String(128), nullable=True, comment='客户端 IP')
+ user_agent: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='脱敏 User-Agent')
+ failure_code: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='失败码')
+ detail: Mapped[dict[str, object] | None] = mapped_column(JSON, nullable=True, comment='脱敏扩展详情')
+ create_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='事件时间'
+ )
class SysOAuthAuditArchive(Base):
@@ -53,21 +61,25 @@ class SysOAuthAuditArchive(Base):
{'comment': 'OAuth Audit Archive'},
)
- event_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=False, comment='原事件ID')
- trace_id = Column(String(64), nullable=True, comment='链路追踪ID')
- event_type = Column(String(64), nullable=False, comment='事件类型')
- result = Column(String(16), nullable=False, comment='结果')
- risk_level = Column(String(16), nullable=False, comment='风险等级')
- client_id = Column(String(64), nullable=True, comment='Client ID 快照')
- resource_id = Column(String(64), nullable=True, comment='Resource ID 快照')
- user_id = Column(BigInteger, nullable=True, comment='用户ID快照')
- subject_id = Column(String(36), nullable=True, comment='Subject 快照')
- sid = Column(String(36), nullable=True, comment='单点登录会话标识')
- grant_id = Column(String(36), nullable=True, comment='授权记录标识')
- token_id = Column(String(36), nullable=True, comment='令牌标识')
- ip_address = Column(String(128), nullable=True, comment='客户端 IP')
- user_agent = Column(String(500), nullable=True, comment='脱敏 User-Agent')
- failure_code = Column(String(64), nullable=True, comment='失败码')
- detail = Column(JSON, nullable=True, comment='脱敏扩展详情')
- create_time = Column(DbUtcDateTime(), nullable=False, comment='事件时间')
- archived_at = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='归档时间')
+ event_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=False, comment='原事件ID'
+ )
+ trace_id: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='链路追踪ID')
+ event_type: Mapped[str] = mapped_column(String(64), nullable=False, comment='事件类型')
+ result: Mapped[AuditResult] = mapped_column(String(16), nullable=False, comment='结果')
+ risk_level: Mapped[AuditRiskLevel] = mapped_column(String(16), nullable=False, comment='风险等级')
+ client_id: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='Client ID 快照')
+ resource_id: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='Resource ID 快照')
+ user_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='用户ID快照')
+ subject_id: Mapped[str | None] = mapped_column(String(36), nullable=True, comment='Subject 快照')
+ sid: Mapped[str | None] = mapped_column(String(36), nullable=True, comment='单点登录会话标识')
+ grant_id: Mapped[str | None] = mapped_column(String(36), nullable=True, comment='授权记录标识')
+ token_id: Mapped[str | None] = mapped_column(String(36), nullable=True, comment='令牌标识')
+ ip_address: Mapped[str | None] = mapped_column(String(128), nullable=True, comment='客户端 IP')
+ user_agent: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='脱敏 User-Agent')
+ failure_code: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='失败码')
+ detail: Mapped[dict[str, object] | None] = mapped_column(JSON, nullable=True, comment='脱敏扩展详情')
+ create_time: Mapped[datetime] = mapped_column(DbUtcDateTime(), nullable=False, comment='事件时间')
+ archived_at: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='归档时间'
+ )
diff --git a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_client_do.py b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_client_do.py
index 9bf8fc500..12dfcfa27 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_client_do.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_client_do.py
@@ -1,8 +1,9 @@
+from datetime import datetime
+
from sqlalchemy import (
CHAR,
JSON,
BigInteger,
- Column,
ForeignKey,
Index,
Integer,
@@ -10,7 +11,7 @@
String,
UniqueConstraint,
)
-from sqlalchemy.orm import validates
+from sqlalchemy.orm import Mapped, mapped_column, validates
from common.types import DbUtcDateTime
from config.database import Base
@@ -28,42 +29,56 @@ class SysOAuthClient(Base):
{'comment': 'OAuth Client'},
)
- client_pk = Column(
+ client_pk: Mapped[int] = mapped_column(
BigInteger().with_variant(Integer, 'sqlite'),
primary_key=True,
nullable=False,
autoincrement=True,
comment='内部主键',
)
- client_id = Column(String(64), nullable=False, comment='客户端标识')
- client_name = Column(String(100), nullable=False, comment='客户端名称')
- client_type = Column(String(20), nullable=False, comment='Client 类型')
- token_endpoint_auth_method = Column(String(32), nullable=False, comment='Token 端点认证方式')
- grant_types = Column(JSON, nullable=False, comment='Grant Type 列表')
- response_types = Column(JSON, nullable=False, comment='Response Type 列表')
- subject_type = Column(String(16), nullable=False, server_default='public', comment='Subject 类型')
- require_pkce = Column(SmallInteger, nullable=False, server_default='1', comment='是否要求 PKCE')
- require_consent = Column(SmallInteger, nullable=False, server_default='1', comment='是否要求同意')
- trusted_client = Column(SmallInteger, nullable=False, server_default='0', comment='是否受信任 Client')
- policy_version = Column(BigInteger, nullable=False, server_default='1', comment='安全策略版本')
- id_token_signed_response_alg = Column(String(16), nullable=False, server_default='RS256', comment='ID Token 算法')
- access_token_ttl_seconds = Column(Integer, nullable=True, comment='Access Token 有效期')
- refresh_token_idle_seconds = Column(Integer, nullable=True, comment='Refresh Token 闲置有效期')
- refresh_token_absolute_seconds = Column(Integer, nullable=True, comment='Refresh Token 绝对有效期')
- logo_uri = Column(String(500), nullable=True, comment='标志图片地址')
- policy_uri = Column(String(500), nullable=True, comment='隐私政策 URI')
- tos_uri = Column(String(500), nullable=True, comment='服务条款 URI')
- backchannel_logout_session_required = Column(
+ client_id: Mapped[str] = mapped_column(String(64), nullable=False, comment='客户端标识')
+ client_name: Mapped[str] = mapped_column(String(100), nullable=False, comment='客户端名称')
+ client_type: Mapped[str] = mapped_column(String(20), nullable=False, comment='Client 类型')
+ token_endpoint_auth_method: Mapped[str] = mapped_column(String(32), nullable=False, comment='Token 端点认证方式')
+ grant_types: Mapped[list[str]] = mapped_column(JSON, nullable=False, comment='Grant Type 列表')
+ response_types: Mapped[list[str]] = mapped_column(JSON, nullable=False, comment='Response Type 列表')
+ subject_type: Mapped[str] = mapped_column(
+ String(16), nullable=False, server_default='public', comment='Subject 类型'
+ )
+ require_pkce: Mapped[int] = mapped_column(SmallInteger, nullable=False, server_default='1', comment='是否要求 PKCE')
+ require_consent: Mapped[int] = mapped_column(
+ SmallInteger, nullable=False, server_default='1', comment='是否要求同意'
+ )
+ trusted_client: Mapped[int] = mapped_column(
+ SmallInteger, nullable=False, server_default='0', comment='是否受信任 Client'
+ )
+ policy_version: Mapped[int] = mapped_column(BigInteger, nullable=False, server_default='1', comment='安全策略版本')
+ id_token_signed_response_alg: Mapped[str] = mapped_column(
+ String(16), nullable=False, server_default='RS256', comment='ID Token 算法'
+ )
+ access_token_ttl_seconds: Mapped[int | None] = mapped_column(Integer, nullable=True, comment='Access Token 有效期')
+ refresh_token_idle_seconds: Mapped[int | None] = mapped_column(
+ Integer, nullable=True, comment='Refresh Token 闲置有效期'
+ )
+ refresh_token_absolute_seconds: Mapped[int | None] = mapped_column(
+ Integer, nullable=True, comment='Refresh Token 绝对有效期'
+ )
+ logo_uri: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='标志图片地址')
+ policy_uri: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='隐私政策 URI')
+ tos_uri: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='服务条款 URI')
+ backchannel_logout_session_required: Mapped[int] = mapped_column(
SmallInteger, nullable=False, server_default='1', comment='是否要求 Back-Channel Session'
)
- status = Column(CHAR(1), nullable=False, server_default='0', comment='状态(0正常 1停用)')
- create_by = Column(String(64), nullable=False, server_default='', comment='创建者')
- create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间')
- update_by = Column(String(64), nullable=False, server_default='', default='', comment='更新者')
- update_time = Column(
+ status: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='0', comment='状态(0正常 1停用)')
+ create_by: Mapped[str] = mapped_column(String(64), nullable=False, server_default='', comment='创建者')
+ create_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间'
+ )
+ update_by: Mapped[str] = mapped_column(String(64), nullable=False, server_default='', default='', comment='更新者')
+ update_time: Mapped[datetime] = mapped_column(
DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, onupdate=TimezoneUtil.utc_now, comment='更新时间'
)
- remark = Column(String(500), nullable=True, comment='备注')
+ remark: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='备注')
class SysOAuthClientSecret(Base):
@@ -75,23 +90,27 @@ class SysOAuthClientSecret(Base):
{'comment': 'OAuth Client Secret'},
)
- secret_id = Column(String(36), primary_key=True, nullable=False, comment='密钥标识')
- client_pk = Column(
+ secret_id: Mapped[str] = mapped_column(String(36), primary_key=True, nullable=False, comment='密钥标识')
+ client_pk: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_oauth_client.client_pk', name='fk_oauth_client_secret_client', ondelete='RESTRICT'),
nullable=False,
comment='Client 主键',
)
- secret_hash = Column(String(100), nullable=False, comment='Secret 强哈希')
- secret_hint = Column(String(12), nullable=False, comment='Secret 提示')
- status = Column(String(16), nullable=False, server_default='active', comment='Secret 状态')
- not_before = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='生效时间')
- expires_at = Column(DbUtcDateTime(), nullable=True, comment='过期时间')
- last_used_at = Column(DbUtcDateTime(), nullable=True, comment='最近使用时间')
- create_by = Column(String(64), nullable=False, comment='创建者')
- create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间')
- revoked_by = Column(String(64), nullable=True, comment='撤销者')
- revoked_at = Column(DbUtcDateTime(), nullable=True, comment='撤销时间')
+ secret_hash: Mapped[str] = mapped_column(String(100), nullable=False, comment='Secret 强哈希')
+ secret_hint: Mapped[str] = mapped_column(String(12), nullable=False, comment='Secret 提示')
+ status: Mapped[str] = mapped_column(String(16), nullable=False, server_default='active', comment='Secret 状态')
+ not_before: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='生效时间'
+ )
+ expires_at: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='过期时间')
+ last_used_at: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='最近使用时间')
+ create_by: Mapped[str] = mapped_column(String(64), nullable=False, comment='创建者')
+ create_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间'
+ )
+ revoked_by: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='撤销者')
+ revoked_at: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='撤销时间')
class SysOAuthClientUri(Base):
@@ -104,25 +123,27 @@ class SysOAuthClientUri(Base):
{'comment': 'OAuth Client URI'},
)
- uri_id = Column(
+ uri_id: Mapped[int] = mapped_column(
BigInteger().with_variant(Integer, 'sqlite'),
primary_key=True,
nullable=False,
autoincrement=True,
comment='URI 主键',
)
- client_pk = Column(
+ client_pk: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_oauth_client.client_pk', name='fk_oauth_client_uri_client', ondelete='RESTRICT'),
nullable=False,
comment='Client 主键',
)
- uri_type = Column(String(32), nullable=False, comment='URI 类型')
- uri = Column(String(1000), nullable=False, comment='精确 URI')
- uri_hash = Column(CHAR(64), nullable=False, comment='URI SHA-256 摘要')
- is_default = Column(SmallInteger, nullable=False, server_default='0', comment='是否默认 URI')
- status = Column(CHAR(1), nullable=False, server_default='0', comment='状态(0正常 1停用)')
- create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间')
+ uri_type: Mapped[str] = mapped_column(String(32), nullable=False, comment='URI 类型')
+ uri: Mapped[str] = mapped_column(String(1000), nullable=False, comment='精确 URI')
+ uri_hash: Mapped[str] = mapped_column(CHAR(64), nullable=False, comment='URI SHA-256 摘要')
+ is_default: Mapped[int] = mapped_column(SmallInteger, nullable=False, server_default='0', comment='是否默认 URI')
+ status: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='0', comment='状态(0正常 1停用)')
+ create_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间'
+ )
@validates('uri')
def derive_uri_hash(self, key: str, value: str) -> str:
diff --git a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_grant_do.py b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_grant_do.py
index c573dd7fc..aee6a50d9 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_grant_do.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_grant_do.py
@@ -1,7 +1,11 @@
-from sqlalchemy import CHAR, JSON, BigInteger, Column, ForeignKey, Index, SmallInteger, String, UniqueConstraint
+from datetime import datetime
+
+from sqlalchemy import CHAR, JSON, BigInteger, ForeignKey, Index, SmallInteger, String, UniqueConstraint
+from sqlalchemy.orm import Mapped, mapped_column
from common.types import DbUtcDateTime
from config.database import Base
+from module_identity.entity.types import AccessStatus, AuthorizationStatus
from utils.time_util import TimezoneUtil
@@ -11,24 +15,28 @@ class SysOAuthAccessPolicy(Base):
__tablename__ = 'sys_oauth_access_policy'
__table_args__ = ({'comment': 'OAuth 用户应用访问控制'},)
- user_id = Column(
+ user_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_user.user_id', name='fk_oauth_access_user', ondelete='RESTRICT'),
primary_key=True,
nullable=False,
comment='用户ID',
)
- client_pk = Column(
+ client_pk: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_oauth_client.client_pk', name='fk_oauth_access_client', ondelete='RESTRICT'),
primary_key=True,
nullable=False,
comment='Client 主键',
)
- access_status = Column(String(16), nullable=False, server_default='allowed', comment='allowed允许 blocked禁止')
- reason = Column(String(200), nullable=True, comment='访问控制原因')
- update_by = Column(String(64), nullable=False, comment='操作人')
- update_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='操作时间')
+ access_status: Mapped[AccessStatus] = mapped_column(
+ String(16), nullable=False, server_default='allowed', comment='allowed允许 blocked禁止'
+ )
+ reason: Mapped[str | None] = mapped_column(String(200), nullable=True, comment='访问控制原因')
+ update_by: Mapped[str] = mapped_column(String(64), nullable=False, comment='操作人')
+ update_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='操作时间'
+ )
class SysOAuthGrant(Base):
@@ -42,31 +50,37 @@ class SysOAuthGrant(Base):
{'comment': 'OAuth Grant'},
)
- grant_id = Column(String(36), primary_key=True, nullable=False, comment='授权记录标识')
- user_id = Column(
+ grant_id: Mapped[str] = mapped_column(String(36), primary_key=True, nullable=False, comment='授权记录标识')
+ user_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_user.user_id', name='fk_oauth_grant_user', ondelete='RESTRICT'),
nullable=False,
comment='用户ID',
)
- subject_id = Column(String(36), nullable=False, comment='Subject 快照')
- client_pk = Column(
+ subject_id: Mapped[str] = mapped_column(String(36), nullable=False, comment='Subject 快照')
+ client_pk: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_oauth_client.client_pk', name='fk_oauth_grant_client', ondelete='RESTRICT'),
nullable=False,
comment='Client 主键',
)
- granted_scopes = Column(JSON, nullable=False, comment='已同意 Scope')
- granted_resources = Column(JSON, nullable=False, comment='已同意 Resource audience')
- remembered_scopes = Column(JSON, nullable=True, comment='后续可免确认的 Scope')
- remembered_resources = Column(JSON, nullable=True, comment='后续可免确认的 Resource audience')
- client_policy_version = Column(BigInteger, nullable=False, comment='客户端策略版本')
- status = Column(String(16), nullable=False, server_default='active', comment='Grant 状态')
- consented_at = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='同意时间')
- expires_at = Column(DbUtcDateTime(), nullable=True, comment='过期时间')
- revoked_at = Column(DbUtcDateTime(), nullable=True, comment='撤销时间')
- revoke_reason = Column(String(200), nullable=True, comment='撤销原因')
- last_used_at = Column(DbUtcDateTime(), nullable=True, comment='最近使用时间')
+ granted_scopes: Mapped[list[str]] = mapped_column(JSON, nullable=False, comment='已同意 Scope')
+ granted_resources: Mapped[list[str]] = mapped_column(JSON, nullable=False, comment='已同意 Resource audience')
+ remembered_scopes: Mapped[list[str] | None] = mapped_column(JSON, nullable=True, comment='后续可免确认的 Scope')
+ remembered_resources: Mapped[list[str] | None] = mapped_column(
+ JSON, nullable=True, comment='后续可免确认的 Resource audience'
+ )
+ client_policy_version: Mapped[int] = mapped_column(BigInteger, nullable=False, comment='客户端策略版本')
+ status: Mapped[AuthorizationStatus] = mapped_column(
+ String(16), nullable=False, server_default='active', comment='Grant 状态'
+ )
+ consented_at: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='同意时间'
+ )
+ expires_at: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='过期时间')
+ revoked_at: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='撤销时间')
+ revoke_reason: Mapped[str | None] = mapped_column(String(200), nullable=True, comment='撤销原因')
+ last_used_at: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='最近使用时间')
class SysSsoSession(Base):
@@ -80,29 +94,37 @@ class SysSsoSession(Base):
{'comment': 'OIDC SSO Session'},
)
- sid = Column(String(36), primary_key=True, nullable=False, comment='OIDC 会话标识')
- session_secret_hash = Column(CHAR(64), nullable=False, comment='SSO Cookie 摘要')
- user_id = Column(
+ sid: Mapped[str] = mapped_column(String(36), primary_key=True, nullable=False, comment='OIDC 会话标识')
+ session_secret_hash: Mapped[str] = mapped_column(CHAR(64), nullable=False, comment='SSO Cookie 摘要')
+ user_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_user.user_id', name='fk_sso_session_user', ondelete='RESTRICT'),
nullable=False,
comment='用户ID',
)
- subject_id = Column(String(36), nullable=False, comment='Subject 快照')
- auth_version = Column(BigInteger, nullable=False, comment='认证安全版本')
- auth_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='认证时间')
- last_seen_at = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='最近活动时间')
- idle_expires_at = Column(DbUtcDateTime(), nullable=False, comment='闲置过期时间')
- absolute_expires_at = Column(DbUtcDateTime(), nullable=False, comment='绝对过期时间')
- acr = Column(String(100), nullable=False, comment='认证上下文')
- amr = Column(JSON, nullable=False, comment='认证方式')
- remember_me = Column(SmallInteger, nullable=False, server_default='0', comment='是否长期会话')
- ip_address = Column(String(128), nullable=True, comment='登录 IP')
- user_agent_hash = Column(CHAR(64), nullable=True, comment='User-Agent 摘要')
- status = Column(String(16), nullable=False, server_default='active', comment='Session 状态')
- revoked_at = Column(DbUtcDateTime(), nullable=True, comment='撤销时间')
- revoke_reason = Column(String(200), nullable=True, comment='撤销原因')
- create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间')
+ subject_id: Mapped[str] = mapped_column(String(36), nullable=False, comment='Subject 快照')
+ auth_version: Mapped[int] = mapped_column(BigInteger, nullable=False, comment='认证安全版本')
+ auth_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='认证时间'
+ )
+ last_seen_at: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='最近活动时间'
+ )
+ idle_expires_at: Mapped[datetime] = mapped_column(DbUtcDateTime(), nullable=False, comment='闲置过期时间')
+ absolute_expires_at: Mapped[datetime] = mapped_column(DbUtcDateTime(), nullable=False, comment='绝对过期时间')
+ acr: Mapped[str] = mapped_column(String(100), nullable=False, comment='认证上下文')
+ amr: Mapped[list[str]] = mapped_column(JSON, nullable=False, comment='认证方式')
+ remember_me: Mapped[int] = mapped_column(SmallInteger, nullable=False, server_default='0', comment='是否长期会话')
+ ip_address: Mapped[str | None] = mapped_column(String(128), nullable=True, comment='登录 IP')
+ user_agent_hash: Mapped[str | None] = mapped_column(CHAR(64), nullable=True, comment='User-Agent 摘要')
+ status: Mapped[AuthorizationStatus] = mapped_column(
+ String(16), nullable=False, server_default='active', comment='Session 状态'
+ )
+ revoked_at: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='撤销时间')
+ revoke_reason: Mapped[str | None] = mapped_column(String(200), nullable=True, comment='撤销原因')
+ create_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间'
+ )
class SysSsoSessionClient(Base):
@@ -111,22 +133,26 @@ class SysSsoSessionClient(Base):
__tablename__ = 'sys_sso_session_client'
__table_args__ = (Index('idx_sso_session_client_client', 'client_pk'), {'comment': 'SSO 会话参与应用'})
- sid = Column(
+ sid: Mapped[str] = mapped_column(
String(36),
ForeignKey('sys_sso_session.sid', name='fk_sso_session_client_sid', ondelete='RESTRICT'),
primary_key=True,
nullable=False,
comment='单点登录会话标识',
)
- client_pk = Column(
+ client_pk: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_oauth_client.client_pk', name='fk_sso_session_client_client', ondelete='RESTRICT'),
primary_key=True,
nullable=False,
comment='Client 主键',
)
- create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='首次授权时间')
- last_used_at = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='最近授权时间')
+ create_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='首次授权时间'
+ )
+ last_used_at: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='最近授权时间'
+ )
class SysOAuthRefreshToken(Base):
@@ -143,54 +169,56 @@ class SysOAuthRefreshToken(Base):
{'comment': 'OAuth Refresh Token'},
)
- token_id = Column(String(36), primary_key=True, nullable=False, comment='令牌标识')
- token_hash = Column(CHAR(64), nullable=False, comment='Token HMAC 摘要')
- family_id = Column(String(36), nullable=False, comment='令牌族标识')
- parent_token_id = Column(
+ token_id: Mapped[str] = mapped_column(String(36), primary_key=True, nullable=False, comment='令牌标识')
+ token_hash: Mapped[str] = mapped_column(CHAR(64), nullable=False, comment='Token HMAC 摘要')
+ family_id: Mapped[str] = mapped_column(String(36), nullable=False, comment='令牌族标识')
+ parent_token_id: Mapped[str | None] = mapped_column(
String(36),
ForeignKey('sys_oauth_refresh_token.token_id', name='fk_oauth_refresh_parent', ondelete='RESTRICT'),
nullable=True,
comment='父 Token ID',
)
- replaced_by_token_id = Column(
+ replaced_by_token_id: Mapped[str | None] = mapped_column(
String(36),
ForeignKey('sys_oauth_refresh_token.token_id', name='fk_oauth_refresh_replaced_by', ondelete='RESTRICT'),
nullable=True,
comment='替代 Token ID',
)
- grant_id = Column(
+ grant_id: Mapped[str] = mapped_column(
String(36),
ForeignKey('sys_oauth_grant.grant_id', name='fk_oauth_refresh_grant', ondelete='RESTRICT'),
nullable=False,
comment='授权记录标识',
)
- user_id = Column(
+ user_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_user.user_id', name='fk_oauth_refresh_user', ondelete='RESTRICT'),
nullable=False,
comment='用户ID',
)
- subject_id = Column(String(36), nullable=False, comment='Subject 快照')
- auth_version = Column(BigInteger, nullable=False, comment='认证安全版本')
- client_pk = Column(
+ subject_id: Mapped[str] = mapped_column(String(36), nullable=False, comment='Subject 快照')
+ auth_version: Mapped[int] = mapped_column(BigInteger, nullable=False, comment='认证安全版本')
+ client_pk: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_oauth_client.client_pk', name='fk_oauth_refresh_client', ondelete='RESTRICT'),
nullable=False,
comment='Client 主键',
)
- sid = Column(
+ sid: Mapped[str] = mapped_column(
String(36),
ForeignKey('sys_sso_session.sid', name='fk_oauth_refresh_sid', ondelete='RESTRICT'),
nullable=False,
comment='单点登录会话标识',
)
- scopes = Column(JSON, nullable=False, comment='绑定 Scope')
- resources = Column(JSON, nullable=False, comment='绑定 Resource audience')
- status = Column(String(24), nullable=False, server_default='active', comment='Token 状态')
- issued_at = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='签发时间')
- last_used_at = Column(DbUtcDateTime(), nullable=True, comment='最近使用时间')
- idle_expires_at = Column(DbUtcDateTime(), nullable=False, comment='闲置过期时间')
- absolute_expires_at = Column(DbUtcDateTime(), nullable=False, comment='绝对过期时间')
- revoked_at = Column(DbUtcDateTime(), nullable=True, comment='撤销时间')
- revoke_reason = Column(String(200), nullable=True, comment='撤销原因')
- reuse_detected_at = Column(DbUtcDateTime(), nullable=True, comment='重放检测时间')
+ scopes: Mapped[list[str]] = mapped_column(JSON, nullable=False, comment='绑定 Scope')
+ resources: Mapped[list[str]] = mapped_column(JSON, nullable=False, comment='绑定 Resource audience')
+ status: Mapped[str] = mapped_column(String(24), nullable=False, server_default='active', comment='Token 状态')
+ issued_at: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='签发时间'
+ )
+ last_used_at: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='最近使用时间')
+ idle_expires_at: Mapped[datetime] = mapped_column(DbUtcDateTime(), nullable=False, comment='闲置过期时间')
+ absolute_expires_at: Mapped[datetime] = mapped_column(DbUtcDateTime(), nullable=False, comment='绝对过期时间')
+ revoked_at: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='撤销时间')
+ revoke_reason: Mapped[str | None] = mapped_column(String(200), nullable=True, comment='撤销原因')
+ reuse_detected_at: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='重放检测时间')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_resource_do.py b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_resource_do.py
index d3b01e95b..c8a917106 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/do/oauth_resource_do.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/do/oauth_resource_do.py
@@ -1,8 +1,9 @@
+from datetime import datetime
+
from sqlalchemy import (
CHAR,
JSON,
BigInteger,
- Column,
ForeignKey,
Index,
Integer,
@@ -11,6 +12,7 @@
String,
UniqueConstraint,
)
+from sqlalchemy.orm import Mapped, mapped_column
from common.types import DbUtcDateTime
from config.database import Base
@@ -28,34 +30,36 @@ class SysOAuthResource(Base):
{'comment': 'OAuth Resource'},
)
- resource_pk = Column(
+ resource_pk: Mapped[int] = mapped_column(
BigInteger().with_variant(Integer, 'sqlite'),
primary_key=True,
nullable=False,
autoincrement=True,
comment='内部主键',
)
- resource_id = Column(String(64), nullable=False, comment='资源标识')
- resource_name = Column(String(100), nullable=False, comment='Resource 名称')
- audience = Column(String(500), nullable=False, comment='访问令牌受众')
- token_format = Column(String(16), nullable=False, server_default='jwt', comment='Token 格式')
- signing_alg = Column(String(16), nullable=False, server_default='RS256', comment='签名算法')
- access_token_ttl_seconds = Column(Integer, nullable=True, comment='Access Token 有效期')
- introspection_client_pk = Column(
+ resource_id: Mapped[str] = mapped_column(String(64), nullable=False, comment='资源标识')
+ resource_name: Mapped[str] = mapped_column(String(100), nullable=False, comment='Resource 名称')
+ audience: Mapped[str] = mapped_column(String(500), nullable=False, comment='访问令牌受众')
+ token_format: Mapped[str] = mapped_column(String(16), nullable=False, server_default='jwt', comment='Token 格式')
+ signing_alg: Mapped[str] = mapped_column(String(16), nullable=False, server_default='RS256', comment='签名算法')
+ access_token_ttl_seconds: Mapped[int | None] = mapped_column(Integer, nullable=True, comment='Access Token 有效期')
+ introspection_client_pk: Mapped[int | None] = mapped_column(
BigInteger,
ForeignKey('sys_oauth_client.client_pk', name='fk_oauth_resource_introspection_client', ondelete='RESTRICT'),
nullable=True,
comment='Introspection Client 主键',
)
- allowed_claims = Column(JSON, nullable=False, comment='允许的 Claims')
- status = Column(CHAR(1), nullable=False, server_default='0', comment='状态(0正常 1停用)')
- create_by = Column(String(64), nullable=False, comment='创建者')
- create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间')
- update_by = Column(String(64), nullable=False, comment='更新者')
- update_time = Column(
+ allowed_claims: Mapped[list[str]] = mapped_column(JSON, nullable=False, comment='允许的 Claims')
+ status: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='0', comment='状态(0正常 1停用)')
+ create_by: Mapped[str] = mapped_column(String(64), nullable=False, comment='创建者')
+ create_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间'
+ )
+ update_by: Mapped[str] = mapped_column(String(64), nullable=False, comment='更新者')
+ update_time: Mapped[datetime] = mapped_column(
DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, onupdate=TimezoneUtil.utc_now, comment='更新时间'
)
- remark = Column(String(500), nullable=True, comment='备注')
+ remark: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='备注')
class SysOAuthScope(Base):
@@ -69,33 +73,37 @@ class SysOAuthScope(Base):
{'comment': 'OAuth Scope'},
)
- scope_pk = Column(
+ scope_pk: Mapped[int] = mapped_column(
BigInteger().with_variant(Integer, 'sqlite'),
primary_key=True,
nullable=False,
autoincrement=True,
comment='内部主键',
)
- scope_code = Column(String(100), nullable=False, comment='Scope 编码')
- scope_name = Column(String(100), nullable=False, comment='Scope 名称')
- scope_type = Column(String(16), nullable=False, comment='Scope 类型')
- resource_pk = Column(
+ scope_code: Mapped[str] = mapped_column(String(100), nullable=False, comment='Scope 编码')
+ scope_name: Mapped[str] = mapped_column(String(100), nullable=False, comment='Scope 名称')
+ scope_type: Mapped[str] = mapped_column(String(16), nullable=False, comment='Scope 类型')
+ resource_pk: Mapped[int | None] = mapped_column(
BigInteger,
ForeignKey('sys_oauth_resource.resource_pk', name='fk_oauth_scope_resource', ondelete='RESTRICT'),
nullable=True,
comment='Resource 主键',
)
- claims = Column(JSON, nullable=False, comment='Claims 列表')
- consent_required = Column(SmallInteger, nullable=False, server_default='1', comment='是否需要同意')
- sensitive = Column(SmallInteger, nullable=False, server_default='0', comment='是否敏感')
- status = Column(CHAR(1), nullable=False, server_default='0', comment='状态(0正常 1停用)')
- create_by = Column(String(64), nullable=False, comment='创建者')
- create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间')
- update_by = Column(String(64), nullable=False, comment='更新者')
- update_time = Column(
+ claims: Mapped[list[str]] = mapped_column(JSON, nullable=False, comment='Claims 列表')
+ consent_required: Mapped[int] = mapped_column(
+ SmallInteger, nullable=False, server_default='1', comment='是否需要同意'
+ )
+ sensitive: Mapped[int] = mapped_column(SmallInteger, nullable=False, server_default='0', comment='是否敏感')
+ status: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='0', comment='状态(0正常 1停用)')
+ create_by: Mapped[str] = mapped_column(String(64), nullable=False, comment='创建者')
+ create_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间'
+ )
+ update_by: Mapped[str] = mapped_column(String(64), nullable=False, comment='更新者')
+ update_time: Mapped[datetime] = mapped_column(
DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, onupdate=TimezoneUtil.utc_now, comment='更新时间'
)
- remark = Column(String(500), nullable=True, comment='备注')
+ remark: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='备注')
class SysOAuthClientScope(Base):
@@ -108,24 +116,28 @@ class SysOAuthClientScope(Base):
{'comment': 'OAuth Client Scope'},
)
- client_pk = Column(
+ client_pk: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_oauth_client.client_pk', name='fk_oauth_client_scope_client', ondelete='RESTRICT'),
primary_key=True,
nullable=False,
comment='Client 主键',
)
- scope_pk = Column(
+ scope_pk: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_oauth_scope.scope_pk', name='fk_oauth_client_scope_scope', ondelete='RESTRICT'),
primary_key=True,
nullable=False,
comment='Scope 主键',
)
- is_default = Column(SmallInteger, nullable=False, server_default='0', comment='是否默认 Scope')
- pre_authorized = Column(SmallInteger, nullable=False, server_default='0', comment='是否预授权')
- claim_filter = Column(JSON, nullable=True, comment='Client Claim 过滤策略')
- create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间')
+ is_default: Mapped[int] = mapped_column(SmallInteger, nullable=False, server_default='0', comment='是否默认 Scope')
+ pre_authorized: Mapped[int] = mapped_column(SmallInteger, nullable=False, server_default='0', comment='是否预授权')
+ claim_filter: Mapped[list[str] | dict[str, list[str]] | None] = mapped_column(
+ JSON, nullable=True, comment='Client Claim 过滤策略'
+ )
+ create_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间'
+ )
class SysOAuthClientResource(Base):
@@ -138,19 +150,23 @@ class SysOAuthClientResource(Base):
{'comment': 'OAuth Client Resource'},
)
- client_pk = Column(
+ client_pk: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_oauth_client.client_pk', name='fk_oauth_client_resource_client', ondelete='RESTRICT'),
primary_key=True,
nullable=False,
comment='Client 主键',
)
- resource_pk = Column(
+ resource_pk: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('sys_oauth_resource.resource_pk', name='fk_oauth_client_resource_resource', ondelete='RESTRICT'),
primary_key=True,
nullable=False,
comment='Resource 主键',
)
- is_default = Column(SmallInteger, nullable=False, server_default='0', comment='是否默认 Resource')
- create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间')
+ is_default: Mapped[int] = mapped_column(
+ SmallInteger, nullable=False, server_default='0', comment='是否默认 Resource'
+ )
+ create_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间'
+ )
diff --git a/ruoyi-fastapi-backend/module_identity/entity/do/oidc_key_do.py b/ruoyi-fastapi-backend/module_identity/entity/do/oidc_key_do.py
index 719c6b319..e212a6dfe 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/do/oidc_key_do.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/do/oidc_key_do.py
@@ -1,4 +1,7 @@
-from sqlalchemy import JSON, BigInteger, CheckConstraint, Column, Index, Integer, String, Text, UniqueConstraint
+from datetime import datetime
+
+from sqlalchemy import JSON, BigInteger, CheckConstraint, Index, Integer, String, Text, UniqueConstraint
+from sqlalchemy.orm import Mapped, mapped_column
from common.types import DbUtcDateTime
from config.database import Base
@@ -21,24 +24,30 @@ class SysOidcSigningKey(Base):
{'comment': 'OIDC Signing Key'},
)
- key_pk = Column(
+ key_pk: Mapped[int] = mapped_column(
BigInteger().with_variant(Integer, 'sqlite'),
primary_key=True,
nullable=False,
autoincrement=True,
comment='内部主键',
)
- kid = Column(String(100), nullable=False, comment='JWKS 密钥标识')
- key_use = Column(String(16), nullable=False, server_default='sig', comment='JWK 用途')
- alg = Column(String(16), nullable=False, server_default='RS256', comment='签名算法')
- public_jwk = Column(JSON, nullable=False, comment='公开 JWK')
- private_key_ref = Column(String(1000), nullable=True, comment='KMS/HSM/文件引用')
- private_key_ciphertext = Column(Text, nullable=True, comment='加密私钥材料')
- status = Column(String(16), nullable=False, comment='密钥状态')
- publish_at = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='发布时间')
- signing_start_at = Column(DbUtcDateTime(), nullable=True, comment='开始签名时间')
- signing_stop_at = Column(DbUtcDateTime(), nullable=True, comment='停止签名时间')
- remove_from_jwks_at = Column(DbUtcDateTime(), nullable=True, comment='移出 JWKS 时间')
- create_by = Column(String(64), nullable=False, comment='创建者')
- create_time = Column(DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间')
- remark = Column(String(500), nullable=True, comment='备注')
+ kid: Mapped[str] = mapped_column(String(100), nullable=False, comment='JWKS 密钥标识')
+ key_use: Mapped[str] = mapped_column(String(16), nullable=False, server_default='sig', comment='JWK 用途')
+ alg: Mapped[str] = mapped_column(String(16), nullable=False, server_default='RS256', comment='签名算法')
+ public_jwk: Mapped[dict[str, str]] = mapped_column(JSON, nullable=False, comment='公开 JWK')
+ private_key_ref: Mapped[str | None] = mapped_column(String(1000), nullable=True, comment='KMS/HSM/文件引用')
+ private_key_ciphertext: Mapped[str | None] = mapped_column(Text, nullable=True, comment='加密私钥材料')
+ status: Mapped[str] = mapped_column(String(16), nullable=False, comment='密钥状态')
+ publish_at: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='发布时间'
+ )
+ signing_start_at: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='开始签名时间')
+ signing_stop_at: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='停止签名时间')
+ remove_from_jwks_at: Mapped[datetime | None] = mapped_column(
+ DbUtcDateTime(), nullable=True, comment='移出 JWKS 时间'
+ )
+ create_by: Mapped[str] = mapped_column(String(64), nullable=False, comment='创建者')
+ create_time: Mapped[datetime] = mapped_column(
+ DbUtcDateTime(), nullable=False, default=TimezoneUtil.utc_now, comment='创建时间'
+ )
+ remark: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='备注')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/types.py b/ruoyi-fastapi-backend/module_identity/entity/types.py
new file mode 100644
index 000000000..19fa56110
--- /dev/null
+++ b/ruoyi-fastapi-backend/module_identity/entity/types.py
@@ -0,0 +1,74 @@
+from typing import Literal, NotRequired, TypedDict
+
+AccessStatus = Literal['allowed', 'blocked']
+AuthorizationStatus = Literal['active', 'revoked', 'expired']
+AuditResult = Literal['success', 'failure']
+AuditRiskLevel = Literal['normal', 'medium', 'high', 'critical']
+ClientUriType = Literal['redirect', 'post_logout', 'backchannel_logout', 'cors_origin']
+InteractionAction = Literal['login', 'consent', 'redirect', 'changePassword']
+
+
+ResponseType = Literal['code']
+ResponseMode = Literal['query']
+SubjectType = Literal['public']
+SigningAlgorithm = Literal['RS256']
+TokenEndpointAuthMethod = Literal['none', 'client_secret_basic']
+CodeChallengeMethod = Literal['S256']
+
+
+class InteractionRecord(TypedDict):
+ """
+ 从 Redis 读取并校验后的认证交互记录。
+
+ :ivar interactionId: 交互标识
+ :ivar requestedAt: 发起请求的 UTC 时间
+ :ivar csrfHash: 当前交互的 CSRF 摘要
+ :ivar status: 当前交互状态
+ :ivar version: 状态变更的版本号
+ :ivar clientPk: 客户端主键
+ :ivar clientId: 客户端公开标识
+ :ivar redirectUri: 已验证的回调地址
+ :ivar responseType: 授权响应类型
+ :ivar scopes: 请求的权限范围
+ :ivar resources: 请求的资源受众
+ :ivar state: 客户端传入的状态值
+ :ivar nonce: 与授权请求绑定的随机值
+ :ivar codeChallenge: PKCE 挑战值
+ :ivar codeChallengeMethod: PKCE 挑战算法
+ :ivar prompt: 授权请求的交互提示
+ :ivar maxAge: 允许的最长认证间隔秒数
+ :ivar consentRequired: 是否需要用户同意
+ :ivar grantId: 已持久化的授权标识
+ :ivar authenticatedSid: 已认证的会话标识
+ :ivar userId: 已认证的用户编号
+ :ivar subjectId: 已认证的主体标识
+ :ivar authVersion: 当前用户的认证版本
+ :ivar credentialProofHash: 密码认证证明的摘要
+ :ivar rememberMe: 用户是否选择保持登录
+ """
+
+ interactionId: str
+ requestedAt: str
+ csrfHash: str
+ status: str
+ version: int
+ clientPk: int
+ clientId: str
+ redirectUri: str
+ responseType: Literal['code']
+ scopes: list[str]
+ resources: list[str]
+ state: str | None
+ nonce: str
+ codeChallenge: str
+ codeChallengeMethod: Literal['S256']
+ prompt: list[str] | str | None
+ maxAge: int | None
+ consentRequired: bool
+ grantId: NotRequired[str | None]
+ authenticatedSid: NotRequired[str | None]
+ userId: NotRequired[int | None]
+ subjectId: NotRequired[str | None]
+ authVersion: NotRequired[int | None]
+ credentialProofHash: NotRequired[str | None]
+ rememberMe: NotRequired[bool]
diff --git a/ruoyi-fastapi-backend/module_identity/entity/vo/interaction_vo.py b/ruoyi-fastapi-backend/module_identity/entity/vo/interaction_vo.py
index bcc6805b7..e53ce3f54 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/vo/interaction_vo.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/vo/interaction_vo.py
@@ -1,19 +1,19 @@
-from typing import Literal
+from pydantic import ConfigDict, Field, model_validator
-from pydantic import BaseModel, ConfigDict, Field, model_validator
-from pydantic.alias_generators import to_camel
+from common.vo import CamelModel
+from module_identity.entity.types import InteractionAction
_MAX_INTERACTION_SCOPE_LENGTH = 100
-class InteractionModel(BaseModel):
+class InteractionModel(CamelModel):
"""
认证交互 API 模型基类。
交互字段使用 camelCase,并拒绝未定义字段。
"""
- model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(extra='forbid')
class InteractionLoginModel(InteractionModel):
@@ -105,7 +105,7 @@ class InteractionViewModel(InteractionModel):
interaction_id: str = Field(description='认证交互标识')
client: InteractionClientModel = Field(description='发起认证的客户端摘要')
requested_scopes: list[RequestedScopeModel] = Field(default_factory=list, description='客户端请求的权限列表')
- next_action: Literal['login', 'consent', 'redirect', 'changePassword'] = Field(description='认证交互的下一步动作')
+ next_action: InteractionAction = Field(description='认证交互的下一步动作')
captcha_enabled: bool = Field(default=False, description='是否启用验证码')
expires_in: int = Field(description='剩余有效时间,单位为秒')
@@ -113,7 +113,7 @@ class InteractionViewModel(InteractionModel):
class InteractionResultModel(InteractionModel):
"""登录、同意或改密后的下一步动作模型。"""
- next_action: Literal['login', 'consent', 'redirect', 'changePassword'] = Field(description='认证交互的下一步动作')
+ next_action: InteractionAction = Field(description='认证交互的下一步动作')
interaction_id: str | None = Field(default=None, description='认证交互标识')
redirect_url: str | None = Field(default=None, description='服务端返回的下一步跳转地址')
reason: str | None = Field(default=None, description='下一步动作的原因')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_client_vo.py b/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_client_vo.py
index 2615089d1..3a6128b61 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_client_vo.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_client_vo.py
@@ -1,18 +1,19 @@
from typing import Any, Literal
-from pydantic import BaseModel, ConfigDict, Field, model_validator
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field, model_validator
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
+from module_identity.entity.types import ClientUriType, ResponseType
from utils.oidc_util import OidcUtil
_MAX_ROLE_KEY_LENGTH = 100
-class ClientModel(BaseModel):
+class ClientModel(CamelModel):
"""OAuth Client 管理模型基类。"""
- model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True, extra='forbid')
+ model_config = ConfigDict(from_attributes=True, extra='forbid')
class ClientCreateModel(ClientModel):
@@ -24,8 +25,8 @@ class ClientCreateModel(ClientModel):
)
token_endpoint_auth_method: Literal['none', 'client_secret_basic'] = Field(description='令牌端点的客户端认证方式')
grant_types: list[str] = Field(default_factory=lambda: ['authorization_code'], description='允许使用的授权类型')
- response_types: list[Literal['code']] = Field(
- default_factory=lambda: ['code'], description='允许使用的授权响应类型'
+ response_types: list[ResponseType] = Field(
+ default_factory=lambda: list[ResponseType](('code',)), description='允许使用的授权响应类型'
)
require_pkce: bool = Field(default=True, description='是否强制使用PKCE')
require_consent: bool = Field(default=True, description='是否要求用户确认授权')
@@ -166,9 +167,7 @@ class ClientUriModel(ClientModel):
URI 在 DTO 边界执行精确匹配所需的安全校验。
"""
- uri_type: Literal['redirect', 'post_logout', 'backchannel_logout', 'cors_origin'] = Field(
- description='注册地址类型'
- )
+ uri_type: ClientUriType = Field(description='注册地址类型')
uri: str = Field(min_length=1, max_length=1000, description='完整注册地址')
is_default: bool = Field(default=False, description='是否为默认地址')
status: Literal['0', '1'] = Field(default='0', description='状态(0正常 1停用)')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_resource_vo.py b/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_resource_vo.py
index f59bde511..560503aef 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_resource_vo.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_resource_vo.py
@@ -1,15 +1,15 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field, field_validator, model_validator
+from common.vo import CamelModel
from utils.oidc_util import OidcUtil
-class ResourceModel(BaseModel):
+class ResourceModel(CamelModel):
"""Resource 与 Scope 管理模型基类。"""
- model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True, extra='forbid')
+ model_config = ConfigDict(from_attributes=True, extra='forbid')
class ScopeModel(ResourceModel):
diff --git a/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_session_vo.py b/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_session_vo.py
index 70386e8f0..a64935518 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_session_vo.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/vo/oauth_session_vo.py
@@ -1,19 +1,18 @@
-from typing import Literal
-
-from pydantic import BaseModel, ConfigDict, Field, model_validator
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field, model_validator
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
+from module_identity.entity.types import AccessStatus, AuditResult, AuditRiskLevel, AuthorizationStatus
-class SessionModel(BaseModel):
+class SessionModel(CamelModel):
"""
Session、Grant 和 Audit 管理模型基类。
管理端字段接受 camelCase 别名并拒绝额外字段。
"""
- model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True, extra='forbid')
+ model_config = ConfigDict(from_attributes=True, extra='forbid')
class GrantModel(SessionModel):
@@ -28,11 +27,9 @@ class GrantModel(SessionModel):
granted_resources: list[str] = Field(default_factory=list, description='已同意的资源受众列表')
remembered_scopes: list[str] = Field(default_factory=list, description='后续可免确认的权限列表')
remembered_resources: list[str] = Field(default_factory=list, description='后续可免确认的资源列表')
- access_status: Literal['allowed', 'blocked'] = Field(default='allowed', description='用户对应用的访问策略')
+ access_status: AccessStatus = Field(default='allowed', description='用户对应用的访问策略')
access_reason: str | None = Field(default=None, description='访问策略的操作原因')
- status: Literal['active', 'revoked', 'expired'] = Field(
- default='active', description='状态(active有效 revoked已撤销 expired已过期)'
- )
+ status: AuthorizationStatus = Field(default='active', description='状态(active有效 revoked已撤销 expired已过期)')
client_policy_version: int | None = Field(default=None, description='授权时的客户端策略版本')
consented_at: ApiUtcDateTime | None = Field(default=None, description='用户同意授权的时间')
last_used_at: ApiUtcDateTime | None = Field(default=None, description='授权最近使用时间')
@@ -55,9 +52,7 @@ class SsoSessionModel(SessionModel):
amr: list[str] = Field(default_factory=list, description='认证方式列表')
remember_me: bool = Field(default=False, description='是否保持长期登录')
ip_address: str | None = Field(default=None, description='IP地址')
- status: Literal['active', 'revoked', 'expired'] = Field(
- default='active', description='状态(active有效 revoked已撤销 expired已过期)'
- )
+ status: AuthorizationStatus = Field(default='active', description='状态(active有效 revoked已撤销 expired已过期)')
revoked_at: ApiUtcDateTime | None = Field(default=None, description='撤销时间')
revoke_reason: str | None = Field(default=None, description='撤销原因')
create_time: ApiUtcDateTime | None = Field(default=None, description='创建时间')
@@ -81,7 +76,7 @@ class SessionPageQueryModel(SessionModel):
user_id: int | None = Field(default=None, description='用户ID')
ip_address: str | None = Field(default=None, description='IP地址')
- status: Literal['active', 'revoked', 'expired'] | None = Field(
+ status: AuthorizationStatus | None = Field(
default=None, description='状态(active有效 revoked已撤销 expired已过期)'
)
start_time: ApiUtcDateTime | None = Field(default=None, description='查询开始时间')
@@ -107,10 +102,10 @@ class GrantPageQueryModel(SessionModel):
user_id: int | None = Field(default=None, description='用户ID')
client_id: str | None = Field(default=None, description='客户端标识')
- status: Literal['active', 'revoked', 'expired'] | None = Field(
+ status: AuthorizationStatus | None = Field(
default=None, description='状态(active有效 revoked已撤销 expired已过期)'
)
- access_status: Literal['allowed', 'blocked'] | None = Field(default=None, description='用户对应用的访问策略')
+ access_status: AccessStatus | None = Field(default=None, description='用户对应用的访问策略')
page_num: int = Field(default=1, ge=1, description='当前页码')
page_size: int = Field(default=10, ge=1, le=200, description='每页记录数')
@@ -122,7 +117,7 @@ class AccessPolicyModel(SessionModel):
user_name: str = Field(description='用户名称')
client_id: str = Field(description='客户端标识')
client_name: str = Field(description='客户端名称')
- access_status: Literal['allowed', 'blocked'] = Field(description='用户对应用的访问策略')
+ access_status: AccessStatus = Field(description='用户对应用的访问策略')
reason: str | None = Field(default=None, description='操作原因')
update_by: str | None = Field(default=None, description='操作人')
update_time: ApiUtcDateTime = Field(description='最近操作时间')
@@ -133,7 +128,7 @@ class AccessPolicyPageQueryModel(SessionModel):
user_id: int | None = Field(default=None, gt=0, description='用户ID')
client_id: str | None = Field(default=None, max_length=128, description='客户端标识')
- access_status: Literal['allowed', 'blocked'] | None = Field(default=None, description='访问策略')
+ access_status: AccessStatus | None = Field(default=None, description='访问策略')
page_num: int = Field(default=1, ge=1, description='当前页码')
page_size: int = Field(default=10, ge=1, le=200, description='每页记录数')
@@ -148,10 +143,8 @@ class AuditPageQueryModel(SessionModel):
event_type: str | None = Field(default=None, description='审计事件类型')
client_id: str | None = Field(default=None, description='客户端标识')
user_id: int | None = Field(default=None, description='用户ID')
- result: Literal['success', 'failure'] | None = Field(
- default=None, description='处理结果(success成功 failure失败)'
- )
- risk_level: Literal['normal', 'medium', 'high', 'critical'] | None = Field(
+ result: AuditResult | None = Field(default=None, description='处理结果(success成功 failure失败)')
+ risk_level: AuditRiskLevel | None = Field(
default=None, description='风险等级(normal普通 medium中等 high高 critical严重)'
)
start_time: ApiUtcDateTime | None = Field(default=None, description='查询开始时间')
@@ -177,8 +170,8 @@ class AuditModel(SessionModel):
audit_id: int = Field(description='审计记录ID')
event_type: str = Field(description='审计事件类型')
- result: Literal['success', 'failure'] = Field(description='处理结果(success成功 failure失败)')
- risk_level: Literal['normal', 'medium', 'high', 'critical'] = Field(
+ result: AuditResult = Field(description='处理结果(success成功 failure失败)')
+ risk_level: AuditRiskLevel = Field(
default='normal', description='风险等级(normal普通 medium中等 high高 critical严重)'
)
trace_id: str | None = Field(default=None, description='请求跟踪标识')
diff --git a/ruoyi-fastapi-backend/module_identity/entity/vo/oidc_key_vo.py b/ruoyi-fastapi-backend/module_identity/entity/vo/oidc_key_vo.py
index e106a3729..428aa7e7a 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/vo/oidc_key_vo.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/vo/oidc_key_vo.py
@@ -1,17 +1,17 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field, field_validator
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field, field_validator
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from module_identity.entity.vo.protocol_vo import Jwk
from utils.oidc_util import OidcUtil
-class OidcKeyModel(BaseModel):
+class OidcKeyModel(CamelModel):
"""OIDC 签名密钥管理模型基类。"""
- model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True, extra='forbid')
+ model_config = ConfigDict(from_attributes=True, extra='forbid')
class OidcKeyRotateModel(OidcKeyModel):
diff --git a/ruoyi-fastapi-backend/module_identity/entity/vo/protocol_vo.py b/ruoyi-fastapi-backend/module_identity/entity/vo/protocol_vo.py
index 78e279bae..1c623a7f6 100644
--- a/ruoyi-fastapi-backend/module_identity/entity/vo/protocol_vo.py
+++ b/ruoyi-fastapi-backend/module_identity/entity/vo/protocol_vo.py
@@ -1,7 +1,15 @@
-from typing import Literal
+from typing import Literal, get_args
from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, field_validator, model_validator
+from module_identity.entity.types import (
+ CodeChallengeMethod,
+ ResponseMode,
+ ResponseType,
+ SigningAlgorithm,
+ SubjectType,
+ TokenEndpointAuthMethod,
+)
from utils.oidc_util import OidcUtil
@@ -12,7 +20,7 @@ class ProtocolModel(BaseModel):
标准端点字段保持 snake_case,并拒绝未定义参数。
"""
- model_config = ConfigDict(extra='forbid', populate_by_name=True, str_strip_whitespace=True)
+ model_config = ConfigDict(extra='forbid', validate_by_name=True, validate_by_alias=True, str_strip_whitespace=True)
class AuthorizeRequest(ProtocolModel):
@@ -23,7 +31,7 @@ class AuthorizeRequest(ProtocolModel):
"""
response_type: str = Field(min_length=1, max_length=100, description='授权响应类型')
- response_mode: Literal['query'] = Field(default='query', description='授权响应参数传递方式')
+ response_mode: ResponseMode = Field(default='query', description='授权响应参数传递方式')
client_id: str = Field(min_length=1, max_length=64, description='客户端标识')
redirect_uri: str = Field(min_length=1, max_length=1000, description='已注册的授权回调地址')
scope: str = Field(min_length=1, max_length=2000, description='空格分隔的权限范围')
@@ -147,7 +155,12 @@ def as_dict(self) -> dict[str, str]:
:return: 排除 None 字段的标准错误字典
"""
- return self.model_dump(exclude_none=True)
+ fields = {'error': self.error}
+ if self.error_description is not None:
+ fields['error_description'] = self.error_description
+ if self.error_uri is not None:
+ fields['error_uri'] = self.error_uri
+ return fields
class Jwk(ProtocolModel):
@@ -160,7 +173,7 @@ class Jwk(ProtocolModel):
kty: Literal['RSA'] = Field(default='RSA', description='公钥类型')
use: Literal['sig'] = Field(default='sig', description='公钥用途')
kid: str = Field(min_length=1, max_length=100, description='签名密钥标识')
- alg: Literal['RS256'] = Field(default='RS256', description='签名算法')
+ alg: SigningAlgorithm = Field(default='RS256', description='签名算法')
n: str = Field(min_length=1, description='RSA公钥模数的Base64URL编码')
e: str = Field(min_length=1, description='RSA公钥指数的Base64URL编码')
@@ -191,26 +204,26 @@ class DiscoveryResponse(ProtocolModel):
introspection_endpoint: str = Field(description='令牌内省端点地址')
end_session_endpoint: str = Field(description='退出端点地址')
scopes_supported: list[str] = Field(default_factory=list, description='支持的权限列表')
- response_types_supported: list[Literal['code']] = Field(
- default_factory=lambda: ['code'], description='支持的授权响应类型列表'
+ response_types_supported: list[ResponseType] = Field(
+ default_factory=lambda: list(get_args(ResponseType)), description='支持的授权响应类型列表'
)
- response_modes_supported: list[Literal['query']] = Field(
- default_factory=lambda: ['query'], description='支持的授权响应模式列表'
+ response_modes_supported: list[ResponseMode] = Field(
+ default_factory=lambda: list(get_args(ResponseMode)), description='支持的授权响应模式列表'
)
grant_types_supported: list[str] = Field(
default_factory=lambda: ['authorization_code', 'refresh_token'], description='支持的授权类型列表'
)
- subject_types_supported: list[Literal['public']] = Field(
- default_factory=lambda: ['public'], description='支持的主体标识类型列表'
+ subject_types_supported: list[SubjectType] = Field(
+ default_factory=lambda: list(get_args(SubjectType)), description='支持的主体标识类型列表'
)
- id_token_signing_alg_values_supported: list[Literal['RS256']] = Field(
- default_factory=lambda: ['RS256'], description='支持的ID Token签名算法列表'
+ id_token_signing_alg_values_supported: list[SigningAlgorithm] = Field(
+ default_factory=lambda: list(get_args(SigningAlgorithm)), description='支持的ID Token签名算法列表'
)
- token_endpoint_auth_methods_supported: list[Literal['none', 'client_secret_basic']] = Field(
- default_factory=lambda: ['none', 'client_secret_basic'], description='支持的令牌端点认证方式列表'
+ token_endpoint_auth_methods_supported: list[TokenEndpointAuthMethod] = Field(
+ default_factory=lambda: list(get_args(TokenEndpointAuthMethod)), description='支持的令牌端点认证方式列表'
)
- code_challenge_methods_supported: list[Literal['S256']] = Field(
- default_factory=lambda: ['S256'], description='支持的PKCE挑战方法列表'
+ code_challenge_methods_supported: list[CodeChallengeMethod] = Field(
+ default_factory=lambda: list(get_args(CodeChallengeMethod)), description='支持的PKCE挑战方法列表'
)
claims_supported: list[str] = Field(default_factory=list, description='支持的声明字段列表')
authorization_response_iss_parameter_supported: bool = Field(
@@ -234,17 +247,17 @@ class OAuthServerMetadata(ProtocolModel):
revocation_endpoint: str | None = Field(default=None, description='令牌撤销端点地址')
introspection_endpoint: str | None = Field(default=None, description='令牌内省端点地址')
scopes_supported: list[str] = Field(default_factory=list, description='支持的权限列表')
- response_types_supported: list[Literal['code']] = Field(
- default_factory=lambda: ['code'], description='支持的授权响应类型列表'
+ response_types_supported: list[ResponseType] = Field(
+ default_factory=lambda: list(get_args(ResponseType)), description='支持的授权响应类型列表'
)
grant_types_supported: list[str] = Field(
default_factory=lambda: ['authorization_code', 'refresh_token'], description='支持的授权类型列表'
)
- token_endpoint_auth_methods_supported: list[Literal['none', 'client_secret_basic']] = Field(
- default_factory=lambda: ['none', 'client_secret_basic'], description='支持的令牌端点认证方式列表'
+ token_endpoint_auth_methods_supported: list[TokenEndpointAuthMethod] = Field(
+ default_factory=lambda: list(get_args(TokenEndpointAuthMethod)), description='支持的令牌端点认证方式列表'
)
- code_challenge_methods_supported: list[Literal['S256']] = Field(
- default_factory=lambda: ['S256'], description='支持的PKCE挑战方法列表'
+ code_challenge_methods_supported: list[CodeChallengeMethod] = Field(
+ default_factory=lambda: list(get_args(CodeChallengeMethod)), description='支持的PKCE挑战方法列表'
)
diff --git a/ruoyi-fastapi-backend/module_identity/security/backchannel_transport.py b/ruoyi-fastapi-backend/module_identity/security/backchannel_transport.py
index a3f22b6fe..92d24baf2 100644
--- a/ruoyi-fastapi-backend/module_identity/security/backchannel_transport.py
+++ b/ruoyi-fastapi-backend/module_identity/security/backchannel_transport.py
@@ -1,10 +1,10 @@
-from collections.abc import Awaitable, Callable
-from typing import Any
+from collections.abc import AsyncIterator, Awaitable, Callable, Iterable
from urllib.parse import urlsplit
import httpcore
import httpx
from httpcore._backends.auto import AutoBackend
+from typing_extensions import override
_MAX_BACKCHANNEL_RESPONSE_BYTES = 64 * 1024
_HTTP_CLIENT_ERROR_MIN = 400
@@ -53,13 +53,23 @@ def __init__(self, hostname: str, addresses: set[str]) -> None:
self._addresses = addresses
self._backend = AutoBackend()
- async def connect_tcp(self, host: str, port: int, **kwargs: Any) -> httpcore.AsyncNetworkStream:
+ @override
+ async def connect_tcp(
+ self,
+ host: str,
+ port: int,
+ timeout: float | None = None,
+ local_address: str | None = None,
+ socket_options: Iterable[httpcore.SOCKET_OPTION] | None = None,
+ ) -> httpcore.AsyncNetworkStream:
"""
连接已验证主机对应的固定公网地址。
:param host: HTTP Core 请求的原始主机名
:param port: 目标 TCP 端口
- :param kwargs: HTTP Core 连接参数
+ :param timeout: 建立连接的超时秒数
+ :param local_address: 本地绑定地址
+ :param socket_options: 传给底层套接字的选项
:return: 已建立的异步网络流
:raises OSError: 主机未验证、地址为空或全部地址连接失败
"""
@@ -69,7 +79,9 @@ async def connect_tcp(self, host: str, port: int, **kwargs: Any) -> httpcore.Asy
last_error: OSError | None = None
for address in sorted(self._addresses):
try:
- return await self._backend.connect_tcp(address, port, **kwargs)
+ return await self._backend.connect_tcp(
+ address, port, timeout=timeout, local_address=local_address, socket_options=socket_options
+ )
except OSError as exc:
last_error = exc
raise last_error or OSError('没有通过安全校验的网络目标')
@@ -123,14 +135,14 @@ def __init__(self) -> None:
"""初始化已接收字节计数器。"""
self._received = 0
- async def __aiter__(self) -> Any:
+ async def __aiter__(self) -> AsyncIterator[bytes]:
"""
逐块读取响应并执行大小限制。
:yield: HTTP 响应字节块异步迭代器
:raises OSError: 响应体超过大小限制
"""
- async for chunk in response.stream:
+ async for chunk in response.aiter_stream():
self._received += len(chunk)
if self._received > _MAX_BACKCHANNEL_RESPONSE_BYTES:
await response.aclose()
diff --git a/ruoyi-fastapi-backend/module_identity/security/jwt_profile.py b/ruoyi-fastapi-backend/module_identity/security/jwt_profile.py
index d2c00e2ee..7983e08e4 100644
--- a/ruoyi-fastapi-backend/module_identity/security/jwt_profile.py
+++ b/ruoyi-fastapi-backend/module_identity/security/jwt_profile.py
@@ -334,6 +334,8 @@ def _decode(
raise JwtProfileError('JWT 用途类型不匹配')
key_source = verification_key if verification_key is not None else verification_keys
key = _key_for_kid(key_source, str(headers['kid']))
+ if not isinstance(key, (RSAPublicKey, jwt.PyJWK, str, bytes)):
+ raise JwtProfileError('签名密钥不存在或不可用')
try:
payload = jwt.decode(
token,
diff --git a/ruoyi-fastapi-backend/module_identity/security/uri_validator.py b/ruoyi-fastapi-backend/module_identity/security/uri_validator.py
index 7236385db..66871712d 100644
--- a/ruoyi-fastapi-backend/module_identity/security/uri_validator.py
+++ b/ruoyi-fastapi-backend/module_identity/security/uri_validator.py
@@ -31,9 +31,13 @@ async def public_dns_addresses(hostname: str, port: int) -> set[str]:
)
except (OSError, socket.gaierror, ValueError):
return set()
- addresses = {item[4][0] for item in records if item[4]}
-
- return addresses if addresses and all(OidcUtil.is_public_ip(address) for address in addresses) else set()
+ addresses: set[str] = set()
+ for _, _, _, _, sockaddr in records:
+ address = sockaddr[0]
+ if not isinstance(address, str) or not OidcUtil.is_public_ip(address):
+ return set()
+ addresses.add(address)
+ return addresses
async def is_safe_backchannel_uri(uri: object) -> bool:
diff --git a/ruoyi-fastapi-backend/module_identity/service/audit_service.py b/ruoyi-fastapi-backend/module_identity/service/audit_service.py
index ac4aabc44..33c6e5690 100644
--- a/ruoyi-fastapi-backend/module_identity/service/audit_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/audit_service.py
@@ -1,12 +1,12 @@
from collections.abc import Awaitable, Callable, Mapping
-from typing import Any
+from typing import Any, cast
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from common.constant import OidcAuditEvent
from config.database import DataSourceRegistry
from exceptions.exception import OidcInteractionException
-from module_identity.dao.oauth_audit_dao import OAuthAuditDao
+from module_identity.dao.oauth_audit_dao import AuditFilters, OAuthAuditDao
from module_identity.entity.do.oauth_audit_do import SysOAuthAuditLog
from module_identity.entity.vo.oauth_session_vo import AuditModel, AuditPageQueryModel
from utils.excel_util import ExcelUtil
@@ -197,7 +197,7 @@ async def append(cls, db: AsyncSession, event: SysOAuthAuditLog | Mapping[str, A
return await OAuthAuditDao.append(db, row)
@staticmethod
- def _admin_filters(query: AuditPageQueryModel) -> dict[str, object]:
+ def _admin_filters(query: AuditPageQueryModel) -> AuditFilters:
"""
构造管理端审计查询条件。
@@ -222,7 +222,7 @@ def _admin_model(row: SysOAuthAuditLog) -> dict[str, object]:
:param row: 审计日志实体
:return: 不含详情敏感字段的管理端模型字典
"""
- return AuditModel(
+ model = AuditModel(
audit_id=row.event_id,
event_type=row.event_type,
result=row.result,
@@ -236,7 +236,8 @@ def _admin_model(row: SysOAuthAuditLog) -> dict[str, object]:
ip_address=getattr(row, 'ip_address', None),
failure_code=getattr(row, 'failure_code', None),
create_time=row.create_time,
- ).model_dump(by_alias=True)
+ )
+ return cast('dict[str, object]', model.model_dump(by_alias=True))
@classmethod
async def list_admin_page(cls, db: AsyncSession, query: AuditPageQueryModel) -> tuple[list[dict[str, object]], int]:
diff --git a/ruoyi-fastapi-backend/module_identity/service/authorization_service.py b/ruoyi-fastapi-backend/module_identity/service/authorization_service.py
index a5166c2ae..89e7def04 100644
--- a/ruoyi-fastapi-backend/module_identity/service/authorization_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/authorization_service.py
@@ -1,6 +1,6 @@
import json
import re
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any
@@ -24,6 +24,7 @@
SysOAuthResource,
SysOAuthScope,
)
+from module_identity.entity.types import InteractionRecord
from module_identity.entity.vo.protocol_vo import AuthorizeRequest
from module_identity.redis_keys import OidcRedisKey
from module_identity.security.opaque_token import (
@@ -410,7 +411,8 @@ async def _complete_authorization(cls, db: AsyncSession, redis: Any, interaction
registered_uri = await cls.verified_redirect_for_client(db, client_pk, redirect_uri)
if registered_uri is None:
raise OAuthProtocolException('server_error', 'Validated redirect URI is unavailable', 500)
- session = await cls.active_session(db, record.get('authenticatedSid', ''), now=TimezoneUtil.utc_now())
+ sid = record.get('authenticatedSid')
+ session = await cls.active_session(db, sid, now=TimezoneUtil.utc_now()) if sid else None
if session is None:
raise OAuthProtocolException('login_required', 'A current login is required', 400)
grant = await cls._completion_grant(db, record, session)
@@ -455,7 +457,9 @@ async def _complete_authorization(cls, db: AsyncSession, redis: Any, interaction
raise OAuthProtocolException('server_error', 'Authorization code could not be completed', 500) from exc
@classmethod
- async def _completion_grant(cls, db: AsyncSession, record: dict[str, Any], session: SysSsoSession) -> SysOAuthGrant:
+ async def _completion_grant(
+ cls, db: AsyncSession, record: InteractionRecord, session: SysSsoSession
+ ) -> SysOAuthGrant:
"""
重新检查访问策略并为免确认流程补齐授权记录。
@@ -841,9 +845,7 @@ async def validate_request(cls, db: AsyncSession, request: AuthorizeRequest) ->
)
@staticmethod
- async def _load_scope_models(
- db: AsyncSession, bindings: list[SysOAuthClientScope] | tuple[SysOAuthClientScope, ...]
- ) -> list[SysOAuthScope]:
+ async def _load_scope_models(db: AsyncSession, bindings: Sequence[SysOAuthClientScope]) -> list[SysOAuthScope]:
"""
加载 Client Scope 绑定对应的有效 Scope 定义。
@@ -859,9 +861,7 @@ async def _load_scope_models(
return [scope for scope in definitions if scope.scope_pk in scope_ids]
@staticmethod
- async def load_scope_models(
- db: AsyncSession, bindings: list[SysOAuthClientScope] | tuple[SysOAuthClientScope, ...]
- ) -> list[SysOAuthScope]:
+ async def load_scope_models(db: AsyncSession, bindings: Sequence[SysOAuthClientScope]) -> list[SysOAuthScope]:
"""
加载 Client Scope 绑定对应的 Scope 定义。
@@ -874,8 +874,8 @@ async def load_scope_models(
@staticmethod
def _resolve_resource(
requested_resource: str | None,
- resources: list[SysOAuthResource] | tuple[SysOAuthResource, ...],
- resource_bindings: list[SysOAuthClientResource] | tuple[SysOAuthClientResource, ...],
+ resources: Sequence[SysOAuthResource],
+ resource_bindings: Sequence[SysOAuthClientResource],
requested_scopes: list[SysOAuthScope],
redirect_uri: str,
state: str | None,
@@ -1041,7 +1041,7 @@ async def issue(
payload: Mapping[str, Any],
*,
ttl_seconds: int | None = None,
- pepper: str | None = None,
+ pepper: str | bytes | None = None,
) -> str:
"""
签发短期 Authorization Code 并以 NX 写入 Redis。
@@ -1075,7 +1075,7 @@ async def consume(
redis: Redis,
code: str,
*,
- pepper: str | None = None,
+ pepper: str | bytes | None = None,
) -> dict[str, Any]:
"""
使用 Redis Lua 原子校验并消费 Authorization Code。
@@ -1128,7 +1128,7 @@ async def consumed_payload(
redis: Redis,
code: str,
*,
- pepper: str | None = None,
+ pepper: str | bytes | None = None,
) -> dict[str, Any] | None:
"""
读取已消费授权码的短期绑定载荷。
@@ -1260,8 +1260,8 @@ async def complete(redis: Redis, interaction_id: str, db: AsyncSession) -> 'Inte
raise OidcInteractionException(
interaction_id, '认证交互已完成,请勿重复提交', error='invalid_request', status_code=409
)
- redirect_uri = record.get('redirectUri')
try:
+ redirect_uri = record['redirectUri']
registered = await OAuthClientDao.find_exact_uri(db, record['clientPk'], 'redirect', redirect_uri)
except Exception:
await InteractionFlowService.best_effort_delete(redis, marker)
@@ -1281,7 +1281,7 @@ async def complete(redis: Redis, interaction_id: str, db: AsyncSession) -> 'Inte
return await InteractionCompletionService._issue_code(db, redis, record, registered.uri, marker)
@staticmethod
- async def active_session(db: AsyncSession, record: dict[str, Any]) -> SysSsoSession | None:
+ async def active_session(db: AsyncSession, record: InteractionRecord) -> SysSsoSession | None:
"""
读取活动会话。
@@ -1305,7 +1305,7 @@ async def active_session(db: AsyncSession, record: dict[str, Any]) -> SysSsoSess
@staticmethod
async def _issue_code(
- db: AsyncSession, redis: Any, record: dict[str, Any], redirect_uri: str, marker: str
+ db: AsyncSession, redis: Any, record: InteractionRecord, redirect_uri: str, marker: str
) -> 'InteractionCompletionResult':
"""
签发授权码。
@@ -1375,7 +1375,7 @@ async def _issue_code(
@staticmethod
def _redirect(
redirect_uri: str,
- record: dict[str, Any],
+ record: InteractionRecord,
*,
code: str | None = None,
error: str | None = None,
@@ -1394,8 +1394,9 @@ def _redirect(
query.append(('code', code))
if error is not None:
query.append(('error', error))
- if record.get('state') is not None:
- query.append(('state', record['state']))
+ state = record.get('state')
+ if state is not None:
+ query.append(('state', state))
query.append(('iss', OidcConfig.oidc_issuer))
location = OidcUtil.replace_query_parameters(
redirect_uri, query, {'code', 'error', 'state', 'iss'}, fragment=''
diff --git a/ruoyi-fastapi-backend/module_identity/service/consent_service.py b/ruoyi-fastapi-backend/module_identity/service/consent_service.py
index cf593300c..ecb39e87c 100644
--- a/ruoyi-fastapi-backend/module_identity/service/consent_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/consent_service.py
@@ -11,6 +11,7 @@
from module_identity.dao.oauth_client_dao import OAuthClientDao
from module_identity.dao.oauth_grant_dao import OAuthGrantDao, OAuthGrantSnapshot
from module_identity.entity.do.oauth_grant_do import SysOAuthGrant
+from module_identity.entity.types import InteractionRecord
from module_identity.entity.vo.interaction_vo import InteractionConsentModel, InteractionResultModel
from module_identity.service.audit_service import AuditService
from module_identity.service.authorization_service import (
@@ -239,7 +240,7 @@ class InteractionConsentService:
"""认证中心授权同意流程模块服务层。"""
@staticmethod
- async def context_from_record(db: AsyncSession, record: dict[str, object]) -> AuthorizationContext:
+ async def context_from_record(db: AsyncSession, record: InteractionRecord) -> AuthorizationContext:
"""
从 Interaction 白名单记录和当前数据库策略重建同意上下文。
@@ -305,7 +306,7 @@ async def context_from_record(db: AsyncSession, record: dict[str, object]) -> Au
nonce=record['nonce'],
code_challenge=record['codeChallenge'],
code_challenge_method=record['codeChallengeMethod'],
- prompt=' '.join(record.get('prompt') or ()),
+ prompt=record['prompt'] if isinstance(record['prompt'], str) else ' '.join(record['prompt'] or ()),
max_age=record.get('maxAge'),
required_scopes=required,
)
diff --git a/ruoyi-fastapi-backend/module_identity/service/identity_service.py b/ruoyi-fastapi-backend/module_identity/service/identity_service.py
index 643943ca4..de3e78aba 100644
--- a/ruoyi-fastapi-backend/module_identity/service/identity_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/identity_service.py
@@ -126,7 +126,7 @@ async def authenticate_legacy(
*,
client_ip: str | None,
skip_captcha: bool = False,
- ) -> Row[tuple[SysUser, SysDept]]:
+ ) -> Row[SysUser, SysDept | None]:
"""
执行 Legacy 登录的原有凭据检查,不签发 JWT。
@@ -256,6 +256,8 @@ async def _check_ip(cls, client_ip: str | None, redis: Redis) -> None:
:raises CredentialAuthenticationError: 客户端 IP 命中禁止登录名单
"""
value = await redis.get(f'{RedisInitKeyConfig.SYS_CONFIG.key}:sys.login.blackIPList')
+ if isinstance(value, bytes):
+ value = value.decode()
if client_ip in (value.split(',') if value else []):
raise CredentialAuthenticationError('ip_blocked', I18nMessage('当前IP禁止登录', msg_key='auth.ipBlocked'))
@@ -468,7 +470,9 @@ def effective_claims(
:return: 可安全生成的 Claim 名称集合
"""
requested = OidcUtil.scope_set(requested_scopes)
- client_claims = set().union(*(cls._client_claims_for_scope(scope, client_scope_policy) for scope in requested))
+ client_claims = {
+ claim for scope in requested for claim in cls._client_claims_for_scope(scope, client_scope_policy)
+ }
resource_claims = cls._claim_set(resource_allowed_claims)
return (client_claims & resource_claims) - cls.FORBIDDEN_CLAIMS
diff --git a/ruoyi-fastapi-backend/module_identity/service/interaction_service.py b/ruoyi-fastapi-backend/module_identity/service/interaction_service.py
index 48c5266d6..83a519d34 100644
--- a/ruoyi-fastapi-backend/module_identity/service/interaction_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/interaction_service.py
@@ -5,7 +5,7 @@
from collections.abc import Awaitable, Callable, Collection, Mapping
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, cast
from uuid import uuid4
from redis.asyncio import Redis
@@ -20,6 +20,7 @@
from module_admin.service.user_service import UserService
from module_identity.dao.identity_user_dao import IdentityUserDao
from module_identity.dao.oauth_client_dao import OAuthClientDao
+from module_identity.entity.types import InteractionAction, InteractionRecord
from module_identity.entity.vo.interaction_vo import (
CaptchaResponseModel,
ChangePasswordModel,
@@ -234,7 +235,7 @@ async def get(cls, redis: Redis, interaction_id: str, db: AsyncSession) -> dict[
return cls._page_projection(record, ttl, client, scopes)
@classmethod
- async def get_record(cls, redis: Redis, interaction_id: str) -> dict[str, Any]:
+ async def get_record(cls, redis: Redis, interaction_id: str) -> InteractionRecord:
"""
获取仅供后端状态处理使用的完整 Interaction 记录。
@@ -336,7 +337,7 @@ def verify_csrf(cls, record: Mapping[str, Any], csrf_token: str, *, pepper: str
return hmac.compare_digest(actual, stored)
@classmethod
- async def _get_record(cls, redis: Redis, interaction_id: str) -> dict[str, Any]:
+ async def _get_record(cls, redis: Redis, interaction_id: str) -> InteractionRecord:
"""
读取并校验后端完整记录。
@@ -369,7 +370,7 @@ async def _get_record(cls, redis: Redis, interaction_id: str) -> dict[str, Any]:
cls._validate_record(record)
except ValueError as exc:
raise OidcInteractionException(message='认证交互状态无效', error='server_error', status_code=500) from exc
- return record
+ return cast('InteractionRecord', record)
@classmethod
def _validate_record(cls, record: Mapping[str, Any]) -> None:
@@ -720,7 +721,7 @@ async def transition() -> None:
)
@staticmethod
- async def csrf_record(redis: Redis, interaction_id: str, csrf_token: str | None) -> dict[str, Any]:
+ async def csrf_record(redis: Redis, interaction_id: str, csrf_token: str | None) -> InteractionRecord:
"""
校验 CSRF 并返回交互记录。
@@ -738,7 +739,7 @@ async def csrf_record(redis: Redis, interaction_id: str, csrf_token: str | None)
return record
@staticmethod
- def require_status(record: dict[str, Any], expected: str) -> None:
+ def require_status(record: InteractionRecord, expected: str) -> None:
"""
校验业务前置条件。
@@ -821,7 +822,7 @@ async def reserve_completion(redis: Redis, interaction_id: str) -> str | None:
return marker if reserved else None
@staticmethod
- def interaction_result(interaction_id: str, next_action: str) -> InteractionResultModel:
+ def interaction_result(interaction_id: str, next_action: InteractionAction) -> InteractionResultModel:
"""
构建交互结果响应。
@@ -1061,6 +1062,7 @@ async def change_password(
user is None
or user.status != '0'
or user.del_flag != '0'
+ or user.password is None
or not PwdUtil.verify_password(body.old_password, user.password)
or not hmac.compare_digest(str(record.get('credentialProofHash') or ''), proof)
):
diff --git a/ruoyi-fastapi-backend/module_identity/service/key_service.py b/ruoyi-fastapi-backend/module_identity/service/key_service.py
index 6b4ef54de..c0624e707 100644
--- a/ruoyi-fastapi-backend/module_identity/service/key_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/key_service.py
@@ -4,7 +4,7 @@
from collections.abc import AsyncGenerator, Awaitable, Callable
from contextlib import asynccontextmanager
from datetime import datetime, timedelta
-from typing import Any, Literal, TypeVar
+from typing import Any, Literal, TypeVar, cast
from anyio import Path as AsyncPath
from cryptography.hazmat.primitives import serialization
@@ -190,7 +190,7 @@ async def load_private_key_async(
:raises KeyServiceError: 状态、来源、格式或公私钥不匹配
"""
cls._require_enabled(management=management)
- current = TimezoneUtil.to_optional_utc(now or TimezoneUtil.utc_now())
+ current = TimezoneUtil.to_utc(now or TimezoneUtil.utc_now())
cls._validate_record_window(record, current, require_active=require_active)
material = await cls._private_material_async(record, decrypt_private_key)
try:
@@ -267,7 +267,7 @@ async def build_jwks(cls, db: AsyncSession, *, now: datetime | None = None) -> d
:raises KeyServiceError: OIDC 关闭或公开密钥记录不合法
"""
cls._require_enabled()
- current = TimezoneUtil.to_optional_utc(now or TimezoneUtil.utc_now())
+ current = TimezoneUtil.to_utc(now or TimezoneUtil.utc_now())
records = await OidcKeyDao.list_published(db, now=current)
keys: list[dict[str, str]] = []
for record in records:
@@ -316,7 +316,7 @@ async def activate_key(
if not OidcUtil.is_valid_kid(kid):
raise KeyServiceError('签名密钥标识 kid 包含不允许的字符')
async with cls._rotation_lock(redis):
- current = TimezoneUtil.to_optional_utc(now or TimezoneUtil.utc_now())
+ current = TimezoneUtil.to_utc(now or TimezoneUtil.utc_now())
await OidcKeyDao.lock_algorithm_for_update(db, alg=RS256)
target = await OidcKeyDao.get_by_kid_for_update(db, kid)
if target is None or target.alg != RS256 or target.status != 'pending':
@@ -390,8 +390,8 @@ async def create_pending_key(
encryption_material = str(OidcConfig.oidc_signing_key_encryption_key or '').encode()
if len(encryption_material) < _MIN_ENCRYPTION_KEY_BYTES:
raise KeyServiceError('签名私钥加密密钥不能为空')
- current = TimezoneUtil.to_optional_utc(now or TimezoneUtil.utc_now())
- publish_at = TimezoneUtil.to_optional_utc(publish_at)
+ current = TimezoneUtil.to_utc(now or TimezoneUtil.utc_now())
+ publish_at = TimezoneUtil.to_utc(publish_at)
activate_at = TimezoneUtil.to_optional_utc(activate_at)
if activate_at is not None and activate_at < publish_at:
raise KeyServiceError('密钥生效时间不得早于发布时间')
@@ -456,7 +456,7 @@ async def bootstrap_signing_key(
:return: 签名密钥记录与本次是否创建新密钥
:raises KeyServiceError: 密钥配置、状态或材料不可用
"""
- current = TimezoneUtil.to_optional_utc(now or TimezoneUtil.utc_now())
+ current = TimezoneUtil.to_utc(now or TimezoneUtil.utc_now())
async with cls._rotation_lock(redis):
records = await OidcKeyDao.lock_algorithm_for_update(db, alg=RS256)
active = next(
@@ -464,8 +464,8 @@ async def bootstrap_signing_key(
row
for row in reversed(records)
if row.status == 'active'
- and TimezoneUtil.to_optional_utc(row.signing_start_at) is not None
- and TimezoneUtil.to_optional_utc(row.signing_start_at) <= current
+ and row.signing_start_at is not None
+ and TimezoneUtil.to_utc(row.signing_start_at) <= current
),
None,
)
@@ -526,7 +526,7 @@ async def retire_key(
cls._require_enabled(management=True)
if not OidcUtil.is_valid_kid(kid):
raise KeyServiceError('签名密钥标识 kid 包含不允许的字符')
- current = TimezoneUtil.to_optional_utc(now or TimezoneUtil.utc_now())
+ current = TimezoneUtil.to_utc(now or TimezoneUtil.utc_now())
record = await OidcKeyDao.get_by_kid_for_update(db, kid)
if record is None or record.status not in {'active', 'retiring'}:
raise KeyServiceError('签名密钥未处于活动状态')
@@ -584,7 +584,7 @@ async def activate_due(
:return: 本次成功激活的密钥数量
"""
cls._require_enabled()
- current = TimezoneUtil.to_optional_utc(now or TimezoneUtil.utc_now())
+ current = TimezoneUtil.to_utc(now or TimezoneUtil.utc_now())
pending = await OidcKeyDao.list_due_pending(db, now=current)
activated = 0
for record in pending:
@@ -676,18 +676,8 @@ def view(row: SysOidcSigningKey) -> dict[str, object]:
:param row: 签名密钥 ORM 记录
:return: 签名密钥管理视图字段映射
"""
- return OidcKeyViewModel(
- kid=row.kid,
- key_use=row.key_use,
- alg=row.alg,
- public_jwk=row.public_jwk,
- status=row.status,
- publish_at=TimezoneUtil.to_optional_utc(row.publish_at),
- signing_start_at=TimezoneUtil.to_optional_utc(row.signing_start_at),
- signing_stop_at=TimezoneUtil.to_optional_utc(row.signing_stop_at),
- remove_from_jwks_at=TimezoneUtil.to_optional_utc(row.remove_from_jwks_at),
- create_time=TimezoneUtil.to_optional_utc(row.create_time),
- ).model_dump(by_alias=True)
+ model = OidcKeyViewModel.model_validate(row)
+ return cast('dict[str, object]', model.model_dump(by_alias=True))
@classmethod
async def bootstrap(
diff --git a/ruoyi-fastapi-backend/module_identity/service/logout_confirmation_service.py b/ruoyi-fastapi-backend/module_identity/service/logout_confirmation_service.py
index 9bb45e401..d7c28b6a1 100644
--- a/ruoyi-fastapi-backend/module_identity/service/logout_confirmation_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/logout_confirmation_service.py
@@ -95,7 +95,15 @@ async def consume(
OidcUtil.logout_confirmation_digest(bound_sso, browser_nonce, pepper=OidcConfig.oidc_token_hash_pepper),
):
raise ValueError('退出确认的浏览器会话已变更,请重新发起退出')
- return record['parameters']
+ parameters = record['parameters']
+ if not isinstance(parameters, dict):
+ raise ValueError('退出确认参数无效')
+ result: dict[str, str] = {}
+ for key, value in parameters.items():
+ if not isinstance(key, str) or not isinstance(value, str):
+ raise ValueError('退出确认参数无效')
+ result[key] = value
+ return result
@classmethod
async def form_redirect_origin(cls, db: AsyncSession, parameters: dict[str, str]) -> str | None:
@@ -110,9 +118,11 @@ async def form_redirect_origin(cls, db: AsyncSession, parameters: dict[str, str]
"""
hint = parameters.get('id_token_hint')
uri = parameters.get('post_logout_redirect_uri')
- if not hint or not OidcUtil.is_safe_post_logout_uri(uri):
+ if not hint or not uri or not OidcUtil.is_safe_post_logout_uri(uri):
return None
parsed = urlsplit(uri)
+ if parsed.hostname is None:
+ return None
hostname = parsed.hostname.encode('idna').decode('ascii')
if not re.fullmatch(r'[A-Za-z0-9.:-]+', hostname):
return None
diff --git a/ruoyi-fastapi-backend/module_identity/service/oauth_management_service.py b/ruoyi-fastapi-backend/module_identity/service/oauth_management_service.py
index a96b4dc81..89cd015a7 100644
--- a/ruoyi-fastapi-backend/module_identity/service/oauth_management_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/oauth_management_service.py
@@ -16,6 +16,7 @@
from module_identity.dao.oauth_resource_dao import OAuthResourceDao
from module_identity.entity.do.oauth_client_do import SysOAuthClient, SysOAuthClientSecret, SysOAuthClientUri
from module_identity.entity.do.oauth_resource_do import SysOAuthResource, SysOAuthScope
+from module_identity.entity.types import ClientUriType
from module_identity.entity.vo.oauth_client_vo import (
ClientCreateModel,
ClientPageQueryModel,
@@ -129,7 +130,7 @@ async def _transaction(
_MAX_CLAIMS = 64
_MAX_CLAIM_NAME_LENGTH = 64
_MAX_CLIENT_ID_LENGTH = 64
- _URI_TYPES = (
+ _URI_TYPES: tuple[tuple[ClientUriType, str], ...] = (
('redirect', 'redirect_uris'),
('post_logout', 'post_logout_redirect_uris'),
('backchannel_logout', 'backchannel_logout_uris'),
@@ -260,7 +261,7 @@ def _validate_resource_ttls(cls, payload: ResourceCreateModel) -> None:
raise OAuthClientManagementError('资源访问令牌有效期超过平台上限')
@classmethod
- def _validate_uri(cls, uri_type: str, uri: str) -> str:
+ def _validate_uri(cls, uri_type: ClientUriType, uri: str) -> str:
"""
校验并规范化 Client 注册 URI。
@@ -986,7 +987,7 @@ async def detail(cls, db: AsyncSession, client_id: str) -> ClientViewModel:
if isinstance(role, str)
}
)
- uri_map = {uri_type: [] for uri_type, _ in cls._URI_TYPES}
+ uri_map: dict[str, list[str]] = {uri_type: [] for uri_type, _ in cls._URI_TYPES}
for row in uri_rows:
if row.status != '0':
continue
diff --git a/ruoyi-fastapi-backend/module_identity/service/runtime_service.py b/ruoyi-fastapi-backend/module_identity/service/runtime_service.py
index 95cb37868..aab5fb4c3 100644
--- a/ruoyi-fastapi-backend/module_identity/service/runtime_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/runtime_service.py
@@ -5,6 +5,7 @@
from time import monotonic
from fastapi import FastAPI
+from redis.asyncio import Redis
from sqlalchemy.ext.asyncio import AsyncSession
from common.constant import OidcAuditEvent
@@ -334,7 +335,7 @@ async def key_lifecycle_loop(cls, app: FastAPI) -> None:
logger.error('OIDC 签名密钥生命周期维护任务执行失败')
@staticmethod
- async def backchannel_retry_loop(redis: object) -> None:
+ async def backchannel_retry_loop(redis: Redis) -> None:
"""
运行 Back-Channel 重试后台循环。
diff --git a/ruoyi-fastapi-backend/module_identity/service/session_service.py b/ruoyi-fastapi-backend/module_identity/service/session_service.py
index 483580ca1..16236b089 100644
--- a/ruoyi-fastapi-backend/module_identity/service/session_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/session_service.py
@@ -6,12 +6,13 @@
from collections.abc import Awaitable, Callable, Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta
-from typing import Any
+from typing import Any, Literal, NotRequired, TypedDict, overload
from urllib.parse import urlsplit
from uuid import uuid4
import jwt
-from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
+from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey
+from jwt.algorithms import RSAAlgorithm
from redis.asyncio import Redis
from sqlalchemy.ext.asyncio import AsyncSession
@@ -60,6 +61,34 @@
_SESSION_STATUS_EXPIRED = 'expired'
+class SsoCookieParameters(TypedDict):
+ """
+ 写入或清除单点登录 Cookie 时使用的 HTTP 属性。
+
+ :ivar key: Cookie 名称
+ :ivar path: Cookie 生效路径
+ :ivar secure: 是否仅通过 HTTPS 传输
+ :ivar httponly: 是否禁止浏览器脚本读取
+ :ivar samesite: 跨站请求中的 Cookie 发送策略
+ """
+
+ key: str
+ path: str
+ secure: bool
+ httponly: bool
+ samesite: Literal['lax']
+
+
+class SsoSetCookieParameters(SsoCookieParameters):
+ """
+ 写入单点登录 Cookie 时可附带有效期。
+
+ :ivar max_age: 持久 Cookie 的最长有效秒数
+ """
+
+ max_age: NotRequired[int]
+
+
class SsoSessionError(ValueError):
"""SSO Session 创建、校验和撤销错误类型。"""
@@ -179,17 +208,13 @@ def _cache_payload(cls, row: SsoSessionSnapshot) -> dict[str, Any]:
'user_id': row.user_id,
'subject_id': row.subject_id,
'auth_version': row.auth_version,
- 'auth_time': TimezoneUtil.to_optional_utc(row.auth_time).isoformat()
- if TimezoneUtil.to_optional_utc(row.auth_time)
- else None,
- 'last_seen_at': TimezoneUtil.to_optional_utc(row.last_seen_at).isoformat()
- if TimezoneUtil.to_optional_utc(row.last_seen_at)
- else None,
- 'idle_expires_at': TimezoneUtil.to_optional_utc(row.idle_expires_at).isoformat()
- if TimezoneUtil.to_optional_utc(row.idle_expires_at)
+ 'auth_time': TimezoneUtil.to_utc(row.auth_time).isoformat() if row.auth_time is not None else None,
+ 'last_seen_at': TimezoneUtil.to_utc(row.last_seen_at).isoformat() if row.last_seen_at is not None else None,
+ 'idle_expires_at': TimezoneUtil.to_utc(row.idle_expires_at).isoformat()
+ if row.idle_expires_at is not None
else None,
- 'absolute_expires_at': TimezoneUtil.to_optional_utc(row.absolute_expires_at).isoformat()
- if TimezoneUtil.to_optional_utc(row.absolute_expires_at)
+ 'absolute_expires_at': TimezoneUtil.to_utc(row.absolute_expires_at).isoformat()
+ if row.absolute_expires_at is not None
else None,
'acr': row.acr,
'amr': row.amr,
@@ -818,7 +843,15 @@ def cookie_max_age(cls, session: SysSsoSession, *, now: datetime | None = None)
return cls._remaining_ttl(absolute, TimezoneUtil.to_optional_utc(now) or TimezoneUtil.utc_now())
@staticmethod
- def cookie_parameters(*, max_age: int | None = None) -> dict[str, str | bool | int]:
+ @overload
+ def cookie_parameters() -> SsoCookieParameters: ...
+
+ @staticmethod
+ @overload
+ def cookie_parameters(*, max_age: int | None) -> SsoSetCookieParameters: ...
+
+ @staticmethod
+ def cookie_parameters(*, max_age: int | None = None) -> SsoCookieParameters:
"""
根据配置构造 SSO Cookie 的 HTTP 属性。
@@ -832,7 +865,7 @@ def cookie_parameters(*, max_age: int | None = None) -> dict[str, str | bool | i
raise SsoSessionError('单点登录 Cookie 的安全配置无效')
if max_age is not None and (isinstance(max_age, bool) or not isinstance(max_age, int) or max_age <= 0):
raise SsoSessionError('单点登录 Cookie 的有效期无效')
- parameters: dict[str, str | bool | int] = {
+ parameters: SsoSetCookieParameters = {
'key': OidcConfig.oidc_sso_cookie_name,
'path': '/',
'secure': True,
@@ -1013,22 +1046,26 @@ async def _logout( # noqa: PLR0912, PLR0913, PLR0915
session = None
client = None
validated_redirect: str | None = None
- hint_valid = False
if id_token_hint:
try:
claims, client = await cls._validate_id_token_hint(db, id_token_hint, current)
- hint_valid = True
except (JwtProfileError, KeyServiceError, LogoutServiceError, TypeError, ValueError, jwt.PyJWTError):
client = None
- if hint_valid:
+ else:
sid = claims['sid']
session = await SsoSessionDao.get_by_sid(db, sid, for_update=True)
- if hint_valid and (
- session is None or session.status not in {'active', 'expired'} or session.subject_id != claims['sub']
+ if (
+ session is None
+ or session.status not in {'active', 'expired'}
+ or session.subject_id != claims['sub']
+ ):
+ session = None
+ client = None
+ if (
+ client is not None
+ and post_logout_redirect_uri
+ and OidcUtil.is_safe_post_logout_uri(post_logout_redirect_uri)
):
- session = None
- hint_valid = False
- if hint_valid and post_logout_redirect_uri and OidcUtil.is_safe_post_logout_uri(post_logout_redirect_uri):
registered = await OAuthClientDao.find_exact_uri(
db, client.client_pk, _URI_POST_LOGOUT, post_logout_redirect_uri
)
@@ -1036,7 +1073,7 @@ async def _logout( # noqa: PLR0912, PLR0913, PLR0915
validated_redirect = post_logout_redirect_uri
else:
state = None
- elif hint_valid and post_logout_redirect_uri:
+ elif client is not None and post_logout_redirect_uri:
state = None
browser_session = None
if cookie:
@@ -1114,7 +1151,9 @@ async def _validate_id_token_hint(cls, db: AsyncSession, token: str, now: dateti
if key_record is None or key_record.status not in _VERIFYING_KEY_STATUSES:
raise LogoutServiceError('签名密钥不存在或不可用')
public_jwk = OidcUtil.normalize_public_jwk(key_record)
- verification_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(public_jwk, separators=(',', ':')))
+ verification_key = RSAAlgorithm.from_jwk(json.dumps(public_jwk, separators=(',', ':')))
+ if not isinstance(verification_key, RSAPublicKey):
+ raise LogoutServiceError('签名公钥无效')
claims = decode_id_token_hint(
token,
verification_key=verification_key,
@@ -1343,6 +1382,8 @@ async def consume_backchannel_retry( # noqa: PLR0912, PLR0915
item: dict[str, Any] | None = None
try:
try:
+ if not isinstance(raw, (str, bytes)):
+ raise PermanentBackchannelError('invalid retry payload', '后端退出通知重试载荷无效')
item = json.loads(raw)
except (TypeError, UnicodeDecodeError, json.JSONDecodeError) as exc:
raise PermanentBackchannelError('invalid retry payload', '后端退出通知重试载荷无效') from exc
diff --git a/ruoyi-fastapi-backend/module_identity/service/token_protocol_service.py b/ruoyi-fastapi-backend/module_identity/service/token_protocol_service.py
index 0316790d8..a7b99b7ca 100644
--- a/ruoyi-fastapi-backend/module_identity/service/token_protocol_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/token_protocol_service.py
@@ -68,7 +68,7 @@ async def introspect(
now: datetime | None = None,
token_type_hint: str | None = None,
pepper: str | bytes | None = None,
- ) -> dict[str, Any]:
+ ) -> dict[str, object]:
"""
验证 Token 并生成 OAuth Introspection 响应。
@@ -117,7 +117,7 @@ async def _introspect_transaction(
now: datetime | None = None,
token_type_hint: str | None = None,
pepper: str | bytes | None = None,
- ) -> dict[str, Any]:
+ ) -> dict[str, object]:
"""
在事务边界内执行 Token 内省。
@@ -164,7 +164,7 @@ async def introspect_request(
verification_key: Any = None,
verification_key_loader: Callable[[AsyncSession, str], Awaitable[Any]] | None = None,
token_type_hint: str | None = None,
- ) -> dict[str, Any]:
+ ) -> dict[str, object]:
"""
认证调用 Client 并处理内省请求。
@@ -237,7 +237,7 @@ async def _introspect_access( # noqa: PLR0912
now: datetime,
verification_keys: Any,
verification_key: Any,
- ) -> dict[str, Any]:
+ ) -> dict[str, object]:
"""
验证 Access Token 并生成内省声明。
@@ -287,7 +287,7 @@ async def _introspect_access( # noqa: PLR0912
user_state = await cls._access_user_state(db, claims, issuer_client, resources, now)
if user_state is None:
return {'active': False}
- result: dict[str, Any] = {'active': True, 'token_type': 'Bearer'}
+ result: dict[str, object] = {'active': True, 'token_type': 'Bearer'}
for name in cls._STANDARD_CLAIMS:
if name in claims:
result[name] = claims[name]
@@ -400,7 +400,7 @@ async def _introspect_refresh(
caller: Any,
now: datetime,
pepper: str | bytes | None,
- ) -> dict[str, Any]:
+ ) -> dict[str, object]:
"""
验证 Refresh Token 并生成内省声明。
@@ -420,10 +420,7 @@ async def _introspect_refresh(
issuer_client = await OAuthClientDao.get_by_pk(db, row.client_pk, active_only=True)
if issuer_client is None or issuer_client.status != cls._ACTIVE_CLIENT_STATUS:
return {'active': False}
- if (
- TimezoneUtil.to_optional_utc(row.idle_expires_at) <= now
- or TimezoneUtil.to_optional_utc(row.absolute_expires_at) <= now
- ):
+ if TimezoneUtil.to_utc(row.idle_expires_at) <= now or TimezoneUtil.to_utc(row.absolute_expires_at) <= now:
return {'active': False}
if not await cls._refresh_family_active(db, row.family_id):
return {'active': False}
@@ -462,7 +459,7 @@ async def _introspect_refresh(
resources = OidcUtil.normalize_audiences(row.resources)
if not resources or not await cls._resources_owned_by_caller(db, resources, caller.client_pk):
return {'active': False}
- result: dict[str, Any] = {
+ result: dict[str, object] = {
'active': True,
'client_id': issuer_client.client_id,
'token_type': 'refresh_token',
@@ -519,7 +516,7 @@ def _grant_active(
and grant.client_pk == client.client_pk
and grant.status == cls._ACTIVE_GRANT_STATUS
and grant.client_policy_version == client.policy_version
- and (grant.expires_at is None or TimezoneUtil.to_optional_utc(grant.expires_at) > now)
+ and (grant.expires_at is None or TimezoneUtil.to_utc(grant.expires_at) > now)
and set(scopes).issubset(set(OidcUtil.json_list(grant.granted_scopes)))
and set(resources).issubset(set(OidcUtil.json_list(grant.granted_resources)))
)
diff --git a/ruoyi-fastapi-backend/module_identity/service/token_service.py b/ruoyi-fastapi-backend/module_identity/service/token_service.py
index 7ef64788f..7fe95da75 100644
--- a/ruoyi-fastapi-backend/module_identity/service/token_service.py
+++ b/ruoyi-fastapi-backend/module_identity/service/token_service.py
@@ -2,7 +2,7 @@
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta
-from typing import Any
+from typing import Any, Never
from uuid import uuid4
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
@@ -186,7 +186,7 @@ def capture_secret_match(secret_hash: str) -> None:
authorization,
client_id=client_id,
client_secret=client_secret,
- secret_hashes=secrets,
+ secret_hashes=(secret.secret_hash for secret in secrets),
secret_match_callback=capture_secret_match,
)
except (ClientAuthenticationError, TypeError, ValueError):
@@ -295,11 +295,13 @@ async def authorization_code(
raise
except (OAuthProtocolException, OpaqueTokenError, RedisError) as exc:
cls._map_oauth_failure(exc, 'invalid_grant')
- if code_payload.get('clientPk') != client_row.client_pk:
- cls._invalid_grant()
- if parsed.get('redirect_uri') != code_payload.get('redirectUri'):
+ if code_payload.get('clientPk') != client_row.client_pk or parsed.get('redirect_uri') != code_payload.get(
+ 'redirectUri'
+ ):
cls._invalid_grant()
verifier = parsed.get('code_verifier')
+ if not isinstance(verifier, str):
+ cls._invalid_grant()
try:
if not verify_code_challenge(verifier, code_payload['codeChallenge'], code_payload['codeChallengeMethod']):
cls._invalid_grant()
@@ -1029,7 +1031,7 @@ async def _require_grant(
or grant.client_pk != client_pk
or grant.status != cls._ACTIVE_GRANT_STATUS
or grant.client_policy_version != client.policy_version
- or (grant.expires_at is not None and TimezoneUtil.to_optional_utc(grant.expires_at) <= now)
+ or (grant.expires_at is not None and TimezoneUtil.to_utc(grant.expires_at) <= now)
or not set(scopes).issubset(set(grant.granted_scopes or []))
or not set(resources).issubset(set(grant.granted_resources or []))
):
@@ -1321,7 +1323,7 @@ def _numeric_time(value: datetime | None) -> int:
return int(current.timestamp())
@staticmethod
- def _map_oauth_failure(error: Exception, fallback: str) -> None:
+ def _map_oauth_failure(error: Exception, fallback: str) -> Never:
"""
将底层异常映射为 OAuth 协议错误。
@@ -1334,7 +1336,7 @@ def _map_oauth_failure(error: Exception, fallback: str) -> None:
raise OAuthProtocolException(fallback, 'The authorization grant is invalid or expired', 400) from None
@staticmethod
- def _invalid_request() -> None:
+ def _invalid_request() -> Never:
"""
抛出 invalid_request 协议错误。
@@ -1343,7 +1345,7 @@ def _invalid_request() -> None:
raise OAuthProtocolException('invalid_request', 'Invalid token request', 400)
@staticmethod
- def _invalid_client() -> None:
+ def _invalid_client() -> Never:
"""
抛出 invalid_client 协议错误。
@@ -1352,7 +1354,7 @@ def _invalid_client() -> None:
raise OAuthProtocolException('invalid_client', 'Client authentication failed', 401)
@staticmethod
- def _invalid_grant() -> None:
+ def _invalid_grant() -> Never:
"""
抛出 invalid_grant 协议错误。
@@ -1361,7 +1363,7 @@ def _invalid_grant() -> None:
raise OAuthProtocolException('invalid_grant', 'The authorization grant is invalid or expired', 400)
@staticmethod
- def _invalid_scope() -> None:
+ def _invalid_scope() -> Never:
"""
抛出 invalid_scope 协议错误。
@@ -1370,7 +1372,7 @@ def _invalid_scope() -> None:
raise OAuthProtocolException('invalid_scope', 'Requested scope is not authorized', 400)
@staticmethod
- def _server_error() -> None:
+ def _server_error() -> Never:
"""
抛出 server_error 协议错误。
diff --git a/ruoyi-fastapi-backend/module_plugin/controller/plugin_browser_controller.py b/ruoyi-fastapi-backend/module_plugin/controller/plugin_browser_controller.py
index 5515f9b7b..143cfc531 100644
--- a/ruoyi-fastapi-backend/module_plugin/controller/plugin_browser_controller.py
+++ b/ruoyi-fastapi-backend/module_plugin/controller/plugin_browser_controller.py
@@ -31,8 +31,11 @@ async def create_plugin_browser_session(
query_db: Annotated[AsyncSession, DBSessionDependency()],
) -> Response:
runtime = getattr(request.app.state, 'plugin_explicit_runtime', None)
- loaded = runtime.loaded.get(plugin_id) if isinstance(runtime, ExplicitPluginRuntime) else None
- if loaded is None or loaded.plugin.discovered_plugin.manifest.frontend.delivery.type != 'bundle':
+ if (
+ not isinstance(runtime, ExplicitPluginRuntime)
+ or (loaded := runtime.loaded.get(plugin_id)) is None
+ or loaded.plugin.discovered_plugin.manifest.frontend.delivery.type != 'bundle'
+ ):
raise HTTPException(status_code=404, detail=I18nMessage('插件页面不存在', msg_key='plugin.session.pageMissing'))
if not loaded.active or loaded.lifespan is None or not loaded.lifespan.ready:
raise HTTPException(status_code=503, detail=I18nMessage('插件页面尚未就绪', msg_key='plugin.session.notReady'))
diff --git a/ruoyi-fastapi-backend/module_plugin/controller/plugin_controller.py b/ruoyi-fastapi-backend/module_plugin/controller/plugin_controller.py
index 4e65e31d8..b8bfb1196 100644
--- a/ruoyi-fastapi-backend/module_plugin/controller/plugin_controller.py
+++ b/ruoyi-fastapi-backend/module_plugin/controller/plugin_controller.py
@@ -474,18 +474,16 @@ async def diagnose_system_plugin(
redis=getattr(request.app.state, 'redis', None),
ready_key=getattr(application_runtime, 'ready_key', None),
)
- logger.info(diagnose_plugin_result.get('message', '插件诊断包生成完成'))
+ default_message = I18nMessage('插件诊断包生成完成', msg_key='plugin.runtime.diagnostics.completed')
+ logger.info(diagnose_plugin_result.get('message', default_message))
if all(key in diagnose_plugin_result for key in ('info', 'check', 'config', 'menuPlan', 'audit')):
# 完整诊断包中的 ok=false 表示检查发现问题,仍需让页面读取其运行观测证据。
return ResponseUtil.success(
- msg=diagnose_plugin_result.get('message')
- or I18nMessage('插件诊断包生成完成', msg_key='plugin.runtime.diagnostics.completed'),
+ msg=PluginOperationResult.from_payload(diagnose_plugin_result, default_message=default_message).message,
data=_public_plugin_payload(diagnose_plugin_result),
)
- return _plugin_operation_response(
- diagnose_plugin_result, I18nMessage('插件诊断包生成完成', msg_key='plugin.runtime.diagnostics.completed')
- )
+ return _plugin_operation_response(diagnose_plugin_result, default_message)
@plugin_controller.get(
diff --git a/ruoyi-fastapi-backend/module_plugin/controller/plugin_metrics_controller.py b/ruoyi-fastapi-backend/module_plugin/controller/plugin_metrics_controller.py
index ae345135a..d859eaba1 100644
--- a/ruoyi-fastapi-backend/module_plugin/controller/plugin_metrics_controller.py
+++ b/ruoyi-fastapi-backend/module_plugin/controller/plugin_metrics_controller.py
@@ -50,9 +50,10 @@ async def get_plugin_config_status(
plugin_id: Annotated[str, Path(description='插件ID', pattern=r'^[a-z][a-z0-9_]{1,63}$')],
) -> Response:
payload = await get_plugin_runtime_service().get_plugin_config(plugin_id, reveal_secret=True)
- if not payload.get('ok'):
+ configs = payload.get('configs', [])
+ if not payload.get('ok') or not isinstance(configs, list):
return ResponseUtil.failure(msg_key='plugin.config.statusReadFailed')
- values = {item['key']: item.get('value') for item in payload.get('configs', [])}
+ values = {item['key']: item.get('value') for item in configs}
reporter = getattr(request.app.state, 'plugin_metrics_reporter', None)
report = await reporter.read(plugin_id) if isinstance(reporter, PluginMetricsReporter) else {'scope': 'unavailable'}
return ResponseUtil.success(data=build_config_status(plugin_id, config_revision(plugin_id, values), report))
diff --git a/ruoyi-fastapi-backend/module_plugin/service/plugin_service.py b/ruoyi-fastapi-backend/module_plugin/service/plugin_service.py
index 3a4772cbd..2c42fb3cc 100644
--- a/ruoyi-fastapi-backend/module_plugin/service/plugin_service.py
+++ b/ruoyi-fastapi-backend/module_plugin/service/plugin_service.py
@@ -1,5 +1,3 @@
-from typing import cast
-
from sqlalchemy.ext.asyncio import AsyncSession
from module_admin.dao.dict_dao import DictDataDao
@@ -50,13 +48,13 @@ async def diagnose_plugin_with_audit_services(
:param audit_limit: 最近审计记录数量
:return: 插件诊断包负载
"""
- payload = cast('dict[str, object]', await self.runtime_service.diagnose_plugin(plugin_id))
+ payload = await self.runtime_service.diagnose_plugin(plugin_id)
payload['audit'] = await self._build_recent_audit_snapshot(query_db, plugin_id, audit_limit=audit_limit)
- return cast('PluginDiagnoseResponse', payload)
+ return payload
@classmethod
- async def get_plugin_operation_dict_services(cls, query_db: AsyncSession) -> dict[str, str]:
+ async def get_plugin_operation_dict_services(cls, query_db: AsyncSession) -> dict[str, str | None]:
"""
获取插件管理页面使用的操作类型字典映射。
@@ -89,7 +87,7 @@ async def _build_recent_audit_snapshot(
"""
operation_logs = await PluginService.get_plugin_operation_log_export_list_services(
query_db,
- PluginOperationLogExportQueryModel(exportLimit=audit_limit * AUDIT_LOG_OVERFETCH_MULTIPLIER),
+ PluginOperationLogExportQueryModel(export_limit=audit_limit * AUDIT_LOG_OVERFETCH_MULTIPLIER),
)
return PluginAuditPayloadBuilder.build_recent_snapshot_payload(
plugin_id,
diff --git a/ruoyi-fastapi-backend/plugins/ai/controller/ai_model_controller.py b/ruoyi-fastapi-backend/plugins/ai/controller/ai_model_controller.py
index 9c1effdd2..1923cdf42 100644
--- a/ruoyi-fastapi-backend/plugins/ai/controller/ai_model_controller.py
+++ b/ruoyi-fastapi-backend/plugins/ai/controller/ai_model_controller.py
@@ -157,7 +157,7 @@ async def delete_ai_model(
for model_id in model_id_list:
if not current_user.user.admin:
await AiModelService.check_ai_model_data_scope_services(query_db, int(model_id), data_scope_sql)
- delete_ai_model = DeleteAiModelModel(modelIds=model_ids)
+ delete_ai_model = DeleteAiModelModel(model_ids=model_ids)
delete_ai_model_result = await AiModelService.delete_ai_model_services(query_db, delete_ai_model)
logger.info(delete_ai_model_result.message)
diff --git a/ruoyi-fastapi-backend/plugins/ai/dao/ai_model_dao.py b/ruoyi-fastapi-backend/plugins/ai/dao/ai_model_dao.py
index 71c450191..77644552d 100644
--- a/ruoyi-fastapi-backend/plugins/ai/dao/ai_model_dao.py
+++ b/ruoyi-fastapi-backend/plugins/ai/dao/ai_model_dao.py
@@ -1,6 +1,6 @@
from typing import Any
-from sqlalchemy import ColumnElement, delete, select, update
+from sqlalchemy import ColumnElement, delete, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
@@ -41,11 +41,11 @@ async def get_ai_model_list(
query = (
select(AiModels)
.where(
- AiModels.model_id == query_object.model_id if query_object.model_id else True,
- AiModels.model_name.like(f'%{query_object.model_name}%') if query_object.model_name else True,
- AiModels.model_code.like(f'%{query_object.model_code}%') if query_object.model_code else True,
- AiModels.provider == query_object.provider if query_object.provider else True,
- AiModels.status == query_object.status if query_object.status else True,
+ AiModels.model_id == query_object.model_id if query_object.model_id else true(),
+ AiModels.model_name.like(f'%{query_object.model_name}%') if query_object.model_name else true(),
+ AiModels.model_code.like(f'%{query_object.model_code}%') if query_object.model_code else true(),
+ AiModels.provider == query_object.provider if query_object.provider else true(),
+ AiModels.status == query_object.status if query_object.status else true(),
data_scope_sql,
)
.order_by(AiModels.model_sort)
diff --git a/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_chat_do.py b/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_chat_do.py
index 70fc8b69d..e2f3dedba 100644
--- a/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_chat_do.py
+++ b/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_chat_do.py
@@ -1,4 +1,5 @@
-from sqlalchemy import CHAR, BigInteger, Column, Float, Integer, Text
+from sqlalchemy import CHAR, BigInteger, Float, Integer, Text
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin
from config.database import Base
@@ -10,12 +11,18 @@ class AiChatConfig(AuditTimeMixin, Base):
__tablename__ = 'ai_chat_config'
__table_args__ = {'comment': 'AI对话配置表'}
- chat_config_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='配置主键')
- user_id = Column(BigInteger, nullable=False, unique=True, comment='用户ID')
- temperature = Column(Float, nullable=True, comment='默认温度')
- add_history_to_context = Column(CHAR(1), server_default='0', comment='是否添加历史记录(0是, 1否)')
- num_history_runs = Column(Integer, nullable=True, comment='历史记录条数')
- system_prompt = Column(Text, nullable=True, comment='系统提示词')
- metrics_default_visible = Column(CHAR(1), server_default='0', comment='默认显示指标(0是, 1否)')
- vision_enabled = Column(CHAR(1), server_default='1', comment='是否开启视觉(0是, 1否)')
- image_max_size_mb = Column(Integer, nullable=True, comment='图片最大大小(MB)')
+ chat_config_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='配置主键'
+ )
+ user_id: Mapped[int] = mapped_column(BigInteger, nullable=False, unique=True, comment='用户ID')
+ temperature: Mapped[float | None] = mapped_column(Float, nullable=True, comment='默认温度')
+ add_history_to_context: Mapped[str | None] = mapped_column(
+ CHAR(1), server_default='0', comment='是否添加历史记录(0是, 1否)'
+ )
+ num_history_runs: Mapped[int | None] = mapped_column(Integer, nullable=True, comment='历史记录条数')
+ system_prompt: Mapped[str | None] = mapped_column(Text, nullable=True, comment='系统提示词')
+ metrics_default_visible: Mapped[str | None] = mapped_column(
+ CHAR(1), server_default='0', comment='默认显示指标(0是, 1否)'
+ )
+ vision_enabled: Mapped[str | None] = mapped_column(CHAR(1), server_default='1', comment='是否开启视觉(0是, 1否)')
+ image_max_size_mb: Mapped[int | None] = mapped_column(Integer, nullable=True, comment='图片最大大小(MB)')
diff --git a/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_model_do.py b/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_model_do.py
index 0b91ce90f..af899e886 100644
--- a/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_model_do.py
+++ b/ruoyi-fastapi-backend/plugins/ai/entity/do/ai_model_do.py
@@ -1,4 +1,5 @@
-from sqlalchemy import CHAR, BigInteger, Column, Float, Integer, String
+from sqlalchemy import CHAR, BigInteger, Float, Integer, String
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin
from config.database import Base
@@ -12,44 +13,46 @@ class AiModels(AuditTimeMixin, Base):
__tablename__ = 'ai_models'
__table_args__ = {'comment': 'AI模型表'}
- model_id = Column(BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='模型主键')
- model_code = Column(String(100), nullable=False, comment='模型编码')
- model_name = Column(
+ model_id: Mapped[int] = mapped_column(
+ BigInteger, primary_key=True, nullable=False, autoincrement=True, comment='模型主键'
+ )
+ model_code: Mapped[str] = mapped_column(String(100), nullable=False, comment='模型编码')
+ model_name: Mapped[str | None] = mapped_column(
String(100),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='模型名称',
)
- provider = Column(String(50), nullable=False, comment='提供商')
- model_sort = Column(Integer, nullable=False, comment='显示顺序')
- api_key = Column(
+ provider: Mapped[str] = mapped_column(String(50), nullable=False, comment='提供商')
+ model_sort: Mapped[int] = mapped_column(Integer, nullable=False, comment='显示顺序')
+ api_key: Mapped[str | None] = mapped_column(
String(255),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='接口访问密钥',
)
- base_url = Column(
+ base_url: Mapped[str | None] = mapped_column(
String(255),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='服务基础地址',
)
- model_type = Column(
+ model_type: Mapped[str | None] = mapped_column(
String(50),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
comment='模型类型',
)
- max_tokens = Column(Integer, nullable=True, comment='最大输出token')
- temperature = Column(Float, nullable=True, comment='默认温度')
- support_reasoning = Column(CHAR(1), server_default='N', comment='是否支持推理')
- support_images = Column(CHAR(1), server_default='N', comment='是否支持图片')
- status = Column(CHAR(1), server_default='0', comment='模型状态')
- user_id = Column(BigInteger, nullable=True, comment='用户ID')
- dept_id = Column(BigInteger, nullable=True, comment='部门ID')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- remark = Column(
+ max_tokens: Mapped[int | None] = mapped_column(Integer, nullable=True, comment='最大输出token')
+ temperature: Mapped[float | None] = mapped_column(Float, nullable=True, comment='默认温度')
+ support_reasoning: Mapped[str | None] = mapped_column(CHAR(1), server_default='N', comment='是否支持推理')
+ support_images: Mapped[str | None] = mapped_column(CHAR(1), server_default='N', comment='是否支持图片')
+ status: Mapped[str | None] = mapped_column(CHAR(1), server_default='0', comment='模型状态')
+ user_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='用户ID')
+ dept_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment='部门ID')
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ remark: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
diff --git a/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_chat_vo.py b/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_chat_vo.py
index 969be1f18..27344457d 100644
--- a/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_chat_vo.py
+++ b/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_chat_vo.py
@@ -1,16 +1,14 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import Field
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
-class AiChatRequestModel(BaseModel):
+class AiChatRequestModel(CamelModel):
"""AI对话请求模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
session_id: str | None = Field(default=None, description='会话ID')
model_id: int = Field(description='模型ID')
message: str = Field(description='用户消息')
@@ -18,11 +16,9 @@ class AiChatRequestModel(BaseModel):
images: list[str] | None = Field(default=None, description='图片URL列表')
-class AiChatConfigModel(BaseModel):
+class AiChatConfigModel(CamelModel):
"""AI对话配置模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
chat_config_id: int | None = Field(default=None, description='配置主键')
user_id: int | None = Field(default=None, description='用户ID')
temperature: float | None = Field(default=None, description='默认温度')
@@ -36,11 +32,9 @@ class AiChatConfigModel(BaseModel):
update_time: ApiUtcDateTime | None = Field(default=None, description='更新时间')
-class AiChatSessionBaseModel(BaseModel):
+class AiChatSessionBaseModel(CamelModel):
"""AI对话会话基础模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
session_id: str = Field(description='会话ID')
session_title: str | None = Field(default=None, description='会话标题')
session_type: str | None = Field(default=None, description='会话类型')
@@ -49,31 +43,25 @@ class AiChatSessionBaseModel(BaseModel):
updated_at: ApiUtcDateTime | None = Field(default=None, description='更新时间')
-class ModelInfoModel(BaseModel):
+class ModelInfoModel(CamelModel):
"""对话会话数据模型-模型信息模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
id: str | None = Field(default=None, description='模型ID')
name: str | None = Field(default=None, description='模型名称')
provider: str | None = Field(default=None, description='模型提供者')
temperature: float | None = Field(default=None, description='模型温度')
-class AgentDataModel(BaseModel):
+class AgentDataModel(CamelModel):
"""对话会话数据模型-智能体数据模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
model: ModelInfoModel | None = Field(default=None, description='模型信息')
agent_id: str | None = Field(default=None, description='智能体ID')
-class SessionMetricsModel(BaseModel):
+class SessionMetricsModel(CamelModel):
"""对话会话数据模型-会话指标模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
cost: float | None = Field(default=None, description='成本(元)')
timer: float | None = Field(default=None, description='运行时长(秒)')
duration: float | None = Field(default=None, description='运行时长(秒)')
@@ -91,20 +79,16 @@ class SessionMetricsModel(BaseModel):
time_to_first_token: float | None = Field(default=None, description='到第一个Token的时间(秒)')
-class SessionDataModel(BaseModel):
+class SessionDataModel(CamelModel):
"""对话会话数据模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
session_state: dict | None = Field(default=None, description='会话状态')
session_metrics: SessionMetricsModel | None = Field(default=None, description='会话指标')
-class MessageMetrics(BaseModel):
+class MessageMetrics(CamelModel):
"""对话消息模型-消息指标模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
input_tokens: int | None = Field(default=None, description='输入Token数量')
total_tokens: int | None = Field(default=None, description='总Token数量')
output_tokens: int | None = Field(default=None, description='输出Token数量')
@@ -113,11 +97,9 @@ class MessageMetrics(BaseModel):
time_to_first_token: float | None = Field(default=None, description='到第一个Token的时间(秒)')
-class ChatMessageModel(BaseModel):
+class ChatMessageModel(CamelModel):
"""对话消息模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
id: str | None = Field(default=None, description='消息ID')
role: str | None = Field(default=None, description='角色')
content: str | None = Field(default=None, description='内容')
@@ -132,8 +114,6 @@ class ChatMessageModel(BaseModel):
class AiChatSessionModel(AiChatSessionBaseModel):
"""AI对话会话模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
agent_id: str | None = Field(default=None, description='智能体ID')
session_data: SessionDataModel | None = Field(default=None, description='会话数据')
agent_data: AgentDataModel | None = Field(default=None, description='智能体数据')
diff --git a/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_model_vo.py b/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_model_vo.py
index e4c164df1..803e13f3c 100644
--- a/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_model_vo.py
+++ b/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_model_vo.py
@@ -1,17 +1,17 @@
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field
from pydantic_validation_decorator import NotBlank, Size
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from i18n.message import I18nMessage
-class AiModelModel(BaseModel):
+class AiModelModel(CamelModel):
"""AI模型表对应pydantic模型。"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
model_id: int | None = Field(default=None, description='模型主键')
model_code: str | None = Field(default=None, description='模型编码')
@@ -72,9 +72,7 @@ class AiModelPageQueryModel(AiModelModel):
page_size: int = Field(default=10, description='每页记录数')
-class DeleteAiModelModel(BaseModel):
+class DeleteAiModelModel(CamelModel):
"""删除AI模型模型。"""
- model_config = ConfigDict(alias_generator=to_camel)
-
model_ids: str = Field(description='需要删除的模型主键')
diff --git a/ruoyi-fastapi-backend/plugins/ai/service/ai_chat_service.py b/ruoyi-fastapi-backend/plugins/ai/service/ai_chat_service.py
index 95f20c59e..09ebb3979 100644
--- a/ruoyi-fastapi-backend/plugins/ai/service/ai_chat_service.py
+++ b/ruoyi-fastapi-backend/plugins/ai/service/ai_chat_service.py
@@ -1,16 +1,16 @@
import json
import os
import uuid
-from collections.abc import AsyncGenerator, AsyncIterator
+from collections.abc import AsyncGenerator, AsyncIterator, Sequence
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from agno.agent import Agent
from agno.db.base import SessionType
from agno.media import Image
-from agno.run.agent import RunEvent, RunOutput, RunOutputEvent
+from agno.run.agent import RunEvent, RunOutputEvent
from agno.run.cancel import acancel_run
-from agno.session import Session
+from agno.session import AgentSession
from sqlalchemy.ext.asyncio import AsyncSession
from common.context import LocaleContext, RequestContext
@@ -20,6 +20,7 @@
from i18n.translator import I18nUtil
from plugins.ai.dao.ai_chat_dao import AiChatConfigDao
from plugins.ai.dao.ai_model_dao import AiModelDao
+from plugins.ai.entity.do.ai_model_do import AiModels
from plugins.ai.entity.vo.ai_chat_vo import (
AgentDataModel,
AiChatConfigModel,
@@ -31,22 +32,19 @@
SessionDataModel,
SessionMetricsModel,
)
-from plugins.ai.entity.vo.ai_model_vo import AiModelModel
from plugins.ai.utils.ai_util import AiUtil
from utils.common_util import CamelCaseUtil
from utils.crypto_util import CryptoUtil
if TYPE_CHECKING:
from agno.models.message import Message
- from agno.run.team import TeamRunOutput
- from agno.run.workflow import WorkflowRunOutput
class AiChatService:
"""AI对话服务层。"""
@classmethod
- def _resolve_temperature(cls, user_config: AiChatConfigModel, model_config: AiModelModel) -> float:
+ def _resolve_temperature(cls, user_config: AiChatConfigModel, model_config: AiModels) -> float | None:
"""
解析温度配置,优先级为 用户配置 > 模型配置。
@@ -54,11 +52,10 @@ def _resolve_temperature(cls, user_config: AiChatConfigModel, model_config: AiMo
:param model_config: 模型配置对象
:return: 解析后的温度值
"""
- temperature = user_config.temperature or model_config.temperature
- return temperature
+ return model_config.temperature if user_config.temperature is None else user_config.temperature
@classmethod
- def _resolve_is_reasoning(cls, chat_req: AiChatRequestModel, model_config: AiModelModel) -> bool:
+ def _resolve_is_reasoning(cls, chat_req: AiChatRequestModel, model_config: AiModels) -> bool:
"""
解析深度思考开关,结合请求参数与模型配置确定最终是否开启。
@@ -86,8 +83,8 @@ def _resolve_history_config(cls, user_config: AiChatConfigModel) -> tuple[bool,
@classmethod
def _build_agent(
cls,
- model_config: AiModelModel,
- temperature: float,
+ model_config: AiModels,
+ temperature: float | None,
system_prompt: str | None,
user_id: int,
session_id: str,
@@ -106,7 +103,7 @@ def _build_agent(
:param num_history: 历史消息轮数
:return: Agent对象
"""
- real_api_key = CryptoUtil.decrypt(model_config.api_key)
+ real_api_key = CryptoUtil.decrypt(model_config.api_key) if model_config.api_key else model_config.api_key
model = AiUtil.get_model_from_factory(
provider=model_config.provider,
@@ -180,7 +177,7 @@ def _resolve_upload_image_path(cls, image_path: str | None) -> str | None:
return abs_path
@classmethod
- def _convert_images_to_upload_paths(cls, images: list[Image] | None) -> list[str] | None:
+ def _convert_images_to_upload_paths(cls, images: Sequence[Image] | None) -> list[str] | None:
"""
将Agno Image对象列表转换为前端可访问的上传路径列表。
@@ -207,9 +204,9 @@ def _convert_images_to_upload_paths(cls, images: list[Image] | None) -> list[str
full_url = f'{UploadConfig.UPLOAD_PREFIX}/{url_path}'.replace('//', '/')
result.append(full_url)
else:
- result.append(img.filepath)
+ result.append(os.fspath(img.filepath))
except Exception:
- result.append(img.filepath)
+ result.append(os.fspath(img.filepath))
# 如果是URL
elif hasattr(img, 'url') and img.url:
result.append(img.url)
@@ -238,8 +235,6 @@ async def _stream_agent(
:yield: SSE消息生成器
"""
locale_context = locale_context or RequestContext.get_current_locale()
- full_response = ''
- full_reasoning = ''
try:
yield json.dumps({'session_id': session_id, 'type': 'meta'}) + '\n'
@@ -254,23 +249,18 @@ async def _stream_agent(
if chunk.event == RunEvent.run_content:
content = chunk.content
- if hasattr(chunk, 'reasoning_content') and chunk.reasoning_content:
- reasoning = chunk.reasoning_content
+ reasoning = getattr(chunk, 'reasoning_content', None)
if reasoning and is_reasoning:
- full_reasoning += reasoning
yield json.dumps({'content': reasoning, 'type': 'reasoning'}) + '\n'
- if chunk.event == RunEvent.run_completed and chunk.metrics:
+ if chunk.event == RunEvent.run_completed and (metrics := getattr(chunk, 'metrics', None)):
yield (
- json.dumps(
- {'metrics': CamelCaseUtil.transform_result(chunk.metrics.to_dict()), 'type': 'metrics'}
- )
+ json.dumps({'metrics': CamelCaseUtil.transform_result(metrics.to_dict()), 'type': 'metrics'})
+ '\n'
)
if content:
- full_response += content
yield json.dumps({'content': content, 'type': 'content'}) + '\n'
except Exception as e:
yield cls._stream_error(e, locale_context)
@@ -334,10 +324,9 @@ async def _chat_services(
:yield: 对话响应流
:raises ServiceException: 模型不存在;模型已停用
"""
- ai_model = await AiModelDao.get_ai_model_detail_by_id(query_db, chat_req.model_id)
- if ai_model is None:
+ model_config = await AiModelDao.get_ai_model_detail_by_id(query_db, chat_req.model_id)
+ if model_config is None:
raise ServiceException(message='模型不存在', msg_key='ai.model.notFound', domain='plugin.ai')
- model_config = AiModelModel(**CamelCaseUtil.transform_result(ai_model))
if model_config.status != '0':
raise ServiceException(message='模型已停用', msg_key='ai.model.disabled', domain='plugin.ai')
@@ -428,6 +417,18 @@ async def save_ai_chat_config_services(
return CrudResponseModel(is_success=True, message='保存成功', msg_key='common.saved')
+ @staticmethod
+ def _session_title(session: AgentSession) -> str:
+ """
+ 从首次运行的输入生成会话标题。
+
+ :param session: 智能体会话
+ :return: 会话标题,无输入时返回空字符串
+ """
+ if not session.runs or session.runs[0].input is None:
+ return ''
+ return session.runs[0].input.input_content_string()[:20] + '...'
+
@classmethod
async def get_chat_session_list_services(cls, user_id: int) -> list[AiChatSessionBaseModel]:
"""
@@ -438,7 +439,7 @@ async def get_chat_session_list_services(cls, user_id: int) -> list[AiChatSessio
"""
# 获取Agno会话列表
storage = AiUtil.get_storage_engine()
- sessions: list[Session] = await storage.get_sessions(
+ sessions = await storage.get_sessions(
user_id=str(user_id),
component_id='chat-agent',
session_type=SessionType.AGENT,
@@ -446,25 +447,24 @@ async def get_chat_session_list_services(cls, user_id: int) -> list[AiChatSessio
result = []
for s in sessions:
+ if not isinstance(s, AgentSession):
+ continue
created_at = datetime.fromtimestamp(s.created_at, tz=UTC) if s.created_at else None
updated_at = datetime.fromtimestamp(s.updated_at, tz=UTC) if s.updated_at else None
- title_limit = 20
- session_title = s.runs[0].input.input_content[:title_limit] + '...' if s.runs else ''
-
result.append(
AiChatSessionBaseModel(
- sessionId=s.session_id,
- sessionTitle=session_title if len(session_title) <= title_limit else session_title[:title_limit],
- userId=s.user_id,
- createdAt=created_at,
- updatedAt=updated_at,
+ session_id=s.session_id,
+ session_title=cls._session_title(s)[:20],
+ user_id=s.user_id,
+ created_at=created_at,
+ updated_at=updated_at,
)
)
return result
@classmethod
- async def _get_owned_session(cls, storage: Any, session_id: str, user_id: int) -> Session:
+ async def _get_owned_session(cls, storage: Any, session_id: str, user_id: int) -> AgentSession:
"""
获取并校验当前用户拥有的会话。
@@ -474,7 +474,7 @@ async def _get_owned_session(cls, storage: Any, session_id: str, user_id: int) -
:return: 会话对象
:raises ServiceException: 会话不存在;无权访问该会话
"""
- session: Session | None = await storage.get_session(session_id=session_id, session_type=SessionType.AGENT)
+ session: AgentSession | None = await storage.get_session(session_id=session_id, session_type=SessionType.AGENT)
if not session:
raise ServiceException(message='会话不存在', msg_key='identity.session.notFound')
if str(session.user_id) != str(user_id):
@@ -511,27 +511,22 @@ async def get_chat_session_detail_services(cls, session_id: str, user_id: int) -
storage = AiUtil.get_storage_engine()
session = await cls._get_owned_session(storage, session_id, user_id)
- session_data: dict[str, Any] = session.session_data
- agent_data: dict[str, Any] = session.agent_data
- runs: list[RunOutput | TeamRunOutput | WorkflowRunOutput] = session.runs
+ session_data = session.session_data or {}
+ agent_data = session.agent_data or {}
messages: list[Message] = session.get_messages(skip_roles=['system'])
run_metrics_map = {}
- if runs:
- for run in runs:
- if run.model_provider_data and (provider_id := run.model_provider_data.get('id')):
- run_metrics_map[provider_id] = run.metrics
+ for run in session.runs or []:
+ if run.model_provider_data and (provider_id := run.model_provider_data.get('id')):
+ run_metrics_map[provider_id] = run.metrics
chat_messages = []
for m in messages:
- if hasattr(m, 'provider_data') and m.provider_data:
- provider_id = m.provider_data.get('id')
- if provider_id and provider_id in run_metrics_map:
- m.metrics = run_metrics_map[provider_id]
-
+ provider_id = m.provider_data.get('id') if m.provider_data else None
+ metrics = run_metrics_map.get(provider_id, m.metrics) if provider_id else m.metrics
metrics_model = None
- if getattr(m, 'metrics', None) and hasattr(m.metrics, 'to_dict'):
- metrics_dict = m.metrics.to_dict()
+ if metrics is not None:
+ metrics_dict = metrics.to_dict()
if metrics_dict:
metrics_model = MessageMetrics(**CamelCaseUtil.transform_result(metrics_dict))
@@ -539,30 +534,30 @@ async def get_chat_session_detail_services(cls, session_id: str, user_id: int) -
ChatMessageModel(
id=m.id,
role=m.role,
- content=m.content,
+ content=m.get_content_string() if isinstance(m.content, list) else m.content,
images=cls._convert_images_to_upload_paths(m.images),
metrics=metrics_model,
- createdAt=datetime.fromtimestamp(m.created_at, tz=UTC) if m.created_at else None,
- reasoningContent=m.reasoning_content,
- fromHistory=m.from_history,
- stopAfterToolCall=m.stop_after_tool_call,
+ created_at=datetime.fromtimestamp(m.created_at, tz=UTC) if m.created_at else None,
+ reasoning_content=m.reasoning_content,
+ from_history=m.from_history,
+ stop_after_tool_call=m.stop_after_tool_call,
)
)
session_detail = AiChatSessionModel(
- sessionId=session.session_id,
- sessionTitle=session.runs[0].input.input_content[:20] + '...' if session.runs else '',
- userId=session.user_id,
- createdAt=datetime.fromtimestamp(session.created_at, tz=UTC) if session.created_at else None,
- updatedAt=datetime.fromtimestamp(session.updated_at, tz=UTC) if session.updated_at else None,
- agentId=session.agent_id,
- sessionData=SessionDataModel(
- sessionState=session_data.get('session_state'),
- sessionMetrics=SessionMetricsModel(
+ session_id=session.session_id,
+ session_title=cls._session_title(session),
+ user_id=session.user_id,
+ created_at=datetime.fromtimestamp(session.created_at, tz=UTC) if session.created_at else None,
+ updated_at=datetime.fromtimestamp(session.updated_at, tz=UTC) if session.updated_at else None,
+ agent_id=session.agent_id,
+ session_data=SessionDataModel(
+ session_state=session_data.get('session_state'),
+ session_metrics=SessionMetricsModel(
**CamelCaseUtil.transform_result(session_data.get('session_metrics'))
),
),
- agentData=AgentDataModel(**CamelCaseUtil.transform_result(agent_data)),
+ agent_data=AgentDataModel(**CamelCaseUtil.transform_result(agent_data)),
messages=chat_messages,
)
@@ -595,11 +590,13 @@ async def _user_owns_run(cls, run_id: str, user_id: int) -> bool:
:return: 是否属于当前用户
"""
storage = AiUtil.get_storage_engine()
- sessions: list[Session] = await storage.get_sessions(
+ sessions = await storage.get_sessions(
user_id=str(user_id),
session_type=SessionType.AGENT,
)
for session in sessions:
+ if not isinstance(session, AgentSession):
+ continue
for run in session.runs or []:
if str(getattr(run, 'run_id', '') or getattr(run, 'id', '')) == str(run_id):
return True
diff --git a/ruoyi-fastapi-backend/plugins/ai/service/ai_model_service.py b/ruoyi-fastapi-backend/plugins/ai/service/ai_model_service.py
index f92501d00..d8e78e03d 100644
--- a/ruoyi-fastapi-backend/plugins/ai/service/ai_model_service.py
+++ b/ruoyi-fastapi-backend/plugins/ai/service/ai_model_service.py
@@ -1,4 +1,4 @@
-from typing import Any
+from typing import Any, Literal, overload
from sqlalchemy import ColumnElement
from sqlalchemy.ext.asyncio import AsyncSession
@@ -14,6 +14,26 @@
class AiModelService:
"""AI模型管理服务层。"""
+ @classmethod
+ @overload
+ async def get_ai_model_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: AiModelPageQueryModel,
+ data_scope_sql: ColumnElement,
+ is_page: Literal[True],
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_ai_model_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: AiModelPageQueryModel,
+ data_scope_sql: ColumnElement,
+ is_page: Literal[False] = False,
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_ai_model_list_services(
cls,
@@ -44,7 +64,7 @@ async def get_ai_model_list_services(
async def check_ai_model_data_scope_services(
cls,
query_db: AsyncSession,
- model_id: int,
+ model_id: int | None,
data_scope_sql: ColumnElement,
) -> CrudResponseModel:
"""
@@ -56,8 +76,10 @@ async def check_ai_model_data_scope_services(
:return: 校验结果
:raises ServiceException: 没有权限访问AI模型数据
"""
+ if model_id is None:
+ raise ServiceException(message='AI模型不存在', msg_key='ai.model.missing', domain='plugin.ai')
ai_models = await AiModelDao.get_ai_model_list(
- query_db, AiModelModel(modelId=model_id), data_scope_sql, is_page=False
+ query_db, AiModelPageQueryModel(model_id=model_id), data_scope_sql, is_page=False
)
if ai_models:
return CrudResponseModel(is_success=True, message='校验通过', msg_key='common.validated')
@@ -102,6 +124,8 @@ async def edit_ai_model_services(cls, query_db: AsyncSession, page_object: AiMod
else:
edit_ai_model['api_key'] = CryptoUtil.encrypt(page_object.api_key)
+ if page_object.model_id is None:
+ raise ServiceException(message='AI模型不存在', msg_key='ai.model.missing', domain='plugin.ai')
ai_model_info = await cls.ai_model_detail_services(query_db, page_object.model_id)
if ai_model_info.model_id:
try:
@@ -131,7 +155,7 @@ async def delete_ai_model_services(
model_id_list = page_object.model_ids.split(',')
try:
for model_id in model_id_list:
- await AiModelDao.delete_ai_model_dao(query_db, AiModelModel(modelId=model_id))
+ await AiModelDao.delete_ai_model_dao(query_db, AiModelModel(model_id=model_id))
await query_db.commit()
return CrudResponseModel(is_success=True, message='删除成功', msg_key='common.deleted')
except Exception as e:
diff --git a/ruoyi-fastapi-backend/plugins/ai/utils/ai_util.py b/ruoyi-fastapi-backend/plugins/ai/utils/ai_util.py
index 30b33a697..10eb940bd 100644
--- a/ruoyi-fastapi-backend/plugins/ai/utils/ai_util.py
+++ b/ruoyi-fastapi-backend/plugins/ai/utils/ai_util.py
@@ -1,13 +1,16 @@
import ipaddress
from importlib import import_module
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, cast
from urllib.parse import urlparse
from config.database import DataSourceRegistry
from config.env import DataBaseConfig
if TYPE_CHECKING:
- from agno.db.base import AsyncBaseDb
+ from collections.abc import Callable
+
+ from agno.db.mysql import AsyncMySQLDb
+ from agno.db.postgres import AsyncPostgresDb
from agno.models.base import Model
# 提供商名称 -> (模块路径, 类名) 的映射,延迟导入避免启动时加载所有AI SDK
@@ -58,15 +61,15 @@
}
# 已加载的提供商类缓存,避免重复import_module
-_provider_class_cache: dict[str, 'type[Model]'] = {}
-_storage_class_cache: dict[str, 'type[AsyncBaseDb]'] = {}
+_provider_class_cache: dict[str, 'Callable[..., Model]'] = {}
+_storage_class_cache: dict[str, 'type[AsyncMySQLDb] | type[AsyncPostgresDb]'] = {}
class AiUtil:
"""AI工具类。"""
@classmethod
- def _resolve_provider_class(cls, provider: str) -> 'type[Model] | None':
+ def _resolve_provider_class(cls, provider: str) -> 'Callable[..., Model] | None':
"""
按需加载并缓存提供商模型类。
@@ -84,7 +87,7 @@ def _resolve_provider_class(cls, provider: str) -> 'type[Model] | None':
return provider_cls
@classmethod
- def _resolve_storage_class(cls, db_type: str) -> 'type[AsyncBaseDb]':
+ def _resolve_storage_class(cls, db_type: str) -> 'type[AsyncMySQLDb] | type[AsyncPostgresDb]':
"""
按需加载并缓存存储引擎类。
@@ -98,12 +101,14 @@ def _resolve_storage_class(cls, db_type: str) -> 'type[AsyncBaseDb]':
# 默认使用MySQL
entry = _STORAGE_ENGINE_REGISTRY['mysql']
module_path, class_name = entry
- storage_cls = getattr(import_module(module_path), class_name)
+ storage_cls = cast(
+ 'type[AsyncMySQLDb] | type[AsyncPostgresDb]', getattr(import_module(module_path), class_name)
+ )
_storage_class_cache[db_type] = storage_cls
return storage_cls
@classmethod
- def get_storage_engine(cls) -> 'AsyncBaseDb':
+ def get_storage_engine(cls) -> 'AsyncMySQLDb | AsyncPostgresDb':
"""
获取存储引擎实例。
diff --git a/ruoyi-fastapi-backend/plugins/core/artifacts/package.py b/ruoyi-fastapi-backend/plugins/core/artifacts/package.py
index a139f93d9..31c62b5fd 100644
--- a/ruoyi-fastapi-backend/plugins/core/artifacts/package.py
+++ b/ruoyi-fastapi-backend/plugins/core/artifacts/package.py
@@ -7,7 +7,7 @@
import tempfile
from collections.abc import Mapping
from pathlib import Path
-from typing import BinaryIO
+from typing import IO
from zipfile import ZIP_DEFLATED, ZIP_STORED, BadZipFile, ZipFile, ZipInfo
import yaml
@@ -30,7 +30,8 @@
from plugins.core.artifacts.schema import (
private_key as load_private_key,
)
-from plugins.core.manifest.schema import EXPLICIT_MANIFEST_VERSION, PluginManifest, PluginManifestFactory
+from plugins.core.manifest.schema import EXPLICIT_MANIFEST_VERSION, PluginManifestFactory
+from plugins.core.manifest.v2 import VersionedPluginManifest
CHUNK_BYTES = 1024 * 1024
ZIP_END = struct.Struct('<4s4H2LH')
@@ -163,7 +164,7 @@ def _scan_directory(
return files, directories
-def _read_limited(stream: BinaryIO, maximum: int) -> bytes:
+def _read_limited(stream: IO[bytes], maximum: int) -> bytes:
"""
在指定字节上限内读取完整文档。
@@ -178,7 +179,7 @@ def _read_limited(stream: BinaryIO, maximum: int) -> bytes:
return data
-def _hash_stream(stream: BinaryIO, maximum: int, output: BinaryIO | None = None) -> tuple[int, str]:
+def _hash_stream(stream: IO[bytes], maximum: int, output: IO[bytes] | None = None) -> tuple[int, str]:
"""
分块读取内容并计算大小和 SHA256,可同时复制到输出流。
@@ -232,7 +233,7 @@ def _preflight_zip(path: Path, limits: ArtifactLimits) -> None:
_preflight_entries(stream, central_end, count, limits)
-def _preflight_entries(stream: BinaryIO, central_end: int, count: int, limits: ArtifactLimits) -> None:
+def _preflight_entries(stream: IO[bytes], central_end: int, count: int, limits: ArtifactLimits) -> None:
"""
逐条检查 ZIP 中央目录记录,并核对实际数量与结束位置。
@@ -346,7 +347,7 @@ def _verify_documents(
return metadata, signature, hashlib.sha256(canonical).hexdigest()
-def _verify_manifest(data: bytes, metadata: ArtifactMetadata, limits: ArtifactLimits) -> PluginManifest:
+def _verify_manifest(data: bytes, metadata: ArtifactMetadata, limits: ArtifactLimits) -> VersionedPluginManifest:
"""
静态解析插件清单,检查协议、身份、版本及前端交付类型。
diff --git a/ruoyi-fastapi-backend/plugins/core/artifacts/schema.py b/ruoyi-fastapi-backend/plugins/core/artifacts/schema.py
index 5f5168c69..a0ba0d620 100644
--- a/ruoyi-fastapi-backend/plugins/core/artifacts/schema.py
+++ b/ruoyi-fastapi-backend/plugins/core/artifacts/schema.py
@@ -10,7 +10,7 @@
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
-from plugins.core.manifest.schema import PluginManifest
+from plugins.core.manifest.v2 import VersionedPluginManifest
from plugins.core.utils import is_windows_reserved, validate_plugin_id_value
DIGEST_PATTERN = re.compile(r'^[a-f0-9]{64}$')
@@ -384,7 +384,7 @@ class VerifiedArtifact:
files: tuple[ArtifactFile, ...]
metadata: ArtifactMetadata
signature: ArtifactSignature
- manifest: PluginManifest
+ manifest: VersionedPluginManifest
artifact_path: Path
@@ -412,6 +412,6 @@ class StoredArtifact:
files: tuple[ArtifactFile, ...]
metadata: ArtifactMetadata
signature: ArtifactSignature
- manifest: PluginManifest
+ manifest: VersionedPluginManifest
root_path: Path
plugin_path: Path
diff --git a/ruoyi-fastapi-backend/plugins/core/artifacts/store.py b/ruoyi-fastapi-backend/plugins/core/artifacts/store.py
index de0bb3d37..30b4a65cc 100644
--- a/ruoyi-fastapi-backend/plugins/core/artifacts/store.py
+++ b/ruoyi-fastapi-backend/plugins/core/artifacts/store.py
@@ -5,7 +5,7 @@
import stat
import tempfile
import time
-from collections.abc import Callable, Iterator, Mapping
+from collections.abc import Callable, Generator, Mapping
from contextlib import contextmanager
from dataclasses import replace
from pathlib import Path
@@ -289,7 +289,7 @@ def _verify_directory(
)
@contextmanager
- def _digest_lock(self, digest: str) -> Iterator[None]:
+ def _digest_lock(self, digest: str) -> Generator[None, None, None]:
"""
使用操作系统文件锁串行化同一摘要的发布,进程退出时自动释放。
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/config.py b/ruoyi-fastapi-backend/plugins/core/deployment/config.py
index d86458fcf..1f932ca2b 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/config.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/config.py
@@ -13,7 +13,7 @@
class TrustedPublisher(BaseModel):
"""将公钥与可发布插件ID显式绑定的发布者配置。"""
- model_config = ConfigDict(extra='forbid', populate_by_name=True, strict=True)
+ model_config = ConfigDict(extra='forbid', validate_by_name=True, validate_by_alias=True, strict=True)
key_id: str = Field(alias='keyId', pattern=r'^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$', description='签名密钥标识')
public_key: str = Field(alias='publicKey', min_length=1, max_length=8192, description='用于验证制品签名的公钥')
plugin_ids: list[str] = Field(alias='pluginIds', min_length=1, max_length=256, description='插件标识列表')
@@ -41,7 +41,7 @@ def validate_plugin_ids(cls, values: list[str]) -> list[str]:
class PluginTrustDocument(BaseModel):
"""由宿主管理的发布者公钥及授权范围配置文档。"""
- model_config = ConfigDict(extra='forbid', populate_by_name=True, strict=True)
+ model_config = ConfigDict(extra='forbid', validate_by_name=True, validate_by_alias=True, strict=True)
schema_version: int = Field(alias='schemaVersion', ge=1, le=1, description='数据结构的版本')
keys: list[TrustedPublisher] = Field(max_length=256, description='受信任的制品签发者及其密钥')
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/convergence.py b/ruoyi-fastapi-backend/plugins/core/deployment/convergence.py
index 102626401..efd98d986 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/convergence.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/convergence.py
@@ -169,7 +169,7 @@ def _valid_summary(summary: Mapping[str, Any]) -> bool:
else:
expected_status = 'pending_restart'
expected_restart = summary['targetDigest'] is not None and expected_status not in {'active', 'disabled'}
- return (
+ return bool(
summary['status'] == expected_status
and summary['restartRequired'] == expected_restart
and (expected_status not in {'active', 'disabled'} or summary['missingWorkers'] == 0)
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/enablement.py b/ruoyi-fastapi-backend/plugins/core/deployment/enablement.py
index d208d2b8a..dc6161c30 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/enablement.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/enablement.py
@@ -1,7 +1,7 @@
from typing import Any
from uuid import uuid4
-from sqlalchemy import select, update
+from sqlalchemy import CursorResult, select, update
from i18n.message import I18nMessage
from plugins.core.deployment.service import PluginDeploymentService
@@ -85,7 +85,7 @@ async def set_enabled(
.values(generation=generation, update_by=actor)
.execution_options(synchronize_session=False)
)
- if changed.rowcount != 1:
+ if not isinstance(changed, CursorResult) or changed.rowcount != 1:
raise PluginReleaseConflictError('发布状态已变化,启停操作未执行')
result = await PluginService.update_plugin_enabled_services(db, plugin_id, enabled, discovered)
if not result.is_success:
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/maintenance.py b/ruoyi-fastapi-backend/plugins/core/deployment/maintenance.py
index 1076a9299..386be28d5 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/maintenance.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/maintenance.py
@@ -8,7 +8,7 @@
from pathlib import Path
from typing import Any
-from sqlalchemy import delete, update
+from sqlalchemy import CursorResult, delete, update
from plugins.core.artifacts import ArtifactStore, verify_artifact
from plugins.core.artifacts.schema import DIGEST_PATTERN, safe_artifact_path, strict_json
@@ -362,7 +362,7 @@ async def rotate_signature(
)
.values(key_id=stored.key_id)
)
- if result.rowcount != 1:
+ if not isinstance(result, CursorResult) or result.rowcount != 1:
raise ValueError('制品签名索引发生并发变化')
payload = {
'ok': True,
diff --git a/ruoyi-fastapi-backend/plugins/core/discovery/registry.py b/ruoyi-fastapi-backend/plugins/core/discovery/registry.py
index b929ebab1..a4b88e6fe 100644
--- a/ruoyi-fastapi-backend/plugins/core/discovery/registry.py
+++ b/ruoyi-fastapi-backend/plugins/core/discovery/registry.py
@@ -1,3 +1,4 @@
+from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
@@ -62,7 +63,7 @@ def __init__(self, registered_plugins: list[RegisteredPlugin]) -> None:
def build(
cls,
discovered_plugins: list[DiscoveredPlugin],
- database_plugins: list[PluginStateRecord] | None = None,
+ database_plugins: Sequence[PluginStateRecord] | None = None,
) -> 'PluginRegistry':
"""
根据已发现插件和数据库状态构建插件运行时注册表。
diff --git a/ruoyi-fastapi-backend/plugins/core/discovery/scanner.py b/ruoyi-fastapi-backend/plugins/core/discovery/scanner.py
index 6c38e420f..18804a473 100644
--- a/ruoyi-fastapi-backend/plugins/core/discovery/scanner.py
+++ b/ruoyi-fastapi-backend/plugins/core/discovery/scanner.py
@@ -5,7 +5,8 @@
import yaml
from pydantic import ValidationError
-from plugins.core.manifest.schema import PluginManifest, PluginManifestError, PluginManifestFactory
+from plugins.core.manifest.schema import PluginManifestError, PluginManifestFactory
+from plugins.core.manifest.v2 import VersionedPluginManifest
PLUGIN_MANIFEST_NAME = 'plugin.yaml'
UNSUPPORTED_PLUGIN_MANIFEST_NAMES = ('plugin.yml',)
@@ -23,14 +24,14 @@ class DiscoveredPlugin:
:ivar artifact_generation: 发现该插件时对应的制品代次
"""
- manifest: PluginManifest
+ manifest: VersionedPluginManifest
backend_path: Path
manifest_path: Path
artifact_digest: str | None = None
artifact_generation: str | None = None
-def is_artifact_plugin(plugin: DiscoveredPlugin) -> bool:
+def is_artifact_plugin(plugin: DiscoveredPlugin | None) -> bool:
"""
只有显式的非空字符串摘要表示制品来源,兼容旧扫描器返回对象。
diff --git a/ruoyi-fastapi-backend/plugins/core/lifecycle/jobs.py b/ruoyi-fastapi-backend/plugins/core/lifecycle/jobs.py
index 05a57eeb4..68d0bc29d 100644
--- a/ruoyi-fastapi-backend/plugins/core/lifecycle/jobs.py
+++ b/ruoyi-fastapi-backend/plugins/core/lifecycle/jobs.py
@@ -5,7 +5,7 @@
from module_admin.entity.do.job_do import SysJob
from module_admin.entity.vo.job_vo import JobModel
from plugins.core.discovery.scanner import DiscoveredPlugin
-from plugins.core.manifest.schema import PluginJobManifest, PluginManifest
+from plugins.core.manifest.v2 import VersionedPluginJobManifest, VersionedPluginManifest
from plugins.core.utils import escape_sql_like
@@ -27,7 +27,12 @@ class PluginJobModelBuilder:
@classmethod
def build(
- cls, plugin_id: str, job: PluginJobManifest, *, enabled: bool = True, manifest: PluginManifest | None = None
+ cls,
+ plugin_id: str,
+ job: VersionedPluginJobManifest,
+ *,
+ enabled: bool = True,
+ manifest: VersionedPluginManifest | None = None,
) -> JobModel:
"""
构建系统定时任务模型。
@@ -51,21 +56,21 @@ def build(
else:
cls._validate_callable_belongs_to_plugin(plugin_id, job.callable)
return JobModel(
- jobName=cls.build_job_name(plugin_id, job.id),
- jobGroup=cls.JOB_GROUP,
- jobStore=job.job_store,
- jobExecutor=job.executor,
- invokeTarget=target,
- jobArgs=args,
- jobKwargs=kwargs,
- cronExpression=job.cron_expression,
- timeZone=job.time_zone,
- misfireGraceTime=job.misfire_grace_time,
+ job_name=cls.build_job_name(plugin_id, job.id),
+ job_group=cls.JOB_GROUP,
+ job_store=job.job_store,
+ job_executor=job.executor,
+ invoke_target=target,
+ job_args=args,
+ job_kwargs=kwargs,
+ cron_expression=job.cron_expression,
+ time_zone=job.time_zone,
+ misfire_grace_time=job.misfire_grace_time,
coalesce=job.coalesce,
- maxInstances=job.max_instances,
+ max_instances=job.max_instances,
status='0' if enabled and job.enabled else '1',
- createBy='plugin',
- updateBy='plugin',
+ create_by='plugin',
+ update_by='plugin',
remark=cls.build_remark(plugin_id, job),
)
@@ -97,7 +102,7 @@ def build_job_name(cls, plugin_id: str, job_id: str) -> str:
return f'{plugin_id}:{job_id}'
@classmethod
- def build_remark(cls, plugin_id: str, job: PluginJobManifest) -> str:
+ def build_remark(cls, plugin_id: str, job: VersionedPluginJobManifest) -> str:
"""
构建插件任务备注。
@@ -269,8 +274,10 @@ async def upsert_plugin_job(self, job_model: JobModel) -> SysJob:
:param job_model: 系统定时任务模型
:return: 写入后的系统任务对象
- :raises ValueError: 同组已有同名的非插件任务
+ :raises ValueError: 缺少任务名称或分组,或同组已有同名的非插件任务
"""
+ if job_model.job_name is None or job_model.job_group is None:
+ raise ValueError('插件任务必须声明任务名称和分组')
existing_job = await self.repository.get_job_detail_by_name_group(job_model.job_name, job_model.job_group)
if existing_job:
ownership_prefix = f'{PluginJobModelBuilder.REMARK_PREFIX} {job_model.job_name}'
diff --git a/ruoyi-fastapi-backend/plugins/core/management/dao/dao.py b/ruoyi-fastapi-backend/plugins/core/management/dao/dao.py
index 40ac1385b..5f24f0e9c 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/dao/dao.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/dao/dao.py
@@ -2,10 +2,11 @@
from datetime import datetime
from typing import Any
-from sqlalchemy import delete, func, or_, select, update
+from sqlalchemy import delete, func, or_, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
+from config.database import execute_rowcount
from i18n.translation import TranslationUtil
from module_admin.entity.do.menu_do import SysMenu
from module_admin.entity.do.role_do import SysRoleMenu
@@ -90,11 +91,11 @@ async def get_plugin_page_list(
query = (
select(SysPlugin)
.where(
- SysPlugin.plugin_id.like(f'%{query_object.plugin_id}%') if query_object.plugin_id else True,
- SysPlugin.plugin_name.like(f'%{query_object.plugin_name}%') if query_object.plugin_name else True,
- SysPlugin.enabled == query_object.enabled if query_object.enabled else True,
- SysPlugin.status == query_object.status if query_object.status else True,
- SysPlugin.source == query_object.source if query_object.source else True,
+ SysPlugin.plugin_id.like(f'%{query_object.plugin_id}%') if query_object.plugin_id else true(),
+ SysPlugin.plugin_name.like(f'%{query_object.plugin_name}%') if query_object.plugin_name else true(),
+ SysPlugin.enabled == query_object.enabled if query_object.enabled else true(),
+ SysPlugin.status == query_object.status if query_object.status else true(),
+ SysPlugin.source == query_object.source if query_object.source else true(),
)
.order_by(SysPlugin.plugin_id)
.distinct()
@@ -380,7 +381,7 @@ async def get_plugin_migration_list(
select(SysPluginMigration)
.where(
SysPluginMigration.plugin_id == plugin_id,
- SysPluginMigration.status == status if status else True,
+ SysPluginMigration.status == status if status else true(),
)
.order_by(SysPluginMigration.migration_path)
)
@@ -698,8 +699,8 @@ def _build_operation_log_query(
:return: SQLAlchemy 查询对象
"""
return select(SysPluginOperationLog).where(
- SysPluginOperationLog.operation == query_object.operation if query_object.operation else True,
- SysPluginOperationLog.status == query_object.status if query_object.status else True,
+ SysPluginOperationLog.operation == query_object.operation if query_object.operation else true(),
+ SysPluginOperationLog.status == query_object.status if query_object.status else true(),
cls._build_plugin_ids_filter(query_object.plugin_id),
cls._build_operation_log_time_filter(query_object),
)
@@ -738,7 +739,10 @@ def _build_operation_log_time_filter(
if not query_object.begin_time or not query_object.end_time:
return True
- start, end = TimezoneUtil.local_date_strings_to_utc(query_object.begin_time, query_object.end_time)
+ time_range = TimezoneUtil.local_date_strings_to_utc(query_object.begin_time, query_object.end_time)
+ if time_range is None:
+ return True
+ start, end = time_range
return (SysPluginOperationLog.create_time >= start) & (SysPluginOperationLog.create_time < end)
@classmethod
@@ -798,12 +802,10 @@ async def delete_plugin_operation_logs_before(
:param cutoff_time: 清理截止时间
:return: 删除的插件批量操作审计日志数量
"""
- delete_result = await db.execute(
- delete(SysPluginOperationLog).where(SysPluginOperationLog.create_time < cutoff_time)
+ return await execute_rowcount(
+ db, delete(SysPluginOperationLog).where(SysPluginOperationLog.create_time < cutoff_time)
)
- return int(delete_result.rowcount or 0)
-
@classmethod
async def get_sys_menu_by_id(cls, db: AsyncSession, menu_id: int) -> SysMenu | None:
"""
diff --git a/ruoyi-fastapi-backend/plugins/core/management/dao/release_dao.py b/ruoyi-fastapi-backend/plugins/core/management/dao/release_dao.py
index ffe04026b..46b753757 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/dao/release_dao.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/dao/release_dao.py
@@ -11,6 +11,7 @@
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.ext.asyncio import AsyncSession
+from config.database import execute_rowcount
from plugins.core.management.entity.do.models import SysPlugin
from plugins.core.management.entity.do.release_models import SysPluginArtifact, SysPluginRelease, SysPluginWorker
from utils.time_util import TimezoneUtil
@@ -255,8 +256,8 @@ async def set_preparation_status(
update_by=actor,
)
)
- result = await db.execute(statement.execution_options(synchronize_session=False))
- if result.rowcount != 1:
+ matched = await execute_rowcount(db, statement.execution_options(synchronize_session=False))
+ if matched != 1:
raise PluginReleaseConflictError('发布代际已变化,维护准备结果未写入')
await db.flush()
await db.refresh(release)
@@ -326,8 +327,8 @@ async def select_target(
last_error=None,
)
)
- result = await db.execute(statement.execution_options(synchronize_session=False))
- if result.rowcount != 1:
+ matched = await execute_rowcount(db, statement.execution_options(synchronize_session=False))
+ if matched != 1:
raise PluginReleaseConflictError('发布代际或维护准备状态已变化,目标未切换')
await db.flush()
await db.refresh(release)
diff --git a/ruoyi-fastapi-backend/plugins/core/management/entity/do/models.py b/ruoyi-fastapi-backend/plugins/core/management/entity/do/models.py
index 929b97b4d..d3d6e3f64 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/entity/do/models.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/entity/do/models.py
@@ -1,4 +1,7 @@
-from sqlalchemy import CHAR, BigInteger, CheckConstraint, Column, Integer, String, Text, UniqueConstraint
+from datetime import datetime
+
+from sqlalchemy import CHAR, BigInteger, CheckConstraint, Integer, String, Text, UniqueConstraint
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin, CreateTimeMixin
from common.types import DbUtcDateTime
@@ -24,20 +27,20 @@ class SysPlugin(AuditTimeMixin, Base):
{'comment': '插件信息表'},
)
- plugin_id = Column(String(64), primary_key=True, nullable=False, comment='插件ID')
- plugin_name = Column(String(128), nullable=False, comment='插件名称')
- version = Column(String(32), nullable=False, comment='当前源码版本')
- installed_version = Column(String(32), nullable=True, comment='已安装版本')
- enabled = Column(CHAR(1), nullable=False, server_default='0', comment='是否启用(0启用 1停用)')
- status = Column(String(32), nullable=False, server_default='discovered', comment='插件状态')
- source = Column(String(32), nullable=False, server_default='local', comment='插件来源')
- backend_path = Column(String(255), nullable=True, comment='后端插件相对路径')
- frontend_path = Column(String(255), nullable=True, comment='前端插件相对路径')
- last_error = Column(String(1000), nullable=True, comment='最近一次错误信息')
- description = Column(String(500), nullable=True, comment='插件说明')
- create_by = Column(String(64), nullable=True, server_default="''", comment='创建者')
- update_by = Column(String(64), nullable=True, server_default="''", comment='更新者')
- remark = Column(
+ plugin_id: Mapped[str] = mapped_column(String(64), primary_key=True, nullable=False, comment='插件ID')
+ plugin_name: Mapped[str] = mapped_column(String(128), nullable=False, comment='插件名称')
+ version: Mapped[str] = mapped_column(String(32), nullable=False, comment='当前源码版本')
+ installed_version: Mapped[str | None] = mapped_column(String(32), nullable=True, comment='已安装版本')
+ enabled: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='0', comment='是否启用(0启用 1停用)')
+ status: Mapped[str] = mapped_column(String(32), nullable=False, server_default='discovered', comment='插件状态')
+ source: Mapped[str] = mapped_column(String(32), nullable=False, server_default='local', comment='插件来源')
+ backend_path: Mapped[str | None] = mapped_column(String(255), nullable=True, comment='后端插件相对路径')
+ frontend_path: Mapped[str | None] = mapped_column(String(255), nullable=True, comment='前端插件相对路径')
+ last_error: Mapped[str | None] = mapped_column(String(1000), nullable=True, comment='最近一次错误信息')
+ description: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='插件说明')
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, server_default="''", comment='更新者')
+ remark: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
@@ -58,9 +61,9 @@ class SysPluginMenu(CreateTimeMixin, Base):
{'comment': '插件和菜单关联表'},
)
- plugin_id = Column(String(64), primary_key=True, nullable=False, comment='插件ID')
- menu_id = Column(BigInteger, primary_key=True, nullable=False, comment='菜单ID')
- menu_key = Column(String(255), nullable=False, comment='插件内菜单自然键')
+ plugin_id: Mapped[str] = mapped_column(String(64), primary_key=True, nullable=False, comment='插件ID')
+ menu_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, nullable=False, comment='菜单ID')
+ menu_key: Mapped[str] = mapped_column(String(255), nullable=False, comment='插件内菜单自然键')
class SysPluginMigration(AuditTimeMixin, Base):
@@ -75,16 +78,18 @@ class SysPluginMigration(AuditTimeMixin, Base):
__update_time_insert_default__ = False
__table_args__ = {'comment': '插件 migration 执行历史表'}
- plugin_id = Column(String(64), primary_key=True, nullable=False, comment='插件ID')
- migration_path = Column(String(255), primary_key=True, nullable=False, comment='migration 相对路径')
- migration_checksum = Column(String(64), nullable=False, comment='migration 内容校验值')
- version = Column(String(32), nullable=True, comment='执行时插件版本')
- statement_count = Column(Integer, nullable=False, default=0, comment='SQL 语句数量')
- status = Column(String(32), nullable=False, server_default='success', comment='执行状态')
- error_message = Column(Text, nullable=True, comment='失败错误信息')
- attempt_count = Column(Integer, nullable=False, default=0, comment='尝试次数')
- started_time = Column(DbUtcDateTime(), nullable=True, comment='最近开始时间')
- finished_time = Column(DbUtcDateTime(), nullable=True, comment='最近结束时间')
+ plugin_id: Mapped[str] = mapped_column(String(64), primary_key=True, nullable=False, comment='插件ID')
+ migration_path: Mapped[str] = mapped_column(
+ String(255), primary_key=True, nullable=False, comment='migration 相对路径'
+ )
+ migration_checksum: Mapped[str] = mapped_column(String(64), nullable=False, comment='migration 内容校验值')
+ version: Mapped[str | None] = mapped_column(String(32), nullable=True, comment='执行时插件版本')
+ statement_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment='SQL 语句数量')
+ status: Mapped[str] = mapped_column(String(32), nullable=False, server_default='success', comment='执行状态')
+ error_message: Mapped[str | None] = mapped_column(Text, nullable=True, comment='失败错误信息')
+ attempt_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment='尝试次数')
+ started_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='最近开始时间')
+ finished_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment='最近结束时间')
class SysPluginConfig(AuditTimeMixin, Base):
@@ -97,16 +102,16 @@ class SysPluginConfig(AuditTimeMixin, Base):
__tablename__ = 'sys_plugin_config'
__table_args__ = {'comment': '插件配置表'}
- plugin_id = Column(String(64), primary_key=True, nullable=False, comment='插件ID')
- config_key = Column(String(128), primary_key=True, nullable=False, comment='配置键名')
- config_label = Column(String(128), nullable=True, comment='配置展示名称')
- config_type = Column(String(32), nullable=False, server_default='string', comment='配置值类型')
- config_value = Column(Text, nullable=True, comment='配置值')
- default_value = Column(Text, nullable=True, comment='默认配置值')
- required = Column(CHAR(1), nullable=False, server_default='1', comment='是否必填(0是 1否)')
- secret = Column(CHAR(1), nullable=False, server_default='1', comment='是否敏感(0是 1否)')
- options = Column(Text, nullable=True, comment='配置选项JSON')
- description = Column(String(500), nullable=True, comment='配置说明')
+ plugin_id: Mapped[str] = mapped_column(String(64), primary_key=True, nullable=False, comment='插件ID')
+ config_key: Mapped[str] = mapped_column(String(128), primary_key=True, nullable=False, comment='配置键名')
+ config_label: Mapped[str | None] = mapped_column(String(128), nullable=True, comment='配置展示名称')
+ config_type: Mapped[str] = mapped_column(String(32), nullable=False, server_default='string', comment='配置值类型')
+ config_value: Mapped[str | None] = mapped_column(Text, nullable=True, comment='配置值')
+ default_value: Mapped[str | None] = mapped_column(Text, nullable=True, comment='默认配置值')
+ required: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='1', comment='是否必填(0是 1否)')
+ secret: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='1', comment='是否敏感(0是 1否)')
+ options: Mapped[str | None] = mapped_column(Text, nullable=True, comment='配置选项JSON')
+ description: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='配置说明')
class SysPluginOperationLog(CreateTimeMixin, Base):
@@ -119,21 +124,23 @@ class SysPluginOperationLog(CreateTimeMixin, Base):
__tablename__ = 'sys_plugin_operation_log'
__table_args__ = {'comment': '插件批量操作审计日志表'}
- operation_id = Column(
+ operation_id: Mapped[int] = mapped_column(
BigInteger().with_variant(Integer, 'sqlite'),
primary_key=True,
autoincrement=True,
nullable=False,
comment='操作日志ID',
)
- operation = Column(String(32), nullable=False, comment='操作类型')
- plugin_ids = Column(Text, nullable=True, comment='目标插件ID JSON')
- dry_run = Column(CHAR(1), nullable=False, server_default='1', comment='是否预演(0是 1否)')
- continue_on_error = Column(CHAR(1), nullable=False, server_default='1', comment='失败后是否继续(0是 1否)')
- status = Column(String(32), nullable=False, comment='执行状态')
- summary = Column(Text, nullable=True, comment='执行汇总JSON')
- result = Column(Text, nullable=True, comment='完整执行结果JSON')
- remark = Column(
+ operation: Mapped[str] = mapped_column(String(32), nullable=False, comment='操作类型')
+ plugin_ids: Mapped[str | None] = mapped_column(Text, nullable=True, comment='目标插件ID JSON')
+ dry_run: Mapped[str] = mapped_column(CHAR(1), nullable=False, server_default='1', comment='是否预演(0是 1否)')
+ continue_on_error: Mapped[str] = mapped_column(
+ CHAR(1), nullable=False, server_default='1', comment='失败后是否继续(0是 1否)'
+ )
+ status: Mapped[str] = mapped_column(String(32), nullable=False, comment='执行状态')
+ summary: Mapped[str | None] = mapped_column(Text, nullable=True, comment='执行汇总JSON')
+ result: Mapped[str | None] = mapped_column(Text, nullable=True, comment='完整执行结果JSON')
+ remark: Mapped[str | None] = mapped_column(
String(500),
nullable=True,
server_default=SqlalchemyUtil.get_server_default_null(DataBaseConfig.default_source.db_type),
diff --git a/ruoyi-fastapi-backend/plugins/core/management/entity/do/release_models.py b/ruoyi-fastapi-backend/plugins/core/management/entity/do/release_models.py
index 68fa331d9..dd14d6f14 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/entity/do/release_models.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/entity/do/release_models.py
@@ -1,4 +1,7 @@
-from sqlalchemy import CheckConstraint, Column, Index, Integer, String, Text
+from datetime import datetime
+
+from sqlalchemy import CheckConstraint, Index, Integer, String, Text
+from sqlalchemy.orm import Mapped, mapped_column
from common.mixin import AuditTimeMixin, CreateTimeMixin
from common.types import DbUtcDateTime
@@ -14,13 +17,13 @@ class SysPluginArtifact(CreateTimeMixin, Base):
{'comment': '插件已验证制品表'},
)
- digest = Column(String(64), primary_key=True, nullable=False, comment='制品SHA256')
- plugin_id = Column(String(64), nullable=False, comment='插件ID')
- version = Column(String(32), nullable=False, comment='制品版本')
- key_id = Column(String(128), nullable=False, comment='签名公钥标识')
- relative_path = Column(String(512), nullable=False, comment='制品存储内不可变相对目录')
- manifest_json = Column(Text, nullable=False, comment='验证后的清单JSON')
- created_by = Column(String(64), nullable=True, comment='导入者')
+ digest: Mapped[str] = mapped_column(String(64), primary_key=True, nullable=False, comment='制品SHA256')
+ plugin_id: Mapped[str] = mapped_column(String(64), nullable=False, comment='插件ID')
+ version: Mapped[str] = mapped_column(String(32), nullable=False, comment='制品版本')
+ key_id: Mapped[str] = mapped_column(String(128), nullable=False, comment='签名公钥标识')
+ relative_path: Mapped[str] = mapped_column(String(512), nullable=False, comment='制品存储内不可变相对目录')
+ manifest_json: Mapped[str] = mapped_column(Text, nullable=False, comment='验证后的清单JSON')
+ created_by: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='导入者')
class SysPluginRelease(AuditTimeMixin, Base):
@@ -36,17 +39,23 @@ class SysPluginRelease(AuditTimeMixin, Base):
{'comment': '插件目标发布表'},
)
- plugin_id = Column(String(64), primary_key=True, nullable=False, comment='插件ID')
- target_digest = Column(String(64), nullable=True, comment='目标制品SHA256')
- previous_digest = Column(String(64), nullable=True, comment='上一次目标制品SHA256')
- prepared_digest = Column(String(64), nullable=True, comment='维护准备成功的制品SHA256')
- generation = Column(String(32), nullable=False, comment='目标发布代际UUID')
- expected_workers = Column(Integer, nullable=False, server_default='1', comment='预期宿主worker数量')
- prepare_status = Column(String(16), nullable=False, server_default='idle', comment='维护准备状态')
- prepared_version = Column(String(32), nullable=True, comment='维护确认的数据结构安装版本')
- last_error = Column(Text, nullable=True, comment='维护准备错误')
- create_by = Column(String(64), nullable=True, comment='创建者')
- update_by = Column(String(64), nullable=True, comment='更新者')
+ plugin_id: Mapped[str] = mapped_column(String(64), primary_key=True, nullable=False, comment='插件ID')
+ target_digest: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='目标制品SHA256')
+ previous_digest: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='上一次目标制品SHA256')
+ prepared_digest: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='维护准备成功的制品SHA256')
+ generation: Mapped[str] = mapped_column(String(32), nullable=False, comment='目标发布代际UUID')
+ expected_workers: Mapped[int] = mapped_column(
+ Integer, nullable=False, server_default='1', comment='预期宿主worker数量'
+ )
+ prepare_status: Mapped[str] = mapped_column(
+ String(16), nullable=False, server_default='idle', comment='维护准备状态'
+ )
+ prepared_version: Mapped[str | None] = mapped_column(
+ String(32), nullable=True, comment='维护确认的数据结构安装版本'
+ )
+ last_error: Mapped[str | None] = mapped_column(Text, nullable=True, comment='维护准备错误')
+ create_by: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='创建者')
+ update_by: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='更新者')
class SysPluginWorker(AuditTimeMixin, Base):
@@ -59,11 +68,11 @@ class SysPluginWorker(AuditTimeMixin, Base):
{'comment': '插件worker加载状态表'},
)
- worker_id = Column(String(32), primary_key=True, nullable=False, comment='宿主进程UUID')
- plugin_id = Column(String(64), primary_key=True, nullable=False, comment='插件ID或__runtime__')
- artifact_digest = Column(String(64), nullable=True, comment='实际加载的制品SHA256')
- version = Column(String(32), nullable=True, comment='实际加载的制品版本')
- generation = Column(String(32), nullable=True, comment='实际加载的发布代际UUID')
- state = Column(String(16), nullable=False, comment='worker状态')
- heartbeat_time = Column(DbUtcDateTime(), nullable=False, comment='UTC心跳时间')
- error = Column(Text, nullable=True, comment='加载或运行错误')
+ worker_id: Mapped[str] = mapped_column(String(32), primary_key=True, nullable=False, comment='宿主进程UUID')
+ plugin_id: Mapped[str] = mapped_column(String(64), primary_key=True, nullable=False, comment='插件ID或__runtime__')
+ artifact_digest: Mapped[str | None] = mapped_column(String(64), nullable=True, comment='实际加载的制品SHA256')
+ version: Mapped[str | None] = mapped_column(String(32), nullable=True, comment='实际加载的制品版本')
+ generation: Mapped[str | None] = mapped_column(String(32), nullable=True, comment='实际加载的发布代际UUID')
+ state: Mapped[str] = mapped_column(String(16), nullable=False, comment='worker状态')
+ heartbeat_time: Mapped[datetime] = mapped_column(DbUtcDateTime(), nullable=False, comment='UTC心跳时间')
+ error: Mapped[str | None] = mapped_column(Text, nullable=True, comment='加载或运行错误')
diff --git a/ruoyi-fastapi-backend/plugins/core/management/entity/vo/schemas.py b/ruoyi-fastapi-backend/plugins/core/management/entity/vo/schemas.py
index efdc1da77..e430355fd 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/entity/vo/schemas.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/entity/vo/schemas.py
@@ -1,24 +1,24 @@
from typing import Any, Literal
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field
from common.mixin import DateRangeQueryMixin
from common.types import ApiUtcDateTime
+from common.vo import CamelModel
from plugins.core.state import PluginStatus
from plugins.core.types import PluginConfigValue
PluginEnabled = Literal['0', '1']
-class PluginModel(BaseModel):
+class PluginModel(CamelModel):
"""
插件信息表对应 pydantic 模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
plugin_id: str = Field(description='插件ID')
plugin_name: str | None = Field(default=None, description='插件名称')
@@ -47,14 +47,14 @@ class PluginModel(BaseModel):
release: dict[str, Any] | None = Field(default=None, description='制品目标发布及各worker实际加载状态')
-class PluginQueryModel(BaseModel):
+class PluginQueryModel(CamelModel):
"""
插件管理不分页查询模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
plugin_id: str | None = Field(default=None, description='插件ID')
plugin_name: str | None = Field(default=None, description='插件名称')
@@ -74,14 +74,14 @@ class PluginPageQueryModel(PluginQueryModel):
page_size: int = Field(default=10, description='每页记录数')
-class PluginBatchActionModel(BaseModel):
+class PluginBatchActionModel(CamelModel):
"""
插件批量执行请求体模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
operation: Literal['install', 'enable', 'upgrade'] = Field(description='批量操作类型:install、enable 或 upgrade')
plugin_ids: list[str] | None = Field(default=None, description='插件ID列表')
@@ -89,14 +89,14 @@ class PluginBatchActionModel(BaseModel):
continue_on_error: bool = Field(default=False, description='失败后是否继续执行后续插件')
-class PluginOperationLogModel(BaseModel):
+class PluginOperationLogModel(CamelModel):
"""
插件批量操作审计日志表对应 pydantic 模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
operation_id: int | None = Field(default=None, description='操作日志ID')
operation: str = Field(description='操作类型')
@@ -110,14 +110,14 @@ class PluginOperationLogModel(BaseModel):
remark: str | None = Field(default=None, description='备注')
-class PluginOperationLogQueryModel(DateRangeQueryMixin, BaseModel):
+class PluginOperationLogQueryModel(DateRangeQueryMixin, CamelModel):
"""
插件批量操作审计日志不分页查询模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
plugin_id: str | None = Field(default=None, description='插件ID')
operation: str | None = Field(default=None, description='操作类型')
@@ -147,14 +147,14 @@ class PluginOperationLogExportQueryModel(PluginOperationLogQueryModel):
export_limit: int = Field(default=5000, ge=1, le=50000, description='导出最大记录数')
-class PluginOperationLogDetailModel(BaseModel):
+class PluginOperationLogDetailModel(CamelModel):
"""
插件批量操作审计日志详情模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
operation_id: int | None = Field(default=None, description='操作日志ID')
operation: str = Field(description='操作类型')
@@ -168,27 +168,27 @@ class PluginOperationLogDetailModel(BaseModel):
remark: str | None = Field(default=None, description='备注')
-class PluginOperationLogRetentionModel(BaseModel):
+class PluginOperationLogRetentionModel(CamelModel):
"""
插件批量操作审计日志保留策略模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
retention_days: int = Field(default=180, ge=0, description='审计日志保留天数,0表示清理当前时间之前的全部日志')
dry_run: bool = Field(default=True, description='是否仅预览清理结果')
-class PluginOperationLogRetentionResultModel(BaseModel):
+class PluginOperationLogRetentionResultModel(CamelModel):
"""
插件批量操作审计日志保留策略执行结果模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
retention_days: int = Field(description='审计日志保留天数')
cutoff_time: ApiUtcDateTime = Field(description='清理截止时间')
@@ -197,14 +197,14 @@ class PluginOperationLogRetentionResultModel(BaseModel):
dry_run: bool = Field(description='是否仅预览清理结果')
-class PluginMenuModel(BaseModel):
+class PluginMenuModel(CamelModel):
"""
插件和菜单关联表对应 pydantic 模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
plugin_id: str = Field(description='插件ID')
menu_id: int = Field(description='菜单ID')
@@ -212,14 +212,14 @@ class PluginMenuModel(BaseModel):
create_time: ApiUtcDateTime | None = Field(default=None, description='创建时间')
-class PluginMigrationModel(BaseModel):
+class PluginMigrationModel(CamelModel):
"""
插件 migration 执行历史表对应 pydantic 模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
plugin_id: str = Field(description='插件ID')
migration_path: str = Field(description='migration 相对路径')
@@ -235,27 +235,27 @@ class PluginMigrationModel(BaseModel):
update_time: ApiUtcDateTime | None = Field(default=None, description='更新时间')
-class PluginMigrationRecoveryModel(BaseModel):
+class PluginMigrationRecoveryModel(CamelModel):
"""
插件 migration 人工恢复请求模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
migration_path: str = Field(description='migration 相对路径')
note: str | None = Field(default=None, description='人工恢复备注')
-class PluginConfigModel(BaseModel):
+class PluginConfigModel(CamelModel):
"""
插件配置表对应 pydantic 模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
plugin_id: str = Field(description='插件ID')
config_key: str = Field(description='配置键名')
@@ -271,14 +271,14 @@ class PluginConfigModel(BaseModel):
update_time: ApiUtcDateTime | None = Field(default=None, description='更新时间')
-class PluginConfigValueModel(BaseModel):
+class PluginConfigValueModel(CamelModel):
"""
插件配置值模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
key: str = Field(description='配置键名')
label: str | None = Field(default=None, description='配置展示名称')
@@ -297,25 +297,25 @@ class PluginConfigValueModel(BaseModel):
description: str | None = Field(default=None, description='配置说明')
-class PluginConfigUpdateModel(BaseModel):
+class PluginConfigUpdateModel(CamelModel):
"""
插件配置更新模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
values: dict[str, PluginConfigValue] = Field(default_factory=dict, description='待更新的插件配置键值')
-class PluginConfigImportModel(BaseModel):
+class PluginConfigImportModel(CamelModel):
"""
插件配置导入模型。
模型字段说明通过 Field 的 description 声明。
"""
- model_config = ConfigDict(alias_generator=to_camel, from_attributes=True)
+ model_config = ConfigDict(from_attributes=True)
values: dict[str, PluginConfigValue] = Field(default_factory=dict, description='待导入的插件配置键值')
diff --git a/ruoyi-fastapi-backend/plugins/core/management/service/config.py b/ruoyi-fastapi-backend/plugins/core/management/service/config.py
index d31eb9f18..ff6e64d44 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/service/config.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/service/config.py
@@ -2,6 +2,7 @@
import re
from typing import cast
+from plugins.core.management.entity.do.models import SysPluginConfig
from plugins.core.management.entity.vo.schemas import PluginConfigModel, PluginConfigValueModel
from plugins.core.manifest.schema import PluginConfigItemManifest
from plugins.core.types import PluginConfigValue
@@ -34,12 +35,12 @@ def build_config_model(cls, plugin_id: str, item: PluginConfigItemManifest) -> P
serialized_default = cls.serialize_config_value(item.default, secret=item.secret)
return PluginConfigModel(
- pluginId=plugin_id,
- configKey=item.key,
- configLabel=item.label,
- configType=item.type,
- configValue=serialized_default,
- defaultValue=serialized_default,
+ plugin_id=plugin_id,
+ config_key=item.key,
+ config_label=item.label,
+ config_type=item.type,
+ config_value=serialized_default,
+ default_value=serialized_default,
required='0' if item.required else '1',
secret='0' if item.secret else '1',
options=cls.serialize_value([option.model_dump() for option in item.options]),
@@ -49,7 +50,7 @@ def build_config_model(cls, plugin_id: str, item: PluginConfigItemManifest) -> P
@classmethod
def build_config_value(
cls,
- config: object,
+ config: SysPluginConfig | PluginConfigModel,
manifest_item: PluginConfigItemManifest | None = None,
*,
reveal_secret: bool = False,
@@ -94,7 +95,7 @@ def build_config_value(
@classmethod
def migrate_config_secret_storage(
cls,
- config: object,
+ config: SysPluginConfig | PluginConfigModel,
item: PluginConfigItemManifest,
) -> str | None:
"""
@@ -106,7 +107,7 @@ def migrate_config_secret_storage(
"""
old_secret = getattr(config, 'secret', '1') == '0'
if old_secret == item.secret:
- return getattr(config, 'config_value', None)
+ return config.config_value
current_value = cls.deserialize_config_value(
getattr(config, 'config_value', None),
@@ -227,14 +228,14 @@ def validate_update_value(cls, item: PluginConfigItemManifest, value: PluginConf
raise ValueError(f'配置 {item.key} 不能为空')
if item.type == 'boolean' and not isinstance(value, bool):
raise ValueError(f'配置 {item.key} 必须是布尔值')
- if item.type == 'number' and (not isinstance(value, int | float) or isinstance(value, bool)):
- raise ValueError(f'配置 {item.key} 必须是数字')
+ if item.type == 'number':
+ if not isinstance(value, int | float) or isinstance(value, bool):
+ raise ValueError(f'配置 {item.key} 必须是数字')
+ cls._validate_number_range(item, value)
if item.type == 'select' and item.options:
allowed_values = [option.value for option in item.options]
if value not in allowed_values:
raise ValueError(f'配置 {item.key} 不在允许的选项范围内')
- if item.type == 'number':
- cls._validate_number_range(item, value)
if (
item.pattern
and item.type in {'string', 'textarea', 'password'}
diff --git a/ruoyi-fastapi-backend/plugins/core/management/service/gateway.py b/ruoyi-fastapi-backend/plugins/core/management/service/gateway.py
index eb9111c6d..227083c56 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/service/gateway.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/service/gateway.py
@@ -1,7 +1,6 @@
-import subprocess
-from collections.abc import Mapping
+from __future__ import annotations
+
from importlib import import_module
-from pathlib import Path
from typing import TYPE_CHECKING
from plugins.core.lifecycle.migration import PluginMigrationRunner
@@ -12,16 +11,31 @@
run_plugin_command,
)
from plugins.core.runtime.service.migration_store import PluginDatabaseMigrationHistoryStore
-from plugins.core.types import PluginConfigValue, PluginStateRecord
if TYPE_CHECKING:
+ import subprocess
+ from collections.abc import Awaitable, Callable, Mapping
+ from contextlib import AbstractAsyncContextManager
+ from pathlib import Path
+ from types import TracebackType
+
+ from sqlalchemy.ext.asyncio import AsyncSession
+
+ from common.vo import CrudResponseModel
+ from plugins.core.discovery.scanner import DiscoveredPlugin
+ from plugins.core.lifecycle.migration import PluginMigrationResult
+ from plugins.core.lifecycle.purge import PluginPurgePlan
from plugins.core.management.entity.vo.schemas import (
+ PluginConfigModel,
PluginConfigUpdateModel,
PluginConfigValueModel,
PluginMigrationModel,
+ PluginModel,
PluginOperationLogDetailModel,
PluginOperationLogExportQueryModel,
)
+ from plugins.core.types import PluginConfigValue, PluginStateRecord
+ from plugins.core.validation.menus import PluginMenuConflictItem
class PluginManagementLifecycleUnitOfWork:
@@ -31,7 +45,7 @@ class PluginManagementLifecycleUnitOfWork:
:ivar async_session_local: 异步数据库会话工厂
:ivar plugin_service: 插件管理服务类
:ivar session_context: 当前会话的上下文
- :ivar session: 数据库会话
+ :ivar _session: 已进入上下文的数据库会话
"""
def __init__(
@@ -47,20 +61,35 @@ def __init__(
"""
self.async_session_local = async_session_local
self.plugin_service = plugin_service
- self.session_context: object | None = None
- self.session: object | None = None
+ self.session_context: AbstractAsyncContextManager[AsyncSession] | None = None
+ self._session: AsyncSession | None = None
+
+ @property
+ def session(self) -> AsyncSession:
+ """
+ 获取生命周期事务正在使用的会话。
- async def __aenter__(self) -> 'PluginManagementLifecycleUnitOfWork':
+ :return: 已进入上下文的数据库会话
+ :raises RuntimeError: 工作单元尚未进入或已经关闭
+ """
+ if self._session is None:
+ raise RuntimeError('插件生命周期事务尚未打开')
+ return self._session
+
+ async def __aenter__(self) -> PluginManagementLifecycleUnitOfWork:
"""
打开生命周期主事务会话。
:return: 生命周期主事务工作单元
"""
- self.session_context = self.async_session_local()
- self.session = await self.session_context.__aenter__()
+ context = self.async_session_local()
+ self._session = await context.__aenter__()
+ self.session_context = context
return self
- async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> None:
+ async def __aexit__(
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, traceback: TracebackType | None
+ ) -> None:
"""
关闭生命周期主事务会话。
@@ -70,11 +99,13 @@ async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> N
"""
if self.session_context is None:
return
- await self.session_context.__aexit__(exc_type, exc, traceback)
- self.session_context = None
- self.session = None
+ try:
+ await self.session_context.__aexit__(exc_type, exc, traceback)
+ finally:
+ self.session_context = None
+ self._session = None
- async def check_installed_menu_conflicts(self, discovered_plugin: object) -> list[object]:
+ async def check_installed_menu_conflicts(self, discovered_plugin: DiscoveredPlugin) -> list[PluginMenuConflictItem]:
"""
检查已安装菜单冲突。
@@ -85,10 +116,10 @@ async def check_installed_menu_conflicts(self, discovered_plugin: object) -> lis
async def upsert_discovered_plugin(
self,
- discovered_plugin: object,
- backend_root: object,
- frontend_root: object | None = None,
- ) -> object:
+ discovered_plugin: DiscoveredPlugin,
+ backend_root: Path,
+ frontend_root: Path | None = None,
+ ) -> PluginModel:
"""
写入或更新已发现插件。
@@ -104,7 +135,7 @@ async def upsert_discovered_plugin(
frontend_root,
)
- async def install_plugin_menu(self, discovered_plugin: object, *, enabled: bool) -> None:
+ async def install_plugin_menu(self, discovered_plugin: DiscoveredPlugin, *, enabled: bool) -> None:
"""
安装插件菜单。
@@ -113,7 +144,7 @@ async def install_plugin_menu(self, discovered_plugin: object, *, enabled: bool)
"""
await self.plugin_service.install_plugin_menu_services(self.session, discovered_plugin, enabled=enabled)
- async def install_plugin_default_config(self, discovered_plugin: object) -> list[object]:
+ async def install_plugin_default_config(self, discovered_plugin: DiscoveredPlugin) -> list[PluginConfigModel]:
"""
安装插件默认配置。
@@ -122,7 +153,7 @@ async def install_plugin_default_config(self, discovered_plugin: object) -> list
"""
return await self.plugin_service.install_plugin_default_config_services(self.session, discovered_plugin)
- async def install_plugin_jobs(self, discovered_plugin: object, *, enabled: bool) -> None:
+ async def install_plugin_jobs(self, discovered_plugin: DiscoveredPlugin, *, enabled: bool) -> None:
"""
同步单个插件任务。
@@ -135,7 +166,7 @@ async def install_plugin_jobs(self, discovered_plugin: object, *, enabled: bool)
enabled=enabled,
)
- async def mark_plugin_installed(self, discovered_plugin: object) -> object:
+ async def mark_plugin_installed(self, discovered_plugin: DiscoveredPlugin) -> PluginModel:
"""
标记插件已安装。
@@ -144,7 +175,7 @@ async def mark_plugin_installed(self, discovered_plugin: object) -> object:
"""
return await self.plugin_service.mark_plugin_installed_services(self.session, discovered_plugin)
- async def build_plugin_purge_plan(self, discovered_plugin: object) -> object:
+ async def build_plugin_purge_plan(self, discovered_plugin: DiscoveredPlugin) -> PluginPurgePlan:
"""
构建插件物理清理计划。
@@ -153,7 +184,7 @@ async def build_plugin_purge_plan(self, discovered_plugin: object) -> object:
"""
return await self.plugin_service.build_plugin_purge_plan_services(self.session, discovered_plugin)
- async def purge_plugin_metadata(self, discovered_plugin: object) -> object:
+ async def purge_plugin_metadata(self, discovered_plugin: DiscoveredPlugin) -> PluginPurgePlan:
"""
清理插件平台元数据。
@@ -162,7 +193,7 @@ async def purge_plugin_metadata(self, discovered_plugin: object) -> object:
"""
return await self.plugin_service.purge_plugin_services(self.session, discovered_plugin)
- async def build_plugin_purge_plan_by_id(self, plugin_id: str) -> object:
+ async def build_plugin_purge_plan_by_id(self, plugin_id: str) -> PluginPurgePlan:
"""
按插件 ID 构建孤儿元数据清理计划。
@@ -171,7 +202,7 @@ async def build_plugin_purge_plan_by_id(self, plugin_id: str) -> object:
"""
return await self.plugin_service.build_plugin_purge_plan_by_id_services(self.session, plugin_id)
- async def purge_plugin_metadata_by_id(self, plugin_id: str) -> object:
+ async def purge_plugin_metadata_by_id(self, plugin_id: str) -> PluginPurgePlan:
"""
按插件 ID 清理孤儿元数据。
@@ -228,7 +259,7 @@ async def list_plugin_states(self) -> list[PluginStateRecord]:
async_session_local = self.get_async_session_local()
plugin_service = self.get_plugin_service()
async with async_session_local() as session:
- return await plugin_service.get_plugin_list_services(session)
+ return list(await plugin_service.get_plugin_list_services(session))
async def get_plugin_state(self, plugin_id: str) -> PluginStateRecord | None:
"""
@@ -240,10 +271,12 @@ async def get_plugin_state(self, plugin_id: str) -> PluginStateRecord | None:
async_session_local = self.get_async_session_local()
plugin_service = self.get_plugin_service()
async with async_session_local() as session:
- state_reader = getattr(plugin_service, 'get_plugin_state_services', plugin_service.plugin_detail_services)
+ state_reader: Callable[[AsyncSession, str], Awaitable[PluginStateRecord | None]] = getattr(
+ plugin_service, 'get_plugin_state_services', plugin_service.plugin_detail_services
+ )
return await state_reader(session, plugin_id)
- async def get_selected_artifact_plugin(self, plugin_id: str, backend_root: Path) -> object:
+ async def get_selected_artifact_plugin(self, plugin_id: str, backend_root: Path) -> DiscoveredPlugin:
"""
按发布目标和当前宿主信任配置解析制品清单,供只读配置入口使用。
@@ -272,7 +305,7 @@ async def get_selected_artifact_plugin(self, plugin_id: str, backend_root: Path)
return catalog.discovered(artifact, generation)
@staticmethod
- def build_operation_log_export_query(export_limit: int) -> 'PluginOperationLogExportQueryModel':
+ def build_operation_log_export_query(export_limit: int) -> PluginOperationLogExportQueryModel:
"""
构建插件操作日志导出查询对象。
@@ -280,10 +313,10 @@ def build_operation_log_export_query(export_limit: int) -> 'PluginOperationLogEx
:return: 插件操作日志导出查询对象
"""
plugin_vo = import_module('plugins.core.management.entity.vo.schemas')
- return plugin_vo.PluginOperationLogExportQueryModel(exportLimit=export_limit)
+ return plugin_vo.PluginOperationLogExportQueryModel(export_limit=export_limit)
@staticmethod
- def build_config_update(values: dict[str, PluginConfigValue]) -> 'PluginConfigUpdateModel':
+ def build_config_update(values: dict[str, PluginConfigValue]) -> PluginConfigUpdateModel:
"""
构建插件配置更新对象。
@@ -295,10 +328,10 @@ def build_config_update(values: dict[str, PluginConfigValue]) -> 'PluginConfigUp
async def get_plugin_config(
self,
- discovered_plugin: object,
+ discovered_plugin: DiscoveredPlugin,
*,
reveal_secret: bool = False,
- ) -> list['PluginConfigValueModel']:
+ ) -> list[PluginConfigValueModel]:
"""
获取插件配置。
@@ -318,9 +351,9 @@ async def get_plugin_config(
async def update_plugin_config(
self,
- discovered_plugin: object,
+ discovered_plugin: DiscoveredPlugin,
values: dict[str, PluginConfigValue],
- ) -> list['PluginConfigValueModel']:
+ ) -> list[PluginConfigValueModel]:
"""
更新插件配置。
@@ -342,12 +375,12 @@ async def update_plugin_config(
async def set_plugin_config(
self,
- discovered_plugin: object,
+ discovered_plugin: DiscoveredPlugin,
values: dict[str, PluginConfigValue],
*,
audit_operation: str,
success_message: str,
- ) -> list['PluginConfigValueModel']:
+ ) -> list[PluginConfigValueModel]:
"""
在同一事务中更新插件配置并记录审计日志。
@@ -392,7 +425,7 @@ async def set_plugin_config(
@staticmethod
async def _ensure_plugin_installed(
- session: object,
+ session: AsyncSession,
plugin_service: type[PluginManagementServiceProtocol],
plugin_id: str,
) -> None:
@@ -432,7 +465,7 @@ async def add_plugin_operation_log(
)
await session.commit()
- async def list_plugin_operation_logs(self, *, export_limit: int) -> list['PluginOperationLogDetailModel']:
+ async def list_plugin_operation_logs(self, *, export_limit: int) -> list[PluginOperationLogDetailModel]:
"""
获取插件操作审计日志列表。
@@ -468,7 +501,7 @@ async def list_plugin_migrations(
self,
plugin_id: str,
status: str | None = None,
- ) -> list['PluginMigrationModel']:
+ ) -> list[PluginMigrationModel]:
"""
查询插件 migration 历史。
@@ -481,7 +514,7 @@ async def list_plugin_migrations(
async with async_session_local() as session:
return await plugin_service.get_plugin_migration_list_services(session, plugin_id, status)
- async def get_plugin_migration(self, plugin_id: str, migration_path: str) -> 'PluginMigrationModel | None':
+ async def get_plugin_migration(self, plugin_id: str, migration_path: str) -> PluginMigrationModel | None:
"""
获取插件 migration 历史。
@@ -500,7 +533,7 @@ async def mark_plugin_migration_status(
migration_path: str,
status: str,
error_message: str | None = None,
- ) -> 'PluginMigrationModel | None':
+ ) -> PluginMigrationModel | None:
"""
人工标记插件 migration 历史状态。
@@ -524,7 +557,7 @@ async def mark_plugin_migration_status(
await session.commit()
return migration
- async def build_plugin_purge_plan(self, discovered_plugin: object) -> object:
+ async def build_plugin_purge_plan(self, discovered_plugin: DiscoveredPlugin) -> PluginPurgePlan:
"""
构建插件物理清理计划。
@@ -540,8 +573,8 @@ async def set_plugin_enabled_state(
self,
plugin_id: str,
enabled: bool,
- discovered_plugin: object | None = None,
- ) -> object:
+ discovered_plugin: DiscoveredPlugin | None = None,
+ ) -> CrudResponseModel:
"""
更新插件启停状态,并在启用时同步插件菜单。
@@ -565,7 +598,7 @@ async def set_plugin_enabled_state(
await session.commit()
return response
- async def mark_plugin_uninstalled_state(self, plugin_id: str) -> object:
+ async def mark_plugin_uninstalled_state(self, plugin_id: str) -> CrudResponseModel:
"""
标记插件安全卸载。
@@ -580,7 +613,7 @@ async def mark_plugin_uninstalled_state(self, plugin_id: str) -> object:
await session.commit()
return response
- async def run_plugin_migrations(self, discovered_plugin: object) -> object:
+ async def run_plugin_migrations(self, discovered_plugin: DiscoveredPlugin) -> list[PluginMigrationResult]:
"""
使用独立执行事务运行插件 migration。
@@ -609,7 +642,7 @@ def build_migration_record(
statement_count: int,
status: str = 'success',
error_message: str | None = None,
- ) -> 'PluginMigrationModel':
+ ) -> PluginMigrationModel:
"""
构建插件 migration 执行历史对象。
@@ -624,13 +657,13 @@ def build_migration_record(
"""
plugin_vo = import_module('plugins.core.management.entity.vo.schemas')
return plugin_vo.PluginMigrationModel(
- pluginId=plugin_id,
- migrationPath=migration_path,
- migrationChecksum=checksum,
+ plugin_id=plugin_id,
+ migration_path=migration_path,
+ migration_checksum=checksum,
version=version,
- statementCount=statement_count,
+ statement_count=statement_count,
status=status,
- errorMessage=error_message,
+ error_message=error_message,
)
@staticmethod
diff --git a/ruoyi-fastapi-backend/plugins/core/management/service/logs.py b/ruoyi-fastapi-backend/plugins/core/management/service/logs.py
index d00f1feb8..9c15ab159 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/service/logs.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/service/logs.py
@@ -1,6 +1,6 @@
import json
from collections.abc import Mapping
-from typing import cast
+from typing import Any, cast
from plugins.core.management.entity.vo.schemas import PluginOperationLogDetailModel, PluginOperationLogModel
from utils.log_util import logger
@@ -16,7 +16,7 @@ class PluginOperationLogBuilder:
@staticmethod
def build_export_row(
operation_log: PluginOperationLogDetailModel,
- operation_dict: dict[str, str] | None = None,
+ operation_dict: Mapping[str, str | None] | None = None,
) -> dict[str, object]:
"""
构建插件批量操作审计日志导出行。
@@ -40,7 +40,7 @@ def build_export_row(
}
@classmethod
- def build_detail(cls, operation_log: Mapping[str, object]) -> PluginOperationLogDetailModel:
+ def build_detail(cls, operation_log: Mapping[str, Any]) -> PluginOperationLogDetailModel:
"""
构建插件批量操作审计日志详情。
@@ -48,15 +48,15 @@ def build_detail(cls, operation_log: Mapping[str, object]) -> PluginOperationLog
:return: 插件批量操作审计日志详情
"""
return PluginOperationLogDetailModel(
- operationId=operation_log.get('operationId'),
+ operation_id=operation_log.get('operationId'),
operation=operation_log.get('operation') or '-',
- pluginIds=cls.deserialize_json_list(operation_log.get('pluginIds')),
- dryRun=operation_log.get('dryRun') == '0',
- continueOnError=operation_log.get('continueOnError') == '0',
+ plugin_ids=cls.deserialize_json_list(operation_log.get('pluginIds')),
+ dry_run=operation_log.get('dryRun') == '0',
+ continue_on_error=operation_log.get('continueOnError') == '0',
status=operation_log.get('status') or '-',
summary=cls.deserialize_json_dict(operation_log.get('summary')),
result=cls.deserialize_json_dict(operation_log.get('result')),
- createTime=operation_log.get('createTime'),
+ create_time=operation_log.get('createTime'),
remark=operation_log.get('remark'),
)
@@ -121,9 +121,9 @@ def build_model(
return PluginOperationLogModel(
operation=str(payload.get('operation', 'unknown')),
- pluginIds=json.dumps(plugin_ids, ensure_ascii=False),
- dryRun='0' if dry_run else '1',
- continueOnError='0' if continue_on_error else '1',
+ plugin_ids=json.dumps(plugin_ids, ensure_ascii=False),
+ dry_run='0' if dry_run else '1',
+ continue_on_error='0' if continue_on_error else '1',
status=cls.resolve_status(payload),
summary=json.dumps(summary, ensure_ascii=False),
result=json.dumps(dict(payload), ensure_ascii=False, default=str),
@@ -140,8 +140,8 @@ def resolve_plugin_ids(payload: Mapping[str, object]) -> list[str]:
"""
plan_value = payload.get('plan')
plan = cast('dict[str, object]', plan_value) if isinstance(plan_value, dict) else {}
- ordered_plugin_ids = plan.get('orderedPluginIds') if isinstance(plan.get('orderedPluginIds'), list) else []
- if ordered_plugin_ids:
+ ordered_plugin_ids = plan.get('orderedPluginIds')
+ if isinstance(ordered_plugin_ids, list) and ordered_plugin_ids:
return [str(plugin_id) for plugin_id in ordered_plugin_ids]
plugin_id = payload.get('pluginId')
if plugin_id:
diff --git a/ruoyi-fastapi-backend/plugins/core/management/service/menus.py b/ruoyi-fastapi-backend/plugins/core/management/service/menus.py
index 003ee887d..41f13c00c 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/service/menus.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/service/menus.py
@@ -5,7 +5,8 @@
from plugins.core.management.dao.dao import PluginDao
from plugins.core.management.entity.vo.schemas import PluginMenuModel
from plugins.core.manifest.menu_key import InstalledPluginMenu, PluginMenuKeyBuilder
-from plugins.core.manifest.schema import PluginManifest, PluginMenuManifest, PluginPermissionManifest
+from plugins.core.manifest.schema import PluginMenuManifest, PluginPermissionManifest
+from plugins.core.manifest.v2 import VersionedPluginManifest
from utils.log_util import logger
ROOT_MENU_ID = 0
@@ -41,7 +42,7 @@ def __init__(self, query_db: AsyncSession) -> None:
"""
self.query_db = query_db
- async def install_manifest_menus(self, manifest: PluginManifest) -> list[InstalledPluginMenu]:
+ async def install_manifest_menus(self, manifest: VersionedPluginManifest) -> list[InstalledPluginMenu]:
"""
安装插件清单中的菜单。
@@ -125,7 +126,7 @@ async def _install_menu_tree(
async def _install_permission_button_menus(
self,
- manifest: PluginManifest,
+ manifest: VersionedPluginManifest,
installed_menus: list[InstalledPluginMenu],
seen_menu_keys: set[str],
) -> list[InstalledPluginMenu]:
@@ -216,12 +217,12 @@ def _build_permission_button_menu(permission: PluginPermissionManifest, order_in
action = permission.code.rsplit(':', maxsplit=1)[-1]
return PluginMenuManifest(
name=permission.name or PERMISSION_BUTTON_LABELS.get(action, action),
- nameI18n=permission.name_i18n,
+ name_i18n=permission.name_i18n,
path=action,
component='',
perms=permission.code,
type='F',
- orderNum=AUTO_BUTTON_ORDER_START + order_index,
+ order_num=AUTO_BUTTON_ORDER_START + order_index,
icon='#',
)
@@ -287,7 +288,7 @@ async def _upsert_plugin_menu(self, plugin_id: str, menu_id: int, menu_key: str)
:param menu_id: 菜单ID
:param menu_key: 插件菜单自然键
"""
- plugin_menu_model = PluginMenuModel(pluginId=plugin_id, menuId=menu_id, menuKey=menu_key)
+ plugin_menu_model = PluginMenuModel(plugin_id=plugin_id, menu_id=menu_id, menu_key=menu_key)
existing_plugin_menu = await PluginDao.get_plugin_menu_by_key(self.query_db, plugin_id, menu_key)
if existing_plugin_menu and existing_plugin_menu.menu_id != menu_id:
await PluginDao.update_plugin_menu_by_key(self.query_db, plugin_menu_model)
@@ -332,18 +333,18 @@ def _build_menu_model(
"""
menu_remark = PluginMenuInstaller._build_remark(plugin_id, existing_remark)
return MenuModel(
- menuId=menu_id,
- menuName=menu.name,
- menuNameI18n=menu.name_i18n,
- parentId=parent_id,
- orderNum=menu.order_num,
+ menu_id=menu_id,
+ menu_name=menu.name,
+ menu_name_i18n=menu.name_i18n,
+ parent_id=parent_id,
+ order_num=menu.order_num,
path=menu.path,
component=menu.component,
query=menu.query,
- routeName=menu.route_name,
- isFrame=menu.is_frame,
- isCache=menu.is_cache,
- menuType=menu.type,
+ route_name=menu.route_name,
+ is_frame=menu.is_frame,
+ is_cache=menu.is_cache,
+ menu_type=menu.type,
visible=menu.visible,
status=menu.status,
perms=menu.perms or None,
diff --git a/ruoyi-fastapi-backend/plugins/core/management/service/service.py b/ruoyi-fastapi-backend/plugins/core/management/service/service.py
index b6de87bdb..eaccfd3ff 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/service/service.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/service/service.py
@@ -1,7 +1,7 @@
from collections.abc import Iterable, Mapping
from datetime import timedelta
from pathlib import Path
-from typing import Any
+from typing import Any, Literal, overload
from sqlalchemy.ext.asyncio import AsyncSession
@@ -13,6 +13,7 @@
from plugins.core.lifecycle.jobs import PluginJobInstaller, PluginJobRepository
from plugins.core.lifecycle.purge import PluginPurgePlan, PluginPurgePlanner
from plugins.core.management.dao.dao import PluginDao
+from plugins.core.management.entity.do.models import SysPlugin
from plugins.core.management.entity.vo.schemas import (
PluginConfigModel,
PluginConfigUpdateModel,
@@ -75,6 +76,30 @@ async def get_plugin_state_services(cls, query_db: AsyncSession, plugin_id: str)
plugin = await PluginDao.get_plugin_by_id(query_db, plugin_id)
return PluginModel(**CamelCaseUtil.transform_result(plugin)) if plugin is not None else None
+ @classmethod
+ @overload
+ async def get_plugin_page_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: PluginPageQueryModel,
+ is_page: Literal[True] = True,
+ *,
+ backend_root: Path | None = None,
+ frontend_root: Path | None = None,
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_plugin_page_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: PluginPageQueryModel,
+ is_page: Literal[False],
+ *,
+ backend_root: Path | None = None,
+ frontend_root: Path | None = None,
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_plugin_page_list_services(
cls,
@@ -159,7 +184,7 @@ async def plugin_detail_services(
@classmethod
async def _build_artifact_plugin_models(
- cls, query_db: AsyncSession, plugins: Iterable[object], backend_root: Path, frontend_root: Path | None
+ cls, query_db: AsyncSession, plugins: Iterable[SysPlugin], backend_root: Path, frontend_root: Path | None
) -> dict[str, PluginModel]:
"""
筛选制品来源的插件记录,并构建包含发布状态的展示模型。
@@ -288,16 +313,16 @@ async def mark_plugin_installed_services(
plugin = await PluginDao.get_plugin_by_id(query_db, manifest.id)
return PluginModel(
- pluginId=manifest.id,
- pluginName=manifest.name,
+ plugin_id=manifest.id,
+ plugin_name=manifest.name,
version=manifest.version,
- installedVersion=manifest.version,
+ installed_version=manifest.version,
enabled=enabled,
status=status,
source='local',
- backendPath=str(discovered_plugin.backend_path),
+ backend_path=str(discovered_plugin.backend_path),
description=manifest.description,
- updateTime=getattr(plugin, 'update_time', None),
+ update_time=getattr(plugin, 'update_time', None),
)
@classmethod
@@ -515,6 +540,24 @@ async def add_plugin_operation_log_services(
return PluginOperationLogModel(**CamelCaseUtil.transform_result(db_operation_log))
+ @classmethod
+ @overload
+ async def get_plugin_operation_log_page_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: PluginOperationLogPageQueryModel,
+ is_page: Literal[True] = True,
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def get_plugin_operation_log_page_list_services(
+ cls,
+ query_db: AsyncSession,
+ query_object: PluginOperationLogPageQueryModel,
+ is_page: Literal[False],
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_plugin_operation_log_page_list_services(
cls,
@@ -559,7 +602,7 @@ async def get_plugin_operation_log_export_list_services(
def export_plugin_operation_log_list_services(
cls,
operation_log_list: list[PluginOperationLogDetailModel],
- operation_dict: dict[str, str] | None = None,
+ operation_dict: Mapping[str, str | None] | None = None,
) -> bytes:
"""
导出插件批量操作审计日志。
@@ -606,11 +649,11 @@ async def retain_plugin_operation_log_services(
deleted_count = await PluginDao.delete_plugin_operation_logs_before(query_db, cutoff_time)
return PluginOperationLogRetentionResultModel(
- retentionDays=retention_model.retention_days,
- cutoffTime=cutoff_time,
- matchedCount=matched_count,
- deletedCount=deleted_count,
- dryRun=retention_model.dry_run,
+ retention_days=retention_model.retention_days,
+ cutoff_time=cutoff_time,
+ matched_count=matched_count,
+ deleted_count=deleted_count,
+ dry_run=retention_model.dry_run,
)
@classmethod
@@ -908,7 +951,7 @@ async def upsert_plugin_menu_services(
:return: 插件菜单关联对象
"""
existing_plugin_menu = await PluginDao.get_plugin_menu_by_key(query_db, plugin_id, menu_key)
- plugin_menu_model = PluginMenuModel(pluginId=plugin_id, menuId=menu_id, menuKey=menu_key)
+ plugin_menu_model = PluginMenuModel(plugin_id=plugin_id, menu_id=menu_id, menu_key=menu_key)
if existing_plugin_menu and existing_plugin_menu.menu_id != menu_id:
await PluginDao.update_plugin_menu_by_key(query_db, plugin_menu_model)
@@ -1036,7 +1079,9 @@ def _build_plugin_model(
status = PluginService._resolve_status(manifest.version, installed_version, enabled, current_status)
if is_artifact_plugin(discovered_plugin) and current_status is not None:
status = current_status
- frontend_path = frontend_root / manifest.frontend.plugin_id if frontend_root else None
+ frontend_path = (
+ frontend_root / manifest.frontend.plugin_id if frontend_root and manifest.frontend.plugin_id else None
+ )
frontend_menus = PluginMenuTree.flatten(manifest.frontend.menus)
frontend_framework = (
PLUGIN_RUNTIME_ENVIRONMENT.get_frontend_framework(
@@ -1048,22 +1093,22 @@ def _build_plugin_model(
frontend_dependencies = manifest.dependencies.resolve_frontend(frontend_framework or 'vue3')
return PluginModel(
- pluginId=manifest.id,
- pluginName=manifest.name,
+ plugin_id=manifest.id,
+ plugin_name=manifest.name,
version=manifest.version,
- installedVersion=installed_version,
+ installed_version=installed_version,
enabled=enabled,
status=status,
source='artifact' if is_artifact_plugin(discovered_plugin) else 'local',
- backendPath=(
+ backend_path=(
f'artifact:{discovered_plugin.artifact_digest}'
if is_artifact_plugin(discovered_plugin)
else str(discovered_plugin.backend_path.relative_to(backend_root))
),
- frontendPath=str(frontend_path.relative_to(frontend_root)) if frontend_path and frontend_root else None,
- lastError=last_error,
+ frontend_path=str(frontend_path.relative_to(frontend_root)) if frontend_path and frontend_root else None,
+ last_error=last_error,
description=manifest.description,
- updateTime=TimezoneUtil.utc_now(),
+ update_time=TimezoneUtil.utc_now(),
capability=capability.to_payload(),
metadata=manifest.metadata.model_dump(by_alias=True),
backend={
@@ -1099,7 +1144,7 @@ def _build_plugin_model(
else {}
),
},
- pluginDependencies=[dependency.model_dump(by_alias=True) for dependency in manifest.dependencies.plugins],
+ plugin_dependencies=[dependency.model_dump(by_alias=True) for dependency in manifest.dependencies.plugins],
)
@classmethod
diff --git a/ruoyi-fastapi-backend/plugins/core/manifest/__init__.py b/ruoyi-fastapi-backend/plugins/core/manifest/__init__.py
index 0cbedb2a4..f92cc34ab 100644
--- a/ruoyi-fastapi-backend/plugins/core/manifest/__init__.py
+++ b/ruoyi-fastapi-backend/plugins/core/manifest/__init__.py
@@ -1 +1,2 @@
+from plugins.core.manifest import v2 as v2
from plugins.core.manifest.schema import * # noqa: F403
diff --git a/ruoyi-fastapi-backend/plugins/core/manifest/menu_tree.py b/ruoyi-fastapi-backend/plugins/core/manifest/menu_tree.py
index f3cfdb860..8625d4c48 100644
--- a/ruoyi-fastapi-backend/plugins/core/manifest/menu_tree.py
+++ b/ruoyi-fastapi-backend/plugins/core/manifest/menu_tree.py
@@ -2,7 +2,8 @@
from typing import TYPE_CHECKING
if TYPE_CHECKING:
- from plugins.core.manifest.schema import PluginManifest, PluginMenuManifest
+ from plugins.core.manifest.schema import PluginMenuManifest
+ from plugins.core.manifest.v2 import VersionedPluginManifest
MIN_PLUGIN_COMPONENT_PARTS = 3
@@ -84,7 +85,7 @@ def is_plugin_component(component: str) -> bool:
@staticmethod
def resolve_plugin_view_path(
- manifest: 'PluginManifest', component: str, frontend_framework: str = 'vue3'
+ manifest: 'VersionedPluginManifest', component: str, frontend_framework: str = 'vue3'
) -> Path | None:
"""
将插件组件路径解析为前端插件内视图路径。
diff --git a/ruoyi-fastapi-backend/plugins/core/manifest/schema.py b/ruoyi-fastapi-backend/plugins/core/manifest/schema.py
index 23fb6b359..7d1fc26ea 100644
--- a/ruoyi-fastapi-backend/plugins/core/manifest/schema.py
+++ b/ruoyi-fastapi-backend/plugins/core/manifest/schema.py
@@ -1,11 +1,13 @@
import re
from collections import Counter
-from typing import Any, Literal
+from typing import Annotated, Any, Generic, Literal, Self
from packaging.requirements import InvalidRequirement
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, ValidationInfo, field_validator, model_validator
+from typing_extensions import TypeVar
from i18n.translation import TranslationUtil
+from plugins.core import manifest as manifest_models
from plugins.core.frontend import validate_frontend_framework
from plugins.core.manifest.menu_tree import PluginMenuTree
from plugins.core.types import PluginConfigValue
@@ -54,7 +56,7 @@ class PluginManifestError(ValueError):
class RouterManifest(BaseModel):
"""插件路由声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
auto_scan: bool = Field(default=True, alias='autoScan', description='是否自动扫描插件控制器')
@@ -62,7 +64,7 @@ class RouterManifest(BaseModel):
class HealthManifest(BaseModel):
"""插件健康检查声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
checker: str | None = Field(default=None, description='插件健康检查 callable,格式为 :')
@@ -84,7 +86,7 @@ def validate_checker(cls, value: str | None) -> str | None:
class HookManifest(BaseModel):
"""插件生命周期钩子声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
on_install: str | None = Field(default=None, alias='onInstall', description='插件安装钩子')
on_upgrade: str | None = Field(default=None, alias='onUpgrade', description='插件升级钩子')
@@ -107,10 +109,13 @@ def validate_hook(cls, value: str | None) -> str | None:
raise ValueError('生命周期钩子必须使用 : 格式')
-class PluginJobManifest(BaseModel):
+_ExecutorT = TypeVar('_ExecutorT', bound=Literal['default', 'processpool'], default=Literal['default', 'processpool'])
+
+
+class PluginJobManifest(BaseModel, Generic[_ExecutorT]):
"""插件定时任务声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
id: str = Field(description='插件内定时任务唯一标识')
name: str | None = Field(default=None, description='定时任务展示名称')
@@ -132,7 +137,7 @@ class PluginJobManifest(BaseModel):
job_store: Literal['default', 'sqlalchemy', 'redis'] = Field(
default='default', alias='jobStore', description='调度存储'
)
- executor: Literal['default', 'processpool'] = Field(default='default', description='任务执行器')
+ executor: Annotated[_ExecutorT, Field(default='default', description='任务执行器')]
@field_validator('id')
@classmethod
@@ -202,7 +207,7 @@ def validate_time_zone(cls, value: str) -> str:
return TimezoneUtil.validate_timezone_name(value)
@model_validator(mode='after')
- def fill_name(self) -> 'PluginJobManifest':
+ def fill_name(self) -> Self:
"""
填充任务展示名称默认值。
@@ -213,10 +218,13 @@ def fill_name(self) -> 'PluginJobManifest':
return self
-class BackendManifest(BaseModel):
+_JobT = TypeVar('_JobT', bound='PluginJobManifest | manifest_models.v2.PluginJobManifestV2', default=PluginJobManifest)
+
+
+class BackendManifest(BaseModel, Generic[_JobT]):
"""插件后端声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
module: str = Field(description='插件后端 Python 模块路径')
routers: RouterManifest = Field(default_factory=RouterManifest, description='插件路由声明')
@@ -224,7 +232,7 @@ class BackendManifest(BaseModel):
migrations: list[str] = Field(default_factory=list, description='数据库迁移脚本列表')
seeds: list[str] = Field(default_factory=list, description='初始化数据脚本列表')
hooks: HookManifest = Field(default_factory=HookManifest, description='生命周期钩子声明')
- jobs: list[PluginJobManifest] = Field(default_factory=list, description='插件定时任务声明列表')
+ jobs: list[_JobT] = Field(default_factory=list, description='插件定时任务声明列表')
@field_validator('module')
@classmethod
@@ -241,7 +249,7 @@ def validate_module(cls, value: str) -> str:
return value
@model_validator(mode='after')
- def validate_unique_jobs(self) -> 'BackendManifest':
+ def validate_unique_jobs(self) -> Self:
"""
校验插件定时任务 ID 唯一性。
@@ -258,7 +266,7 @@ def validate_unique_jobs(self) -> 'BackendManifest':
class PluginDependencyManifest(BaseModel):
"""插件间依赖声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
id: str = Field(description='依赖插件ID')
version: str | None = Field(default=None, description='依赖插件版本约束,例如 >=1.0.0')
@@ -315,7 +323,7 @@ def validate_version_constraint(cls, value: str | None) -> str | None:
class FrontendDependencyManifest(BaseModel):
"""指定前端框架的宿主前端依赖声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
npm: list[str] = Field(default_factory=list, description='前端 npm 依赖声明')
npm_dev: list[str] = Field(default_factory=list, alias='npmDev', description='前端 npm 开发依赖声明')
@@ -328,7 +336,7 @@ class DependencyManifest(BaseModel):
前端依赖按宿主前端框架在 frontend 中分类声明,各分类独立维护完整依赖列表。
"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
python: list[str] = Field(default_factory=list, description='Python 依赖声明')
frontend: dict[str, FrontendDependencyManifest] = Field(
@@ -416,7 +424,7 @@ def validate_unique_plugins(self) -> 'DependencyManifest':
class PluginMetadataManifest(BaseModel):
"""插件展示元数据声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
category: str = Field(default='', description='插件分类')
tags: list[str] = Field(default_factory=list, description='插件标签')
@@ -474,7 +482,7 @@ def validate_tags(cls, value: list[str]) -> list[str]:
class CompatibilityManifest(BaseModel):
"""插件平台兼容性声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
backend_version: str | None = Field(default=None, alias='backendVersion', description='后端版本约束')
frontend_version: str | None = Field(default=None, alias='frontendVersion', description='前端版本约束')
@@ -520,7 +528,7 @@ def validate_unique_databases(
class PluginResourceManifest(BaseModel):
"""插件资源声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
static: list[str] = Field(default_factory=list, description='插件静态资源相对路径列表')
uploads: list[str] = Field(default_factory=list, description='插件上传资源相对路径列表')
@@ -549,7 +557,7 @@ def validate_resource_paths(cls, value: list[str]) -> list[str]:
class PluginPermissionManifest(BaseModel):
"""插件权限声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
code: str = Field(validation_alias=AliasChoices('code', 'perms', 'permission'), description='权限标识')
name: str | None = Field(default=None, description='权限展示名称')
@@ -626,7 +634,7 @@ def validate_description(cls, value: str) -> str:
class PluginConfigOptionManifest(BaseModel):
"""插件配置选项声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
label: str = Field(description='配置选项展示名称')
value: PluginConfigValue = Field(description='配置选项值')
@@ -635,7 +643,7 @@ class PluginConfigOptionManifest(BaseModel):
class PluginConfigItemManifest(BaseModel):
"""插件配置项声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
key: str = Field(description='配置键名')
label: str | None = Field(default=None, description='配置展示名称')
@@ -750,8 +758,6 @@ def _validate_default_value(self) -> None:
return
if self.type == 'boolean' and not isinstance(self.default, bool):
raise ValueError(f'配置 {self.key} 的 default 必须是布尔值')
- if self.type == 'number' and (not isinstance(self.default, int | float) or isinstance(self.default, bool)):
- raise ValueError(f'配置 {self.key} 的 default 必须是数字')
if self.type == 'json' and not isinstance(self.default, dict | list):
raise ValueError(f'配置 {self.key} 的 default 必须是对象或数组')
@@ -759,12 +765,14 @@ def _validate_number_range(self) -> None:
"""
校验数字配置范围。
- :raises ValueError: 上下限互相矛盾或默认值超出范围
+ :raises ValueError: 上下限互相矛盾,或数字配置的默认值类型、取值范围有误
"""
if self.min_value is not None and self.max_value is not None and self.min_value > self.max_value:
raise ValueError(f'配置 {self.key} 的 min 不能大于 max')
if self.default is None or self.type != 'number':
return
+ if not isinstance(self.default, int | float) or isinstance(self.default, bool):
+ raise ValueError(f'配置 {self.key} 的 default 必须是数字')
if self.min_value is not None and self.default < self.min_value:
raise ValueError(f'配置 {self.key} 的 default 不能小于 min')
if self.max_value is not None and self.default > self.max_value:
@@ -793,7 +801,7 @@ def _validate_pattern(self) -> None:
class PluginConfigManifest(BaseModel):
"""插件配置声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
items: list[PluginConfigItemManifest] = Field(default_factory=list, description='插件配置项列表')
@@ -841,7 +849,7 @@ def validate_unique_keys(self) -> 'PluginConfigManifest':
class PluginMenuManifest(BaseModel):
"""插件菜单声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
name: str = Field(description='菜单名称')
name_i18n: dict[str, str] = Field(default_factory=dict, alias='nameI18n', description='多语言名称')
@@ -944,25 +952,35 @@ def validate_component_for_menu_type(self) -> 'PluginMenuManifest':
return self
-class FrontendDeliveryManifest(BaseModel):
+_DeliveryKindT = TypeVar('_DeliveryKindT', bound=Literal['none', 'source', 'bundle'], default=Literal['none', 'source'])
+
+
+class FrontendDeliveryManifest(BaseModel, Generic[_DeliveryKindT]):
"""插件前端交付声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
- type: Literal['none', 'source'] = Field(default='none', description='前端交付类型')
+ type: Annotated[_DeliveryKindT, Field(default='none', description='前端交付类型')]
build_required: bool = Field(default=False, alias='buildRequired', description='前端资源是否需要构建后生效')
-class FrontendManifest(BaseModel):
+_DeliveryT = TypeVar(
+ '_DeliveryT',
+ bound='FrontendDeliveryManifest | manifest_models.v2.FrontendDeliveryManifestV2',
+ default=FrontendDeliveryManifest,
+)
+
+
+class FrontendManifest(BaseModel, Generic[_DeliveryT]):
"""插件前端声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
plugin_id: str | None = Field(default=None, alias='pluginId', description='前端插件目录名')
base_path: str | None = Field(default=None, alias='basePath', description='前端基础路径')
views_path: str = Field(default='views', alias='viewsPath', description='前端视图目录')
api_path: str = Field(default='api', alias='apiPath', description='前端 API 目录')
- delivery: FrontendDeliveryManifest = Field(default_factory=FrontendDeliveryManifest, description='前端交付声明')
+ delivery: Annotated[_DeliveryT, Field(default_factory=FrontendDeliveryManifest, description='前端交付声明')]
menus: list[PluginMenuManifest] = Field(default_factory=list, description='菜单声明列表')
@field_validator('plugin_id')
@@ -1005,26 +1023,41 @@ def validate_relative_path(cls, value: str) -> str:
return value
-class PluginManifest(BaseModel):
+_VersionT = TypeVar('_VersionT', bound=Literal[1, 2], default=Literal[1])
+_BackendT = TypeVar(
+ '_BackendT', bound='BackendManifest | manifest_models.v2.BackendManifestV2', default=BackendManifest
+)
+_FrontendT = TypeVar(
+ '_FrontendT', bound='FrontendManifest | manifest_models.v2.FrontendManifestV2', default=FrontendManifest
+)
+_CompatibilityT = TypeVar('_CompatibilityT', bound=CompatibilityManifest, default=CompatibilityManifest)
+
+
+class PluginManifest(BaseModel, Generic[_VersionT, _BackendT, _FrontendT, _CompatibilityT]):
"""插件主清单。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
- manifest_version: Literal[1] = Field(
- default=SUPPORTED_MANIFEST_VERSION,
- alias='manifestVersion',
- description='插件清单版本',
- )
+ manifest_version: Annotated[
+ _VersionT,
+ Field(
+ default=SUPPORTED_MANIFEST_VERSION,
+ alias='manifestVersion',
+ description='插件清单版本',
+ ),
+ ]
id: str = Field(description='插件唯一标识')
name: str = Field(description='插件名称')
version: str = Field(description='插件版本')
description: str = Field(default='', description='插件说明')
metadata: PluginMetadataManifest = Field(default_factory=PluginMetadataManifest, description='插件展示元数据')
- backend: BackendManifest = Field(description='后端声明')
- frontend: FrontendManifest = Field(default_factory=FrontendManifest, description='前端声明')
+ backend: _BackendT = Field(description='后端声明')
+ frontend: Annotated[_FrontendT, Field(default_factory=FrontendManifest, description='前端声明')]
permissions: list[PluginPermissionManifest] = Field(default_factory=list, description='权限声明列表')
dependencies: DependencyManifest = Field(default_factory=DependencyManifest, description='依赖声明')
- compatibility: CompatibilityManifest = Field(default_factory=CompatibilityManifest, description='平台兼容性声明')
+ compatibility: Annotated[
+ _CompatibilityT, Field(default_factory=CompatibilityManifest, description='平台兼容性声明')
+ ]
resources: PluginResourceManifest = Field(default_factory=PluginResourceManifest, description='插件资源声明')
config: PluginConfigManifest = Field(default_factory=PluginConfigManifest, description='插件配置声明')
@@ -1089,7 +1122,7 @@ def runtime_kind(self) -> str:
:return: 插件后端交付类型
"""
- return getattr(self.backend, 'runtime', 'python')
+ return self.backend.runtime if isinstance(self.backend, manifest_models.v2.BackendManifestV2) else 'python'
@property
def integration_kind(self) -> str:
@@ -1098,7 +1131,7 @@ def integration_kind(self) -> str:
:return: 插件 Web 接入类型
"""
- return getattr(self.backend, 'integration', 'router')
+ return self.backend.integration if isinstance(self.backend, manifest_models.v2.BackendManifestV2) else 'router'
@property
def uses_entrypoint(self) -> bool:
@@ -1119,7 +1152,7 @@ def permission_name_map(self) -> dict[str, str]:
return {permission.code: permission.name for permission in self.permissions if permission.name}
@model_validator(mode='after')
- def fill_frontend_defaults(self) -> 'PluginManifest':
+ def fill_frontend_defaults(self) -> Self:
"""
填充前端声明默认值并执行跨字段校验。
@@ -1271,7 +1304,7 @@ class PluginManifestFactory:
"""
@classmethod
- def create(cls, raw_manifest: dict[str, Any]) -> PluginManifest:
+ def create(cls, raw_manifest: dict[str, Any]) -> 'manifest_models.v2.VersionedPluginManifest':
"""
从原始字典创建插件清单。
@@ -1279,7 +1312,5 @@ def create(cls, raw_manifest: dict[str, Any]) -> PluginManifest:
:return: 插件清单模型
"""
if raw_manifest.get('manifestVersion', raw_manifest.get('manifest_version', 1)) == EXPLICIT_MANIFEST_VERSION:
- from plugins.core.manifest.v2 import PluginManifestV2 # noqa: PLC0415
-
- return PluginManifestV2.model_validate(raw_manifest)
+ return manifest_models.v2.PluginManifestV2.model_validate(raw_manifest)
return PluginManifest.model_validate(raw_manifest)
diff --git a/ruoyi-fastapi-backend/plugins/core/manifest/v2.py b/ruoyi-fastapi-backend/plugins/core/manifest/v2.py
index e07da79f0..2c30c1f2e 100644
--- a/ruoyi-fastapi-backend/plugins/core/manifest/v2.py
+++ b/ruoyi-fastapi-backend/plugins/core/manifest/v2.py
@@ -1,5 +1,5 @@
import re
-from typing import Literal
+from typing import Literal, TypeAlias
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
@@ -37,7 +37,7 @@ def validate_relative_resource(value: str) -> str:
class NativeManifest(BaseModel):
"""已经离线安装到插件目录的原生发行包声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
distribution: str = Field(
pattern=r'^[A-Za-z0-9](?:[A-Za-z0-9_.-]*[A-Za-z0-9])?$', description='已安装的原生发行包名称'
@@ -50,13 +50,13 @@ class NativeManifest(BaseModel):
class AsgiManifest(BaseModel):
"""子应用挂载与生命周期声明。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
mount_path: str | None = Field(default=None, alias='mountPath', description='ASGI 子应用的挂载路径')
lifespan: Literal['managed', 'none'] = Field(default='managed', description='子应用生命周期管理方式')
-class PluginJobManifestV2(PluginJobManifest):
+class PluginJobManifestV2(PluginJobManifest[Literal['default']]):
"""在宿主事件循环中分发,禁止把原生对象发送至进程池。"""
executor: Literal['default'] = Field(default='default', description='调度任务使用的执行器')
@@ -70,14 +70,14 @@ class PluginJobManifestV2(PluginJobManifest):
)
-class BackendManifestV2(BackendManifest):
+class BackendManifestV2(BackendManifest[PluginJobManifestV2]):
"""交付运行时和 Web 接入方式彼此独立。"""
runtime: Literal['python', 'native'] = Field(default='python', description='插件后端运行时类型')
integration: Literal['router', 'asgi'] = Field(default='router', description='插件接入宿主的方式')
entrypoint: str = Field(description='创建插件后端的入口函数路径')
routers: RouterManifest = Field(
- default_factory=lambda: RouterManifest(autoScan=False), description='插件的路由注册配置'
+ default_factory=lambda: RouterManifest(auto_scan=False), description='插件的路由注册配置'
)
native: NativeManifest | None = Field(default=None, description='原生后端的发行包配置')
asgi: AsgiManifest | None = Field(default=None, description='ASGI 子应用配置')
@@ -130,16 +130,14 @@ def validate_delivery(self) -> 'BackendManifestV2':
return self
-class FrontendDeliveryManifestV2(FrontendDeliveryManifest):
+class FrontendDeliveryManifestV2(FrontendDeliveryManifest[Literal['none', 'source', 'bundle']]):
"""独立构建产物不参与宿主前端构建。"""
- type: Literal['none', 'source', 'bundle'] = Field(default='none', description='前端交付类型')
-
class FrontendBundleManifest(BaseModel):
"""插件内的静态构建资源。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
directory: str = Field(default='web/dist', description='前端资源包目录')
entry: str = Field(default='index.html', description='前端资源包的入口文件')
@@ -162,7 +160,7 @@ def validate_html_entry(cls, value: str) -> str:
return value
-class FrontendManifestV2(FrontendManifest):
+class FrontendManifestV2(FrontendManifest[FrontendDeliveryManifestV2]):
"""兼容源码页面并增加构建产物声明。"""
delivery: FrontendDeliveryManifestV2 = Field(
@@ -191,7 +189,7 @@ def validate_host_api_version(cls, value: str) -> str:
return value
-class PluginManifestV2(PluginManifest):
+class PluginManifestV2(PluginManifest[Literal[2], BackendManifestV2, FrontendManifestV2, CompatibilityManifestV2]):
"""继承通用权限、菜单、配置及依赖规则,替换交付相关约束。"""
manifest_version: Literal[2] = Field(default=2, alias='manifestVersion', description='插件清单格式版本')
@@ -260,3 +258,7 @@ def _validate_job_callable_prefixes(self) -> None:
expected_prefix = f'{self.backend.module}.'
if any(not job.callable.startswith(expected_prefix) for job in self.backend.jobs):
raise ValueError(f'插件任务 callable 必须使用 {expected_prefix} 前缀')
+
+
+VersionedPluginManifest: TypeAlias = PluginManifest | PluginManifestV2
+VersionedPluginJobManifest: TypeAlias = PluginJobManifest | PluginJobManifestV2
diff --git a/ruoyi-fastapi-backend/plugins/core/native/wheel.py b/ruoyi-fastapi-backend/plugins/core/native/wheel.py
index deef02483..0127cfcfd 100644
--- a/ruoyi-fastapi-backend/plugins/core/native/wheel.py
+++ b/ruoyi-fastapi-backend/plugins/core/native/wheel.py
@@ -16,7 +16,7 @@
from packaging.utils import canonicalize_name, parse_wheel_filename
from packaging.version import Version
-from plugins.core.manifest.schema import PluginManifest
+from plugins.core.manifest.v2 import BackendManifestV2, VersionedPluginManifest
from plugins.core.utils import is_windows_reserved
MAX_WHEEL_FILES = 10000
@@ -25,17 +25,32 @@
RECORD_COLUMN_COUNT = 3
-def _matching_rank(path: Path, manifest: PluginManifest) -> int:
+def _native_distribution(manifest: VersionedPluginManifest) -> str:
+ """
+ 从原生插件清单中读取 wheel 的发行包名称。
+
+ :param manifest: 插件清单对象
+ :return: 原生后端声明的发行包名称
+ :raises ValueError: 当前清单缺少原生运行时或发行包声明
+ """
+ backend = manifest.backend
+ if not isinstance(backend, BackendManifestV2) or backend.runtime != 'native' or backend.native is None:
+ raise ValueError('仅 native 插件可使用原生 wheel')
+ return backend.native.distribution
+
+
+def _matching_rank(path: Path, distribution: str, plugin_version: str) -> int:
"""
校验 wheel 身份并计算当前解释器支持的最佳平台标签优先级。
:param path: 待处理的文件路径
- :param manifest: 插件清单对象
+ :param distribution: 清单声明的原生发行包名称
+ :param plugin_version: 清单声明的插件版本
:return: 匹配标签在解释器支持列表中的最小序号
:raises ValueError: wheel 身份不匹配或当前解释器、ABI、平台不受支持
"""
name, version, _, tags = parse_wheel_filename(path.name)
- if name != canonicalize_name(manifest.backend.native.distribution) or version != Version(manifest.version):
+ if name != canonicalize_name(distribution) or version != Version(plugin_version):
raise ValueError('wheel 名称或版本与插件清单不一致')
ranks = [
index for index, tag in enumerate(sys_tags()) if tag in tags and tag.abi != 'none' and tag.platform != 'any'
@@ -45,7 +60,7 @@ def _matching_rank(path: Path, manifest: PluginManifest) -> int:
return min(ranks)
-def select_native_wheel(directory: Path, manifest: PluginManifest) -> Path:
+def select_native_wheel(directory: Path, manifest: VersionedPluginManifest) -> Path:
"""
从目录中选择名称、版本及解释器平台标签均匹配的原生 wheel。
@@ -54,8 +69,7 @@ def select_native_wheel(directory: Path, manifest: PluginManifest) -> Path:
:return: 兼容性优先级最高的 wheel 文件路径
:raises ValueError: 插件不是原生类型或目录中没有匹配的 wheel
"""
- if manifest.runtime_kind != 'native':
- raise ValueError('仅 native 插件可选择 wheel')
+ distribution = _native_distribution(manifest)
def candidate(path: Path) -> tuple[int, str, Path] | None:
"""
@@ -65,7 +79,7 @@ def candidate(path: Path) -> tuple[int, str, Path] | None:
:return: 标签优先级、文件名和路径,不兼容时为 None
"""
try:
- return _matching_rank(path, manifest), path.name, path
+ return _matching_rank(path, distribution, manifest.version), path.name, path
except ValueError:
return None
@@ -96,7 +110,7 @@ def _safe_member(name: str) -> PurePosixPath:
return path
-def _inventory(archive: ZipFile, manifest: PluginManifest) -> tuple[dict[str, ZipInfo], str]:
+def _inventory(archive: ZipFile, manifest: VersionedPluginManifest) -> tuple[dict[str, ZipInfo], str]:
"""
检查压缩条目、资源上限及允许的模块边界,并定位唯一元数据目录。
@@ -154,14 +168,15 @@ def _verify_dependency(value: str) -> None:
raise ValueError(f'宿主 wheel 依赖版本不匹配:{requirement}')
-def _verify_metadata(archive: ZipFile, metadata_root: str, wheel: Path, manifest: PluginManifest) -> None:
+def _verify_metadata(archive: ZipFile, metadata_root: str, wheel: Path, distribution: str, plugin_version: str) -> None:
"""
核对 wheel 发行包身份、版本、Python 要求及已安装依赖。
:param archive: 已打开的 ZIP 压缩容器
:param metadata_root: wheel 内唯一的 dist-info 元数据目录名
:param wheel: 待验证或展开的原生 wheel 文件路径
- :param manifest: 插件清单对象
+ :param distribution: 清单声明的原生发行包名称
+ :param plugin_version: 清单声明的插件版本
:raises ValueError: 发行包元数据、平台标签或宿主依赖不匹配
"""
metadata_path = f'{metadata_root}/METADATA'
@@ -169,9 +184,9 @@ def _verify_metadata(archive: ZipFile, metadata_root: str, wheel: Path, manifest
if metadata_path not in archive.namelist() or record_path not in archive.namelist():
raise ValueError('wheel 缺少 METADATA 或 RECORD')
metadata = Parser().parsestr(archive.read(metadata_path).decode('utf-8'))
- if canonicalize_name(metadata.get('Name', '')) != canonicalize_name(manifest.backend.native.distribution):
+ if canonicalize_name(metadata.get('Name', '')) != canonicalize_name(distribution):
raise ValueError('wheel METADATA 的发行包名称不匹配')
- if Version(metadata.get('Version', '')) != Version(manifest.version):
+ if Version(metadata.get('Version', '')) != Version(plugin_version):
raise ValueError('wheel METADATA 的版本不匹配')
if metadata.get('Requires-Python') and not SpecifierSet(metadata['Requires-Python']).contains(
platform.python_version()
@@ -221,7 +236,7 @@ def _verify_record(archive: ZipFile, files: dict[str, ZipInfo], record_path: str
raise ValueError(f'wheel 文件摘要不匹配:{name}')
-def install_native_wheel(wheel: Path, destination: Path, manifest: PluginManifest) -> None:
+def install_native_wheel(wheel: Path, destination: Path, manifest: VersionedPluginManifest) -> None:
"""
验证原生 wheel 后展开到全新目录,不覆盖已有版本或执行安装脚本。
@@ -235,15 +250,14 @@ def install_native_wheel(wheel: Path, destination: Path, manifest: PluginManifes
:raises FileExistsError: 目标目录已经存在,不能覆盖安装
:raises BaseException: 执行中断,清理后向调用方传播原异常
"""
- if manifest.runtime_kind != 'native':
- raise ValueError('仅 native 插件可安装 wheel')
+ distribution = _native_distribution(manifest)
target = destination.resolve()
if target.exists():
raise FileExistsError('原生安装目录已存在,请使用新目录并通过重启切换版本')
with ZipFile(wheel) as archive:
- _matching_rank(wheel, manifest)
+ _matching_rank(wheel, distribution, manifest.version)
files, metadata_root = _inventory(archive, manifest)
- _verify_metadata(archive, metadata_root, wheel, manifest)
+ _verify_metadata(archive, metadata_root, wheel, distribution, manifest.version)
_verify_record(archive, files, f'{metadata_root}/RECORD')
target.mkdir(parents=True, exist_ok=False)
try:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/application.py b/ruoyi-fastapi-backend/plugins/core/runtime/application.py
index 5678841dc..9d10466d7 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/application.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/application.py
@@ -3,6 +3,7 @@
import time
from collections.abc import Awaitable, Callable, Mapping
from functools import cache
+from typing import TYPE_CHECKING
from fastapi import FastAPI
@@ -15,6 +16,9 @@
from .service.lifecycle_lock import NoopPluginLifecycleLock, PluginLifecycleLock
+if TYPE_CHECKING:
+ from plugins.core.deployment.worker import PluginReleaseWorker
+
class PluginApplicationRuntime:
"""
@@ -42,10 +46,10 @@ def __init__(
ready_expire_seconds: int = LockConstant.PLUGIN_STARTUP_READY_EXPIRE_SECONDS,
failed_expire_seconds: int = LockConstant.PLUGIN_STARTUP_FAILED_EXPIRE_SECONDS,
ready_wait_timeout_seconds: int = LockConstant.PLUGIN_STARTUP_READY_WAIT_TIMEOUT_SECONDS,
- ready_wait_interval_seconds: int = LockConstant.PLUGIN_STARTUP_READY_WAIT_INTERVAL_SECONDS,
+ ready_wait_interval_seconds: float = LockConstant.PLUGIN_STARTUP_READY_WAIT_INTERVAL_SECONDS,
lifecycle_lock: PluginLifecycleLock | None = None,
startup_generation: str | None = None,
- release_worker: object | None = None,
+ release_worker: 'PluginReleaseWorker | None' = None,
) -> None:
"""
初始化插件应用运行时适配器。
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/asgi.py b/ruoyi-fastapi-backend/plugins/core/runtime/asgi.py
index b25c41075..8c36d3510 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/asgi.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/asgi.py
@@ -110,7 +110,7 @@ async def _startup(self) -> None:
scope = {'type': 'lifespan', 'asgi': {'version': '3.0', 'spec_version': '2.0'}, 'state': self.state}
self._task = asyncio.create_task(self._invoke(scope))
try:
- await self._exchange('startup')
+ await self._exchange('startup', self._task)
self.started = True
except BaseException:
await self._cancel_task()
@@ -131,12 +131,13 @@ async def _shutdown(self) -> None:
was_started = self.started
self.started = False
try:
- if was_started and self.managed:
- await self._exchange('shutdown')
- done, _ = await asyncio.wait({self._task}, timeout=self.timeout)
+ task = self._task
+ if was_started and self.managed and task is not None:
+ await self._exchange('shutdown', task)
+ done, _ = await asyncio.wait({task}, timeout=self.timeout)
if not done:
raise TimeoutError('ASGI lifespan.shutdown 确认后未退出')
- self._check_task_result()
+ self._check_task_result(task)
finally:
await self._cancel_task()
@@ -148,45 +149,46 @@ async def _invoke(self, scope: Scope) -> None:
"""
await self.app(scope, self._receive.get, self._send.put)
- async def _exchange(self, event: str) -> None:
+ async def _exchange(self, event: str, task: asyncio.Task[None]) -> None:
"""
发送生命周期事件并等待子应用确认。
:param event: 生命周期事件名称,支持 startup 和 shutdown
+ :param task: 处理本轮生命周期事件的子应用任务
:raises RuntimeError: ASGI lifespan 在 startup 后提前退出
:raises TimeoutError: 等待 ASGI 生命周期应答超时
"""
await self._receive.put({'type': f'lifespan.{event}'})
response = asyncio.create_task(self._send.get())
try:
- done, _ = await asyncio.wait(
- (response, self._task), timeout=self.timeout, return_when=asyncio.FIRST_COMPLETED
- )
+ done, _ = await asyncio.wait((response, task), timeout=self.timeout, return_when=asyncio.FIRST_COMPLETED)
if response not in done:
- if self._task in done:
- self._check_task_result()
+ if task in done:
+ self._check_task_result(task)
raise RuntimeError(f'ASGI 应用在 lifespan.{event} 确认前退出')
raise TimeoutError(f'ASGI lifespan.{event} 超时')
message = response.result()
if message.get('type') != f'lifespan.{event}.complete':
raise RuntimeError(f'ASGI lifespan.{event} 失败:{message.get("message", message.get("type"))}')
- if event == 'startup' and self._task.done():
- self._check_task_result()
+ if event == 'startup' and task.done():
+ self._check_task_result(task)
raise RuntimeError('ASGI lifespan 在 startup 后提前退出')
finally:
response.cancel()
with suppress(asyncio.CancelledError):
await response
- def _check_task_result(self) -> None:
+ @staticmethod
+ def _check_task_result(task: asyncio.Task[None]) -> None:
"""
将子应用自行取消作为协议失败,保留宿主调用者自身的取消语义。
+ :param task: 已结束的生命周期任务
:raises RuntimeError: ASGI 生命周期任务自行取消
"""
- if self._task.cancelled():
+ if task.cancelled():
raise RuntimeError('ASGI 生命周期任务自行取消')
- self._task.result()
+ task.result()
async def _cancel_task(self) -> None:
"""取消并回收当前 worker 的生命周期任务。"""
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/configuration.py b/ruoyi-fastapi-backend/plugins/core/runtime/configuration.py
index 4ad99c7a5..ebf5d6bfd 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/configuration.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/configuration.py
@@ -5,9 +5,9 @@
from collections.abc import Callable, Mapping
from typing import Any
-from pydantic import BaseModel, ConfigDict, Field
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field
+from common.vo import CamelModel
from config.env import JwtConfig
from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.sdk.config import PluginConfigSnapshot
@@ -31,10 +31,10 @@ def config_revision(plugin_id: str, values: Mapping[str, Any]) -> str:
return hmac.new(JwtConfig.jwt_secret_key.encode('utf-8'), payload, hashlib.sha256).hexdigest()
-class PluginConfigObservation(BaseModel):
+class PluginConfigObservation(CamelModel):
"""当前 worker 的启动配置和最近一次按需读取版本,不包含配置值。"""
- model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra='forbid', strict=True)
+ model_config = ConfigDict(extra='forbid', strict=True)
plugin_id: str = Field(pattern=r'^[a-z][a-z0-9_]{1,63}$', description='插件标识')
version: str = Field(max_length=128, description='插件版本')
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/connections.py b/ruoyi-fastapi-backend/plugins/core/runtime/connections.py
index 8152c6373..2ddea7c41 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/connections.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/connections.py
@@ -106,7 +106,7 @@ def __init__(
self.cancel_timeout = cancel_timeout
self.closing = False
self.connections: set[_PluginConnection] = set()
- self._unfinished: set[asyncio.Task[Any]] = set()
+ self._unfinished: set[asyncio.Future[Any]] = set()
def connection_counts(self) -> dict[str, int]:
"""
@@ -119,7 +119,7 @@ def connection_counts(self) -> dict[str, int]:
'websocket': sum(connection.scope['type'] == 'websocket' for connection in self.connections),
}
- def pending_tasks(self) -> frozenset[asyncio.Task[Any]]:
+ def pending_tasks(self) -> frozenset[asyncio.Future[Any]]:
"""
为宿主诊断提供尚未结束的取消超时任务快照,不改变任务或清理集合。
@@ -155,13 +155,17 @@ async def drain(self) -> None:
connections = tuple(self.connections)
for connection in connections:
connection.stop(PLUGIN_SHUTDOWN)
- owners = {connection.owner for connection in connections if connection.owner is not asyncio.current_task()}
+ owners = {
+ connection.owner
+ for connection in connections
+ if connection.owner is not None and connection.owner is not asyncio.current_task()
+ }
if owners:
_, pending = await asyncio.wait(owners, timeout=self.cancel_timeout * 2 + 1)
if pending:
logger.warning('插件连接关闭等待超时:{} 个请求尚未退出', len(pending))
- async def cancel_task(self, task: asyncio.Task[Any]) -> None:
+ async def cancel_task(self, task: asyncio.Future[Any]) -> None:
"""
有界等待协作式取消,保留未退出任务并回收它们最终的异常。
@@ -178,7 +182,7 @@ async def cancel_task(self, task: asyncio.Task[Any]) -> None:
task.add_done_callback(self._finish_task)
logger.warning('插件连接任务未响应取消;输出已隔离,等待任务自行退出')
- def _finish_task(self, task: asyncio.Task[Any]) -> None:
+ def _finish_task(self, task: asyncio.Future[Any]) -> None:
"""
释放迟到任务并读取异常,避免未处理任务异常告警。
@@ -388,7 +392,7 @@ async def _close_response(self, reason: ConnectionClosure) -> None:
self.scope, self.receive, self.send
)
return
- sender = asyncio.create_task(self.send(message))
+ sender = asyncio.ensure_future(self.send(message))
try:
done, _ = await asyncio.wait({sender}, timeout=self.manager.cancel_timeout)
if sender in done:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics.py b/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics.py
index f5fe861eb..516fc6469 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics.py
@@ -2,23 +2,24 @@
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, Literal
-from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, ValidationInfo, field_validator, model_validator
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field, NonNegativeInt, ValidationInfo, field_validator, model_validator
+from common.vo import CamelModel
from plugins.core.runtime.task_cleanup import pending_plugin_tasks
if TYPE_CHECKING:
+ import asyncio
+
from plugins.core.runtime.explicit import ExplicitPluginRuntime, LoadedExplicitPlugin
from plugins.core.runtime.health import PluginHealthResult
- from plugins.core.runtime.metrics import PluginMetricSeries
MAX_DIAGNOSTIC_PLUGINS = 1024
-class _DiagnosticModel(BaseModel):
+class _DiagnosticModel(CamelModel):
"""只接收有界的宿主观测字段,禁止混入插件业务对象或额外字段。"""
- model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra='forbid', strict=True)
+ model_config = ConfigDict(extra='forbid', strict=True)
@model_validator(mode='before')
@classmethod
@@ -173,21 +174,18 @@ def _recent_errors(runtime: 'ExplicitPluginRuntime') -> dict[str, PluginDiagnost
:param runtime: 当前 worker 的显式插件运行时
:return: 按插件 ID 索引的错误关联摘要
"""
- latest: dict[str, PluginMetricSeries] = {}
+ latest: dict[str, PluginDiagnosticError] = {}
for series in runtime.metrics.series.values():
if series.last_error_at is None or not series.last_error_type:
continue
previous = latest.get(series.plugin_id)
- if previous is None or series.last_error_at > previous.last_error_at:
- latest[series.plugin_id] = series
- return {
- plugin_id: PluginDiagnosticError(
- error_type=series.last_error_type,
- request_id=series.last_error_request_id,
- at=series.last_error_at,
- )
- for plugin_id, series in latest.items()
- }
+ if previous is None or series.last_error_at > previous.at:
+ latest[series.plugin_id] = PluginDiagnosticError(
+ error_type=series.last_error_type,
+ request_id=series.last_error_request_id,
+ at=series.last_error_at,
+ )
+ return latest
def _plugin_observation(
@@ -249,7 +247,7 @@ def collect_runtime_diagnostics(runtime: 'ExplicitPluginRuntime') -> PluginRunti
:param runtime: 当前 worker 的显式插件运行时
:return: 有界且独立于后续资源变化的诊断快照
"""
- pending = set(pending_plugin_tasks())
+ pending: set[asyncio.Future[Any]] = set(pending_plugin_tasks())
for loaded in runtime.loaded.values():
if loaded.gateway is not None:
pending.update(loaded.gateway.connections.pending_tasks())
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics_query.py b/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics_query.py
index ac8f941c0..99771fdd0 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics_query.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics_query.py
@@ -139,6 +139,7 @@ def build_runtime_diagnostics(
if host.get('state') != 'stopped' and _heartbeat_fresh(host, now, ttl)
}
workers = []
+ observed = []
for worker_id in sorted(set(snapshots) | set(hosts) | set(plugins) | stale_ids | invalid_ids):
snapshot = snapshots.get(worker_id)
reported_snapshot = reported_snapshots.get(worker_id)
@@ -147,6 +148,8 @@ def build_runtime_diagnostics(
if snapshot
else None
)
+ if actual is not None:
+ observed.append(actual)
freshness = (
'fresh'
if snapshot
@@ -181,13 +184,12 @@ def build_runtime_diagnostics(
'releaseReport': _release_report(worker_report, now, ttl),
}
)
- observed = [worker for worker in workers if worker['actual'] is not None]
totals = None
if observed:
totals = {
- **{key: sum(worker['actual'][key] for worker in observed) for key in RUNTIME_COUNTERS},
- 'sse': sum(worker['actual']['connections']['sse'] for worker in observed),
- 'websocket': sum(worker['actual']['connections']['websocket'] for worker in observed),
+ **{key: sum(plugin[key] for plugin in observed) for key in RUNTIME_COUNTERS},
+ 'sse': sum(plugin['connections']['sse'] for plugin in observed),
+ 'websocket': sum(plugin['connections']['websocket'] for plugin in observed),
}
expected = summary.get('expectedWorkers') if summary else None
missing = len(live_hosts - set(snapshots))
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/entrypoint.py b/ruoyi-fastapi-backend/plugins/core/runtime/entrypoint.py
index 2a8bdce05..b0a45aed8 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/entrypoint.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/entrypoint.py
@@ -8,6 +8,7 @@
import sysconfig
from dataclasses import dataclass
from importlib.machinery import EXTENSION_SUFFIXES
+from os import PathLike
from pathlib import Path
from types import ModuleType
from typing import Any
@@ -17,6 +18,7 @@
from packaging.version import Version
from plugins.core.discovery.scanner import DiscoveredPlugin
+from plugins.core.manifest.v2 import PluginManifestV2
from plugins.core.sdk import PluginDefinition, PluginHostContext
@@ -51,9 +53,10 @@ def __init__(self, plugin: DiscoveredPlugin) -> None:
:raises ValueError: 显式入口加载器仅用于 manifestVersion 2
"""
self.plugin = plugin
- self.backend = plugin.manifest.backend
- if not plugin.manifest.uses_entrypoint:
+ manifest = plugin.manifest
+ if not isinstance(manifest, PluginManifestV2):
raise ValueError('显式入口加载器仅用于 manifestVersion 2')
+ self.backend = manifest.backend
@property
def module_root(self) -> Path:
@@ -62,7 +65,7 @@ def module_root(self) -> Path:
:return: Python 插件目录或原生发行包安装目录的绝对路径
"""
- if self.plugin.manifest.runtime_kind == 'native':
+ if self.backend.native is not None:
return self._contained(self.plugin.backend_path / self.backend.native.module_root)
return self.plugin.backend_path.resolve()
@@ -130,11 +133,13 @@ def _check_native_distribution(self, location: PluginModuleLocation) -> None:
"""
if platform.python_implementation() != 'CPython' or sysconfig.get_config_var('Py_GIL_DISABLED'):
raise ValueError('当前 native 运行时仅支持带 GIL 的 CPython')
+ if self.backend.native is None:
+ raise ValueError('原生插件缺少发行包配置')
expected = canonicalize_name(self.backend.native.distribution)
matches = [
dist
for dist in importlib.metadata.distributions(path=[str(self.module_root)])
- if canonicalize_name(dist.metadata.get('Name', '')) == expected
+ if 'Name' in (metadata := dist.metadata) and canonicalize_name(metadata['Name']) == expected
]
if len(matches) != 1:
raise ValueError('native.moduleRoot 必须包含唯一匹配的已安装 wheel 元数据')
@@ -148,7 +153,11 @@ def _check_native_distribution(self, location: PluginModuleLocation) -> None:
tags.update(parse_tag(line.removeprefix('Tag: ').strip()))
if not any(tag.abi != 'none' and tag.platform != 'any' for tag in tags.intersection(sys_tags())):
raise ValueError('原生 wheel 平台、Python 或 ABI 与当前解释器不兼容')
- entries = [entry for entry in dist.files or [] if Path(dist.locate_file(entry)).resolve() == location.path]
+ entries = [
+ entry
+ for entry in dist.files or []
+ if isinstance(path := dist.locate_file(entry), (str, PathLike)) and Path(path).resolve() == location.path
+ ]
if len(entries) != 1 or entries[0].hash is None or entries[0].hash.mode != 'sha256':
raise ValueError('原生入口必须包含在发行包 RECORD 中并声明 SHA256')
digest = hashlib.sha256(location.path.read_bytes()).digest()
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/explicit.py b/ruoyi-fastapi-backend/plugins/core/runtime/explicit.py
index 12c31865d..5c9435f4f 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/explicit.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/explicit.py
@@ -6,7 +6,7 @@
from fastapi import Depends, FastAPI, HTTPException
from starlette.requests import Request
from starlette.routing import Mount
-from starlette.types import Scope
+from starlette.types import ASGIApp, Scope
from config.database import Base, DataSourceRegistry
from exceptions.exception import AuthException
@@ -15,6 +15,7 @@
from module_admin.service.login_service import LoginService
from plugins.core.discovery.registry import PluginRegistry, RegisteredPlugin
from plugins.core.discovery.scanner import is_artifact_plugin
+from plugins.core.manifest.v2 import PluginManifestV2
from plugins.core.runtime.asgi import PluginGatewayASGI, PluginLifespanManager
from plugins.core.runtime.browser_session import authenticate_browser_session
from plugins.core.runtime.bundle import PluginBundleASGI
@@ -305,7 +306,6 @@ async def _activate_web(self, loaded: LoadedExplicitPlugin, app: FastAPI) -> Non
:param loaded: 当前 worker 已准备的插件实例
:param app: 宿主 FastAPI 应用
:raises RuntimeError: 插件运行时已进入关闭阶段,不能注册路由
- :raises TypeError: app_factory 必须同步返回 ASGI 应用;app_factory 必须返回 ASGI callable
:raises ValueError: 挂载路径与应用已有路由冲突
:raises BaseException: 启动或挂载过程中断,清理资源后传播原异常
"""
@@ -317,20 +317,17 @@ async def _activate_web(self, loaded: LoadedExplicitPlugin, app: FastAPI) -> Non
raise RuntimeError('插件运行时已进入关闭阶段,不能注册路由')
self._register_routers(loaded, app)
else:
- child = loaded.definition.app_factory(loaded.host)
- if inspect.isawaitable(child):
- if inspect.iscoroutine(child):
- child.close()
- raise TypeError('app_factory 必须同步返回 ASGI 应用')
- if not callable(child):
- raise TypeError('app_factory 必须返回 ASGI callable')
- if isinstance(child, FastAPI):
- child.state.plugin_host = loaded.host
- child.state.redis = loaded.host.redis
- mount_path = manifest.backend.asgi.mount_path
+ if (
+ not isinstance(manifest, PluginManifestV2)
+ or (asgi := manifest.backend.asgi) is None
+ or not asgi.mount_path
+ ):
+ raise ValueError('ASGI 插件缺少挂载配置')
+ mount_path = asgi.mount_path
+ child = self._create_asgi_app(loaded)
if any(getattr(route, 'path', None) == mount_path for route in app.routes):
raise ValueError(f'插件挂载路径冲突:{mount_path}')
- manager = PluginLifespanManager(child, managed=manifest.backend.asgi.lifespan == 'managed')
+ manager = PluginLifespanManager(child, managed=asgi.lifespan == 'managed')
loaded.lifespan = manager
try:
await manager.startup()
@@ -338,7 +335,7 @@ async def _activate_web(self, loaded: LoadedExplicitPlugin, app: FastAPI) -> Non
if self._closing:
raise RuntimeError('插件运行时已进入关闭阶段,不能挂载子应用')
web_app = child
- if manifest.frontend.delivery.type == 'bundle':
+ if manifest.frontend.bundle is not None:
web_app = PluginBundleASGI(child, plugin_id, loaded.plugin.backend_path, manifest.frontend.bundle)
gateway = PluginGatewayASGI(web_app, manager, self._authorizer(loaded, app))
observed = PluginObservedASGI(gateway, self.metrics, plugin_id)
@@ -351,6 +348,29 @@ async def _activate_web(self, loaded: LoadedExplicitPlugin, app: FastAPI) -> Non
logger.exception(f'插件激活失败后的 ASGI 回收失败:{plugin_id}')
raise
+ @staticmethod
+ def _create_asgi_app(loaded: LoadedExplicitPlugin) -> ASGIApp:
+ """
+ 调用插件工厂创建子应用,并向 FastAPI 子应用传入宿主上下文。
+
+ :param loaded: 当前 worker 已准备的插件实例
+ :return: 插件工厂创建的 ASGI 应用
+ :raises TypeError: 缺少工厂,或工厂未同步返回可调用的 ASGI 应用
+ """
+ if loaded.definition.app_factory is None:
+ raise TypeError('ASGI 插件缺少 app_factory')
+ child = loaded.definition.app_factory(loaded.host)
+ if inspect.isawaitable(child):
+ if inspect.iscoroutine(child):
+ child.close()
+ raise TypeError('app_factory 必须同步返回 ASGI 应用')
+ if not callable(child):
+ raise TypeError('app_factory 必须返回 ASGI callable')
+ if isinstance(child, FastAPI):
+ child.state.plugin_host = loaded.host
+ child.state.redis = loaded.host.redis
+ return child
+
@staticmethod
async def _check_health(loaded: LoadedExplicitPlugin, app: FastAPI) -> None:
"""
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/host_services.py b/ruoyi-fastapi-backend/plugins/core/runtime/host_services.py
index 887316712..e2abfb62b 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/host_services.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/host_services.py
@@ -1,6 +1,6 @@
import json
import re
-from collections.abc import AsyncIterator, Callable
+from collections.abc import AsyncGenerator, Callable
from contextlib import asynccontextmanager
from typing import Any
@@ -30,7 +30,7 @@ def _require_request(context: PluginRequestContext, plugin_id: str, capability:
@asynccontextmanager
-async def _request_session(context: PluginRequestContext, factory: Callable[..., Any]) -> AsyncIterator[Any]:
+async def _request_session(context: PluginRequestContext, factory: Callable[..., Any]) -> AsyncGenerator[Any, None]:
"""
复用当前任务的显式事务;未开启事务时为单次只读服务创建独立会话。
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/job_dispatcher.py b/ruoyi-fastapi-backend/plugins/core/runtime/job_dispatcher.py
index af72b3278..a1753dc51 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/job_dispatcher.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/job_dispatcher.py
@@ -1,11 +1,12 @@
import asyncio
from collections.abc import Callable
from dataclasses import dataclass, field
-from typing import Any
+from typing import TYPE_CHECKING, Any
from uuid import uuid4
from middlewares.trace_middleware.ctx import CTX_REQUEST_ID
from plugins.core.discovery.scanner import DiscoveredPlugin
+from plugins.core.manifest.v2 import PluginJobManifestV2
from plugins.core.runtime.entrypoint import PluginEntrypointLoader
from plugins.core.runtime.metrics import MetricOutcome, PluginRuntimeMetrics
from plugins.core.runtime.route_guard import PluginRouteStateGateway
@@ -13,6 +14,9 @@
from plugins.core.sdk import PluginHostContext, PluginTaskContext, await_plugin_callback
from utils.log_util import logger
+if TYPE_CHECKING:
+ from plugins.core.runtime.service.gateway import AsyncSessionFactoryProtocol
+
DISPATCH_TARGET = 'plugins.core.runtime.job_dispatcher.dispatch_plugin_job'
@@ -24,6 +28,7 @@ class PluginJobBinding:
:ivar plugin: 任务所属的已发现插件
:ivar host: 任务使用的宿主能力上下文
:ivar gateway: 插件启用状态查询网关
+ :ivar session_factory: 绑定时选定的数据库会话工厂
:ivar ready: 查询插件是否就绪的回调
:ivar loop: 所属宿主事件循环
:ivar tasks: 当前仍在执行的插件异步任务集合
@@ -36,6 +41,7 @@ class PluginJobBinding:
gateway: PluginRouteStateGateway
ready: Callable[[], bool]
loop: asyncio.AbstractEventLoop
+ session_factory: 'AsyncSessionFactoryProtocol'
tasks: set[asyncio.Task[Any]] = field(default_factory=set)
metrics: PluginRuntimeMetrics | None = None
closing: bool = False
@@ -81,7 +87,9 @@ def bind_plugin_jobs(
raise RuntimeError(f'插件任务运行时已绑定:{plugin_id}')
if host.plugin_id != plugin_id or host.session_factory is None:
raise ValueError('任务宿主身份不匹配或缺少数据库会话工厂')
- binding = PluginJobBinding(plugin, host, gateway, ready, asyncio.get_running_loop(), metrics=metrics)
+ binding = PluginJobBinding(
+ plugin, host, gateway, ready, asyncio.get_running_loop(), host.session_factory, metrics=metrics
+ )
_bindings[plugin_id] = binding
return binding
@@ -116,19 +124,16 @@ async def unbind_plugin_jobs(binding: PluginJobBinding, *, grace_seconds: float
_release_binding(binding)
-async def dispatch_plugin_job(plugin_id: str, job_id: str, version: str) -> Any:
+def _resolve_job(plugin_id: str, job_id: str, version: str) -> tuple[PluginJobBinding, PluginJobManifestV2]:
"""
- APScheduler 仅保存此函数及三个字符串;不持久化上下文或原生 callable。
+ 根据调度记录解析当前事件循环中可执行的插件任务。
:param plugin_id: 任务所属的插件 ID
:param job_id: 插件清单声明的任务 ID
:param version: 调度记录绑定的插件版本
- :return: 插件异步任务回调的执行结果
- :raises RuntimeError: 插件任务必须在所属宿主事件循环执行
+ :return: 当前进程的任务绑定及清单中的任务声明
+ :raises RuntimeError: 插件未就绪、事件循环不匹配或插件版本已变更
:raises LookupError: 插件未声明指定的任务
- :raises asyncio.CancelledError: 异步操作被取消时
- :raises PermissionError: 当前执行上下文缺少调用所需的权限
- :raises Exception: 底层操作失败时向调用方传播异常
"""
binding = _bindings.get(plugin_id)
if binding is None or binding.closing or not binding.ready():
@@ -139,9 +144,29 @@ async def dispatch_plugin_job(plugin_id: str, job_id: str, version: str) -> Any:
if manifest.version != version:
raise RuntimeError(f'插件任务版本不匹配:{plugin_id},需重启并重新同步任务')
job = next((item for item in manifest.backend.jobs if item.id == job_id), None)
- if job is None:
+ if not isinstance(job, PluginJobManifestV2):
raise LookupError(f'插件未声明任务:{plugin_id}:{job_id}')
+ return binding, job
+
+
+async def dispatch_plugin_job(plugin_id: str, job_id: str, version: str) -> Any:
+ """
+ APScheduler 仅保存此函数及三个字符串;不持久化上下文或原生 callable。
+
+ :param plugin_id: 任务所属的插件 ID
+ :param job_id: 插件清单声明的任务 ID
+ :param version: 调度记录绑定的插件版本
+ :return: 插件异步任务回调的执行结果
+ :raises RuntimeError: 插件任务必须在所属宿主事件循环执行
+ :raises LookupError: 插件未声明指定的任务
+ :raises asyncio.CancelledError: 异步操作被取消时
+ :raises PermissionError: 当前执行上下文缺少调用所需的权限
+ :raises Exception: 底层操作失败时向调用方传播异常
+ """
+ binding, job = _resolve_job(plugin_id, job_id, version)
task = asyncio.current_task()
+ if task is None:
+ raise RuntimeError('插件任务必须由宿主异步任务执行')
binding.tasks.add(task)
request_id = uuid4().hex
token = CTX_REQUEST_ID.set(request_id)
@@ -155,7 +180,7 @@ async def dispatch_plugin_job(plugin_id: str, job_id: str, version: str) -> Any:
error_type, timed_out = None, False
try:
with logger.contextualize(**log_fields):
- async with binding.host.session_factory() as db:
+ async with binding.session_factory() as db:
if not await binding.gateway.is_plugin_enabled(db, plugin_id):
raise PermissionError(f'插件未启用:{plugin_id}')
# 数据库等待期间可能开始关闭,不能在解绑后再启动原生回调。
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/metrics.py b/ruoyi-fastapi-backend/plugins/core/runtime/metrics.py
index e75a7f59d..6a7f03852 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/metrics.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/metrics.py
@@ -6,11 +6,11 @@
from typing import Any, Literal
from uuid import uuid4
-from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, model_validator
-from pydantic.alias_generators import to_camel
+from pydantic import ConfigDict, Field, NonNegativeInt, model_validator
from starlette import status
from starlette.types import ASGIApp, Message, Receive, Scope, Send
+from common.vo import CamelModel
from middlewares.trace_middleware.ctx import CTX_REQUEST_ID
from plugins.core.runtime.configuration import PluginConfigObservation
from plugins.core.runtime.connections import CONNECTION_OUTCOME_KEY, ConnectionClosure
@@ -22,10 +22,10 @@
MetricOutcome = Literal['succeeded', 'rejected', 'failed', 'cancelled']
-class PluginMetricSeries(BaseModel):
+class PluginMetricSeries(CamelModel):
"""一个 worker 上某插件和操作的累计指标,不包含请求参数、路径或用户数据。"""
- model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra='forbid', strict=True)
+ model_config = ConfigDict(extra='forbid', strict=True)
plugin_id: str = Field(pattern=r'^[a-z][a-z0-9_]{1,63}$', description='插件标识')
version: str = Field(max_length=128, description='插件版本')
@@ -90,10 +90,10 @@ def to_payload(self) -> dict[str, Any]:
}
-class PluginMetricSnapshot(BaseModel):
+class PluginMetricSnapshot(CamelModel):
"""带采样时间和进程标识的有界指标快照。"""
- model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra='forbid', strict=True)
+ model_config = ConfigDict(extra='forbid', strict=True)
schema_version: Literal[1] = Field(default=1, description='数据结构的版本')
worker_id: str = Field(pattern=r'^[0-9a-f]{32}$', description='工作进程标识')
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/route_guard.py b/ruoyi-fastapi-backend/plugins/core/runtime/route_guard.py
index 6d8bfc729..42737ee57 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/route_guard.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/route_guard.py
@@ -1,6 +1,6 @@
-from typing import Protocol, runtime_checkable
+from typing import Annotated, Protocol, runtime_checkable
-from fastapi import Depends, params
+from fastapi import params
from sqlalchemy.ext.asyncio import AsyncSession
from common.aspect.db_session import DBSessionDependency
@@ -11,7 +11,7 @@
class PluginRouteStateGateway(Protocol):
"""插件路由状态读取端口。"""
- async def is_plugin_enabled(self, db: AsyncSession, plugin_id: str) -> bool:
+ async def is_plugin_enabled(self, db: AsyncSession, plugin_id: str, /) -> bool:
"""
判断插件路由是否允许访问。
@@ -55,7 +55,7 @@ def __init__(self, plugin_id: str, state_gateway: PluginRouteStateGateway | None
self.plugin_id = plugin_id
self.state_gateway = state_gateway or UnavailablePluginRouteStateGateway()
- async def __call__(self, db: AsyncSession = DBSessionDependency()) -> bool:
+ async def __call__(self, db: Annotated[AsyncSession, DBSessionDependency()]) -> bool:
"""
执行插件启用状态校验。
@@ -79,4 +79,4 @@ def PluginEnabledDependency( # noqa: N802
:param state_gateway: 插件路由状态读取端口
:return: 插件启用状态依赖
"""
- return Depends(CheckPluginEnabled(plugin_id, state_gateway))
+ return params.Depends(CheckPluginEnabled(plugin_id, state_gateway))
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/batch.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/batch.py
index eefe81c48..dd07a618f 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/batch.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/batch.py
@@ -1,6 +1,6 @@
from collections.abc import Mapping
from pathlib import Path
-from typing import Protocol, cast
+from typing import Protocol
from i18n.message import I18nMessage
from plugins.core.capability import PluginRuntimeCapability
@@ -229,7 +229,7 @@ def _build_plan_plugins_payload(
:return: 插件批量操作拓扑计划负载
"""
try:
- if operation not in {'install', 'enable', 'upgrade'}:
+ if operation not in ('install', 'enable', 'upgrade'):
return PluginRuntimePayloadBuilder.build_invalid_operation_payload(
None,
operation,
@@ -256,7 +256,7 @@ def _build_plan_plugins_payload(
payload['ok'] = False
payload['message'] = '插件批量操作计划存在环境阻断项'
payload['capabilityBlockers'] = capability_blockers
- return cast('PluginPlanResponse', payload)
+ return payload
except Exception as exc:
return PluginRuntimePayloadBuilder.build_exception_payload(
I18nMessage('生成插件批量操作计划失败', msg_key='plugin.runtime.batch.planFailed'), exc
@@ -316,7 +316,7 @@ async def batch_plugins(
:return: 插件批量执行结果负载
"""
try:
- plan_payload = cast('dict[str, object]', await self.plan_plugins_async(operation, plugin_ids))
+ plan_payload = await self.plan_plugins_async(operation, plugin_ids)
if not plan_payload.get('ok', False):
plan_payload = PluginBatchReportBuilder.build_plan_blocked_payload(
plan_payload,
@@ -329,14 +329,11 @@ async def batch_plugins(
dry_run=dry_run,
continue_on_error=continue_on_error,
)
- return cast('PluginBatchResponse', plan_payload)
+ return plan_payload
if dry_run:
- return cast(
- 'PluginBatchResponse',
- PluginBatchReportBuilder.build_dry_run_payload(
- plan_payload,
- continue_on_error=continue_on_error,
- ),
+ return PluginBatchReportBuilder.build_dry_run_payload(
+ plan_payload,
+ continue_on_error=continue_on_error,
)
reports = []
@@ -366,7 +363,7 @@ async def batch_plugins(
continue_on_error=continue_on_error,
)
- return cast('PluginBatchResponse', payload)
+ return payload
except Exception as exc:
return PluginRuntimePayloadBuilder.build_exception_payload(
I18nMessage('插件批量操作失败', msg_key='plugin.runtime.batch.failed'), exc
@@ -385,23 +382,14 @@ async def execute_batch_plugin_item(
:return: 单插件操作结果负载
"""
if operation == 'install':
- return cast(
- 'BatchOperationResultPayload',
- await self.runtime_operations.install_plugin(plugin_id, dry_run=False, record_operation_log=False),
- )
+ return await self.runtime_operations.install_plugin(plugin_id, dry_run=False, record_operation_log=False)
if operation == 'enable':
- return cast(
- 'BatchOperationResultPayload',
- await self.runtime_operations.set_plugin_enabled(
- plugin_id,
- enabled=True,
- dry_run=False,
- record_operation_log=False,
- ),
+ return await self.runtime_operations.set_plugin_enabled(
+ plugin_id,
+ enabled=True,
+ dry_run=False,
+ record_operation_log=False,
)
if operation == 'upgrade':
- return cast(
- 'BatchOperationResultPayload',
- await self.runtime_operations.upgrade_plugin(plugin_id, dry_run=False, record_operation_log=False),
- )
+ return await self.runtime_operations.upgrade_plugin(plugin_id, dry_run=False, record_operation_log=False)
return PluginRuntimePayloadBuilder.build_batch_item_unsupported_payload(operation, plugin_id)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/config.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/config.py
index 68fc0f6db..4faf24311 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/config.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/config.py
@@ -1,5 +1,3 @@
-from typing import cast
-
from i18n.message import I18nMessage
from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.runtime.support import (
@@ -73,7 +71,7 @@ async def export_plugin_config(self, plugin_id: str, *, reveal_secret: bool = Fa
:param reveal_secret: 是否导出敏感配置明文
:return: 插件配置导出负载
"""
- payload = cast('dict[str, object]', await self.get_plugin_config(plugin_id, reveal_secret=reveal_secret))
+ payload = await self.get_plugin_config(plugin_id, reveal_secret=reveal_secret)
if not payload.get('ok', False):
return PluginConfigPayloadBuilder.build_export_failure_payload(
plugin_id,
@@ -81,8 +79,10 @@ async def export_plugin_config(self, plugin_id: str, *, reveal_secret: bool = Fa
reveal_secret=reveal_secret,
)
- configs = payload.get('configs') if isinstance(payload.get('configs'), list) else []
- return PluginConfigPayloadBuilder.build_export_payload(plugin_id, configs, reveal_secret=reveal_secret)
+ configs = payload.get('configs')
+ return PluginConfigPayloadBuilder.build_export_payload(
+ plugin_id, configs if isinstance(configs, list) else [], reveal_secret=reveal_secret
+ )
async def set_plugin_config(
self,
@@ -134,13 +134,10 @@ async def import_plugin_config(
:param values: 待导入配置键值
:return: 插件配置导入负载
"""
- payload = cast(
- 'dict[str, object]',
- await self.set_plugin_config(
- plugin_id,
- values,
- audit_operation='config_import',
- success_message='插件配置导入完成',
- ),
+ payload = await self.set_plugin_config(
+ plugin_id,
+ values,
+ audit_operation='config_import',
+ success_message='插件配置导入完成',
)
return PluginConfigPayloadBuilder.build_import_payload(plugin_id, payload, values)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/context.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/context.py
index 7bd5c70c9..22508ba87 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/context.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/context.py
@@ -1,6 +1,7 @@
import asyncio
from pathlib import Path
from time import monotonic
+from typing import TYPE_CHECKING
from i18n.message import I18nMessage
from plugins.core.capability import STATE_CHANGE_OPERATIONS, PluginRuntimeCapability, PluginRuntimeCapabilityResolver
@@ -33,6 +34,10 @@
from .migration_store import PluginMigrationHistoryGatewayStore
from .responses import PluginRuntimeBlockedPayload, PluginRuntimeBlockedPayloadDict
+if TYPE_CHECKING:
+ from collections.abc import Awaitable, Callable
+
+
PLUGIN_DISCOVERY_CACHE_TTL_SECONDS = 2.0
DATABASE_PLUGIN_STATE_SYNC_LOOP_ERROR = '当前事件循环内不能同步读取数据库插件状态,已返回空列表'
@@ -217,7 +222,9 @@ async def get_readonly_discovered_plugin(self, plugin_id: str) -> DiscoveredPlug
raise ValueError('无法确认插件来源,配置读取已中止')
if getattr(plugin, 'source', None) != 'artifact':
return self.get_discovered_plugin(plugin_id)
- resolver = getattr(self.dependencies.state_query_gateway, 'get_selected_artifact_plugin', None)
+ resolver: Callable[[str, Path], Awaitable[DiscoveredPlugin]] | None = getattr(
+ self.dependencies.state_query_gateway, 'get_selected_artifact_plugin', None
+ )
if not callable(resolver):
raise ValueError('插件状态适配器未提供已选制品的只读解析能力')
return await resolver(plugin_id, Path(self.dependencies.runtime_environment.get_backend_dir()))
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/dependencies.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/dependencies.py
index aff2cfae9..5a67dfb60 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/dependencies.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/dependencies.py
@@ -1,6 +1,5 @@
import asyncio
from pathlib import Path
-from typing import cast
from i18n.message import I18nMessage
from plugins.core.discovery.scanner import DiscoveredPlugin
@@ -69,10 +68,7 @@ def _build_operation_blocked_payload(
:param dry_run: 是否预演
:return: 阻断负载,不阻断时返回 None
"""
- return cast(
- 'PluginRuntimeBlockedPayloadDict | None',
- self.context.build_operation_blocked_payload(discovered_plugin, operation, dry_run=dry_run),
- )
+ return self.context.build_operation_blocked_payload(discovered_plugin, operation, dry_run=dry_run)
def _with_plugin_capability(
self,
@@ -86,7 +82,7 @@ def _with_plugin_capability(
:param discovered_plugin: 已发现插件
:return: 附加能力后的响应负载
"""
- return cast('dict[str, object]', self.context.with_plugin_capability(payload, discovered_plugin))
+ return self.context.with_plugin_capability(payload, discovered_plugin)
@staticmethod
def _with_dependency_install_metadata(
@@ -182,7 +178,7 @@ def install_plugin_dependencies_from_cli(
confirmed=confirmed,
output_callback=output_callback,
)
- cast('dict[str, object]', payload).pop('capability', None)
+ payload.pop('capability', None)
return payload
except Exception as exc:
return PluginRuntimePayloadBuilder.build_exception_payload(
@@ -264,11 +260,8 @@ def install_plugin_dependencies_from_result(
install_plan_items,
policy_decision,
)
- payload = self._with_dependency_install_metadata(cast('dict[str, object]', payload), confirmed=confirmed)
- return cast(
- 'PluginDependencyInstallResponse',
- self._with_plugin_capability(cast('dict[str, object]', payload), discovered_plugin),
- )
+ payload = self._with_dependency_install_metadata(payload, confirmed=confirmed)
+ return self._with_plugin_capability(payload, discovered_plugin)
if not install_plan.has_actions:
payload = PluginDependencyInstallPayloadBuilder.build_satisfied_payload(
plugin_id,
@@ -276,11 +269,8 @@ def install_plugin_dependencies_from_result(
install_plan_items,
policy_decision,
)
- payload = self._with_dependency_install_metadata(cast('dict[str, object]', payload), confirmed=confirmed)
- return cast(
- 'PluginDependencyInstallResponse',
- self._with_plugin_capability(cast('dict[str, object]', payload), discovered_plugin),
- )
+ payload = self._with_dependency_install_metadata(payload, confirmed=confirmed)
+ return self._with_plugin_capability(payload, discovered_plugin)
if not policy_decision.allowed:
payload = PluginDependencyInstallPayloadBuilder.build_payload(
plugin_id=plugin_id,
@@ -291,11 +281,8 @@ def install_plugin_dependencies_from_result(
message=I18nMessage('插件依赖安装被策略阻断', msg_key='plugin.runtime.dependencies.installBlocked'),
policy_decision=policy_decision,
)
- payload = self._with_dependency_install_metadata(cast('dict[str, object]', payload), confirmed=confirmed)
- return cast(
- 'PluginDependencyInstallResponse',
- self._with_plugin_capability(cast('dict[str, object]', payload), discovered_plugin),
- )
+ payload = self._with_dependency_install_metadata(payload, confirmed=confirmed)
+ return self._with_plugin_capability(payload, discovered_plugin)
install_results = []
total = len(install_plan_items)
@@ -322,11 +309,8 @@ def install_plugin_dependencies_from_result(
install_results,
policy_decision,
)
- payload = self._with_dependency_install_metadata(cast('dict[str, object]', payload), confirmed=confirmed)
- return cast(
- 'PluginDependencyInstallResponse',
- self._with_plugin_capability(cast('dict[str, object]', payload), discovered_plugin),
- )
+ payload = self._with_dependency_install_metadata(payload, confirmed=confirmed)
+ return self._with_plugin_capability(payload, discovered_plugin)
async def install_plugin_dependencies_from_result_async(
self,
@@ -371,11 +355,8 @@ async def install_plugin_dependencies_from_result_async(
install_plan_items,
policy_decision,
)
- payload = self._with_dependency_install_metadata(cast('dict[str, object]', payload), confirmed=confirmed)
- return cast(
- 'PluginDependencyInstallResponse',
- self._with_plugin_capability(cast('dict[str, object]', payload), discovered_plugin),
- )
+ payload = self._with_dependency_install_metadata(payload, confirmed=confirmed)
+ return self._with_plugin_capability(payload, discovered_plugin)
if not install_plan.has_actions:
payload = PluginDependencyInstallPayloadBuilder.build_satisfied_payload(
plugin_id,
@@ -383,11 +364,8 @@ async def install_plugin_dependencies_from_result_async(
install_plan_items,
policy_decision,
)
- payload = self._with_dependency_install_metadata(cast('dict[str, object]', payload), confirmed=confirmed)
- return cast(
- 'PluginDependencyInstallResponse',
- self._with_plugin_capability(cast('dict[str, object]', payload), discovered_plugin),
- )
+ payload = self._with_dependency_install_metadata(payload, confirmed=confirmed)
+ return self._with_plugin_capability(payload, discovered_plugin)
if not policy_decision.allowed:
payload = PluginDependencyInstallPayloadBuilder.build_payload(
plugin_id=plugin_id,
@@ -398,11 +376,8 @@ async def install_plugin_dependencies_from_result_async(
message=I18nMessage('插件依赖安装被策略阻断', msg_key='plugin.runtime.dependencies.installBlocked'),
policy_decision=policy_decision,
)
- payload = self._with_dependency_install_metadata(cast('dict[str, object]', payload), confirmed=confirmed)
- return cast(
- 'PluginDependencyInstallResponse',
- self._with_plugin_capability(cast('dict[str, object]', payload), discovered_plugin),
- )
+ payload = self._with_dependency_install_metadata(payload, confirmed=confirmed)
+ return self._with_plugin_capability(payload, discovered_plugin)
install_results = []
total = len(install_plan_items)
@@ -430,11 +405,8 @@ async def install_plugin_dependencies_from_result_async(
install_results,
policy_decision,
)
- payload = self._with_dependency_install_metadata(cast('dict[str, object]', payload), confirmed=confirmed)
- return cast(
- 'PluginDependencyInstallResponse',
- self._with_plugin_capability(cast('dict[str, object]', payload), discovered_plugin),
- )
+ payload = self._with_dependency_install_metadata(payload, confirmed=confirmed)
+ return self._with_plugin_capability(payload, discovered_plugin)
@staticmethod
def _emit_install_status(
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/facade.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/facade.py
index f0504f39b..77fc66899 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/facade.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/facade.py
@@ -2,11 +2,13 @@
from collections.abc import Awaitable, Callable, Mapping
from typing import cast
+from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.environment import PLUGIN_RUNTIME_ENVIRONMENT, PluginRuntimeEnvironmentService
from plugins.core.runtime.support import PluginRuntimePayloadBuilder
from plugins.core.types import PluginConfigValue
-from plugins.core.validation.dependencies import NpmDependencyInspector, PluginDependencyChecker
+from plugins.core.validation.dependencies import DependencyCheckResult, NpmDependencyInspector, PluginDependencyChecker
from plugins.core.validation.dependency_policy import DependencyInstallPolicyConfig
+from plugins.core.validation.plugin_deps import PluginBatchOperation
from .audit import PluginAuditUseCase
from .batch import PluginBatchUseCase
@@ -179,7 +181,7 @@ def list_plugins(self) -> PluginCatalogListResponse:
:return: 插件列表负载
"""
- return cast('PluginCatalogListResponse', self.query.list_plugins())
+ return self.query.list_plugins()
async def list_plugins_with_state(self) -> PluginCatalogListResponse:
"""
@@ -187,7 +189,7 @@ async def list_plugins_with_state(self) -> PluginCatalogListResponse:
:return: 插件列表负载
"""
- return cast('PluginCatalogListResponse', await self.query.list_plugins_with_state())
+ return await self.query.list_plugins_with_state()
def get_plugin_info(self, plugin_id: str) -> PluginCatalogInfoResponse:
"""
@@ -196,7 +198,7 @@ def get_plugin_info(self, plugin_id: str) -> PluginCatalogInfoResponse:
:param plugin_id: 插件ID
:return: 插件详情负载
"""
- return cast('PluginCatalogInfoResponse', self.query.get_plugin_info(plugin_id))
+ return self.query.get_plugin_info(plugin_id)
async def get_plugin_info_with_state(self, plugin_id: str) -> PluginCatalogInfoResponse:
"""
@@ -205,7 +207,7 @@ async def get_plugin_info_with_state(self, plugin_id: str) -> PluginCatalogInfoR
:param plugin_id: 插件ID
:return: 插件详情负载
"""
- return cast('PluginCatalogInfoResponse', await self.query.get_plugin_info_with_state(plugin_id))
+ return await self.query.get_plugin_info_with_state(plugin_id)
def check_plugin(self, plugin_id: str | None = None) -> PluginCheckResponse:
"""
@@ -214,7 +216,7 @@ def check_plugin(self, plugin_id: str | None = None) -> PluginCheckResponse:
:param plugin_id: 插件ID,未传入时检查全部插件
:return: 插件检查负载
"""
- return cast('PluginCheckResponse', self.query.check_plugin(plugin_id))
+ return self.query.check_plugin(plugin_id)
async def check_plugin_async(self, plugin_id: str | None = None) -> PluginCheckResponse:
"""
@@ -223,7 +225,7 @@ async def check_plugin_async(self, plugin_id: str | None = None) -> PluginCheckR
:param plugin_id: 插件ID,未传入时检查全部插件
:return: 插件检查负载
"""
- return cast('PluginCheckResponse', await self.query.check_plugin_async(plugin_id))
+ return await self.query.check_plugin_async(plugin_id)
def check_plugin_dependencies(self, plugin_id: str) -> PluginDependencyCheckResponse:
"""
@@ -232,7 +234,7 @@ def check_plugin_dependencies(self, plugin_id: str) -> PluginDependencyCheckResp
:param plugin_id: 插件ID
:return: 插件依赖检查负载
"""
- return cast('PluginDependencyCheckResponse', self.query.check_plugin_dependencies(plugin_id))
+ return self.query.check_plugin_dependencies(plugin_id)
async def health_plugin(self, plugin_id: str) -> PluginHealthResponse:
"""
@@ -241,7 +243,7 @@ async def health_plugin(self, plugin_id: str) -> PluginHealthResponse:
:param plugin_id: 插件ID
:return: 插件健康检查负载
"""
- return cast('PluginHealthResponse', await self.query.health_plugin(plugin_id))
+ return await self.query.health_plugin(plugin_id)
async def diagnose_plugin(self, plugin_id: str) -> PluginDiagnoseResponse:
"""
@@ -250,7 +252,7 @@ async def diagnose_plugin(self, plugin_id: str) -> PluginDiagnoseResponse:
:param plugin_id: 插件ID
:return: 插件诊断包负载
"""
- return cast('PluginDiagnoseResponse', await self.query.diagnose_plugin(plugin_id))
+ return await self.query.diagnose_plugin(plugin_id)
async def get_plugin_config(self, plugin_id: str, *, reveal_secret: bool = False) -> PluginConfigStateResponse:
"""
@@ -260,9 +262,7 @@ async def get_plugin_config(self, plugin_id: str, *, reveal_secret: bool = False
:param reveal_secret: 是否展示敏感配置原值
:return: 插件配置负载
"""
- return cast(
- 'PluginConfigStateResponse', await self.config.get_plugin_config(plugin_id, reveal_secret=reveal_secret)
- )
+ return await self.config.get_plugin_config(plugin_id, reveal_secret=reveal_secret)
async def export_plugin_config(self, plugin_id: str, *, reveal_secret: bool = False) -> PluginConfigExportResponse:
"""
@@ -272,9 +272,7 @@ async def export_plugin_config(self, plugin_id: str, *, reveal_secret: bool = Fa
:param reveal_secret: 是否导出敏感配置明文
:return: 插件配置导出负载
"""
- return cast(
- 'PluginConfigExportResponse', await self.config.export_plugin_config(plugin_id, reveal_secret=reveal_secret)
- )
+ return await self.config.export_plugin_config(plugin_id, reveal_secret=reveal_secret)
async def set_plugin_config(
self,
@@ -293,14 +291,11 @@ async def set_plugin_config(
:param success_message: 操作成功提示
:return: 插件配置更新负载
"""
- return cast(
- 'PluginConfigStateResponse',
- await self.config.set_plugin_config(
- plugin_id,
- values,
- audit_operation=audit_operation,
- success_message=success_message,
- ),
+ return await self.config.set_plugin_config(
+ plugin_id,
+ values,
+ audit_operation=audit_operation,
+ success_message=success_message,
)
async def import_plugin_config(
@@ -313,9 +308,11 @@ async def import_plugin_config(
:param values: 待导入配置键值
:return: 插件配置导入负载
"""
- return cast('PluginConfigImportResponse', await self.config.import_plugin_config(plugin_id, values))
+ return await self.config.import_plugin_config(plugin_id, values)
- async def precheck_plugin_operation(self, plugin_id: str, operation: str) -> PluginPrecheckResponse:
+ async def precheck_plugin_operation(
+ self, plugin_id: str, operation: PluginBatchOperation
+ ) -> PluginPrecheckResponse:
"""
执行插件操作预检。
@@ -323,9 +320,9 @@ async def precheck_plugin_operation(self, plugin_id: str, operation: str) -> Plu
:param operation: 操作类型
:return: 插件操作预检负载
"""
- return cast('PluginPrecheckResponse', await self.precheck.precheck_plugin_operation(plugin_id, operation))
+ return await self.precheck.precheck_plugin_operation(plugin_id, operation)
- def plan_plugins(self, operation: str, plugin_ids: list[str] | None = None) -> PluginPlanResponse:
+ def plan_plugins(self, operation: PluginBatchOperation, plugin_ids: list[str] | None = None) -> PluginPlanResponse:
"""
生成插件批量操作拓扑计划。
@@ -333,9 +330,11 @@ def plan_plugins(self, operation: str, plugin_ids: list[str] | None = None) -> P
:param plugin_ids: 插件ID列表
:return: 插件批量操作拓扑计划负载
"""
- return cast('PluginPlanResponse', self.batch.plan_plugins(operation, plugin_ids))
+ return self.batch.plan_plugins(operation, plugin_ids)
- async def plan_plugins_async(self, operation: str, plugin_ids: list[str] | None = None) -> PluginPlanResponse:
+ async def plan_plugins_async(
+ self, operation: PluginBatchOperation, plugin_ids: list[str] | None = None
+ ) -> PluginPlanResponse:
"""
异步生成插件批量操作拓扑计划。
@@ -343,11 +342,11 @@ async def plan_plugins_async(self, operation: str, plugin_ids: list[str] | None
:param plugin_ids: 插件ID列表
:return: 插件批量操作拓扑计划负载
"""
- return cast('PluginPlanResponse', await self.batch.plan_plugins_async(operation, plugin_ids))
+ return await self.batch.plan_plugins_async(operation, plugin_ids)
async def batch_plugins(
self,
- operation: str,
+ operation: PluginBatchOperation,
plugin_ids: list[str] | None = None,
*,
dry_run: bool = False,
@@ -362,17 +361,16 @@ async def batch_plugins(
:param continue_on_error: 失败后是否继续执行后续插件
:return: 插件批量执行结果负载
"""
- return cast(
- 'PluginBatchResponse',
- await self.batch.batch_plugins(
- operation,
- plugin_ids,
- dry_run=dry_run,
- continue_on_error=continue_on_error,
- ),
+ return await self.batch.batch_plugins(
+ operation,
+ plugin_ids,
+ dry_run=dry_run,
+ continue_on_error=continue_on_error,
)
- async def execute_batch_plugin_item(self, operation: str, plugin_id: str) -> PluginBatchItemExecutionResponse:
+ async def execute_batch_plugin_item(
+ self, operation: PluginBatchOperation, plugin_id: str
+ ) -> PluginBatchItemExecutionResponse:
"""
执行单个批量插件操作项。
@@ -380,9 +378,7 @@ async def execute_batch_plugin_item(self, operation: str, plugin_id: str) -> Plu
:param plugin_id: 插件ID
:return: 单插件操作结果负载
"""
- return cast(
- 'PluginBatchItemExecutionResponse', await self.batch.execute_batch_plugin_item(operation, plugin_id)
- )
+ return await self.batch.execute_batch_plugin_item(operation, plugin_id)
def install_plugin_dependencies(
self,
@@ -517,10 +513,10 @@ async def execute_with_source_check() -> PluginDependencyInstallResponse:
def install_plugin_dependencies_from_result(
self,
plugin_id: str,
- dependency_result: object,
+ dependency_result: DependencyCheckResult,
*,
dry_run: bool = False,
- discovered_plugin: object | None = None,
+ discovered_plugin: DiscoveredPlugin | None = None,
policy_config: DependencyInstallPolicyConfig | None = None,
confirmed: bool = False,
) -> PluginDependencyInstallResponse:
@@ -535,25 +531,22 @@ def install_plugin_dependencies_from_result(
:param confirmed: 是否已显式确认
:return: 插件依赖安装负载
"""
- return cast(
- 'PluginDependencyInstallResponse',
- self.dependency.install_plugin_dependencies_from_result(
- plugin_id,
- dependency_result,
- dry_run=dry_run,
- discovered_plugin=discovered_plugin,
- policy_config=policy_config,
- confirmed=confirmed,
- ),
+ return self.dependency.install_plugin_dependencies_from_result(
+ plugin_id,
+ dependency_result,
+ dry_run=dry_run,
+ discovered_plugin=discovered_plugin,
+ policy_config=policy_config,
+ confirmed=confirmed,
)
async def install_plugin_dependencies_from_result_async(
self,
plugin_id: str,
- dependency_result: object,
+ dependency_result: DependencyCheckResult,
*,
dry_run: bool = False,
- discovered_plugin: object | None = None,
+ discovered_plugin: DiscoveredPlugin | None = None,
policy_config: DependencyInstallPolicyConfig | None = None,
confirmed: bool = False,
) -> PluginDependencyInstallResponse:
@@ -568,16 +561,13 @@ async def install_plugin_dependencies_from_result_async(
:param confirmed: 是否已显式确认
:return: 插件依赖安装负载
"""
- return cast(
- 'PluginDependencyInstallResponse',
- await self.dependency.install_plugin_dependencies_from_result_async(
- plugin_id,
- dependency_result,
- dry_run=dry_run,
- discovered_plugin=discovered_plugin,
- policy_config=policy_config,
- confirmed=confirmed,
- ),
+ return await self.dependency.install_plugin_dependencies_from_result_async(
+ plugin_id,
+ dependency_result,
+ dry_run=dry_run,
+ discovered_plugin=discovered_plugin,
+ policy_config=policy_config,
+ confirmed=confirmed,
)
async def record_plugin_operation_log(
@@ -691,13 +681,10 @@ async def _mark_plugin_migration_status(
operation = f'migration_mark_{status}'
async with self.lifecycle_lock.lock(plugin_id, operation) as lock_result:
if not lock_result.acquired:
- return cast(
- 'dict[str, object]',
- PluginRuntimePayloadBuilder.build_invalid_operation_payload(
- plugin_id,
- operation,
- message=lock_result.message,
- ),
+ return PluginRuntimePayloadBuilder.build_invalid_operation_payload(
+ plugin_id,
+ operation,
+ message=lock_result.message,
)
payload = await self.migration.mark_plugin_migration_status(
plugin_id,
@@ -878,13 +865,10 @@ async def _run_with_lifecycle_lock(
return await operation()
async with self.lifecycle_lock.lock(plugin_id, lock_operation) as lock_result:
if not lock_result.acquired:
- return cast(
- 'PluginLifecycleResponse',
- PluginRuntimePayloadBuilder.build_invalid_operation_payload(
- plugin_id,
- lock_operation,
- message=lock_result.message,
- ),
+ return PluginRuntimePayloadBuilder.build_invalid_operation_payload(
+ plugin_id,
+ lock_operation,
+ message=lock_result.message,
)
return await operation()
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/gateway.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/gateway.py
index 15736e972..c32c284c9 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/gateway.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/gateway.py
@@ -1,6 +1,6 @@
import subprocess
import threading
-from collections.abc import Callable, Mapping
+from collections.abc import Callable, Mapping, Sequence
from contextlib import AbstractAsyncContextManager
from pathlib import Path
from typing import Any, Literal, Protocol, TypeAlias, runtime_checkable
@@ -108,7 +108,7 @@ def consume_stream(
stderr_thread.join()
raise subprocess.TimeoutExpired(
command,
- timeout,
+ exc.timeout,
output=''.join(stdout_parts),
stderr=''.join(stderr_parts),
) from exc
@@ -140,7 +140,7 @@ class PluginManagementServiceProtocol(Protocol):
"""插件运行时依赖的管理服务协议。"""
@classmethod
- async def get_plugin_list_services(cls, query_db: AsyncSession) -> list[PluginStateRecord]:
+ async def get_plugin_list_services(cls, query_db: AsyncSession) -> Sequence[PluginStateRecord]:
"""
获取插件状态列表。
@@ -690,7 +690,14 @@ class PluginLifecycleUnitOfWork(Protocol):
:ivar session: 当前操作共用的会话
"""
- session: AsyncSession
+ @property
+ def session(self) -> AsyncSession:
+ """
+ 获取当前操作共用的数据库会话。
+
+ :return: 当前生命周期事务的会话
+ """
+ ...
async def check_installed_menu_conflicts(self, discovered_plugin: DiscoveredPlugin) -> list[PluginMenuConflictItem]:
"""
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/common.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/common.py
index 1123e2cc8..9505232b2 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/common.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/common.py
@@ -1,23 +1,86 @@
+from contextlib import AbstractAsyncContextManager
from pathlib import Path
-from typing import Any, Protocol, cast
+from typing import TypeVar
+
+from sqlalchemy.ext.asyncio import AsyncSession
from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.runtime.support import PluginPrecheckContext
from ..context import PluginRuntimeContextService
+from ..gateway import PluginLifecycleUnitOfWork
from ..responses import PluginLifecycleResponse, PluginRuntimeBlockedPayloadDict
+_T = TypeVar('_T')
+
+
+def require_step_result(value: _T | None, step: str) -> _T:
+ """
+ 读取前置生命周期步骤已经产生的结果。
+
+ :param value: 上下文中保存的步骤结果
+ :param step: 应当产生该结果的步骤名
+ :return: 前置步骤产生的值
+ :raises RuntimeError: 前置步骤尚未提供所需结果
+ """
+ if value is None:
+ raise RuntimeError(f'缺少插件生命周期步骤 {step} 的结果')
+ return value
+
-class PluginLifecycleSessionContext(Protocol):
+class PluginDiscoveryContext:
"""
- 带数据库会话的生命周期上下文。
+ 为依赖插件发现和预检的步骤提供已完成的结果。
- :ivar session_context: 当前会话的上下文
- :ivar session: 当前操作共用的会话
+ :ivar discovered_plugin: 发现步骤匹配的插件
+ :ivar precheck: 插件预检结果
+ :ivar session_context: 负责打开和关闭会话的上下文
+ :ivar session: 当前步骤共享的数据库会话
"""
- session_context: Any | None
- session: Any | None
+ __slots__ = ('discovered_plugin', 'precheck', 'session', 'session_context')
+ discovered_plugin: DiscoveredPlugin | None
+ precheck: PluginPrecheckContext | None
+ session_context: AbstractAsyncContextManager[PluginLifecycleUnitOfWork] | None
+ session: AsyncSession | None
+
+ @property
+ def resolved_plugin(self) -> DiscoveredPlugin:
+ """
+ 获取发现步骤匹配的插件。
+
+ :return: 已发现的目标插件
+ """
+ return require_step_result(self.discovered_plugin, 'discover_plugin')
+
+ @property
+ def precheck_result(self) -> PluginPrecheckContext:
+ """
+ 获取预检步骤生成的结果。
+
+ :return: 插件预检结果
+ """
+ return require_step_result(self.precheck, 'build_precheck')
+
+
+class PluginTransactionContext(PluginDiscoveryContext):
+ """
+ 为需要主事务的生命周期步骤提供工作单元。
+
+ :ivar lifecycle_uow: 打开会话步骤创建的事务工作单元
+ """
+
+ __slots__ = ('lifecycle_uow',)
+ lifecycle_uow: PluginLifecycleUnitOfWork | None
+
+ @property
+ def active_transaction(self) -> PluginLifecycleUnitOfWork:
+ """
+ 获取本次操作使用的事务工作单元。
+
+ :return: 已打开的事务工作单元
+ """
+ return require_step_result(self.lifecycle_uow, '打开主事务')
class PluginLifecycleUseCaseSupport:
@@ -106,21 +169,21 @@ def _with_plugin_capability(
:param discovered_plugin: 已发现插件
:return: 附加能力后的响应负载
"""
- return cast(
- 'PluginLifecycleResponse',
- self.context.with_plugin_capability(cast('dict[str, object]', payload), discovered_plugin),
- )
+ return self.context.with_plugin_capability(payload, discovered_plugin)
- async def _close_lifecycle_session(self, context: object) -> None:
+ async def _close_lifecycle_session(self, context: PluginDiscoveryContext) -> None:
"""
关闭生命周期上下文中的数据库会话。
:param context: 生命周期上下文
"""
- lifecycle_context = cast('PluginLifecycleSessionContext', context)
- session_context = lifecycle_context.session_context
+ session_context = context.session_context
if session_context is None:
return
- await session_context.__aexit__(None, None, None)
- lifecycle_context.session_context = None
- lifecycle_context.session = None
+ try:
+ await session_context.__aexit__(None, None, None)
+ finally:
+ context.session_context = None
+ context.session = None
+ if isinstance(context, PluginTransactionContext):
+ context.lifecycle_uow = None
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/enable.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/enable.py
index 942479edc..a947bd5ff 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/enable.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/enable.py
@@ -1,9 +1,10 @@
+from contextlib import AbstractAsyncContextManager
from dataclasses import dataclass
from pathlib import Path
-from typing import cast
from sqlalchemy.ext.asyncio import AsyncSession
+from common.vo import CrudResponseModel
from i18n.catalogs import CatalogRegistry, CatalogSnapshot
from i18n.message import I18nMessage
from plugins.core.discovery.scanner import DiscoveredPlugin
@@ -17,14 +18,15 @@
from ..context import PluginRuntimeContextService
from ..dependency_container import PluginRuntimeDependencies
+from ..gateway import PluginLifecycleUnitOfWork
from ..responses import PluginLifecycleResponse
-from .common import PluginLifecycleUseCaseSupport
+from .common import PluginDiscoveryContext, PluginLifecycleUseCaseSupport, require_step_result
from .operations import PluginLifecycleRuntimeOperations
from .runner import PluginLifecycleStep, PluginLifecycleStepFailed, PluginLifecycleStepRunner
@dataclass(slots=True)
-class PluginEnabledLifecycleContext:
+class PluginEnabledLifecycleContext(PluginDiscoveryContext):
"""
插件启停声明式生命周期上下文。
@@ -55,15 +57,15 @@ class PluginEnabledLifecycleContext:
precheck: PluginPrecheckContext | None = None
actions: list[dict[str, object]] | None = None
dependency_payload: dict[str, object] | None = None
- response: dict[str, object] | None = None
+ response: CrudResponseModel | None = None
session: AsyncSession | None = None
plugin_service: object | None = None
- session_context: object | None = None
+ session_context: AbstractAsyncContextManager[PluginLifecycleUnitOfWork] | None = None
catalog_snapshot: CatalogSnapshot | None = None
@dataclass(slots=True)
-class PluginUninstallLifecycleContext:
+class PluginUninstallLifecycleContext(PluginDiscoveryContext):
"""
插件卸载声明式生命周期上下文。
@@ -89,10 +91,10 @@ class PluginUninstallLifecycleContext:
precheck: PluginPrecheckContext | None = None
actions: list[dict[str, object]] | None = None
dependency_payload: dict[str, object] | None = None
- response: dict[str, object] | None = None
+ response: CrudResponseModel | None = None
session: AsyncSession | None = None
plugin_service: object | None = None
- session_context: object | None = None
+ session_context: AbstractAsyncContextManager[PluginLifecycleUnitOfWork] | None = None
class PluginEnableUseCase(PluginLifecycleUseCaseSupport):
@@ -134,7 +136,7 @@ async def _build_enabled_dependents_payload(
:return: 依赖方检查负载
"""
dependent_result = await self.context.check_enabled_plugin_dependents(plugin_id, discovered_plugins)
- return cast('dict[str, object]', PluginEnablePayloadBuilder.build_dependency_payload(dependent_result))
+ return PluginEnablePayloadBuilder.build_dependency_payload(dependent_result)
async def _disable_plugin(
self,
@@ -218,7 +220,7 @@ async def set_plugin_enabled(
if blocked:
return blocked
payload = await self._set_plugin_enabled(plugin_id, enabled=enabled, dry_run=dry_run)
- payload_view = cast('dict[str, object]', payload)
+ payload_view = payload
payload_view['operation'] = 'enable' if enabled else 'disable'
if enabled and not dry_run:
await self.runtime_operations.record_plugin_failure_state(payload_view, '插件启用失败')
@@ -340,20 +342,19 @@ async def _enabled_step_build_precheck(
:return: dry-run 或阻断 payload
"""
context.catalog_snapshot = CatalogRegistry.prepare_plugin(
- context.plugin_id, context.discovered_plugin.backend_path
+ context.plugin_id, context.resolved_plugin.backend_path
)
context.precheck = await self._build_precheck_context(
- cast('Path', context.backend_root),
- cast('DiscoveredPlugin', context.discovered_plugin),
+ require_step_result(context.backend_root, 'discover_plugin'),
+ context.resolved_plugin,
context.discovered_plugins or [],
)
context.actions = PluginPayloadBuilder.build_enabled_actions(
context.enabled,
context.precheck.plugin_dependency_result.ok,
)
- context.dependency_payload = cast(
- 'dict[str, object]',
- PluginEnablePayloadBuilder.build_dependency_payload(context.precheck.plugin_dependency_result),
+ context.dependency_payload = PluginEnablePayloadBuilder.build_dependency_payload(
+ context.precheck.plugin_dependency_result
)
if not context.dry_run:
return PluginLifecyclePayloadBuilder.build_first_precheck_blocker_payload(
@@ -451,7 +452,7 @@ def _build_enabled_success_payload(
context.plugin_id,
operation=context.operation,
enabled=context.enabled,
- message=context.response.message,
+ message=require_step_result(context.response, 'update_enabled_state').message,
dependency_payload=context.dependency_payload or {},
)
return self._with_plugin_capability(payload, context.discovered_plugin)
@@ -487,8 +488,8 @@ async def uninstall_plugin(
if blocked:
return blocked
result = await self._uninstall_plugin(plugin_id, dry_run=dry_run)
- result = PluginEnablePayloadBuilder.build_uninstall_payload(cast('dict[str, object]', result), dry_run=dry_run)
- result_view = cast('dict[str, object]', result)
+ result = PluginEnablePayloadBuilder.build_uninstall_payload(result, dry_run=dry_run)
+ result_view = result
if record_operation_log and not dry_run:
if operated_by is not None:
result_view['operatedBy'] = operated_by
@@ -616,7 +617,7 @@ async def _uninstall_step_build_precheck(
if not context.discovered_plugin:
return None
context.precheck = await self._build_precheck_context(
- cast('Path', context.backend_root),
+ require_step_result(context.backend_root, 'discover_plugin'),
context.discovered_plugin,
context.discovered_plugins or [],
)
@@ -679,7 +680,7 @@ def _build_uninstall_success_payload(
context.plugin_id,
operation='uninstall',
enabled=False,
- message=context.response.message,
+ message=require_step_result(context.response, 'mark_uninstalled').message,
dependency_payload=context.dependency_payload or {},
)
return self._with_plugin_capability(payload, context.discovered_plugin)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/install.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/install.py
index a72af4925..2cf3d66ed 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/install.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/install.py
@@ -1,6 +1,6 @@
+from contextlib import AbstractAsyncContextManager
from dataclasses import dataclass
from pathlib import Path
-from typing import cast
from sqlalchemy.ext.asyncio import AsyncSession
@@ -9,6 +9,7 @@
from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.lifecycle.migration import PluginMigrationError, PluginMigrationResult
from plugins.core.lifecycle.seed import PluginSeedResult, PluginSeedRunner
+from plugins.core.management.entity.vo.schemas import PluginConfigModel, PluginModel
from plugins.core.runtime.hooks import PluginHookResult, PluginHookRunner
from plugins.core.runtime.support import (
PluginLifecyclePayloadBuilder,
@@ -19,14 +20,15 @@
from ..context import PluginRuntimeContextService
from ..dependency_container import PluginRuntimeDependencies
+from ..gateway import PluginLifecycleUnitOfWork
from ..responses import PluginLifecycleResponse
-from .common import PluginLifecycleUseCaseSupport
+from .common import PluginLifecycleUseCaseSupport, PluginTransactionContext, require_step_result
from .operations import PluginLifecycleRuntimeOperations
from .runner import PluginLifecycleStep, PluginLifecycleStepFailed, PluginLifecycleStepRunner
@dataclass(slots=True)
-class PluginInstallLifecycleContext:
+class PluginInstallLifecycleContext(PluginTransactionContext):
"""
插件安装声明式生命周期上下文。
@@ -57,14 +59,14 @@ class PluginInstallLifecycleContext:
precheck: PluginPrecheckContext | None = None
actions: list[dict[str, object]] | None = None
dependency_install_view: dict[str, object] | None = None
- plugin: object | None = None
- installed_configs: list[object] | None = None
+ plugin: PluginModel | None = None
+ installed_configs: list[PluginConfigModel] | None = None
migration_results: list[PluginMigrationResult] | None = None
seed_results: list[PluginSeedResult] | None = None
hook_result: PluginHookResult | None = None
session: AsyncSession | None = None
- lifecycle_uow: object | None = None
- session_context: object | None = None
+ lifecycle_uow: PluginLifecycleUnitOfWork | None = None
+ session_context: AbstractAsyncContextManager[PluginLifecycleUnitOfWork] | None = None
catalog_snapshot: CatalogSnapshot | None = None
@@ -115,7 +117,7 @@ async def install_plugin(
if blocked:
return blocked
payload = await self._install_plugin(plugin_id, dry_run=dry_run)
- payload_view = cast('dict[str, object]', payload)
+ payload_view = payload
payload_view['operation'] = 'install'
if not dry_run:
await self.runtime_operations.record_plugin_failure_state(payload_view, '插件安装失败')
@@ -237,14 +239,14 @@ async def _install_step_build_precheck(
:return: dry-run 或阻断 payload
"""
context.catalog_snapshot = CatalogRegistry.prepare_plugin(
- context.plugin_id, context.discovered_plugin.backend_path
+ context.plugin_id, context.resolved_plugin.backend_path
)
self._refresh_install_actions(await self._build_install_precheck(context), context)
if context.dry_run:
payload = PluginLifecyclePayloadBuilder.build_install_dry_run_payload(
context.plugin_id,
context.actions or [],
- cast('PluginPrecheckContext', context.precheck),
+ context.precheck_result,
)
payload['operation'] = 'install'
return self._with_plugin_capability(payload, context.discovered_plugin)
@@ -253,7 +255,7 @@ async def _install_step_build_precheck(
context.plugin_id,
operation='install',
actions=context.actions or [],
- precheck=cast('PluginPrecheckContext', context.precheck),
+ precheck=context.precheck_result,
)
async def _install_step_install_dependencies(
@@ -268,11 +270,11 @@ async def _install_step_install_dependencies(
"""
dependency_install_payload = await self.runtime_operations.install_plugin_dependencies_from_result_async(
context.plugin_id,
- cast('PluginPrecheckContext', context.precheck).dependency_result,
+ context.precheck_result.dependency_result,
dry_run=True,
discovered_plugin=context.discovered_plugin,
)
- context.dependency_install_view = cast('dict[str, object]', dependency_install_payload)
+ context.dependency_install_view = dependency_install_payload
if context.dependency_install_view.get('dependencyOk', False):
return None
@@ -282,7 +284,7 @@ async def _install_step_install_dependencies(
'插件依赖缺失,安装已中止,请先显式安装依赖', msg_key='plugin.runtime.install.missingDependencies'
),
actions=context.actions or [],
- precheck=cast('PluginPrecheckContext', context.precheck),
+ precheck=context.precheck_result,
extra_payload={'dependencyInstall': context.dependency_install_view},
)
@@ -320,8 +322,9 @@ async def _install_step_open_session(
:param context: 插件安装上下文
"""
- context.session_context = self.dependencies.lifecycle_uow_gateway.open_lifecycle_unit_of_work()
- context.lifecycle_uow = await context.session_context.__aenter__()
+ session_context = self.dependencies.lifecycle_uow_gateway.open_lifecycle_unit_of_work()
+ context.lifecycle_uow = await session_context.__aenter__()
+ context.session_context = session_context
context.session = context.lifecycle_uow.session
return None
@@ -336,8 +339,8 @@ async def _install_step_check_installed_menu_conflicts(
:param context: 插件安装上下文
:return: 菜单冲突 payload 或 None
"""
- installed_menu_conflicts = await context.lifecycle_uow.check_installed_menu_conflicts(
- context.discovered_plugin,
+ installed_menu_conflicts = await context.active_transaction.check_installed_menu_conflicts(
+ context.resolved_plugin,
)
if not installed_menu_conflicts:
return None
@@ -348,7 +351,7 @@ async def _install_step_check_installed_menu_conflicts(
'插件菜单与已安装菜单存在冲突,安装已中止', msg_key='plugin.runtime.install.menuConflict'
),
actions=context.actions or [],
- precheck=cast('PluginPrecheckContext', context.precheck),
+ precheck=context.precheck_result,
installed_menu_conflicts=installed_menu_conflicts,
)
@@ -361,8 +364,8 @@ async def _install_step_upsert_plugin(
:param context: 插件安装上下文
"""
- context.plugin = await context.lifecycle_uow.upsert_discovered_plugin(
- context.discovered_plugin,
+ context.plugin = await context.active_transaction.upsert_discovered_plugin(
+ context.resolved_plugin,
Path(self.dependencies.runtime_environment.get_backend_plugins_dir()),
Path(self.dependencies.runtime_environment.get_frontend_plugins_dir()),
)
@@ -379,8 +382,8 @@ async def _install_step_install_menus(
:param context: 插件安装上下文
"""
plugin_enabled = getattr(context.plugin, 'enabled', '0') == '0'
- await context.lifecycle_uow.install_plugin_menu(
- context.discovered_plugin,
+ await context.active_transaction.install_plugin_menu(
+ context.resolved_plugin,
enabled=plugin_enabled,
)
@@ -395,8 +398,8 @@ async def _install_step_install_configs(
:param context: 插件安装上下文
"""
- context.installed_configs = await context.lifecycle_uow.install_plugin_default_config(
- context.discovered_plugin,
+ context.installed_configs = await context.active_transaction.install_plugin_default_config(
+ context.resolved_plugin,
)
return None
@@ -411,8 +414,8 @@ async def _install_step_install_jobs(
:param context: 插件安装上下文
"""
plugin_enabled = getattr(context.plugin, 'enabled', '0') == '0'
- await context.lifecycle_uow.install_plugin_jobs(
- context.discovered_plugin,
+ await context.active_transaction.install_plugin_jobs(
+ context.resolved_plugin,
enabled=plugin_enabled,
)
@@ -428,7 +431,7 @@ async def _install_step_run_migrations(
:param context: 插件安装上下文
"""
context.migration_results = await self.dependencies.migration_execution_gateway.run_plugin_migrations(
- context.discovered_plugin,
+ context.resolved_plugin,
)
return None
@@ -442,7 +445,7 @@ async def _install_step_run_seeds(
:param context: 插件安装上下文
"""
- context.seed_results = await PluginSeedRunner(context.discovered_plugin).run(context.session)
+ context.seed_results = await PluginSeedRunner(context.resolved_plugin).run(context.session)
return None
@@ -455,7 +458,7 @@ async def _install_step_run_install_hook(
:param context: 插件安装上下文
"""
- context.hook_result = await PluginHookRunner(context.discovered_plugin).run(
+ context.hook_result = await PluginHookRunner(context.resolved_plugin).run(
'on_install',
query_db=context.session,
)
@@ -471,8 +474,8 @@ async def _install_step_mark_installed(
:param context: 插件安装上下文
"""
- context.plugin = await context.lifecycle_uow.mark_plugin_installed(
- context.discovered_plugin,
+ context.plugin = await context.active_transaction.mark_plugin_installed(
+ context.resolved_plugin,
)
return None
@@ -486,7 +489,7 @@ async def _install_step_commit(
:param context: 插件安装上下文
"""
- await context.lifecycle_uow.commit()
+ await context.active_transaction.commit()
CatalogRegistry.commit_plugin(
context.plugin_id, context.catalog_snapshot, enabled=getattr(context.plugin, 'enabled', '0') == '0'
)
@@ -526,8 +529,8 @@ async def _build_install_precheck(
:return: 插件预检上下文
"""
return await self._build_precheck_context(
- cast('Path', context.backend_root),
- cast('DiscoveredPlugin', context.discovered_plugin),
+ require_step_result(context.backend_root, 'discover_plugin'),
+ context.resolved_plugin,
context.discovered_plugins or [],
)
@@ -544,7 +547,7 @@ def _refresh_install_actions(
"""
context.precheck = precheck
context.actions = PluginPayloadBuilder.build_install_actions(
- cast('DiscoveredPlugin', context.discovered_plugin),
+ context.resolved_plugin,
precheck.dependency_result.ok,
precheck.plugin_dependency_result.ok,
precheck.structure_result.ok,
@@ -565,11 +568,11 @@ def _build_install_success_payload(
context.plugin_id,
message=I18nMessage('插件安装完成', msg_key='plugin.runtime.install.completed'),
actions=context.actions or [],
- precheck=cast('PluginPrecheckContext', context.precheck),
- plugin=context.plugin,
- installed_configs=context.installed_configs,
- migration_results=context.migration_results,
- seed_results=context.seed_results,
+ precheck=context.precheck_result,
+ plugin=require_step_result(context.plugin, 'mark_installed'),
+ installed_configs=require_step_result(context.installed_configs, 'install_configs'),
+ migration_results=require_step_result(context.migration_results, 'run_migrations'),
+ seed_results=require_step_result(context.seed_results, 'run_seeds'),
hook_result=context.hook_result,
extra_payload={'dependencyInstall': context.dependency_install_view or {}},
)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/operations.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/operations.py
index ae6c2c69a..2fb3c89d7 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/operations.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/operations.py
@@ -1,6 +1,9 @@
from collections.abc import Mapping
from typing import Protocol
+from plugins.core.discovery.scanner import DiscoveredPlugin
+from plugins.core.validation.dependencies import DependencyCheckResult
+
from ..context import PluginRuntimeContextService
from ..dependency_container import PluginRuntimeDependencies
from ..responses import PluginDependencyInstallResponse
@@ -43,10 +46,10 @@ async def record_plugin_failure_state(self, payload: Mapping[str, object], defau
def install_plugin_dependencies_from_result(
self,
plugin_id: str,
- dependency_result: object,
+ dependency_result: DependencyCheckResult,
*,
dry_run: bool = False,
- discovered_plugin: object | None = None,
+ discovered_plugin: DiscoveredPlugin | None = None,
) -> PluginDependencyInstallResponse:
"""
根据既有依赖检查结果生成计划并执行依赖安装。
@@ -61,10 +64,10 @@ def install_plugin_dependencies_from_result(
async def install_plugin_dependencies_from_result_async(
self,
plugin_id: str,
- dependency_result: object,
+ dependency_result: DependencyCheckResult,
*,
dry_run: bool = False,
- discovered_plugin: object | None = None,
+ discovered_plugin: DiscoveredPlugin | None = None,
) -> PluginDependencyInstallResponse:
"""
根据既有依赖检查结果异步生成计划并执行依赖安装。
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/purge.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/purge.py
index fb7286c73..2f7b61f9c 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/purge.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/purge.py
@@ -1,11 +1,12 @@
+from contextlib import AbstractAsyncContextManager
from dataclasses import dataclass
from pathlib import Path
-from typing import cast
from sqlalchemy.ext.asyncio import AsyncSession
from i18n.message import I18nMessage
from plugins.core.discovery.scanner import DiscoveredPlugin
+from plugins.core.lifecycle.purge import PluginPurgePlan
from plugins.core.runtime.hooks import PluginHookResult, PluginHookRunner
from plugins.core.runtime.support import (
PluginEnablePayloadBuilder,
@@ -18,14 +19,15 @@
from ..context import PluginRuntimeContextService
from ..dependency_container import PluginRuntimeDependencies
+from ..gateway import PluginLifecycleUnitOfWork
from ..responses import PluginLifecycleResponse
-from .common import PluginLifecycleUseCaseSupport
+from .common import PluginLifecycleUseCaseSupport, PluginTransactionContext, require_step_result
from .operations import PluginLifecycleRuntimeOperations
from .runner import PluginLifecycleStep, PluginLifecycleStepFailed, PluginLifecycleStepRunner
@dataclass(slots=True)
-class PluginPurgeLifecycleContext:
+class PluginPurgeLifecycleContext(PluginTransactionContext):
"""
插件物理清理声明式生命周期上下文。
@@ -52,11 +54,11 @@ class PluginPurgeLifecycleContext:
precheck: PluginPrecheckContext | None = None
dependency_payload: dict[str, object] | None = None
actions: list[dict[str, object]] | None = None
- plan: object | None = None
+ plan: PluginPurgePlan | None = None
hook_result: PluginHookResult | None = None
session: AsyncSession | None = None
- lifecycle_uow: object | None = None
- session_context: object | None = None
+ lifecycle_uow: PluginLifecycleUnitOfWork | None = None
+ session_context: AbstractAsyncContextManager[PluginLifecycleUnitOfWork] | None = None
class PluginPurgeUseCase(PluginLifecycleUseCaseSupport):
@@ -98,7 +100,7 @@ async def _build_enabled_dependents_payload(
:return: 依赖方检查负载
"""
dependent_result = await self.context.check_enabled_plugin_dependents(plugin_id, discovered_plugins)
- return cast('dict[str, object]', PluginEnablePayloadBuilder.build_dependency_payload(dependent_result))
+ return PluginEnablePayloadBuilder.build_dependency_payload(dependent_result)
async def purge_plugin(
self,
@@ -121,7 +123,7 @@ async def purge_plugin(
if blocked:
return blocked
payload = await self._purge_plugin(plugin_id, dry_run=dry_run)
- payload_view = cast('dict[str, object]', payload)
+ payload_view = payload
payload_view['operation'] = 'purge'
if record_operation_log and not dry_run:
if operated_by is not None:
@@ -155,7 +157,7 @@ async def _purge_plugin(self, plugin_id: str, *, dry_run: bool = False) -> Plugi
return result.stop.payload
payload = PluginPurgePayloadBuilder.build_success_payload(
result.context.plugin_id,
- result.context.plan,
+ require_step_result(result.context.plan, 'build_purge_plan'),
result.context.hook_result,
)
return self._with_plugin_capability(payload, result.context.discovered_plugin)
@@ -215,7 +217,7 @@ async def _purge_orphan_plugin_metadata(
**dependency_payload,
}
)
- return cast('PluginLifecycleResponse', payload)
+ return payload
if not bool(dependency_payload.get('pluginDependencyOk', True)):
return PluginEnablePayloadBuilder.build_dependency_blocker_payload(
@@ -237,7 +239,7 @@ async def _purge_orphan_plugin_metadata(
'warnings': ['插件源码不存在,已跳过 onPurge;插件自有业务资源需人工确认'],
}
)
- return cast('PluginLifecycleResponse', payload)
+ return payload
finally:
await session_context.__aexit__(None, None, None)
@@ -292,7 +294,7 @@ async def _purge_step_discover_plugins(
:param context: 插件物理清理上下文
"""
- context.backend_root = context.discovered_plugin.backend_path.parent.parent
+ context.backend_root = context.resolved_plugin.backend_path.parent.parent
context.discovered_plugins = self._discover_plugins(context.backend_root)
return None
@@ -307,13 +309,13 @@ async def _purge_step_build_precheck(
:param context: 插件物理清理上下文
"""
context.precheck = await self._build_precheck_context(
- cast('Path', context.backend_root),
- cast('DiscoveredPlugin', context.discovered_plugin),
+ require_step_result(context.backend_root, 'discover_plugin'),
+ context.resolved_plugin,
context.discovered_plugins or [],
)
context.actions = PluginRuntimePayloadBuilder.build_precheck_actions(
'purge',
- context.discovered_plugin,
+ context.resolved_plugin,
context.precheck,
)
@@ -344,11 +346,12 @@ async def _purge_step_build_purge_plan(
:param context: 插件物理清理上下文
"""
- context.session_context = self.dependencies.lifecycle_uow_gateway.open_lifecycle_unit_of_work()
- context.lifecycle_uow = await context.session_context.__aenter__()
+ session_context = self.dependencies.lifecycle_uow_gateway.open_lifecycle_unit_of_work()
+ context.lifecycle_uow = await session_context.__aenter__()
+ context.session_context = session_context
context.session = context.lifecycle_uow.session
context.plan = await context.lifecycle_uow.build_plugin_purge_plan(
- context.discovered_plugin,
+ context.resolved_plugin,
)
return None
@@ -364,6 +367,7 @@ async def _purge_step_check_purge_blockers(
:return: dry-run 或阻断 payload
"""
if context.dry_run:
+ plan = require_step_result(context.plan, 'build_purge_plan')
payload = PluginLifecyclePayloadBuilder.build_operation_dry_run_payload(
context.plugin_id,
operation='purge',
@@ -371,11 +375,11 @@ async def _purge_step_check_purge_blockers(
'插件物理清理演练完成,未执行实际删除', msg_key='plugin.runtime.purge.previewCompleted'
),
actions=context.actions or [],
- precheck=cast('PluginPrecheckContext', context.precheck),
+ precheck=context.precheck_result,
extra_payload={
'safeMode': False,
- 'removesSource': context.plan.removes_source,
- 'plan': PluginPayloadBuilder.build_purge_plan(context.plan),
+ 'removesSource': plan.removes_source,
+ 'plan': PluginPayloadBuilder.build_purge_plan(plan),
**(context.dependency_payload or {}),
},
ok_from_precheck=False,
@@ -404,7 +408,7 @@ async def _purge_step_run_purge_hook(
:param context: 插件物理清理上下文
"""
- context.hook_result = await PluginHookRunner(context.discovered_plugin).run(
+ context.hook_result = await PluginHookRunner(context.resolved_plugin).run(
'on_purge',
query_db=context.session,
)
@@ -420,7 +424,7 @@ async def _purge_step_purge_metadata(
:param context: 插件物理清理上下文
"""
- await context.lifecycle_uow.purge_plugin_metadata(context.discovered_plugin)
+ await context.active_transaction.purge_plugin_metadata(context.resolved_plugin)
return None
@@ -433,7 +437,7 @@ async def _purge_step_commit(
:param context: 插件物理清理上下文
"""
- await context.lifecycle_uow.commit()
+ await context.active_transaction.commit()
await self._close_purge_session(context)
return None
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/upgrade.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/upgrade.py
index 66fb803b7..772f3cdf6 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/upgrade.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle/upgrade.py
@@ -1,6 +1,6 @@
+from contextlib import AbstractAsyncContextManager
from dataclasses import dataclass
from pathlib import Path
-from typing import cast
from sqlalchemy.ext.asyncio import AsyncSession
@@ -9,25 +9,28 @@
from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.lifecycle.migration import PluginMigrationError, PluginMigrationResult
from plugins.core.lifecycle.seed import PluginSeedResult, PluginSeedRunner
+from plugins.core.management.entity.vo.schemas import PluginConfigModel, PluginModel
from plugins.core.runtime.hooks import PluginHookResult, PluginHookRunner
from plugins.core.runtime.support import (
PluginLifecyclePayloadBuilder,
PluginPayloadBuilder,
PluginPrecheckContext,
PluginRuntimePayloadBuilder,
+ UpgradeDryRunPayloadContext,
)
from plugins.core.types import PluginStateRecord
from ..context import PluginRuntimeContextService
from ..dependency_container import PluginRuntimeDependencies
+from ..gateway import PluginLifecycleUnitOfWork
from ..responses import PluginLifecycleResponse
-from .common import PluginLifecycleUseCaseSupport
+from .common import PluginLifecycleUseCaseSupport, PluginTransactionContext, require_step_result
from .operations import PluginLifecycleRuntimeOperations
from .runner import PluginLifecycleStep, PluginLifecycleStepFailed, PluginLifecycleStepRunner
@dataclass(slots=True)
-class PluginUpgradeLifecycleContext:
+class PluginUpgradeLifecycleContext(PluginTransactionContext):
"""
插件升级声明式生命周期上下文。
@@ -62,14 +65,14 @@ class PluginUpgradeLifecycleContext:
database_plugin: PluginStateRecord | None = None
database_error: str | None = None
version_state: dict[str, object] | None = None
- plugin: object | None = None
- installed_configs: list[object] | None = None
+ plugin: PluginModel | None = None
+ installed_configs: list[PluginConfigModel] | None = None
migration_results: list[PluginMigrationResult] | None = None
seed_results: list[PluginSeedResult] | None = None
hook_result: PluginHookResult | None = None
session: AsyncSession | None = None
- lifecycle_uow: object | None = None
- session_context: object | None = None
+ lifecycle_uow: PluginLifecycleUnitOfWork | None = None
+ session_context: AbstractAsyncContextManager[PluginLifecycleUnitOfWork] | None = None
catalog_snapshot: CatalogSnapshot | None = None
@@ -129,7 +132,7 @@ async def upgrade_plugin(
if blocked:
return blocked
payload = await self._upgrade_plugin(plugin_id, dry_run=dry_run)
- payload_view = cast('dict[str, object]', payload)
+ payload_view = payload
payload_view['operation'] = 'upgrade'
if not dry_run:
await self.runtime_operations.record_plugin_failure_state(payload_view, '插件升级失败')
@@ -251,7 +254,7 @@ async def _upgrade_step_build_precheck(
:return: dry-run payload 或 None
"""
context.catalog_snapshot = CatalogRegistry.prepare_plugin(
- context.plugin_id, context.discovered_plugin.backend_path
+ context.plugin_id, context.resolved_plugin.backend_path
)
precheck = await self._build_upgrade_precheck(context)
self._refresh_upgrade_actions(precheck, context)
@@ -260,7 +263,7 @@ async def _upgrade_step_build_precheck(
context.database_plugin, context.database_error = await self._load_database_plugin_state(context.plugin_id)
context.version_state = PluginPayloadBuilder.build_upgrade_version_state(
- context.discovered_plugin,
+ context.resolved_plugin,
context.database_plugin,
)
payload = PluginPayloadBuilder.build_upgrade_dry_run_payload(
@@ -282,7 +285,7 @@ async def _upgrade_step_load_installed_plugin(
"""
context.database_plugin = await self.dependencies.state_query_gateway.get_plugin_state(context.plugin_id)
context.version_state = PluginPayloadBuilder.build_upgrade_version_state(
- context.discovered_plugin,
+ context.resolved_plugin,
context.database_plugin,
)
@@ -297,8 +300,9 @@ async def _upgrade_step_open_session(
:param context: 插件升级上下文
"""
- context.session_context = self.dependencies.lifecycle_uow_gateway.open_lifecycle_unit_of_work()
- context.lifecycle_uow = await context.session_context.__aenter__()
+ session_context = self.dependencies.lifecycle_uow_gateway.open_lifecycle_unit_of_work()
+ context.lifecycle_uow = await session_context.__aenter__()
+ context.session_context = session_context
context.session = context.lifecycle_uow.session
return None
@@ -317,7 +321,7 @@ async def _upgrade_step_check_upgrade_blockers(
context.plugin_id,
context.version_state or {},
context.actions or [],
- cast('PluginPrecheckContext', context.precheck),
+ context.precheck_result,
)
if blocker_payload:
return blocker_payload
@@ -325,7 +329,7 @@ async def _upgrade_step_check_upgrade_blockers(
payload = PluginLifecyclePayloadBuilder.build_upgrade_latest_payload(
context.plugin_id,
context.version_state or {},
- cast('PluginPrecheckContext', context.precheck),
+ context.precheck_result,
)
payload['operation'] = 'upgrade'
return self._with_plugin_capability(payload, context.discovered_plugin)
@@ -334,7 +338,7 @@ async def _upgrade_step_check_upgrade_blockers(
context.plugin_id,
operation='upgrade',
actions=context.actions or [],
- precheck=cast('PluginPrecheckContext', context.precheck),
+ precheck=context.precheck_result,
extra_payload=context.version_state or {},
)
@@ -348,8 +352,8 @@ async def _upgrade_step_check_installed_menu_conflicts(
:param context: 插件升级上下文
:return: 菜单冲突 payload 或 None
"""
- installed_menu_conflicts = await context.lifecycle_uow.check_installed_menu_conflicts(
- context.discovered_plugin,
+ installed_menu_conflicts = await context.active_transaction.check_installed_menu_conflicts(
+ context.resolved_plugin,
)
if not installed_menu_conflicts:
return None
@@ -360,7 +364,7 @@ async def _upgrade_step_check_installed_menu_conflicts(
'插件菜单与已安装菜单存在冲突,升级已中止', msg_key='plugin.runtime.upgrade.menuConflict'
),
actions=context.actions or [],
- precheck=cast('PluginPrecheckContext', context.precheck),
+ precheck=context.precheck_result,
installed_menu_conflicts=installed_menu_conflicts,
extra_payload=context.version_state or {},
)
@@ -374,8 +378,8 @@ async def _upgrade_step_upsert_plugin(
:param context: 插件升级上下文
"""
- await context.lifecycle_uow.upsert_discovered_plugin(
- context.discovered_plugin,
+ await context.active_transaction.upsert_discovered_plugin(
+ context.resolved_plugin,
Path(self.dependencies.runtime_environment.get_backend_plugins_dir()),
Path(self.dependencies.runtime_environment.get_frontend_plugins_dir()),
)
@@ -392,8 +396,8 @@ async def _upgrade_step_install_menus(
:param context: 插件升级上下文
"""
plugin_enabled = getattr(context.database_plugin, 'enabled', '1') == '0'
- await context.lifecycle_uow.install_plugin_menu(
- context.discovered_plugin,
+ await context.active_transaction.install_plugin_menu(
+ context.resolved_plugin,
enabled=plugin_enabled,
)
@@ -408,8 +412,8 @@ async def _upgrade_step_install_configs(
:param context: 插件升级上下文
"""
- context.installed_configs = await context.lifecycle_uow.install_plugin_default_config(
- context.discovered_plugin,
+ context.installed_configs = await context.active_transaction.install_plugin_default_config(
+ context.resolved_plugin,
)
return None
@@ -424,8 +428,8 @@ async def _upgrade_step_install_jobs(
:param context: 插件升级上下文
"""
plugin_enabled = getattr(context.database_plugin, 'enabled', '1') == '0'
- await context.lifecycle_uow.install_plugin_jobs(
- context.discovered_plugin,
+ await context.active_transaction.install_plugin_jobs(
+ context.resolved_plugin,
enabled=plugin_enabled,
)
@@ -441,7 +445,7 @@ async def _upgrade_step_run_migrations(
:param context: 插件升级上下文
"""
context.migration_results = await self.dependencies.migration_execution_gateway.run_plugin_migrations(
- context.discovered_plugin,
+ context.resolved_plugin,
)
return None
@@ -455,7 +459,7 @@ async def _upgrade_step_run_seeds(
:param context: 插件升级上下文
"""
- context.seed_results = await PluginSeedRunner(context.discovered_plugin).run(context.session)
+ context.seed_results = await PluginSeedRunner(context.resolved_plugin).run(context.session)
return None
@@ -468,7 +472,7 @@ async def _upgrade_step_run_upgrade_hook(
:param context: 插件升级上下文
"""
- context.hook_result = await PluginHookRunner(context.discovered_plugin).run(
+ context.hook_result = await PluginHookRunner(context.resolved_plugin).run(
'on_upgrade',
query_db=context.session,
)
@@ -484,8 +488,8 @@ async def _upgrade_step_mark_installed(
:param context: 插件升级上下文
"""
- context.plugin = await context.lifecycle_uow.mark_plugin_installed(
- context.discovered_plugin,
+ context.plugin = await context.active_transaction.mark_plugin_installed(
+ context.resolved_plugin,
)
return None
@@ -499,7 +503,7 @@ async def _upgrade_step_commit(
:param context: 插件升级上下文
"""
- await context.lifecycle_uow.commit()
+ await context.active_transaction.commit()
CatalogRegistry.commit_plugin(
context.plugin_id, context.catalog_snapshot, enabled=getattr(context.plugin, 'enabled', '0') == '0'
)
@@ -530,8 +534,8 @@ async def _build_upgrade_precheck(
:return: 插件预检上下文
"""
return await self._build_precheck_context(
- cast('Path', context.backend_root),
- cast('DiscoveredPlugin', context.discovered_plugin),
+ require_step_result(context.backend_root, 'discover_plugin'),
+ context.resolved_plugin,
context.discovered_plugins or [],
)
@@ -548,7 +552,7 @@ def _refresh_upgrade_actions(
"""
context.precheck = precheck
context.actions = PluginPayloadBuilder.build_upgrade_actions(
- cast('DiscoveredPlugin', context.discovered_plugin),
+ context.resolved_plugin,
precheck.dependency_result.ok,
precheck.plugin_dependency_result.ok,
precheck.structure_result.ok,
@@ -558,14 +562,14 @@ def _refresh_upgrade_actions(
def _build_upgrade_operation_payload(
self,
context: PluginUpgradeLifecycleContext,
- ) -> dict[str, object]:
+ ) -> UpgradeDryRunPayloadContext:
"""
构建升级预检操作 payload。
:param context: 插件升级上下文
:return: 升级操作 payload
"""
- precheck = cast('PluginPrecheckContext', context.precheck)
+ precheck = context.precheck_result
return {
'versionState': context.version_state or {},
'dependencyResult': precheck.dependency_result,
@@ -595,11 +599,11 @@ def _build_upgrade_success_payload(
context.plugin_id,
message=I18nMessage('插件升级完成', msg_key='plugin.runtime.upgrade.completed'),
actions=context.actions or [],
- precheck=cast('PluginPrecheckContext', context.precheck),
- plugin=context.plugin,
- installed_configs=context.installed_configs,
- migration_results=context.migration_results,
- seed_results=context.seed_results,
+ precheck=context.precheck_result,
+ plugin=require_step_result(context.plugin, 'mark_installed'),
+ installed_configs=require_step_result(context.installed_configs, 'install_configs'),
+ migration_results=require_step_result(context.migration_results, 'run_migrations'),
+ seed_results=require_step_result(context.seed_results, 'run_seeds'),
hook_result=context.hook_result,
extra_payload=context.version_state or {},
)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/migration.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/migration.py
index b876e1b8a..c08c77528 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/migration.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/migration.py
@@ -1,4 +1,4 @@
-from typing import Literal
+from typing import Literal, cast
from i18n.message import I18nMessage
from plugins.core.runtime.support import PluginRuntimePayloadBuilder
@@ -149,7 +149,7 @@ def _dump_migration_model(migration: object) -> dict[str, object]:
"""
model_dump = getattr(migration, 'model_dump', None)
if callable(model_dump):
- return model_dump(by_alias=True)
+ return cast('dict[str, object]', model_dump(by_alias=True))
return {
'pluginId': getattr(migration, 'plugin_id', None),
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/migration_store.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/migration_store.py
index 0108ec6d0..1390e5ebb 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/migration_store.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/migration_store.py
@@ -12,6 +12,8 @@
if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncSession
+ from plugins.core.management.entity.vo.schemas import PluginMigrationModel
+
class PluginDatabaseMigrationHistoryStore(PluginMigrationHistoryStore):
"""
@@ -185,7 +187,7 @@ async def record_failure(
),
)
- async def _add_plugin_migration(self, query_db: 'AsyncSession', plugin_migration: object) -> None:
+ async def _add_plugin_migration(self, query_db: 'AsyncSession', plugin_migration: 'PluginMigrationModel') -> None:
"""
写入 migration 历史,优先使用独立会话提交。
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/precheck.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/precheck.py
index cc7ce5e30..bcaba68cc 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/precheck.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/precheck.py
@@ -1,5 +1,4 @@
from pathlib import Path
-from typing import cast
from i18n.message import I18nMessage
from plugins.core.discovery.scanner import DiscoveredPlugin
@@ -92,7 +91,7 @@ def _with_plugin_capability(
:param discovered_plugin: 已发现插件
:return: 附加能力后的响应负载
"""
- return cast('dict[str, object]', self.context.with_plugin_capability(payload, discovered_plugin))
+ return self.context.with_plugin_capability(payload, discovered_plugin)
async def precheck_plugin_operation(
self, plugin_id: str, operation: PluginBatchOperation
@@ -139,10 +138,7 @@ async def precheck_plugin_operation(
purge_plan=purge_plan,
purge_plan_error=purge_plan_error,
)
- return cast(
- 'PluginPrecheckResponse',
- self._with_plugin_capability(cast('dict[str, object]', payload), discovered_plugin),
- )
+ return self._with_plugin_capability(payload, discovered_plugin)
except Exception as exc:
return PluginRuntimePayloadBuilder.build_exception_payload(
I18nMessage('插件操作预检失败', msg_key='plugin.runtime.precheck.failed'), exc
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/query.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/query.py
index 84dc4154b..23e89644d 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/query.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/query.py
@@ -147,7 +147,7 @@ def _with_plugin_capability(
:param discovered_plugin: 已发现插件
:return: 附加能力后的响应负载
"""
- return cast('dict[str, object]', self.context.with_plugin_capability(payload, discovered_plugin))
+ return self.context.with_plugin_capability(payload, discovered_plugin)
def list_plugins(self) -> PluginCatalogListResponse:
"""
@@ -161,7 +161,7 @@ def list_plugins(self) -> PluginCatalogListResponse:
plugin_items = cast('list[dict[str, object]]', payload['plugins'])
for item, plugin in zip(plugin_items, registry.list_plugins(), strict=False):
self._with_plugin_capability(item, plugin.discovered_plugin)
- return cast('PluginCatalogListResponse', payload)
+ return payload
except Exception as exc:
return PluginRuntimePayloadBuilder.build_exception_payload(
I18nMessage('读取插件列表失败', msg_key='plugin.runtime.listFailed'), exc
@@ -186,7 +186,7 @@ async def list_plugins_with_state(self) -> PluginCatalogListResponse:
plugin_items = cast('list[dict[str, object]]', payload['plugins'])
for item, plugin in zip(plugin_items, registry.list_plugins(), strict=False):
self._with_plugin_capability(item, plugin.discovered_plugin)
- return cast('PluginCatalogListResponse', payload)
+ return payload
except Exception as exc:
return PluginRuntimePayloadBuilder.build_exception_payload(
I18nMessage('读取插件列表失败', msg_key='plugin.runtime.listFailed'), exc
@@ -205,13 +205,10 @@ def get_plugin_info(self, plugin_id: str) -> PluginCatalogInfoResponse:
if not plugin:
return PluginPayloadBuilder.build_plugin_not_found_payload(plugin_id)
dependency_result = self.dependencies.dependency_checker.check_manifest(plugin.discovered_plugin.manifest)
- return cast(
- 'PluginCatalogInfoResponse',
- PluginPayloadBuilder.build_plugin_info_payload(
- plugin,
- dependency_result.items,
- capability=self._resolve_plugin_capability(plugin.discovered_plugin),
- ),
+ return PluginPayloadBuilder.build_plugin_info_payload(
+ plugin,
+ dependency_result.items,
+ capability=self._resolve_plugin_capability(plugin.discovered_plugin),
)
except Exception as exc:
return PluginRuntimePayloadBuilder.build_exception_payload(
@@ -234,16 +231,15 @@ async def get_plugin_info_with_state(self, plugin_id: str) -> PluginCatalogInfoR
database_plugin, database_error = await self._load_database_plugin_state(plugin_id)
if database_plugin:
plugin = PluginRegistry.build([plugin.discovered_plugin], [database_plugin]).get_plugin(plugin_id)
+ if plugin is None:
+ return PluginPayloadBuilder.build_plugin_not_found_payload(plugin_id)
dependency_result = self.dependencies.dependency_checker.check_manifest(plugin.discovered_plugin.manifest)
- return cast(
- 'PluginCatalogInfoResponse',
- PluginPayloadBuilder.build_plugin_info_payload(
- plugin,
- dependency_result.items,
- database_error=database_error,
- capability=self._resolve_plugin_capability(plugin.discovered_plugin),
- ),
+ return PluginPayloadBuilder.build_plugin_info_payload(
+ plugin,
+ dependency_result.items,
+ database_error=database_error,
+ capability=self._resolve_plugin_capability(plugin.discovered_plugin),
)
except Exception as exc:
return PluginRuntimePayloadBuilder.build_exception_payload(
@@ -332,14 +328,9 @@ def _build_check_plugin_payload(
menu_conflict_result,
)
check_item = PluginPayloadBuilder.build_check_item(plugin.plugin_id, precheck)
- checks.append(
- cast(
- 'dict[str, object]',
- self._with_plugin_capability(cast('dict[str, object]', check_item), plugin.discovered_plugin),
- )
- )
+ checks.append(self._with_plugin_capability(check_item, plugin.discovered_plugin))
- return cast('PluginCheckResponse', PluginPayloadBuilder.build_check_payload(checks, database_error))
+ return PluginPayloadBuilder.build_check_payload(checks, database_error)
except Exception as exc:
return PluginRuntimePayloadBuilder.build_exception_payload(
I18nMessage('插件检查失败', msg_key='plugin.runtime.checkFailed'), exc
@@ -359,10 +350,7 @@ def check_plugin_dependencies(self, plugin_id: str) -> PluginDependencyCheckResp
dependency_result = self.dependencies.dependency_checker.check_manifest(discovered_plugin.manifest)
payload = PluginPayloadBuilder.build_dependency_check_payload(plugin_id, dependency_result)
- return cast(
- 'PluginDependencyCheckResponse',
- self._with_plugin_capability(cast('dict[str, object]', payload), discovered_plugin),
- )
+ return self._with_plugin_capability(payload, discovered_plugin)
except Exception as exc:
return PluginRuntimePayloadBuilder.build_exception_payload(
I18nMessage('检查插件依赖失败', msg_key='plugin.runtime.dependencies.checkFailed'), exc
@@ -396,21 +384,20 @@ async def diagnose_plugin(self, plugin_id: str) -> PluginDiagnoseResponse:
:param plugin_id: 插件ID
:return: 插件诊断包负载
"""
- info_payload = cast('dict[str, object]', await self.get_plugin_info_with_state(plugin_id))
+ info_payload = await self.get_plugin_info_with_state(plugin_id)
if not info_payload.get('ok', False):
database_plugin, database_error = await self._load_database_plugin_state(plugin_id)
if (
database_error is None
- and getattr(database_plugin, 'source', None) == 'artifact'
+ and database_plugin is not None
+ and database_plugin.source == 'artifact'
and self._get_discovered_plugin(plugin_id) is None
):
return await self._diagnose_database_artifact(plugin_id, database_plugin)
return PluginRuntimePayloadBuilder.build_diagnose_failure_payload(plugin_id, info_payload)
- check_payload = cast('dict[str, object]', await self.check_plugin_async(plugin_id))
- config_payload = cast(
- 'dict[str, object]', await self.runtime_operations.get_plugin_config(plugin_id, reveal_secret=False)
- )
+ check_payload = await self.check_plugin_async(plugin_id)
+ config_payload = await self.runtime_operations.get_plugin_config(plugin_id, reveal_secret=False)
config_payload['summary'] = PluginConfigPayloadBuilder.build_diagnostic_summary(config_payload.get('configs'))
audit_payload = await self._build_recent_audit_snapshot(plugin_id)
discovered_plugin = self._get_discovered_plugin(plugin_id)
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/responses.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/responses.py
index 2c6656fa8..c99414a1f 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/responses.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/responses.py
@@ -18,7 +18,6 @@
PluginEnableUpdateFailurePayloadDict,
PluginLifecyclePayloadDict,
PluginNotFoundPayloadDict,
- PluginPlanResponsePayload,
PluginPurgeStatePayloadDict,
PluginRuntimeBatchItemUnsupportedPayloadDict,
PluginRuntimeDiagnoseFailurePayloadDict,
@@ -101,7 +100,7 @@ class PluginRuntimeBlockedPayload(PluginPayloadModel):
PluginConfigExportResponse: TypeAlias = PluginConfigExportPayloadDict | PluginConfigExportFailurePayloadDict
PluginConfigImportResponse: TypeAlias = PluginConfigImportPayloadDict
PluginPrecheckResponse: TypeAlias = PluginRuntimePrecheckPayloadDict | PluginRuntimeFailureResponse
-PluginPlanResponse: TypeAlias = PluginPlanResponsePayload | PluginRuntimeInvalidOperationPayloadDict
+PluginPlanResponse: TypeAlias = dict[str, object] | PluginRuntimeInvalidOperationPayloadDict
PluginBatchResponse: TypeAlias = PluginPlanResponse | PluginBatchRunResponseDict | PluginRuntimeExceptionPayloadDict
PluginBatchItemExecutionResponse: TypeAlias = (
BatchOperationResultPayload
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/startup.py b/ruoyi-fastapi-backend/plugins/core/runtime/startup.py
index cc19e8998..6dde08506 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/startup.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/startup.py
@@ -379,7 +379,7 @@ async def activate_explicit_plugins(self, app: FastAPI, *, startup_write_enabled
runtime = getattr(app.state, 'plugin_explicit_runtime', None)
if not isinstance(runtime, ExplicitPluginRuntime):
return
- registry = getattr(app.state, 'plugin_registry', None)
+ registry: PluginRegistry = app.state.plugin_registry
enabled = {plugin.plugin_id for plugin in registry.list_enabled_plugins()}
failures: set[str] = set()
try:
@@ -515,7 +515,7 @@ def _has_startup_dependency_error(plugin: RegisteredPlugin) -> bool:
database_plugin = plugin.database_plugin
last_error = getattr(database_plugin, 'last_error', None) if database_plugin else None
return (
- getattr(database_plugin, 'status', None) == 'error'
+ bool(getattr(database_plugin, 'status', None) == 'error')
and isinstance(last_error, str)
and last_error.startswith(PLUGIN_STARTUP_DEPENDENCY_ERROR_PREFIX)
)
@@ -929,9 +929,8 @@ def _should_sync_plugin_install_state(plugin: RegisteredPlugin) -> bool:
database_plugin = plugin.database_plugin
if database_plugin is None:
return True
- return (
- not getattr(database_plugin, 'installed_version', None)
- and getattr(database_plugin, 'status', None) == 'discovered'
+ return not getattr(database_plugin, 'installed_version', None) and bool(
+ getattr(database_plugin, 'status', None) == 'discovered'
)
async def run_plugin_install_scripts(self, query_db: Any, discovered_plugin: Any) -> None:
@@ -1249,8 +1248,8 @@ def _should_sync_default_enabled_builtin_plugin(database_plugin: Any | None) ->
return True
return (
not getattr(database_plugin, 'installed_version', None)
- and getattr(database_plugin, 'status', None) == 'discovered'
- and getattr(database_plugin, 'enabled', None) == '0'
+ and bool(getattr(database_plugin, 'status', None) == 'discovered')
+ and bool(getattr(database_plugin, 'enabled', None) == '0')
)
@staticmethod
@@ -1291,7 +1290,7 @@ def get_registered_plugin(app: FastAPI, plugin_id: str) -> RegisteredPlugin | No
:param plugin_id: 插件ID
:return: 插件运行时快照
"""
- plugin_registry = getattr(app.state, 'plugin_registry', None)
+ plugin_registry: PluginRegistry | None = getattr(app.state, 'plugin_registry', None)
if plugin_registry is None:
return None
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/startup_coordination.py b/ruoyi-fastapi-backend/plugins/core/runtime/startup_coordination.py
index 1da116740..0e7c4177d 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/startup_coordination.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/startup_coordination.py
@@ -3,6 +3,7 @@
from config.env import AppConfig
from plugins.core.discovery.scanner import PluginScanner
+from plugins.core.manifest.v2 import PluginManifestV2
PLUGIN_STARTUP_FINGERPRINT_SUFFIXES = frozenset(
{'.py', '.sql', '.yaml', '.yml', '.pyd', '.so', '.whl', '.dll', '.dylib'}
@@ -66,13 +67,14 @@ def resolve(self) -> str:
# 在不可变制品索引接入前,按清单精确覆盖 bundle 和 native 安装目录。
# 不把上传数据、日志、pycache 等可变内容计入发布代际。
for plugin in PluginScanner(plugins_root).discover_with_errors().plugins:
- if not plugin.manifest.uses_entrypoint:
+ manifest = plugin.manifest
+ if not isinstance(manifest, PluginManifestV2):
continue
resource_dirs = []
- if plugin.manifest.runtime_kind == 'native':
- resource_dirs.append(plugin.backend_path / plugin.manifest.backend.native.module_root)
- if plugin.manifest.frontend.delivery.type == 'bundle':
- resource_dirs.append(plugin.backend_path / plugin.manifest.frontend.bundle.directory)
+ if manifest.backend.native is not None:
+ resource_dirs.append(plugin.backend_path / manifest.backend.native.module_root)
+ if manifest.frontend.bundle is not None:
+ resource_dirs.append(plugin.backend_path / manifest.frontend.bundle.directory)
for resource_dir in resource_dirs:
if not resource_dir.resolve().is_relative_to(plugin.backend_path.resolve()):
continue
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/batch_report.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/batch_report.py
index b32f38061..9e110d090 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/batch_report.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/batch_report.py
@@ -188,13 +188,16 @@ def resolve_executable_plugin_ids(plan_payload: BatchPlanPayload) -> list[str]:
return []
requested_plugin_ids = plan.get('requestedPluginIds')
ordered_plugin_ids = plan.get('orderedPluginIds')
- if not isinstance(requested_plugin_ids, list) or not requested_plugin_ids:
- return ordered_plugin_ids if isinstance(ordered_plugin_ids, list) else []
if not isinstance(ordered_plugin_ids, list):
- return requested_plugin_ids
-
- requested_plugin_id_set = set(requested_plugin_ids)
- return [plugin_id for plugin_id in ordered_plugin_ids if plugin_id in requested_plugin_id_set]
+ ordered_plugin_ids = requested_plugin_ids
+ if not isinstance(ordered_plugin_ids, list):
+ return []
+ requested = set(requested_plugin_ids) if isinstance(requested_plugin_ids, list) else set()
+ return [
+ plugin_id
+ for plugin_id in ordered_plugin_ids
+ if isinstance(plugin_id, str) and (not requested or plugin_id in requested)
+ ]
@classmethod
def build_plan_blocked_payload(
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/npm_package.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/npm_package.py
index 457b673d4..3846e89ae 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/npm_package.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/npm_package.py
@@ -1,10 +1,9 @@
import json
+from collections.abc import Mapping, Sequence
from pathlib import Path
from plugins.core.validation.dependencies import DependencyInstallPlanItem, DependencyRequirementParser
-from .payload.dependencies import DependencyInstallReturnCodePayload
-
class PluginNpmPackageJsonSynchronizer:
"""
@@ -18,7 +17,7 @@ class PluginNpmPackageJsonSynchronizer:
def sync_successful_items(
cls,
install_plan_items: list[DependencyInstallPlanItem],
- install_results: list[DependencyInstallReturnCodePayload],
+ install_results: Sequence[Mapping[str, object]],
) -> None:
"""
同步安装成功的 npm 依赖声明。
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/audit.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/audit.py
index bbc091d88..05769138f 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/audit.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/audit.py
@@ -1,4 +1,4 @@
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from typing import Protocol, TypeAlias, cast
from pydantic import Field
@@ -81,7 +81,7 @@ def build_recent_snapshot_failure(error: Exception) -> PluginAuditSnapshotFailur
def build_recent_snapshot_payload(
cls,
plugin_id: str,
- operation_logs: list[object],
+ operation_logs: Sequence[object],
*,
audit_limit: int,
) -> PluginAuditSnapshotPayloadDict:
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/base.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/base.py
index 030b0286a..7233e7245 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/base.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/base.py
@@ -1,4 +1,4 @@
-from typing import Any
+from typing import Any, cast
from pydantic import BaseModel, ConfigDict, ValidatorFunctionWrapHandler, field_validator
@@ -8,7 +8,7 @@
class PluginPayloadModel(BaseModel):
"""插件运行时 payload 模型基类。"""
- model_config = ConfigDict(populate_by_name=True, extra='forbid')
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra='forbid')
@field_validator('message', 'suggestion', mode='wrap', check_fields=False)
@classmethod
@@ -23,14 +23,14 @@ def preserve_message_metadata(cls, value: Any, handler: ValidatorFunctionWrapHan
validated = handler(value)
return value if isinstance(value, I18nMessage) else validated
- def to_payload(self, *, exclude_none: bool = False) -> dict[str, Any]:
+ def to_payload(self, *, exclude_none: bool = False) -> dict[str, object]:
"""
序列化为现有运行时 dict payload 契约。
:param exclude_none: 是否排除 None 字段
:return: payload 字典
"""
- return self.model_dump(by_alias=True, exclude_none=exclude_none)
+ return cast('dict[str, object]', self.model_dump(by_alias=True, exclude_none=exclude_none))
__all__ = ['PluginPayloadModel']
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/catalog.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/catalog.py
index d67abcfc6..a74e7da4f 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/catalog.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/catalog.py
@@ -7,14 +7,15 @@
from plugins.core.manifest.menu_tree import PluginMenuTree
from plugins.core.manifest.schema import (
PluginConfigItemManifest,
- PluginJobManifest,
PluginMenuManifest,
PluginPermissionManifest,
)
+from plugins.core.manifest.v2 import VersionedPluginJobManifest
from plugins.core.types import PluginStateRecord, SupportsToPayload
from plugins.core.validation.dependencies import DependencyCheckItem
from .base import PluginPayloadModel
+from .validation import PluginValidationPayloadMixin
class PluginCatalogSummaryPayload(PluginPayloadModel):
@@ -264,7 +265,7 @@ def build_plugin_detail(
}
for dependency in manifest.dependencies.plugins
],
- 'dependencies': [cls.build_dependency_item(item) for item in dependency_items],
+ 'dependencies': [PluginValidationPayloadMixin.build_dependency_item(item) for item in dependency_items],
}
@staticmethod
@@ -352,16 +353,16 @@ def _build_menu_plan_item(cls, menu: PluginMenuManifest) -> dict[str, object]:
perms=menu.perms,
type=menu.type,
query=menu.query,
- routeName=menu.route_name,
- isFrame=menu.is_frame,
- isCache=menu.is_cache,
+ route_name=menu.route_name,
+ is_frame=menu.is_frame,
+ is_cache=menu.is_cache,
visible=menu.visible,
status=menu.status,
children=len(menu.children),
).to_payload()
@staticmethod
- def build_manifest_job_item(job: PluginJobManifest) -> dict[str, object]:
+ def build_manifest_job_item(job: VersionedPluginJobManifest) -> dict[str, object]:
"""
构建 manifest 定时任务声明负载。
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/config.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/config.py
index 000594a7b..27a0d328d 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/config.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/config.py
@@ -1,4 +1,4 @@
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from typing import TypeAlias, cast
from pydantic import Field
@@ -109,7 +109,7 @@ class PluginConfigPayloadBuilder:
"""
@classmethod
- def build_read_payload(cls, plugin_id: str, configs: list[SupportsModelDump]) -> PluginConfigStatePayloadDict:
+ def build_read_payload(cls, plugin_id: str, configs: Sequence[SupportsModelDump]) -> PluginConfigStatePayloadDict:
"""
构建插件配置读取负载。
@@ -205,9 +205,9 @@ def build_export_payload(
reveal_secret=reveal_secret,
configs=config_items,
values={
- config.get('key'): cast('PluginConfigValue', config.get('value'))
+ key: cast('PluginConfigValue', config.get('value'))
for config in config_items
- if isinstance(config.get('key'), str)
+ if isinstance(key := config.get('key'), str)
},
metadata=[cls._build_export_metadata(config) for config in config_items],
).to_payload()
@@ -219,7 +219,7 @@ def build_update_payload(
*,
operation: str,
message: str,
- configs: list[SupportsModelDump],
+ configs: Sequence[SupportsModelDump],
) -> PluginConfigStatePayloadDict:
"""
构建插件配置更新负载。
@@ -268,8 +268,8 @@ def build_audit_payload(
*,
operation: str,
values: dict[str, PluginConfigValue],
- before_configs: list[SupportsModelDump],
- after_configs: list[SupportsModelDump],
+ before_configs: Sequence[SupportsModelDump],
+ after_configs: Sequence[SupportsModelDump],
message: str,
) -> PluginConfigAuditPayloadDict:
"""
@@ -307,7 +307,7 @@ def _build_state_payload(
*,
plugin_id: str,
message: str,
- configs: list[SupportsModelDump],
+ configs: Sequence[SupportsModelDump],
operation: str | None = None,
) -> PluginConfigStatePayloadDict:
"""
@@ -356,7 +356,7 @@ def _build_export_metadata(config: Mapping[str, object]) -> dict[str, object]:
}
@staticmethod
- def _build_audit_map(configs: list[SupportsModelDump]) -> dict[str, dict[str, PluginConfigValue]]:
+ def _build_audit_map(configs: Sequence[SupportsModelDump]) -> dict[str, dict[str, PluginConfigValue]]:
"""
构建按配置键索引的审计配置映射。
@@ -378,7 +378,7 @@ def _build_audit_item(
key: str,
before_config: dict[str, PluginConfigValue],
after_config: dict[str, PluginConfigValue],
- ) -> PluginConfigAuditChangePayload:
+ ) -> dict[str, object]:
"""
构建单个配置项的脱敏变更摘要。
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/lifecycle.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/lifecycle.py
index 9f9d43fe7..bbd4b6051 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/lifecycle.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/lifecycle.py
@@ -1,4 +1,4 @@
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from typing import Protocol, TypeAlias, cast
from pydantic import Field
@@ -12,44 +12,20 @@
from . import PluginPayloadBuilder
from .base import PluginPayloadModel
-from .plan import ActionPayload, VersionStatePayload
-from .validation import MenuConflictItemPayload
+from .validation import PluginRuntimePrecheckProtocol
-class SupportsOk(Protocol):
- """
- 支持 ok 属性的检查结果协议。
-
- :ivar ok: 操作或检查是否成功
- """
-
- ok: bool
-
+class PluginLifecyclePrecheckProtocol(PluginRuntimePrecheckProtocol, Protocol):
+ """生命周期响应所需的预检结果。"""
-class PluginLifecyclePrecheckProtocol(Protocol):
- """
- lifecycle payload 所需的预检上下文协议。
-
- :ivar ok: 操作或检查是否成功
- :ivar dependency_result: 依赖检查结果
- :ivar manifest_result: manifest 非阻断检查结果
- :ivar plugin_dependency_result: 插件间依赖检查结果
- :ivar structure_result: 插件结构检查结果
- :ivar menu_conflict_result: 菜单冲突检查结果
- :ivar operation_payload: 描述当前操作的结构化数据
- :ivar check_payload: 预检结果的结构化数据
- :ivar menu_conflicts: 菜单冲突负载
- """
+ @property
+ def menu_conflicts(self) -> Sequence[dict[str, object]]:
+ """
+ 获取菜单冲突明细。
- ok: bool
- dependency_result: SupportsOk
- manifest_result: SupportsOk
- plugin_dependency_result: SupportsOk
- structure_result: SupportsOk
- menu_conflict_result: SupportsOk
- operation_payload: Mapping[str, object]
- check_payload: Mapping[str, object]
- menu_conflicts: list[MenuConflictItemPayload]
+ :return: 菜单冲突明细
+ """
+ ...
class PluginLifecyclePayload(PluginPayloadModel):
@@ -135,7 +111,7 @@ class PluginLifecyclePayloadBuilder:
@staticmethod
def build_install_dry_run_payload(
plugin_id: str,
- actions: list[ActionPayload],
+ actions: list[dict[str, object]],
precheck: PluginLifecyclePrecheckProtocol,
) -> PluginLifecyclePayloadDict:
"""
@@ -164,7 +140,7 @@ def build_precheck_blocker_payload(
plugin_id: str,
*,
message: str,
- actions: list[ActionPayload],
+ actions: list[dict[str, object]],
precheck: PluginLifecyclePrecheckProtocol,
dry_run: bool = False,
extra_payload: Mapping[str, object] | None = None,
@@ -198,7 +174,7 @@ def build_first_precheck_blocker_payload(
plugin_id: str,
*,
operation: str,
- actions: list[ActionPayload],
+ actions: list[dict[str, object]],
precheck: PluginLifecyclePrecheckProtocol,
extra_payload: Mapping[str, object] | None = None,
) -> PluginLifecyclePayloadDict | None:
@@ -247,7 +223,7 @@ def build_dependency_blocker_payload(
cls,
plugin_id: str,
*,
- actions: list[ActionPayload],
+ actions: list[dict[str, object]],
precheck: PluginLifecyclePrecheckProtocol,
dependency_install_payload: Mapping[str, object],
) -> PluginLifecyclePayloadDict | None:
@@ -277,7 +253,7 @@ def build_operation_dry_run_payload(
*,
operation: str,
message: str,
- actions: list[ActionPayload],
+ actions: list[dict[str, object]],
precheck: PluginLifecyclePrecheckProtocol,
extra_payload: Mapping[str, object] | None = None,
ok_from_precheck: bool = True,
@@ -318,7 +294,7 @@ def build_installed_menu_conflict_payload(
plugin_id: str,
*,
message: str,
- actions: list[ActionPayload],
+ actions: list[dict[str, object]],
precheck: PluginLifecyclePrecheckProtocol,
installed_menu_conflicts: list[PluginMenuConflictItem],
extra_payload: Mapping[str, object] | None = None,
@@ -355,7 +331,7 @@ def build_installed_menu_conflict_payload(
@staticmethod
def build_upgrade_latest_payload(
plugin_id: str,
- version_state: VersionStatePayload,
+ version_state: dict[str, object],
precheck: PluginLifecyclePrecheckProtocol,
) -> PluginLifecyclePayloadDict:
"""
@@ -383,10 +359,10 @@ def build_success_payload(
plugin_id: str,
*,
message: str,
- actions: list[ActionPayload],
+ actions: list[dict[str, object]],
precheck: PluginLifecyclePrecheckProtocol,
plugin: SupportsModelDump,
- installed_configs: list[SupportsModelDump],
+ installed_configs: Sequence[SupportsModelDump],
migration_results: list[PluginMigrationResult],
seed_results: list[PluginSeedResult],
hook_result: PluginHookResult | None,
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/plan.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/plan.py
index 88f6d69b5..8608e35d9 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/plan.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/plan.py
@@ -1,5 +1,5 @@
from subprocess import CompletedProcess
-from typing import TYPE_CHECKING, Protocol, TypeAlias, cast
+from typing import TypeAlias, TypedDict
from pydantic import Field
@@ -8,28 +8,18 @@
from plugins.core.lifecycle.purge import PluginPurgePlan, PluginPurgePlanItem
from plugins.core.manifest.menu_tree import PluginMenuTree
from plugins.core.validation.dependencies import DependencyCheckResult, DependencyInstallPlanItem
+from plugins.core.validation.menus import PluginMenuConflictResult
from plugins.core.validation.plugin_deps import (
PluginDependencyCheckResult,
PluginDependencyPlan,
PluginDependencyPlanBlocker,
PluginDependencyPlanItem,
)
+from plugins.core.validation.structure import PluginStructureCheckResult
from plugins.core.validation.versioning import PluginVersionComparator
from .base import PluginPayloadModel
-
-if TYPE_CHECKING:
- from plugins.core.validation.structure import PluginStructureCheckResult
-
-
-class SupportsOk(Protocol):
- """
- 支持 ok 属性的检查结果协议。
-
- :ivar ok: 操作或检查是否成功
- """
-
- ok: bool
+from .validation import PluginValidationPayloadMixin
class PluginPlanBlockerPayload(PluginPayloadModel):
@@ -159,7 +149,36 @@ class VersionStatePayload(PluginPayloadModel):
needs_upgrade: bool = Field(alias='needsUpgrade', description='是否需要升级已安装版本')
-UpgradeDryRunPayloadContext: TypeAlias = dict[str, object]
+class UpgradeDryRunPayloadContext(TypedDict):
+ """
+ 升级预演所需的版本状态、动作和预检结果。
+
+ :ivar versionState: 升级前后的版本信息
+ :ivar dependencyResult: 软件包依赖检查结果
+ :ivar pluginDependencyResult: 插件间依赖检查结果
+ :ivar structureResult: 插件结构检查结果
+ :ivar menuConflictResult: 菜单冲突检查结果
+ :ivar manifestOk: 插件清单是否通过检查
+ :ivar actions: 预演动作
+ :ivar manifestIssues: 插件清单错误
+ :ivar manifestWarnings: 插件清单警告
+ :ivar pluginDependencyErrors: 插件间依赖错误
+ :ivar structureErrors: 插件结构错误
+ :ivar menuConflicts: 菜单冲突明细
+ """
+
+ versionState: dict[str, object]
+ dependencyResult: DependencyCheckResult
+ pluginDependencyResult: PluginDependencyCheckResult
+ structureResult: PluginStructureCheckResult
+ menuConflictResult: PluginMenuConflictResult
+ manifestOk: bool
+ actions: list[dict[str, object]]
+ manifestIssues: list[dict[str, object]]
+ manifestWarnings: list[dict[str, object]]
+ pluginDependencyErrors: list[dict[str, object]]
+ structureErrors: list[dict[str, object]]
+ menuConflicts: list[dict[str, object]]
class UpgradeDryRunPayload(PluginPayloadModel):
@@ -202,7 +221,7 @@ class PluginPlanPayloadMixin:
"""插件依赖拓扑、执行动作和物理清理计划负载构建能力。"""
@staticmethod
- def build_plugin_plan_blocker(item: PluginDependencyPlanBlocker) -> PluginPlanBlockerPayload:
+ def build_plugin_plan_blocker(item: PluginDependencyPlanBlocker) -> dict[str, object]:
"""
构建插件批量操作计划阻塞项负载。
@@ -217,7 +236,7 @@ def build_plugin_plan_blocker(item: PluginDependencyPlanBlocker) -> PluginPlanBl
).to_payload()
@classmethod
- def build_plugin_plan_item(cls, item: PluginDependencyPlanItem) -> PluginPlanItemPayload:
+ def build_plugin_plan_item(cls, item: PluginDependencyPlanItem) -> dict[str, object]:
"""
构建插件批量操作计划项负载。
@@ -262,7 +281,7 @@ def build_plan_payload(
cls,
plan: PluginDependencyPlan,
database_error: str | None = None,
- ) -> PluginPlanResponsePayload:
+ ) -> dict[str, object]:
"""
构建插件批量操作计划响应负载。
@@ -282,7 +301,7 @@ def build_plan_payload(
).to_payload()
@staticmethod
- def build_dependency_install_plan_item(item: DependencyInstallPlanItem) -> DependencyInstallPlanItemPayload:
+ def build_dependency_install_plan_item(item: DependencyInstallPlanItem) -> dict[str, object]:
"""
构建依赖安装计划项负载。
@@ -304,7 +323,7 @@ def build_dependency_install_plan_item(item: DependencyInstallPlanItem) -> Depen
def build_dependency_install_result(
item: DependencyInstallPlanItem,
completed: CompletedProcess[str],
- ) -> DependencyInstallResultPayload:
+ ) -> dict[str, object]:
"""
构建依赖安装执行结果负载。
@@ -325,7 +344,7 @@ def build_dependency_install_result(
).to_payload()
@staticmethod
- def build_command_result(completed: CompletedProcess[str]) -> CommandResultPayload:
+ def build_command_result(completed: CompletedProcess[str]) -> dict[str, object]:
"""
构建通用系统命令执行结果负载。
@@ -339,7 +358,7 @@ def build_command_result(completed: CompletedProcess[str]) -> CommandResultPaylo
).to_payload()
@staticmethod
- def build_purge_plan_item(item: PluginPurgePlanItem) -> PurgePlanItemPayload:
+ def build_purge_plan_item(item: PluginPurgePlanItem) -> dict[str, object]:
"""
构建插件物理清理计划项负载。
@@ -356,7 +375,7 @@ def build_purge_plan_item(item: PluginPurgePlanItem) -> PurgePlanItemPayload:
).to_payload()
@classmethod
- def build_purge_plan(cls, plan: PluginPurgePlan) -> PurgePlanPayload:
+ def build_purge_plan(cls, plan: PluginPurgePlan) -> dict[str, object]:
"""
构建插件物理清理计划负载。
@@ -379,7 +398,7 @@ def build_install_actions(
plugin_dependency_ok: bool,
structure_ok: bool,
menu_conflict_ok: bool,
- ) -> list[ActionPayload]:
+ ) -> list[dict[str, object]]:
"""
构建插件安装动作计划。
@@ -448,7 +467,7 @@ def build_upgrade_actions(
plugin_dependency_ok: bool,
structure_ok: bool,
menu_conflict_ok: bool,
- ) -> list[ActionPayload]:
+ ) -> list[dict[str, object]]:
"""
构建插件升级动作计划。
@@ -515,7 +534,7 @@ def build_upgrade_actions(
def build_upgrade_version_state(
discovered_plugin: DiscoveredPlugin,
database_plugin: object | None,
- ) -> VersionStatePayload:
+ ) -> dict[str, object]:
"""
构建插件升级版本状态。
@@ -548,10 +567,10 @@ def build_upgrade_dry_run_payload(
:return: 插件升级 dry-run 负载
"""
version_state = payload_context['versionState']
- dependency_result = cast('DependencyCheckResult', payload_context['dependencyResult'])
- plugin_dependency_result = cast('PluginDependencyCheckResult', payload_context['pluginDependencyResult'])
- structure_result = cast('PluginStructureCheckResult', payload_context['structureResult'])
- menu_conflict_result = cast('SupportsOk', payload_context['menuConflictResult'])
+ dependency_result = payload_context['dependencyResult']
+ plugin_dependency_result = payload_context['pluginDependencyResult']
+ structure_result = payload_context['structureResult']
+ menu_conflict_result = payload_context['menuConflictResult']
return UpgradeDryRunPayload.model_validate(
{
'ok': True,
@@ -574,15 +593,18 @@ def build_upgrade_dry_run_payload(
'pluginDependencyErrors': payload_context['pluginDependencyErrors'],
'structureErrors': payload_context['structureErrors'],
'menuConflicts': payload_context['menuConflicts'],
- 'dependencies': [cls.build_dependency_item(item) for item in dependency_result.items],
+ 'dependencies': [
+ PluginValidationPayloadMixin.build_dependency_item(item) for item in dependency_result.items
+ ],
'pluginDependencies': [
- cls.build_plugin_dependency_item(item) for item in plugin_dependency_result.items
+ PluginValidationPayloadMixin.build_plugin_dependency_item(item)
+ for item in plugin_dependency_result.items
],
}
).to_payload()
@staticmethod
- def build_enabled_actions(enabled: bool, plugin_dependency_ok: bool = True) -> list[ActionPayload]:
+ def build_enabled_actions(enabled: bool, plugin_dependency_ok: bool = True) -> list[dict[str, object]]:
"""
构建插件启停动作计划。
@@ -590,7 +612,7 @@ def build_enabled_actions(enabled: bool, plugin_dependency_ok: bool = True) -> l
:param plugin_dependency_ok: 插件间依赖检查是否通过
:return: 插件启停动作计划
"""
- actions = [
+ actions: list[dict[str, object]] = [
{
'name': 'update_plugin_enabled',
'label': '更新插件启停状态',
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/runtime.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/runtime.py
index a2230fdbd..9c0ad4844 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/runtime.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/runtime.py
@@ -1,77 +1,18 @@
-from collections.abc import Mapping
-from typing import Protocol, TypeAlias
+from collections.abc import Iterable, Mapping
+from typing import TypeAlias
from pydantic import Field
from i18n.message import I18nMessage
from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.lifecycle.purge import PluginPurgePlan
-from plugins.core.types import JSONObject
+from plugins.core.runtime.health import PluginHealthResult
from plugins.core.validation.plugin_deps import PluginBatchOperation
from utils.log_util import logger
from . import PluginPayloadBuilder
from .base import PluginPayloadModel
-from .catalog import PluginMenuDiagnosticPlanPayload
-from .plan import ActionPayload, VersionStatePayload
-
-
-class SupportsOk(Protocol):
- """
- 支持 ok 属性的检查结果协议。
-
- :ivar ok: 操作或检查是否成功
- """
-
- ok: bool
-
-
-class PluginRuntimePrecheckProtocol(Protocol):
- """
- runtime payload 所需的预检上下文协议。
-
- :ivar ok: 操作或检查是否成功
- :ivar dependency_result: 依赖检查结果
- :ivar manifest_result: manifest 非阻断检查结果
- :ivar plugin_dependency_result: 插件间依赖检查结果
- :ivar structure_result: 插件结构检查结果
- :ivar menu_conflict_result: 菜单冲突检查结果
- :ivar operation_payload: 描述当前操作的结构化数据
- :ivar check_payload: 插件检查负载
- """
-
- ok: bool
- dependency_result: SupportsOk
- manifest_result: SupportsOk
- plugin_dependency_result: SupportsOk
- structure_result: SupportsOk
- menu_conflict_result: SupportsOk
- operation_payload: Mapping[str, object]
- check_payload: Mapping[str, object]
-
-
-class PluginHealthResultProtocol(Protocol):
- """
- runtime 健康检查结果协议。
-
- :ivar plugin_id: 插件清单中的唯一标识
- :ivar ok: 操作或检查是否成功
- :ivar status: 操作或记录所处的状态
- :ivar message: 与当前结果一起返回的说明
- :ivar checker: 用于取得或验证健康状态的检查器
- :ivar duration_ms: 健康检查实际耗用的毫秒数
- :ivar details: 用于诊断健康状态的详情
- :ivar error: 异常对象
- """
-
- plugin_id: str
- ok: bool
- status: str
- message: str
- checker: str | None
- duration_ms: float
- details: JSONObject
- error: str | None
+from .validation import PluginRuntimePrecheckProtocol
class PluginRuntimeDiagnosePayload(PluginPayloadModel):
@@ -267,14 +208,15 @@ def build_exception_payload(
:return: 运行时异常负载
"""
logger.exception(f'{message}:{error}')
- return PluginRuntimeExceptionPayload(
+ fields = dict(
ok=False,
message=message,
error=str(error),
plugin_id=plugin_id,
failed_step=failed_step,
**(extra_payload or {}),
- ).to_payload(exclude_none=True)
+ )
+ return PluginRuntimeExceptionPayload.model_validate(fields).to_payload(exclude_none=True)
@staticmethod
def build_invalid_operation_payload(
@@ -300,7 +242,7 @@ def build_invalid_operation_payload(
@staticmethod
def build_health_response_payload(
- plugin_id: str, health_result: PluginHealthResultProtocol
+ plugin_id: str, health_result: PluginHealthResult
) -> PluginRuntimeHealthResponsePayloadDict:
"""
构建插件健康检查响应负载。
@@ -356,7 +298,7 @@ def build_diagnose_failure_payload(
).to_payload()
@staticmethod
- def build_empty_menu_plan() -> PluginMenuDiagnosticPlanPayload:
+ def build_empty_menu_plan() -> dict[str, object]:
"""
构建空插件菜单诊断计划。
@@ -370,7 +312,7 @@ def build_diagnose_payload(
*,
info_payload: Mapping[str, object],
check_payload: Mapping[str, object],
- menu_plan: PluginMenuDiagnosticPlanPayload,
+ menu_plan: Mapping[str, object],
config_payload: Mapping[str, object],
audit_payload: Mapping[str, object],
) -> PluginRuntimeDiagnosePayloadDict:
@@ -405,8 +347,8 @@ def build_precheck_payload(
operation: PluginBatchOperation,
*,
precheck: PluginRuntimePrecheckProtocol,
- version_state: VersionStatePayload,
- actions: list[ActionPayload],
+ version_state: dict[str, object],
+ actions: list[dict[str, object]],
database_error: str | None,
purge_plan: PluginPurgePlan | None = None,
purge_plan_error: str | None = None,
@@ -423,11 +365,15 @@ def build_precheck_payload(
:param purge_plan: 插件物理清理计划
:param purge_plan_error: 插件物理清理计划构建错误
:return: 插件操作预检负载
+ :raises TypeError: 清理计划出错时已有的警告不可迭代
"""
check_payload = dict(precheck.check_payload)
if purge_plan_error:
+ warnings = check_payload.get('warnings', [])
+ if not isinstance(warnings, Iterable):
+ raise TypeError('插件预检警告必须是可迭代对象')
check_payload['warnings'] = [
- *[str(warning) for warning in check_payload.get('warnings', [])],
+ *[str(warning) for warning in warnings],
f'插件物理清理计划构建失败:{purge_plan_error}',
]
payload: PluginRuntimePrecheckPayloadDict = {
@@ -454,7 +400,7 @@ def build_precheck_payload(
return result
@staticmethod
- def build_health_payload(health_result: PluginHealthResultProtocol) -> PluginRuntimeHealthPayloadDict:
+ def build_health_payload(health_result: PluginHealthResult) -> PluginRuntimeHealthPayloadDict:
"""
构建插件健康检查负载。
@@ -493,7 +439,7 @@ def build_precheck_actions(
operation: PluginBatchOperation,
discovered_plugin: DiscoveredPlugin,
precheck: PluginRuntimePrecheckProtocol,
- ) -> list[ActionPayload]:
+ ) -> list[dict[str, object]]:
"""
构建插件操作预检动作清单。
@@ -528,8 +474,8 @@ def build_precheck_actions(
@staticmethod
def build_upgrade_pre_execution_blocker(
plugin_id: str,
- version_state: VersionStatePayload,
- actions: list[ActionPayload],
+ version_state: dict[str, object],
+ actions: list[dict[str, object]],
precheck: PluginRuntimePrecheckProtocol,
) -> PluginRuntimeUpgradeBlockerPayloadDict | None:
"""
@@ -567,8 +513,8 @@ def _build_upgrade_blocker_payload(
*,
plugin_id: str,
message: str,
- version_state: VersionStatePayload,
- actions: list[ActionPayload],
+ version_state: dict[str, object],
+ actions: list[dict[str, object]],
precheck: PluginRuntimePrecheckProtocol,
) -> PluginRuntimeUpgradeBlockerPayloadDict:
"""
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/validation.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/validation.py
index 076a457ab..4b0c3f439 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/validation.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/payload/validation.py
@@ -206,14 +206,21 @@ def build_menu_conflict_item(item: PluginMenuConflictItem) -> MenuConflictItemPa
...
-class PluginCheckPrecheckProtocol(Protocol):
- """
- 插件检查单项所需的预检上下文协议。
+class SupportsOk(Protocol):
+ """提供检查结果的成功状态。"""
+
+ @property
+ def ok(self) -> bool:
+ """
+ 获取检查成功标记。
+
+ :return: 检查成功标记
+ """
+ ...
- :ivar ok: 操作或检查是否成功
- """
- ok: bool
+class PluginCheckPrecheckProtocol(SupportsOk, Protocol):
+ """插件检查单项所需的预检上下文。"""
@property
def check_payload(self) -> Mapping[str, object]:
@@ -225,6 +232,64 @@ def check_payload(self) -> Mapping[str, object]:
...
+class PluginRuntimePrecheckProtocol(PluginCheckPrecheckProtocol, Protocol):
+ """构建运行时响应时使用的预检结果。"""
+
+ @property
+ def dependency_result(self) -> SupportsOk:
+ """
+ 获取软件包依赖检查结果。
+
+ :return: 软件包依赖检查结果
+ """
+ ...
+
+ @property
+ def manifest_result(self) -> SupportsOk:
+ """
+ 获取插件清单检查结果。
+
+ :return: 插件清单检查结果
+ """
+ ...
+
+ @property
+ def plugin_dependency_result(self) -> SupportsOk:
+ """
+ 获取插件间依赖检查结果。
+
+ :return: 插件间依赖检查结果
+ """
+ ...
+
+ @property
+ def structure_result(self) -> SupportsOk:
+ """
+ 获取插件结构检查结果。
+
+ :return: 插件结构检查结果
+ """
+ ...
+
+ @property
+ def menu_conflict_result(self) -> SupportsOk:
+ """
+ 获取菜单冲突检查结果。
+
+ :return: 菜单冲突检查结果
+ """
+ ...
+
+ @property
+ def operation_payload(self) -> Mapping[str, object]:
+ """
+ 获取当前操作的预检数据。
+
+ :return: 当前操作的预检数据
+ """
+ ...
+
+
class PluginValidationPayloadMixin:
"""插件依赖、结构、manifest 和菜单冲突检查结果负载构建能力。"""
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/support/precheck.py b/ruoyi-fastapi-backend/plugins/core/runtime/support/precheck.py
index 239083640..d5689a21c 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/support/precheck.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/support/precheck.py
@@ -3,13 +3,6 @@
from pydantic import Field
-from plugins.core.runtime.support.payload.validation import (
- DependencyItemPayload,
- MenuConflictItemPayload,
- PluginDependencyItemPayload,
- StructureItemPayload,
- ValidationIssuePayload,
-)
from plugins.core.validation.dependencies import DependencyCheckResult
from plugins.core.validation.manifest import PluginManifestCheckResult
from plugins.core.validation.menus import PluginMenuConflictResult
@@ -19,25 +12,8 @@
from .payload import PluginPayloadBuilder
from .payload.base import PluginPayloadModel
-PrecheckOperationPayloadDict: TypeAlias = dict[
- str,
- bool
- | list[DependencyItemPayload]
- | list[PluginDependencyItemPayload]
- | list[ValidationIssuePayload]
- | list[StructureItemPayload]
- | list[MenuConflictItemPayload],
-]
-PrecheckCheckPayloadDict: TypeAlias = dict[
- str,
- bool
- | list[str]
- | list[DependencyItemPayload]
- | list[PluginDependencyItemPayload]
- | list[ValidationIssuePayload]
- | list[StructureItemPayload]
- | list[MenuConflictItemPayload],
-]
+PrecheckOperationPayloadDict: TypeAlias = dict[str, object]
+PrecheckCheckPayloadDict: TypeAlias = dict[str, object]
class PluginPrecheckOperationPayload(PluginPayloadModel):
@@ -96,11 +72,11 @@ class PluginPrecheckContext:
:ivar unsatisfied_dependencies: 版本不满足依赖名称列表
"""
- dependency_result: object
- manifest_result: object
- plugin_dependency_result: object
- structure_result: object
- menu_conflict_result: object
+ dependency_result: DependencyCheckResult
+ manifest_result: PluginManifestCheckResult
+ plugin_dependency_result: PluginDependencyCheckResult
+ structure_result: PluginStructureCheckResult
+ menu_conflict_result: PluginMenuConflictResult
manifest_issues: list[dict[str, object]]
manifest_warnings: list[dict[str, object]]
plugin_dependency_errors: list[dict[str, object]]
diff --git a/ruoyi-fastapi-backend/plugins/core/sdk/context.py b/ruoyi-fastapi-backend/plugins/core/sdk/context.py
index 5fa372530..a05628abc 100644
--- a/ruoyi-fastapi-backend/plugins/core/sdk/context.py
+++ b/ruoyi-fastapi-backend/plugins/core/sdk/context.py
@@ -1,5 +1,5 @@
import asyncio
-from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
+from collections.abc import AsyncGenerator, Awaitable, Callable, Mapping
from contextlib import asynccontextmanager
from dataclasses import dataclass, field, replace
from pathlib import Path
@@ -109,6 +109,18 @@ class PluginRequestContext:
request: PluginHttpRequest | None = None
_transaction: '_PluginTransactionState | None' = field(default=None, repr=False, compare=False)
+ @property
+ def http_request(self) -> PluginHttpRequest:
+ """
+ 获取当前 HTTP 接口的请求快照。
+
+ :return: 宿主已解析的 HTTP 请求
+ :raises RuntimeError: 当前上下文不属于 HTTP 接口
+ """
+ if self.request is None:
+ raise RuntimeError('当前插件上下文缺少 HTTP 请求快照')
+ return self.request
+
def require_permission(self, permission: str) -> None:
"""
执行接口权限检查;数据权限由具体服务按当前用户处理。
@@ -120,7 +132,7 @@ def require_permission(self, permission: str) -> None:
raise PermissionError(f'缺少权限:{permission}')
@asynccontextmanager
- async def transaction(self) -> AsyncIterator['PluginRequestContext']:
+ async def transaction(self) -> AsyncGenerator['PluginRequestContext', None]:
"""
为当前任务创建显式事务,成功提交、异常或取消回滚,并关闭独占会话。
diff --git a/ruoyi-fastapi-backend/plugins/core/state.py b/ruoyi-fastapi-backend/plugins/core/state.py
index b6b186979..7f5ab6a60 100644
--- a/ruoyi-fastapi-backend/plugins/core/state.py
+++ b/ruoyi-fastapi-backend/plugins/core/state.py
@@ -88,7 +88,7 @@ def is_enabled(database_plugin: object | None) -> bool:
return False
database_enabled = getattr(database_plugin, 'enabled', None) if database_plugin else None
if database_enabled is not None:
- return database_enabled == '0'
+ return bool(database_enabled == '0')
return False
@staticmethod
diff --git a/ruoyi-fastapi-backend/plugins/core/types.py b/ruoyi-fastapi-backend/plugins/core/types.py
index 806bd03dd..fbe932a2c 100644
--- a/ruoyi-fastapi-backend/plugins/core/types.py
+++ b/ruoyi-fastapi-backend/plugins/core/types.py
@@ -35,24 +35,76 @@ def to_payload(self) -> dict[str, object]:
class PluginStateRecord(Protocol):
- """
- 插件数据库状态记录协议。
-
- :ivar plugin_id: 插件清单中的唯一标识
- :ivar installed_version: 已安装版本
- :ivar enabled: 是否启用该项功能
- :ivar status: 操作或记录所处的状态
- :ivar last_error: 最近一次错误信息
- :ivar source: 待检查的源文本或输入来源
- :ivar backend_path: 后端插件相对路径
- :ivar frontend_path: 前端插件相对路径
- """
-
- plugin_id: str
- installed_version: str | None
- enabled: str | None
- status: str | None
- last_error: str | None
- source: str | None
- backend_path: str | None
- frontend_path: str | None
+ """运行时查询使用的插件持久化状态。"""
+
+ @property
+ def plugin_id(self) -> str:
+ """
+ 获取插件标识。
+
+ :return: 插件标识
+ """
+ ...
+
+ @property
+ def installed_version(self) -> str | None:
+ """
+ 获取已安装版本。
+
+ :return: 已安装版本
+ """
+ ...
+
+ @property
+ def enabled(self) -> str | None:
+ """
+ 获取启停状态。
+
+ :return: 启停状态
+ """
+ ...
+
+ @property
+ def status(self) -> str | None:
+ """
+ 获取生命周期状态。
+
+ :return: 生命周期状态
+ """
+ ...
+
+ @property
+ def last_error(self) -> str | None:
+ """
+ 获取最近一次错误信息。
+
+ :return: 最近一次错误信息
+ """
+ ...
+
+ @property
+ def source(self) -> str | None:
+ """
+ 获取插件来源。
+
+ :return: 插件来源
+ """
+ ...
+
+ @property
+ def backend_path(self) -> str | None:
+ """
+ 获取后端插件相对路径。
+
+ :return: 后端插件相对路径
+ """
+ ...
+
+ @property
+ def frontend_path(self) -> str | None:
+ """
+ 获取前端插件相对路径。
+
+ :return: 前端插件相对路径
+ """
+ ...
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/dependencies.py b/ruoyi-fastapi-backend/plugins/core/validation/dependencies.py
index 625daedf6..d2791992f 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/dependencies.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/dependencies.py
@@ -7,10 +7,11 @@
from typing import Literal
from packaging.requirements import InvalidRequirement
+from pydantic import TypeAdapter
from i18n.message import I18nMessage
from plugins.core.environment import PLUGIN_RUNTIME_ENVIRONMENT, PluginRuntimeEnvironmentService
-from plugins.core.manifest.schema import PluginManifest
+from plugins.core.manifest.v2 import VersionedPluginManifest
from plugins.core.validation.python_requirements import PythonRequirementParser
from plugins.core.validation.versioning import PluginVersionComparator, PluginVersionConstraintMatcher
@@ -528,7 +529,7 @@ def _load_installed_packages(self) -> dict[str, str]:
dependencies = package_json.get('dependencies', {})
dev_dependencies = package_json.get('devDependencies', {})
- return {**dependencies, **dev_dependencies}
+ return TypeAdapter(dict[str, str]).validate_python({**dependencies, **dev_dependencies}, strict=True)
@staticmethod
def _normalize_npm_version(version: str | None) -> str | None:
@@ -597,7 +598,7 @@ def __init__(
)
self.frontend_mode = frontend_mode
- def check_manifest(self, manifest: PluginManifest) -> DependencyCheckResult:
+ def check_manifest(self, manifest: VersionedPluginManifest) -> DependencyCheckResult:
"""
检查插件清单依赖。
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/manifest.py b/ruoyi-fastapi-backend/plugins/core/validation/manifest.py
index 496243da0..9cc668b92 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/manifest.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/manifest.py
@@ -10,7 +10,7 @@
from i18n.message import I18nMessage
from plugins.core.environment import PluginRuntimeEnvironmentService
from plugins.core.manifest.menu_tree import PluginMenuTree
-from plugins.core.manifest.schema import PluginManifest
+from plugins.core.manifest.v2 import PluginManifestV2, VersionedPluginManifest
from plugins.core.sdk.version import HOST_API_VERSION
from plugins.core.validation.dependencies import DependencyRequirementParser
from plugins.core.validation.python_requirements import PythonRequirementParser
@@ -99,7 +99,7 @@ def __init__(
self.python_version = python_version or platform.python_version()
self.node_version = node_version
- def check(self, manifest: PluginManifest) -> PluginManifestCheckResult:
+ def check(self, manifest: VersionedPluginManifest) -> PluginManifestCheckResult:
"""
检查插件 manifest 提示类问题。
@@ -125,7 +125,7 @@ def check(self, manifest: PluginManifest) -> PluginManifestCheckResult:
return PluginManifestCheckResult(plugin_id=manifest.id, issues=issues)
- def _check_secret_config_defaults(self, manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_secret_config_defaults(self, manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查敏感配置默认值声明。
@@ -157,7 +157,7 @@ def _check_secret_config_defaults(self, manifest: PluginManifest) -> list[Plugin
return issues
@staticmethod
- def _check_secret_config_type_alignment(manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_secret_config_type_alignment(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查敏感配置类型和 secret 标记是否一致。
@@ -207,7 +207,8 @@ def _check_secret_config_type_alignment(manifest: PluginManifest) -> list[Plugin
return issues
- def _check_unpinned_dependencies(self, manifest: PluginManifest) -> list[PluginValidationIssue]:
+ @staticmethod
+ def _check_unpinned_dependencies(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查未声明版本约束的依赖。
@@ -278,7 +279,7 @@ def _check_unpinned_dependencies(self, manifest: PluginManifest) -> list[PluginV
return issues
@staticmethod
- def _check_resources_without_purge_hook(manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_resources_without_purge_hook(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查资源声明是否缺少物理清理钩子。
@@ -309,7 +310,7 @@ def _check_resources_without_purge_hook(manifest: PluginManifest) -> list[Plugin
]
@staticmethod
- def _check_required_config_without_default(manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_required_config_without_default(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查必填配置是否缺少默认值。
@@ -342,7 +343,7 @@ def _check_required_config_without_default(manifest: PluginManifest) -> list[Plu
return issues
@staticmethod
- def _check_ineffective_config_constraints(manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_ineffective_config_constraints(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查配置项声明了当前类型不会生效的增强约束。
@@ -414,7 +415,7 @@ def _check_ineffective_config_constraints(manifest: PluginManifest) -> list[Plug
return issues
@staticmethod
- def _check_permissions_without_plugin_prefix(manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_permissions_without_plugin_prefix(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查权限标识是否使用插件 ID 前缀。
@@ -448,7 +449,7 @@ def _check_permissions_without_plugin_prefix(manifest: PluginManifest) -> list[P
]
@staticmethod
- def _check_frontend_menus_without_permissions(manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_frontend_menus_without_permissions(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查前端菜单是否完全缺少权限声明。
@@ -480,7 +481,7 @@ def _check_frontend_menus_without_permissions(manifest: PluginManifest) -> list[
]
@staticmethod
- def _check_button_menus_without_permission(manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_button_menus_without_permission(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查按钮菜单是否声明权限标识。
@@ -513,7 +514,7 @@ def _check_button_menus_without_permission(manifest: PluginManifest) -> list[Plu
return issues
@staticmethod
- def _check_button_menu_structure(manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_button_menu_structure(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查按钮菜单结构是否混入路由菜单语义。
@@ -566,7 +567,7 @@ def _check_button_menu_structure(manifest: PluginManifest) -> list[PluginValidat
return issues
@staticmethod
- def _check_permission_button_parent(manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_permission_button_parent(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查自动权限按钮是否存在可挂载的页面或目录菜单。
@@ -602,7 +603,7 @@ def _check_permission_button_parent(manifest: PluginManifest) -> list[PluginVali
]
@staticmethod
- def _check_lifecycle_script_order(manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_lifecycle_script_order(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查 migration 和 seed 声明顺序是否稳定。
@@ -639,7 +640,7 @@ def _check_lifecycle_script_order(manifest: PluginManifest) -> list[PluginValida
return issues
@staticmethod
- def _check_enabled_jobs_without_health_checker(manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_enabled_jobs_without_health_checker(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查默认启用任务是否缺少健康检查声明。
@@ -669,7 +670,7 @@ def _check_enabled_jobs_without_health_checker(manifest: PluginManifest) -> list
]
@staticmethod
- def _check_unpaired_runtime_hooks(manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_unpaired_runtime_hooks(manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查启动和关闭钩子是否成对声明。
@@ -701,7 +702,7 @@ def _check_unpaired_runtime_hooks(manifest: PluginManifest) -> list[PluginValida
)
]
- def _check_compatibility(self, manifest: PluginManifest) -> list[PluginValidationIssue]:
+ def _check_compatibility(self, manifest: VersionedPluginManifest) -> list[PluginValidationIssue]:
"""
检查插件平台兼容性声明。
@@ -715,7 +716,7 @@ def _check_compatibility(self, manifest: PluginManifest) -> list[PluginValidatio
('pythonVersion', compatibility.python_version, lambda: self.python_version, 'python'),
('nodeVersion', compatibility.node_version, self._resolve_node_version, 'node'),
]
- if manifest.uses_entrypoint:
+ if isinstance(manifest, PluginManifestV2):
checks.append(
('hostApiVersion', manifest.compatibility.host_api_version, lambda: HOST_API_VERSION, 'hostApi')
)
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/plugin_deps.py b/ruoyi-fastapi-backend/plugins/core/validation/plugin_deps.py
index 54830b77f..55042d0bd 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/plugin_deps.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/plugin_deps.py
@@ -3,7 +3,8 @@
from i18n.message import I18nMessage
from plugins.core.discovery.scanner import DiscoveredPlugin
-from plugins.core.manifest.schema import PluginDependencyManifest, PluginManifest
+from plugins.core.manifest.schema import PluginDependencyManifest
+from plugins.core.manifest.v2 import VersionedPluginManifest
from plugins.core.state import PluginStateResolver
from plugins.core.types import PluginStateRecord
from plugins.core.validation.dependencies import DependencyRequirementParser, ParsedDependency
@@ -242,7 +243,7 @@ def __init__(
self.discovered_plugin_map = {plugin.manifest.id: plugin for plugin in discovered_plugins}
self.database_plugin_map = {plugin.plugin_id: plugin for plugin in database_plugins or []}
- def check_manifest(self, manifest: PluginManifest) -> PluginDependencyCheckResult:
+ def check_manifest(self, manifest: VersionedPluginManifest) -> PluginDependencyCheckResult:
"""
检查单个插件清单的插件间依赖。
@@ -379,7 +380,7 @@ def _resolve_installed_version(
:param database_plugin: 数据库插件状态
:return: 已安装版本
"""
- installed_version = getattr(database_plugin, 'installed_version', None)
+ installed_version = database_plugin.installed_version if database_plugin else None
if installed_version:
return installed_version
return discovered_plugin.manifest.version if discovered_plugin else None
@@ -702,7 +703,7 @@ def _build_plan_item(
def _build_dependency_blockers(
self,
- manifest: PluginManifest,
+ manifest: VersionedPluginManifest,
operation: PluginBatchOperation,
) -> list[PluginDependencyPlanBlocker]:
"""
@@ -720,7 +721,7 @@ def _build_dependency_blockers(
def _build_single_dependency_blocker(
self,
- manifest: PluginManifest,
+ manifest: VersionedPluginManifest,
dependency: PluginDependencyManifest,
operation: PluginBatchOperation,
) -> list[PluginDependencyPlanBlocker]:
diff --git a/ruoyi-fastapi-backend/plugins/core/validation/structure.py b/ruoyi-fastapi-backend/plugins/core/validation/structure.py
index 2eaf7d815..d590c4ad2 100644
--- a/ruoyi-fastapi-backend/plugins/core/validation/structure.py
+++ b/ruoyi-fastapi-backend/plugins/core/validation/structure.py
@@ -7,7 +7,8 @@
from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.environment import PluginRuntimeEnvironmentService
from plugins.core.manifest.menu_tree import PluginMenuTree
-from plugins.core.manifest.schema import PluginJobManifest, PluginManifest, PluginMenuManifest
+from plugins.core.manifest.schema import PluginMenuManifest
+from plugins.core.manifest.v2 import FrontendManifestV2, VersionedPluginJobManifest, VersionedPluginManifest
from plugins.core.validation.result import PluginValidationIssue, PluginValidationLevelResolver, ValidationLevel
from utils.cron_util import CronUtil
@@ -201,15 +202,16 @@ def _check_explicit_plugin(
for callback in callbacks:
loader.locate_module(callback.split(':', 1)[0])
except (ImportError, ValueError, OSError) as exc:
- items.append(PluginStructureCheckItem('entrypoint', plugin.manifest.backend.entrypoint, False, str(exc)))
+ items.append(PluginStructureCheckItem('entrypoint', loader.backend.entrypoint, False, str(exc)))
items.extend(self._check_migration_files(plugin))
items.extend(self._check_seed_files(plugin))
for job in plugin.manifest.backend.jobs:
items.append(self._check_job_name_length(plugin.manifest.id, job))
items.append(self._check_job_callable_boundary(plugin.manifest.backend.module, job))
items.append(self._check_job_cron_expression(job))
- if plugin.manifest.frontend.delivery.type == 'bundle':
- bundle = plugin.manifest.frontend.bundle
+ frontend = plugin.manifest.frontend
+ if isinstance(frontend, FrontendManifestV2) and frontend.bundle is not None:
+ bundle = frontend.bundle
items.append(
self._check_plugin_relative_file(
'frontend_bundle', plugin.backend_path, f'{bundle.directory}/{bundle.entry}'
@@ -462,7 +464,7 @@ def _check_jobs(self, discovered_plugin: DiscoveredPlugin) -> list[PluginStructu
return items
@staticmethod
- def _check_job_name_length(plugin_id: str, job: PluginJobManifest) -> PluginStructureCheckItem:
+ def _check_job_name_length(plugin_id: str, job: VersionedPluginJobManifest) -> PluginStructureCheckItem:
"""
检查插件任务映射到系统任务表后的名称长度。
@@ -482,7 +484,7 @@ def _check_job_name_length(plugin_id: str, job: PluginJobManifest) -> PluginStru
@staticmethod
def _check_job_callable_boundary(
backend_module: str,
- job: PluginJobManifest,
+ job: VersionedPluginJobManifest,
) -> PluginStructureCheckItem:
"""
检查任务 callable 是否位于当前插件后端模块内。
@@ -499,7 +501,7 @@ def _check_job_callable_boundary(
message=f'任务 callable 位于插件模块内:{job.callable}' if ok else f'任务 callable 越界:{job.callable}',
)
- def _check_job_callable_importable(self, job: PluginJobManifest) -> PluginStructureCheckItem:
+ def _check_job_callable_importable(self, job: VersionedPluginJobManifest) -> PluginStructureCheckItem:
"""
检查任务 callable 是否可通过源码静态解析。
@@ -598,7 +600,7 @@ def _module_file_declares_async_callable(module_file: Path, callable_name: str)
return any(isinstance(node, ast.AsyncFunctionDef) and node.name == callable_name for node in module_ast.body)
@staticmethod
- def _check_job_cron_expression(job: PluginJobManifest) -> PluginStructureCheckItem:
+ def _check_job_cron_expression(job: VersionedPluginJobManifest) -> PluginStructureCheckItem:
"""
检查任务 cron 表达式。
@@ -752,7 +754,7 @@ def _check_frontend(self, discovered_plugin: DiscoveredPlugin) -> list[PluginStr
def _check_plugin_view(
self,
frontend_plugin_root: Path,
- manifest: PluginManifest,
+ manifest: VersionedPluginManifest,
menu: PluginMenuManifest,
frontend_framework: str = 'vue3',
) -> PluginStructureCheckItem:
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/__init__.py b/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/__init__.py
index c43942889..4e8e8bdaa 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/__init__.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/__init__.py
@@ -15,7 +15,7 @@ class EchoBody(BaseModel):
async def echo(context: PluginRequestContext) -> dict[str, Any]:
- return {**context.request.to_payload(), 'requestId': context.request_id}
+ return {**context.http_request.to_payload(), 'requestId': context.request_id}
def create_plugin(host: PluginHostContext) -> PluginDefinition:
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/__init__.py b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/__init__.py
index 19334640a..7504f350d 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/__init__.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/__init__.py
@@ -1,5 +1,5 @@
from types import SimpleNamespace
-from typing import Any
+from typing import Any, TypeVar
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, ValidationError
@@ -16,7 +16,10 @@
_runtime = SimpleNamespace(session_factory=None)
-def _validate(model: type[BaseModel], values: dict[str, Any]) -> Any:
+_Model = TypeVar('_Model', bound=BaseModel)
+
+
+def _validate(model: type[_Model], values: dict[str, Any]) -> _Model:
"""
校验 SDK 请求快照中的路径和查询参数。
@@ -41,7 +44,7 @@ def _task_id(context: PluginRequestContext) -> str:
:param context: 含 HTTP 请求快照的宿主上下文
:return: 已校验的任务标识
"""
- return _validate(TaskIdentifier, {'id': context.request.path_params['task_id']}).id
+ return _validate(TaskIdentifier, {'id': context.http_request.path_params['task_id']}).id
async def info(context: PluginRequestContext) -> dict[str, Any]:
@@ -49,9 +52,9 @@ async def info(context: PluginRequestContext) -> dict[str, Any]:
async def list_tasks(context: PluginRequestContext) -> dict[str, Any]:
- if any(len(values) != 1 for values in context.request.query.values()):
+ if any(len(values) != 1 for values in context.http_request.query.values()):
raise HTTPException(status_code=422, detail='查询参数不能重复')
- query = _validate(TaskQuery, {key: values[0] for key, values in context.request.query.items()})
+ query = _validate(TaskQuery, {key: values[0] for key, values in context.http_request.query.items()})
return await service.list_tasks(context, query)
@@ -60,11 +63,11 @@ async def get_task(context: PluginRequestContext) -> dict[str, Any]:
async def create_task(context: PluginRequestContext) -> dict[str, Any]:
- return await service.create_task(context, context.request.body)
+ return await service.create_task(context, context.http_request.body)
async def update_task(context: PluginRequestContext) -> dict[str, Any]:
- return await service.update_task(context, _task_id(context), context.request.body)
+ return await service.update_task(context, _task_id(context), context.http_request.body)
async def delete_task(context: PluginRequestContext) -> dict[str, bool]:
diff --git a/ruoyi-fastapi-backend/requirements-pg.txt b/ruoyi-fastapi-backend/requirements-pg.txt
index 02cf298b6..447ad4138 100644
--- a/ruoyi-fastapi-backend/requirements-pg.txt
+++ b/ruoyi-fastapi-backend/requirements-pg.txt
@@ -24,6 +24,7 @@ Sphinx==9.0.4
SQLAlchemy[asyncio]==2.1.9
sqlglot==30.33.0
textual==8.2.8
+ty==0.0.108
tzdata==2026.6
user-agents==2.2.0
.
diff --git a/ruoyi-fastapi-backend/requirements.txt b/ruoyi-fastapi-backend/requirements.txt
index 5c86e9130..3f0201ce6 100644
--- a/ruoyi-fastapi-backend/requirements.txt
+++ b/ruoyi-fastapi-backend/requirements.txt
@@ -24,6 +24,7 @@ Sphinx==9.0.4
SQLAlchemy[asyncio]==2.1.9
sqlglot==30.33.0
textual==8.2.8
+ty==0.0.108
tzdata==2026.6
user-agents==2.2.0
.
diff --git a/ruoyi-fastapi-backend/scripts/build_native_plugin.py b/ruoyi-fastapi-backend/scripts/build_native_plugin.py
index 662bdfe32..994972cff 100644
--- a/ruoyi-fastapi-backend/scripts/build_native_plugin.py
+++ b/ruoyi-fastapi-backend/scripts/build_native_plugin.py
@@ -5,13 +5,16 @@
import subprocess
import sys
from pathlib import Path
-from typing import Any
+from typing import TYPE_CHECKING
from zipfile import ZIP_DEFLATED, ZipFile
+if TYPE_CHECKING:
+ from plugins.core.manifest.v2 import PluginManifestV2
+
BACKEND_ROOT = Path(__file__).resolve().parents[1]
-def _resource_roots(source: Path, manifest: Any, output: Path) -> list[Path]:
+def _resource_roots(source: Path, manifest: 'PluginManifestV2', output: Path) -> list[Path]:
"""
检查清单声明的资源根路径及前端入口,在构建前拒绝缺失产物。
@@ -28,8 +31,8 @@ def _resource_roots(source: Path, manifest: Any, output: Path) -> list[Path]:
resources.update(str(item) for item in manifest.backend.seeds)
if (source / 'plugin.lock.yaml').exists():
resources.add('plugin.lock.yaml')
- if manifest.frontend.delivery.type == 'bundle':
- bundle = manifest.frontend.bundle
+ bundle = manifest.frontend.bundle
+ if bundle is not None:
resources.add(bundle.directory)
if not (source / bundle.directory / bundle.entry).is_file():
raise ValueError('缺少 bundle HTML 入口,请先独立构建前端后再组装制品')
@@ -50,7 +53,7 @@ def _resource_roots(source: Path, manifest: Any, output: Path) -> list[Path]:
return roots
-def collect_deployment_resources(source: Path, manifest: Any, output: Path) -> dict[str, Path]:
+def collect_deployment_resources(source: Path, manifest: 'PluginManifestV2', output: Path) -> dict[str, Path]:
"""
收集清单资源和已构建 bundle,拒绝开发工程、敏感文件及链接。
@@ -58,7 +61,7 @@ def collect_deployment_resources(source: Path, manifest: Any, output: Path) -> d
:param manifest: 已解析的插件清单
:param output: 待创建的构建输出目录
:return: 插件内相对路径与对应源码文件的映射
- :raises ValueError: 交付资源超过制品文件数量或大小限制
+ :raises ValueError: 清单缺少原生发行包声明,或交付资源超过制品文件数量、大小限制
"""
from plugins.core.artifacts.package import ( # noqa: PLC0415
CACHE_DIRECTORIES,
@@ -75,6 +78,8 @@ def collect_deployment_resources(source: Path, manifest: Any, output: Path) -> d
files: dict[str, Path] = {}
total_bytes = 0
+ if manifest.backend.native is None:
+ raise ValueError('清单缺少原生发行包声明')
native_root = Path(manifest.backend.native.module_root)
for resource in _resource_roots(source, manifest, output):
pending = [resource]
@@ -137,7 +142,7 @@ def main() -> None:
from plugins.core.validation.structure import PluginStructureChecker # noqa: PLC0415
manifest = PluginScanner(source.parent).load_manifest(source / 'plugin.yaml').manifest
- if manifest.runtime_kind != 'native':
+ if manifest.manifest_version == 1 or manifest.backend.native is None:
parser.error('清单必须声明 native 运行时')
if manifest.frontend.delivery.type not in {'none', 'bundle'}:
parser.error('原生交付只支持 none 或已独立构建的 bundle 前端')
diff --git a/ruoyi-fastapi-backend/scripts/check_docstrings.py b/ruoyi-fastapi-backend/scripts/check_docstrings.py
index 067915ef5..0790d1ca5 100644
--- a/ruoyi-fastapi-backend/scripts/check_docstrings.py
+++ b/ruoyi-fastapi-backend/scripts/check_docstrings.py
@@ -4,7 +4,7 @@
import subprocess
import sys
import tokenize
-from collections.abc import Iterator
+from collections.abc import Generator, Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from functools import cache
@@ -281,10 +281,11 @@ def resolve_binding(expr: ast.expr | None, bindings: Bindings) -> ast.expr | str
:return: 导入的完整名称、绑定的表达式或空值
"""
seen = set()
- while isinstance(expr, ast.Name) and expr.id in bindings and expr.id not in seen:
- seen.add(expr.id)
- expr = bindings[expr.id]
- return expr
+ resolved: ast.expr | str | None = expr
+ while isinstance(resolved, ast.Name) and resolved.id in bindings and resolved.id not in seen:
+ seen.add(resolved.id)
+ resolved = bindings[resolved.id]
+ return resolved
def imported_name(expr: ast.expr | None, bindings: Bindings) -> str:
@@ -588,23 +589,24 @@ def registered_callback(call: ast.Call) -> ast.expr | None:
return callback
-def router_method(call: ast.expr, methods: set[str], routers: set[str]) -> bool:
+def router_method(call: ast.Call, routers: set[str]) -> str | None:
"""
- 判断调用是否来自路由对象或应用自带的路由器。
+ 识别路由对象或应用自带路由器上的方法名。
:param call: 待识别的装饰器或注册调用
- :param methods: 需要匹配的路由方法名
:param routers: 当前作用域的路由对象名称
- :return: 调用是否来自路由对象或应用自带的路由器
+ :return: 路由方法名,未匹配时返回空值
"""
- if not isinstance(call, ast.Call) or not isinstance(call.func, ast.Attribute) or call.func.attr not in methods:
- return False
+ if not isinstance(call.func, ast.Attribute):
+ return None
receiver = call.func.value
if ast.unparse(receiver) in routers:
- return True
+ return call.func.attr
if isinstance(receiver, ast.Attribute) and receiver.attr in {'router', 'webhooks'}:
receiver = receiver.value
- return ast.unparse(receiver) in routers or (isinstance(receiver, ast.Attribute) and receiver.attr == 'app')
+ if ast.unparse(receiver) in routers or (isinstance(receiver, ast.Attribute) and receiver.attr == 'app'):
+ return call.func.attr
+ return None
def inspect_routes(tree: ast.Module) -> tuple[set[ast.AST], list[tuple[int, str]]]:
@@ -704,19 +706,19 @@ def check_registration(call: ast.Call) -> None:
:param call: 当前语句中的调用
"""
- if router_method(call.func, ROUTE_METHODS, routers) and call.args:
+ if isinstance(call.func, ast.Call) and router_method(call.func, routers) in ROUTE_METHODS and call.args:
operation, callback = call.func, call.args[0]
elif (
(isinstance(call.func, ast.Attribute) and call.func.attr == 'add_api_route')
or ast.unparse(call.func) in api_route_types
- or router_method(call, ROUTE_REGISTRATIONS, routers)
+ or router_method(call, routers) in ROUTE_REGISTRATIONS
):
operation, callback = call, registered_callback(call)
else:
return
- if ast.unparse(operation.func) in api_route_types or operation.func.attr in HTTP_OPERATIONS | {
- 'add_api_route'
- }:
+ if ast.unparse(operation.func) in api_route_types or (
+ isinstance(operation.func, ast.Attribute) and operation.func.attr in HTTP_OPERATIONS | {'add_api_route'}
+ ):
errors.extend(route_doc_errors(operation, bindings))
if isinstance(callback, ast.Name) and callback.id in functions:
routes.add(functions[callback.id])
@@ -730,9 +732,12 @@ def check_registration(call: ast.Call) -> None:
bindings.update((target.id, node.value) for target in targets if isinstance(target, ast.Name))
elif isinstance(node, DEFINITIONS):
for decorator in node.decorator_list:
- if router_method(decorator, ROUTE_METHODS, routers):
+ if (
+ isinstance(decorator, ast.Call)
+ and (method := router_method(decorator, routers)) in ROUTE_METHODS
+ ):
routes.add(node)
- if decorator.func.attr in HTTP_OPERATIONS:
+ if method in HTTP_OPERATIONS:
errors.extend(route_doc_errors(decorator, bindings))
visit(node, functions, routers, bindings)
@@ -788,7 +793,7 @@ def test_functions(tree: ast.Module, path: Path) -> set[ast.AST]:
@contextmanager
-def sphinx_settings() -> Iterator[frontend.Values]:
+def sphinx_settings() -> Generator[frontend.Values, None, None]:
"""
初始化一次 Sphinx 内置域和指令,供同一次扫描的文档共用。
@@ -799,7 +804,7 @@ def sphinx_settings() -> Iterator[frontend.Values]:
app = Sphinx(
root, None, root / 'out', root / 'trees', 'dummy', status=None, warning=None, exception_on_warning=True
)
- settings = frontend.get_default_settings(Parser)
+ settings = frontend.get_default_settings(Parser())
settings.env = app.env
settings.file_insertion_enabled = settings.raw_enabled = False
settings.warning_stream = False # 解析器诊断由 reporter 收集并统一输出源文件行号。
@@ -820,7 +825,7 @@ class Parameters:
accepts_keywords: bool
-def parameters_for(owner: ast.AST, methods: set[ast.AST]) -> Parameters | None:
+def parameters_for(owner: ast.AST, methods: set[ast.stmt]) -> Parameters | None:
"""
取函数或显式构造函数的签名,省略实例和类方法的隐式首参。
@@ -828,15 +833,16 @@ def parameters_for(owner: ast.AST, methods: set[ast.AST]) -> Parameters | None:
:param methods: 类体中声明的方法集合
:return: ``Parameters`` 实例
"""
- if isinstance(owner, ast.ClassDef):
- owner = next(
- (item for item in owner.body if isinstance(item, ast.FunctionDef) and item.name == '__init__'), None
- )
- if not isinstance(owner, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ function = (
+ next((item for item in owner.body if isinstance(item, ast.FunctionDef) and item.name == '__init__'), None)
+ if isinstance(owner, ast.ClassDef)
+ else owner
+ )
+ if not isinstance(function, (ast.FunctionDef, ast.AsyncFunctionDef)):
return None
- args = owner.args
+ args = function.args
positional = [*args.posonlyargs, *args.args]
- if owner in methods and bound_receiver(owner):
+ if function in methods and bound_receiver(function):
positional = positional[1:]
names = {arg.arg for arg in (*positional, *args.kwonlyargs)}
for prefix, arg in (('*', args.vararg), ('**', args.kwarg)):
@@ -902,7 +908,7 @@ def parameter_error(field: nodes.field, name: str, param: str, parameters: Param
if parameters.accepts_keywords and identifier == param:
if name in KEYWORD_FIELDS:
return ''
- if FIELD_KINDS[name] == 'parametertype':
+ if FIELD_KINDS[name] == 'parametertype' and field.parent is not None:
for sibling in field.parent.findall(nodes.field):
words = sibling[0].astext().split()
if words[0] in KEYWORD_FIELDS and words[-1] == param:
@@ -942,7 +948,7 @@ def comment_language(source: str, tree: ast.Module, path: Path) -> Iterator[tupl
if path.resolve() == ALEMBIC_ENV:
return
router = preserved_router(tree, path)
- preserved = range(router.lineno, router.end_lineno + 1) if router else ()
+ preserved = range(router.lineno, (router.end_lineno or router.lineno) + 1) if router else ()
for token in tokenize.generate_tokens(StringIO(source).readline):
line = token.start[0]
if token.type != tokenize.COMMENT or line in preserved:
@@ -1137,7 +1143,7 @@ def violations(
required = {}
if isinstance(node, ast.ClassDef) and not models[node][0]:
required = dict.fromkeys(class_attributes(node), 'variable')
- elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node not in tests and node not in routes:
+ elif not isinstance(node, ast.ClassDef) and parameters is not None and node not in tests and node not in routes:
required = dict.fromkeys((name for name in parameters.names if name.isidentifier()), 'parameter')
yield from check_docstring(doc, parameters, start, settings, required, node, node in tests, node in routes)
for identifier, kind in sorted(required.items()):
@@ -1176,7 +1182,7 @@ def check_docstring(
if not CHINESE.search(lines[0]):
yield start, '文档摘要必须使用中文,可混用技术术语'
document = utils.new_document('', settings)
- messages = []
+ messages: list[nodes.system_message] = []
document.reporter.attach_observer(messages.append)
settings.env.prepare_settings('docstring')
try:
@@ -1186,7 +1192,8 @@ def check_docstring(
yield start, str(error)
for message in messages:
if message['level'] >= utils.Reporter.WARNING_LEVEL:
- yield start + (message.get('line') or 1) - 1, message[0].astext()
+ description: nodes.Node = message.children[0]
+ yield start + (message.get('line') or 1) - 1, description.astext()
fields = []
for block in document.findall(nodes.Element):
if block.line is None:
@@ -1257,12 +1264,17 @@ def check_prose(block: nodes.Element, start: int) -> Iterator[tuple[int, str]]:
"""
source = block.rawsource
parent = block.parent
- type_field = isinstance(parent, nodes.field_body) and FIELD_KINDS.get(parent.parent[0].astext().split()[0], '') in {
- 'returntype',
- 'parametertype',
- 'variabletype',
- 'meta',
- }
+ type_field = (
+ isinstance(parent, nodes.field_body)
+ and isinstance(parent.parent, nodes.field)
+ and FIELD_KINDS.get(parent.parent[0].astext().split()[0], '')
+ in {
+ 'returntype',
+ 'parametertype',
+ 'variabletype',
+ 'meta',
+ }
+ )
if (
not type_field
and re.search('[a-zA-Z]', source)
diff --git a/ruoyi-fastapi-backend/scripts/check_types.py b/ruoyi-fastapi-backend/scripts/check_types.py
new file mode 100644
index 000000000..9df53a7ea
--- /dev/null
+++ b/ruoyi-fastapi-backend/scripts/check_types.py
@@ -0,0 +1,56 @@
+import argparse
+import subprocess
+import sys
+from pathlib import Path
+
+BACKEND = Path(__file__).resolve().parents[1]
+E2E = BACKEND.parent / 'ruoyi-fastapi-test'
+CI = BACKEND.parent / '.github'
+PROJECTS = (BACKEND, E2E, CI)
+
+
+def project_targets(targets: list[Path]) -> dict[Path, list[Path]]:
+ """
+ 将目标分配到各自的 Python 导入根目录,避免两个工程的同名模块互相遮蔽。
+
+ :param targets: 用户指定的源码文件或目录
+ :return: 按工程分组的绝对路径
+ """
+ groups: dict[Path, list[Path]] = {}
+ for target in targets:
+ path = target.resolve()
+ owner = next((project for project in PROJECTS if path.is_relative_to(project)), None)
+ if owner:
+ groups.setdefault(owner, []).append(path)
+ elif path == BACKEND.parent:
+ for project in PROJECTS:
+ groups.setdefault(project, []).append(project)
+ else:
+ groups.setdefault(BACKEND, []).append(path)
+ return groups
+
+
+def main() -> int:
+ """
+ 通过当前解释器运行 ty 并汇总各工程的退出状态。
+
+ :return: 所有工程通过时返回零,否则返回子进程的错误码
+ """
+ parser = argparse.ArgumentParser(description='按工程运行 ty 类型检查')
+ parser.add_argument('--full', action='store_true', help='兼容旧命令,默认即报告全部诊断')
+ parser.add_argument('--python-version', metavar='X.Y', help='覆盖 ty 配置中的目标 Python 版本')
+ parser.add_argument('paths', type=Path, nargs='*', help='要检查的文件或目录,默认检查当前目录')
+ args = parser.parse_args()
+ status = 0
+ command = [sys.executable, '-m', 'ty', 'check', '--python', sys.executable]
+ if args.python_version:
+ command.extend(['--python-version', args.python_version])
+ for project, paths in project_targets(args.paths or [Path.cwd()]).items():
+ print(f'ty check [{project.name}]', flush=True)
+ result = subprocess.run([*command, '--', *paths], cwd=project, check=False)
+ status = max(status, result.returncode if result.returncode >= 0 else 1)
+ return status
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/ruoyi-fastapi-backend/scripts/compile_i18n.py b/ruoyi-fastapi-backend/scripts/compile_i18n.py
index a1997e7ae..ba0b03789 100644
--- a/ruoyi-fastapi-backend/scripts/compile_i18n.py
+++ b/ruoyi-fastapi-backend/scripts/compile_i18n.py
@@ -4,7 +4,7 @@
from pathlib import Path
from uuid import uuid4
-from babel.messages.catalog import Catalog
+from babel.messages.catalog import Catalog, TranslationError
from babel.messages.mofile import write_mo
from babel.messages.pofile import PoFileError, read_po
@@ -16,7 +16,7 @@
from plugins.core.environment import PLUGIN_RUNTIME_ENVIRONMENT
SOURCE_PLUGINS = Path(PLUGIN_RUNTIME_ENVIRONMENT.get_backend_plugins_dir()).resolve()
-CoreModuleKeys = dict[str, set[tuple[str | None, str | tuple[str, str]]]]
+CoreModuleKeys = dict[str, set[tuple[str | None, str | tuple[str, ...]]]]
def _read_catalog(path: Path, code: str) -> Catalog:
@@ -38,7 +38,7 @@ def _read_catalog(path: Path, code: str) -> Catalog:
if message.id:
values = message.string if isinstance(message.string, (list, tuple)) else (message.string,)
if message.fuzzy or not all(values):
- failures.append((message, ['Unreviewed or empty translation']))
+ failures.append((message, [TranslationError('Unreviewed or empty translation')]))
if failures:
raise ValueError(f'{path}: {failures}')
return catalog
@@ -70,7 +70,7 @@ def _read_core_modules(spec: CatalogSpec, code: str) -> tuple[Catalog, CoreModul
for message in catalog:
if not message.id:
continue
- keys.add((message.context, message.id))
+ keys.add((message.context, message.id if isinstance(message.id, str) else tuple(message.id)))
if merged is not None:
if merged.get(message.id, message.context) is not None:
raise ValueError(f'{path}: duplicate core msgid {message.id!r} (context {message.context!r})')
diff --git a/ruoyi-fastapi-backend/scripts/migrate_job_fields.py b/ruoyi-fastapi-backend/scripts/migrate_job_fields.py
index 68994f844..d93409e66 100644
--- a/ruoyi-fastapi-backend/scripts/migrate_job_fields.py
+++ b/ruoyi-fastapi-backend/scripts/migrate_job_fields.py
@@ -6,6 +6,7 @@
from sqlalchemy import JSON, MetaData, Table, bindparam, func, inspect, select, text, update
from sqlalchemy.engine import Connection
+from sqlalchemy.engine.interfaces import ReflectedColumn
from config.database import create_sync_db_engine
from module_admin.entity.do.job_runtime_do import SysJobExecution, SysJobSync
@@ -176,7 +177,7 @@ def read(name: str, default: Any = None) -> Any:
return values
-def table_columns(connection: Connection, name: str) -> dict[str, dict]:
+def table_columns(connection: Connection, name: str) -> dict[str, ReflectedColumn]:
"""
读取当前表结构,支持DDL部分完成后的再次运行。
@@ -336,8 +337,8 @@ def apply_migration(connection: Connection, plan: dict[str, Any]) -> dict[str, A
mysql = connection.dialect.name == 'mysql'
if connection.dialect.name not in {'mysql', 'postgresql'}:
raise ValueError('字段迁移仅支持MySQL和PostgreSQL')
- SysJobSync.__table__.create(connection, checkfirst=True)
- SysJobExecution.__table__.create(connection, checkfirst=True)
+ SysJobSync.get_table().create(connection, checkfirst=True)
+ SysJobExecution.get_table().create(connection, checkfirst=True)
for table in ('sys_job', 'sys_job_log'):
for name in ('job_args', 'job_kwargs'):
archive_column(connection, table, name)
@@ -392,9 +393,11 @@ def finalize_schema(connection: Connection) -> None:
if primary['constrained_columns'] != ['job_id']:
if mysql:
connection.exec_driver_sql('ALTER TABLE sys_job DROP PRIMARY KEY, ADD PRIMARY KEY (job_id)')
- else:
+ elif primary['name'] is not None:
name = connection.dialect.identifier_preparer.quote(primary['name'])
connection.exec_driver_sql(f'ALTER TABLE sys_job DROP CONSTRAINT {name}, ADD PRIMARY KEY (job_id)')
+ else:
+ connection.exec_driver_sql('ALTER TABLE sys_job ADD PRIMARY KEY (job_id)')
types = {
'job_name': 'VARCHAR(64)',
'job_group': 'VARCHAR(64)',
diff --git a/ruoyi-fastapi-backend/scripts/migrate_legacy_files.py b/ruoyi-fastapi-backend/scripts/migrate_legacy_files.py
index 626bb777f..068289a27 100644
--- a/ruoyi-fastapi-backend/scripts/migrate_legacy_files.py
+++ b/ruoyi-fastapi-backend/scripts/migrate_legacy_files.py
@@ -202,19 +202,19 @@ async def build_legacy_file_info(legacy_file: LegacyFileInfo) -> FileInfoModel:
:return: 文件信息模型
"""
return FileInfoModel(
- fileId=str(uuid.uuid4()),
- originalName=legacy_file.filename,
- storedName=legacy_file.filename,
- storageKey=legacy_file.storage_key,
- accessType='public',
+ file_id=str(uuid.uuid4()),
+ original_name=legacy_file.filename,
+ stored_name=legacy_file.filename,
+ storage_key=legacy_file.storage_key,
+ access_type='public',
extension=legacy_file.extension,
- contentType=legacy_file.content_type,
- fileSize=legacy_file.file_size,
- fileHash=await calculate_file_hash(legacy_file.filepath, legacy_file.signature),
- createBy='migration',
- createTime=legacy_file.file_time,
- updateBy='migration',
- updateTime=legacy_file.file_time,
+ content_type=legacy_file.content_type,
+ file_size=legacy_file.file_size,
+ file_hash=await calculate_file_hash(legacy_file.filepath, legacy_file.signature),
+ create_by='migration',
+ create_time=legacy_file.file_time,
+ update_by='migration',
+ update_time=legacy_file.file_time,
)
diff --git a/ruoyi-fastapi-backend/scripts/plugin_release_integration.py b/ruoyi-fastapi-backend/scripts/plugin_release_integration.py
index 85acdb08a..fa57f0312 100644
--- a/ruoyi-fastapi-backend/scripts/plugin_release_integration.py
+++ b/ruoyi-fastapi-backend/scripts/plugin_release_integration.py
@@ -10,14 +10,17 @@
import sys
import tempfile
import time
-from contextlib import asynccontextmanager
+from contextlib import asynccontextmanager, contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any
+from unittest.mock import patch
from uuid import uuid4
if TYPE_CHECKING:
- from collections.abc import AsyncGenerator
+ from collections.abc import AsyncGenerator, Generator
+
+ from redis.asyncio import Redis
BACKEND_ROOT = Path(__file__).resolve().parents[1]
PLUGIN_ID = 'release_it_demo'
@@ -192,7 +195,7 @@ def database_engine(spec: RunSpec, *, admin: bool = False) -> Any:
)
-def redis_client() -> Any:
+def redis_client() -> Redis:
"""
从验收专用环境变量创建异步 Redis 客户端。
@@ -212,20 +215,21 @@ def redis_client() -> Any:
)
-def wire_runtime(spec: RunSpec, engine: Any) -> tuple[Any, Any]:
+@contextmanager
+def wire_runtime(spec: RunSpec, engine: Any) -> Generator[tuple[Any, Any], None, None]:
"""
替换资源工厂和 Redis 命名空间,保留真实 DAO、锁与续租逻辑。
:param spec: 当前验收的隔离运行信息,不包含连接密码
:param engine: 隔离数据库的异步连接池
- :return: 制品部署配置和异步会话工厂
+ :yield: 制品部署配置和异步会话工厂
"""
from sqlalchemy.ext.asyncio import async_sessionmaker # noqa: PLC0415
+ from common.constant import LockConstant # noqa: PLC0415
from config.database import DataSourceRegistry # noqa: PLC0415
from config.get_redis import RedisUtil # noqa: PLC0415
from plugins.core.deployment.config import PluginDeploymentConfig # noqa: PLC0415
- from plugins.core.runtime.service.lifecycle_lock import RedisPluginLifecycleLock # noqa: PLC0415
sessions = async_sessionmaker(engine, expire_on_commit=False)
@@ -254,14 +258,16 @@ async def isolated_redis(*args: Any, **kwargs: Any) -> Any:
"""
return redis_client()
- DataSourceRegistry.session = isolated_session
- RedisUtil.create_redis_pool = staticmethod(isolated_redis)
- RedisPluginLifecycleLock._build_lock_key = staticmethod(lambda: f'{spec.redis_prefix}lifecycle:global')
root = Path(spec.root)
config = PluginDeploymentConfig(
root / 'host', root / 'store', root / 'trusted.json', heartbeat_seconds=1, worker_ttl_seconds=TTL_SECONDS
)
- return config, sessions
+ with (
+ patch.object(DataSourceRegistry, 'session', staticmethod(isolated_session)),
+ patch.object(RedisUtil, 'create_redis_pool', staticmethod(isolated_redis)),
+ patch.object(LockConstant, 'PLUGIN_LIFECYCLE_LOCK_PREFIX', f'{spec.redis_prefix}lifecycle'),
+ ):
+ yield config, sessions
async def create_isolated_database(spec: RunSpec, admin: Any) -> None:
@@ -490,34 +496,35 @@ async def maintenance_process(spec: RunSpec, action: str, digest: str | None) ->
from plugins.core.management.dao.release_dao import PluginReleaseDao # noqa: PLC0415
engine = database_engine(spec)
- config, sessions = wire_runtime(spec, engine)
- service = PluginDeploymentService(config, session_factory=sessions)
- try:
- if action == 'prepare':
- return await service.prepare(PLUGIN_ID, str(digest), maintenance=True, actor='real-service-it')
- async with sessions() as db:
- release = await PluginReleaseDao.get_release(db, PLUGIN_ID)
- generation = release.generation
- if action == 'select':
- return await service.select(
- PLUGIN_ID,
- str(digest),
- expected_generation=generation,
- expected_workers=2,
- maintenance=True,
- actor='real-service-it',
- )
- if action == 'rollback':
- return await service.rollback(
- PLUGIN_ID,
- expected_generation=generation,
- schema_compatible=True,
- maintenance=True,
- actor='real-service-it',
- )
- raise ValueError('Unknown isolated maintenance action')
- finally:
- await engine.dispose()
+ with wire_runtime(spec, engine) as (config, sessions):
+ service = PluginDeploymentService(config, session_factory=sessions)
+ try:
+ if action == 'prepare':
+ return await service.prepare(PLUGIN_ID, str(digest), maintenance=True, actor='real-service-it')
+ async with sessions() as db:
+ release = await PluginReleaseDao.get_release(db, PLUGIN_ID)
+ assert release is not None, '未找到待维护的插件发布记录'
+ generation = release.generation
+ if action == 'select':
+ return await service.select(
+ PLUGIN_ID,
+ str(digest),
+ expected_generation=generation,
+ expected_workers=2,
+ maintenance=True,
+ actor='real-service-it',
+ )
+ if action == 'rollback':
+ return await service.rollback(
+ PLUGIN_ID,
+ expected_generation=generation,
+ schema_compatible=True,
+ maintenance=True,
+ actor='real-service-it',
+ )
+ raise ValueError('Unknown isolated maintenance action')
+ finally:
+ await engine.dispose()
async def worker_process(spec: RunSpec, queue: Any, stop: Any, launch: str, fail: bool) -> None:
@@ -544,62 +551,62 @@ async def worker_process(spec: RunSpec, queue: Any, stop: Any, launch: str, fail
os.environ['RUOYI_PLUGIN_IT_FAIL_WORKER'] = '1' if fail else '0'
engine = database_engine(spec)
- config, sessions = wire_runtime(spec, engine)
- client = redis_client()
- app = FastAPI()
- app.state.redis = client
- builder = PluginRuntimeBuilder(config.backend_root)
- manager = PluginRuntimeStartupManager(
- builder,
- management_gateway=PluginManagementStartupGateway(),
- route_state_gateway=PluginManagementRouteStateGateway(),
- default_enabled_builtin_plugin_ids=set(),
- )
- worker = PluginReleaseWorker(config, session_factory=sessions)
- runtime = PluginApplicationRuntime(
- manager,
- ready_key=f'{spec.redis_prefix}ready',
- startup_generation=launch,
- lifecycle_lock=RedisPluginLifecycleLock(expire_seconds=6),
- release_worker=worker,
- ready_wait_timeout_seconds=60,
- ready_wait_interval_seconds=0.1,
- )
- runtime.bind_app(app)
+ with wire_runtime(spec, engine) as (config, sessions):
+ client = redis_client()
+ app = FastAPI()
+ app.state.redis = client
+ builder = PluginRuntimeBuilder(config.backend_root)
+ manager = PluginRuntimeStartupManager(
+ builder,
+ management_gateway=PluginManagementStartupGateway(),
+ route_state_gateway=PluginManagementRouteStateGateway(),
+ default_enabled_builtin_plugin_ids=set(),
+ )
+ worker = PluginReleaseWorker(config, session_factory=sessions)
+ runtime = PluginApplicationRuntime(
+ manager,
+ ready_key=f'{spec.redis_prefix}ready',
+ startup_generation=launch,
+ lifecycle_lock=RedisPluginLifecycleLock(expire_seconds=6),
+ release_worker=worker,
+ ready_wait_timeout_seconds=60,
+ ready_wait_interval_seconds=0.1,
+ )
+ runtime.bind_app(app)
- async def create_tables() -> None:
- # 表结构已经准备完成,此处只通过真实 Redis 统计启动写入回调的执行次数。
- """通过 Redis 计数验证只有启动写入进程执行此回调。"""
- await client.incr(f'{spec.redis_prefix}writer:{launch}')
+ async def create_tables() -> None:
+ # 表结构已经准备完成,此处只通过真实 Redis 统计启动写入回调的执行次数。
+ """通过 Redis 计数验证只有启动写入进程执行此回调。"""
+ await client.execute_command('INCR', f'{spec.redis_prefix}writer:{launch}')
- started = False
- try:
- await runtime.startup(app, create_tables=create_tables)
- started = True
- target = worker.targets[0]
- module = sys.modules[f'plugins.{PLUGIN_ID}']
- loaded = app.state.plugin_explicit_runtime.loaded[PLUGIN_ID]
- await app.state.plugin_diagnostics_reporter.publish()
- queue.put(
- {
- 'ok': True,
- 'workerId': worker.worker_id,
- 'version': module.LOADED_VERSION,
- 'modulePath': module.__file__,
- 'active': loaded.active,
- 'digest': target.digest,
- 'artifactGeneration': target.generation,
- 'writer': bool(app.state.plugin_startup_write_enabled),
- 'failed': fail,
- 'generation': app.state.plugin_startup_generation,
- }
- )
- await asyncio.to_thread(stop.wait)
- finally:
- if started:
- await runtime.shutdown(app)
- await client.aclose()
- await engine.dispose()
+ started = False
+ try:
+ await runtime.startup(app, create_tables=create_tables)
+ started = True
+ target = worker.targets[0]
+ module = sys.modules[f'plugins.{PLUGIN_ID}']
+ loaded = app.state.plugin_explicit_runtime.loaded[PLUGIN_ID]
+ await app.state.plugin_diagnostics_reporter.publish()
+ queue.put(
+ {
+ 'ok': True,
+ 'workerId': worker.worker_id,
+ 'version': module.LOADED_VERSION,
+ 'modulePath': module.__file__,
+ 'active': loaded.active,
+ 'digest': target.digest,
+ 'artifactGeneration': target.generation,
+ 'writer': bool(app.state.plugin_startup_write_enabled),
+ 'failed': fail,
+ 'generation': app.state.plugin_startup_generation,
+ }
+ )
+ await asyncio.to_thread(stop.wait)
+ finally:
+ if started:
+ await runtime.shutdown(app)
+ await client.aclose()
+ await engine.dispose()
def child_entry(spec: RunSpec, queue: Any, action: str, payload: Any, stop: Any = None) -> None:
@@ -1004,6 +1011,7 @@ async def verify_migrations(sessions: Any, installed: str, rows: int) -> None:
async with sessions() as db:
plugin = await PluginDao.get_plugin_by_id(db, PLUGIN_ID)
+ assert plugin is not None, '未找到已安装的插件记录'
check(plugin.installed_version == installed, f'Unexpected installedVersion: {plugin.installed_version}')
check(await db.scalar(text('SELECT COUNT(*) FROM plugin_it_probe')) == rows, 'Migration probe rows changed')
migrations = (await db.scalars(select(SysPluginMigration))).all()
@@ -1070,71 +1078,73 @@ async def exercise_release(spec: RunSpec, engine: Any) -> None:
"""
from plugins.core.deployment.service import PluginDeploymentService # noqa: PLC0415
- config, sessions = wire_runtime(spec, engine)
- service = PluginDeploymentService(config, session_factory=sessions)
- archive1, archive2 = make_artifacts(spec)
- digest1 = (await service.catalog.import_artifact(archive1))['digest']
- digest2 = (await service.catalog.import_artifact(archive2))['digest']
- await test_real_lock(spec)
- await run_maintenance(spec, 'prepare', digest1)
- await verify_migrations(sessions, '1.0.0', 1)
- initial_target = await run_maintenance(spec, 'select', digest1)
- await verify_release_wait(service, initial_target, 'before_workers', 'not_converged')
- await verify_release_wait(service, initial_target, 'before_workers_timeout', 'timeout', timeout_seconds=0.3)
- await verify_release_wait_cli(spec, initial_target, 'before_workers', 'not_converged')
- async with Workers(spec) as workers:
- await verify_release_wait(service, initial_target, 'initial_active', 'converged', timeout_seconds=3)
- await verify_release_wait_cli(spec, initial_target, 'initial_active', 'converged')
- state = await release_state(service)
- check(
- state['status'] == 'active' and state['healthyWorkers'] == EXPECTED_WORKER_COUNT,
- f'Initial release not active: {state}',
- )
- check(
- all(
- item['version'] == '1.0.0' and item['digest'] == digest1 and item['active'] for item in workers.reports
- ),
- 'Wrong initial runtime code',
- )
- check(
- all(Path(item['modulePath']).is_relative_to(config.store_root) for item in workers.reports),
- 'Worker loaded outside artifact store',
- )
- await expect_maintenance_blocked(service, digest2)
- emit('initial_active', workers=2, writer=1, reader=1, maintenanceBlocked=True)
- await run_maintenance(spec, 'prepare', digest2)
- await verify_migrations(sessions, '2.0.0', 2)
- upgrade_target = await run_maintenance(spec, 'select', digest2)
- await verify_release_wait(service, initial_target, 'upgrade_rejects_previous_target', 'target_changed')
- async with Workers(spec) as workers:
- await verify_release_wait(service, upgrade_target, 'upgrade_active', 'converged', timeout_seconds=3)
- state = await release_state(service)
- check(state['status'] == 'active', f'Upgrade did not converge: {state}')
- check(
- all(item['version'] == '2.0.0' and item['digest'] == digest2 for item in workers.reports),
- 'Upgrade reused old code',
- )
- emit('upgrade_active', codeVersion='2.0.0', installedVersion=state['installedVersion'])
- rollback_target = await run_maintenance(spec, 'rollback')
- await verify_migrations(sessions, '2.0.0', 2)
- async with Workers(spec) as workers:
- await verify_release_wait(service, rollback_target, 'rollback_active', 'converged', timeout_seconds=3)
- await verify_release_wait(service, upgrade_target, 'rollback_rejects_upgrade_target', 'target_changed')
- await verify_release_wait(service, initial_target, 'rollback_rejects_old_generation', 'target_changed')
- state = await release_state(service)
- check(
- state['status'] == 'active' and state['installedVersion'] == '2.0.0', f'Rollback lost schema state: {state}'
- )
- check(
- all(item['version'] == '1.0.0' and item['digest'] == digest1 for item in workers.reports),
- 'Rollback did not load prior artifact',
- )
- emit('rollback_active', codeVersion='1.0.0', installedVersion='2.0.0', migrationRows=2)
- await exercise_release_recovery(spec, service, rollback_target)
- await service.catalog.get(digest1)
- await service.catalog.get(digest2)
- check(not list(config.store_root.rglob('*.pyc')), 'Artifact runtime produced bytecode inside immutable store')
- check(f'plugins.{PLUGIN_ID}' not in sys.modules, 'Supervisor imported plugin runtime code')
+ with wire_runtime(spec, engine) as (config, sessions):
+ service = PluginDeploymentService(config, session_factory=sessions)
+ archive1, archive2 = make_artifacts(spec)
+ digest1 = (await service.catalog.import_artifact(archive1))['digest']
+ digest2 = (await service.catalog.import_artifact(archive2))['digest']
+ await test_real_lock(spec)
+ await run_maintenance(spec, 'prepare', digest1)
+ await verify_migrations(sessions, '1.0.0', 1)
+ initial_target = await run_maintenance(spec, 'select', digest1)
+ await verify_release_wait(service, initial_target, 'before_workers', 'not_converged')
+ await verify_release_wait(service, initial_target, 'before_workers_timeout', 'timeout', timeout_seconds=0.3)
+ await verify_release_wait_cli(spec, initial_target, 'before_workers', 'not_converged')
+ async with Workers(spec) as workers:
+ await verify_release_wait(service, initial_target, 'initial_active', 'converged', timeout_seconds=3)
+ await verify_release_wait_cli(spec, initial_target, 'initial_active', 'converged')
+ state = await release_state(service)
+ check(
+ state['status'] == 'active' and state['healthyWorkers'] == EXPECTED_WORKER_COUNT,
+ f'Initial release not active: {state}',
+ )
+ check(
+ all(
+ item['version'] == '1.0.0' and item['digest'] == digest1 and item['active']
+ for item in workers.reports
+ ),
+ 'Wrong initial runtime code',
+ )
+ check(
+ all(Path(item['modulePath']).is_relative_to(config.store_root) for item in workers.reports),
+ 'Worker loaded outside artifact store',
+ )
+ await expect_maintenance_blocked(service, digest2)
+ emit('initial_active', workers=2, writer=1, reader=1, maintenanceBlocked=True)
+ await run_maintenance(spec, 'prepare', digest2)
+ await verify_migrations(sessions, '2.0.0', 2)
+ upgrade_target = await run_maintenance(spec, 'select', digest2)
+ await verify_release_wait(service, initial_target, 'upgrade_rejects_previous_target', 'target_changed')
+ async with Workers(spec) as workers:
+ await verify_release_wait(service, upgrade_target, 'upgrade_active', 'converged', timeout_seconds=3)
+ state = await release_state(service)
+ check(state['status'] == 'active', f'Upgrade did not converge: {state}')
+ check(
+ all(item['version'] == '2.0.0' and item['digest'] == digest2 for item in workers.reports),
+ 'Upgrade reused old code',
+ )
+ emit('upgrade_active', codeVersion='2.0.0', installedVersion=state['installedVersion'])
+ rollback_target = await run_maintenance(spec, 'rollback')
+ await verify_migrations(sessions, '2.0.0', 2)
+ async with Workers(spec) as workers:
+ await verify_release_wait(service, rollback_target, 'rollback_active', 'converged', timeout_seconds=3)
+ await verify_release_wait(service, upgrade_target, 'rollback_rejects_upgrade_target', 'target_changed')
+ await verify_release_wait(service, initial_target, 'rollback_rejects_old_generation', 'target_changed')
+ state = await release_state(service)
+ check(
+ state['status'] == 'active' and state['installedVersion'] == '2.0.0',
+ f'Rollback lost schema state: {state}',
+ )
+ check(
+ all(item['version'] == '1.0.0' and item['digest'] == digest1 for item in workers.reports),
+ 'Rollback did not load prior artifact',
+ )
+ emit('rollback_active', codeVersion='1.0.0', installedVersion='2.0.0', migrationRows=2)
+ await exercise_release_recovery(spec, service, rollback_target)
+ await service.catalog.get(digest1)
+ await service.catalog.get(digest2)
+ check(not list(config.store_root.rglob('*.pyc')), 'Artifact runtime produced bytecode inside immutable store')
+ check(f'plugins.{PLUGIN_ID}' not in sys.modules, 'Supervisor imported plugin runtime code')
async def run(spec: RunSpec) -> None:
@@ -1163,14 +1173,14 @@ async def run(spec: RunSpec) -> None:
from plugins.core.deployment.service import PluginDeploymentService # noqa: PLC0415
from scripts.plugin_task_integration import exercise_task_delivery # noqa: PLC0415
- config, sessions = wire_runtime(spec, engine)
- task_result = await exercise_task_delivery(
- PluginDeploymentService(config, session_factory=sessions),
- sessions,
- task_source,
- Path(spec.root) / 'task-delivery',
- )
- emit('task_delivery', **task_result)
+ with wire_runtime(spec, engine) as (config, sessions):
+ task_result = await exercise_task_delivery(
+ PluginDeploymentService(config, session_factory=sessions),
+ sessions,
+ task_source,
+ Path(spec.root) / 'task-delivery',
+ )
+ emit('task_delivery', **task_result)
finally:
if engine is not None:
try:
diff --git a/ruoyi-fastapi-backend/scripts/plugin_task_integration.py b/ruoyi-fastapi-backend/scripts/plugin_task_integration.py
index 2c4c20536..bc818de5a 100644
--- a/ruoyi-fastapi-backend/scripts/plugin_task_integration.py
+++ b/ruoyi-fastapi-backend/scripts/plugin_task_integration.py
@@ -155,6 +155,7 @@ async def exercise_task_api(plugin: Any, sessions: Any) -> None:
:param sessions: 隔离数据库会话工厂
:raises AssertionError: 迁移改变原业务数据、权限边界失效或 CRUD 结果不符
"""
+ from fastapi import FastAPI # noqa: PLC0415
from httpx import ASGITransport, AsyncClient # noqa: PLC0415
from plugins.core.runtime.entrypoint import PluginEntrypointLoader # noqa: PLC0415
@@ -162,7 +163,9 @@ async def exercise_task_api(plugin: Any, sessions: Any) -> None:
host = PluginHostContext(TASK_PLUGIN_ID, plugin.backend_path, session_factory=sessions)
definition = PluginEntrypointLoader(plugin).load(host)
+ assert definition.app_factory is not None, '任务插件缺少应用工厂'
app = definition.app_factory(host)
+ assert isinstance(app, FastAPI), '任务插件必须提供 FastAPI 子应用'
permissions = frozenset({'task_demo:view', 'task_demo:write'})
@app.middleware('http')
diff --git a/ruoyi-fastapi-backend/scripts/verify_timezone_database.py b/ruoyi-fastapi-backend/scripts/verify_timezone_database.py
index 894666c7e..f799052ef 100644
--- a/ruoyi-fastapi-backend/scripts/verify_timezone_database.py
+++ b/ruoyi-fastapi-backend/scripts/verify_timezone_database.py
@@ -9,7 +9,9 @@
from uuid import uuid4
from dotenv import dotenv_values
-from sqlalchemy import Column, Integer, MetaData, Table, inspect, select, text
+from sqlalchemy import Column, Integer, MetaData, String, Table, inspect, select, text
+from sqlalchemy.dialects.mysql import DATETIME
+from sqlalchemy.dialects.postgresql import TIMESTAMP
from common.types import DbUtcDateTime
from config.database import Base, create_async_db_engine, create_sync_db_engine
@@ -31,11 +33,15 @@ def load_source(args: argparse.Namespace) -> DataSourceSettings:
:param args: 命令行参数
:return: 数据源连接配置
+ :raises ValueError: DB_SOURCES 缺少数据库配置
"""
if args.config:
return DataSourceSettings.model_validate_json(Path(args.config).read_text(encoding='utf-8'))
values = dotenv_values(args.env_file)
- sources = json.loads(values['DB_SOURCES'])
+ raw_sources = values.get('DB_SOURCES')
+ if raw_sources is None:
+ raise ValueError('DB_SOURCES 缺少数据库配置')
+ sources = json.loads(raw_sources)
return DataSourceSettings.model_validate(sources[args.source or values['DB_DEFAULT_SOURCE']])
@@ -136,6 +142,7 @@ def inspect_schema(source: DataSourceSettings, report: dict) -> None:
try:
catalog = inspect(engine)
columns = []
+ plugin_count = 0
for table in Base.metadata.tables.values():
instants = [column for column in table.columns if isinstance(column.type, DbUtcDateTime)]
if not instants:
@@ -144,14 +151,18 @@ def inspect_schema(source: DataSourceSettings, report: dict) -> None:
for column in instants:
found = actual[column.name]
assert found['nullable'] == column.nullable, f'{table.name}.{column.name}: nullable mismatch'
+ column_type = found['type']
if source.db_type == 'mysql':
- assert type(found['type']).__name__ == 'DATETIME' and found['type'].fsp == MILLISECOND_PRECISION
+ assert isinstance(column_type, DATETIME) and column_type.fsp == MILLISECOND_PRECISION
else:
- assert found['type'].timezone is True and found['type'].precision == MILLISECOND_PRECISION
+ assert isinstance(column_type, TIMESTAMP) and column_type.timezone is True
+ assert column_type.precision == MILLISECOND_PRECISION
default = found['default']
assert default is None or re.fullmatch(r'NULL(?:::[\w ()]+)?', default), (
f'{table.name}.{column.name}: unexpected server default'
)
+ if table.name.startswith('ai_'):
+ plugin_count += 1
columns.append(
{
'table': table.name,
@@ -163,15 +174,15 @@ def inspect_schema(source: DataSourceSettings, report: dict) -> None:
'server_default': found['default'],
}
)
- main = [column for column in columns if not column['table'].startswith('ai_')]
- plugin = [column for column in columns if column['table'].startswith('ai_')]
- assert len(main) == MAIN_INSTANT_COLUMNS and len(plugin) == PLUGIN_INSTANT_COLUMNS, (len(main), len(plugin))
+ main_count = len(columns) - plugin_count
+ assert (main_count, plugin_count) == (MAIN_INSTANT_COLUMNS, PLUGIN_INSTANT_COLUMNS), (main_count, plugin_count)
logs = {column['name']: column for column in catalog.get_columns('sys_job_log')}
assert type(logs['run_duration_ms']['type']).__name__ == 'BIGINT'
assert logs['run_duration_ms']['nullable'] and logs['time_zone']['nullable']
- assert logs['time_zone']['type'].length == TIMEZONE_LENGTH
+ zone_type = logs['time_zone']['type']
+ assert isinstance(zone_type, String) and zone_type.length == TIMEZONE_LENGTH
report['schema_columns'] = columns
- report['main_instant_columns'], report['plugin_instant_columns'] = len(main), len(plugin)
+ report['main_instant_columns'], report['plugin_instant_columns'] = main_count, plugin_count
finally:
engine.dispose()
@@ -275,7 +286,7 @@ async def verify_metadata_and_scheduler(source: DataSourceSettings, report: dict
try:
async with async_sessionmaker(async_engine)() as session:
rows = await GenTableDao.get_gen_db_table_list(session, GenTablePageQueryModel(), source_config=source)
- assert rows
+ assert isinstance(rows, list) and rows
for row in rows:
for key in ['createTime', 'updateTime']:
value = row.get(key)
@@ -285,7 +296,7 @@ async def verify_metadata_and_scheduler(source: DataSourceSettings, report: dict
assert TimezoneUtil.parse_rfc3339(value) <= TimezoneUtil.utc_now() + timedelta(seconds=1)
if source.db_type == 'mysql':
filtered = await GenTableDao.get_gen_db_table_list(
- session, GenTablePageQueryModel(beginTime='2000-01-01'), source_config=source
+ session, GenTablePageQueryModel(begin_time='2000-01-01'), source_config=source
)
assert filtered
report['metadata_time_contract'] = 'passed'
diff --git a/ruoyi-fastapi-backend/tests/cli/completion/test_installers.py b/ruoyi-fastapi-backend/tests/cli/completion/test_installers.py
index 7fe8d3adb..379073709 100644
--- a/ruoyi-fastapi-backend/tests/cli/completion/test_installers.py
+++ b/ruoyi-fastapi-backend/tests/cli/completion/test_installers.py
@@ -2,7 +2,7 @@
from unittest.mock import patch
import typer
-from pytest import MonkeyPatch
+from click.shell_completion import ShellComplete
from cli.completion.installers import (
CompletionInstallerService,
@@ -37,22 +37,13 @@ def test_make_bash_completion_script_compatible_wraps_legacy_instructions() -> N
assert 'complete -o nosort -F _ruoyi_completion ruoyi 2>/dev/null' in compatible_script
-def test_render_completion_script_uses_runtime_policy_transformer(monkeypatch: MonkeyPatch) -> None:
+def test_render_completion_script_uses_runtime_policy_transformer() -> None:
"""校验脚本渲染会通过 shell 运行时策略执行脚本后处理。"""
- class DummyComplete:
+ class DummyComplete(ShellComplete):
"""模拟 Click completion 生成器。"""
- def __init__(self, *args, **kwargs) -> None:
- """
- 初始化模拟生成器。
-
- :param args: 位置参数
- :param kwargs: 关键字参数
- """
-
- @staticmethod
- def source() -> str:
+ def source(self) -> str:
"""
返回原始脚本文本。
@@ -71,9 +62,9 @@ def source() -> str:
}
)
installer = CompletionInstallerService(shell_runtime_policy_registry=runtime_policy_registry)
- monkeypatch.setattr(installer, 'build_completion_click_command', lambda root_cli: object())
+ root_cli = typer.Typer(callback=lambda: None)
- rendered_script = installer.render_completion_script(typer.Typer(), 'bash')
+ rendered_script = installer.render_completion_script(root_cli, 'bash')
assert rendered_script == 'transformed::raw-script'
diff --git a/ruoyi-fastapi-backend/tests/cli/completion/test_providers.py b/ruoyi-fastapi-backend/tests/cli/completion/test_providers.py
index 3e77ab342..4a1f1d443 100644
--- a/ruoyi-fastapi-backend/tests/cli/completion/test_providers.py
+++ b/ruoyi-fastapi-backend/tests/cli/completion/test_providers.py
@@ -4,6 +4,8 @@
from pathlib import Path
from pytest import MonkeyPatch
+from typer import Context
+from typer.core import TyperCommand
BACKEND_DIR = Path(__file__).resolve().parents[3]
@@ -243,14 +245,8 @@ def list_cache_keys(cache_name: str) -> dict[str, str]:
CACHE_RUNTIME = CacheRuntime()
- class _FakeContext:
- """
- 模拟 Click 上下文。
-
- :cvar params: 调用时传入的参数
- """
-
- params = {'cache_name': 'sys_config'}
+ ctx = Context(TyperCommand('get'))
+ ctx.params['cache_name'] = 'sys_config'
monkeypatch.setattr(
completion_registry.dynamic_service, 'load_runtime_module', lambda module_name: _FakeCacheRuntime
@@ -264,7 +260,7 @@ class _FakeContext:
},
)
- candidates = completion_gateway.complete_cache_keys(_FakeContext(), None, 'site.n')
+ candidates = completion_gateway.complete_cache_keys(ctx, None, 'site.n')
assert candidates == ['site.name']
diff --git a/ruoyi-fastapi-backend/tests/cli/completion/test_shells.py b/ruoyi-fastapi-backend/tests/cli/completion/test_shells.py
index fe755f9b2..87e153494 100644
--- a/ruoyi-fastapi-backend/tests/cli/completion/test_shells.py
+++ b/ruoyi-fastapi-backend/tests/cli/completion/test_shells.py
@@ -28,3 +28,35 @@ def completion() -> None:
captured = capsys.readouterr()
assert captured.err == ''
assert any(line.split('\t', 2)[:2] == ['plain', 'completion'] for line in captured.out.splitlines())
+
+
+@pytest.mark.parametrize(
+ ('instruction', 'cursor', 'expected'),
+ [
+ ('bash_complete', '2', 'plain,show'),
+ ('zsh_complete', '2', 'plain\nshow\n'),
+ ('fish_complete', 'sh', 'plain,show'),
+ ('powershell_complete', 'sh', 'plain\tshow\t'),
+ ('complete_bash', '2', 'show'),
+ ],
+)
+def test_nested_command_completion_uses_shell_protocol(
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], instruction: str, cursor: str, expected: str
+) -> None:
+ """嵌套命令按各个 shell 的协议返回候选项。"""
+ monkeypatch.setenv('_RUOYI_COMPLETE', instruction)
+ monkeypatch.setenv('COMP_WORDS', 'ruoyi config sh')
+ monkeypatch.setenv('COMP_CWORD', cursor)
+ app = typer.Typer(add_completion=False)
+ config = typer.Typer()
+ app.add_typer(config, name='config')
+
+ @config.command()
+ def show() -> None:
+ """显示配置。"""
+
+ with pytest.raises(SystemExit) as result:
+ CompletionDispatcher().dispatch(app)
+
+ assert result.value.code == 0
+ assert expected in capsys.readouterr().out
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_artifact_commands.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_artifact_commands.py
index 0cfe6ea83..cd07bb6c0 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_artifact_commands.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_artifact_commands.py
@@ -5,8 +5,8 @@
import subprocess
import sys
from pathlib import Path
-from types import SimpleNamespace
from typing import Any
+from unittest.mock import create_autospec
import pytest
import typer
@@ -16,6 +16,7 @@
from cli.context import CliContext
from cli.core import CliContextFactory, CliExecutionService
+from cli.core.context_factory import CliRuntimeState
from cli.exit_codes import ARGUMENT_ERROR, GUARD_REJECTED
from cli.groups.plugin.artifact_controller import PluginArtifactCommandController
from cli.groups.plugin.commands.artifact import register_artifact_commands
@@ -280,7 +281,7 @@ def test_help_keeps_config_crypto_database_and_plugin_code_unloaded(help_argumen
assert not any(payload['loaded'].values())
-class RecordingContextFactory:
+class RecordingContextFactory(CliContextFactory):
"""
记录上下文创建顺序的工厂替身。
@@ -307,6 +308,7 @@ def build_regular(self, env: str, output: str, allow_prod: bool, yes: bool, dry_
:return: ``CliContext`` 实例
"""
self.events.append('context')
+ assert output in {'text', 'json'}
return CliContext(env=env, output=output, allow_prod=allow_prod, yes=yes, dry_run=dry_run)
def build_dangerous(
@@ -327,7 +329,7 @@ def build_dangerous(
return self.build_regular(env, output, allow_prod, yes, dry_run)
-class RecordingExecution:
+class RecordingExecution(CliExecutionService):
"""
记录命令结果的执行服务替身。
@@ -348,11 +350,12 @@ def run_async(coroutine: Any) -> Any:
"""
return asyncio.run(coroutine)
- def complete_payload(self, ctx: CliContext, payload: dict[str, Any]) -> None:
+ def complete_payload(self, ctx: CliContext, payload: dict[str, Any], *, default_exit_code: int = 0) -> None:
"""
保存 CLI 命令最终输出的结果。
:param ctx: CLI 运行上下文
+ :param default_exit_code: 默认退出码
:param payload: 随调用传入或返回的结构化数据
"""
self.payload = payload
@@ -364,9 +367,7 @@ def quiet_context_factory() -> CliContextFactory:
:return: 不初始化日志输出的测试上下文工厂
"""
- return CliContextFactory(
- runtime_state=SimpleNamespace(suppress_logs=lambda: None, suppress_sqlalchemy_logs=lambda: None)
- )
+ return CliContextFactory(runtime_state=create_autospec(CliRuntimeState, instance=True, spec_set=True))
def test_production_mutations_are_guarded_before_loading_runtime(monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_command_controller.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_command_controller.py
index a34b8869d..472654d76 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_command_controller.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_command_controller.py
@@ -1,8 +1,12 @@
import asyncio
import inspect
import sys
+from collections.abc import Callable
from typing import Any
+from unittest.mock import Mock
+from cli.context import CliContext
+from cli.core import CliContextFactory, CliExecutionService
from cli.exit_codes import ARGUMENT_ERROR, DEPENDENCY_ERROR, RUNTIME_ERROR
from cli.groups.plugin.controller import PluginCommandController
from cli.groups.plugin.options import (
@@ -10,9 +14,11 @@
PluginDependencyInstallCommandOptions,
PluginDependencyLockCommandOptions,
)
+from cli.runtime.plugin.service import CliPluginRuntimeService
+from plugins.core.runtime.service import PluginRuntimeService
-class FakeContextFactory:
+class FakeContextFactory(CliContextFactory):
"""测试用 CLI 上下文工厂。"""
def build_dangerous(
@@ -24,7 +30,7 @@ def build_dangerous(
dry_run: bool,
*,
command_name: str,
- ) -> Any:
+ ) -> CliContext:
"""
构造危险命令上下文。
@@ -36,7 +42,7 @@ def build_dangerous(
:param command_name: 命令唯一标识
:return: 危险命令上下文
"""
- return type('FakeContext', (), {'env': env, 'output': output})()
+ return self.build_regular(env, output, allow_prod, yes, dry_run)
def build_regular(
self,
@@ -45,7 +51,7 @@ def build_regular(
allow_prod: bool,
yes: bool,
dry_run: bool,
- ) -> Any:
+ ) -> CliContext:
"""
构造普通命令上下文。
@@ -56,13 +62,10 @@ def build_regular(
:param dry_run: 是否只预览操作结果
:return: 普通命令上下文
"""
- return type(
- 'FakeContext',
- (),
- {'env': env, 'output': output, 'allow_prod': allow_prod, 'yes': yes, 'dry_run': dry_run},
- )()
+ assert output in {'text', 'json'}
+ return CliContext(env=env, output=output, allow_prod=allow_prod, yes=yes, dry_run=dry_run)
- def build_readonly(self, env: str, output: str) -> Any:
+ def build_readonly(self, env: str, output: str) -> CliContext:
"""
构造只读命令上下文。
@@ -70,10 +73,10 @@ def build_readonly(self, env: str, output: str) -> Any:
:param output: 命令或操作的输出
:return: 只读命令上下文
"""
- return type('FakeContext', (), {'env': env, 'output': output})()
+ return self.build_regular(env, output, False, False, False)
-class FakeExecutionService:
+class FakeExecutionService(CliExecutionService):
"""
测试用 CLI 执行服务。
@@ -86,24 +89,25 @@ def __init__(self) -> None:
self.completed_payload: dict[str, Any] | None = None
self.default_exit_code: int | None = None
- def run_async(self, value: Any) -> Any:
+ def run_async(self, coroutine: Any) -> Any:
"""
直接返回测试中的 awaitable 结果。
- :param value: 待处理的输入值
+ :param coroutine: 待处理的输入值
:return: 可等待对象执行完毕后的值
"""
- if inspect.isawaitable(value):
- return asyncio.run(value)
- return value
+ if inspect.isawaitable(coroutine):
+ return asyncio.run(coroutine)
+ return coroutine
def complete_payload_with_text(
self,
- ctx: Any,
+ ctx: CliContext,
payload: dict[str, Any],
*,
- text_builder: Any,
- default_exit_code: int,
+ text_builder: Callable[[dict[str, Any]], Any],
+ default_exit_code: int = 0,
+ text_condition: Callable[[dict[str, Any]], bool] | None = None,
) -> None:
"""
记录完成参数。
@@ -111,106 +115,13 @@ def complete_payload_with_text(
:param ctx: 当前命令的执行上下文
:param payload: 随调用传入或返回的结构化数据
:param text_builder: 文本结果构建函数
+ :param text_condition: 判断是否生成文本输出的回调
:param default_exit_code: 默认退出码
"""
self.completed_payload = payload
self.default_exit_code = default_exit_code
-class FakePresenter:
- """测试用 presenter。"""
-
- @staticmethod
- def build_list_text(payload: dict[str, Any]) -> str:
- """
- 构造列表文本。
-
- :param payload: 随调用传入或返回的结构化数据
- :return: 列表文本
- """
- return str(payload)
-
- @staticmethod
- def build_info_text(payload: dict[str, Any]) -> str:
- """
- 构造详情文本。
-
- :param payload: 随调用传入或返回的结构化数据
- :return: 详情文本
- """
- return str(payload)
-
- @staticmethod
- def build_enabled_text(payload: dict[str, Any]) -> str:
- """
- 构造启停文本。
-
- :param payload: 随调用传入或返回的结构化数据
- :return: 启停文本
- """
- return str(payload)
-
- @staticmethod
- def build_install_text(payload: dict[str, Any]) -> str:
- """
- 构造安装文本。
-
- :param payload: 随调用传入或返回的结构化数据
- :return: 安装文本
- """
- return str(payload)
-
- @staticmethod
- def build_check_text(payload: dict[str, Any]) -> str:
- """
- 构造检查文本。
-
- :param payload: 随调用传入或返回的结构化数据
- :return: 检查文本
- """
- return str(payload)
-
- @staticmethod
- def build_config_text(payload: dict[str, Any]) -> str:
- """
- 构造配置文本。
-
- :param payload: 随调用传入或返回的结构化数据
- :return: 配置文本
- """
- return str(payload)
-
- @staticmethod
- def build_dependency_install_text(payload: dict[str, Any]) -> str:
- """
- 构造依赖安装文本。
-
- :param payload: 随调用传入或返回的结构化数据
- :return: 依赖安装文本
- """
- return str(payload)
-
- @staticmethod
- def build_dependency_lock_text(payload: dict[str, Any]) -> str:
- """
- 构造依赖锁文件文本。
-
- :param payload: 随调用传入或返回的结构化数据
- :return: 依赖锁文件文本
- """
- return str(payload)
-
- @staticmethod
- def build_dependency_allowlist_example_text(payload: dict[str, Any]) -> str:
- """
- 构造允许列表示例文本。
-
- :param payload: 随调用传入或返回的结构化数据
- :return: 允许列表示例文本
- """
- return str(payload)
-
-
class FakeCoreRuntime:
"""
测试用核心插件运行时。
@@ -316,18 +227,21 @@ def install_plugin_dependencies_from_cli(
}
-class FakePluginRuntime:
+class FakePluginRuntime(CliPluginRuntimeService):
"""
测试用插件 CLI 运行时。
- :ivar core_runtime: 被测命令使用的核心运行时
+ :ivar recorded_core: 记录插件命令调用的测试替身
+ :ivar _core_runtime: 使用核心运行时接口约束的模拟对象
:ivar dependency_lock_calls: 记录 ``dependency_lock`` 的调用情况
:ivar dependency_allowlist_example_calls: 记录 ``dependency_allowlist_example`` 的调用情况
"""
def __init__(self) -> None:
"""初始化测试用插件 CLI 运行时。"""
- self.core_runtime = FakeCoreRuntime()
+ super().__init__()
+ self.recorded_core = FakeCoreRuntime()
+ self._core_runtime = Mock(spec_set=PluginRuntimeService, wraps=self.recorded_core)
self.dependency_lock_calls: list[dict[str, Any]] = []
self.dependency_allowlist_example_calls: list[dict[str, Any]] = []
@@ -407,13 +321,12 @@ def test_list_plugins_uses_database_state_aware_query() -> None:
controller = PluginCommandController(
context_factory=FakeContextFactory(),
execution_service=execution_service,
- presenter=FakePresenter(),
plugin_runtime=plugin_runtime,
)
controller.list_plugins('dev', 'json')
- assert plugin_runtime.core_runtime.list_with_state_called is True
+ assert plugin_runtime.recorded_core.list_with_state_called is True
assert execution_service.completed_payload is not None
assert execution_service.completed_payload['plugins'][0]['runtimeEnabled'] is True
assert 'enabled' not in execution_service.completed_payload['plugins'][0]
@@ -426,7 +339,6 @@ def test_install_plugin_uses_failure_exit_code_when_payload_is_not_ok() -> None:
controller = PluginCommandController(
context_factory=FakeContextFactory(),
execution_service=execution_service,
- presenter=FakePresenter(),
plugin_runtime=FakePluginRuntime(),
)
@@ -443,7 +355,6 @@ def test_check_plugin_uses_failure_exit_code_when_payload_has_no_ok() -> None:
controller = PluginCommandController(
context_factory=FakeContextFactory(),
execution_service=execution_service,
- presenter=FakePresenter(),
plugin_runtime=FakePluginRuntime(),
)
@@ -460,14 +371,13 @@ def test_plugin_config_set_uses_failure_exit_code_when_payload_is_not_ok() -> No
controller = PluginCommandController(
context_factory=FakeContextFactory(),
execution_service=execution_service,
- presenter=FakePresenter(),
plugin_runtime=FakePluginRuntime(),
)
controller.plugin_config(
'demo',
'set',
- ['provider="openai"'],
+ ['provider="openai"', 'options={"limits":[3,null],"enabled":true}'],
'dev',
'text',
allow_prod=False,
@@ -476,7 +386,10 @@ def test_plugin_config_set_uses_failure_exit_code_when_payload_is_not_ok() -> No
assert execution_service.completed_payload is not None
assert execution_service.completed_payload['ok'] is False
- assert execution_service.completed_payload['values'] == {'provider': 'openai'}
+ assert execution_service.completed_payload['values'] == {
+ 'provider': 'openai',
+ 'options': {'limits': [3, None], 'enabled': True},
+ }
assert execution_service.default_exit_code == DEPENDENCY_ERROR
@@ -487,7 +400,6 @@ def test_plugin_config_set_argument_error_uses_structured_payload() -> None:
controller = PluginCommandController(
context_factory=FakeContextFactory(),
execution_service=execution_service,
- presenter=FakePresenter(),
plugin_runtime=plugin_runtime,
)
@@ -501,7 +413,7 @@ def test_plugin_config_set_argument_error_uses_structured_payload() -> None:
yes=True,
)
- assert plugin_runtime.core_runtime.config_set_calls == []
+ assert plugin_runtime.recorded_core.config_set_calls == []
assert execution_service.completed_payload is not None
assert execution_service.completed_payload['ok'] is False
assert execution_service.completed_payload['message'] == '配置参数必须使用 key=value 格式:badpair'
@@ -528,7 +440,6 @@ def test_install_plugin_dependencies_passes_policy_config_to_runtime() -> None:
controller = PluginCommandController(
context_factory=FakeContextFactory(),
execution_service=execution_service,
- presenter=FakePresenter(),
plugin_runtime=plugin_runtime,
)
@@ -563,8 +474,8 @@ def test_install_plugin_dependencies_passes_policy_config_to_runtime() -> None:
assert str(policy_config.allowlist_path) == 'config/plugin_dependency_allowlist.yaml'
assert str(policy_config.offline_dir) == 'artifacts/plugin-dependencies'
assert policy_config.require_lockfile is True
- assert len(plugin_runtime.core_runtime.dependency_install_calls) == 1
- assert callable(plugin_runtime.core_runtime.dependency_install_calls[0]['output_callback'])
+ assert len(plugin_runtime.recorded_core.dependency_install_calls) == 1
+ assert callable(plugin_runtime.recorded_core.dependency_install_calls[0]['output_callback'])
def test_install_plugin_dependencies_json_output_disables_live_progress() -> None:
@@ -574,7 +485,6 @@ def test_install_plugin_dependencies_json_output_disables_live_progress() -> Non
controller = PluginCommandController(
context_factory=FakeContextFactory(),
execution_service=execution_service,
- presenter=FakePresenter(),
plugin_runtime=plugin_runtime,
)
@@ -585,7 +495,7 @@ def test_install_plugin_dependencies_json_output_disables_live_progress() -> Non
options=PluginDependencyInstallCommandOptions(yes=True),
)
- assert plugin_runtime.core_runtime.dependency_install_calls[0]['output_callback'] is None
+ assert plugin_runtime.recorded_core.dependency_install_calls[0]['output_callback'] is None
def test_dependency_install_output_callback_routes_stderr_separately(monkeypatch: Any) -> None:
@@ -595,7 +505,7 @@ def test_dependency_install_output_callback_routes_stderr_separately(monkeypatch
'typer.echo',
lambda text, *, nl, err: emitted.append((text, err)),
)
- ctx = type('FakeContext', (), {'output': 'text'})()
+ ctx = CliContext(output='text')
output_callback = PluginCommandController._build_dependency_install_output_callback(ctx)
@@ -619,7 +529,6 @@ def test_install_plugin_dependencies_tty_confirm_previews_then_executes(
controller = PluginCommandController(
context_factory=FakeContextFactory(),
execution_service=execution_service,
- presenter=FakePresenter(),
plugin_runtime=plugin_runtime,
)
monkeypatch.setattr(sys.stdin, 'isatty', lambda: True)
@@ -634,8 +543,8 @@ def test_install_plugin_dependencies_tty_confirm_previews_then_executes(
options=PluginDependencyInstallCommandOptions(dry_run=False, yes=False),
)
- assert [call['dry_run'] for call in plugin_runtime.core_runtime.dependency_install_calls] == [True, False]
- assert [call['confirmed'] for call in plugin_runtime.core_runtime.dependency_install_calls] == [True, True]
+ assert [call['dry_run'] for call in plugin_runtime.recorded_core.dependency_install_calls] == [True, False]
+ assert [call['confirmed'] for call in plugin_runtime.recorded_core.dependency_install_calls] == [True, True]
assert emitted_lines
assert execution_service.completed_payload is not None
assert execution_service.completed_payload['dryRun'] is False
@@ -651,7 +560,6 @@ def test_install_plugin_dependencies_tty_decline_does_not_execute_real_install(
controller = PluginCommandController(
context_factory=FakeContextFactory(),
execution_service=execution_service,
- presenter=FakePresenter(),
plugin_runtime=plugin_runtime,
)
monkeypatch.setattr(sys.stdin, 'isatty', lambda: True)
@@ -665,7 +573,7 @@ def test_install_plugin_dependencies_tty_decline_does_not_execute_real_install(
options=PluginDependencyInstallCommandOptions(dry_run=False, yes=False),
)
- assert [call['dry_run'] for call in plugin_runtime.core_runtime.dependency_install_calls] == [True]
+ assert [call['dry_run'] for call in plugin_runtime.recorded_core.dependency_install_calls] == [True]
assert execution_service.completed_payload is not None
assert execution_service.completed_payload['ok'] is False
assert execution_service.completed_payload['message'] == '已取消插件依赖安装'
@@ -680,7 +588,6 @@ def test_install_plugin_dependencies_non_tty_without_yes_does_not_preview(
controller = PluginCommandController(
context_factory=FakeContextFactory(),
execution_service=execution_service,
- presenter=FakePresenter(),
plugin_runtime=plugin_runtime,
)
monkeypatch.setattr(sys.stdin, 'isatty', lambda: False)
@@ -692,8 +599,8 @@ def test_install_plugin_dependencies_non_tty_without_yes_does_not_preview(
options=PluginDependencyInstallCommandOptions(dry_run=False, yes=False),
)
- assert [call['dry_run'] for call in plugin_runtime.core_runtime.dependency_install_calls] == [False]
- assert plugin_runtime.core_runtime.dependency_install_calls[0]['confirmed'] is False
+ assert [call['dry_run'] for call in plugin_runtime.recorded_core.dependency_install_calls] == [False]
+ assert plugin_runtime.recorded_core.dependency_install_calls[0]['confirmed'] is False
def test_lock_plugin_dependencies_passes_options_to_runtime() -> None:
@@ -703,7 +610,6 @@ def test_lock_plugin_dependencies_passes_options_to_runtime() -> None:
controller = PluginCommandController(
context_factory=FakeContextFactory(),
execution_service=execution_service,
- presenter=FakePresenter(),
plugin_runtime=plugin_runtime,
)
@@ -740,7 +646,6 @@ def test_generate_plugin_dependency_allowlist_example_passes_options_to_runtime(
controller = PluginCommandController(
context_factory=FakeContextFactory(),
execution_service=execution_service,
- presenter=FakePresenter(),
plugin_runtime=plugin_runtime,
)
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_diagnostics.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_diagnostics.py
index 2730a38fc..1f7eba9e1 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_diagnostics.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_diagnostics.py
@@ -1,5 +1,4 @@
from pathlib import Path
-from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
@@ -7,19 +6,22 @@
from cli.groups.plugin.payload import PluginCommandPayloadAdapter
from cli.groups.plugin.presenter import PluginCommandPresenter
from cli.runtime.plugin.service import CliPluginRuntimeService
+from plugins.core.environment import PluginRuntimeEnvironmentService
@pytest.mark.asyncio
-async def test_cli_diagnose_appends_runtime_without_changing_static_result(monkeypatch: pytest.MonkeyPatch) -> None:
+async def test_cli_diagnose_appends_runtime_without_changing_static_result(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
"""命令行诊断在静态结果后追加运行时信息。"""
read = AsyncMock(return_value={'state': 'unavailable', 'observedTotals': None})
monkeypatch.setattr('plugins.core.runtime.diagnostics_query.read_cli_runtime_diagnostics', read)
- runtime = CliPluginRuntimeService(runtime_environment=SimpleNamespace(get_backend_dir=lambda: '/backend'))
- runtime._core_runtime = SimpleNamespace(diagnose_plugin=AsyncMock(return_value={'ok': True, 'info': {'x': 1}}))
+ runtime = CliPluginRuntimeService(runtime_environment=PluginRuntimeEnvironmentService(backend_root=tmp_path))
+ monkeypatch.setattr(runtime.core_runtime, 'diagnose_plugin', AsyncMock(return_value={'ok': True, 'info': {'x': 1}}))
payload = await runtime.diagnose_plugin_with_runtime('demo')
assert payload['ok'] is True and payload['info'] == {'x': 1}
- assert payload['runtime']['state'] == 'unavailable'
- read.assert_awaited_once_with('demo', backend_root=Path('/backend'))
+ assert payload['runtime'] == {'state': 'unavailable', 'observedTotals': None}
+ read.assert_awaited_once_with('demo', backend_root=tmp_path)
def test_runtime_shared_contract_and_unknown_text_are_preserved() -> None:
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_lazy_import.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_lazy_import.py
index d3b21d8c1..00e4c11a9 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_lazy_import.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_lazy_import.py
@@ -5,6 +5,7 @@
from pathlib import Path
import pytest
+from pydantic import TypeAdapter
pytestmark = pytest.mark.contract
BACKEND_ROOT = Path(__file__).resolve().parents[3]
@@ -31,7 +32,7 @@ def inspect_cold_import(module_name: str, observed_modules: tuple[str, ...]) ->
text=True,
timeout=30,
)
- return json.loads(completed.stdout)
+ return TypeAdapter(dict[str, bool]).validate_json(completed.stdout, strict=True)
def test_cli_plugin_cold_import_boundaries() -> None:
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_release_wait.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_release_wait.py
index c222d211f..4928413fe 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_release_wait.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_release_wait.py
@@ -3,13 +3,14 @@
import os
from types import SimpleNamespace
from typing import Any
-from unittest.mock import AsyncMock, Mock
+from unittest.mock import AsyncMock, Mock, create_autospec
import pytest
import typer
from typer.testing import CliRunner
from cli.core import CliContextFactory, CliExecutionService
+from cli.core.context_factory import CliRuntimeState
from cli.exit_codes import ARGUMENT_ERROR, RUNTIME_ERROR, SUCCESS
from cli.groups.plugin.artifact_controller import PluginArtifactCommandController
from cli.groups.plugin.commands.artifact import register_artifact_commands
@@ -58,9 +59,7 @@ def controller_for(service: Any, *, config_factory: Any = object) -> PluginArtif
:param config_factory: 可记录或拒绝部署配置加载的工厂
:return: 不连接外部服务的被测控制器
"""
- context = CliContextFactory(
- runtime_state=SimpleNamespace(suppress_logs=lambda: None, suppress_sqlalchemy_logs=lambda: None)
- )
+ context = CliContextFactory(runtime_state=create_autospec(CliRuntimeState, instance=True, spec_set=True))
return PluginArtifactCommandController(
context_factory=context,
execution_service=CliExecutionService(),
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_utils.py b/ruoyi-fastapi-backend/tests/cli/root/test_utils.py
index 663a16ad3..34a0c1ce6 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_utils.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_utils.py
@@ -88,7 +88,7 @@ def _fake_subprocess_run(*args: object, **kwargs: object) -> SimpleNamespace:
result = cli_utils.NESTED_CLI_SUPPORT.run('job', 'run-once', '1', '--output=json', parse_json=True)
- assert result.payload is not None
+ assert isinstance(result.payload, dict)
assert result.payload.get('ok') is True
assert result.payload.get('message') == '任务已提交到调度器'
assert result.payload.get('fallback') == 'non_json_output'
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/conftest.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/conftest.py
index b1fbb7241..e90a9b12d 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/conftest.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/conftest.py
@@ -4,7 +4,8 @@
from cli.runtime.plugin.service import CliPluginRuntimeService
from plugins.core.environment import PluginRuntimeEnvironmentService
-from plugins.core.frontend import PluginFrontendFrameworkResolver
+from plugins.core.management.service.gateway import PluginManagementRuntimeGateway
+from plugins.core.runtime.service.gateway import PluginCommandOutputCallback
from plugins.core.validation.dependencies import (
NpmDependencyInspector,
PluginDependencyChecker,
@@ -14,96 +15,27 @@
EXPECTED_FRONTEND_BUILD_TIMEOUT = 300
-class FakeRuntimeEnvironment:
+class FakeRuntimeEnvironment(PluginRuntimeEnvironmentService):
"""
- 测试用插件 CLI 运行时环境服务。
+ 使用测试目录和当前 Python 解释器的开发环境。
- :ivar backend_dir: 后端项目目录
- :ivar frontend_dir: 前端项目目录
+ :ivar frontend_mode: 测试固定使用的前端开发模式
+ :ivar backend_runtime_mode: 测试固定使用的后端开发模式
"""
def __init__(self, backend_dir: Path, frontend_dir: Path | None = None) -> None:
"""
- 初始化测试用插件 CLI 运行时环境服务。
+ 设置测试用插件目录和解释器。
- :param backend_dir: 后端项目目录
- :param frontend_dir: 前端项目目录
+ :param backend_dir: 后端根目录
+ :param frontend_dir: 前端根目录
"""
- self.backend_dir = backend_dir
- self.frontend_dir = frontend_dir or Path(
- PluginRuntimeEnvironmentService(backend_root=backend_dir).get_frontend_dir()
- )
-
- def get_backend_dir(self) -> str:
- """
- 获取后端项目根目录。
-
- :return: 后端项目根目录
- """
- return str(self.backend_dir)
-
- def get_backend_plugins_dir(self) -> str:
- """
- 获取后端插件根目录。
-
- :return: 后端插件根目录
- """
- return str(self.backend_dir / 'plugins')
-
- def get_frontend_dir(self) -> str:
- """
- 获取前端项目根目录。
-
- :return: 前端项目根目录
- """
- return str(self.frontend_dir)
-
- def get_frontend_framework(self, frontend_root: Path | None = None) -> str:
- """
- 获取指定测试前端工程的框架标识。
-
- :param frontend_root: 前端项目的根目录
- :return: 指定测试前端工程的框架标识
- """
- return PluginFrontendFrameworkResolver.resolve(frontend_root or self.frontend_dir)
-
- def get_frontend_plugins_dir(self) -> str:
- """
- 获取前端插件根目录。
-
- :return: 前端插件根目录
- """
- return str(self.frontend_dir / 'plugins')
-
- @staticmethod
- def get_frontend_mode() -> str:
- """
- 获取测试用前端运行模式。
-
- :return: 此分支的固定值 ``'dev'``
- """
- return 'dev'
-
- @staticmethod
- def get_backend_runtime_mode() -> str:
- """
- 获取测试用后端运行模式。
-
- :return: 此分支的固定值 ``'dev'``
- """
- return 'dev'
-
- @staticmethod
- def get_python_executable() -> str:
- """
- 获取测试用 Python 解释器。
-
- :return: 测试用 Python 解释器
- """
- return sys.executable
+ super().__init__(backend_root=backend_dir, frontend_root=frontend_dir, python_executable=sys.executable)
+ self.frontend_mode = 'dev'
+ self.backend_runtime_mode = 'dev'
-class FakePluginRuntimeGateway:
+class FakePluginRuntimeGateway(PluginManagementRuntimeGateway):
"""
测试用插件 CLI 运行时适配器。
@@ -122,12 +54,14 @@ def run_command(
workdir: str,
*,
timeout: int | None = None,
+ output_callback: PluginCommandOutputCallback | None = None,
) -> CompletedProcess[str]:
"""
记录测试用系统命令。
:param command: 执行的命令及其参数
:param workdir: 命令执行时使用的工作目录
+ :param output_callback: 接收命令输出的回调
:param timeout: 等待操作完成的超时限制
:return: 供调用方使用的 ``self.completed_process``
"""
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_dependency_allowlist.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_dependency_allowlist.py
index 16d5008ba..80062278a 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_dependency_allowlist.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_dependency_allowlist.py
@@ -69,5 +69,6 @@ def test_plugin_runtime_allowlist_example_rejects_existing_file_without_overwrit
assert payload['ok'] is False
assert payload['written'] is False
assert payload['outputFile'] == str(output_path)
+ assert isinstance(payload['message'], str)
assert '已存在' in payload['message']
assert output_path.read_text(encoding='utf-8') == 'python: {}\n'
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_dependency_lock.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_dependency_lock.py
index 7f90b327a..d3faa5682 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_dependency_lock.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_dependency_lock.py
@@ -40,6 +40,7 @@ def test_plugin_runtime_lock_dependencies_dry_run_returns_lockfile_template(tmp_
assert payload['outputFile'] == str(backend_root / 'plugins' / 'demo' / 'plugin.lock.yaml')
assert payload['written'] is False
assert payload['entryCount'] == EXPECTED_LOCK_ENTRY_COUNT
+ assert isinstance(payload['warnings'], list)
assert 'resolvedVersion' in payload['warnings'][0]
assert not (backend_root / 'plugins' / 'demo' / 'plugin.lock.yaml').exists()
@@ -87,6 +88,7 @@ def test_plugin_runtime_lock_dependencies_rejects_existing_file_without_overwrit
assert payload['ok'] is False
assert payload['written'] is False
assert payload['outputFile'] == str(lockfile_path)
+ assert isinstance(payload['message'], str)
assert '已存在' in payload['message']
assert lockfile_path.read_text(encoding='utf-8') == 'plugin: existing\n'
@@ -172,6 +174,7 @@ def test_plugin_runtime_lock_dependencies_warns_when_offline_artifact_missing(tm
assert payload['ok'] is True
assert payload['artifactCount'] == 0
+ assert isinstance(payload['warnings'], list)
assert any('未找到离线制品:python openai' in warning for warning in payload['warnings'])
assert any('未找到离线制品:npm dayjs' in warning for warning in payload['warnings'])
lockfile = yaml.safe_load(payload['lockfile'])
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_gateway.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_gateway.py
index d14a3e0d8..2f5474586 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_gateway.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_gateway.py
@@ -1,6 +1,9 @@
from pathlib import Path
+import pytest
+
from cli.runtime.plugin.service import CliPluginRuntimeService
+from plugins.core.runtime.service.lifecycle_lock import NoopPluginLifecycleLock
from plugins.core.validation.dependencies import PluginDependencyChecker
from tests.cli.runtime.plugin.conftest import (
FakePluginRuntimeGateway,
@@ -48,12 +51,12 @@ def test_plugin_runtime_core_runtime_initializes_without_getattr_recursion(tmp_p
assert core_runtime is not runtime
-def test_plugin_runtime_exposes_only_cli_workflow_surface(tmp_path: Path) -> None:
+def test_plugin_runtime_exposes_only_cli_workflow_surface(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""校验 CLI 运行时只暴露命令工作流所需接口。"""
backend_root = tmp_path / 'ruoyi-fastapi-backend'
backend_root.mkdir()
runtime = build_runtime(backend_root)
- runtime.core_runtime.dynamic_core_only = 'hidden'
+ monkeypatch.setattr(runtime.core_runtime, 'dynamic_core_only', 'hidden', raising=False)
assert not hasattr(runtime, '_missing_internal')
assert not hasattr(runtime, 'dynamic_core_only')
@@ -86,17 +89,31 @@ def test_plugin_runtime_dependencies_are_exposed_through_container(tmp_path: Pat
runtime_gateway = FakePluginRuntimeGateway()
runtime = build_runtime_with_gateway(backend_root, runtime_gateway)
+ assert runtime.dependencies.runtime_environment is not None
assert runtime.dependencies.runtime_environment.get_backend_dir() == str(backend_root)
assert runtime.dependencies.management_gateway is runtime_gateway
assert runtime.dependencies.model_gateway is runtime_gateway
assert runtime.dependencies.command_gateway is runtime_gateway
+def test_injected_management_gateway_supplies_default_model_and_command_gateways(tmp_path: Path) -> None:
+ """单独注入管理网关时,模型构建和命令执行均使用该网关。"""
+ gateway = FakePluginRuntimeGateway()
+ runtime = CliPluginRuntimeService(
+ runtime_environment=FakeRuntimeEnvironment(tmp_path),
+ management_gateway=gateway,
+ )
+
+ assert runtime.core_runtime.dependencies.config_gateway is gateway
+ assert runtime.core_runtime.dependencies.model_gateway is gateway
+ assert runtime.core_runtime.dependencies.command_gateway is gateway
+
+
def test_plugin_runtime_passes_lifecycle_lock_to_core_runtime(tmp_path: Path) -> None:
"""校验 CLI 创建核心插件运行时时会显式注入生命周期锁。"""
backend_root = tmp_path / 'ruoyi-fastapi-backend'
backend_root.mkdir()
- lifecycle_lock = object()
+ lifecycle_lock = NoopPluginLifecycleLock()
runtime = CliPluginRuntimeService(
runtime_environment=FakeRuntimeEnvironment(backend_root),
dependency_checker=PluginDependencyChecker(),
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_react_scaffold.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_react_scaffold.py
index 9f9e397e9..2d9d8f466 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_react_scaffold.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_react_scaffold.py
@@ -1,6 +1,7 @@
import json
import shutil
import subprocess
+from functools import partial
from pathlib import Path
import pytest
@@ -36,14 +37,16 @@ def test_react_scaffold_generates_checkable_files_and_route_test(
backend_root=backend, frontend_root=frontend if selection == 'package' else container
)
runtime = CliPluginRuntimeService(runtime_environment=environment)
- kwargs = {'frontend_framework': 'react'} if selection == 'explicit' else {}
- preview = runtime.create_plugin('react_demo', template=template, dry_run=True, **kwargs)
+ create = partial(runtime.create_plugin, 'react_demo', template=template)
+ if selection == 'explicit':
+ create = partial(create, frontend_framework='react')
+ preview = create(dry_run=True)
assert preview['ok'] is True
assert preview['frontendFramework'] == 'react'
assert not (backend / 'plugins' / 'react_demo').exists()
assert not (frontend / 'plugins' / 'react_demo').exists()
- created = runtime.create_plugin('react_demo', template=template, **kwargs)
+ created = create()
assert created['ok'] is True
view = frontend / 'plugins' / 'react_demo' / 'views' / 'index.jsx'
api = frontend / 'plugins' / 'react_demo' / 'api' / 'react_demo.js'
@@ -59,9 +62,10 @@ def test_react_scaffold_generates_checkable_files_and_route_test(
)
checked = react_runtime.core_runtime.check_plugin('react_demo')
assert checked['ok'] is True, checked
+ assert isinstance(checked['checks'], list)
assert checked['checks'][0]['structureErrors'] == []
before = {path: path.read_bytes() for path in frontend.rglob('*') if path.is_file()}
- conflict = runtime.create_plugin('react_demo', template=template, **kwargs)
+ conflict = create()
assert conflict['ok'] is False
assert before == {path: path.read_bytes() for path in frontend.rglob('*') if path.is_file()}
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold.py
index 1426313d8..c5ec87894 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold.py
@@ -3,6 +3,7 @@
import pytest
+from cli.runtime.plugin.gateway import PluginRuntimeGateway
from cli.runtime.plugin.service import CliPluginRuntimeService
from plugins.core.discovery.scanner import PluginScanner
from plugins.core.environment import PluginRuntimeEnvironmentService
@@ -24,7 +25,7 @@ def write_frontend_package(frontend_root: Path, dependencies: dict[str, str]) ->
)
-class LazyPluginGateway:
+class LazyPluginGateway(PluginRuntimeGateway):
"""
测试用 CLI 插件网关,验证开发者能力可懒解析运行时依赖。
@@ -92,6 +93,7 @@ def test_plugin_runtime_create_plugin_dry_run_does_not_write_files(tmp_path: Pat
assert payload['test'] is True
assert payload['backendTest'] is True
assert payload['frontendTest'] is True
+ assert isinstance(payload['targetDirs'], list)
assert str(backend_root / 'tests' / 'plugins' / 'demo') in payload['targetDirs']
assert (
str(project_root / 'ruoyi-fastapi-frontend' / 'vue3' / 'web' / 'tests' / 'plugins' / 'demo')
@@ -192,6 +194,7 @@ def test_plugin_runtime_create_plugin_supports_frontend_framework_override(tmp_p
dry_run=True,
)
+ assert isinstance(payload['files'], list)
view_payload = next(file for file in payload['files'] if str(file['path']).endswith('/views/index.vue'))
assert payload['ok'] is True
assert payload['frontendFramework'] == 'vue2'
@@ -298,6 +301,7 @@ def test_plugin_runtime_create_plugin_generates_checkable_template(tmp_path: Pat
assert create_payload['ok'] is True
assert check_payload['ok'] is True
+ assert isinstance(check_payload['checks'], list)
assert check_payload['checks'][0]['structureErrors'] == []
assert check_payload['checks'][0]['manifestWarnings'] == []
assert (backend_root / 'plugins' / 'demo' / 'plugin.yaml').is_file()
@@ -345,6 +349,7 @@ def test_plugin_runtime_create_plugin_supports_optional_scaffold_parts(tmp_path:
assert create_payload['config'] is False
assert create_payload['test'] is False
assert check_payload['ok'] is True
+ assert isinstance(check_payload['checks'], list)
assert check_payload['checks'][0]['structureErrors'] == []
assert not (project_root / 'ruoyi-fastapi-frontend' / 'vue3' / 'web' / 'plugins' / 'demo').exists()
assert not (backend_root / 'plugins' / 'demo' / 'jobs.py').exists()
@@ -421,6 +426,7 @@ def test_plugin_runtime_create_plugin_supports_crud_page_template(tmp_path: Path
assert create_payload['crud'] is True
assert create_payload['job'] is False
assert check_payload['ok'] is True
+ assert isinstance(check_payload['checks'], list)
assert check_payload['checks'][0]['manifestWarnings'] == []
assert (backend_root / 'plugins' / 'demo' / 'controller' / 'demo_controller.py').is_file()
assert (backend_root / 'plugins' / 'demo' / 'service' / 'demo_service.py').is_file()
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold_v2.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold_v2.py
index b4da97897..613489be1 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold_v2.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold_v2.py
@@ -5,6 +5,7 @@
import runpy
import subprocess
import sys
+from collections.abc import Sequence
from pathlib import Path
from types import SimpleNamespace
@@ -24,17 +25,20 @@
TEMPLATES = ('python-asgi', 'python-bundle', 'rust-asgi', 'rust-bundle')
-def generate(tmp_path: Path, template: str, **kwargs: object) -> tuple[dict, Path]:
+def generate(tmp_path: Path, template: str, *, dry_run: bool = False, test: bool = True) -> tuple[dict, Path]:
"""
在临时宿主目录中生成指定 v2 模板。
:param tmp_path: pytest 为当前用例创建的临时目录
:param template: 用于生成文件的模板
- :param kwargs: 传给被调用对象的关键字参数
+ :param dry_run: 是否只预览生成结果
+ :param test: 是否包含测试文件
:return: 生成结果及生成的插件目录
"""
backend = tmp_path / 'backend'
- payload = build_runtime(backend, frontend_root=FRONTEND_ROOT).create_plugin(PLUGIN_ID, template=template, **kwargs)
+ payload = build_runtime(backend, frontend_root=FRONTEND_ROOT).create_plugin(
+ PLUGIN_ID, template=template, dry_run=dry_run, test=test
+ )
assert payload['ok'], payload
return payload, backend / 'plugin-projects' / PLUGIN_ID
@@ -70,7 +74,7 @@ def write_bundle(source: Path) -> None:
(dist / 'assets' / 'app.js').write_text('export const built = true\n', encoding='utf-8')
-def write_release_files(source: Path, names: list[object]) -> None:
+def write_release_files(source: Path, names: Sequence[object]) -> None:
"""
为隔离工程写入受控交付清单,允许传入非法项供拒绝路径测试。
@@ -78,7 +82,7 @@ def write_release_files(source: Path, names: list[object]) -> None:
:param names: 清单中的完整文件列表
"""
(source / 'release-files.json').write_text(
- json.dumps({'schemaVersion': 1, 'files': names}, ensure_ascii=False), encoding='utf-8'
+ json.dumps({'schemaVersion': 1, 'files': list(names)}, ensure_ascii=False), encoding='utf-8'
)
@@ -98,6 +102,7 @@ def test_v2_templates_create_independent_projects_without_importing_or_installin
assert plugin.manifest.id == PLUGIN_ID
serialized = plugin.manifest.model_dump_json(by_alias=True)
assert type(plugin.manifest).model_validate_json(serialized) == plugin.manifest
+ assert plugin.manifest.backend.asgi is not None
assert plugin.manifest.backend.asgi.mount_path == f'/apps/{PLUGIN_ID}'
assert payload['sourceDir'] == source.as_posix()
assert payload['frontendFramework'] is None
@@ -174,6 +179,7 @@ def test_bundle_template_preserves_independent_host_framework_with_auto_option(t
assert payload['ok'] is True
assert payload['frontendFramework'] is None
+ assert isinstance(payload['files'], list)
metadata = next(item for item in payload['files'] if item['path'].endswith('/pluginBridge.sdk.json'))
assert json.loads(metadata['content'])['source']['directory'] == (
'ruoyi-fastapi-frontend/custom_ui-1/web/src/utils'
@@ -302,6 +308,7 @@ def test_v2_templates_reject_incompatible_legacy_options(
PLUGIN_ID, template=template, **options
)
assert payload['ok'] is False
+ assert isinstance(payload['error'], str)
assert error in payload['error']
assert not (tmp_path / 'backend' / 'plugin-projects').exists()
@@ -310,6 +317,7 @@ def test_bundle_template_requires_verified_host_sdk_and_no_test_is_honored(tmp_p
"""验证 bundle 需要宿主桥接 SDK,且遵守不生成测试的选项。"""
missing = build_runtime(tmp_path / 'backend').create_plugin(PLUGIN_ID, template='python-bundle')
assert missing['ok'] is False
+ assert isinstance(missing['error'], str)
assert '桥接 SDK' in missing['error']
assert not (tmp_path / 'backend' / 'plugin-projects').exists()
payload, source = generate(tmp_path, 'python-bundle', test=False)
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_testing.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_testing.py
index ea1be1697..b4fd99474 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_testing.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_testing.py
@@ -2,6 +2,7 @@
from pathlib import Path
from subprocess import CompletedProcess
+from cli.runtime.plugin.gateway import PluginRuntimeGateway
from cli.runtime.plugin.service import CliPluginRuntimeService
from .conftest import (
@@ -13,7 +14,7 @@
)
-class LazyPluginGateway:
+class LazyPluginGateway(PluginRuntimeGateway):
"""
测试用 CLI 插件网关,验证测试命令可懒解析运行时依赖。
@@ -100,6 +101,7 @@ def test_plugin_runtime_test_plugin_runs_pytest_target(tmp_path: Path) -> None:
assert result['message'] == '插件测试执行完成'
assert result['pluginId'] == 'demo'
assert result['targets'] == [str(test_root)]
+ assert isinstance(result['test'], dict)
assert result['test']['returnCode'] == 0
assert gateway.commands[0][0] == [
sys.executable,
@@ -132,6 +134,7 @@ def test_plugin_runtime_test_plugin_runs_backend_and_frontend_targets(tmp_path:
assert result['targets'] == [str(backend_test_root), str(frontend_test_file)]
assert result['test'] is None
assert result['command'] is None
+ assert isinstance(result['results'], list)
assert [item['kind'] for item in result['results']] == ['backend', 'frontend']
assert gateway.commands[0][0] == [sys.executable, '-m', 'pytest', str(backend_test_root)]
assert gateway.commands[0][1] == str(backend_root)
@@ -172,6 +175,7 @@ def test_plugin_runtime_test_plugin_can_run_frontend_build_acceptance(tmp_path:
assert result['ok'] is True
assert result['frontendBuild'] is True
+ assert isinstance(result['results'], list)
assert [item['kind'] for item in result['results']] == ['backend', 'frontend-build']
assert result['targets'] == [str(backend_test_root), str(frontend_root)]
assert gateway.commands[0][0] == [sys.executable, '-m', 'pytest', str(backend_test_root)]
@@ -187,6 +191,7 @@ def test_plugin_runtime_test_plugin_reports_missing_test_dir(tmp_path: Path) ->
result = build_runtime(backend_root).test_plugin('demo')
assert result['ok'] is False
+ assert isinstance(result['message'], str)
assert result['message'].startswith('插件测试目录不存在')
assert result['targets'] == [
str(backend_root / 'tests' / 'plugins' / 'demo'),
@@ -231,6 +236,7 @@ def test_plugin_runtime_test_plugin_reports_pytest_failure(tmp_path: Path) -> No
assert result['ok'] is False
assert result['message'] == '插件测试执行失败'
+ assert isinstance(result['test'], dict)
assert result['test']['returnCode'] == 1
assert result['test']['stderr'] == 'failed\n'
@@ -250,5 +256,6 @@ def test_plugin_runtime_test_plugin_truncates_command_output(tmp_path: Path) ->
result = build_runtime_with_gateway(backend_root, gateway).test_plugin('demo')
assert result['ok'] is True
+ assert isinstance(result['test'], dict)
assert result['test']['stdout'] == 'x' * 4000
assert result['test']['stderr'] == 'y' * 4000
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_config.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_config.py
index f41f4b113..58f97dbeb 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_config.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_config.py
@@ -4,6 +4,7 @@
from cli.runtime.config import ConfigRuntimeService
from cli.runtime.config.gateway import ConfigInfrastructureGateway
from cli.runtime.config.support import ConfigDomainSupport
+from module_admin.entity.vo import config_vo
MISSING_CONFIG_KEY = 'sys.demo.key'
@@ -90,34 +91,10 @@ class FakeOrmConfigRecord:
update_time = None
remark = '初始化密码 123456'
- class FakeConfigModel:
- """
- 模拟 VO 配置模型。
-
- :ivar kwargs: 传给被调用对象的关键字参数
- """
-
- def __init__(self, **kwargs: object) -> None:
- """
- 初始化测试夹具的 ``kwargs``。
-
- :param kwargs: 传给被调用对象的关键字参数
- """
- self.kwargs = kwargs
-
- class FakeConfigVoModule:
- """
- 模拟配置 VO 模块。
-
- :cvar ConfigModel: 测试暴露的配置模型
- """
-
- ConfigModel = FakeConfigModel
-
- model = ConfigRuntimeService.build_cli_config_model(FakeConfigVoModule, FakeOrmConfigRecord())
+ model = ConfigRuntimeService.build_cli_config_model(config_vo, FakeOrmConfigRecord())
- assert isinstance(model, FakeConfigModel)
- assert model.kwargs == {
+ assert isinstance(model, config_vo.ConfigModel)
+ assert model.model_dump(by_alias=True) == {
'configId': 2,
'configName': '用户管理-账号初始密码',
'configKey': 'sys.user.initPassword',
@@ -208,7 +185,7 @@ async def get_config_detail_by_info(session: FakeSession, config_model: FakeConf
:param config_model: 配置模型
"""
assert isinstance(session, FakeSession)
- assert config_model.kwargs == {'configKey': MISSING_CONFIG_KEY}
+ assert config_model.kwargs == {'config_key': MISSING_CONFIG_KEY}
gateway = ConfigInfrastructureGateway()
service = ConfigRuntimeService(infrastructure_gateway=gateway)
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_dev.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_dev.py
index 9f716577b..9f3f74c2a 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_dev.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_dev.py
@@ -5,6 +5,28 @@
from cli.runtime.dev import DevelopmentRuntimeService
from cli.runtime.dev.gateway import DevelopmentProcessGateway
from cli.runtime.dev.support import DevelopmentCommandSupport, DevelopmentToolingSupport
+from scripts.check_types import BACKEND, CI, E2E, project_targets
+
+
+def test_dev_lint_rejects_new_type_error(tmp_path: Path) -> None:
+ """验证新增类型错误使 CLI 失败,修正同一文件后通过。"""
+ target = tmp_path / 'example.py'
+ target.write_text("answer: int = '42'\n", encoding='utf-8')
+ runtime = DevelopmentRuntimeService()
+ failure = runtime.run_lint([str(target)], check_only=True)
+ assert failure['docstrings']['ok']
+ assert not failure['ok']
+ assert failure['exit_code'] == RUNTIME_ERROR
+ assert 'invalid-assignment' in failure['ty']['stdout']
+ target.write_text('answer: int = 42\n', encoding='utf-8')
+ assert runtime.run_lint([str(target)], check_only=True)['ok']
+
+
+def test_ty_uses_separate_project_roots() -> None:
+ """验证整仓或混合路径检查按实际导入根目录分组。"""
+ assert project_targets([BACKEND.parent]) == {root: [root] for root in (BACKEND, E2E, CI)}
+ targets = [BACKEND / 'common', E2E / 'common', CI / 'scripts', CI / 'tests']
+ assert project_targets(targets) == {BACKEND: targets[:1], E2E: targets[1:2], CI: targets[2:]}
def test_lint_reports_route_metadata_even_when_function_has_docstring(tmp_path: Path) -> None:
@@ -174,4 +196,5 @@ def run_command(self, command: list[str]) -> dict[str, object]:
['format-command'],
['check-command'],
['/usr/bin/python3', 'scripts/check_docstrings.py', 'tests/cli'],
+ ['/usr/bin/python3', 'scripts/check_types.py', 'tests/cli'],
]
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/test_job.py b/ruoyi-fastapi-backend/tests/cli/runtime/test_job.py
index 52e3bff52..a1d78e0e9 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/test_job.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/test_job.py
@@ -197,7 +197,7 @@ async def test_job_operation_retains_execution_and_sync_results(
gateway.get_redis_util.return_value.create_redis_pool = AsyncMock()
gateway.get_scheduler_manager.return_value.init_system_scheduler = AsyncMock()
gateway.get_job_service.return_value = job_service
- scheduler_support = SimpleNamespace(close_scheduler_context=AsyncMock())
+ scheduler_support = MagicMock(spec=JobSchedulerSupport, close_scheduler_context=AsyncMock())
service = JobRuntimeService(infrastructure_gateway=gateway, scheduler_support=scheduler_support)
payload = await service.run_with_scheduler_context(operation, 7)
assert payload['result'] == result
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/actions/test_action_execution.py b/ruoyi-fastapi-backend/tests/cli/tui/actions/test_action_execution.py
index d08de7db6..592e75d61 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/actions/test_action_execution.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/actions/test_action_execution.py
@@ -2,11 +2,15 @@
import importlib
import sys
from pathlib import Path
+from typing import TYPE_CHECKING
from unittest.mock import AsyncMock
import pytest
from pytest import MonkeyPatch
+if TYPE_CHECKING:
+ from cli.tui.adapters.models import BrowserRecordSnapshot
+
BACKEND_DIR = Path(__file__).resolve().parents[4]
sys.path.insert(0, str(BACKEND_DIR))
@@ -21,7 +25,7 @@
adapters_module = importlib.import_module('cli.tui.adapters')
-def build_record(key: str, title: str, *, status: str = 'ok') -> object:
+def build_record(key: str, title: str, *, status: str = 'ok') -> 'BrowserRecordSnapshot':
"""
构建动作解析测试使用的浏览记录。
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/adapters/conftest.py b/ruoyi-fastapi-backend/tests/cli/tui/adapters/conftest.py
index 8572c3cf0..7d6b07afb 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/adapters/conftest.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/adapters/conftest.py
@@ -1,9 +1,9 @@
import asyncio
import importlib
import sys
-from collections.abc import Callable
+from collections.abc import Callable, Iterator
from pathlib import Path
-from types import ModuleType
+from types import ModuleType, SimpleNamespace
import pytest
@@ -19,7 +19,7 @@ class RuntimeQueryStub:
:ivar runner: 执行命令或后台任务的对象
"""
- def __init__(self, runner: Callable[..., object]) -> None:
+ def __init__(self, runner: Callable[..., SimpleNamespace]) -> None:
"""
初始化测试夹具的 ``runner``。
@@ -307,14 +307,17 @@ async def get_config_detail(self, config_key: str) -> object:
@pytest.fixture
-def install_query_service() -> Callable[[ModuleType, Callable[..., object]], RuntimeQueryStub]:
+def install_query_service(
+ monkeypatch: pytest.MonkeyPatch,
+) -> Callable[[ModuleType, Callable[..., SimpleNamespace]], RuntimeQueryStub]:
"""
向适配器及其采集/分区协作对象注入异步查询桩。
+ :param monkeypatch: 测试结束后恢复原查询服务的夹具
:return: 供调用方使用的 ``install``
"""
- def install(module: ModuleType, runner: Callable[..., object]) -> RuntimeQueryStub:
+ def install(module: ModuleType, runner: Callable[..., SimpleNamespace]) -> RuntimeQueryStub:
"""
安装测试使用的运行时查询适配器。
@@ -335,7 +338,7 @@ def inject(target: object) -> None:
return
visited.add(id(target))
if hasattr(target, 'query_service'):
- target.query_service = query_service
+ monkeypatch.setattr(target, 'query_service', query_service)
for attribute_name in ('snapshot_collector', 'section_builder'):
child = getattr(target, attribute_name, None)
if child is not None:
@@ -462,7 +465,7 @@ def load_adapter_module() -> Callable[[str], ModuleType]:
@pytest.fixture(autouse=True)
-def dispose_async_db_engine_after_test() -> None:
+def dispose_async_db_engine_after_test() -> Iterator[None]:
"""
在每个 TUI adapter 测试结束后尝试释放全局异步数据库连接池。
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_app_ops_snapshots.py b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_app_ops_snapshots.py
index 4cadbbde3..6ad81a53b 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_app_ops_snapshots.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_app_ops_snapshots.py
@@ -9,7 +9,7 @@
async def test_collect_app_page_snapshot_builds_env_config_and_route_sections(
monkeypatch: MonkeyPatch,
app_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""应用快照包含环境、配置和路由分区。"""
@@ -181,7 +181,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_app_page_snapshot_applies_query_filter(
monkeypatch: MonkeyPatch,
app_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""应用快照按查询条件过滤。"""
@@ -250,7 +250,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_ops_page_snapshot_builds_health_dependency_and_server_sections(
monkeypatch: MonkeyPatch,
ops_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""运维快照包含健康、依赖和服务器分区。"""
@@ -354,7 +354,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_ops_page_snapshot_surfaces_health_risk_subtitle(
monkeypatch: MonkeyPatch,
ops_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""运维快照在副标题显示健康风险。"""
@@ -393,3 +393,12 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
snapshot.subtitle
== '聚焦:数据库连通性 / Redis 连通性 / 依赖版本 | 运维探活存在异常,优先核对数据库/Redis 连通性与依赖版本'
)
+
+
+def test_app_sections_handle_malformed_payloads(app_adapter: ModuleType) -> None:
+ """环境分区区分缺失与空字典,补全分区在 shell 元数据无效时使用默认值。"""
+ builder = app_adapter.AppSectionBuilder
+ assert builder.build_env_section(None).status == 'fail'
+ assert builder.build_env_section({'ok': True, 'runtime': []}).status == 'fail'
+ assert builder.build_env_section({'ok': True, 'runtime': {}}).status == 'ok'
+ assert builder.resolve_completion_preview_shell({'activeShell': 'fish', 'shells': []}) == 'bash'
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_cache_db_crypto_snapshots.py b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_cache_db_crypto_snapshots.py
index 9a0e1466b..df37c82ee 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_cache_db_crypto_snapshots.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_cache_db_crypto_snapshots.py
@@ -9,7 +9,7 @@
async def test_collect_cache_page_snapshot_builds_cache_browser_records(
monkeypatch: MonkeyPatch,
cache_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""缓存快照生成可浏览的记录。"""
calls: list[tuple[str, ...]] = []
@@ -105,7 +105,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_cache_browser_adapter_collect_snapshot_exposes_search_context(
monkeypatch: MonkeyPatch,
cache_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""缓存浏览器快照提供搜索上下文。"""
@@ -150,7 +150,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_database_page_snapshot_builds_check_heads_and_history_sections(
monkeypatch: MonkeyPatch,
database_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""数据库快照包含检查、迁移头和历史分区。"""
@@ -263,7 +263,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_database_page_snapshot_surfaces_failed_heads(
monkeypatch: MonkeyPatch,
database_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""数据库快照显示异常迁移头。"""
@@ -313,7 +313,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_database_page_snapshot_applies_query_filter(
monkeypatch: MonkeyPatch,
database_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""数据库快照按查询条件过滤。"""
@@ -355,7 +355,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_crypto_page_snapshot_builds_validate_and_public_key_sections(
monkeypatch: MonkeyPatch,
crypto_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""加密快照显示校验结果和公钥。"""
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_configs_dashboard_snapshots.py b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_configs_dashboard_snapshots.py
index 6f220bc2b..7467fb3d7 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_configs_dashboard_snapshots.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_configs_dashboard_snapshots.py
@@ -9,7 +9,7 @@
async def test_collect_dashboard_snapshot_adds_risk_heat_panel(
monkeypatch: MonkeyPatch,
health_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""仪表盘快照包含风险热度面板。"""
@@ -133,7 +133,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_dashboard_adapter_collect_snapshot_exposes_metrics(
monkeypatch: MonkeyPatch,
health_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""仪表盘适配器快照提供指标。"""
@@ -182,7 +182,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_dashboard_snapshot_uses_focus_hints_for_healthy_business_entry(
monkeypatch: MonkeyPatch,
health_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""业务入口健康时仪表盘提供焦点提示。"""
@@ -242,7 +242,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_configs_page_snapshot_surfaces_failure_message(
monkeypatch: MonkeyPatch,
configs_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""配置快照显示失败原因。"""
@@ -280,7 +280,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_configs_browser_adapter_collect_snapshot_exposes_search_context(
monkeypatch: MonkeyPatch,
configs_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""配置浏览器快照提供搜索上下文。"""
@@ -342,7 +342,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_configs_page_snapshot_builds_browser_records(
monkeypatch: MonkeyPatch,
configs_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""配置快照生成可浏览的记录。"""
calls: list[tuple[str, ...]] = []
@@ -445,7 +445,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_configs_page_snapshot_sorts_and_filters_risky_records(
monkeypatch: MonkeyPatch,
configs_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""配置快照对风险记录排序并过滤。"""
@@ -536,7 +536,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_configs_page_snapshot_applies_query_filter(
monkeypatch: MonkeyPatch,
configs_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""配置快照按查询条件过滤。"""
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_jobs_gen_snapshots.py b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_jobs_gen_snapshots.py
index 7b7f21ddb..fda52e455 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_jobs_gen_snapshots.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/adapters/test_jobs_gen_snapshots.py
@@ -9,7 +9,7 @@
async def test_collect_jobs_page_snapshot_links_first_job_detail_and_logs(
monkeypatch: MonkeyPatch,
jobs_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""任务快照关联首个任务的详情和日志。"""
calls: list[tuple[str, ...]] = []
@@ -133,7 +133,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_jobs_page_snapshot_applies_failed_filter(
monkeypatch: MonkeyPatch,
jobs_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""任务快照可筛选失败任务。"""
@@ -215,7 +215,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_jobs_page_snapshot_applies_query_filter(
monkeypatch: MonkeyPatch,
jobs_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""任务快照按查询条件过滤。"""
@@ -268,7 +268,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_jobs_page_snapshot_surfaces_failure_message(
monkeypatch: MonkeyPatch,
jobs_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""任务快照显示失败原因。"""
@@ -303,7 +303,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_collect_gen_page_snapshot_links_first_table_detail(
monkeypatch: MonkeyPatch,
gen_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""生成器快照关联首张表的详情。"""
calls: list[tuple[str, ...]] = []
@@ -468,7 +468,7 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
async def test_gen_browser_adapter_collect_snapshot_exposes_search_context(
monkeypatch: MonkeyPatch,
gen_adapter: ModuleType,
- install_query_service: Callable[[ModuleType, Callable[..., object]], object],
+ install_query_service: Callable[[ModuleType, Callable[..., SimpleNamespace]], object],
) -> None:
"""生成器浏览器快照提供搜索上下文。"""
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_command_app.py b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_command_app.py
index be7d580c4..b626db729 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_command_app.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_command_app.py
@@ -693,6 +693,13 @@ async def collect_ops(env: str, query: str = '') -> object:
assert type(app.screen).__name__ == 'DashboardScreen'
assert app.current_view == 'dashboard'
+ sidebar = app.screen.query_one(tui_modules.cli_tui_widgets.WorkspaceSidebar)
+ assert app.focused is sidebar
+ app.screen.focus_next()
+ assert app.focused is not sidebar
+ app.screen.focus_previous()
+ assert app.focused is sidebar
+
await pilot.press('down')
await app._view_task
await pilot.pause()
diff --git a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_detail_screen.py b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_detail_screen.py
index 19af9a3b3..0d79eed3a 100644
--- a/ruoyi-fastapi-backend/tests/cli/tui/test_tui_detail_screen.py
+++ b/ruoyi-fastapi-backend/tests/cli/tui/test_tui_detail_screen.py
@@ -1,10 +1,13 @@
import asyncio
from types import SimpleNamespace
-from typing import Any
+from typing import TYPE_CHECKING, Any
import pytest
from pytest import MonkeyPatch
+if TYPE_CHECKING:
+ from cli.tui.adapters.models import DetailSectionSnapshot
+
def test_detail_screen_updates_section_detail_view(tui_modules: SimpleNamespace) -> None:
"""详情界面更新分区内容。"""
@@ -24,12 +27,12 @@ def test_detail_screen_updates_section_detail_view(tui_modules: SimpleNamespace)
refreshed_at='2026-04-30 10:00:00',
)
- recorded_sections: list[object] = []
+ recorded_sections: list[DetailSectionSnapshot] = []
class FakeSectionDetailView:
"""记录传入详情视图的区块。"""
- def show_section(self, section: object, query: str = '') -> None:
+ def show_section(self, section: 'DetailSectionSnapshot', query: str = '') -> None:
"""
记录详情面板选中的区块。
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/test_cache_clear.py b/ruoyi-fastapi-backend/tests/cli/wizard/test_cache_clear.py
index 4b3bdc45e..e4b2770b2 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/test_cache_clear.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/test_cache_clear.py
@@ -1,4 +1,5 @@
from types import ModuleType, SimpleNamespace
+from unittest.mock import Mock
from pytest import MonkeyPatch
@@ -9,7 +10,7 @@ def test_cache_clear_wizard_cancels_when_confirmation_rejected(
exit_codes: ModuleType,
) -> None:
"""拒绝确认后取消清缓存操作。"""
- captured: dict[str, object] = {}
+ complete_result = Mock()
answers = iter(['dev', 'cache-name', 'sys_config', True, False])
monkeypatch.setattr(
cache_clear_flow.CacheClearWizardFlow,
@@ -30,14 +31,16 @@ def test_cache_clear_wizard_cancels_when_confirmation_rejected(
monkeypatch.setattr(
cache_clear_flow.CacheClearWizardFlow.execution_service,
'complete_result',
- lambda ctx, result: captured.update({'ctx': ctx, 'result': result}),
+ complete_result,
)
cache_clear_flow.run_cache_clear_wizard('text')
- assert captured['ctx'].env == 'dev'
- assert captured['result'].exit_code == exit_codes.GUARD_REJECTED
- assert captured['result'].data['message'] == '已取消向导执行:wizard cache-clear'
+ complete_result.assert_called_once()
+ ctx, result = complete_result.call_args.args
+ assert ctx.env == 'dev'
+ assert result.exit_code == exit_codes.GUARD_REJECTED
+ assert result.data['message'] == '已取消向导执行:wizard cache-clear'
def test_cache_clear_wizard_accepts_default_context_values(
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/test_db_upgrade.py b/ruoyi-fastapi-backend/tests/cli/wizard/test_db_upgrade.py
index 2819e50ee..80e5e001b 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/test_db_upgrade.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/test_db_upgrade.py
@@ -1,4 +1,5 @@
from types import ModuleType, SimpleNamespace
+from unittest.mock import Mock
from pytest import MonkeyPatch
@@ -8,7 +9,7 @@ def test_db_upgrade_wizard_executes_nested_cli_with_confirmed_inputs(
db_upgrade_flow: ModuleType,
) -> None:
"""数据库升级向导按确认的输入执行命令。"""
- captured: dict[str, object] = {}
+ complete_payload = Mock()
monkeypatch.setattr(
db_upgrade_flow.DbUpgradeWizardFlow,
'prompt_service',
@@ -40,21 +41,17 @@ def test_db_upgrade_wizard_executes_nested_cli_with_confirmed_inputs(
monkeypatch.setattr(
db_upgrade_flow.DbUpgradeWizardFlow.execution_service,
'complete_payload',
- lambda ctx, payload, default_exit_code=0: captured.update(
- {
- 'ctx': ctx,
- 'payload': payload,
- 'default_exit_code': default_exit_code,
- }
- ),
+ complete_payload,
)
db_upgrade_flow.run_db_upgrade_wizard('json')
- assert captured['ctx'].env == 'dev'
- assert captured['ctx'].output == 'json'
- assert captured['ctx'].dry_run is True
- assert captured['payload'] == {'ok': True, 'message': '数据库已升级到 head', 'dryRun': True}
+ complete_payload.assert_called_once()
+ ctx, payload = complete_payload.call_args.args
+ assert ctx.env == 'dev'
+ assert ctx.output == 'json'
+ assert ctx.dry_run is True
+ assert payload == {'ok': True, 'message': '数据库已升级到 head', 'dryRun': True}
def test_db_upgrade_wizard_accepts_default_context_values(
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_export.py b/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_export.py
index 9d96dc637..a8abb6b51 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_export.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_export.py
@@ -1,4 +1,5 @@
from types import ModuleType, SimpleNamespace
+from unittest.mock import Mock
from pytest import MonkeyPatch
@@ -8,7 +9,7 @@ def test_gen_export_wizard_executes_nested_cli_with_selected_tables(
gen_export_flow: ModuleType,
) -> None:
"""导出向导将选中的表传给嵌套命令。"""
- captured: dict[str, object] = {}
+ complete_payload = Mock()
answers = iter(['dev', 'sys_user,sys_role', 'zip', 'build/demo.zip', True, True])
monkeypatch.setattr(
gen_export_flow.GenExportWizardFlow,
@@ -50,22 +51,18 @@ def test_gen_export_wizard_executes_nested_cli_with_selected_tables(
monkeypatch.setattr(
gen_export_flow.GenExportWizardFlow.execution_service,
'complete_payload',
- lambda ctx, payload, default_exit_code=0: captured.update(
- {
- 'ctx': ctx,
- 'payload': payload,
- 'default_exit_code': default_exit_code,
- }
- ),
+ complete_payload,
)
gen_export_flow.run_gen_export_wizard('json')
- assert captured['ctx'].env == 'dev'
- assert captured['ctx'].output == 'json'
- assert captured['ctx'].dry_run is True
- assert captured['payload']['tableNames'] == ['sys_user', 'sys_role']
- assert captured['payload']['mode'] == 'zip'
+ complete_payload.assert_called_once()
+ ctx, payload = complete_payload.call_args.args
+ assert ctx.env == 'dev'
+ assert ctx.output == 'json'
+ assert ctx.dry_run is True
+ assert payload['tableNames'] == ['sys_user', 'sys_role']
+ assert payload['mode'] == 'zip'
def test_gen_export_wizard_accepts_default_context_values(
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_import.py b/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_import.py
index 1ac0ea839..7189b47bb 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_import.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/test_gen_import.py
@@ -1,4 +1,5 @@
from types import ModuleType, SimpleNamespace
+from unittest.mock import Mock
from pytest import MonkeyPatch
@@ -8,7 +9,7 @@ def test_gen_import_wizard_executes_nested_cli_with_selected_tables(
gen_import_flow: ModuleType,
) -> None:
"""导入向导将选中的表传给嵌套命令。"""
- captured: dict[str, object] = {}
+ complete_payload = Mock()
answers = iter(['dev', 'sys_user,sys_role', True, True])
monkeypatch.setattr(
gen_import_flow.GenImportWizardFlow,
@@ -46,21 +47,17 @@ def test_gen_import_wizard_executes_nested_cli_with_selected_tables(
monkeypatch.setattr(
gen_import_flow.GenImportWizardFlow.execution_service,
'complete_payload',
- lambda ctx, payload, default_exit_code=0: captured.update(
- {
- 'ctx': ctx,
- 'payload': payload,
- 'default_exit_code': default_exit_code,
- }
- ),
+ complete_payload,
)
gen_import_flow.run_gen_import_wizard('json')
- assert captured['ctx'].env == 'dev'
- assert captured['ctx'].output == 'json'
- assert captured['ctx'].dry_run is True
- assert captured['payload']['tableNames'] == ['sys_user', 'sys_role']
+ complete_payload.assert_called_once()
+ ctx, payload = complete_payload.call_args.args
+ assert ctx.env == 'dev'
+ assert ctx.output == 'json'
+ assert ctx.dry_run is True
+ assert payload['tableNames'] == ['sys_user', 'sys_role']
def test_gen_import_wizard_accepts_default_context_values(
@@ -112,7 +109,7 @@ def test_gen_import_wizard_falls_back_to_failure_payload_when_nested_result_has_
gen_import_flow: ModuleType,
) -> None:
"""导入命令缺少字典结果时返回失败信息。"""
- captured: dict[str, object] = {}
+ complete_payload = Mock()
answers = iter(['dev', 'sys_notice', True, True])
monkeypatch.setattr(
gen_import_flow.GenImportWizardFlow,
@@ -147,19 +144,15 @@ def test_gen_import_wizard_falls_back_to_failure_payload_when_nested_result_has_
monkeypatch.setattr(
gen_import_flow.GenImportWizardFlow.execution_service,
'complete_payload',
- lambda ctx, payload, default_exit_code=0: captured.update(
- {
- 'ctx': ctx,
- 'payload': payload,
- 'default_exit_code': default_exit_code,
- }
- ),
+ complete_payload,
)
gen_import_flow.run_gen_import_wizard('text')
- assert captured['ctx'].env == 'dev'
- assert captured['payload'] == {
+ complete_payload.assert_called_once()
+ ctx, payload = complete_payload.call_args.args
+ assert ctx.env == 'dev'
+ assert payload == {
'ok': False,
'message': '代码生成导入向导执行失败',
'error': 'OK SUCCESS\nmessage: 导入表结构演练完成,未执行实际写入',
diff --git a/ruoyi-fastapi-backend/tests/cli/wizard/test_prod_check.py b/ruoyi-fastapi-backend/tests/cli/wizard/test_prod_check.py
index 2e9ffd725..c3166114d 100644
--- a/ruoyi-fastapi-backend/tests/cli/wizard/test_prod_check.py
+++ b/ruoyi-fastapi-backend/tests/cli/wizard/test_prod_check.py
@@ -1,4 +1,5 @@
from types import ModuleType, SimpleNamespace
+from unittest.mock import Mock
from pytest import MonkeyPatch
@@ -8,7 +9,7 @@ def test_prod_check_wizard_aggregates_nested_cli_payloads(
prod_check_flow: ModuleType,
) -> None:
"""生产检查向导汇总嵌套命令的结果。"""
- captured: dict[str, object] = {}
+ complete_payload = Mock()
answers = iter(['prod', True, True])
monkeypatch.setattr(
prod_check_flow.ProdCheckWizardFlow,
@@ -69,16 +70,18 @@ def fake_run_nested_cli_command(*arguments: str, parse_json: bool = False) -> Si
monkeypatch.setattr(
prod_check_flow.ProdCheckWizardFlow.execution_service,
'complete_payload',
- lambda ctx, payload, default_exit_code=0: captured.update({'ctx': ctx, 'payload': payload}),
+ complete_payload,
)
prod_check_flow.run_prod_check_wizard('json')
- assert captured['ctx'].env == 'prod'
- assert captured['payload']['ok'] is True
- assert captured['payload']['doctor']['message'] == '应用启动前检查通过'
- assert captured['payload']['runtime']['cliEnv'] == 'prod'
- assert captured['payload']['config']['name'] == 'demo'
+ complete_payload.assert_called_once()
+ ctx, payload = complete_payload.call_args.args
+ assert ctx.env == 'prod'
+ assert payload['ok'] is True
+ assert payload['doctor']['message'] == '应用启动前检查通过'
+ assert payload['runtime']['cliEnv'] == 'prod'
+ assert payload['config']['name'] == 'demo'
def test_prod_check_wizard_accepts_default_context_values(
diff --git a/ruoyi-fastapi-backend/tests/common/test_auth_policy.py b/ruoyi-fastapi-backend/tests/common/test_auth_policy.py
index d5beb14a0..5821fece9 100644
--- a/ruoyi-fastapi-backend/tests/common/test_auth_policy.py
+++ b/ruoyi-fastapi-backend/tests/common/test_auth_policy.py
@@ -1,5 +1,4 @@
import ast
-import builtins
import subprocess
import sys
from collections.abc import AsyncIterator
@@ -133,8 +132,10 @@ def test_authentication_import_order_preserves_dependency_identity(modules: tupl
assert CurrentUserDependency().dependency == LoginService.get_current_user
dependency = inspect.signature(PreAuth.__call__).parameters['current_user'].default
assert dependency.dependency == LoginService.get_current_user
- token = inspect.signature(LoginService.get_current_user).parameters['token'].default
- assert token.dependency is oauth2_scheme
+ from fastapi.dependencies.utils import get_dependant
+
+ dependencies = get_dependant(path='/private', call=LoginService.get_current_user).dependencies
+ assert next(item.call for item in dependencies if item.name == 'token') is oauth2_scheme
""",
*modules,
)
@@ -177,7 +178,7 @@ async def database() -> AsyncIterator[object]:
yield object()
user = CurrentUserModel(
- permissions=['demo:read'], roles=['reader'], user=UserInfoModel(userId=2, userName='reader')
+ permissions=['demo:read'], roles=['reader'], user=UserInfoModel(user_id=2, user_name='reader')
)
resolver = AsyncMock(return_value=user)
monkeypatch.setattr(LoginService, '_resolve_current_user', resolver)
@@ -201,25 +202,9 @@ async def public() -> dict:
async def protected(current_user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict:
return {'userId': current_user.user.user_id}
- original_import = builtins.__import__
-
- def import_without_pre_auth(name: str, *args: object, **kwargs: object) -> object:
- """
- 模拟预认证模块不可导入时的依赖解析。
-
- :param name: 用于查找或标识当前对象的名称
- :param args: 传给被调用对象的位置参数
- :param kwargs: 传给被调用对象的关键字参数
- :raises AssertionError: 登录服务不应在执行时反向导入前置依赖
- :return: 按原导入机制取得的模块
- """
- if name == 'common.aspect.pre_auth':
- raise AssertionError('登录服务不应在执行时反向导入前置依赖')
- return original_import(name, *args, **kwargs)
-
try:
with monkeypatch.context() as import_patch:
- import_patch.setattr(builtins, '__import__', import_without_pre_auth)
+ import_patch.setitem(sys.modules, 'common.aspect.pre_auth', None)
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client:
public_response = await client.get('/public', headers={'Authorization': 'Bearer invalid'})
assert public_response.json() == {'public': True}
@@ -296,7 +281,7 @@ async def test_dependency_override_preserves_function_scope(public: bool, monkey
handle_exception(app)
add_context_cleanup_middleware(app)
app.dependency_overrides[get_db_session_provider(None)] = object
- user = CurrentUserModel(permissions=[], roles=[], user=UserInfoModel(userId=2, userName='reader'))
+ user = CurrentUserModel(permissions=[], roles=[], user=UserInfoModel(user_id=2, user_name='reader'))
resolver = AsyncMock(return_value=user)
monkeypatch.setattr(LoginService, '_resolve_current_user', resolver)
events = []
diff --git a/ruoyi-fastapi-backend/tests/common/test_data_scope.py b/ruoyi-fastapi-backend/tests/common/test_data_scope.py
index a3c2601f3..b09a5d826 100644
--- a/ruoyi-fastapi-backend/tests/common/test_data_scope.py
+++ b/ruoyi-fastapi-backend/tests/common/test_data_scope.py
@@ -7,6 +7,8 @@
from common.aspect.data_scope import GetDataScope
from common.context import RequestContext
+from module_admin.entity.do.role_do import SysRoleDept
+from module_admin.entity.do.user_do import SysUser
from module_admin.entity.vo.role_vo import RoleModel
from utils.dependency_util import DependencyUtil
@@ -18,6 +20,8 @@
([('1', '1', '0')], False, []),
([('1', '0', '2')], False, []),
([(None, '0', '0')], False, []),
+ ([('2', '0', '0')], False, [1, 2]),
+ ([('2', '0', '0'), ('2', '0', '0')], False, [1, 2, 3]),
([('5', '0', '0')], False, [1]),
([('3', '0', '0')], False, [1, 2]),
([('3', '0', '0'), ('5', '0', '0')], False, [1, 2]),
@@ -48,7 +52,7 @@ class Record:
dept_id=10,
admin=admin,
role=[
- RoleModel(roleId=index + 2, dataScope=scope, status=status, delFlag=deleted)
+ RoleModel.model_validate({'roleId': index + 2, 'dataScope': scope, 'status': status, 'delFlag': deleted})
for index, (scope, status, deleted) in enumerate(roles)
],
)
@@ -60,6 +64,9 @@ class Record:
metadata.create_all(engine)
try:
with engine.begin() as connection:
+ role_dept = SysRoleDept.get_table()
+ role_dept.create(connection)
+ connection.execute(role_dept.insert(), [{'role_id': 2, 'dept_id': 10}, {'role_id': 3, 'dept_id': 20}])
connection.execute(
table.insert(),
[
@@ -74,3 +81,32 @@ class Record:
finally:
engine.dispose()
mapper.dispose()
+
+
+@pytest.mark.parametrize(
+ ('user', 'user_alias', 'dept_alias'),
+ [
+ (None, 'user_id', 'dept_id'),
+ ({'role': [None]}, 'user_id', 'dept_id'),
+ ({'role': [{'dataScope': '5', 'status': '0', 'delFlag': '0'}]}, 'user_id', 'dept_id'),
+ ({'deptId': 10, 'role': [{'dataScope': '3', 'status': '0', 'delFlag': '0'}]}, None, None),
+ ],
+)
+def test_incomplete_data_scope_grants_no_rows(
+ monkeypatch: pytest.MonkeyPatch, user: dict | None, user_alias: str | None, dept_alias: str | None
+) -> None:
+ """用户、角色、本人标识或所需列缺失时,限制条件应拒绝全部记录。"""
+ # 绕过认证依赖,验证数据权限对异常上下文的防御行为。
+ profile = None
+ if user is not None:
+ profile = SimpleNamespace(
+ admin=False,
+ user_id=user.get('userId'),
+ dept_id=user.get('deptId'),
+ role=[RoleModel.model_validate(role) if role else None for role in user['role']],
+ )
+ current = SimpleNamespace(user=profile)
+ monkeypatch.setattr(RequestContext, 'get_current_user', lambda: current)
+ monkeypatch.setattr(DependencyUtil, 'check_exclude_routes', lambda *args, **kwargs: None)
+ condition = GetDataScope(SysUser, user_alias, dept_alias)(Request({'type': 'http'}))
+ assert str(condition) == 'false'
diff --git a/ruoyi-fastapi-backend/tests/common/test_exception_responses.py b/ruoyi-fastapi-backend/tests/common/test_exception_responses.py
index 497ea8f0e..f949ab5b7 100644
--- a/ruoyi-fastapi-backend/tests/common/test_exception_responses.py
+++ b/ruoyi-fastapi-backend/tests/common/test_exception_responses.py
@@ -115,10 +115,8 @@ async def endpoint(request: Request) -> None:
app.get('/logged', summary='获取审计后的错误响应', description='通过操作日志装饰器触发相同异常,以便比对响应。')(
Log(title='测试', business_type=BusinessType.OTHER)(endpoint)
)
- if audit_fails:
- monkeypatch.setattr(
- LogQueueService, 'enqueue_operation_log', AsyncMock(side_effect=RuntimeError('queue unavailable'))
- )
+ enqueue_log = AsyncMock(side_effect=RuntimeError('queue unavailable') if audit_fails else None)
+ monkeypatch.setattr(LogQueueService, 'enqueue_operation_log', enqueue_log)
client = TestClient(app, raise_server_exceptions=False)
plain = client.get('/plain', follow_redirects=False)
logged = client.get('/logged', follow_redirects=False)
@@ -132,4 +130,4 @@ async def endpoint(request: Request) -> None:
assert actual == expected
else:
assert not logged.content
- LogQueueService.enqueue_operation_log.assert_awaited_once()
+ enqueue_log.assert_awaited_once()
diff --git a/ruoyi-fastapi-backend/tests/common/test_model_aliases.py b/ruoyi-fastapi-backend/tests/common/test_model_aliases.py
new file mode 100644
index 000000000..2fbde8a05
--- /dev/null
+++ b/ruoyi-fastapi-backend/tests/common/test_model_aliases.py
@@ -0,0 +1,25 @@
+import pytest
+from fastapi import FastAPI, status
+from fastapi.testclient import TestClient
+
+from module_admin.entity.vo.user_vo import UpdateUserProfileModel
+
+
+@pytest.mark.parametrize('field', ['nick_name', 'nickName'])
+def test_profile_accepts_both_input_names_and_returns_camel_case(field: str) -> None:
+ """资料请求接受两种字段名,响应和接口文档统一使用驼峰别名。"""
+ app = FastAPI()
+
+ @app.post('/profile', summary='更新资料', description='校验并返回提交的用户资料。')
+ async def profile(body: UpdateUserProfileModel) -> UpdateUserProfileModel:
+ return body
+
+ profile_model = UpdateUserProfileModel(nick_name='小王')
+ with TestClient(app) as client:
+ response = client.post('/profile', json={field: '小王'})
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == profile_model.model_dump(by_alias=True)
+ assert response.json()['nickName'] == '小王'
+ schema = app.openapi()['components']['schemas']['UpdateUserProfileModel']
+ assert 'nickName' in schema['properties']
+ assert 'nick_name' not in schema['properties']
diff --git a/ruoyi-fastapi-backend/tests/common/test_pre_auth.py b/ruoyi-fastapi-backend/tests/common/test_pre_auth.py
index e1373d4c8..85631dfbc 100644
--- a/ruoyi-fastapi-backend/tests/common/test_pre_auth.py
+++ b/ruoyi-fastapi-backend/tests/common/test_pre_auth.py
@@ -1,13 +1,14 @@
import asyncio
from collections.abc import AsyncIterator, Iterator
from types import SimpleNamespace
-from typing import Annotated
-from unittest.mock import AsyncMock
+from typing import TYPE_CHECKING, Annotated
+from unittest.mock import AsyncMock, Mock
import httpx
import pytest
from fastapi import APIRouter, Depends, FastAPI, Request, status
from sqlalchemy import ColumnElement
+from sqlalchemy.ext.asyncio import AsyncSession
from common.aspect.data_scope import DataScopeDependency
from common.aspect.db_session import get_db_session_provider
@@ -24,6 +25,9 @@
from module_admin.service.login_service import LoginService, oauth2_scheme
from utils.dependency_util import DependencyUtil
+if TYPE_CHECKING:
+ from common.auth_policy import ExcludeRoute
+
USER_IDS = {'alice': 1, 'bob': 2}
TWO_AUTH_CALLS = 2
THREE_AUTH_CALLS = 3
@@ -40,9 +44,9 @@ def _user(user_id: int) -> CurrentUserModel:
permissions=[f'user:{user_id}:read'],
roles=['reader'],
user=UserInfoModel(
- userId=user_id,
- userName=f'user-{user_id}',
- role=[RoleModel(roleId=2, roleKey='reader', dataScope='5', status='0', delFlag='0')],
+ user_id=user_id,
+ user_name=f'user-{user_id}',
+ role=[RoleModel(role_id=2, role_key='reader', data_scope='5', status='0', del_flag='0')],
),
)
@@ -258,7 +262,7 @@ def test_current_user_dependency_keeps_original_oauth_token_url(auth_app: Simple
async def test_direct_calls_authenticate_each_time(monkeypatch: pytest.MonkeyPatch) -> None:
"""每次直接调用均执行认证。"""
request = Request({'type': 'http', 'headers': []})
- database = object()
+ database = AsyncSession()
resolver = AsyncMock(side_effect=[_user(USER_IDS['alice']), _user(USER_IDS['alice'])])
monkeypatch.setattr(LoginService, '_resolve_current_user', resolver)
first = await LoginService.get_current_user(request, 'alice', database)
@@ -272,7 +276,7 @@ async def test_direct_calls_authenticate_each_time(monkeypatch: pytest.MonkeyPat
async def test_failed_authentication_is_not_saved(monkeypatch: pytest.MonkeyPatch) -> None:
"""认证失败时不缓存结果。"""
request = Request({'type': 'http', 'headers': []})
- database = object()
+ database = AsyncSession()
user = _user(USER_IDS['alice'])
resolver = AsyncMock(side_effect=[AuthException(message='认证失败'), user])
monkeypatch.setattr(LoginService, '_resolve_current_user', resolver)
@@ -287,7 +291,7 @@ async def test_failed_authentication_is_not_saved(monkeypatch: pytest.MonkeyPatc
async def test_cancelled_authentication_is_not_saved(monkeypatch: pytest.MonkeyPatch) -> None:
"""取消认证时不缓存结果。"""
request = Request({'type': 'http', 'headers': []})
- database = object()
+ database = AsyncSession()
entered = asyncio.Event()
async def blocked(*args: object, **kwargs: object) -> CurrentUserModel:
@@ -382,8 +386,8 @@ async def overridden(
@pytest.mark.asyncio
async def test_calls_without_request_state_authenticate_each_time(monkeypatch: pytest.MonkeyPatch) -> None:
"""没有请求状态时每次调用均执行认证。"""
- request = SimpleNamespace()
- database = object()
+ request = Mock(spec_set=[])
+ database = AsyncSession()
resolver = AsyncMock(return_value=_user(USER_IDS['alice']))
monkeypatch.setattr(LoginService, '_resolve_current_user', resolver)
await LoginService.get_current_user(request, 'alice', database)
@@ -396,7 +400,7 @@ async def test_calls_without_request_state_authenticate_each_time(monkeypatch: p
async def test_plugin_session_validation_never_reuses_main_request_result(monkeypatch: pytest.MonkeyPatch) -> None:
"""插件会话校验独立于主请求的认证结果。"""
request = Request({'type': 'http', 'headers': []})
- database = object()
+ database = AsyncSession()
resolver = AsyncMock(return_value=_user(USER_IDS['alice']))
monkeypatch.setattr(LoginService, '_resolve_current_user', resolver)
await LoginService.get_current_user(request, 'alice', database)
@@ -409,10 +413,34 @@ async def test_plugin_session_validation_never_reuses_main_request_result(monkey
@pytest.mark.asyncio
async def test_non_string_token_keeps_auth_exception_conversion() -> None:
"""非字符串令牌仍按约定转换认证异常。"""
- request = Request({'type': 'http', 'headers': []})
- with pytest.raises(AuthException) as exc_info:
- await LoginService.get_current_user(request, b'invalid', object())
+ app = FastAPI()
+ requests: list[Request] = []
+
+ def invalid_token(request: Request) -> bytes:
+ """
+ 模拟自定义依赖返回未经解码的令牌。
+
+ :param request: 参与本次鉴权的请求
+ :return: 无效的二进制令牌
+ """
+ requests.append(request)
+ return b'invalid'
+
+ app.dependency_overrides[oauth2_scheme] = invalid_token
+
+ @app.get('/', summary='校验令牌', description='通过当前用户依赖验证令牌。', dependencies=[CurrentUserDependency()])
+ async def protected() -> None:
+ pass
+
+ async with (
+ AsyncSession() as db,
+ httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client,
+ ):
+ app.dependency_overrides[get_db_session_provider(None)] = lambda: db
+ with pytest.raises(AuthException) as exc_info:
+ await client.get('/')
assert exc_info.value.message == '用户token已失效,请重新登录'
+ (request,) = requests
assert not hasattr(request.state, '_current_user_auth')
@@ -651,7 +679,7 @@ async def test_direct_call_without_a_token_requires_login() -> None:
"""直接调用时缺少令牌必须登录。"""
request = Request({'type': 'http', 'headers': []})
with pytest.raises(AuthException) as exc_info:
- await LoginService.get_current_user(request, None, object())
+ await LoginService.get_current_user(request, None, AsyncSession())
assert exc_info.value.message == '用户未登录,请先完成登录'
@@ -884,7 +912,7 @@ async def test_explicit_oauth_dependency_returns_bare_token_and_still_requires_l
auth_app: SimpleNamespace, excluded: bool
) -> None:
"""显式 OAuth 依赖返回纯令牌并要求登录。"""
- exclude_routes = [{'path': '/token'}] if excluded else None
+ exclude_routes: list[ExcludeRoute] | None = [{'path': '/token'}] if excluded else None
@auth_app.app.get(
'/token',
@@ -1168,7 +1196,9 @@ async def test_encoded_path_separators_cannot_expand_public_routes(
) -> None:
"""编码后的分隔符无法扩大公开路由范围。"""
protected_path = f'/encoded/public{decoded}'
- rule = {'path': '/encoded/{name}', 'ignore_paths': [protected_path]} if ignore_path else {'path': '/encoded/public'}
+ rule: ExcludeRoute = (
+ {'path': '/encoded/{name}', 'ignore_paths': [protected_path]} if ignore_path else {'path': '/encoded/public'}
+ )
@auth_app.app.get(
'/encoded/{name}',
@@ -1266,6 +1296,6 @@ def test_direct_dependency_path_keeps_configured_prefix_fallback(
request = (
Request({'type': 'http', 'path': path, 'headers': []})
if with_scope
- else SimpleNamespace(url=SimpleNamespace(path=path))
+ else Mock(spec_set=['url'], url=SimpleNamespace(path=path))
)
assert DependencyUtil.get_request_path(request) == expected
diff --git a/ruoyi-fastapi-backend/tests/common/test_pydantic_annotation.py b/ruoyi-fastapi-backend/tests/common/test_pydantic_annotation.py
new file mode 100644
index 000000000..387d5fe06
--- /dev/null
+++ b/ruoyi-fastapi-backend/tests/common/test_pydantic_annotation.py
@@ -0,0 +1,42 @@
+from typing import Annotated
+
+import httpx
+import pytest
+from fastapi import Depends, FastAPI, status
+from pydantic import BaseModel, Field
+
+from common.annotation.pydantic_annotation import as_form, as_query
+
+
+@as_query
+@as_form
+class RequestFields(BaseModel):
+ """校验装饰器生成的查询和表单依赖。"""
+
+ name: str = Field(description='必填名称')
+ item_id: int = Field(alias='item-id', description='条目标识')
+ display_name: str = Field(default='', alias='label', description='展示名称')
+ label: str = Field(default='', alias='alternateName', description='备用名称')
+ tags: list[str] = Field(default_factory=list, description='附加标签')
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize('source', ['query', 'form'])
+async def test_fastapi_model_dependency_parses_aliases_and_defaults(source: str) -> None:
+ """查询和表单依赖均应解析外部别名、检查必填项,并应用默认工厂。"""
+ app = FastAPI()
+ dependency = getattr(RequestFields, f'as_{source}')
+
+ @app.post('/items', summary='校验模型参数', description='返回校验后的查询或表单参数。')
+ async def read_fields(fields: Annotated[RequestFields, Depends(dependency)]) -> RequestFields:
+ return fields
+
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client:
+ values = {'name': '测试', 'item-id': '7', 'label': '名称', 'alternateName': '别名'}
+ if source == 'query':
+ response = await client.post('/items', params=values)
+ else:
+ response = await client.post('/items', data=values)
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {**values, 'item-id': 7, 'tags': []}
+ assert (await client.post('/items')).status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
diff --git a/ruoyi-fastapi-backend/tests/common/test_query_time.py b/ruoyi-fastapi-backend/tests/common/test_query_time.py
index 283b38406..a5573ca32 100644
--- a/ruoyi-fastapi-backend/tests/common/test_query_time.py
+++ b/ruoyi-fastapi-backend/tests/common/test_query_time.py
@@ -1,11 +1,13 @@
from datetime import UTC, datetime
from typing import Annotated
+from unittest.mock import AsyncMock
import pytest
from fastapi import FastAPI, Query, status
from fastapi.testclient import TestClient
from pydantic import ValidationError
from sqlalchemy import Select
+from sqlalchemy.ext.asyncio import AsyncSession
from module_admin.dao.config_dao import ConfigDao
from module_admin.entity.vo.config_vo import ConfigPageQueryModel
@@ -20,10 +22,10 @@
def test_invalid_timezone_is_a_model_validation_error(zone: str) -> None:
"""无效时区触发模型校验错误。"""
with pytest.raises(ValidationError, match='IANA'):
- JobModel(timeZone=zone)
+ JobModel(time_zone=zone)
with pytest.raises(ValidationError, match='IANA'):
PluginJobManifest(
- id='daily', callable='module_task.scheduler_test.job', cronExpression='0 0 9 * * ?', timeZone=zone
+ id='daily', callable='module_task.scheduler_test.job', cron_expression='0 0 9 * * ?', time_zone=zone
)
@@ -51,13 +53,13 @@ def date_query(query: Annotated[ConfigPageQueryModel, Query()]) -> dict:
def test_instant_query_compares_instants_instead_of_offset_strings() -> None:
"""时间点查询按实际时刻比较。"""
- query = FileInfoQueryModel(beginTime='2026-08-28T10:00:00+08:00', endTime='2026-08-28T03:00:00Z')
+ query = FileInfoQueryModel(begin_time='2026-08-28T10:00:00+08:00', end_time='2026-08-28T03:00:00Z')
assert TimezoneUtil.rfc3339_range_to_utc(query.begin_time, query.end_time) == (
datetime(2026, 8, 28, 2, tzinfo=UTC),
datetime(2026, 8, 28, 3, tzinfo=UTC),
)
with pytest.raises(ValidationError):
- FileInfoQueryModel(beginTime='2026-08-28T03:00:00Z', endTime='2026-08-28T10:00:00+08:00')
+ FileInfoQueryModel(begin_time='2026-08-28T03:00:00Z', end_time='2026-08-28T10:00:00+08:00')
@pytest.mark.asyncio
@@ -74,21 +76,14 @@ async def test_date_query_filters_only_provided_boundaries_in_business_timezone(
monkeypatch: pytest.MonkeyPatch, boundaries: dict[str, str], expected_times: list[datetime]
) -> None:
"""日期查询按业务时区仅过滤指定的边界。"""
-
- async def capture_query(_db: object, query: Select, *args: object) -> Select:
- """
- 向调用方返回 ``query``。
-
- :param _db: 回调签名接收的数据库会话
- :param query: 限制查询结果的条件
- :param args: 传给被调用对象的位置参数
- :return: 限制查询结果的条件
- """
- return query
-
- monkeypatch.setattr(PageUtil, 'paginate', capture_query)
+ paginate = AsyncMock(return_value=[])
+ monkeypatch.setattr(PageUtil, 'paginate', paginate)
monkeypatch.setattr(TimezoneUtil, 'get_request_timezone', lambda: 'Asia/Shanghai')
- query = await ConfigDao.get_config_list(None, ConfigPageQueryModel(**boundaries))
+ await ConfigDao.get_config_list(AsyncSession(), ConfigPageQueryModel.model_validate(boundaries))
+ paginate.assert_awaited_once()
+ assert paginate.await_args is not None
+ query = paginate.await_args.args[1]
+ assert isinstance(query, Select)
sql = str(query)
assert ('sys_config.create_time >=' in sql) == ('beginTime' in boundaries)
assert ('sys_config.create_time <' in sql) == ('endTime' in boundaries)
diff --git a/ruoyi-fastapi-backend/tests/common/test_request_timezone.py b/ruoyi-fastapi-backend/tests/common/test_request_timezone.py
index 328ad1ef5..4b6a692db 100644
--- a/ruoyi-fastapi-backend/tests/common/test_request_timezone.py
+++ b/ruoyi-fastapi-backend/tests/common/test_request_timezone.py
@@ -6,6 +6,8 @@
import pytest
from fastapi import FastAPI, Request, status
from openpyxl import load_workbook
+from sqlalchemy import Select
+from sqlalchemy.ext.asyncio import AsyncSession
from common.annotation.cache_annotation import ApiCache
from common.context import RequestContext
@@ -31,7 +33,7 @@ def timezone_app(monkeypatch: pytest.MonkeyPatch) -> FastAPI:
app = FastAPI()
add_context_cleanup_middleware(app)
- async def capture_query(db: object, query: object, *args: object) -> dict:
+ async def capture_query(db: object, query: Select, *args: object) -> list[dict]:
"""
提取 SQL 语句的绑定参数。
@@ -40,7 +42,7 @@ async def capture_query(db: object, query: object, *args: object) -> dict:
:param args: 传给被调用对象的位置参数
:return: SQL 语句的绑定参数
"""
- return query.compile().params
+ return [query.compile().params or {}]
monkeypatch.setattr(PageUtil, 'paginate', capture_query)
@@ -49,13 +51,17 @@ async def capture_query(db: object, query: object, *args: object) -> dict:
)
async def date_range(request: Request, preference: str = 'auto') -> dict:
RequestContext.set_current_user(
- CurrentUserModel(permissions=[], roles=[], user=UserInfoModel(userId=1, timeZone=preference))
+ CurrentUserModel(
+ permissions=[], roles=[], user=UserInfoModel(user_id=1, user_name='reader', time_zone=preference)
+ )
)
# 交错执行多个请求,以暴露进程全局时区被覆盖的问题。
await asyncio.sleep(0)
- params = await ConfigDao.get_config_list(
- None, ConfigPageQueryModel(beginTime='2026-03-08', endTime='2026-03-08')
+ rows = await ConfigDao.get_config_list(
+ AsyncSession(), ConfigPageQueryModel(begin_time='2026-03-08', end_time='2026-03-08'), is_page=False
)
+ assert isinstance(rows, list)
+ (params,) = rows
bounds = sorted(value for value in params.values() if isinstance(value, datetime))
workbook = load_workbook(
BytesIO(ExcelUtil.export_list2excel([{'at': datetime(2026, 3, 8, 7, 30, tzinfo=UTC)}], {'at': '时间'}))
diff --git a/ruoyi-fastapi-backend/tests/common/test_router_register.py b/ruoyi-fastapi-backend/tests/common/test_router_register.py
index c35bcd5c9..72cc02372 100644
--- a/ruoyi-fastapi-backend/tests/common/test_router_register.py
+++ b/ruoyi-fastapi-backend/tests/common/test_router_register.py
@@ -1,7 +1,8 @@
import sys
from pathlib import Path
-from fastapi import FastAPI
+import pytest
+from fastapi import Depends, FastAPI
BACKEND_ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(BACKEND_ROOT))
@@ -89,7 +90,7 @@ def test_router_register_includes_plugin_management_controller() -> None:
assert str(project_root / 'module_plugin' / 'controller' / 'plugin_controller.py') in controller_files
-def test_auto_register_routers_uses_builtin_controller_registration(monkeypatch: object) -> None:
+def test_auto_register_routers_uses_builtin_controller_registration(monkeypatch: pytest.MonkeyPatch) -> None:
"""校验 auto_register_routers 保持内置 controller 注册语义。"""
called = []
@@ -119,7 +120,9 @@ def register_routers(self) -> None:
assert called == [True]
-def test_router_register_register_routers_uses_common_controller_file_pipeline(tmp_path: Path) -> None:
+def test_router_register_register_routers_uses_common_controller_file_pipeline(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
"""校验内置路由注册复用统一 controller 文件注册流水线。"""
project_root = tmp_path / 'backend'
builtin_controller = touch_file(project_root / 'module_demo' / 'controller' / 'demo_controller.py')
@@ -134,14 +137,14 @@ def fake_register_controller_files(controller_files: list[str]) -> None:
"""
captured_controller_files.extend(controller_files)
- router_register._register_controller_files = fake_register_controller_files
+ monkeypatch.setattr(router_register, '_register_controller_files', fake_register_controller_files)
router_register.register_routers()
assert captured_controller_files == [str(builtin_controller)]
-def test_auto_register_controller_files_delegates_to_router_register(monkeypatch: object) -> None:
+def test_auto_register_controller_files_delegates_to_router_register(monkeypatch: pytest.MonkeyPatch) -> None:
"""校验指定 controller 文件自动注册函数委托给 RouterRegister。"""
captured_controller_files = []
captured_dependencies = []
@@ -175,7 +178,7 @@ def _register_controller_files(
monkeypatch.setattr('common.router.RouterRegister', FakeRouterRegister)
- dependency = object()
+ dependency = Depends(lambda: None)
auto_register_controller_files(FastAPI(), ['demo_controller.py'], dependencies=[dependency])
assert captured_controller_files == ['demo_controller.py']
diff --git a/ruoyi-fastapi-backend/tests/common/test_types.py b/ruoyi-fastapi-backend/tests/common/test_types.py
index da3bdcc5a..561e6354f 100644
--- a/ruoyi-fastapi-backend/tests/common/test_types.py
+++ b/ruoyi-fastapi-backend/tests/common/test_types.py
@@ -27,7 +27,7 @@ class TestApiUtcDateTime:
)
def test_aware_inputs_keep_the_same_instant(self, value: object) -> None:
"""带时区的输入保留同一时刻。"""
- model = TimestampModel(occurred_at=value)
+ model = TimestampModel.model_validate({'occurred_at': value})
assert model.occurred_at == datetime(2026, 8, 28, 2, 30, 0, 123000, tzinfo=UTC)
assert model.occurred_at.tzinfo is UTC
@@ -51,7 +51,7 @@ def test_aware_inputs_keep_the_same_instant(self, value: object) -> None:
def test_datetime_requires_a_complete_valid_rfc3339_instant(self, value: object) -> None:
"""日期时间必须是完整有效的 RFC 3339 时刻。"""
with pytest.raises(ValidationError, match='RFC 3339'):
- TimestampModel(occurred_at=value)
+ TimestampModel.model_validate({'occurred_at': value})
class TestDbUtcDateTime:
@@ -89,9 +89,11 @@ def test_database_roundtrip_preserves_utc_and_millisecond_precision(
value = datetime(2026, 8, 28, 10, 30, 0, 123456, tzinfo=timezone(timedelta(hours=8)))
stored = column_type.process_bind_param(value, dialect)
+ assert stored is not None
assert stored == datetime(2026, 8, 28, 2, 30, 0, 123000, tzinfo=stored_timezone)
assert stored.tzinfo is stored_timezone
restored = column_type.process_result_value(stored, dialect)
+ assert restored is not None
assert restored == datetime(2026, 8, 28, 2, 30, 0, 123000, tzinfo=UTC)
assert restored.tzinfo is UTC
diff --git a/ruoyi-fastapi-backend/tests/config/test_current_user_cache_resources.py b/ruoyi-fastapi-backend/tests/config/test_current_user_cache_resources.py
index dda1490ca..be25bca59 100644
--- a/ruoyi-fastapi-backend/tests/config/test_current_user_cache_resources.py
+++ b/ruoyi-fastapi-backend/tests/config/test_current_user_cache_resources.py
@@ -15,6 +15,7 @@
CacheUser,
cache_transactions, # noqa: F401
)
+from tests.config.test_database_registry import _settings, _source
from utils.cache_util import CurrentUserCacheUtil
@@ -171,9 +172,7 @@ def _registry(env: SimpleNamespace) -> _DataSourceRegistry:
:param env: 当前运行环境
:return: 供调用方使用的 ``registry``
"""
- registry = _DataSourceRegistry(
- SimpleNamespace(db_default_source='primary', db_sources={'primary': object(), 'reporting': object()})
- )
+ registry = _DataSourceRegistry(_settings(primary=_source(), reporting=_source()))
for name in ('primary', 'reporting'):
runtime = registry._runtime(name)
runtime.async_engine = env.engine
@@ -199,7 +198,9 @@ async def test_registry_sessions_borrow_registered_cache_client(
async with registry.session(source, log_sql=log_sql) as db:
assert db.info[CurrentUserCacheSession._REDIS_KEY] is redis
assert isinstance(db.sync_session, CurrentUserCacheSession)
- assert (await db.get(CacheUser, 1)).user_name == 'first'
+ user = await db.get(CacheUser, 1)
+ assert user is not None
+ assert user.user_name == 'first'
finally:
await registry.dispose_all()
assert registry._cache_redis is None
diff --git a/ruoyi-fastapi-backend/tests/config/test_current_user_cache_settings.py b/ruoyi-fastapi-backend/tests/config/test_current_user_cache_settings.py
index 5213b2965..2170a67fe 100644
--- a/ruoyi-fastapi-backend/tests/config/test_current_user_cache_settings.py
+++ b/ruoyi-fastapi-backend/tests/config/test_current_user_cache_settings.py
@@ -43,7 +43,7 @@ def test_current_user_cache_environment_configuration(monkeypatch: pytest.Monkey
def test_environment_templates_include_current_user_cache_settings(environment: str) -> None:
"""各部署环境明确提供缓存开关及默认硬过期时间。"""
environment_file = Path(__file__).resolve().parents[2] / f'.env.{environment}'
- content = environment_file.read_text()
+ content = environment_file.read_text(encoding='utf-8')
assert 'APP_CURRENT_USER_CACHE_ENABLED = true' in content
assert 'APP_CURRENT_USER_CACHE_TTL_SECONDS = 5' in content
diff --git a/ruoyi-fastapi-backend/tests/config/test_current_user_cache_transactions.py b/ruoyi-fastapi-backend/tests/config/test_current_user_cache_transactions.py
index e1ddaa6df..f30c91ed5 100644
--- a/ruoyi-fastapi-backend/tests/config/test_current_user_cache_transactions.py
+++ b/ruoyi-fastapi-backend/tests/config/test_current_user_cache_transactions.py
@@ -11,6 +11,7 @@
import pytest_asyncio
from redis.exceptions import ConnectionError as RedisConnectionError
from sqlalchemy import (
+ Alias,
Column,
Integer,
String,
@@ -41,6 +42,15 @@
class CacheTestBase(DeclarativeBase):
"""提供缓存集成测试的声明式模型基类。"""
+ @classmethod
+ def core_table(cls) -> Table:
+ """
+ 获取已注册的 SQLAlchemy 表,用于构造 Core 语句。
+
+ :return: 当前映射模型的数据库表
+ """
+ return cls.metadata.tables[cls.__tablename__]
+
class CacheUser(CacheTestBase):
"""缓存集成测试使用的用户表映射。"""
@@ -247,9 +257,10 @@ async def test_alias_mutations_invalidate_only_auth_tables(
target = aliased(model)
target_id = getattr(target, id_column)
else:
- target = model.__table__.alias()
+ target = model.core_table().alias()
if alias_type == 'nested':
target = target.alias()
+ assert isinstance(target, Alias)
target_id = target.c[id_column]
statement = update(target).values({name_column: 'changed'}) if operation == 'update' else delete(target)
async with env.sessions.begin() as db:
@@ -275,8 +286,9 @@ async def test_alias_target_with_original_table_filter_invalidates_all_users(
) -> None:
"""别名目标使用原表过滤时使全部用户缓存失效。"""
env = cache_transactions
- users = CacheUser.__table__
+ users = CacheUser.core_table()
target = users.alias('target')
+ assert isinstance(target, Alias)
statement = update(target).where(users.c.user_id == 1).values(user_name=target.c.user_name + '-changed')
async with env.sessions.begin() as db:
with pytest.warns(SAWarning, match='cartesian product'):
@@ -346,7 +358,7 @@ def test_nested_dml_cte_invalidates_auth_writes_conservatively(
) -> None:
"""嵌套 DML 公用表表达式按保守策略使认证缓存失效。"""
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', True)
- target = CacheUser.__table__ if auth_table else CacheJob.__table__
+ target = CacheUser.core_table() if auth_table else CacheJob.core_table()
id_column, name_column = ('user_id', 'user_name') if auth_table else ('job_id', 'job_name')
if operation == 'insert':
mutation = insert(target).values({id_column: 3, name_column: 'created'})
@@ -358,9 +370,11 @@ def test_nested_dml_cte_invalidates_auth_writes_conservatively(
if outer == 'select':
statement = select(nested)
elif outer == 'user_update':
- statement = update(CacheUser.__table__).where(CacheUser.user_id == 1).values(user_name='outer').add_cte(nested)
+ statement = (
+ update(CacheUser.core_table()).where(CacheUser.user_id == 1).values(user_name='outer').add_cte(nested)
+ )
else:
- statement = update(CacheJob.__table__).where(CacheJob.job_id == 1).values(job_name='outer').add_cte(nested)
+ statement = update(CacheJob.core_table()).where(CacheJob.job_id == 1).values(job_name='outer').add_cte(nested)
assert str(statement.compile(dialect=postgresql.dialect())).startswith('WITH nested_change AS')
with CurrentUserCacheSession() as db, db.begin() as transaction:
state = SimpleNamespace(
@@ -426,8 +440,8 @@ def test_join_update_tracks_auth_tables_after_sql_execution(
) -> None:
"""连接更新在 SQL 执行后跟踪认证表。"""
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', True)
- target = model.__table__
- joined = joined_model.__table__.alias('joined')
+ target = model.core_table()
+ joined = joined_model.core_table().alias('joined')
statement = (
update(target.join(joined, target.c[id_column] == joined.c[joined_id_column]))
.where(target.c[id_column] == 1)
@@ -782,7 +796,7 @@ async def test_anyio_cancellation_finishes_cache_cleanup_and_preserves_commit(
closed = anyio.Event()
cancelled = anyio.Event()
cleanup_cancelled = anyio.Event()
- cancel_scope = None
+ cancel_scope: anyio.CancelScope
async def invalidate(*args: Any) -> None:
"""
@@ -925,7 +939,7 @@ async def test_core_bulk_update_cannot_assume_parameter_is_a_primary_key_filter(
env = cache_transactions
async with env.sessions.begin() as db:
await db.execute(
- update(CacheUser.__table__).where(CacheUser.user_id == 1), [{'user_id': 3, 'user_name': 'changed'}]
+ update(CacheUser.core_table()).where(CacheUser.user_id == 1), [{'user_id': 3, 'user_name': 'changed'}]
)
assert env.invalidations[0][0] is None
@@ -937,7 +951,7 @@ async def test_user_relation_move_invalidates_old_and_new_users(
) -> None:
"""移动用户关联后同时使新旧用户缓存失效。"""
env = cache_transactions
- relation = CacheUserRole.__table__
+ relation = CacheUserRole.core_table()
async with env.engine.begin() as connection:
await connection.execute(insert(relation).values(user_id=1, role_id=1))
statement = update(relation).where(relation.c.user_id == 1)
@@ -968,7 +982,7 @@ async def test_user_relation_move_invalidates_old_and_new_users(
async def test_core_tuple_parameters_commit_with_precise_user_scope(cache_transactions: SimpleNamespace) -> None:
"""Core 元组参数提交后按准确的用户范围使缓存失效。"""
env = cache_transactions
- users = CacheUser.__table__
+ users = CacheUser.core_table()
statement = update(users).where(users.c.user_id == bindparam('target_id')).values(user_name=bindparam('next_name'))
parameters = ({'target_id': 1, 'next_name': 'changed-first'}, {'target_id': 2, 'next_name': 'changed-second'})
async with env.sessions.begin() as db:
diff --git a/ruoyi-fastapi-backend/tests/config/test_database_exception_handlers.py b/ruoyi-fastapi-backend/tests/config/test_database_exception_handlers.py
index 4928b8887..c451502a5 100644
--- a/ruoyi-fastapi-backend/tests/config/test_database_exception_handlers.py
+++ b/ruoyi-fastapi-backend/tests/config/test_database_exception_handlers.py
@@ -1,7 +1,8 @@
import json
+from inspect import isawaitable
import pytest
-from fastapi import FastAPI, status
+from fastapi import FastAPI, Request, status
from common.constant import HttpStatusConstant
from exceptions.exception import (
@@ -28,8 +29,9 @@ async def test_data_source_exceptions_use_service_exception_handler(exception: E
handle_exception(app)
handler = app.exception_handlers[ServiceException]
- response = await handler(None, exception)
- payload = json.loads(response.body)
+ result = handler(Request({'type': 'http', 'headers': []}), exception)
+ response = await result if isawaitable(result) else result
+ payload = json.loads(bytes(response.body))
assert response.status_code == status.HTTP_200_OK
assert payload['code'] == HttpStatusConstant.ERROR
diff --git a/ruoyi-fastapi-backend/tests/config/test_database_registry.py b/ruoyi-fastapi-backend/tests/config/test_database_registry.py
index 23e464e05..2bfbf6b16 100644
--- a/ruoyi-fastapi-backend/tests/config/test_database_registry.py
+++ b/ruoyi-fastapi-backend/tests/config/test_database_registry.py
@@ -1,28 +1,28 @@
-from collections.abc import AsyncGenerator
-from contextlib import asynccontextmanager
from types import SimpleNamespace
-from typing import Self
+from typing import Literal, Self
from unittest.mock import AsyncMock, MagicMock, call
import pytest
from sqlalchemy import URL
from sqlalchemy.exc import OperationalError
+from sqlalchemy.ext.asyncio import async_sessionmaker
from common.aspect.db_session import DBSessionDependency, get_db_session_provider
from config import database
+from config.env import DataBaseSettings, DataSourceSettings
from exceptions.exception import DataSourceInitializationException, DataSourceUnavailableException
EXPECTED_CONNECT_TIMEOUT = 7
-def _source(*, required: bool = True) -> SimpleNamespace:
+def _source(*, required: bool = True) -> DataSourceSettings:
"""
- 创建测试使用的 ``SimpleNamespace`` 实例。
+ 构造使用测试连接参数的数据源配置。
- :param required: 是否必须提供该字段
- :return: 测试使用的 ``SimpleNamespace`` 实例
+ :param required: 该数据源是否必须在启动时可用
+ :return: 注册表使用的数据源配置
"""
- return SimpleNamespace(
+ return DataSourceSettings(
db_type='mysql',
db_host='db.example',
db_port=3306,
@@ -39,6 +39,16 @@ def _source(*, required: bool = True) -> SimpleNamespace:
)
+def _settings(**sources: DataSourceSettings) -> DataBaseSettings:
+ """
+ 配置注册表测试使用的默认数据源和附加数据源。
+
+ :param sources: 按名称提供的各数据源配置
+ :return: 以 primary 为默认源的数据库配置
+ """
+ return DataBaseSettings(_env_file=None, db_default_source='primary', db_sources=sources)
+
+
def test_database_urls_use_structured_url_and_hide_password() -> None:
"""以结构化 URL 表示数据库地址并隐藏密码。"""
config = _source()
@@ -52,6 +62,13 @@ def test_database_urls_use_structured_url_and_hide_password() -> None:
assert 'p@ss' not in repr(async_url)
+def test_error_details_without_driver_exception() -> None:
+ """驱动原始异常缺失时,错误摘要仍能报告异常类型。"""
+ error = OperationalError('SELECT 1', {}, OSError('connection lost'))
+ error.orig = None
+ assert database._error_details(error) == ('OperationalError', None)
+
+
@pytest.mark.parametrize(
('db_type', 'db_port', 'async_timeout_key', 'sync_timeout_key'),
[
@@ -61,7 +78,7 @@ def test_database_urls_use_structured_url_and_hide_password() -> None:
)
def test_engine_factories_use_driver_specific_connect_timeout(
monkeypatch: pytest.MonkeyPatch,
- db_type: str,
+ db_type: Literal['mysql', 'postgresql'],
db_port: int,
async_timeout_key: str,
sync_timeout_key: str,
@@ -103,6 +120,8 @@ def create_sync_engine(_url: URL, **options: object) -> object:
assert database.create_sync_db_engine(config=config) is sync_engine
async_connect_args = captured_options['async']['connect_args']
sync_connect_args = captured_options['sync']['connect_args']
+ assert isinstance(async_connect_args, dict)
+ assert isinstance(sync_connect_args, dict)
assert async_connect_args[async_timeout_key] == EXPECTED_CONNECT_TIMEOUT
assert sync_connect_args[sync_timeout_key] == EXPECTED_CONNECT_TIMEOUT
if db_type == 'mysql':
@@ -202,9 +221,7 @@ async def test_health_check_rejects_non_utc_database_session(monkeypatch: pytest
engine.should_fail = False
engine.session_timezone = 'SYSTEM'
monkeypatch.setattr(database, 'create_async_db_engine', lambda config: engine)
- registry = database._DataSourceRegistry(
- SimpleNamespace(db_default_source='primary', db_sources={'primary': _source()})
- )
+ registry = database._DataSourceRegistry(_settings(primary=_source()))
with pytest.raises(DataSourceInitializationException) as exc_info:
await registry.initialize(log_enabled=False)
@@ -224,12 +241,7 @@ async def test_initialize_can_suppress_worker_startup_logs(monkeypatch: pytest.M
'create_async_db_engine',
lambda config: primary_engine if config.db_required else optional_engine,
)
- registry = database._DataSourceRegistry(
- SimpleNamespace(
- db_default_source='primary',
- db_sources={'primary': _source(), 'reporting': _source(required=False)},
- )
- )
+ registry = database._DataSourceRegistry(_settings(primary=_source(), reporting=_source(required=False)))
source_logger = MagicMock()
monkeypatch.setattr(database, 'logger', source_logger)
@@ -253,9 +265,7 @@ async def test_initialize_logs_source_name(monkeypatch: pytest.MonkeyPatch) -> N
engine = _Engine()
engine.should_fail = False
monkeypatch.setattr(database, 'create_async_db_engine', lambda config: engine)
- registry = database._DataSourceRegistry(
- SimpleNamespace(db_default_source='primary', db_sources={'primary': _source()})
- )
+ registry = database._DataSourceRegistry(_settings(primary=_source()))
source_logger = MagicMock()
monkeypatch.setattr(database, 'logger', source_logger)
@@ -279,10 +289,7 @@ async def test_optional_source_recovers_after_cooldown(monkeypatch: pytest.Monke
'create_async_db_engine',
lambda config: primary_engine if config.db_required else optional_engine,
)
- settings = SimpleNamespace(
- db_default_source='primary',
- db_sources={'primary': _source(), 'reporting': _source(required=False)},
- )
+ settings = _settings(primary=_source(), reporting=_source(required=False))
registry = database._DataSourceRegistry(settings)
await registry.initialize()
@@ -307,7 +314,7 @@ async def test_optional_engine_creation_failure_degrades_and_recovers(monkeypatc
optional_engine.should_fail = False
optional_creation_fails = True
- def create_engine(config: SimpleNamespace) -> _Engine:
+ def create_engine(config: DataSourceSettings) -> _Engine:
"""
根据测试数据源配置创建引擎替身。
@@ -321,12 +328,7 @@ def create_engine(config: SimpleNamespace) -> _Engine:
return optional_engine if config is optional_config else primary_engine
monkeypatch.setattr(database, 'create_async_db_engine', create_engine)
- registry = database._DataSourceRegistry(
- SimpleNamespace(
- db_default_source='primary',
- db_sources={'primary': primary_config, 'reporting': optional_config},
- )
- )
+ registry = database._DataSourceRegistry(_settings(primary=primary_config, reporting=optional_config))
await registry.initialize()
runtime = registry._runtimes['reporting']
@@ -351,7 +353,7 @@ async def test_required_engine_creation_failure_disposes_other_sources(monkeypat
optional_engine = _Engine()
optional_engine.should_fail = False
- def create_engine(config: SimpleNamespace) -> _Engine:
+ def create_engine(config: DataSourceSettings) -> _Engine:
"""
根据测试数据源配置创建引擎替身。
@@ -364,12 +366,7 @@ def create_engine(config: SimpleNamespace) -> _Engine:
return optional_engine
monkeypatch.setattr(database, 'create_async_db_engine', create_engine)
- registry = database._DataSourceRegistry(
- SimpleNamespace(
- db_default_source='primary',
- db_sources={'primary': primary_config, 'reporting': optional_config},
- )
- )
+ registry = database._DataSourceRegistry(_settings(primary=primary_config, reporting=optional_config))
with pytest.raises(DataSourceInitializationException):
await registry.initialize()
@@ -389,12 +386,7 @@ async def test_initialize_logs_all_sources_and_safe_failure_details(monkeypatch:
'create_async_db_engine',
lambda config: primary_engine if config.db_required else reporting_engine,
)
- registry = database._DataSourceRegistry(
- SimpleNamespace(
- db_default_source='primary',
- db_sources={'primary': _source(), 'reporting': _source(required=False)},
- )
- )
+ registry = database._DataSourceRegistry(_settings(primary=_source(), reporting=_source(required=False)))
source_logger = MagicMock()
monkeypatch.setattr(database, 'logger', source_logger)
@@ -428,29 +420,14 @@ async def test_invalidated_operational_error_marks_source_down_then_recovers(mon
engine = _Engine()
engine.should_fail = False
monkeypatch.setattr(database, 'create_async_db_engine', lambda config: engine)
- registry = database._DataSourceRegistry(
- SimpleNamespace(db_default_source='primary', db_sources={'primary': _source()})
- )
+ registry = database._DataSourceRegistry(_settings(primary=_source()))
await registry.initialize()
runtime = registry._runtimes['primary']
- session_closed = False
-
- @asynccontextmanager
- async def session_factory() -> AsyncGenerator[object, None]:
- """
- 提供测试会话并跟踪关闭状态。
-
- :yield: 测试会话并跟踪关闭状态
- """
- nonlocal session_closed
- try:
- yield object()
- finally:
- session_closed = True
-
- runtime.async_session_factory = session_factory
+ runtime.async_session_factory = async_sessionmaker()
+ failed_session = None
with pytest.raises(DataSourceUnavailableException):
- async with registry.session():
+ async with registry.session() as failed_session:
+ await failed_session.begin()
raise OperationalError(
'SELECT 1',
{},
@@ -458,7 +435,8 @@ async def session_factory() -> AsyncGenerator[object, None]:
connection_invalidated=True,
)
- assert session_closed
+ assert failed_session is not None
+ assert not failed_session.in_transaction()
assert not runtime.available
with pytest.raises(DataSourceUnavailableException):
async with registry.session():
@@ -477,22 +455,11 @@ async def test_non_invalidated_operational_error_does_not_mark_source_down(monke
engine = _Engine()
engine.should_fail = False
monkeypatch.setattr(database, 'create_async_db_engine', lambda config: engine)
- registry = database._DataSourceRegistry(
- SimpleNamespace(db_default_source='primary', db_sources={'primary': _source()})
- )
+ registry = database._DataSourceRegistry(_settings(primary=_source()))
await registry.initialize()
runtime = registry._runtimes['primary']
- @asynccontextmanager
- async def session_factory() -> AsyncGenerator[object, None]:
- """
- 提供测试会话并跟踪关闭状态。
-
- :yield: 测试会话并跟踪关闭状态
- """
- yield object()
-
- runtime.async_session_factory = session_factory
+ runtime.async_session_factory = async_sessionmaker()
with pytest.raises(OperationalError):
async with registry.session():
@@ -512,12 +479,7 @@ async def test_multiple_sources_have_independent_engines_and_factories(monkeypat
for engine in engines.values():
engine.should_fail = False
monkeypatch.setattr(database, 'create_async_db_engine', lambda config: engines[id(config)])
- registry = database._DataSourceRegistry(
- SimpleNamespace(
- db_default_source='primary',
- db_sources={'primary': primary_config, 'reporting': reporting_config},
- )
- )
+ registry = database._DataSourceRegistry(_settings(primary=primary_config, reporting=reporting_config))
await registry.initialize()
@@ -537,9 +499,7 @@ async def test_dispose_all_releases_sync_and_async_engines(monkeypatch: pytest.M
sync_engine = MagicMock()
monkeypatch.setattr(database, 'create_async_db_engine', lambda config: engine)
monkeypatch.setattr(database, 'create_sync_db_engine', lambda config: sync_engine)
- registry = database._DataSourceRegistry(
- SimpleNamespace(db_default_source='primary', db_sources={'primary': _source()})
- )
+ registry = database._DataSourceRegistry(_settings(primary=_source()))
await registry.initialize()
assert registry.get_sync_engine() is sync_engine
@@ -553,12 +513,7 @@ async def test_dispose_all_releases_sync_and_async_engines(monkeypatch: pytest.M
@pytest.mark.asyncio
async def test_dispose_all_attempts_every_engine_when_disposal_fails(monkeypatch: pytest.MonkeyPatch) -> None:
"""某个引擎释放失败后仍尝试释放其他引擎。"""
- registry = database._DataSourceRegistry(
- SimpleNamespace(
- db_default_source='primary',
- db_sources={'primary': _source(), 'reporting': _source(required=False)},
- )
- )
+ registry = database._DataSourceRegistry(_settings(primary=_source(), reporting=_source(required=False)))
primary = registry._runtime('primary')
reporting = registry._runtime('reporting')
primary.sync_engine = MagicMock()
diff --git a/ruoyi-fastapi-backend/tests/config/test_database_settings.py b/ruoyi-fastapi-backend/tests/config/test_database_settings.py
index c0ff82ac3..ea493c937 100644
--- a/ruoyi-fastapi-backend/tests/config/test_database_settings.py
+++ b/ruoyi-fastapi-backend/tests/config/test_database_settings.py
@@ -45,14 +45,14 @@ def test_db_sources_json_is_parsed_and_password_is_secret(monkeypatch: pytest.Mo
def test_postgresql_uses_sqlglot_postgres_dialect() -> None:
"""PostgreSQL 使用 sqlglot 的 postgres 方言。"""
- source = DataSourceSettings(**_source(db_type='postgresql', db_port=5432))
+ source = DataSourceSettings.model_validate(_source(db_type='postgresql', db_port=5432))
assert source.sqlglot_parse_dialect == 'postgres'
def test_data_source_allows_disabling_pool_recycle() -> None:
"""数据源支持禁用连接池回收。"""
- source = DataSourceSettings(**_source(db_pool_recycle=-1))
+ source = DataSourceSettings.model_validate(_source(db_pool_recycle=-1))
assert source.db_pool_recycle == -1
@@ -61,7 +61,7 @@ def test_data_source_allows_disabling_pool_recycle() -> None:
def test_data_source_rejects_invalid_connect_timeout(db_connect_timeout: int) -> None:
"""数据源拒绝无效的连接超时。"""
with pytest.raises(ValidationError):
- DataSourceSettings(**_source(db_connect_timeout=db_connect_timeout))
+ DataSourceSettings.model_validate(_source(db_connect_timeout=db_connect_timeout))
@pytest.mark.parametrize(
@@ -92,7 +92,7 @@ def test_database_settings_rejects_invalid_source_name() -> None:
DataBaseSettings(
_env_file=None,
db_default_source='Primary',
- db_sources={'Primary': DataSourceSettings(**_source())},
+ db_sources={'Primary': DataSourceSettings.model_validate(_source())},
)
@@ -100,7 +100,7 @@ def test_database_settings_does_not_expose_legacy_flat_fields() -> None:
"""数据库设置不暴露旧的平铺字段。"""
settings = DataBaseSettings(
_env_file=None,
- db_sources={'primary': DataSourceSettings(**_source())},
+ db_sources={'primary': DataSourceSettings.model_validate(_source())},
)
assert not hasattr(settings, 'db_type')
@@ -111,7 +111,7 @@ def test_get_source_rejects_unconfigured_name() -> None:
"""获取未配置的数据源时报错。"""
settings = DataBaseSettings(
_env_file=None,
- db_sources={'primary': DataSourceSettings(**_source())},
+ db_sources={'primary': DataSourceSettings.model_validate(_source())},
)
with pytest.raises(DataSourceNotFoundException):
diff --git a/ruoyi-fastapi-backend/tests/config/test_oidc_settings.py b/ruoyi-fastapi-backend/tests/config/test_oidc_settings.py
index 69d48ae90..67262fce4 100644
--- a/ruoyi-fastapi-backend/tests/config/test_oidc_settings.py
+++ b/ruoyi-fastapi-backend/tests/config/test_oidc_settings.py
@@ -6,9 +6,9 @@
def _enabled_values() -> dict[str, object]:
"""
- 返回含 ``_env_file``, ``oidc_enabled``, ``oidc_issuer``, ``oidc_public_base_url`` 等字段 的测试数据。
+ 构造启用 OIDC 的有效配置,禁用本地环境文件以隔离测试。
- :return: 含 ``_env_file``, ``oidc_enabled``, ``oidc_issuer``, ``oidc_public_base_url`` 等字段 的测试数据
+ :return: 可按用例覆盖的原始配置字段
"""
return {
'_env_file': None,
@@ -33,7 +33,7 @@ def test_oidc_disabled_does_not_require_runtime_secrets() -> None:
def test_oidc_enabled_accepts_secure_defaults() -> None:
"""启用 OIDC 时接受安全默认值。"""
- settings = OidcSettings(**_enabled_values())
+ settings = OidcSettings.model_validate(_enabled_values())
assert settings.oidc_require_pkce is True
assert settings.oidc_legacy_auth_isolation_enabled is True
@@ -54,22 +54,24 @@ def test_oidc_enabled_accepts_secure_defaults() -> None:
def test_oidc_enabled_rejects_unsafe_configuration(overrides: dict[str, object]) -> None:
"""启用 OIDC 时拒绝不安全配置。"""
with pytest.raises(ValidationError):
- OidcSettings(**(_enabled_values() | overrides))
+ OidcSettings.model_validate(_enabled_values() | overrides)
def test_oidc_cors_origin_rejects_userinfo_and_non_local_http(monkeypatch: pytest.MonkeyPatch) -> None:
"""OIDC 跨域来源拒绝用户信息和非本地 HTTP。"""
with pytest.raises(ValidationError):
- OidcSettings(**(_enabled_values() | {'oidc_cors_allowed_origins': 'https://user:pass@client.example'}))
+ OidcSettings.model_validate(
+ _enabled_values() | {'oidc_cors_allowed_origins': 'https://user:pass@client.example'}
+ )
monkeypatch.setenv('APP_ENV', 'prod')
with pytest.raises(ValidationError):
- OidcSettings(**(_enabled_values() | {'oidc_cors_allowed_origins': 'http://client.example'}))
+ OidcSettings.model_validate(_enabled_values() | {'oidc_cors_allowed_origins': 'http://client.example'})
monkeypatch.setenv('APP_ENV', 'dev')
with pytest.raises(ValidationError):
- OidcSettings(**(_enabled_values() | {'oidc_cors_allowed_origins': 'http://client.example'}))
- settings = OidcSettings(**(_enabled_values() | {'oidc_cors_allowed_origins': 'http://localhost:5173'}))
+ OidcSettings.model_validate(_enabled_values() | {'oidc_cors_allowed_origins': 'http://client.example'})
+ settings = OidcSettings.model_validate(_enabled_values() | {'oidc_cors_allowed_origins': 'http://localhost:5173'})
assert settings.cors_origin_list == ('http://localhost:5173',)
@@ -79,4 +81,4 @@ def test_oidc_pepper_cannot_reuse_signing_key_encryption_key() -> None:
values['oidc_signing_key_encryption_key'] = values['oidc_token_hash_pepper']
with pytest.raises(ValidationError):
- OidcSettings(**values)
+ OidcSettings.model_validate(values)
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py
index cabc91cfd..4024073b5 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py
@@ -103,6 +103,7 @@ async def test_running_process_blocks_new_executor_and_can_finish_after_delete(
)
async with runtime.sessions() as db:
response = await JobService.execute_job_once_services(db, job)
+ assert isinstance(response.result, dict)
execution_id = response.result['executionId']
runtime.scheduler.resume()
try:
@@ -112,10 +113,10 @@ async def test_running_process_blocks_new_executor_and_can_finish_after_delete(
await JobService.edit_job_services(
db,
EditJobModel(
- jobId=42,
- jobExecutor='default',
- invokeTarget='module_task.scheduler_test.runtime_harmless',
- jobArgs=[],
+ job_id=42,
+ job_executor='default',
+ invoke_target='module_task.scheduler_test.runtime_harmless',
+ job_args=[],
),
)
cron = runtime.scheduler.get_job('42')
@@ -134,7 +135,7 @@ async def test_running_process_blocks_new_executor_and_can_finish_after_delete(
await SchedulerManager._drain_execution_requests()
monkeypatch.setattr(SchedulerManager, '_is_leader', True)
async with runtime.sessions() as db:
- await JobService.delete_job_services(db, DeleteJobModel(jobIds='42'))
+ await JobService.delete_job_services(db, DeleteJobModel(job_ids='42'))
assert (await runtime.execution(execution_id))['status'] == 'running'
finally:
release.touch()
@@ -149,7 +150,9 @@ async def test_expired_dispatch_token_cannot_run_reclaimed_request(runtime: Runt
async with runtime.sessions() as db:
request = await JobRuntimeDao.create_request(db, job, None)
await db.commit()
+ assert job.job_id is not None
old = await JobRuntimeDao.claim_request(db, request.execution_id, job.job_id)
+ assert old is not None and old.owner_token is not None
old_token = old.owner_token
await db.commit()
await db.execute(
@@ -180,10 +183,11 @@ async def test_only_original_owner_can_finish_unknown_execution(runtime: Runtime
job = await runtime.save()
execution_id = uuid4().hex
now = TimezoneUtil.utc_now()
+ assert job.job_id is not None
claim = await asyncio.to_thread(
JobExecutionStore.claim, execution_id, job.job_id, job.model_dump(mode='json', by_alias=True), now
)
- assert claim.accepted
+ assert claim.accepted and claim.token is not None
async with runtime.sessions() as db:
await db.execute(
update(SysJobExecution)
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_retry.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_retry.py
index 913b53c53..848a90a85 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_retry.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_retry.py
@@ -1,4 +1,5 @@
import asyncio
+from collections.abc import Sequence
from datetime import timedelta
from types import SimpleNamespace
from typing import Any
@@ -39,7 +40,7 @@ def database_error(code: int | str, *, attribute: str = 'sqlstate', invalidated:
def inject_finish_failures(
runtime: Runtime,
monkeypatch: pytest.MonkeyPatch,
- failures: list[DBAPIError | None],
+ failures: Sequence[DBAPIError | None],
stage: str,
) -> tuple[list[Session], list[str], list[float]]:
"""
@@ -136,10 +137,11 @@ async def claimed_execution(runtime: Runtime) -> tuple[str, str, dict[str, Any]]
job = await runtime.save()
execution_id = uuid4().hex
start = TimezoneUtil.utc_now()
+ assert job.job_id is not None
claim = await asyncio.to_thread(
JobExecutionStore.claim, execution_id, job.job_id, job.model_dump(mode='json', by_alias=True), start
)
- assert claim.accepted
+ assert claim.accepted and claim.token is not None
return (
execution_id,
claim.token,
@@ -173,6 +175,7 @@ async def test_finish_retries_rolled_back_transaction_in_a_new_session(
assert delays == [0.05]
with Session(runtime.engine) as db:
saved = db.get(SysJobExecution, execution_id)
+ assert saved is not None
assert saved.status == ('failed' if failed else 'success')
assert saved.owner_token == token
assert saved.message == result['message']
@@ -231,7 +234,8 @@ async def test_finish_retry_keeps_owner_guard_and_does_not_overwrite_completed_r
await asyncio.to_thread(JobExecutionStore.finish, execution_id, 'wrong-owner', **result)
assert (await runtime.execution(execution_id))['status'] == 'running'
await asyncio.to_thread(JobExecutionStore.finish, execution_id, token, **result)
- await asyncio.to_thread(JobExecutionStore.finish, execution_id, token, **{**result, 'failed': True})
+ result['failed'] = True
+ await asyncio.to_thread(JobExecutionStore.finish, execution_id, token, **result)
assert (await runtime.execution(execution_id))['status'] == 'success'
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py
index 53236769f..466adf339 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py
@@ -2,6 +2,7 @@
import math
import pickle
import threading
+from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, timedelta
from unittest.mock import Mock, patch
@@ -14,6 +15,7 @@
EVENT_JOB_MISSED,
EVENT_JOB_SUBMITTED,
JobSubmissionEvent,
+ SchedulerEvent,
)
from apscheduler.executors.base import MaxInstancesReachedError
from apscheduler.schedulers.asyncio import AsyncIOScheduler
@@ -70,8 +72,8 @@ def test_failure_and_misfire_have_distinct_execution_metadata() -> None:
assert missed.start_time is missed.end_time is missed.run_duration_ms is None
assert failed.code == EVENT_JOB_ERROR
assert isinstance(failed.exception, ValueError)
- assert failed.run_duration_ms >= 0
- assert 'job.func' in failed.traceback
+ assert failed.run_duration_ms is not None and failed.run_duration_ms >= 0
+ assert failed.traceback is not None and 'job.func' in failed.traceback
assert missed.execution_id != failed.execution_id
finally:
scheduler.shutdown()
@@ -88,7 +90,7 @@ async def test_executors_preserve_return_value_and_log_deleted_one_shot(kind: st
def receive(event: TimedJobExecutionEvent) -> None:
"""
- 为下游 ASGI 应用提供待接收的测试消息。
+ 记录调度器提交和完成任务的通知。
:param event: 包含任务快照、真实起止时刻和耗时的执行事件
"""
@@ -151,9 +153,9 @@ async def test_thread_queue_wait_does_not_become_execution_start() -> None:
submitted = asyncio.Event()
scheduler = AsyncIOScheduler(executors={'default': TimedAsyncIOExecutor()})
- def receive(event: object) -> None:
+ def receive(event: SchedulerEvent) -> None:
"""
- 为下游 ASGI 应用提供待接收的测试消息。
+ 记录调度器提交和完成任务的通知。
:param event: 待处理的事件
"""
@@ -167,7 +169,7 @@ def receive(event: object) -> None:
scheduler.add_job(pow, args=[2, 3])
original_run_in_executor = loop.run_in_executor
- def use_single_worker(executor: object, function: object, *args) -> asyncio.Future:
+ def use_single_worker(executor: object, function: Callable, *args) -> asyncio.Future:
"""
将执行任务提交给指定的工作线程池。
@@ -213,7 +215,7 @@ async def test_scheduler_emits_one_standard_max_instances_event_and_preserves_re
def receive(event: JobSubmissionEvent) -> None:
"""
- 为下游 ASGI 应用提供待接收的测试消息。
+ 记录调度器提交和完成任务的通知。
:param event: 待处理的事件
"""
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_fields.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_fields.py
index 0650ab702..226330212 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_fields.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_fields.py
@@ -10,6 +10,7 @@
from sqlalchemy import Integer, MetaData, select, update
from sqlalchemy.exc import IntegrityError
+from common.vo import PageModel
from config.scheduler.manager import SchedulerManager
from exceptions.exception import ServiceException
from module_admin.dao.job_log_dao import JobLogDao
@@ -101,11 +102,13 @@ async def test_json_parameters_and_unlimited_delay_survive_database_roundtrip(ru
value = {'text': 'x' * 600, 'flags': [True, None, 3.25], 'name': 'tenant,a'}
saved = await runtime.save(job_info(jobArgs=[value], misfireGraceTime=None))
async with runtime.sessions() as db:
+ assert saved.job_id is not None
result = await JobService.job_detail_services(db, saved.job_id)
assert result.job_args == [value]
assert result.misfire_grace_time is None
async with runtime.sessions() as db:
submitted = await JobService.execute_job_once_services(db, saved)
+ assert isinstance(submitted.result, dict)
runtime.scheduler.resume()
await runtime.wait_execution(submitted.result['executionId'], {'success'})
assert [value] == CALLS
@@ -120,14 +123,14 @@ async def test_group_changes_preserve_storage_and_schedule_progress(runtime: Run
previous_time = TimezoneUtil.utc_now() - timedelta(minutes=5)
runtime.scheduler.modify_job('42', jobstore='sqlalchemy', next_run_time=previous_time)
async with runtime.sessions() as db:
- await JobService.edit_job_services(db, EditJobModel(jobId=42, jobGroup='财务', coalesce=True))
+ await JobService.edit_job_services(db, EditJobModel(job_id=42, job_group='财务', coalesce=True))
current = runtime.scheduler.get_job('42', jobstore='sqlalchemy')
assert current.next_run_time == previous_time
assert current.trigger.task_job_group == '财务'
assert pickle.loads(pickle.dumps(current.trigger)).task_job_group == '财务'
assert runtime.scheduler.get_job('42', jobstore='default') is None
async with runtime.sessions() as db:
- await JobService.edit_job_services(db, EditJobModel(jobId=42, jobStore='default'))
+ await JobService.edit_job_services(db, EditJobModel(job_id=42, job_store='default'))
current = runtime.scheduler.get_job('42', jobstore='default')
assert current.next_run_time == previous_time
assert current.trigger.task_job_group == '财务'
@@ -138,16 +141,16 @@ async def test_group_changes_preserve_storage_and_schedule_progress(runtime: Run
async def test_id_is_unique_and_name_is_unique_within_business_group(runtime: Runtime) -> None:
"""任务标识全局唯一,名称在业务组内唯一。"""
await runtime.save()
- assert list(SysJob.__table__.primary_key.columns.keys()) == ['job_id']
+ assert list(SysJob.get_table().primary_key.columns.keys()) == ['job_id']
async with runtime.sessions() as db:
with pytest.raises(ServiceException) as error:
await JobService.add_job_services(db, job_info(jobArgs=['different']))
- assert '已存在' in error.value.message
+ assert error.value.message is not None and '已存在' in error.value.message
async with runtime.sessions() as db:
db.add(
SysJob(
**job_info(jobName='another', jobGroup='another').model_dump(
- include=set(SysJob.__table__.columns.keys())
+ include=set(SysJob.get_table().columns.keys())
)
)
)
@@ -156,6 +159,7 @@ async def test_id_is_unique_and_name_is_unique_within_business_group(runtime: Ru
await db.rollback()
async with runtime.sessions() as db:
result = await JobService.add_job_services(db, job_info(jobGroup='another'))
+ assert isinstance(result.result, dict)
assert result.result['saved']
@@ -175,7 +179,7 @@ async def test_actual_schedule_is_observed_from_leader_and_separate_from_preview
async with runtime.sessions() as db:
result = await JobService.job_detail_services(db, 42)
assert result.next_run_time == actual
- assert result.cron_next_time > actual
+ assert result.cron_next_time is not None and result.cron_next_time > actual
async with runtime.sessions() as db:
await db.execute(
update(SysJobSync).values(schedule_observed_time=TimezoneUtil.utc_now() - timedelta(minutes=1))
@@ -186,7 +190,7 @@ async def test_actual_schedule_is_observed_from_leader_and_separate_from_preview
assert stale.cron_next_time is not None
monkeypatch.setattr(SchedulerManager, '_is_leader', True)
async with runtime.sessions() as db:
- await JobService.edit_job_services(db, EditJobModel(jobId=42, status='1', type='status'))
+ await JobService.edit_job_services(db, EditJobModel(job_id=42, status='1', type='status'))
disabled = await JobService.job_detail_services(db, 42)
assert disabled.next_run_time is None
assert disabled.cron_next_time is not None
@@ -199,7 +203,7 @@ async def test_log_ids_keep_history_queryable_after_rename_and_delete(
) -> None:
"""重命名或删除任务后仍可按日志标识查询历史。"""
metadata = MetaData()
- logs = SysJobLog.__table__.to_metadata(metadata)
+ logs = SysJobLog.get_table().to_metadata(metadata)
logs.c.job_log_id.type = Integer()
metadata.create_all(runtime.engine)
recorded = []
@@ -219,6 +223,7 @@ def record(log: object) -> None:
job = await runtime.save(job_info(jobGroup='业务分组', jobArgs=['tenant,a']))
async with runtime.sessions() as db:
submitted = await JobService.execute_job_once_services(db, job)
+ assert isinstance(submitted.result, dict)
runtime.scheduler.resume()
await runtime.wait_execution(submitted.result['executionId'], {'success'})
# 执行结果先提交、事件随后分发,等待事件循环完成日志通知。
@@ -233,13 +238,15 @@ def record(log: object) -> None:
async with runtime.sessions() as db:
db.add(SysJobLog(**log.model_dump(exclude={'job_log_id'})))
await db.commit()
- await JobService.edit_job_services(db, EditJobModel(jobId=42, jobName='改名后'))
- await JobService.delete_job_services(db, DeleteJobModel(jobIds='42'))
- result = await JobLogDao.get_job_log_list(db, JobLogPageQueryModel(jobId=42), is_page=True)
+ await JobService.edit_job_services(db, EditJobModel(job_id=42, job_name='改名后'))
+ await JobService.delete_job_services(db, DeleteJobModel(job_ids='42'))
+ result = await JobLogDao.get_job_log_list(db, JobLogPageQueryModel(job_id=42), is_page=True)
+ assert isinstance(result, PageModel)
assert result.total == 1
assert result.rows[0]['jobName'] == job.job_name
by_execution = await JobLogDao.get_job_log_list(
- db, JobLogPageQueryModel(executionId=log.execution_id), is_page=True
+ db, JobLogPageQueryModel(execution_id=log.execution_id), is_page=True
)
+ assert isinstance(by_execution, PageModel)
assert by_execution.rows[0]['jobId'] == job.job_id
assert (await db.scalars(select(SysJob))).first() is None
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_persistence.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_persistence.py
index 1df9fe4b4..917293ebb 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_persistence.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_persistence.py
@@ -7,6 +7,7 @@
from apscheduler.events import EVENT_JOB_EXECUTED, JobExecutionEvent
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.schedulers.asyncio import AsyncIOScheduler
+from redis.asyncio import Redis
from sqlalchemy import Engine, create_engine
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from sqlalchemy.orm import Session
@@ -46,17 +47,19 @@ async def verify_persistent_scheduler(
:param sessions: 异步数据库会话工厂
:param execution_engine: 执行记录使用的数据库引擎,未指定时使用任务仓库引擎
"""
- info = JobModel(
- jobId=81,
- jobName='persistent timezone check',
- jobGroup='default',
- jobExecutor='default',
- invokeTarget=f'{__name__}.persisted_callable',
- cronExpression='0 30 2 * * ?',
- timeZone='America/New_York',
- status='0',
- misfireGraceTime=1,
- maxInstances=1,
+ info = JobModel.model_validate(
+ {
+ 'jobId': 81,
+ 'jobName': 'persistent timezone check',
+ 'jobGroup': 'default',
+ 'jobExecutor': 'default',
+ 'invokeTarget': f'{__name__}.persisted_callable',
+ 'cronExpression': '0 30 2 * * ?',
+ 'timeZone': 'America/New_York',
+ 'status': '0',
+ 'misfireGraceTime': 1,
+ 'maxInstances': 1,
+ }
)
async with sessions() as db:
assert await JobDao.get_job_detail_by_id(db, 81) is None
@@ -104,12 +107,13 @@ def build_scheduler() -> AsyncIOScheduler:
JobExecutionStore, 'session', staticmethod(lambda: Session(execution_engine or engine, expire_on_commit=False))
)
try:
- await SchedulerManager._start_scheduler_as_leader(None)
+ await SchedulerManager._start_scheduler_as_leader(AsyncMock(spec=Redis))
current.pause()
assert current.get_job('82') is None
restored = current.get_job('81')
assert SchedulerManager._jobs.is_config_current(restored, updated)
assert old_signature != SchedulerManager._jobs.trigger_signature(restored.trigger)
+ assert updated.cron_expression is not None
expected = MyCronTrigger.from_crontab(updated.cron_expression, updated.time_zone)
start = datetime(2026, 11, 1, tzinfo=UTC)
assert restored.trigger.get_next_fire_time(None, start) == expected.get_next_fire_time(None, start)
@@ -165,6 +169,7 @@ def on_complete(event: JobExecutionEvent) -> None:
current.add_listener(on_complete, EVENT_JOB_EXECUTED)
async with sessions() as db:
response = await JobService.execute_job_once_services(db, updated)
+ assert response.result is not None
execution_id = response.result['executionId']
original_next = current.get_job('81').next_run_time
original_trigger = SchedulerManager._jobs.trigger_signature(current.get_job('81').trigger)
@@ -181,7 +186,7 @@ def on_complete(event: JobExecutionEvent) -> None:
assert SchedulerManager._jobs.is_config_current(current.get_job('81'), updated)
async with sessions() as db:
execution = await JobRuntimeDao.get_execution(db, execution_id)
- assert execution.status == 'success'
- assert execution.run_duration_ms >= 0
+ assert execution is not None and execution.status == 'success'
+ assert execution.run_duration_ms is not None and execution.run_duration_ms >= 0
state = (await JobRuntimeDao.get_states(db, [81]))[81]
assert state['configVersion'] == state['appliedVersion'] == UPDATED_CONFIG_VERSION
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py
index fb46f499e..3fed8cda8 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py
@@ -67,10 +67,13 @@ async def test_timezone_only_update_rebuilds_trigger_and_failure_remains_retryab
jobs.update_job(job_id, changed, original, changed_at)
assert jobs.get_job(job_id) is original
+ assert original is not None
assert str(original.trigger.timezone) == 'Asia/Shanghai'
jobs.update_job(job_id, changed, original, changed_at)
- assert str(jobs.get_job(job_id).trigger.timezone) == 'UTC'
- assert jobs.is_config_current(jobs.get_job(job_id), changed)
+ updated = jobs.get_job(job_id)
+ assert updated is not None
+ assert str(updated.trigger.timezone) == 'UTC'
+ assert jobs.is_config_current(updated, changed)
@pytest.mark.asyncio
@@ -81,12 +84,14 @@ async def test_non_leader_only_notifies_ids_and_tolerates_notification_failure(
) -> None:
"""非主节点仅通知任务标识,并容忍通知失败。"""
monkeypatch.setattr(SchedulerManager, '_is_leader', False)
- publish = SchedulerManager._redis.publish
+ publish = runtime.publish
publish.side_effect = RuntimeError('offline') if publish_fails else None
sync = AsyncMock()
monkeypatch.setattr(SchedulerManager, '_sync_jobs_from_database', sync)
result = await SchedulerManager.request_scheduler_sync({42, 43}, immediate=immediate)
assert result['syncStatus'] == 'pending'
+ publish.assert_awaited_once()
+ assert publish.await_args is not None
assert json.loads(publish.await_args.args[1]) == {'jobIds': [42, 43]}
sync.assert_not_awaited()
assert SchedulerManager._sync_task is None
@@ -109,7 +114,8 @@ async def test_immediate_sync_notifies_new_leader_if_lease_is_lost_waiting_for_l
result = await asyncio.wait_for(task, timeout=1)
assert result['syncStatus'] == 'pending'
sync.assert_not_awaited()
- assert json.loads(SchedulerManager._redis.publish.await_args.args[1]) == {'jobIds': [42]}
+ assert runtime.publish.await_args is not None
+ assert json.loads(runtime.publish.await_args.args[1]) == {'jobIds': [42]}
@pytest.mark.asyncio
@@ -135,4 +141,5 @@ async def read_jobs(_session: object) -> list:
result = await SchedulerManager.request_scheduler_sync(immediate=True)
assert result['syncStatus'] == 'pending'
assert runtime.scheduler.get_job('42') is original
- assert json.loads(SchedulerManager._redis.publish.await_args.args[1]) == {'jobIds': None}
+ assert runtime.publish.await_args is not None
+ assert json.loads(runtime.publish.await_args.args[1]) == {'jobIds': None}
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_leader_lease.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_leader_lease.py
index f4df84c86..3430de240 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_leader_lease.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_leader_lease.py
@@ -1,4 +1,5 @@
import asyncio
+from collections.abc import Coroutine
from unittest.mock import AsyncMock, MagicMock, call, patch
import pytest
@@ -81,7 +82,7 @@ async def test_non_leader_scheduler_starts_reacquire_task() -> None:
SchedulerManager._reacquire_task = None
SchedulerManager._is_closing = False
- def create_task(coroutine: object) -> MagicMock:
+ def create_task(coroutine: Coroutine) -> MagicMock:
"""
创建测试任务并将其交给调用方。
@@ -221,7 +222,7 @@ def test_scheduler_lock_lost_callback_revokes_leader_state() -> None:
original_lock_lost_task = SchedulerManager._lock_lost_task
scheduled_task = MagicMock()
- def create_task(coroutine: object) -> MagicMock:
+ def create_task(coroutine: Coroutine) -> MagicMock:
"""
创建测试任务并将其交给调用方。
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_runtime.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_runtime.py
index a437bc1f6..f68c16c96 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_runtime.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_runtime.py
@@ -53,6 +53,7 @@ async def test_registration_error_is_saved_and_can_be_retried(
)
async with runtime.sessions() as db:
result = await JobService.add_job_services(db, job_info())
+ assert isinstance(result.result, dict)
state = result.result['jobs'][0]
assert result.result['saved'] is True
assert result.result['syncStatus'] == 'failed'
@@ -64,6 +65,7 @@ async def test_registration_error_is_saved_and_can_be_retried(
monkeypatch.setattr(runtime.scheduler, 'add_job', original_add)
async with runtime.sessions() as db:
result = await JobService.retry_sync_services(db, state['jobId'])
+ assert isinstance(result.result, dict)
assert result.result['syncStatus'] == 'applied'
assert runtime.scheduler.get_job(str(state['jobId'])) is not None
@@ -83,10 +85,11 @@ async def test_edit_is_targeted_and_invalid_edit_preserves_both_states(
)
async with runtime.sessions() as db:
with pytest.raises(ValidationError):
- await JobService.edit_job_services(db, EditJobModel(jobId=42, jobKwargs='[1]'))
+ await JobService.edit_job_services(db, EditJobModel.model_validate({'jobId': 42, 'jobKwargs': '[1]'}))
assert runtime.scheduler.get_job('42') is original
async with runtime.sessions() as db:
- result = await JobService.edit_job_services(db, EditJobModel(jobId=42, timeZone='Asia/Shanghai'))
+ result = await JobService.edit_job_services(db, EditJobModel(job_id=42, time_zone='Asia/Shanghai'))
+ assert isinstance(result.result, dict)
assert result.result['jobs'][0]['configVersion'] == UPDATED_CONFIG_VERSION
assert result.result['jobs'][0]['appliedVersion'] == UPDATED_CONFIG_VERSION
assert str(runtime.scheduler.get_job('42').trigger.timezone) == 'Asia/Shanghai'
@@ -131,6 +134,7 @@ async def test_manual_request_survives_sync_without_changing_cron(runtime: Runti
original = runtime.scheduler.get_job('42')
async with runtime.sessions() as db:
submitted = await JobService.execute_job_once_services(db, job, requested_by='tester')
+ assert isinstance(submitted.result, dict)
execution_id = submitted.result['executionId']
assert submitted.result['status'] == 'pending'
assert runtime.scheduler.get_job(f'_manual:{execution_id}') is not None
@@ -157,9 +161,11 @@ async def test_cron_and_manual_share_the_same_concurrency_limit(runtime: Runtime
for _ in range(limit - 1):
async with runtime.sessions() as db:
accepted = await JobService.execute_job_once_services(db, job)
+ assert isinstance(accepted.result, dict)
await runtime.wait_execution(accepted.result['executionId'], {'running'})
async with runtime.sessions() as db:
submitted = await JobService.execute_job_once_services(db, job)
+ assert isinstance(submitted.result, dict)
rejected = await runtime.wait_execution(submitted.result['executionId'], {'rejected'})
assert f'并发上限 {limit}' in rejected['message']
assert rejected['startTime'] is None
@@ -176,9 +182,10 @@ async def test_lost_notification_is_recovered_and_duplicate_wakeup_does_not_repe
"""恢复遗漏通知且重复唤醒不会重复执行。"""
job = await runtime.save()
monkeypatch.setattr(SchedulerManager, '_is_leader', False)
- SchedulerManager._redis.publish.side_effect = RuntimeError('offline')
+ runtime.publish.side_effect = RuntimeError('offline')
async with runtime.sessions() as db:
pending = await JobService.execute_job_once_services(db, job)
+ assert isinstance(pending.result, dict)
assert runtime.scheduler.get_jobs() == []
assert (await runtime.execution(pending.result['executionId']))['status'] == 'pending'
monkeypatch.setattr(SchedulerManager, '_is_leader', True)
@@ -197,8 +204,10 @@ async def test_delete_cancels_unstarted_requests_and_keeps_queryable_tombstone(r
job = await runtime.save()
async with runtime.sessions() as db:
submitted = await JobService.execute_job_once_services(db, job)
+ assert isinstance(submitted.result, dict)
async with runtime.sessions() as db:
- result = await JobService.delete_job_services(db, DeleteJobModel(jobIds='42'))
+ result = await JobService.delete_job_services(db, DeleteJobModel(job_ids='42'))
+ assert isinstance(result.result, dict)
assert result.result['jobs'][0]['deleted'] is True
assert result.result['syncStatus'] == 'applied'
runtime.scheduler.resume()
@@ -210,7 +219,7 @@ async def test_delete_cancels_unstarted_requests_and_keeps_queryable_tombstone(r
async with runtime.sessions() as db:
page = await JobService.sync_list_services(db, JobSyncQueryModel())
assert page.rows[0]['deleted'] is True
- page = await JobService.execution_list_services(db, JobExecutionQueryModel(jobId=42))
+ page = await JobService.execution_list_services(db, JobExecutionQueryModel(job_id=42))
assert page.rows[0]['status'] == 'cancelled'
assert 'ownerToken' not in page.rows[0]
assert 'jobSnapshot' not in page.rows[0]
@@ -284,7 +293,9 @@ async def edit(change: dict) -> dict:
:return: 执行当前操作得到的结果
"""
async with runtime.sessions() as db:
- return (await JobService.edit_job_services(db, EditJobModel(jobId=42, **change))).result
+ response = await JobService.edit_job_services(db, EditJobModel(job_id=42, **change))
+ assert isinstance(response.result, dict)
+ return response.result
monkeypatch.setattr(SchedulerManager, 'request_scheduler_sync', delayed_notification)
results = await asyncio.gather(edit({'timeZone': 'UTC'}), edit({'jobName': 'changed name'}))
@@ -311,12 +322,14 @@ async def test_deleted_configuration_remains_retryable_when_removal_fails(
runtime.scheduler, 'remove_job', lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError('store offline'))
)
async with runtime.sessions() as db:
- result = await JobService.delete_job_services(db, DeleteJobModel(jobIds='42'))
+ result = await JobService.delete_job_services(db, DeleteJobModel(job_ids='42'))
+ assert isinstance(result.result, dict)
assert result.result['saved']
assert result.result['syncStatus'] == 'failed'
assert result.result['jobs'][0]['deleted']
monkeypatch.setattr(runtime.scheduler, 'remove_job', remove)
async with runtime.sessions() as db:
retried = await JobService.retry_sync_services(db, 42)
+ assert isinstance(retried.result, dict)
assert retried.result['syncStatus'] == 'applied'
assert runtime.scheduler.get_job('42') is None
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_sql_logging.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_sql_logging.py
index 7a0cde814..2e190d0ee 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_sql_logging.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_sql_logging.py
@@ -6,7 +6,7 @@
import pytest
import pytest_asyncio
-from sqlalchemy import MetaData, create_engine, text
+from sqlalchemy import Engine, MetaData, create_engine, text
from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine
from sqlalchemy.orm import Session
@@ -47,8 +47,8 @@ async def sql_engine(
runtime.available = True
monkeypatch.setattr('config.scheduler.resources.DataSourceRegistry', registry)
metadata = MetaData()
- SysJobExecution.__table__.to_metadata(metadata)
- SysJobSync.__table__.to_metadata(metadata)
+ SysJobExecution.get_table().to_metadata(metadata)
+ SysJobSync.get_table().to_metadata(metadata)
async with engine.begin() as connection:
await connection.run_sync(metadata.create_all)
try:
@@ -98,6 +98,7 @@ async def business_query() -> None:
caplog.clear()
capsys.readouterr()
async with SchedulerManager._resources.session() as db:
+ assert isinstance(db.bind, AsyncEngine)
assert db.bind.pool is sql_engine.pool
assert await db.scalar(text("SELECT 'internal_sql_hidden'")) == 'internal_sql_hidden'
await asyncio.create_task(business_query())
@@ -127,6 +128,7 @@ async def test_failed_or_cancelled_internal_session_keeps_errors_and_subsequent_
with pytest.raises(exception_type):
async with SchedulerManager._resources.session() as db:
await db.execute(text("SELECT 'failed_internal_sql_hidden'"))
+ assert isinstance(db.bind, AsyncEngine)
token = db.bind.get_execution_options()['logging_token']
engine_logger = logging.getLogger(f'sqlalchemy.engine.Engine.{sql_engine.sync_engine.logging_name}')
engine_logger.warning('[%s] internal_warning_visible', token)
@@ -158,7 +160,7 @@ def test_execution_lease_sql_is_quiet_without_muting_shared_engine(
engine_logger = logging.getLogger(logger_name)
original_handlers = engine_logger.handlers[:]
engine = create_engine(f'sqlite:///{tmp_path / "lease.sqlite"}', logging_name=logging_name)
- SysJobExecution.__table__.create(engine)
+ SysJobExecution.get_table().create(engine)
engine.echo = echo
monkeypatch.setattr(DataSourceRegistry, 'get_sync_engine', lambda _name: engine)
caplog.clear()
@@ -169,6 +171,7 @@ def test_execution_lease_sql_is_quiet_without_muting_shared_engine(
assert caplog.records == []
assert capsys.readouterr().out == ''
with JobExecutionStore.session() as db:
+ assert isinstance(db.bind, Engine)
assert db.bind.pool is engine.pool
with Session(engine) as db:
db.execute(text("SELECT 'sync_business_sql_visible'"))
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_catalog_domains.py b/ruoyi-fastapi-backend/tests/i18n/test_catalog_domains.py
index a107acc86..48debbdf0 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_catalog_domains.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_catalog_domains.py
@@ -3,13 +3,13 @@
from collections.abc import Generator
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, create_autospec
import pytest
from babel.messages.catalog import Catalog
from babel.messages.mofile import write_mo
from babel.messages.pofile import write_po
-from fastapi import FastAPI
+from fastapi import FastAPI, Response
from starlette.requests import Request
from common.annotation.cache_annotation import ApiCache
@@ -22,14 +22,17 @@
from i18n.translator import I18nUtil
from plugins.core.discovery.registry import PluginRegistry, RegisteredPlugin
from plugins.core.discovery.scanner import PluginScanner
+from plugins.core.management.entity.vo.schemas import PluginModel
from plugins.core.manifest.schema import PluginManifestError
+from plugins.core.runtime.service import PluginRuntimeService
+from plugins.core.runtime.service.dependency_container import PluginRuntimeGatewayOverrides
+from plugins.core.runtime.service.gateway import PluginLifecycleStateGateway, PluginLifecycleUnitOfWork
from plugins.core.runtime.service.lifecycle.enable import (
PluginEnabledLifecycleContext,
- PluginEnableUseCase,
PluginUninstallLifecycleContext,
)
-from plugins.core.runtime.service.lifecycle.install import PluginInstallLifecycleContext, PluginInstallUseCase
-from plugins.core.runtime.service.lifecycle.upgrade import PluginUpgradeLifecycleContext, PluginUpgradeUseCase
+from plugins.core.runtime.service.lifecycle.install import PluginInstallLifecycleContext
+from plugins.core.runtime.service.lifecycle.upgrade import PluginUpgradeLifecycleContext
from plugins.core.runtime.startup import PluginRuntimeStartupManager
from scripts.compile_i18n import compile_catalogs
from utils.response_util import ResponseUtil
@@ -129,7 +132,7 @@ def test_response_and_service_metadata_survive_copy_and_rendering(tmp_path: Path
message=str(message),
msg_key=message.msg_key,
domain=message.domain,
- count=message.count,
+ count=message.plural_count,
plural_key=message.plural_key,
)
error = ServiceException(
@@ -147,14 +150,14 @@ def test_response_and_service_metadata_survive_copy_and_rendering(tmp_path: Path
),
]
for response in responses:
- payload = json.loads(response.body)
+ payload = json.loads(bytes(response.body))
assert payload['msg'] == expected
assert payload['msgKey'] == 'items.one'
assert payload['msgDomain'] == 'plugin.counts'
- assert payload['msgCount'] == message.count
+ assert payload['msgCount'] == message.plural_count
assert payload['msgPluralKey'] == 'items.many'
- assert payload['msgParams']['count'] == message.count
- assert json.loads(responses[0].body)['data']['nested'] == expected
+ assert payload['msgParams']['count'] == message.plural_count
+ assert json.loads(bytes(responses[0].body))['data']['nested'] == expected
finally:
RequestContext.reset_current_locale(token)
@@ -306,7 +309,7 @@ async def test_catalog_refresh_during_request_does_not_write_old_release_cache(t
request._body = b''
@ApiCache('catalog-refresh', vary_by_user=False)
- async def endpoint(request: Request) -> object:
+ async def endpoint(request: Request) -> Response:
"""
处理请求并提供供路由断言使用的响应。
@@ -318,39 +321,35 @@ async def endpoint(request: Request) -> object:
return ResponseUtil.success(msg=t('common.success', domain='plugin.counts', locale='en-US'))
response = await endpoint(request)
- assert json.loads(response.body)['msg'] == 'New version'
+ assert json.loads(bytes(response.body))['msg'] == 'New version'
app.state.redis.get.assert_awaited_once()
app.state.redis.set.assert_not_awaited()
@pytest.mark.asyncio
-@pytest.mark.parametrize(
- ('use_case', 'context_type', 'method'),
- [
- (PluginInstallUseCase, PluginInstallLifecycleContext, '_install_step_build_precheck'),
- (PluginUpgradeUseCase, PluginUpgradeLifecycleContext, '_upgrade_step_build_precheck'),
- (PluginEnableUseCase, PluginEnabledLifecycleContext, '_enabled_step_build_precheck'),
- ],
-)
-async def test_invalid_catalog_is_rejected_before_lifecycle_writes(
- tmp_path: Path,
- use_case: type,
- context_type: type,
- method: str,
-) -> None:
+@pytest.mark.parametrize('operation', ['install', 'upgrade', 'enable'])
+async def test_invalid_catalog_is_rejected_before_lifecycle_writes(tmp_path: Path, operation: str) -> None:
"""验证安装、启用和升级流程会在持久化之前拒绝损坏的词库。"""
- spec = write_plugin(tmp_path)
- CatalogRegistry.register_plugin('counts', tmp_path)
+ directory = tmp_path / 'counts'
+ spec = write_plugin(directory)
+ CatalogRegistry.register_plugin('counts', directory)
previous = CatalogRegistry.fingerprint()
+ discovered = PluginScanner(tmp_path).load_manifest(directory / 'plugin.yaml')
spec.path('en-US', '.mo').write_bytes(b'broken')
- context = (
- context_type('counts', True, False, 'enable')
- if context_type is PluginEnabledLifecycleContext
- else context_type('counts', False)
- )
- context.discovered_plugin = SimpleNamespace(backend_path=tmp_path)
+ runtime = PluginRuntimeService()
with pytest.raises(ValueError, match='Invalid compiled'):
- await getattr(use_case.__new__(use_case), method)(context)
+ if operation == 'install':
+ await runtime.install._install_step_build_precheck(
+ PluginInstallLifecycleContext('counts', False, discovered_plugin=discovered)
+ )
+ elif operation == 'upgrade':
+ await runtime.upgrade._upgrade_step_build_precheck(
+ PluginUpgradeLifecycleContext('counts', False, discovered_plugin=discovered)
+ )
+ else:
+ await runtime.enable._enabled_step_build_precheck(
+ PluginEnabledLifecycleContext('counts', True, False, 'enable', discovered_plugin=discovered)
+ )
assert CatalogRegistry.fingerprint() == previous
@@ -368,7 +367,7 @@ async def test_startup_isolates_corrupt_plugin_and_keeps_plugins_without_catalog
discovered = [PluginScanner(tmp_path).load_manifest(path / 'plugin.yaml') for path in (valid, broken, plain)]
app = FastAPI()
app.state.plugin_registry = PluginRegistry([RegisteredPlugin(item, None, True, 'installed') for item in discovered])
- manager = PluginRuntimeStartupManager(SimpleNamespace())
+ manager = PluginRuntimeStartupManager()
await manager.prepare_enabled_plugin_catalogs(app, startup_write_enabled=False)
assert {item.plugin_id for item in app.state.plugin_registry.list_enabled_plugins()} == {'valid', 'plain'}
assert t('common.success', domain='plugin.valid', locale='en-US') == 'Plugin ready'
@@ -383,31 +382,28 @@ async def test_lifecycle_commit_upgrade_disable_and_uninstall_publish_catalogs(t
"""验证插件事务提交后发布新译文,停用和卸载时移除相应词库。"""
write_plugin(tmp_path)
initial = CatalogRegistry.prepare_plugin('counts', tmp_path)
+ gateway = create_autospec(PluginLifecycleStateGateway, instance=True, spec_set=True)
+ gateway.set_plugin_enabled_state.return_value = CrudResponseModel(is_success=True, message='启停状态已更新')
+ gateway.mark_plugin_uninstalled_state.return_value = CrudResponseModel(is_success=True, message='插件已卸载')
+ runtime = PluginRuntimeService(gateways=PluginRuntimeGatewayOverrides(lifecycle_state_gateway=gateway))
installed = PluginInstallLifecycleContext('counts', False, catalog_snapshot=initial)
- installed.lifecycle_uow = SimpleNamespace(commit=AsyncMock())
- installed.plugin = SimpleNamespace(enabled='0')
- await PluginInstallUseCase.__new__(PluginInstallUseCase)._install_step_commit(installed)
+ installed.lifecycle_uow = create_autospec(PluginLifecycleUnitOfWork, instance=True)
+ installed.plugin = PluginModel.model_validate({'pluginId': 'counts', 'enabled': '0'})
+ await runtime.install._install_step_commit(installed)
assert t('common.success', domain='plugin.counts', locale='en-US') == 'Plugin ready'
write_plugin(tmp_path, english='Upgrade')
upgrade = PluginUpgradeLifecycleContext(
'counts', False, catalog_snapshot=CatalogRegistry.prepare_plugin('counts', tmp_path)
)
- upgrade.lifecycle_uow = SimpleNamespace(commit=AsyncMock())
- upgrade.plugin = SimpleNamespace(enabled='0')
- await PluginUpgradeUseCase.__new__(PluginUpgradeUseCase)._upgrade_step_commit(upgrade)
+ upgrade.lifecycle_uow = create_autospec(PluginLifecycleUnitOfWork, instance=True)
+ upgrade.plugin = PluginModel.model_validate({'pluginId': 'counts', 'enabled': '0'})
+ await runtime.upgrade._upgrade_step_commit(upgrade)
assert t('common.success', domain='plugin.counts', locale='en-US') == 'Upgrade'
- use_case = PluginEnableUseCase.__new__(PluginEnableUseCase)
- use_case.dependencies = SimpleNamespace(
- lifecycle_state_gateway=SimpleNamespace(
- set_plugin_enabled_state=AsyncMock(return_value=SimpleNamespace(is_success=True)),
- mark_plugin_uninstalled_state=AsyncMock(return_value=SimpleNamespace(is_success=True)),
- )
- )
disabled = PluginEnabledLifecycleContext('counts', False, False, 'disable')
- await use_case._enabled_step_update_enabled_state(disabled)
+ await runtime.enable._enabled_step_update_enabled_state(disabled)
assert t('common.success', domain='plugin.counts', locale='en-US') == t('common.unavailable', locale='en-US')
enabled = PluginEnabledLifecycleContext('counts', True, False, 'enable', catalog_snapshot=upgrade.catalog_snapshot)
- await use_case._enabled_step_update_enabled_state(enabled)
+ await runtime.enable._enabled_step_update_enabled_state(enabled)
assert t('common.success', domain='plugin.counts', locale='en-US') == 'Upgrade'
- await use_case._uninstall_step_mark_uninstalled(PluginUninstallLifecycleContext('counts', False))
+ await runtime.enable._uninstall_step_mark_uninstalled(PluginUninstallLifecycleContext('counts', False))
assert t('common.success', domain='plugin.counts', locale='en-US') == t('common.unavailable', locale='en-US')
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_database_initialization.py b/ruoyi-fastapi-backend/tests/i18n/test_database_initialization.py
index b04959193..8554040a2 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_database_initialization.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_database_initialization.py
@@ -5,6 +5,7 @@
from sqlalchemy.dialects import mysql, postgresql, sqlite
from sqlalchemy.engine import Dialect
+from config.database import Base
from module_admin.entity.do.dict_do import SysDictData, SysDictType
from module_admin.entity.do.menu_do import SysMenu
@@ -23,7 +24,7 @@
def test_translation_columns_compile_to_comparable_postgres_jsonb(dialect: Dialect, expected: str) -> None:
"""菜单和字典的整行 DISTINCT 查询要求 PostgreSQL 译文列具备相等运算。"""
for model, field, _ in TRANSLATION_FIELDS:
- column = model.__table__.c[f'{field}_i18n']
+ column = model.get_table().c[f'{field}_i18n']
assert column.type.compile(dialect=dialect) == expected
@@ -38,10 +39,12 @@ def test_fresh_database_user_locale_defaults() -> None:
@pytest.mark.parametrize('model,field,example', TRANSLATION_FIELDS)
-def test_fresh_database_scripts_insert_matching_translations(model: type, field: str, example: tuple[str, str]) -> None:
+def test_fresh_database_scripts_insert_matching_translations(
+ model: type[Base], field: str, example: tuple[str, str]
+) -> None:
"""按两套脚本各自的建表顺序插入,逐行核对内置记录的原文和译文。"""
name = model.__tablename__
- model_table = model.__table__
+ model_table = model.get_table()
translation = f'{field}_i18n'
primary_key = next(iter(model_table.primary_key)).name
results = []
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_dict_cache_publication.py b/ruoyi-fastapi-backend/tests/i18n/test_dict_cache_publication.py
index 10cb1abfc..af1a9e9a8 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_dict_cache_publication.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_dict_cache_publication.py
@@ -12,6 +12,7 @@
from module_admin.entity.do.dict_do import SysDictData, SysDictType
from module_admin.entity.vo.dict_vo import DeleteDictDataModel, DeleteDictTypeModel, DictDataModel, DictTypeModel
from module_admin.service.dict_service import DictDataService, DictTypeService
+from tests.module_admin.service.helpers import make_redis_request
from tests.utils.test_current_user_cache_util import cache_redis, redis_socket # noqa: F401
PUBLICATION_READS_WITH_ONE_CONFLICT = 3
@@ -32,7 +33,7 @@ async def test_late_dict_refresh_cannot_overwrite_a_newer_publication(
latest: list[dict | None],
) -> None:
"""在旧查询读完后发布新值,确认重试使用新的数据库会话。"""
- rows = [{'dictLabel': '红', 'dictLabelI18n': {'en-US': 'Red'}}]
+ rows: list[dict | None] = [{'dictLabel': '红', 'dictLabelI18n': {'en-US': 'Red'}}]
old_read = asyncio.Event()
resume_refresh = asyncio.Event()
read_sessions: list[AsyncSession] = []
@@ -55,15 +56,15 @@ async def query(db: AsyncSession, name: str) -> list[dict | None]:
monkeypatch.setattr(DictDataDao, 'query_dict_data_list', query)
monkeypatch.setattr(DictTypeDao, 'get_all_dict_type', AsyncMock(return_value=[SimpleNamespace(dict_type='colors')]))
- db = SimpleNamespace(bind=None)
- refresh = asyncio.create_task(DictDataService.init_cache_sys_dict_services(db, cache_redis))
- try:
- await asyncio.wait_for(old_read.wait(), timeout=3)
- rows = latest.copy()
- await DictDataService.publish_dict_cache(db, cache_redis, 'colors')
- finally:
- resume_refresh.set()
- await asyncio.wait_for(refresh, timeout=3)
+ async with AsyncSession() as db:
+ refresh = asyncio.create_task(DictDataService.init_cache_sys_dict_services(db, cache_redis))
+ try:
+ await asyncio.wait_for(old_read.wait(), timeout=3)
+ rows = latest.copy()
+ await DictDataService.publish_dict_cache(db, cache_redis, 'colors')
+ finally:
+ resume_refresh.set()
+ await asyncio.wait_for(refresh, timeout=3)
assert len(set(read_sessions)) == PUBLICATION_READS_WITH_ONE_CONFLICT
assert await DictDataService.query_dict_data_list_from_cache_services(cache_redis, 'colors') == [
row for row in latest if row
@@ -75,43 +76,45 @@ async def query(db: AsyncSession, name: str) -> list[dict | None]:
async def test_cache_tracks_type_and_data_crud(cache_redis: Redis) -> None: # noqa: F811
"""缓存跟踪字典类型和字典数据的增删改查。"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
- request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=cache_redis)))
+ request = make_redis_request(cache_redis)
read = DictDataService.query_dict_data_list_from_cache_services
try:
async with engine.begin() as conn:
- await conn.run_sync(SysDictType.__table__.create)
- await conn.run_sync(SysDictData.__table__.create)
+ await conn.run_sync(SysDictType.get_table().create)
+ await conn.run_sync(SysDictData.get_table().create)
async with AsyncSession(bind=engine, expire_on_commit=False) as db:
await DictTypeService.add_dict_type_services(
- request, db, DictTypeModel(dictId=1, dictType='colors', dictName='颜色', status='0')
+ request, db, DictTypeModel(dict_id=1, dict_type='colors', dict_name='颜色', status='0')
)
await DictDataService.add_dict_data_services(
- request, db, DictDataModel(dictCode=1, dictType='colors', dictValue='R', dictLabel='红', status='0')
+ request, db, DictDataModel(dict_code=1, dict_type='colors', dict_value='R', dict_label='红', status='0')
)
# 迁移后未补译的数据在数据库中可以为空,发布到缓存时统一使用空映射。
await db.execute(update(SysDictData).where(SysDictData.dict_code == 1).values(dict_label_i18n=None))
await db.commit()
await DictDataService.publish_dict_cache(db, cache_redis, 'colors')
- cached = json.loads(await cache_redis.get('sys_dict:colors'))[0]
+ snapshot = await cache_redis.get('sys_dict:colors')
+ assert snapshot is not None
+ cached = json.loads(snapshot)[0]
assert cached['dictLabel'] == '红'
assert cached['dictLabelI18n'] == {}
await DictDataService.edit_dict_data_services(
request,
db,
DictDataModel(
- dictCode=1, dictType='colors', dictValue='R', dictLabel='红', dictLabelI18n={'en-US': 'Red'}
+ dict_code=1, dict_type='colors', dict_value='R', dict_label='红', dict_label_i18n={'en-US': 'Red'}
),
)
assert (await read(cache_redis, 'colors'))[0]['dictLabelI18n'] == {'en-US': 'Red'}
await DictTypeService.edit_dict_type_services(
- request, db, DictTypeModel(dictId=1, dictType='palette', dictName='调色板', status='0')
+ request, db, DictTypeModel(dict_id=1, dict_type='palette', dict_name='调色板', status='0')
)
assert not await cache_redis.exists('sys_dict:colors')
assert (await read(cache_redis, 'palette'))[0]['dictType'] == 'palette'
- await DictDataService.delete_dict_data_services(request, db, DeleteDictDataModel(dictCodes='1'))
+ await DictDataService.delete_dict_data_services(request, db, DeleteDictDataModel(dict_codes='1'))
assert await read(cache_redis, 'palette') == []
assert await cache_redis.exists('sys_dict:palette')
- await DictTypeService.delete_dict_type_services(request, db, DeleteDictTypeModel(dictIds='1'))
+ await DictTypeService.delete_dict_type_services(request, db, DeleteDictTypeModel(dict_ids='1'))
assert not await cache_redis.exists('sys_dict:palette')
finally:
await engine.dispose()
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_excel_i18n.py b/ruoyi-fastapi-backend/tests/i18n/test_excel_i18n.py
index da58c6413..f39cab92b 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_excel_i18n.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_excel_i18n.py
@@ -6,6 +6,7 @@
import pytest
from fastapi import UploadFile
from openpyxl import load_workbook
+from sqlalchemy import true
from common.context import LocaleContext, RequestContext
from exceptions.exception import ServiceException
@@ -15,6 +16,7 @@
from module_admin.service.dict_service import DictDataService, DictTypeService
from module_admin.service.user_service import UserService
from module_identity.service.identity_service import IdentitySubjectService
+from tests.module_admin.service.helpers import make_current_user, make_query_db, make_redis_request
from utils.excel_util import ExcelUtil
from utils.user_import_util import UserImportUtil
@@ -54,15 +56,15 @@ async def test_published_user_templates_round_trip_independently_of_interface_la
add_user = AsyncMock(return_value=SimpleNamespace(user_id=77))
monkeypatch.setattr(UserDao, 'add_user_dao', add_user)
monkeypatch.setattr(IdentitySubjectService, 'create_for_new_user', AsyncMock())
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ db = make_query_db()
result = await UserService.batch_import_user_services(
- SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=object()))),
+ make_redis_request(object()),
db,
UploadFile(file=io.BytesIO(stream.getvalue()), filename='users.xlsx'),
False,
- SimpleNamespace(user=SimpleNamespace(admin=True, user_name='admin')),
- None,
- None,
+ make_current_user(1, user_name='admin', admin=True),
+ true(),
+ true(),
)
created = add_user.call_args.args[1]
assert created.user_name == 'ada'
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_locale.py b/ruoyi-fastapi-backend/tests/i18n/test_locale.py
index b11a203de..03e55c70a 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_locale.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_locale.py
@@ -76,7 +76,7 @@ def test_negotiation(header: str, expected: str) -> None:
def test_disabled_locales_are_excluded_from_negotiation_catalogs_and_names(monkeypatch: pytest.MonkeyPatch) -> None:
"""验证停用语言从协商结果、发布词库和显示名称的回退链中移除。"""
- monkeypatch.setitem(LOCALES['en-US'], 'enabled', False)
+ monkeypatch.setitem(LOCALES, 'en-US', {**LOCALES['en-US'], 'enabled': False})
monkeypatch.setitem(LOCALES, 'en-GB', {'aliases': (), 'fallback': ('en-US',)})
assert LocaleRegistry.enabled_locales() == ('zh-CN', 'en-GB')
assert all(LocaleRegistry.match_locale(tag) is None for tag in ('en-US', 'en', 'en-AU'))
@@ -120,7 +120,7 @@ def test_preferences_are_extensible(value: str) -> None:
"""验证账号偏好可保存合法的扩展语言标签。"""
assert UserLocaleModel(locale=value).locale == value
with pytest.raises(ValueError):
- UserLocaleModel(locale=value, userId=2)
+ UserLocaleModel.model_validate({'locale': value, 'userId': 2})
def test_locale_normalization() -> None:
@@ -279,7 +279,7 @@ async def call_next(request: Request) -> Response:
await middleware.dispatch(request, call_next)
else:
response = await middleware.dispatch(request, call_next)
- assert json.loads(response.body)['msg'] == 'Operation successful'
+ assert json.loads(bytes(response.body))['msg'] == 'Operation successful'
assert RequestContext.get_current_locale() == context
finally:
RequestContext.reset_current_locale(token)
@@ -312,7 +312,7 @@ def test_explicit_message_key_takes_precedence_in_both_languages() -> None:
token = RequestContext.set_current_locale(LocaleContext('en-US'))
try:
response = ResponseUtil.success('旧文案', msg_key='profile.localeSaved')
- assert json.loads(response.body)['msg'] == 'Language preference saved'
+ assert json.loads(bytes(response.body))['msg'] == 'Language preference saved'
assert I18nUtil.message_fields('custom original')['msg'] == 'custom original'
assert I18nUtil.translate('missing.internal.key') != 'missing.internal.key'
finally:
@@ -412,7 +412,7 @@ async def test_locale_endpoint_only_changes_current_account() -> None:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
try:
async with engine.begin() as connection:
- await connection.run_sync(SysUser.__table__.create)
+ await connection.run_sync(SysUser.get_table().create)
sessions = async_sessionmaker(engine, expire_on_commit=False)
async with sessions() as db:
db.add_all(
@@ -426,7 +426,7 @@ async def test_locale_endpoint_only_changes_current_account() -> None:
response = await inspect.unwrap(change_system_user_locale)(
SimpleNamespace(), UserLocaleModel(locale='ja-JP'), db, current
)
- assert json.loads(response.body)['data']['locale'] == 'ja-JP'
+ assert json.loads(bytes(response.body))['data']['locale'] == 'ja-JP'
async with sessions() as db:
users = (await db.scalars(select(SysUser).order_by(SysUser.user_id))).all()
assert [user.locale for user in users] == ['ja-JP', 'zh-CN']
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_locale_revision.py b/ruoyi-fastapi-backend/tests/i18n/test_locale_revision.py
index 4788bd7f6..3d450385b 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_locale_revision.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_locale_revision.py
@@ -8,7 +8,7 @@
import httpx
import pytest
import pytest_asyncio
-from fastapi import FastAPI
+from fastapi import FastAPI, Request
from sqlalchemy.dialects import mysql, postgresql
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
@@ -24,6 +24,7 @@
from module_admin.entity.vo.user_vo import CurrentUserModel, UserInfoModel, UserLocaleModel, UserModel
from module_admin.service.login_service import LoginService
from module_admin.service.user_service import UserService
+from tests.module_admin.service.helpers import make_current_user, make_query_db
from utils.common_util import CamelCaseUtil
@@ -36,7 +37,7 @@ async def sessions() -> AsyncIterator[async_sessionmaker[AsyncSession]]:
"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
async with engine.begin() as connection:
- await connection.run_sync(SysUser.__table__.create)
+ await connection.run_sync(SysUser.get_table().create)
factory = async_sessionmaker(engine, expire_on_commit=False)
async with factory.begin() as db:
db.add_all(
@@ -64,6 +65,7 @@ async def test_login_writes_only_an_explicit_valid_preference(
async with sessions() as db:
app.dependency_overrides[get_db_session_provider(None)] = lambda: db
user = await db.get(SysUser, 1)
+ assert user is not None
monkeypatch.setattr(LoginService, 'authenticate_user', AsyncMock(return_value=(user, None)))
monkeypatch.setattr(UserService, 'user_detail_services', AsyncMock(return_value=SimpleNamespace(data=user)))
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client:
@@ -85,28 +87,28 @@ async def test_preference_endpoint_returns_monotonic_revision_and_get_info_prese
sessions: async_sessionmaker[AsyncSession],
) -> None:
"""偏好接口返回递增版本且用户信息保留大整数精度。"""
- current = SimpleNamespace(user=SimpleNamespace(user_id=1, user_name='one'))
+ current = make_current_user(1, user_name='one')
+ request = Request({'type': 'http'})
async with sessions() as db:
- first = await inspect.unwrap(change_system_user_locale)(
- SimpleNamespace(), UserLocaleModel(locale='en_US'), db, current
- )
- second = await inspect.unwrap(change_system_user_locale)(
- SimpleNamespace(), UserLocaleModel(locale='en-US'), db, current
- )
- assert json.loads(first.body)['data'] == {'locale': 'en-US', 'revision': '1'}
- assert json.loads(second.body)['data'] == {'locale': 'en-US', 'revision': '2'}
+ first = await inspect.unwrap(change_system_user_locale)(request, UserLocaleModel(locale='en_US'), db, current)
+ second = await inspect.unwrap(change_system_user_locale)(request, UserLocaleModel(locale='en-US'), db, current)
+ assert json.loads(bytes(first.body))['data'] == {'locale': 'en-US', 'revision': '1'}
+ assert json.loads(bytes(second.body))['data'] == {'locale': 'en-US', 'revision': '2'}
async with sessions.begin() as db:
user = await db.get(SysUser, 1)
+ assert user is not None
user.locale_revision = 2**53 + 1
async with sessions() as db:
result = await UserService.update_user_locale_services(db, 1, 'one', 'auto')
assert result.result == {'locale': 'auto', 'revision': str(2**53 + 2)}
async with sessions() as db:
user = await db.get(SysUser, 1)
+ assert user is not None
info = CurrentUserModel(permissions=[], roles=[], user=UserInfoModel(**CamelCaseUtil.transform_result(user)))
- response = await get_login_user_info(SimpleNamespace(), info)
- assert json.loads(response.body)['user']['localeRevision'] == str(2**53 + 2)
+ response = await get_login_user_info(request, info)
+ assert json.loads(bytes(response.body))['user']['localeRevision'] == str(2**53 + 2)
untouched = await db.get(SysUser, 2)
+ assert untouched is not None
assert (untouched.locale, untouched.locale_revision) == ('zh-CN', 0)
@@ -125,9 +127,10 @@ async def test_other_user_edits_cannot_overwrite_revision_and_locale_rollback_is
await db.rollback()
async with sessions() as db:
user = await db.get(SysUser, 1)
+ assert user is not None
assert (user.locale, user.locale_revision, user.nick_name) == ('en-GB', 1, 'Changed')
added = await UserDao.add_user_dao(
- db, UserModel(userId=3, userName='three', nickName='Three', localeRevision='999')
+ db, UserModel(user_id=3, user_name='three', nick_name='Three', locale_revision='999')
)
assert added.locale_revision == 0
@@ -135,7 +138,8 @@ async def test_other_user_edits_cannot_overwrite_revision_and_locale_rollback_is
@pytest.mark.asyncio
async def test_locale_update_locks_the_row_and_uses_database_increment() -> None:
"""更新语言时锁定记录并通过数据库递增版本。"""
- db = SimpleNamespace(scalar=AsyncMock(side_effect=[1, 42]), execute=AsyncMock())
+ db = make_query_db()
+ db.scalar.side_effect = [1, 42]
assert await UserDao.edit_user_dao(db, {'user_id': 1, 'locale': 'en-US'}) == {'locale': 'en-US', 'revision': '42'}
lock = db.scalar.call_args_list[0].args[0]
update = db.execute.call_args.args[0]
@@ -177,4 +181,4 @@ def test_exact_registered_locale_wins_and_chinese_scripts_do_not_merge(monkeypat
def test_locale_endpoint_does_not_accept_client_revision() -> None:
"""语言接口拒绝客户端提供的版本。"""
with pytest.raises(ValueError):
- UserLocaleModel(locale='en-US', revision='12')
+ UserLocaleModel.model_validate({'locale': 'en-US', 'revision': '12'})
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_plugin_messages.py b/ruoyi-fastapi-backend/tests/i18n/test_plugin_messages.py
index 16eecc368..162fedbbc 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_plugin_messages.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_plugin_messages.py
@@ -16,13 +16,13 @@
def test_plugin_payload_preserves_semantics_until_response_rendering(locale: str) -> None:
"""验证插件操作消息在响应阶段按当前语言翻译。"""
message = I18nMessage('插件安装完成', msg_key='plugin.runtime.install.completed')
- payload = PluginRuntimeInvalidOperationPayload(ok=False, operation='install', pluginId='demo', message=message)
+ payload = PluginRuntimeInvalidOperationPayload(ok=False, operation='install', plugin_id='demo', message=message)
data = payload.to_payload()
assert data['message'] is message
assert PluginOperationResult.from_payload(data).message is message
token = RequestContext.set_current_locale(LocaleContext(locale))
try:
- response = json.loads(_plugin_operation_response(data, '操作完成').body)
+ response = json.loads(bytes(_plugin_operation_response(data, '操作完成').body))
expected = 'Plugin installation completed' if locale == 'en-US' else '插件安装完成'
assert response['msg'] == response['data']['message'] == expected
assert response['msgKey'] == 'plugin.runtime.install.completed'
@@ -38,7 +38,7 @@ def test_batch_feedback_preserves_message_metadata_and_user_data() -> None:
assert report.message is message
token = RequestContext.set_current_locale(LocaleContext('en-US'))
try:
- response = json.loads(ResponseUtil.success(data={'report': report, 'customName': '用户插件'}).body)
+ response = json.loads(bytes(ResponseUtil.success(data={'report': report, 'customName': '用户插件'}).body))
assert response['data']['report']['message'] == 'Plugin installation completed'
assert response['data']['customName'] == '用户插件'
finally:
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_response_completion.py b/ruoyi-fastapi-backend/tests/i18n/test_response_completion.py
index 38f9f9a52..37092c056 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_response_completion.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_response_completion.py
@@ -14,6 +14,7 @@
from plugins.core.runtime.support.payload.validation import PluginValidationPayloadMixin
from plugins.core.validation.manifest import PluginManifestChecker
from scripts.compile_i18n import compile_catalogs
+from tests.module_admin.service.helpers import make_redis_request
from utils.response_util import ResponseUtil
@@ -34,10 +35,10 @@ def test_authentication_error_helpers_keep_status_and_translate(locale: str) ->
assert invalid.status_code == status.HTTP_400_BAD_REQUEST
assert disabled.status_code == status.HTTP_404_NOT_FOUND
assert invalid.headers['cache-control'] == 'no-store'
- assert json.loads(invalid.body)['msg'] == (
+ assert json.loads(bytes(invalid.body))['msg'] == (
'Invalid authentication interaction request' if locale == 'en-US' else '认证交互请求无效'
)
- assert json.loads(disabled.body)['msg'] == (
+ assert json.loads(bytes(disabled.body))['msg'] == (
'The authentication service is not enabled' if locale == 'en-US' else '认证服务未启用'
)
@@ -54,11 +55,8 @@ async def test_captcha_failure_keeps_http_contract_and_localizes(
'captcha',
AsyncMock(return_value=SimpleNamespace(rate_limited=limited, unavailable=not limited, retry_after=17)),
)
- request = SimpleNamespace(
- app=SimpleNamespace(state=SimpleNamespace(redis=object())),
- client=SimpleNamespace(host='127.0.0.1'),
- headers={},
- )
+ request = make_redis_request(object())
+ request.scope['client'] = ('127.0.0.1', 8080)
token = RequestContext.set_current_locale(LocaleContext('en-US'))
try:
response = await captcha(request, 'interaction')
@@ -67,10 +65,10 @@ async def test_captcha_failure_keeps_http_contract_and_localizes(
if limited:
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
assert response.headers['retry-after'] == '17'
- assert json.loads(response.body)['msg'] == 'Too many requests. Please try again later'
+ assert json.loads(bytes(response.body))['msg'] == 'Too many requests. Please try again later'
else:
assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
- assert json.loads(response.body)['msg'] == 'The authentication service is temporarily unavailable'
+ assert json.loads(bytes(response.body))['msg'] == 'The authentication service is temporarily unavailable'
@pytest.mark.parametrize('locale', ['zh-CN', 'en-US'])
@@ -89,11 +87,11 @@ def test_plugin_precheck_suggestion_survives_payload_and_response(locale: str) -
payload = PluginValidationPayloadMixin.build_validation_issue(issue)
token = RequestContext.set_current_locale(LocaleContext(locale))
try:
- response = json.loads(ResponseUtil.success(data=payload).body)
+ response = json.loads(bytes(ResponseUtil.success(data=payload).body))
batch = PluginBatchReportBuilder.build_item_report(
'install', 'demo', {'ok': False, 'structureErrors': ['invalid']}, 1
)
- batch_response = json.loads(ResponseUtil.success(data=batch).body)
+ batch_response = json.loads(bytes(ResponseUtil.success(data=batch).body))
finally:
RequestContext.reset_current_locale(token)
assert response['data']['suggestion'] == (
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_translations.py b/ruoyi-fastapi-backend/tests/i18n/test_translations.py
index cf2341c13..9b427491b 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_translations.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_translations.py
@@ -1,6 +1,5 @@
from collections.abc import Awaitable, Callable
from copy import deepcopy
-from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
@@ -18,6 +17,7 @@
from i18n.translator import I18nUtil
from module_admin.dao.dict_dao import DictDataDao, DictTypeDao
from module_admin.dao.menu_dao import MenuDao
+from module_admin.dao.user_dao import UserDao
from module_admin.entity.do.dict_do import SysDictData, SysDictType
from module_admin.entity.do.menu_do import SysMenu
from module_admin.entity.vo.dict_vo import DictDataModel, DictDataPageQueryModel, DictTypeModel, DictTypePageQueryModel
@@ -25,6 +25,8 @@
from module_admin.service.login_service import LoginService
from module_admin.service.menu_service import MenuService
from plugins.core.management.dao.dao import PluginDao
+from plugins.core.management.service.router_metadata import PluginRouterMetadataService
+from tests.module_admin.service.helpers import make_query_db
@pytest.mark.parametrize(
@@ -79,7 +81,7 @@ async def test_updates_merge_languages_and_preserve_maps_from_old_clients(
sessions = async_sessionmaker(engine, expire_on_commit=False)
try:
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[model.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[model.get_table()])
async with sessions() as session:
session.add(model(**{primary_key: 1, field: {'en-US': 'Original', 'ja-JP': '日本語'}, **attributes}))
await session.commit()
@@ -102,15 +104,19 @@ async def test_updates_merge_languages_and_preserve_maps_from_old_clients(
@pytest.mark.parametrize('dialect', [mysql.dialect(), postgresql.dialect()])
async def test_translation_update_locks_latest_database_value(dialect: Dialect) -> None:
"""验证合并译文前会读取并锁定数据库中的最新记录。"""
- db = SimpleNamespace(scalar=AsyncMock(return_value={'ja-JP': '日本語'}), execute=AsyncMock())
+ db = make_query_db()
+ db.scalar.return_value = {'ja-JP': '日本語'}
await MenuDao.edit_menu_dao(db, {'menu_id': 1, 'menu_name_i18n': {'en-US': 'Users'}})
statement = db.scalar.call_args.args[0]
assert str(statement.compile(dialect=dialect)).endswith(' FOR UPDATE')
assert db.execute.call_args.args[1][0]['menu_name_i18n'] == {'ja-JP': '日本語', 'en-US': 'Users'}
+@pytest.mark.asyncio
@pytest.mark.parametrize('kind', ['directory', 'page', 'root_page', 'inner_link'])
-def test_router_and_permission_tree_keep_raw_titles_and_translation_maps(kind: str) -> None:
+async def test_router_and_permission_tree_keep_raw_titles_and_translation_maps(
+ kind: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
"""验证路由与授权菜单树同时保留原始标题和译文。"""
menu = SysMenu(
menu_id=1,
@@ -123,11 +129,18 @@ def test_router_and_permission_tree_keep_raw_titles_and_translation_maps(kind: s
is_frame=1,
is_cache=0,
)
- menus = LoginService._LoginService__generate_menus(menu.parent_id, [menu])
- routes = LoginService._LoginService__generate_user_router_menu(menus)
- route = routes[0].children[0] if routes[0].children else routes[0]
- assert route.meta.title == '用户管理'
- assert route.meta.title_i18n == {'en-US': 'Users', 'ja-JP': '利用者'}
+ menu.order_num = 1
+ user_menus = [menu]
+ if kind == 'page':
+ user_menus.insert(
+ 0, SysMenu(menu_id=10, menu_name='父目录', menu_type='M', parent_id=0, path='system', order_num=0)
+ )
+ monkeypatch.setattr(UserDao, 'get_user_by_id', AsyncMock(return_value={'user_menu_info': user_menus}))
+ monkeypatch.setattr(PluginRouterMetadataService, 'get_menu_plugin_ids', AsyncMock(return_value={}))
+ routes = await LoginService.get_current_user_routers(1, make_query_db())
+ route = routes[0]['children'][0] if routes[0].get('children') else routes[0]
+ assert route['meta']['title'] == '用户管理'
+ assert route['meta']['titleI18n'] == {'en-US': 'Users', 'ja-JP': '利用者'}
tree = MenuService.list_to_tree([menu])[0].model_dump(by_alias=True)
assert tree['label'] == '用户管理'
assert tree['labelI18n'] == {'en-US': 'Users', 'ja-JP': '利用者'}
@@ -189,3 +202,13 @@ def test_message_copy_preserves_deferred_translation_metadata() -> None:
assert cloned.msg_key == message.msg_key
assert cloned.msg_params == message.msg_params
assert cloned.msg_params is not message.msg_params
+
+
+def test_legacy_plural_state_preserves_string_count() -> None:
+ """恢复旧消息时,复数数量与字符串的计数方法都可用。"""
+ quantity = 5
+ message = I18nMessage('条目,条目', msg_key='item', count=quantity, plural_key='items')
+ message.__setstate__({'count': quantity})
+ cloned = deepcopy(message)
+ assert cloned.plural_count == message.plural_count == quantity
+ assert cloned.count('条目') == message.count('条目') == str(message).count('条目')
diff --git a/ruoyi-fastapi-backend/tests/module_admin/controller/test_dept_controller.py b/ruoyi-fastapi-backend/tests/module_admin/controller/test_dept_controller.py
index 928e982ab..7a0178705 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/controller/test_dept_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/controller/test_dept_controller.py
@@ -26,9 +26,9 @@ async def test_add_dept_rejects_parent_outside_data_scope() -> None:
pytest.raises(ServiceException),
):
await inspect.unwrap(add_system_dept)(
- object(), DeptModel(parentId=parent_id, deptName='新部门'), object(), current_user, object()
+ object(), DeptModel(parent_id=parent_id, dept_name='新部门'), object(), current_user, object()
)
- assert check_scope.await_args.args[1] == parent_id
+ assert check_scope.await_args_list[-1].args[1] == parent_id
add_dept.assert_not_awaited()
@@ -44,14 +44,16 @@ async def test_edit_dept_checks_changed_parent_scope(parent_id: int, parent_chan
'check_dept_data_scope_services',
AsyncMock(side_effect=[None, ServiceException(message='没有权限访问部门数据')]),
) as check_scope,
- patch.object(DeptService, 'dept_detail_services', AsyncMock(return_value=DeptModel(deptId=101, parentId=100))),
+ patch.object(
+ DeptService, 'dept_detail_services', AsyncMock(return_value=DeptModel(dept_id=101, parent_id=100))
+ ),
patch.object(
DeptService,
'edit_dept_services',
AsyncMock(return_value=CrudResponseModel(is_success=True, message='更新成功')),
) as edit_dept,
):
- args = (object(), DeptModel(deptId=101, parentId=parent_id), query_db, current_user, scope)
+ args = (object(), DeptModel(dept_id=101, parent_id=parent_id), query_db, current_user, scope)
if parent_changed:
with pytest.raises(ServiceException):
await inspect.unwrap(edit_system_dept)(*args)
@@ -76,7 +78,7 @@ async def test_admin_add_dept_does_not_require_parent_data_scope() -> None:
) as add_dept,
):
await inspect.unwrap(add_system_dept)(
- object(), DeptModel(parentId=100, deptName='新部门'), object(), current_user, object()
+ object(), DeptModel(parent_id=100, dept_name='新部门'), object(), current_user, object()
)
check_scope.assert_not_awaited()
add_dept.assert_awaited_once()
diff --git a/ruoyi-fastapi-backend/tests/module_admin/controller/test_user_controller.py b/ruoyi-fastapi-backend/tests/module_admin/controller/test_user_controller.py
index 4372a406e..032bd74e2 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/controller/test_user_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/controller/test_user_controller.py
@@ -14,6 +14,7 @@
)
from module_admin.entity.vo.user_vo import EditUserModel, UpdateUserProfileModel
from module_admin.service.user_service import UserService
+from tests.module_admin.service.helpers import make_redis_request
from utils.pwd_util import PwdUtil
@@ -21,14 +22,16 @@
async def test_admin_reset_password_uses_front_end_default_rule() -> None:
"""管理员重置密码使用前端默认规则。"""
redis = SimpleNamespace()
- request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis)))
- reset_user = EditUserModel(userId=2, password='abcdef')
+ request = make_redis_request(redis)
+ reset_user = EditUserModel(user_id=2, password='abcdef')
current_user = SimpleNamespace(user=SimpleNamespace(admin=True, user_name='admin'))
expected = object()
with (
patch.object(UserService, 'check_user_allowed_services', new_callable=AsyncMock),
- patch.object(UserService, 'validate_password_services', new_callable=AsyncMock) as validate_password,
+ patch.object(
+ UserService, 'validate_password_services', new=AsyncMock(return_value='abcdef')
+ ) as validate_password,
patch.object(
UserService,
'edit_user_services',
@@ -66,7 +69,7 @@ async def test_admin_reset_password_uses_front_end_default_rule() -> None:
def test_update_user_profile_model_rejects_management_fields(management_field: dict) -> None:
"""用户资料模型拒绝管理字段。"""
with pytest.raises(ValidationError):
- UpdateUserProfileModel(nickName='普通用户', **management_field)
+ UpdateUserProfileModel(nick_name='普通用户', **management_field)
@pytest.mark.asyncio
@@ -74,7 +77,7 @@ async def test_update_user_profile_only_forwards_editable_fields() -> None:
"""更新用户资料仅转发可编辑字段。"""
request = SimpleNamespace()
user_info = UpdateUserProfileModel(
- nickName='新昵称',
+ nick_name='新昵称',
email='user@example.com',
phonenumber='13800138000',
sex='2',
@@ -109,7 +112,7 @@ async def test_update_user_profile_only_forwards_editable_fields() -> None:
)
assert result is expected
- edit_user = edit_user_services.await_args.args[1]
+ edit_user = edit_user_services.await_args_list[-1].args[1]
update_fields = edit_user.model_dump(exclude_unset=True)
assert update_fields['nick_name'] == '新昵称'
assert update_fields['email'] == 'user@example.com'
@@ -131,17 +134,17 @@ async def test_update_user_profile_only_forwards_editable_fields() -> None:
async def test_edit_user_does_not_accept_password_or_internal_operation_type(operation_type: str | None) -> None:
"""普通编辑权限不能调用密码重置路径或写入内部维护字段。"""
payload = EditUserModel(
- userId=2,
- deptId=100,
- userName='tester',
- nickName='新昵称',
- roleIds=[2],
- postIds=[3],
+ user_id=2,
+ dept_id=100,
+ user_name='tester',
+ nick_name='新昵称',
+ role_ids=[2],
+ post_ids=[3],
password='injected-password-hash',
type=operation_type,
- delFlag='2',
- loginIp='forged-ip',
- createBy='forged-creator',
+ del_flag='2',
+ login_ip='forged-ip',
+ create_by='forged-creator',
)
current_user = SimpleNamespace(user=SimpleNamespace(admin=True, user_name='admin'))
with patch.object(
@@ -151,7 +154,7 @@ async def test_edit_user_does_not_accept_password_or_internal_operation_type(ope
) as edit_user:
await inspect.unwrap(edit_system_user)(object(), payload, object(), current_user, object(), object(), object())
- update = edit_user.await_args.args[1]
+ update = edit_user.await_args_list[-1].args[1]
fields = update.model_dump(exclude_unset=True)
assert not {'password', 'type', 'del_flag', 'login_ip', 'create_by'}.intersection(fields)
assert update.nick_name == '新昵称'
diff --git a/ruoyi-fastapi-backend/tests/module_admin/dao/test_log_sort.py b/ruoyi-fastapi-backend/tests/module_admin/dao/test_log_sort.py
new file mode 100644
index 000000000..34e064959
--- /dev/null
+++ b/ruoyi-fastapi-backend/tests/module_admin/dao/test_log_sort.py
@@ -0,0 +1,38 @@
+from datetime import UTC, datetime
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
+
+from module_admin.dao.log_dao import LoginLogDao
+from module_admin.entity.do.log_do import SysLogininfor
+from module_admin.entity.vo.log_vo import LoginLogPageQueryModel
+
+
+@pytest.mark.asyncio
+async def test_login_logs_use_requested_column_or_latest_time() -> None:
+ """登录日志支持按驼峰列名排序,缺少有效排序条件时优先返回最近记录。"""
+ engine = create_async_engine('sqlite+aiosqlite:///:memory:')
+ table = SysLogininfor.get_table()
+ try:
+ async with engine.begin() as conn:
+ await conn.run_sync(table.create)
+ async with AsyncSession(engine) as db:
+ db.add_all(
+ [
+ SysLogininfor(info_id=1, login_time=datetime(2025, 1, 1, tzinfo=UTC)),
+ SysLogininfor(info_id=2, login_time=datetime(2025, 1, 2, tzinfo=UTC)),
+ ]
+ )
+ await db.flush()
+ for parameters, expected in [
+ ({'orderByColumn': 'infoId', 'isAsc': 'ascending'}, [1, 2]),
+ ({'orderByColumn': 'infoId', 'isAsc': 'descending'}, [2, 1]),
+ ({'orderByColumn': 'metadata', 'isAsc': 'ascending'}, [2, 1]),
+ ({'isAsc': 'ascending'}, [2, 1]),
+ ({}, [2, 1]),
+ ]:
+ result = await LoginLogDao.get_login_log_list(db, LoginLogPageQueryModel.model_validate(parameters))
+ assert isinstance(result, list)
+ assert [row['infoId'] for row in result] == expected
+ finally:
+ await engine.dispose()
diff --git a/ruoyi-fastapi-backend/tests/module_admin/dao/test_user_auth_queries.py b/ruoyi-fastapi-backend/tests/module_admin/dao/test_user_auth_queries.py
index 3ce6bee3a..5bc828adb 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/dao/test_user_auth_queries.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/dao/test_user_auth_queries.py
@@ -60,7 +60,7 @@ async def user_query_env() -> AsyncIterator[SimpleNamespace]:
sessions = async_sessionmaker(engine, expire_on_commit=False, autoflush=False)
async with engine.begin() as connection:
await connection.run_sync(
- lambda conn: Base.metadata.create_all(conn, tables=[model.__table__ for model in tables])
+ lambda conn: Base.metadata.create_all(conn, tables=[model.get_table() for model in tables])
)
async with sessions.begin() as db:
db.add_all(
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/file_helpers.py b/ruoyi-fastapi-backend/tests/module_admin/service/file_helpers.py
new file mode 100644
index 000000000..d85408ed0
--- /dev/null
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/file_helpers.py
@@ -0,0 +1,25 @@
+from fastapi import FastAPI, Request
+
+
+def make_file_request(
+ *, headers: list[tuple[bytes, bytes]] | None = None, client: tuple[str, int] | None = None
+) -> Request:
+ """
+ 构造挂载在 API 前缀下的文件服务请求。
+
+ :param headers: 原始 HTTP 请求头
+ :param client: 客户端地址和端口
+ :return: 带独立应用状态的请求
+ """
+ return Request(
+ {
+ 'type': 'http',
+ 'scheme': 'https',
+ 'server': ('example.test', 443),
+ 'root_path': '/prod-api',
+ 'path': '/prod-api/common',
+ 'headers': headers or [],
+ 'client': client,
+ 'app': FastAPI(),
+ }
+ )
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/helpers.py b/ruoyi-fastapi-backend/tests/module_admin/service/helpers.py
new file mode 100644
index 000000000..b855c56fb
--- /dev/null
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/helpers.py
@@ -0,0 +1,66 @@
+from unittest.mock import NonCallableMagicMock, create_autospec
+
+from fastapi import FastAPI, Request
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from module_admin.entity.vo.dept_vo import DeptModel
+from module_admin.entity.vo.role_vo import RoleModel
+from module_admin.entity.vo.user_vo import CurrentUserModel, UserInfoModel
+
+
+def make_query_db(commit_error: Exception | None = None) -> NonCallableMagicMock:
+ """
+ 创建记录事务操作的异步会话替身。
+
+ :param commit_error: 提交时抛出的异常
+ :return: 遵循异步数据库会话接口的模拟对象
+ """
+ session = create_autospec(AsyncSession, instance=True, spec_set=True)
+ assert isinstance(session, NonCallableMagicMock)
+ session.commit.side_effect = commit_error
+ return session
+
+
+def make_current_user(
+ user_id: int = 10,
+ *,
+ user_name: str | None = None,
+ admin: bool = False,
+ role_ids: list[int] | None = None,
+ dept_id: int | None = None,
+ ancestors: str = '',
+) -> CurrentUserModel:
+ """
+ 构造后台服务测试使用的当前用户。
+
+ :param user_id: 用户标识
+ :param user_name: 用户账号
+ :param admin: 是否为管理员
+ :param role_ids: 已分配角色标识
+ :param dept_id: 所属部门标识
+ :param ancestors: 部门祖先标识串
+ :return: 包含角色和部门信息的当前用户
+ """
+ roles = role_ids or []
+ user = UserInfoModel(
+ user_id=user_id,
+ user_name=user_name if user_name is not None else f'user{user_id}',
+ admin=admin,
+ role=[RoleModel(role_id=role_id) for role_id in roles],
+ role_ids=','.join(str(role_id) for role_id in roles),
+ dept_id=dept_id,
+ dept=DeptModel(dept_id=dept_id, ancestors=ancestors) if dept_id is not None else None,
+ )
+ return CurrentUserModel(user=user, roles=[], permissions=[])
+
+
+def make_redis_request(redis: object) -> Request:
+ """
+ 构造带有 Redis 客户端的后台请求。
+
+ :param redis: 当前应用使用的 Redis 客户端或测试替身
+ :return: 携带独立应用状态的 HTTP 请求
+ """
+ app = FastAPI()
+ app.state.redis = redis
+ return Request({'type': 'http', 'app': app, 'headers': []})
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_cached_session_races.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_cached_session_races.py
index 901803afd..11f104c9e 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_cached_session_races.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_cached_session_races.py
@@ -43,6 +43,7 @@ async def _prepare_cached_session(
"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
token = env.headers[USER_ID]['Authorization'].removeprefix('Bearer ')
+ assert isinstance(token, str)
token_id = f'session-{USER_ID}' if same_time_login else str(USER_ID)
token_key = f'access_token:{token_id}'
await env.redis.set(token_key, token, ex=60)
@@ -64,7 +65,7 @@ async def _prepare_cached_session(
async def _resolve_cached_session(
env: SimpleNamespace, request: Request, token: str, for_plugin: bool
-) -> CurrentUserModel:
+) -> CurrentUserModel | None:
"""
通过新数据库会话进入真实缓存命中及最终会话校验路径。
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_common_file_security.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_common_file_security.py
index b3b9af811..91248ff88 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_common_file_security.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_common_file_security.py
@@ -5,6 +5,7 @@
from datetime import UTC, datetime, timedelta
from pathlib import Path
from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock, patch
import pytest
@@ -17,8 +18,12 @@
from middlewares.cors_middleware import add_cors_middleware
from module_admin.dao.file_access_dao import FileAclDao
from module_admin.dao.file_info_dao import FileInfoDao
+from module_admin.entity.vo.common_vo import UploadResponseModel
+from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.common_service import CommonService
from sub_applications.staticfiles import SecureStaticFiles
+from tests.module_admin.service.file_helpers import make_file_request
+from tests.module_admin.service.helpers import make_current_user, make_query_db
from utils.file_util import FileUtil
from utils.upload_util import FilePathUtil, UploadUtil
@@ -61,29 +66,6 @@ def make_upload(filename: str, content: bytes) -> UploadFile:
return UploadFile(file=io.BytesIO(content), filename=filename)
-def make_current_user(user_id: int = 10, admin: bool = False, dept_id: int = 100) -> SimpleNamespace:
- """
- 创建测试使用的 ``SimpleNamespace`` 实例。
-
- :param user_id: 用户的唯一标识
- :param admin: 是否使用管理员身份
- :param dept_id: 部门id
- :return: 测试使用的 ``SimpleNamespace`` 实例
- """
- return SimpleNamespace(
- user=SimpleNamespace(user_id=user_id, user_name=f'user{user_id}', admin=admin, dept_id=dept_id)
- )
-
-
-def make_query_db() -> SimpleNamespace:
- """
- 创建测试使用的 ``SimpleNamespace`` 实例。
-
- :return: 测试使用的 ``SimpleNamespace`` 实例
- """
- return SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
-
-
@pytest.mark.parametrize(
('range_header', 'expected'),
[
@@ -277,9 +259,9 @@ def test_upload_uses_server_generated_filename_and_stays_in_upload_root(tmp_path
"""上传使用服务端生成的名称并写入上传根目录。"""
upload_root = tmp_path / 'profile'
upload = make_upload('../../attack:bad?.txt', b'safe-content')
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
query_db = make_query_db()
- current_user = make_current_user()
+ current_user = make_current_user(dept_id=100)
with (
patch.object(UploadConfig, 'UPLOAD_PATH', str(upload_root)),
@@ -288,17 +270,21 @@ def test_upload_uses_server_generated_filename_and_stays_in_upload_root(tmp_path
patch.object(CommonService, '_enqueue_file_access_log', new_callable=AsyncMock),
):
result = asyncio.run(CommonService.upload_service(request, query_db, current_user, upload))
+ uploaded = result.result
+ assert isinstance(uploaded, UploadResponseModel)
+ assert uploaded.new_file_name is not None
+ assert uploaded.file_name is not None
written_files = list(upload_root.rglob('*.*'))
assert len(written_files) == 1
assert written_files[0].resolve().is_relative_to(upload_root.resolve())
assert written_files[0].read_bytes() == b'safe-content'
- assert result.result.original_filename == 'attack:bad?.txt'
- assert re.fullmatch(r'attack_bad_\d{14}A\d{3}\.txt', result.result.new_file_name)
- assert written_files[0].name == result.result.new_file_name
- assert result.result.access_type == 'public'
- assert result.result.file_id
- file_info = add_file_info.await_args.args[1]
+ assert uploaded.original_filename == 'attack:bad?.txt'
+ assert re.fullmatch(r'attack_bad_\d{14}A\d{3}\.txt', uploaded.new_file_name)
+ assert written_files[0].name == uploaded.new_file_name
+ assert uploaded.access_type == 'public'
+ assert uploaded.file_id
+ file_info = add_file_info.await_args_list[-1].args[1]
assert file_info.upload_user_id == current_user.user.user_id
assert file_info.owner_user_id == current_user.user.user_id
assert file_info.dept_id == current_user.user.dept_id
@@ -307,7 +293,7 @@ def test_upload_uses_server_generated_filename_and_stays_in_upload_root(tmp_path
query_db.commit.assert_awaited_once()
with patch.object(UploadConfig, 'UPLOAD_PATH', str(upload_root)):
- download_result = asyncio.run(CommonService.download_resource_services(result.result.file_name))
+ download_result = asyncio.run(CommonService.download_resource_services(uploaded.file_name))
assert asyncio.run(collect_stream(download_result.data)) == b'safe-content'
@@ -316,9 +302,9 @@ def test_upload_accepts_html_as_download_only_file(tmp_path: Path, extension: st
"""允许上传 HTML 并仅供下载。"""
file_content = b''
upload = make_upload(f'attack.{extension}', file_content)
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
query_db = make_query_db()
- current_user = make_current_user()
+ current_user = make_current_user(dept_id=100)
with (
patch.object(UploadConfig, 'UPLOAD_PATH', str(tmp_path)),
@@ -327,21 +313,25 @@ def test_upload_accepts_html_as_download_only_file(tmp_path: Path, extension: st
patch.object(CommonService, '_enqueue_file_access_log', new_callable=AsyncMock),
):
result = asyncio.run(CommonService.upload_service(request, query_db, current_user, upload))
- download_result = asyncio.run(CommonService.download_resource_services(result.result.file_name))
+ uploaded = result.result
+ assert isinstance(uploaded, UploadResponseModel)
+ assert uploaded.new_file_name is not None
+ assert uploaded.file_name is not None
+ download_result = asyncio.run(CommonService.download_resource_services(uploaded.file_name))
written_files = [path for path in tmp_path.rglob('*') if path.is_file()]
assert len(written_files) == 1
assert written_files[0].read_bytes() == file_content
- assert re.fullmatch(rf'attack_\d{{14}}A\d{{3}}\.{extension}', result.result.new_file_name)
+ assert re.fullmatch(rf'attack_\d{{14}}A\d{{3}}\.{extension}', uploaded.new_file_name)
assert asyncio.run(collect_stream(download_result.data)) == file_content
def test_upload_enforces_total_size_and_removes_partial_file(tmp_path: Path) -> None:
"""上传限制总大小并清理未完成文件。"""
upload = make_upload('large.txt', b'12345')
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
query_db = make_query_db()
- current_user = make_current_user()
+ current_user = make_current_user(dept_id=100)
with (
patch.object(UploadConfig, 'UPLOAD_PATH', str(tmp_path)),
@@ -353,16 +343,19 @@ def test_upload_enforces_total_size_and_removes_partial_file(tmp_path: Path) ->
assert [path for path in tmp_path.rglob('*') if path.is_file()] == []
-def test_upload_rejects_unknown_access_type_before_writing(tmp_path: Path) -> None:
+@pytest.mark.parametrize('access_type', ['shared', ''])
+def test_upload_rejects_unknown_access_type_before_writing(tmp_path: Path, access_type: Any) -> None:
"""写入前拒绝未知访问类型。"""
upload = make_upload('report.txt', b'report-content')
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
with (
patch.object(UploadConfig, 'PRIVATE_UPLOAD_PATH', str(tmp_path)),
pytest.raises(ServiceException),
):
- asyncio.run(CommonService.upload_service(request, make_query_db(), make_current_user(), upload, 'shared'))
+ asyncio.run(
+ CommonService.upload_service(request, make_query_db(), make_current_user(dept_id=100), upload, access_type)
+ )
assert list(tmp_path.rglob('*')) == []
@@ -370,9 +363,9 @@ def test_upload_rejects_unknown_access_type_before_writing(tmp_path: Path) -> No
def test_upload_removes_file_when_metadata_write_fails(tmp_path: Path) -> None:
"""元数据写入失败时清理已上传文件。"""
upload = make_upload('report.txt', b'report-content')
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
query_db = make_query_db()
- current_user = make_current_user()
+ current_user = make_current_user(dept_id=100)
with (
patch.object(UploadConfig, 'UPLOAD_PATH', str(tmp_path)),
@@ -393,9 +386,9 @@ def test_upload_retries_name_collision_without_deleting_existing_file(tmp_path:
existing_file.parent.mkdir(parents=True)
existing_file.write_bytes(b'existing-content')
upload = make_upload('report.txt', b'new-content')
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
query_db = make_query_db()
- current_user = make_current_user()
+ current_user = make_current_user(dept_id=100)
with (
patch.object(UploadConfig, 'UPLOAD_PATH', str(tmp_path)),
@@ -405,10 +398,12 @@ def test_upload_retries_name_collision_without_deleting_existing_file(tmp_path:
patch.object(CommonService, '_enqueue_file_access_log', new_callable=AsyncMock),
):
result = asyncio.run(CommonService.upload_service(request, query_db, current_user, upload))
+ uploaded = result.result
+ assert isinstance(uploaded, UploadResponseModel)
assert existing_file.read_bytes() == b'existing-content'
- assert result.result.new_file_name == 'report_20260719120000A002.txt'
- assert (existing_file.parent / result.result.new_file_name).read_bytes() == b'new-content'
+ assert uploaded.new_file_name == 'report_20260719120000A002.txt'
+ assert (existing_file.parent / uploaded.new_file_name).read_bytes() == b'new-content'
def test_private_upload_is_physically_isolated_and_owner_can_download(tmp_path: Path) -> None:
@@ -416,9 +411,9 @@ def test_private_upload_is_physically_isolated_and_owner_can_download(tmp_path:
public_root = tmp_path / 'public'
private_root = tmp_path / 'private'
upload = make_upload('contract.pdf', b'private-content')
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
query_db = make_query_db()
- current_user = make_current_user()
+ current_user = make_current_user(dept_id=100)
with (
patch.object(UploadConfig, 'UPLOAD_PATH', str(public_root)),
@@ -429,18 +424,22 @@ def test_private_upload_is_physically_isolated_and_owner_can_download(tmp_path:
result = asyncio.run(
CommonService.upload_service(request, query_db, current_user, upload, access_type='private')
)
- file_info = add_file_info.await_args.args[1]
+ uploaded = result.result
+ assert isinstance(uploaded, UploadResponseModel)
+ assert uploaded.file_name is not None
+ assert uploaded.file_id is not None
+ file_info = add_file_info.await_args_list[-1].args[1]
with patch.object(FileInfoDao, 'get_file_info_by_id', new=AsyncMock(return_value=file_info)):
download_result = asyncio.run(
- CommonService.download_managed_file_services(request, query_db, current_user, result.result.file_id)
+ CommonService.download_managed_file_services(request, query_db, current_user, uploaded.file_id)
)
assert asyncio.run(collect_stream(download_result.data)) == b'private-content'
assert list(public_root.rglob('*')) == []
assert len([path for path in private_root.rglob('*') if path.is_file()]) == 1
- assert result.result.file_name.startswith('/common/files/')
- assert not result.result.file_name.startswith(UploadConfig.UPLOAD_PREFIX)
- assert result.result.access_type == 'private'
+ assert uploaded.file_name.startswith('/common/files/')
+ assert not uploaded.file_name.startswith(UploadConfig.UPLOAD_PREFIX)
+ assert uploaded.access_type == 'private'
assert download_result.filename == 'contract.pdf'
audit_results = [call.kwargs['result'] for call in enqueue_audit.await_args_list]
assert audit_results == ['completed', 'allowed', 'completed']
@@ -461,9 +460,9 @@ def test_private_download_rejects_other_user(tmp_path: Path) -> None:
storage_key='upload/2026/07/contract_20260719120000A001.pdf',
original_name='contract.pdf',
)
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
query_db = make_query_db()
- other_user = make_current_user(user_id=20)
+ other_user = make_current_user(dept_id=100, user_id=20)
with (
patch.object(UploadConfig, 'PRIVATE_UPLOAD_PATH', str(private_root)),
@@ -475,7 +474,7 @@ def test_private_download_rejects_other_user(tmp_path: Path) -> None:
asyncio.run(CommonService.download_managed_file_services(request, query_db, other_user, 'file-id'))
enqueue_audit.assert_awaited_once()
- assert enqueue_audit.await_args.kwargs['result'] == 'denied'
+ assert enqueue_audit.await_args_list[-1].kwargs['result'] == 'denied'
def test_file_manager_can_download_private_file_without_owner_match(tmp_path: Path) -> None:
@@ -493,9 +492,9 @@ def test_file_manager_can_download_private_file_without_owner_match(tmp_path: Pa
storage_key='upload/2026/07/contract_20260719120000A001.pdf',
original_name='contract.pdf',
)
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
query_db = make_query_db()
- file_manager = make_current_user(user_id=20)
+ file_manager = make_current_user(dept_id=100, user_id=20)
with (
patch.object(UploadConfig, 'PRIVATE_UPLOAD_PATH', str(private_root)),
@@ -518,9 +517,9 @@ def test_file_manager_can_download_private_file_without_owner_match(tmp_path: Pa
def test_file_manager_download_rejects_file_outside_data_scope() -> None:
"""文件管理员不能下载数据范围外的文件。"""
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
query_db = make_query_db()
- file_manager = make_current_user(user_id=20)
+ file_manager = make_current_user(dept_id=100, user_id=20)
file_data_scope_sql = false()
with (
@@ -539,21 +538,21 @@ def test_file_manager_download_rejects_file_outside_data_scope() -> None:
)
)
- assert get_file_info.await_args.args[2] is file_data_scope_sql
- assert enqueue_audit.await_args.kwargs['result'] == 'denied'
+ assert get_file_info.await_args_list[-1].args[2] is file_data_scope_sql
+ assert enqueue_audit.await_args_list[-1].kwargs['result'] == 'denied'
@pytest.mark.parametrize(
('access_type', 'current_user'),
[
- ('private', make_current_user(user_id=1, admin=True)),
- ('public', make_current_user(user_id=20)),
+ ('private', make_current_user(dept_id=100, user_id=1, admin=True)),
+ ('public', make_current_user(dept_id=100, user_id=20)),
],
)
def test_managed_download_allows_administrator_or_public_file(
tmp_path: Path,
access_type: str,
- current_user: SimpleNamespace,
+ current_user: CurrentUserModel,
) -> None:
"""托管下载允许管理员或公开文件访问。"""
storage_root = tmp_path / access_type
@@ -569,7 +568,7 @@ def test_managed_download_allows_administrator_or_public_file(
storage_key='upload/2026/07/report_20260719120000A001.txt',
original_name='report.txt',
)
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
query_db = make_query_db()
with (
@@ -600,9 +599,9 @@ def test_private_download_rejects_expired_file(tmp_path: Path, admin: bool) -> N
storage_key='upload/2026/07/report_20260719120000A001.txt',
original_name='report.txt',
)
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
query_db = make_query_db()
- current_user = make_current_user(user_id=10, admin=admin)
+ current_user = make_current_user(dept_id=100, user_id=10, admin=admin)
with (
patch.object(UploadConfig, 'PRIVATE_UPLOAD_PATH', str(private_root)),
@@ -613,15 +612,15 @@ def test_private_download_rejects_expired_file(tmp_path: Path, admin: bool) -> N
asyncio.run(CommonService.download_managed_file_services(request, query_db, current_user, 'file-id'))
enqueue_audit.assert_awaited_once()
- assert enqueue_audit.await_args.kwargs['result'] == 'denied'
+ assert enqueue_audit.await_args_list[-1].kwargs['result'] == 'denied'
def test_managed_download_records_interrupted_stream(tmp_path: Path) -> None:
"""托管下载记录被中断的数据流。"""
target = tmp_path / 'report.txt'
target.write_bytes(b'partial-content')
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
- current_user = make_current_user()
+ request = make_file_request()
+ current_user = make_current_user(dept_id=100)
with patch.object(CommonService, '_enqueue_file_access_log', new_callable=AsyncMock) as enqueue_audit:
byte_range = FileUtil.parse_byte_range(None, target.stat().st_size)
@@ -629,8 +628,8 @@ def test_managed_download_records_interrupted_stream(tmp_path: Path) -> None:
assert asyncio.run(collect_first_chunk_and_close(stream)) == b'partial-content'
enqueue_audit.assert_awaited_once()
- assert enqueue_audit.await_args.kwargs['result'] == 'failed'
- assert enqueue_audit.await_args.kwargs['error_message'] == 'StreamClosed'
+ assert enqueue_audit.await_args_list[-1].kwargs['result'] == 'failed'
+ assert enqueue_audit.await_args_list[-1].kwargs['error_message'] == 'StreamClosed'
def test_managed_download_supports_range_and_records_partial_bytes(tmp_path: Path) -> None:
@@ -648,9 +647,9 @@ def test_managed_download_supports_range_and_records_partial_bytes(tmp_path: Pat
storage_key='upload/2026/07/report_20260719120000A001.txt',
original_name='report.txt',
)
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
query_db = make_query_db()
- current_user = make_current_user()
+ current_user = make_current_user(dept_id=100)
with (
patch.object(UploadConfig, 'PRIVATE_UPLOAD_PATH', str(storage_root)),
@@ -695,7 +694,7 @@ def test_managed_download_audits_unsatisfied_range_without_disclosing_before_per
storage_key='upload/2026/07/report_20260719120000A001.txt',
original_name='report.txt',
)
- request = SimpleNamespace(base_url='https://example.test/prod-api/', headers={}, client=None)
+ request = make_file_request()
with (
patch.object(UploadConfig, 'PRIVATE_UPLOAD_PATH', str(storage_root)),
@@ -707,15 +706,15 @@ def test_managed_download_audits_unsatisfied_range_without_disclosing_before_per
CommonService.download_managed_file_services(
request,
make_query_db(),
- make_current_user(),
+ make_current_user(dept_id=100),
'file-id',
range_header='bytes=20-',
)
)
enqueue_audit.assert_awaited_once()
- assert enqueue_audit.await_args.kwargs['result'] == 'failed'
- assert enqueue_audit.await_args.kwargs['error_message'] == 'RangeNotSatisfiable'
+ assert enqueue_audit.await_args_list[-1].kwargs['result'] == 'failed'
+ assert enqueue_audit.await_args_list[-1].kwargs['error_message'] == 'RangeNotSatisfiable'
def test_download_headers_force_attachment_and_disable_sniffing() -> None:
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py
index 05b60dedd..f615d0927 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py
@@ -429,15 +429,16 @@ async def test_multi_bind_sessions_keep_original_database_resolution(
"""多绑定会话保留原数据库解析行为。"""
engine = cache_env.sessions.kw['bind']
secondary = create_async_engine(engine.url)
- bindings = dict.fromkeys(
- (SysUser, SysDept, SysRole, SysPost, SysMenu, SysUserRole, SysUserPost, SysRoleMenu), engine
- )
- if default_bind:
- bindings[SysRole] = secondary
read = AsyncMock(side_effect=AssertionError('多绑定会话不应访问用户快照缓存'))
monkeypatch.setattr(CurrentUserCacheUtil, 'read', read)
try:
- async with AsyncSession(bind=engine if default_bind else None, binds=bindings) as db:
+ async with AsyncSession(
+ bind=engine if default_bind else None,
+ binds={
+ model: secondary if default_bind and model is SysRole else engine
+ for model in (SysUser, SysDept, SysRole, SysPost, SysMenu, SysUserRole, SysUserPost, SysRoleMenu)
+ },
+ ) as db:
user = await LoginService._get_current_user_snapshot(cache_env.redis, db, USER_ID)
assert user.user.user_id == USER_ID
assert user.permissions == ['demo:read']
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_mutations.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_mutations.py
index 37d42cbff..122a74b8a 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_mutations.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_mutations.py
@@ -2,7 +2,7 @@
from typing import Any
import pytest
-from sqlalchemy import delete, update
+from sqlalchemy import Alias, delete, update
from sqlalchemy.orm import aliased
from common.constant import HttpStatusConstant
@@ -112,7 +112,7 @@ async def test_user_role_assignment_and_revocation_refresh_admin_permission(
) -> None:
"""分配或撤销用户角色后刷新管理员权限。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
- assignment = UserRoleModel(userId=USER_ID, roleId=ADMIN_ID)
+ assignment = UserRoleModel(user_id=USER_ID, role_id=ADMIN_ID)
async with cache_env.sessions.begin() as db:
await UserDao.add_user_role_dao(db, assignment)
@@ -131,7 +131,7 @@ async def test_user_role_assignment_and_revocation_refresh_admin_permission(
async def test_user_post_removal_and_assignment_refresh_cached_post_ids(cache_env: SimpleNamespace) -> None: # noqa: F811
"""删除或分配用户岗位后刷新缓存的岗位标识。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
- assignment = UserPostModel(userId=USER_ID, postId=USER_ID)
+ assignment = UserPostModel(user_id=USER_ID, post_id=USER_ID)
async with cache_env.sessions.begin() as db:
await UserDao.delete_user_post_dao(db, assignment)
@@ -179,10 +179,17 @@ async def test_aliased_mutations_refresh_cached_user_and_permissions(
"""通过别名修改数据后刷新用户及权限缓存。"""
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
assert first.json()['permissions'] == ['demo:read']
- model = SysUser if target_name == 'user' else SysMenu
- target = aliased(model, name='cache_target') if alias_type == 'orm' else model.__table__.alias('cache_target')
- columns = target if alias_type == 'orm' else target.c
- target_id = columns.user_id if target_name == 'user' else columns.menu_id
+ if alias_type == 'core':
+ table = SysUser.__table__ if target_name == 'user' else SysMenu.__table__
+ target = table.alias('cache_target')
+ assert isinstance(target, Alias)
+ target_id = target.c.user_id if target_name == 'user' else target.c.menu_id
+ elif target_name == 'user':
+ target = aliased(SysUser, name='cache_target')
+ target_id = target.user_id
+ else:
+ target = aliased(SysMenu, name='cache_target')
+ target_id = target.menu_id
if mutation == 'update':
values = {'nick_name': 'Alias updated reader'} if target_name == 'user' else {'perms': 'demo:updated'}
statement = update(target).where(target_id == USER_ID).values(**values)
@@ -215,7 +222,9 @@ async def test_alias_update_with_original_table_condition_refreshes_all_affected
for user_id in (ADMIN_ID, USER_ID):
response = await cache_env.client.get('/profile', headers=cache_env.headers[user_id])
assert response.json()['user']['userId'] == user_id
- target = SysUser.__table__.alias('cache_target')
+ table = SysUser.__table__
+ target = table.alias('cache_target')
+ assert isinstance(target, Alias)
async with cache_env.sessions.begin() as db:
# 条件引用原表,匹配管理员时会更新别名目标中的全部用户。
await db.execute(
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py
index a951080b4..dffe209c6 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py
@@ -101,7 +101,7 @@ async def resolution_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Asy
tables = [SysUser, SysDept, SysRole, SysPost, SysMenu, SysUserRole, SysUserPost, SysRoleMenu]
async with engine.begin() as connection:
await connection.run_sync(
- lambda conn: Base.metadata.create_all(conn, tables=[model.__table__ for model in tables])
+ lambda conn: Base.metadata.create_all(conn, tables=[model.get_table() for model in tables])
)
async with sessions.begin() as db:
db.add_all(
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_dept_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_dept_service.py
index 646e13f66..2877d4ff3 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_dept_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_dept_service.py
@@ -1,4 +1,3 @@
-from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, patch
@@ -12,6 +11,17 @@
from module_admin.entity.do.dept_do import SysDept
from module_admin.entity.vo.dept_vo import DeptModel, DeptSortModel
from module_admin.service.dept_service import DeptService
+from tests.module_admin.service.helpers import make_query_db
+
+
+def test_dept_tree_keeps_unnamed_root_with_its_children() -> None:
+ """部门名称和父编号为空时,树仍应保留该部门及其子节点。"""
+ root = SysDept(dept_id=10, dept_name=None, parent_id=None)
+ child = SysDept(dept_id=11, dept_name='研发', parent_id=10)
+ (tree,) = DeptService.list_to_tree([child, root])
+ assert (tree.id, tree.label, tree.parent_id) == (10, '部门(10)', 0)
+ assert tree.children is not None
+ assert [node.id for node in tree.children] == [11]
async def _create_dept_table() -> tuple[AsyncEngine, async_sessionmaker[AsyncSession]]:
@@ -34,13 +44,13 @@ def register_find_in_set(connection: Any, _record: Any) -> None:
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysDept.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysDept.get_table()])
return engine, session_maker
def test_parse_dept_sort_items_preserves_corresponding_order_values() -> None:
"""解析部门排序时保留各部门对应的顺序值。"""
- result = DeptService.parse_dept_sort_items(DeptSortModel(deptIds='101, 102', orderNums='3, 1'))
+ result = DeptService.parse_dept_sort_items(DeptSortModel(dept_ids='101, 102', order_nums='3, 1'))
assert result == [
{'dept_id': 101, 'order_num': 3},
@@ -61,7 +71,7 @@ def test_parse_dept_sort_items_preserves_corresponding_order_values() -> None:
def test_parse_dept_sort_items_rejects_invalid_parameters(dept_ids: str, order_nums: str) -> None:
"""部门排序拒绝无效参数。"""
with pytest.raises(ServiceException) as exc_info:
- DeptService.parse_dept_sort_items(DeptSortModel(deptIds=dept_ids, orderNums=order_nums))
+ DeptService.parse_dept_sort_items(DeptSortModel(dept_ids=dept_ids, order_nums=order_nums))
assert exc_info.value.message == '部门排序参数不正确'
@@ -82,7 +92,7 @@ async def test_update_dept_sort_updates_all_rows_in_one_transaction() -> None:
result = await DeptService.update_dept_sort_services(
session,
- DeptSortModel(deptIds='101,102', orderNums='5,4'),
+ DeptSortModel(dept_ids='101,102', order_nums='5,4'),
)
rows = (await session.execute(select(SysDept.dept_id, SysDept.order_num).order_by(SysDept.dept_id))).all()
@@ -95,7 +105,7 @@ async def test_update_dept_sort_updates_all_rows_in_one_transaction() -> None:
@pytest.mark.asyncio
async def test_update_dept_sort_rolls_back_and_wraps_database_error() -> None:
"""部门排序遇到数据库错误时回滚并转换异常。"""
- query_db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ query_db = make_query_db()
with (
patch.object(DeptDao, 'update_dept_sort_dao', AsyncMock(side_effect=RuntimeError('database error'))),
@@ -103,7 +113,7 @@ async def test_update_dept_sort_rolls_back_and_wraps_database_error() -> None:
):
await DeptService.update_dept_sort_services(
query_db,
- DeptSortModel(deptIds='101', orderNums='2'),
+ DeptSortModel(dept_ids='101', order_nums='2'),
)
assert exc_info.value.message == '保存排序异常,请联系管理员'
@@ -142,7 +152,7 @@ async def test_edit_dept_rejects_cycles_and_invalid_parents_without_writing(pare
before = (await session.execute(query)).all()
with pytest.raises(ServiceException):
await DeptService.edit_dept_services(
- session, DeptModel(deptId=101, parentId=parent_id, deptName='研发部门', orderNum=1)
+ session, DeptModel(dept_id=101, parent_id=parent_id, dept_name='研发部门', order_num=1)
)
assert (await session.execute(query)).all() == before
finally:
@@ -159,7 +169,7 @@ async def test_edit_dept_moves_whole_subtree_and_rebuilds_ancestors(parent_id: i
await _seed_dept_tree(session)
result = await DeptService.edit_dept_services(
session,
- DeptModel(deptId=101, parentId=parent_id, deptName='研发部门', ancestors='forged', orderNum=1),
+ DeptModel(dept_id=101, parent_id=parent_id, dept_name='研发部门', ancestors='forged', order_num=1),
)
ancestor_prefix = '0' if parent_id == 0 else '0,100,200'
rows = (
@@ -190,7 +200,7 @@ async def test_edit_dept_preserves_omitted_parent_and_ignores_supplied_ancestors
query = select(SysDept.parent_id, SysDept.ancestors).where(SysDept.dept_id == dept_id)
before = (await session.execute(query)).one()
await DeptService.edit_dept_services(
- session, DeptModel(deptId=dept_id, deptName='新名称', ancestors='0,999', orderNum=1)
+ session, DeptModel(dept_id=dept_id, dept_name='新名称', ancestors='0,999', order_num=1)
)
assert (await session.execute(query)).one() == before
finally:
@@ -207,9 +217,31 @@ async def test_add_dept_rejects_missing_or_deleted_parent(parent_id: int | None)
await _seed_dept_tree(session)
with pytest.raises(ServiceException) as exc_info:
await DeptService.add_dept_services(
- session, DeptModel(deptId=300, parentId=parent_id, deptName='新部门', orderNum=1)
+ session, DeptModel(dept_id=300, parent_id=parent_id, dept_name='新部门', order_num=1)
)
assert exc_info.value.message == '上级部门不存在'
assert await session.get(SysDept, 300) is None
finally:
await engine.dispose()
+
+
+@pytest.mark.asyncio
+async def test_moving_subtree_with_missing_ancestor_path_rolls_back() -> None:
+ """祖级列表缺失时,移动部门应回滚,保留原有父子关系。"""
+ engine, sessions = await _create_dept_table()
+ try:
+ async with sessions() as session:
+ await _seed_dept_tree(session)
+ dept_id = 101
+ dept = await session.get(SysDept, dept_id)
+ assert dept is not None
+ previous_parent = dept.parent_id
+ dept.ancestors = ''
+ await session.commit()
+ with pytest.raises(ValueError, match='部门祖级列表不完整'):
+ await DeptService.edit_dept_services(
+ session, DeptModel(dept_id=dept_id, parent_id=200, dept_name='研发部门')
+ )
+ assert await session.scalar(select(SysDept.parent_id).where(SysDept.dept_id == dept_id)) == previous_parent
+ finally:
+ await engine.dispose()
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_access_log.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_access_log.py
index 6390e5e5d..796bbd781 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_access_log.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_access_log.py
@@ -2,8 +2,9 @@
import json
from datetime import UTC, datetime
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, create_autospec, patch
+from redis.asyncio import Redis
from sqlalchemy import Text
from config.env import LogConfig
@@ -12,6 +13,8 @@
from module_admin.entity.vo.file_vo import FileAccessLogModel
from module_admin.service.file_access_service import FileAuditService
from module_admin.service.log_service import LogAggregatorService, LogQueueService
+from tests.module_admin.service.file_helpers import make_file_request
+from tests.module_admin.service.helpers import make_current_user, make_query_db
FILE_SIZE = 12
BATCH_FILE_COUNT = 2
@@ -69,18 +72,18 @@ def make_file_access_log() -> FileAccessLogModel:
:return: 测试使用的 ``FileAccessLogModel`` 实例
"""
return FileAccessLogModel(
- fileId='file-id',
+ file_id='file-id',
action='download',
- actorUserId=10,
- actorName='user10',
+ actor_user_id=10,
+ actor_name='user10',
result='completed',
- requestId='request-id',
- traceId='trace-id',
- ipAddress='127.0.0.1',
- userAgent='pytest',
- bytesSent=FILE_SIZE,
- operationDetail='{"newStatus":"active"}',
- accessTime=datetime(2026, 7, 19, 12, 0, 0, tzinfo=UTC),
+ request_id='request-id',
+ trace_id='trace-id',
+ ip_address='127.0.0.1',
+ user_agent='pytest',
+ bytes_sent=FILE_SIZE,
+ operation_detail='{"newStatus":"active"}',
+ access_time=datetime(2026, 7, 19, 12, 0, 0, tzinfo=UTC),
)
@@ -95,7 +98,8 @@ def test_file_access_log_operation_detail_uses_unbounded_text_type() -> None:
def test_file_access_log_is_enqueued_to_redis_stream() -> None:
"""文件访问日志进入 Redis Stream。"""
redis = SimpleNamespace(xadd=AsyncMock())
- request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis)))
+ request = make_file_request()
+ request.app.state.redis = redis
with (
patch('module_admin.service.log_service.TraceCtx.get_request_id', return_value='request-id'),
@@ -105,7 +109,7 @@ def test_file_access_log_is_enqueued_to_redis_stream() -> None:
asyncio.run(LogQueueService.enqueue_file_access_log(request, make_file_access_log(), 'file:download:completed'))
redis.xadd.assert_awaited_once()
- stream_name, event = redis.xadd.await_args.args
+ stream_name, event = redis.xadd.await_args_list[-1].args
assert stream_name == LogConfig.log_stream_key
assert event['event_type'] == 'file_access'
payload = json.loads(event['payload'])
@@ -118,8 +122,11 @@ def test_file_access_log_is_enqueued_to_redis_stream() -> None:
def test_file_access_log_event_is_persisted_and_acknowledged() -> None:
"""持久化文件访问日志后确认事件。"""
- session = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
- redis = SimpleNamespace(set=AsyncMock(return_value=True), xack=AsyncMock(), delete=AsyncMock())
+ session = make_query_db()
+ redis = create_autospec(Redis, instance=True, spec_set=True)
+ redis.set = AsyncMock(return_value=True)
+ redis.xack = AsyncMock()
+ redis.delete = AsyncMock()
file_access_log = make_file_access_log()
messages = [
(
@@ -144,7 +151,7 @@ def test_file_access_log_event_is_persisted_and_acknowledged() -> None:
asyncio.run(LogAggregatorService._process_messages(redis, LogConfig.log_stream_key, messages))
add_file_access_log.assert_awaited_once()
- saved_log = add_file_access_log.await_args.args[1]
+ saved_log = add_file_access_log.await_args_list[-1].args[1]
assert saved_log.file_id == 'file-id'
assert saved_log.result == 'completed'
assert saved_log.operation_detail == '{"newStatus":"active"}'
@@ -155,12 +162,9 @@ def test_file_access_log_event_is_persisted_and_acknowledged() -> None:
def test_file_audit_batch_events_use_independent_deduplication_keys() -> None:
"""批量审计事件使用独立的去重键。"""
redis = SimpleNamespace(xadd=AsyncMock())
- request = SimpleNamespace(
- app=SimpleNamespace(state=SimpleNamespace(redis=redis)),
- headers={'User-Agent': 'pytest'},
- client=SimpleNamespace(host='127.0.0.1'),
- )
- current_user = SimpleNamespace(user=SimpleNamespace(user_id=10, user_name='user10'))
+ request = make_file_request(headers=[(b'user-agent', b'pytest')], client=('127.0.0.1', 12345))
+ request.app.state.redis = redis
+ current_user = make_current_user()
async def enqueue_batch() -> None:
"""向文件审计队列投递测试批次。"""
@@ -204,3 +208,29 @@ def test_file_audit_operation_detail_is_not_truncated() -> None:
parsed_detail = json.loads(serialized_detail)
assert parsed_detail['reason'] == reason
+
+
+def test_log_stream_batches_accept_redis_response_formats() -> None:
+ """不同 Redis 流响应格式应产生相同的消息顺序并跳过无标识的空项。"""
+ entries = [('1-0', {'event_id': '一'}), ('2-0', {'event_id': '二'})]
+ expected = [('audit', entries)]
+ assert list(LogAggregatorService._stream_batches([['audit', entries]])) == expected
+ assert (
+ list(
+ LogAggregatorService._stream_batches(
+ {'audit': [('1-0', {'event_id': '一'}), (None, None), ('2-0', {'event_id': '二'})]}
+ )
+ )
+ == expected
+ )
+ assert (
+ list(
+ LogAggregatorService._stream_batches(
+ {'audit': [[('1-0', {'event_id': '一'}), ('2-0', {'event_id': '二'})]]}
+ )
+ )
+ == expected
+ )
+ assert list(LogAggregatorService._stream_batches({b'audit': [(b'1-0', {b'payload': b'{}'})]})) == [
+ (b'audit', [(b'1-0', {'payload': '{}'})])
+ ]
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_acl.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_acl.py
index 07c6bbc9f..9eb92b919 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_acl.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_acl.py
@@ -9,9 +9,12 @@
from exceptions.exception import ServiceException
from module_admin.dao.file_access_dao import FileAclDao
from module_admin.dao.file_info_dao import FileInfoDao
+from module_admin.entity.do.file_do import SysFileAcl, SysFileInfo
from module_admin.entity.vo.file_vo import BatchSaveFileAclModel, SaveFileAclModel
+from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.common_service import CommonService
from module_admin.service.file_access_service import FileAclService, FileAuditService
+from tests.module_admin.service.helpers import make_current_user, make_query_db
FILE_ID = '11111111-1111-4111-8111-111111111111'
FILE_ID_2 = '22222222-2222-4222-8222-222222222222'
@@ -20,60 +23,20 @@
BATCH_FILE_COUNT = 2
-def make_query_db() -> SimpleNamespace:
- """
- 创建测试使用的 ``SimpleNamespace`` 实例。
-
- :return: 测试使用的 ``SimpleNamespace`` 实例
- """
- return SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
-
-
-def make_current_user(
- user_id: int,
- role_ids: list[int] | None = None,
- dept_id: int | None = None,
- ancestors: str = '',
- admin: bool = False,
-) -> SimpleNamespace:
- """
- 构造带有测试所需角色和权限的用户。
-
- :param user_id: 用户的唯一标识
- :param role_ids: 角色id
- :param dept_id: 部门id
- :param ancestors: 当前部门的祖先路径
- :param admin: 是否使用管理员身份
- :return: 带有测试所需角色和权限的用户
- """
- roles = [SimpleNamespace(role_id=role_id) for role_id in (role_ids or [])]
- dept = SimpleNamespace(dept_id=dept_id, ancestors=ancestors) if dept_id else None
- user = SimpleNamespace(
- user_id=user_id,
- user_name=f'user{user_id}',
- admin=admin,
- role=roles,
- role_ids=','.join(str(role_id) for role_id in role_ids or []),
- dept_id=dept_id,
- dept=dept,
- )
- return SimpleNamespace(user=user)
-
-
def make_file_info(
owner_user_id: int = 10,
upload_user_id: int = 11,
uploader_access_enabled: str = '1',
-) -> SimpleNamespace:
+) -> SysFileInfo:
"""
- 创建测试使用的 ``SimpleNamespace`` 实例。
+ 创建测试使用的 ``SysFileInfo`` 实例。
:param owner_user_id: 新所有者用户ID
:param upload_user_id: 上传用户ID
:param uploader_access_enabled: 是否保留上传人访问权限
- :return: 测试使用的 ``SimpleNamespace`` 实例
+ :return: 测试使用的 ``SysFileInfo`` 实例
"""
- return SimpleNamespace(
+ return SysFileInfo(
owner_user_id=owner_user_id,
upload_user_id=upload_user_id,
uploader_access_enabled=uploader_access_enabled,
@@ -113,7 +76,7 @@ def make_acl(
],
)
def test_private_file_acl_allows_matching_user_role_or_department(
- current_user: SimpleNamespace,
+ current_user: CurrentUserModel,
file_acl: SimpleNamespace,
) -> None:
"""私有文件授权匹配用户、角色或部门。"""
@@ -161,12 +124,22 @@ def test_file_acl_department_options_are_returned_as_tree() -> None:
result = asyncio.run(FileAclService.get_file_acl_dept_tree_services(make_query_db(), true()))
assert result[0].id == PARENT_DEPT_ID
+ assert result[0].children
assert result[0].children[0].id == CHILD_DEPT_ID
-def test_file_acl_list_returns_current_version() -> None:
- """文件授权列表返回当前版本。"""
+def test_file_acl_list_returns_current_version_and_entries() -> None:
+ """文件授权列表返回当前版本、部门授权和受限主体的显示名称。"""
acl_version = 7
+ acl = SysFileAcl(
+ acl_id=1,
+ file_id=FILE_ID,
+ subject_type='dept',
+ subject_id=PARENT_DEPT_ID,
+ permission='download',
+ effect='deny',
+ include_children='1',
+ )
with (
patch.object(
FileInfoDao,
@@ -181,7 +154,7 @@ def test_file_acl_list_returns_current_version() -> None:
)
),
),
- patch.object(FileAclDao, 'get_file_acl_list', new=AsyncMock(return_value=[])),
+ patch.object(FileAclDao, 'get_file_acl_list', new=AsyncMock(return_value=[acl])),
patch.object(
FileAclDao,
'get_acl_subject_name_map',
@@ -199,7 +172,12 @@ def test_file_acl_list_returns_current_version() -> None:
)
assert result.acl_version == acl_version
- assert result.entries == []
+ (entry,) = result.entries
+ assert entry.acl_id == acl.acl_id
+ assert (entry.subject_type, entry.subject_id) == ('dept', PARENT_DEPT_ID)
+ assert entry.subject_name == f'不可用或无权查看主体({PARENT_DEPT_ID})'
+ assert entry.effect == 'deny'
+ assert entry.include_children is True
assert [item.source for item in result.builtin_permissions] == ['admin', 'owner', 'uploader']
assert result.builtin_permissions[1].subject_name == '文件所有者'
assert result.builtin_permissions[1].deny_overridable is False
@@ -210,7 +188,7 @@ def test_file_acl_list_returns_current_version() -> None:
def test_file_acl_list_marks_uploader_permission_non_overridable_when_uploader_is_owner() -> None:
"""上传者也是所有者时其权限标记为不可覆盖。"""
- file_info = SimpleNamespace(
+ file_info = SysFileInfo(
acl_version=0,
access_type='private',
owner_user_id=10,
@@ -248,7 +226,7 @@ def test_file_acl_list_marks_uploader_permission_non_overridable_when_uploader_i
def test_file_acl_list_exposes_disabled_uploader_permission() -> None:
"""文件授权列表显示已禁用的上传者权限。"""
- file_info = SimpleNamespace(
+ file_info = SysFileInfo(
access_type='private',
owner_user_id=10,
upload_user_id=11,
@@ -269,14 +247,11 @@ def test_file_acl_list_exposes_disabled_uploader_permission() -> None:
def test_file_acl_role_options_exclude_roles_with_members_outside_user_data_scope() -> None:
"""文件授权角色选项排除成员超出当前用户数据范围的角色。"""
- query_db = SimpleNamespace(
- execute=AsyncMock(
- side_effect=[
- SimpleNamespace(all=lambda: [(5, 20), (5, 30), (6, 20)]),
- SimpleNamespace(all=lambda: [(5, 20), (6, 20)]),
- ]
- )
- )
+ query_db = make_query_db()
+ query_db.execute.side_effect = [
+ SimpleNamespace(all=lambda: [(5, 20), (5, 30), (6, 20)]),
+ SimpleNamespace(all=lambda: [(5, 20), (6, 20)]),
+ ]
result = asyncio.run(
FileAclDao._filter_role_rows_by_data_scope(
@@ -327,7 +302,7 @@ def test_private_file_acl_does_not_allow_uploader_when_compatibility_access_is_d
@pytest.mark.parametrize('current_user', [make_current_user(20, admin=True), make_current_user(20)])
-def test_private_file_acl_admin_or_owner_is_not_blocked_by_deny(current_user: SimpleNamespace) -> None:
+def test_private_file_acl_admin_or_owner_is_not_blocked_by_deny(current_user: CurrentUserModel) -> None:
"""管理员或所有者不受私有文件拒绝规则阻拦。"""
file_info = make_file_info(owner_user_id=20 if not current_user.user.admin else 10)
get_acl_list = AsyncMock(return_value=[make_acl('user', 20, effect='deny')])
@@ -352,9 +327,9 @@ def test_save_file_acl_normalizes_department_scope_and_commits() -> None:
query_db = make_query_db()
current_user = make_current_user(1, admin=True)
acl_version = 3
- file_info = SimpleNamespace(access_type='private', acl_version=acl_version, update_by=None, update_time=None)
+ file_info = SysFileInfo(access_type='private', acl_version=acl_version, update_by=None, update_time=None)
save_model = SaveFileAclModel(
- aclVersion=acl_version,
+ acl_version=acl_version,
entries=[
{
'subjectType': 'dept',
@@ -394,7 +369,7 @@ def test_save_file_acl_normalizes_department_scope_and_commits() -> None:
)
)
- saved_acl_list = replace_file_acl_list.await_args.args[2]
+ saved_acl_list = replace_file_acl_list.await_args_list[-1].args[2]
assert result.is_success is True
assert saved_acl_list[0].include_children == '1'
assert saved_acl_list[1].include_children == '0'
@@ -402,8 +377,8 @@ def test_save_file_acl_normalizes_department_scope_and_commits() -> None:
assert file_info.update_by == 'user1'
query_db.commit.assert_awaited_once()
enqueue_file_audit.assert_awaited_once()
- assert enqueue_file_audit.await_args.args[3:5] == ('acl_update', 'completed')
- audit_detail = enqueue_file_audit.await_args.kwargs['operation_detail']
+ assert enqueue_file_audit.await_args_list[-1].args[3:5] == ('acl_update', 'completed')
+ audit_detail = enqueue_file_audit.await_args_list[-1].kwargs['operation_detail']
assert audit_detail['previousAclVersion'] == acl_version
assert audit_detail['newAclVersion'] == acl_version + 1
assert audit_detail['allowCount'] == 1
@@ -419,7 +394,7 @@ def test_batch_save_file_acl_replaces_all_selected_private_files() -> None:
SimpleNamespace(file_id=FILE_ID_2, access_type='private', acl_version=4, update_by=None, update_time=None),
]
save_model = BatchSaveFileAclModel(
- fileIds=f'{FILE_ID},{FILE_ID_2}',
+ file_ids=f'{FILE_ID},{FILE_ID_2}',
entries=[{'subjectType': 'user', 'subjectId': 20, 'effect': 'allow'}],
)
@@ -444,7 +419,7 @@ def test_batch_save_file_acl_replaces_all_selected_private_files() -> None:
)
)
- saved_acl_list = replace_file_acl_lists.await_args.args[2]
+ saved_acl_list = replace_file_acl_lists.await_args_list[-1].args[2]
assert result.is_success is True
assert {item.file_id for item in saved_acl_list} == {FILE_ID, FILE_ID_2}
assert [file_info.acl_version for file_info in file_infos] == [3, 5]
@@ -456,7 +431,7 @@ def test_batch_save_file_acl_replaces_all_selected_private_files() -> None:
def test_batch_save_file_acl_rejects_public_files() -> None:
"""批量保存文件授权时拒绝公开文件。"""
query_db = make_query_db()
- save_model = BatchSaveFileAclModel(fileIds=FILE_ID, entries=[])
+ save_model = BatchSaveFileAclModel(file_ids=FILE_ID, entries=[])
file_infos = [SimpleNamespace(file_id=FILE_ID, access_type='public', acl_version=0)]
with (
@@ -484,16 +459,16 @@ def test_save_file_acl_rejects_duplicate_or_expired_entries() -> None:
"""保存文件授权时拒绝重复或过期条目。"""
query_db = make_query_db()
current_user = make_current_user(1, admin=True)
- file_info = SimpleNamespace(access_type='private', acl_version=0)
+ file_info = SysFileInfo(access_type='private', acl_version=0)
duplicate_model = SaveFileAclModel(
- aclVersion=0,
+ acl_version=0,
entries=[
{'subjectType': 'user', 'subjectId': 20, 'effect': 'allow'},
{'subjectType': 'user', 'subjectId': 20, 'effect': 'deny'},
],
)
expired_model = SaveFileAclModel(
- aclVersion=0,
+ acl_version=0,
entries=[
{
'subjectType': 'user',
@@ -538,9 +513,9 @@ def test_save_file_acl_rejects_subject_outside_data_scope() -> None:
"""保存文件授权时拒绝数据范围外的主体。"""
query_db = make_query_db()
current_user = make_current_user(1, admin=True)
- file_info = SimpleNamespace(access_type='private', acl_version=0)
+ file_info = SysFileInfo(access_type='private', acl_version=0)
save_model = SaveFileAclModel(
- aclVersion=0,
+ acl_version=0,
entries=[{'subjectType': 'user', 'subjectId': 20, 'effect': 'allow'}],
)
@@ -568,7 +543,7 @@ def test_save_file_acl_rejects_file_outside_data_scope() -> None:
"""保存文件授权时拒绝数据范围外的文件。"""
query_db = make_query_db()
current_user = make_current_user(20)
- save_model = SaveFileAclModel(aclVersion=0, entries=[])
+ save_model = SaveFileAclModel(acl_version=0, entries=[])
file_data_scope_sql = false()
with (
@@ -592,7 +567,7 @@ def test_save_file_acl_rejects_file_outside_data_scope() -> None:
)
)
- assert get_file_info.await_args.args[2] is file_data_scope_sql
+ assert get_file_info.await_args_list[-1].args[2] is file_data_scope_sql
assert scope_error.value.message == '文件信息不存在、已删除或超出数据权限'
replace_file_acl_list.assert_not_awaited()
@@ -600,8 +575,8 @@ def test_save_file_acl_rejects_file_outside_data_scope() -> None:
def test_save_file_acl_rejects_stale_acl_version() -> None:
"""保存文件授权时拒绝过期版本。"""
query_db = make_query_db()
- file_info = SimpleNamespace(access_type='private', acl_version=2)
- save_model = SaveFileAclModel(aclVersion=1, entries=[])
+ file_info = SysFileInfo(access_type='private', acl_version=2)
+ save_model = SaveFileAclModel(acl_version=1, entries=[])
with (
patch.object(FileInfoDao, 'get_file_info_by_id_for_update', new=AsyncMock(return_value=file_info)),
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_lifecycle_retention_execution.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_lifecycle_retention_execution.py
index 3f6f463de..4fe353a1d 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_lifecycle_retention_execution.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_lifecycle_retention_execution.py
@@ -23,6 +23,8 @@
FileRetentionPolicyService,
)
from module_admin.service.file_service import FileLifecycleService, FileRetentionDispositionService
+from tests.module_admin.service.file_helpers import make_file_request
+from tests.module_admin.service.helpers import make_current_user, make_query_db
from utils.file_util import FileUtil
from utils.time_util import TimezoneUtil
@@ -30,24 +32,6 @@
PURGE_COMMIT_COUNT = 2
-def make_query_db() -> SimpleNamespace:
- """
- 创建测试使用的 ``SimpleNamespace`` 实例。
-
- :return: 测试使用的 ``SimpleNamespace`` 实例
- """
- return SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
-
-
-def make_current_user() -> SimpleNamespace:
- """
- 创建测试使用的 ``SimpleNamespace`` 实例。
-
- :return: 测试使用的 ``SimpleNamespace`` 实例
- """
- return SimpleNamespace(user=SimpleNamespace(user_id=1, user_name='admin', admin=True))
-
-
def make_file_info(
access_type: str = 'private',
expire_time: datetime | None = None,
@@ -104,7 +88,7 @@ def test_purge_file_removes_recycle_content_and_metadata(tmp_path: Path) -> None
result = asyncio.run(
FileLifecycleService.purge_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
FILE_ID,
true(),
)
@@ -115,7 +99,7 @@ def test_purge_file_removes_recycle_content_and_metadata(tmp_path: Path) -> None
mark_purging.assert_awaited_once()
purge_file_infos.assert_awaited_once_with(query_db, [FILE_ID])
assert query_db.commit.await_count == PURGE_COMMIT_COUNT
- assert enqueue_file_audit.await_args.args[2:5] == (FILE_ID, 'purge', 'completed')
+ assert enqueue_file_audit.await_args_list[-1].args[2:5] == (FILE_ID, 'purge', 'completed')
def test_purge_file_rejects_business_reference(tmp_path: Path) -> None:
@@ -140,7 +124,7 @@ def test_purge_file_rejects_business_reference(tmp_path: Path) -> None:
asyncio.run(
FileLifecycleService.purge_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
FILE_ID,
true(),
)
@@ -193,7 +177,7 @@ def test_retention_scan_creates_expiring_and_expired_notices() -> None:
assert result.expiring_count == 1
assert result.expired_count == 1
invalidate_notices.assert_awaited_once_with(query_db, [FILE_ID])
- notice_list = add_notices.await_args.args[1]
+ notice_list = add_notices.await_args_list[-1].args[1]
assert [(notice.file_id, notice.notice_type) for notice in notice_list] == [
(FILE_ID, 'expired'),
(expiring_file.file_id, 'expiring'),
@@ -241,9 +225,9 @@ def test_mark_retention_notice_read_checks_data_scope() -> None:
)
assert result == []
- assert get_notice_list.await_args.args[3] is True
+ assert get_notice_list.await_args_list[-1].args[3] is True
assert read_result.is_success is True
- assert mark_notices_read.await_args.args[1] == [1, 2]
+ assert mark_notices_read.await_args_list[-1].args[1] == [1, 2]
query_db.commit.assert_awaited_once()
@@ -318,11 +302,11 @@ def test_extend_file_retention_updates_terminal_references() -> None:
result = asyncio.run(
FileRetentionDispositionService.extend_file_retention_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
1,
- ExtendFileRetentionModel(expireTime=new_expire_time, reason='业务继续留存'),
+ ExtendFileRetentionModel(expire_time=new_expire_time, reason='业务继续留存'),
true(),
- request=SimpleNamespace(),
+ request=make_file_request(),
)
)
@@ -332,7 +316,7 @@ def test_extend_file_retention_updates_terminal_references() -> None:
assert reference.retention_expire_time == expected_expire_time
invalidate_notices.assert_awaited_once_with(query_db, FILE_ID)
query_db.commit.assert_awaited_once()
- assert enqueue_file_audit.await_args.args[3:5] == ('retention_extend', 'completed')
+ assert enqueue_file_audit.await_args_list[-1].args[3:5] == ('retention_extend', 'completed')
def test_dispose_expired_file_releases_expired_references() -> None:
@@ -368,11 +352,11 @@ def test_dispose_expired_file_releases_expired_references() -> None:
result = asyncio.run(
FileRetentionDispositionService.dispose_expired_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
1,
DisposeExpiredFileModel(reason='保留期已结束'),
true(),
- request=SimpleNamespace(),
+ request=make_file_request(),
)
)
@@ -380,8 +364,8 @@ def test_dispose_expired_file_releases_expired_references() -> None:
delete_references.assert_awaited_once_with(query_db, FILE_ID)
soft_delete_file_infos.assert_awaited_once()
query_db.commit.assert_awaited_once()
- assert enqueue_file_audit.await_args.args[3:5] == ('retention_dispose', 'completed')
- assert enqueue_file_audit.await_args.kwargs['operation_detail']['releasedReferenceCount'] == 1
+ assert enqueue_file_audit.await_args_list[-1].args[3:5] == ('retention_dispose', 'completed')
+ assert enqueue_file_audit.await_args_list[-1].kwargs['operation_detail']['releasedReferenceCount'] == 1
def test_dispose_expired_file_rejects_active_reference() -> None:
@@ -412,7 +396,7 @@ def test_dispose_expired_file_rejects_active_reference() -> None:
asyncio.run(
FileRetentionDispositionService.dispose_expired_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
1,
DisposeExpiredFileModel(reason='保留期已结束'),
true(),
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_management.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_management.py
index 6d4bc1204..81b7e355b 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_management.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_management.py
@@ -2,6 +2,7 @@
from collections.abc import Generator
from pathlib import Path
from types import SimpleNamespace
+from typing import Literal
from unittest.mock import AsyncMock, patch
import pytest
@@ -14,8 +15,11 @@
from module_admin.dao.file_info_dao import FileInfoDao
from module_admin.entity.do.file_do import SysFileInfo
from module_admin.entity.vo.file_vo import DeleteFileModel, TransferFileModel
+from module_admin.entity.vo.role_vo import RoleModel
from module_admin.service.file_access_service import FileAuditService
from module_admin.service.file_service import FileLifecycleService, FileQueryService, FileTransferService
+from tests.module_admin.service.file_helpers import make_file_request
+from tests.module_admin.service.helpers import make_current_user, make_query_db
from utils.file_util import FileUtil
from utils.upload_util import UploadUtil
@@ -26,26 +30,6 @@
BATCH_FILE_COUNT = 2
-def make_query_db(commit_error: Exception | None = None) -> SimpleNamespace:
- """
- 准备测试所需的异步数据库会话。
-
- :param commit_error: 模拟事务提交失败时抛出的异常
- :return: ``SimpleNamespace`` 实例
- """
- commit = AsyncMock(side_effect=commit_error) if commit_error else AsyncMock()
- return SimpleNamespace(commit=commit, rollback=AsyncMock())
-
-
-def make_current_user() -> SimpleNamespace:
- """
- 创建测试使用的 ``SimpleNamespace`` 实例。
-
- :return: 测试使用的 ``SimpleNamespace`` 实例
- """
- return SimpleNamespace(user=SimpleNamespace(user_id=1, user_name='admin', admin=True))
-
-
def make_file_info(
file_id: str,
access_type: str,
@@ -99,16 +83,12 @@ def mock_file_reference_count() -> Generator[None, None, None]:
@pytest.mark.parametrize('data_scope', [GetDataScope.DATA_SCOPE_DEPT, GetDataScope.DATA_SCOPE_DEPT_AND_CHILD])
-def test_file_data_scope_does_not_match_unowned_files_when_user_has_no_department(data_scope: str) -> None:
+def test_file_data_scope_does_not_match_unowned_files_when_user_has_no_department(
+ data_scope: Literal['3', '4'],
+) -> None:
"""无所属部门的用户不能匹配无所有者文件。"""
- current_user = SimpleNamespace(
- user=SimpleNamespace(
- user_id=20,
- dept_id=None,
- admin=False,
- role=[SimpleNamespace(role_id=2, data_scope=data_scope, status='0', del_flag='0')],
- )
- )
+ current_user = make_current_user(20)
+ current_user.user.role = [RoleModel(role_id=2, data_scope=data_scope, status='0', del_flag='0')]
with (
patch('common.aspect.data_scope.DependencyUtil.check_exclude_routes'),
@@ -118,7 +98,7 @@ def test_file_data_scope_does_not_match_unowned_files_when_user_has_no_departmen
SysFileInfo,
user_alias='owner_user_id',
dept_alias='dept_id',
- )(SimpleNamespace())
+ )(make_file_request())
assert str(file_data_scope_sql).lower() == 'false'
@@ -201,9 +181,9 @@ def test_transfer_file_updates_owner_and_department_with_data_scope() -> None:
"""移交文件时按数据范围更新所有者和部门。"""
query_db = make_query_db()
transfer_model = TransferFileModel(
- ownerUserId=TARGET_USER_ID,
- deptId=TARGET_DEPT_ID,
- retainUploaderAccess=False,
+ owner_user_id=TARGET_USER_ID,
+ dept_id=TARGET_DEPT_ID,
+ retain_uploader_access=False,
reason='岗位调整',
)
target_user = SimpleNamespace(user_id=TARGET_USER_ID, user_name='target-user', dept_id=TARGET_DEPT_ID)
@@ -232,7 +212,7 @@ def test_transfer_file_updates_owner_and_department_with_data_scope() -> None:
result = asyncio.run(
FileTransferService.transfer_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
PUBLIC_FILE_ID,
transfer_model,
true(),
@@ -242,21 +222,21 @@ def test_transfer_file_updates_owner_and_department_with_data_scope() -> None:
)
assert result.is_success is True
- assert get_user.await_args.args[1] == TARGET_USER_ID
- assert get_dept.await_args.args[1] == TARGET_DEPT_ID
- assert get_files.await_args.args[2].compare(true())
- assert transfer_files.await_args.args[1:5] == ([PUBLIC_FILE_ID], TARGET_USER_ID, TARGET_DEPT_ID, False)
+ assert get_user.await_args_list[-1].args[1] == TARGET_USER_ID
+ assert get_dept.await_args_list[-1].args[1] == TARGET_DEPT_ID
+ assert get_files.await_args_list[-1].args[2].compare(true())
+ assert transfer_files.await_args_list[-1].args[1:5] == ([PUBLIC_FILE_ID], TARGET_USER_ID, TARGET_DEPT_ID, False)
query_db.commit.assert_awaited_once()
enqueue_file_audit.assert_awaited_once()
- assert enqueue_file_audit.await_args.args[2:5] == (PUBLIC_FILE_ID, 'transfer', 'completed')
- assert enqueue_file_audit.await_args.kwargs['operation_detail']['reason'] == '岗位调整'
- assert enqueue_file_audit.await_args.kwargs['operation_detail']['previousUploaderAccessEnabled'] is True
- assert enqueue_file_audit.await_args.kwargs['operation_detail']['newUploaderAccessEnabled'] is False
+ assert enqueue_file_audit.await_args_list[-1].args[2:5] == (PUBLIC_FILE_ID, 'transfer', 'completed')
+ assert enqueue_file_audit.await_args_list[-1].kwargs['operation_detail']['reason'] == '岗位调整'
+ assert enqueue_file_audit.await_args_list[-1].kwargs['operation_detail']['previousUploaderAccessEnabled'] is True
+ assert enqueue_file_audit.await_args_list[-1].kwargs['operation_detail']['newUploaderAccessEnabled'] is False
def test_transfer_file_model_retains_uploader_access_by_default() -> None:
"""移交文件默认保留上传者访问权。"""
- transfer_model = TransferFileModel(ownerUserId=TARGET_USER_ID, deptId=TARGET_DEPT_ID, reason='岗位调整')
+ transfer_model = TransferFileModel(owner_user_id=TARGET_USER_ID, dept_id=TARGET_DEPT_ID, reason='岗位调整')
assert transfer_model.retain_uploader_access is True
@@ -264,7 +244,7 @@ def test_transfer_file_model_retains_uploader_access_by_default() -> None:
def test_transfer_file_rejects_target_outside_data_scope() -> None:
"""拒绝向数据范围外的目标移交文件。"""
query_db = make_query_db()
- transfer_model = TransferFileModel(ownerUserId=TARGET_USER_ID, deptId=TARGET_DEPT_ID, reason='岗位调整')
+ transfer_model = TransferFileModel(owner_user_id=TARGET_USER_ID, dept_id=TARGET_DEPT_ID, reason='岗位调整')
user_data_scope_sql = false()
with (
@@ -280,7 +260,7 @@ def test_transfer_file_rejects_target_outside_data_scope() -> None:
asyncio.run(
FileTransferService.transfer_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
PUBLIC_FILE_ID,
transfer_model,
true(),
@@ -289,7 +269,7 @@ def test_transfer_file_rejects_target_outside_data_scope() -> None:
)
)
- assert get_user.await_args.args[2] is user_data_scope_sql
+ assert get_user.await_args_list[-1].args[2] is user_data_scope_sql
assert scope_error.value.message == '目标用户或部门不存在、已停用或超出数据权限'
transfer_files.assert_not_awaited()
query_db.rollback.assert_awaited_once()
@@ -298,7 +278,7 @@ def test_transfer_file_rejects_target_outside_data_scope() -> None:
def test_transfer_file_rejects_owner_department_mismatch() -> None:
"""移交文件时拒绝所有者与部门不匹配的请求。"""
query_db = make_query_db()
- transfer_model = TransferFileModel(ownerUserId=TARGET_USER_ID, deptId=TARGET_DEPT_ID, reason='岗位调整')
+ transfer_model = TransferFileModel(owner_user_id=TARGET_USER_ID, dept_id=TARGET_DEPT_ID, reason='岗位调整')
with (
patch.object(
@@ -317,7 +297,7 @@ def test_transfer_file_rejects_owner_department_mismatch() -> None:
asyncio.run(
FileTransferService.transfer_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
PUBLIC_FILE_ID,
transfer_model,
true(),
@@ -334,7 +314,7 @@ def test_transfer_file_rejects_owner_department_mismatch() -> None:
def test_transfer_file_rejects_source_outside_data_scope() -> None:
"""拒绝移交数据范围外的源文件。"""
query_db = make_query_db()
- transfer_model = TransferFileModel(ownerUserId=TARGET_USER_ID, deptId=TARGET_DEPT_ID, reason='岗位调整')
+ transfer_model = TransferFileModel(owner_user_id=TARGET_USER_ID, dept_id=TARGET_DEPT_ID, reason='岗位调整')
file_data_scope_sql = false()
with (
@@ -355,7 +335,7 @@ def test_transfer_file_rejects_source_outside_data_scope() -> None:
asyncio.run(
FileTransferService.transfer_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
PUBLIC_FILE_ID,
transfer_model,
file_data_scope_sql,
@@ -364,7 +344,7 @@ def test_transfer_file_rejects_source_outside_data_scope() -> None:
)
)
- assert get_files.await_args.args[2] is file_data_scope_sql
+ assert get_files.await_args_list[-1].args[2] is file_data_scope_sql
assert scope_error.value.message == '部分文件不存在、已删除或超出数据权限'
transfer_files.assert_not_awaited()
query_db.rollback.assert_awaited_once()
@@ -399,8 +379,8 @@ def test_delete_file_moves_both_storage_types_to_recycle_bin(tmp_path: Path) ->
result = asyncio.run(
FileLifecycleService.delete_file_services(
query_db,
- make_current_user(),
- DeleteFileModel(fileIds=f'{PUBLIC_FILE_ID},{PRIVATE_FILE_ID}'),
+ make_current_user(1, user_name='admin', admin=True),
+ DeleteFileModel(file_ids=f'{PUBLIC_FILE_ID},{PRIVATE_FILE_ID}'),
true(),
)
)
@@ -410,7 +390,7 @@ def test_delete_file_moves_both_storage_types_to_recycle_bin(tmp_path: Path) ->
assert not private_file.exists()
assert (trash_root / PUBLIC_FILE_ID / 'public.txt').read_bytes() == b'public-content'
assert (trash_root / PRIVATE_FILE_ID / 'private.txt').read_bytes() == b'private-content'
- assert soft_delete_file_infos.await_args.args[1] == [PUBLIC_FILE_ID, PRIVATE_FILE_ID]
+ assert soft_delete_file_infos.await_args_list[-1].args[1] == [PUBLIC_FILE_ID, PRIVATE_FILE_ID]
query_db.commit.assert_awaited_once()
assert enqueue_file_audit.await_count == BATCH_FILE_COUNT
assert [item.args[2:5] for item in enqueue_file_audit.await_args_list] == [
@@ -443,8 +423,8 @@ def test_delete_file_rejects_business_reference_before_moving_file(tmp_path: Pat
asyncio.run(
FileLifecycleService.delete_file_services(
query_db,
- make_current_user(),
- DeleteFileModel(fileIds=PUBLIC_FILE_ID),
+ make_current_user(1, user_name='admin', admin=True),
+ DeleteFileModel(file_ids=PUBLIC_FILE_ID),
true(),
)
)
@@ -453,8 +433,8 @@ def test_delete_file_rejects_business_reference_before_moving_file(tmp_path: Pat
assert public_file.read_bytes() == b'public-content'
soft_delete_file_infos.assert_not_awaited()
query_db.rollback.assert_awaited_once()
- assert enqueue_file_audit.await_args.args[2:5] == (PUBLIC_FILE_ID, 'delete', 'denied')
- assert enqueue_file_audit.await_args.kwargs['operation_detail']['referenceCount'] == 1
+ assert enqueue_file_audit.await_args_list[-1].args[2:5] == (PUBLIC_FILE_ID, 'delete', 'denied')
+ assert enqueue_file_audit.await_args_list[-1].kwargs['operation_detail']['referenceCount'] == 1
def test_delete_file_rejects_legacy_business_reference(tmp_path: Path) -> None:
@@ -485,8 +465,8 @@ def test_delete_file_rejects_legacy_business_reference(tmp_path: Path) -> None:
asyncio.run(
FileLifecycleService.delete_file_services(
query_db,
- make_current_user(),
- DeleteFileModel(fileIds=PUBLIC_FILE_ID),
+ make_current_user(1, user_name='admin', admin=True),
+ DeleteFileModel(file_ids=PUBLIC_FILE_ID),
true(),
)
)
@@ -516,8 +496,8 @@ def test_delete_file_restores_physical_file_when_database_commit_fails(tmp_path:
asyncio.run(
FileLifecycleService.delete_file_services(
query_db,
- make_current_user(),
- DeleteFileModel(fileIds=PUBLIC_FILE_ID),
+ make_current_user(1, user_name='admin', admin=True),
+ DeleteFileModel(file_ids=PUBLIC_FILE_ID),
true(),
)
)
@@ -545,8 +525,8 @@ def test_delete_file_rejects_storage_path_escape(tmp_path: Path) -> None:
asyncio.run(
FileLifecycleService.delete_file_services(
query_db,
- make_current_user(),
- DeleteFileModel(fileIds=PUBLIC_FILE_ID),
+ make_current_user(1, user_name='admin', admin=True),
+ DeleteFileModel(file_ids=PUBLIC_FILE_ID),
true(),
)
)
@@ -579,8 +559,8 @@ def test_delete_file_does_not_overwrite_existing_recycle_bin_file(tmp_path: Path
asyncio.run(
FileLifecycleService.delete_file_services(
query_db,
- make_current_user(),
- DeleteFileModel(fileIds=PUBLIC_FILE_ID),
+ make_current_user(1, user_name='admin', admin=True),
+ DeleteFileModel(file_ids=PUBLIC_FILE_ID),
true(),
)
)
@@ -614,8 +594,8 @@ def test_delete_file_restores_already_staged_files_when_later_path_is_invalid(tm
asyncio.run(
FileLifecycleService.delete_file_services(
query_db,
- make_current_user(),
- DeleteFileModel(fileIds=f'{PUBLIC_FILE_ID},{PRIVATE_FILE_ID}'),
+ make_current_user(1, user_name='admin', admin=True),
+ DeleteFileModel(file_ids=f'{PUBLIC_FILE_ID},{PRIVATE_FILE_ID}'),
true(),
)
)
@@ -641,8 +621,8 @@ def test_delete_file_allows_missing_physical_file_to_close_metadata(tmp_path: Pa
result = asyncio.run(
FileLifecycleService.delete_file_services(
query_db,
- make_current_user(),
- DeleteFileModel(fileIds=PUBLIC_FILE_ID),
+ make_current_user(1, user_name='admin', admin=True),
+ DeleteFileModel(file_ids=PUBLIC_FILE_ID),
true(),
)
)
@@ -665,8 +645,8 @@ def test_delete_file_rejects_invalid_or_missing_file_ids() -> None:
asyncio.run(
FileLifecycleService.delete_file_services(
query_db,
- make_current_user(),
- DeleteFileModel(fileIds=PUBLIC_FILE_ID),
+ make_current_user(1, user_name='admin', admin=True),
+ DeleteFileModel(file_ids=PUBLIC_FILE_ID),
true(),
)
)
@@ -691,13 +671,13 @@ def test_delete_file_rejects_file_outside_data_scope() -> None:
asyncio.run(
FileLifecycleService.delete_file_services(
query_db,
- make_current_user(),
- DeleteFileModel(fileIds=PUBLIC_FILE_ID),
+ make_current_user(1, user_name='admin', admin=True),
+ DeleteFileModel(file_ids=PUBLIC_FILE_ID),
file_data_scope_sql,
)
)
- assert get_file_infos.await_args.args[2] is file_data_scope_sql
+ assert get_file_infos.await_args_list[-1].args[2] is file_data_scope_sql
assert scope_error.value.message == '部分文件不存在、已删除或超出数据权限'
soft_delete_file_infos.assert_not_awaited()
query_db.rollback.assert_awaited_once()
@@ -748,7 +728,7 @@ def move_file_after_database_commit(source: Path, target: Path) -> None:
result = asyncio.run(
FileLifecycleService.restore_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
f'{PUBLIC_FILE_ID},{PRIVATE_FILE_ID}',
true(),
)
@@ -759,7 +739,7 @@ def move_file_after_database_commit(source: Path, target: Path) -> None:
assert (private_root / 'upload' / 'private.txt').read_bytes() == b'private-content'
assert not public_trash_file.exists()
assert not private_trash_file.exists()
- assert restore_file_infos.await_args.args[1] == [PUBLIC_FILE_ID, PRIVATE_FILE_ID]
+ assert restore_file_infos.await_args_list[-1].args[1] == [PUBLIC_FILE_ID, PRIVATE_FILE_ID]
query_db.commit.assert_awaited_once()
assert enqueue_file_audit.await_count == BATCH_FILE_COUNT
assert [item.args[2:5] for item in enqueue_file_audit.await_args_list] == [
@@ -792,7 +772,7 @@ def test_restore_file_returns_physical_file_to_recycle_bin_when_database_commit_
asyncio.run(
FileLifecycleService.restore_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
PUBLIC_FILE_ID,
true(),
)
@@ -855,7 +835,7 @@ def fail_second_move(source: Path, target: Path) -> None:
asyncio.run(
FileLifecycleService.restore_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
f'{PUBLIC_FILE_ID},{PRIVATE_FILE_ID}',
true(),
)
@@ -897,7 +877,7 @@ def test_restore_file_rejects_existing_original_path(tmp_path: Path) -> None:
asyncio.run(
FileLifecycleService.restore_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
PUBLIC_FILE_ID,
true(),
)
@@ -927,13 +907,13 @@ def test_restore_file_rejects_file_outside_data_scope() -> None:
asyncio.run(
FileLifecycleService.restore_file_services(
query_db,
- make_current_user(),
+ make_current_user(1, user_name='admin', admin=True),
PUBLIC_FILE_ID,
file_data_scope_sql,
)
)
- assert get_file_infos.await_args.args[2] is file_data_scope_sql
+ assert get_file_infos.await_args_list[-1].args[2] is file_data_scope_sql
assert scope_error.value.message == '部分文件不存在、未删除或超出数据权限'
restore_file_infos.assert_not_awaited()
query_db.rollback.assert_awaited_once()
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reconcile.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reconcile.py
index a88a37c6f..55455d26b 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reconcile.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reconcile.py
@@ -3,19 +3,20 @@
import os
from datetime import UTC, datetime
from pathlib import Path
-from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import pytest
from common.vo import PageModel
from module_admin.dao.file_info_dao import FileInfoDao
+from module_admin.entity.do.file_do import SysFileReconcileIssue
from module_admin.entity.vo.file_vo import (
FileReconcileHandleModel,
FileReconcileIssuePageQueryModel,
FileReconcileRunPageQueryModel,
)
from module_admin.service.file_service import FileReconcileService
+from tests.module_admin.service.helpers import make_current_user, make_query_db
from utils.file_util import FileReconcileScanResult, FileReconcileUtil
FILE_ID = '11111111-1111-4111-8111-111111111111'
@@ -175,13 +176,13 @@ def test_reconcile_scan_rejects_unsafe_metadata_path(tmp_path: Path) -> None:
def test_reconcile_available_actions_follow_issue_status() -> None:
"""核对问题的状态决定可用操作。"""
- open_orphan = SimpleNamespace(
+ open_orphan = SysFileReconcileIssue(
status='open',
issue_type='orphan_file',
actual_root='public',
quarantine_key=None,
)
- quarantined = SimpleNamespace(
+ quarantined = SysFileReconcileIssue(
status='quarantined',
issue_type='orphan_file',
actual_root='public',
@@ -214,8 +215,8 @@ def test_reconcile_move_rejects_existing_target(tmp_path: Path) -> None:
def test_reconcile_start_creates_manual_run_with_boolean_hash_flag() -> None:
"""手动核对任务使用布尔值控制哈希检查。"""
- query_db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
- current_user = SimpleNamespace(user=SimpleNamespace(admin=True, user_name='admin'))
+ query_db = make_query_db()
+ current_user = make_current_user(1, user_name='admin', admin=True)
with (
patch.object(FileInfoDao, 'release_stale_runs', new=AsyncMock()),
@@ -232,13 +233,13 @@ def test_reconcile_start_creates_manual_run_with_boolean_hash_flag() -> None:
assert reconcile_run.check_hash is True
assert reconcile_run.trigger_type == 'manual'
assert reconcile_run.started_by == 'admin'
- assert add_run.await_args.args[1].check_hash == '1'
+ assert add_run.await_args_list[-1].args[1].check_hash == '1'
query_db.commit.assert_awaited_once()
def test_reconcile_run_page_converts_database_field_names() -> None:
"""核对任务分页转换数据库字段名。"""
- current_user = SimpleNamespace(user=SimpleNamespace(admin=True, user_name='admin'))
+ current_user = make_current_user(1, user_name='admin', admin=True)
run_page = PageModel.model_validate(
{
'rows': [
@@ -265,7 +266,7 @@ def test_reconcile_run_page_converts_database_field_names() -> None:
):
result = asyncio.run(
FileReconcileService.get_reconcile_run_list_services(
- SimpleNamespace(),
+ make_query_db(),
current_user,
FileReconcileRunPageQueryModel(),
)
@@ -278,7 +279,7 @@ def test_reconcile_run_page_converts_database_field_names() -> None:
def test_reconcile_issue_page_calculates_actions_from_camel_case_rows() -> None:
"""核对问题分页根据驼峰字段推导可用操作。"""
- current_user = SimpleNamespace(user=SimpleNamespace(admin=True, user_name='admin'))
+ current_user = make_current_user(1, user_name='admin', admin=True)
current_time = datetime(2026, 7, 26, 12, 0, 0, tzinfo=UTC)
issue_page = PageModel(
rows=[
@@ -295,10 +296,10 @@ def test_reconcile_issue_page_calculates_actions_from_camel_case_rows() -> None:
'lastSeenTime': current_time,
}
],
- pageNum=1,
- pageSize=10,
+ page_num=1,
+ page_size=10,
total=1,
- hasNext=False,
+ has_next=False,
)
with patch.object(
@@ -308,7 +309,7 @@ def test_reconcile_issue_page_calculates_actions_from_camel_case_rows() -> None:
):
result = asyncio.run(
FileReconcileService.get_reconcile_issue_list_services(
- SimpleNamespace(),
+ make_query_db(),
current_user,
FileReconcileIssuePageQueryModel(),
)
@@ -328,7 +329,7 @@ def test_reconcile_move_is_compensated_when_database_commit_fails(tmp_path: Path
trash_key = f'{FILE_ID}/{STORED_NAME}'
source = write_file(roots['trash'], trash_key, b'content')
target = roots['public'] / Path(STORAGE_KEY)
- issue = SimpleNamespace(
+ issue = SysFileReconcileIssue(
issue_id=1,
file_id=FILE_ID,
issue_type='unexpected_trash',
@@ -343,11 +344,8 @@ def test_reconcile_move_is_compensated_when_database_commit_fails(tmp_path: Path
handled_by=None,
handled_time=None,
)
- query_db = SimpleNamespace(
- commit=AsyncMock(side_effect=RuntimeError('commit failed')),
- rollback=AsyncMock(),
- )
- current_user = SimpleNamespace(user=SimpleNamespace(admin=True, user_name='admin', user_id=1, dept_id=100))
+ query_db = make_query_db(commit_error=RuntimeError('commit failed'))
+ current_user = make_current_user(1, user_name='admin', admin=True, dept_id=100)
handle = FileReconcileHandleModel(action='restore_source', reason='恢复事务中断文件')
with (
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reference.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reference.py
index 98237bb04..8a34a2cbd 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reference.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_reference.py
@@ -9,22 +9,14 @@
from exceptions.exception import ServiceException
from module_admin.dao.file_business_dao import FileReferenceDao
from module_admin.dao.file_info_dao import FileInfoDao
-from module_admin.entity.do.file_do import SysFileReference
+from module_admin.entity.do.file_do import SysFileInfo, SysFileReference
from module_admin.entity.vo.file_vo import FileRetentionPolicyModel
from module_admin.service.file_business_service import FileReferenceService, FileRetentionPolicyService
+from tests.module_admin.service.helpers import make_query_db
FILE_ID = '11111111-1111-4111-8111-111111111111'
-def make_query_db() -> SimpleNamespace:
- """
- 创建测试使用的 ``SimpleNamespace`` 实例。
-
- :return: 测试使用的 ``SimpleNamespace`` 实例
- """
- return SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
-
-
def test_get_file_reference_list_includes_legacy_reference() -> None:
"""文件引用列表包含旧版引用。"""
file_info = {
@@ -137,8 +129,8 @@ def test_replace_business_file_references_locks_files_without_committing() -> No
)
)
- assert get_file_infos.await_args.args[1] == [FILE_ID]
- reference_list = replace_references.await_args.args[3]
+ assert get_file_infos.await_args_list[-1].args[1] == [FILE_ID]
+ reference_list = replace_references.await_args_list[-1].args[3]
assert len(reference_list) == 1
assert isinstance(reference_list[0], SysFileReference)
assert reference_list[0].file_id == FILE_ID
@@ -198,7 +190,7 @@ def test_remove_business_file_references_does_not_lock_files() -> None:
)
)
- assert replace_references.await_args.args[3] == []
+ assert replace_references.await_args_list[-1].args[3] == []
query_db.commit.assert_not_awaited()
@@ -206,7 +198,7 @@ def test_replace_business_file_references_applies_retention_policy() -> None:
"""替换业务文件引用时应用保留策略。"""
query_db = make_query_db()
create_time = datetime(2026, 7, 23, 10, 0, 0, tzinfo=UTC)
- policy = FileRetentionPolicyModel(businessType='notice', retentionDays=30)
+ policy = FileRetentionPolicyModel(business_type='notice', retention_days=30)
with (
patch.object(
FileInfoDao,
@@ -236,7 +228,7 @@ def test_replace_business_file_references_applies_retention_policy() -> None:
)
)
- reference = replace_references.await_args.args[3][0]
+ reference = replace_references.await_args_list[-1].args[3][0]
assert reference.retention_expire_time == create_time + timedelta(days=30)
@@ -269,21 +261,15 @@ def test_refresh_file_expire_times_uses_latest_reference_expiration() -> None:
"""按最晚引用到期时间刷新文件的过期时间。"""
first_expire_time = datetime(2026, 8, 1, tzinfo=UTC)
last_expire_time = datetime(2026, 9, 1, tzinfo=UTC)
- file_info = SimpleNamespace(
+ file_info = SysFileInfo(
file_id=FILE_ID,
business_type=None,
business_id=None,
expire_time=None,
)
- query_db = SimpleNamespace(
- execute=AsyncMock(
- return_value=SimpleNamespace(
- all=lambda: [
- (FILE_ID, first_expire_time),
- (FILE_ID, last_expire_time),
- ]
- )
- )
+ query_db = make_query_db()
+ query_db.execute.return_value = SimpleNamespace(
+ all=lambda: [(FILE_ID, first_expire_time), (FILE_ID, last_expire_time)]
)
asyncio.run(
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_retention_policy.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_retention_policy.py
index 4b980511d..fd609e5f5 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_file_retention_policy.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_file_retention_policy.py
@@ -9,19 +9,11 @@
from module_admin.entity.do.file_do import SysFileRetentionPolicy
from module_admin.entity.vo.file_vo import FileRetentionPolicyModel
from module_admin.service.file_business_service import FileRetentionPolicyService
+from tests.module_admin.service.helpers import make_query_db
RETENTION_DAYS = 365
-def make_query_db() -> SimpleNamespace:
- """
- 创建测试使用的 ``SimpleNamespace`` 实例。
-
- :return: 测试使用的 ``SimpleNamespace`` 实例
- """
- return SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
-
-
def test_get_file_retention_policy_list_maps_orm_field_names() -> None:
"""文件保留策略列表映射 ORM 字段名。"""
query_db = make_query_db()
@@ -73,8 +65,8 @@ def test_add_file_retention_policy_commits_new_policy() -> None:
"""新增文件保留策略后提交事务。"""
query_db = make_query_db()
policy = FileRetentionPolicyModel(
- businessType='notice',
- retentionDays=RETENTION_DAYS,
+ business_type='notice',
+ retention_days=RETENTION_DAYS,
status='0',
remark='公告附件',
)
@@ -99,16 +91,16 @@ def test_add_file_retention_policy_commits_new_policy() -> None:
)
assert result.is_success is True
- assert add_policy.await_args.args[1].business_type == 'notice'
- assert add_policy.await_args.args[1].retention_days == RETENTION_DAYS
- assert add_policy.await_args.args[1].create_by == 'admin'
+ assert add_policy.await_args_list[-1].args[1].business_type == 'notice'
+ assert add_policy.await_args_list[-1].args[1].retention_days == RETENTION_DAYS
+ assert add_policy.await_args_list[-1].args[1].create_by == 'admin'
query_db.commit.assert_awaited_once()
def test_add_file_retention_policy_rejects_duplicate_business_type() -> None:
"""新增策略时拒绝重复的业务类型。"""
query_db = make_query_db()
- policy = FileRetentionPolicyModel(businessType='notice', retentionDays=30)
+ policy = FileRetentionPolicyModel(business_type='notice', retention_days=30)
with (
patch.object(
FileRetentionPolicyDao,
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_identity_security_integration.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_identity_security_integration.py
index 1cf342ae0..d589e8538 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_identity_security_integration.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_identity_security_integration.py
@@ -10,17 +10,18 @@
from module_admin.service.role_service import RoleService
from module_admin.service.user_service import UserService
from module_identity.service.identity_service import IdentitySecurityEventService, IdentitySubjectService
+from tests.module_admin.service.helpers import make_query_db
@pytest.mark.asyncio
async def test_add_user_creates_subject_before_commit(monkeypatch: pytest.MonkeyPatch) -> None:
"""新增用户必须在同一会话提交前建立稳定 Subject。"""
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ db = make_query_db()
monkeypatch.setattr(UserService, 'check_user_name_unique_services', AsyncMock(return_value=True))
monkeypatch.setattr(UserDao, 'add_user_dao', AsyncMock(return_value=SimpleNamespace(user_id=7)))
create_subject = AsyncMock()
monkeypatch.setattr(IdentitySubjectService, 'create_for_new_user', create_subject)
- payload = AddUserModel(userName='new-user', nickName='New User', createBy='admin')
+ payload = AddUserModel(user_name='new-user', nick_name='New User', create_by='admin')
await UserService.add_user_services(db, payload)
@@ -32,12 +33,12 @@ async def test_add_user_creates_subject_before_commit(monkeypatch: pytest.Monkey
@pytest.mark.asyncio
async def test_password_security_failure_rolls_back_user_change(monkeypatch: pytest.MonkeyPatch) -> None:
"""密码安全失效失败时不得提交已写入的新密码。"""
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ db = make_query_db()
monkeypatch.setattr(UserDao, 'edit_user_dao', AsyncMock())
monkeypatch.setattr('module_admin.service.user_service.PwdUtil.get_password_hash', lambda value: f'hash:{value}')
security_event = AsyncMock(side_effect=RuntimeError('security state unavailable'))
monkeypatch.setattr(IdentitySecurityEventService, 'handle_user_event', security_event)
- payload = ResetUserModel(userId=8, password='New123!', updateBy='admin')
+ payload = ResetUserModel(user_id=8, password='New123!', update_by='admin')
with pytest.raises(RuntimeError, match='security state unavailable'):
await UserService.reset_user_services(db, payload)
@@ -50,23 +51,25 @@ async def test_password_security_failure_rolls_back_user_change(monkeypatch: pyt
@pytest.mark.asyncio
async def test_disabling_role_invalidates_members_before_commit(monkeypatch: pytest.MonkeyPatch) -> None:
"""角色停用必须在角色更新事务中处理受影响用户。"""
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ db = make_query_db()
monkeypatch.setattr(
RoleService,
'role_detail_services',
- AsyncMock(return_value=AddRoleModel(roleId=5, roleName='普通角色', roleKey='common', roleSort=1, status='0')),
+ AsyncMock(
+ return_value=AddRoleModel(role_id=5, role_name='普通角色', role_key='common', role_sort=1, status='0')
+ ),
)
monkeypatch.setattr(RoleDao, 'edit_role_dao', AsyncMock())
security_event = AsyncMock()
monkeypatch.setattr(IdentitySecurityEventService, 'handle_role_event', security_event)
payload = AddRoleModel(
- roleId=5,
- roleName='普通角色',
- roleKey='common',
- roleSort=1,
+ role_id=5,
+ role_name='普通角色',
+ role_key='common',
+ role_sort=1,
status='1',
type='status',
- updateBy='admin',
+ update_by='admin',
)
await RoleService.edit_role_services(db, payload)
@@ -79,11 +82,13 @@ async def test_disabling_role_invalidates_members_before_commit(monkeypatch: pyt
@pytest.mark.asyncio
async def test_changing_role_key_invalidates_external_role_claims(monkeypatch: pytest.MonkeyPatch) -> None:
"""角色标识变化必须让成员的旧外部角色声明失效。"""
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ db = make_query_db()
monkeypatch.setattr(
RoleService,
'role_detail_services',
- AsyncMock(return_value=AddRoleModel(roleId=5, roleName='普通角色', roleKey='reader', roleSort=1, status='0')),
+ AsyncMock(
+ return_value=AddRoleModel(role_id=5, role_name='普通角色', role_key='reader', role_sort=1, status='0')
+ ),
)
monkeypatch.setattr(RoleDao, 'edit_role_dao', AsyncMock())
monkeypatch.setattr(RoleDao, 'delete_role_menu_dao', AsyncMock())
@@ -94,13 +99,13 @@ async def test_changing_role_key_invalidates_external_role_claims(monkeypatch: p
security_event = AsyncMock()
monkeypatch.setattr(IdentitySecurityEventService, 'handle_role_event', security_event)
payload = AddRoleModel(
- roleId=5,
- roleName='普通角色',
- roleKey='auditor',
- roleSort=1,
+ role_id=5,
+ role_name='普通角色',
+ role_key='auditor',
+ role_sort=1,
status='0',
- menuIds=[],
- updateBy='admin',
+ menu_ids=[],
+ update_by='admin',
)
await RoleService.edit_role_services(db, payload)
@@ -113,8 +118,8 @@ async def test_changing_role_key_invalidates_external_role_claims(monkeypatch: p
@pytest.mark.asyncio
async def test_changing_role_menu_invalidates_external_claims(monkeypatch: pytest.MonkeyPatch) -> None:
"""角色菜单授权变化必须让成员的旧外部声明失效。"""
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
- role = AddRoleModel(roleId=5, roleName='普通角色', roleKey='reader', roleSort=1, status='0')
+ db = make_query_db()
+ role = AddRoleModel(role_id=5, role_name='普通角色', role_key='reader', role_sort=1, status='0')
monkeypatch.setattr(RoleService, 'role_detail_services', AsyncMock(return_value=role))
monkeypatch.setattr(RoleDao, 'list_role_menu_ids', AsyncMock(return_value=[10]))
monkeypatch.setattr(RoleDao, 'edit_role_dao', AsyncMock())
@@ -125,13 +130,13 @@ async def test_changing_role_menu_invalidates_external_claims(monkeypatch: pytes
security_event = AsyncMock()
monkeypatch.setattr(IdentitySecurityEventService, 'handle_role_event', security_event)
payload = AddRoleModel(
- roleId=5,
- roleName='普通角色',
- roleKey='reader',
- roleSort=1,
+ role_id=5,
+ role_name='普通角色',
+ role_key='reader',
+ role_sort=1,
status='0',
- menuIds=[11],
- updateBy='admin',
+ menu_ids=[11],
+ update_by='admin',
)
await RoleService.edit_role_services(db, payload)
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_job_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_job_service.py
index 62c9d236d..72bb11421 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_job_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_job_service.py
@@ -1,3 +1,4 @@
+from functools import partial
from unittest.mock import AsyncMock
import pytest
@@ -10,6 +11,7 @@
from module_admin.entity.do.job_runtime_do import SysJobSync
from module_admin.entity.vo.job_vo import DeleteJobModel, EditJobModel, JobModel
from module_admin.service.job_service import JobService
+from tests.module_admin.service.helpers import make_query_db
from tests.scheduler_helpers import Runtime, job_info
@@ -55,19 +57,20 @@ async def sync(job_ids: set[int], *, immediate: bool) -> dict:
monkeypatch.setattr(db, 'commit', committing)
monkeypatch.setattr(SchedulerManager, 'request_scheduler_sync', sync)
- method, argument = {
- 'add': (JobService.add_job_services, job_info()),
- 'edit': (JobService.edit_job_services, EditJobModel(jobId=42, timeZone='UTC')),
- 'disable': (JobService.edit_job_services, EditJobModel(jobId=42, status='1', type='status')),
- 'delete': (JobService.delete_job_services, DeleteJobModel(jobIds='42')),
+ mutate = {
+ 'add': partial(JobService.add_job_services, db, job_info()),
+ 'edit': partial(JobService.edit_job_services, db, EditJobModel(job_id=42, time_zone='UTC')),
+ 'disable': partial(JobService.edit_job_services, db, EditJobModel(job_id=42, status='1', type='status')),
+ 'delete': partial(JobService.delete_job_services, db, DeleteJobModel(job_ids='42')),
}[action]
if commit_fails:
with pytest.raises(RuntimeError, match='transaction failed'):
- await method(db, argument)
+ await mutate()
assert events == ['commit']
assert runtime.scheduler.get_job('42') is original
else:
- result = await method(db, argument)
+ result = await mutate()
+ assert isinstance(result.result, dict)
assert result.result['saved']
assert result.result['syncStatus'] == 'applied'
assert events == ['commit', 'sync']
@@ -83,11 +86,10 @@ async def sync(job_ids: set[int], *, immediate: bool) -> dict:
assert job is None
assert await db.scalar(select(func.count()).select_from(SysJobSync)) == 0
assert runtime.scheduler.get_jobs() == []
- if action == 'disable' and not commit_fails:
- assert job.time_zone == 'America/New_York'
- if commit_fails and action != 'add':
- assert job.time_zone == 'America/New_York'
- assert job.status == '0'
+ elif commit_fails or action == 'disable':
+ assert job is not None and job.time_zone == 'America/New_York'
+ if commit_fails:
+ assert job.status == '0'
@pytest.mark.asyncio
@@ -100,13 +102,15 @@ async def test_sync_failure_after_commit_reports_saved_and_keeps_retryable_state
SchedulerManager, 'request_scheduler_sync', AsyncMock(side_effect=RuntimeError('sync unavailable'))
)
async with runtime.sessions() as db:
- result = await JobService.delete_job_services(db, DeleteJobModel(jobIds='42'))
+ result = await JobService.delete_job_services(db, DeleteJobModel(job_ids='42'))
+ assert isinstance(result.result, dict)
assert result.result['saved'] is True
assert result.result['syncStatus'] == 'failed'
assert '删除已提交' in result.message
async with runtime.sessions() as db:
assert (await db.scalars(select(SysJob))).first() is None
state = await db.get(SysJobSync, 42)
+ assert state is not None
assert state.deleted
assert state.sync_status == 'pending'
@@ -116,29 +120,33 @@ async def test_disable_broken_target_remains_possible_but_enable_is_rejected(run
"""允许停用损坏的任务目标并拒绝启用。"""
await runtime.save(job_info(invokeTarget='module_task.scheduler_test.missing'))
async with runtime.sessions() as db:
- result = await JobService.edit_job_services(db, EditJobModel(jobId=42, status='1', type='status'))
+ result = await JobService.edit_job_services(db, EditJobModel(job_id=42, status='1', type='status'))
+ assert isinstance(result.result, dict)
assert result.result['syncStatus'] == 'applied'
async with runtime.sessions() as db:
with pytest.raises(ServiceException):
- await JobService.edit_job_services(db, EditJobModel(jobId=42, status='0', type='status'))
- assert (await JobDao.get_job_detail_by_id(db, 42)).status == '1'
+ await JobService.edit_job_services(db, EditJobModel(job_id=42, status='0', type='status'))
+ job = await JobDao.get_job_detail_by_id(db, 42)
+ assert job is not None
+ assert job.status == '1'
@pytest.mark.asyncio
async def test_add_job_rejects_plugin_invoke_target_from_system_job_form() -> None:
"""校验系统定时任务入口不会放开到整个 plugins 包。"""
job = JobModel(
- jobName='plugin-core-task',
- jobGroup='default',
- jobExecutor='default',
- invokeTarget='plugins.core.lifecycle.jobs.PluginJobInstaller.pause_plugin_jobs',
- cronExpression='0/5 * * * * ?',
- misfireGraceTime=1,
- maxInstances=1,
+ job_name='plugin-core-task',
+ job_group='default',
+ job_executor='default',
+ invoke_target='plugins.core.lifecycle.jobs.PluginJobInstaller.pause_plugin_jobs',
+ cron_expression='0/5 * * * * ?',
+ misfire_grace_time=1,
+ max_instances=1,
status='1',
)
with pytest.raises(ServiceException) as exc_info:
- await JobService.add_job_services(object(), job)
+ await JobService.add_job_services(make_query_db(), job)
+ assert exc_info.value.message is not None
assert '目标字符串不在白名单内' in exc_info.value.message
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_plugin_routes.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_plugin_routes.py
index 3bae963ca..c3dd94411 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_plugin_routes.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_plugin_routes.py
@@ -62,8 +62,8 @@ async def test_plugin_metadata_uses_menu_ownership_for_nested_and_root_pages() -
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
try:
async with engine.begin() as connection:
- await connection.run_sync(SysPlugin.__table__.create)
- await connection.run_sync(SysPluginMenu.__table__.create)
+ await connection.run_sync(SysPlugin.get_table().create)
+ await connection.run_sync(SysPluginMenu.get_table().create)
session_factory = async_sessionmaker(engine)
async with session_factory() as db:
db.add(_plugin('demo'))
@@ -106,8 +106,8 @@ async def test_menu_ownership_rejects_inactive_uninstalled_and_ambiguous_plugins
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
try:
async with engine.begin() as connection:
- await connection.run_sync(SysPlugin.__table__.create)
- await connection.run_sync(SysPluginMenu.__table__.create)
+ await connection.run_sync(SysPlugin.get_table().create)
+ await connection.run_sync(SysPluginMenu.get_table().create)
session_factory = async_sessionmaker(engine)
async with session_factory() as db:
db.add_all(
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_service.py
index 85ab649d2..d37b9fc1a 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_service.py
@@ -1,36 +1,30 @@
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
import jwt
import pytest
+from fastapi import Request
+from pydantic import ValidationError
+from sqlalchemy.ext.asyncio import AsyncSession
from common.enums import PasswordCharacterType
from config.env import JwtConfig
from exceptions.exception import AuthException, ServiceException
from module_admin.dao.user_dao import UserDao
from module_admin.entity.vo.login_vo import UserRegister
-from module_admin.entity.vo.user_vo import CurrentUserModel
+from module_admin.entity.vo.user_vo import CurrentUserModel, ResetUserModel, UserInfoModel
from module_admin.service.login_service import LoginService
from module_admin.service.user_service import UserService
+from tests.module_admin.service.helpers import make_current_user, make_query_db, make_redis_request
from utils.pwd_util import PwdUtil
-def _current_user(user_name: str = 'admin') -> SimpleNamespace:
- """
- 创建测试使用的 ``SimpleNamespace`` 实例。
-
- :param user_name: 当前用户的账号名称
- :return: 测试使用的 ``SimpleNamespace`` 实例
- """
- return SimpleNamespace(user=SimpleNamespace(user_name=user_name))
-
-
@pytest.mark.asyncio
@pytest.mark.parametrize(('config_value', 'expected'), [(None, '0'), ('4', '4')])
async def test_get_sys_account_chrtype_uses_config_and_default(config_value: str | None, expected: str) -> None:
"""密码字符类型取自配置并支持默认值。"""
redis = SimpleNamespace(get=AsyncMock(return_value=config_value))
- request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis)))
+ request = make_redis_request(redis)
result = await LoginService.get_sys_account_chrtype(request)
@@ -40,7 +34,9 @@ async def test_get_sys_account_chrtype_uses_config_and_default(config_value: str
def test_current_user_model_exposes_password_character_type_alias() -> None:
"""当前用户模型公开密码字符类型的别名。"""
- current_user = CurrentUserModel(permissions=[], roles=[], user=None, pwdChrtype='3')
+ current_user = CurrentUserModel(
+ permissions=[], roles=[], user=UserInfoModel(user_id=1, user_name='admin'), pwd_chrtype='3'
+ )
assert current_user.model_dump(by_alias=True)['pwdChrtype'] == '3'
@@ -58,7 +54,7 @@ async def test_get_current_user_rejects_malformed_user_id_claim() -> None:
patch.object(UserDao, 'get_user_by_id', new_callable=AsyncMock) as get_user,
pytest.raises(AuthException) as exc_info,
):
- await LoginService.get_current_user(SimpleNamespace(), token, object())
+ await LoginService.get_current_user(Request({'type': 'http'}), token, make_query_db())
assert exc_info.value.message == '用户token已失效,请重新登录'
get_user.assert_not_awaited()
@@ -71,7 +67,7 @@ async def test_unlock_screen_rejects_empty_password() -> None:
patch.object(UserDao, 'get_user_by_name', new_callable=AsyncMock) as get_user,
pytest.raises(ServiceException) as exc_info,
):
- await LoginService.unlock_screen_services(object(), _current_user(), '')
+ await LoginService.unlock_screen_services(make_query_db(), make_current_user(1, user_name='admin'), '')
assert exc_info.value.message == '密码不能为空'
get_user.assert_not_awaited()
@@ -84,7 +80,7 @@ async def test_unlock_screen_rejects_missing_current_user() -> None:
patch.object(UserDao, 'get_user_by_name', new=AsyncMock(return_value=None)) as get_user,
pytest.raises(ServiceException) as exc_info,
):
- await LoginService.unlock_screen_services(object(), _current_user(), 'password')
+ await LoginService.unlock_screen_services(make_query_db(), make_current_user(1, user_name='admin'), 'password')
assert exc_info.value.message == '服务器超时,请重新登录'
get_user.assert_awaited_once()
@@ -99,7 +95,9 @@ async def test_unlock_screen_rejects_wrong_password() -> None:
patch.object(PwdUtil, 'verify_password', return_value=False) as verify_password,
pytest.raises(ServiceException) as exc_info,
):
- await LoginService.unlock_screen_services(object(), _current_user(), 'wrong-password')
+ await LoginService.unlock_screen_services(
+ make_query_db(), make_current_user(1, user_name='admin'), 'wrong-password'
+ )
assert exc_info.value.message == '密码错误,请重新输入'
verify_password.assert_called_once_with('wrong-password', 'hashed-password')
@@ -113,11 +111,13 @@ async def test_unlock_screen_accepts_correct_password() -> None:
patch.object(UserDao, 'get_user_by_name', new=AsyncMock(return_value=user)) as get_user,
patch.object(PwdUtil, 'verify_password', return_value=True) as verify_password,
):
- result = await LoginService.unlock_screen_services(object(), _current_user('ry'), 'correct-password')
+ result = await LoginService.unlock_screen_services(
+ make_query_db(), make_current_user(1, user_name='ry'), 'correct-password'
+ )
assert result is True
get_user.assert_awaited_once()
- assert get_user.await_args.args[1] == 'ry'
+ assert get_user.await_args_list[-1].args[1] == 'ry'
verify_password.assert_called_once_with('correct-password', 'hashed-password')
@@ -125,11 +125,11 @@ async def test_unlock_screen_accepts_correct_password() -> None:
async def test_register_uses_front_end_default_password_rule() -> None:
"""注册使用前端默认的密码规则。"""
redis = SimpleNamespace(get=AsyncMock(side_effect=['true', 'false']))
- request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis)))
+ request = make_redis_request(redis)
user_register = UserRegister(
username='test_user',
password='abcdef',
- confirmPassword='abcdef',
+ confirm_password='abcdef',
)
expected = object()
@@ -138,7 +138,48 @@ async def test_register_uses_front_end_default_password_rule() -> None:
patch.object(UserService, 'add_user_services', new=AsyncMock(return_value=expected)),
patch.object(PwdUtil, 'get_password_hash', return_value='hashed-password'),
):
- result = await LoginService.register_user_services(request, object(), user_register)
+ result = await LoginService.register_user_services(request, make_query_db(), user_register)
assert result is expected
validate_password.assert_awaited_once_with(redis, 'abcdef', PasswordCharacterType.DEFAULT)
+
+
+@pytest.mark.parametrize('profile', [None, {}, {'userId': 1}, {'userName': 'reader'}])
+def test_current_user_requires_identity(profile: dict | None) -> None:
+ """受保护操作应拒绝缺少用户资料的快照。"""
+ with pytest.raises(ValidationError):
+ CurrentUserModel.model_validate({'permissions': [], 'roles': [], 'user': profile})
+
+
+@pytest.mark.asyncio
+async def test_password_recovery_passes_validated_password_to_reset_service() -> None:
+ """校验短信验证码后将原始密码交给负责哈希和保存的服务。"""
+ request = MagicMock(spec=Request)
+ request.app.state.redis.get = AsyncMock(return_value='123456')
+ user_id = 3
+ reset = ResetUserModel.model_validate(
+ {'userName': 'reader', 'password': 'new-password', 'smsCode': '123456', 'sessionId': 'session'}
+ )
+ async with AsyncSession() as db:
+ with (
+ patch.object(UserDao, 'get_user_by_name', new=AsyncMock(return_value=SimpleNamespace(user_id=user_id))),
+ patch.object(UserService, 'validate_password_services', new_callable=AsyncMock),
+ patch.object(UserService, 'reset_user_services', new_callable=AsyncMock) as save,
+ ):
+ result = await LoginService.forget_user_services(request, db, reset)
+ save.assert_awaited_once_with(db, reset)
+ assert result is save.return_value
+ assert reset.password == 'new-password'
+ assert reset.user_id == user_id
+
+
+@pytest.mark.asyncio
+async def test_password_recovery_requires_an_existing_code() -> None:
+ """缓存和请求均缺少验证码时按过期处理。"""
+ request = MagicMock(spec=Request)
+ request.app.state.redis.get = AsyncMock(return_value=None)
+ async with AsyncSession() as db:
+ with patch.object(UserService, 'reset_user_services', new_callable=AsyncMock) as save:
+ result = await LoginService.forget_user_services(request, db, ResetUserModel())
+ assert not result.is_success
+ save.assert_not_awaited()
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_session_renewal.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_session_renewal.py
index f1f00b352..0c4d96167 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_session_renewal.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_session_renewal.py
@@ -1,8 +1,9 @@
import asyncio
-from types import SimpleNamespace
-from unittest.mock import AsyncMock, Mock
+from dataclasses import dataclass
+from unittest.mock import AsyncMock, Mock, NonCallableMagicMock
import pytest
+from fastapi import Request
from redis.exceptions import TimeoutError as RedisTimeoutError
from common.context import RequestContext
@@ -10,6 +11,7 @@
from exceptions.exception import AuthException
from module_admin.entity.vo.user_vo import CurrentUserModel, UserInfoModel
from module_admin.service.login_service import _SESSION_LOGOUT_SCRIPT, _SESSION_RENEW_SCRIPT, LoginService
+from tests.module_admin.service.helpers import make_query_db, make_redis_request
from utils.jwt_util import JwtUtil
from utils.time_util import TimezoneUtil
@@ -106,32 +108,53 @@ async def eval(self, script: str, count: int, key: str, token: str, seconds: int
return 1
+@dataclass
+class SessionCase:
+ """
+ 登录会话续期测试所需的请求、凭据和替身。
+
+ :ivar redis: 可控制时间的会话缓存
+ :ivar db: 异步数据库会话替身
+ :ivar request: 携带会话缓存的请求
+ :ivar token: 当前用户的访问令牌
+ :ivar user: 令牌对应的用户
+ :ivar get_user: 查询当前用户的异步替身
+ """
+
+ redis: SessionRedis
+ db: NonCallableMagicMock
+ request: Request
+ token: str
+ user: CurrentUserModel
+ get_user: AsyncMock
+
+
@pytest.fixture
-def session_case(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
+def session_case(monkeypatch: pytest.MonkeyPatch) -> SessionCase:
"""
组合会话续期所需的请求、缓存和用户。
:param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
- :return: ``SimpleNamespace`` 实例
+ :return: ``SessionCase`` 实例
"""
redis = SessionRedis()
- request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis)))
+ request = make_redis_request(redis)
token = JwtUtil.encode(
{'user_id': '7', 'session_id': 'session-a', 'exp': int(TimezoneUtil.utc_now().timestamp()) + 3600}
)
user = CurrentUserModel(
- permissions=['demo:read'], roles=['reader'], user=UserInfoModel(userId=7, userName='tester')
+ permissions=['demo:read'], roles=['reader'], user=UserInfoModel(user_id=7, user_name='tester')
)
get_user = AsyncMock(return_value=user)
monkeypatch.setattr(LoginService, '_get_current_user_from_db', get_user)
RequestContext.clear_all()
- return SimpleNamespace(redis=redis, request=request, token=token, user=user, get_user=get_user)
+ return SessionCase(redis=redis, db=make_query_db(), request=request, token=token, user=user, get_user=get_user)
@pytest.mark.asyncio
@pytest.mark.parametrize('same_time_login', [True, False])
async def test_valid_session_renews_only_its_expiration(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
"""有效会话仅更新自身的有效期。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
@@ -139,7 +162,7 @@ async def test_valid_session_renews_only_its_expiration(
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
session_case.redis.now = 5
- result = await LoginService.get_current_user(session_case.request, f'Bearer {session_case.token}', object())
+ result = await LoginService.get_current_user(session_case.request, f'Bearer {session_case.token}', session_case.db)
assert result is session_case.user
assert await session_case.redis.get(key) == session_case.token
@@ -154,7 +177,7 @@ async def test_valid_session_renews_only_its_expiration(
@pytest.mark.parametrize('change', ['logout', 'new_login', 'expired'])
@pytest.mark.parametrize('for_plugin', [True, False])
async def test_concurrent_session_change_cannot_be_overwritten_or_restored(
- session_case: SimpleNamespace,
+ session_case: SessionCase,
monkeypatch: pytest.MonkeyPatch,
same_time_login: bool,
change: str,
@@ -181,7 +204,7 @@ async def load_user(*args: object) -> CurrentUserModel:
set_user = Mock()
monkeypatch.setattr(RequestContext, 'set_current_user', set_user)
resolve_user = LoginService.get_current_user_for_plugin_session if for_plugin else LoginService.get_current_user
- pending = asyncio.create_task(resolve_user(session_case.request, session_case.token, object()))
+ pending = asyncio.create_task(resolve_user(session_case.request, session_case.token, session_case.db))
await loaded.wait()
if change == 'logout':
token_id = 'session-a' if same_time_login else '7'
@@ -208,7 +231,7 @@ async def load_user(*args: object) -> CurrentUserModel:
@pytest.mark.asyncio
async def test_expired_session_does_not_load_user_or_renew(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch
) -> None:
"""会话过期后不加载用户也不续期。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', True)
@@ -217,7 +240,7 @@ async def test_expired_session_does_not_load_user_or_renew(
session_case.redis.now = _SESSION_TTL + 1
with pytest.raises(AuthException) as exc_info:
- await LoginService.get_current_user(session_case.request, session_case.token, object())
+ await LoginService.get_current_user(session_case.request, session_case.token, session_case.db)
assert exc_info.value.message == '用户token已失效,请重新登录'
session_case.get_user.assert_not_awaited()
@@ -226,7 +249,7 @@ async def test_expired_session_does_not_load_user_or_renew(
@pytest.mark.asyncio
async def test_renewal_failure_does_not_authenticate_request(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch
) -> None:
"""续期失败时拒绝认证请求。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', True)
@@ -237,7 +260,7 @@ async def test_renewal_failure_does_not_authenticate_request(
monkeypatch.setattr(RequestContext, 'set_current_user', set_user)
with pytest.raises(RedisTimeoutError):
- await LoginService.get_current_user(session_case.request, session_case.token, object())
+ await LoginService.get_current_user(session_case.request, session_case.token, session_case.db)
set_user.assert_not_called()
assert session_case.redis.deadlines[key] == _SESSION_TTL
@@ -246,7 +269,7 @@ async def test_renewal_failure_does_not_authenticate_request(
@pytest.mark.asyncio
@pytest.mark.parametrize('same_time_login', [True, False])
async def test_committed_renewal_timeout_does_not_authenticate_request(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
"""已提交的续期超时后拒绝认证请求。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
@@ -274,7 +297,7 @@ async def renew_then_timeout(script: str, count: int, cache_key: str, token: str
monkeypatch.setattr(RequestContext, 'set_current_user', set_user)
with pytest.raises(RedisTimeoutError):
- await LoginService.get_current_user(session_case.request, session_case.token, object())
+ await LoginService.get_current_user(session_case.request, session_case.token, session_case.db)
set_user.assert_not_called()
assert session_case.redis.renew_calls == [(key, session_case.token, JwtConfig.jwt_redis_expire_minutes * 60)]
@@ -285,7 +308,7 @@ async def renew_then_timeout(script: str, count: int, cache_key: str, token: str
@pytest.mark.asyncio
@pytest.mark.parametrize('same_time_login', [True, False])
async def test_cancelled_committed_renewal_does_not_authenticate_request(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
"""取消已提交的续期后拒绝认证请求。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
@@ -314,7 +337,9 @@ async def renew_then_wait(script: str, count: int, cache_key: str, token: str, s
monkeypatch.setattr(session_case.redis, 'eval', renew_then_wait)
set_user = Mock()
monkeypatch.setattr(RequestContext, 'set_current_user', set_user)
- pending = asyncio.create_task(LoginService.get_current_user(session_case.request, session_case.token, object()))
+ pending = asyncio.create_task(
+ LoginService.get_current_user(session_case.request, session_case.token, session_case.db)
+ )
await renewed.wait()
pending.cancel()
with pytest.raises(asyncio.CancelledError):
@@ -328,7 +353,7 @@ async def renew_then_wait(script: str, count: int, cache_key: str, token: str, s
@pytest.mark.asyncio
async def test_concurrent_requests_can_renew_the_same_session(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch
) -> None:
"""并发请求可续期同一会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', True)
@@ -337,7 +362,10 @@ async def test_concurrent_requests_can_renew_the_same_session(
requests = 5
results = await asyncio.gather(
- *(LoginService.get_current_user(session_case.request, session_case.token, object()) for _ in range(requests))
+ *(
+ LoginService.get_current_user(session_case.request, session_case.token, session_case.db)
+ for _ in range(requests)
+ )
)
assert len(results) == requests
@@ -347,7 +375,7 @@ async def test_concurrent_requests_can_renew_the_same_session(
@pytest.mark.asyncio
async def test_cancelled_request_does_not_renew_session(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch
) -> None:
"""取消请求时不续期会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', True)
@@ -367,7 +395,9 @@ async def load_user(*args: object) -> CurrentUserModel:
return session_case.user
monkeypatch.setattr(LoginService, '_get_current_user_from_db', load_user)
- pending = asyncio.create_task(LoginService.get_current_user(session_case.request, session_case.token, object()))
+ pending = asyncio.create_task(
+ LoginService.get_current_user(session_case.request, session_case.token, session_case.db)
+ )
await loaded.wait()
pending.cancel()
with pytest.raises(asyncio.CancelledError):
@@ -381,14 +411,16 @@ async def load_user(*args: object) -> CurrentUserModel:
@pytest.mark.asyncio
@pytest.mark.parametrize('same_time_login', [True, False])
async def test_plugin_validation_never_renews_main_session(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
"""插件校验不续期主会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
key = 'access_token:session-a' if same_time_login else 'access_token:7'
await session_case.redis.set(key, session_case.token, ex=_SESSION_TTL)
- result = await LoginService.get_current_user_for_plugin_session(session_case.request, session_case.token, object())
+ result = await LoginService.get_current_user_for_plugin_session(
+ session_case.request, session_case.token, session_case.db
+ )
assert result is session_case.user
assert session_case.redis.renew_calls == []
@@ -399,7 +431,7 @@ async def test_plugin_validation_never_renews_main_session(
@pytest.mark.asyncio
@pytest.mark.parametrize('same_time_login', [True, False])
async def test_plugin_final_session_check_failure_does_not_authenticate(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
"""插件最终会话校验失败时拒绝认证。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
@@ -428,7 +460,9 @@ async def read_session(cache_key: str) -> str | None:
monkeypatch.setattr(RequestContext, 'set_current_user', set_user)
with pytest.raises(RedisTimeoutError):
- await LoginService.get_current_user_for_plugin_session(session_case.request, session_case.token, object())
+ await LoginService.get_current_user_for_plugin_session(
+ session_case.request, session_case.token, session_case.db
+ )
assert session_reads == _PLUGIN_SESSION_READS
session_case.get_user.assert_awaited_once()
@@ -441,7 +475,7 @@ async def read_session(cache_key: str) -> str | None:
@pytest.mark.asyncio
@pytest.mark.parametrize('same_time_login', [True, False])
async def test_cancelled_plugin_final_session_check_does_not_authenticate(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
"""取消插件最终会话校验时拒绝认证。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
@@ -470,7 +504,7 @@ async def read_session(cache_key: str) -> str | None:
set_user = Mock()
monkeypatch.setattr(RequestContext, 'set_current_user', set_user)
pending = asyncio.create_task(
- LoginService.get_current_user_for_plugin_session(session_case.request, session_case.token, object())
+ LoginService.get_current_user_for_plugin_session(session_case.request, session_case.token, session_case.db)
)
await checking.wait()
pending.cancel()
@@ -488,7 +522,7 @@ async def read_session(cache_key: str) -> str | None:
@pytest.mark.asyncio
@pytest.mark.parametrize('same_time_login', [True, False])
async def test_logout_is_idempotent_and_only_removes_its_session(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
"""重复注销只移除本次会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
@@ -520,7 +554,7 @@ async def test_logout_is_idempotent_and_only_removes_its_session(
@pytest.mark.parametrize('same_time_login', [True, False])
@pytest.mark.parametrize('state', ['missing', 'expired', 'replaced'])
async def test_logout_of_stale_token_keeps_current_session(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool, state: str
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch, same_time_login: bool, state: str
) -> None:
"""旧令牌注销时保留当前会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
@@ -547,7 +581,7 @@ async def test_logout_of_stale_token_keeps_current_session(
@pytest.mark.parametrize('same_time_login', [True, False])
@pytest.mark.parametrize('login_before_logout', [True, False])
async def test_concurrent_new_login_survives_old_token_logout(
- session_case: SimpleNamespace,
+ session_case: SessionCase,
monkeypatch: pytest.MonkeyPatch,
same_time_login: bool,
login_before_logout: bool,
@@ -574,7 +608,10 @@ async def delayed_logout(script: str, count: int, cache_key: str, token: str) ->
result = None if login_before_logout else await original_eval(script, count, cache_key, token)
entered.set()
await resume.wait()
- return await original_eval(script, count, cache_key, token) if login_before_logout else result
+ if login_before_logout:
+ return await original_eval(script, count, cache_key, token)
+ assert isinstance(result, int)
+ return result
monkeypatch.setattr(session_case.redis, 'eval', delayed_logout)
pending = asyncio.create_task(LoginService.logout_services(session_case.request, token_id, session_case.token))
@@ -595,7 +632,7 @@ async def delayed_logout(script: str, count: int, cache_key: str, token: str) ->
@pytest.mark.asyncio
@pytest.mark.parametrize('same_time_login', [True, False])
async def test_logout_after_committed_renewal_does_not_restore_session(
- session_case: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
+ session_case: SessionCase, monkeypatch: pytest.MonkeyPatch, same_time_login: bool
) -> None:
"""续期提交后注销不会恢复会话。"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', same_time_login)
@@ -623,7 +660,9 @@ async def delayed_renewal(script: str, count: int, cache_key: str, token: str, s
return result
monkeypatch.setattr(session_case.redis, 'eval', delayed_renewal)
- pending = asyncio.create_task(LoginService.get_current_user(session_case.request, session_case.token, object()))
+ pending = asyncio.create_task(
+ LoginService.get_current_user(session_case.request, session_case.token, session_case.db)
+ )
await renewed.wait()
assert await LoginService.logout_services(session_case.request, token_id, session_case.token) is True
resume.set()
@@ -633,7 +672,7 @@ async def delayed_renewal(script: str, count: int, cache_key: str, token: str, s
assert await session_case.redis.get(key) is None
assert key not in session_case.redis.deadlines
with pytest.raises(AuthException):
- await LoginService.get_current_user(session_case.request, session_case.token, object())
+ await LoginService.get_current_user(session_case.request, session_case.token, session_case.db)
assert len(session_case.redis.renew_calls) == 1
@@ -642,7 +681,7 @@ async def delayed_renewal(script: str, count: int, cache_key: str, token: str, s
@pytest.mark.parametrize('committed', [True, False])
@pytest.mark.parametrize('failure', ['timeout', 'cancelled'])
async def test_failed_logout_and_retry_cannot_delete_new_login(
- session_case: SimpleNamespace,
+ session_case: SessionCase,
monkeypatch: pytest.MonkeyPatch,
same_time_login: bool,
committed: bool,
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_menu_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_menu_service.py
index d57b61bf9..b625df0a0 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_menu_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_menu_service.py
@@ -12,6 +12,17 @@
from module_admin.entity.do.menu_do import SysMenu
from module_admin.entity.vo.menu_vo import MenuModel, MenuSortModel
from module_admin.service.menu_service import MenuService
+from tests.module_admin.service.helpers import make_query_db
+
+
+def test_menu_tree_keeps_root_with_null_parent_id() -> None:
+ """父编号为空的菜单应作为根节点并保留其子菜单。"""
+ root = SysMenu(menu_id=10, menu_name='系统', parent_id=None)
+ child = SysMenu(menu_id=11, menu_name='用户', parent_id=10)
+ (tree,) = MenuService.list_to_tree([child, root])
+ assert (tree.id, tree.label, tree.parent_id) == (10, '系统', 0)
+ assert tree.children is not None
+ assert [node.id for node in tree.children] == [11]
def _menu(
@@ -46,15 +57,15 @@ def _menu(
('page_object', 'existing_menu'),
[
(
- MenuModel(menuId=2, parentId=1, path='system/user', routeName='SystemUser'),
+ MenuModel(menu_id=2, parent_id=1, path='system/user', route_name='SystemUser'),
_menu(menu_id=1, parent_id=1, path='SYSTEM/USER', route_name='OtherRoute'),
),
(
- MenuModel(menuId=2, parentId=0, path='system/user', routeName='SystemUser'),
+ MenuModel(menu_id=2, parent_id=0, path='system/user', route_name='SystemUser'),
_menu(menu_id=1, parent_id=9, path='SYSTEM/USER', route_name='OtherRoute'),
),
(
- MenuModel(menuId=2, parentId=2, path='different/path', routeName='SystemUser'),
+ MenuModel(menu_id=2, parent_id=2, path='different/path', route_name='SystemUser'),
_menu(menu_id=1, parent_id=1, path='system/user', route_name='systemuser'),
),
],
@@ -68,7 +79,7 @@ async def test_check_route_config_unique_rejects_route_conflicts(
'get_menus_by_path_or_route_name',
new=AsyncMock(return_value=[existing_menu]),
):
- result = await MenuService.check_route_config_unique_services(object(), page_object)
+ result = await MenuService.check_route_config_unique_services(make_query_db(), page_object)
assert result == CommonConstant.NOT_UNIQUE
@@ -76,14 +87,14 @@ async def test_check_route_config_unique_rejects_route_conflicts(
@pytest.mark.asyncio
async def test_check_route_config_unique_allows_same_path_under_different_parent_with_distinct_route_name() -> None:
"""不同上级下的同路径可使用不同路由名。"""
- page_object = MenuModel(menuId=2, parentId=2, path='system/user', routeName='SecondSystemUser')
+ page_object = MenuModel(menu_id=2, parent_id=2, path='system/user', route_name='SecondSystemUser')
existing_menu = _menu(menu_id=1, parent_id=1, path='system/user', route_name='FirstSystemUser')
with patch.object(
MenuDao,
'get_menus_by_path_or_route_name',
new=AsyncMock(return_value=[existing_menu]),
):
- result = await MenuService.check_route_config_unique_services(object(), page_object)
+ result = await MenuService.check_route_config_unique_services(make_query_db(), page_object)
assert result == CommonConstant.UNIQUE
@@ -91,14 +102,14 @@ async def test_check_route_config_unique_allows_same_path_under_different_parent
@pytest.mark.asyncio
async def test_check_route_config_unique_ignores_current_menu() -> None:
"""校验路由唯一性时排除当前菜单。"""
- page_object = MenuModel(menuId=1, parentId=1, path='system/user', routeName='SystemUser')
+ page_object = MenuModel(menu_id=1, parent_id=1, path='system/user', route_name='SystemUser')
current_menu = _menu(menu_id=1, parent_id=1, path='system/user', route_name='SystemUser')
with patch.object(
MenuDao,
'get_menus_by_path_or_route_name',
new=AsyncMock(return_value=[current_menu]),
):
- result = await MenuService.check_route_config_unique_services(object(), page_object)
+ result = await MenuService.check_route_config_unique_services(make_query_db(), page_object)
assert result == CommonConstant.UNIQUE
@@ -106,14 +117,14 @@ async def test_check_route_config_unique_ignores_current_menu() -> None:
@pytest.mark.asyncio
async def test_add_menu_rejects_duplicate_route_config() -> None:
"""新增菜单拒绝重复路由配置。"""
- page_object = MenuModel(menuName='用户管理', parentId=1, path='system/user', routeName='SystemUser', isFrame=1)
+ page_object = MenuModel(menu_name='用户管理', parent_id=1, path='system/user', route_name='SystemUser', is_frame=1)
with (
patch.object(MenuService, 'check_menu_name_unique_services', new=AsyncMock(return_value=True)),
patch.object(MenuService, 'check_route_config_unique_services', new=AsyncMock(return_value=False)),
patch.object(MenuDao, 'add_menu_dao', new_callable=AsyncMock) as add_menu,
pytest.raises(ServiceException) as exc_info,
):
- await MenuService.add_menu_services(object(), page_object)
+ await MenuService.add_menu_services(make_query_db(), page_object)
assert exc_info.value.message == '新增菜单用户管理失败,路由名称或地址已存在'
add_menu.assert_not_awaited()
@@ -125,7 +136,7 @@ async def test_get_menus_by_path_or_route_name_is_case_insensitive_and_excludes_
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysMenu.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysMenu.get_table()])
try:
async with session_maker() as session:
@@ -168,7 +179,7 @@ async def test_get_menus_by_path_or_route_name_is_case_insensitive_and_excludes_
def test_parse_menu_sort_items_preserves_corresponding_order_values() -> None:
"""解析菜单排序时保留各菜单对应的顺序值。"""
- result = MenuService.parse_menu_sort_items(MenuSortModel(menuIds='101, 102', orderNums='3, 1'))
+ result = MenuService.parse_menu_sort_items(MenuSortModel(menu_ids='101, 102', order_nums='3, 1'))
assert result == [
{'menu_id': 101, 'order_num': 3},
@@ -189,7 +200,7 @@ def test_parse_menu_sort_items_preserves_corresponding_order_values() -> None:
def test_parse_menu_sort_items_rejects_invalid_parameters(menu_ids: str, order_nums: str) -> None:
"""菜单排序拒绝无效参数。"""
with pytest.raises(ServiceException) as exc_info:
- MenuService.parse_menu_sort_items(MenuSortModel(menuIds=menu_ids, orderNums=order_nums))
+ MenuService.parse_menu_sort_items(MenuSortModel(menu_ids=menu_ids, order_nums=order_nums))
assert exc_info.value.message == '菜单排序参数不正确'
@@ -200,7 +211,7 @@ async def test_update_menu_sort_updates_all_rows_in_one_transaction() -> None:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysMenu.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysMenu.get_table()])
try:
async with session_maker() as session:
@@ -214,7 +225,7 @@ async def test_update_menu_sort_updates_all_rows_in_one_transaction() -> None:
result = await MenuService.update_menu_sort_services(
session,
- MenuSortModel(menuIds='101,102', orderNums='5,4'),
+ MenuSortModel(menu_ids='101,102', order_nums='5,4'),
)
rows = (await session.execute(select(SysMenu.menu_id, SysMenu.order_num).order_by(SysMenu.menu_id))).all()
@@ -227,7 +238,7 @@ async def test_update_menu_sort_updates_all_rows_in_one_transaction() -> None:
@pytest.mark.asyncio
async def test_update_menu_sort_rolls_back_and_wraps_database_error() -> None:
"""菜单排序遇到数据库错误时回滚并转换异常。"""
- query_db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ query_db = make_query_db()
with (
patch.object(MenuDao, 'update_menu_sort_dao', AsyncMock(side_effect=RuntimeError('database error'))),
@@ -235,7 +246,7 @@ async def test_update_menu_sort_rolls_back_and_wraps_database_error() -> None:
):
await MenuService.update_menu_sort_services(
query_db,
- MenuSortModel(menuIds='101', orderNums='2'),
+ MenuSortModel(menu_ids='101', order_nums='2'),
)
assert exc_info.value.message == '保存排序异常,请联系管理员'
@@ -252,7 +263,7 @@ async def _create_menu_tree() -> tuple[AsyncEngine, async_sessionmaker[AsyncSess
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
sessions = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysMenu.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysMenu.get_table()])
async with sessions() as session:
session.add_all(
[
@@ -281,7 +292,7 @@ async def test_edit_menu_rejects_invalid_parent_chains_without_writing(parent_id
with pytest.raises(ServiceException):
await MenuService.edit_menu_services(
session,
- MenuModel(menuId=501, parentId=parent_id, menuName='系统目录', menuType='M', path='system'),
+ MenuModel(menu_id=501, parent_id=parent_id, menu_name='系统目录', menu_type='M', path='system'),
)
assert (await session.execute(query)).all() == before
finally:
@@ -297,7 +308,7 @@ async def test_edit_menu_preserves_root_or_moves_subtree_to_valid_parent(parent_
async with sessions() as session:
result = await MenuService.edit_menu_services(
session,
- MenuModel(menuId=501, parentId=parent_id, menuName='新系统目录', menuType='M', path='system'),
+ MenuModel(menu_id=501, parent_id=parent_id, menu_name='新系统目录', menu_type='M', path='system'),
)
rows = (
await session.execute(
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_html_security.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_html_security.py
index 1d603bfc2..3906c7e2c 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_html_security.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_html_security.py
@@ -31,6 +31,7 @@ def test_direct_api_input_is_cleaned_before_persistence() -> None:
@app.post('/notice', summary='提交通知内容', description='返回通过模型校验的通知内容,用于验证写入前的 HTML 清理。')
def notice(payload: NoticeModel) -> NoticeModel:
+ assert payload.notice_content is not None
assert_safe(payload.notice_content.decode())
return payload
@@ -54,6 +55,7 @@ async def test_legacy_notice_detail_and_list_are_sanitized(monkeypatch: pytest.M
)
monkeypatch.setattr(NoticeDao, 'get_notice_list', AsyncMock(return_value=[{'noticeContent': PAYLOAD}]))
result = await NoticeService.notice_detail_services(AsyncMock(), 2)
+ assert result.notice_content is not None
assert_safe(result.notice_content.decode())
rows = await NoticeService.get_notice_list_services(AsyncMock(), NoticePageQueryModel(), False)
assert_safe(rows[0]['noticeContent'])
@@ -62,7 +64,8 @@ async def test_legacy_notice_detail_and_list_are_sanitized(monkeypatch: pytest.M
@pytest.mark.parametrize('url', ['javascript:alert(1)', 'javascript:alert(1)', 'data:text/html,x', 'vbscript:x'])
def test_rejects_dangerous_urls_and_embedded_content(url: str) -> None:
"""拒绝危险链接及嵌入内容。"""
- result = NoticeModel(noticeContent=f'x ')
+ result = NoticeModel(notice_content=f'x ')
+ assert result.notice_content is not None
content = result.notice_content.decode()
assert 'href=' not in content
assert 'src=' not in content
@@ -72,16 +75,20 @@ def test_rejects_dangerous_urls_and_embedded_content(url: str) -> None:
def test_legal_rich_text_and_partial_updates_are_preserved() -> None:
"""保留合法富文本并支持部分更新。"""
content = '标题 '
- result = NoticeModel(noticeContent=content).notice_content.decode()
+ notice = NoticeModel(notice_content=content)
+ assert notice.notice_content is not None
+ result = notice.notice_content.decode()
assert '标题 ' in result and '正文 ' in result and 'colspan="2"' in result
assert 'notice_content' not in NoticeModel(status='1').model_dump(exclude_unset=True)
def test_quill_text_styles_are_preserved_without_layout_styles() -> None:
"""保留 Quill 文本样式并剔除布局样式。"""
- content = NoticeModel(
- noticeContent='正文
'
- ).notice_content.decode()
+ notice = NoticeModel(
+ notice_content='正文
'
+ )
+ assert notice.notice_content is not None
+ content = notice.notice_content.decode()
assert 'ql-align-center' in content
assert 'color:red' in content and 'background-color:yellow' in content
assert 'position' not in content
@@ -89,11 +96,15 @@ def test_quill_text_styles_are_preserved_without_layout_styles() -> None:
def test_quill_video_is_sandboxed_and_cannot_embed_inline_script() -> None:
"""Quill 视频在沙箱中播放且不能嵌入内联脚本。"""
- content = NoticeModel(
- noticeContent=''
- ).notice_content.decode()
+ notice = NoticeModel(
+ notice_content=''
+ )
+ assert notice.notice_content is not None
+ content = notice.notice_content.decode()
assert 'src="https://video.example/embed/1"' in content
assert 'sandbox="allow-scripts allow-presentation"' in content
assert 'srcdoc' not in content and 'allow-same-origin' not in content
- content = NoticeModel(noticeContent='正文 ').notice_content.decode()
+ notice = NoticeModel(notice_content='正文 ')
+ assert notice.notice_content is not None
+ content = notice.notice_content.decode()
assert 'expression' not in content
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_service.py
index 4c1beb40b..aa230e4e6 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_notice_service.py
@@ -49,7 +49,7 @@ async def _create_notice_tables() -> tuple[AsyncEngine, async_sessionmaker[Async
)
await connection.run_sync(
Base.metadata.create_all,
- tables=[SysDept.__table__, SysUser.__table__, SysNoticeRead.__table__],
+ tables=[SysDept.get_table(), SysUser.get_table(), SysNoticeRead.get_table()],
)
return engine, session_maker
@@ -160,11 +160,11 @@ async def test_get_notice_read_user_list_supports_search_and_pagination() -> Non
page = await NoticeService.get_notice_read_user_list_services(
session,
- NoticeReadUserPageQueryModel(noticeId=1, pageNum=1, pageSize=1),
+ NoticeReadUserPageQueryModel(notice_id=1, page_num=1, page_size=1),
)
search_page = await NoticeService.get_notice_read_user_list_services(
session,
- NoticeReadUserPageQueryModel(noticeId=1, searchValue='ali'),
+ NoticeReadUserPageQueryModel(notice_id=1, search_value='ali'),
)
assert page.total == EXPECTED_VISIBLE_READ_USER_COUNT
@@ -186,7 +186,7 @@ async def test_delete_notice_removes_read_records_in_same_transaction() -> None:
await NoticeDao.add_notice_reads(session, CURRENT_USER_ID, [1])
await session.commit()
- result = await NoticeService.delete_notice_services(session, DeleteNoticeModel(noticeIds='1'))
+ result = await NoticeService.delete_notice_services(session, DeleteNoticeModel(notice_ids='1'))
notice_count = (await session.execute(select(func.count()).select_from(SysNotice))).scalar_one()
read_count = (await session.execute(select(func.count()).select_from(SysNoticeRead))).scalar_one()
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_online_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_online_service.py
index be3de7adb..aede2ffc0 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_online_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_online_service.py
@@ -6,6 +6,7 @@
from exceptions.exception import AuthException
from module_admin.entity.vo.online_vo import OnlineQueryModel
from module_admin.service.online_service import OnlineService
+from tests.module_admin.service.helpers import make_redis_request
@pytest.mark.asyncio
@@ -15,7 +16,7 @@ async def test_online_list_skips_tokens_that_cannot_be_decoded() -> None:
keys=AsyncMock(return_value=['access_token:stale-session']),
get=AsyncMock(return_value='invalid-token'),
)
- request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis)))
+ request = make_redis_request(redis)
with patch(
'module_admin.service.online_service.JwtUtil.decode',
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_server_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_server_service.py
index 19695ba6c..897cc6255 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_server_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_server_service.py
@@ -43,6 +43,7 @@ async def test_server_disks_sample_each_mountpoint_once(
partitions.assert_called_once_with()
assert usage.call_args_list == [call(mountpoint) for mountpoint in mountpoints]
+ assert result.sys_files is not None
assert [disk.model_dump(by_alias=True) for disk in result.sys_files] == [
{
'dirName': devices[0],
@@ -136,6 +137,7 @@ def test_missing_mount_metadata_still_reads_real_root_disk(monkeypatch: pytest.M
assert disks[0].total == bytes2human(expected.total)
assert disks[0].used
assert disks[0].free
+ assert disks[0].usage is not None
assert disks[0].usage.endswith('%')
@@ -154,9 +156,13 @@ async def test_server_monitor_retains_other_metrics_when_all_disks_are_unreadabl
result = await ServerService.get_server_monitor_info()
assert result.sys_files == []
+ assert result.cpu is not None and result.cpu.cpu_num is not None
assert result.cpu.cpu_num > 0
+ assert result.mem is not None
assert result.mem.total
+ assert result.sys is not None
assert result.sys.os_name
+ assert result.py is not None
assert result.py.version
usage.assert_called_once_with(root)
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_user_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_user_service.py
index 81aa1c39f..b80e09c7c 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_user_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_user_service.py
@@ -1,13 +1,20 @@
from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, MagicMock
import pytest
+from redis.asyncio import Redis
+from sqlalchemy import true
+from sqlalchemy.ext.asyncio import AsyncSession
from common.enums import PasswordCharacterType
+from common.vo import PageModel
from exceptions.exception import ServiceException
from module_admin.dao.user_dao import UserDao
-from module_admin.entity.vo.user_vo import EditUserModel
+from module_admin.entity.vo.user_vo import EditUserModel, UserInfoModel, UserRolePageQueryModel
+from module_admin.service.post_service import PostService
+from module_admin.service.role_service import RoleService
from module_admin.service.user_service import UserService
+from tests.module_admin.service.helpers import make_query_db
@pytest.mark.asyncio
@@ -16,8 +23,8 @@ async def test_edit_user_accepts_form_without_readonly_roles(
monkeypatch: pytest.MonkeyPatch, readonly_fields: dict
) -> None:
"""编辑表单可以省略只读角色详情,用户字段与角色/岗位关联仍全部保存。"""
- user = EditUserModel(userId=2, userName='tester', sex='1', roleIds=[2], postIds=[1], **readonly_fields)
- database = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ user = EditUserModel(user_id=2, user_name='tester', sex='1', role_ids=[2], post_ids=[1], **readonly_fields)
+ database = make_query_db()
monkeypatch.setattr(UserService, 'user_detail_services', AsyncMock(return_value=SimpleNamespace(data=user)))
monkeypatch.setattr(UserService, 'check_user_name_unique_services', AsyncMock(return_value=True))
security_event = AsyncMock()
@@ -39,8 +46,10 @@ async def test_edit_user_accepts_form_without_readonly_roles(
operations['edit_user_dao'].assert_awaited_once_with(database, {'user_id': 2, 'user_name': 'tester', 'sex': '1'})
for operation in operations.values():
operation.assert_awaited_once()
- assert operations['add_user_role_dao'].await_args.args[1].role_id == user.role_ids[0]
- assert operations['add_user_post_dao'].await_args.args[1].post_id == user.post_ids[0]
+ assert user.role_ids
+ assert operations['add_user_role_dao'].await_args_list[-1].args[1].role_id == user.role_ids[0]
+ assert user.post_ids
+ assert operations['add_user_post_dao'].await_args_list[-1].args[1].post_id == user.post_ids[0]
security_event.assert_awaited_once_with(database, user, user)
database.commit.assert_awaited_once()
database.rollback.assert_not_awaited()
@@ -59,7 +68,8 @@ async def test_edit_user_accepts_form_without_readonly_roles(
)
async def test_validate_password_accepts_each_character_type(pwd_chrtype: str, password: str) -> None:
"""密码校验接受各类允许的字符。"""
- redis = SimpleNamespace(get=AsyncMock(return_value=pwd_chrtype))
+ redis = MagicMock(spec_set=Redis)
+ redis.get = AsyncMock(return_value=pwd_chrtype)
await UserService.validate_password_services(redis, password)
@@ -79,7 +89,8 @@ async def test_validate_password_accepts_each_character_type(pwd_chrtype: str, p
)
async def test_validate_password_rejects_invalid_character_type(pwd_chrtype: str, password: str, message: str) -> None:
"""密码校验拒绝不允许的字符类型。"""
- redis = SimpleNamespace(get=AsyncMock(return_value=pwd_chrtype))
+ redis = MagicMock(spec_set=Redis)
+ redis.get = AsyncMock(return_value=pwd_chrtype)
with pytest.raises(ServiceException) as exc_info:
await UserService.validate_password_services(redis, password)
@@ -91,7 +102,8 @@ async def test_validate_password_rejects_invalid_character_type(pwd_chrtype: str
@pytest.mark.parametrize('password', ['12345', '123456789012345678901'])
async def test_validate_password_rejects_invalid_length(password: str) -> None:
"""密码校验拒绝无效长度。"""
- redis = SimpleNamespace(get=AsyncMock(return_value='0'))
+ redis = MagicMock(spec_set=Redis)
+ redis.get = AsyncMock(return_value='0')
with pytest.raises(ServiceException) as exc_info:
await UserService.validate_password_services(redis, password)
@@ -102,7 +114,8 @@ async def test_validate_password_rejects_invalid_length(password: str) -> None:
@pytest.mark.asyncio
async def test_validate_password_uses_fixed_rule_without_reading_config() -> None:
"""指定固定密码规则时无需读取配置。"""
- redis = SimpleNamespace(get=AsyncMock(return_value='4'))
+ redis = MagicMock(spec_set=Redis)
+ redis.get = AsyncMock(return_value='4')
await UserService.validate_password_services(redis, 'abcdef', PasswordCharacterType.DEFAULT)
@@ -113,6 +126,54 @@ async def test_validate_password_uses_fixed_rule_without_reading_config() -> Non
@pytest.mark.parametrize('config_value', [None, '', 'invalid'])
async def test_validate_password_falls_back_to_default_rule(config_value: str | None) -> None:
"""密码校验支持回退到默认规则。"""
- redis = SimpleNamespace(get=AsyncMock(return_value=config_value))
+ redis = MagicMock(spec_set=Redis)
+ redis.get = AsyncMock(return_value=config_value)
await UserService.validate_password_services(redis, 'abcdef')
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize('allocated', [True, False])
+async def test_role_user_lists_support_paged_and_unpaged_queries(
+ monkeypatch: pytest.MonkeyPatch, allocated: bool
+) -> None:
+ """验证已分配和未分配用户列表均保留分页信息,并支持默认的不分页查询。"""
+ rows = [{'userId': 3, 'userName': 'reader'}]
+ page = PageModel(rows=rows, page_num=2, page_size=1, total=3, has_next=True)
+ fetch = AsyncMock(side_effect=[rows, page])
+ if allocated:
+ monkeypatch.setattr(UserDao, 'get_user_role_allocated_list_by_role_id', fetch)
+ list_users = RoleService.get_role_user_allocated_list_services
+ else:
+ monkeypatch.setattr(UserDao, 'get_user_role_unallocated_list_by_role_id', fetch)
+ list_users = RoleService.get_role_user_unallocated_list_services
+ query = UserRolePageQueryModel.model_validate({'roleId': 2})
+ async with AsyncSession() as db:
+ users = await list_users(db, query, true())
+ paged_users = await list_users(db, query, true(), is_page=True)
+ assert users == [UserInfoModel(user_id=3, user_name='reader')]
+ assert paged_users.rows == users
+ assert (paged_users.page_num, paged_users.page_size, paged_users.total, paged_users.has_next) == (2, 1, 3, True)
+ assert [call.args[-1] for call in fetch.await_args_list] == [False, True]
+
+
+@pytest.mark.asyncio
+async def test_missing_user_has_no_profile_or_role_details(monkeypatch: pytest.MonkeyPatch) -> None:
+ """用户不存在时,详情、个人资料和角色选择接口均返回空的用户资料。"""
+ missing = {
+ 'user_basic_info': None,
+ 'user_dept_info': None,
+ 'user_post_info': [],
+ 'user_role_info': [],
+ 'user_menu_info': [],
+ }
+ monkeypatch.setattr(UserDao, 'get_user_detail_by_id', AsyncMock(return_value=missing))
+ monkeypatch.setattr(PostService, 'get_post_list_services', AsyncMock(return_value=[]))
+ monkeypatch.setattr(RoleService, 'get_role_select_option_services', AsyncMock(return_value=[]))
+ async with AsyncSession() as db:
+ detail = await UserService.user_detail_services(db, 2)
+ profile = await UserService.user_profile_services(db, 2)
+ roles = await UserService.get_user_role_allocated_list_services(db, UserRolePageQueryModel(user_id=2))
+ assert detail.data is None
+ assert profile.data is None
+ assert roles.user is None
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_user_timezone.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_user_timezone.py
index a74d30261..1844b5143 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_user_timezone.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_user_timezone.py
@@ -12,31 +12,32 @@
from module_admin.entity.do.user_do import SysUser
from module_admin.entity.vo.user_vo import UserInfoModel, UserModel, UserTimezoneModel
from module_admin.service.user_service import UserService
+from tests.module_admin.service.helpers import make_query_db
from utils.common_util import CamelCaseUtil
@pytest.mark.parametrize('value', ['auto', 'UTC', 'Asia/Shanghai', 'America/New_York', ' Asia/Kathmandu '])
def test_timezone_preference_validation(value: str) -> None:
"""校验用户的时区偏好。"""
- assert UserTimezoneModel(timeZone=value).time_zone == value.strip()
- assert UserModel(timeZone=value).time_zone == value.strip()
+ assert UserTimezoneModel(time_zone=value).time_zone == value.strip()
+ assert UserModel(time_zone=value).time_zone == value.strip()
@pytest.mark.parametrize('value', ['', None, 'Mars/Olympus', 'UTC+8', '../UTC', 'a' * 65])
def test_invalid_timezone_preference_rejected(value: object) -> None:
"""拒绝无效的时区偏好。"""
with pytest.raises(ValidationError):
- UserTimezoneModel(timeZone=value)
+ UserTimezoneModel.model_validate({'timeZone': value})
with pytest.raises(ValidationError):
- UserModel(timeZone=value)
+ UserModel.model_validate({'timeZone': value})
def test_timezone_endpoint_rejects_identity_and_management_fields() -> None:
"""时区接口拒绝身份及管理字段。"""
with pytest.raises(ValidationError):
- UserTimezoneModel(timeZone='UTC', userId=2)
+ UserTimezoneModel.model_validate({'timeZone': 'UTC', 'userId': 2})
with pytest.raises(ValidationError):
- UserTimezoneModel(timeZone='UTC', roleIds=[1])
+ UserTimezoneModel.model_validate({'timeZone': 'UTC', 'roleIds': [1]})
@pytest.mark.asyncio
@@ -45,7 +46,7 @@ async def test_timezone_update_persists_only_current_account() -> None:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
try:
async with engine.begin() as connection:
- await connection.run_sync(SysUser.__table__.create)
+ await connection.run_sync(SysUser.get_table().create)
sessions = async_sessionmaker(engine, expire_on_commit=False)
async with sessions() as db:
db.add_all(
@@ -58,7 +59,7 @@ async def test_timezone_update_persists_only_current_account() -> None:
async with sessions() as db:
current_user = SimpleNamespace(user=SimpleNamespace(user_id=1, user_name='one'))
await inspect.unwrap(change_system_user_timezone)(
- SimpleNamespace(), UserTimezoneModel(timeZone='America/New_York'), db, current_user
+ SimpleNamespace(), UserTimezoneModel(time_zone='America/New_York'), db, current_user
)
async with sessions() as db:
users = (await db.scalars(select(SysUser).order_by(SysUser.user_id))).all()
@@ -70,7 +71,9 @@ async def test_timezone_update_persists_only_current_account() -> None:
assert info.model_dump(by_alias=True)['timeZone'] == 'America/New_York'
await UserService.update_user_timezone_services(db, 1, 'one', 'auto')
async with sessions() as db:
- assert (await db.get(SysUser, 1)).time_zone == 'auto'
+ user = await db.get(SysUser, 1)
+ assert user is not None
+ assert user.time_zone == 'auto'
finally:
await engine.dispose()
@@ -78,7 +81,7 @@ async def test_timezone_update_persists_only_current_account() -> None:
@pytest.mark.asyncio
async def test_timezone_update_rolls_back_on_failure(monkeypatch: pytest.MonkeyPatch) -> None:
"""时区更新失败时回滚。"""
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ db = make_query_db()
monkeypatch.setattr(UserDao, 'edit_user_dao', AsyncMock(side_effect=RuntimeError('database unavailable')))
with pytest.raises(RuntimeError):
await UserService.update_user_timezone_services(db, 1, 'one', 'UTC')
diff --git a/ruoyi-fastapi-backend/tests/module_generator/dao/test_gen_dao.py b/ruoyi-fastapi-backend/tests/module_generator/dao/test_gen_dao.py
index 39838cbad..47b1cde98 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/dao/test_gen_dao.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/dao/test_gen_dao.py
@@ -1,9 +1,10 @@
from datetime import UTC, datetime
-from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+from config.env import DataBaseConfig
from module_generator.dao.gen_dao import GenTableColumnDao, GenTableDao
from module_generator.entity.vo.gen_vo import GenTablePageQueryModel
from utils.page_util import PageUtil
@@ -24,7 +25,7 @@ async def test_get_gen_table_by_name_is_scoped_to_data_source() -> None:
await GenTableDao.get_gen_table_by_name(db, 'orders', 'reporting')
- statement = db.execute.await_args.args[0]
+ statement = db.execute.await_args_list[-1].args[0]
params = statement.compile().params
assert 'orders' in params.values()
assert 'reporting' in params.values()
@@ -33,24 +34,24 @@ async def test_get_gen_table_by_name_is_scoped_to_data_source() -> None:
@pytest.mark.asyncio
async def test_get_gen_table_list_filters_source_when_requested() -> None:
"""生成表列表可按指定数据源过滤。"""
- query_object = GenTablePageQueryModel(dataSourceName='reporting')
+ query_object = GenTablePageQueryModel(data_source_name='reporting')
with patch.object(PageUtil, 'paginate', new=AsyncMock(return_value=[])) as paginate:
- await GenTableDao.get_gen_table_list(object(), query_object, is_page=True)
+ await GenTableDao.get_gen_table_list(AsyncMock(spec=AsyncSession), query_object, is_page=True)
- query = paginate.await_args.args[1]
+ query = paginate.await_args_list[-1].args[1]
assert 'reporting' in query.compile().params.values()
@pytest.mark.asyncio
async def test_get_gen_db_table_list_does_not_bind_unreferenced_model_defaults() -> None:
"""查询数据库表时跳过未引用的模型默认值。"""
- query_object = GenTablePageQueryModel(formColNum=3)
+ query_object = GenTablePageQueryModel(form_col_num=3)
with patch.object(PageUtil, 'paginate', new=AsyncMock(return_value=[])) as paginate:
- result = await GenTableDao.get_gen_db_table_list(object(), query_object, is_page=True)
+ result = await GenTableDao.get_gen_db_table_list(AsyncMock(spec=AsyncSession), query_object, is_page=True)
- query = paginate.await_args.args[1]
+ query = paginate.await_args_list[-1].args[1]
assert query.compile().params == {}
assert result == []
@@ -59,19 +60,21 @@ async def test_get_gen_db_table_list_does_not_bind_unreferenced_model_defaults()
async def test_get_gen_db_table_list_only_binds_active_sql_filters() -> None:
"""查询数据库表时仅绑定启用的过滤条件。"""
query_object = GenTablePageQueryModel(
- tableName='sys_user',
- tableComment='用户',
- beginTime='2026-07-01',
- endTime='2026-07-30',
- formColNum=2,
+ table_name='sys_user',
+ table_comment='用户',
+ begin_time='2026-07-01',
+ end_time='2026-07-30',
+ form_col_num=2,
)
with patch.object(PageUtil, 'paginate', new=AsyncMock(return_value=[])) as paginate:
- await GenTableDao.get_gen_db_table_list(object(), query_object)
+ await GenTableDao.get_gen_db_table_list(AsyncMock(spec=AsyncSession), query_object)
- query = paginate.await_args.args[1]
+ query = paginate.await_args_list[-1].args[1]
compiled_sql = str(query.compile())
- begin, end = TimezoneUtil.local_date_strings_to_utc('2026-07-01', '2026-07-30')
+ bounds = TimezoneUtil.local_date_strings_to_utc('2026-07-01', '2026-07-30')
+ assert bounds is not None
+ begin, end = bounds
assert query.compile().params == {
'table_name': 'sys_user',
'table_comment': '用户',
@@ -88,13 +91,13 @@ async def test_get_gen_db_table_list_uses_target_source_config() -> None:
with patch.object(PageUtil, 'paginate', new=AsyncMock(return_value=[])) as paginate:
await GenTableDao.get_gen_db_table_list(
- object(),
+ AsyncMock(spec=AsyncSession),
query_object,
excluded_table_names={'sys_user'},
- source_config=SimpleNamespace(db_type='postgresql'),
+ source_config=DataBaseConfig.default_source.model_copy(update={'db_type': 'postgresql'}),
)
- query = paginate.await_args.args[1]
+ query = paginate.await_args_list[-1].args[1]
assert 'list_table' in str(query.compile())
assert query.compile().params['excluded_table_names'] == ('sys_user',)
@@ -110,7 +113,7 @@ async def test_edit_gen_table_keeps_alias_fields_while_excluding_audit_times() -
{'tableId': TABLE_ID, 'tableName': 'orders', 'updateTime': CLIENT_AUDIT_TIME},
)
- params = db.execute.await_args.args[1][0]
+ params = db.execute.await_args_list[-1].args[1][0]
assert params['table_id'] == TABLE_ID
assert params['table_name'] == 'orders'
assert 'create_time' not in params
@@ -128,7 +131,7 @@ async def test_edit_gen_table_column_keeps_alias_fields_while_excluding_audit_ti
{'columnId': COLUMN_ID, 'columnName': 'order_id', 'updateTime': CLIENT_AUDIT_TIME},
)
- params = db.execute.await_args.args[1][0]
+ params = db.execute.await_args_list[-1].args[1][0]
assert params['column_id'] == COLUMN_ID
assert params['column_name'] == 'order_id'
assert 'create_time' not in params
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_gen_service.py b/ruoyi-fastapi-backend/tests/module_generator/test_gen_service.py
index 456c11f7e..c42cf089b 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_gen_service.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_gen_service.py
@@ -5,12 +5,43 @@
import pytest
from sqlalchemy import create_engine, text
+from sqlalchemy.ext.asyncio import AsyncSession
+from common.constant import GenConstant
from exceptions.exception import ServiceException
-from module_generator.entity.vo.gen_vo import EditGenTableModel, GenTableColumnModel
+from module_generator.entity.vo.gen_vo import EditGenTableModel, GenTableColumnModel, GenTableModel
from module_generator.service.gen_service import GenTableService
+@pytest.mark.asyncio
+async def test_primary_keys_use_marked_column_or_first_child_column() -> None:
+ """主表选择已标记的主键,子表未标记主键时选择自己的第一列。"""
+ table = GenTableModel.model_validate(
+ {
+ 'tplCategory': GenConstant.TPL_SUB,
+ 'columns': [{'columnName': 'name'}, {'columnName': 'id', 'isPk': '1'}],
+ 'subTable': {'columns': [{'columnName': 'child_id'}, {'columnName': 'detail'}]},
+ }
+ )
+ await GenTableService.set_pk_column(table)
+ assert table.pk_column is not None and table.pk_column.column_name == 'id'
+ assert table.sub_table is not None and table.sub_table.pk_column is not None
+ assert table.sub_table.pk_column.column_name == 'child_id'
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize('columns', [None, []])
+async def test_primary_key_requires_columns_or_an_existing_key(columns: list | None) -> None:
+ """缺少字段时返回配置错误,已有的主键配置仍然有效。"""
+ table = GenTableModel(columns=columns)
+ with pytest.raises(ServiceException) as exc:
+ await GenTableService.set_pk_column(table)
+ assert exc.value.msg_key == 'generator.configurationRequired'
+ table.pk_column = GenTableColumnModel(column_name='preset')
+ await GenTableService.set_pk_column(table)
+ assert table.pk_column.column_name == 'preset'
+
+
def test_get_data_source_list_services_returns_camel_case_response(monkeypatch: pytest.MonkeyPatch) -> None:
"""数据源列表服务以驼峰字段返回。"""
settings = SimpleNamespace(
@@ -61,7 +92,9 @@ async def session(_source_name: str) -> AsyncGenerator[object, None]:
'module_generator.service.gen_service.GenTableDao.get_gen_db_table_list_by_names',
new=AsyncMock(return_value=rows),
):
- result = await GenTableService.get_gen_db_table_list_by_name_services(object(), ['sys_user'], 'reporting')
+ result = await GenTableService.get_gen_db_table_list_by_name_services(
+ AsyncMock(spec=AsyncSession), ['sys_user'], 'reporting'
+ )
assert result[0].table_name == 'sys_user'
assert result[0].data_source_name == 'reporting'
@@ -79,7 +112,7 @@ async def test_batch_gen_code_services_rejects_tables_from_other_sources() -> No
pytest.raises(ServiceException) as exc_info,
):
await GenTableService.batch_gen_code_services(
- object(),
+ AsyncMock(spec=AsyncSession),
['sys_user', 'report_order'],
'reporting',
)
@@ -94,12 +127,12 @@ async def test_edit_gen_table_services_preserves_alias_fields_for_both_daos() ->
table_id = 7
column_id = 9
page_object = EditGenTableModel(
- tableId=table_id,
- tableName='orders',
- updateBy='admin',
- columns=[GenTableColumnModel(columnId=column_id, columnName='order_id')],
+ table_id=table_id,
+ table_name='orders',
+ update_by='admin',
+ columns=[GenTableColumnModel(column_id=column_id, column_name='order_id')],
)
- query_db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ query_db = AsyncMock(spec=AsyncSession)
table_info = SimpleNamespace(table_id=table_id, data_source_name='primary')
with (
@@ -119,8 +152,8 @@ async def test_edit_gen_table_services_preserves_alias_fields_for_both_daos() ->
):
await GenTableService.edit_gen_table_services(query_db, page_object)
- table_payload = edit_table.await_args.args[1]
- column_payload = edit_column.await_args.args[1]
+ table_payload = edit_table.await_args_list[-1].args[1]
+ column_payload = edit_column.await_args_list[-1].args[1]
assert table_payload['tableId'] == table_id
assert table_payload['tableName'] == 'orders'
assert column_payload['columnId'] == column_id
@@ -129,3 +162,24 @@ async def test_edit_gen_table_services_preserves_alias_fields_for_both_daos() ->
assert 'updateTime' not in table_payload
assert 'createTime' not in column_payload
assert 'updateTime' not in column_payload
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ('configuration', 'expected_key'),
+ [
+ ({'tplCategory': 'tree'}, 'generator.treeCodeRequired'),
+ ({'tplCategory': 'tree', 'params': {'treeCode': 'id'}}, 'generator.treeParentCodeRequired'),
+ (
+ {'tplCategory': 'tree', 'params': {'treeCode': 'id', 'treeParentCode': 'parent_id'}},
+ 'generator.treeNameRequired',
+ ),
+ ({'tplCategory': 'sub'}, 'generator.childTableRequired'),
+ ({'tplCategory': 'sub', 'subTableName': 'detail'}, 'generator.childForeignKeyRequired'),
+ ],
+)
+async def test_validate_edit_reports_missing_template_fields(configuration: dict, expected_key: str) -> None:
+ """树表和主子表缺少必填配置时返回对应的错误消息。"""
+ with pytest.raises(ServiceException) as error:
+ await GenTableService.validate_edit(EditGenTableModel.model_validate(configuration))
+ assert error.value.msg_key == expected_key
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_generated_i18n.py b/ruoyi-fastapi-backend/tests/module_generator/test_generated_i18n.py
index 36c762293..136cd96ec 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_generated_i18n.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_generated_i18n.py
@@ -11,6 +11,7 @@
import pytest
from babel.messages.pofile import read_po, write_po
from jinja2 import StrictUndefined
+from sqlalchemy.ext.asyncio import AsyncSession
from test_generated_time_contract import column, make_table
from common.context import LocaleContext
@@ -44,7 +45,7 @@ def render_files(table: GenTableModel) -> tuple[list[Any], dict[str, str]]:
info = render_info(table)
env = TemplateInitializer.init_jinja2()
env.undefined = StrictUndefined
- return info, GenTableService._GenTableService__render_files(env, info)
+ return info, GenTableService._render_files(env, info)
def flatten(value: dict, prefix: str = '') -> dict:
@@ -72,6 +73,7 @@ def test_generated_sources_register_literal_module_keys_and_compile(
) -> None:
"""生成代码注册字面模块键并可编译。"""
table = make_table('mysql', category, web_type)
+ assert table.columns
table.columns[1].is_required = '1'
table.columns[1].column_comment = '名称“业务”'
info, files = render_files(table)
@@ -133,6 +135,7 @@ def test_generated_sources_register_literal_module_keys_and_compile(
def test_generator_uses_configured_locales_and_reports_unknown_translations() -> None:
"""生成器采用配置的语言并报告未知译文。"""
table = make_table('mysql', 'crud', 'element-ui')
+ assert table.options
options = json.loads(table.options)
options.update(
i18nLocales=['en-US', 'fr-FR'],
@@ -195,10 +198,11 @@ async def test_generation_failure_keeps_internal_paths_out_of_messages(locale: s
patch.object(
GenTableService, '_GenTableService__get_gen_render_info', AsyncMock(return_value=render_info(table))
),
- patch.object(GenTableService, '_GenTableService__get_output_root', side_effect=PermissionError(secret)),
+ patch.object(GenTableService, '_get_output_root', side_effect=PermissionError(secret)),
pytest.raises(ServiceException) as error,
):
- await GenTableService.generate_code_services(object(), table.table_name)
+ assert table.table_name is not None
+ await GenTableService.generate_code_services(AsyncMock(spec=AsyncSession), table.table_name)
fields = I18nUtil.message_fields(
error.value.message,
msg_key=error.value.msg_key,
@@ -221,6 +225,7 @@ async def test_generation_failure_keeps_internal_paths_out_of_messages(locale: s
def test_generator_rejects_conflicting_sources_and_invalid_locale_options(options: dict[str, Any]) -> None:
"""生成器拒绝冲突的数据源和无效语言选项。"""
table = make_table('mysql', 'crud', 'element-ui')
+ assert table.options
table.options = json.dumps({**json.loads(table.options), **options})
with pytest.raises(ServiceWarning):
TemplateUtils.prepare_context(table)
@@ -229,7 +234,7 @@ def test_generator_rejects_conflicting_sources_and_invalid_locale_options(option
def test_generator_parameter_model_keeps_explicit_language_options() -> None:
"""生成参数模型保留显式语言选项。"""
value = GenTableParamsModel(
- i18nSourceLocale='zh-CN', i18nLocales=['en-US', 'fr-FR'], i18nTranslations={'fr-FR': {'title': 'Titre'}}
+ i18n_source_locale='zh-CN', i18n_locales=['en-US', 'fr-FR'], i18n_translations={'fr-FR': {'title': 'Titre'}}
).model_dump(by_alias=True, exclude_unset=True)
assert value['i18nSourceLocale'] == 'zh-CN'
assert value['i18nLocales'] == ['en-US', 'fr-FR']
@@ -241,6 +246,7 @@ def test_field_keys_are_stable_when_comments_change() -> None:
table = make_table('mysql', 'crud', 'element-ui')
first, first_files = render_files(table)
table.function_name = '另一个显示名称'
+ assert table.columns
table.columns[1].column_comment = '另一个字段名'
second, second_files = render_files(table)
path = 'frontend/src/i18n/locales/zh-CN/generated.test.item.json'
@@ -259,7 +265,8 @@ async def test_preview_zip_and_disk_include_resources_without_overwriting_transl
'_GenTableService__get_gen_render_info',
new=AsyncMock(side_effect=lambda *_: render_info(table)),
):
- await GenTableService.generate_code_services(object(), table.table_name)
+ assert table.table_name is not None
+ await GenTableService.generate_code_services(AsyncMock(spec=AsyncSession), table.table_name)
path = tmp_path / 'frontend/src/i18n/locales/en-US/generated.test.item.json'
english = json.loads(path.read_text(encoding='utf-8'))
english['fields']['itemName']['label'] = 'Handwritten name'
@@ -273,8 +280,9 @@ async def test_preview_zip_and_disk_include_resources_without_overwriting_transl
),
encoding='utf-8',
)
+ assert table.columns
table.columns.append(column('new_label', 'varchar(64)', 'str'))
- await GenTableService.generate_code_services(object(), table.table_name)
+ await GenTableService.generate_code_services(AsyncMock(spec=AsyncSession), table.table_name)
english = json.loads(path.read_text(encoding='utf-8'))
assert english['fields']['itemName']['label'] == 'Handwritten name'
assert english['custom']['kept'] == 'Manual text'
@@ -291,7 +299,7 @@ async def test_preview_zip_and_disk_include_resources_without_overwriting_transl
'module_generator.service.gen_service.GenTableDao.get_gen_table_names',
new=AsyncMock(return_value={table.table_name}),
):
- content = await GenTableService.batch_gen_code_services(object(), [table.table_name])
+ content = await GenTableService.batch_gen_code_services(AsyncMock(spec=AsyncSession), [table.table_name])
with zipfile.ZipFile(io.BytesIO(content)) as archive:
assert 'frontend/src/views/test/item/index.vue' in archive.namelist()
assert 'frontend/src/i18n/locales/zh-CN/generated.test.item.json' in archive.namelist()
@@ -308,7 +316,7 @@ async def test_preview_zip_and_disk_include_resources_without_overwriting_transl
patch.object(GenTableService, 'set_pk_column', new=AsyncMock()),
patch('module_generator.service.gen_service.TemplateUtils.prepare_context', return_value=info[2]),
):
- preview = await GenTableService.preview_code_services(object(), 1)
+ preview = await GenTableService.preview_code_services(AsyncMock(spec=AsyncSession), 1)
assert 'vue/index.vue.jinja2' in preview
assert 'frontend/src/i18n/locales/zh-CN/generated.test.item.json' in preview
assert 'backend/i18n/catalogs/zh-CN/LC_MESSAGES/core/generated.test.item.po' in preview
@@ -340,7 +348,8 @@ async def test_invalid_existing_catalog_stops_before_overwriting_generated_sourc
),
pytest.raises(ServiceWarning) as caught,
):
- await GenTableService.generate_code_services(object(), table.table_name)
+ assert table.table_name is not None
+ await GenTableService.generate_code_services(AsyncMock(spec=AsyncSession), table.table_name)
assert caught.value.msg_key == 'generator.i18nCatalogInvalid'
assert source.read_text(encoding='utf-8') == 'Keep the existing source'
assert catalog.read_text(encoding='utf-8') == invalid
@@ -374,6 +383,7 @@ async def test_batch_generation_writes_one_backend_catalog_per_business_module()
second.table_name = 'second_table'
second.business_name = 'second'
second.class_name = 'Second'
+ assert first.table_name is not None
tables = {first.table_name: first, second.table_name: second}
with (
patch.object(
@@ -386,7 +396,7 @@ async def test_batch_generation_writes_one_backend_catalog_per_business_module()
new=AsyncMock(return_value=set(tables)),
),
):
- content = await GenTableService.batch_gen_code_services(object(), list(tables))
+ content = await GenTableService.batch_gen_code_services(AsyncMock(spec=AsyncSession), list(tables))
with zipfile.ZipFile(io.BytesIO(content)) as archive:
assert len(archive.namelist()) == len(set(archive.namelist()))
for locale in ('zh-CN', 'en-US'):
@@ -395,7 +405,11 @@ async def test_batch_generation_writes_one_backend_catalog_per_business_module()
path = f'backend/i18n/catalogs/{locale}/LC_MESSAGES/core/{namespace}.po'
catalog = read_po(io.BytesIO(archive.read(path)))
assert f'{namespace}.fields.itemName.label' in catalog
- assert all(message.id.startswith(f'{namespace}.') for message in catalog if message.id)
+ assert all(
+ isinstance(message.id, str) and message.id.startswith(f'{namespace}.')
+ for message in catalog
+ if message.id
+ )
def test_generated_output_does_not_write_directly_into_an_existing_application() -> None:
@@ -403,7 +417,7 @@ def test_generated_output_does_not_write_directly_into_an_existing_application()
table = make_table('mysql', 'crud', 'element-ui')
table.gen_path = str(GenI18nUtil.PROJECT_ROOT / 'ruoyi-fastapi-frontend/vue2/web/src')
with pytest.raises(ServiceWarning) as caught:
- GenTableService._GenTableService__get_output_root(table)
+ GenTableService._get_output_root(table)
assert caught.value.msg_key == 'generator.outputMustBeBundleRoot'
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py b/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
index f98e36f6a..612f4f8cc 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
@@ -36,18 +36,18 @@ def column(
:return: 测试使用的 ``GenTableColumnModel`` 实例
"""
return GenTableColumnModel(
- columnName=name,
- columnComment=name,
- columnType=sql_type,
- pythonType=python_type,
- pythonField=TemplateUtils.to_camel_case(name),
- isPk='1' if pk else '0',
- isInsert='1',
- isEdit='0' if pk else '1',
- isList='1',
- isQuery='0' if pk else '1',
- queryType=query_type,
- htmlType='time' if python_type == 'time' else 'datetime' if python_type in {'date', 'datetime'} else 'input',
+ column_name=name,
+ column_comment=name,
+ column_type=sql_type,
+ python_type=python_type,
+ python_field=TemplateUtils.to_camel_case(name),
+ is_pk='1' if pk else '0',
+ is_insert='1',
+ is_edit='0' if pk else '1',
+ is_list='1',
+ is_query='0' if pk else '1',
+ query_type=query_type,
+ html_type='time' if python_type == 'time' else 'datetime' if python_type in {'date', 'datetime'} else 'input',
)
@@ -79,22 +79,22 @@ def make_table(db_type: str, category: str, web_type: str) -> GenTableModel:
if category == 'tree':
columns.append(column('parent_id', 'bigint', 'int'))
table = GenTableModel(
- tableName='generated_time_item',
- tableComment='时间样例',
- className='TimeItem',
- tplCategory=category,
- tplWebType=web_type,
- packageName='module_generated_time',
- moduleName='test',
- businessName='item',
- functionName='时间样例',
- functionAuthor='test',
- formColNum=2,
+ table_name='generated_time_item',
+ table_comment='时间样例',
+ class_name='TimeItem',
+ tpl_category=category,
+ tpl_web_type=web_type,
+ package_name='module_generated_time',
+ module_name='test',
+ business_name='item',
+ function_name='时间样例',
+ function_author='test',
+ form_col_num=2,
options=json.dumps(
{'genView': True, 'treeCode': 'item_id', 'treeParentCode': 'parent_id', 'treeName': 'item_name'}
),
columns=columns,
- pkColumn=columns[0],
+ pk_column=columns[0],
)
if category == 'sub':
children = [
@@ -107,13 +107,13 @@ def make_table(db_type: str, category: str, web_type: str) -> GenTableModel:
# 子表外键刻意使用不同于主表主键的名称,验证生成关联字段的映射。
table.sub_table_fk_name = 'parent_item_id'
table.sub_table = GenTableModel(
- tableName=table.sub_table_name,
- tableComment='子表',
- className='TimeDetail',
- businessName='detail',
- functionName='子表',
+ table_name=table.sub_table_name,
+ table_comment='子表',
+ class_name='TimeDetail',
+ business_name='detail',
+ function_name='子表',
columns=children,
- pkColumn=children[0],
+ pk_column=children[0],
)
return table
@@ -131,8 +131,10 @@ def render_case(db_type: str, category: str, web_type: str, *, field_constraints
with patch.object(type(database.DataBaseConfig), 'get_source', return_value=SimpleNamespace(db_type=db_type)):
table = make_table(db_type, category, web_type)
if field_constraints:
+ assert table.columns
table.columns[1].unique = table.columns[1].required = True
if table.sub_table:
+ assert table.sub_table.columns
table.sub_table.columns[1].required = True
context = TemplateUtils.prepare_context(table)
environment = TemplateInitializer.init_jinja2()
@@ -220,6 +222,7 @@ class TestBase(DeclarativeBase):
path = tmp_path / f'item_{kind}.py'
path.write_text(rendered[f'python/{kind}.py.jinja2'], encoding='utf-8')
spec = importlib.util.spec_from_file_location(name, path)
+ assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
monkeypatch.setitem(sys.modules, name, module)
spec.loader.exec_module(module)
@@ -230,6 +233,8 @@ class TestBase(DeclarativeBase):
def test_generated_models_publish_column_metadata(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""验证主表和子表的列说明能传递到数据库元数据与接口模式。"""
table = make_table('mysql', 'sub', 'element-plus')
+ assert table.pk_column is not None and table.columns
+ assert table.sub_table is not None and table.sub_table.columns
table.pk_column.column_comment = None
label = """客户的 "VIP" 生日和 O'Brien 备注"""
table.columns[2].column_comment = label
@@ -276,10 +281,10 @@ async def test_generated_import_crud_and_query(
await dao.ItemDao.add_detail_dao(
session,
vo.DetailModel(
- detailId=10,
- parentItemId=1,
+ detail_id=10,
+ parent_item_id=1,
birthday='2000-02-29',
- occurredAt='2026-11-01T01:30:00.456-05:00',
+ occurred_at='2026-11-01T01:30:00.456-05:00',
),
)
await session.commit()
@@ -300,23 +305,23 @@ async def test_generated_import_crud_and_query(
assert len(rows) == 1
assert rows[0]['itemName'] == 'changed'
empty = await dao.ItemDao.get_item_list(
- session, vo.ItemPageQueryModel(endBirthday='2000-02-28'), is_page=False
+ session, vo.ItemPageQueryModel(end_birthday='2000-02-28'), is_page=False
)
assert empty == []
if category == 'sub':
await dao.ItemDao.edit_detail_dao(session, {'detail_id': 10, 'occurred_at': None})
- await dao.ItemDao.delete_detail_dao(session, vo.DetailModel(detailId=10))
- await dao.ItemDao.delete_item_dao(session, vo.ItemModel(itemId=1))
+ await dao.ItemDao.delete_detail_dao(session, vo.DetailModel(detail_id=10))
+ await dao.ItemDao.delete_item_dao(session, vo.ItemModel(item_id=1))
await session.commit()
assert await dao.ItemDao.get_item_detail_by_id(session, 1) is None
with pytest.raises(ValidationError):
vo.ItemModel(birthday='2000-02-30')
with pytest.raises(ValidationError):
- vo.ItemModel(openingTime='25:00:00')
+ vo.ItemModel(opening_time='25:00:00')
with pytest.raises(ValidationError):
- vo.ItemPageQueryModel(beginBirthday='2000-03-01', endBirthday='2000-02-29')
+ vo.ItemPageQueryModel(begin_birthday='2000-03-01', end_birthday='2000-02-29')
with pytest.raises(ValidationError):
- (vo.DetailModel if category == 'sub' else vo.ItemModel)(occurredAt='2026-03-08 02:30:00')
+ (vo.DetailModel if category == 'sub' else vo.ItemModel)(occurred_at='2026-03-08 02:30:00')
finally:
await engine.dispose()
@@ -325,18 +330,22 @@ async def test_generated_import_crud_and_query(
def test_rejects_postgres_ambiguous_timestamp(column_type: str) -> None:
"""拒绝 PostgreSQL 有歧义的时间戳。"""
table = make_table('postgresql', 'crud', 'element-plus')
+ assert table.columns
table.columns[4].column_type = column_type
with patch.object(type(database.DataBaseConfig), 'get_source', return_value=SimpleNamespace(db_type='postgresql')):
with pytest.raises(ServiceWarning) as error:
TemplateUtils.prepare_context(table)
+ assert error.value.message is not None
assert 'TIMESTAMP(3) WITH TIME ZONE' in error.value.message
def test_mysql_time_requires_explicit_time_of_day_control() -> None:
"""MySQL 时间字段需要明确的时刻控件。"""
table = make_table('mysql', 'crud', 'element-plus')
+ assert table.columns
table.columns[3].html_type = 'datetime'
with patch.object(type(database.DataBaseConfig), 'get_source', return_value=SimpleNamespace(db_type='mysql')):
with pytest.raises(ServiceWarning) as error:
TemplateUtils.prepare_context(table)
+ assert error.value.message is not None
assert 'MySQL TIME' in error.value.message
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_react_templates.py b/ruoyi-fastapi-backend/tests/module_generator/test_react_templates.py
index 785130829..0dda4363c 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_react_templates.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_react_templates.py
@@ -61,14 +61,16 @@ def test_react_preview_preserves_unicode_and_safe_string_literals(category: str,
"""React 预览保留 Unicode 并安全生成字符串字面量。"""
table = make_table('mysql', category, 'react-antd')
label = '中文名称「测试」😀 "引号" \\路径 <标签> & 单引号\''
+ assert table.columns
table.columns[1].column_comment = label
if table.sub_table:
+ assert table.sub_table.columns
table.sub_table.columns[2].column_comment = '子表日期'
context = TemplateUtils.prepare_context(table)
environment = TemplateInitializer.init_jinja2()
templates = TemplateUtils.get_template_list(table)
filenames = [TemplateUtils.get_file_name(name, table) for name in templates]
- files = GenTableService._GenTableService__render_files(environment, [templates, filenames, context, table])
+ files = GenTableService._render_files(environment, [templates, filenames, context, table])
namespace = context['i18nNamespace']
resource = files[f'frontend/src/i18n/locales/zh-CN/{namespace}.json']
assert '中文名称「测试」😀' in resource
@@ -84,6 +86,7 @@ def test_react_preview_preserves_unicode_and_safe_string_literals(category: str,
assert f"t('{label_key}')" in rendered
assert '<标签>' not in rendered
if category == 'sub' and not name.endswith('/view.jsx'):
+ assert table.sub_table is not None and table.sub_table.columns
child = table.sub_table.columns[2]
child_key = f'{namespace}:subfields.{table.sub_table.business_name}.{child.python_field}.label'
assert f"t('{child_key}')" in rendered
diff --git a/ruoyi-fastapi-backend/tests/module_identity/architecture/test_architecture_boundaries.py b/ruoyi-fastapi-backend/tests/module_identity/architecture/test_architecture_boundaries.py
index 524738063..a774c2972 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/architecture/test_architecture_boundaries.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/architecture/test_architecture_boundaries.py
@@ -150,7 +150,11 @@ def _block_docstring(path: Path, node: ast.FunctionDef | ast.AsyncFunctionDef) -
if not node.body or not isinstance(node.body[0], ast.Expr):
return False
expression = node.body[0].value
- if not isinstance(expression, ast.Constant) or not isinstance(expression.value, str):
+ if (
+ not isinstance(expression, ast.Constant)
+ or not isinstance(expression.value, str)
+ or expression.end_lineno is None
+ ):
return False
lines = path.read_text(encoding='utf-8').splitlines()
opening_index = expression.lineno - 1
diff --git a/ruoyi-fastapi-backend/tests/module_identity/conftest.py b/ruoyi-fastapi-backend/tests/module_identity/conftest.py
index 76f73928d..b85d6873c 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/conftest.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/conftest.py
@@ -1,5 +1,6 @@
import json
import os
+from collections.abc import AsyncIterator
from unittest.mock import AsyncMock
os.environ.setdefault(
@@ -54,7 +55,7 @@ def _compile_mysql_tinyint_for_sqlite(_type: TINYINT, _compiler: object, **_kwar
@pytest_asyncio.fixture
-async def data_session() -> AsyncSession:
+async def data_session() -> AsyncIterator[AsyncSession]:
"""
创建只包含认证模块表的独立内存 SQLite 异步会话。
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/conftest.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/conftest.py
index b312423fa..8941e3f5d 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/conftest.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/conftest.py
@@ -43,6 +43,8 @@ def create_client(router: APIRouter, session: object, current_user: object) -> A
if not isinstance(route, APIRoute):
continue
for dependency in route.dependant.dependencies:
+ if dependency.call is None:
+ continue
if dependency.name == 'query_db':
app.dependency_overrides[dependency.call] = lambda: session
elif dependency.name == 'current_user':
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_authorization_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_authorization_controller.py
index 8baa83141..263fbe39a 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_authorization_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_authorization_controller.py
@@ -5,6 +5,7 @@
from typing import Any
import pytest
+from fastapi import Request
from sqlalchemy import select
from common.constant import OidcAuditEvent
@@ -19,7 +20,9 @@
from module_identity.service.authorization_service import AuthorizationService
from module_identity.service.interaction_service import InteractionService
from tests.module_identity.services.test_authorization_service import _seed_authorization_data
+from tests.module_identity.support.http import make_request
from tests.module_identity.support.redis_fakes import FakeRedis
+from tests.module_identity.support.sessions import RecordingSession
_REDIRECT_URI = 'https://portal.example/callback?tenant=one'
_CHALLENGE = 'A' * 43
@@ -29,55 +32,15 @@
_HTTP_TOO_MANY_REQUESTS = 429
-class _QueryParams:
+def _request(values: list[tuple[str, str]], redis: FakeRedis | None = None) -> Request:
"""
- 提供 Starlette QueryParams 所需的多值读取接口。
+ 构造授权端点接收的查询请求。
- :ivar values: 当前处理的值集合
+ :param values: 请求的查询参数
+ :param redis: 授权流程使用的测试缓存
+ :return: 带有客户端地址和缓存依赖的请求
"""
-
- def __init__(self, values: list[tuple[str, str]]) -> None:
- """
- 初始化测试夹具的 ``values``。
-
- :param values: 当前处理的值集合
- """
- self.values = values
-
- def multi_items(self) -> list[tuple[str, str]]:
- """
- 向调用方返回 ``self.values``。
-
- :return: 测试缓存当前保存的值
- """
- return self.values
-
-
-class _Request:
- """
- 构造不携带 Legacy 会话的认证请求。
-
- :ivar method: 当前请求的 HTTP 方法
- :ivar query_params: 模拟 HTTP 请求中的查询参数
- :ivar cookies: 模拟请求或响应携带的 Cookie
- :ivar headers: 响应或请求携带的 HTTP 头
- :ivar client: 发起当前调用的客户端
- :ivar app: 正在配置或处理请求的 ASGI 应用
- """
-
- def __init__(self, values: list[tuple[str, str]], redis: FakeRedis | None = None) -> None:
- """
- 初始化测试夹具的 ``method``, ``query_params``, ``cookies``, ``headers``。
-
- :param values: 当前处理的值集合
- :param redis: 用于缓存或发布消息的 Redis 客户端
- """
- self.method = 'GET'
- self.query_params = _QueryParams(values)
- self.cookies: dict[str, str] = {}
- self.headers: dict[str, str] = {}
- self.client = SimpleNamespace(host='198.51.100.10')
- self.app = SimpleNamespace(state=SimpleNamespace(redis=redis or FakeRedis()))
+ return make_request((redis or FakeRedis()).client, query=values, host='198.51.100.10')
class _RateRedis(FakeRedis):
@@ -143,7 +106,7 @@ def oidc_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
async def test_authorize_creates_real_interaction_with_fragment_csrf(data_session: Any) -> None:
"""有效请求真实执行校验和 Interaction 创建,CSRF 只进入 Fragment。"""
await _seed_authorization_data(data_session)
- response = await authorize(_Request(_values()), data_session)
+ response = await authorize(_request(_values()), data_session)
assert response.status_code == _HTTP_SEE_OTHER
location = response.headers['location']
assert 'interaction=' in location
@@ -158,15 +121,15 @@ async def test_authorize_invalid_redirect_is_local_and_plain_pkce_is_redirectabl
"""未注册 Redirect 不得跳转;精确注册后 plain PKCE 才允许协议错误回跳。"""
await _seed_authorization_data(data_session)
with pytest.raises(OAuthProtocolException) as local:
- await authorize(_Request(_values(redirect_uri='https://evil.example/callback')), data_session)
+ await authorize(_request(_values(redirect_uri='https://evil.example/callback')), data_session)
assert local.value.can_redirect is False
with pytest.raises(OAuthProtocolException) as redirectable:
- await authorize(_Request(_values(code_challenge_method='plain')), data_session)
+ await authorize(_request(_values(code_challenge_method='plain')), data_session)
assert redirectable.value.error == 'invalid_request'
assert redirectable.value.can_redirect is True
with pytest.raises(OAuthProtocolException) as unsupported:
- await authorize(_Request(_values(response_type='token')), data_session)
+ await authorize(_request(_values(response_type='token')), data_session)
assert unsupported.value.error == 'unsupported_response_type'
assert unsupported.value.can_redirect is True
@@ -195,7 +158,7 @@ async def load_stale(*args: object, **kwargs: object) -> Any:
return stale
monkeypatch.setattr(AuthorizationService, '_load_sso_session', load_stale)
- response = await authorize(_Request(_values(max_age='1')), data_session)
+ response = await authorize(_request(_values(max_age='1')), data_session)
assert response.status_code == _HTTP_SEE_OTHER
assert '/auth-center/login' in response.headers['location']
@@ -205,11 +168,10 @@ async def load_stale(*args: object, **kwargs: object) -> Any:
async def test_authorize_ip_limit_is_atomic_and_hashes_ip(monkeypatch: pytest.MonkeyPatch) -> None:
"""授权固定窗口并发计数只使用 HMAC-IP Redis Key。"""
redis = _RateRedis()
- request = _Request(_values(), redis)
- request.client = SimpleNamespace(host='198.51.100.10')
- await asyncio.gather(*(controller._enforce_authorization_rate_limit(request, redis) for _ in range(30)))
+ request = _request(_values(), redis)
+ await asyncio.gather(*(controller._enforce_authorization_rate_limit(request, redis.client) for _ in range(30)))
with pytest.raises(OAuthProtocolException) as limited:
- await controller._enforce_authorization_rate_limit(request, redis)
+ await controller._enforce_authorization_rate_limit(request, redis.client)
assert limited.value.status_code == _HTTP_TOO_MANY_REQUESTS
assert limited.value.redirect_uri is None
assert all('198.51.100.10' not in key for key in redis.values)
@@ -221,7 +183,7 @@ async def test_authorize_ip_limit_is_atomic_and_hashes_ip(monkeypatch: pytest.Mo
async def test_authorize_audit_events_are_structured_and_secret_free(data_session: Any) -> None:
"""授权成功事件落库且不携带协议秘密。"""
await _seed_authorization_data(data_session)
- await authorize(_Request(_values()), data_session)
+ await authorize(_request(_values()), data_session)
rows = (
(
await data_session.execute(
@@ -247,7 +209,7 @@ async def test_authorize_prompt_none_without_sso_returns_login_required_without_
await _seed_authorization_data(data_session)
redis = FakeRedis()
with pytest.raises(OAuthProtocolException) as raised:
- await authorize(_Request(_values(prompt='none'), redis), data_session)
+ await authorize(_request(_values(prompt='none'), redis), data_session)
assert raised.value.error == 'login_required'
assert raised.value.can_redirect is True
assert not any(key.startswith('oidc:interaction:') for key in redis.values)
@@ -257,7 +219,7 @@ async def test_authorize_prompt_none_without_sso_returns_login_required_without_
async def test_authorize_disabled_is_local_404(data_session: Any, monkeypatch: pytest.MonkeyPatch) -> None:
"""OIDC 关闭时授权入口返回本地 404。"""
monkeypatch.setattr(OidcConfig, 'oidc_enabled', False)
- response = await authorize(_Request(_values()), data_session)
+ response = await authorize(_request(_values()), data_session)
assert response.status_code == _HTTP_NOT_FOUND
assert response.headers['cache-control'] == 'no-store'
@@ -301,34 +263,12 @@ async def test_complete_code_audit_failure_cleans_code_and_marker(monkeypatch: p
monkeypatch.setattr(AuthorizationService, 'active_session', lambda *_args, **_kwargs: _async(session))
monkeypatch.setattr(AuditService, 'record', lambda *_args, **_kwargs: _raise_async(RuntimeError('audit')))
with pytest.raises(OAuthProtocolException) as raised:
- await AuthorizationService._complete_authorization(_Db(), redis, interaction_id)
+ await AuthorizationService._complete_authorization(RecordingSession(), redis, interaction_id)
assert raised.value.error == 'server_error'
assert await redis.get(marker) is None
assert not any(key.startswith('oidc:authorization_code:') for key in redis.values)
-class _Db:
- """
- 记录授权完成测试的事务动作。
-
- :ivar commits: 测试中记录的提交次数
- :ivar rollbacks: 测试中记录的回滚次数
- """
-
- def __init__(self) -> None:
- """初始化测试夹具的 ``commits``, ``rollbacks``。"""
- self.commits = 0
- self.rollbacks = 0
-
- async def commit(self) -> None:
- """累加 ``commits`` 供后续断言检查。"""
- self.commits += 1
-
- async def rollback(self) -> None:
- """累加 ``rollbacks`` 供后续断言检查。"""
- self.rollbacks += 1
-
-
async def _async(value: object) -> Any:
"""
构造异步测试结果。
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_client_ip_resolution.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_client_ip_resolution.py
index c9a656140..14d8de548 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_client_ip_resolution.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_client_ip_resolution.py
@@ -6,6 +6,7 @@
import pytest
from fastapi import Request, status
+from sqlalchemy.ext.asyncio import AsyncSession
from config.env import AppConfig, OidcConfig
from exceptions.exception import OAuthProtocolException
@@ -101,6 +102,7 @@ def client_request(
"""
peer, hops, headers, expected = request.param
monkeypatch.setattr(AppConfig, 'app_trusted_proxy_hops', hops)
+ assert isinstance(expected, str)
return _request(peer, headers), expected
@@ -114,9 +116,9 @@ async def test_login_passes_resolved_ip_to_credentials_and_session_flow(
login = AsyncMock(return_value=InteractionLoginOutcome(failure_message='认证信息无效'))
monkeypatch.setattr(InteractionLoginService, 'login', login)
- await login_endpoint(request, 'interaction-1', object(), 'csrf')
+ await login_endpoint(request, 'interaction-1', AsyncSession(), 'csrf')
- assert login.await_args.args[5] == expected
+ assert login.await_args_list[-1].args[5] == expected
@pytest.mark.asyncio
@@ -145,7 +147,7 @@ async def test_authorize_rate_limit_hashes_the_resolved_client_ip(
await _enforce_authorization_rate_limit(request, request.app.state.redis)
digest = hmac.new(_PEPPER.encode(), expected.encode(), hashlib.sha256).hexdigest()
- assert enforce.await_args.args[1] == OidcRedisKey.authorize_ip_rate_limit(digest)
+ assert enforce.await_args_list[-1].args[1] == OidcRedisKey.authorize_ip_rate_limit(digest)
@pytest.mark.asyncio
@@ -159,11 +161,11 @@ async def test_logout_rate_limit_hashes_the_resolved_client_ip(
monkeypatch.setattr(LogoutConfirmationService, 'issue', AsyncMock(return_value=('confirmation', 'nonce')))
monkeypatch.setattr(LogoutConfirmationService, 'form_redirect_origin', AsyncMock(return_value=None))
- response = await logout(request, object())
+ response = await logout(request, AsyncSession())
assert response.status_code == status.HTTP_200_OK
digest = hmac.new(_PEPPER.encode(), expected.encode(), hashlib.sha256).hexdigest()
- assert enforce.await_args.args[1] == OidcRedisKey.logout_rate_limit(digest)
+ assert enforce.await_args_list[-1].args[1] == OidcRedisKey.logout_rate_limit(digest)
@pytest.mark.asyncio
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_discovery_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_discovery_controller.py
index a5e0c4762..5e9b724e2 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_discovery_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_discovery_controller.py
@@ -1,9 +1,10 @@
-from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
from starlette.requests import Request
-from config.env import OidcConfig
+from config.env import OidcConfig, OidcSettings
from module_identity.controller import discovery_controller as controller
from module_identity.service.key_service import KeyServiceError
@@ -26,7 +27,7 @@ def _request(headers: dict[str, str] | None = None, host: str = 'evil.example')
return Request({'type': 'http', 'method': 'GET', 'path': '/', 'headers': raw_headers})
-def _enabled(monkeypatch: pytest.MonkeyPatch) -> OidcConfig:
+def _enabled(monkeypatch: pytest.MonkeyPatch) -> OidcSettings:
"""
将全局配置设为启用且固定 issuer。
@@ -39,60 +40,39 @@ def _enabled(monkeypatch: pytest.MonkeyPatch) -> OidcConfig:
return OidcConfig
-class _DiscoveryDb:
- """提供 Discovery 动态 Scope 查询的最小显式会话替身。"""
-
- class _Scalars:
- """提供数据库查询结果的标量访问接口。"""
-
- def all(self) -> list[str]:
- """
- 向测试用例返回空集合。
-
- :return: 不含记录的查询列表
- """
- return []
-
- class _Result:
- """模拟数据库查询结果。"""
-
- def scalars(self) -> '_DiscoveryDb._Scalars':
- """
- 提供 SQLAlchemy 标量查询结果的测试替身。
-
- :return: SQLAlchemy 标量查询结果的测试替身
- """
- return _DiscoveryDb._Scalars()
-
- async def execute(self, statement: object) -> '_DiscoveryDb._Result':
- """
- 按测试场景处理数据库查询并提供结果。
+def _discovery_db(scopes: list[str] | None = None) -> AsyncMock:
+ """
+ 模拟查询启用的资源范围。
- :param statement: 即将执行的数据库语句
- :return: 包含模拟发现数据的查询结果
- """
- return _DiscoveryDb._Result()
+ :param scopes: 查询返回的范围名称
+ :return: 提供标量查询结果的异步会话
+ """
+ session = AsyncMock(spec=AsyncSession)
+ result = Mock()
+ result.scalars.return_value.all.return_value = scopes or []
+ session.execute.return_value = result
+ return session
@pytest.mark.asyncio
async def test_discovery_is_raw_static_and_supports_304(monkeypatch: pytest.MonkeyPatch) -> None:
"""发现响应使用静态 issuer、裸 JSON 和 ETag 304。"""
_enabled(monkeypatch)
- response = await controller.openid_configuration(_request(host='attacker.example'), _DiscoveryDb())
+ response = await controller.openid_configuration(_request(host='attacker.example'), _discovery_db())
assert response.status_code == _HTTP_OK
assert response.media_type == 'application/json'
assert response.headers['cache-control'] == 'public, max-age=300'
assert b'attacker.example' not in response.body
not_modified = await controller.openid_configuration(
- _request({'If-None-Match': response.headers['etag']}), _DiscoveryDb()
+ _request({'If-None-Match': response.headers['etag']}), _discovery_db()
)
assert not_modified.status_code == _HTTP_NOT_MODIFIED
assert not not_modified.body
listed = await controller.openid_configuration(
- _request({'If-None-Match': '"other", ' + response.headers['etag']}), _DiscoveryDb()
+ _request({'If-None-Match': '"other", ' + response.headers['etag']}), _discovery_db()
)
assert listed.status_code == _HTTP_NOT_MODIFIED
- wildcard = await controller.openid_configuration(_request({'If-None-Match': '*'}), _DiscoveryDb())
+ wildcard = await controller.openid_configuration(_request({'If-None-Match': '*'}), _discovery_db())
assert wildcard.status_code == _HTTP_NOT_MODIFIED
@@ -100,7 +80,7 @@ async def test_discovery_is_raw_static_and_supports_304(monkeypatch: pytest.Monk
async def test_oauth_metadata_does_not_claim_oidc_only_fields(monkeypatch: pytest.MonkeyPatch) -> None:
"""RFC 8414 子集不要求 userinfo/end_session 等 OIDC 专属字段。"""
_enabled(monkeypatch)
- response = await controller.oauth_authorization_server_metadata(_request(), _DiscoveryDb())
+ response = await controller.oauth_authorization_server_metadata(_request(), _discovery_db())
assert response.status_code == _HTTP_OK
assert b'userinfo_endpoint' not in response.body
assert b'end_session_endpoint' not in response.body
@@ -113,7 +93,7 @@ async def test_oidc_metadata_declares_implemented_machine_and_backchannel_flows(
) -> None:
"""OIDC Discovery 声明当前已实现的机器授权和 Back-Channel 能力。"""
_enabled(monkeypatch)
- response = await controller.openid_configuration(_request(), _DiscoveryDb())
+ response = await controller.openid_configuration(_request(), _discovery_db())
assert response.status_code == _HTTP_OK
assert b'client_credentials' in response.body
assert b'backchannel_logout_supported' in response.body
@@ -125,41 +105,7 @@ async def test_discovery_publishes_only_active_database_scopes(monkeypatch: pyte
"""Discovery 应发布启用的 Resource Scope,并在停用后通过 ETag 变化。"""
_enabled(monkeypatch)
- class _Scalars:
- """提供数据库查询结果的标量访问接口。"""
-
- def all(self) -> list[str]:
- """
- 返回本次查询的全部测试行。
-
- :return: 本次查询的全部测试行
- """
- return ['openid', 'orders.read', 'zzz.read']
-
- class _Result:
- """模拟数据库查询结果。"""
-
- def scalars(self) -> _Scalars:
- """
- 提供 SQLAlchemy 标量查询结果的测试替身。
-
- :return: SQLAlchemy 标量查询结果的测试替身
- """
- return _Scalars()
-
- class _Db:
- """模拟当前测试所需的数据库操作。"""
-
- async def execute(self, statement: object) -> _Result:
- """
- 按测试场景处理数据库查询并提供结果。
-
- :param statement: 即将执行的数据库语句
- :return: 包含预设记录的查询结果
- """
- return _Result()
-
- response = await controller.openid_configuration(_request(), _Db())
+ response = await controller.openid_configuration(_request(), _discovery_db(['openid', 'orders.read', 'zzz.read']))
assert response.status_code == _HTTP_OK
assert b'orders.read' in response.body
assert response.headers['etag']
@@ -170,19 +116,10 @@ async def test_discovery_scope_query_failure_is_no_store_503(monkeypatch: pytest
"""动态 Scope 查询失败时不得发布静态或不完整元数据。"""
_enabled(monkeypatch)
- class _FailingDb:
- """模拟数据库操作失败时的会话。"""
-
- async def execute(self, statement: object) -> object:
- """
- 模拟此操作抛出 RuntimeError 的情形。
-
- :param statement: 即将执行的数据库语句
- :raises RuntimeError: 模拟数据库查询不可用
- """
- raise RuntimeError('database unavailable')
+ db = _discovery_db()
+ db.execute.side_effect = RuntimeError('数据库查询失败')
- response = await controller.openid_configuration(_request(), _FailingDb())
+ response = await controller.openid_configuration(_request(), db)
assert response.status_code == _HTTP_UNAVAILABLE
assert response.headers['cache-control'] == 'no-store'
assert response.body == b'{"error":"temporarily_unavailable"}'
@@ -193,7 +130,7 @@ async def test_discovery_fails_closed_when_disabled(monkeypatch: pytest.MonkeyPa
"""OIDC 关闭时所有 Discovery 请求均拒绝。"""
monkeypatch.setattr(OidcConfig, 'oidc_enabled', False)
monkeypatch.setattr(controller, 'OidcConfig', OidcConfig)
- response = await controller.openid_configuration(_request(), SimpleNamespace())
+ response = await controller.openid_configuration(_request(), AsyncSession())
assert response.status_code == _HTTP_NOT_FOUND
assert response.headers['cache-control'] == 'no-store'
assert response.body == b'{"error":"not_found"}'
@@ -215,10 +152,10 @@ async def build(*args: object, **kwargs: object) -> dict[str, list[dict[str, str
return {'keys': [{'kty': 'RSA', 'use': 'sig', 'kid': 'k1', 'alg': 'RS256', 'n': 'n', 'e': 'AQAB'}]}
monkeypatch.setattr(controller.KeyService, 'build_jwks', build)
- response = await controller.jwks(_request(), SimpleNamespace())
+ response = await controller.jwks(_request(), AsyncSession())
assert response.status_code == _HTTP_OK
assert response.headers['cache-control'] == 'public, max-age=300'
- assert response.body.startswith(b'{"keys"')
+ assert bytes(response.body).startswith(b'{"keys"')
@pytest.mark.asyncio
@@ -237,7 +174,7 @@ async def build(*args: object, **kwargs: object) -> dict[str, list[dict[str, str
raise KeyServiceError('public JWK RSA numbers are invalid')
monkeypatch.setattr(controller.KeyService, 'build_jwks', build)
- response = await controller.jwks(_request(), SimpleNamespace())
+ response = await controller.jwks(_request(), AsyncSession())
assert response.status_code == _HTTP_UNAVAILABLE
assert response.headers['cache-control'] == 'no-store'
assert response.body == b'{"error":"temporarily_unavailable"}'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_interaction_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_interaction_controller.py
index 1b5ea0fa4..0fab897f3 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_interaction_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_interaction_controller.py
@@ -1,13 +1,14 @@
import json
-from dataclasses import dataclass
from datetime import UTC, datetime
from types import SimpleNamespace
from typing import Any
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
import pytest
-from fastapi import FastAPI
+from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
+from redis.asyncio import Redis
+from sqlalchemy.ext.asyncio import AsyncSession
from common.aspect.db_session import get_db_session_provider
from common.constant import OidcAuditEvent
@@ -15,6 +16,7 @@
from config.env import OidcConfig
from exceptions.exception import OAuthProtocolException, OidcInteractionException
from exceptions.handle import handle_exception
+from module_admin.entity.do.user_do import SysUser
from module_admin.service.user_service import UserService
from module_identity.controller.interaction_controller import (
_failure_response,
@@ -27,6 +29,7 @@
from module_identity.dao.oauth_client_dao import OAuthClientDao
from module_identity.dao.oauth_grant_dao import OAuthGrantDao, OAuthGrantSnapshot
from module_identity.dependencies import require_oidc_protocol_ready
+from module_identity.entity.do.oauth_grant_do import SysOAuthGrant
from module_identity.entity.vo.interaction_vo import (
CaptchaResponseModel,
ChangePasswordModel,
@@ -59,6 +62,7 @@
InteractionService,
)
from module_identity.service.session_service import SsoSessionDao, SsoSessionService
+from tests.module_identity.support.http import make_request
from tests.module_identity.support.redis_fakes import FakeRedis
from utils.oidc_util import OidcUtil
from utils.pwd_util import PwdUtil
@@ -74,53 +78,6 @@
_MIN_EXPECTED_COMMITS = 2
-class _Db:
- """
- 记录交互控制器事务边界。
-
- :ivar commits: 测试中记录的提交次数
- :ivar rollbacks: 测试中记录的回滚次数
- :ivar events: 保存已发出事件的序列
- """
-
- def __init__(self) -> None:
- """初始化测试夹具的 ``commits``, ``rollbacks``, ``events``。"""
- self.commits = 0
- self.rollbacks = 0
- self.events: list[object] = []
-
- def add(self, value: object) -> None:
- """
- 将测试对象加入待检查的操作记录。
-
- :param value: 待处理的输入值
- """
- self.events.append(value)
-
- async def flush(self) -> None:
- """完成无需返回值的回调。"""
- return
-
- async def commit(self) -> None:
- """累加 ``commits`` 供后续断言检查。"""
- self.commits += 1
-
- async def rollback(self) -> None:
- """累加 ``rollbacks`` 供后续断言检查。"""
- self.rollbacks += 1
-
-
-@dataclass
-class _User:
- """
- 登录成功所需的最小用户标量。
-
- :ivar user_id: 用户的唯一标识
- """
-
- user_id: int = 2
-
-
def _payload(status: str = 'awaiting_login', **overrides: object) -> dict[str, object]:
"""
构造 Interaction 内部白名单载荷。
@@ -153,7 +110,7 @@ def _payload(status: str = 'awaiting_login', **overrides: object) -> dict[str, o
return payload
-def _request(redis: FakeRedis, csrf: str | None = None) -> SimpleNamespace:
+def _request(redis: FakeRedis, csrf: str | None = None) -> Request:
"""
构造交互页面请求替身。
@@ -161,12 +118,7 @@ def _request(redis: FakeRedis, csrf: str | None = None) -> SimpleNamespace:
:param csrf: 请求中的 CSRF 校验值
:return: 交互页面请求替身
"""
- return SimpleNamespace(
- app=SimpleNamespace(state=SimpleNamespace(redis=redis)),
- headers={'x-csrf-token': csrf} if csrf else {},
- client=SimpleNamespace(host='127.0.0.1'),
- cookies={},
- )
+ return make_request(redis.client, headers={'x-csrf-token': csrf} if csrf else {})
def _context() -> AuthorizationContext:
@@ -211,9 +163,9 @@ def oidc_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
async def test_login_and_complete_real_interaction_lifecycle(monkeypatch: pytest.MonkeyPatch) -> None:
"""真实 Interaction Redis 状态机贯通 CSRF、登录、完成和授权码一次消费标记。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
result = CredentialAuthenticationResult(
- user=_User(),
+ user=SysUser(user_id=2),
dept=None,
acr='urn:ruoyi:acr:pwd',
amr=('pwd',),
@@ -268,11 +220,11 @@ async def create_sso(*args: object, **kwargs: object) -> tuple[str, Any]:
monkeypatch.setattr(CredentialAuthenticationService, 'authenticate_oidc', authenticate)
monkeypatch.setattr(IdentitySubjectService, 'require_by_user_id', require_subject)
monkeypatch.setattr(SsoSessionService, 'create', create_sso)
- db = _Db()
+ db = AsyncMock(spec=AsyncSession)
outcome = await InteractionLoginService.login(
- redis,
+ redis.client,
created.interaction_id,
- InteractionLoginModel(userName='alice', password='password'),
+ InteractionLoginModel(user_name='alice', password='password'),
db,
created.csrf_token,
'127.0.0.1',
@@ -280,7 +232,7 @@ async def create_sso(*args: object, **kwargs: object) -> tuple[str, Any]:
)
assert outcome.result is not None
assert outcome.cookie is not None
- assert (await InteractionService.get_record(redis, created.interaction_id))['status'] == 'completed'
+ assert (await InteractionService.get_record(redis.client, created.interaction_id))['status'] == 'completed'
assert 'ss1.sid-1.' in outcome.cookie
monkeypatch.setattr(
@@ -301,11 +253,11 @@ async def record_audit(*args: object, **kwargs: object) -> None:
audit_events.append(str(args[1]))
monkeypatch.setattr(AuditService, 'record', record_audit)
- completed = await InteractionCompletionService.complete(redis, created.interaction_id, db)
+ completed = await InteractionCompletionService.complete(redis.client, created.interaction_id, db)
assert 'code=ac1.' in completed.location
assert audit_events == [OidcAuditEvent.AUTHORIZE_SUCCEEDED]
with pytest.raises(OidcInteractionException):
- await InteractionCompletionService.complete(redis, created.interaction_id, db)
+ await InteractionCompletionService.complete(redis.client, created.interaction_id, db)
assert await redis.ttl(OidcRedisKey.interaction(f'{created.interaction_id}-completion')) > 0
@@ -316,9 +268,9 @@ async def test_forced_password_login_creates_no_sso_cookie_or_active_session(
) -> None:
"""强制改密登录只推进短时证明状态,不提前创建 SSO。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
result = CredentialAuthenticationResult(
- user=_User(),
+ user=SysUser(user_id=2),
dept=None,
acr='urn:ruoyi:acr:pwd',
amr=('pwd',),
@@ -362,15 +314,15 @@ async def forbidden_sso(*args: object, **kwargs: object) -> Any:
monkeypatch.setattr(IdentitySubjectService, 'require_by_user_id', require_subject)
monkeypatch.setattr(SsoSessionService, 'create', forbidden_sso)
outcome = await InteractionLoginService.login(
- redis,
+ redis.client,
created.interaction_id,
- InteractionLoginModel(userName='alice', password='password'),
- _Db(),
+ InteractionLoginModel(user_name='alice', password='password'),
+ AsyncMock(spec=AsyncSession),
created.csrf_token,
)
assert outcome.result is not None
assert outcome.cookie is None
- record = await InteractionService.get_record(redis, created.interaction_id)
+ record = await InteractionService.get_record(redis.client, created.interaction_id)
assert record['status'] == 'password_change_required'
assert record['authenticatedSid'] is None
assert isinstance(record['credentialProofHash'], str)
@@ -382,11 +334,11 @@ async def forbidden_sso(*args: object, **kwargs: object) -> Any:
async def test_get_interaction_requires_csrf_header() -> None:
"""Interaction 页面读取也必须使用原始 CSRF Header。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
with pytest.raises(OidcInteractionException):
- await get_interaction(_request(redis), created.interaction_id, _Db())
+ await get_interaction(_request(redis), created.interaction_id, AsyncMock(spec=AsyncSession))
response = await get_interaction(
- _request(redis, created.csrf_token), created.interaction_id, _Db(), created.csrf_token
+ _request(redis, created.csrf_token), created.interaction_id, AsyncMock(spec=AsyncSession), created.csrf_token
)
assert response.status_code == _HTTP_OK
@@ -398,22 +350,22 @@ async def test_get_interaction_requires_csrf_header() -> None:
async def test_get_interaction_captcha_enabled_reflects_system_config(stored_value: str, expected: bool) -> None:
"""Interaction 页面验证码开关必须来自系统配置,而不是固定默认值。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
config_key = f'{RedisInitKeyConfig.SYS_CONFIG.key}:sys.account.captchaEnabled'
await redis.set(config_key, stored_value)
response = await get_interaction(
- _request(redis, created.csrf_token), created.interaction_id, _Db(), created.csrf_token
+ _request(redis, created.csrf_token), created.interaction_id, AsyncMock(spec=AsyncSession), created.csrf_token
)
assert response.status_code == _HTTP_OK
- assert json.loads(response.body)['data']['captchaEnabled'] is expected
+ assert json.loads(bytes(response.body))['data']['captchaEnabled'] is expected
def test_interaction_error_responses_use_the_unified_response_util_envelope() -> None:
"""交互 HTTP 错误保留统一 code/msg/success/time 业务 envelope。"""
response = _failure_response('invalid interaction', _HTTP_BAD_REQUEST)
- payload = json.loads(response.body)
+ payload = json.loads(bytes(response.body))
assert response.status_code == _HTTP_BAD_REQUEST
assert payload['code'] is not None
@@ -429,7 +381,7 @@ async def test_captcha_endpoint_has_independent_oidc_limit_and_fail_closed(
) -> None:
"""验证码端点使用 Interaction/IP 摘要限流,Redis 故障不放行。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
monkeypatch.setattr(InteractionFlowService, 'captcha_enabled', lambda *_args: _async(False))
request = _request(redis)
for _ in range(5):
@@ -461,11 +413,11 @@ async def _raise_async(error: Exception) -> Any:
async def test_mutations_require_csrf_and_consent_cannot_expand_scope(monkeypatch: pytest.MonkeyPatch) -> None:
"""登录/同意变更必须有 CSRF,提交 Scope 不能超出原请求。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload('awaiting_consent'), pepper=_PEPPER)
- db = _Db()
+ created = await InteractionService.create(redis.client, _payload('awaiting_consent'), pepper=_PEPPER)
+ db = AsyncMock(spec=AsyncSession)
with pytest.raises(OidcInteractionException):
await InteractionConsentService.consent(
- redis,
+ redis.client,
created.interaction_id,
InteractionConsentModel(approved=True, scopes=['openid', 'profile']),
db,
@@ -479,14 +431,14 @@ async def test_mutations_require_csrf_and_consent_cannot_expand_scope(monkeypatc
monkeypatch.setattr(AuditService, 'record_independent', lambda *args, **kwargs: _async(None))
with pytest.raises(OAuthProtocolException) as expanded:
await InteractionConsentService.consent(
- redis,
+ redis.client,
created.interaction_id,
InteractionConsentModel(approved=True, scopes=['openid', 'profile', 'admin']),
db,
created.csrf_token,
)
assert expanded.value.error == 'invalid_scope'
- assert (await InteractionService.get_record(redis, created.interaction_id))['status'] == 'awaiting_consent'
+ assert (await InteractionService.get_record(redis.client, created.interaction_id))['status'] == 'awaiting_consent'
@pytest.mark.asyncio
@@ -494,19 +446,20 @@ async def test_mutations_require_csrf_and_consent_cannot_expand_scope(monkeypatc
async def test_cancel_is_csrf_protected_and_legacy_cookie_is_ignored() -> None:
"""取消操作使用 CAS,且交互控制器不读取 Legacy access_token Cookie。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
- request = _request(redis, created.csrf_token)
- request.cookies = {'access_token': 'legacy-token'}
- response = await cancel(request, created.interaction_id, _Db(), created.csrf_token)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
+ request = make_request(
+ redis.client, headers={'x-csrf-token': created.csrf_token, 'cookie': 'access_token=legacy-token'}
+ )
+ response = await cancel(request, created.interaction_id, AsyncMock(spec=AsyncSession), created.csrf_token)
assert response.status_code == _HTTP_OK
- assert (await InteractionService.get_record(redis, created.interaction_id))['status'] == 'denied'
+ assert (await InteractionService.get_record(redis.client, created.interaction_id))['status'] == 'denied'
@pytest.mark.asyncio
async def test_interaction_disabled_is_local_404(monkeypatch: pytest.MonkeyPatch) -> None:
"""OIDC 关闭时交互页面和写入口均返回本地 404。"""
monkeypatch.setattr(OidcConfig, 'oidc_enabled', False)
- response = await get_interaction(_request(FakeRedis()), 'interaction-id', _Db())
+ response = await get_interaction(_request(FakeRedis()), 'interaction-id', AsyncMock(spec=AsyncSession))
assert response.status_code == _HTTP_NOT_FOUND
assert response.headers['cache-control'] == 'no-store'
@@ -522,43 +475,22 @@ def test_consent_scope_dto_rejects_duplicate_and_oversized_values() -> None:
@pytest.mark.asyncio
async def test_body_parser_rejects_duplicate_unknown_and_oversized_json_without_echoing_password() -> None:
"""JSON 解析错误统一脱敏,且受 16KiB 总体大小限制。"""
-
- class BodyRequest:
- """
- 分块提供测试请求体。
-
- :ivar headers: 响应或请求携带的 HTTP 头
- :ivar value: 待处理的输入值
- """
-
- def __init__(self, value: bytes) -> None:
- """
- 初始化测试夹具的 ``headers``, ``value``。
-
- :param value: 待处理的输入值
- """
- self.headers = {'content-type': 'application/json'}
- self.value = value
-
- async def stream(self) -> Any:
- """
- 将请求数据分段异步输出。
-
- :yield: 按读取进度切分的请求体字节块
- """
- midpoint = len(self.value) // 2
- yield self.value[:midpoint]
- yield self.value[midpoint:]
- yield b''
-
cases = [
('duplicate', b'{"userName":"alice","password":"super-secret","password":"again"}'),
('unknown', json.dumps({'userName': 'alice', 'password': 'super-secret', 'unknown': True}).encode()),
('oversized', b'{' + b'"password":"' + b'x' * (16 * 1024) + b'"}'),
]
for reason, value in cases:
+ midpoint = len(value) // 2
+ receive = AsyncMock(
+ side_effect=[
+ {'type': 'http.request', 'body': value[:midpoint], 'more_body': True},
+ {'type': 'http.request', 'body': value[midpoint:], 'more_body': False},
+ ]
+ )
+ request = Request({'type': 'http', 'headers': [(b'content-type', b'application/json')]}, receive)
with pytest.raises(OidcInteractionException) as raised:
- await _safe_json_body(BodyRequest(value), InteractionLoginModel)
+ await _safe_json_body(request, InteractionLoginModel)
assert raised.value.error == 'invalid_request', reason
assert 'super-secret' not in str(raised.value)
@@ -576,7 +508,7 @@ async def db_override() -> Any:
:yield: 本次请求使用的模拟数据库会话
"""
- yield _Db()
+ yield AsyncMock(spec=AsyncSession)
app.dependency_overrides[get_db_session_provider(None)] = db_override
app.dependency_overrides[require_oidc_protocol_ready] = lambda: None
@@ -604,7 +536,7 @@ async def db_override() -> Any:
async def test_db_commit_then_redis_cas_failure_runs_compensation(monkeypatch: pytest.MonkeyPatch) -> None:
"""DB 已提交但 Redis CAS 失败时必须执行补偿且保留可重试状态。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
compensated = False
async def failed_transition(*args: object, **kwargs: object) -> object:
@@ -625,15 +557,15 @@ async def compensate() -> None:
monkeypatch.setattr(InteractionService, 'transition', failed_transition)
with pytest.raises(OidcInteractionException):
await InteractionFlowService.commit_transition(
- _Db(),
+ AsyncMock(spec=AsyncSession),
AfterCommitCoordinator(),
- redis,
+ redis.client,
created.interaction_id,
'completed',
compensate=compensate,
)
assert compensated is True
- assert (await InteractionService.get_record(redis, created.interaction_id))['status'] == 'awaiting_login'
+ assert (await InteractionService.get_record(redis.client, created.interaction_id))['status'] == 'awaiting_login'
@pytest.mark.asyncio
@@ -643,11 +575,11 @@ async def test_consent_commit_then_redis_cas_failure_compensates_persisted_grant
"""同意 Grant 已提交但 Interaction CAS 失败时必须持久化撤销补偿。"""
redis = FakeRedis()
created = await InteractionService.create(
- redis,
+ redis.client,
_payload('awaiting_consent', userId=2, subjectId='subject-2', authVersion=1),
pepper=_PEPPER,
)
- grant = SimpleNamespace(grant_id='grant-after-commit', user_id=2, subject_id='subject-2')
+ grant = SysOAuthGrant(grant_id='grant-after-commit', user_id=2, subject_id='subject-2')
persisted = OAuthGrantSnapshot(
grant_id=grant.grant_id,
user_id=grant.user_id,
@@ -669,7 +601,7 @@ async def test_consent_commit_then_redis_cas_failure_compensates_persisted_grant
grant=grant,
persisted_grant=persisted,
)
- db = _Db()
+ db = AsyncMock(spec=AsyncSession)
compensated = False
async def revoke(*_args: object, **_kwargs: object) -> bool:
@@ -705,14 +637,14 @@ async def cas_failure(*_args: object, **_kwargs: object) -> None:
await InteractionFlowService.commit_transition(
db,
AfterCommitCoordinator(),
- redis,
+ redis.client,
created.interaction_id,
'completed',
compensate=compensate,
)
assert compensated is True
- assert db.commits >= _MIN_EXPECTED_COMMITS
+ assert db.commit.await_count >= _MIN_EXPECTED_COMMITS
@pytest.mark.asyncio
@@ -730,8 +662,8 @@ async def test_password_change_cas_failure_runs_full_security_saga(monkeypatch:
),
)
redis = FakeRedis()
- created = await InteractionService.create(redis, payload, pepper=_PEPPER)
- stored = await InteractionService.get_record(redis, created.interaction_id)
+ created = await InteractionService.create(redis.client, payload, pepper=_PEPPER)
+ stored = await InteractionService.get_record(redis.client, created.interaction_id)
stored['status'] = 'password_change_required'
stored['credentialProofHash'] = OidcUtil.credential_proof(
created.interaction_id, 2, subject_id, 1, pepper=OidcConfig.oidc_token_hash_pepper
@@ -750,7 +682,7 @@ async def test_password_change_cas_failure_runs_full_security_saga(monkeypatch:
)
subject = SimpleNamespace(subject_id=subject_id, auth_version=2)
session = SimpleNamespace(sid='new-session', user_id=2, subject_id=subject_id, auth_version=2)
- db = _ScalarDb(user)
+ db = _scalar_session(user)
revoked: list[str] = []
audit_events: list[str] = []
@@ -802,10 +734,10 @@ async def cas_fail(*args: object, **kwargs: object) -> None:
monkeypatch.setattr(InteractionService, 'transition', cas_fail)
with pytest.raises(OidcInteractionException) as raised:
await InteractionLoginService.change_password(
- redis,
+ redis.client,
created.interaction_id,
ChangePasswordModel(
- oldPassword='old-password', newPassword='new-password-A1!', confirmPassword='new-password-A1!'
+ old_password='old-password', new_password='new-password-A1!', confirm_password='new-password-A1!'
),
db,
created.csrf_token,
@@ -814,7 +746,7 @@ async def cas_fail(*args: object, **kwargs: object) -> None:
assert await redis.get(OidcRedisKey.interaction(created.interaction_id)) is None
assert revoked == [session.sid]
assert audit_events == [OidcAuditEvent.LOGIN_FAILED]
- assert db.commits >= _MIN_EXPECTED_COMMITS
+ assert db.commit.await_count >= _MIN_EXPECTED_COMMITS
@pytest.mark.asyncio
@@ -825,8 +757,8 @@ async def test_password_change_saga_continues_when_interaction_delete_fails(
"""补偿删除 Interaction 失败时仍继续撤销 Session 和独立审计。"""
subject_id = '11111111-1111-4111-8111-111111111111'
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
- stored = await InteractionService.get_record(redis, created.interaction_id)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
+ stored = await InteractionService.get_record(redis.client, created.interaction_id)
stored.update(
{
'status': 'password_change_required',
@@ -847,7 +779,7 @@ async def test_password_change_saga_continues_when_interaction_delete_fails(
pwd_update_date=None,
)
session = SimpleNamespace(sid='new-session', user_id=2, subject_id=subject_id, auth_version=2)
- db = _ScalarDb(user)
+ db = _scalar_session(user)
revoked: list[str] = []
audits: list[str] = []
@@ -887,10 +819,10 @@ async def cas_fail(*_args: object, **_kwargs: object) -> None:
monkeypatch.setattr(InteractionService, 'transition', cas_fail)
with pytest.raises(OidcInteractionException):
await InteractionLoginService.change_password(
- redis,
+ redis.client,
created.interaction_id,
ChangePasswordModel(
- oldPassword='old-password', newPassword='new-password-A1!', confirmPassword='new-password-A1!'
+ old_password='old-password', new_password='new-password-A1!', confirm_password='new-password-A1!'
),
db,
created.csrf_token,
@@ -899,69 +831,26 @@ async def cas_fail(*_args: object, **_kwargs: object) -> None:
assert audits == [OidcAuditEvent.LOGIN_FAILED]
-class _ScalarDb(_Db):
+def _scalar_session(value: object) -> AsyncMock:
"""
- 支持改密测试查询用户的最小数据库替身。
+ 构造直接标量查询和结果集查询都返回指定对象的会话。
- :ivar value: 待处理的输入值
+ :param value: 应返回的记录
+ :return: 可检查事务调用的数据库会话替身
"""
-
- def __init__(self, value: object) -> None:
- """
- 初始化测试夹具的 ``value``。
-
- :param value: 待处理的输入值
- """
- super().__init__()
- self.value = value
-
- async def scalar(self, *_args: object, **_kwargs: object) -> object:
- """
- 向调用方返回 ``self.value``。
-
- :param _args: 调用方传入的其余位置参数
- :param _kwargs: 调用方按名称传入的附加选项
- :return: 测试对象保存的值
- """
- return self.value
-
- async def execute(self, *_args: object, **_kwargs: object) -> object:
- """
- 按测试场景处理数据库查询并提供结果。
-
- :param _args: 调用方传入的其余位置参数
- :param _kwargs: 调用方按名称传入的附加选项
- :return: 包含预设记录的查询结果
- """
- value = self.value
-
- class _Result:
- """模拟数据库查询结果。"""
-
- def scalars(self) -> object:
- """
- 向调用方返回 ``self``。
-
- :return: 当前测试对象
- """
- return self
-
- def first(self) -> object:
- """
- 向调用方返回 ``value``。
-
- :return: 为此调用预设的值
- """
- return value
-
- return _Result()
+ session = AsyncMock(spec=AsyncSession)
+ session.scalar.return_value = value
+ result = Mock()
+ result.scalars.return_value.first.return_value = value
+ session.execute.return_value = result
+ return session
@pytest.mark.asyncio
async def test_cache_callback_failure_does_not_compensate_committed_session() -> None:
"""提交后缓存回调失败与状态 CAS 失败分离,不撤销已落库 Session。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
compensated = False
async def cache_failure() -> None:
@@ -981,22 +870,23 @@ async def compensate() -> None:
await coordinator.register(cache_failure)
with pytest.raises(OidcInteractionException):
await InteractionFlowService.commit_transition(
- _Db(),
+ AsyncMock(spec=AsyncSession),
coordinator,
- redis,
+ redis.client,
created.interaction_id,
'completed',
compensate=compensate,
)
assert compensated is False
- assert (await InteractionService.get_record(redis, created.interaction_id))['status'] == 'completed'
+ assert (await InteractionService.get_record(redis.client, created.interaction_id))['status'] == 'completed'
@pytest.mark.asyncio
@pytest.mark.usefixtures('oidc_enabled')
async def test_code_audit_failure_invalidates_code_and_marker(monkeypatch: pytest.MonkeyPatch) -> None:
"""审计或提交失败时授权码与 completion marker 均不可继续使用。"""
- redis = FakeRedis()
+ store = FakeRedis()
+ redis = Mock(spec=Redis, wraps=store)
created = await InteractionService.create(redis, _payload('completed'), pepper=_PEPPER)
marker = OidcRedisKey.interaction(f'{created.interaction_id}-completion')
await redis.set(marker, 'reserved', ex=60)
@@ -1028,20 +918,21 @@ async def audit_failure(*_args: object, **_kwargs: object) -> None:
raise RuntimeError('audit unavailable')
monkeypatch.setattr(AuditService, 'record', audit_failure)
+ record = await InteractionService.get_record(redis, created.interaction_id)
with pytest.raises(OAuthProtocolException) as raised:
await InteractionCompletionService._issue_code(
- _Db(), redis, _payload('completed'), 'https://portal.example/callback', marker
+ AsyncMock(spec=AsyncSession), redis, record, 'https://portal.example/callback', marker
)
assert raised.value.error == 'server_error'
assert await redis.get(marker) is None
- assert not any(key.startswith('oidc:authorization_code:') for key in redis.values)
+ assert not any(key.startswith('oidc:authorization_code:') for key in store.values)
@pytest.mark.asyncio
@pytest.mark.usefixtures('oidc_enabled')
async def test_code_invalidate_failure_still_cleans_marker_and_rolls_back(monkeypatch: pytest.MonkeyPatch) -> None:
"""授权码失效补偿自身失败时仍继续清理 marker、回滚且只返回脱敏错误。"""
- redis = FakeRedis()
+ redis = Mock(spec=Redis, wraps=FakeRedis())
created = await InteractionService.create(redis, _payload('completed'), pepper=_PEPPER)
marker = OidcRedisKey.interaction(f'{created.interaction_id}-completion')
await redis.set(marker, 'reserved', ex=60)
@@ -1058,23 +949,20 @@ async def test_code_invalidate_failure_still_cleans_marker_and_rolls_back(monkey
lambda *_args, **_kwargs: _async(session),
)
monkeypatch.setattr(AuditService, 'record', lambda *_args, **_kwargs: _raise_async(RuntimeError('audit')))
+ invalidate = AsyncMock(side_effect=RuntimeError('redis invalidate failed'))
+ monkeypatch.setattr(AuthorizationCodeService, 'invalidate', invalidate)
monkeypatch.setattr(
- AuthorizationCodeService,
- 'invalidate',
- lambda *_args, **_kwargs: _raise_async(RuntimeError('redis invalidate failed')),
+ 'module_identity.service.authorization_service.AuthorizationService._completion_grant',
+ AsyncMock(return_value=SimpleNamespace(grant_id='grant-1')),
)
- db = _Db()
+ db = AsyncMock(spec=AsyncSession)
+ record = await InteractionService.get_record(redis, created.interaction_id)
with pytest.raises(OAuthProtocolException) as raised:
- await InteractionCompletionService._issue_code(
- db, redis, _payload('completed'), 'https://portal.example/callback', marker
- )
+ await InteractionCompletionService._issue_code(db, redis, record, 'https://portal.example/callback', marker)
assert raised.value.error == 'server_error'
assert await redis.get(marker) is None
- assert db.rollbacks == 1
- monkeypatch.setattr(
- 'module_identity.service.authorization_service.AuthorizationService._completion_grant',
- AsyncMock(return_value=SimpleNamespace(grant_id='grant-1')),
- )
+ invalidate.assert_awaited_once()
+ db.rollback.assert_awaited_once()
def _async(value: object) -> Any:
@@ -1121,7 +1009,7 @@ async def test_interaction_http_response_matches_frontend_data_contract(
) -> None:
"""真实 HTTP 响应按 OpenAPI 和页面约定将交互字段放在 data 下。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
result = InteractionResultModel(
next_action='redirect', interaction_id=created.interaction_id, redirect_url='/auth/interaction/complete'
)
@@ -1144,7 +1032,7 @@ async def db_override() -> Any:
:yield: 本次请求使用的模拟数据库会话
"""
- yield _Db()
+ yield AsyncMock(spec=AsyncSession)
app.dependency_overrides[get_db_session_provider(None)] = db_override
app.dependency_overrides[require_oidc_protocol_ready] = lambda: None
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_logout_confirmation.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_logout_confirmation.py
index 3c1c733d1..728cccf3c 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_logout_confirmation.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_logout_confirmation.py
@@ -7,6 +7,7 @@
import pytest
from fastapi import FastAPI, status
from fastapi.testclient import TestClient
+from sqlalchemy.ext.asyncio import AsyncSession
from common.aspect.db_session import get_db_session_provider
from config.env import OidcConfig
@@ -58,6 +59,20 @@ async def eval(self, _script: str, _count: int, key: str) -> str | None:
return value if expires > monotonic() else None
+def _confirmation_token(html: str) -> str:
+ """
+ 提取确认表单中的一次性令牌。
+
+ :param html: 注销确认页面
+ :return: 表单提交所需的令牌
+ """
+ match = re.search(r'name="confirmation" value="(?P[^"]+)"', html)
+ assert match is not None
+ token = match.group('token')
+ assert isinstance(token, str)
+ return token
+
+
@pytest.fixture
def logout_client(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[TestClient, AsyncMock]]:
"""
@@ -75,9 +90,9 @@ def logout_client(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[TestClient,
app.add_middleware(OidcCorsMiddleware)
app.state.redis = ConfirmationRedis()
app.include_router(authorization_controller)
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ db = AsyncMock(spec=AsyncSession)
- async def get_db() -> AsyncIterator[SimpleNamespace]:
+ async def get_db() -> AsyncIterator[AsyncMock]:
"""
为请求提供数据库会话。
@@ -115,7 +130,7 @@ def test_standard_logout_requires_confirmation_then_redirects(
assert "frame-ancestors 'none'" in response.headers['content-security-policy']
assert "form-action 'self' https://rp.example;" in response.headers['content-security-policy']
execute.assert_not_awaited()
- token = re.search(r'name="confirmation" value="([^"]+)"', response.text).group(1)
+ token = _confirmation_token(response.text)
response = client.post(
'/oauth2/logout/confirm',
data={'confirmation': token, 'decision': 'confirm'},
@@ -123,8 +138,8 @@ def test_standard_logout_requires_confirmation_then_redirects(
)
assert response.status_code == status.HTTP_303_SEE_OTHER
assert response.headers['location'] == 'https://rp.example/done?state=state-1'
- assert execute.await_args.kwargs['confirmed'] is True
- assert execute.await_args.kwargs['id_token_hint'] == 'private-hint'
+ assert execute.await_args_list[-1].kwargs['confirmed'] is True
+ assert execute.await_args_list[-1].kwargs['id_token_hint'] == 'private-hint'
execute.reset_mock()
replay = client.post(
'/oauth2/logout/confirm',
@@ -140,7 +155,7 @@ def test_cancel_keeps_sso_cookie_and_never_calls_revocation(logout_client: tuple
client, execute = logout_client
client.cookies.set(OidcConfig.oidc_sso_cookie_name, 'current-sso', domain='auth.example', path='/')
page = client.get('/oauth2/logout')
- token = re.search(r'name="confirmation" value="([^"]+)"', page.text).group(1)
+ token = _confirmation_token(page.text)
response = client.post(
'/oauth2/logout/confirm',
data={'confirmation': token, 'decision': 'cancel'},
@@ -159,11 +174,12 @@ def test_confirmation_rejects_wrong_origin_browser_or_expiry(
"""注销确认时拒绝来源、浏览器或有效期不符的请求。"""
client, execute = logout_client
page = client.get('/oauth2/logout')
- token = re.search(r'name="confirmation" value="([^"]+)"', page.text).group(1)
+ token = _confirmation_token(page.text)
origin = 'https://evil.example' if attack == 'origin' else 'https://auth.example'
if attack == 'cookie':
client.cookies.clear()
if attack == 'expired':
+ assert isinstance(client.app, FastAPI)
redis = client.app.state.redis
redis.values = {key: (value, 0) for key, (value, _expires) in redis.values.items()}
response = client.post(
@@ -180,7 +196,7 @@ def test_cross_site_post_may_omit_lax_sso_cookie_until_confirmation(
client, execute = logout_client
page = client.post('/oauth2/logout', data={'state': 'cross-site'})
assert page.headers['referrer-policy'] == 'strict-origin'
- token = re.search(r'name="confirmation" value="([^"]+)"', page.text).group(1)
+ token = _confirmation_token(page.text)
client.cookies.set(OidcConfig.oidc_sso_cookie_name, 'current-sso', domain='auth.example', path='/')
response = client.post(
'/oauth2/logout/confirm',
@@ -188,7 +204,7 @@ def test_cross_site_post_may_omit_lax_sso_cookie_until_confirmation(
headers={'Origin': 'https://auth.example'},
)
assert response.status_code == status.HTTP_303_SEE_OTHER
- assert execute.await_args.kwargs['cookie'] == 'current-sso'
+ assert execute.await_args_list[-1].kwargs['cookie'] == 'current-sso'
def test_changing_an_initially_bound_sso_cookie_rejects_confirmation(
@@ -198,7 +214,7 @@ def test_changing_an_initially_bound_sso_cookie_rejects_confirmation(
client, execute = logout_client
client.cookies.set(OidcConfig.oidc_sso_cookie_name, 'first-sso', domain='auth.example', path='/')
page = client.get('/oauth2/logout')
- token = re.search(r'name="confirmation" value="([^"]+)"', page.text).group(1)
+ token = _confirmation_token(page.text)
client.cookies.set(OidcConfig.oidc_sso_cookie_name, 'second-sso', domain='auth.example', path='/')
response = client.post(
'/oauth2/logout/confirm',
@@ -224,13 +240,13 @@ async def test_confirmation_csp_allows_only_verified_registered_redirect(
AsyncMock(return_value=SimpleNamespace(status='0') if registered else None),
)
origin = await LogoutConfirmationService.form_redirect_origin(
- object(), {'id_token_hint': 'valid-hint', 'post_logout_redirect_uri': 'https://rp.example:9443/done'}
+ AsyncSession(), {'id_token_hint': 'valid-hint', 'post_logout_redirect_uri': 'https://rp.example:9443/done'}
)
assert origin == ('https://rp.example:9443' if registered else None)
monkeypatch.setattr(LogoutService, '_validate_id_token_hint', AsyncMock(side_effect=ValueError('invalid hint')))
assert (
await LogoutConfirmationService.form_redirect_origin(
- object(), {'id_token_hint': 'invalid-hint', 'post_logout_redirect_uri': 'https://rp.example/done'}
+ AsyncSession(), {'id_token_hint': 'invalid-hint', 'post_logout_redirect_uri': 'https://rp.example/done'}
)
is None
)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_audit_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_audit_controller.py
index 1e9df1a6a..842ac608b 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_audit_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_audit_controller.py
@@ -10,6 +10,7 @@
from common.annotation.rate_limit_annotation import ApiRateLimit
from common.context import RequestContext
+from module_admin.entity.vo.user_vo import CurrentUserModel, UserInfoModel
from module_admin.service.log_service import LogQueueService
from module_identity.controller.oauth_audit_controller import (
list_oauth_audit,
@@ -18,22 +19,7 @@
from module_identity.dao.oauth_audit_dao import OAuthAuditDao
from module_identity.entity.vo.oauth_session_vo import AuditPageQueryModel
from module_identity.service.audit_service import AuditService
-
-
-class _Session:
- """
- 提供只读回滚边界。
-
- :ivar rollbacks: 测试中记录的回滚次数
- """
-
- def __init__(self) -> None:
- """初始化测试夹具的 ``rollbacks``。"""
- self.rollbacks = 0
-
- async def rollback(self) -> None:
- """累加 ``rollbacks`` 供后续断言检查。"""
- self.rollbacks += 1
+from tests.module_identity.support.sessions import RecordingSession
def test_audit_routes_use_list_and_export_permissions() -> None:
@@ -42,7 +28,7 @@ def test_audit_routes_use_list_and_export_permissions() -> None:
(route.path, method): route
for route in oauth_audit_controller.routes
if isinstance(route, APIRoute)
- for method in route.methods
+ for method in route.methods or ()
}
assert 'monitor:oauthAudit:list' in [
getattr(dep.call, 'perm', None) for dep in routes[('/monitor/oauth/audit/list', 'GET')].dependant.dependencies
@@ -97,7 +83,7 @@ async def test_audit_list_uses_real_total_and_safe_projection(monkeypatch: pytes
),
]
- async def list_page(*args: object, **kwargs: object) -> list[object]:
+ async def list_page(*args: object, **kwargs: object) -> list[SimpleNamespace]:
"""
向调用方返回 ``rows``。
@@ -119,7 +105,7 @@ async def count(*args: object, **kwargs: object) -> int:
monkeypatch.setattr(OAuthAuditDao, 'list_admin_page', list_page)
monkeypatch.setattr(OAuthAuditDao, 'count_admin', count)
- response = await list_oauth_audit(AuditPageQueryModel(page_num=1, page_size=2), _Session())
+ response = await list_oauth_audit(AuditPageQueryModel(page_num=1, page_size=2), RecordingSession())
assert b'"total":37' in response.body
assert b'"detail"' not in response.body
assert b'access_token' not in response.body
@@ -129,8 +115,8 @@ async def count(*args: object, **kwargs: object) -> int:
async def test_audit_export_runs_rate_limit_and_operation_log(monkeypatch: pytest.MonkeyPatch) -> None:
"""HTTP 审计导出经过完整装饰器链,保留文件响应并记录操作日志。"""
query = AuditPageQueryModel()
- db = _Session()
- user = SimpleNamespace(user=SimpleNamespace(user_id=1, user_name='admin', dept=None))
+ db = RecordingSession()
+ user = CurrentUserModel(permissions=[], roles=[], user=UserInfoModel(user_id=1, user_name='admin'))
route = next(
route
for route in oauth_audit_controller.routes
@@ -140,6 +126,8 @@ async def test_audit_export_runs_rate_limit_and_operation_log(monkeypatch: pytes
app.state.redis = SimpleNamespace()
app.include_router(oauth_audit_controller)
for dependency in route.dependant.dependencies:
+ if dependency.call is None:
+ continue
if dependency.name == 'query_db':
app.dependency_overrides[dependency.call] = lambda: db
else:
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_client_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_client_controller.py
index ee7d82f21..73a3d83c5 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_client_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_client_controller.py
@@ -13,34 +13,13 @@
get_system_oauth_client_list,
oauth_client_controller,
)
-from module_identity.entity.vo.oauth_client_vo import ClientSecretResponseModel
+from module_identity.entity.vo.oauth_client_vo import ClientPageQueryModel, ClientSecretResponseModel
from module_identity.service.oauth_management_service import (
OAuthClientManagementError,
OAuthClientManagementService,
)
from module_identity.service.runtime_service import OidcRuntimeService
-
-
-class _FakeSession:
- """
- 记录 Controller 的 commit/rollback 边界。
-
- :ivar commits: 测试中记录的提交次数
- :ivar rollbacks: 测试中记录的回滚次数
- """
-
- def __init__(self) -> None:
- """初始化测试夹具的 ``commits``, ``rollbacks``。"""
- self.commits = 0
- self.rollbacks = 0
-
- async def commit(self) -> None:
- """累加 ``commits`` 供后续断言检查。"""
- self.commits += 1
-
- async def rollback(self) -> None:
- """累加 ``rollbacks`` 供后续断言检查。"""
- self.rollbacks += 1
+from tests.module_identity.support.sessions import RecordingSession
@pytest.fixture(autouse=True)
@@ -139,7 +118,7 @@ def test_client_router_paths_methods_permissions_and_pre_auth() -> None:
('/system/oauth/client/{client_id}/uri', 'POST'): 'system:oauthClient:edit',
('/system/oauth/client/{client_id}/uri/{uri_id}', 'DELETE'): 'system:oauthClient:edit',
}
- routes = {(route.path, method): route for route in _routes() for method in route.methods}
+ routes = {(route.path, method): route for route in _routes() for method in route.methods or ()}
assert set(routes) == set(expected)
for key, permission in expected.items():
dependency_calls = [getattr(item.call, 'perm', None) for item in routes[key].dependant.dependencies]
@@ -154,7 +133,7 @@ async def test_client_create_commits_and_secret_is_only_in_rotation_response(
oauth_management_client: Callable[[APIRouter, object, object], AsyncClient],
) -> None:
"""写操作由服务层管理事务,轮换响应含明文而普通错误不包含敏感字段。"""
- session = _FakeSession()
+ session = RecordingSession()
async def fake_create(*args: object, **kwargs: object) -> object:
"""
@@ -227,7 +206,7 @@ async def test_client_batch_failure_rolls_back_all_items(
oauth_management_client: Callable[[APIRouter, object, object], AsyncClient],
) -> None:
"""批量停用任一项失败时整体回滚,不提前提交。"""
- session = _FakeSession()
+ session = RecordingSession()
calls: list[str] = []
async def fake_disable(*args: object, **kwargs: object) -> object:
@@ -240,6 +219,7 @@ async def fake_disable(*args: object, **kwargs: object) -> object:
:return: ``SimpleNamespace`` 实例
"""
client_id = args[1]
+ assert isinstance(client_id, str)
calls.append(client_id)
if client_id == 'cli_bad':
raise OAuthClientManagementError('client not found')
@@ -282,7 +262,7 @@ async def test_client_list_uses_real_total_and_actor_failure_is_mapped(
oauth_management_client: Callable[[APIRouter, object, object], AsyncClient],
) -> None:
"""列表返回服务层全量计数,actor 缺失时稳定返回业务失败。"""
- session = _FakeSession()
+ session = RecordingSession()
async def fake_rows(*args: object, **kwargs: object) -> list[str]:
"""
@@ -306,7 +286,7 @@ async def fake_count(*args: object, **kwargs: object) -> int:
monkeypatch.setattr(OAuthClientManagementService, 'list_clients', fake_rows)
monkeypatch.setattr(OAuthClientManagementService, 'count_clients', fake_count)
- response = await get_system_oauth_client_list(SimpleNamespace(), session)
+ response = await get_system_oauth_client_list(ClientPageQueryModel(), session)
assert b'"total":37' in response.body
assert b'"rows":["row-1","row-2"]' in response.body
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_resource_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_resource_controller.py
index b2a0b4ea4..c32049543 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_resource_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_resource_controller.py
@@ -16,32 +16,12 @@
oauth_resource_controller,
oauth_scope_controller,
)
+from module_identity.entity.vo.oauth_resource_vo import ResourcePageQueryModel, ScopePageQueryModel
from module_identity.service.oauth_management_service import (
OAuthClientManagementError,
OAuthResourceManagementService,
)
-
-
-class _FakeSession:
- """
- 记录 Controller 提交和回滚次数。
-
- :ivar commits: 测试中记录的提交次数
- :ivar rollbacks: 测试中记录的回滚次数
- """
-
- def __init__(self) -> None:
- """初始化测试夹具的 ``commits``, ``rollbacks``。"""
- self.commits = 0
- self.rollbacks = 0
-
- async def commit(self) -> None:
- """累加 ``commits`` 供后续断言检查。"""
- self.commits += 1
-
- async def rollback(self) -> None:
- """累加 ``rollbacks`` 供后续断言检查。"""
- self.rollbacks += 1
+from tests.module_identity.support.sessions import RecordingSession
@pytest.fixture(autouse=True)
@@ -74,7 +54,7 @@ def _user() -> SimpleNamespace:
return SimpleNamespace(user=SimpleNamespace(user_name='admin', dept=SimpleNamespace(dept_name='测试部门')))
-def _route_map(router: object) -> dict[tuple[str, str], APIRoute]:
+def _route_map(router: APIRouter) -> dict[tuple[str, str], APIRoute]:
"""
构造路由路径和方法索引。
@@ -82,10 +62,10 @@ def _route_map(router: object) -> dict[tuple[str, str], APIRoute]:
:return: 路由路径和方法索引
"""
routes = [route for route in router.routes if isinstance(route, APIRoute)]
- return {(route.path, method): route for route in routes for method in route.methods}
+ return {(route.path, method): route for route in routes for method in route.methods or ()}
-def _assert_routes(router: object, expected: dict[tuple[str, str], str]) -> None:
+def _assert_routes(router: APIRouter, expected: dict[tuple[str, str], str]) -> None:
"""
断言路由路径、方法和权限依赖。
@@ -133,7 +113,7 @@ async def test_resource_batch_failure_rolls_back_without_partial_commit(
oauth_management_client: Callable[[APIRouter, object, object], AsyncClient],
) -> None:
"""Resource 批量停用任一项失败时整体回滚。"""
- session = _FakeSession()
+ session = RecordingSession()
calls: list[str] = []
async def fake_disable(*args: object, **kwargs: object) -> object:
@@ -146,6 +126,7 @@ async def fake_disable(*args: object, **kwargs: object) -> object:
:return: ``SimpleNamespace`` 实例
"""
resource_id = args[1]
+ assert isinstance(resource_id, str)
calls.append(resource_id)
if resource_id == 'resource-bad':
raise OAuthClientManagementError('resource not found')
@@ -167,7 +148,7 @@ async def test_scope_batch_rejects_empty_duplicate_and_invalid_encoding(
oauth_management_client: Callable[[APIRouter, object, object], AsyncClient],
) -> None:
"""Scope 批量路径拒绝空项、重复项和未解析的百分号编码。"""
- session = _FakeSession()
+ session = RecordingSession()
user = _user()
async with oauth_management_client(oauth_scope_controller, session, user) as client:
for value, message in (
@@ -190,7 +171,7 @@ async def test_resource_scope_lists_use_real_total_and_actor_failure_is_mapped(
oauth_management_client: Callable[[APIRouter, object, object], AsyncClient],
) -> None:
"""Resource/Scope 列表使用真实全量计数,缺少 actor 时不逃逸异常。"""
- session = _FakeSession()
+ session = RecordingSession()
async def fake_rows(*args: object, **kwargs: object) -> list[str]:
"""
@@ -214,13 +195,13 @@ async def fake_count(*args: object, **kwargs: object) -> int:
monkeypatch.setattr(OAuthResourceManagementService, 'list_resources', fake_rows)
monkeypatch.setattr(OAuthResourceManagementService, 'count_resources', fake_count)
- resource_response = await get_system_oauth_resource_list(SimpleNamespace(), session)
+ resource_response = await get_system_oauth_resource_list(ResourcePageQueryModel(), session)
assert b'"total":37' in resource_response.body
assert b'"rows":["row-1","row-2"]' in resource_response.body
monkeypatch.setattr(OAuthResourceManagementService, 'list_scopes', fake_rows)
monkeypatch.setattr(OAuthResourceManagementService, 'count_scopes', fake_count)
- scope_response = await get_system_oauth_scope_list(SimpleNamespace(), session)
+ scope_response = await get_system_oauth_scope_list(ScopePageQueryModel(), session)
assert b'"total":37' in scope_response.body
assert b'"rows":["row-1","row-2"]' in scope_response.body
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_session_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_session_controller.py
index 37a339f99..3e5e868af 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_session_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oauth_session_controller.py
@@ -8,9 +8,12 @@
from fastapi import APIRouter, FastAPI, Request
from fastapi.routing import APIRoute
from httpx import ASGITransport, AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
+from common.annotation.log_annotation import Log
from common.annotation.rate_limit_annotation import ApiRateLimit
from common.context import RequestContext
+from module_admin.entity.vo.user_vo import CurrentUserModel, UserInfoModel
from module_admin.service.log_service import LogQueueService
from module_identity.controller.oauth_session_controller import (
get_oauth_grant,
@@ -22,40 +25,20 @@
from module_identity.dao.oauth_access_policy_dao import OAuthAccessPolicyDao
from module_identity.dao.oauth_client_dao import OAuthClientDao
from module_identity.dao.oauth_grant_dao import OAuthGrantDao
+from module_identity.entity.vo.oauth_session_vo import SessionRevokeModel
from module_identity.service.audit_service import AuditService
from module_identity.service.oauth_session_management_service import OAuthSessionManagementService
from module_identity.service.session_service import SsoSessionService
+from tests.module_identity.support.sessions import RecordingSession
-class _Session:
- """
- 记录 Controller 事务边界。
-
- :ivar commits: 测试中记录的提交次数
- :ivar rollbacks: 测试中记录的回滚次数
- """
-
- def __init__(self) -> None:
- """初始化测试夹具的 ``commits``, ``rollbacks``。"""
- self.commits = 0
- self.rollbacks = 0
-
- async def commit(self) -> None:
- """累加 ``commits`` 供后续断言检查。"""
- self.commits += 1
-
- async def rollback(self) -> None:
- """累加 ``rollbacks`` 供后续断言检查。"""
- self.rollbacks += 1
-
-
-def _user() -> SimpleNamespace:
+def _user() -> CurrentUserModel:
"""
构造最小管理用户。
:return: 最小管理用户
"""
- return SimpleNamespace(user=SimpleNamespace(user_name='admin', user_id=1, dept=None))
+ return CurrentUserModel(permissions=[], roles=[], user=UserInfoModel(user_id=1, user_name='admin'))
def _request() -> Request:
@@ -79,7 +62,7 @@ async def receive() -> dict[str, object]:
)
-def _route_map(router: object) -> dict[tuple[str, str], APIRoute]:
+def _route_map(router: APIRouter) -> dict[tuple[str, str], APIRoute]:
"""
索引路由路径、方法。
@@ -90,7 +73,7 @@ def _route_map(router: object) -> dict[tuple[str, str], APIRoute]:
(route.path, method): route
for route in router.routes
if isinstance(route, APIRoute)
- for method in route.methods
+ for method in route.methods or ()
}
@@ -124,7 +107,7 @@ async def test_batch_revoke_is_atomic_and_reason_does_not_leak(
oauth_management_client: Callable[[APIRouter, object, object], AsyncClient],
) -> None:
"""批量撤销失败时回滚且不回显内部敏感字段。"""
- db = _Session()
+ db = RecordingSession()
async def audit(*args: object, **kwargs: object) -> None:
"""
@@ -190,9 +173,7 @@ async def grant_revoke(*args: object, **kwargs: object) -> bool:
monkeypatch.setattr(OAuthGrantDao, 'revoke_for_user_client', AsyncMock(return_value=['grant-1']))
token = RequestContext.set_current_user(_user())
try:
- response = await revoke_oauth_grants.__wrapped__(
- _request(), 'grant-1', SimpleNamespace(reason='撤销'), db, _user()
- )
+ response = await revoke_oauth_grants(_request(), 'grant-1', SessionRevokeModel(reason='撤销'), db, _user())
finally:
RequestContext.reset_current_user(token)
assert b'true' in response.body
@@ -204,7 +185,11 @@ async def test_session_controller_injects_redis_without_passing_request_to_servi
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Session 管理 Controller 向 Service 传入精确 Redis 依赖,而非 FastAPI Request。"""
- db = _Session()
+ monkeypatch.setattr(
+ ApiRateLimit, '_acquire_rate_limit', AsyncMock(return_value={'allowed': True, 'remaining': 1, 'reset_at': 0})
+ )
+ monkeypatch.setattr(Log, '_get_oper_location', AsyncMock(return_value='测试'))
+ db = RecordingSession()
request = _request()
captured: dict[str, object] = {}
@@ -234,12 +219,11 @@ async def enqueue_operation_log(*args: object, **kwargs: object) -> None:
monkeypatch.setattr(LogQueueService, 'enqueue_operation_log', enqueue_operation_log)
token = RequestContext.set_current_user(_user())
try:
- response = await revoke_oauth_sessions.__wrapped__(
- request, 'sid-1', SimpleNamespace(reason='管理员操作'), db, _user()
- )
+ response = await revoke_oauth_sessions(request, 'sid-1', SessionRevokeModel(reason='管理员操作'), db, _user())
finally:
RequestContext.reset_current_user(token)
assert b'true' in response.body
+ assert isinstance(captured['args'], tuple)
assert captured['args'][1] is request.app.state.redis
assert not isinstance(captured['args'][1], Request)
@@ -293,8 +277,8 @@ async def client_id(*args: object, **kwargs: object) -> str:
return 'client-2'
monkeypatch.setattr(OAuthClientDao, 'id_for_pk', client_id)
- db = _Session()
- db.execute = execute
+ db = AsyncMock(spec=AsyncSession)
+ db.execute.side_effect = execute
response = await get_oauth_grant('g1', db)
assert b'refresh_token_hash' not in response.body
@@ -303,7 +287,7 @@ async def client_id(*args: object, **kwargs: object) -> str:
@pytest.mark.parametrize('grant_ids', ['grant-1', 'grant-1,grant-2'])
async def test_grant_revoke_runs_rate_limit_and_operation_log(monkeypatch: pytest.MonkeyPatch, grant_ids: str) -> None:
"""HTTP 撤销请求经过完整装饰器链并记录实际请求和撤销结果。"""
- db = _Session()
+ db = RecordingSession()
user = _user()
path = f'/system/oauth/grant/{grant_ids}'
route = _route_map(oauth_grant_controller)[('/system/oauth/grant/{grant_ids}', 'DELETE')]
@@ -311,6 +295,8 @@ async def test_grant_revoke_runs_rate_limit_and_operation_log(monkeypatch: pytes
app.state.redis = SimpleNamespace()
app.include_router(oauth_grant_controller)
for dependency in route.dependant.dependencies:
+ if dependency.call is None:
+ continue
if dependency.name == 'query_db':
app.dependency_overrides[dependency.call] = lambda: db
elif dependency.name == 'current_user':
@@ -356,13 +342,15 @@ async def test_grant_revoke_runs_rate_limit_and_operation_log(monkeypatch: pytes
@pytest.mark.parametrize('blocked', [True, False])
async def test_access_policy_runs_rate_limit_and_operation_log(monkeypatch: pytest.MonkeyPatch, blocked: bool) -> None:
"""禁止及解除访问通过真实 HTTP 装饰器链,准确传递用户、应用和原因。"""
- db, user = _Session(), _user()
+ db, user = RecordingSession(), _user()
path = '/system/oauth/grant/user/7/client/business-app/access'
route = _route_map(oauth_grant_controller)[('/system/oauth/grant/user/{user_id}/client/{client_id}/access', 'PUT')]
app = FastAPI()
app.state.redis = SimpleNamespace()
app.include_router(oauth_grant_controller)
for dependency in route.dependant.dependencies:
+ if dependency.call is None:
+ continue
if dependency.name == 'query_db':
app.dependency_overrides[dependency.call] = lambda: db
elif dependency.name == 'current_user':
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oidc_key_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oidc_key_controller.py
index 0e3cfac7f..64413330b 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oidc_key_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_oidc_key_controller.py
@@ -1,4 +1,5 @@
from datetime import UTC, datetime
+from inspect import unwrap
from types import SimpleNamespace
import pytest
@@ -15,28 +16,7 @@
)
from module_identity.service.key_service import KeyService, KeyServiceError, OidcKeyManagementService
from module_identity.service.runtime_service import OidcReadiness, OidcRuntimeService
-
-
-class _Session:
- """
- 记录提交和回滚。
-
- :ivar commits: 测试中记录的提交次数
- :ivar rollbacks: 测试中记录的回滚次数
- """
-
- def __init__(self) -> None:
- """初始化测试夹具的 ``commits``, ``rollbacks``。"""
- self.commits = 0
- self.rollbacks = 0
-
- async def commit(self) -> None:
- """累加 ``commits`` 供后续断言检查。"""
- self.commits += 1
-
- async def rollback(self) -> None:
- """累加 ``rollbacks`` 供后续断言检查。"""
- self.rollbacks += 1
+from tests.module_identity.support.sessions import RecordingSession
def _user() -> SimpleNamespace:
@@ -64,7 +44,7 @@ def test_key_routes_use_separate_permissions_for_rotation_and_activation() -> No
(route.path, method): route
for route in oidc_key_controller.routes
if isinstance(route, APIRoute)
- for method in route.methods
+ for method in route.methods or ()
}
assert ('/system/oauth/key/{kid}/activate', 'PUT') in routes
assert ('/system/oauth/key/{kid}/retire', 'PUT') in routes
@@ -81,7 +61,7 @@ def test_key_routes_use_separate_permissions_for_rotation_and_activation() -> No
@pytest.mark.asyncio
async def test_key_write_failures_rollback_and_never_return_private_fields(monkeypatch: pytest.MonkeyPatch) -> None:
"""密钥状态异常稳定回滚,响应不包含私钥引用。"""
- db = _Session()
+ db = RecordingSession()
async def fail(*args: object, **kwargs: object) -> bool:
"""
@@ -95,7 +75,8 @@ async def fail(*args: object, **kwargs: object) -> bool:
monkeypatch.setattr(KeyService, 'activate_key', fail)
with pytest.raises(ServiceException) as exc_info:
- await activate_oidc_key.__wrapped__.__wrapped__(_request(), 'kid-1', db, _user())
+ await unwrap(activate_oidc_key)(_request(), 'kid-1', db, _user())
+ assert exc_info.value.message is not None
assert 'private_key_ciphertext' not in exc_info.value.message
assert db.rollbacks == 1 and db.commits == 0
@@ -110,19 +91,19 @@ async def retire(*args: object, **kwargs: object) -> bool:
return True
monkeypatch.setattr(KeyService, 'retire_key', retire)
- response = await retire_oidc_key.__wrapped__.__wrapped__(_request(), 'kid-1', db, _user())
+ response = await unwrap(retire_oidc_key)(_request(), 'kid-1', db, _user())
assert b'true' in response.body
assert db.commits == 1
monkeypatch.setattr(KeyService, 'delete_key', retire)
- response = await delete_oidc_key.__wrapped__.__wrapped__(_request(), 'kid-1', db, _user())
+ response = await unwrap(delete_oidc_key)(_request(), 'kid-1', db, _user())
assert b'true' in response.body
@pytest.mark.asyncio
async def test_key_activation_returns_clear_message_before_publication(monkeypatch: pytest.MonkeyPatch) -> None:
"""密钥尚未公开时返回可操作提示,不暴露内部异常。"""
- db = _Session()
+ db = RecordingSession()
async def unpublished(*args: object, **kwargs: object) -> bool:
"""
@@ -136,7 +117,8 @@ async def unpublished(*args: object, **kwargs: object) -> bool:
monkeypatch.setattr(KeyService, 'activate_key', unpublished)
with pytest.raises(ServiceException) as exc_info:
- await activate_oidc_key.__wrapped__.__wrapped__(_request(), 'kid-1', db, _user())
+ await unwrap(activate_oidc_key)(_request(), 'kid-1', db, _user())
+ assert exc_info.value.message is not None
assert '签名公钥尚未到公开时间' in exc_info.value.message
assert db.rollbacks == 1 and db.commits == 0
@@ -145,12 +127,6 @@ async def unpublished(*args: object, **kwargs: object) -> bool:
async def test_key_list_exposes_only_safe_enabled_capability(monkeypatch: pytest.MonkeyPatch) -> None:
"""密钥列表向管理页暴露启用能力,但不阻断 OIDC 关闭时的引导。"""
- class _Db:
- """模拟当前测试所需的数据库操作。"""
-
- async def rollback(self) -> None:
- """在测试会话中处理事务回滚。"""
-
async def list_page(*args: object, **kwargs: object) -> tuple[list[object], int]:
"""
提供分页查询的测试结果。
@@ -167,7 +143,7 @@ async def list_page(*args: object, **kwargs: object) -> tuple[list[object], int]
'inspect_readiness',
lambda db: _async_readiness(OidcReadiness(False, False, 'disabled', datetime.now(UTC))),
)
- response = await list_oidc_keys(_Db())
+ response = await list_oidc_keys(RecordingSession())
assert b'"enabled":false' in response.body
assert b'"ready":false' in response.body
assert b'private_key' not in response.body
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_token_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_token_controller.py
index 3afcce133..0126d23a1 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_token_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_token_controller.py
@@ -6,13 +6,16 @@
import jwt
import pytest
from cryptography.hazmat.primitives.asymmetric import rsa
-from fastapi import HTTPException
+from fastapi import HTTPException, Request
from jwt.algorithms import RSAAlgorithm
+from sqlalchemy.ext.asyncio import AsyncSession
from exceptions.exception import OAuthProtocolException
from module_identity.controller import token_controller as controller
from module_identity.security.principal import OAuthClientPrincipal
from module_identity.service.token_service import RefreshTokenReuseDetected, TokenResult, TokenService
+from tests.module_identity.support.http import make_request
+from tests.module_identity.support.sessions import RecordingSession
_OK = 200
_BAD_REQUEST = 400
@@ -42,29 +45,7 @@ async def allow(*_args: object, **_kwargs: object) -> None:
monkeypatch.setattr(controller.OidcRateLimiter, 'enforce', allow)
-class _Db:
- """
- 记录 Controller 事务边界的最小异步会话替身。
-
- :ivar commits: 测试中记录的提交次数
- :ivar rollbacks: 测试中记录的回滚次数
- """
-
- def __init__(self) -> None:
- """初始化测试夹具的 ``commits``, ``rollbacks``。"""
- self.commits = 0
- self.rollbacks = 0
-
- async def commit(self) -> None:
- """累加 ``commits`` 供后续断言检查。"""
- self.commits += 1
-
- async def rollback(self) -> None:
- """累加 ``rollbacks`` 供后续断言检查。"""
- self.rollbacks += 1
-
-
-class _FailCommitDb(_Db):
+class _FailCommitDb(RecordingSession):
"""提交失败并允许回滚的会话替身。"""
async def commit(self) -> None:
@@ -77,22 +58,20 @@ async def commit(self) -> None:
raise RuntimeError('commit failed')
-def _request() -> SimpleNamespace:
+def _request(*, basic: bool = True) -> Request:
"""
构造携带应用 Redis 状态的请求替身。
+ :param basic: 是否使用 Basic 认证头
:return: 携带应用 Redis 状态的请求替身
"""
- return SimpleNamespace(
- headers={'authorization': 'Basic test'},
- app=SimpleNamespace(state=SimpleNamespace(redis=object())),
- )
+ return make_request(object(), headers={'authorization': 'Basic test'} if basic else {})
@pytest.mark.asyncio
async def test_token_success_is_bare_json_and_commits(monkeypatch: pytest.MonkeyPatch) -> None:
"""Token 成功响应提交事务且带 no-store。"""
- db = _Db()
+ db = RecordingSession()
monkeypatch.setattr(controller, 'read_form', lambda request: _async(_form()))
monkeypatch.setattr(
TokenService,
@@ -114,7 +93,7 @@ async def test_token_success_is_bare_json_and_commits(monkeypatch: pytest.Monkey
@pytest.mark.asyncio
async def test_token_invalid_client_has_basic_challenge(monkeypatch: pytest.MonkeyPatch) -> None:
"""Token invalid_client 必须返回 RFC Basic challenge。"""
- db = _Db()
+ db = RecordingSession()
monkeypatch.setattr(controller, 'read_form', lambda request: _async(_form()))
async def invalid(*args: object, **kwargs: object) -> object:
@@ -138,7 +117,7 @@ async def test_token_rejects_oversized_or_basic_plus_body_secret_before_issue(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Token Endpoint 不允许绕过 Secret 长度、位置和互斥边界。"""
- db = _Db()
+ db = RecordingSession()
authenticate = AsyncMock(side_effect=OAuthProtocolException('invalid_client', 'Client authentication failed', 401))
issue = AsyncMock()
monkeypatch.setattr(TokenService, 'authenticate_client', authenticate)
@@ -164,20 +143,19 @@ async def test_token_rejects_oversized_or_basic_plus_body_secret_before_issue(
issue.assert_not_awaited()
authenticate.reset_mock()
- request_without_basic = _request()
- request_without_basic.headers = {}
+ request_without_basic = _request(basic=False)
response = await controller.token(request_without_basic, db)
assert response.status_code == _UNAUTHORIZED
authenticate.assert_awaited_once()
- assert authenticate.await_args.kwargs['authorization'] is None
- assert authenticate.await_args.kwargs['client_secret'] == 'body'
+ assert authenticate.await_args_list[-1].kwargs['authorization'] is None
+ assert authenticate.await_args_list[-1].kwargs['client_secret'] == 'body'
issue.assert_not_awaited()
@pytest.mark.asyncio
async def test_refresh_reuse_commits_family_before_invalid_grant(monkeypatch: pytest.MonkeyPatch) -> None:
"""Refresh 重放异常必须提交 Family 撤销,而非回滚。"""
- db = _Db()
+ db = RecordingSession()
monkeypatch.setattr(controller, 'read_form', lambda request: _async(_form()))
monkeypatch.setattr(
TokenService,
@@ -198,7 +176,7 @@ async def reuse(*args: object, **kwargs: object) -> TokenResult:
monkeypatch.setattr(TokenService, 'issue_token', reuse)
response = await controller.token(_request(), db)
assert response.status_code == _BAD_REQUEST
- assert response.body.startswith(b'{"error":"invalid_grant"')
+ assert bytes(response.body).startswith(b'{"error":"invalid_grant"')
assert db.commits == 1
assert db.rollbacks == 0
@@ -234,7 +212,7 @@ async def reuse(*args: object, **kwargs: object) -> TokenResult:
@pytest.mark.asyncio
async def test_introspect_rejects_public_client_with_basic_challenge(monkeypatch: pytest.MonkeyPatch) -> None:
"""Introspection 在 Controller 边界拒绝公共 Client。"""
- db = _Db()
+ db = RecordingSession()
monkeypatch.setattr(controller, 'read_form', lambda request: _async({'client_id': 'c', 'token': 'x'}))
monkeypatch.setattr(
TokenService,
@@ -253,7 +231,7 @@ async def test_introspect_rejects_public_client_with_basic_challenge(monkeypatch
@pytest.mark.parametrize('status_code', [_BAD_REQUEST, _UNSUPPORTED_MEDIA])
async def test_introspect_form_boundary_preserves_http_error(monkeypatch: pytest.MonkeyPatch, status_code: int) -> None:
"""Introspection 的重复字段和媒体类型错误不得被转换为 500。"""
- db = _Db()
+ db = RecordingSession()
async def invalid_form(request: object) -> dict[str, str]:
"""
@@ -284,18 +262,6 @@ async def test_revoke_and_introspect_receive_database_rsa_verification_key(monke
public_jwk=json.loads(RSAAlgorithm.to_jwk(key.public_key())),
)
- class KeyDb(_Db):
- """提供令牌校验时的密钥查询结果。"""
-
- async def scalar(self, statement: object) -> object:
- """
- 向调用方返回 ``record``。
-
- :param statement: 即将执行的数据库语句
- :return: 与当前标识匹配的记录
- """
- return record
-
token = jwt.encode(
{
'iss': 'https://issuer.example',
@@ -311,7 +277,8 @@ async def scalar(self, statement: object) -> object:
algorithm='RS256',
headers={'kid': 'kid-route', 'typ': 'at+jwt'},
)
- db = KeyDb()
+ db = AsyncMock(spec=AsyncSession)
+ db.scalar.return_value = record
captured: list[object] = []
monkeypatch.setattr('module_identity.dependencies.OidcKeyDao.get_verifying', lambda *args: _async(record))
monkeypatch.setattr(controller, 'read_form', lambda request: _async({'client_id': 'c', 'token': token}))
@@ -337,7 +304,8 @@ async def revoke_service(*args: object, **kwargs: object) -> None:
monkeypatch.setattr(controller.RevocationService, 'revoke', revoke_service)
await controller.revoke(_request(), db)
- assert captured and captured[0].public_numbers() == key.public_key().public_numbers()
+ assert captured and isinstance(captured[0], rsa.RSAPublicKey)
+ assert captured[0].public_numbers() == key.public_key().public_numbers()
captured.clear()
@@ -354,8 +322,9 @@ async def introspect_service(*args: object, **kwargs: object) -> dict[str, bool]
monkeypatch.setattr(controller.IntrospectionService, 'introspect', introspect_service)
await controller.introspect(_request(), db)
- assert captured and captured[0].public_numbers() == key.public_key().public_numbers()
- assert db.commits == _EXPECTED_CONTROLLER_COMMITS
+ assert captured and isinstance(captured[0], rsa.RSAPublicKey)
+ assert captured[0].public_numbers() == key.public_key().public_numbers()
+ assert db.commit.await_count == _EXPECTED_CONTROLLER_COMMITS
def _form() -> dict[str, str]:
diff --git a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_userinfo_controller.py b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_userinfo_controller.py
index 4d380fe56..5f668c4e8 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/controllers/test_userinfo_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/controllers/test_userinfo_controller.py
@@ -2,25 +2,28 @@
from typing import Any
import pytest
+from fastapi import Request
+from sqlalchemy.ext.asyncio import AsyncSession
from module_admin.entity.do.user_do import SysUser
from module_identity.controller import token_controller as controller
from module_identity.dependencies import AccessTokenContext
from module_identity.service import token_protocol_service as service
+from tests.module_identity.support.http import make_request
_OK = 200
_NOT_FOUND = 404
_UNAUTHORIZED = 401
-def _request(redis: object | None = None) -> SimpleNamespace:
+def _request(redis: object | None = None) -> Request:
"""
构造 UserInfo 请求替身。
:param redis: 用于缓存或发布消息的 Redis 客户端
:return: UserInfo 请求替身
"""
- return SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=redis or object())))
+ return make_request(redis or object())
class _ActiveRedis:
@@ -132,7 +135,7 @@ async def test_userinfo_returns_only_minimal_claims(monkeypatch: pytest.MonkeyPa
'exp': 1,
},
)
- response = await controller.userinfo(_request(_ActiveRedis()), context, SimpleNamespace())
+ response = await controller.userinfo(_request(_ActiveRedis()), context, AsyncSession())
assert response.status_code == _OK
assert b'"sub":"subject-1"' in response.body
assert '数据库用户'.encode() in response.body
@@ -197,7 +200,7 @@ async def test_userinfo_uses_current_database_claims_not_token_claims(monkeypatc
'ver': 3,
},
)
- response = await controller.userinfo(_request(_ActiveRedis()), context, SimpleNamespace())
+ response = await controller.userinfo(_request(_ActiveRedis()), context, AsyncSession())
assert b'subject-1' in response.body
assert b'Forged Name' not in response.body
assert b'database-role' in response.body
@@ -246,7 +249,7 @@ async def exists(self, key: str) -> bool:
None if failure == 'session' else SimpleNamespace(user_id=2, subject_id='subject-1', auth_version=3)
),
)
- response = await controller.userinfo(_request(_Redis()), AccessTokenContext('token', claims), SimpleNamespace())
+ response = await controller.userinfo(_request(_Redis()), AccessTokenContext('token', claims), AsyncSession())
assert response.status_code == _UNAUTHORIZED
assert response.headers['www-authenticate'] == 'Bearer error="invalid_token"'
assert b'redis unavailable' not in response.body
@@ -256,7 +259,7 @@ async def exists(self, key: str) -> bool:
async def test_userinfo_disabled_is_local_not_found(monkeypatch: pytest.MonkeyPatch) -> None:
"""OIDC 关闭时 UserInfo 返回本地 404,不进入重定向流程。"""
monkeypatch.setattr(controller.OidcConfig, 'oidc_enabled', False)
- response = await controller.userinfo(_request(), SimpleNamespace(), SimpleNamespace())
+ response = await controller.userinfo(_request(), AccessTokenContext('token', {}), AsyncSession())
assert response.status_code == _NOT_FOUND
assert b'not_found' in response.body
diff --git a/ruoyi-fastapi-backend/tests/module_identity/dao/test_grant_policy_dao.py b/ruoyi-fastapi-backend/tests/module_identity/dao/test_grant_policy_dao.py
index 688f987f3..2ac77efba 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/dao/test_grant_policy_dao.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/dao/test_grant_policy_dao.py
@@ -46,6 +46,7 @@ async def test_valid_grant_requires_active_unexpired_and_current_client_policy(
assert await OAuthGrantDao.get_valid_for_user_client(data_session, 4101, 4101) is not None
grant = await OAuthGrantDao.get_active_for_user_client(data_session, 4101, 4101)
+ assert grant is not None
grant.expires_at = now - timedelta(seconds=1)
await data_session.flush()
assert await OAuthGrantDao.get_valid_for_user_client(data_session, 4101, 4101) is None
diff --git a/ruoyi-fastapi-backend/tests/module_identity/dao/test_oidc_key_dao.py b/ruoyi-fastapi-backend/tests/module_identity/dao/test_oidc_key_dao.py
index 4b9d80b76..56a719b82 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/dao/test_oidc_key_dao.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/dao/test_oidc_key_dao.py
@@ -3,7 +3,7 @@
import pytest
from sqlalchemy import event, select
-from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from module_identity.dao.oidc_key_dao import OidcKeyDao
from module_identity.entity.do.oidc_key_do import SysOidcSigningKey
@@ -57,12 +57,14 @@ def capture(
if statement.lstrip().upper().startswith(('UPDATE', 'SELECT')):
statements.append(statement.upper())
- event.listen(data_session.bind.sync_engine, 'before_cursor_execute', capture)
+ engine = data_session.bind
+ assert isinstance(engine, AsyncEngine)
+ event.listen(engine.sync_engine, 'before_cursor_execute', capture)
try:
assert await OidcKeyDao.activate(data_session, 'pending-a', 'RS256')
await data_session.flush()
finally:
- event.remove(data_session.bind.sync_engine, 'before_cursor_execute', capture)
+ event.remove(engine.sync_engine, 'before_cursor_execute', capture)
rows = (await data_session.execute(select(SysOidcSigningKey))).scalars().all()
assert [row.status for row in rows].count('active') == 1
diff --git a/ruoyi-fastapi-backend/tests/module_identity/dao/test_refresh_token_dao.py b/ruoyi-fastapi-backend/tests/module_identity/dao/test_refresh_token_dao.py
index 974c0756d..628728e6a 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/dao/test_refresh_token_dao.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/dao/test_refresh_token_dao.py
@@ -89,7 +89,9 @@ async def test_refresh_family_lock_rotation_and_reuse_distribution(data_session:
assert [token.token_id for token in family] == ['token-1', 'token-2']
injected_now = datetime(2026, 8, 24, 5, 6, 7, tzinfo=UTC)
assert await OAuthTokenDao.mark_used(data_session, 'token-1', 'token-2', now=injected_now)
- assert (await OAuthTokenDao.get_by_token_id(data_session, 'token-1')).last_used_at == injected_now
+ stored_token = await OAuthTokenDao.get_by_token_id(data_session, 'token-1')
+ assert stored_token is not None
+ assert stored_token.last_used_at == injected_now
changed = await OAuthTokenDao.refresh_token_family_reuse(data_session, 'family-1', 'token-1', now=injected_now)
assert changed == _REUSED_TOKEN_COUNT
await data_session.flush()
@@ -141,4 +143,6 @@ async def test_refresh_expire_due_handles_idle_and_absolute_expiry(data_session:
)
await data_session.flush()
assert await OAuthTokenDao.expire_due(data_session) == 1
- assert (await OAuthTokenDao.get_by_token_id(data_session, 'token-idle')).status == 'expired'
+ stored_token = await OAuthTokenDao.get_by_token_id(data_session, 'token-idle')
+ assert stored_token is not None
+ assert stored_token.status == 'expired'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/models/test_identity_models.py b/ruoyi-fastapi-backend/tests/module_identity/models/test_identity_models.py
index 674bb7d70..b83172b34 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/models/test_identity_models.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/models/test_identity_models.py
@@ -1,7 +1,7 @@
import hashlib
import pytest
-from sqlalchemy import CheckConstraint
+from sqlalchemy import CheckConstraint, String
from sqlalchemy.ext.asyncio import AsyncSession
from module_identity.entity.do.identity_subject_do import SysIdentitySubject
@@ -37,7 +37,7 @@ def test_all_identity_tables_are_registered() -> None:
'sys_oauth_audit_log',
}
actual = {
- model.__table__.name
+ model.get_table().name
for model in (
SysIdentitySubject,
SysOAuthClient,
@@ -59,26 +59,30 @@ def test_all_identity_tables_are_registered() -> None:
def test_identity_constraints_and_indexes_are_security_relevant() -> None:
"""断言主体、URI、Refresh Token 和密钥的唯一性/外键/索引存在。"""
- subject = SysIdentitySubject.__table__
+ subject = SysIdentitySubject.get_table()
assert {'uk_identity_subject_user', 'uk_identity_subject_subject'} <= {
constraint.name for constraint in subject.constraints if constraint.name
}
assert any(fk.name == 'fk_identity_subject_user' and fk.ondelete == 'RESTRICT' for fk in subject.foreign_keys)
- uri = SysOAuthClientUri.__table__
+ uri = SysOAuthClientUri.get_table()
assert 'uri_hash' in uri.c
assert 'uk_oauth_client_uri_hash' in {constraint.name for constraint in uri.constraints if constraint.name}
assert any(index.name == 'idx_oauth_client_uri_type' for index in uri.indexes)
- refresh = SysOAuthRefreshToken.__table__
+ refresh = SysOAuthRefreshToken.get_table()
+ assert isinstance(refresh.c.token_hash.type, String)
assert refresh.c.token_hash.type.length == _HASH_HEX_LENGTH
- assert SysSsoSession.__table__.c.session_secret_hash.type.length == _HASH_HEX_LENGTH
- assert SysSsoSession.__table__.c.user_agent_hash.type.length == _HASH_HEX_LENGTH
+ for column in (SysSsoSession.get_table().c.session_secret_hash, SysSsoSession.get_table().c.user_agent_hash):
+ assert isinstance(column.type, String)
+ assert column.type.length == _HASH_HEX_LENGTH
assert 'uk_oauth_refresh_token_hash' in {constraint.name for constraint in refresh.constraints if constraint.name}
assert any(index.name == 'idx_oauth_refresh_family' for index in refresh.indexes)
key_constraints = [
- constraint for constraint in SysOidcSigningKey.__table__.constraints if isinstance(constraint, CheckConstraint)
+ constraint
+ for constraint in SysOidcSigningKey.get_table().constraints
+ if isinstance(constraint, CheckConstraint)
]
assert any(constraint.name == 'ck_oidc_signing_key_private_material' for constraint in key_constraints)
@@ -91,8 +95,8 @@ def test_client_update_by_is_not_datetime_updated_automatically() -> None:
def test_client_scope_relationships_have_only_named_composite_primary_keys() -> None:
"""断言关系表元数据与 migration 使用一致的复合主键。"""
- scope_table = SysOAuthClientScope.__table__
- resource_table = SysOAuthClientResource.__table__
+ scope_table = SysOAuthClientScope.get_table()
+ resource_table = SysOAuthClientResource.get_table()
assert scope_table.primary_key.name == 'pk_oauth_client_scope'
assert resource_table.primary_key.name == 'pk_oauth_client_resource'
assert 'pk_oauth_client_scope' not in {index.name for index in scope_table.indexes}
diff --git a/ruoyi-fastapi-backend/tests/module_identity/models/test_oidc_key_vo.py b/ruoyi-fastapi-backend/tests/module_identity/models/test_oidc_key_vo.py
index e860a6e22..2377faf89 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/models/test_oidc_key_vo.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/models/test_oidc_key_vo.py
@@ -12,8 +12,8 @@ def test_public_jwk_rejects_private_rsa_parameters() -> None:
OidcKeyViewModel(
kid='key-1',
status='active',
- publishAt='2026-01-01T00:00:00Z',
- publicJwk={
+ publish_at='2026-01-01T00:00:00Z',
+ public_jwk={
'kty': 'RSA',
'use': 'sig',
'kid': 'key-1',
@@ -26,14 +26,14 @@ def test_public_jwk_rejects_private_rsa_parameters() -> None:
@pytest.mark.parametrize('value', ['2026-08-28 10:00:00', datetime(2026, 8, 28, 10, 0)])
-def test_rotation_request_rejects_missing_timezone(value: object) -> None:
+def test_rotation_request_rejects_missing_timezone(value: datetime | str) -> None:
"""轮换请求拒绝缺少时区的时间。"""
with pytest.raises(ValidationError):
- OidcKeyRotateModel(kid='key-1', publishAt=value)
+ OidcKeyRotateModel(kid='key-1', publish_at=value)
def test_rotation_request_normalizes_offset_to_utc() -> None:
"""轮换请求将带偏移的时刻转换为 UTC。"""
- model = OidcKeyRotateModel(kid='key-1', publishAt='2026-08-28T10:00:00+08:00')
+ model = OidcKeyRotateModel(kid='key-1', publish_at='2026-08-28T10:00:00+08:00')
assert model.publish_at == datetime(2026, 8, 28, 2, 0, tzinfo=UTC)
assert model.model_dump(mode='json', by_alias=True)['publishAt'] == '2026-08-28T02:00:00.000Z'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/models/test_protocol_vo.py b/ruoyi-fastapi-backend/tests/module_identity/models/test_protocol_vo.py
index d20682aa9..bed65c45c 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/models/test_protocol_vo.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/models/test_protocol_vo.py
@@ -102,12 +102,12 @@ def test_token_request_limits_untrusted_form_string_lengths() -> None:
def test_audit_query_supports_owner_and_time_filters() -> None:
"""审计查询支持按所有者和时间过滤。"""
query = AuditPageQueryModel(
- clientId='external-client',
- userId=_AUDIT_USER_ID,
- startTime='2026-01-01T00:00:00Z',
- endTime='2026-01-02T00:00:00Z',
+ client_id='external-client',
+ user_id=_AUDIT_USER_ID,
+ start_time='2026-01-01T00:00:00Z',
+ end_time='2026-01-02T00:00:00Z',
)
assert query.client_id == 'external-client'
assert query.user_id == _AUDIT_USER_ID
with pytest.raises(ValidationError):
- AuditPageQueryModel(startTime='2026-01-02T00:00:00Z', endTime='2026-01-01T00:00:00Z')
+ AuditPageQueryModel(start_time='2026-01-02T00:00:00Z', end_time='2026-01-01T00:00:00Z')
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_client_auth.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_client_auth.py
index 9a98dbdc9..305c68f98 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_client_auth.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_client_auth.py
@@ -139,7 +139,7 @@ def test_client_pkce_grant_and_uri_policy() -> None:
'backchannel_logout_uris': ['https://client.example/backchannel'],
'cors_origins': ['https://client.example:8443'],
}
- assert ClientCreateModel(**valid).cors_origins == ['https://client.example:8443']
+ assert ClientCreateModel.model_validate(valid).cors_origins == ['https://client.example:8443']
for field in ('redirect_uris', 'post_logout_redirect_uris', 'backchannel_logout_uris', 'cors_origins'):
with pytest.raises(ValueError):
- ClientCreateModel(**{**valid, field: ['https://user:password@client.example/callback']})
+ ClientCreateModel.model_validate({**valid, field: ['https://user:password@client.example/callback']})
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_identity_dependencies.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_identity_dependencies.py
index 3283cd8aa..9f4cc8978 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_identity_dependencies.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_identity_dependencies.py
@@ -5,7 +5,9 @@
import jwt
import pytest
from cryptography.hazmat.primitives.asymmetric import rsa
-from fastapi import HTTPException
+from fastapi import FastAPI, HTTPException
+from fastapi.routing import APIRoute
+from sqlalchemy.ext.asyncio import AsyncSession
from starlette.requests import Request
from exceptions.exception import OAuthProtocolException
@@ -118,7 +120,7 @@ async def test_access_key_helper_rejects_remote_key_header(monkeypatch: pytest.M
headers={'kid': 'kid-1', 'typ': 'at+jwt', 'jku': 'https://evil.example/jwks'},
)
with pytest.raises(dependencies.JwtProfileError):
- await dependencies.load_access_verification_key(token, object())
+ await dependencies.load_access_verification_key(token, AsyncSession())
@pytest.mark.asyncio
@@ -161,7 +163,7 @@ async def test_userinfo_accepts_case_insensitive_scheme_without_changing_token(
'headers': [(b'authorization', f'{scheme} {token}'.encode())],
}
)
- context = await dependencies.get_oidc_access_token(request, object())
+ context = await dependencies.get_oidc_access_token(request, AsyncSession())
assert context.token == token
assert context.claims['sub'] == 'subject-1'
@@ -180,7 +182,7 @@ async def test_userinfo_rejects_other_schemes_and_missing_space(monkeypatch: pyt
}
)
with pytest.raises(HTTPException) as raised:
- await dependencies.get_oidc_access_token(request, object())
+ await dependencies.get_oidc_access_token(request, AsyncSession())
assert raised.value.status_code == _UNAUTHORIZED
@@ -201,9 +203,9 @@ async def invalid(*args: object, **kwargs: object) -> object:
raise OAuthProtocolException('invalid_client', 'Client authentication failed', 401)
monkeypatch.setattr(dependencies.TokenService, 'authenticate_client', invalid)
- request = SimpleNamespace(headers={})
+ request = Request({'type': 'http', 'headers': []})
with pytest.raises(HTTPException) as raised:
- await dependencies.get_oidc_client(request, object())
+ await dependencies.get_oidc_client(request, AsyncSession())
assert raised.value.status_code == _UNAUTHORIZED
assert raised.value.headers == {'WWW-Authenticate': 'Basic realm="oauth2/token"'}
@@ -216,6 +218,7 @@ def test_protocol_routers_have_no_legacy_preauth_dependency() -> None:
for dependency in route.dependencies
)
for route in token_controller.routes
+ if isinstance(route, APIRoute)
)
@@ -231,9 +234,9 @@ async def test_protocol_readiness_dependency_returns_503_without_active_key(
'cached_readiness',
lambda *args: _async(not_ready),
)
- request = SimpleNamespace(app=SimpleNamespace())
+ request = Request({'type': 'http', 'app': FastAPI()})
with pytest.raises(OAuthProtocolException) as raised:
- await dependencies.require_oidc_protocol_ready(request, object())
+ await dependencies.require_oidc_protocol_ready(request, AsyncSession())
assert raised.value.error == 'temporarily_unavailable'
assert raised.value.status_code == _SERVICE_UNAVAILABLE
@@ -242,6 +245,7 @@ def test_invalid_token_challenge_is_standard_bearer() -> None:
"""Access Token 依赖的失败响应不泄漏验签细节。"""
error = dependencies._invalid_token()
assert error.status_code == _UNAUTHORIZED
+ assert error.headers is not None
assert error.headers['WWW-Authenticate'] == 'Bearer error="invalid_token"'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_jwt_profile.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_jwt_profile.py
index 58035a692..a3662d40d 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_jwt_profile.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_jwt_profile.py
@@ -18,7 +18,7 @@
@pytest.fixture()
-def key_pair() -> tuple[object, object]:
+def key_pair() -> tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey]:
"""
生成用于令牌测试的临时 RSA 密钥对。
@@ -37,7 +37,9 @@ def _now() -> int:
return int(datetime.now(UTC).timestamp())
-def test_access_profile_requires_at_jwt_and_checks_audience(key_pair: tuple[object, object]) -> None:
+def test_access_profile_requires_at_jwt_and_checks_audience(
+ key_pair: tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey],
+) -> None:
"""访问令牌校验要求 at+jwt 并检查受众。"""
private, public = key_pair
now = _now()
@@ -69,7 +71,9 @@ def test_access_profile_requires_at_jwt_and_checks_audience(key_pair: tuple[obje
decode_access_token(token, verification_key=public, issuer='https://other.example', audience='resource-a')
-def test_id_token_cannot_be_used_as_access_token_and_leeway_is_forwarded(key_pair: tuple[object, object]) -> None:
+def test_id_token_cannot_be_used_as_access_token_and_leeway_is_forwarded(
+ key_pair: tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey],
+) -> None:
"""拒绝将身份令牌当作访问令牌并传递允许的时间偏差。"""
private, public = key_pair
now = _now()
@@ -98,7 +102,9 @@ def test_id_token_cannot_be_used_as_access_token_and_leeway_is_forwarded(key_pai
encode_id_token({key: value for key, value in claims.items() if key != 'nonce'}, private, 'key-1')
-def test_wrong_algorithm_kid_and_numeric_types_are_rejected(key_pair: tuple[object, object]) -> None:
+def test_wrong_algorithm_kid_and_numeric_types_are_rejected(
+ key_pair: tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey],
+) -> None:
"""拒绝错误的算法、密钥标识及数值类型。"""
private, public = key_pair
now = _now()
@@ -142,7 +148,7 @@ def test_wrong_algorithm_kid_and_numeric_types_are_rejected(key_pair: tuple[obje
decode_access_token(unsafe_header, verification_key=public, issuer=claims['iss'], audience='r')
-def test_signed_non_finite_numeric_date_is_rejected(key_pair: tuple[object, object]) -> None:
+def test_signed_non_finite_numeric_date_is_rejected(key_pair: tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey]) -> None:
"""拒绝签名中非有限的数值日期。"""
private, public = key_pair
now = _now()
@@ -162,7 +168,7 @@ def test_signed_non_finite_numeric_date_is_rejected(key_pair: tuple[object, obje
def test_access_profile_requires_gty_and_rejects_machine_user_field_confusion(
- key_pair: tuple[object, object],
+ key_pair: tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey],
) -> None:
"""Access Profile 强制 gty,并隔离机器与用户绑定字段。"""
private, public = key_pair
@@ -202,7 +208,9 @@ def test_access_profile_requires_gty_and_rejects_machine_user_field_confusion(
)
-def test_logout_profile_requires_event_and_non_empty_sid_or_sub(key_pair: tuple[object, object]) -> None:
+def test_logout_profile_requires_event_and_non_empty_sid_or_sub(
+ key_pair: tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey],
+) -> None:
"""注销令牌必须含注销事件及非空的会话或主体标识。"""
private, public = key_pair
now = _now()
@@ -247,7 +255,7 @@ def test_logout_profile_requires_event_and_non_empty_sid_or_sub(key_pair: tuple[
],
)
def test_logout_profile_rejects_invalid_signed_claims(
- key_pair: tuple[object, object], changes: dict[str, object]
+ key_pair: tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey], changes: dict[str, object]
) -> None:
"""即使 RSA 签名有效,也必须拒绝错误的退出事件、身份绑定和时效声明。"""
private, public = key_pair
@@ -267,7 +275,9 @@ def test_logout_profile_rejects_invalid_signed_claims(
@pytest.mark.parametrize('expiry', [None, 'future', True, 0, -1])
-def test_logout_profile_rejects_missing_invalid_or_expired_exp(key_pair: tuple[object, object], expiry: object) -> None:
+def test_logout_profile_rejects_missing_invalid_or_expired_exp(
+ key_pair: tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey], expiry: object
+) -> None:
"""接收方拒绝缺失、类型错误或过期的退出令牌。"""
private, public = key_pair
claims = {
diff --git a/ruoyi-fastapi-backend/tests/module_identity/security/test_redis_keys.py b/ruoyi-fastapi-backend/tests/module_identity/security/test_redis_keys.py
index 2e0e66ce3..55fa9ef80 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/security/test_redis_keys.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/security/test_redis_keys.py
@@ -1,3 +1,5 @@
+from collections.abc import Callable
+
import pytest
from module_identity.redis_keys import OidcRedisKey
@@ -30,8 +32,6 @@ def test_sensitive_identifiers_use_independent_32_byte_pepper() -> None:
with pytest.raises(ValueError):
OidcUtil.hash_sensitive_identifier('user@example.com', 'short')
- with pytest.raises(TypeError):
- OidcUtil.hash_sensitive_identifier('user@example.com', 123) # type: ignore[arg-type]
@pytest.mark.parametrize('value', ['../escape', 'space value', 'a' * 129])
@@ -45,5 +45,13 @@ def test_digest_components_must_be_sha256_hex() -> None:
"""摘要组件必须使用 SHA-256 十六进制格式。"""
with pytest.raises(ValueError):
OidcRedisKey.sso_cookie('not-a-digest')
+
+
+@pytest.mark.parametrize(
+ ('operation', 'args'),
+ [(OidcUtil.hash_sensitive_identifier, ('user@example.com', 123)), (OidcRedisKey.sso_cookie, (123,))],
+)
+def test_identifier_helpers_reject_non_string_input(operation: Callable[..., str], args: tuple[object, ...]) -> None:
+ """敏感标识和摘要键遇到类型错误的输入时抛出类型异常。"""
with pytest.raises(TypeError):
- OidcRedisKey.sso_cookie(123) # type: ignore[arg-type]
+ operation(*args)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_audit_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_audit_service.py
index dc574ed56..0f34e42cf 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_audit_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_audit_service.py
@@ -1,3 +1,4 @@
+from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
from io import BytesIO
from types import SimpleNamespace
@@ -15,6 +16,7 @@
from module_identity.entity.do.oauth_audit_do import SysOAuthAuditArchive, SysOAuthAuditLog
from module_identity.entity.vo.oauth_session_vo import AuditPageQueryModel
from module_identity.service.audit_service import AuditService
+from tests.module_identity.support.sessions import RecordingSession
from utils.oidc_util import OidcUtil
_ADMIN_EVENT_ID = 7
@@ -26,7 +28,7 @@
@pytest_asyncio.fixture
-async def audit_session() -> AsyncSession:
+async def audit_session() -> AsyncIterator[AsyncSession]:
"""
创建只包含审计表的真实 SQLite 会话。
@@ -37,7 +39,7 @@ async def audit_session() -> AsyncSession:
await connection.run_sync(
lambda sync_connection: Base.metadata.create_all(
sync_connection,
- tables=[SysOAuthAuditLog.__table__, SysOAuthAuditArchive.__table__],
+ tables=[SysOAuthAuditLog.get_table(), SysOAuthAuditArchive.get_table()],
)
)
factory = async_sessionmaker(engine, expire_on_commit=False)
@@ -177,8 +179,8 @@ async def count_admin(*args: object, **kwargs: object) -> int:
monkeypatch.setattr(OAuthAuditDao, 'count_admin', count_admin)
query = AuditPageQueryModel(page_num=2, page_size=_ADMIN_PAGE_SIZE, client_id='client-1')
- rows, total = await AuditService.list_admin_page(SimpleNamespace(), query)
- exported = await AuditService.export_admin(SimpleNamespace(), query)
+ rows, total = await AuditService.list_admin_page(AsyncSession(), query)
+ exported = await AuditService.export_admin(AsyncSession(), query)
assert total == _ADMIN_TOTAL
assert rows[0]['auditId'] == _ADMIN_EVENT_ID
@@ -230,21 +232,6 @@ async def test_audit_export_serializes_stored_utc_in_request_timezone(
async def test_interaction_failure_audit_rolls_back_and_wraps_failure(monkeypatch: pytest.MonkeyPatch) -> None:
"""交互失败审计保持双重回滚和统一异常包装语义。"""
- class _Db:
- """
- 模拟当前测试所需的数据库操作。
-
- :ivar rollbacks: 测试中记录的回滚次数
- """
-
- def __init__(self) -> None:
- """初始化测试夹具的 ``rollbacks``。"""
- self.rollbacks = 0
-
- async def rollback(self) -> None:
- """累加 ``rollbacks`` 供后续断言检查。"""
- self.rollbacks += 1
-
async def fail(*args: object, **kwargs: object) -> object:
"""
模拟此操作抛出 RuntimeError 的情形。
@@ -256,7 +243,7 @@ async def fail(*args: object, **kwargs: object) -> object:
raise RuntimeError('audit unavailable')
monkeypatch.setattr(AuditService, 'record_independent', fail)
- db = _Db()
+ db = RecordingSession()
with pytest.raises(OidcInteractionException) as raised:
await AuditService.record_interaction_failure(db, 'login_failed', failure_code='invalid_credentials')
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_authentication_regressions.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_authentication_regressions.py
index 145d4c135..a255a7dd5 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_authentication_regressions.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_authentication_regressions.py
@@ -1,6 +1,7 @@
from datetime import timedelta
from http.cookies import SimpleCookie
from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock
from urllib.parse import parse_qs, urlsplit
from uuid import uuid4
@@ -97,7 +98,7 @@ async def auth_flow(data_session: AsyncSession, monkeypatch: pytest.MonkeyPatch)
connection = await data_session.connection()
await connection.run_sync(
lambda sync: SysUser.metadata.create_all(
- sync, tables=[SysDept.__table__, SysRole.__table__, SysUserRole.__table__]
+ sync, tables=[SysDept.get_table(), SysRole.get_table(), SysUserRole.get_table()]
)
)
user = SysUser(user_id=2001, user_name='alice', nick_name='Alice', status='0', del_flag='0')
@@ -193,7 +194,7 @@ async def auth_flow(data_session: AsyncSession, monkeypatch: pytest.MonkeyPatch)
coordinator = AfterCommitCoordinator()
cookie, session = await SsoSessionService.create(
data_session,
- redis,
+ redis.client,
user.user_id,
subject.subject_id,
subject.auth_version,
@@ -243,7 +244,7 @@ def _authorize_request(flow: SimpleNamespace, *, offline: bool = False) -> dict[
async def _user_token(
flow: SimpleNamespace, *, remember: bool = False, offline: bool = False
-) -> tuple[TokenResult, SysOAuthGrant | None]:
+) -> tuple[TokenResult, SysOAuthGrant]:
"""
通过真实同意和授权码流程签发用户令牌。
@@ -252,7 +253,7 @@ async def _user_token(
:param offline: 是否使用离线资源
:return: 已签发的用户令牌与对应的授权记录
"""
- request = AuthorizeRequest(**_authorize_request(flow, offline=offline))
+ request = AuthorizeRequest.model_validate(_authorize_request(flow, offline=offline))
context = await AuthorizationService.validate_request(flow.db, request)
consent = await ConsentService.submit_consent(
flow.db,
@@ -263,6 +264,7 @@ async def _user_token(
user_id=flow.user.user_id,
subject_id=flow.subject.subject_id,
)
+ assert consent.grant is not None
code = await AuthorizationCodeService.issue(
flow.redis,
{
@@ -272,7 +274,7 @@ async def _user_token(
'subjectId': flow.subject.subject_id,
'authVersion': flow.subject.auth_version,
'sid': flow.session.sid,
- 'grantId': consent.grant.grant_id if consent.grant is not None else None,
+ 'grantId': consent.grant.grant_id,
'scopes': list(consent.scopes),
'resources': [flow.resource.audience],
'nonce': request.nonce,
@@ -334,7 +336,7 @@ async def _introspect(flow: SimpleNamespace, token: str) -> dict[str, object]:
)
-def _claims(flow: SimpleNamespace, token: str) -> dict[str, object]:
+def _claims(flow: SimpleNamespace, token: str) -> dict[str, Any]:
"""
验证 Access Token 的签名、Issuer 和 Resource Audience。
@@ -375,7 +377,7 @@ async def test_one_time_consent_has_revocable_grant_without_remembering_consent(
assert _claims(auth_flow, token.access_token)['grant_id'] == grant.grant_id
assert await auth_flow.db.scalar(select(func.count()).select_from(SysOAuthGrant)) == 1
context = await AuthorizationService.validate_request(
- auth_flow.db, AuthorizeRequest(**_authorize_request(auth_flow))
+ auth_flow.db, AuthorizeRequest.model_validate(_authorize_request(auth_flow))
)
assert not ConsentService.consent_is_satisfied(context, grant)
result = await _introspect(auth_flow, token.access_token)
@@ -441,6 +443,7 @@ async def test_saved_grant_revocation_cannot_be_bypassed_by_a_later_grant(
with pytest.raises(ValueError, match='授权已失效'):
await UserInfoService.build(auth_flow.db, _claims(auth_flow, token.access_token), auth_flow.redis)
if offline:
+ assert token.refresh_token is not None
assert await _introspect(auth_flow, token.refresh_token) == {'active': False}
with pytest.raises(OAuthProtocolException) as error:
await TokenService.refresh_token(
@@ -614,7 +617,9 @@ async def test_login_cookie_persistence_survives_forced_password_change(
) -> None:
"""普通登录及强制改密后的 Cookie 持久化行为均遵守保持登录选项。"""
flow = auth_flow
- context = await AuthorizationService.validate_request(flow.db, AuthorizeRequest(**_authorize_request(flow)))
+ context = await AuthorizationService.validate_request(
+ flow.db, AuthorizeRequest.model_validate(_authorize_request(flow))
+ )
created = await InteractionService.create(flow.redis, context.to_internal_payload('cookie-test'), pepper=_PEPPER)
flow.user.password = PwdUtil.get_password_hash('old-password')
await flow.db.commit()
@@ -636,7 +641,7 @@ async def test_login_cookie_persistence_survives_forced_password_change(
outcome = await InteractionLoginService.login(
flow.redis,
created.interaction_id,
- InteractionLoginModel(userName='alice', password='old-password', rememberMe=remember),
+ InteractionLoginModel(user_name='alice', password='old-password', remember_me=remember),
flow.db,
created.csrf_token,
)
@@ -647,9 +652,9 @@ async def test_login_cookie_persistence_survives_forced_password_change(
flow.redis,
created.interaction_id,
ChangePasswordModel(
- oldPassword='old-password',
- newPassword='new-password-A1!',
- confirmPassword='new-password-A1!',
+ old_password='old-password',
+ new_password='new-password-A1!',
+ confirm_password='new-password-A1!',
),
flow.db,
created.csrf_token,
@@ -678,7 +683,9 @@ async def test_block_and_unblock_require_new_authorization(auth_flow: SimpleName
flow = auth_flow
token, grant = await _user_token(flow, offline=offline)
client_id, user_id, grant_id = flow.app.client_id, flow.user.user_id, grant.grant_id
- context = await AuthorizationService.validate_request(flow.db, AuthorizeRequest(**_authorize_request(flow)))
+ context = await AuthorizationService.validate_request(
+ flow.db, AuthorizeRequest.model_validate(_authorize_request(flow))
+ )
code_payload = {
'clientPk': flow.app.client_pk,
'redirectUri': context.redirect_uri,
@@ -729,8 +736,9 @@ async def test_block_and_unblock_require_new_authorization(auth_flow: SimpleName
)
assert error.value.error == 'invalid_grant'
if offline:
+ assert token.refresh_token is not None
assert await _introspect(flow, token.refresh_token) == {'active': False}
- rows, total = await OAuthSessionManagementService.list_grants(flow.db, GrantPageQueryModel(accessStatus='blocked'))
+ rows, total = await OAuthSessionManagementService.list_grants(flow.db, GrantPageQueryModel(access_status='blocked'))
assert total == 1 and rows[0].access_status == 'blocked' and rows[0].access_reason == '禁止访问'
assert await OAuthSessionManagementService.set_access(flow.db, user_id, client_id, False, 'admin', '解除禁止') == 0
assert await _introspect(flow, token.access_token) == {'active': False}
@@ -790,7 +798,7 @@ async def test_batch_revoke_covers_all_grants_for_selected_user_client(auth_flow
granted_scopes=list(grant.granted_scopes),
granted_resources=list(grant.granted_resources),
client_policy_version=flow.app.policy_version,
- remembered_scopes=list(grant.remembered_scopes),
+ remembered_scopes=list(grant.remembered_scopes or []),
status='active',
)
other_user = SysUser(user_id=2002, user_name='bob', nick_name='Bob', status='0', del_flag='0')
@@ -844,7 +852,9 @@ async def test_interactive_completion_binds_a_grant(auth_flow: SimpleNamespace,
flow = auth_flow
flow.app.require_consent = int(confirm)
await flow.db.commit()
- context = await AuthorizationService.validate_request(flow.db, AuthorizeRequest(**_authorize_request(flow)))
+ context = await AuthorizationService.validate_request(
+ flow.db, AuthorizeRequest.model_validate(_authorize_request(flow))
+ )
payload = context.to_internal_payload('pending')
payload.update(
{
@@ -859,7 +869,7 @@ async def test_interactive_completion_binds_a_grant(auth_flow: SimpleNamespace,
await InteractionConsentService.consent(
flow.redis,
created.interaction_id,
- InteractionConsentModel(approved=True, scopes=list(context.scopes), rememberConsent=False),
+ InteractionConsentModel(approved=True, scopes=list(context.scopes), remember_consent=False),
flow.db,
created.csrf_token,
)
@@ -893,7 +903,9 @@ async def test_revocation_between_consent_and_completion_prevents_code(
) -> None:
"""同意后、签码前发生撤销或禁止,不得继续发码或复用授权记录。"""
flow = auth_flow
- context = await AuthorizationService.validate_request(flow.db, AuthorizeRequest(**_authorize_request(flow)))
+ context = await AuthorizationService.validate_request(
+ flow.db, AuthorizeRequest.model_validate(_authorize_request(flow))
+ )
payload = context.to_internal_payload('pending')
payload.update(
{
@@ -907,7 +919,7 @@ async def test_revocation_between_consent_and_completion_prevents_code(
await InteractionConsentService.consent(
flow.redis,
created.interaction_id,
- InteractionConsentModel(approved=True, scopes=list(context.scopes), rememberConsent=False),
+ InteractionConsentModel(approved=True, scopes=list(context.scopes), remember_consent=False),
flow.db,
created.csrf_token,
)
@@ -917,7 +929,9 @@ async def test_revocation_between_consent_and_completion_prevents_code(
flow.db, flow.user.user_id, flow.app.client_id, True, 'admin', '禁止'
)
else:
- await OAuthSessionManagementService.revoke_grants(flow.db, [record['grantId']], 'admin', '撤销')
+ grant_id = record.get('grantId')
+ assert grant_id is not None
+ await OAuthSessionManagementService.revoke_grants(flow.db, [grant_id], 'admin', '撤销')
issue = AsyncMock()
monkeypatch.setattr(AuthorizationCodeService, 'issue', issue)
with pytest.raises(OAuthProtocolException) as error:
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_code_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_code_service.py
index 9af7b23d8..870ab151b 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_code_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_code_service.py
@@ -44,7 +44,7 @@ def _payload(**overrides: object) -> dict[str, object]:
async def test_issue_uses_ac_key_nx_ttl_and_never_stores_plain_code() -> None:
"""验证授权码使用独立 key、NX/TTL,并只保存摘要。"""
redis = FakeRedis()
- code = await AuthorizationCodeService.issue(redis, _payload(), ttl_seconds=90, pepper=_PEPPER)
+ code = await AuthorizationCodeService.issue(redis.client, _payload(), ttl_seconds=90, pepper=_PEPPER)
assert code.startswith('ac1.')
key = OidcRedisKey.authorization_code(code.split('.')[1])
stored = redis.values[key][0]
@@ -55,11 +55,11 @@ async def test_issue_uses_ac_key_nx_ttl_and_never_stores_plain_code() -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('ttl', [0, False, -1])
-async def test_issue_rejects_explicit_invalid_ttl(ttl: object) -> None:
+async def test_issue_rejects_explicit_invalid_ttl(ttl: int) -> None:
"""验证显式零值、布尔值和负数不会回退到默认 Code TTL。"""
redis = FakeRedis()
with pytest.raises(ValueError):
- await AuthorizationCodeService.issue(redis, _payload(), ttl_seconds=ttl, pepper=_PEPPER) # type: ignore[arg-type]
+ await AuthorizationCodeService.issue(redis.client, _payload(), ttl_seconds=ttl, pepper=_PEPPER)
assert not redis.values
@@ -67,21 +67,23 @@ async def test_issue_rejects_explicit_invalid_ttl(ttl: object) -> None:
async def test_wrong_secret_does_not_consume_and_correct_secret_consumes_once() -> None:
"""验证错误 Secret 不删除 Code,正确消费具备一次性语义。"""
redis = FakeRedis()
- code = await AuthorizationCodeService.issue(redis, _payload(), pepper=_PEPPER)
+ code = await AuthorizationCodeService.issue(redis.client, _payload(), pepper=_PEPPER)
parts = code.split('.')
replacement = 'A' if parts[2][0] != 'A' else 'B'
wrong = f'{parts[0]}.{parts[1]}.{replacement}{parts[2][1:]}'
with pytest.raises(OAuthProtocolException) as raised:
- await AuthorizationCodeService.consume(redis, wrong, pepper=_PEPPER)
+ await AuthorizationCodeService.consume(redis.client, wrong, pepper=_PEPPER)
assert raised.value.error == 'invalid_grant'
assert await redis.get(OidcRedisKey.authorization_code(parts[1])) is not None
assert await redis.get(OidcRedisKey.authorization_code_consumed(parts[1])) is None
- consumed = await AuthorizationCodeService.consume(redis, code, pepper=_PEPPER)
+ consumed = await AuthorizationCodeService.consume(redis.client, code, pepper=_PEPPER)
assert consumed['clientPk'] == _CLIENT_PK
assert await redis.get(OidcRedisKey.authorization_code_consumed(parts[1])) == 'consumed'
- assert (await AuthorizationCodeService.consumed_payload(redis, code, pepper=_PEPPER))['grantId'] == 'grant-2001'
+ payload = await AuthorizationCodeService.consumed_payload(redis.client, code, pepper=_PEPPER)
+ assert payload is not None
+ assert payload['grantId'] == 'grant-2001'
with pytest.raises(OAuthProtocolException) as reused:
- await AuthorizationCodeService.consume(redis, code, pepper=_PEPPER)
+ await AuthorizationCodeService.consume(redis.client, code, pepper=_PEPPER)
assert isinstance(reused.value, AuthorizationCodeReuseError)
@@ -92,9 +94,9 @@ async def test_reuse_tombstone_ttl_covers_long_authorization_code_ttl(
"""验证授权码 TTL 超过最小墓碑 TTL 时,重用墓碑覆盖完整 Code 生命周期。"""
monkeypatch.setattr(OidcConfig, 'oidc_authorization_code_ttl_seconds', _LONG_CODE_TTL)
redis = FakeRedis()
- code = await AuthorizationCodeService.issue(redis, _payload(), pepper=_PEPPER)
+ code = await AuthorizationCodeService.issue(redis.client, _payload(), pepper=_PEPPER)
- await AuthorizationCodeService.consume(redis, code, pepper=_PEPPER)
+ await AuthorizationCodeService.consume(redis.client, code, pepper=_PEPPER)
assert redis.eval_calls[-1][1][-1] == _LONG_CODE_TTL
@@ -103,10 +105,10 @@ async def test_reuse_tombstone_ttl_covers_long_authorization_code_ttl(
async def test_concurrent_correct_consumption_only_succeeds_once() -> None:
"""验证两个并发正确消费请求只有一个能取得载荷。"""
redis = FakeRedis()
- code = await AuthorizationCodeService.issue(redis, _payload(), pepper=_PEPPER)
+ code = await AuthorizationCodeService.issue(redis.client, _payload(), pepper=_PEPPER)
results = await asyncio.gather(
- AuthorizationCodeService.consume(redis, code, pepper=_PEPPER),
- AuthorizationCodeService.consume(redis, code, pepper=_PEPPER),
+ AuthorizationCodeService.consume(redis.client, code, pepper=_PEPPER),
+ AuthorizationCodeService.consume(redis.client, code, pepper=_PEPPER),
return_exceptions=True,
)
assert sum(isinstance(result, dict) for result in results) == 1
@@ -119,11 +121,13 @@ async def test_invalid_payload_and_format_fail_closed_without_redis_write() -> N
"""验证缺失、未知对象和畸形 Code 均 fail closed。"""
redis = FakeRedis()
with pytest.raises(ValueError):
- await AuthorizationCodeService.issue(redis, _payload(extra='unknown'), pepper=_PEPPER)
+ await AuthorizationCodeService.issue(redis.client, _payload(extra='unknown'), pepper=_PEPPER)
with pytest.raises(ValueError):
- await AuthorizationCodeService.issue(redis, _payload(scopes=['openid'], codeChallenge='short'), pepper=_PEPPER)
+ await AuthorizationCodeService.issue(
+ redis.client, _payload(scopes=['openid'], codeChallenge='short'), pepper=_PEPPER
+ )
with pytest.raises(OAuthProtocolException) as raised:
- await AuthorizationCodeService.consume(redis, 'ac1.invalid.short', pepper=_PEPPER)
+ await AuthorizationCodeService.consume(redis.client, 'ac1.invalid.short', pepper=_PEPPER)
assert raised.value.error == 'invalid_grant'
assert not redis.values
@@ -132,11 +136,11 @@ async def test_invalid_payload_and_format_fail_closed_without_redis_write() -> N
async def test_expired_code_is_invalid_grant() -> None:
"""验证 Redis TTL 到期后返回统一 invalid_grant。"""
redis = FakeRedis()
- code = await AuthorizationCodeService.issue(redis, _payload(), ttl_seconds=1, pepper=_PEPPER)
+ code = await AuthorizationCodeService.issue(redis.client, _payload(), ttl_seconds=1, pepper=_PEPPER)
key = OidcRedisKey.authorization_code(code.split('.')[1])
redis.values[key] = (redis.values[key][0], 0)
with pytest.raises(OAuthProtocolException) as raised:
- await AuthorizationCodeService.consume(redis, code, pepper=_PEPPER)
+ await AuthorizationCodeService.consume(redis.client, code, pepper=_PEPPER)
assert raised.value.error == 'invalid_grant'
assert await redis.get(OidcRedisKey.authorization_code_consumed(code.split('.')[1])) is None
@@ -146,21 +150,21 @@ async def test_invalid_auth_time_and_duplicate_lists_are_rejected() -> None:
"""验证授权码时间必须为 UTC,Scope/Resource 列表不得重复。"""
redis = FakeRedis()
with pytest.raises(ValueError):
- await AuthorizationCodeService.issue(redis, _payload(authTime='2026-08-24T04:00:00'), pepper=_PEPPER)
+ await AuthorizationCodeService.issue(redis.client, _payload(authTime='2026-08-24T04:00:00'), pepper=_PEPPER)
with pytest.raises(ValueError):
- await AuthorizationCodeService.issue(redis, _payload(scopes=['openid', 'openid']), pepper=_PEPPER)
+ await AuthorizationCodeService.issue(redis.client, _payload(scopes=['openid', 'openid']), pepper=_PEPPER)
with pytest.raises(ValueError):
- await AuthorizationCodeService.issue(redis, _payload(resources=['api', 'api']), pepper=_PEPPER)
+ await AuthorizationCodeService.issue(redis.client, _payload(resources=['api', 'api']), pepper=_PEPPER)
@pytest.mark.asyncio
async def test_consumed_corrupt_payload_is_invalid_grant() -> None:
"""验证 Lua 已删除但载荷校验失败仍返回统一 OAuth 错误。"""
redis = FakeRedis()
- code = await AuthorizationCodeService.issue(redis, _payload(), pepper=_PEPPER)
+ code = await AuthorizationCodeService.issue(redis.client, _payload(), pepper=_PEPPER)
key = OidcRedisKey.authorization_code(code.split('.')[1])
value, expiry = redis.values[key]
redis.values[key] = (value.replace('"authTime":"2026-08-24T04:00:00+00:00"', '"authTime":"bad"'), expiry)
with pytest.raises(OAuthProtocolException) as raised:
- await AuthorizationCodeService.consume(redis, code, pepper=_PEPPER)
+ await AuthorizationCodeService.consume(redis.client, code, pepper=_PEPPER)
assert raised.value.error == 'invalid_grant'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_service.py
index 8aa1cbfc3..16a04c1a6 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_authorization_service.py
@@ -41,7 +41,7 @@ def _request(**overrides: object) -> AuthorizeRequest:
'code_challenge_method': 'S256',
}
values.update(overrides)
- return AuthorizeRequest(**values)
+ return AuthorizeRequest.model_validate(values)
async def _seed_authorization_data(db: AsyncSession, *, second_resource_scope: bool = False) -> None:
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_consent_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_consent_service.py
index 3b84327f9..c86edf7d0 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_consent_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_consent_service.py
@@ -178,6 +178,7 @@ async def test_remember_consent_merges_grant_without_commit(data_session: AsyncS
user_id=8001,
subject_id='subject-8001',
)
+ assert updated.grant is not None and result.grant is not None
assert updated.grant.grant_id == result.grant.grant_id
assert set(updated.grant.granted_scopes) == set(context.scopes)
assert ConsentService.consent_is_satisfied(context, updated.grant) is remembered
@@ -281,7 +282,8 @@ async def test_compensation_does_not_revoke_concurrently_updated_new_grant(data_
session_factory = async_sessionmaker(data_session.bind, expire_on_commit=False)
async with session_factory() as concurrent_session:
await concurrent_session.execute(
- SysOAuthGrant.__table__.update()
+ SysOAuthGrant.get_table()
+ .update()
.where(SysOAuthGrant.grant_id == grant.grant_id)
.values(granted_scopes=['openid', 'admin'], subject_id='concurrent-subject')
)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_credential_authentication_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_credential_authentication_service.py
index c996bb422..2367a3978 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_credential_authentication_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_credential_authentication_service.py
@@ -1,8 +1,11 @@
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, Mock, patch
import pytest
+from fastapi import Request
+from redis.asyncio import Redis
+from sqlalchemy.ext.asyncio import AsyncSession
from common.enums import RedisInitKeyConfig
from config.env import OidcConfig
@@ -14,6 +17,7 @@
CredentialAuthenticationError,
CredentialAuthenticationService,
)
+from tests.module_identity.support.http import make_request
from utils.oidc_util import OidcUtil
from utils.pwd_util import PwdUtil
@@ -25,6 +29,7 @@ class _Redis:
"""
记录认证服务访问的 Redis 最小异步替身。
+ :ivar client: 供被测服务调用的异步 Redis 客户端替身
:ivar values: 当前处理的值集合
:ivar eval_values: 用于模拟 Redis 脚本结果的值
:ivar get_calls: 记录 ``get`` 的调用情况
@@ -40,6 +45,7 @@ def __init__(self, values: dict[str, object] | None = None, eval_values: list[ob
:param values: 当前处理的值集合
:param eval_values: 用于模拟 Redis 脚本结果的值
"""
+ self.client: Redis = Mock(spec_set=Redis, wraps=self)
self.values = values or {}
self.eval_values = list(eval_values or [])
self.get_calls: list[str] = []
@@ -106,9 +112,13 @@ async def eval(self, script: str, count: int, *keys_and_args: object) -> object:
if "redis.call('incr'" not in script:
return self.eval_values.pop(0) if self.eval_values else None
failure_key, lock_key, threshold, _ttl = keys_and_args
+ assert isinstance(failure_key, str) and isinstance(lock_key, str)
+ assert isinstance(threshold, (str, int))
if self.values.get(lock_key):
return -1
- current = int(self.values.get(failure_key, 0)) + 1
+ previous = self.values.get(failure_key, 0)
+ assert isinstance(previous, (str, int))
+ current = int(previous) + 1
if current > int(threshold):
self.values.pop(failure_key, None)
self.values[lock_key] = '1'
@@ -117,19 +127,15 @@ async def eval(self, script: str, count: int, *keys_and_args: object) -> object:
return current
-def _request(redis: _Redis, *, host: str = '127.0.0.1') -> SimpleNamespace:
+def _request(redis: _Redis, *, host: str = '127.0.0.1') -> Request:
"""
- 创建测试使用的 ``SimpleNamespace`` 实例。
+ 创建携带测试缓存的请求。
:param redis: 模拟测试所需的 Redis 命令
:param host: 连接目标或插件宿主上下文
- :return: 测试使用的 ``SimpleNamespace`` 实例
+ :return: 测试请求
"""
- return SimpleNamespace(
- app=SimpleNamespace(state=SimpleNamespace(redis=redis)),
- client=SimpleNamespace(host=host),
- headers={},
- )
+ return make_request(redis.client, host=host)
def _user(user_name: str = 'alice', *, status: str = '0', update_date: object = None) -> SimpleNamespace:
@@ -163,7 +169,9 @@ async def test_oidc_unknown_user_and_wrong_password_are_equivalent_and_dummy_ver
patch.object(PwdUtil, 'verify_password', return_value=False) as verify,
pytest.raises(CredentialAuthenticationError) as unknown,
):
- await CredentialAuthenticationService.authenticate_oidc(redis, object(), user_name='alice', password='wrong')
+ await CredentialAuthenticationService.authenticate_oidc(
+ redis.client, AsyncSession(), user_name='alice', password='wrong'
+ )
verify.assert_called_once_with('wrong', '$2b$12$ySHJfAWxzh49cIc7M5L21e5GlPyA7QhE2GkLn9XuUTqmKIRqhWIja')
redis_keys = [item[0] for item in redis.set_calls]
assert unknown.value.reason == 'invalid_credentials'
@@ -179,7 +187,9 @@ async def test_oidc_unknown_user_and_wrong_password_are_equivalent_and_dummy_ver
patch.object(PwdUtil, 'verify_password', return_value=False),
pytest.raises(CredentialAuthenticationError) as wrong,
):
- await CredentialAuthenticationService.authenticate_oidc(redis, object(), user_name='alice', password='wrong')
+ await CredentialAuthenticationService.authenticate_oidc(
+ redis.client, AsyncSession(), user_name='alice', password='wrong'
+ )
assert wrong.value.reason == unknown.value.reason
assert str(wrong.value) == str(unknown.value) == '账号或密码错误'
@@ -198,8 +208,8 @@ async def test_oidc_captcha_is_atomically_consumed_and_success_does_not_write_le
patch.object(PwdUtil, 'verify_password', return_value=True),
):
result = await CredentialAuthenticationService.authenticate_oidc(
- redis,
- object(),
+ redis.client,
+ AsyncSession(),
user_name='alice',
password='correct',
code='1234',
@@ -211,8 +221,8 @@ async def test_oidc_captcha_is_atomically_consumed_and_success_does_not_write_le
assert result.remember_me is True
with pytest.raises(CredentialAuthenticationError) as replay:
await CredentialAuthenticationService.authenticate_oidc(
- redis,
- object(),
+ redis.client,
+ AsyncSession(),
user_name='alice',
password='correct',
code='1234',
@@ -238,7 +248,9 @@ async def test_oidc_disabled_user_is_rejected() -> None:
patch.object(PwdUtil, 'verify_password', return_value=True),
pytest.raises(CredentialAuthenticationError) as exc_info,
):
- await CredentialAuthenticationService.authenticate_oidc(redis, object(), user_name='alice', password='correct')
+ await CredentialAuthenticationService.authenticate_oidc(
+ redis.client, AsyncSession(), user_name='alice', password='correct'
+ )
assert exc_info.value.reason == expected_reason
@@ -260,7 +272,7 @@ async def test_oidc_initial_and_expired_password_flags_handle_naive_and_aware_da
patch.object(PwdUtil, 'verify_password', return_value=True),
):
result = await CredentialAuthenticationService.authenticate_oidc(
- redis, object(), user_name='alice', password='correct'
+ redis.client, AsyncSession(), user_name='alice', password='correct'
)
assert result.password_change_required is True
assert result.password_change_reason == 'initial_password'
@@ -280,7 +292,7 @@ async def test_oidc_expired_aware_password_is_reported_without_datetime_error()
patch.object(PwdUtil, 'verify_password', return_value=True),
):
result = await CredentialAuthenticationService.authenticate_oidc(
- redis, object(), user_name='alice', password='correct'
+ redis.client, AsyncSession(), user_name='alice', password='correct'
)
assert result.password_change_required is True
assert result.password_change_reason == 'password_expired'
@@ -301,7 +313,9 @@ async def test_oidc_hashed_error_state_locks_without_plain_username() -> None:
):
digest = OidcUtil.hash_sensitive_identifier('alice', 'p' * 32)
redis.values[OidcRedisKey.login_user_rate_limit(digest)] = 5
- await CredentialAuthenticationService.authenticate_oidc(redis, object(), user_name='alice', password='wrong')
+ await CredentialAuthenticationService.authenticate_oidc(
+ redis.client, AsyncSession(), user_name='alice', password='wrong'
+ )
assert exc_info.value.reason == 'account_locked'
assert all('alice' not in key for key, _, _ in redis.set_calls)
@@ -319,7 +333,9 @@ async def test_oidc_error_counter_uses_atomic_incr_expire_and_lock_script() -> N
patch.object(PwdUtil, 'verify_password', return_value=False),
pytest.raises(CredentialAuthenticationError),
):
- await CredentialAuthenticationService.authenticate_oidc(redis, object(), user_name='alice', password='wrong')
+ await CredentialAuthenticationService.authenticate_oidc(
+ redis.client, AsyncSession(), user_name='alice', password='wrong'
+ )
script, key_count, arguments = redis.eval_calls[-1]
assert "redis.call('incr'" in script
assert "redis.call('expire'" in script
@@ -336,9 +352,9 @@ async def test_oidc_failure_script_stays_locked_after_atomic_lock_transition() -
lock_key = f'{failure_key}:lock'
redis.values[failure_key] = 5
with pytest.raises(CredentialAuthenticationError) as first:
- await CredentialAuthenticationService._record_oidc_password_error(redis, failure_key, lock_key)
+ await CredentialAuthenticationService._record_oidc_password_error(redis.client, failure_key, lock_key)
with pytest.raises(CredentialAuthenticationError) as second:
- await CredentialAuthenticationService._record_oidc_password_error(redis, failure_key, lock_key)
+ await CredentialAuthenticationService._record_oidc_password_error(redis.client, failure_key, lock_key)
assert first.value.reason == 'account_locked'
assert second.value.reason == 'account_locked'
assert failure_key not in redis.values
@@ -359,7 +375,7 @@ async def test_legacy_success_and_wrong_password_keep_legacy_keys_and_messages()
patch.object(PwdUtil, 'verify_password', return_value=True),
):
result = await LoginService.authenticate_user(
- _request(redis), object(), UserLogin(userName='alice', password='correct', captchaEnabled=False)
+ _request(redis), AsyncSession(), UserLogin(user_name='alice', password='correct', captcha_enabled=False)
)
assert result[0] is user
assert f'{RedisInitKeyConfig.PASSWORD_ERROR_COUNT.key}:alice' in redis.delete_calls
@@ -375,7 +391,7 @@ async def test_legacy_success_and_wrong_password_keep_legacy_keys_and_messages()
pytest.raises(LoginException) as exc_info,
):
await LoginService.authenticate_user(
- _request(redis), object(), UserLogin(userName='alice', password='wrong', captchaEnabled=False)
+ _request(redis), AsyncSession(), UserLogin(user_name='alice', password='wrong', captcha_enabled=False)
)
assert exc_info.value.message == '密码错误'
assert any(key == 'password_error_count:alice' for key, _, _ in redis.set_calls)
@@ -393,7 +409,7 @@ async def test_legacy_unknown_user_keeps_message_and_does_not_create_error_key()
pytest.raises(LoginException) as exc_info,
):
await LoginService.authenticate_user(
- _request(redis), object(), UserLogin(userName='alice', password='wrong', captchaEnabled=False)
+ _request(redis), AsyncSession(), UserLogin(user_name='alice', password='wrong', captcha_enabled=False)
)
assert exc_info.value.message == '用户不存在'
assert not any(key.startswith('password_error_count:') for key, _, _ in redis.set_calls)
@@ -411,7 +427,7 @@ async def test_legacy_lock_captcha_and_blacklist_keep_original_messages_and_keys
pytest.raises(LoginException) as locked,
):
await LoginService.authenticate_user(
- _request(lock_redis), object(), UserLogin(userName='alice', password='wrong', captchaEnabled=False)
+ _request(lock_redis), AsyncSession(), UserLogin(user_name='alice', password='wrong', captcha_enabled=False)
)
assert locked.value.message == '账号已锁定,请稍后再试'
login_by_account.assert_not_awaited()
@@ -427,8 +443,8 @@ async def test_legacy_lock_captcha_and_blacklist_keep_original_messages_and_keys
):
await LoginService.authenticate_user(
_request(captcha_redis),
- object(),
- UserLogin(userName='alice', password='wrong', code='1', uuid='u', captchaEnabled=True),
+ AsyncSession(),
+ UserLogin(user_name='alice', password='wrong', code='1', uuid='u', captcha_enabled=True),
)
assert captcha_error.value.message == '验证码已失效'
login_by_account.assert_not_awaited()
@@ -443,7 +459,7 @@ async def test_legacy_lock_captcha_and_blacklist_keep_original_messages_and_keys
pytest.raises(LoginException) as ip_error,
):
await LoginService.authenticate_user(
- _request(ip_redis), object(), UserLogin(userName='alice', password='wrong', captchaEnabled=False)
+ _request(ip_redis), AsyncSession(), UserLogin(user_name='alice', password='wrong', captcha_enabled=False)
)
assert ip_error.value.message == '当前IP禁止登录'
login_by_account.assert_not_awaited()
@@ -452,7 +468,7 @@ async def test_legacy_lock_captcha_and_blacklist_keep_original_messages_and_keys
@pytest.mark.asyncio
async def test_legacy_service_delegates_and_maps_original_login_exception() -> None:
"""旧版服务委托登录并映射原有登录异常。"""
- login_user = UserLogin(userName='alice', password='wrong', captchaEnabled=False)
+ login_user = UserLogin(user_name='alice', password='wrong', captcha_enabled=False)
request = _request(_Redis())
with (
patch.object(
@@ -462,5 +478,5 @@ async def test_legacy_service_delegates_and_maps_original_login_exception() -> N
),
pytest.raises(LoginException) as exc_info,
):
- await LoginService.authenticate_user(request, object(), login_user)
+ await LoginService.authenticate_user(request, AsyncSession(), login_user)
assert exc_info.value.message == '密码错误'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_security_event_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_security_event_service.py
index 807f5bb6c..18cb14dc4 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_security_event_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_security_event_service.py
@@ -1,3 +1,4 @@
+from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
import pytest
@@ -23,7 +24,7 @@
@pytest_asyncio.fixture
-async def security_session() -> AsyncSession:
+async def security_session() -> AsyncIterator[AsyncSession]:
"""
创建身份安全事件涉及表的真实异步数据库会话。
@@ -31,12 +32,12 @@ async def security_session() -> AsyncSession:
"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
tables = [
- SysUser.__table__,
- SysUserRole.__table__,
- SysIdentitySubject.__table__,
- SysSsoSession.__table__,
- SysOAuthRefreshToken.__table__,
- SysOAuthAuditLog.__table__,
+ SysUser.get_table(),
+ SysUserRole.get_table(),
+ SysIdentitySubject.get_table(),
+ SysSsoSession.get_table(),
+ SysOAuthRefreshToken.get_table(),
+ SysOAuthAuditLog.get_table(),
]
async with engine.begin() as connection:
await connection.run_sync(lambda sync_connection: Base.metadata.create_all(sync_connection, tables=tables))
@@ -121,7 +122,9 @@ async def test_password_change_increments_version_and_keeps_only_current_session
)
assert result.revoked_sessions == 1
assert result.revoked_refresh_tokens == _PASSWORD_REFRESH_COUNT
- assert (await security_session.get(SysIdentitySubject, 1)).auth_version == _INITIAL_VERSION + 1
+ subject = await security_session.get(SysIdentitySubject, 1)
+ assert subject is not None
+ assert subject.auth_version == _INITIAL_VERSION + 1
sessions = (await security_session.execute(select(SysSsoSession).order_by(SysSsoSession.sid))).scalars().all()
assert [row.status for row in sessions] == ['active', 'revoked']
tokens = (
@@ -131,6 +134,7 @@ async def test_password_change_increments_version_and_keeps_only_current_session
)
assert all(row.status == 'revoked' for row in tokens)
audit = (await security_session.execute(select(SysOAuthAuditLog))).scalar_one()
+ assert audit.detail is not None
assert audit.detail['event'] == 'password_changed'
assert audit.detail['actor'] == 'admin'
assert audit.risk_level == 'high'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_subject_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_subject_service.py
index af6ef094e..08a32981d 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_subject_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_identity_subject_service.py
@@ -1,3 +1,4 @@
+from collections.abc import AsyncIterator
from pathlib import Path
import pytest
@@ -21,7 +22,7 @@
@pytest_asyncio.fixture
-async def service_session(tmp_path: Path) -> AsyncSession:
+async def service_session(tmp_path: Path) -> AsyncIterator[AsyncSession]:
"""
创建只包含主体服务所需表的真实 SQLite 会话。
@@ -29,7 +30,7 @@ async def service_session(tmp_path: Path) -> AsyncSession:
:yield: 只包含主体服务所需表的真实 SQLite 会话
"""
engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "subject-service.sqlite3"}')
- tables = [SysUser.__table__, SysIdentitySubject.__table__, SysOAuthAuditLog.__table__]
+ tables = [SysUser.get_table(), SysIdentitySubject.get_table(), SysOAuthAuditLog.get_table()]
async with engine.begin() as connection:
await connection.run_sync(lambda sync_connection: Base.metadata.create_all(sync_connection, tables=tables))
factory = async_sessionmaker(engine, expire_on_commit=False)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_interaction_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_interaction_service.py
index f3443d088..440ef3228 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_interaction_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_interaction_service.py
@@ -3,6 +3,8 @@
from unittest.mock import AsyncMock
import pytest
+from pydantic import TypeAdapter
+from sqlalchemy.ext.asyncio import AsyncSession
from exceptions.exception import OidcInteractionException
from module_identity.dao.oauth_client_dao import OAuthClientDao
@@ -47,8 +49,8 @@ def _payload(**overrides: object) -> dict[str, object]:
async def test_create_uses_nx_ttl_and_returns_csrf_only_once() -> None:
"""验证 Interaction 创建使用 NX/TTL,Redis 仅存 csrfHash。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), ttl_seconds=300, pepper=_PEPPER)
- record = await InteractionService.get_record(redis, created.interaction_id)
+ created = await InteractionService.create(redis.client, _payload(), ttl_seconds=300, pepper=_PEPPER)
+ record = await InteractionService.get_record(redis.client, created.interaction_id)
csrf = created.csrf_token
key = OidcRedisKey.interaction(created.interaction_id)
stored = redis.values[key][0]
@@ -57,17 +59,17 @@ async def test_create_uses_nx_ttl_and_returns_csrf_only_once() -> None:
assert 'csrfHash' in stored
assert csrf not in stored
assert redis.set_calls[-1][1] == {'ex': 300, 'nx': True}
- page = await InteractionService.get(redis, created.interaction_id, object())
+ page = await InteractionService.get(redis.client, created.interaction_id, AsyncSession())
assert page['expiresIn'] > 0
@pytest.mark.asyncio
@pytest.mark.parametrize('ttl', [0, False, -1])
-async def test_create_rejects_explicit_invalid_ttl(ttl: object) -> None:
+async def test_create_rejects_explicit_invalid_ttl(ttl: int) -> None:
"""验证显式零值、布尔值和负数不会回退到默认 TTL。"""
redis = FakeRedis()
with pytest.raises(ValueError):
- await InteractionService.create(redis, _payload(), ttl_seconds=ttl, pepper=_PEPPER) # type: ignore[arg-type]
+ await InteractionService.create(redis.client, _payload(), ttl_seconds=ttl, pepper=_PEPPER)
assert not redis.values
@@ -76,8 +78,8 @@ async def test_create_rejects_explicit_invalid_ttl(ttl: object) -> None:
async def test_page_projection_never_leaks_internal_protocol_fields() -> None:
"""验证页面载荷不包含 Redirect、协议绑定、用户或 CSRF 内部字段。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
- page = await InteractionService.get(redis, created.interaction_id, object())
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
+ page = await InteractionService.get(redis.client, created.interaction_id, AsyncSession())
forbidden = {
'redirectUri',
'state',
@@ -110,12 +112,12 @@ async def test_page_projection_never_leaks_internal_protocol_fields() -> None:
async def test_csrf_is_constant_time_verified_and_not_rotated_by_read() -> None:
"""验证 CSRF 正确匹配、错误拒绝,读取页面不会重新建立 Token。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
- record = await InteractionService.get_record(redis, created.interaction_id)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
+ record = await InteractionService.get_record(redis.client, created.interaction_id)
csrf = created.csrf_token
assert InteractionService.verify_csrf(record, csrf, pepper=_PEPPER) is True
assert InteractionService.verify_csrf(record, csrf + 'x', pepper=_PEPPER) is False
- await InteractionService.get(redis, created.interaction_id, object())
+ await InteractionService.get(redis.client, created.interaction_id, AsyncSession())
assert InteractionService.verify_csrf(record, csrf, pepper=_PEPPER) is True
@@ -123,16 +125,22 @@ async def test_csrf_is_constant_time_verified_and_not_rotated_by_read() -> None:
async def test_transition_uses_lua_cas_and_rejects_illegal_rollback() -> None:
"""验证状态流转保留 TTL,非法回退和终态回退均拒绝。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
- updated = await InteractionService.transition(redis, created.interaction_id, {'awaiting_login'}, 'awaiting_consent')
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
+ updated = await InteractionService.transition(
+ redis.client, created.interaction_id, {'awaiting_login'}, 'awaiting_consent'
+ )
assert updated['nextAction'] == 'consent'
assert redis.eval_calls
with pytest.raises(ValueError):
- await InteractionService.transition(redis, created.interaction_id, {'awaiting_consent'}, 'awaiting_login')
- completed = await InteractionService.transition(redis, created.interaction_id, {'awaiting_consent'}, 'completed')
+ await InteractionService.transition(
+ redis.client, created.interaction_id, {'awaiting_consent'}, 'awaiting_login'
+ )
+ completed = await InteractionService.transition(
+ redis.client, created.interaction_id, {'awaiting_consent'}, 'completed'
+ )
assert completed['nextAction'] == 'redirect'
with pytest.raises(ValueError):
- await InteractionService.transition(redis, created.interaction_id, {'completed'}, 'denied')
+ await InteractionService.transition(redis.client, created.interaction_id, {'completed'}, 'denied')
@pytest.mark.asyncio
@@ -140,12 +148,12 @@ async def test_prompt_none_fails_without_interactive_creation() -> None:
"""验证 prompt=none 不登录时返回 login_required,不写入交互状态。"""
redis = FakeRedis()
with pytest.raises(OidcInteractionException) as raised:
- await InteractionService.create(redis, _payload(prompt='none'), pepper=_PEPPER)
+ await InteractionService.create(redis.client, _payload(prompt='none'), pepper=_PEPPER)
assert raised.value.error == 'login_required'
assert not redis.values
with pytest.raises(OidcInteractionException) as raised:
- await InteractionService.create(redis, _payload(prompt='none', authenticatedSid='sid-1'), pepper=_PEPPER)
+ await InteractionService.create(redis.client, _payload(prompt='none', authenticatedSid='sid-1'), pepper=_PEPPER)
assert raised.value.error == 'consent_required'
assert not redis.values
@@ -155,33 +163,33 @@ async def test_initial_status_respects_sso_prompt_and_consent() -> None:
"""验证已有 SSO、prompt 和同意要求共同决定初始状态。"""
redis = FakeRedis()
created = await InteractionService.create(
- redis, _payload(prompt=None, authenticatedSid='sid-1', consentRequired=True), pepper=_PEPPER
+ redis.client, _payload(prompt=None, authenticatedSid='sid-1', consentRequired=True), pepper=_PEPPER
)
assert created.initial_status == 'awaiting_consent'
login = await InteractionService.create(
- redis, _payload(prompt='login', authenticatedSid='sid-2', consentRequired=False), pepper=_PEPPER
+ redis.client, _payload(prompt='login', authenticatedSid='sid-2', consentRequired=False), pepper=_PEPPER
)
assert login.initial_status == 'awaiting_login'
silent = await InteractionService.create(
- redis, _payload(prompt='none', authenticatedSid='sid-3', consentRequired=False), pepper=_PEPPER
+ redis.client, _payload(prompt='none', authenticatedSid='sid-3', consentRequired=False), pepper=_PEPPER
)
assert silent.initial_status == 'completed'
- assert (await InteractionService.get_record(redis, silent.interaction_id))['status'] == 'completed'
+ assert (await InteractionService.get_record(redis.client, silent.interaction_id))['status'] == 'completed'
@pytest.mark.asyncio
async def test_record_validation_and_missing_ttl_fail_closed() -> None:
"""验证损坏记录和永久键不会进入状态机。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
key = OidcRedisKey.interaction(created.interaction_id)
value, _ = redis.values[key]
corrupted = value.replace('"version":1', '"version":-1')
redis.values[key] = (corrupted, None)
with pytest.raises(OidcInteractionException) as raised:
- await InteractionService.get(redis, created.interaction_id, object())
+ await InteractionService.get(redis.client, created.interaction_id, AsyncSession())
assert raised.value.error == 'invalid_request'
assert key not in redis.values
@@ -190,7 +198,7 @@ async def test_record_validation_and_missing_ttl_fail_closed() -> None:
async def test_transition_rejects_interaction_without_ttl(monkeypatch: pytest.MonkeyPatch) -> None:
"""服务层将 Redis CAS 返回的无 TTL 哨兵转换为协议错误并清理键。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
key = OidcRedisKey.interaction(created.interaction_id)
value, _ = redis.values[key]
redis.values[key] = (value, None)
@@ -203,11 +211,13 @@ async def get_record(*_args: object, **_kwargs: object) -> dict[str, object]:
:param _kwargs: 调用方按名称传入的附加选项
:return: 从缓存中解码的交互记录
"""
- return json.loads(value)
+ return TypeAdapter(dict[str, object]).validate_json(value)
monkeypatch.setattr(InteractionService, '_get_record', classmethod(get_record))
with pytest.raises(OidcInteractionException, match='认证交互有效期无效'):
- await InteractionService.transition(redis, created.interaction_id, {'awaiting_login'}, 'awaiting_consent')
+ await InteractionService.transition(
+ redis.client, created.interaction_id, {'awaiting_login'}, 'awaiting_consent'
+ )
assert key not in redis.values
@@ -216,11 +226,11 @@ async def test_transition_rejects_duplicate_scope_and_incomplete_identity() -> N
"""验证创建和状态更新不接受重复 Scope 或不完整身份三元组。"""
redis = FakeRedis()
with pytest.raises(ValueError):
- await InteractionService.create(redis, _payload(scopes=['openid', 'openid']), pepper=_PEPPER)
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
+ await InteractionService.create(redis.client, _payload(scopes=['openid', 'openid']), pepper=_PEPPER)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
with pytest.raises(ValueError):
await InteractionService.transition(
- redis, created.interaction_id, {'awaiting_login'}, 'awaiting_consent', {'userId': 1}
+ redis.client, created.interaction_id, {'awaiting_login'}, 'awaiting_consent', {'userId': 1}
)
@@ -238,10 +248,10 @@ def test_max_age_decision_uses_project_local_time() -> None:
async def test_page_rejects_removed_application_or_scope(monkeypatch: pytest.MonkeyPatch, change: str) -> None:
"""请求创建后停用应用或移除权限时,不继续展示陈旧授权选项。"""
redis = FakeRedis()
- created = await InteractionService.create(redis, _payload(), pepper=_PEPPER)
+ created = await InteractionService.create(redis.client, _payload(), pepper=_PEPPER)
if change == 'client_disabled':
monkeypatch.setattr(OAuthClientDao, 'get_by_pk', AsyncMock(return_value=None))
else:
monkeypatch.setattr(OAuthClientDao, 'list_scopes', AsyncMock(return_value=[]))
with pytest.raises(OidcInteractionException):
- await InteractionService.get(redis, created.interaction_id, object())
+ await InteractionService.get(redis.client, created.interaction_id, AsyncSession())
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_introspection_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_introspection_service.py
index a02cda946..fb2c9e971 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_introspection_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_introspection_service.py
@@ -1,7 +1,9 @@
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
+from typing import Any
import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
from config.env import OidcConfig
from module_identity.dao.oauth_access_policy_dao import OAuthAccessPolicyDao
@@ -69,9 +71,10 @@ def _principal(client_type: str = 'confidential') -> OAuthClientPrincipal:
@pytest.mark.asyncio
-async def test_introspection_rejects_non_client_principal(monkeypatch: pytest.MonkeyPatch) -> None:
+@pytest.mark.parametrize('invalid_principal', [object()])
+async def test_introspection_rejects_non_client_principal(invalid_principal: Any) -> None:
"""任意用户主体或普通对象都不能调用内省端点。"""
- result = await IntrospectionService.introspect(object(), FakeRedis(), 'not-a-token', object())
+ result = await IntrospectionService.introspect(AsyncSession(), FakeRedis().client, 'not-a-token', invalid_principal)
assert result == {'active': False}
@@ -91,7 +94,7 @@ async def client_lookup(*_args: object, **_kwargs: object) -> SimpleNamespace:
return _client('public')
monkeypatch.setattr('module_identity.service.token_protocol_service.OAuthClientDao.get_by_client_id', client_lookup)
- result = await IntrospectionService.introspect(object(), FakeRedis(), 'not-a-token', _principal())
+ result = await IntrospectionService.introspect(AsyncSession(), FakeRedis().client, 'not-a-token', _principal())
assert result == {'active': False}
@@ -123,7 +126,7 @@ async def test_introspection_auth_method_pair_is_exact(
)
result = await IntrospectionService._resolve_caller(
- object(), OAuthClientPrincipal('introspector', principal_type, principal_method)
+ AsyncSession(), OAuthClientPrincipal('introspector', principal_type, principal_method)
)
assert (result is not None) is expected
@@ -169,7 +172,7 @@ async def client_lookup(*_args: object, **_kwargs: object) -> SimpleNamespace:
await redis.set('oidc:revoked_jti:jti-1', '1', ex=60)
result = await IntrospectionService.introspect(
- object(), redis, 'signed-access', _principal(), now=datetime.now(UTC)
+ AsyncSession(), redis.client, 'signed-access', _principal(), now=datetime.now(UTC)
)
assert result == {'active': False}
@@ -216,7 +219,7 @@ async def client_lookup(_db: object, client_id: str, active_only: bool = True) -
monkeypatch.setattr(IntrospectionService, '_resources_owned_by_caller', lambda *_args, **_kwargs: _async_true())
monkeypatch.setattr(IntrospectionService, '_client_allows_access', lambda *_args, **_kwargs: _async_true())
monkeypatch.setattr(IntrospectionService, '_access_user_state', lambda *_args, **_kwargs: _async_user())
- result = await IntrospectionService.introspect(object(), FakeRedis(), 'signed-access', _principal())
+ result = await IntrospectionService.introspect(AsyncSession(), FakeRedis().client, 'signed-access', _principal())
assert result['active'] is True
assert result['client_id'] == 'business-a'
@@ -262,7 +265,7 @@ async def client_lookup(_db: object, client_id: str, active_only: bool = True) -
)
monkeypatch.setattr(IntrospectionService, '_resources_owned_by_caller', lambda *_args, **_kwargs: _async_false())
- result = await IntrospectionService.introspect(object(), FakeRedis(), 'signed-access', _principal())
+ result = await IntrospectionService.introspect(AsyncSession(), FakeRedis().client, 'signed-access', _principal())
assert result == {'active': False}
@@ -276,7 +279,7 @@ async def test_access_user_state_rejects_each_real_time_failure(
subject = SimpleNamespace(subject_id='subject-a', user_id=7, auth_version=3)
user = SimpleNamespace(status='0', del_flag='0', user_name='alice')
session = SimpleNamespace(user_id=7, subject_id='subject-a', auth_version=3)
- db = object()
+ db = AsyncSession()
if invalid_state == 'subject':
subject = None
elif invalid_state == 'user':
@@ -347,7 +350,7 @@ async def client_lookup(_db: object, client_id: str, active_only: bool = True) -
monkeypatch.setattr(IntrospectionService, '_resources_owned_by_caller', lambda *_args, **_kwargs: _async_true())
monkeypatch.setattr(IntrospectionService, '_client_allows_access', lambda *_args, **_kwargs: _async_true())
- result = await IntrospectionService.introspect(object(), FakeRedis(), 'machine-access', _principal())
+ result = await IntrospectionService.introspect(AsyncSession(), FakeRedis().client, 'machine-access', _principal())
assert result['active'] is True
@@ -367,7 +370,7 @@ async def client_lookup(*_args: object, **_kwargs: object) -> SimpleNamespace:
return _client()
monkeypatch.setattr('module_identity.service.token_protocol_service.OAuthClientDao.get_by_client_id', client_lookup)
- result = await IntrospectionService.introspect(object(), FakeRedis(), 'rt1.token-id', _principal())
+ result = await IntrospectionService.introspect(AsyncSession(), FakeRedis().client, 'rt1.token-id', _principal())
assert result == {'active': False}
@@ -436,13 +439,13 @@ async def test_refresh_introspection_rechecks_identity_session_grant_and_resourc
'module_identity.service.token_protocol_service.SsoSessionDao.get_active',
_lookup(SimpleNamespace(subject_id='subject-7', user_id=7, auth_version=session_auth_version)),
)
- db = object()
+ db = AsyncSession()
monkeypatch.setattr(
'module_identity.service.token_protocol_service.IntrospectionService._resources_owned_by_caller',
lambda *_args, **_kwargs: _async_true(),
)
- result = await IntrospectionService.introspect(db, FakeRedis(), token, _principal(), now=now)
+ result = await IntrospectionService.introspect(db, FakeRedis().client, token, _principal(), now=now)
assert result['active'] is (session_auth_version == _AUTH_VERSION)
if session_auth_version == _AUTH_VERSION:
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_key_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_key_service.py
index 638cc6a24..add70eed2 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_key_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_key_service.py
@@ -1,3 +1,4 @@
+from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
from pathlib import Path
from types import SimpleNamespace
@@ -13,25 +14,26 @@
from common.constant import OidcAuditEvent
from config.database import Base
-from config.env import OidcConfig
+from config.env import OidcConfig, OidcSettings
from module_identity.dao.oidc_key_dao import OidcKeyDao
from module_identity.entity.do.oauth_audit_do import SysOAuthAuditLog
from module_identity.entity.do.oidc_key_do import SysOidcSigningKey
from module_identity.service.key_service import KeyService, KeyServiceError, OidcKeyManagementService
+from tests.module_identity.support.sessions import RecordingSession
from utils.oidc_util import OidcUtil
_MIN_TEST_RSA_BITS = 2048
@pytest_asyncio.fixture
-async def data_session() -> AsyncSession:
+async def data_session() -> AsyncIterator[AsyncSession]:
"""
仅创建密钥和审计表,隔离项目其他 ORM 的 SQLite 方言差异。
:yield: 当前操作共用的会话
"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
- tables = [SysOidcSigningKey.__table__, SysOAuthAuditLog.__table__]
+ tables = [SysOidcSigningKey.get_table(), SysOAuthAuditLog.get_table()]
async with engine.begin() as connection:
await connection.run_sync(lambda sync_connection: Base.metadata.create_all(sync_connection, tables=tables))
session_factory = async_sessionmaker(engine, expire_on_commit=False)
@@ -64,7 +66,7 @@ def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(OidcConfig, name, value)
-def _config() -> OidcConfig:
+def _config() -> OidcSettings:
"""
返回当前测试使用的全局 OIDC 配置。
@@ -116,7 +118,7 @@ async def test_key_lifecycle_rejects_unsafe_kid_before_database_access(kid: str)
"""激活、退役和删除入口统一拒绝无法安全放入路径的 kid。"""
for operation in (KeyService.activate_key, KeyService.retire_key, KeyService.delete_key):
with pytest.raises(KeyServiceError, match='包含不允许的字符'):
- await operation(object(), kid)
+ await operation(AsyncSession(), kid)
@pytest.mark.asyncio
@@ -124,27 +126,7 @@ async def test_activate_due_processes_only_scheduled_keys_and_rolls_back_failure
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""后台只处理到期 pending,并在单项失败时回滚该项事务。"""
-
- class _Session:
- """
- 模拟测试事务的会话生命周期。
-
- :cvar commits: 测试中记录的提交次数
- :cvar rollbacks: 测试中记录的回滚次数
- """
-
- commits = 0
- rollbacks = 0
-
- async def commit(self) -> None:
- """累加 ``commits`` 供后续断言检查。"""
- self.commits += 1
-
- async def rollback(self) -> None:
- """累加 ``rollbacks`` 供后续断言检查。"""
- self.rollbacks += 1
-
- session = _Session()
+ session = RecordingSession()
due = SimpleNamespace(kid='due-key')
scheduled: list[str] = []
@@ -166,6 +148,7 @@ async def activate(*args: object, **kwargs: object) -> bool:
:param kwargs: 传给被调用对象的关键字参数
:return: 此分支的固定值 ``True``
"""
+ assert isinstance(args[1], str)
scheduled.append(args[1])
return True
@@ -206,27 +189,7 @@ async def audit_writer(*args: object, **kwargs: object) -> None:
@pytest.mark.asyncio
async def test_activate_due_audits_first_failure_and_continues_next_key(monkeypatch: pytest.MonkeyPatch) -> None:
"""首把激活失败必须独立审计,且不得阻断后续到期密钥。"""
-
- class _Session:
- """
- 模拟测试事务的会话生命周期。
-
- :cvar commits: 测试中记录的提交次数
- :cvar rollbacks: 测试中记录的回滚次数
- """
-
- commits = 0
- rollbacks = 0
-
- async def commit(self) -> None:
- """累加 ``commits`` 供后续断言检查。"""
- self.commits += 1
-
- async def rollback(self) -> None:
- """累加 ``rollbacks`` 供后续断言检查。"""
- self.rollbacks += 1
-
- session = _Session()
+ session = RecordingSession()
pending = [SimpleNamespace(kid='first'), SimpleNamespace(kid='second')]
audit_events: list[dict[str, object]] = []
@@ -276,15 +239,6 @@ async def test_activate_due_continues_when_failure_audit_writer_fails(monkeypatc
pending = [SimpleNamespace(kid='first'), SimpleNamespace(kid='second')]
activated: list[str] = []
- class _Session:
- """模拟测试事务的会话生命周期。"""
-
- async def commit(self) -> None:
- """在测试会话中处理事务提交。"""
-
- async def rollback(self) -> None:
- """在测试会话中处理事务回滚。"""
-
async def due_keys(*args: object, **kwargs: object) -> list[SimpleNamespace]:
"""
向调用方返回 ``pending``。
@@ -327,7 +281,7 @@ async def failed_audit(*args: object, **kwargs: object) -> None:
)
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.list_due_pending', due_keys)
monkeypatch.setattr(KeyService, 'activate_key', activate)
- assert await KeyService.activate_due(_Session(), audit_writer=failed_audit) == 1
+ assert await KeyService.activate_due(RecordingSession(), audit_writer=failed_audit) == 1
assert activated == ['second']
assert warnings == [
'OIDC 签名密钥激活审计记录写入失败,密钥标识=first',
@@ -490,7 +444,7 @@ async def published(*args: object, **kwargs: object) -> list[SimpleNamespace]:
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.list_published', published)
with pytest.raises(KeyServiceError, match='包含不允许的字符'):
- await KeyService.build_jwks(object())
+ await KeyService.build_jwks(AsyncSession())
@pytest.mark.asyncio
@@ -506,6 +460,7 @@ async def test_management_key_bootstrap_is_available_when_oidc_disabled(data_ses
actor='admin',
)
assert row.status == 'pending'
+ assert row.private_key_ciphertext is not None
assert row.private_key_ciphertext.startswith('v2.')
@@ -696,7 +651,7 @@ async def published(*args: object, **kwargs: object) -> list[SimpleNamespace]:
return [record]
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.list_published', published)
- payload = await KeyService.build_jwks(object(), now=now)
+ payload = await KeyService.build_jwks(AsyncSession(), now=now)
assert payload == {
'keys': [
{
@@ -755,7 +710,7 @@ async def published(*args: object, **kwargs: object) -> list[SimpleNamespace]:
return records
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.list_published', published)
- assert await KeyService.build_jwks(object(), now=now) == {'keys': []}
+ assert await KeyService.build_jwks(AsyncSession(), now=now) == {'keys': []}
@pytest.mark.asyncio
@@ -778,7 +733,7 @@ async def published(*args: object, **kwargs: object) -> list[SimpleNamespace]:
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.list_published', published)
with pytest.raises(KeyServiceError, match=r'Base64URL|RSA 参数'):
- await KeyService.build_jwks(object(), now=now)
+ await KeyService.build_jwks(AsyncSession(), now=now)
@pytest.mark.asyncio
@@ -838,7 +793,7 @@ async def activate(*args: object, **kwargs: object) -> bool:
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.get_active', get_old)
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.activate', activate)
with pytest.raises(KeyServiceError, match='不匹配'):
- await KeyService.activate_key(object(), 'k1')
+ await KeyService.activate_key(AsyncSession(), 'k1')
assert changed is False
@@ -913,9 +868,9 @@ async def activate(*args: object, **kwargs: object) -> bool:
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.activate', activate)
set_retiring = AsyncMock(return_value=True)
monkeypatch.setattr('module_identity.service.key_service.OidcKeyDao.set_retiring', set_retiring)
- assert await KeyService.activate_key(object(), 'k1', now=now)
+ assert await KeyService.activate_key(AsyncSession(), 'k1', now=now)
set_retiring.assert_awaited_once()
- assert set_retiring.await_args.args[1:] == ('old', now + timedelta(seconds=7200), now)
+ assert set_retiring.await_args_list[-1].args[1:] == ('old', now + timedelta(seconds=7200), now)
def test_etag_is_stable_and_private_fields_are_not_serialized() -> None:
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_logout.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_logout.py
index 09be42a42..4ed81c541 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_logout.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_logout.py
@@ -8,7 +8,9 @@
import jwt
import pytest
from cryptography.hazmat.primitives.asymmetric import rsa
+from httpcore._backends.auto import AutoBackend
from jwt.utils import base64url_encode
+from sqlalchemy.ext.asyncio import AsyncSession
from starlette.requests import Request
from config.env import OidcConfig
@@ -96,11 +98,11 @@ def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(OidcConfig, 'oidc_token_hash_pepper', _PEPPER)
-def _key_record(private_key: object, now: datetime, kid: str = 'key-1') -> SimpleNamespace:
+def _key_record(private_key: rsa.RSAPrivateKey, now: datetime, kid: str = 'key-1') -> SimpleNamespace:
"""
构造本地数据库公开 JWK 记录。
- :param private_key: 仅在当前构建进程内使用的 Ed25519 签名私钥
+ :param private_key: 用于签发测试令牌的 RSA 私钥
:param now: 用于设置签发和过期时间的基准时刻
:param kid: 用于定位签名密钥的标识
:return: 本地数据库公开 JWK 记录
@@ -125,11 +127,11 @@ def _key_record(private_key: object, now: datetime, kid: str = 'key-1') -> Simpl
)
-def _id_token(private_key: object, *, now: datetime, kid: str = 'key-1', aud: str = 'portal') -> str:
+def _id_token(private_key: rsa.RSAPrivateKey, *, now: datetime, kid: str = 'key-1', aud: str = 'portal') -> str:
"""
签发用于测试的真实 ID Token。
- :param private_key: 仅在当前构建进程内使用的 Ed25519 签名私钥
+ :param private_key: 用于签发测试令牌的 RSA 私钥
:param now: 用于设置签发和过期时间的基准时刻
:param kid: 用于定位签名密钥的标识
:param aud: 令牌声明的受众
@@ -167,7 +169,7 @@ async def test_id_token_hint_uses_local_rsa_kid_and_rejects_remote_header(
'module_identity.service.session_service.OidcKeyDao.get_verifying',
_async_return(_key_record(private_key, now)),
)
- db = SimpleNamespace()
+ db = AsyncSession()
token = _id_token(private_key, now=now, aud='portal')
claims, resolved = await LogoutService._validate_id_token_hint(db, token, now)
@@ -197,7 +199,7 @@ async def test_pending_signing_key_cannot_validate_id_token_hint(
key = _key_record(private_key, now)
key.status = 'pending'
monkeypatch.setattr('module_identity.service.session_service.OidcKeyDao.get_verifying', _async_return(key))
- db = SimpleNamespace()
+ db = AsyncSession()
token = _id_token(private_key, now=now, aud='portal')
with pytest.raises(LogoutServiceError):
@@ -229,6 +231,7 @@ async def register_backchannel(*args: object, **kwargs: object) -> None:
:param kwargs: 传给被调用对象的关键字参数
"""
coordinator = kwargs['coordinator']
+ assert isinstance(coordinator, AfterCommitCoordinator)
async def notify() -> None:
"""记录待发送的后通道注销通知。"""
@@ -237,7 +240,7 @@ async def notify() -> None:
await coordinator.register(notify)
monkeypatch.setattr(LogoutService, '_register_backchannel', register_backchannel)
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ db = AsyncMock(spec=AsyncSession)
coordinator = AfterCommitCoordinator()
monkeypatch.setattr(
@@ -245,7 +248,7 @@ async def notify() -> None:
)
result = await LogoutService._logout(
db,
- object(),
+ FakeRedis().client,
id_token_hint='opaque-input-not-logged',
post_logout_redirect_uri='https://portal.example/logged-out',
state='opaque-state',
@@ -263,7 +266,7 @@ async def notify() -> None:
coordinator = AfterCommitCoordinator()
result = await LogoutService._logout(
db,
- object(),
+ FakeRedis().client,
id_token_hint='opaque-input-not-logged',
post_logout_redirect_uri='https://portal.example/logged-out',
state='opaque-state',
@@ -306,8 +309,8 @@ async def invalid_hint(*_args: object, **_kwargs: object) -> object:
'module_identity.service.session_service.SsoSessionDao.client_ids_for_sid', AsyncMock(return_value=[])
)
result = await LogoutService._logout(
- SimpleNamespace(),
- object(),
+ AsyncSession(),
+ FakeRedis().client,
id_token_hint='bad-hint',
cookie='ss1.valid-cookie',
post_logout_redirect_uri='https://portal.example/logged-out',
@@ -340,7 +343,7 @@ async def test_unsafe_or_unregistered_redirect_falls_back_to_local_and_logout_to
monkeypatch.setattr(LogoutService, '_lock_session_refresh_tokens', _async_return([]))
monkeypatch.setattr(LogoutService, '_revoke_session_state', _async_noop)
monkeypatch.setattr(LogoutService, '_register_backchannel', _async_noop)
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ db = AsyncMock(spec=AsyncSession)
coordinator = AfterCommitCoordinator()
monkeypatch.setattr(
@@ -348,7 +351,7 @@ async def test_unsafe_or_unregistered_redirect_falls_back_to_local_and_logout_to
)
result = await LogoutService._logout(
db,
- object(),
+ FakeRedis().client,
id_token_hint='hint',
post_logout_redirect_uri='https://evil.example/redirect#fragment',
state='do-not-echo',
@@ -368,6 +371,7 @@ async def test_unsafe_or_unregistered_redirect_falls_back_to_local_and_logout_to
signing_kid='key-1',
db=db,
)
+ assert token is not None
claims = decode_logout_token(token, verification_key=private_key.public_key(), issuer=_ISSUER, audience='portal')
assert claims['sid'] == 'sid-1'
assert claims['exp'] == claims['iat'] + 120
@@ -384,6 +388,7 @@ async def test_unsafe_or_unregistered_redirect_falls_back_to_local_and_logout_to
signing_kid='key-1',
db=db,
)
+ assert subject_token is not None
subject_claims = decode_logout_token(
subject_token, verification_key=private_key.public_key(), issuer=_ISSUER, audience='portal'
)
@@ -596,7 +601,7 @@ async def audit(event: str, _uri: str, _client_id: str, _sid: str, **kwargs: obj
audited.append(f'{event}:{kwargs.get("failure_code")}')
monkeypatch.setattr(LogoutService, '_audit_writer', lambda _db: audit)
- assert await LogoutService.consume_backchannel_retry(object(), redis) == 1
+ assert await LogoutService.consume_backchannel_retry(AsyncSession(), redis.client) == 1
dead = await redis.lpop(OidcRedisKey.backchannel_retry_queue() + ':dead')
assert dead == '{"error":"invalid_retry_payload"}'
assert audited == ['backchannel_logout_failed:invalid retry payload']
@@ -610,16 +615,15 @@ async def test_pinned_transport_uses_approved_ip_and_preserves_origin_host(monke
stream.start_tls.return_value = stream
stream.get_extra_info.return_value = None
transport = PinnedHttpxTransport('client.example', {'203.0.113.7'})
- backend = transport._pool._network_backend
connect = AsyncMock(return_value=stream)
- monkeypatch.setattr(backend._backend, 'connect_tcp', connect)
+ monkeypatch.setattr(AutoBackend, 'connect_tcp', connect)
async with httpx.AsyncClient(transport=transport) as client:
response = await client.post('https://client.example/logout', data={'logout_token': 'opaque'})
assert response.content == b'OK'
- assert connect.await_args.args[:2] == ('203.0.113.7', 443)
- assert stream.start_tls.await_args.kwargs['server_hostname'] == 'client.example'
+ assert connect.await_args_list[-1].args[:2] == ('203.0.113.7', 443)
+ assert stream.start_tls.await_args_list[-1].kwargs['server_hostname'] == 'client.example'
sent = b''.join(call.args[0] for call in stream.write.await_args_list)
assert b'host: client.example\r\n' in sent.lower()
@@ -627,6 +631,7 @@ async def test_pinned_transport_uses_approved_ip_and_preserves_origin_host(monke
@pytest.mark.asyncio
async def test_pinned_transport_stops_oversized_response_stream() -> None:
"""远端超大响应在流读取时主动中止,不在内存中无限累积。"""
+ closed = AsyncMock()
class Stream:
"""提供可异步迭代和关闭的响应流。"""
@@ -640,17 +645,17 @@ async def __aiter__(self) -> Any:
yield b'x' * (70 * 1024)
async def aclose(self) -> None:
- """完成无需返回值的回调。"""
- return
+ """记录底层响应流已关闭。"""
+ await closed()
- response = SimpleNamespace(status=200, headers=[], stream=Stream(), extensions={}, aclose=AsyncMock())
+ response = httpcore.Response(200, content=Stream())
transport = PinnedHttpxTransport('client.example', {'203.0.113.7'})
transport._pool.handle_async_request = AsyncMock(return_value=response)
result = await transport.handle_async_request(httpx.Request('POST', 'https://client.example/logout'))
with pytest.raises(OSError, match='响应大小超过限制'):
async for _chunk in result.aiter_bytes():
pass
- response.aclose.assert_awaited_once()
+ closed.assert_awaited_once()
@pytest.mark.asyncio
@@ -686,7 +691,7 @@ async def notify(uri: str, token: str) -> None:
"""
sent.append((uri, token))
- result = await LogoutService.consume_backchannel_retry(object(), redis, notifier=notify)
+ result = await LogoutService.consume_backchannel_retry(AsyncSession(), redis.client, notifier=notify)
assert result == 1
assert sent == [('https://client.example/logout', 'fresh.logout.token')]
@@ -700,7 +705,7 @@ async def test_logout_endpoint_disabled_is_local_404_without_legacy_pre_auth(
"""OIDC 关闭时直接返回裸 404,不执行数据库或 Legacy PreAuth。"""
config = SimpleNamespace(oidc_enabled=False)
monkeypatch.setattr(controller, 'OidcConfig', config)
- response = await controller.logout(_request(), object())
+ response = await controller.logout(_request(), AsyncSession())
assert response.status_code == _HTTP_NOT_FOUND
@@ -730,7 +735,7 @@ async def fake_logout(*_args: object, **_kwargs: object) -> LogoutResult:
return LogoutResult('https://portal.example/logged-out', 'state-1', True)
monkeypatch.setattr(controller.LogoutService, 'execute_logout', fake_logout)
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ db = AsyncMock(spec=AsyncSession)
monkeypatch.setattr(controller.LogoutConfirmationService, 'issue', AsyncMock(return_value=('t' * 43, 'n' * 43)))
execute = AsyncMock()
monkeypatch.setattr(controller.LogoutService, 'execute_logout', execute)
@@ -772,7 +777,7 @@ async def fail(*_args: object, **_kwargs: object) -> LogoutResult:
monkeypatch.setattr(controller.LogoutConfirmationService, 'issue', fail)
request = _request(headers=[(b'cookie', b'__Host-ruoyi-sso=valid-cookie')])
- response = await controller.logout(request, SimpleNamespace())
+ response = await controller.logout(request, AsyncSession())
assert response.status_code == _HTTP_SERVICE_UNAVAILABLE
assert 'set-cookie' not in response.headers
@@ -817,7 +822,7 @@ async def prepare(_redis: object, parameters: dict[str, str], _cookie: str | Non
body=body,
)
- response = await controller.logout(request, SimpleNamespace())
+ response = await controller.logout(request, AsyncSession())
assert response.status_code == _HTTP_OK
assert captured['id_token_hint'] == 'hint-value'
@@ -907,7 +912,7 @@ async def test_expired_id_token_is_accepted_only_as_logout_hint(monkeypatch: pyt
'module_identity.service.session_service.OidcKeyDao.get_verifying',
_async_return(_key_record(private_key, now)),
)
- claims, _ = await LogoutService._validate_id_token_hint(object(), token, now)
+ claims, _ = await LogoutService._validate_id_token_hint(AsyncSession(), token, now)
assert claims['sid'] == 'sid-1'
with pytest.raises(JwtProfileError):
decode_id_token(token, verification_key=private_key.public_key(), issuer=_ISSUER, audience='portal')
@@ -936,13 +941,13 @@ async def test_confirmed_logout_does_not_revoke_another_accounts_hint_session(
'module_identity.service.session_service.SsoSessionDao.client_ids_for_sid', AsyncMock(return_value=[])
)
result = await LogoutService._logout(
- object(),
- object(),
+ AsyncSession(),
+ FakeRedis().client,
id_token_hint='signed-other-account',
cookie='current-cookie',
confirmed=True,
coordinator=AfterCommitCoordinator(),
now=now,
)
- assert revoked.await_args.args[2] == 'current-sid'
+ assert revoked.await_args_list[-1].args[2] == 'current-sid'
assert result.redirect_uri is None
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_management_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_management_service.py
index 5e5ad659b..be0e64004 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_management_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_management_service.py
@@ -1,3 +1,4 @@
+from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
import pytest
@@ -33,12 +34,13 @@
OAuthClientManagementService,
OAuthManagementBaseService,
)
+from tests.module_identity.support.sessions import RecordingSession
_EXPECTED_PAGE_TOTAL = 3
@pytest_asyncio.fixture
-async def management_session() -> AsyncSession:
+async def management_session() -> AsyncIterator[AsyncSession]:
"""
创建只包含 OAuth 管理表的真实 SQLite 异步会话。
@@ -46,17 +48,17 @@ async def management_session() -> AsyncSession:
"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
tables = [
- SysOAuthClient.__table__,
- SysOAuthResource.__table__,
- SysOAuthScope.__table__,
- SysOAuthClientSecret.__table__,
- SysOAuthClientUri.__table__,
- SysOAuthClientScope.__table__,
- SysOAuthClientResource.__table__,
- SysOAuthGrant.__table__,
- SysSsoSession.__table__,
- SysOAuthRefreshToken.__table__,
- SysOAuthAuditLog.__table__,
+ SysOAuthClient.get_table(),
+ SysOAuthResource.get_table(),
+ SysOAuthScope.get_table(),
+ SysOAuthClientSecret.get_table(),
+ SysOAuthClientUri.get_table(),
+ SysOAuthClientScope.get_table(),
+ SysOAuthClientResource.get_table(),
+ SysOAuthGrant.get_table(),
+ SysSsoSession.get_table(),
+ SysOAuthRefreshToken.get_table(),
+ SysOAuthAuditLog.get_table(),
]
async with engine.begin() as connection:
await connection.run_sync(lambda sync_connection: Base.metadata.create_all(sync_connection, tables=tables))
@@ -139,27 +141,7 @@ def _confidential_payload(**changes: object) -> ClientCreateModel:
@pytest.mark.asyncio
async def test_after_commit_failure_does_not_rollback_committed_management_change() -> None:
"""提交后的运行时回调失败不得回滚已提交的管理事务。"""
-
- class _Db:
- """
- 模拟当前测试所需的数据库操作。
-
- :cvar commits: 测试中记录的提交次数
- :cvar rollbacks: 测试中记录的回滚次数
- """
-
- commits = 0
- rollbacks = 0
-
- async def commit(self) -> None:
- """累加 ``commits`` 供后续断言检查。"""
- self.commits += 1
-
- async def rollback(self) -> None:
- """累加 ``rollbacks`` 供后续断言检查。"""
- self.rollbacks += 1
-
- db = _Db()
+ db = RecordingSession()
async def operation() -> str:
"""
@@ -199,9 +181,9 @@ async def test_create_detail_bindings_secret_and_cors_snapshot(management_sessio
assert detail.scope_codes == ['openid', 'resource.read']
assert detail.pre_authorized_scope_codes == ['openid']
assert detail.resource_ids == ['resource-a']
- assert verify_client_secret(
- secret.client_secret, (await management_session.get(SysOAuthClientSecret, secret.secret_id)).secret_hash
- )
+ stored_secret = await management_session.get(SysOAuthClientSecret, secret.secret_id)
+ assert stored_secret is not None
+ assert verify_client_secret(secret.client_secret, stored_secret.secret_hash)
assert secret.client_secret not in repr(detail)
assert await OAuthClientManagementService.list_active_cors_origins(management_session) == (
'https://client.example',
@@ -306,9 +288,15 @@ async def test_status_soft_disable_and_secret_revoke_are_safe(management_session
management_session, ClientStatusModel(client_id=second.client_id, status='1'), actor='admin'
)
assert disabled.status == '1'
- assert (await management_session.get(SysOAuthGrant, 'grant-disable')).status == 'revoked'
- assert (await management_session.get(SysOAuthRefreshToken, 'refresh-disable')).status == 'revoked'
- assert (await management_session.get(SysSsoSession, 'sid-disable')).status == 'active'
+ stored_grant = await management_session.get(SysOAuthGrant, 'grant-disable')
+ assert stored_grant is not None
+ assert stored_grant.status == 'revoked'
+ stored_token = await management_session.get(SysOAuthRefreshToken, 'refresh-disable')
+ assert stored_token is not None
+ assert stored_token.status == 'revoked'
+ stored_session = await management_session.get(SysSsoSession, 'sid-disable')
+ assert stored_session is not None
+ assert stored_session.status == 'active'
disabled_again = await OAuthClientManagementService.change_client_status(
management_session, ClientStatusModel(client_id=second.client_id, status='1'), actor='admin'
)
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_resource_scope_management.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_resource_scope_management.py
index 8ee51a5b4..03bfdbf43 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_resource_scope_management.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_oauth_resource_scope_management.py
@@ -1,3 +1,4 @@
+from collections.abc import AsyncIterator
from datetime import UTC, datetime
import pytest
@@ -41,7 +42,7 @@
@pytest_asyncio.fixture
-async def resource_session() -> AsyncSession:
+async def resource_session() -> AsyncIterator[AsyncSession]:
"""
创建只包含 Resource/Scope/Client 管理表的真实 SQLite 会话。
@@ -49,17 +50,17 @@ async def resource_session() -> AsyncSession:
"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
tables = [
- SysOAuthClient.__table__,
- SysOAuthResource.__table__,
- SysOAuthScope.__table__,
- SysOAuthClientSecret.__table__,
- SysOAuthClientUri.__table__,
- SysOAuthClientScope.__table__,
- SysOAuthClientResource.__table__,
- SysOAuthGrant.__table__,
- SysSsoSession.__table__,
- SysOAuthRefreshToken.__table__,
- SysOAuthAuditLog.__table__,
+ SysOAuthClient.get_table(),
+ SysOAuthResource.get_table(),
+ SysOAuthScope.get_table(),
+ SysOAuthClientSecret.get_table(),
+ SysOAuthClientUri.get_table(),
+ SysOAuthClientScope.get_table(),
+ SysOAuthClientResource.get_table(),
+ SysOAuthGrant.get_table(),
+ SysSsoSession.get_table(),
+ SysOAuthRefreshToken.get_table(),
+ SysOAuthAuditLog.get_table(),
]
async with engine.begin() as connection:
await connection.run_sync(lambda sync_connection: Base.metadata.create_all(sync_connection, tables=tables))
@@ -174,7 +175,9 @@ async def test_resource_crud_introspection_policy_and_invalidation_snapshot(reso
resource_session, ResourceStatusModel(resource_id='orders-api', status='1'), actor='admin'
)
assert disabled.status == '1'
- assert (await resource_session.get(SysOAuthClient, 1)).policy_version == _SECOND_POLICY_CHANGE
+ stored_client = await resource_session.get(SysOAuthClient, 1)
+ assert stored_client is not None
+ assert stored_client.policy_version == _SECOND_POLICY_CHANGE
@pytest.mark.asyncio
@@ -245,7 +248,9 @@ async def test_scope_binding_claim_whitelist_and_builtin_openid(resource_session
actor='admin',
)
assert changed.claims == ['sub']
- assert (await resource_session.get(SysOAuthClient, 1)).policy_version == _FIRST_POLICY_CHANGE
+ stored_client = await resource_session.get(SysOAuthClient, 1)
+ assert stored_client is not None
+ assert stored_client.policy_version == _FIRST_POLICY_CHANGE
with pytest.raises(OAuthClientManagementError, match='不允许发布的声明'):
await OAuthResourceManagementService.create_scope(
resource_session,
@@ -321,7 +326,9 @@ async def test_display_only_client_resource_scope_updates_do_not_bump_policy_ver
actor='admin',
)
assert changed_resource.resource_name == '新的 Resource 展示名'
- assert (await resource_session.get(SysOAuthClient, 1)).policy_version == 1
+ stored_client = await resource_session.get(SysOAuthClient, 1)
+ assert stored_client is not None
+ assert stored_client.policy_version == 1
changed_scope = await OAuthResourceManagementService.update_scope(
resource_session,
@@ -336,7 +343,9 @@ async def test_display_only_client_resource_scope_updates_do_not_bump_policy_ver
actor='admin',
)
assert changed_scope.scope_name == '新的 Scope 展示名'
- assert (await resource_session.get(SysOAuthClient, 1)).policy_version == 1
+ stored_client = await resource_session.get(SysOAuthClient, 1)
+ assert stored_client is not None
+ assert stored_client.policy_version == 1
@pytest.mark.asyncio
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_review_completion.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_review_completion.py
index d22329b25..7f13599f0 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_review_completion.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_review_completion.py
@@ -2,6 +2,7 @@
from datetime import timedelta
from http import HTTPStatus
from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock
from urllib.parse import parse_qs, quote_plus, urlencode, urlsplit
@@ -72,7 +73,7 @@ async def _confidential_token(flow: SimpleNamespace) -> tuple:
secret = await OAuthClientManagementService._new_secret(flow.db, flow.app, 'admin', flow.now, not_before=flow.now)
await flow.db.commit()
authorization = _basic(flow.app.client_id, secret.client_secret)
- request = AuthorizeRequest(**_authorize_request(flow, offline=True))
+ request = AuthorizeRequest.model_validate(_authorize_request(flow, offline=True))
context = await AuthorizationService.validate_request(flow.db, request)
consent = await ConsentService.submit_consent(
flow.db,
@@ -83,6 +84,7 @@ async def _confidential_token(flow: SimpleNamespace) -> tuple:
user_id=flow.user.user_id,
subject_id=flow.subject.subject_id,
)
+ assert consent.grant is not None
code = await AuthorizationCodeService.issue(
flow.redis,
{
@@ -127,6 +129,7 @@ async def test_revoke_user_terminates_expired_offline_sessions(auth_flow: Simple
flow.session.idle_expires_at = flow.now - timedelta(seconds=1)
flow.session.status = stored_status
await flow.db.commit()
+ assert token.refresh_token is not None
assert (await _introspect(flow, token.refresh_token))['active'] is True
count = await OAuthSessionManagementService.revoke_user(
flow.db, flow.redis, flow.user.user_id, 'admin', '终止该用户的全部外部会话'
@@ -244,8 +247,12 @@ async def test_effective_expiry_matches_list_count_detail_without_mutating_state
assert count == grant_count == 1
assert sessions[0].status == grants[0].status == 'expired'
assert sessions[0].client_ids == ['business-app']
- assert (await OAuthSessionManagementService.get_session(flow.db, flow.session.sid)).status == 'expired'
- assert (await OAuthSessionManagementService.get_grant(flow.db, grant.grant_id)).status == 'expired'
+ stored_session = await OAuthSessionManagementService.get_session(flow.db, flow.session.sid)
+ assert stored_session is not None
+ assert stored_session.status == 'expired'
+ stored_grant = await OAuthSessionManagementService.get_grant(flow.db, grant.grant_id)
+ assert stored_grant is not None
+ assert stored_grant.status == 'expired'
assert await OAuthSessionManagementService.list_sessions(flow.db, SessionPageQueryModel(status='active')) == ([], 0)
assert await OAuthSessionManagementService.list_grants(flow.db, GrantPageQueryModel(status='active')) == ([], 0)
assert flow.session.status == grant.status == 'active'
@@ -319,20 +326,20 @@ async def test_failed_token_transaction_rolls_back_session_participation(
"""令牌签发事务失败时不能残留成功登录关联记录。"""
record = AuditService.record
- async def fail_token_audit(db: AsyncSession, event_type: str, *args: object, **kwargs: object) -> object:
+ async def fail_token_audit(db: AsyncSession, event_type: str, result: str, **kwargs: Any) -> object:
"""
在令牌签发审计时模拟写入失败。
:param db: 当前操作使用的数据库会话
:param event_type: 审计事件类型
- :param args: 传给被调用对象的位置参数
+ :param result: 审计事件的处理结果
:param kwargs: 传给被调用对象的关键字参数
:raises RuntimeError: 模拟写入令牌审计时服务不可用
:return: 未注入故障时原审计函数的结果
"""
if event_type == OidcAuditEvent.TOKEN_ISSUED:
raise RuntimeError('audit unavailable')
- return await record(db, event_type, *args, **kwargs)
+ return await record(db, event_type, result, **kwargs)
monkeypatch.setattr(AuditService, 'record', fail_token_audit)
with pytest.raises(RuntimeError, match='audit unavailable'):
@@ -384,6 +391,8 @@ def _http_app(flow: SimpleNamespace, router: APIRouter) -> FastAPI:
for route in router.routes:
if isinstance(route, APIRoute):
for dependency in route.dependant.dependencies:
+ if dependency.call is None:
+ continue
if dependency.name == 'query_db':
app.dependency_overrides[dependency.call] = lambda: flow.db
else:
@@ -401,9 +410,10 @@ async def test_authorize_accepts_query_response_mode_on_both_methods(
values = {**_authorize_request(auth_flow), 'response_mode': 'query', 'prompt': 'none', 'state': 'test-state'}
app = _http_app(auth_flow, authorization_controller)
async with AsyncClient(transport=ASGITransport(app=app), base_url='https://auth.example.com') as client:
- response = await client.request(
- method, '/oauth2/authorize', **({'params': values} if method == 'GET' else {'data': values})
- )
+ if method == 'GET':
+ response = await client.get('/oauth2/authorize', params=values)
+ else:
+ response = await client.post('/oauth2/authorize', data=values)
assert response.status_code == HTTPStatus.SEE_OTHER
location = urlsplit(response.headers['location'])
assert location.netloc == 'app.example.com'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_review_regressions.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_review_regressions.py
index fa22a9099..fb22b0600 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_review_regressions.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_review_regressions.py
@@ -150,8 +150,10 @@ async def test_rotation_with_real_foreign_keys_and_replay_revocation(
result = await refresh(data_session, old)
await data_session.commit()
old_row = await OAuthTokenDao.get_by_token_id(data_session, parse_opaque_token(old, 'rt1').token_id)
+ assert result.refresh_token is not None
new_id = parse_opaque_token(result.refresh_token, 'rt1').token_id
successor = await OAuthTokenDao.get_by_token_id(data_session, new_id)
+ assert old_row is not None and successor is not None
assert old_row.status == 'used'
assert old_row.replaced_by_token_id == new_id
assert successor.parent_token_id == old_row.token_id
@@ -174,6 +176,7 @@ async def test_failed_signing_rolls_back_both_rotation_rows(
await data_session.rollback()
assert await data_session.scalar(select(func.count()).select_from(SysOAuthRefreshToken)) == 1
old_row = await OAuthTokenDao.get_by_token_id(data_session, parse_opaque_token(old, 'rt1').token_id)
+ assert old_row is not None
assert old_row.status == 'active'
assert old_row.replaced_by_token_id is None
@@ -200,8 +203,8 @@ async def test_real_key_list_readiness_and_client_response_are_rfc3339(monkeypat
'module_identity.controller.oidc_key_controller.OidcKeyManagementService.list_page',
AsyncMock(return_value=([], 0)),
)
- response = await list_oidc_keys(object(), status=None, page_num=1, page_size=10)
- assert json.loads(response.body)['readinessCheckedAt'].endswith('Z')
+ response = await list_oidc_keys(AsyncSession(), status=None, page_num=1, page_size=10)
+ assert json.loads(bytes(response.body))['readinessCheckedAt'].endswith('Z')
model = ClientViewModel(
client_id='public',
client_name='Public',
@@ -210,7 +213,10 @@ async def test_real_key_list_readiness_and_client_response_are_rfc3339(monkeypat
redirect_uris=['https://client.example/callback'],
update_time=NOW,
)
- assert json.loads(ResponseUtil.success(rows=[model]).body)['rows'][0]['updateTime'] == '2026-09-12T10:00:00.000Z'
+ assert (
+ json.loads(bytes(ResponseUtil.success(rows=[model]).body))['rows'][0]['updateTime']
+ == '2026-09-12T10:00:00.000Z'
+ )
def test_role_values_require_an_explicit_client_allowlist() -> None:
@@ -240,6 +246,7 @@ async def test_confirmed_logout_revokes_offline_grant_with_expired_owned_cookie(
sid = '99010000-0000-4000-8000-000000000001'
session = await SsoSessionDao.get_by_sid(data_session, sid)
secret = 's' * 43
+ assert session is not None
session.session_secret_hash = OidcUtil.session_secret_digest(secret, PEPPER)
await data_session.commit()
result = await LogoutService.execute_logout(
@@ -250,7 +257,9 @@ async def test_confirmed_logout_revokes_offline_grant_with_expired_owned_cookie(
now=NOW,
)
assert result.session_revoked is True
- assert (await SsoSessionDao.get_by_sid(data_session, sid)).status == 'revoked'
- assert (
- await OAuthTokenDao.get_by_token_id(data_session, parse_opaque_token(old, 'rt1').token_id)
- ).status == 'revoked'
+ stored_session = await SsoSessionDao.get_by_sid(data_session, sid)
+ assert stored_session is not None
+ assert stored_session.status == 'revoked'
+ stored_token = await OAuthTokenDao.get_by_token_id(data_session, parse_opaque_token(old, 'rt1').token_id)
+ assert stored_token is not None
+ assert stored_token.status == 'revoked'
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_revocation_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_revocation_service.py
index c9f05557a..da0763867 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_revocation_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_revocation_service.py
@@ -3,6 +3,7 @@
from unittest.mock import AsyncMock
import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
from config.env import OidcConfig
from module_identity.security.opaque_token import generate_refresh_token, token_digest
@@ -74,11 +75,11 @@ async def test_public_client_can_revoke_only_its_own_refresh_family(monkeypatch:
revoke_family = AsyncMock()
monkeypatch.setattr('module_identity.service.token_protocol_service.OAuthTokenDao.get_by_token_id', get_by_token_id)
monkeypatch.setattr('module_identity.service.token_protocol_service.OAuthTokenDao.revoke_family', revoke_family)
- db = object()
+ db = AsyncSession()
await RevocationService.revoke(
db,
- FakeRedis(),
+ FakeRedis().client,
token,
OAuthClientPrincipal('client-a', 'public', 'none'),
)
@@ -115,7 +116,7 @@ async def test_revocation_auth_method_pair_is_exact(
)
result = await RevocationService._resolve_caller(
- object(), OAuthClientPrincipal('client-a', principal_type, principal_method)
+ AsyncSession(), OAuthClientPrincipal('client-a', principal_type, principal_method)
)
assert (result is not None) is expected
@@ -133,8 +134,8 @@ async def test_unknown_refresh_is_idempotent_success(monkeypatch: pytest.MonkeyP
)
result = await RevocationService.revoke(
- object(),
- FakeRedis(),
+ AsyncSession(),
+ FakeRedis().client,
generate_refresh_token('token-0002'),
OAuthClientPrincipal('client-a', 'public', 'none'),
)
@@ -164,12 +165,12 @@ async def test_access_revocation_is_written_only_after_commit(monkeypatch: pytes
)
redis = FakeRedis()
coordinator = AfterCommitCoordinator()
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ db = AsyncMock(spec=AsyncSession)
now = datetime.fromtimestamp(200, UTC)
await RevocationService.revoke(
db,
- redis,
+ redis.client,
'signed-access',
OAuthClientPrincipal('client-a', 'confidential', 'client_secret_basic'),
coordinator=coordinator,
@@ -203,11 +204,11 @@ async def test_public_client_can_revoke_its_own_access_after_commit(monkeypatch:
)
redis = FakeRedis()
coordinator = AfterCommitCoordinator()
- db = SimpleNamespace(commit=AsyncMock(), rollback=AsyncMock())
+ db = AsyncMock(spec=AsyncSession)
await RevocationService.revoke(
db,
- redis,
+ redis.client,
'signed-public-access',
OAuthClientPrincipal('client-a', 'public', 'none'),
coordinator=coordinator,
@@ -241,7 +242,7 @@ async def test_public_client_cannot_revoke_other_client_access(monkeypatch: pyte
)
redis = FakeRedis()
await RevocationService.revoke(
- object(), redis, 'foreign-access', OAuthClientPrincipal('client-a', 'public', 'none')
+ AsyncSession(), redis.client, 'foreign-access', OAuthClientPrincipal('client-a', 'public', 'none')
)
assert not redis.values
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_sso_session_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_sso_session_service.py
index 0f1902a28..e524645c5 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_sso_session_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_sso_session_service.py
@@ -2,14 +2,16 @@
import builtins
import json
from datetime import UTC, datetime, timedelta
+from unittest.mock import Mock
from uuid import UUID, uuid4
import pytest
from fastapi import Response
+from redis.asyncio import Redis
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from config.env import OidcConfig
+from config.env import OidcConfig, OidcSettings
from module_admin.entity.do.user_do import SysUser
from module_identity.dao.sso_session_dao import SsoSessionDao
from module_identity.entity.do.identity_subject_do import SysIdentitySubject
@@ -29,6 +31,7 @@ class SessionFakeRedis:
"""
覆盖 Session 服务所需字符串、Set 和 publish 语义的 FakeRedis。
+ :ivar client: 供被测服务调用的异步 Redis 客户端替身
:ivar values: 当前处理的值集合
:ivar sets: 模拟 Redis 保存的集合数据
:ivar set_expiries: 为模拟键设置的到期时间
@@ -39,6 +42,7 @@ class SessionFakeRedis:
def __init__(self) -> None:
"""初始化测试夹具的 ``values``, ``sets``, ``set_expiries``, ``expire_seconds``。"""
+ self.client: Redis = Mock(spec_set=Redis, wraps=self)
self.values: dict[str, tuple[str, float | None]] = {}
self.sets: dict[str, set[str]] = {}
self.set_expiries: dict[str, float] = {}
@@ -195,7 +199,7 @@ def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(OidcConfig, name, value)
-def _config() -> OidcConfig:
+def _config() -> OidcSettings:
"""
返回当前测试使用的全局 OIDC 配置。
@@ -204,7 +208,7 @@ def _config() -> OidcConfig:
return OidcConfig
-def _config_with_long_remember() -> OidcConfig:
+def _config_with_long_remember() -> OidcSettings:
"""
创建超过协议上限的 remember-me 配置。
@@ -239,7 +243,7 @@ async def _create(db: AsyncSession, redis: SessionFakeRedis, *, remember: bool =
queue = AfterCommitCoordinator()
result = await SsoSessionService.create(
db,
- redis,
+ redis.client,
1,
_SUBJECT_ID,
2,
@@ -274,7 +278,7 @@ async def test_create_validate_and_remember_absolute_ttl(data_session: AsyncSess
assert 'session_secret_hash' not in session_payload
queue = AfterCommitCoordinator()
validated = await SsoSessionService.validate(
- data_session, redis, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue
+ data_session, redis.client, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue
)
await queue.commit(data_session)
assert validated.subject_id == _SUBJECT_ID
@@ -286,7 +290,7 @@ async def test_create_validate_and_remember_absolute_ttl(data_session: AsyncSess
queue = AfterCommitCoordinator()
capped = await SsoSessionService.create(
data_session,
- redis,
+ redis.client,
1,
_SUBJECT_ID,
2,
@@ -322,7 +326,7 @@ async def test_stale_cookie_index_does_not_reject_valid_database_session(data_se
await redis.set(OidcRedisKey.sso_cookie(digest), str(uuid4()), ex=3600)
coordinator = AfterCommitCoordinator()
validated = await SsoSessionService.validate(
- data_session, redis, cookie, pepper=_PEPPER, now=_NOW, coordinator=coordinator
+ data_session, redis.client, cookie, pepper=_PEPPER, now=_NOW, coordinator=coordinator
)
await coordinator.commit(data_session)
assert validated.sid == sid == row.sid
@@ -366,17 +370,20 @@ async def test_wrong_secret_and_security_version_fail_closed(data_session: Async
wrong = f'ss1.{sid}.{wrong_secret}'
queue = AfterCommitCoordinator()
with pytest.raises(SsoSessionError):
- await SsoSessionService.validate(data_session, redis, wrong, pepper=_PEPPER, now=_NOW, coordinator=queue)
+ await SsoSessionService.validate(data_session, redis.client, wrong, pepper=_PEPPER, now=_NOW, coordinator=queue)
await queue.commit(data_session)
assert row.status == 'active'
cookie, row = await _create(data_session, redis)
subject = await data_session.scalar(select(SysIdentitySubject).where(SysIdentitySubject.user_id == 1))
+ assert subject is not None
subject.auth_version = 3
await data_session.flush()
queue = AfterCommitCoordinator()
with pytest.raises(SsoSessionError):
- await SsoSessionService.validate(data_session, redis, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue)
+ await SsoSessionService.validate(
+ data_session, redis.client, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue
+ )
await queue.commit(data_session)
assert row.status == 'revoked'
@@ -392,7 +399,7 @@ async def test_touch_never_crosses_absolute_and_rotation_invalidates_old(data_se
queue = AfterCommitCoordinator()
touched = await SsoSessionService.touch(
data_session,
- redis,
+ redis.client,
cookie,
pepper=_PEPPER,
now=_NOW + timedelta(seconds=90),
@@ -402,16 +409,20 @@ async def test_touch_never_crosses_absolute_and_rotation_invalidates_old(data_se
assert touched.idle_expires_at == _NOW + timedelta(seconds=100)
queue = AfterCommitCoordinator()
rotated = await SsoSessionService.rotate_cookie(
- data_session, redis, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue
+ data_session, redis.client, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue
)
await queue.commit(data_session)
queue = AfterCommitCoordinator()
with pytest.raises(SsoSessionError):
- await SsoSessionService.validate(data_session, redis, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue)
+ await SsoSessionService.validate(
+ data_session, redis.client, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue
+ )
await queue.commit(data_session)
queue = AfterCommitCoordinator()
assert (
- await SsoSessionService.validate(data_session, redis, rotated, pepper=_PEPPER, now=_NOW, coordinator=queue)
+ await SsoSessionService.validate(
+ data_session, redis.client, rotated, pepper=_PEPPER, now=_NOW, coordinator=queue
+ )
).sid == row.sid
await queue.commit(data_session)
@@ -426,7 +437,7 @@ async def test_expired_session_is_marked_expired(data_session: AsyncSession) ->
with pytest.raises(SsoSessionError):
await SsoSessionService.validate(
data_session,
- redis,
+ redis.client,
cookie,
pepper=_PEPPER,
now=_NOW + timedelta(seconds=8 * 60 * 60 + 1),
@@ -446,14 +457,16 @@ async def test_db_revocation_invalidates_cached_hit_and_after_commit_order(data_
await data_session.commit()
queue = AfterCommitCoordinator()
with pytest.raises(SsoSessionError):
- await SsoSessionService.validate(data_session, redis, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue)
+ await SsoSessionService.validate(
+ data_session, redis.client, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue
+ )
await queue.commit(data_session)
cookie, row = await _create(data_session, redis)
coordinator = AfterCommitCoordinator()
assert await SsoSessionService.revoke(
- data_session, redis, row.sid, reason='admin', now=_NOW, coordinator=coordinator
+ data_session, redis.client, row.sid, reason='admin', now=_NOW, coordinator=coordinator
)
assert row.status == 'revoked'
assert redis.values
@@ -484,7 +497,7 @@ async def fail(*args: object, **kwargs: object) -> bool:
monkeypatch.setattr(SsoSessionDao, 'revoke', fail)
queue = AfterCommitCoordinator()
with pytest.raises(RuntimeError):
- await SsoSessionService.revoke(data_session, redis, row.sid, now=_NOW, coordinator=queue)
+ await SsoSessionService.revoke(data_session, redis.client, row.sid, now=_NOW, coordinator=queue)
assert redis.values
@@ -498,7 +511,7 @@ async def test_revoke_rollback_keeps_cache_until_after_commit(data_session: Asyn
sid = row.sid
coordinator = AfterCommitCoordinator()
- assert await SsoSessionService.revoke(data_session, redis, sid, now=_NOW, coordinator=coordinator)
+ assert await SsoSessionService.revoke(data_session, redis.client, sid, now=_NOW, coordinator=coordinator)
await coordinator.rollback(data_session)
assert redis.values
assert coordinator.pending_count == 0
@@ -515,7 +528,7 @@ async def test_commit_failure_does_not_run_registered_cleanup(
redis = SessionFakeRedis()
_, row = await _create(data_session, redis)
queue = AfterCommitCoordinator()
- assert await SsoSessionService.revoke(data_session, redis, row.sid, now=_NOW, coordinator=queue)
+ assert await SsoSessionService.revoke(data_session, redis.client, row.sid, now=_NOW, coordinator=queue)
async def fail_commit() -> None:
"""
@@ -542,7 +555,9 @@ async def test_inactive_validation_only_cleans_cache_without_event(data_session:
await data_session.commit()
queue = AfterCommitCoordinator()
with pytest.raises(SsoSessionError):
- await SsoSessionService.validate(data_session, redis, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue)
+ await SsoSessionService.validate(
+ data_session, redis.client, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue
+ )
await queue.commit(data_session)
assert not redis.published
@@ -558,7 +573,7 @@ async def test_create_requires_uuid_and_positive_integer_ttls(data_session: Asyn
with pytest.raises(SsoSessionError):
await SsoSessionService.create(
data_session,
- redis,
+ redis.client,
1,
_SUBJECT_ID,
2,
@@ -572,7 +587,7 @@ async def test_create_requires_uuid_and_positive_integer_ttls(data_session: Asyn
with pytest.raises(SsoSessionError):
await SsoSessionService.create(
data_session,
- redis,
+ redis.client,
1,
_SUBJECT_ID,
2,
@@ -592,7 +607,7 @@ async def test_create_rotate_touch_cache_writes_wait_for_commit(data_session: As
queue = AfterCommitCoordinator()
await SsoSessionService.create(
data_session,
- redis,
+ redis.client,
1,
_SUBJECT_ID,
2,
@@ -609,7 +624,9 @@ async def test_create_rotate_touch_cache_writes_wait_for_commit(data_session: As
await _seed_identity(data_session)
cookie, _ = await _create(data_session, redis)
queue = AfterCommitCoordinator()
- await SsoSessionService.rotate_cookie(data_session, redis, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue)
+ await SsoSessionService.rotate_cookie(
+ data_session, redis.client, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue
+ )
assert redis.values
await data_session.rollback()
assert redis.values
@@ -622,7 +639,7 @@ async def test_touch_cache_write_waits_for_commit(data_session: AsyncSession) ->
redis = SessionFakeRedis()
cookie, _ = await _create(data_session, redis)
queue = AfterCommitCoordinator()
- await SsoSessionService.touch(data_session, redis, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue)
+ await SsoSessionService.touch(data_session, redis.client, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue)
await data_session.rollback()
assert redis.values
@@ -637,7 +654,7 @@ async def test_after_commit_uses_snapshot_and_publishes_when_cache_clear_fails(
coordinator = AfterCommitCoordinator()
cookie, row = await SsoSessionService.create(
data_session,
- redis,
+ redis.client,
1,
_SUBJECT_ID,
2,
@@ -666,7 +683,7 @@ async def fail_clear(*args: object, **kwargs: object) -> None:
raise RuntimeError('redis clear failed')
monkeypatch.setattr(SsoSessionService, '_clear_cache', fail_clear)
- await SsoSessionService._best_effort_cleanup(redis, snapshot, reason='logout')
+ await SsoSessionService._best_effort_cleanup(redis.client, snapshot, reason='logout')
assert redis.published
@@ -677,11 +694,14 @@ async def test_user_status_and_cookie_response_security(data_session: AsyncSessi
redis = SessionFakeRedis()
cookie, _ = await _create(data_session, redis)
user = await data_session.scalar(select(SysUser).where(SysUser.user_id == 1))
+ assert user is not None
user.status = '1'
await data_session.flush()
queue = AfterCommitCoordinator()
with pytest.raises(SsoSessionError):
- await SsoSessionService.validate(data_session, redis, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue)
+ await SsoSessionService.validate(
+ data_session, redis.client, cookie, pepper=_PEPPER, now=_NOW, coordinator=queue
+ )
await queue.commit(data_session)
response = Response()
OidcUtil.parse_sso_cookie(cookie)
@@ -735,7 +755,7 @@ async def test_session_entry_points_preserve_domain_errors_for_invalid_credentia
else:
await SsoSessionService.validate(
data_session,
- SessionFakeRedis(),
+ SessionFakeRedis().client,
cookie,
pepper=pepper,
now=_NOW,
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_token_service.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_token_service.py
index 9123e575c..62a08fd3a 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_token_service.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_token_service.py
@@ -7,7 +7,7 @@
import pytest
from cryptography.hazmat.primitives.asymmetric import rsa
-from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from config.env import OidcConfig
from exceptions.exception import OAuthProtocolException
@@ -15,7 +15,9 @@
from module_admin.entity.do.role_do import SysRole
from module_admin.entity.do.user_do import SysUser, SysUserRole
from module_identity.dao.oauth_access_policy_dao import OAuthAccessPolicyDao
+from module_identity.entity.do.identity_subject_do import SysIdentitySubject
from module_identity.entity.do.oauth_client_do import SysOAuthClient
+from module_identity.entity.do.oauth_grant_do import SysSsoSession
from module_identity.entity.do.oauth_resource_do import (
SysOAuthClientResource,
SysOAuthClientScope,
@@ -59,7 +61,7 @@ async def test_confidential_auth_marks_only_matching_secret_used(monkeypatch: py
)
mark_used = AsyncMock(return_value=True)
monkeypatch.setattr('module_identity.service.token_service.OAuthClientDao.mark_secret_used', mark_used)
- db = object()
+ db = AsyncSession()
header = 'Basic ' + base64.b64encode(f'{client.client_id}:{secret}'.encode()).decode()
await TokenService.authenticate_client(db, authorization=header)
@@ -109,7 +111,7 @@ def _configure_oidc(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(OidcConfig, name, value)
-def _client(**overrides: object) -> SimpleNamespace:
+def _client(**overrides: object) -> SysOAuthClient:
"""
构造 Token 流程所需的 Client 标量快照。
@@ -128,7 +130,7 @@ def _client(**overrides: object) -> SimpleNamespace:
'status': '0',
}
value.update(overrides)
- return SimpleNamespace(**value)
+ return SysOAuthClient(**value)
def _code_payload(**overrides: object) -> dict[str, object]:
@@ -227,10 +229,10 @@ async def session(*args: object, **kwargs: object) -> SimpleNamespace:
monkeypatch.setattr(TokenService, '_issue_id_token', lambda *args, **kwargs: _async_value('id'))
redis = FakeRedis()
- code = await AuthorizationCodeService.issue(redis, payload, pepper=_PEPPER)
+ code = await AuthorizationCodeService.issue(redis.client, payload, pepper=_PEPPER)
result = await TokenService.authorization_code(
- object(),
- redis,
+ AsyncSession(),
+ redis.client,
{
'grant_type': 'authorization_code',
'client_id': 'portal-client',
@@ -245,10 +247,11 @@ async def session(*args: object, **kwargs: object) -> SimpleNamespace:
assert result.refresh_token is None
assert await redis.get(f'oidc:authorization_code:{code.split(".")[1]}') is None
+ code = await AuthorizationCodeService.issue(redis.client, payload, pepper=_PEPPER)
with pytest.raises(OAuthProtocolException) as raised:
await TokenService.authorization_code(
- object(),
- redis,
+ AsyncSession(),
+ redis.client,
{
'grant_type': 'authorization_code',
'client_id': 'portal-client',
@@ -261,10 +264,11 @@ async def session(*args: object, **kwargs: object) -> SimpleNamespace:
)
assert raised.value.error == 'invalid_grant'
+ code = await AuthorizationCodeService.issue(redis.client, payload, pepper=_PEPPER)
with pytest.raises(OAuthProtocolException) as raised:
await TokenService.authorization_code(
- object(),
- redis,
+ AsyncSession(),
+ redis.client,
{
'grant_type': 'authorization_code',
'client_id': 'portal-client',
@@ -299,12 +303,12 @@ async def test_authorization_code_reuse_revokes_bound_grant(monkeypatch: pytest.
revoke = AsyncMock(return_value=True)
monkeypatch.setattr('module_identity.service.token_service.OAuthGrantDao.revoke', revoke)
monkeypatch.setattr(AuditService, 'record_independent', AsyncMock())
- db = SimpleNamespace(execute=AsyncMock())
+ db = AsyncMock(spec=AsyncSession)
with pytest.raises(AuthorizationCodeReuseError):
await TokenService.authorization_code(
db,
- FakeRedis(),
+ FakeRedis().client,
{
'grant_type': 'authorization_code',
'client_id': 'portal-client',
@@ -337,7 +341,7 @@ async def test_client_credentials_is_machine_domain_isolated(monkeypatch: pytest
)
monkeypatch.setattr(TokenService, '_resolve_signer', lambda *args, **kwargs: _async_value((key, 'kid-1')))
result = await TokenService.client_credentials(
- object(),
+ AsyncSession(),
{'grant_type': 'client_credentials', 'scope': 'portal.service.read', 'resource': 'https://api.example'},
OAuthClientPrincipal('portal-client', 'confidential', 'client_secret_basic'),
)
@@ -360,11 +364,11 @@ async def test_client_credentials_uses_real_async_dao_and_resource_scope(monkeyp
"""验证 Client Credentials 通过真实 AsyncSession 查询 Client/Scope/Resource 绑定。"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
tables = [
- SysOAuthClient.__table__,
- SysOAuthResource.__table__,
- SysOAuthScope.__table__,
- SysOAuthClientScope.__table__,
- SysOAuthClientResource.__table__,
+ SysOAuthClient.get_table(),
+ SysOAuthResource.get_table(),
+ SysOAuthScope.get_table(),
+ SysOAuthClientScope.get_table(),
+ SysOAuthClientResource.get_table(),
]
async with engine.begin() as connection:
await connection.run_sync(lambda sync: SysOAuthClient.metadata.create_all(sync, tables=tables))
@@ -428,10 +432,10 @@ async def test_user_access_and_id_profiles_have_fixed_claims_and_ttl(monkeypatch
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
config = _config()
client = _client(access_token_ttl_seconds=_ACCESS_TTL)
- user = SimpleNamespace(user_id=2001, user_name='user', nick_name='User', status='0', del_flag='0')
- subject = SimpleNamespace(subject_id='subject-2001', auth_version=4)
+ user = SysUser(user_id=2001, user_name='user', nick_name='User', status='0', del_flag='0')
+ subject = SysIdentitySubject(subject_id='subject-2001', auth_version=4)
now = datetime.now(UTC)
- session = SimpleNamespace(
+ session = SysSsoSession(
sid='sid-2001',
auth_time=now - timedelta(minutes=1),
acr='urn:test:pwd',
@@ -453,7 +457,7 @@ async def test_user_access_and_id_profiles_have_fixed_claims_and_ttl(monkeypatch
)
monkeypatch.setattr(TokenService, '_resolve_signer', lambda *args, **kwargs: _async_value((key, 'kid-1')))
access, expires = await TokenService._issue_access_token(
- object(),
+ AsyncSession(),
client,
user,
subject,
@@ -478,7 +482,7 @@ async def test_user_access_and_id_profiles_have_fixed_claims_and_ttl(monkeypatch
assert claims['sid'] == 'sid-2001'
assert 'user_id' not in claims
identity = await TokenService._issue_id_token(
- object(),
+ AsyncSession(),
client,
user,
subject,
@@ -505,7 +509,7 @@ async def test_user_access_and_id_profiles_have_fixed_claims_and_ttl(monkeypatch
async def test_user_claims_load_real_roles_and_department_rows(monkeypatch: pytest.MonkeyPatch) -> None:
"""验证 Claims 从真实角色、用户角色和部门行加载,并仍受三层白名单约束。"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
- tables = [SysUser.__table__, SysDept.__table__, SysRole.__table__, SysUserRole.__table__]
+ tables = [SysUser.get_table(), SysDept.get_table(), SysRole.get_table(), SysUserRole.get_table()]
async with engine.begin() as connection:
await connection.run_sync(lambda sync: SysUser.metadata.create_all(sync, tables=tables))
session_factory = async_sessionmaker(engine, expire_on_commit=False)
@@ -554,7 +558,7 @@ async def test_user_claims_load_real_roles_and_department_rows(monkeypatch: pyte
db,
client,
user,
- SimpleNamespace(subject_id='subject-7201'),
+ SysIdentitySubject(subject_id='subject-7201'),
['roles', 'dept'],
None,
)
@@ -568,19 +572,20 @@ def test_access_ttl_uses_overrides_and_global_cap() -> None:
"""验证默认、Client/Resource 覆盖和全局上限的最严格策略。"""
assert TokenService._access_ttl(_client(), None) == _DEFAULT_TTL
assert TokenService._access_ttl(_client(access_token_ttl_seconds=_LONG_TTL), None) == _LONG_TTL
- resource = SimpleNamespace(access_token_ttl_seconds=_RESOURCE_TTL)
+ resource = SysOAuthResource(access_token_ttl_seconds=_RESOURCE_TTL)
assert TokenService._access_ttl(_client(access_token_ttl_seconds=_LONG_TTL), resource) == _RESOURCE_TTL
assert TokenService._access_ttl(_client(access_token_ttl_seconds=3000), None) == _MAX_TTL
@pytest.mark.asyncio
-async def test_public_token_entrypoints_require_authenticated_principal() -> None:
+@pytest.mark.parametrize('invalid_principal', ['portal-client'])
+async def test_public_token_entrypoints_require_authenticated_principal(invalid_principal: Any) -> None:
"""验证公开 Token 流程拒绝 ORM 行和裸 Client ID。"""
with pytest.raises(OAuthProtocolException) as raised:
await TokenService.client_credentials(
- object(),
+ AsyncSession(),
{'grant_type': 'client_credentials'},
- 'portal-client',
+ invalid_principal,
)
assert raised.value.error == 'invalid_client'
@@ -608,7 +613,7 @@ async def load(value: object, **kwargs: object) -> object:
return private_key
monkeypatch.setattr('module_identity.service.token_service.KeyService.load_private_key_async', load)
- key, kid = await TokenService._resolve_signer(object(), None, None, datetime.now(UTC))
+ key, kid = await TokenService._resolve_signer(AsyncSession(), None, None, datetime.now(UTC))
assert key is private_key
assert kid == 'kid-stable'
assert calls == [record]
@@ -663,7 +668,7 @@ async def test_refresh_scope_expansion_is_rejected_before_rotation(monkeypatch:
)
with pytest.raises(OAuthProtocolException) as raised:
await TokenService.refresh_token(
- object(),
+ AsyncSession(),
{
'grant_type': 'refresh_token',
'client_id': 'portal-client',
@@ -700,7 +705,9 @@ async def test_refresh_concurrent_rotation_has_one_success_and_reuse_revoke(monk
)
token = generate_refresh_token()
row.token_hash = token_digest(token, _PEPPER)
- state = {'rotated': False, 'reuse': 0, 'mark_now': None}
+ rotated = False
+ reuse_count = 0
+ mark_now = None
lock = asyncio.Lock()
monkeypatch.setattr(
'module_identity.service.token_service.OAuthClientDao.get_by_client_id',
@@ -740,11 +747,12 @@ async def mark_used(*args: object, **kwargs: object) -> bool:
:param kwargs: 传给被调用对象的关键字参数
:return: 是否记录授权凭据被使用的时间
"""
- state['mark_now'] = kwargs.get('now')
+ nonlocal rotated, mark_now
+ mark_now = kwargs.get('now')
async with lock:
- if state['rotated']:
+ if rotated:
return False
- state['rotated'] = True
+ rotated = True
return True
async def reuse(*args: object, **kwargs: object) -> int:
@@ -755,7 +763,8 @@ async def reuse(*args: object, **kwargs: object) -> int:
:param kwargs: 传给被调用对象的关键字参数
:return: 此分支的固定值 ``1``
"""
- state['reuse'] += 1
+ nonlocal reuse_count
+ reuse_count += 1
return 1
monkeypatch.setattr('module_identity.service.token_service.OAuthTokenDao.mark_used', mark_used)
@@ -764,13 +773,13 @@ async def reuse(*args: object, **kwargs: object) -> int:
monkeypatch.setattr(TokenService, '_issue_access_token', lambda *a, **k: _async_value(('access', 600)))
results = await asyncio.gather(
TokenService.refresh_token(
- object(),
+ AsyncSession(),
{'grant_type': 'refresh_token', 'client_id': 'portal-client', 'refresh_token': token},
OAuthClientPrincipal('portal-client', 'public', 'none'),
token_pepper=_PEPPER,
),
TokenService.refresh_token(
- object(),
+ AsyncSession(),
{'grant_type': 'refresh_token', 'client_id': 'portal-client', 'refresh_token': token},
OAuthClientPrincipal('portal-client', 'public', 'none'),
token_pepper=_PEPPER,
@@ -779,9 +788,9 @@ async def reuse(*args: object, **kwargs: object) -> int:
)
assert sum(isinstance(item, TokenResult) for item in results) == 1
assert sum(isinstance(item, RefreshTokenReuseDetected) for item in results) == 1
- assert state['reuse'] == 1
- assert isinstance(state['mark_now'], datetime)
- assert state['mark_now'].tzinfo is UTC
+ assert reuse_count == 1
+ assert isinstance(mark_now, datetime)
+ assert mark_now.tzinfo is UTC
def _async_value(value: object) -> Any:
diff --git a/ruoyi-fastapi-backend/tests/module_identity/support/http.py b/ruoyi-fastapi-backend/tests/module_identity/support/http.py
new file mode 100644
index 000000000..d8549842d
--- /dev/null
+++ b/ruoyi-fastapi-backend/tests/module_identity/support/http.py
@@ -0,0 +1,36 @@
+from urllib.parse import urlencode
+
+from fastapi import FastAPI, Request
+
+
+def make_request(
+ redis: object,
+ *,
+ headers: dict[str, str] | None = None,
+ query: list[tuple[str, str]] | None = None,
+ host: str = '127.0.0.1',
+) -> Request:
+ """
+ 构造携带客户端地址和应用缓存的 HTTP 请求。
+
+ :param redis: 注入到应用状态的测试缓存
+ :param headers: 请求头
+ :param query: 保留顺序和重复键的查询参数
+ :param host: 请求来源地址
+ :return: 供控制器或服务直接使用的请求
+ """
+ app = FastAPI()
+ app.state.redis = redis
+ return Request(
+ {
+ 'type': 'http',
+ 'method': 'GET',
+ 'path': '/',
+ 'app': app,
+ 'headers': [
+ (key.lower().encode('latin-1'), value.encode('latin-1')) for key, value in (headers or {}).items()
+ ],
+ 'query_string': urlencode(query or []).encode('ascii'),
+ 'client': (host, 12345),
+ }
+ )
diff --git a/ruoyi-fastapi-backend/tests/module_identity/support/redis_fakes.py b/ruoyi-fastapi-backend/tests/module_identity/support/redis_fakes.py
index ec2e0a0f1..ee9e02757 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/support/redis_fakes.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/support/redis_fakes.py
@@ -2,12 +2,16 @@
import json
import time
from typing import Any
+from unittest.mock import Mock
+
+from redis.asyncio import Redis
class FakeRedis:
"""
实现本轮服务所用 SET NX、TTL、GET/DEL 和 Lua 等效语义的 FakeRedis。
+ :ivar client: 供被测服务调用的异步 Redis 客户端替身
:ivar values: 当前处理的值集合
:ivar lists: 模拟 Redis 保存的列表数据
:ivar lock: 用于串行访问共享资源的锁
@@ -17,8 +21,9 @@ class FakeRedis:
def __init__(self) -> None:
"""初始化测试夹具的 ``values``, ``lists``, ``lock``, ``set_calls``。"""
+ self.client: Redis = Mock(spec_set=Redis, wraps=self)
self.values: dict[str, tuple[str, float | None]] = {}
- self.lists: dict[str, list[str]] = {}
+ self.lists: dict[str, list[str | bytes]] = {}
self.lock = asyncio.Lock()
self.set_calls: list[tuple[str, dict[str, Any]]] = []
self.eval_calls: list[tuple[str, tuple[Any, ...]]] = []
@@ -86,7 +91,7 @@ async def delete(self, key: str) -> int:
self._purge(key)
return int(self.values.pop(key, None) is not None)
- async def rpush(self, key: str, value: str) -> int:
+ async def rpush(self, key: str, value: str | bytes) -> int:
"""
追加队列元素。
@@ -98,7 +103,7 @@ async def rpush(self, key: str, value: str) -> int:
self.lists.setdefault(key, []).append(value)
return len(self.lists[key])
- async def lpop(self, key: str) -> str | None:
+ async def lpop(self, key: str) -> str | bytes | None:
"""
原子弹出队首元素。
diff --git a/ruoyi-fastapi-backend/tests/module_identity/support/sessions.py b/ruoyi-fastapi-backend/tests/module_identity/support/sessions.py
new file mode 100644
index 000000000..fbd43871c
--- /dev/null
+++ b/ruoyi-fastapi-backend/tests/module_identity/support/sessions.py
@@ -0,0 +1,24 @@
+from sqlalchemy.ext.asyncio import AsyncSession
+
+
+class RecordingSession(AsyncSession):
+ """
+ 记录事务边界的测试会话。
+
+ :ivar commits: 提交次数
+ :ivar rollbacks: 回滚次数
+ """
+
+ def __init__(self) -> None:
+ """创建无绑定的会话并初始化事务计数。"""
+ super().__init__()
+ self.commits = 0
+ self.rollbacks = 0
+
+ async def commit(self) -> None:
+ """记录一次提交。"""
+ self.commits += 1
+
+ async def rollback(self) -> None:
+ """记录一次回滚。"""
+ self.rollbacks += 1
diff --git a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py
index adf64fb96..5ab25af79 100644
--- a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py
@@ -1,9 +1,12 @@
import json
from collections.abc import Generator
from datetime import UTC, datetime
-from types import SimpleNamespace
import pytest
+from fastapi import Request
+from sqlalchemy.ext.asyncio import AsyncSession
+from starlette.responses import Response, StreamingResponse
+from starlette.types import Message
from common.annotation import log_annotation
from common.context import RequestContext
@@ -18,13 +21,14 @@
PluginOperationLogRetentionModel,
PluginOperationLogRetentionResultModel,
)
+from plugins.core.validation.dependency_policy import DependencyInstallPolicyConfig
HTTP_OK = 200
EXPECTED_RETENTION_MATCHED_COUNT = 2
PLUGIN_OPERATION_FAILURE_EXIT_CODE = 10
-def build_request(path: str = '/system/plugin/batch', method: str = 'POST') -> object:
+def build_request(path: str = '/system/plugin/batch', method: str = 'POST') -> Request:
"""
构造测试用请求对象。
@@ -33,33 +37,35 @@ def build_request(path: str = '/system/plugin/batch', method: str = 'POST') -> o
:return: 测试用请求对象
"""
- async def empty_body() -> bytes:
+ async def receive() -> Message:
"""
- 返回测试用空请求体。
+ 提供此次请求的空 HTTP 消息体。
- :return: 此分支的固定值 ``b''``
+ :return: 已完整接收的 HTTP 请求消息
"""
- return b''
-
- return SimpleNamespace(
- url=SimpleNamespace(path=path),
- method=method,
- headers={'User-Agent': 'pytest'},
- client=SimpleNamespace(host='127.0.0.1'),
- query_params={},
- path_params={},
- body=empty_body,
+ return {'type': 'http.request', 'body': b'', 'more_body': False}
+
+ return Request(
+ {
+ 'type': 'http',
+ 'method': method,
+ 'path': path,
+ 'headers': [(b'user-agent', b'pytest')],
+ 'client': ('127.0.0.1', 12345),
+ 'query_string': b'',
+ },
+ receive=receive,
)
-def load_response_body(response: object) -> dict:
+def load_response_body(response: Response) -> dict:
"""
解析测试响应体。
:param response: 当前调用产生的响应
:return: 从响应体解码的 JSON 数据
"""
- return json.loads(response.body.decode())
+ return json.loads(bytes(response.body))
def test_plugin_operation_response_hides_exit_code_from_web_payload() -> None:
@@ -80,7 +86,7 @@ def test_plugin_operation_response_hides_exit_code_from_web_payload() -> None:
assert payload['exit_code'] == PLUGIN_OPERATION_FAILURE_EXIT_CODE
-class FakeAsyncSession:
+class FakeAsyncSession(AsyncSession):
"""
测试用异步数据库会话。
@@ -89,6 +95,7 @@ class FakeAsyncSession:
def __init__(self) -> None:
"""初始化测试会话。"""
+ super().__init__()
self.committed = False
async def commit(self) -> None:
@@ -107,7 +114,7 @@ def fake_request_context(monkeypatch: pytest.MonkeyPatch) -> Generator[CurrentUs
user = CurrentUserModel(
permissions=['*:*:*'],
roles=[],
- user=UserInfoModel(userName='admin', dept=None, role=[]),
+ user=UserInfoModel(user_id=1, user_name='admin', dept=None, role=[]),
)
user_token = RequestContext.set_current_user(user)
pattern_token = RequestContext.set_current_exclude_patterns([])
@@ -169,9 +176,9 @@ async def batch_plugins(
request=build_request('/system/plugin/batch'),
batch_action=PluginBatchActionModel(
operation='install',
- dryRun=True,
- continueOnError=True,
- pluginIds=['demo', 'ai'],
+ dry_run=True,
+ continue_on_error=True,
+ plugin_ids=['demo', 'ai'],
),
)
@@ -282,7 +289,7 @@ def install_plugin_dependencies(
plugin_id: str,
*,
dry_run: bool = True,
- policy_config: object | None = None,
+ policy_config: DependencyInstallPolicyConfig,
) -> dict[str, object]:
"""
记录依赖安装参数。
@@ -384,11 +391,11 @@ async def test_get_system_plugin_operation_log_list_returns_page_payload(monkeyp
"""校验审计列表接口会返回分页负载并透传查询条件。"""
recorded: dict[str, object] = {}
operation_log = PluginOperationLogDetailModel(
- operationId=1,
+ operation_id=1,
operation='install',
- pluginIds=['demo'],
- dryRun=False,
- continueOnError=False,
+ plugin_ids=['demo'],
+ dry_run=False,
+ continue_on_error=False,
status='success',
summary={'total': 1},
result={'ok': True},
@@ -396,10 +403,10 @@ async def test_get_system_plugin_operation_log_list_returns_page_payload(monkeyp
)
page_result = PageModel[PluginOperationLogDetailModel](
rows=[operation_log],
- pageNum=1,
- pageSize=10,
+ page_num=1,
+ page_size=10,
total=1,
- hasNext=False,
+ has_next=False,
)
class FakePluginService:
@@ -437,11 +444,11 @@ async def get_plugin_operation_log_page_list_services(
response = await plugin_controller.get_system_plugin_operation_log_list(
request=build_request('/system/plugin/operation-log/list', method='GET'),
operation_log_page_query=PluginOperationLogPageQueryModel(
- pluginId='demo',
+ plugin_id='demo',
operation='install',
status='success',
- pageNum=1,
- pageSize=10,
+ page_num=1,
+ page_size=10,
),
query_db=query_db,
)
@@ -466,11 +473,11 @@ async def test_query_detail_system_plugin_operation_log_returns_payload(monkeypa
"""校验审计详情接口会返回插件操作审计详情。"""
recorded: dict[str, object] = {}
operation_log = PluginOperationLogDetailModel(
- operationId=1,
+ operation_id=1,
operation='install',
- pluginIds=['demo'],
- dryRun=False,
- continueOnError=False,
+ plugin_ids=['demo'],
+ dry_run=False,
+ continue_on_error=False,
status='success',
summary={'total': 1},
result={'ok': True},
@@ -551,11 +558,11 @@ async def test_retain_system_plugin_operation_log_commits_session(monkeypatch: p
"""校验审计保留策略接口会调用管理服务并提交事务。"""
recorded: dict[str, object] = {}
retention_result = PluginOperationLogRetentionResultModel(
- retentionDays=0,
- cutoffTime=datetime(2026, 5, 22, 12, 0, 0, tzinfo=UTC),
- matchedCount=2,
- deletedCount=0,
- dryRun=True,
+ retention_days=0,
+ cutoff_time=datetime(2026, 5, 22, 12, 0, 0, tzinfo=UTC),
+ matched_count=2,
+ deleted_count=0,
+ dry_run=True,
)
class FakePluginService:
@@ -582,7 +589,7 @@ async def retain_plugin_operation_log_services(
response = await plugin_controller.retain_system_plugin_operation_log(
request=build_request('/system/plugin/operation-log/retention', method='DELETE'),
- retention_query=PluginOperationLogRetentionModel(retentionDays=0, dryRun=True),
+ retention_query=PluginOperationLogRetentionModel(retention_days=0, dry_run=True),
query_db=query_db,
)
@@ -602,11 +609,11 @@ async def test_export_system_plugin_operation_log_uses_operation_dict(
"""校验审计导出接口会使用操作类型字典映射。"""
recorded: dict[str, object] = {}
operation_log = PluginOperationLogDetailModel(
- operationId=1,
+ operation_id=1,
operation='config_set',
- pluginIds=['demo'],
- dryRun=False,
- continueOnError=False,
+ plugin_ids=['demo'],
+ dry_run=False,
+ continue_on_error=False,
status='success',
summary={},
result={},
@@ -673,13 +680,17 @@ async def get_plugin_operation_dict_services(cls, query_db: object) -> dict[str,
response = await plugin_controller.export_system_plugin_operation_log_list(
request=build_request('/system/plugin/operation-log/export'),
- operation_log_export_query=PluginOperationLogExportQueryModel(exportLimit=10),
+ operation_log_export_query=PluginOperationLogExportQueryModel(export_limit=10),
query_db=query_db,
)
- chunks = [chunk async for chunk in response.body_iterator]
+ assert isinstance(response, StreamingResponse)
+ body = bytearray()
+ async for chunk in response.body_iterator:
+ assert isinstance(chunk, bytes | memoryview)
+ body.extend(chunk)
assert response.status_code == HTTP_OK
- assert b''.join(chunks) == b'plugin audit export'
+ assert body == b'plugin audit export'
assert recorded == {
'query_db': query_db,
'export_limit': 10,
diff --git a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_diagnostics_controller.py b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_diagnostics_controller.py
index 1251ef49c..18b9f0bfb 100644
--- a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_diagnostics_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_diagnostics_controller.py
@@ -4,6 +4,7 @@
import pytest
from fastapi import FastAPI, Request
+from sqlalchemy.ext.asyncio import AsyncSession
from common.context import LocaleContext, RequestContext
from i18n.message import I18nMessage
@@ -37,10 +38,10 @@ async def test_diagnose_api_attaches_runtime_without_changing_static_ok(monkeypa
monkeypatch.setattr('plugins.core.runtime.diagnostics_query.read_plugin_runtime_diagnostics', read)
token = RequestContext.set_current_locale(LocaleContext('en-US'))
try:
- response = await diagnose_system_plugin(Request({'type': 'http', 'app': app}), object(), 'demo')
+ response = await diagnose_system_plugin(Request({'type': 'http', 'app': app}), AsyncSession(), 'demo')
finally:
RequestContext.reset_current_locale(token)
- result = json.loads(response.body)
+ result = json.loads(bytes(response.body))
assert result['msgKey'] == 'plugin.runtime.diagnostics.completed'
payload = result['data']
assert result['msg'] == payload['message'] == 'Plugin diagnostic bundle generated'
@@ -64,8 +65,8 @@ async def test_failed_check_remains_visible_but_generation_failure_keeps_error_e
'plugins.core.runtime.diagnostics_query.read_plugin_runtime_diagnostics',
AsyncMock(return_value={'state': 'observed'}),
)
- response = await diagnose_system_plugin(Request({'type': 'http', 'app': FastAPI()}), object(), 'demo')
- result = json.loads(response.body)
+ response = await diagnose_system_plugin(Request({'type': 'http', 'app': FastAPI()}), AsyncSession(), 'demo')
+ result = json.loads(bytes(response.body))
assert result['code'] == (200 if complete else 601)
assert result['data']['ok'] is False
assert result['data']['runtime'] == {'state': 'observed'}
diff --git a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_metrics_controller.py b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_metrics_controller.py
index 644214b7b..c2e219ba9 100644
--- a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_metrics_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_metrics_controller.py
@@ -4,6 +4,7 @@
import pytest
from fastapi import FastAPI, Request
+from fastapi.routing import APIRoute
from common.aspect.interface_auth import CheckUserInterfaceAuth
from module_plugin.controller.plugin_metrics_controller import (
@@ -18,6 +19,7 @@
def test_runtime_metrics_endpoint_is_readonly_and_permission_gated() -> None:
"""运行指标仅通过受插件查询权限保护的 GET 接口公开。"""
route = plugin_metrics_controller.routes[0]
+ assert isinstance(route, APIRoute)
assert route.path == '/system/plugin/runtime/metrics'
assert route.methods == {'GET'}
assert any(
@@ -31,7 +33,7 @@ def test_runtime_metrics_endpoint_is_readonly_and_permission_gated() -> None:
async def test_metrics_endpoint_without_explicit_runtime_reports_unsupported() -> None:
"""未加载显式插件时不可用状态不能伪装成全部指标为零。"""
response = await get_plugin_runtime_metrics(Request({'type': 'http', 'app': FastAPI()}))
- payload = json.loads(response.body)['data']
+ payload = json.loads(bytes(response.body))['data']
assert payload['supported'] is False
assert payload['scope'] == 'unavailable'
@@ -44,14 +46,18 @@ async def test_metrics_endpoint_forwards_plugin_filter() -> None:
reporter.read = AsyncMock(return_value={'ok': True, 'scope': 'current_worker', 'series': []})
app.state.plugin_metrics_reporter = reporter
response = await get_plugin_runtime_metrics(Request({'type': 'http', 'app': app}), 'metric_demo')
- assert json.loads(response.body)['data']['scope'] == 'current_worker'
+ assert json.loads(bytes(response.body))['data']['scope'] == 'current_worker'
reporter.read.assert_awaited_once_with('metric_demo')
@pytest.mark.asyncio
async def test_config_status_is_query_gated_and_never_exposes_config_values(monkeypatch: pytest.MonkeyPatch) -> None:
"""读取敏感配置只用于计算版本,API 与无指标场景均不回显明文。"""
- route = next(route for route in plugin_metrics_controller.routes if route.path.endswith('/config/status'))
+ route = next(
+ route
+ for route in plugin_metrics_controller.routes
+ if isinstance(route, APIRoute) and route.path.endswith('/config/status')
+ )
assert route.methods == {'GET'}
assert any(
isinstance(dependency.dependency, CheckUserInterfaceAuth)
@@ -71,10 +77,10 @@ async def test_config_status_is_query_gated_and_never_exposes_config_values(monk
lambda: runtime,
)
response = await get_plugin_config_status(Request({'type': 'http', 'app': FastAPI()}), 'config_demo')
- data = json.loads(response.body)['data']
+ data = json.loads(bytes(response.body))['data']
assert data['state'] == 'unobserved' and data['scope'] == 'unavailable'
- assert 'private-config-secret' not in response.body.decode() and 'api_key' not in response.body.decode()
+ assert b'private-config-secret' not in bytes(response.body) and b'api_key' not in bytes(response.body)
runtime.get_plugin_config.assert_awaited_once_with('config_demo', reveal_secret=True)
runtime.get_plugin_config.return_value = {'ok': False, 'message': 'private exception value'}
failure = await get_plugin_config_status(Request({'type': 'http', 'app': FastAPI()}), 'config_demo')
- assert 'private exception value' not in failure.body.decode()
+ assert b'private exception value' not in bytes(failure.body)
diff --git a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_release_controller.py b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_release_controller.py
index 96b41744a..fbbcf879b 100644
--- a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_release_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_release_controller.py
@@ -3,6 +3,7 @@
from unittest.mock import AsyncMock
import pytest
+from fastapi.routing import APIRoute
from common.aspect.interface_auth import CheckUserInterfaceAuth
from module_plugin.controller import plugin_release_controller as controller
@@ -12,19 +13,21 @@
def test_artifact_http_endpoints_are_get_only_and_require_query_permission() -> None:
"""验证制品 HTTP 接口只接受查询且要求插件查询权限。"""
- routes = controller.plugin_release_controller.routes
- assert {route.path for route in routes} == {
- '/system/plugin/artifacts/list',
- '/system/plugin/release/status',
- '/system/plugin/release/plan',
- }
- for route in routes:
+ paths = set()
+ for route in controller.plugin_release_controller.routes:
+ assert isinstance(route, APIRoute)
+ paths.add(route.path)
assert route.methods == {'GET'}
assert any(
isinstance(dependency.dependency, CheckUserInterfaceAuth)
and dependency.dependency.perm == 'system:plugin:query'
for dependency in route.dependencies
)
+ assert paths == {
+ '/system/plugin/artifacts/list',
+ '/system/plugin/release/status',
+ '/system/plugin/release/plan',
+ }
@pytest.mark.asyncio
@@ -41,7 +44,7 @@ async def test_readonly_endpoints_forward_filters_and_plan_target(monkeypatch: p
await controller.get_plugin_release_status('demo'),
await controller.plan_plugin_release('demo', DIGEST),
]
- assert all(json.loads(response.body)['success'] for response in responses)
+ assert all(json.loads(bytes(response.body))['success'] for response in responses)
service.catalog.list_artifacts.assert_awaited_once_with('demo')
service.status.assert_awaited_once_with('demo')
service.plan.assert_awaited_once_with('demo', DIGEST)
@@ -60,7 +63,7 @@ def unavailable() -> None:
raise ValueError('签名制品发布功能未启用')
monkeypatch.setattr(controller, 'get_plugin_deployment_service', unavailable)
- body = json.loads((await controller.get_plugin_release_status()).body)
+ body = json.loads(bytes((await controller.get_plugin_release_status()).body))
assert body['success'] is False
assert body['data']['status'] == 'blocked'
assert '未启用' in body['msg']
@@ -80,5 +83,5 @@ def unavailable() -> None:
monkeypatch.setattr(controller, 'get_plugin_deployment_service', unavailable)
response = await controller.list_plugin_artifacts()
- assert json.loads(response.body)['success'] is False
+ assert json.loads(bytes(response.body))['success'] is False
assert b'secret-password' not in response.body
diff --git a/ruoyi-fastapi-backend/tests/module_plugin/service/test_plugin_service.py b/ruoyi-fastapi-backend/tests/module_plugin/service/test_plugin_service.py
index 186329bca..5bf1df79a 100644
--- a/ruoyi-fastapi-backend/tests/module_plugin/service/test_plugin_service.py
+++ b/ruoyi-fastapi-backend/tests/module_plugin/service/test_plugin_service.py
@@ -1,4 +1,5 @@
from pathlib import Path
+from unittest.mock import create_autospec
import pytest
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
@@ -12,6 +13,7 @@
)
from plugins.core.management.entity.do.models import SysPluginOperationLog
from plugins.core.management.service.service import PluginService
+from plugins.core.runtime.service import PluginRuntimeService
def test_get_plugin_operation_service_reuses_singleton() -> None:
@@ -38,7 +40,7 @@ async def test_plugin_diagnose_with_audit_filters_recent_logs(tmp_path: Path) ->
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.get_table()])
try:
async with session_maker() as session:
@@ -68,27 +70,19 @@ async def test_plugin_diagnose_with_audit_filters_recent_logs(tmp_path: Path) ->
)
await session.commit()
- class FakeRuntimeService:
- """测试用插件运行时服务。"""
-
- async def diagnose_plugin(self, plugin_id: str) -> dict[str, object]:
- """
- 返回测试用插件诊断结果。
-
- :param plugin_id: 插件清单中的唯一标识
- :return: 测试用插件诊断结果
- """
- return {
- 'ok': True,
- 'message': '插件诊断包生成完成',
- 'pluginId': plugin_id,
- 'audit': {'available': False, 'items': []},
- }
-
- payload = await PluginOperationService(
- runtime_service=FakeRuntimeService()
- ).diagnose_plugin_with_audit_services(session, 'demo')
+ runtime = create_autospec(PluginRuntimeService, instance=True, spec_set=True)
+ runtime.diagnose_plugin.return_value = {
+ 'ok': True,
+ 'message': '插件诊断包生成完成',
+ 'pluginId': 'demo',
+ 'audit': {'available': False, 'items': []},
+ }
+ payload = await PluginOperationService(runtime_service=runtime).diagnose_plugin_with_audit_services(
+ session, 'demo'
+ )
+ runtime.diagnose_plugin.assert_awaited_once_with('demo')
+ assert isinstance(payload['audit'], dict)
assert payload['audit']['available'] is True
assert payload['audit']['count'] == 1
assert payload['audit']['items'][0]['pluginIds'] == ['demo']
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/conftest.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/conftest.py
index 0b9e08dc9..f1e765331 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/conftest.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/conftest.py
@@ -48,7 +48,7 @@ async def deployment_sessions(tmp_path: Path) -> AsyncIterator[async_sessionmake
await connection.run_sync(
Base.metadata.create_all,
tables=[
- item.__table__
+ item.get_table()
for item in (
SysPlugin,
SysPluginArtifact,
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py
index ab454b148..9e5682552 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py
@@ -1,6 +1,8 @@
import asyncio
+from collections.abc import Awaitable, Callable
from copy import deepcopy
from datetime import UTC, datetime, timedelta
+from typing import Any
from unittest.mock import AsyncMock
import pytest
@@ -141,7 +143,7 @@ def clock(monkeypatch: pytest.MonkeyPatch) -> Clock:
return value
-async def wait(reader: object, **changes: object) -> dict:
+async def wait(reader: Callable[[str], Awaitable[dict[str, Any]]], **changes: object) -> dict:
"""
使用固定身份调用被测等待器,同时允许单项参数边界覆盖。
@@ -398,7 +400,7 @@ async def reader(plugin_id: str) -> dict:
:raises asyncio.CancelledError: 异步操作被取消时
"""
try:
- await asyncio.Future()
+ return await asyncio.Future[dict]()
except asyncio.CancelledError:
if swallow_cancel:
return payload(ready(WORKER, OTHER))
@@ -436,10 +438,11 @@ async def blocked(value: object) -> dict:
将调用保持在等待状态以验证取消行为。
:param value: 待处理的输入值
+ :return: 等待本应提供的发布状态
"""
entered.set()
try:
- await asyncio.Future()
+ return await asyncio.Future[dict]()
finally:
finished.set()
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_deployment_catalog.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_deployment_catalog.py
index a4deb1d3a..29849ffe6 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_deployment_catalog.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_deployment_catalog.py
@@ -33,6 +33,7 @@ async def test_import_indexes_immutable_object_without_installing_or_selecting(
assert (await catalog.list_artifacts('artifact_demo'))['artifacts'][0]['digest'] == stored.digest
async with deployment_sessions() as db:
record = await db.get(SysPluginArtifact, stored.digest)
+ assert record is not None
assert record.created_by == 'publisher-test'
assert record.relative_path == f'artifact_demo/1.0.0/{stored.digest}'
assert (await db.scalars(select(SysPlugin))).all() == []
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_enablement.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_enablement.py
index 10376d3bb..0ae8a119b 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_enablement.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_enablement.py
@@ -49,7 +49,8 @@ async def set_plugin_enabled(self, plugin_id: str, *, enabled: bool, dry_run: bo
:param dry_run: 是否只预览操作结果
:return: 测试指定的启停预检结果
"""
- owner: EnablementFactory = self.owner
+ owner = self.owner
+ assert isinstance(owner, EnablementFactory)
owner.checks.append((plugin_id, enabled, dry_run))
if owner.before_check is not None:
await owner.before_check()
@@ -160,6 +161,7 @@ async def _seed_resources(sessions: async_sessionmaker[AsyncSession], *, disable
status = '1' if disabled else '0'
async with sessions() as db:
plugin = await db.get(SysPlugin, PLUGIN_ID)
+ assert plugin is not None
plugin.enabled = status
db.add(SysMenu(menu_id=PLUGIN_MENU_ID, menu_name='Owned menu', status=status))
db.add(SysMenu(menu_id=OTHER_MENU_ID, menu_name='Unrelated menu', status='0'))
@@ -217,7 +219,9 @@ async def _snapshot(sessions: async_sessionmaker[AsyncSession]) -> dict[str, Any
"""
async with sessions() as db:
plugin = await db.get(SysPlugin, PLUGIN_ID)
+ assert plugin is not None
release = await db.get(SysPluginRelease, PLUGIN_ID)
+ assert release is not None
return {
'plugin': (plugin.enabled, plugin.status, plugin.version, plugin.installed_version),
'release': (
@@ -342,10 +346,18 @@ async def failed_audit(db: AsyncSession, payload: dict[str, Any], actor: str | N
:param actor: 发起操作的主体
:raises RuntimeError: 模拟审计服务不可用
"""
- assert (await db.get(SysPlugin, PLUGIN_ID)).enabled == '1'
- assert (await db.get(SysMenu, PLUGIN_MENU_ID)).status == '1'
- assert (await db.get(SysJob, FIRST_JOB_ID)).status == '1'
- assert (await db.get(SysPluginRelease, PLUGIN_ID)).generation == payload['generation']
+ stored_plugin = await db.get(SysPlugin, PLUGIN_ID)
+ assert stored_plugin is not None
+ assert stored_plugin.enabled == '1'
+ stored_menu = await db.get(SysMenu, PLUGIN_MENU_ID)
+ assert stored_menu is not None
+ assert stored_menu.status == '1'
+ stored_job = await db.get(SysJob, FIRST_JOB_ID)
+ assert stored_job is not None
+ assert stored_job.status == '1'
+ stored_pluginrelease = await db.get(SysPluginRelease, PLUGIN_ID)
+ assert stored_pluginrelease is not None
+ assert stored_pluginrelease.generation == payload['generation']
raise RuntimeError('audit unavailable')
monkeypatch.setattr(enablement_service, '_audit', failed_audit)
@@ -368,6 +380,7 @@ async def test_job_ownership_failure_rolls_back_prior_menu_and_plugin_writes(
)
async with deployment_sessions() as db:
job = await db.get(SysJob, FIRST_JOB_ID)
+ assert job is not None
job.remark = 'Existing user-owned task must not be overwritten'
await db.commit()
before = await _snapshot(deployment_sessions)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_maintenance.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_maintenance.py
index fcb8c0709..75ac1e4e8 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_maintenance.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_maintenance.py
@@ -1,6 +1,6 @@
import base64
import json
-from collections.abc import AsyncIterator
+from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from datetime import timedelta
from pathlib import Path
@@ -271,7 +271,7 @@ class TrackingLock:
"""记录文件发布和索引写入是否在同一锁范围内。"""
@asynccontextmanager
- async def lock(self, plugin_id: str, operation: str) -> AsyncIterator[PluginLifecycleLockResult]:
+ async def lock(self, plugin_id: str, operation: str) -> AsyncGenerator[PluginLifecycleLockResult, None]:
"""
记录导入锁进入与退出顺序。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_service.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_service.py
index 17995139b..ea2963053 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_service.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_service.py
@@ -234,10 +234,13 @@ async def test_install_plan_prepare_select_and_pending_restart_are_distinct(
prepared = await service.prepare(PLUGIN_ID, digest, maintenance=True, actor='operator')
async with deployment_sessions() as db:
row = await db.get(SysPluginRelease, PLUGIN_ID)
+ assert row is not None
assert row.target_digest is None
assert row.prepared_digest == digest
assert row.prepared_version == '1.0.0'
- assert (await db.get(SysPlugin, PLUGIN_ID)).installed_version == '1.0.0'
+ stored = await db.get(SysPlugin, PLUGIN_ID)
+ assert stored is not None
+ assert stored.installed_version == '1.0.0'
again = await service.prepare(PLUGIN_ID, digest, maintenance=True)
assert again['ok']
assert maintenance_factory.calls.count(('install', False, '1.0.0')) == 1
@@ -282,7 +285,9 @@ async def test_same_version_digest_is_not_guessed_from_installed_version(
PLUGIN_ID, imported['digest'], maintenance=True, expected_generation=selected['generation']
)
async with deployment_sessions() as db:
- assert (await db.get(SysPluginRelease, PLUGIN_ID)).target_digest == selected['digest']
+ stored = await db.get(SysPluginRelease, PLUGIN_ID)
+ assert stored is not None
+ assert stored.target_digest == selected['digest']
@pytest.mark.asyncio
@@ -323,6 +328,7 @@ async def test_failed_preparation_clears_proof_and_preserves_previous_target(
await service.prepare(PLUGIN_ID, imported['digest'], maintenance=True)
async with deployment_sessions() as db:
row = await db.get(SysPluginRelease, PLUGIN_ID)
+ assert row is not None
assert row.target_digest == selected['digest']
assert row.generation == selected['generation']
assert row.prepare_status == 'failed'
@@ -362,7 +368,9 @@ async def test_upgrade_and_explicit_code_rollback_preserve_newer_installed_schem
assert maintenance_factory.calls == [*before, ('check', True, '1.0.0')]
async with deployment_sessions() as db:
plugin = await db.get(SysPlugin, PLUGIN_ID)
+ assert plugin is not None
release = await db.get(SysPluginRelease, PLUGIN_ID)
+ assert release is not None
assert plugin.installed_version == '2.0.0'
assert plugin.version == '1.0.0'
assert release.target_digest == first['digest']
@@ -461,6 +469,7 @@ async def failed_audit(*args: Any, **kwargs: Any) -> None:
)
async with deployment_sessions() as db:
row = await db.get(SysPluginRelease, PLUGIN_ID)
+ assert row is not None
assert row.target_digest is None and row.generation == prepared['generation']
assert row.prepared_digest == imported['digest']
@@ -497,7 +506,9 @@ async def failed_audit(*args: Any, **kwargs: Any) -> None:
)
async with deployment_sessions() as db:
plugin = await db.get(SysPlugin, PLUGIN_ID)
+ assert plugin is not None
row = await db.get(SysPluginRelease, PLUGIN_ID)
+ assert row is not None
assert plugin.version == plugin.installed_version == '2.0.0'
assert row.generation == second['generation']
assert row.target_digest == second['digest'] and row.previous_digest == first['digest']
@@ -568,7 +579,9 @@ async def test_real_maintenance_runtime_prepares_minimal_signed_artifact_in_sqli
assert prepared['ok']
async with deployment_sessions() as db:
plugin = await db.get(SysPlugin, PLUGIN_ID)
+ assert plugin is not None
release = await db.get(SysPluginRelease, PLUGIN_ID)
+ assert release is not None
assert plugin.installed_version == '1.0.0'
assert plugin.source == 'artifact'
assert plugin.backend_path == f'artifact:{imported["digest"]}'
@@ -592,6 +605,7 @@ async def test_status_reports_disabled_only_after_worker_confirms_current_genera
selected = await import_prepare_select(service, deployment_archive)
async with deployment_sessions() as db:
plugin = await db.get(SysPlugin, PLUGIN_ID)
+ assert plugin is not None
plugin.enabled = '1'
await PluginReleaseDao.upsert_worker_report(
db,
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_task_delivery.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_task_delivery.py
index 1b49d379c..a4ad2c600 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_task_delivery.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_task_delivery.py
@@ -28,10 +28,10 @@ async def test_task_signed_delivery_preserves_data_and_exercises_crud(
import shutil # noqa: PLC0415
# SQLite 只有 INTEGER PRIMARY KEY 才会生成自增值,宿主生产表使用 BIGINT。
- sqlite_menu = SysMenu.__table__.to_metadata(MetaData())
+ sqlite_menu = SysMenu.get_table().to_metadata(MetaData())
sqlite_menu.c.menu_id.type = Integer()
async with deployment_sessions.kw['bind'].begin() as connection:
- await connection.run_sync(SysMenu.__table__.drop)
+ await connection.run_sync(SysMenu.get_table().drop)
await connection.run_sync(sqlite_menu.create)
# SQLite 不能同时持有生命周期 UoW 与迁移历史的两个写事务;只对宿主维护会话使用自动提交。
# 业务 CRUD 保留下面传入的常规事务会话,真实数据库 CI 不使用此适配。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_worker.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_worker.py
index d4535e5cb..009afec99 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_worker.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_worker.py
@@ -10,7 +10,7 @@
from pathlib import Path
from types import SimpleNamespace
from typing import Any
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
import pytest
import pytest_asyncio
@@ -34,8 +34,10 @@
from plugins.core.runtime.application import PluginApplicationRuntime
from plugins.core.runtime.bootstrap import PluginRuntimeBuilder
from plugins.core.runtime.explicit import ExplicitPluginRuntime
+from plugins.core.runtime.route_guard import UnavailablePluginRouteStateGateway
from plugins.core.runtime.service.lifecycle_lock import NoopPluginLifecycleLock
from plugins.core.runtime.startup import PluginRuntimeStartupManager
+from plugins.core.runtime.startup_gateway import PluginStartupManagementGateway
from utils.time_util import TimezoneUtil
@@ -68,10 +70,10 @@ async def deployment(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncIt
await connection.run_sync(
Base.metadata.create_all,
tables=[
- SysPlugin.__table__,
- SysPluginArtifact.__table__,
- SysPluginRelease.__table__,
- SysPluginWorker.__table__,
+ SysPlugin.get_table(),
+ SysPluginArtifact.get_table(),
+ SysPluginRelease.get_table(),
+ SysPluginWorker.get_table(),
],
)
sessions = async_sessionmaker(engine, expire_on_commit=False)
@@ -151,7 +153,9 @@ async def publish(deployment: SimpleNamespace, version: str = '1.0.0', *, fail:
expected_workers=2,
)
await db.commit()
- return result['digest']
+ digest = result['digest']
+ assert isinstance(digest, str)
+ return digest
async def activate_worker(config: PluginDeploymentConfig, sessions: Any) -> tuple[Any, Any]:
@@ -170,7 +174,7 @@ async def activate_worker(config: PluginDeploymentConfig, sessions: Any) -> tupl
async with sessions() as db:
registry = PluginRegistry.build(builder.discover_plugins(), await PluginDao.get_plugin_list(db))
app.state.plugin_registry = registry
- runtime = ExplicitPluginRuntime(SimpleNamespace())
+ runtime = ExplicitPluginRuntime(UnavailablePluginRouteStateGateway())
app.state.plugin_explicit_runtime = runtime
for plugin in registry.list_enabled_plugins():
runtime.prepare(plugin, app, startup_write_enabled=True)
@@ -192,6 +196,7 @@ async def summary(deployment: SimpleNamespace, plugin_id: str = 'release_demo')
"""
async with deployment.sessions() as db:
release = await PluginReleaseDao.get_release(db, plugin_id)
+ assert release is not None
reports = await PluginReleaseDao.list_worker_reports(db)
return aggregate_release(release, reports, now=TimezoneUtil.utc_now(), ttl_seconds=6).to_payload()
@@ -201,7 +206,7 @@ async def test_lock_deadline_only_limits_acquisition(deployment: SimpleNamespace
"""锁截止时间仅限制获取锁。"""
@asynccontextmanager
- async def busy_lock(_plugin_id: str, _operation: str) -> AsyncIterator[SimpleNamespace]:
+ async def busy_lock(_plugin_id: str, _operation: str) -> AsyncGenerator[SimpleNamespace, None]:
"""
提供未能取得的插件生命周期锁。
@@ -304,6 +309,7 @@ async def test_imported_unselected_id_cannot_fall_back_to_a_source_directory(dep
await publish(deployment)
async with deployment.sessions() as db:
release = await PluginReleaseDao.get_release(db, 'release_demo')
+ assert release is not None
release.target_digest = None
await db.commit()
shutil.copytree(
@@ -327,8 +333,10 @@ async def test_disabled_snapshot_reports_stopped_without_executing_entrypoint(de
await publish(deployment)
async with deployment.sessions() as db:
plugin = await PluginDao.get_plugin_by_id(db, 'release_demo')
+ assert plugin is not None
plugin.enabled = '1'
release = await PluginReleaseDao.get_release(db, 'release_demo')
+ assert release is not None
release.expected_workers = 1
await db.commit()
worker, runtime = await activate_worker(deployment.config, deployment.sessions)
@@ -405,27 +413,17 @@ async def test_real_application_startup_does_not_run_artifact_install_or_resourc
await publish(deployment)
monkeypatch.setattr('config.database.DataSourceRegistry.session', deployment.sessions)
- class ReadOnlyGateway:
- """
- 提供只读工作进程使用的插件查询接口。
-
- :cvar list_plugins: 模拟查询插件列表的操作
- :cvar install_plugin_resources: 模拟安装插件资源的操作
- :cvar upsert_discovered_plugin: 模拟写入已发现插件记录的操作
- """
-
- list_plugins = staticmethod(PluginDao.get_plugin_list)
- install_plugin_resources = AsyncMock(
- side_effect=AssertionError('startup must not reinstall artifact resources')
- )
- upsert_discovered_plugin = AsyncMock(side_effect=AssertionError('startup must not install artifacts'))
-
- gateway = ReadOnlyGateway()
+ gateway = Mock(
+ spec_set=PluginStartupManagementGateway,
+ list_plugins=PluginDao.get_plugin_list,
+ install_plugin_resources=AsyncMock(side_effect=AssertionError('startup must not reinstall artifact resources')),
+ upsert_discovered_plugin=AsyncMock(side_effect=AssertionError('startup must not install artifacts')),
+ )
builder = PluginRuntimeBuilder(deployment.config.backend_root)
manager = PluginRuntimeStartupManager(
builder,
management_gateway=gateway,
- route_state_gateway=SimpleNamespace(),
+ route_state_gateway=UnavailablePluginRouteStateGateway(),
default_enabled_builtin_plugin_ids={'release_demo'},
)
worker = PluginReleaseWorker(deployment.config, session_factory=deployment.sessions)
@@ -453,7 +451,10 @@ async def test_worker_failure_does_not_mark_global_plugin_error(deployment: Simp
worker, runtime = await activate_worker(deployment.config, deployment.sessions)
app = worker.app
app.state.plugin_release_worker = worker
- gateway = SimpleNamespace(mark_plugin_error=AsyncMock(side_effect=AssertionError('must remain per-worker')))
+ gateway = Mock(
+ spec_set=PluginStartupManagementGateway,
+ mark_plugin_error=AsyncMock(side_effect=AssertionError('must remain per-worker')),
+ )
manager = PluginRuntimeStartupManager(management_gateway=gateway)
try:
await manager.mark_plugin_runtime_error(app, 'release_demo', 'one worker failed')
@@ -461,6 +462,7 @@ async def test_worker_failure_does_not_mark_global_plugin_error(deployment: Simp
assert (await summary(deployment))['status'] == 'failed'
async with deployment.sessions() as db:
plugin = await PluginDao.get_plugin_by_id(db, 'release_demo')
+ assert plugin is not None
assert plugin.status == 'installed'
assert plugin.enabled == '0'
finally:
@@ -477,7 +479,8 @@ async def test_failed_artifact_stays_disabled_after_source_failure_reloads_regis
await publish(deployment)
monkeypatch.setattr('config.database.DataSourceRegistry.session', deployment.sessions)
builder = PluginRuntimeBuilder(deployment.config.backend_root)
- gateway = SimpleNamespace(
+ gateway = Mock(
+ spec_set=PluginStartupManagementGateway,
list_plugins=PluginDao.get_plugin_list,
mark_plugin_error=AsyncMock(return_value=SimpleNamespace(is_success=True)),
)
@@ -624,6 +627,7 @@ async def test_restarted_process_loads_upgrade_then_rollback_without_downgrading
assert reports[0]['version'] == '2.0.0'
async with deployment.sessions() as db:
release = await PluginReleaseDao.get_release(db, 'release_demo')
+ assert release is not None
generation = release.generation
await PluginReleaseDao.set_preparation_status(
db,
@@ -645,7 +649,9 @@ async def test_restarted_process_loads_upgrade_then_rollback_without_downgrading
assert reports[0]['version'] == '1.0.0'
assert (await summary(deployment))['status'] == 'active'
async with deployment.sessions() as db:
- assert (await PluginDao.get_plugin_by_id(db, 'release_demo')).installed_version == '2.0.0'
+ stored_plugin = await PluginDao.get_plugin_by_id(db, 'release_demo')
+ assert stored_plugin is not None
+ assert stored_plugin.installed_version == '2.0.0'
@pytest.mark.asyncio
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/discovery/test_registry.py b/ruoyi-fastapi-backend/tests/plugins/core/discovery/test_registry.py
index ef615e1c2..0dc846e4f 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/discovery/test_registry.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/discovery/test_registry.py
@@ -2,8 +2,9 @@
from plugins.core.discovery.registry import PluginRegistry
from plugins.core.discovery.scanner import DiscoveredPlugin
-from plugins.core.management.entity.vo.schemas import PluginModel
+from plugins.core.management.entity.vo.schemas import PluginEnabled, PluginModel
from plugins.core.manifest.schema import PluginManifest
+from plugins.core.state import PluginStatus
def build_discovered_plugin(
@@ -37,7 +38,9 @@ def build_discovered_plugin(
return DiscoveredPlugin(manifest=manifest, backend_path=backend_path, manifest_path=manifest_path)
-def build_database_plugin(plugin_id: str = 'demo', *, enabled: str = '0', status: str = 'installed') -> PluginModel:
+def build_database_plugin(
+ plugin_id: str = 'demo', *, enabled: PluginEnabled = '0', status: PluginStatus = 'installed'
+) -> PluginModel:
"""
构造测试用数据库插件状态。
@@ -47,10 +50,10 @@ def build_database_plugin(plugin_id: str = 'demo', *, enabled: str = '0', status
:return: 测试用数据库插件状态
"""
return PluginModel(
- pluginId=plugin_id,
- pluginName='演示插件',
+ plugin_id=plugin_id,
+ plugin_name='演示插件',
version='1.0.0',
- installedVersion='1.0.0',
+ installed_version='1.0.0',
enabled=enabled,
status=status,
)
@@ -87,10 +90,10 @@ def test_registry_marks_pending_upgrade_when_versions_differ(tmp_path: Path) ->
"""校验源码版本高于已安装版本时标记待升级。"""
discovered_plugin = build_discovered_plugin(tmp_path, version='1.1.0')
database_plugin = PluginModel(
- pluginId='demo',
- pluginName='演示插件',
+ plugin_id='demo',
+ plugin_name='演示插件',
version='1.1.0',
- installedVersion='1.0.0',
+ installed_version='1.0.0',
enabled='0',
status='installed',
)
@@ -107,10 +110,10 @@ def test_registry_keeps_installed_when_source_version_is_older(tmp_path: Path) -
"""校验源码版本低于已安装版本时不会误标记待升级。"""
discovered_plugin = build_discovered_plugin(tmp_path, version='1.2.0')
database_plugin = PluginModel(
- pluginId='demo',
- pluginName='演示插件',
+ plugin_id='demo',
+ plugin_name='演示插件',
version='1.2.0',
- installedVersion='1.10.0',
+ installed_version='1.10.0',
enabled='0',
status='installed',
)
@@ -126,10 +129,10 @@ def test_registry_keeps_error_status(tmp_path: Path) -> None:
"""校验异常状态插件不会继续进入启用运行时列表。"""
discovered_plugin = build_discovered_plugin(tmp_path)
database_plugin = PluginModel(
- pluginId='demo',
- pluginName='演示插件',
+ plugin_id='demo',
+ plugin_name='演示插件',
version='1.0.0',
- installedVersion='1.0.0',
+ installed_version='1.0.0',
enabled='0',
status='error',
)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/management/test_artifact_views.py b/ruoyi-fastapi-backend/tests/plugins/core/management/test_artifact_views.py
index a544fdfc2..1ad2b92f8 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/management/test_artifact_views.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/management/test_artifact_views.py
@@ -3,6 +3,7 @@
from unittest.mock import AsyncMock
import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.management.dao.dao import PluginDao
@@ -47,15 +48,19 @@ async def test_disabled_feature_preserves_artifact_identity_and_never_queries_re
get_release = AsyncMock(side_effect=AssertionError('feature disabled must not query release tables'))
monkeypatch.setattr(release_view.PluginReleaseDao, 'get_release', get_release)
backend_plugins = tmp_path / 'backend' / 'plugins'
- model = await PluginService.plugin_detail_services(object(), 'demo', backend_root=backend_plugins)
+ model = await PluginService.plugin_detail_services(AsyncSession(), 'demo', backend_root=backend_plugins)
+ assert model is not None
assert model.source == 'artifact'
assert model.installed_version == '2.0.0'
+ assert model.release is not None
assert model.release['status'] == 'unavailable'
+ assert model.capability is not None
assert model.capability['runtimeManageable'] is False
assert 'purge' in model.capability['blockedOperations']
items = await PluginService.get_plugin_page_list_services(
- object(), PluginPageQueryModel(), is_page=False, backend_root=backend_plugins
+ AsyncSession(), PluginPageQueryModel(), is_page=False, backend_root=backend_plugins
)
+ assert isinstance(items, list)
assert len(items) == 1
assert items[0]['source'] == 'artifact'
get_release.assert_not_awaited()
@@ -149,12 +154,14 @@ def discovered(artifact: object, generation: str) -> DiscoveredPlugin:
monkeypatch.setattr(release_view, 'PluginArtifactCatalog', Catalog)
model = await release_view.build_artifact_plugin_view(
- object(), artifact_record(), tmp_path / 'backend' / 'plugins', None, PluginService._build_plugin_model
+ AsyncSession(), artifact_record(), tmp_path / 'backend' / 'plugins', None, PluginService._build_plugin_model
)
assert model.source == 'artifact'
assert model.installed_version == '2.0.0'
assert model.status == 'installed'
+ assert model.capability is not None
assert model.capability['runtimeManageable'] is False
+ assert model.release is not None
assert model.release['targetDigest'] == DIGEST
assert model.release['preparedDigest'] == DIGEST
assert model.release['previousDigest'] == PREVIOUS_DIGEST
@@ -177,4 +184,4 @@ async def test_artifact_metadata_cannot_be_purged_as_orphan(monkeypatch: pytest.
"""验证制品插件不会被当作孤儿记录允许清理。"""
monkeypatch.setattr(PluginDao, 'get_plugin_by_id', AsyncMock(return_value=artifact_record()))
with pytest.raises(ValueError, match='制品插件不能'):
- await getattr(PluginService, method)(object(), 'demo')
+ await getattr(PluginService, method)(AsyncSession(), 'demo')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/management/test_menu_installer.py b/ruoyi-fastapi-backend/tests/plugins/core/management/test_menu_installer.py
index 4f6507316..1c6f3ed05 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/management/test_menu_installer.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/management/test_menu_installer.py
@@ -1,7 +1,10 @@
from types import SimpleNamespace
import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+from module_admin.entity.vo.menu_vo import MenuModel
+from plugins.core.management.entity.vo.schemas import PluginMenuModel
from plugins.core.management.service import menus as menu_service
from plugins.core.management.service.menus import PluginMenuInstaller
from plugins.core.manifest.menu_key import PluginMenuKeyBuilder
@@ -145,7 +148,7 @@ async def get_sys_menu_by_name_path(
return None
@classmethod
- async def add_sys_menu(cls, db: object, menu: object) -> SimpleNamespace:
+ async def add_sys_menu(cls, db: object, menu: MenuModel) -> SimpleNamespace:
"""
新增系统菜单。
@@ -187,7 +190,7 @@ async def update_sys_menu_status_by_ids(cls, db: object, menu_ids: list[int], st
cls.menus[menu_id].status = status
@classmethod
- async def add_plugin_menu(cls, db: object, plugin_menu: object) -> SimpleNamespace:
+ async def add_plugin_menu(cls, db: object, plugin_menu: PluginMenuModel) -> SimpleNamespace:
"""
新增插件菜单关联。
@@ -202,7 +205,7 @@ async def add_plugin_menu(cls, db: object, plugin_menu: object) -> SimpleNamespa
return plugin_menu_model
@classmethod
- async def update_plugin_menu_by_key(cls, db: object, plugin_menu: object) -> None:
+ async def update_plugin_menu_by_key(cls, db: object, plugin_menu: PluginMenuModel) -> None:
"""
根据插件菜单自然键更新插件菜单关联。
@@ -215,7 +218,7 @@ async def update_plugin_menu_by_key(cls, db: object, plugin_menu: object) -> Non
]
@classmethod
- async def update_plugin_menu_key_by_menu_id(cls, db: object, plugin_menu: object) -> None:
+ async def update_plugin_menu_key_by_menu_id(cls, db: object, plugin_menu: PluginMenuModel) -> None:
"""
根据菜单 ID 更新插件菜单自然键。
@@ -316,7 +319,7 @@ async def test_plugin_menu_installer_inserts_manifest_menu_tree(monkeypatch: pyt
FakePluginDao.reset()
monkeypatch.setattr(menu_service, 'PluginDao', FakePluginDao)
- installed_menus = await PluginMenuInstaller(object()).install_manifest_menus(build_manifest())
+ installed_menus = await PluginMenuInstaller(AsyncSession()).install_manifest_menus(build_manifest())
assert [menu.menu_key for menu in installed_menus] == ['route:demo/demo#Layout', 'perm:demo:page:list']
assert FakePluginDao.menus[PARENT_MENU_ID].menu_name == '演示目录'
@@ -345,7 +348,7 @@ async def test_plugin_menu_installer_uses_permission_name_for_auto_button(
)
)
- installed_menus = await PluginMenuInstaller(object()).install_manifest_menus(manifest)
+ installed_menus = await PluginMenuInstaller(AsyncSession()).install_manifest_menus(manifest)
button_menu = FakePluginDao.menus[CHILD_MENU_ID + 1]
assert [menu.menu_key for menu in installed_menus] == [
@@ -379,7 +382,7 @@ async def test_plugin_menu_installer_reuses_existing_plugin_menu(monkeypatch: py
)
monkeypatch.setattr(menu_service, 'PluginDao', FakePluginDao)
- await PluginMenuInstaller(object()).install_manifest_menus(build_manifest())
+ await PluginMenuInstaller(AsyncSession()).install_manifest_menus(build_manifest())
assert FakePluginDao.menus[EXISTING_MENU_ID].menu_name == '演示目录'
assert FakePluginDao.menus[EXISTING_MENU_ID].remark == '旧备注 | plugin:demo'
@@ -403,7 +406,7 @@ async def test_plugin_menu_installer_does_not_reuse_unowned_existing_menu(
)
monkeypatch.setattr(menu_service, 'PluginDao', FakePluginDao)
- await PluginMenuInstaller(object()).install_manifest_menus(build_manifest())
+ await PluginMenuInstaller(AsyncSession()).install_manifest_menus(build_manifest())
assert FakePluginDao.menus[EXISTING_MENU_ID].menu_name == '平台菜单'
assert FakePluginDao.menus[EXISTING_MENU_ID].remark == 'core menu'
@@ -423,7 +426,7 @@ async def test_plugin_menu_installer_updates_plugin_menu_status(monkeypatch: pyt
)
monkeypatch.setattr(menu_service, 'PluginDao', FakePluginDao)
- await PluginMenuInstaller(object()).set_plugin_menu_status('demo', '1')
+ await PluginMenuInstaller(AsyncSession()).set_plugin_menu_status('demo', '1')
assert FakePluginDao.menus[PARENT_MENU_ID].status == '1'
@@ -433,7 +436,7 @@ async def test_plugin_menu_installer_removes_menus_deleted_from_manifest(monkeyp
"""校验升级时从 manifest 删除的菜单不会继续残留。"""
FakePluginDao.reset()
monkeypatch.setattr(menu_service, 'PluginDao', FakePluginDao)
- installer = PluginMenuInstaller(object())
+ installer = PluginMenuInstaller(AsyncSession())
await installer.install_manifest_menus(build_manifest())
empty_manifest = PluginManifest.model_validate(
{
@@ -453,13 +456,13 @@ async def test_plugin_menu_installer_removes_menus_deleted_from_manifest(monkeyp
def test_plugin_translation_maps_keep_menu_identity_and_support_future_locales() -> None:
"""验证插件菜单保留原有身份字段,并允许声明未来语言的译名。"""
menu = PluginMenuManifest(
- name='新增', nameI18n={'en-US': 'Add', 'ja-JP': '追加'}, path='add', component='', perms='demo:add', type='F'
+ name='新增', name_i18n={'en-US': 'Add', 'ja-JP': '追加'}, path='add', component='', perms='demo:add', type='F'
)
assert PluginMenuKeyBuilder.build(menu, 'perm:demo:list') == 'button:perm:demo:list/新增#demo:add'
model = PluginMenuInstaller._build_menu_model('demo', menu, PARENT_MENU_ID)
assert model.menu_name == '新增'
assert model.menu_name_i18n == {'en-US': 'Add', 'ja-JP': '追加'}
- permission = PluginPermissionManifest(code='demo:edit', name='修改', nameI18n={'en-US': 'Edit'})
+ permission = PluginPermissionManifest(code='demo:edit', name='修改', name_i18n={'en-US': 'Edit'})
button = PluginMenuInstaller._build_permission_button_menu(permission, 1)
assert button.name_i18n == {'en-US': 'Edit'}
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/management/test_plugin_state.py b/ruoyi-fastapi-backend/tests/plugins/core/management/test_plugin_state.py
index 6ba551999..d95369f22 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/management/test_plugin_state.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/management/test_plugin_state.py
@@ -2,13 +2,15 @@
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
+from unittest.mock import MagicMock
import pytest
from openpyxl import load_workbook
-from sqlalchemy import text, update
+from sqlalchemy import UniqueConstraint, text, update
from sqlalchemy.exc import IntegrityError
-from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from sqlalchemy.ext.asyncio import AsyncConnection, AsyncSession, async_sessionmaker, create_async_engine
+from common.vo import PageModel
from config.database import Base
from module_admin.dao.job_dao import JobDao
from module_admin.entity.do.job_do import SysJob
@@ -34,7 +36,7 @@
PluginPageQueryModel,
)
from plugins.core.management.service.config import PluginConfigManager
-from plugins.core.management.service.gateway import PluginManagementRuntimeGateway
+from plugins.core.management.service.gateway import PluginManagementLifecycleUnitOfWork, PluginManagementRuntimeGateway
from plugins.core.management.service.logs import PluginOperationLogBuilder
from plugins.core.management.service.service import PluginService
from plugins.core.manifest.schema import PluginManifest
@@ -50,13 +52,49 @@
EXPECTED_PERMISSION_BUTTON_MENU_COUNT = 5
+@pytest.mark.asyncio
+async def test_lifecycle_unit_of_work_exposes_only_the_active_session() -> None:
+ """验证工作单元只在事务期间提供会话,重新进入时使用新会话。"""
+ unit = PluginManagementLifecycleUnitOfWork(async_sessionmaker(), PluginService)
+ with pytest.raises(RuntimeError, match='事务尚未打开'):
+ _ = unit.session
+ async with unit:
+ first_session = unit.session
+ assert isinstance(first_session, AsyncSession)
+ assert unit.session is first_session
+ with pytest.raises(RuntimeError, match='事务尚未打开'):
+ _ = unit.session
+ async with unit:
+ assert unit.session is not first_session
+
+
+@pytest.mark.asyncio
+async def test_lifecycle_unit_of_work_releases_session_when_close_fails() -> None:
+ """验证业务异常传入会话,关闭失败后工作单元也会释放会话引用。"""
+ factory = MagicMock()
+ manager = factory.return_value
+ manager.__aexit__.side_effect = RuntimeError('关闭失败')
+ unit = PluginManagementLifecycleUnitOfWork(factory, PluginService)
+ error = ValueError('操作失败')
+ with pytest.raises(RuntimeError, match='关闭失败'):
+ async with unit:
+ raise error
+ exc_type, exc, traceback = manager.__aexit__.await_args.args
+ assert exc_type is ValueError
+ assert exc is error
+ assert traceback is not None
+ assert unit.session_context is None
+ with pytest.raises(RuntimeError, match='事务尚未打开'):
+ _ = unit.session
+
+
@pytest.mark.asyncio
async def test_plugin_table_rejects_invalid_state_domains() -> None:
"""校验数据库约束拒绝绕过服务层写入非法启停值和生命周期状态。"""
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.get_table()])
try:
async with session_maker() as session:
@@ -88,7 +126,7 @@ async def test_plugin_table_rejects_invalid_state_domains() -> None:
await engine.dispose()
-async def create_sqlite_sys_job_table(connection: object) -> None:
+async def create_sqlite_sys_job_table(connection: AsyncConnection) -> None:
"""
创建适配 SQLite 的测试用 sys_job 表。
@@ -123,7 +161,7 @@ async def create_sqlite_sys_job_table(connection: object) -> None:
)
-async def create_sqlite_sys_menu_table(connection: object) -> None:
+async def create_sqlite_sys_menu_table(connection: AsyncConnection) -> None:
"""
创建适配 SQLite 的测试用 sys_menu 表。
@@ -372,18 +410,22 @@ def test_plugin_tables_are_registered_with_expected_names() -> None:
assert SysPluginMigration.__tablename__ == 'sys_plugin_migration'
assert SysPluginConfig.__tablename__ == 'sys_plugin_config'
assert SysPluginOperationLog.__tablename__ == 'sys_plugin_operation_log'
- assert 'plugin_id' in SysPlugin.__table__.columns
- assert 'last_error' in SysPlugin.__table__.columns
- assert 'continue_on_error' in SysPluginOperationLog.__table__.columns
- assert set(SysPluginMenu.__table__.primary_key.columns.keys()) == {'plugin_id', 'menu_id'}
- unique_constraints = {constraint.name: constraint for constraint in SysPluginMenu.__table__.constraints}
+ assert 'plugin_id' in SysPlugin.get_table().columns
+ assert 'last_error' in SysPlugin.get_table().columns
+ assert 'continue_on_error' in SysPluginOperationLog.get_table().columns
+ assert set(SysPluginMenu.get_table().primary_key.columns.keys()) == {'plugin_id', 'menu_id'}
+ unique_constraints = {
+ constraint.name: constraint
+ for constraint in SysPluginMenu.get_table().constraints
+ if isinstance(constraint, UniqueConstraint)
+ }
assert set(unique_constraints['uk_sys_plugin_menu_key'].columns.keys()) == {'plugin_id', 'menu_key'}
- assert set(SysPluginMigration.__table__.primary_key.columns.keys()) == {'plugin_id', 'migration_path'}
- assert 'attempt_count' in SysPluginMigration.__table__.columns
- assert 'started_time' in SysPluginMigration.__table__.columns
- assert 'finished_time' in SysPluginMigration.__table__.columns
- assert 'update_time' in SysPluginMigration.__table__.columns
- assert set(SysPluginConfig.__table__.primary_key.columns.keys()) == {'plugin_id', 'config_key'}
+ assert set(SysPluginMigration.get_table().primary_key.columns.keys()) == {'plugin_id', 'migration_path'}
+ assert 'attempt_count' in SysPluginMigration.get_table().columns
+ assert 'started_time' in SysPluginMigration.get_table().columns
+ assert 'finished_time' in SysPluginMigration.get_table().columns
+ assert 'update_time' in SysPluginMigration.get_table().columns
+ assert set(SysPluginConfig.get_table().primary_key.columns.keys()) == {'plugin_id', 'config_key'}
def test_plugin_job_model_builder_maps_manifest_to_job_model(tmp_path: Path) -> None:
@@ -477,7 +519,7 @@ async def test_upsert_discovered_plugin_persists_plugin(tmp_path: Path) -> None:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.__table__, SysPluginMenu.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.get_table(), SysPluginMenu.get_table()])
try:
async with session_maker() as session:
@@ -507,7 +549,7 @@ async def test_mark_plugin_installed_updates_installed_version(tmp_path: Path) -
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.__table__, SysPluginMenu.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.get_table(), SysPluginMenu.get_table()])
try:
async with session_maker() as session:
@@ -540,7 +582,7 @@ async def test_install_plugin_with_disabled_menus_can_be_enabled_later(tmp_path:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.__table__, SysPluginMenu.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.get_table(), SysPluginMenu.get_table()])
await create_sqlite_sys_menu_table(connection)
await create_sqlite_sys_job_table(connection)
@@ -590,7 +632,7 @@ async def test_install_plugin_menu_services_generates_permission_buttons(tmp_pat
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginMenu.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginMenu.get_table()])
await create_sqlite_sys_menu_table(connection)
try:
@@ -617,6 +659,9 @@ async def test_install_plugin_menu_services_generates_permission_buttons(tmp_pat
'demo',
'button:perm:demo:user:list/删除#demo:user:remove',
)
+ assert add_button_link is not None
+ assert edit_button_link is not None
+ assert remove_button_link is not None
add_button = await PluginDao.get_sys_menu_by_id(session, add_button_link.menu_id)
edit_button = await PluginDao.get_sys_menu_by_id(session, edit_button_link.menu_id)
remove_button = await PluginDao.get_sys_menu_by_id(session, remove_button_link.menu_id)
@@ -645,7 +690,7 @@ async def test_mark_plugin_uninstalled_clears_installed_version(tmp_path: Path)
async with engine.begin() as connection:
await connection.run_sync(
Base.metadata.create_all,
- tables=[SysMenu.__table__, SysRoleMenu.__table__, SysPlugin.__table__, SysPluginMenu.__table__],
+ tables=[SysMenu.get_table(), SysRoleMenu.get_table(), SysPlugin.get_table(), SysPluginMenu.get_table()],
)
await create_sqlite_sys_job_table(connection)
@@ -741,7 +786,7 @@ async def test_mark_plugin_error_preserves_desired_state_and_isolates_resources(
async with engine.begin() as connection:
await connection.run_sync(
Base.metadata.create_all,
- tables=[SysMenu.__table__, SysPlugin.__table__, SysPluginMenu.__table__],
+ tables=[SysMenu.get_table(), SysPlugin.get_table(), SysPluginMenu.get_table()],
)
await create_sqlite_sys_job_table(connection)
@@ -816,7 +861,7 @@ async def test_recover_plugin_dependency_error_restores_lifecycle_state(
async with engine.begin() as connection:
await connection.run_sync(
Base.metadata.create_all,
- tables=[SysMenu.__table__, SysPlugin.__table__, SysPluginMenu.__table__],
+ tables=[SysMenu.get_table(), SysPlugin.get_table(), SysPluginMenu.get_table()],
)
await create_sqlite_sys_job_table(connection)
@@ -862,7 +907,7 @@ async def test_recover_plugin_dependency_error_preserves_explicit_disable_intent
async with engine.begin() as connection:
await connection.run_sync(
Base.metadata.create_all,
- tables=[SysMenu.__table__, SysPlugin.__table__, SysPluginMenu.__table__],
+ tables=[SysMenu.get_table(), SysPlugin.get_table(), SysPluginMenu.get_table()],
)
await create_sqlite_sys_job_table(connection)
@@ -906,7 +951,7 @@ async def test_recover_plugin_dependency_error_preserves_unrelated_error(tmp_pat
async with engine.begin() as connection:
await connection.run_sync(
Base.metadata.create_all,
- tables=[SysMenu.__table__, SysPlugin.__table__, SysPluginMenu.__table__],
+ tables=[SysMenu.get_table(), SysPlugin.get_table(), SysPluginMenu.get_table()],
)
await create_sqlite_sys_job_table(connection)
@@ -944,7 +989,7 @@ async def test_enable_plugin_rejects_uninstalled_error_state(tmp_path: Path) ->
async with engine.begin() as connection:
await connection.run_sync(
Base.metadata.create_all,
- tables=[SysMenu.__table__, SysPlugin.__table__, SysPluginMenu.__table__],
+ tables=[SysMenu.get_table(), SysPlugin.get_table(), SysPluginMenu.get_table()],
)
await create_sqlite_sys_job_table(connection)
@@ -981,7 +1026,7 @@ async def test_enable_plugin_rejects_error_state_without_repair_lifecycle(tmp_pa
async with engine.begin() as connection:
await connection.run_sync(
Base.metadata.create_all,
- tables=[SysMenu.__table__, SysPlugin.__table__, SysPluginMenu.__table__],
+ tables=[SysMenu.get_table(), SysPlugin.get_table(), SysPluginMenu.get_table()],
)
await create_sqlite_sys_job_table(connection)
@@ -1121,7 +1166,7 @@ async def test_disable_plugin_pauses_plugin_jobs(tmp_path: Path) -> None:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.__table__, SysPluginMenu.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.get_table(), SysPluginMenu.get_table()])
await create_sqlite_sys_job_table(connection)
try:
@@ -1153,7 +1198,7 @@ async def test_enable_plugin_restores_plugin_jobs(tmp_path: Path) -> None:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.__table__, SysPluginMenu.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.get_table(), SysPluginMenu.get_table()])
await create_sqlite_sys_job_table(connection)
try:
@@ -1192,7 +1237,7 @@ async def test_get_plugin_page_list_filters_by_status(tmp_path: Path) -> None:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.__table__, SysPluginMenu.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.get_table(), SysPluginMenu.get_table()])
try:
async with session_maker() as session:
@@ -1212,6 +1257,7 @@ async def test_get_plugin_page_list_filters_by_status(tmp_path: Path) -> None:
frontend_root=tmp_path / 'frontend_plugins',
)
+ assert isinstance(plugin_page_result, PageModel)
assert plugin_page_result.total == 1
assert plugin_page_result.rows[0]['pluginId'] == 'demo'
assert plugin_page_result.rows[0]['status'] == 'installed'
@@ -1225,7 +1271,7 @@ async def test_get_plugin_page_list_includes_discovered_plugins_without_database
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.get_table()])
try:
async with session_maker() as session:
@@ -1249,6 +1295,7 @@ async def test_get_plugin_page_list_includes_discovered_plugins_without_database
frontend_root=tmp_path / 'frontend_plugins',
)
+ assert isinstance(plugin_page_result, PageModel)
assert plugin_page_result.total == 1
assert plugin_page_result.rows[0]['pluginId'] == 'demo'
assert plugin_page_result.rows[0]['pluginName'] == '演示插件'
@@ -1264,7 +1311,7 @@ async def test_get_plugin_page_list_includes_database_orphan_for_metadata_purge(
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.get_table()])
try:
async with session_maker() as session:
@@ -1295,6 +1342,7 @@ async def test_get_plugin_page_list_includes_database_orphan_for_metadata_purge(
frontend_root=tmp_path / 'frontend_plugins',
)
+ assert isinstance(plugin_page_result, PageModel)
assert plugin_page_result.total == 1
orphan_row = plugin_page_result.rows[0]
assert orphan_row['pluginId'] == 'orphan'
@@ -1313,7 +1361,7 @@ async def test_plugin_detail_returns_discovered_plugin_without_database_state(tm
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.get_table()])
try:
async with session_maker() as session:
@@ -1352,7 +1400,7 @@ async def test_upsert_plugin_menu_updates_existing_menu_key(tmp_path: Path) -> N
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.__table__, SysPluginMenu.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.get_table(), SysPluginMenu.get_table()])
try:
async with session_maker() as session:
@@ -1375,18 +1423,18 @@ async def test_plugin_migration_history_can_be_persisted_and_read(tmp_path: Path
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginMigration.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginMigration.get_table()])
try:
async with session_maker() as session:
await PluginService.add_plugin_migration_services(
session,
PluginMigrationModel(
- pluginId='demo',
- migrationPath='migrations/001_demo.sql',
- migrationChecksum='checksum',
+ plugin_id='demo',
+ migration_path='migrations/001_demo.sql',
+ migration_checksum='checksum',
version='1.0.0',
- statementCount=EXPECTED_MIGRATION_STATEMENT_COUNT,
+ statement_count=EXPECTED_MIGRATION_STATEMENT_COUNT,
),
)
await session.commit()
@@ -1414,30 +1462,30 @@ async def test_plugin_migration_history_upserts_failed_record_to_success() -> No
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
failed_statement_count = 1
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginMigration.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginMigration.get_table()])
try:
async with session_maker() as session:
await PluginService.add_plugin_migration_services(
session,
PluginMigrationModel(
- pluginId='demo',
- migrationPath='migrations/001_demo.sql',
- migrationChecksum='checksum',
+ plugin_id='demo',
+ migration_path='migrations/001_demo.sql',
+ migration_checksum='checksum',
version='1.0.0',
- statementCount=failed_statement_count,
+ statement_count=failed_statement_count,
status='failed',
- errorMessage='boom',
+ error_message='boom',
),
)
await PluginService.add_plugin_migration_services(
session,
PluginMigrationModel(
- pluginId='demo',
- migrationPath='migrations/001_demo.sql',
- migrationChecksum='checksum',
+ plugin_id='demo',
+ migration_path='migrations/001_demo.sql',
+ migration_checksum='checksum',
version='1.0.0',
- statementCount=EXPECTED_MIGRATION_STATEMENT_COUNT,
+ statement_count=EXPECTED_MIGRATION_STATEMENT_COUNT,
status='success',
),
)
@@ -1465,29 +1513,29 @@ async def test_plugin_migration_history_can_be_listed_and_marked() -> None:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginMigration.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginMigration.get_table()])
try:
async with session_maker() as session:
await PluginService.add_plugin_migration_services(
session,
PluginMigrationModel(
- pluginId='demo',
- migrationPath='migrations/001_demo.sql',
- migrationChecksum='checksum-1',
+ plugin_id='demo',
+ migration_path='migrations/001_demo.sql',
+ migration_checksum='checksum-1',
version='1.0.0',
- statementCount=1,
+ statement_count=1,
status='success',
),
)
await PluginService.add_plugin_migration_services(
session,
PluginMigrationModel(
- pluginId='demo',
- migrationPath='migrations/002_demo.sql',
- migrationChecksum='checksum-2',
+ plugin_id='demo',
+ migration_path='migrations/002_demo.sql',
+ migration_checksum='checksum-2',
version='1.0.0',
- statementCount=1,
+ statement_count=1,
status='running',
),
)
@@ -1523,7 +1571,7 @@ async def test_check_installed_menu_conflict_reports_core_permission(tmp_path: P
async with engine.begin() as connection:
await connection.run_sync(
Base.metadata.create_all,
- tables=[SysMenu.__table__, SysPlugin.__table__, SysPluginMenu.__table__],
+ tables=[SysMenu.get_table(), SysPlugin.get_table(), SysPluginMenu.get_table()],
)
try:
@@ -1559,7 +1607,7 @@ async def test_plugin_default_config_can_be_installed_and_masked(tmp_path: Path)
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.get_table()])
try:
async with session_maker() as session:
@@ -1588,7 +1636,7 @@ async def test_secret_plugin_config_is_encrypted_at_rest(tmp_path: Path) -> None
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.get_table()])
try:
async with session_maker() as session:
@@ -1610,6 +1658,7 @@ async def test_secret_plugin_config_is_encrypted_at_rest(tmp_path: Path) -> None
masked_api_key = next(config for config in masked_configs if config.key == 'api_key')
revealed_api_key = next(config for config in revealed_configs if config.key == 'api_key')
assert db_config is not None
+ assert db_config.config_value is not None
assert db_config.config_value.startswith(PluginConfigManager.ENCRYPTED_PREFIX)
assert 'secret-updated' not in db_config.config_value
assert masked_api_key.value == PluginConfigManager.MASK_VALUE
@@ -1626,7 +1675,7 @@ async def test_plugin_config_sync_removes_items_deleted_from_manifest(tmp_path:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.get_table()])
try:
async with session_maker() as session:
@@ -1650,7 +1699,7 @@ async def test_plugin_config_sync_reencrypts_value_when_secret_policy_changes(tm
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.get_table()])
try:
async with session_maker() as session:
@@ -1675,6 +1724,7 @@ async def test_plugin_config_sync_reencrypts_value_when_secret_policy_changes(tm
provider_config = next(config for config in configs if config.key == 'provider')
assert db_config is not None
assert db_config.secret == '0'
+ assert db_config.config_value is not None
assert db_config.config_value.startswith(PluginConfigManager.ENCRYPTED_PREFIX)
assert provider_config.value == 'mistral'
finally:
@@ -1683,7 +1733,7 @@ async def test_plugin_config_sync_reencrypts_value_when_secret_policy_changes(tm
def test_secret_plugin_config_rejects_plaintext_storage() -> None:
"""校验敏感插件配置读取时拒绝未加密存储值。"""
- config = SimpleNamespace(
+ config = SysPluginConfig(
config_key='api_key',
config_label='API Key',
config_type='string',
@@ -1726,7 +1776,7 @@ async def test_get_plugin_config_services_reuses_bulk_config_lookup(
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.get_table()])
async def fail_get_config_by_key(*_args: object, **_kwargs: object) -> None:
"""
@@ -1760,14 +1810,14 @@ async def test_plugin_config_gateway_rejects_uninstalled_plugin_updates(tmp_path
async with engine.begin() as connection:
await connection.run_sync(
Base.metadata.create_all,
- tables=[SysPlugin.__table__, SysPluginConfig.__table__],
+ tables=[SysPlugin.get_table(), SysPluginConfig.get_table()],
)
class TestPluginManagementRuntimeGateway(PluginManagementRuntimeGateway):
"""注入测试数据库会话工厂。"""
@staticmethod
- def get_async_session_local() -> object:
+ def get_async_session_local() -> async_sessionmaker[AsyncSession]:
"""
获取测试数据库会话工厂。
@@ -1814,7 +1864,7 @@ async def test_plugin_config_can_be_updated(tmp_path: Path) -> None:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.get_table()])
try:
async with session_maker() as session:
@@ -1837,7 +1887,7 @@ async def test_plugin_config_update_validates_enhanced_constraints(tmp_path: Pat
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginConfig.get_table()])
try:
async with session_maker() as session:
@@ -1867,14 +1917,14 @@ async def test_build_plugin_purge_plan_counts_platform_metadata(tmp_path: Path)
await connection.run_sync(
Base.metadata.create_all,
tables=[
- SysMenu.__table__,
- SysRoleMenu.__table__,
- SysPlugin.__table__,
- SysPluginMenu.__table__,
- SysPluginConfig.__table__,
+ SysMenu.get_table(),
+ SysRoleMenu.get_table(),
+ SysPlugin.get_table(),
+ SysPluginMenu.get_table(),
+ SysPluginConfig.get_table(),
],
)
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginMigration.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginMigration.get_table()])
await create_sqlite_sys_job_table(connection)
try:
@@ -1903,11 +1953,11 @@ async def test_build_plugin_purge_plan_counts_platform_metadata(tmp_path: Path)
await PluginService.add_plugin_migration_services(
session,
PluginMigrationModel(
- pluginId='demo',
- migrationPath='migrations/001_demo.sql',
- migrationChecksum='checksum',
+ plugin_id='demo',
+ migration_path='migrations/001_demo.sql',
+ migration_checksum='checksum',
version='1.0.0',
- statementCount=1,
+ statement_count=1,
),
)
await PluginJobInstaller(session).install_plugin_jobs(build_discovered_plugin_with_job(tmp_path))
@@ -1935,14 +1985,14 @@ async def test_purge_plugin_metadata_by_id_deletes_orphan_platform_metadata(tmp_
await connection.run_sync(
Base.metadata.create_all,
tables=[
- SysMenu.__table__,
- SysRoleMenu.__table__,
- SysPlugin.__table__,
- SysPluginMenu.__table__,
- SysPluginConfig.__table__,
+ SysMenu.get_table(),
+ SysRoleMenu.get_table(),
+ SysPlugin.get_table(),
+ SysPluginMenu.get_table(),
+ SysPluginConfig.get_table(),
],
)
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginMigration.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginMigration.get_table()])
await create_sqlite_sys_job_table(connection)
try:
@@ -1971,11 +2021,11 @@ async def test_purge_plugin_metadata_by_id_deletes_orphan_platform_metadata(tmp_
await PluginService.add_plugin_migration_services(
session,
PluginMigrationModel(
- pluginId='demo',
- migrationPath='migrations/001_demo.sql',
- migrationChecksum='checksum',
+ plugin_id='demo',
+ migration_path='migrations/001_demo.sql',
+ migration_checksum='checksum',
version='1.0.0',
- statementCount=1,
+ statement_count=1,
),
)
await PluginJobInstaller(session).install_plugin_jobs(build_discovered_plugin_with_job(tmp_path))
@@ -2056,7 +2106,7 @@ async def test_add_plugin_operation_log_services_persists_batch_report() -> None
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.get_table()])
try:
async with session_maker() as session:
@@ -2085,6 +2135,7 @@ async def test_add_plugin_operation_log_services_persists_batch_report() -> None
assert operation_log.continue_on_error == '0'
assert db_operation_log is not None
assert db_operation_log.plugin_ids == '["base", "app"]'
+ assert db_operation_log.summary is not None
assert '"failed": 1' in db_operation_log.summary
finally:
await engine.dispose()
@@ -2096,7 +2147,7 @@ async def test_plugin_operation_log_services_returns_page_and_detail() -> None:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.get_table()])
try:
async with session_maker() as session:
@@ -2120,19 +2171,23 @@ async def test_plugin_operation_log_services_returns_page_and_detail() -> None:
page_result = await PluginService.get_plugin_operation_log_page_list_services(
session,
- PluginOperationLogPageQueryModel(pageNum=1, pageSize=10, operation='enable', pluginId='app'),
+ PluginOperationLogPageQueryModel(page_num=1, page_size=10, operation='enable', plugin_id='app'),
is_page=True,
)
+ assert operation_log.operation_id is not None
detail_result = await PluginService.plugin_operation_log_detail_services(
session,
operation_log.operation_id,
)
+ assert isinstance(page_result, PageModel)
assert page_result.total == 1
assert page_result.rows[0].plugin_ids == ['base', 'app']
assert page_result.rows[0].summary['succeeded'] == EXPECTED_BATCH_SUCCEEDED_COUNT
assert detail_result is not None
- assert detail_result.result['executed'][1]['pluginId'] == 'app'
+ executed = detail_result.result['executed']
+ assert isinstance(executed, list)
+ assert executed[1]['pluginId'] == 'app'
assert detail_result.continue_on_error is False
finally:
await engine.dispose()
@@ -2182,7 +2237,7 @@ async def test_plugin_operation_log_plugin_id_filter_matches_json_array_element(
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.get_table()])
try:
async with session_maker() as session:
@@ -2208,10 +2263,11 @@ async def test_plugin_operation_log_plugin_id_filter_matches_json_array_element(
page_result = await PluginService.get_plugin_operation_log_page_list_services(
session,
- PluginOperationLogPageQueryModel(pageNum=1, pageSize=10, pluginId='foo'),
+ PluginOperationLogPageQueryModel(page_num=1, page_size=10, plugin_id='foo'),
is_page=True,
)
+ assert isinstance(page_result, PageModel)
assert page_result.total == 1
assert page_result.rows[0].plugin_ids == ['foo']
finally:
@@ -2224,7 +2280,7 @@ async def test_plugin_operation_log_plugin_id_filter_treats_like_wildcards_as_li
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.get_table()])
try:
async with session_maker() as session:
@@ -2257,10 +2313,11 @@ async def test_plugin_operation_log_plugin_id_filter_treats_like_wildcards_as_li
page_result = await PluginService.get_plugin_operation_log_page_list_services(
session,
- PluginOperationLogPageQueryModel(pageNum=1, pageSize=10, pluginId='foo_bar'),
+ PluginOperationLogPageQueryModel(page_num=1, page_size=10, plugin_id='foo_bar'),
is_page=True,
)
+ assert isinstance(page_result, PageModel)
assert page_result.total == 1
assert page_result.rows[0].plugin_ids == ['foo_bar']
finally:
@@ -2273,7 +2330,7 @@ async def test_plugin_operation_log_export_services_returns_filtered_rows() -> N
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.get_table()])
try:
async with session_maker() as session:
@@ -2321,10 +2378,10 @@ async def test_plugin_operation_log_export_services_returns_filtered_rows() -> N
PluginOperationLogExportQueryModel(
operation='upgrade',
status='failed',
- pluginId='demo',
- beginTime=today,
- endTime=today,
- exportLimit=10,
+ plugin_id='demo',
+ begin_time=today,
+ end_time=today,
+ export_limit=10,
),
)
export_binary = PluginService.export_plugin_operation_log_list_services(
@@ -2349,7 +2406,7 @@ async def test_retain_plugin_operation_log_services_supports_dry_run_and_delete(
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.get_table()])
try:
async with session_maker() as session:
@@ -2377,11 +2434,11 @@ async def test_retain_plugin_operation_log_services_supports_dry_run_and_delete(
dry_run_result = await PluginService.retain_plugin_operation_log_services(
session,
- PluginOperationLogRetentionModel(retentionDays=7, dryRun=True),
+ PluginOperationLogRetentionModel(retention_days=7, dry_run=True),
)
delete_result = await PluginService.retain_plugin_operation_log_services(
session,
- PluginOperationLogRetentionModel(retentionDays=7, dryRun=False),
+ PluginOperationLogRetentionModel(retention_days=7, dry_run=False),
)
await session.commit()
remaining_count = await PluginDao.count_plugin_operation_logs_before(
@@ -2404,7 +2461,7 @@ async def test_retain_plugin_operation_log_services_accepts_zero_days() -> None:
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPluginOperationLog.get_table()])
try:
async with session_maker() as session:
@@ -2422,7 +2479,7 @@ async def test_retain_plugin_operation_log_services_accepts_zero_days() -> None:
delete_result = await PluginService.retain_plugin_operation_log_services(
session,
- PluginOperationLogRetentionModel(retentionDays=0, dryRun=False),
+ PluginOperationLogRetentionModel(retention_days=0, dry_run=False),
)
await session.commit()
remaining_count = await PluginDao.count_plugin_operation_logs_before(
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/management/test_release_dao.py b/ruoyi-fastapi-backend/tests/plugins/core/management/test_release_dao.py
index af595236b..d2504c40a 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/management/test_release_dao.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/management/test_release_dao.py
@@ -33,10 +33,10 @@ async def sessions(tmp_path: Path) -> AsyncIterator[async_sessionmaker[AsyncSess
await connection.run_sync(
Base.metadata.create_all,
tables=[
- SysPlugin.__table__,
- SysPluginArtifact.__table__,
- SysPluginRelease.__table__,
- SysPluginWorker.__table__,
+ SysPlugin.get_table(),
+ SysPluginArtifact.get_table(),
+ SysPluginRelease.get_table(),
+ SysPluginWorker.get_table(),
],
)
try:
@@ -140,7 +140,9 @@ async def test_select_requires_exact_preparation_and_never_changes_installed_ver
assert selected.previous_digest is None
assert selected.generation != old_generation
assert selected.expected_workers == EXPECTED_WORKERS
- assert (await db.get(SysPlugin, 'demo')).installed_version == '1.0.0'
+ stored = await db.get(SysPlugin, 'demo')
+ assert stored is not None
+ assert stored.installed_version == '1.0.0'
with pytest.raises(PluginReleaseConflictError):
await PluginReleaseDao.select_target(db, 'demo', target_digest=DIGEST_A, expected_generation=old_generation)
with pytest.raises(PluginReleaseConflictError):
@@ -166,7 +168,9 @@ async def test_prepare_failure_preserves_target_and_clears_preparation_proof(
assert release.prepared_digest is None
assert release.prepared_version is None
assert release.last_error == 'migration failed'
- assert (await db.get(SysPlugin, 'demo')).installed_version == '1.0.0'
+ stored = await db.get(SysPlugin, 'demo')
+ assert stored is not None
+ assert stored.installed_version == '1.0.0'
@pytest.mark.asyncio
@@ -177,6 +181,7 @@ async def test_explicit_code_rollback_can_keep_newer_data_schema(sessions: async
await PluginReleaseDao.select_target(db, 'demo', target_digest=DIGEST_A, expected_generation=release.generation)
await register(db, DIGEST_B, '2.0.0')
plugin = await db.get(SysPlugin, 'demo')
+ assert plugin is not None
plugin.installed_version = '2.0.0'
await db.flush()
with pytest.raises(ValueError, match='安装版本不一致'):
@@ -227,6 +232,7 @@ async def select_once() -> str:
assert results.count('conflict') == 1
async with sessions() as db:
release = await PluginReleaseDao.get_release(db, 'demo')
+ assert release is not None
assert release.generation in results
assert release.generation != generation
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/native/test_wheel.py b/ruoyi-fastapi-backend/tests/plugins/core/native/test_wheel.py
index c34805756..2267a2c31 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/native/test_wheel.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/native/test_wheel.py
@@ -12,7 +12,8 @@
from packaging.tags import sys_tags
from plugins.core.discovery.scanner import DiscoveredPlugin
-from plugins.core.manifest.schema import PluginManifest, PluginManifestFactory
+from plugins.core.manifest.schema import PluginManifestFactory
+from plugins.core.manifest.v2 import VersionedPluginManifest
from plugins.core.native import wheel as wheel_tools
from plugins.core.native.wheel import install_native_wheel, select_native_wheel
from plugins.core.runtime.entrypoint import PluginEntrypointLoader
@@ -22,7 +23,7 @@
@pytest.fixture
-def manifest() -> PluginManifest:
+def manifest() -> VersionedPluginManifest:
"""
创建原生 wheel 测试使用的插件清单。
@@ -75,7 +76,9 @@ def make_wheel(root: Path, *, extra: dict[str, bytes] | None = None, tag: str |
return path
-def test_install_yields_runtime_loadable_metadata_without_import(tmp_path: Path, manifest: PluginManifest) -> None:
+def test_install_yields_runtime_loadable_metadata_without_import(
+ tmp_path: Path, manifest: VersionedPluginManifest
+) -> None:
"""验证安装生成可加载的元数据布局且不导入插件。"""
wheel = make_wheel(tmp_path)
make_wheel(tmp_path, tag='cp20-cp20-unsupported_platform')
@@ -100,7 +103,7 @@ def test_install_yields_runtime_loadable_metadata_without_import(tmp_path: Path,
],
)
def test_unsafe_archive_rejected_before_creating_destination(
- tmp_path: Path, manifest: PluginManifest, name: str
+ tmp_path: Path, manifest: VersionedPluginManifest, name: str
) -> None:
"""验证不安全容器在创建安装目录前被拒绝。"""
wheel = make_wheel(tmp_path, extra={name: b'bad'})
@@ -112,7 +115,7 @@ def test_unsafe_archive_rejected_before_creating_destination(
@pytest.mark.parametrize('mutation', ['tamper', 'unlisted', 'symlink', 'case_collision'])
-def test_record_and_file_types_are_enforced(tmp_path: Path, manifest: PluginManifest, mutation: str) -> None:
+def test_record_and_file_types_are_enforced(tmp_path: Path, manifest: VersionedPluginManifest, mutation: str) -> None:
"""验证 RECORD 完整性与文件类型限制生效。"""
wheel = make_wheel(tmp_path)
with ZipFile(wheel) as archive:
@@ -134,7 +137,7 @@ def test_record_and_file_types_are_enforced(tmp_path: Path, manifest: PluginMani
assert not (tmp_path / 'native').exists()
-def test_install_never_overwrites_existing_directory(tmp_path: Path, manifest: PluginManifest) -> None:
+def test_install_never_overwrites_existing_directory(tmp_path: Path, manifest: VersionedPluginManifest) -> None:
"""验证 wheel 安装不会覆盖已存在的目录。"""
wheel = make_wheel(tmp_path)
destination = tmp_path / 'native'
@@ -146,7 +149,7 @@ def test_install_never_overwrites_existing_directory(tmp_path: Path, manifest: P
assert sentinel.read_text(encoding='utf-8') == 'keep'
-def test_archive_size_limit(tmp_path: Path, manifest: PluginManifest, monkeypatch: pytest.MonkeyPatch) -> None:
+def test_archive_size_limit(tmp_path: Path, manifest: VersionedPluginManifest, monkeypatch: pytest.MonkeyPatch) -> None:
"""验证 wheel 文件数量和大小限制生效。"""
wheel = make_wheel(tmp_path)
monkeypatch.setattr(wheel_tools, 'MAX_WHEEL_BYTES', 1)
@@ -154,7 +157,7 @@ def test_archive_size_limit(tmp_path: Path, manifest: PluginManifest, monkeypatc
install_native_wheel(wheel, tmp_path / 'native', manifest)
-def test_missing_dependency_is_not_installed(tmp_path: Path, manifest: PluginManifest) -> None:
+def test_missing_dependency_is_not_installed(tmp_path: Path, manifest: VersionedPluginManifest) -> None:
"""验证缺失依赖只会导致失败而不会触发安装。"""
wheel = make_wheel(
tmp_path,
@@ -167,7 +170,7 @@ def test_missing_dependency_is_not_installed(tmp_path: Path, manifest: PluginMan
install_native_wheel(wheel, tmp_path / 'native', manifest)
-def test_incompatible_wheel_has_no_selection(tmp_path: Path, manifest: PluginManifest) -> None:
+def test_incompatible_wheel_has_no_selection(tmp_path: Path, manifest: VersionedPluginManifest) -> None:
"""验证不兼容 wheel 不能被选择为安装候选。"""
make_wheel(tmp_path, tag='cp20-cp20-unsupported_platform')
with pytest.raises(ValueError, match='未找到'):
@@ -175,7 +178,7 @@ def test_incompatible_wheel_has_no_selection(tmp_path: Path, manifest: PluginMan
def test_extract_failure_cleans_only_new_directory(
- tmp_path: Path, manifest: PluginManifest, monkeypatch: pytest.MonkeyPatch
+ tmp_path: Path, manifest: VersionedPluginManifest, monkeypatch: pytest.MonkeyPatch
) -> None:
"""验证展开失败仅清理本次创建的新目录。"""
wheel = make_wheel(tmp_path)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/environment.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/environment.py
index dd0fdb8d3..9460dc9cb 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/environment.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/environment.py
@@ -2,15 +2,13 @@
from pathlib import Path
from plugins.core.environment import PluginRuntimeEnvironmentService
-from plugins.core.frontend import PluginFrontendFrameworkResolver
-class FakeRuntimeEnvironment:
+class FakeRuntimeEnvironment(PluginRuntimeEnvironmentService):
"""
测试用运行时环境服务。
- :ivar backend_dir: 后端项目目录
- :ivar frontend_dir: 前端项目目录
+ :ivar frontend_root: 测试指定的前端工程目录
:ivar frontend_mode: 当前使用的前端集成模式
:ivar backend_runtime_mode: 后端运行模式
"""
@@ -22,76 +20,8 @@ def __init__(self, backend_dir: Path, frontend_dir: Path | None = None) -> None:
:param backend_dir: 后端项目目录
:param frontend_dir: 前端项目目录
"""
- self.backend_dir = backend_dir
- self.frontend_dir = frontend_dir or Path(
- PluginRuntimeEnvironmentService(backend_root=backend_dir).get_frontend_dir()
- )
+ super().__init__(backend_root=backend_dir, frontend_root=frontend_dir, python_executable=sys.executable)
+ if frontend_dir is not None:
+ self.frontend_root = frontend_dir
self.frontend_mode = 'dev'
self.backend_runtime_mode = 'dev'
-
- def get_backend_dir(self) -> str:
- """
- 获取后端项目根目录。
-
- :return: 后端项目根目录
- """
- return str(self.backend_dir)
-
- def get_backend_plugins_dir(self) -> str:
- """
- 获取后端插件根目录。
-
- :return: 后端插件根目录
- """
- return str(self.backend_dir / 'plugins')
-
- def get_frontend_dir(self) -> str:
- """
- 获取前端项目根目录。
-
- :return: 前端项目根目录
- """
- return str(self.frontend_dir)
-
- def get_frontend_framework(self, frontend_root: Path | str | None = None) -> str:
- """
- 获取测试用前端工程的框架标识。
-
- :param frontend_root: 前端项目的根目录
- :return: 测试用前端工程的框架标识
- """
- root = Path(frontend_root) if frontend_root is not None else self.frontend_dir
- return PluginFrontendFrameworkResolver.resolve(root)
-
- def get_frontend_plugins_dir(self) -> str:
- """
- 获取前端插件根目录。
-
- :return: 前端插件根目录
- """
- return str(self.frontend_dir / 'plugins')
-
- @staticmethod
- def get_python_executable() -> str:
- """
- 获取测试用 Python 解释器。
-
- :return: 测试用 Python 解释器
- """
- return sys.executable
-
- def get_frontend_mode(self) -> str:
- """
- 获取测试用前端模式。
-
- :return: 测试用前端模式
- """
- return self.frontend_mode
-
- def get_backend_runtime_mode(self) -> str:
- """
- 获取测试用后端运行模式。
-
- :return: 测试用后端运行模式
- """
- return self.backend_runtime_mode
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/factory.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/factory.py
index 2f6518de7..7f5ae22d1 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/factory.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/factory.py
@@ -42,7 +42,7 @@ def build_runtime(backend_root: Path, frontend_root: Path | None = None) -> Plug
)
-def build_gateway_overrides(gateway: object) -> PluginRuntimeGatewayOverrides:
+def build_gateway_overrides(gateway: FakePluginRuntimeGateway) -> PluginRuntimeGatewayOverrides:
"""
构建测试用插件运行时窄端口覆盖项。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/gateway.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/gateway.py
index d75c50485..47b823596 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/gateway.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/gateway.py
@@ -1,167 +1,41 @@
import json
+from collections.abc import Mapping
from pathlib import Path
from subprocess import CompletedProcess
-from types import SimpleNamespace
-from plugins.core.lifecycle.migration import PluginMigrationRunner
+from common.vo import CrudResponseModel
+from plugins.core.discovery.scanner import DiscoveredPlugin
+from plugins.core.lifecycle.migration import PluginMigrationResult, PluginMigrationRunner
+from plugins.core.lifecycle.purge import PluginPurgePlan
+from plugins.core.management.entity.vo.schemas import (
+ PluginConfigUpdateModel,
+ PluginConfigValueModel,
+ PluginMigrationModel,
+ PluginOperationLogDetailModel,
+ PluginOperationLogExportQueryModel,
+)
+from plugins.core.management.service.gateway import PluginManagementLifecycleUnitOfWork
from plugins.core.runtime.service.gateway import PluginCommandOutputCallback
from plugins.core.runtime.service.migration_store import PluginDatabaseMigrationHistoryStore
from plugins.core.runtime.support import PluginConfigPayloadBuilder
+from plugins.core.types import PluginConfigValue, PluginStateRecord
from .management import FakePluginService
-from .session import FakeSession, FakeSessionLocal
+from .session import FakeSessionLocal
MIN_NPM_INSTALL_COMMAND_LENGTH = 3
-class FakePluginLifecycleUnitOfWork:
- """
- 测试用插件生命周期主事务工作单元。
-
- :ivar gateway: 代理底层操作的网关
- :ivar session_context: 当前会话的上下文
- :ivar session: 当前操作共用的会话
- """
+class FakePluginLifecycleUnitOfWork(PluginManagementLifecycleUnitOfWork):
+ """使用内存管理服务和记录型会话验证生命周期事务。"""
def __init__(self, gateway: 'FakePluginRuntimeGateway') -> None:
"""
- 初始化测试生命周期 UoW。
-
- :param gateway: 代理底层操作的网关
- """
- self.gateway = gateway
- self.session_context: FakeSession | None = None
- self.session: FakeSession | None = None
-
- async def __aenter__(self) -> 'FakePluginLifecycleUnitOfWork':
- """
- 打开测试生命周期主事务会话。
-
- :return: 当前实例
- """
- self.session_context = self.gateway.session_local()
- self.session = await self.session_context.__aenter__()
- return self
-
- async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> None:
- """
- 关闭测试生命周期主事务会话。
-
- :param exc_type: 退出上下文时的异常类型
- :param exc: 捕获到的异常实例
- :param traceback: 异常的调用栈
- """
- if self.session_context is None:
- return
- await self.session_context.__aexit__(exc_type, exc, traceback)
- self.session_context = None
- self.session = None
-
- async def check_installed_menu_conflicts(self, discovered_plugin: object) -> list[SimpleNamespace]:
- """
- 检查已安装菜单冲突。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :return: 安装菜单的冲突检查结果
- """
- return await FakePluginService.check_installed_menu_conflict_services(self.session, discovered_plugin)
-
- async def upsert_discovered_plugin(
- self,
- discovered_plugin: object,
- backend_root: Path,
- frontend_root: Path | None = None,
- ) -> SimpleNamespace:
- """
- 写入或更新已发现插件。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :param backend_root: 后端项目的根目录
- :param frontend_root: 前端项目的根目录
- :return: 保存后的插件状态
- """
- return await FakePluginService.upsert_discovered_plugin_services(
- self.session,
- discovered_plugin,
- backend_root,
- frontend_root,
- )
-
- async def install_plugin_menu(self, discovered_plugin: object, *, enabled: bool) -> None:
- """
- 安装插件菜单。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :param enabled: 是否启用该项功能
- """
- await FakePluginService.install_plugin_menu_services(self.session, discovered_plugin, enabled=enabled)
-
- async def install_plugin_default_config(self, discovered_plugin: object) -> list[SimpleNamespace]:
- """
- 安装插件默认配置。
+ 将工作单元连接到测试网关的会话工厂。
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :return: 默认配置的安装结果
- """
- return await FakePluginService.install_plugin_default_config_services(self.session, discovered_plugin)
-
- async def install_plugin_jobs(self, discovered_plugin: object, *, enabled: bool) -> None:
- """
- 同步插件任务。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :param enabled: 是否启用该项功能
- """
- await FakePluginService.install_plugin_job_services(self.session, discovered_plugin, enabled=enabled)
-
- async def mark_plugin_installed(self, discovered_plugin: object) -> SimpleNamespace:
- """
- 标记插件已安装。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :return: 更新后的安装标记
- """
- return await FakePluginService.mark_plugin_installed_services(self.session, discovered_plugin)
-
- async def build_plugin_purge_plan(self, discovered_plugin: object) -> object:
- """
- 构建插件物理清理计划。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :return: 插件物理清理计划
+ :param gateway: 提供记录型会话工厂的测试网关
"""
- return await FakePluginService.build_plugin_purge_plan_services(self.session, discovered_plugin)
-
- async def purge_plugin_metadata(self, discovered_plugin: object) -> object:
- """
- 清理插件平台元数据。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :return: 插件元数据的清理结果
- """
- return await FakePluginService.purge_plugin_services(self.session, discovered_plugin)
-
- async def build_plugin_purge_plan_by_id(self, plugin_id: str) -> object:
- """
- 按插件 ID 构建孤儿元数据清理计划。
-
- :param plugin_id: 插件清单中的唯一标识
- :return: 按插件标识生成的清理计划
- """
- return await FakePluginService.build_plugin_purge_plan_by_id_services(self.session, plugin_id)
-
- async def purge_plugin_metadata_by_id(self, plugin_id: str) -> object:
- """
- 按插件 ID 清理孤儿元数据。
-
- :param plugin_id: 插件清单中的唯一标识
- :return: 按插件标识执行的清理结果
- """
- return await FakePluginService.purge_plugin_metadata_by_id_services(self.session, plugin_id)
-
- async def commit(self) -> None:
- """提交测试生命周期主事务。"""
- await self.session.commit()
+ super().__init__(gateway.session_local, FakePluginService)
class FakePluginRuntimeGateway:
@@ -207,16 +81,16 @@ def get_plugin_service(self) -> type[FakePluginService]:
"""
return FakePluginService
- async def list_plugin_states(self) -> list[SimpleNamespace]:
+ async def list_plugin_states(self) -> list[PluginStateRecord]:
"""
获取测试插件状态列表。
:return: 测试插件状态列表
"""
async with self.session_local() as session:
- return await FakePluginService.get_plugin_list_services(session)
+ return list(await FakePluginService.get_plugin_list_services(session))
- async def get_plugin_state(self, plugin_id: str) -> SimpleNamespace | None:
+ async def get_plugin_state(self, plugin_id: str) -> PluginStateRecord | None:
"""
读取内存状态,不在生命周期事务记录中创建只读会话。
@@ -226,31 +100,31 @@ async def get_plugin_state(self, plugin_id: str) -> SimpleNamespace | None:
return await FakePluginService.plugin_detail_services(None, plugin_id)
@staticmethod
- def build_operation_log_export_query(export_limit: int) -> SimpleNamespace:
+ def build_operation_log_export_query(export_limit: int) -> PluginOperationLogExportQueryModel:
"""
构建测试用插件操作日志导出查询对象。
:param export_limit: 导出数量上限
:return: 测试用插件操作日志导出查询对象
"""
- return SimpleNamespace(export_limit=export_limit, exportLimit=export_limit)
+ return PluginOperationLogExportQueryModel(export_limit=export_limit)
@staticmethod
- def build_config_update(values: dict[str, object]) -> SimpleNamespace:
+ def build_config_update(values: dict[str, PluginConfigValue]) -> PluginConfigUpdateModel:
"""
构建测试用插件配置更新对象。
:param values: 当前处理的值集合
:return: 测试用插件配置更新对象
"""
- return SimpleNamespace(values=values)
+ return PluginConfigUpdateModel(values=values)
async def get_plugin_config(
self,
- discovered_plugin: object,
+ discovered_plugin: DiscoveredPlugin,
*,
reveal_secret: bool = False,
- ) -> list[SimpleNamespace]:
+ ) -> list[PluginConfigValueModel]:
"""
获取测试插件配置。
@@ -268,9 +142,9 @@ async def get_plugin_config(
async def update_plugin_config(
self,
- discovered_plugin: object,
- values: dict[str, object],
- ) -> list[SimpleNamespace]:
+ discovered_plugin: DiscoveredPlugin,
+ values: dict[str, PluginConfigValue],
+ ) -> list[PluginConfigValueModel]:
"""
更新测试插件配置。
@@ -289,12 +163,12 @@ async def update_plugin_config(
async def set_plugin_config(
self,
- discovered_plugin: object,
- values: dict[str, object],
+ discovered_plugin: DiscoveredPlugin,
+ values: dict[str, PluginConfigValue],
*,
audit_operation: str,
success_message: str,
- ) -> list[SimpleNamespace]:
+ ) -> list[PluginConfigValueModel]:
"""
在同一事务中更新测试插件配置并记录审计日志。
@@ -334,7 +208,7 @@ async def set_plugin_config(
async def add_plugin_operation_log(
self,
- payload: dict[str, object],
+ payload: Mapping[str, object],
*,
dry_run: bool,
continue_on_error: bool,
@@ -349,13 +223,13 @@ async def add_plugin_operation_log(
async with self.session_local() as session:
await FakePluginService.add_plugin_operation_log_services(
session,
- payload,
+ dict(payload),
dry_run=dry_run,
continue_on_error=continue_on_error,
)
await session.commit()
- async def list_plugin_operation_logs(self, *, export_limit: int) -> list[SimpleNamespace]:
+ async def list_plugin_operation_logs(self, *, export_limit: int) -> list[PluginOperationLogDetailModel]:
"""
获取测试插件操作审计日志列表。
@@ -387,7 +261,7 @@ async def list_plugin_migrations(
self,
plugin_id: str,
status: str | None = None,
- ) -> list[SimpleNamespace]:
+ ) -> list[PluginMigrationModel]:
"""
查询测试插件 migration 历史。
@@ -398,7 +272,7 @@ async def list_plugin_migrations(
async with self.session_local() as session:
return await FakePluginService.get_plugin_migration_list_services(session, plugin_id, status)
- async def get_plugin_migration(self, plugin_id: str, migration_path: str) -> SimpleNamespace | None:
+ async def get_plugin_migration(self, plugin_id: str, migration_path: str) -> PluginMigrationModel | None:
"""
获取测试插件 migration 历史。
@@ -415,7 +289,7 @@ async def mark_plugin_migration_status(
migration_path: str,
status: str,
error_message: str | None = None,
- ) -> SimpleNamespace | None:
+ ) -> PluginMigrationModel | None:
"""
人工标记测试插件 migration 历史状态。
@@ -437,7 +311,7 @@ async def mark_plugin_migration_status(
await session.commit()
return migration
- async def build_plugin_purge_plan(self, discovered_plugin: object) -> object:
+ async def build_plugin_purge_plan(self, discovered_plugin: DiscoveredPlugin) -> PluginPurgePlan:
"""
构建测试插件物理清理计划。
@@ -447,7 +321,7 @@ async def build_plugin_purge_plan(self, discovered_plugin: object) -> object:
async with self.session_local() as session:
return await FakePluginService.build_plugin_purge_plan_services(session, discovered_plugin)
- async def run_plugin_migrations(self, discovered_plugin: object) -> list[object]:
+ async def run_plugin_migrations(self, discovered_plugin: DiscoveredPlugin) -> list[PluginMigrationResult]:
"""
使用独立测试 session 执行插件 migration。
@@ -469,8 +343,8 @@ async def set_plugin_enabled_state(
self,
plugin_id: str,
enabled: bool,
- discovered_plugin: object | None = None,
- ) -> SimpleNamespace:
+ discovered_plugin: DiscoveredPlugin | None = None,
+ ) -> CrudResponseModel:
"""
更新测试插件启停状态,并在启用时同步菜单。
@@ -492,7 +366,7 @@ async def set_plugin_enabled_state(
await session.commit()
return response
- async def mark_plugin_uninstalled_state(self, plugin_id: str) -> SimpleNamespace:
+ async def mark_plugin_uninstalled_state(self, plugin_id: str) -> CrudResponseModel:
"""
标记测试插件安全卸载。
@@ -514,7 +388,7 @@ def build_migration_record(
statement_count: int,
status: str = 'success',
error_message: str | None = None,
- ) -> SimpleNamespace:
+ ) -> PluginMigrationModel:
"""
构建测试用插件 migration 执行历史对象。
@@ -527,7 +401,7 @@ def build_migration_record(
:param error_message: 记录到结果或审计日志中的错误详情
:return: 测试用插件 migration 执行历史对象
"""
- return SimpleNamespace(
+ return PluginMigrationModel(
plugin_id=plugin_id,
migration_path=migration_path,
migration_checksum=checksum,
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/management.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/management.py
index 1c84484ba..cddf501f3 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/management.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/management.py
@@ -1,7 +1,34 @@
+from dataclasses import dataclass
from pathlib import Path
-from types import SimpleNamespace
-from plugins.core.lifecycle.purge import PluginPurgePlanner
+from common.vo import CrudResponseModel
+from plugins.core.discovery.scanner import DiscoveredPlugin
+from plugins.core.lifecycle.purge import PluginPurgePlan, PluginPurgePlanner
+from plugins.core.management.entity.vo.schemas import (
+ PluginConfigModel,
+ PluginConfigUpdateModel,
+ PluginConfigValueModel,
+ PluginMigrationModel,
+ PluginModel,
+ PluginOperationLogDetailModel,
+ PluginOperationLogExportQueryModel,
+)
+from plugins.core.validation.menus import PluginMenuConflictItem
+
+
+@dataclass
+class RecordedPluginOperation:
+ """
+ 内存审计记录,保留测试中提交的原始操作结果。
+
+ :ivar payload: 提交给审计服务的操作结果
+ :ivar dry_run: 操作是否为预演
+ :ivar continue_on_error: 单项失败后是否继续执行
+ """
+
+ payload: dict[str, object]
+ dry_run: bool
+ continue_on_error: bool
class FakePluginService:
@@ -39,14 +66,14 @@ class FakePluginService:
mark_uninstalled_called_with: str | None = None
purge_called = False
purge_by_id_called_with: str | None = None
- update_enabled_called_with: tuple[str, bool, object | None] | None = None
- detail_plugin: SimpleNamespace | None = None
- upsert_plugin: SimpleNamespace | None = None
- installed_menu_conflicts: list[SimpleNamespace] = []
+ update_enabled_called_with: tuple[str, bool, DiscoveredPlugin | None] | None = None
+ detail_plugin: PluginModel | None = None
+ upsert_plugin: PluginModel | None = None
+ installed_menu_conflicts: list[PluginMenuConflictItem] = []
migration_checksums: dict[tuple[str, str], str] = {}
- migration_records: list[object] = []
- operation_logs: list[object] = []
- plugin_list: list[SimpleNamespace] = []
+ migration_records: list[PluginMigrationModel] = []
+ operation_logs: list[RecordedPluginOperation] = []
+ plugin_list: list[PluginModel] = []
marked_errors: list[tuple[str, str]] = []
@classmethod
@@ -73,7 +100,7 @@ def reset(cls) -> None:
cls.marked_errors = []
@classmethod
- async def get_plugin_list_services(cls, query_db: object) -> list[SimpleNamespace]:
+ async def get_plugin_list_services(cls, query_db: object) -> list[PluginModel]:
"""
读取测试用插件列表。
@@ -83,7 +110,7 @@ async def get_plugin_list_services(cls, query_db: object) -> list[SimpleNamespac
return cls.plugin_list
@classmethod
- async def plugin_detail_services(cls, query_db: object, plugin_id: str) -> SimpleNamespace | None:
+ async def plugin_detail_services(cls, query_db: object, plugin_id: str) -> PluginModel | None:
"""
读取测试插件详情。
@@ -97,10 +124,10 @@ async def plugin_detail_services(cls, query_db: object, plugin_id: str) -> Simpl
async def upsert_discovered_plugin_services(
cls,
query_db: object,
- discovered_plugin: object,
+ discovered_plugin: DiscoveredPlugin,
backend_root: Path,
- frontend_root: Path,
- ) -> SimpleNamespace:
+ frontend_root: Path | None = None,
+ ) -> PluginModel:
"""
记录插件写入调用。
@@ -115,20 +142,19 @@ async def upsert_discovered_plugin_services(
cls.upsert_frontend_root = frontend_root
if cls.upsert_plugin:
return cls.upsert_plugin
- return SimpleNamespace(
+ return PluginModel(
plugin_id=discovered_plugin.manifest.id,
installed_version=discovered_plugin.manifest.version,
enabled='0',
status='installed',
- model_dump=lambda by_alias=True: {'pluginId': discovered_plugin.manifest.id},
)
@classmethod
async def check_installed_menu_conflict_services(
cls,
query_db: object,
- discovered_plugin: object,
- ) -> list[SimpleNamespace]:
+ discovered_plugin: DiscoveredPlugin,
+ ) -> list[PluginMenuConflictItem]:
"""
读取测试用已安装菜单冲突。
@@ -144,7 +170,7 @@ async def get_plugin_migration_services(
query_db: object,
plugin_id: str,
migration_path: str,
- ) -> SimpleNamespace | None:
+ ) -> PluginMigrationModel | None:
"""
读取测试用插件 migration 执行历史。
@@ -154,17 +180,14 @@ async def get_plugin_migration_services(
:return: 测试用插件 migration 执行历史
"""
for migration in reversed(cls.migration_records):
- if (
- getattr(migration, 'plugin_id', None) == plugin_id
- and getattr(migration, 'migration_path', None) == migration_path
- ):
+ if migration.plugin_id == plugin_id and migration.migration_path == migration_path:
return migration
checksum = cls.migration_checksums.get((plugin_id, migration_path))
if not checksum:
return None
- return SimpleNamespace(migration_checksum=checksum)
+ return PluginMigrationModel(plugin_id=plugin_id, migration_path=migration_path, migration_checksum=checksum)
@classmethod
async def get_plugin_migration_list_services(
@@ -172,7 +195,7 @@ async def get_plugin_migration_list_services(
query_db: object,
plugin_id: str,
status: str | None = None,
- ) -> list[SimpleNamespace]:
+ ) -> list[PluginMigrationModel]:
"""
读取测试用插件 migration 执行历史列表。
@@ -184,16 +207,15 @@ async def get_plugin_migration_list_services(
return [
migration
for migration in cls.migration_records
- if getattr(migration, 'plugin_id', None) == plugin_id
- and (not status or getattr(migration, 'status', None) == status)
+ if migration.plugin_id == plugin_id and (not status or migration.status == status)
]
@classmethod
async def add_plugin_migration_services(
cls,
query_db: object,
- plugin_migration: object,
- ) -> object:
+ plugin_migration: PluginMigrationModel,
+ ) -> PluginMigrationModel:
"""
记录插件 migration 执行历史。
@@ -212,7 +234,7 @@ async def mark_plugin_migration_status_services(
migration_path: str,
status: str,
error_message: str | None = None,
- ) -> object | None:
+ ) -> PluginMigrationModel | None:
"""
人工标记测试用插件 migration 执行历史状态。
@@ -224,10 +246,7 @@ async def mark_plugin_migration_status_services(
:return: 插件的数据迁移配置
"""
for migration in reversed(cls.migration_records):
- if (
- getattr(migration, 'plugin_id', None) == plugin_id
- and getattr(migration, 'migration_path', None) == migration_path
- ):
+ if migration.plugin_id == plugin_id and migration.migration_path == migration_path:
migration.status = status
migration.error_message = error_message
return migration
@@ -242,7 +261,7 @@ async def add_plugin_operation_log_services(
*,
dry_run: bool,
continue_on_error: bool,
- ) -> SimpleNamespace:
+ ) -> RecordedPluginOperation:
"""
记录测试用插件批量操作审计日志。
@@ -252,7 +271,7 @@ async def add_plugin_operation_log_services(
:param continue_on_error: 单项操作失败后是否继续执行
:return: 供调用方使用的 ``operation_log``
"""
- operation_log = SimpleNamespace(
+ operation_log = RecordedPluginOperation(
payload=payload,
dry_run=dry_run,
continue_on_error=continue_on_error,
@@ -265,8 +284,8 @@ async def add_plugin_operation_log_services(
async def get_plugin_operation_log_export_list_services(
cls,
query_db: object,
- query_object: object,
- ) -> list[SimpleNamespace]:
+ query_object: PluginOperationLogExportQueryModel,
+ ) -> list[PluginOperationLogDetailModel]:
"""
读取测试用插件操作审计导出列表。
@@ -275,16 +294,17 @@ async def get_plugin_operation_log_export_list_services(
:return: 测试用插件操作审计导出列表
"""
return [
- SimpleNamespace(
- operation_id=index + 1,
- operation=getattr(operation_log, 'payload', {}).get('operation', 'unknown'),
- plugin_ids=[getattr(operation_log, 'payload', {}).get('pluginId', '-')],
- dry_run=getattr(operation_log, 'dry_run', False),
- continue_on_error=getattr(operation_log, 'continue_on_error', False),
- status='success' if getattr(operation_log, 'payload', {}).get('ok', False) else 'failed',
- summary=getattr(operation_log, 'payload', {}).get('summary', {}),
- create_time=None,
- remark=getattr(operation_log, 'payload', {}).get('message'),
+ PluginOperationLogDetailModel.model_validate(
+ {
+ 'operation_id': index + 1,
+ 'operation': operation_log.payload.get('operation', 'unknown'),
+ 'plugin_ids': [operation_log.payload.get('pluginId', '-')],
+ 'dry_run': operation_log.dry_run,
+ 'continue_on_error': operation_log.continue_on_error,
+ 'status': 'success' if operation_log.payload.get('ok') else 'failed',
+ 'summary': operation_log.payload.get('summary', {}),
+ 'remark': operation_log.payload.get('message'),
+ }
)
for index, operation_log in enumerate(cls.operation_logs)
]
@@ -293,7 +313,7 @@ async def get_plugin_operation_log_export_list_services(
async def install_plugin_menu_services(
cls,
query_db: object,
- discovered_plugin: object,
+ discovered_plugin: DiscoveredPlugin,
*,
enabled: bool,
) -> None:
@@ -310,8 +330,8 @@ async def install_plugin_menu_services(
async def install_plugin_default_config_services(
cls,
query_db: object,
- discovered_plugin: object,
- ) -> list[SimpleNamespace]:
+ discovered_plugin: DiscoveredPlugin,
+ ) -> list[PluginConfigModel]:
"""
记录插件默认配置安装调用。
@@ -320,21 +340,16 @@ async def install_plugin_default_config_services(
:return: 供调用方使用的 ``configs``
"""
cls.install_config_called = True
- configs = []
- for item in discovered_plugin.manifest.config.items:
- payload = {
- 'pluginId': discovered_plugin.manifest.id,
- 'configKey': item.key,
- }
- configs.append(SimpleNamespace(model_dump=lambda by_alias=True, payload=payload: payload))
-
- return configs
+ return [
+ PluginConfigModel(plugin_id=discovered_plugin.manifest.id, config_key=item.key)
+ for item in discovered_plugin.manifest.config.items
+ ]
@classmethod
async def install_plugin_job_services(
cls,
query_db: object,
- discovered_plugin: object,
+ discovered_plugin: DiscoveredPlugin,
*,
enabled: bool,
) -> None:
@@ -347,14 +362,25 @@ async def install_plugin_job_services(
"""
cls.install_plugin_job_called_with = (discovered_plugin.manifest.id, enabled)
+ @classmethod
+ async def is_plugin_installed_services(cls, query_db: object, plugin_id: str) -> bool:
+ """
+ 根据内存中的安装记录判断插件是否已安装。
+
+ :param query_db: 当前操作使用的测试会话
+ :param plugin_id: 插件标识
+ :return: 是否存在带有安装版本的匹配记录
+ """
+ return any(plugin.plugin_id == plugin_id and plugin.installed_version for plugin in cls.plugin_list)
+
@classmethod
async def get_plugin_config_services(
cls,
query_db: object,
- discovered_plugin: object,
+ discovered_plugin: DiscoveredPlugin,
*,
reveal_secret: bool = False,
- ) -> list[SimpleNamespace]:
+ ) -> list[PluginConfigValueModel]:
"""
读取测试用插件配置。
@@ -366,20 +392,20 @@ async def get_plugin_config_services(
configs = []
for item in discovered_plugin.manifest.config.items:
value = '******' if item.secret and not reveal_secret else item.default
- default = '******' if item.secret and not reveal_secret else item.default
- payload = {
- 'key': item.key,
- 'value': value,
- 'default': default,
- 'secret': item.secret,
- 'group': item.group,
- 'order': item.order,
- 'placeholder': item.placeholder,
- 'min': item.min_value,
- 'max': item.max_value,
- 'pattern': item.pattern,
- }
- configs.append(SimpleNamespace(model_dump=lambda by_alias=True, payload=payload: payload))
+ configs.append(
+ PluginConfigValueModel(
+ key=item.key,
+ value=value,
+ default=value,
+ secret=item.secret,
+ group=item.group,
+ order=item.order,
+ placeholder=item.placeholder,
+ min=item.min_value,
+ max=item.max_value,
+ pattern=item.pattern,
+ )
+ )
return configs
@@ -387,9 +413,9 @@ async def get_plugin_config_services(
async def update_plugin_config_services(
cls,
query_db: object,
- discovered_plugin: object,
- update_model: object,
- ) -> list[SimpleNamespace]:
+ discovered_plugin: DiscoveredPlugin,
+ update_model: PluginConfigUpdateModel,
+ ) -> list[PluginConfigValueModel]:
"""
更新测试用插件配置。
@@ -398,49 +424,33 @@ async def update_plugin_config_services(
:param update_model: 包含待更新字段的模型
:return: 供调用方使用的 ``configs``
"""
- configs = []
- for key, value in update_model.values.items():
- payload = {
- 'key': key,
- 'value': value,
- 'secret': False,
- }
- configs.append(SimpleNamespace(model_dump=lambda by_alias=True, payload=payload: payload))
-
- return configs
+ return [PluginConfigValueModel(key=key, value=value) for key, value in update_model.values.items()]
@classmethod
async def mark_plugin_installed_services(
cls,
query_db: object,
- discovered_plugin: object,
- ) -> SimpleNamespace:
+ discovered_plugin: DiscoveredPlugin,
+ ) -> PluginModel:
"""
记录插件安装完成标记调用。
:param query_db: 当前操作使用的异步数据库会话
:param discovered_plugin: 扫描插件目录后得到的插件描述
- :return: ``SimpleNamespace`` 实例
+ :return: 操作完成后记录的结果
"""
cls.mark_installed_called = True
cls.plugin_list = [
plugin for plugin in cls.plugin_list if getattr(plugin, 'plugin_id', None) != discovered_plugin.manifest.id
]
- cls.plugin_list.append(
- SimpleNamespace(
- plugin_id=discovered_plugin.manifest.id,
- installed_version=discovered_plugin.manifest.version,
- enabled='0',
- status='installed',
- )
- )
- return SimpleNamespace(
- model_dump=lambda by_alias=True: {
- 'pluginId': discovered_plugin.manifest.id,
- 'installedVersion': discovered_plugin.manifest.version,
- 'status': 'installed',
- }
+ installed = PluginModel(
+ plugin_id=discovered_plugin.manifest.id,
+ installed_version=discovered_plugin.manifest.version,
+ enabled='0',
+ status='installed',
)
+ cls.plugin_list.append(installed)
+ return installed
@classmethod
async def update_plugin_enabled_services(
@@ -448,8 +458,8 @@ async def update_plugin_enabled_services(
query_db: object,
plugin_id: str,
enabled: bool,
- discovered_plugin: object | None = None,
- ) -> SimpleNamespace:
+ discovered_plugin: DiscoveredPlugin | None = None,
+ ) -> CrudResponseModel:
"""
记录插件启停调用。
@@ -457,22 +467,22 @@ async def update_plugin_enabled_services(
:param plugin_id: 插件清单中的唯一标识
:param enabled: 是否启用该项功能
:param discovered_plugin: 扫描插件目录后得到的插件描述
- :return: ``SimpleNamespace`` 实例
+ :return: 操作完成后记录的结果
"""
cls.update_enabled_called_with = (plugin_id, enabled, discovered_plugin)
- return SimpleNamespace(is_success=True, message='启用成功' if enabled else '停用成功')
+ return CrudResponseModel(is_success=True, message='启用成功' if enabled else '停用成功')
@classmethod
- async def mark_plugin_uninstalled_services(cls, query_db: object, plugin_id: str) -> SimpleNamespace:
+ async def mark_plugin_uninstalled_services(cls, query_db: object, plugin_id: str) -> CrudResponseModel:
"""
记录插件卸载标记调用。
:param query_db: 当前操作使用的异步数据库会话
:param plugin_id: 插件清单中的唯一标识
- :return: ``SimpleNamespace`` 实例
+ :return: 操作完成后记录的结果
"""
cls.mark_uninstalled_called_with = plugin_id
- return SimpleNamespace(is_success=True, message='卸载成功')
+ return CrudResponseModel(is_success=True, message='卸载成功')
@classmethod
async def mark_plugin_error_services(
@@ -480,21 +490,23 @@ async def mark_plugin_error_services(
query_db: object,
plugin_id: str,
error_message: str,
- ) -> SimpleNamespace:
+ ) -> CrudResponseModel:
"""
记录插件错误状态标记调用。
:param query_db: 当前操作使用的异步数据库会话
:param plugin_id: 插件清单中的唯一标识
:param error_message: 记录到结果或审计日志中的错误详情
- :return: ``SimpleNamespace`` 实例
+ :return: 操作完成后记录的结果
"""
cls.marked_errors.append((plugin_id, error_message))
- return SimpleNamespace(is_success=True, message='插件状态已标记为异常')
+ return CrudResponseModel(is_success=True, message='插件状态已标记为异常')
@classmethod
- async def build_plugin_purge_plan_services(cls, query_db: object, discovered_plugin: object) -> object:
+ async def build_plugin_purge_plan_services(
+ cls, query_db: object, discovered_plugin: DiscoveredPlugin
+ ) -> PluginPurgePlan:
"""
构建测试用插件物理清理计划。
@@ -511,7 +523,7 @@ async def build_plugin_purge_plan_services(cls, query_db: object, discovered_plu
)
@classmethod
- async def purge_plugin_services(cls, query_db: object, discovered_plugin: object) -> object:
+ async def purge_plugin_services(cls, query_db: object, discovered_plugin: DiscoveredPlugin) -> PluginPurgePlan:
"""
记录插件物理清理调用。
@@ -523,7 +535,7 @@ async def purge_plugin_services(cls, query_db: object, discovered_plugin: object
return await cls.build_plugin_purge_plan_services(query_db, discovered_plugin)
@classmethod
- async def build_plugin_purge_plan_by_id_services(cls, query_db: object, plugin_id: str) -> object:
+ async def build_plugin_purge_plan_by_id_services(cls, query_db: object, plugin_id: str) -> PluginPurgePlan:
"""
构建测试用孤儿插件元数据清理计划。
@@ -541,7 +553,7 @@ async def build_plugin_purge_plan_by_id_services(cls, query_db: object, plugin_i
)
@classmethod
- async def purge_plugin_metadata_by_id_services(cls, query_db: object, plugin_id: str) -> object:
+ async def purge_plugin_metadata_by_id_services(cls, query_db: object, plugin_id: str) -> PluginPurgePlan:
"""
记录按插件 ID 清理孤儿元数据调用。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/session.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/session.py
index 0712608ec..748d89adc 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/session.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/fakes/session.py
@@ -1,7 +1,15 @@
-class FakeSession:
+from unittest.mock import AsyncMock
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+
+class FakeSession(AsyncSession):
"""
测试用异步数据库会话。
+ :ivar execute: 记录 SQL 并避免访问外部数据库的异步执行方法
+ :ivar install_hook_ran: 安装钩子记录的插件标识
+ :ivar purge_hook_ran: 清理钩子记录的插件标识
:ivar committed: 是否已经提交事务
:ivar rolled_back: 是否已经回滚事务
:ivar executed_statements: 测试替身收到的 SQL 语句
@@ -9,27 +17,14 @@ class FakeSession:
def __init__(self) -> None:
"""初始化测试用异步数据库会话。"""
+ super().__init__()
+ self.execute = AsyncMock(side_effect=self.record_statement)
+ self.install_hook_ran: str | None = None
+ self.purge_hook_ran: str | None = None
self.committed = False
self.rolled_back = False
self.executed_statements = []
- async def __aenter__(self) -> 'FakeSession':
- """
- 进入异步上下文。
-
- :return: 当前实例
- """
- return self
-
- async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> None:
- """
- 退出异步上下文。
-
- :param exc_type: 退出上下文时的异常类型
- :param exc: 捕获到的异常实例
- :param traceback: 异常的调用栈
- """
-
async def commit(self) -> None:
"""记录提交动作。"""
self.committed = True
@@ -38,7 +33,7 @@ async def rollback(self) -> None:
"""记录回滚动作。"""
self.rolled_back = True
- async def execute(self, statement: object) -> None:
+ async def record_statement(self, statement: object) -> None:
"""
记录 SQL 执行动作。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_artifact_guards.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_artifact_guards.py
index 017c3ba31..4e4b2dd94 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_artifact_guards.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_artifact_guards.py
@@ -1,9 +1,11 @@
import asyncio
+from collections.abc import Mapping
from pathlib import Path
-from types import SimpleNamespace
import pytest
+from plugins.core.discovery.scanner import DiscoveredPlugin
+from plugins.core.management.entity.vo.schemas import PluginModel
from plugins.core.validation.dependency_policy import DependencyInstallPolicyConfig
from tests.plugins.core.runtime.fakes import (
FakePluginRuntimeGateway,
@@ -23,7 +25,7 @@ async def test_database_artifact_source_blocks_legacy_lifecycle_without_source_d
) -> None:
"""数据库中的产物来源即使没有源码目录也阻止旧生命周期操作。"""
gateway = FakePluginRuntimeGateway()
- FakePluginService.detail_plugin = SimpleNamespace(plugin_id='demo', source='artifact')
+ FakePluginService.detail_plugin = PluginModel(plugin_id='demo', source='artifact')
runtime = build_runtime_with_gateway(tmp_path / 'backend', gateway)
if operation in {'enable', 'disable'}:
payload = await runtime.set_plugin_enabled('demo', enabled=operation == 'enable', dry_run=dry_run)
@@ -32,6 +34,7 @@ async def test_database_artifact_source_blocks_legacy_lifecycle_without_source_d
assert payload['ok'] is False
assert payload['status'] == 'blocked'
assert payload['operation'] == operation
+ assert isinstance(payload['capability'], dict)
assert payload['capability']['runtimeManageable'] is False
assert gateway.lifecycle_uows == []
assert gateway.session_local.sessions == []
@@ -59,6 +62,7 @@ async def get_plugin_state(self, plugin_id: str) -> None:
gateway = FailingGateway()
payload = await build_runtime_with_gateway(tmp_path / 'backend', gateway).purge_plugin('demo')
assert payload['status'] == 'blocked'
+ assert isinstance(payload['message'], str)
assert '无法确认插件来源' in payload['message']
assert gateway.session_local.sessions == []
@@ -83,7 +87,7 @@ async def get_selected_artifact_plugin(self, plugin_id: str, backend_root: Path)
assert backend_root == tmp_path / 'backend'
return selected
- async def get_plugin_config(self, discovered_plugin: object, *, reveal_secret: bool = False) -> list:
+ async def get_plugin_config(self, discovered_plugin: DiscoveredPlugin, *, reveal_secret: bool = False) -> list:
"""
检查插件选择和配置读取参数。
@@ -95,7 +99,7 @@ async def get_plugin_config(self, discovered_plugin: object, *, reveal_secret: b
assert reveal_secret is False
return []
- async def set_plugin_config(self, discovered_plugin: object, values: dict, **kwargs: object) -> list:
+ async def set_plugin_config(self, discovered_plugin: DiscoveredPlugin, values: dict, **kwargs: object) -> list:
"""
校验写入配置的目标插件及字段值。
@@ -108,7 +112,7 @@ async def set_plugin_config(self, discovered_plugin: object, values: dict, **kwa
assert values == {'provider': 'local'}
return []
- FakePluginService.detail_plugin = SimpleNamespace(plugin_id='demo', source='artifact')
+ FakePluginService.detail_plugin = PluginModel(plugin_id='demo', source='artifact')
runtime = build_runtime_with_gateway(tmp_path / 'backend', ArtifactGateway())
result = await runtime.get_plugin_config('demo')
assert result['ok'] is True
@@ -126,7 +130,7 @@ def test_artifact_source_blocks_dependency_install_even_when_same_id_source_exis
'id: demo\nname: Demo\nversion: 1.0.0\nbackend:\n module: plugins.demo\n',
)
gateway = FakePluginRuntimeGateway()
- FakePluginService.detail_plugin = SimpleNamespace(plugin_id='demo', source='artifact')
+ FakePluginService.detail_plugin = PluginModel(plugin_id='demo', source='artifact')
payload = getattr(build_runtime_with_gateway(backend, gateway), method)('demo', confirmed=True)
assert payload['status'] == 'blocked'
assert '签名制品' in payload['message']
@@ -173,6 +177,7 @@ async def get_plugin_state(self, plugin_id: str) -> None:
gateway = UnexpectedQueryGateway()
payload = build_runtime_with_gateway(tmp_path, gateway).install_plugin_dependencies_from_cli('demo', confirmed=True)
assert payload['status'] == 'blocked'
+ assert isinstance(payload['message'], str)
assert '事件循环' in payload['message']
assert gateway.commands == []
@@ -199,7 +204,7 @@ async def get_selected_artifact_plugin(self, plugin_id: str, backend_root: Path)
"""
raise ValueError('制品与源码目录冲突')
- FakePluginService.detail_plugin = SimpleNamespace(plugin_id='demo', source='artifact')
+ FakePluginService.detail_plugin = PluginModel(plugin_id='demo', source='artifact')
gateway = ConflictingGateway()
runtime = build_runtime_with_gateway(backend, gateway)
for payload in (await runtime.get_plugin_config('demo'), await runtime.set_plugin_config('demo', {'key': 'value'})):
@@ -230,7 +235,9 @@ async def get_plugin_state(self, plugin_id: str) -> None:
"""
loops.append(asyncio.get_running_loop())
- async def add_plugin_operation_log(self, payload: dict, *, dry_run: bool, continue_on_error: bool) -> None:
+ async def add_plugin_operation_log(
+ self, payload: Mapping[str, object], *, dry_run: bool, continue_on_error: bool
+ ) -> None:
"""
记录插件日志调用及其事件循环。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_batch_dependencies.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_batch_dependencies.py
index df3eb261d..7d8e0208b 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_batch_dependencies.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_batch_dependencies.py
@@ -1,11 +1,11 @@
import asyncio
from pathlib import Path
-from types import SimpleNamespace
+from typing import Never
import pytest
import plugins.core.runtime.service.audit as audit_module
-from plugins.core.runtime.service.audit import PluginAuditUseCase
+from plugins.core.management.entity.vo.schemas import PluginModel
from plugins.core.runtime.service.dependencies import PLUGIN_DEPENDENCY_INSTALL_TIMEOUT_SECONDS
from plugins.core.validation.dependency_policy import DependencyInstallPolicyConfig
from tests.plugins.core.runtime.fakes import (
@@ -18,6 +18,7 @@
create_frontend_view,
write_manifest,
)
+from tests.plugins.core.runtime.fakes.management import RecordedPluginOperation
def test_plugin_runtime_check_deps_reports_dependency_items(tmp_path: Path) -> None:
@@ -46,6 +47,7 @@ def test_plugin_runtime_check_deps_reports_dependency_items(tmp_path: Path) -> N
assert payload['ok'] is False
assert payload['pluginId'] == 'demo'
assert payload['missingDependencies'] == ['missing-python']
+ assert isinstance(payload['dependencies'], list)
assert len(payload['dependencies']) == EXPECTED_DEPENDENCY_COUNT
@@ -80,6 +82,7 @@ def test_plugin_runtime_plan_plugins_returns_dependency_order(tmp_path: Path) ->
assert payload['ok'] is True
assert payload['operation'] == 'install'
+ assert isinstance(payload['plan'], dict)
assert payload['plan']['orderedPluginIds'] == ['base', 'app']
assert payload['plan']['items'][0]['requested'] is False
assert payload['plan']['items'][1]['requested'] is True
@@ -105,6 +108,7 @@ def test_plugin_runtime_plan_plugins_reports_blockers(tmp_path: Path) -> None:
payload = build_runtime(backend_root).plan_plugins('install', ['app'])
assert payload['ok'] is False
+ assert isinstance(payload['plan'], dict)
assert payload['plan']['blockerCount'] == 1
assert payload['plan']['blockers'][0]['status'] == 'missing'
@@ -151,15 +155,16 @@ def test_plugin_runtime_plan_plugins_reports_database_state_read_error(
assert payload['databaseError'] == 'db unavailable'
-def test_record_plugin_failure_state_logs_and_swallows_persistence_error(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_record_plugin_failure_state_logs_and_swallows_persistence_error(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
"""校验失败状态辅助写入异常会记录日志且不影响主流程。"""
logged_messages = []
- class BrokenAuditGateway:
+ class BrokenAuditGateway(FakePluginRuntimeGateway):
"""测试用异常审计网关。"""
- @staticmethod
- async def mark_plugin_error(plugin_id: str, error_message: str) -> None:
+ async def mark_plugin_error(self, plugin_id: str, error_message: str) -> Never:
"""
模拟标记插件异常失败。
@@ -179,7 +184,7 @@ def fake_exception(message: str, *args: object) -> None:
logged_messages.append(message % args)
monkeypatch.setattr(audit_module.logger, 'exception', fake_exception)
- use_case = PluginAuditUseCase(SimpleNamespace(audit_gateway=BrokenAuditGateway()))
+ use_case = build_runtime_with_gateway(tmp_path, BrokenAuditGateway()).audit
asyncio.run(use_case.record_plugin_failure_state({'ok': False, 'pluginId': 'demo'}, '失败'))
@@ -218,6 +223,7 @@ def test_plugin_runtime_batch_plugins_dry_run_returns_plan(tmp_path: Path) -> No
assert payload['ok'] is True
assert payload['dryRun'] is True
assert payload['continueOnError'] is False
+ assert isinstance(payload['plan'], dict)
assert payload['plan']['orderedPluginIds'] == ['base', 'app']
assert payload['executed'] == []
assert payload['failed'] is None
@@ -246,6 +252,7 @@ def test_plugin_runtime_batch_plugins_stops_when_plan_has_blockers(tmp_path: Pat
assert payload['ok'] is False
assert payload['continueOnError'] is False
+ assert isinstance(payload['plan'], dict)
assert payload['plan']['blockerCount'] == 1
assert payload['executed'] == []
assert payload['failed'] is None
@@ -289,20 +296,23 @@ def test_plugin_runtime_batch_plugins_executes_requested_plugins_only(tmp_path:
create_controller_dir(backend_root / 'plugins' / 'base')
gateway = FakePluginRuntimeGateway()
FakePluginService.plugin_list = [
- SimpleNamespace(plugin_id='base', installed_version='1.0.0', enabled='0', status='installed')
+ PluginModel(plugin_id='base', installed_version='1.0.0', enabled='0', status='installed')
]
payload = asyncio.run(build_runtime_with_gateway(backend_root, gateway).batch_plugins('install', ['app']))
assert payload['ok'] is True
+ assert isinstance(payload['plan'], dict)
assert payload['plan']['orderedPluginIds'] == ['base', 'app']
assert payload['plan']['requestedPluginIds'] == ['app']
+ assert isinstance(payload['executed'], list)
assert [item['pluginId'] for item in payload['executed']] == ['app']
assert all(item['status'] == 'success' for item in payload['executed'])
assert all(isinstance(item['durationMs'], int) for item in payload['executed'])
assert payload['summary'] == {'total': 1, 'succeeded': 1, 'failed': 0, 'skipped': 0}
assert payload['failed'] is None
assert len(FakePluginService.operation_logs) == 1
+ assert isinstance(FakePluginService.operation_logs[0].payload['summary'], dict)
assert FakePluginService.operation_logs[0].payload['summary']['succeeded'] == 1
@@ -325,12 +335,12 @@ def test_plugin_runtime_batch_plugins_continue_on_error_runs_remaining_items(tmp
gateway = FakePluginRuntimeGateway()
FakePluginService.operation_logs = [
- SimpleNamespace(
+ RecordedPluginOperation(
payload={'ok': True, 'operation': 'install', 'pluginId': 'demo', 'message': 'installed'},
dry_run=False,
continue_on_error=False,
),
- SimpleNamespace(
+ RecordedPluginOperation(
payload={'ok': True, 'operation': 'install', 'pluginId': 'other', 'message': 'other installed'},
dry_run=False,
continue_on_error=False,
@@ -361,7 +371,9 @@ async def fake_execute(operation: str, plugin_id: str) -> dict[str, object]:
assert payload['ok'] is False
assert payload['continueOnError'] is True
assert executed_plugin_ids == ['alpha', 'beta', 'gamma']
+ assert isinstance(payload['executed'], list)
assert [item['pluginId'] for item in payload['executed']] == ['alpha', 'beta', 'gamma']
+ assert isinstance(payload['failed'], dict)
assert payload['failed']['pluginId'] == 'beta'
assert payload['summary'] == {'total': 3, 'succeeded': 2, 'failed': 1, 'skipped': 0}
@@ -421,6 +433,7 @@ def test_plugin_runtime_install_deps_dry_run_returns_plan(tmp_path: Path) -> Non
assert payload['ok'] is True
assert payload['dryRun'] is True
assert payload['planCount'] == expected_plan_count
+ assert isinstance(payload['plan'], list)
assert payload['plan'][0]['kind'] == 'python'
assert payload['plan'][0]['command'][1:4] == ['-m', 'pip', 'install']
assert payload['plan'][1]['kind'] == 'npm'
@@ -521,6 +534,7 @@ def test_plugin_runtime_dependency_install_plan_only_policy_blocks_command_execu
assert payload['ok'] is False
assert payload['dryRun'] is False
+ assert isinstance(payload['policy'], dict)
assert payload['policy']['mode'] == 'plan_only'
assert payload['policy']['allowed'] is False
assert '当前策略仅允许生成依赖安装计划' in payload['policy']['reasons']
@@ -559,6 +573,7 @@ def test_plugin_runtime_dependency_install_policy_block_records_operation_log(tm
assert log_payload['operation'] == 'dependency_install'
assert log_payload['pluginId'] == 'demo'
assert log_payload['confirmed'] is True
+ assert isinstance(log_payload['policy'], dict)
assert log_payload['policy']['allowed'] is False
@@ -588,6 +603,7 @@ def test_plugin_runtime_dependency_install_explicit_policy_requires_confirmation
)
assert payload['ok'] is False
+ assert isinstance(payload['policy'], dict)
assert payload['policy']['mode'] == 'explicit'
assert payload['policy']['requirements'] == ['需要显式确认 --yes']
assert gateway.commands == []
@@ -625,8 +641,10 @@ def test_plugin_runtime_dependency_install_success_records_operation_log(tmp_pat
assert log_payload['operation'] == 'dependency_install'
assert log_payload['pluginId'] == 'demo'
assert log_payload['confirmed'] is True
+ assert isinstance(log_payload['policy'], dict)
assert log_payload['policy']['mode'] == 'explicit'
assert log_payload['policy']['allowed'] is True
+ assert isinstance(log_payload['results'], list)
assert log_payload['results'][0]['returnCode'] == 0
@@ -687,6 +705,7 @@ def test_plugin_runtime_blocks_state_changes_in_service_mode(tmp_path: Path) ->
assert payload['ok'] is False
assert payload['status'] == 'blocked'
+ assert isinstance(payload['capability'], dict)
assert payload['capability']['backendRuntimeManageable'] is False
assert 'install' in payload['capability']['blockedOperations']
@@ -758,12 +777,15 @@ def test_plugin_runtime_allows_only_cli_dependency_install_in_built_service_mode
assert web_payload['ok'] is False
assert web_payload['status'] == 'blocked'
+ assert isinstance(web_payload['capability'], dict)
assert 'dependency_install' in web_payload['capability']['blockedOperations']
assert cli_policy_blocked_payload['ok'] is False
+ assert isinstance(cli_policy_blocked_payload['policy'], dict)
assert cli_policy_blocked_payload['policy']['allowed'] is False
assert 'capability' not in cli_policy_blocked_payload
assert cli_payload['ok'] is True
assert 'capability' not in cli_payload
+ assert isinstance(cli_payload['dependencies'], list)
assert [item['kind'] for item in cli_payload['dependencies']] == ['python', 'npm']
assert cli_payload['dependencies'][1]['status'] == 'skipped'
assert len(gateway.commands) == 1
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_catalog.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_catalog.py
index d671b5221..424626e99 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_catalog.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_catalog.py
@@ -1,14 +1,18 @@
import asyncio
from pathlib import Path
-from types import SimpleNamespace
+from typing import Never
+from unittest.mock import create_autospec
import pytest
import plugins.core.runtime.service.context as runtime_context_module
from plugins.core.discovery.scanner import PluginDiscoveryResult
from plugins.core.environment import PluginRuntimeEnvironmentService
+from plugins.core.management.entity.vo.schemas import PluginModel
from plugins.core.runtime.service import PluginRuntimeService
from plugins.core.runtime.service.dependency_container import PluginRuntimeGatewayOverrides
+from plugins.core.runtime.service.query import PluginQueryUseCase
+from plugins.core.types import PluginStateRecord
from plugins.core.validation.dependencies import (
NpmDependencyInspector,
PluginDependencyChecker,
@@ -35,7 +39,7 @@ class QueryOnlyStateGateway:
:ivar list_called: 记录 ``list`` 的调用情况
"""
- def __init__(self, plugin_state: object | None = None) -> None:
+ def __init__(self, plugin_state: PluginStateRecord | None = None) -> None:
"""
初始化查询网关。
@@ -45,7 +49,7 @@ def __init__(self, plugin_state: object | None = None) -> None:
self.detail_calls: list[str] = []
self.list_called = False
- async def get_plugin_state(self, plugin_id: str) -> object | None:
+ async def get_plugin_state(self, plugin_id: str) -> PluginStateRecord | None:
"""
获取插件状态。
@@ -55,7 +59,7 @@ async def get_plugin_state(self, plugin_id: str) -> object | None:
self.detail_calls.append(plugin_id)
return self.plugin_state
- async def list_plugin_states(self) -> list[object]:
+ async def list_plugin_states(self) -> list[PluginStateRecord]:
"""
获取插件状态列表。
@@ -64,7 +68,7 @@ async def list_plugin_states(self) -> list[object]:
self.list_called = True
return [self.plugin_state] if self.plugin_state is not None else []
- def get_plugin_service(self) -> object:
+ def get_plugin_service(self) -> Never:
"""
禁止查询链路回退到管理服务胖接口。
@@ -110,6 +114,7 @@ def test_plugin_runtime_config_uses_dependency_gateway(tmp_path: Path) -> None:
payload = asyncio.run(runtime.get_plugin_config('demo'))
assert payload['ok'] is True
+ assert isinstance(payload['configs'], list)
assert payload['configs'][0]['key'] == 'provider'
assert gateway.session_local.last_session is not None
assert gateway.session_local.last_session.committed is False
@@ -203,7 +208,7 @@ def fake_warning(message: str) -> None:
monkeypatch.setattr(runtime_context_module.logger, 'warning', fake_warning)
- async def load_states_sync_in_loop() -> tuple[list[object], str | None]:
+ async def load_states_sync_in_loop() -> tuple[list[PluginStateRecord], str | None]:
"""
在事件循环内调用同步状态读取。
@@ -329,6 +334,7 @@ def test_plugin_runtime_lists_discovered_plugins(tmp_path: Path) -> None:
assert payload['ok'] is True
assert payload['count'] == 1
+ assert isinstance(payload['plugins'], list)
assert payload['plugins'][0]['pluginId'] == 'demo'
@@ -346,7 +352,7 @@ def test_plugin_runtime_lists_plugins_with_database_state(tmp_path: Path) -> Non
""",
)
query_gateway = QueryOnlyStateGateway(
- SimpleNamespace(
+ PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -365,6 +371,7 @@ def test_plugin_runtime_lists_plugins_with_database_state(tmp_path: Path) -> Non
assert payload['ok'] is True
assert payload['databaseAvailable'] is True
assert payload['databaseError'] is None
+ assert isinstance(payload['plugins'], list)
assert payload['plugins'][0]['enabled'] is True
assert payload['plugins'][0]['status'] == 'installed'
@@ -388,63 +395,20 @@ def test_plugin_runtime_query_entrypoints_delegate_to_query_use_case(
"""校验插件查询入口委托给组合式查询 use case。"""
runtime = build_runtime(tmp_path / 'backend')
- class FakeQueryUseCase:
- """
- 测试用插件查询 use case。
-
- :ivar called_entrypoint: 实际调用的插件入口
- :ivar plugin_id: 插件清单中的唯一标识
- """
-
- def __init__(self) -> None:
- """初始化测试用插件查询 use case。"""
- self.called_entrypoint: str | None = None
- self.plugin_id: str | None = None
-
- def list_plugins(self) -> dict:
- """
- 记录插件列表查询调用。
-
- :return: 包含 ``ok``、``plugins`` 的数据
- """
- self.called_entrypoint = 'list_plugins'
- return {'ok': True, 'plugins': [{'pluginId': 'delegated'}]}
-
- def get_plugin_info(self, plugin_id: str) -> dict:
- """
- 记录插件详情查询调用。
-
- :param plugin_id: 插件清单中的唯一标识
- :return: 包含 ``ok``、``plugin`` 的数据
- """
- self.called_entrypoint = 'get_plugin_info'
- self.plugin_id = plugin_id
- return {'ok': True, 'plugin': {'pluginId': plugin_id}}
-
- async def get_plugin_info_with_state(self, plugin_id: str) -> dict:
- """
- 记录带状态插件详情查询调用。
-
- :param plugin_id: 插件清单中的唯一标识
- :return: 包含 ``ok``、``plugin`` 的数据
- """
- self.called_entrypoint = 'get_plugin_info_with_state'
- self.plugin_id = plugin_id
- return {'ok': True, 'plugin': {'pluginId': plugin_id, 'database': {'available': True}}}
-
- query = FakeQueryUseCase()
+ query = create_autospec(PluginQueryUseCase, instance=True, spec_set=True)
+ handler = getattr(query, entrypoint)
+ handler.return_value = expected_payload
runtime.query = query
if entrypoint == 'list_plugins':
payload = runtime.list_plugins()
+ handler.assert_called_once_with()
elif entrypoint == 'get_plugin_info':
payload = runtime.get_plugin_info('demo')
+ handler.assert_called_once_with('demo')
else:
payload = asyncio.run(runtime.get_plugin_info_with_state('demo'))
-
- assert query.called_entrypoint == entrypoint
- if entrypoint != 'list_plugins':
- assert query.plugin_id == 'demo'
+ handler.assert_awaited_once_with('demo')
assert payload == expected_payload
@@ -514,6 +478,7 @@ def test_plugin_runtime_gets_plugin_info_with_dependencies(tmp_path: Path) -> No
payload = build_runtime(backend_root).get_plugin_info('demo')
assert payload['ok'] is True
+ assert isinstance(payload['plugin'], dict)
assert payload['plugin']['pluginId'] == 'demo'
assert len(payload['plugin']['dependencies']) == EXPECTED_DEPENDENCY_COUNT
assert all(item['ok'] for item in payload['plugin']['dependencies'])
@@ -545,6 +510,7 @@ def test_plugin_runtime_gets_plugin_info_with_config_schema(tmp_path: Path) -> N
payload = build_runtime(backend_root).get_plugin_info('demo')
assert payload['ok'] is True
+ assert isinstance(payload['plugin'], dict)
assert payload['plugin']['config'][0]['key'] == 'provider'
assert payload['plugin']['config'][0]['default'] == 'openai'
@@ -569,7 +535,7 @@ def test_plugin_runtime_gets_plugin_info_with_database_state(tmp_path: Path) ->
""",
)
gateway = FakePluginRuntimeGateway()
- FakePluginService.detail_plugin = SimpleNamespace(
+ FakePluginService.detail_plugin = PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -582,6 +548,7 @@ def test_plugin_runtime_gets_plugin_info_with_database_state(tmp_path: Path) ->
payload = asyncio.run(build_runtime_with_gateway(backend_root, gateway).get_plugin_info_with_state('demo'))
assert payload['ok'] is True
+ assert isinstance(payload['plugin'], dict)
assert payload['plugin']['enabled'] is True
assert payload['plugin']['status'] == 'installed'
assert payload['plugin']['installedVersion'] == '1.0.0'
@@ -603,7 +570,7 @@ def test_plugin_runtime_gets_plugin_info_with_state_through_query_port(tmp_path:
""",
)
query_gateway = QueryOnlyStateGateway(
- SimpleNamespace(
+ PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -622,6 +589,7 @@ def test_plugin_runtime_gets_plugin_info_with_state_through_query_port(tmp_path:
payload = asyncio.run(runtime.get_plugin_info_with_state('demo'))
assert payload['ok'] is True
+ assert isinstance(payload['plugin'], dict)
assert payload['plugin']['pluginId'] == 'demo'
assert payload['plugin']['status'] == 'installed'
assert payload['plugin']['database']['available'] is True
@@ -645,6 +613,7 @@ def test_plugin_runtime_gets_plugin_info_when_database_unavailable(tmp_path: Pat
payload = asyncio.run(build_runtime(backend_root).get_plugin_info_with_state('demo'))
assert payload['ok'] is True
+ assert isinstance(payload['plugin'], dict)
assert payload['plugin']['pluginId'] == 'demo'
assert payload['plugin']['database']['available'] is False
assert payload['plugin']['database']['installed'] is False
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_check_docs.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_check_docs.py
index 281f0e5be..9e1b3c636 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_check_docs.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_check_docs.py
@@ -1,10 +1,13 @@
import asyncio
from pathlib import Path
-from types import SimpleNamespace
+from typing import Never
-from plugins.core.lifecycle.purge import PluginPurgePlanner
+from plugins.core.discovery.scanner import DiscoveredPlugin
+from plugins.core.lifecycle.purge import PluginPurgePlan, PluginPurgePlanner
+from plugins.core.management.entity.vo.schemas import PluginModel
from plugins.core.runtime.service import PluginRuntimeService
from plugins.core.runtime.service.dependency_container import PluginRuntimeGatewayOverrides
+from plugins.core.types import PluginStateRecord
from plugins.core.validation.dependencies import PluginDependencyChecker
from tests.plugins.core.runtime.fakes import (
EXPECTED_PURGE_DESTRUCTIVE_COUNT,
@@ -22,7 +25,7 @@
class PrecheckStateQueryGateway:
"""仅提供预检所需插件状态查询能力的测试网关。"""
- async def get_plugin_state(self, plugin_id: str) -> object | None:
+ async def get_plugin_state(self, plugin_id: str) -> PluginStateRecord | None:
"""
获取插件状态。
@@ -30,7 +33,7 @@ async def get_plugin_state(self, plugin_id: str) -> object | None:
"""
return None
- async def list_plugin_states(self) -> list[object]:
+ async def list_plugin_states(self) -> list[PluginStateRecord]:
"""
获取插件状态列表。
@@ -38,7 +41,7 @@ async def list_plugin_states(self) -> list[object]:
"""
return []
- def get_plugin_service(self) -> object:
+ def get_plugin_service(self) -> Never:
"""
禁止预检状态读取回退到管理服务胖接口。
@@ -58,7 +61,7 @@ def __init__(self) -> None:
"""初始化测试清理计划网关。"""
self.calls: list[str] = []
- async def build_plugin_purge_plan(self, discovered_plugin: object) -> object:
+ async def build_plugin_purge_plan(self, discovered_plugin: DiscoveredPlugin) -> PluginPurgePlan:
"""
构建测试清理计划。
@@ -74,7 +77,7 @@ async def build_plugin_purge_plan(self, discovered_plugin: object) -> object:
job_count=4,
)
- def get_plugin_service(self) -> object:
+ def get_plugin_service(self) -> Never:
"""
禁止清理计划链路回退到管理服务胖接口。
@@ -103,6 +106,7 @@ def test_plugin_runtime_check_reports_missing_dependencies(tmp_path: Path) -> No
payload = build_runtime(backend_root).check_plugin('demo')
assert payload['ok'] is False
+ assert isinstance(payload['checks'], list)
assert payload['checks'][0]['missingDependencies'] == ['missing-python']
assert payload['checks'][0]['dependencies'][0]['level'] == 'error'
@@ -132,6 +136,7 @@ def test_plugin_runtime_check_reports_manifest_warnings(tmp_path: Path) -> None:
payload = build_runtime(backend_root).check_plugin('demo')
assert payload['ok'] is True
+ assert isinstance(payload['checks'], list)
assert payload['checks'][0]['manifestOk'] is True
assert payload['checks'][0]['manifestWarnings'][0]['level'] == 'warning'
assert payload['checks'][0]['manifestWarnings'][0]['kind'] == 'secret_config_default'
@@ -158,6 +163,7 @@ def test_plugin_runtime_check_reports_compatibility_errors(tmp_path: Path) -> No
payload = build_runtime(backend_root).check_plugin('demo')
assert payload['ok'] is False
+ assert isinstance(payload['checks'], list)
assert payload['checks'][0]['ok'] is False
assert payload['checks'][0]['manifestOk'] is False
assert payload['checks'][0]['manifestIssues'][0]['level'] == 'error'
@@ -190,6 +196,7 @@ def test_plugin_runtime_install_dry_run_reports_manifest_warnings(tmp_path: Path
result = asyncio.run(build_runtime(backend_root).install_plugin('demo', dry_run=True))
assert result['ok'] is True, result
+ assert isinstance(result['manifestWarnings'], list)
assert result['manifestWarnings'][0]['level'] == 'warning'
assert result['manifestWarnings'][0]['kind'] == 'secret_config_default'
@@ -217,6 +224,7 @@ def test_plugin_runtime_install_dry_run_reports_compatibility_errors(tmp_path: P
assert result['ok'] is True, result
assert result['dryRun'] is True
assert result['manifestOk'] is False
+ assert isinstance(result['manifestIssues'], list)
assert result['manifestIssues'][0]['level'] == 'error'
assert result['manifestIssues'][0]['kind'] == 'compatibility_unsatisfied'
@@ -258,7 +266,9 @@ def test_plugin_runtime_precheck_plugin_operation_returns_unified_payload(tmp_pa
assert result['pluginDependencyOk'] is True
assert result['structureOk'] is True
assert result['menuConflictOk'] is True
+ assert isinstance(result['precheck'], dict)
assert result['precheck']['menuConflicts'] == []
+ assert isinstance(result['actions'], list)
assert any(action['name'] == 'install_menus' for action in result['actions'])
@@ -291,6 +301,7 @@ def test_plugin_runtime_precheck_purge_uses_purge_plan_port(tmp_path: Path) -> N
assert result['ok'] is True
assert result['operation'] == 'purge'
+ assert isinstance(result['plan'], dict)
assert result['plan']['pluginId'] == 'demo'
assert result['plan']['destructiveCount'] == EXPECTED_PURGE_DESTRUCTIVE_COUNT
assert purge_plan_gateway.calls == ['demo']
@@ -311,7 +322,7 @@ def test_plugin_runtime_precheck_upgrade_includes_version_state(tmp_path: Path)
""",
)
create_controller_dir(plugin_root)
- FakePluginService.detail_plugin = SimpleNamespace(
+ FakePluginService.detail_plugin = PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -391,6 +402,7 @@ def test_plugin_runtime_generate_plugin_docs_from_manifest(tmp_path: Path) -> No
assert result['ok'] is True
assert result['format'] == 'markdown'
+ assert isinstance(result['markdown'], str)
assert '# 演示插件' in result['markdown']
assert '| Demo | `demo` | `plugin/demo/index` | `demo:list` | `C` |' in result['markdown']
assert '| `demo:list` | 演示列表 | - |' in result['markdown']
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_gateway_ports.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_gateway_ports.py
index 80577b0c2..86952addb 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_gateway_ports.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_gateway_ports.py
@@ -1,9 +1,11 @@
import asyncio
import subprocess
from pathlib import Path
+from unittest.mock import Mock
import pytest
+from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.runtime.service.gateway import (
DefaultPluginCommandRunnerGateway,
PluginAuditGateway,
@@ -50,7 +52,10 @@ def test_gateway_protocols_are_runtime_checkable() -> None:
def test_unavailable_gateways_fail_explicitly() -> None:
"""校验不可用网关通过明确异常快速失败。"""
cases = (
- (lambda: asyncio.run(UnavailablePluginConfigGateway().get_plugin_config(object())), '配置适配器'),
+ (
+ lambda: asyncio.run(UnavailablePluginConfigGateway().get_plugin_config(Mock(spec_set=DiscoveredPlugin))),
+ '配置适配器',
+ ),
(
lambda: asyncio.run(UnavailablePluginAuditGateway().list_plugin_operation_logs(export_limit=5)),
'审计适配器',
@@ -70,7 +75,9 @@ def test_unavailable_gateways_fail_explicitly() -> None:
'migration 历史适配器',
),
(
- lambda: asyncio.run(UnavailablePluginPurgePlanGateway().build_plugin_purge_plan(object())),
+ lambda: asyncio.run(
+ UnavailablePluginPurgePlanGateway().build_plugin_purge_plan(Mock(spec_set=DiscoveredPlugin))
+ ),
'清理计划适配器',
),
(
@@ -83,7 +90,9 @@ def test_unavailable_gateways_fail_explicitly() -> None:
),
(UnavailablePluginLifecycleUnitOfWorkGateway().open_lifecycle_unit_of_work, '生命周期主事务适配器'),
(
- lambda: asyncio.run(UnavailablePluginMigrationExecutionGateway().run_plugin_migrations(object())),
+ lambda: asyncio.run(
+ UnavailablePluginMigrationExecutionGateway().run_plugin_migrations(Mock(spec_set=DiscoveredPlugin))
+ ),
'migration 执行适配器',
),
(lambda: asyncio.run(UnavailablePluginStateQueryGateway().list_plugin_states()), '状态查询适配器'),
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_install_config_health.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_install_config_health.py
index 2977866fe..05ef45223 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_install_config_health.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_install_config_health.py
@@ -1,29 +1,32 @@
import asyncio
import json
from pathlib import Path
-from types import SimpleNamespace
+from typing import Never
from pytest import MonkeyPatch
+from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.environment import PluginRuntimeEnvironmentService
from plugins.core.lifecycle.migration import PluginMigrationRunner
+from plugins.core.management.entity.vo.schemas import PluginConfigValueModel, PluginModel
from plugins.core.runtime.service import PluginRuntimeService
from plugins.core.runtime.service.dependency_container import PluginRuntimeGatewayOverrides
-from plugins.core.runtime.service.migration_store import PluginDatabaseMigrationHistoryStore
from plugins.core.runtime.support import PluginConfigPayloadBuilder
+from plugins.core.types import PluginConfigValue
from plugins.core.validation.dependencies import PluginDependencyChecker
+from plugins.core.validation.menus import PluginMenuConflictItem
from tests.plugins.core.runtime.fakes import (
EXPECTED_CONFIG_ORDER,
FakePluginRuntimeGateway,
FakePluginService,
FakeRuntimeEnvironment,
- FakeSession,
build_runtime,
build_runtime_with_gateway,
create_controller_dir,
create_frontend_view,
write_manifest,
)
+from tests.plugins.core.runtime.fakes.management import RecordedPluginOperation
class ConfigOnlyGateway:
@@ -38,10 +41,12 @@ class ConfigOnlyGateway:
def __init__(self) -> None:
"""初始化测试配置网关。"""
self.get_calls: list[tuple[str, bool]] = []
- self.update_calls: list[tuple[str, dict[str, object]]] = []
+ self.update_calls: list[tuple[str, dict[str, PluginConfigValue]]] = []
self.audit_payloads: list[dict[str, object]] = []
- async def get_plugin_config(self, discovered_plugin: object, *, reveal_secret: bool = False) -> list[object]:
+ async def get_plugin_config(
+ self, discovered_plugin: DiscoveredPlugin, *, reveal_secret: bool = False
+ ) -> list[PluginConfigValueModel]:
"""
获取插件配置。
@@ -52,18 +57,11 @@ async def get_plugin_config(self, discovered_plugin: object, *, reveal_secret: b
plugin_id = discovered_plugin.manifest.id
self.get_calls.append((plugin_id, reveal_secret))
value = 'openai-key' if reveal_secret else '******'
- return [
- SimpleNamespace(
- model_dump=lambda by_alias=True: {
- 'key': 'provider',
- 'value': value,
- 'default': value,
- 'secret': True,
- }
- )
- ]
+ return [PluginConfigValueModel(key='provider', value=value, default=value, secret=True)]
- async def update_plugin_config(self, discovered_plugin: object, values: dict[str, object]) -> list[object]:
+ async def update_plugin_config(
+ self, discovered_plugin: DiscoveredPlugin, values: dict[str, PluginConfigValue]
+ ) -> list[PluginConfigValueModel]:
"""
更新插件配置。
@@ -73,25 +71,16 @@ async def update_plugin_config(self, discovered_plugin: object, values: dict[str
"""
plugin_id = discovered_plugin.manifest.id
self.update_calls.append((plugin_id, values))
- return [
- SimpleNamespace(
- model_dump=lambda by_alias=True, key=key, value=value: {
- 'key': key,
- 'value': value,
- 'secret': False,
- }
- )
- for key, value in values.items()
- ]
+ return [PluginConfigValueModel(key=key, value=value) for key, value in values.items()]
async def set_plugin_config(
self,
- discovered_plugin: object,
- values: dict[str, object],
+ discovered_plugin: DiscoveredPlugin,
+ values: dict[str, PluginConfigValue],
*,
audit_operation: str,
success_message: str,
- ) -> list[object]:
+ ) -> list[PluginConfigValueModel]:
"""
在同一事务语义中更新插件配置并记录审计负载。
@@ -115,7 +104,7 @@ async def set_plugin_config(
)
return configs
- def get_plugin_service(self) -> object:
+ def get_plugin_service(self) -> Never:
"""
禁止配置链路回退到管理服务胖接口。
@@ -144,6 +133,7 @@ def test_plugin_runtime_install_plugin_dry_run_returns_actions(tmp_path: Path) -
assert result['ok'] is True, result
assert result['dryRun'] is True
+ assert isinstance(result['actions'], list)
assert result['actions'][0]['name'] == 'upsert_plugin'
assert any(action['name'] == 'check_structure' for action in result['actions'])
assert any(action['name'] == 'check_menu_conflicts' for action in result['actions'])
@@ -207,119 +197,10 @@ def test_plugin_runtime_install_plugin_uses_lifecycle_uow_and_migration_gateway_
(plugin_root / 'seeds').mkdir()
(plugin_root / 'seeds' / 'demo_seed.sql').write_text('select 3;\n', encoding='utf-8')
- class InstallLifecycleUnitOfWork:
- """
- 测试用插件安装生命周期 UoW。
-
- :ivar gateway: 代理底层操作的网关
- :ivar session: 当前操作共用的会话
- :ivar session_context: 当前会话的上下文
- """
-
- def __init__(self, gateway: 'NoFatInstallGateway') -> None:
- """
- 初始化测试 UoW。
-
- :param gateway: 代理底层操作的网关
- """
- self.gateway = gateway
- self.session: FakeSession | None = None
- self.session_context: FakeSession | None = None
-
- async def __aenter__(self) -> 'InstallLifecycleUnitOfWork':
- """
- 打开测试 UoW 会话。
-
- :return: 当前实例
- """
- self.session_context = self.gateway.session_local()
- self.session = await self.session_context.__aenter__()
- return self
-
- async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> None:
- """
- 关闭测试 UoW 会话。
-
- :param exc_type: 退出上下文时的异常类型
- :param exc: 捕获到的异常实例
- :param traceback: 异常的调用栈
- """
- await self.session_context.__aexit__(exc_type, exc, traceback)
-
- async def check_installed_menu_conflicts(self, discovered_plugin: object) -> list[object]:
- """
- 检查已安装菜单冲突。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :return: 安装菜单的冲突检查结果
- """
- return await FakePluginService.check_installed_menu_conflict_services(self.session, discovered_plugin)
-
- async def upsert_discovered_plugin(
- self,
- discovered_plugin: object,
- backend_root: Path,
- frontend_root: Path,
- ) -> object:
- """
- 写入插件基础状态。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :param backend_root: 后端项目的根目录
- :param frontend_root: 前端项目的根目录
- :return: 写入后的插件状态
- """
- return await FakePluginService.upsert_discovered_plugin_services(
- self.session,
- discovered_plugin,
- backend_root,
- frontend_root,
- )
-
- async def install_plugin_menu(self, discovered_plugin: object, *, enabled: bool) -> None:
- """
- 安装插件菜单。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :param enabled: 是否启用该项功能
- """
- await FakePluginService.install_plugin_menu_services(self.session, discovered_plugin, enabled=enabled)
-
- async def install_plugin_default_config(self, discovered_plugin: object) -> list[object]:
- """
- 安装插件默认配置。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :return: 默认配置的安装结果
- """
- return await FakePluginService.install_plugin_default_config_services(self.session, discovered_plugin)
-
- async def install_plugin_jobs(self, discovered_plugin: object, *, enabled: bool) -> None:
- """
- 同步插件任务。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :param enabled: 是否启用该项功能
- """
- await FakePluginService.install_plugin_job_services(self.session, discovered_plugin, enabled=enabled)
-
- async def mark_plugin_installed(self, discovered_plugin: object) -> object:
- """
- 标记插件已安装。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :return: 更新后的安装标记
- """
- return await FakePluginService.mark_plugin_installed_services(self.session, discovered_plugin)
-
- async def commit(self) -> None:
- """提交测试 UoW。"""
- await self.session.commit()
-
class NoFatInstallGateway(FakePluginRuntimeGateway):
"""禁止安装流程读取 fat state gateway 的测试适配器。"""
- def get_async_session_local(self) -> object:
+ def get_async_session_local(self) -> Never:
"""
禁止通过 state gateway 打开数据库会话。
@@ -327,7 +208,7 @@ def get_async_session_local(self) -> object:
"""
raise AssertionError('安装流程不应通过 state gateway 打开数据库会话')
- def get_plugin_service(self) -> object:
+ def get_plugin_service(self) -> Never:
"""
禁止通过 state gateway 获取管理服务。
@@ -335,32 +216,6 @@ def get_plugin_service(self) -> object:
"""
raise AssertionError('安装流程不应通过 state gateway 获取管理服务')
- def open_lifecycle_unit_of_work(self) -> InstallLifecycleUnitOfWork:
- """
- 打开测试生命周期 UoW。
-
- :return: ``InstallLifecycleUnitOfWork`` 实例
- """
- return InstallLifecycleUnitOfWork(self)
-
- async def run_plugin_migrations(self, discovered_plugin: object) -> list[object]:
- """
- 通过独立 migration session 执行插件 migration。
-
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :return: 独立迁移会话的执行结果
- """
- async with self.session_local() as migration_session:
- return await PluginMigrationRunner(
- discovered_plugin,
- PluginDatabaseMigrationHistoryStore.with_model_gateway(
- FakePluginService,
- self,
- self.session_local,
- ),
- manage_execution_transaction=True,
- ).run(migration_session)
-
gateway = NoFatInstallGateway()
result = asyncio.run(
@@ -432,6 +287,7 @@ def test_plugin_runtime_install_plugin_rejects_manifest_errors(tmp_path: Path) -
assert result['ok'] is False
assert result['message'] == '插件 manifest 检查失败,安装已中止'
assert result['manifestOk'] is False
+ assert isinstance(result['manifestIssues'], list)
assert result['manifestIssues'][0]['kind'] == 'compatibility_unsatisfied'
assert FakePluginService.upsert_called is False
assert FakePluginService.marked_errors == [('demo', '插件 manifest 检查失败,安装已中止')]
@@ -463,9 +319,12 @@ def test_plugin_runtime_install_plugin_runs_sql_seed(tmp_path: Path) -> None:
assert result['ok'] is True
assert result['structureOk'] is True
assert result['structureErrors'] == []
+ assert isinstance(result['seeds'], list)
assert result['seeds'][0]['seed_path'] == 'seeds/demo_seed.sql'
assert result['seeds'][0]['statement_count'] == 1
- assert gateway.session_local.executed_session.executed_statements == ['select 1']
+ executed_session = gateway.session_local.executed_session
+ assert executed_session is not None
+ assert executed_session.executed_statements == ['select 1']
assert gateway.session_local.committed_session is not None
@@ -493,6 +352,7 @@ def test_plugin_runtime_install_plugin_runs_sql_migration(tmp_path: Path) -> Non
result = asyncio.run(build_runtime_with_gateway(backend_root, gateway).install_plugin('demo'))
assert result['ok'] is True
+ assert isinstance(result['migrations'], list)
assert result['migrations'][0]['migration_path'] == 'migrations/001_demo.sql'
assert result['migrations'][0]['statement_count'] == 1
assert result['migrations'][0]['checksum']
@@ -536,6 +396,7 @@ def test_plugin_runtime_install_plugin_skips_recorded_migration(tmp_path: Path)
result = asyncio.run(build_runtime_with_gateway(backend_root, gateway).install_plugin('demo'))
assert result['ok'] is True
+ assert isinstance(result['migrations'], list)
assert result['migrations'][0]['skipped'] is True
assert FakePluginService.migration_records == []
assert all(not session.executed_statements for session in gateway.session_local.sessions)
@@ -571,6 +432,7 @@ def test_plugin_runtime_install_dry_run_reports_changed_recorded_migration(tmp_p
assert result['ok'] is True
assert result['manifestOk'] is False
+ assert isinstance(result['manifestIssues'], list)
assert result['manifestIssues'][0]['kind'] == 'migration_checksum_changed'
assert result['manifestIssues'][0]['path'] == 'backend.migrations.migrations/001_demo.sql'
assert result['message'] == '插件安装演练完成,未执行实际写入'
@@ -599,7 +461,7 @@ def test_plugin_runtime_lifecycle_precheck_uses_migration_history_gateway(tmp_pa
class NoFatStateGateway(FakePluginRuntimeGateway):
"""禁止生命周期预检读取 fat state gateway 的测试适配器。"""
- def get_async_session_local(self) -> object:
+ def get_async_session_local(self) -> Never:
"""
禁止通过 state gateway 打开数据库会话。
@@ -607,7 +469,7 @@ def get_async_session_local(self) -> object:
"""
raise AssertionError('生命周期脚本预检不应通过 state gateway 打开数据库会话')
- def get_plugin_service(self) -> object:
+ def get_plugin_service(self) -> Never:
"""
禁止通过 state gateway 获取管理服务。
@@ -621,6 +483,7 @@ def get_plugin_service(self) -> object:
assert result['ok'] is True
assert result['manifestOk'] is True
+ assert isinstance(result['manifestWarnings'], list)
assert [issue['kind'] for issue in result['manifestWarnings']] == ['migration_pending']
@@ -711,7 +574,7 @@ def test_plugin_runtime_install_plugin_stops_when_database_menu_conflict_exists(
create_frontend_view(backend_root, 'demo')
gateway = FakePluginRuntimeGateway()
FakePluginService.installed_menu_conflicts = [
- SimpleNamespace(
+ PluginMenuConflictItem(
kind='installed_permission',
plugin_id='demo',
conflict_plugin_id=None,
@@ -725,6 +588,7 @@ def test_plugin_runtime_install_plugin_stops_when_database_menu_conflict_exists(
assert result['ok'] is False
assert result['message'] == '插件菜单与已安装菜单存在冲突,安装已中止'
assert result['menuConflictOk'] is False
+ assert isinstance(result['menuConflicts'], list)
assert result['menuConflicts'][0]['kind'] == 'installed_permission'
assert FakePluginService.upsert_called is False
assert gateway.session_local.sessions[0] is not None
@@ -800,6 +664,7 @@ def test_plugin_runtime_install_plugin_blocks_when_dependencies_are_missing(tmp_
assert result['ok'] is False
assert result['message'] == '插件依赖缺失,安装已中止,请先显式安装依赖'
+ assert isinstance(result['dependencyInstall'], dict)
assert result['dependencyInstall']['ok'] is True
assert result['dependencyInstall']['dryRun'] is True
assert result['dependencyInstall']['planCount'] == expected_plan_count
@@ -846,6 +711,7 @@ def test_plugin_runtime_install_plugin_does_not_execute_dependency_install_comma
assert result['ok'] is False
assert result['message'] == '插件依赖缺失,安装已中止,请先显式安装依赖'
+ assert isinstance(result['dependencyInstall'], dict)
assert result['dependencyInstall']['ok'] is True
assert result['dependencyInstall']['dryRun'] is True
assert result['dependencyInstall']['dependencyOk'] is False
@@ -885,6 +751,7 @@ def test_plugin_runtime_get_and_set_plugin_config(tmp_path: Path) -> None:
set_result = asyncio.run(runtime.set_plugin_config('demo', {'provider': 'mistral'}))
assert get_result['ok'] is True
+ assert isinstance(get_result['configs'], list)
assert get_result['configs'][0]['key'] == 'provider'
assert get_result['configs'][0]['value'] == 'openai'
assert get_result['configs'][0]['group'] == 'model'
@@ -893,10 +760,12 @@ def test_plugin_runtime_get_and_set_plugin_config(tmp_path: Path) -> None:
assert get_result['configs'][0]['pattern'] == '^[a-z]+$'
assert set_result['ok'] is True
assert set_result['operation'] == 'config_set'
+ assert isinstance(set_result['configs'], list)
assert set_result['configs'][0]['value'] == 'mistral'
assert len(FakePluginService.operation_logs) == 1
operation_log = FakePluginService.operation_logs[0]
assert operation_log.payload['operation'] == 'config_set'
+ assert isinstance(operation_log.payload['summary'], dict)
assert operation_log.payload['summary']['changedKeys'] == ['provider']
assert operation_log.payload['summary']['changes'][0]['before'] == 'openai'
assert operation_log.payload['summary']['changes'][0]['after'] == 'mistral'
@@ -989,8 +858,10 @@ def test_plugin_runtime_config_uses_config_port_without_fat_service_fallback(tmp
set_result = asyncio.run(runtime.set_plugin_config('demo', {'provider': 'mistral'}))
assert get_result['ok'] is True
+ assert isinstance(get_result['configs'], list)
assert get_result['configs'][0]['value'] == 'openai-key'
assert set_result['ok'] is True
+ assert isinstance(set_result['configs'], list)
assert set_result['configs'][0]['value'] == 'mistral'
assert config_gateway.get_calls == [('demo', True), ('demo', True)]
assert config_gateway.update_calls == [('demo', {'provider': 'mistral'})]
@@ -1026,13 +897,19 @@ def test_plugin_runtime_export_plugin_config_masks_secret_by_default(tmp_path: P
assert masked_result['ok'] is True
assert masked_result['revealSecret'] is False
+ assert isinstance(masked_result['values'], dict)
assert masked_result['values']['api_key'] == '******'
+ assert isinstance(masked_result['configs'], list)
assert masked_result['configs'][0]['default'] == '******'
+ assert isinstance(masked_result['metadata'], list)
assert masked_result['metadata'][0]['secret'] is True
assert masked_result['metadata'][0]['default'] == '******'
assert plain_result['revealSecret'] is True
+ assert isinstance(plain_result['values'], dict)
assert plain_result['values']['api_key'] == 'sk-secret'
+ assert isinstance(plain_result['configs'], list)
assert plain_result['configs'][0]['default'] == 'sk-secret'
+ assert isinstance(plain_result['metadata'], list)
assert plain_result['metadata'][0]['default'] == 'sk-secret'
@@ -1065,6 +942,7 @@ def test_plugin_runtime_import_plugin_config_updates_values(tmp_path: Path) -> N
assert result['pluginId'] == 'demo'
assert result['operation'] == 'config_import'
assert result['importedKeys'] == ['provider']
+ assert isinstance(result['configs'], list)
assert result['configs'][0]['value'] == 'mistral'
assert len(FakePluginService.operation_logs) == 1
assert FakePluginService.operation_logs[0].payload['operation'] == 'config_import'
@@ -1104,7 +982,7 @@ def test_plugin_runtime_diagnose_plugin_returns_masked_snapshot(tmp_path: Path)
create_frontend_view(backend_root, 'demo')
gateway = FakePluginRuntimeGateway()
FakePluginService.plugin_list = [
- SimpleNamespace(
+ PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -1116,12 +994,12 @@ def test_plugin_runtime_diagnose_plugin_returns_masked_snapshot(tmp_path: Path)
)
]
FakePluginService.operation_logs = [
- SimpleNamespace(
+ RecordedPluginOperation(
payload={'ok': True, 'operation': 'install', 'pluginId': 'demo', 'message': 'installed'},
dry_run=False,
continue_on_error=False,
),
- SimpleNamespace(
+ RecordedPluginOperation(
payload={'ok': True, 'operation': 'install', 'pluginId': 'other', 'message': 'other installed'},
dry_run=False,
continue_on_error=False,
@@ -1133,13 +1011,17 @@ def test_plugin_runtime_diagnose_plugin_returns_masked_snapshot(tmp_path: Path)
assert result['ok'] is True, result
assert result['pluginId'] == 'demo'
+ assert isinstance(result['info'], dict)
assert result['info']['pluginId'] == 'demo'
+ assert isinstance(result['check'], dict)
assert result['check']['checks'][0]['pluginId'] == 'demo'
assert result['check']['databaseAvailable'] is True
assert result['check']['databaseError'] is None
+ assert isinstance(result['menuPlan'], dict)
assert result['menuPlan']['total'] == 1
assert result['menuPlan']['permissionCount'] == 1
assert result['menuPlan']['items'][0]['component'] == 'plugin/demo/index'
+ assert isinstance(result['config'], dict)
assert result['config']['configs'][0]['key'] == 'api_key'
assert result['config']['configs'][0]['value'] == '******'
assert result['config']['summary'] == {
@@ -1151,6 +1033,7 @@ def test_plugin_runtime_diagnose_plugin_returns_masked_snapshot(tmp_path: Path)
'missingRequiredKeys': [],
'masked': True,
}
+ assert isinstance(result['audit'], dict)
assert result['audit']['available'] is True
assert result['audit']['count'] == 1
assert result['audit']['items'][0]['operation'] == 'install'
@@ -1179,7 +1062,7 @@ def test_plugin_runtime_diagnose_plugin_uses_audit_gateway_for_snapshot(tmp_path
)
create_controller_dir(plugin_root)
FakePluginService.plugin_list = [
- SimpleNamespace(
+ PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -1191,7 +1074,7 @@ def test_plugin_runtime_diagnose_plugin_uses_audit_gateway_for_snapshot(tmp_path
)
]
FakePluginService.operation_logs = [
- SimpleNamespace(
+ RecordedPluginOperation(
payload={'ok': True, 'operation': 'install', 'pluginId': 'demo', 'message': 'installed'},
dry_run=False,
continue_on_error=False,
@@ -1201,7 +1084,7 @@ def test_plugin_runtime_diagnose_plugin_uses_audit_gateway_for_snapshot(tmp_path
class NoFatStateGateway(FakePluginRuntimeGateway):
"""禁止诊断审计快照读取 fat state gateway 的测试适配器。"""
- def get_async_session_local(self) -> object:
+ def get_async_session_local(self) -> Never:
"""
禁止通过 state gateway 打开数据库会话。
@@ -1209,7 +1092,7 @@ def get_async_session_local(self) -> object:
"""
raise AssertionError('诊断审计快照不应通过 state gateway 打开数据库会话')
- def get_plugin_service(self) -> object:
+ def get_plugin_service(self) -> Never:
"""
禁止通过 state gateway 获取管理服务。
@@ -1220,6 +1103,7 @@ def get_plugin_service(self) -> object:
result = asyncio.run(build_runtime_with_gateway(backend_root, NoFatStateGateway()).diagnose_plugin('demo'))
assert result['ok'] is True
+ assert isinstance(result['audit'], dict)
assert result['audit']['available'] is True
assert result['audit']['count'] == 1
assert result['audit']['items'][0]['operation'] == 'install'
@@ -1230,7 +1114,7 @@ def test_plugin_runtime_diagnose_artifact_without_local_source_keeps_database_sn
backend_root = tmp_path / 'backend'
(backend_root / 'plugins').mkdir(parents=True)
FakePluginService.plugin_list = [
- SimpleNamespace(
+ PluginModel(
plugin_id='demo',
installed_version='2.0.0',
enabled='0',
@@ -1248,14 +1132,19 @@ def test_plugin_runtime_diagnose_artifact_without_local_source_keeps_database_sn
result = asyncio.run(runtime.diagnose_plugin('demo'))
assert result['ok'] is False
+ assert isinstance(result['info'], dict)
assert result['info']['scope'] == 'database_only'
assert result['info']['installedVersion'] == '2.0.0'
assert result['info']['database']['enabled'] == '0'
+ assert isinstance(result['check'], dict)
assert result['check']['supported'] is False
assert result['check']['ok'] is False
+ assert isinstance(result['menuPlan'], dict)
assert result['menuPlan']['supported'] is False
+ assert isinstance(result['config'], dict)
assert result['config']['supported'] is False
assert result['config']['ok'] is False
+ assert isinstance(result['audit'], dict)
assert result['audit']['available'] is True
@@ -1286,6 +1175,7 @@ def test_plugin_runtime_health_plugin_returns_checker_result(tmp_path: Path) ->
assert result['ok'] is True
assert result['pluginId'] == 'demo'
+ assert isinstance(result['health'], dict)
assert result['health']['status'] == 'healthy'
assert result['health']['details'] == {'ready': True}
@@ -1325,5 +1215,6 @@ def test_plugin_runtime_install_plugin_runs_seed_files(tmp_path: Path) -> None:
result = asyncio.run(build_runtime_with_gateway(backend_root, gateway).install_plugin('demo'))
assert result['ok'] is True
+ assert isinstance(result['seeds'], list)
assert result['seeds'][0]['seed_path'] == 'seeds/demo_seed.py'
assert any(getattr(session, 'seed_ran', False) is True for session in gateway.session_local.sessions)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_structure_checks.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_structure_checks.py
index a93ebabb3..a98a861c4 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_structure_checks.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_structure_checks.py
@@ -31,6 +31,7 @@ def test_plugin_runtime_check_reports_structure_errors(tmp_path: Path) -> None:
payload = build_runtime(backend_root).check_plugin('demo')
assert payload['ok'] is False
+ assert isinstance(payload['checks'], list)
assert payload['checks'][0]['missingDependencies'] == []
assert [item['kind'] for item in payload['checks'][0]['structureErrors']] == [
'seed_file',
@@ -67,6 +68,7 @@ def test_plugin_runtime_check_uses_runtime_frontend_plugin_root(tmp_path: Path)
payload = build_runtime(backend_root, frontend_root=frontend_root).check_plugin('demo')
assert payload['ok'] is True
+ assert isinstance(payload['checks'], list)
assert payload['checks'][0]['structureErrors'] == []
@@ -93,6 +95,7 @@ def test_plugin_runtime_check_reports_migration_structure_errors(tmp_path: Path)
payload = build_runtime(backend_root).check_plugin('demo')
assert payload['ok'] is False
+ assert isinstance(payload['checks'], list)
assert [item['kind'] for item in payload['checks'][0]['structureErrors']] == [
'migration_file',
'migration_type',
@@ -122,6 +125,7 @@ def test_plugin_runtime_check_reports_hook_structure_errors(tmp_path: Path) -> N
payload = build_runtime(backend_root).check_plugin('demo')
assert payload['ok'] is False
+ assert isinstance(payload['checks'], list)
assert [item['kind'] for item in payload['checks'][0]['structureErrors']] == [
'hook_boundary',
'hook_callable',
@@ -151,6 +155,7 @@ def test_plugin_runtime_check_accepts_sql_seed(tmp_path: Path) -> None:
payload = build_runtime(backend_root).check_plugin('demo')
assert payload['ok'] is True
+ assert isinstance(payload['checks'], list)
assert payload['checks'][0]['structureErrors'] == []
@@ -201,4 +206,5 @@ def test_plugin_runtime_check_accepts_namespaced_permissions(tmp_path: Path) ->
payload = build_runtime(backend_root).check_plugin('sample')
assert payload['ok'] is True
+ assert isinstance(payload['checks'], list)
assert payload['checks'][0]['menuConflicts'] == []
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_upgrade_enable_purge.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_upgrade_enable_purge.py
index 248b7489c..96f559436 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_upgrade_enable_purge.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_upgrade_enable_purge.py
@@ -1,8 +1,12 @@
import asyncio
from pathlib import Path
-from types import SimpleNamespace
+from typing import Never
+from unittest.mock import patch
+from common.vo import CrudResponseModel
+from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.lifecycle.migration import PluginMigrationRunner
+from plugins.core.management.entity.vo.schemas import PluginMigrationModel, PluginModel
from plugins.core.runtime.service import PluginRuntimeService
from plugins.core.runtime.service.dependency_container import PluginRuntimeGatewayOverrides
from plugins.core.validation.dependencies import PluginDependencyChecker
@@ -30,7 +34,7 @@ class MigrationOnlyGateway:
def __init__(self) -> None:
"""初始化测试 migration 历史网关。"""
self.records = [
- SimpleNamespace(
+ PluginMigrationModel(
plugin_id='demo',
migration_path='migrations/001.sql',
migration_checksum='checksum-1',
@@ -44,7 +48,7 @@ def __init__(self) -> None:
create_time=None,
update_time=None,
),
- SimpleNamespace(
+ PluginMigrationModel(
plugin_id='demo',
migration_path='migrations/002.sql',
migration_checksum='checksum-2',
@@ -62,7 +66,7 @@ def __init__(self) -> None:
self.list_calls: list[tuple[str, str | None]] = []
self.mark_calls: list[tuple[str, str, str, str | None]] = []
- async def list_plugin_migrations(self, plugin_id: str, status: str | None = None) -> list[object]:
+ async def list_plugin_migrations(self, plugin_id: str, status: str | None = None) -> list[PluginMigrationModel]:
"""
查询测试 migration 历史。
@@ -77,7 +81,7 @@ async def list_plugin_migrations(self, plugin_id: str, status: str | None = None
if record.plugin_id == plugin_id and (status is None or record.status == status)
]
- async def get_plugin_migration(self, plugin_id: str, migration_path: str) -> object | None:
+ async def get_plugin_migration(self, plugin_id: str, migration_path: str) -> PluginMigrationModel | None:
"""
获取测试 migration 历史。
@@ -96,7 +100,7 @@ async def mark_plugin_migration_status(
migration_path: str,
status: str,
error_message: str | None = None,
- ) -> object | None:
+ ) -> PluginMigrationModel | None:
"""
标记测试 migration 历史状态。
@@ -113,7 +117,7 @@ async def mark_plugin_migration_status(
record.error_message = error_message
return record
- def get_plugin_service(self) -> object:
+ def get_plugin_service(self) -> Never:
"""
禁止 migration 链路回退到管理服务胖接口。
@@ -138,6 +142,7 @@ def test_plugin_runtime_lists_plugin_migration_history(tmp_path: Path) -> None:
assert result['pluginId'] == 'demo'
assert result['status'] == 'running'
assert result['count'] == 1
+ assert isinstance(result['migrations'], list)
assert result['migrations'][0]['migrationPath'] == 'migrations/002.sql'
@@ -162,6 +167,7 @@ def test_plugin_runtime_migration_uses_migration_history_port(tmp_path: Path) ->
assert list_result['ok'] is True
assert list_result['count'] == 1
+ assert isinstance(list_result['migrations'], list)
assert list_result['migrations'][0]['migrationPath'] == 'migrations/001.sql'
assert mark_result['ok'] is True
assert mark_result['operation'] == 'migration_mark_failed'
@@ -239,6 +245,7 @@ def test_plugin_runtime_rejects_invalid_plugin_migration_manual_transition(tmp_p
assert result['ok'] is False
assert result['operation'] == 'migration_mark_failed'
+ assert isinstance(result['message'], str)
assert '不能人工标记为失败' in result['message']
assert migration.status == 'success'
assert migration.error_message is None
@@ -271,6 +278,7 @@ def test_plugin_runtime_install_plugin_runs_install_hook(tmp_path: Path) -> None
result = asyncio.run(build_runtime_with_gateway(backend_root, gateway).install_plugin('demo'))
assert result['ok'] is True
+ assert isinstance(result['hooks'], list)
assert result['hooks'][0]['hook_name'] == 'on_install'
assert gateway.session_local.sessions[0].install_hook_ran == 'demo'
@@ -303,6 +311,7 @@ def test_plugin_runtime_install_plugin_reports_failed_lifecycle_step(tmp_path: P
assert result['ok'] is False
assert result['operation'] == 'install'
assert result['failedStep'] == 'run_install_hook'
+ assert isinstance(result['error'], str)
assert 'install hook failed' in result['error']
assert FakePluginService.marked_errors == [('demo', '插件安装失败:install hook failed')]
@@ -329,7 +338,7 @@ def test_plugin_runtime_upgrade_plugin_dry_run_reports_version_state(tmp_path: P
)
create_controller_dir(plugin_root)
gateway = FakePluginRuntimeGateway()
- FakePluginService.detail_plugin = SimpleNamespace(
+ FakePluginService.detail_plugin = PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -346,8 +355,10 @@ def test_plugin_runtime_upgrade_plugin_dry_run_reports_version_state(tmp_path: P
assert result['needsUpgrade'] is True
assert result['databaseAvailable'] is True
assert result['databaseError'] is None
+ assert isinstance(result['actions'], list)
assert result['actions'][0]['name'] == 'check_installed_version'
assert result['manifestOk'] is True
+ assert isinstance(result['manifestWarnings'], list)
assert result['manifestWarnings'][0]['level'] == 'warning'
assert result['manifestWarnings'][0]['kind'] == 'secret_config_default'
assert FakePluginService.upsert_called is False
@@ -376,7 +387,7 @@ def test_plugin_runtime_upgrade_dry_run_reports_changed_recorded_migration(tmp_p
old_checksum = PluginMigrationRunner._calculate_checksum(migration_file)
migration_file.write_text('select 2;\n', encoding='utf-8')
gateway = FakePluginRuntimeGateway()
- FakePluginService.detail_plugin = SimpleNamespace(
+ FakePluginService.detail_plugin = PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -389,6 +400,7 @@ def test_plugin_runtime_upgrade_dry_run_reports_changed_recorded_migration(tmp_p
assert result['ok'] is True
assert result['message'] == '插件升级演练完成,未执行实际写入'
assert result['manifestOk'] is False
+ assert isinstance(result['manifestIssues'], list)
assert result['manifestIssues'][0]['kind'] == 'migration_checksum_changed'
assert result['needsUpgrade'] is True
assert FakePluginService.upsert_called is False
@@ -412,7 +424,7 @@ def test_plugin_runtime_upgrade_plugin_rejects_manifest_errors(tmp_path: Path) -
)
create_controller_dir(plugin_root)
gateway = FakePluginRuntimeGateway()
- FakePluginService.detail_plugin = SimpleNamespace(
+ FakePluginService.detail_plugin = PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -426,6 +438,7 @@ def test_plugin_runtime_upgrade_plugin_rejects_manifest_errors(tmp_path: Path) -
assert result['installed'] is True
assert result['needsUpgrade'] is True
assert result['manifestOk'] is False
+ assert isinstance(result['manifestIssues'], list)
assert result['manifestIssues'][0]['kind'] == 'compatibility_unsatisfied'
assert FakePluginService.upsert_called is False
assert gateway.lifecycle_uows == []
@@ -473,7 +486,7 @@ def test_plugin_runtime_upgrade_plugin_skips_latest_version(tmp_path: Path) -> N
)
create_controller_dir(plugin_root)
gateway = FakePluginRuntimeGateway()
- FakePluginService.detail_plugin = SimpleNamespace(
+ FakePluginService.detail_plugin = PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -505,7 +518,7 @@ def test_plugin_runtime_upgrade_plugin_skips_older_source_version(tmp_path: Path
)
create_controller_dir(plugin_root)
gateway = FakePluginRuntimeGateway()
- FakePluginService.detail_plugin = SimpleNamespace(
+ FakePluginService.detail_plugin = PluginModel(
plugin_id='demo',
installed_version='1.10.0',
enabled='0',
@@ -558,7 +571,7 @@ def test_plugin_runtime_upgrade_plugin_persists_upgrade(tmp_path: Path) -> None:
encoding='utf-8',
)
gateway = FakePluginRuntimeGateway()
- FakePluginService.detail_plugin = SimpleNamespace(
+ FakePluginService.detail_plugin = PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -579,7 +592,9 @@ def test_plugin_runtime_upgrade_plugin_persists_upgrade(tmp_path: Path) -> None:
assert any(getattr(session, 'upgrade_seed_ran', False) is True for session in gateway.session_local.sessions)
assert any(getattr(session, 'upgrade_hook_ran', None) == 'demo' for session in gateway.session_local.sessions)
assert gateway.session_local.committed_session is not None
+ assert isinstance(result['migrations'], list)
assert result['migrations'][0]['migration_path'] == 'migrations/001_upgrade.py'
+ assert isinstance(result['hooks'], list)
assert result['hooks'][0]['hook_name'] == 'on_upgrade'
@@ -609,7 +624,7 @@ def test_plugin_runtime_upgrade_plugin_reports_failed_lifecycle_step(tmp_path: P
encoding='utf-8',
)
gateway = FakePluginRuntimeGateway()
- FakePluginService.detail_plugin = SimpleNamespace(
+ FakePluginService.detail_plugin = PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -622,6 +637,7 @@ def test_plugin_runtime_upgrade_plugin_reports_failed_lifecycle_step(tmp_path: P
assert result['pluginId'] == 'demo'
assert result['operation'] == 'upgrade'
assert result['failedStep'] == 'run_upgrade_hook'
+ assert isinstance(result['error'], str)
assert 'upgrade hook failed' in result['error']
assert FakePluginService.marked_errors == [('demo', '插件升级失败:upgrade hook failed')]
assert [record.status for record in FakePluginService.migration_records] == ['running', 'success']
@@ -652,7 +668,7 @@ def test_plugin_runtime_upgrade_plugin_uses_injected_dependencies(tmp_path: Path
(plugin_root / 'migrations').mkdir()
(plugin_root / 'migrations' / '001_upgrade.sql').write_text('select 3;\n', encoding='utf-8')
gateway = FakePluginRuntimeGateway()
- FakePluginService.detail_plugin = SimpleNamespace(
+ FakePluginService.detail_plugin = PluginModel(
plugin_id='demo',
installed_version='1.0.0',
enabled='0',
@@ -701,12 +717,14 @@ def test_plugin_runtime_set_plugin_enabled_dry_run_returns_actions(tmp_path: Pat
assert result['ok'] is True
assert result['dryRun'] is True
assert result['operation'] == 'enable'
+ assert isinstance(result['actions'], list)
assert [action['name'] for action in result['actions']] == [
'check_plugin_dependencies',
'update_plugin_enabled',
'update_plugin_menu_status',
]
assert result['manifestOk'] is True
+ assert isinstance(result['precheck'], dict)
assert result['precheck']['structureErrors'] == []
@@ -738,6 +756,7 @@ def test_plugin_runtime_set_plugin_enabled_persists_state(tmp_path: Path) -> Non
assert FakePluginService.install_plugin_menu_called_with == ('demo', True)
assert FakePluginService.update_enabled_called_with is not None
assert FakePluginService.update_enabled_called_with[:2] == ('demo', True)
+ assert FakePluginService.update_enabled_called_with[2] is not None
assert FakePluginService.update_enabled_called_with[2].manifest.id == 'demo'
assert gateway.session_local.sessions[0].committed is True
assert len(FakePluginService.operation_logs) == 1
@@ -777,9 +796,9 @@ class NoFatLifecycleStateGateway(FakePluginRuntimeGateway):
def __init__(self) -> None:
"""初始化测试生命周期状态网关。"""
super().__init__()
- self.enabled_state_calls: list[tuple[str, bool, object | None]] = []
+ self.enabled_state_calls: list[tuple[str, bool, DiscoveredPlugin | None]] = []
- def get_async_session_local(self) -> object:
+ def get_async_session_local(self) -> Never:
"""
禁止通过 state gateway 打开数据库会话。
@@ -787,7 +806,7 @@ def get_async_session_local(self) -> object:
"""
raise AssertionError('启用流程不应通过 state gateway 打开数据库会话')
- def get_plugin_service(self) -> object:
+ def get_plugin_service(self) -> Never:
"""
禁止通过 state gateway 获取管理服务。
@@ -799,8 +818,8 @@ async def set_plugin_enabled_state(
self,
plugin_id: str,
enabled: bool,
- discovered_plugin: object | None = None,
- ) -> object:
+ discovered_plugin: DiscoveredPlugin | None = None,
+ ) -> CrudResponseModel:
"""
通过窄端口更新插件启停状态。
@@ -828,6 +847,7 @@ async def set_plugin_enabled_state(
assert result['ok'] is True
assert gateway.enabled_state_calls[0][0:2] == ('demo', True)
+ assert gateway.enabled_state_calls[0][2] is not None
assert gateway.enabled_state_calls[0][2].manifest.id == 'demo'
assert FakePluginService.install_plugin_menu_called_with == ('demo', True)
assert gateway.session_local.sessions[0].committed is True
@@ -850,35 +870,16 @@ def test_plugin_runtime_set_plugin_enabled_reports_failed_lifecycle_step(tmp_pat
create_controller_dir(plugin_root)
gateway = FakePluginRuntimeGateway()
- async def raise_enable_failure(
- query_db: object,
- plugin_id: str,
- enabled: bool,
- discovered_plugin: object | None = None,
- ) -> object:
- """
- 模拟启用插件失败。
-
- :param query_db: 当前操作使用的异步数据库会话
- :param plugin_id: 插件清单中的唯一标识
- :param enabled: 是否启用该项功能
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :raises RuntimeError: 模拟写入启用状态失败
- """
- raise RuntimeError('enable update failed')
-
- original_update_enabled = FakePluginService.update_plugin_enabled_services
- FakePluginService.update_plugin_enabled_services = raise_enable_failure
-
- try:
+ with patch.object(
+ FakePluginService, 'update_plugin_enabled_services', side_effect=RuntimeError('enable update failed')
+ ):
result = asyncio.run(build_runtime_with_gateway(backend_root, gateway).set_plugin_enabled('demo', enabled=True))
- finally:
- FakePluginService.update_plugin_enabled_services = original_update_enabled
assert result['ok'] is False
assert result['pluginId'] == 'demo'
assert result['operation'] == 'enable'
assert result['failedStep'] == 'update_enabled_state'
+ assert isinstance(result['error'], str)
assert 'enable update failed' in result['error']
assert FakePluginService.marked_errors == [('demo', '更新插件启停状态失败:enable update failed')]
@@ -924,8 +925,8 @@ def test_plugin_runtime_disable_blocks_enabled_dependents(tmp_path: Path) -> Non
create_controller_dir(app_root)
gateway = FakePluginRuntimeGateway()
FakePluginService.plugin_list = [
- SimpleNamespace(plugin_id='base', installed_version='1.0.0', enabled='0', status='installed'),
- SimpleNamespace(plugin_id='app', installed_version='1.0.0', enabled='0', status='installed'),
+ PluginModel(plugin_id='base', installed_version='1.0.0', enabled='0', status='installed'),
+ PluginModel(plugin_id='app', installed_version='1.0.0', enabled='0', status='installed'),
]
result = asyncio.run(build_runtime_with_gateway(backend_root, gateway).set_plugin_enabled('base', enabled=False))
@@ -933,6 +934,7 @@ def test_plugin_runtime_disable_blocks_enabled_dependents(tmp_path: Path) -> Non
assert result['ok'] is False
assert result['message'] == '插件仍被已启用插件依赖,操作已中止'
assert result['operation'] == 'disable'
+ assert isinstance(result['pluginDependencyErrors'], list)
assert result['pluginDependencyErrors'][0]['status'] == 'dependent'
assert result['pluginDependencyErrors'][0]['pluginId'] == 'app'
assert FakePluginService.update_enabled_called_with is None
@@ -979,8 +981,8 @@ def test_plugin_runtime_disable_dry_run_reports_enabled_dependents(tmp_path: Pat
create_controller_dir(app_root)
gateway = FakePluginRuntimeGateway()
FakePluginService.plugin_list = [
- SimpleNamespace(plugin_id='base', installed_version='1.0.0', enabled='0', status='installed'),
- SimpleNamespace(plugin_id='app', installed_version='1.0.0', enabled='0', status='installed'),
+ PluginModel(plugin_id='base', installed_version='1.0.0', enabled='0', status='installed'),
+ PluginModel(plugin_id='app', installed_version='1.0.0', enabled='0', status='installed'),
]
result = asyncio.run(
@@ -990,6 +992,7 @@ def test_plugin_runtime_disable_dry_run_reports_enabled_dependents(tmp_path: Pat
assert result['ok'] is True
assert result['dryRun'] is True
assert result['pluginDependencyOk'] is False
+ assert isinstance(result['actions'], list)
assert result['actions'][0]['name'] == 'check_plugin_dependents'
assert FakePluginService.update_enabled_called_with is None
@@ -1023,6 +1026,7 @@ def test_plugin_runtime_set_plugin_enabled_uses_injected_dependencies(tmp_path:
assert FakePluginService.install_plugin_menu_called_with == ('demo', True)
assert FakePluginService.update_enabled_called_with is not None
assert FakePluginService.update_enabled_called_with[:2] == ('demo', True)
+ assert FakePluginService.update_enabled_called_with[2] is not None
assert FakePluginService.update_enabled_called_with[2].manifest.id == 'demo'
assert gateway.session_local.sessions[0].committed is True
@@ -1053,6 +1057,7 @@ def test_plugin_runtime_check_reports_plugin_dependency_errors(tmp_path: Path) -
payload = build_runtime(backend_root).check_plugin('demo')
assert payload['ok'] is False
+ assert isinstance(payload['checks'], list)
assert payload['checks'][0]['pluginDependencyErrors'][0]['status'] == 'missing'
assert payload['checks'][0]['pluginDependencyErrors'][0]['level'] == 'error'
@@ -1085,6 +1090,7 @@ def test_plugin_runtime_install_blocks_unsatisfied_plugin_dependency(tmp_path: P
assert result['ok'] is False
assert result['message'] == '插件间依赖检查失败,安装已中止'
+ assert isinstance(result['pluginDependencyErrors'], list)
assert result['pluginDependencyErrors'][0]['status'] == 'missing'
assert FakePluginService.upsert_called is False
assert FakePluginService.marked_errors == [('demo', '插件间依赖检查失败,安装已中止')]
@@ -1118,6 +1124,7 @@ def test_plugin_runtime_enable_blocks_unsatisfied_plugin_dependency(tmp_path: Pa
assert result['ok'] is False
assert result['message'] == '插件间依赖检查失败,启用已中止'
+ assert isinstance(result['pluginDependencyErrors'], list)
assert result['pluginDependencyErrors'][0]['status'] == 'missing'
assert FakePluginService.update_enabled_called_with is None
assert FakePluginService.marked_errors == [('demo', '插件间依赖检查失败,启用已中止')]
@@ -1140,37 +1147,18 @@ def test_plugin_runtime_disable_reports_failed_lifecycle_step(tmp_path: Path) ->
create_controller_dir(plugin_root)
gateway = FakePluginRuntimeGateway()
- async def raise_disable_failure(
- query_db: object,
- plugin_id: str,
- enabled: bool,
- discovered_plugin: object | None = None,
- ) -> object:
- """
- 模拟禁用插件失败。
-
- :param query_db: 当前操作使用的异步数据库会话
- :param plugin_id: 插件清单中的唯一标识
- :param enabled: 是否启用该项功能
- :param discovered_plugin: 扫描插件目录后得到的插件描述
- :raises RuntimeError: 模拟写入停用状态失败
- """
- raise RuntimeError('disable update failed')
-
- original_update_enabled = FakePluginService.update_plugin_enabled_services
- FakePluginService.update_plugin_enabled_services = raise_disable_failure
-
- try:
+ with patch.object(
+ FakePluginService, 'update_plugin_enabled_services', side_effect=RuntimeError('disable update failed')
+ ):
result = asyncio.run(
build_runtime_with_gateway(backend_root, gateway).set_plugin_enabled('demo', enabled=False)
)
- finally:
- FakePluginService.update_plugin_enabled_services = original_update_enabled
assert result['ok'] is False
assert result['pluginId'] == 'demo'
assert result['operation'] == 'disable'
assert result['failedStep'] == 'update_enabled_state'
+ assert isinstance(result['error'], str)
assert 'disable update failed' in result['error']
@@ -1215,6 +1203,7 @@ def test_plugin_runtime_uninstall_plugin_dry_run_includes_precheck_when_source_e
assert result['ok'] is True
assert result['operation'] == 'uninstall'
assert result['manifestOk'] is True
+ assert isinstance(result['precheck'], dict)
assert result['precheck']['structureErrors'] == []
assert result['safeMode'] is True
@@ -1260,8 +1249,8 @@ def test_plugin_runtime_uninstall_plugin_blocks_enabled_dependents(tmp_path: Pat
create_controller_dir(app_root)
gateway = FakePluginRuntimeGateway()
FakePluginService.plugin_list = [
- SimpleNamespace(plugin_id='base', installed_version='1.0.0', enabled='0', status='installed'),
- SimpleNamespace(plugin_id='app', installed_version='1.0.0', enabled='0', status='installed'),
+ PluginModel(plugin_id='base', installed_version='1.0.0', enabled='0', status='installed'),
+ PluginModel(plugin_id='app', installed_version='1.0.0', enabled='0', status='installed'),
]
result = asyncio.run(build_runtime_with_gateway(backend_root, gateway).uninstall_plugin('base'))
@@ -1269,6 +1258,7 @@ def test_plugin_runtime_uninstall_plugin_blocks_enabled_dependents(tmp_path: Pat
assert result['ok'] is False
assert result['operation'] == 'uninstall'
assert result['safeMode'] is True
+ assert isinstance(result['pluginDependencyErrors'], list)
assert result['pluginDependencyErrors'][0]['status'] == 'dependent'
assert result['pluginDependencyErrors'][0]['pluginId'] == 'app'
assert FakePluginService.mark_uninstalled_called_with is None
@@ -1297,28 +1287,16 @@ def test_plugin_runtime_uninstall_plugin_reports_failed_lifecycle_step(tmp_path:
backend_root.mkdir()
gateway = FakePluginRuntimeGateway()
- async def raise_uninstall_failure(query_db: object, plugin_id: str) -> object:
- """
- 模拟卸载插件失败。
-
- :param query_db: 当前操作使用的异步数据库会话
- :param plugin_id: 插件清单中的唯一标识
- :raises RuntimeError: 模拟写入卸载状态失败
- """
- raise RuntimeError('uninstall update failed')
-
- original_mark_uninstalled = FakePluginService.mark_plugin_uninstalled_services
- FakePluginService.mark_plugin_uninstalled_services = raise_uninstall_failure
-
- try:
+ with patch.object(
+ FakePluginService, 'mark_plugin_uninstalled_services', side_effect=RuntimeError('uninstall update failed')
+ ):
result = asyncio.run(build_runtime_with_gateway(backend_root, gateway).uninstall_plugin('demo'))
- finally:
- FakePluginService.mark_plugin_uninstalled_services = original_mark_uninstalled
assert result['ok'] is False
assert result['pluginId'] == 'demo'
assert result['operation'] == 'uninstall'
assert result['failedStep'] == 'mark_uninstalled'
+ assert isinstance(result['error'], str)
assert 'uninstall update failed' in result['error']
@@ -1353,6 +1331,7 @@ def test_plugin_runtime_purge_plugin_dry_run_returns_plan(tmp_path: Path) -> Non
assert 'precheck' in result
assert result['safeMode'] is False
assert result['removesSource'] is False
+ assert isinstance(result['plan'], dict)
assert result['plan']['destructiveCount'] == EXPECTED_PURGE_DESTRUCTIVE_COUNT
resource_items = [item for item in result['plan']['items'] if item['name'].startswith('resource_')]
assert resource_items == [
@@ -1417,8 +1396,8 @@ def test_plugin_runtime_purge_plugin_blocks_enabled_dependents(tmp_path: Path) -
create_controller_dir(app_root)
gateway = FakePluginRuntimeGateway()
FakePluginService.plugin_list = [
- SimpleNamespace(plugin_id='base', installed_version='1.0.0', enabled='0', status='installed'),
- SimpleNamespace(plugin_id='app', installed_version='1.0.0', enabled='0', status='installed'),
+ PluginModel(plugin_id='base', installed_version='1.0.0', enabled='0', status='installed'),
+ PluginModel(plugin_id='app', installed_version='1.0.0', enabled='0', status='installed'),
]
result = asyncio.run(build_runtime_with_gateway(backend_root, gateway).purge_plugin('base'))
@@ -1426,6 +1405,7 @@ def test_plugin_runtime_purge_plugin_blocks_enabled_dependents(tmp_path: Path) -
assert result['ok'] is False
assert result['operation'] == 'purge'
assert result['message'] == '插件仍被已启用插件依赖,物理清理已中止'
+ assert isinstance(result['pluginDependencyErrors'], list)
assert result['pluginDependencyErrors'][0]['status'] == 'dependent'
assert result['pluginDependencyErrors'][0]['pluginId'] == 'app'
assert FakePluginService.purge_called is False
@@ -1463,8 +1443,8 @@ def test_plugin_runtime_purge_dry_run_reports_enabled_dependents(tmp_path: Path)
create_controller_dir(app_root)
gateway = FakePluginRuntimeGateway()
FakePluginService.plugin_list = [
- SimpleNamespace(plugin_id='base', installed_version='1.0.0', enabled='0', status='installed'),
- SimpleNamespace(plugin_id='app', installed_version='1.0.0', enabled='0', status='installed'),
+ PluginModel(plugin_id='base', installed_version='1.0.0', enabled='0', status='installed'),
+ PluginModel(plugin_id='app', installed_version='1.0.0', enabled='0', status='installed'),
]
result = asyncio.run(build_runtime_with_gateway(backend_root, gateway).purge_plugin('base', dry_run=True))
@@ -1473,7 +1453,9 @@ def test_plugin_runtime_purge_dry_run_reports_enabled_dependents(tmp_path: Path)
assert result['dryRun'] is True
assert result['operation'] == 'purge'
assert result['pluginDependencyOk'] is False
+ assert isinstance(result['pluginDependencyErrors'], list)
assert result['pluginDependencyErrors'][0]['pluginId'] == 'app'
+ assert isinstance(result['plan'], dict)
assert result['plan']['destructiveCount'] == EXPECTED_PURGE_DESTRUCTIVE_COUNT
assert FakePluginService.purge_called is False
@@ -1504,6 +1486,7 @@ def test_plugin_runtime_purge_plugin_runs_hook_and_cleans_metadata(tmp_path: Pat
assert result['ok'] is True
assert result['operation'] == 'purge'
+ assert isinstance(result['hooks'], list)
assert result['hooks'][0]['hook_name'] == 'on_purge'
assert FakePluginService.purge_called is True
assert gateway.session_local.sessions[0].purge_hook_ran == 'demo'
@@ -1524,6 +1507,7 @@ def test_plugin_runtime_purge_orphan_metadata_without_source(tmp_path: Path) ->
assert result['ok'] is True
assert result['metadataOnly'] is True
assert result['hooks'] == []
+ assert isinstance(result['warnings'], list)
assert '已跳过 onPurge' in result['warnings'][0]
assert FakePluginService.purge_by_id_called_with == 'orphan'
assert FakePluginService.purge_called is False
@@ -1546,6 +1530,7 @@ def test_plugin_runtime_purge_orphan_metadata_dry_run(tmp_path: Path) -> None:
assert result['ok'] is True
assert result['dryRun'] is True
assert result['metadataOnly'] is True
+ assert isinstance(result['plan'], dict)
assert result['plan']['requiresHook'] is False
assert FakePluginService.purge_by_id_called_with is None
assert gateway.session_local.sessions[0].committed is False
@@ -1570,7 +1555,7 @@ def test_plugin_runtime_purge_orphan_metadata_blocks_enabled_dependents(tmp_path
)
create_controller_dir(app_root)
FakePluginService.plugin_list = [
- SimpleNamespace(plugin_id='app', installed_version='1.0.0', enabled='0', status='installed')
+ PluginModel(plugin_id='app', installed_version='1.0.0', enabled='0', status='installed')
]
gateway = FakePluginRuntimeGateway()
@@ -1579,6 +1564,7 @@ def test_plugin_runtime_purge_orphan_metadata_blocks_enabled_dependents(tmp_path
)
assert result['ok'] is False
+ assert isinstance(result['pluginDependencyErrors'], list)
assert result['pluginDependencyErrors'][0]['pluginId'] == 'app'
assert FakePluginService.purge_by_id_called_with is None
assert gateway.session_local.sessions[0].committed is False
@@ -1608,7 +1594,7 @@ def test_plugin_runtime_purge_plugin_uses_lifecycle_uow_without_fat_service(tmp_
class NoFatPurgeGateway(FakePluginRuntimeGateway):
"""禁止物理清理流程读取 fat state gateway 的测试适配器。"""
- def get_async_session_local(self) -> object:
+ def get_async_session_local(self) -> Never:
"""
禁止通过 state gateway 打开数据库会话。
@@ -1616,7 +1602,7 @@ def get_async_session_local(self) -> object:
"""
raise AssertionError('物理清理流程不应通过 state gateway 打开数据库会话')
- def get_plugin_service(self) -> object:
+ def get_plugin_service(self) -> Never:
"""
禁止通过 state gateway 获取管理服务。
@@ -1665,6 +1651,7 @@ def test_plugin_runtime_purge_plugin_reports_failed_lifecycle_step(tmp_path: Pat
assert result['pluginId'] == 'demo'
assert result['operation'] == 'purge'
assert result['failedStep'] == 'run_purge_hook'
+ assert isinstance(result['error'], str)
assert 'purge hook failed' in result['error']
assert FakePluginService.purge_called is False
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/support/test_dependency_payloads.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/support/test_dependency_payloads.py
index c6c386711..5d083c5c5 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/support/test_dependency_payloads.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/support/test_dependency_payloads.py
@@ -1,6 +1,7 @@
import json
from dataclasses import replace
from pathlib import Path
+from typing import Literal
from plugins.core.runtime.support import PluginBatchReportBuilder, PluginNpmPackageJsonSynchronizer
from plugins.core.validation.dependencies import DependencyInstallPlanItem
@@ -9,7 +10,7 @@
def build_npm_plan_item(
workdir: Path,
*,
- kind: str,
+ kind: Literal['npm', 'npmDev'],
requirement: str,
name: str,
) -> DependencyInstallPlanItem:
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_asgi.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_asgi.py
index 2f27bfafa..025beccee 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_asgi.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_asgi.py
@@ -2,6 +2,7 @@
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager, suppress
from pathlib import Path
+from unittest.mock import AsyncMock
import httpx
import pytest
@@ -105,7 +106,7 @@ async def send(message: Message) -> None:
"""
messages.append(message)
- await gateway({'type': 'websocket', 'path': '/ws'}, None, send)
+ await gateway({'type': 'websocket', 'path': '/ws'}, AsyncMock(), send)
assert messages[0]['type'] == 'websocket.close'
assert not reached
@@ -219,6 +220,7 @@ async def child(scope: Scope, receive: Receive, send: Send) -> None:
with pytest.raises(RuntimeError, match='尚未退出'):
await manager.startup()
release.set()
+ assert manager._task is not None
await asyncio.wait({manager._task}, timeout=1)
await manager.startup()
assert manager.ready and manager.state == {'attempt': 2}
@@ -327,9 +329,9 @@ async def child(scope: Scope, receive: Receive, send: Send) -> None:
def test_lifespan_rejects_invalid_time_limits(timeout: float) -> None:
"""生命周期拒绝无效的时间限制。"""
with pytest.raises(ValueError, match='大于零'):
- PluginLifespanManager(None, timeout=timeout)
+ PluginLifespanManager(AsyncMock(), timeout=timeout)
with pytest.raises(ValueError, match='大于零'):
- PluginLifespanManager(None, cancel_timeout=timeout)
+ PluginLifespanManager(AsyncMock(), cancel_timeout=timeout)
@pytest.mark.asyncio
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_browser_session.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_browser_session.py
index 06f175693..1e9ba8e83 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_browser_session.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_browser_session.py
@@ -7,13 +7,14 @@
from pathlib import Path
from types import SimpleNamespace
from typing import Annotated
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
import httpx
import pytest
import pytest_asyncio
import yaml
from fastapi import Depends, FastAPI, HTTPException, Request
+from sqlalchemy.ext.asyncio import AsyncSession
from starlette import status
from common.aspect.db_session import get_db_session_provider
@@ -31,6 +32,7 @@
from plugins.core.discovery.scanner import DiscoveredPlugin, PluginScanner
from plugins.core.runtime.browser_session import COOKIE_NAME_PREFIX, SESSION_KEY_PREFIX
from plugins.core.runtime.explicit import ExplicitPluginRuntime
+from plugins.core.runtime.route_guard import PluginRouteStateGateway
from utils.jwt_util import JwtUtil
@@ -149,7 +151,9 @@ async def browser(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncItera
plugin = _write_browser_plugin(tmp_path)
app = FastAPI()
app.state.redis = redis = MemoryRedis()
- runtime = ExplicitPluginRuntime(SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True)))
+ runtime = ExplicitPluginRuntime(
+ Mock(spec_set=PluginRouteStateGateway, is_plugin_enabled=AsyncMock(return_value=True))
+ )
app.state.plugin_explicit_runtime = runtime
user = SimpleNamespace(user=SimpleNamespace(user_id=7), permissions=['browser_test:view'])
token = JwtUtil.encode({'user_id': '7', 'session_id': 'test-session', 'exp': int(time.time()) + 1800})
@@ -233,7 +237,8 @@ async def issue(browser: SimpleNamespace) -> httpx.Response:
:param browser: 执行页面操作的浏览器实例
:return: 插件浏览器会话的签发响应
"""
- return await browser.client.post(
+ client: httpx.AsyncClient = browser.client
+ return await client.post(
'/plugin/runtime/browser_test/session',
headers={
'Authorization': f'Bearer {browser.token}',
@@ -417,7 +422,8 @@ async def test_renewal_retries_if_record_expires_and_another_tab_replaces_it(
key = next(key for key in browser.redis.values if key.startswith(SESSION_KEY_PREFIX))
replacement = json.loads(browser.redis.values[key])
replacement.update(nonce='n' * 43, csrf='c' * 43)
- expire = browser.redis.expire
+ redis: MemoryRedis = browser.redis
+ expire = redis.expire
replaced = False
async def replace_before_expire(record_key: str, seconds: int) -> bool:
@@ -442,6 +448,7 @@ async def replace_before_expire(record_key: str, seconds: int) -> bool:
assert renewed.json()['data']['csrfToken'] == replacement['csrf']
assert renewed.json()['data']['csrfToken'] != first.json()['data']['csrfToken']
cookie = renewed.cookies.get(f'{COOKIE_NAME_PREFIX}browser_test')
+ assert cookie is not None
assert cookie.endswith('.' + replacement['nonce'])
assert (await browser.client.get('/apps/browser_test/api/info')).status_code == status.HTTP_200_OK
@@ -499,10 +506,10 @@ async def get_with_concurrent_logout(record_key: str) -> str | None:
# 不替换 _resolve_current_user,验证真实 JWT、用户模型和权限构造路径。
if logout_after_read:
with pytest.raises(AuthException):
- await LoginService.get_current_user_for_plugin_session(request, token, object())
+ await LoginService.get_current_user_for_plugin_session(request, token, AsyncSession())
assert key not in redis.values
else:
- user = await LoginService.get_current_user_for_plugin_session(request, token, object())
+ user = await LoginService.get_current_user_for_plugin_session(request, token, AsyncSession())
assert user.user.user_id == user_id
assert user.permissions == ['demo:view']
assert redis.values[key] == token
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle.py
index cc80365f2..22613ddd7 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle.py
@@ -1,6 +1,7 @@
import json
import re
from pathlib import Path
+from unittest.mock import AsyncMock
from urllib.parse import urljoin
import httpx
@@ -58,7 +59,7 @@ async def ping() -> dict[str, str]:
parent = FastAPI()
parent.mount(
'/apps/demo',
- PluginBundleASGI(child, 'demo', plugin_root, FrontendBundleManifest(spaFallback=spa_fallback)),
+ PluginBundleASGI(child, 'demo', plugin_root, FrontendBundleManifest(spa_fallback=spa_fallback)),
)
return parent
@@ -209,7 +210,7 @@ async def child(scope: Scope, receive: Receive, send: Send) -> None:
bundle = PluginBundleASGI(child, 'demo', bundle_root.parents[1], FrontendBundleManifest())
for scope in ({'type': 'lifespan'}, {'type': 'websocket', 'path': '/ui/events'}):
- await bundle(scope, None, None)
+ await bundle(scope, AsyncMock(), AsyncMock())
assert reached[-1] is scope
@@ -293,7 +294,7 @@ async def send(message: Message) -> None:
'headers': [(b'accept', b'text/html'), (b'cookie', b'secret-session=top-secret')],
'query_string': b'token=must-not-be-injected',
}
- await bundle(scope, None, send)
+ await bundle(scope, AsyncMock(), send)
body = b''.join(message.get('body', b'') for message in messages).decode()
match = _CONFIG_SCRIPT.search(body)
assert match is not None
@@ -320,7 +321,9 @@ async def test_runtime_base_is_first_and_preserves_doctype(bundle_root: Path, ht
response = await client.get('/apps/demo/ui/deep/link', headers=_HTML_HEADERS)
assert response.status_code == status.HTTP_200_OK
assert response.text.startswith('')
- assert re.search(r' ', response.text).group(1) == '/apps/demo/ui/'
+ match = re.search(r' ', response.text)
+ assert match is not None
+ assert match[1] == '/apps/demo/ui/'
def test_missing_bundle_or_entry_is_rejected_before_activation(tmp_path: Path) -> None:
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_configuration.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_configuration.py
index 976be294e..90f9c35c0 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_configuration.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_configuration.py
@@ -1,10 +1,10 @@
import asyncio
import json
-from collections.abc import AsyncIterator
+from collections.abc import AsyncGenerator, AsyncIterator
from contextlib import asynccontextmanager
from pathlib import Path
-from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from types import MappingProxyType
+from unittest.mock import AsyncMock, Mock
import pytest
import pytest_asyncio
@@ -25,6 +25,7 @@
from plugins.core.runtime.explicit import ExplicitPluginRuntime
from plugins.core.runtime.metrics import PluginRuntimeMetrics
from plugins.core.runtime.metrics_store import PluginMetricsReporter
+from plugins.core.runtime.route_guard import PluginRouteStateGateway
from plugins.core.runtime.startup import PluginRuntimeStartupManager
from plugins.core.sdk import PluginConfigSnapshot, PluginHostContext
from tests.plugins.core.runtime.test_explicit import clear_modules, write_plugin # noqa: F401
@@ -41,7 +42,7 @@ async def config_sessions(tmp_path: Path) -> AsyncIterator[async_sessionmaker[As
"""
engine = create_async_engine(f'sqlite+aiosqlite:///{tmp_path / "config.sqlite"}')
async with engine.begin() as db:
- await db.run_sync(SysPluginConfig.__table__.create)
+ await db.run_sync(SysPluginConfig.get_table().create)
try:
yield async_sessionmaker(engine, expire_on_commit=False)
finally:
@@ -64,8 +65,7 @@ def test_snapshot_is_independent_and_hides_values_in_repr() -> None:
snapshot = PluginConfigSnapshot(values, 'a' * 64)
values['private']['list'].append('later')
assert snapshot.values['private']['list'] == ['secret-value']
- with pytest.raises(TypeError):
- snapshot.values['private'] = None
+ assert isinstance(snapshot.values, MappingProxyType)
assert 'secret-value' not in repr(snapshot)
@@ -89,7 +89,9 @@ async def test_database_changes_dynamic_reads_and_restart_snapshots_remain_disti
]
monkeypatch.setattr('plugins.core.runtime.startup.DataSourceRegistry.session', config_sessions)
app = FastAPI()
- runtime = ExplicitPluginRuntime(SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True)))
+ runtime = ExplicitPluginRuntime(
+ Mock(spec_set=PluginRouteStateGateway, is_plugin_enabled=AsyncMock(return_value=True))
+ )
initial = await PluginRuntimeStartupManager.load_explicit_plugin_config(plugin)
runtime.prepare(plugin, app, startup_write_enabled=False, config_values=initial)
await runtime.activate(plugin.plugin_id, app)
@@ -123,7 +125,9 @@ async def test_database_changes_dynamic_reads_and_restart_snapshots_remain_disti
finally:
await runtime.shutdown()
assert runtime.metrics.configurations[plugin.plugin_id].active is False
- restarted = ExplicitPluginRuntime(SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True)))
+ restarted = ExplicitPluginRuntime(
+ Mock(spec_set=PluginRouteStateGateway, is_plugin_enabled=AsyncMock(return_value=True))
+ )
restarted_app = FastAPI()
restarted.prepare(
plugin,
@@ -190,7 +194,7 @@ async def test_failed_or_cancelled_read_keeps_previous_observation(
closed = []
@asynccontextmanager
- async def session() -> AsyncIterator[object]:
+ async def session() -> AsyncGenerator[object, None]:
"""
为当前测试操作提供数据库会话。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py
index e5c7dfaac..6cffe590c 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py
@@ -1,5 +1,5 @@
import asyncio
-from collections.abc import AsyncIterator
+from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -224,7 +224,7 @@ async def test_recheck_uses_fresh_closed_db_sessions_and_does_not_refresh_bearer
checked = asyncio.Event()
@asynccontextmanager
- async def session() -> AsyncIterator[object]:
+ async def session() -> AsyncGenerator[object, None]:
"""
统计独立数据库会话在复核之间全部关闭。
@@ -259,6 +259,6 @@ async def read_user(**kwargs: object) -> object:
assert sessions.active == 0 and sessions.opened > 1
initial.assert_awaited_once()
assert readonly.await_count > 0
- assert readonly.await_args.kwargs['token'] == browser.token
+ assert readonly.await_args_list[-1].kwargs['token'] == browser.token
finally:
await finish_stream(stream)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connections.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connections.py
index 5e4b236bc..5643783c5 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connections.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connections.py
@@ -2,6 +2,7 @@
import json
from pathlib import Path
from types import SimpleNamespace
+from unittest.mock import AsyncMock
import httpx
import pytest
@@ -343,18 +344,22 @@ async def authorize(scope: Scope) -> PluginRequestContext:
"""
return PluginRequestContext(PluginHostContext('demo', tmp_path), None)
- async def send(message: Message) -> None:
+ def send(message: Message) -> asyncio.Future[None]:
"""
- 收集应用发送的 ASGI 消息。
+ 记录网关输出,以 Future 模拟直接返回可等待对象的 ASGI 发送器。
- :param message: 与当前结果一起返回的说明
+ :param message: 网关发给客户端的协议消息
+ :return: 表示消息已发送的 Future
"""
messages.append(message)
+ sent: asyncio.Future[None] = asyncio.get_running_loop().create_future()
+ sent.set_result(None)
+ return sent
manager = PluginLifespanManager(child, managed=False)
await manager.startup()
gateway = PluginGatewayASGI(child, manager, authorize, cancel_timeout=0.01)
- task = asyncio.create_task(gateway({'type': 'http', 'headers': []}, None, send))
+ task = asyncio.create_task(gateway({'type': 'http', 'headers': []}, AsyncMock(), send))
try:
await asyncio.wait_for(opened.wait(), timeout=1)
await _cancel_or_drain_request(task, gateway, external_cancel)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py
index d03a2b769..3f50ec4d6 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py
@@ -9,6 +9,7 @@
import pytest
from fastapi import FastAPI
from pydantic import ValidationError
+from starlette.types import Message, Receive, Scope, Send
from plugins.core.discovery.registry import RegisteredPlugin
from plugins.core.discovery.scanner import DiscoveredPlugin
@@ -18,6 +19,7 @@
from plugins.core.runtime.diagnostics import PluginRuntimeDiagnostic, PluginRuntimeDiagnosticSnapshot
from plugins.core.runtime.explicit import ExplicitPluginRuntime, LoadedExplicitPlugin
from plugins.core.runtime.health import PluginHealthChecker, PluginHealthResult
+from plugins.core.runtime.route_guard import UnavailablePluginRouteStateGateway
from plugins.core.runtime.task_cleanup import cancel_plugin_tasks, pending_plugin_tasks
from plugins.core.sdk import PluginDefinition, PluginHostContext, PluginRequestContext
@@ -47,7 +49,7 @@ def diagnostic_runtime(tmp_path: Path, plugin_id: str = 'diagnostic_demo') -> Ex
config_revision='c' * 64,
config_reader=AsyncMock(side_effect=AssertionError('sampling must not read configuration')),
)
- runtime = ExplicitPluginRuntime(SimpleNamespace())
+ runtime = ExplicitPluginRuntime(UnavailablePluginRouteStateGateway())
runtime.loaded[plugin_id] = LoadedExplicitPlugin(
RegisteredPlugin(discovered, None, True, 'installed'), host, PluginDefinition()
)
@@ -72,9 +74,11 @@ def test_snapshot_copies_actual_identity_config_and_most_recent_error(tmp_path:
runtime.metrics.identities['diagnostic_demo']['digest'] = 'e' * 64
runtime.metrics.identities['diagnostic_demo']['generation'] = 'f' * 32
first = runtime.metrics.begin('diagnostic_demo', 'http', 'old-request')
+ assert first is not None
first.finish('failed', error_type='OldError')
first.series.last_error_at = 124.0
second = runtime.metrics.begin('diagnostic_demo', 'job:refresh', 'latest-request')
+ assert second is not None
second.finish('failed', error_type='NewError')
second.series.last_error_at = 125.0
snapshot = runtime.diagnostic_snapshot()
@@ -85,6 +89,7 @@ def test_snapshot_copies_actual_identity_config_and_most_recent_error(tmp_path:
assert plugin.lifespan is None
assert plugin.activation_health.status == 'unknown'
assert plugin.activation_health.checked_at is None
+ assert plugin.last_error is not None
assert plugin.last_error.model_dump(by_alias=True) == {
'errorType': 'NewError',
'requestId': 'latest-request',
@@ -93,6 +98,7 @@ def test_snapshot_copies_actual_identity_config_and_most_recent_error(tmp_path:
assert plugin.config.startup_revision == 'c' * 64
assert plugin.config.last_read_revision == 'd' * 64
assert 'private-config-value' not in snapshot.model_dump_json()
+ assert isinstance(loaded.host.config_reader, AsyncMock)
loaded.host.config_reader.assert_not_called()
runtime.metrics.configurations['diagnostic_demo'].last_read_revision = 'e' * 64
runtime.loaded['diagnostic_demo'].activation_health.status = 'unhealthy'
@@ -157,7 +163,7 @@ async def test_real_lifespan_exit_changes_readiness_without_marking_pending_canc
loaded = runtime.loaded['diagnostic_demo']
release = asyncio.Event()
- async def application(scope: dict, receive: object, send: object) -> None:
+ async def application(scope: Scope, receive: Receive, send: Send) -> None:
"""
模拟应用的生命周期消息交换。
@@ -174,12 +180,15 @@ async def application(scope: dict, receive: object, send: object) -> None:
await loaded.lifespan.startup()
loaded.active = True
running = runtime.diagnostic_snapshot()
+ assert running.plugins[0].lifespan is not None
assert running.plugins[0].lifespan.task_active
assert running.plugins[0].ready
assert running.worker_pending_cleanup_tasks == 0
release.set()
+ assert loaded.lifespan._task is not None
await asyncio.wait({loaded.lifespan._task}, timeout=1)
stopped = runtime.diagnostic_snapshot()
+ assert stopped.plugins[0].lifespan is not None
assert not stopped.plugins[0].lifespan.task_active
assert not stopped.plugins[0].ready
assert stopped.worker_pending_cleanup_tasks == 0
@@ -198,7 +207,7 @@ async def test_live_connection_counts_do_not_include_ordinary_http_or_auth_data(
opened = {'http': asyncio.Event(), 'websocket': asyncio.Event()}
release = asyncio.Event()
- async def authorize(scope: dict) -> PluginRequestContext:
+ async def authorize(scope: Scope) -> PluginRequestContext:
"""
创建测试使用的 ``PluginRequestContext`` 实例。
@@ -207,7 +216,7 @@ async def authorize(scope: dict) -> PluginRequestContext:
"""
return PluginRequestContext(loaded.host, user=SimpleNamespace(private='private-user'))
- async def application(scope: dict, receive: object, send: object) -> None:
+ async def application(scope: Scope, receive: Receive, send: Send) -> None:
"""
模拟应用的生命周期消息交换。
@@ -237,7 +246,7 @@ async def receive() -> dict:
await asyncio.Event().wait()
return {}
- async def send(message: dict) -> None:
+ async def send(message: Message) -> None:
"""
完成无需返回值的回调。
@@ -291,14 +300,16 @@ async def resistant() -> None:
task = asyncio.create_task(resistant())
await started.wait()
- manager = PluginGatewayASGI(AsyncMock(), PluginLifespanManager(AsyncMock(), managed=False), AsyncMock()).connections
- loaded.gateway = SimpleNamespace(connections=manager)
+ loaded.gateway = PluginGatewayASGI(AsyncMock(), PluginLifespanManager(AsyncMock(), managed=False), AsyncMock())
+ manager = loaded.gateway.connections
try:
await cancel_plugin_tasks({task}, grace_seconds=0.01)
await interrupted.wait()
# 模拟同一任务同时由通用回收器与连接回收器保留,诊断只能计算一次。
manager._unfinished.add(task)
- manager._unfinished.add(asyncio.current_task())
+ current = asyncio.current_task()
+ assert current is not None
+ manager._unfinished.add(current)
snapshot = runtime.diagnostic_snapshot()
expected_pending = 2
assert snapshot.worker_pending_cleanup_tasks == expected_pending
@@ -388,15 +399,30 @@ def test_wire_snapshot_requires_every_nested_serialized_field(tmp_path: Path) ->
('plugins', 0, 'config'),
('plugins', 0, 'lastError'),
]
+
+ def object_at(document: dict, path: tuple[str | int, ...]) -> dict:
+ """
+ 沿字段名和数组下标定位待验证的协议对象。
+
+ :param document: 诊断快照的 JSON 对象
+ :param path: 从根节点到目标对象的键和下标
+ :return: 可删除字段的目标字典
+ """
+ node: object = document
+ for key in path:
+ if isinstance(key, int):
+ assert isinstance(node, list)
+ else:
+ assert isinstance(node, dict)
+ node = node[key]
+ assert isinstance(node, dict)
+ return node
+
for path in objects:
- original = payload
- for component in path:
- original = original[component]
+ original = object_at(payload, path)
for field in original:
incomplete = deepcopy(payload)
- target = incomplete
- for component in path:
- target = target[component]
+ target = object_at(incomplete, path)
del target[field]
with pytest.raises(ValidationError, match='缺少协议字段'):
PluginRuntimeDiagnosticSnapshot.model_validate_json(json.dumps(incomplete), context=context)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_store.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_store.py
index c9da0d833..13f133c0d 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_store.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_store.py
@@ -4,14 +4,13 @@
from collections.abc import AsyncIterator
from datetime import UTC, datetime
from fnmatch import fnmatchcase
-from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import FastAPI
-from redis._parsers.encoders import Encoder
from redis.client import NEVER_DECODE
+from plugins.core.deployment.worker import PluginReleaseWorker
from plugins.core.runtime import diagnostics_store as module
from plugins.core.runtime.application import PluginApplicationRuntime
from plugins.core.runtime.diagnostics import PluginRuntimeDiagnostic, PluginRuntimeDiagnosticSnapshot
@@ -36,7 +35,6 @@ class DiagnosticsRedis:
:ivar expirations: 按键记录的失效时间
:ivar writes: 已执行写入操作的记录
:ivar fail: 是否模拟操作失败
- :ivar encoder: 将输入值转换为编码表示的对象
"""
def __init__(self) -> None:
@@ -45,7 +43,6 @@ def __init__(self) -> None:
self.expirations: dict[str, int] = {}
self.writes = 0
self.fail = False
- self.encoder = Encoder('utf-8', 'strict', decode_responses=True)
async def set(self, key: str, value: bytes, *, ex: int) -> None:
"""
@@ -85,7 +82,7 @@ async def scan_iter(self, *, match: str, count: int, **options: object) -> Async
for key in self.values:
raw_key = key.encode() if isinstance(key, str) else key
if fnmatchcase(raw_key, match.encode()):
- yield raw_key if NEVER_DECODE in options else self.encoder.decode(raw_key)
+ yield raw_key if NEVER_DECODE in options else raw_key.decode()
async def mget(self, keys: list[str]) -> list[bytes | None]:
"""
@@ -107,7 +104,7 @@ async def execute_command(self, command: str, *keys: str, **options: object) ->
"""
assert command == 'MGET'
values = await self.mget(list(keys))
- return [value if value is None or NEVER_DECODE in options else self.encoder.decode(value) for value in values]
+ return [value if value is None or NEVER_DECODE in options else value.decode() for value in values]
def snapshot(worker_id: str, *, pending: int = 0, collected_at: float | None = None) -> PluginRuntimeDiagnosticSnapshot:
@@ -379,7 +376,8 @@ async def test_empty_runtime_uses_release_worker_identity_without_fabricating_mi
explicit = ExplicitPluginRuntime(UnavailablePluginRouteStateGateway())
app.state.plugin_explicit_runtime = explicit
worker_id = 'b' * 32
- worker = SimpleNamespace(
+ worker = MagicMock(
+ spec=PluginReleaseWorker,
worker_id=worker_id,
start=AsyncMock(),
ready=AsyncMock(),
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_explicit.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_explicit.py
index e578ef6d3..930f91f56 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_explicit.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_explicit.py
@@ -4,7 +4,7 @@
from contextlib import asynccontextmanager, suppress
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, Mock, patch
import httpx
import pytest
@@ -22,6 +22,8 @@
from plugins.core.runtime.application import PluginApplicationRuntime
from plugins.core.runtime.asgi import PluginLifespanManager
from plugins.core.runtime.explicit import ExplicitPluginRuntime
+from plugins.core.runtime.job_dispatcher import PluginJobBinding
+from plugins.core.runtime.route_guard import PluginRouteStateGateway, UnavailablePluginRouteStateGateway
from plugins.core.runtime.startup import PluginRuntimeStartupManager
from plugins.core.runtime.startup_coordination import PluginStartupGenerationResolver
from plugins.core.sdk import PluginDefinition
@@ -126,7 +128,7 @@ async def test_main_runtime_mounts_authenticates_and_stops_subapplication(tmp_pa
app = FastAPI()
app.state.plugin_registry = PluginRegistry([plugin])
app.state.redis = object()
- gateway = SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True))
+ gateway = Mock(spec_set=PluginRouteStateGateway, is_plugin_enabled=AsyncMock(return_value=True))
manager = PluginRuntimeStartupManager(route_state_gateway=gateway, default_enabled_builtin_plugin_ids=set())
login = AsyncMock(return_value=SimpleNamespace(permissions=['runtime_test:view']))
with (
@@ -174,7 +176,9 @@ async def denied():
app = FastAPI()
app.dependency_overrides[get_db_session_provider(None)] = object
app.dependency_overrides[LoginService.get_current_user] = lambda: SimpleNamespace(permissions=['runtime_test:view'])
- runtime = ExplicitPluginRuntime(SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True)))
+ runtime = ExplicitPluginRuntime(
+ Mock(spec_set=PluginRouteStateGateway, is_plugin_enabled=AsyncMock(return_value=True))
+ )
runtime.prepare(plugin, app, startup_write_enabled=False)
try:
await runtime.activate('runtime_test', app)
@@ -222,7 +226,7 @@ async def info(
app = FastAPI()
app.dependency_overrides[get_db_session_provider(None)] = object
user = CurrentUserModel(
- permissions=['runtime_test:view'], roles=['reader'], user=UserInfoModel(userId=7, userName='tester')
+ permissions=['runtime_test:view'], roles=['reader'], user=UserInfoModel(user_id=7, user_name='tester')
)
resolver = AsyncMock(return_value=user)
monkeypatch.setattr(LoginService, '_resolve_current_user', resolver)
@@ -239,7 +243,9 @@ async def current_user() -> CurrentUserModel:
if override_dependency:
app.dependency_overrides[LoginService.get_current_user] = current_user
- runtime = ExplicitPluginRuntime(SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True)))
+ runtime = ExplicitPluginRuntime(
+ Mock(spec_set=PluginRouteStateGateway, is_plugin_enabled=AsyncMock(return_value=True))
+ )
runtime.prepare(plugin, app, startup_write_enabled=False)
try:
await runtime.activate('runtime_test', app)
@@ -304,7 +310,7 @@ async def test_health_failure_after_startup_shuts_down_child(tmp_path: Path) ->
plugin = write_plugin(tmp_path, source=ASGI_SOURCE + '\nasync def check(context): return False\n')
plugin.discovered_plugin.manifest.backend.health.checker = 'plugins.runtime_test:check'
app = FastAPI()
- runtime = ExplicitPluginRuntime(SimpleNamespace())
+ runtime = ExplicitPluginRuntime(UnavailablePluginRouteStateGateway())
runtime.prepare(plugin, app, startup_write_enabled=False)
with pytest.raises(RuntimeError, match='健康检查'):
await runtime.activate('runtime_test', app)
@@ -318,7 +324,7 @@ async def test_shutdown_isolates_cleanup_failures_and_closes_in_reverse_order(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure_at: str
) -> None:
"""一个清理步骤失败后继续其余资源及依赖插件,关闭开始即拒绝全部激活。"""
- runtime = ExplicitPluginRuntime(SimpleNamespace())
+ runtime = ExplicitPluginRuntime(UnavailablePluginRouteStateGateway())
app = FastAPI()
for plugin_id in ['runtime_test_base', 'runtime_test_consumer']:
runtime.prepare(write_plugin(tmp_path, plugin_id=plugin_id), app, startup_write_enabled=False)
@@ -345,6 +351,7 @@ async def step(name: str, *, fails: bool = False) -> None:
metrics_stop.side_effect = RuntimeError('metrics failed')
monkeypatch.setattr(runtime.metrics_reporter, 'stop', metrics_stop)
consumer = runtime.loaded['runtime_test_consumer']
+ assert consumer.lifespan is not None
actual_shutdown = consumer.lifespan.shutdown
async def consumer_lifespan() -> None:
@@ -366,18 +373,20 @@ async def consumer_jobs(binding: object) -> None:
monkeypatch.setattr(consumer.lifespan, 'shutdown', consumer_lifespan)
monkeypatch.setattr(consumer.gateway, 'drain', consumer_connection)
- consumer.jobs = SimpleNamespace(tasks=set())
+ consumer.jobs = Mock(spec=PluginJobBinding, tasks=set())
monkeypatch.setattr('plugins.core.runtime.explicit.unbind_plugin_jobs', consumer_jobs)
try:
await runtime.shutdown()
assert order == ['consumer:connection', 'consumer:job', 'consumer:lifespan']
assert sys.modules['plugins.runtime_test_base'].events == ['start', 'stop']
assert sys.modules['plugins.runtime_test_consumer'].events == ['start', 'stop']
- assert all(not loaded.lifespan.ready for loaded in runtime.loaded.values())
+ assert all(loaded.lifespan is not None and not loaded.lifespan.ready for loaded in runtime.loaded.values())
metrics_stop.assert_awaited_once()
finally:
await actual_shutdown()
- await runtime.loaded['runtime_test_base'].lifespan.shutdown()
+ base_lifespan = runtime.loaded['runtime_test_base'].lifespan
+ assert base_lifespan is not None
+ await base_lifespan.shutdown()
@pytest.mark.asyncio
@@ -400,7 +409,7 @@ async def test_shutdown_during_health_check_cannot_publish_late_plugin(
)
plugin = write_plugin(tmp_path, source=source, integration=integration)
app = FastAPI()
- runtime = ExplicitPluginRuntime(SimpleNamespace())
+ runtime = ExplicitPluginRuntime(UnavailablePluginRouteStateGateway())
runtime.prepare(plugin, app, startup_write_enabled=False)
entered, release = asyncio.Event(), asyncio.Event()
@@ -436,7 +445,7 @@ async def test_failed_activation_cannot_replace_pending_lifespan(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""显式运行时保留启动失败的管理器,旧资源退出前不能创建第二个子应用。"""
- runtime = ExplicitPluginRuntime(SimpleNamespace())
+ runtime = ExplicitPluginRuntime(UnavailablePluginRouteStateGateway())
app = FastAPI()
runtime.prepare(write_plugin(tmp_path), app, startup_write_enabled=False)
release = asyncio.Event()
@@ -474,11 +483,12 @@ async def child(scope: Scope, receive: Receive, send: Send) -> None:
assert activating.done()
with pytest.raises(TimeoutError):
await activating
- assert loaded.lifespan.has_pending_task
+ assert loaded.lifespan is not None and loaded.lifespan.has_pending_task
with pytest.raises(RuntimeError, match='上一次生命周期尚未退出'):
await runtime.activate('runtime_test', app)
assert len(attempts) == 1
release.set()
+ assert loaded.lifespan._task is not None
await asyncio.wait({loaded.lifespan._task}, timeout=1)
await runtime.activate('runtime_test', app)
assert loaded.active and loaded.lifespan.ready
@@ -495,14 +505,15 @@ async def test_activation_cleanup_failure_preserves_original_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""激活清理失败时保留原始错误。"""
- runtime = ExplicitPluginRuntime(SimpleNamespace())
+ runtime = ExplicitPluginRuntime(UnavailablePluginRouteStateGateway())
app = FastAPI()
plugin = write_plugin(tmp_path, source=ASGI_SOURCE.replace("events.append('stop')", "raise ValueError('cleanup')"))
runtime.prepare(plugin, app, startup_write_enabled=False)
monkeypatch.setattr(runtime, '_check_health', AsyncMock(side_effect=LookupError('primary health failure')))
with pytest.raises(LookupError, match='primary health failure'):
await runtime.activate('runtime_test', app)
- assert not runtime.loaded['runtime_test'].lifespan.has_pending_task
+ lifespan = runtime.loaded['runtime_test'].lifespan
+ assert lifespan is not None and not lifespan.has_pending_task
@pytest.mark.asyncio
@@ -574,7 +585,7 @@ def create_plugin(host):
"""
plugin = write_plugin(tmp_path, source=source, integration='router')
app = FastAPI()
- runtime = ExplicitPluginRuntime(SimpleNamespace())
+ runtime = ExplicitPluginRuntime(UnavailablePluginRouteStateGateway())
runtime.prepare(plugin, app, startup_write_enabled=False)
with pytest.raises(ValueError, match='命名空间'):
await runtime.activate('runtime_test', app)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_health.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_health.py
index c091ee465..0f639ea98 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_health.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_health.py
@@ -1,7 +1,6 @@
import sys
from collections.abc import Generator
from pathlib import Path
-from types import SimpleNamespace
import pytest
from fastapi import FastAPI
@@ -11,6 +10,7 @@
from plugins.core.manifest.schema import EXPLICIT_MANIFEST_VERSION
from plugins.core.runtime.explicit import ExplicitPluginRuntime
from plugins.core.runtime.health import PluginHealthChecker
+from plugins.core.runtime.route_guard import UnavailablePluginRouteStateGateway
@pytest.fixture(autouse=True)
@@ -266,7 +266,7 @@ async def test_v2_invalid_health_result_prevents_router_activation(tmp_path: Pat
discovered = PluginScanner(plugin_root.parent).load_manifest(plugin_root / 'plugin.yaml')
plugin = RegisteredPlugin(discovered, None, True, 'installed')
app = FastAPI()
- runtime = ExplicitPluginRuntime(SimpleNamespace())
+ runtime = ExplicitPluginRuntime(UnavailablePluginRouteStateGateway())
runtime.prepare(plugin, app, startup_write_enabled=False)
try:
with pytest.raises(RuntimeError, match='健康检查'):
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_service_extensions.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_service_extensions.py
index ffcb03ebb..451f30ab5 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_service_extensions.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_service_extensions.py
@@ -1,5 +1,5 @@
import json
-from collections.abc import AsyncIterator
+from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from pathlib import Path
from types import SimpleNamespace
@@ -34,7 +34,7 @@ async def test_dictionary_service_returns_only_public_enabled_options(tmp_path:
db = object()
@asynccontextmanager
- async def session() -> AsyncIterator[object]:
+ async def session() -> AsyncGenerator[object, None]:
"""
为当前测试操作提供数据库会话。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_services.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_services.py
index 834ff89a5..641eb5700 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_services.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_host_services.py
@@ -102,7 +102,7 @@ def native_callback(context: PluginRequestContext) -> object:
)
assert await endpoint(request) == {'ok': True}
callback.assert_awaited_once()
- received = callback.await_args.args[0]
+ received = callback.await_args_list[-1].args[0]
assert received.host is context.host
assert received.user is context.user
assert received.permissions == context.permissions
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_job_dispatcher.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_job_dispatcher.py
index 2b136f817..30ee00dd7 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_job_dispatcher.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_job_dispatcher.py
@@ -6,7 +6,7 @@
from contextlib import asynccontextmanager, suppress
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, Mock, patch
import pytest
import yaml
@@ -22,10 +22,12 @@
from plugins.core.runtime.explicit import ExplicitPluginRuntime, LoadedExplicitPlugin
from plugins.core.runtime.job_dispatcher import (
DISPATCH_TARGET,
+ PluginJobBinding,
bind_plugin_jobs,
dispatch_plugin_job,
unbind_plugin_jobs,
)
+from plugins.core.runtime.route_guard import PluginRouteStateGateway
from plugins.core.sdk import PluginHostContext, PluginTaskContext
from plugins.core.validation.structure import PluginStructureChecker
@@ -87,7 +89,7 @@ async def session() -> AsyncGenerator[object, None]:
sessions.append('close')
host = PluginHostContext('dispatch_test', directory, services={'test.task': service}, session_factory=session)
- gateway = SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True))
+ gateway = Mock(spec_set=PluginRouteStateGateway, is_plugin_enabled=AsyncMock(return_value=True))
runtime = ExplicitPluginRuntime(gateway)
runtime.metrics.register('dispatch_test', plugin.manifest.version, None, None)
definition = PluginEntrypointLoader(plugin).load(host)
@@ -350,7 +352,7 @@ async def resistant(*args: object, **kwargs: object) -> bool:
await release.wait()
return True
- async def bounded_unbind(binding: object) -> None:
+ async def bounded_unbind(binding: PluginJobBinding) -> None:
"""
以较短的宽限期解除插件任务绑定。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics.py
index f99a2afbe..cf8869ba3 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics.py
@@ -38,6 +38,7 @@ def test_invocation_counts_duration_histogram_and_is_idempotent() -> None:
metrics = collector()
metrics.clock = lambda: now[0]
invocation = metrics.begin('metric_demo', 'http', 'trace-1')
+ assert invocation is not None
assert metrics.snapshot().series[0].active == 1
now[0] = 0.2
invocation.finish('succeeded')
@@ -62,6 +63,7 @@ def test_task_metric_names_accept_all_manifest_job_id_forms(job_id: str) -> None
"""指标标签兼容清单允许的短任务 ID 和连接符。"""
metrics = collector()
invocation = metrics.begin('metric_demo', f'job:{job_id}', 'job-request')
+ assert invocation is not None
invocation.finish('succeeded')
assert any(series.operation == f'job:{job_id}' for series in metrics.snapshot().series)
@@ -71,8 +73,12 @@ def test_aggregate_preserves_version_and_generation_boundaries() -> None:
first, second = collector(), collector('b' * 32)
new_version = collector('d' * 32, '2.0.0')
new_generation = collector('e' * 32, generation='f' * 32)
- first.begin('metric_demo', 'http', 'first').finish('succeeded')
- second.begin('metric_demo', 'http', 'second').finish('failed', error_type='TimeoutError', timed_out=True)
+ invocation = first.begin('metric_demo', 'http', 'first')
+ assert invocation is not None
+ invocation.finish('succeeded')
+ invocation = second.begin('metric_demo', 'http', 'second')
+ assert invocation is not None
+ invocation.finish('failed', error_type='TimeoutError', timed_out=True)
rows = aggregate_metric_snapshots([item.snapshot() for item in (first, second, new_version, new_generation)], None)
expected_groups = 3
assert len(rows) == expected_groups
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics_store.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics_store.py
index 0ca7d6203..c597e6b04 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics_store.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_metrics_store.py
@@ -83,7 +83,9 @@ def reporter(worker_id: str) -> PluginMetricsReporter:
"""
metrics = PluginRuntimeMetrics(worker_id=worker_id)
metrics.register('metric_demo', '1.0.0', None, None)
- metrics.begin('metric_demo', 'http', f'trace-{worker_id}').finish('succeeded')
+ invocation = metrics.begin('metric_demo', 'http', f'trace-{worker_id}')
+ assert invocation is not None
+ invocation.finish('succeeded')
return PluginMetricsReporter(metrics)
@@ -96,7 +98,9 @@ async def test_reporting_workers_aggregate_without_double_counting_local_snapsho
item.start(redis, namespace)
await item.publish()
try:
- first.metrics.begin('metric_demo', 'http', 'new').finish('succeeded')
+ invocation = first.metrics.begin('metric_demo', 'http', 'new')
+ assert invocation is not None
+ invocation.finish('succeeded')
result = await first.read('metric_demo')
assert result['scope'] == 'reporting_workers'
expected_workers = 2
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_plugin_bootstrap.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_plugin_bootstrap.py
index 85638e67b..cc018ed60 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_plugin_bootstrap.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_plugin_bootstrap.py
@@ -79,10 +79,10 @@ def test_plugin_runtime_builder_merges_database_plugin_state(tmp_path: Path) ->
""",
)
database_plugin = PluginModel(
- pluginId='demo',
- pluginName='演示插件',
+ plugin_id='demo',
+ plugin_name='演示插件',
version='1.0.0',
- installedVersion='1.0.0',
+ installed_version='1.0.0',
enabled='1',
status='installed',
)
@@ -116,10 +116,10 @@ def test_plugin_runtime_builder_imports_enabled_plugin_entities(tmp_path: Path)
registry = builder.build_registry(
[
PluginModel(
- pluginId='sample_entity',
- pluginName='演示插件',
+ plugin_id='sample_entity',
+ plugin_name='演示插件',
version='1.0.0',
- installedVersion='1.0.0',
+ installed_version='1.0.0',
enabled='0',
status='installed',
)
@@ -154,10 +154,10 @@ def test_plugin_runtime_builder_reports_failed_plugin_entity_import(tmp_path: Pa
registry = builder.build_registry(
[
PluginModel(
- pluginId='broken_entity',
- pluginName='异常插件',
+ plugin_id='broken_entity',
+ plugin_name='异常插件',
version='1.0.0',
- installedVersion='1.0.0',
+ installed_version='1.0.0',
enabled='0',
status='installed',
)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_route_guard.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_route_guard.py
index 4b91d4b60..1c8fc674f 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_route_guard.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_route_guard.py
@@ -1,4 +1,5 @@
import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
from exceptions.exception import PermissionException
from plugins.core.runtime.route_guard import CheckPluginEnabled
@@ -36,7 +37,7 @@ async def is_plugin_enabled(self, db: object, plugin_id: str) -> bool:
@pytest.mark.asyncio
async def test_plugin_route_guard_allows_enabled_plugin() -> None:
"""校验插件路由状态依赖允许启用插件访问。"""
- db = object()
+ db = AsyncSession()
state_gateway = FakePluginRouteStateGateway(enabled=True)
assert await CheckPluginEnabled('demo', state_gateway)(db) is True
@@ -49,5 +50,5 @@ async def test_plugin_route_guard_rejects_disabled_plugin() -> None:
state_gateway = FakePluginRouteStateGateway(enabled=False)
with pytest.raises(PermissionException) as exc_info:
- await CheckPluginEnabled('demo', state_gateway)(object())
+ await CheckPluginEnabled('demo', state_gateway)(AsyncSession())
assert exc_info.value.message == '插件未启用,接口不可访问'
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_sdk_requests.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_sdk_requests.py
index 3af528402..330ca24c6 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_sdk_requests.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_sdk_requests.py
@@ -78,7 +78,7 @@ async def test_endpoint_exposes_typed_body_multi_value_query_and_host_trace(tmp_
'query': {'tag': ['alpha', 'beta'], 'empty': ['']},
'body': {'name': 'report', 'count': 3},
}
- assert callback.await_args.args[0].request_id == 'host-request-123'
+ assert callback.await_args_list[-1].args[0].request_id == 'host-request-123'
assert 'secret-token' not in response.text
assert 'private-cookie' not in response.text
@@ -166,7 +166,7 @@ async def test_permission_check_precedes_reading_body_and_legacy_adapter_leaves_
receive,
)
)
- assert callback.await_args.args[0].request.body is None
+ assert callback.await_args_list[-1].args[0].request.body is None
receive.assert_not_called()
@@ -177,7 +177,7 @@ async def test_payload_copy_does_not_mutate_callback_request(tmp_path: Path) ->
app = endpoint_app(tmp_path, callback, json_body=True)
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client:
await client.post('/reports/7', json={'nested': [1, 2]})
- context = callback.await_args.args[0]
+ context = callback.await_args_list[-1].args[0]
payload = context.request.to_payload()
payload['body']['nested'].append(3)
assert context.request.body == {'nested': [1, 2]}
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_startup.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_startup.py
index 8e8cc8f80..deceaa877 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_startup.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_startup.py
@@ -1,4 +1,4 @@
-from contextlib import asynccontextmanager
+from contextlib import AbstractContextManager, asynccontextmanager
from pathlib import Path
from subprocess import CompletedProcess
from types import SimpleNamespace
@@ -15,7 +15,7 @@
BACKEND_ROOT = Path(__file__).resolve().parents[4]
-def patch_startup_get_db(fake_get_db: Any) -> object:
+def patch_startup_get_db(fake_get_db: Any) -> AbstractContextManager:
"""
替换启动管理器方法使用的默认数据源会话。
@@ -29,7 +29,7 @@ def patch_startup_get_db(fake_get_db: Any) -> object:
)
-def patch_startup_global(name: str, value: object) -> object:
+def patch_startup_global(name: str, value: object) -> AbstractContextManager:
"""
替换启动管理器方法使用的模块全局引用。
@@ -841,10 +841,11 @@ async def test_check_enabled_plugin_python_dependencies_never_installs_during_st
stdout='installed',
stderr='',
)
+ inspector_factory = MagicMock()
startup_manager = PluginRuntimeStartupManager(
MagicMock(),
python_dependency_inspector=first_inspector,
- python_dependency_inspector_factory=MagicMock(),
+ python_dependency_inspector_factory=inspector_factory,
command_runner_gateway=command_runner_gateway,
)
@@ -856,7 +857,7 @@ async def test_check_enabled_plugin_python_dependencies_never_installs_during_st
await startup_manager.check_enabled_plugin_python_dependencies(app)
command_runner_gateway.run_command.assert_not_called()
- startup_manager.python_dependency_inspector_factory.assert_not_called()
+ inspector_factory.assert_not_called()
mark_plugin_runtime_error.assert_awaited_once_with(
app,
'ai',
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_task_cleanup.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_task_cleanup.py
index f6b37055c..1ff1f2ccf 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_task_cleanup.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_task_cleanup.py
@@ -19,7 +19,9 @@ async def work() -> None:
tasks = {asyncio.create_task(work()) for _ in range(3)}
await asyncio.sleep(0)
- assert await cancel_plugin_tasks(tasks | {asyncio.current_task()}, grace_seconds=0.01) == set()
+ current = asyncio.current_task()
+ assert current is not None
+ assert await cancel_plugin_tasks(tasks | {current}, grace_seconds=0.01) == set()
assert len(stopped) == len(tasks)
assert all(task.cancelled() for task in tasks)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/test_state.py b/ruoyi-fastapi-backend/tests/plugins/core/test_state.py
index af888e66b..f6dfbb3d2 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/test_state.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/test_state.py
@@ -1,6 +1,12 @@
from types import SimpleNamespace
-from plugins.core.state import PluginStateResolver, PluginStateSnapshot, PluginStateTransitionTable
+from plugins.core.state import (
+ PluginStateOperation,
+ PluginStateResolver,
+ PluginStateSnapshot,
+ PluginStateTransitionTable,
+ PluginStatus,
+)
def test_state_resolver_covers_lifecycle_states() -> None:
@@ -53,7 +59,7 @@ def test_database_enabled_state_respects_error_status() -> None:
def test_state_transition_table_covers_supported_and_rejected_operations() -> None:
"""校验状态转换表覆盖支持与拒绝的操作。"""
- supported_cases = [
+ supported_cases: list[tuple[PluginStatus, PluginStateOperation, PluginStatus]] = [
('discovered', 'install', 'installed'),
('discovered', 'disable', 'discovered'),
('installed', 'mark_error', 'error'),
@@ -69,7 +75,7 @@ def test_state_transition_table_covers_supported_and_rejected_operations() -> No
def test_state_resolver_and_transition_table_remain_consistent() -> None:
"""校验状态解析器与转换表保持一致。"""
- cases = [
+ cases: list[tuple[PluginStatus | None, PluginStateOperation, PluginStateSnapshot]] = [
(None, 'discover', PluginStateSnapshot(source_version='1.0.0', installed_version=None, enabled=True)),
(
'discovered',
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_dependency_policy.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_dependency_policy.py
index 7122039f9..42e0e091e 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_dependency_policy.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_dependency_policy.py
@@ -5,7 +5,7 @@
import pytest
import config.env as env_config
-from plugins.core.validation.dependencies import DependencyInstallPlan, DependencyInstallPlanItem
+from plugins.core.validation.dependencies import DependencyInstallPlan, DependencyInstallPlanItem, DependencyKind
from plugins.core.validation.dependency_policy import (
DependencyInstallPolicyConfig,
DependencyInstallPolicyEvaluator,
@@ -44,7 +44,7 @@ def build_python_item(requirement: str = 'openai>=2.0.0') -> DependencyInstallPl
def build_npm_item(
requirement: str = 'dayjs>=1.11.0,<2.0.0',
*,
- kind: str = 'npm',
+ kind: DependencyKind = 'npm',
name: str = 'dayjs',
) -> DependencyInstallPlanItem:
"""
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_frontend_dependencies.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_frontend_dependencies.py
index 502f6f42d..0467abdec 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_frontend_dependencies.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_frontend_dependencies.py
@@ -173,6 +173,7 @@ def test_management_detail_uses_selected_frontend_profile(tmp_path: Path, framew
manifest_path=tmp_path / 'plugins' / 'demo' / 'plugin.yaml',
)
model = PluginService._build_plugin_model(plugin, tmp_path / 'plugins', root / 'plugins', None)
+ assert model.dependencies is not None
assert model.dependencies['frontendFramework'] == framework
assert model.dependencies['npm'] == manifest.dependencies.resolve_frontend(framework).npm
assert set(model.dependencies['frontendProfiles']) == {'vue2', 'vue3', 'react'}
@@ -204,6 +205,7 @@ def test_lock_template_contains_only_selected_host_dependencies(tmp_path: Path,
payload = template.to_dict()
assert payload['frontendFramework'] == framework
assert 'frontendVersion' not in payload
+ assert isinstance(payload['npm'], list)
assert {item['requirement'] for item in payload['npm']} == set(
build_manifest().dependencies.resolve_frontend(framework).npm
)
@@ -256,6 +258,7 @@ def test_independent_host_preserves_explicit_framework_through_dependencies(
manifest_path=tmp_path / 'plugins' / 'demo' / 'plugin.yaml',
)
model = PluginService._build_plugin_model(plugin, tmp_path / 'plugins', root / 'plugins', None)
+ assert model.dependencies is not None
assert model.dependencies['frontendFramework'] == 'react18'
assert model.dependencies['npm'] == ['react18-renderer==1.0.0']
for framework in ('auto', environment.get_frontend_framework()):
@@ -263,7 +266,8 @@ def test_independent_host_preserves_explicit_framework_through_dependencies(
manifest, frontend_root=root, frontend_framework=framework
).to_dict()
assert template['frontendFramework'] == 'react18'
- assert {item['requirement'] for item in template['npm']} == {'react18-renderer==1.0.0'}
+ assert isinstance(template['npm'], list)
+ assert {item['requirement'] for item in template['npm']} == {'react18-renderer==1.0.0'}
lock_path = tmp_path / 'react18.lock.yaml'
lock_path.write_text('frontendFramework: react18\n', encoding='utf-8')
evaluator = DependencyInstallPolicyEvaluator(
@@ -331,7 +335,7 @@ def test_profile_dependencies_trigger_frontend_build_and_lint(tmp_path: Path) ->
payload['dependencies'] = {'frontend': {'vue2': {'npm': ['unpinned-package']}}}
manifest = PluginManifest.model_validate(payload)
assert manifest.frontend.delivery.build_required is True
- issues = PluginManifestChecker._check_unpinned_dependencies(None, manifest)
+ issues = PluginManifestChecker._check_unpinned_dependencies(manifest)
assert issues[0].path == 'dependencies.frontend.vue2.npm.0'
plugin = DiscoveredPlugin(manifest=manifest, backend_path=tmp_path, manifest_path=tmp_path / 'plugin.yaml')
capability = PluginRuntimeCapabilityResolver(frontend_mode='built', backend_runtime_mode='service').resolve(plugin)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest.py
index b112abca0..2628b09cb 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest.py
@@ -2,6 +2,7 @@
from types import SimpleNamespace
import pytest
+from pytest import MonkeyPatch
import plugins.core.validation.manifest as manifest_module
from plugins.core.manifest.schema import FrontendManifest, PluginDependencyManifest, PluginManifest
@@ -220,7 +221,7 @@ def test_manifest_checker_accepts_satisfied_compatibility(tmp_path: Path) -> Non
assert result.issues == []
-def test_manifest_checker_accepts_supported_database(monkeypatch: object) -> None:
+def test_manifest_checker_accepts_supported_database(monkeypatch: MonkeyPatch) -> None:
"""校验当前数据库在插件支持列表内时不产生问题。"""
monkeypatch.setattr(manifest_module.DataBaseConfig.default_source, 'db_type', 'postgresql')
manifest = PluginManifest.model_validate(
@@ -239,7 +240,7 @@ def test_manifest_checker_accepts_supported_database(monkeypatch: object) -> Non
assert result.issues == []
-def test_manifest_checker_caches_resolved_node_version(tmp_path: Path, monkeypatch: object) -> None:
+def test_manifest_checker_caches_resolved_node_version(tmp_path: Path, monkeypatch: MonkeyPatch) -> None:
"""校验 Node.js 版本解析会缓存 subprocess 结果。"""
backend_root = tmp_path / 'backend'
frontend_root = tmp_path / 'frontend'
@@ -311,7 +312,7 @@ def test_manifest_checker_reports_unsatisfied_compatibility(tmp_path: Path) -> N
assert result.error_issues[0].path == 'compatibility.pythonVersion'
-def test_manifest_checker_reports_unsupported_database(monkeypatch: object) -> None:
+def test_manifest_checker_reports_unsupported_database(monkeypatch: MonkeyPatch) -> None:
"""校验当前数据库不在插件支持列表内时产生 error。"""
monkeypatch.setattr(manifest_module.DataBaseConfig.default_source, 'db_type', 'postgresql')
manifest = PluginManifest.model_validate(
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest_v2.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest_v2.py
index e41e90a69..c2f002c47 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest_v2.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest_v2.py
@@ -47,9 +47,42 @@ def test_runtime_and_integration_are_independent(native: bool, asgi: bool) -> No
assert manifest.integration_kind == ('asgi' if asgi else 'router')
assert manifest.backend.routers.auto_scan is False
if asgi:
+ assert manifest.backend.asgi is not None
assert manifest.backend.asgi.mount_path == '/apps/demo'
+@pytest.mark.parametrize('explicit', [False, True], ids=['v1', 'v2'])
+def test_manifest_round_trip_preserves_version_specific_fields(explicit: bool) -> None:
+ """按别名往返序列化后,任务执行器、前端交付和兼容性仍使用对应版本的模型。"""
+ payload = (
+ manifest_data(asgi=True, bundle=True)
+ if explicit
+ else {'id': 'demo', 'name': 'Demo', 'version': '1.0.0', 'backend': {'module': 'plugins.demo'}}
+ )
+ job: dict[str, object] = {'id': 'sync', 'callable': 'plugins.demo.jobs.sync', 'cronExpression': '0 0 1 * * ?'}
+ if explicit:
+ job['timeoutSeconds'] = 7
+ payload['compatibility'] = {'hostApiVersion': '^2.0.0'}
+ else:
+ job['executor'] = 'processpool'
+ payload['backend']['jobs'] = [job]
+
+ manifest = PluginManifestFactory.create(payload)
+ data = manifest.model_dump(by_alias=True)
+ assert isinstance(manifest, PluginManifest)
+ assert type(manifest) is (PluginManifestV2 if explicit else PluginManifest)
+ assert data['backend']['jobs'][0]['executor'] == ('default' if explicit else 'processpool')
+ if explicit:
+ assert data['backend']['jobs'][0]['timeoutSeconds'] == job['timeoutSeconds']
+ assert data['frontend']['bundle']['entry'] == 'index.html'
+ assert data['compatibility']['hostApiVersion'] == '^2.0.0'
+ else:
+ assert 'timeoutSeconds' not in data['backend']['jobs'][0]
+ assert 'bundle' not in data['frontend']
+ assert 'hostApiVersion' not in data['compatibility']
+ assert PluginManifestFactory.create(data) == manifest
+
+
def test_v1_keeps_defaults_and_rejects_v2_fields() -> None:
"""第一版配置保留默认值并拒绝第二版字段。"""
data = {'id': 'demo', 'name': 'Demo', 'version': '1', 'backend': {'module': 'plugins.demo'}}
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_plugin_deps.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_plugin_deps.py
index 1dd98fe2b..403bc25e6 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_plugin_deps.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_plugin_deps.py
@@ -1,8 +1,10 @@
from pathlib import Path
+from typing import Literal
from plugins.core.discovery.scanner import DiscoveredPlugin
from plugins.core.management.entity.vo.schemas import PluginModel
from plugins.core.manifest.schema import PluginManifest
+from plugins.core.state import PluginStatus
from plugins.core.validation.plugin_deps import (
PluginDependencyChecker,
PluginDependencyPlanBuilder,
@@ -42,7 +44,7 @@ def build_discovered_plugin(
def build_database_plugin(
- plugin_id: str, version: str, *, enabled: str = '0', status: str = 'installed'
+ plugin_id: str, version: str, *, enabled: Literal['0', '1'] = '0', status: PluginStatus = 'installed'
) -> PluginModel:
"""
构造测试用数据库插件状态。
@@ -54,10 +56,10 @@ def build_database_plugin(
:return: 测试用数据库插件状态
"""
return PluginModel(
- pluginId=plugin_id,
- pluginName=plugin_id,
+ plugin_id=plugin_id,
+ plugin_name=plugin_id,
version=version,
- installedVersion=version,
+ installed_version=version,
enabled=enabled,
status=status,
)
diff --git a/ruoyi-fastapi-backend/tests/plugins/examples/test_task_demo.py b/ruoyi-fastapi-backend/tests/plugins/examples/test_task_demo.py
index 0fadccd89..88257d367 100644
--- a/ruoyi-fastapi-backend/tests/plugins/examples/test_task_demo.py
+++ b/ruoyi-fastapi-backend/tests/plugins/examples/test_task_demo.py
@@ -13,6 +13,7 @@
from sqlalchemy.dialects import mysql, postgresql
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.sql.elements import TextClause
+from starlette.types import Receive, Scope, Send
from config.env import DataBaseConfig
from plugins.core.discovery.scanner import PluginScanner
@@ -79,9 +80,11 @@ def _client(host: PluginHostContext, permissions: frozenset[str] = frozenset({'*
:param permissions: 当前调用允许使用的权限
:return: ``httpx.AsyncClient`` 实例
"""
- child = create_plugin(host).app_factory(host)
+ factory = create_plugin(host).app_factory
+ assert factory is not None
+ child = factory(host)
- async def authenticated_app(scope: dict[str, Any], receive: Any, send: Any) -> None:
+ async def authenticated_app(scope: Scope, receive: Receive, send: Send) -> None:
"""
为插件请求注入已认证上下文后调用下游应用。
@@ -110,6 +113,7 @@ async def test_crud_is_persistent_across_new_app_and_connection_pool(task_host:
assert created['createdAt'].endswith('Z')
task_id = created['id']
+ assert isinstance(task_host.session_factory, async_sessionmaker)
original_engine = task_host.session_factory.kw['bind']
await original_engine.dispose()
restarted_engine = create_async_engine(original_engine.url)
@@ -164,7 +168,9 @@ async def test_permissions_keep_reads_and_writes_independent(task_host: PluginHo
assert (await reader.get(f'/api/tasks/{task_id}')).json()['title'] == '仅写身份更新'
async with _client(task_host, frozenset()) as anonymous:
assert (await anonymous.get('/api/info')).status_code == status.HTTP_403_FORBIDDEN
- app = create_plugin(task_host).app_factory(task_host)
+ factory = create_plugin(task_host).app_factory
+ assert factory is not None
+ app = factory(task_host)
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://task.test') as client:
assert (await client.get('/api/info')).status_code == status.HTTP_401_UNAUTHORIZED
@@ -241,6 +247,7 @@ def broken_payload(row: Any) -> dict[str, Any]:
monkeypatch.setattr(service, '_task_payload', broken_payload)
with pytest.raises(RuntimeError, match='response construction failed'):
await service.create_task(_context(task_host), TaskInput(title='必须回滚').model_dump())
+ assert task_host.session_factory is not None
async with task_host.session_factory() as db:
assert await db.scalar(select(func.count()).select_from(tasks)) == 0
@@ -274,6 +281,7 @@ async def close(self) -> None:
await super().close()
closed.set()
+ assert isinstance(task_host.session_factory, async_sessionmaker)
paused_host = replace(
task_host,
session_factory=async_sessionmaker(task_host.session_factory.kw['bind'], class_=PausedSession),
@@ -286,6 +294,7 @@ async def close(self) -> None:
with pytest.raises(asyncio.CancelledError):
await operation
await asyncio.wait_for(closed.wait(), timeout=5)
+ assert task_host.session_factory is not None
async with task_host.session_factory() as db:
assert await db.scalar(select(func.count()).select_from(tasks)) == 0
created = await service.create_task(_context(task_host), TaskInput(title='回滚后新任务').model_dump())
diff --git a/ruoyi-fastapi-backend/tests/plugins/integration/test_harness_safety.py b/ruoyi-fastapi-backend/tests/plugins/integration/test_harness_safety.py
index 20f2cfb81..c2f5287b5 100644
--- a/ruoyi-fastapi-backend/tests/plugins/integration/test_harness_safety.py
+++ b/ruoyi-fastapi-backend/tests/plugins/integration/test_harness_safety.py
@@ -3,9 +3,12 @@
import os
import threading
from collections.abc import AsyncGenerator, AsyncIterator
-from contextlib import asynccontextmanager
+from contextlib import asynccontextmanager, nullcontext
from fnmatch import fnmatchcase
from importlib import import_module
+from multiprocessing.context import SpawnProcess
+from multiprocessing.queues import Queue
+from multiprocessing.synchronize import Event
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -13,6 +16,9 @@
import pytest
+from config.database import DataSourceRegistry
+from config.get_redis import RedisUtil
+from plugins.core.runtime.service.lifecycle_lock import RedisPluginLifecycleLock
from scripts import plugin_release_integration as harness
@@ -294,11 +300,10 @@ async def test_run_continues_owned_cleanup_after_engine_dispose_error(
monkeypatch.setattr(harness, 'create_isolated_database', AsyncMock())
monkeypatch.setattr(harness, 'prepare_schema', AsyncMock())
monkeypatch.setattr(harness, 'exercise_release', AsyncMock())
- monkeypatch.setattr(harness, 'wire_runtime', Mock(return_value=(object(), object())))
+ monkeypatch.setattr(harness, 'wire_runtime', Mock(return_value=nullcontext((object(), object()))))
monkeypatch.setattr(import_module('plugins.core.deployment.service'), 'PluginDeploymentService', Mock())
- monkeypatch.setattr(
- import_module('scripts.plugin_task_integration'), 'exercise_task_delivery', AsyncMock(return_value={})
- )
+ deliver_task = AsyncMock(return_value={})
+ monkeypatch.setattr(import_module('scripts.plugin_task_integration'), 'exercise_task_delivery', deliver_task)
monkeypatch.setattr(harness, 'clear_own_redis_keys', clear)
monkeypatch.setattr(harness, 'drop_isolated_database', drop)
monkeypatch.setattr(harness, 'emit', Mock())
@@ -306,6 +311,7 @@ async def test_run_continues_owned_cleanup_after_engine_dispose_error(
with pytest.raises(RuntimeError, match='engine disposal failed'):
await harness.run(run_spec)
+ deliver_task.assert_awaited_once()
clear.assert_awaited_once_with(run_spec)
drop.assert_awaited_once_with(run_spec, admin)
admin.dispose.assert_awaited_once()
@@ -422,15 +428,13 @@ def test_workers_pass_independent_stop_events_to_spawned_processes(
@pytest.mark.parametrize('second_state', ['killed', 'dead'])
async def test_workers_close_skips_killed_or_dead_stop_event_but_stops_healthy_worker(second_state: str) -> None:
"""关闭时跳过已终止进程的事件并停止健康进程。"""
- healthy_stop = SimpleNamespace(set=Mock())
- unusable_stop = SimpleNamespace(set=Mock(side_effect=AssertionError('Terminated waiter poisoned this event')))
- healthy = SimpleNamespace(pid=101, exitcode=0, is_alive=Mock(return_value=True), terminate=Mock())
- second = SimpleNamespace(
- pid=102,
- exitcode=-15 if second_state == 'killed' else 0,
- is_alive=Mock(return_value=second_state == 'killed'),
- terminate=Mock(),
- )
+ healthy_stop = Mock(spec_set=Event)
+ unusable_stop = Mock(spec_set=Event)
+ unusable_stop.set.side_effect = AssertionError('Terminated waiter poisoned this event')
+ healthy = Mock(spec_set=SpawnProcess, pid=101, exitcode=0)
+ healthy.is_alive.return_value = True
+ second = Mock(spec_set=SpawnProcess, pid=102, exitcode=-15 if second_state == 'killed' else 0)
+ second.is_alive.return_value = second_state == 'killed'
def join_healthy(timeout: float) -> None:
"""
@@ -455,7 +459,8 @@ def join_second(timeout: float) -> None:
workers.stops = [healthy_stop, unusable_stop]
workers.processes = [healthy, second]
workers.killed = {1} if second_state == 'killed' else set()
- workers.queue = SimpleNamespace(close=Mock(), join_thread=Mock())
+ queue = Mock(spec_set=Queue)
+ workers.queue = queue
await workers.close()
@@ -465,8 +470,8 @@ def join_second(timeout: float) -> None:
second.join.assert_called_once()
healthy.terminate.assert_not_called()
second.terminate.assert_not_called()
- workers.queue.close.assert_called_once()
- workers.queue.join_thread.assert_called_once()
+ queue.close.assert_called_once()
+ queue.join_thread.assert_called_once()
def _wait_for_isolated_stop(stop: Any, ready: Any, index: int) -> None:
@@ -556,3 +561,24 @@ async def test_run_requires_built_bundle_before_opening_any_resource(
configure.assert_not_called()
factory.assert_not_called()
redis.assert_not_called()
+
+
+@pytest.mark.asyncio
+async def test_wire_runtime_restores_host_factories_after_failure(
+ run_spec: harness.RunSpec, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """隔离验收失败后恢复宿主会话工厂、Redis 工厂和生命周期锁命名空间。"""
+ client = Mock()
+ monkeypatch.setattr(harness, 'redis_client', lambda: client)
+ original_session = DataSourceRegistry.session
+ original_pool = RedisUtil.create_redis_pool
+ original_key = RedisPluginLifecycleLock._build_lock_key()
+
+ with pytest.raises(RuntimeError, match='中止验收'), harness.wire_runtime(run_spec, None):
+ assert await RedisUtil.create_redis_pool() is client
+ assert RedisPluginLifecycleLock._build_lock_key() == f'{run_spec.redis_prefix}lifecycle:global'
+ raise RuntimeError('中止验收')
+
+ assert DataSourceRegistry.session == original_session
+ assert RedisUtil.create_redis_pool == original_pool
+ assert RedisPluginLifecycleLock._build_lock_key() == original_key
diff --git a/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py b/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py
index 85572d4e4..857718c38 100644
--- a/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py
+++ b/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py
@@ -5,7 +5,7 @@
import shutil
import socket
import subprocess
-from collections.abc import AsyncIterator, Callable
+from collections.abc import AsyncGenerator, Callable
from contextlib import asynccontextmanager, suppress
from datetime import UTC, datetime, timedelta
from pathlib import Path
@@ -212,7 +212,7 @@ async def notices() -> dict[str, Any]:
@asynccontextmanager
-async def network_servers(fixture: SimpleNamespace, directory: Path, output: Path) -> AsyncIterator[str]:
+async def network_servers(fixture: SimpleNamespace, directory: Path, output: Path) -> AsyncGenerator[str, None]:
"""
启动真实 Uvicorn socket 与对应前端框架的 TLS 代理,并在失败时一并回收。
diff --git a/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke_runner.py b/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke_runner.py
index 947ccce3e..a2c4e0ad5 100644
--- a/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke_runner.py
+++ b/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke_runner.py
@@ -1,6 +1,7 @@
import asyncio
from pathlib import Path
from types import SimpleNamespace
+from typing import TextIO
from unittest.mock import AsyncMock
import pytest
@@ -30,16 +31,17 @@ async def serve(**kwargs: object) -> None:
server.serve = serve
monkeypatch.setattr(smoke.uvicorn, 'Server', lambda config: server)
- async def start_frontend(*args: object, **kwargs: object) -> SimpleNamespace:
+ async def start_frontend(*args: object, stdout: TextIO, **kwargs: object) -> SimpleNamespace:
"""
按测试场景模拟前端启动结果。
:param args: 传给被调用对象的位置参数
+ :param stdout: 写入前端启动日志的文本流
:param kwargs: 传给被调用对象的关键字参数
:return: ``SimpleNamespace`` 实例
"""
if failure == 'startup':
- kwargs['stdout'].write("Cannot find module 'memory-fs'\n")
+ stdout.write("Cannot find module 'memory-fs'\n")
else:
(tmp_path / 'frontend-ready.json').write_text('{"port": 12345}', encoding='utf-8')
return SimpleNamespace(returncode=1)
diff --git a/ruoyi-fastapi-backend/tests/plugins/native/test_native_bundle_build.py b/ruoyi-fastapi-backend/tests/plugins/native/test_native_bundle_build.py
index b33d3a970..0385acfc7 100644
--- a/ruoyi-fastapi-backend/tests/plugins/native/test_native_bundle_build.py
+++ b/ruoyi-fastapi-backend/tests/plugins/native/test_native_bundle_build.py
@@ -7,7 +7,8 @@
import yaml
from plugins.core.artifacts import package
-from plugins.core.manifest.schema import PluginManifest, PluginManifestFactory
+from plugins.core.manifest.schema import PluginManifestFactory
+from plugins.core.manifest.v2 import PluginManifestV2
from scripts import build_native_plugin
@@ -30,7 +31,7 @@ def source(tmp_path: Path) -> Path:
return root
-def manifest(**overrides: object) -> PluginManifest:
+def manifest(**overrides: object) -> PluginManifestV2:
"""
构建原生插件包使用的测试清单。
@@ -52,7 +53,9 @@ def manifest(**overrides: object) -> PluginManifest:
'frontend': {'delivery': {'type': 'bundle'}, 'bundle': {'directory': 'web/dist'}},
}
data.update(overrides)
- return PluginManifestFactory.create(data)
+ result = PluginManifestFactory.create(data)
+ assert isinstance(result, PluginManifestV2)
+ return result
def test_collects_only_built_bundle_and_declared_resource_directories(source: Path, tmp_path: Path) -> None:
diff --git a/ruoyi-fastapi-backend/tests/plugins/native/test_rust_demo.py b/ruoyi-fastapi-backend/tests/plugins/native/test_rust_demo.py
index ed54cce95..59c9df53e 100644
--- a/ruoyi-fastapi-backend/tests/plugins/native/test_rust_demo.py
+++ b/ruoyi-fastapi-backend/tests/plugins/native/test_rust_demo.py
@@ -8,7 +8,7 @@
from importlib.machinery import EXTENSION_SUFFIXES
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, Mock, patch
from zipfile import ZipFile
import httpx
@@ -26,10 +26,12 @@
from plugins.core.discovery.registry import RegisteredPlugin
from plugins.core.discovery.scanner import DiscoveredPlugin, PluginScanner
from plugins.core.lifecycle.jobs import PluginJobModelBuilder
+from plugins.core.manifest.v2 import PluginManifestV2
from plugins.core.runtime.entrypoint import PluginEntrypointLoader
from plugins.core.runtime.explicit import ExplicitPluginRuntime
from plugins.core.runtime.health import PluginHealthChecker
from plugins.core.runtime.job_dispatcher import dispatch_plugin_job
+from plugins.core.runtime.route_guard import PluginRouteStateGateway
from plugins.core.sdk import PluginHostContext, PluginRequestContext, await_plugin_callback
from plugins.core.sdk.version import HOST_API_VERSION
from plugins.core.validation.structure import PluginStructureChecker
@@ -48,6 +50,7 @@ def plugin() -> DiscoveredPlugin:
:return: 测试所需的插件及其清单
"""
+ assert PLUGIN_DIRECTORY is not None
root = Path(PLUGIN_DIRECTORY).resolve()
assert (root / 'plugin.yaml').is_file(), '指定的 Rust 交付目录不存在'
return PluginScanner(root.parent).load_manifest(root / 'plugin.yaml')
@@ -72,7 +75,9 @@ def test_distribution_contains_native_business_code_and_passes_static_discovery(
async def test_compiled_native_health_returns_rust_future(plugin: DiscoveredPlugin) -> None:
"""编译后的原生健康检查返回 Rust Future。"""
loader = PluginEntrypointLoader(plugin)
- callback = loader.load_callable(plugin.manifest.backend.health.checker)
+ checker = plugin.manifest.backend.health.checker
+ assert checker is not None
+ callback = loader.load_callable(checker)
assert not inspect.iscoroutinefunction(callback)
result = await PluginHealthChecker(plugin).check()
assert result.ok, result.error
@@ -92,7 +97,7 @@ async def fake_session() -> AsyncGenerator[object, None]:
async def test_real_native_subapp_uses_host_auth_lifespan_and_python_service(plugin: DiscoveredPlugin) -> None:
"""真实原生子应用使用宿主认证、生命周期和 Python 服务。"""
app = FastAPI()
- gateway = SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True))
+ gateway = Mock(spec_set=PluginRouteStateGateway, is_plugin_enabled=AsyncMock(return_value=True))
runtime = ExplicitPluginRuntime(gateway)
user = SimpleNamespace(user=SimpleNamespace(user_id=7), permissions=['rust_demo:view', 'rust_demo:profile'])
profile = SimpleNamespace(
@@ -110,7 +115,9 @@ async def test_real_native_subapp_uses_host_auth_lifespan_and_python_service(plu
runtime.prepare(RegisteredPlugin(plugin, None, True, 'installed'), app, startup_write_enabled=False)
await runtime.activate('rust_demo', app)
try:
- assert runtime.loaded['rust_demo'].lifespan.state == {'nativeReady': True}
+ lifespan = runtime.loaded['rust_demo'].lifespan
+ assert lifespan is not None
+ assert lifespan.state == {'nativeReady': True}
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client:
assert (await client.get('/apps/rust_demo/api/info')).status_code == status.HTTP_401_UNAUTHORIZED
headers = {'Authorization': 'Bearer test-token'}
@@ -122,6 +129,7 @@ async def test_real_native_subapp_uses_host_auth_lifespan_and_python_service(plu
response = await client.get('/apps/rust_demo/api/profile', headers=headers)
assert response.json()['userName'] == 'rust-user'
assert 'password' not in response.json()
+ assert service.await_args is not None
assert service.await_args.args[1] == user.user.user_id
response = await client.post(
'/apps/rust_demo/api/echo/item-7?tag=first&tag=second',
@@ -144,7 +152,7 @@ async def test_real_native_subapp_uses_host_auth_lifespan_and_python_service(plu
assert response.status_code == status.HTTP_403_FORBIDDEN
finally:
await runtime.shutdown()
- assert not runtime.loaded['rust_demo'].lifespan.ready
+ assert not lifespan.ready
@pytest.mark.asyncio
@@ -208,12 +216,13 @@ async def failed_service(context: PluginRequestContext) -> None:
async def test_real_native_router_gets_host_context_and_permissions(plugin: DiscoveredPlugin) -> None:
"""真实原生路由获取宿主上下文及权限。"""
manifest = plugin.manifest.model_copy(deep=True)
+ assert isinstance(manifest, PluginManifestV2)
manifest.backend.integration = 'router'
manifest.backend.asgi = None
manifest.backend.entrypoint = 'ruoyi_plugin_rust_demo._native:create_router_plugin'
router_plugin = replace(plugin, manifest=manifest)
app = FastAPI()
- gateway = SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True))
+ gateway = Mock(spec_set=PluginRouteStateGateway, is_plugin_enabled=AsyncMock(return_value=True))
runtime = ExplicitPluginRuntime(gateway)
user = SimpleNamespace(user=SimpleNamespace(user_id=7), permissions=['rust_demo:view', 'rust_demo:profile'])
@@ -279,7 +288,7 @@ async def permission_error(request: object, exc: PermissionException) -> JSONRes
async def test_real_scheduler_invokes_rust_awaitable_through_persistent_dispatcher(plugin: DiscoveredPlugin) -> None:
"""真实调度器通过持久化分派器等待 Rust 结果。"""
app = FastAPI()
- gateway = SimpleNamespace(is_plugin_enabled=AsyncMock(return_value=True))
+ gateway = Mock(spec_set=PluginRouteStateGateway, is_plugin_enabled=AsyncMock(return_value=True))
runtime = ExplicitPluginRuntime(gateway)
scheduler = AsyncIOScheduler()
completed = asyncio.get_running_loop().create_future()
diff --git a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_i18n.py b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_i18n.py
index 80bf122e4..871ad7310 100644
--- a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_i18n.py
+++ b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_i18n.py
@@ -1,11 +1,12 @@
import json
from collections.abc import AsyncIterator
from pathlib import Path
-from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
import pytest
import yaml
+from agno.agent import Agent
+from sqlalchemy.ext.asyncio import AsyncSession
from cli.runtime.plugin.support import PluginDependencyLockfileTemplateBuilder
from common.context import LocaleContext, RequestContext
@@ -54,8 +55,8 @@ async def broken_stream(*args: object, **kwargs: object) -> AsyncIterator[object
yield
stream = AiChatService._stream_agent(
- agent=SimpleNamespace(arun=broken_stream),
- chat_req=AiChatRequestModel(modelId=1, message='请保留这段用户输入'),
+ agent=Mock(spec=Agent, arun=broken_stream),
+ chat_req=AiChatRequestModel(model_id=1, message='请保留这段用户输入'),
run_kwargs={},
is_reasoning=False,
session_id='session',
@@ -83,7 +84,7 @@ async def test_stream_setup_failure_is_a_localized_event(monkeypatch: pytest.Mon
"""验证流初始化失败时返回本地化错误事件。"""
monkeypatch.setattr(AiModelDao, 'get_ai_model_detail_by_id', AsyncMock(return_value=None))
stream = AiChatService.chat_services(
- object(), AiChatRequestModel(modelId=1, message='Hello'), 1, locale_context=LocaleContext('en-US')
+ AsyncSession(), AiChatRequestModel(model_id=1, message='Hello'), 1, locale_context=LocaleContext('en-US')
)
events = [json.loads(frame) async for frame in stream]
assert events == [
diff --git a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_plugin.py b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_plugin.py
index 90cd6c0f7..231b21eba 100644
--- a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_plugin.py
+++ b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_plugin.py
@@ -2,12 +2,13 @@
from pathlib import Path
import pytest
-from sqlalchemy.ext.asyncio import create_async_engine
+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from config.database import DataSourceRegistry
from config.env import DataBaseConfig
from plugins.ai.dao.ai_chat_dao import AiChatConfigDao
from plugins.ai.dao.ai_model_dao import AiModelDao
+from plugins.ai.entity.do.ai_model_do import AiModels
from plugins.ai.entity.vo.ai_chat_vo import AiChatConfigModel, AiChatRequestModel
from plugins.ai.service.ai_chat_service import AiChatService
from plugins.ai.utils.ai_util import AiUtil
@@ -111,10 +112,10 @@ def test_ai_plugin_runtime_paths_exist(frontend_framework: str) -> None:
[plugin],
[
PluginModel(
- pluginId='ai',
- pluginName='AI 管理',
+ plugin_id='ai',
+ plugin_name='AI 管理',
version='0.1.0',
- installedVersion='0.1.0',
+ installed_version='0.1.0',
enabled='0',
status='installed',
)
@@ -162,7 +163,7 @@ async def fake_get_chat_config_detail_by_user_id(*_args: object, **_kwargs: obje
fake_get_chat_config_detail_by_user_id,
)
- result = await AiChatService.ai_chat_config_detail_services(query_db=object(), user_id=1)
+ result = await AiChatService.ai_chat_config_detail_services(query_db=AsyncSession(), user_id=1)
assert isinstance(result, AiChatConfigModel)
assert result.num_history_runs == EXPECTED_DEFAULT_NUM_HISTORY_RUNS
@@ -184,8 +185,8 @@ async def fake_get_ai_model_detail_by_id(*_args: object, **_kwargs: object) -> N
monkeypatch.setattr(AiModelDao, 'get_ai_model_detail_by_id', fake_get_ai_model_detail_by_id)
stream = AiChatService.chat_services(
- query_db=object(),
- chat_req=AiChatRequestModel(modelId=404, message='hi'),
+ query_db=AsyncSession(),
+ chat_req=AiChatRequestModel(model_id=404, message='hi'),
user_id=1,
)
@@ -205,7 +206,7 @@ async def fake_get_ai_model_detail_by_id(*_args: object, **_kwargs: object) -> N
async def test_ai_chat_services_rejects_disabled_model(monkeypatch: pytest.MonkeyPatch) -> None:
"""校验 AI 对话不能使用已停用模型。"""
- async def fake_get_ai_model_detail_by_id(*_args: object, **_kwargs: object) -> dict[str, object]:
+ async def fake_get_ai_model_detail_by_id(*_args: object, **_kwargs: object) -> AiModels:
"""
返回测试用 AI 模型配置。
@@ -213,22 +214,22 @@ async def fake_get_ai_model_detail_by_id(*_args: object, **_kwargs: object) -> d
:param _kwargs: 调用方按名称传入的附加选项
:return: 测试用 AI 模型配置
"""
- return {
- 'model_id': 1,
- 'model_code': 'gpt-4o-mini',
- 'model_name': 'GPT',
- 'provider': 'OpenAI',
- 'api_key': 'encrypted',
- 'status': '1',
- 'support_reasoning': 'N',
- 'support_images': 'N',
- }
+ return AiModels(
+ model_id=1,
+ model_code='gpt-4o-mini',
+ model_name='GPT',
+ provider='OpenAI',
+ api_key='encrypted',
+ status='1',
+ support_reasoning='N',
+ support_images='N',
+ )
monkeypatch.setattr(AiModelDao, 'get_ai_model_detail_by_id', fake_get_ai_model_detail_by_id)
stream = AiChatService.chat_services(
- query_db=object(),
- chat_req=AiChatRequestModel(modelId=1, message='hi'),
+ query_db=AsyncSession(),
+ chat_req=AiChatRequestModel(model_id=1, message='hi'),
user_id=1,
)
@@ -345,3 +346,10 @@ def test_ai_plugin_sql_assets_own_ai_schema_and_seed_data() -> None:
assert 'comment on column' in postgres_migration
assert 'auto_increment' not in postgres_migration
assert 'engine=innodb' not in postgres_migration
+
+
+@pytest.mark.parametrize(('user_temperature', 'expected'), [(0.0, 0.0), (None, 0.75)])
+def test_chat_temperature_respects_zero(user_temperature: float | None, expected: float) -> None:
+ """用户设置零温度时保留该值,未设置时采用模型默认值。"""
+ config = AiChatConfigModel(temperature=user_temperature)
+ assert AiChatService._resolve_temperature(config, AiModels(temperature=0.75)) == expected
diff --git a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_react_integration.py b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_react_integration.py
index f0f2e6ca2..1f07ee8c7 100644
--- a/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_react_integration.py
+++ b/ruoyi-fastapi-backend/tests/plugins/sample_plugins/test_ai_react_integration.py
@@ -2,8 +2,10 @@
from pathlib import Path
from types import SimpleNamespace
from typing import TYPE_CHECKING
+from unittest.mock import Mock
import pytest
+from agno.agent import Agent
from agno.run.agent import RunEvent
from cli.runtime.plugin.support import PluginDependencyLockfileTemplateBuilder
@@ -21,13 +23,13 @@
if TYPE_CHECKING:
from collections.abc import AsyncIterator
- from plugins.core.manifest.schema import PluginManifest
+ from plugins.core.manifest.v2 import VersionedPluginManifest
BACKEND_ROOT = Path(__file__).resolve().parents[3]
REACT_ROOT = BACKEND_ROOT.parent / 'ruoyi-fastapi-frontend' / 'react' / 'web'
-def load_ai_manifest() -> 'PluginManifest':
+def load_ai_manifest() -> 'VersionedPluginManifest':
"""
加载实际 AI 插件清单,避免用测试清单掩盖发布遗漏。
@@ -69,6 +71,7 @@ def test_ai_react_dependencies_match_host_and_install_plan(tmp_path: Path) -> No
assert any(expected_markstream in item.command for item in plan.items)
lockfile = PluginDependencyLockfileTemplateBuilder.build(manifest, frontend_root=root).to_dict()
assert lockfile['frontendFramework'] == 'react'
+ assert isinstance(lockfile['npm'], list)
assert {item['name'] for item in lockfile['npm']} == expected_packages
assert lockfile['npmDev'] == []
@@ -86,31 +89,27 @@ async def test_ai_stream_preserves_react_markdown_and_existing_vue_protocol(reas
SimpleNamespace(event=RunEvent.run_completed, metrics=SimpleNamespace(to_dict=lambda: {'input_tokens': 3})),
]
- class FakeAgent:
- """离线流式 Agent,不请求模型或数据库。"""
+ async def stream_chunks() -> 'AsyncIterator[SimpleNamespace]':
+ """
+ 按原始顺序提供测试中的模型事件。
- async def arun(self, message: str, **kwargs) -> 'AsyncIterator[SimpleNamespace]':
- """
- 逐段返回测试模型事件。
-
- :param message: 与当前结果一起返回的说明
- :param kwargs: 传给被调用对象的关键字参数
- :yield: 逐项产生的 ``chunk``
- """
- assert message == '你好'
- assert kwargs == {'stream': True, 'stream_events': True}
- for chunk in chunks:
- yield chunk
+ :yield: 单个模型事件
+ """
+ for chunk in chunks:
+ yield chunk
+ agent = Mock(spec_set=Agent)
+ agent.arun.return_value = stream_chunks()
request = AiChatRequestModel.model_validate(
{'modelId': 1, 'sessionId': 'session-test', 'message': '你好', 'isReasoning': reasoning_enabled}
)
frames = [
frame
async for frame in AiChatService._stream_agent(
- FakeAgent(), request, {'stream': True, 'stream_events': True}, reasoning_enabled, 'session-test'
+ agent, request, {'stream': True, 'stream_events': True}, reasoning_enabled, 'session-test'
)
]
+ agent.arun.assert_called_once_with('你好', stream=True, stream_events=True)
assert all(frame.endswith('\n') for frame in frames)
events = [json.loads(frame) for frame in frames]
assert events[0] == {'type': 'meta', 'session_id': 'session-test'}
diff --git a/ruoyi-fastapi-backend/tests/redis_helpers.py b/ruoyi-fastapi-backend/tests/redis_helpers.py
index 54156076b..eab46eb10 100644
--- a/ruoyi-fastapi-backend/tests/redis_helpers.py
+++ b/ruoyi-fastapi-backend/tests/redis_helpers.py
@@ -5,7 +5,7 @@
import subprocess
import tempfile
import time
-from collections.abc import Iterator
+from collections.abc import Generator
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
@@ -18,10 +18,19 @@
STARTUP_TIMEOUT_SECONDS = 5
DEFAULT_REDIS_PORT = 6379
ABSOLUTE_EXPIRY_SCRIPT = """
-local ttl = redis.call('PTTL', KEYS[1])
-if ttl < 0 then return ttl end
-local clock = redis.call('TIME')
-return tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000) + ttl
+local deadline = redis.pcall('PEXPIRETIME', KEYS[1])
+if type(deadline) == 'number' then return deadline end
+
+-- Redis 6.2 只有相对 TTL,前后两次采样一致时才能与中间的服务器时间相加。
+for attempt = 1, 10 do
+ local ttl = redis.call('PTTL', KEYS[1])
+ if ttl < 0 then return ttl end
+ local clock = redis.call('TIME')
+ if redis.call('PTTL', KEYS[1]) == ttl then
+ return tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000) + ttl
+ end
+end
+return redis.error_reply('无法取得同一毫秒的 TTL 和服务器时间')
"""
@@ -77,7 +86,7 @@ def available_loopback_port() -> int:
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
listener.bind(('127.0.0.1', 0))
- port = listener.getsockname()[1]
+ port = int(listener.getsockname()[1])
if port == DEFAULT_REDIS_PORT:
raise RuntimeError('Refusing to use the default Redis port for an isolated test')
return port
@@ -100,7 +109,7 @@ def stop_redis_process(process: subprocess.Popen) -> None:
@contextmanager
-def isolated_redis_server(executable: str) -> Iterator[IsolatedRedisServer]:
+def isolated_redis_server(executable: str) -> Generator[IsolatedRedisServer, None, None]:
"""
启动隔离 Redis,Linux 使用临时套接字,Windows 使用动态回环端口。
diff --git a/ruoyi-fastapi-backend/tests/scheduler_helpers.py b/ruoyi-fastapi-backend/tests/scheduler_helpers.py
index b3533acca..2589c68c5 100644
--- a/ruoyi-fastapi-backend/tests/scheduler_helpers.py
+++ b/ruoyi-fastapi-backend/tests/scheduler_helpers.py
@@ -12,10 +12,10 @@
import pytest
import pytest_asyncio
from apscheduler.schedulers.asyncio import AsyncIOScheduler
-from sqlalchemy import MetaData, create_engine, event, func, select
+from sqlalchemy import Connection, MetaData, create_engine, event, func, select
from sqlalchemy.engine import Engine
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
-from sqlalchemy.orm import Session
+from sqlalchemy.orm import Session, sessionmaker
import module_task.scheduler_test as task_module
from config.scheduler.dispatcher import SchedulerDispatcher
@@ -46,7 +46,7 @@ def init_execution_process(database_url: str) -> None:
:param database_url: 隔离测试数据库连接地址
"""
engine = create_engine(database_url)
- JobExecutionStore.session = staticmethod(lambda: Session(engine, expire_on_commit=False))
+ pytest.MonkeyPatch().setattr(JobExecutionStore, 'session', sessionmaker(engine, expire_on_commit=False))
def held_process_job(directory: str) -> int:
@@ -91,19 +91,20 @@ def harmless_job(value: str = 'done') -> str:
async def held_job() -> None:
"""保持一次异步执行,用于验证手动与 Cron 共享并发上限。"""
CALLS.append('held')
+ assert STARTED is not None and RELEASE is not None
STARTED.set()
await RELEASE.wait()
-def job_info(**changes) -> JobModel:
+def job_info(**changes: object) -> JobModel:
"""
构造使用未来 Cron 的无业务副作用任务。
:param changes: 需要覆盖的任务字段
:return: 测试任务对象
"""
- return JobModel(
- **{
+ return JobModel.model_validate(
+ {
'jobId': 42,
'jobName': 'runtime verification',
'jobGroup': 'default',
@@ -127,6 +128,7 @@ class Runtime:
:ivar engine: 隔离测试数据库引擎
:ivar sessions: 异步数据库会话工厂
+ :ivar publish: 记录调度通知的 Redis 发布调用
:ivar scheduler: 隔离测试调度器
:ivar started: 是否已经完成启动
:ivar release: 释放资源或同步等待的信号
@@ -137,6 +139,7 @@ class Runtime:
scheduler: AsyncIOScheduler
started: asyncio.Event
release: asyncio.Event
+ publish: AsyncMock
async def save(self, job: JobModel | None = None) -> JobModel:
"""
@@ -161,6 +164,7 @@ async def execution(self, execution_id: str) -> dict:
"""
async with self.sessions() as db:
result = await JobRuntimeDao.get_execution(db, execution_id)
+ assert result is not None, execution_id
return JobRuntimeDao.execution_result(result)
async def wait_execution(self, execution_id: str, expected: set[str]) -> dict:
@@ -172,13 +176,15 @@ async def wait_execution(self, execution_id: str, expected: set[str]) -> dict:
:return: 符合预期的执行状态
:raises AssertionError: 截止时间内没有观察到预期执行状态
"""
- deadline = asyncio.get_running_loop().time() + 5
- while asyncio.get_running_loop().time() < deadline:
- result = await self.execution(execution_id)
- if result['status'] in expected:
- return result
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + 5
+ last_result = None
+ while loop.time() < deadline:
+ last_result = await self.execution(execution_id)
+ if last_result['status'] in expected:
+ return last_result
await asyncio.sleep(0.01)
- raise AssertionError(result)
+ raise AssertionError(f'任务 {execution_id} 未达到预期状态 {expected},最后一次查询结果为 {last_result}')
@pytest_asyncio.fixture
@@ -196,14 +202,14 @@ async def runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncItera
path = tmp_path / 'scheduler-runtime.db'
engine = create_engine(f'sqlite:///{path}')
metadata = MetaData()
- definition = SysJob.__table__.to_metadata(metadata)
+ definition = SysJob.metadata.tables[SysJob.__tablename__].to_metadata(metadata)
# SQLite仅为INTEGER主键分配自增ID;测试副本关闭BIGINT自增并使用插入事件模拟。
definition.c.job_id.autoincrement = False
- SysJobSync.__table__.to_metadata(metadata)
- SysJobExecution.__table__.to_metadata(metadata)
+ for model in (SysJobSync, SysJobExecution):
+ model.metadata.tables[model.__tablename__].to_metadata(metadata)
metadata.create_all(engine)
- def assign_sqlite_id(_mapper: object, connection: object, target: SysJob) -> None:
+ def assign_sqlite_id(_mapper: object, connection: Connection, target: SysJob) -> None:
"""
为 SQLite 测试模拟真实 MySQL/PostgreSQL 的数据库任务 ID 分配。
@@ -212,7 +218,7 @@ def assign_sqlite_id(_mapper: object, connection: object, target: SysJob) -> Non
:param target: 任务模型实例
"""
if target.job_id is None:
- target.job_id = connection.scalar(select(func.coalesce(func.max(SysJob.job_id), 0) + 1))
+ target.job_id = connection.execute(select(func.coalesce(func.max(SysJob.job_id), 0) + 1)).scalar_one()
event.listen(SysJob, 'before_insert', assign_sqlite_id)
async_engine = create_async_engine(f'sqlite+aiosqlite:///{path}')
@@ -224,9 +230,10 @@ def assign_sqlite_id(_mapper: object, connection: object, target: SysJob) -> Non
},
)
scheduler.start(paused=True)
- patch_runtime_globals(monkeypatch, scheduler, sessions, engine)
+ env = Runtime(engine, sessions, scheduler, STARTED, RELEASE, publish=AsyncMock())
+ patch_runtime_globals(monkeypatch, env)
try:
- yield Runtime(engine, sessions, scheduler, STARTED, RELEASE)
+ yield env
finally:
RELEASE.set()
pending = list(scheduler._executors['default']._pending_futures)
@@ -264,29 +271,25 @@ def patch_scheduler_components(monkeypatch: pytest.MonkeyPatch, scheduler: Async
def patch_runtime_globals(
monkeypatch: pytest.MonkeyPatch,
- scheduler: AsyncIOScheduler,
- sessions: async_sessionmaker[AsyncSession],
- engine: Engine,
+ env: Runtime,
) -> None:
"""
隔离调度器单例和数据库工厂,测试结束由 monkeypatch 逐项恢复。
:param monkeypatch: 测试替换对象
- :param scheduler: 隔离测试调度器
- :param sessions: 异步数据库会话工厂
- :param engine: 隔离测试数据库引擎
+ :param env: 提供调度器、数据库和通知模拟对象的测试环境
"""
monkeypatch.setattr(task_module, 'runtime_harmless', harmless_job, raising=False)
monkeypatch.setattr(task_module, 'runtime_held', held_job, raising=False)
- patch_scheduler_components(monkeypatch, scheduler)
+ patch_scheduler_components(monkeypatch, env.scheduler)
monkeypatch.setattr(SchedulerManager, '_is_leader', True)
- monkeypatch.setattr(SchedulerManager, '_redis', SimpleNamespace(publish=AsyncMock()))
+ monkeypatch.setattr(SchedulerManager, '_redis', SimpleNamespace(publish=env.publish))
monkeypatch.setattr(SchedulerManager, '_sync_lock', asyncio.Lock())
monkeypatch.setattr(SchedulerManager, '_sync_pending_ids', set())
monkeypatch.setattr(SchedulerManager, '_sync_full_pending', False)
monkeypatch.setattr(SchedulerManager, '_sync_pending', False)
monkeypatch.setattr(SchedulerManager, '_sync_task', None)
monkeypatch.setattr(SchedulerManager, '_last_sync_at', None)
- monkeypatch.setattr(SchedulerManager._resources, 'session', sessions)
+ monkeypatch.setattr(SchedulerManager._resources, 'session', env.sessions)
monkeypatch.setattr(SchedulerManager._listener, 'persist_log', lambda _log: None)
- monkeypatch.setattr(JobExecutionStore, 'session', staticmethod(lambda: Session(engine, expire_on_commit=False)))
+ monkeypatch.setattr(JobExecutionStore, 'session', staticmethod(lambda: Session(env.engine, expire_on_commit=False)))
diff --git a/ruoyi-fastapi-backend/tests/scripts/test_migrate_legacy_files.py b/ruoyi-fastapi-backend/tests/scripts/test_migrate_legacy_files.py
index 88a2d74c9..30c98ac9a 100644
--- a/ruoyi-fastapi-backend/tests/scripts/test_migrate_legacy_files.py
+++ b/ruoyi-fastapi-backend/tests/scripts/test_migrate_legacy_files.py
@@ -141,6 +141,7 @@ def test_migrate_legacy_files_writes_file_info_model_and_commits(tmp_path: Path)
result = asyncio.run(migrate_legacy_files(batch_size=1, maintenance_confirmed=True))
assert result == (1, 0)
+ assert add_file_info.await_args is not None
file_info = add_file_info.await_args.args[1]
assert isinstance(file_info, FileInfoModel)
assert file_info.storage_type == 'local'
diff --git a/ruoyi-fastapi-backend/tests/server/test_oidc_cors_refresh.py b/ruoyi-fastapi-backend/tests/server/test_oidc_cors_refresh.py
index b7314198e..d950ec9b6 100644
--- a/ruoyi-fastapi-backend/tests/server/test_oidc_cors_refresh.py
+++ b/ruoyi-fastapi-backend/tests/server/test_oidc_cors_refresh.py
@@ -2,6 +2,7 @@
from unittest.mock import AsyncMock
import pytest
+from fastapi import FastAPI
from config.env import OidcConfig
from module_identity.service.runtime_service import OidcRuntimeService
@@ -11,7 +12,8 @@
async def test_registered_cors_changes_reach_other_workers_and_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:
"""注册的跨域规则变更传达到其他进程且失败时拒绝访问。"""
monkeypatch.setattr(OidcConfig, 'oidc_enabled', True)
- state = {'version': '0', 'origins': ('https://old.example',)}
+ version = 0
+ origins: tuple[str, ...] = ('https://old.example',)
async def get(_key: str) -> str:
"""
@@ -20,7 +22,7 @@ async def get(_key: str) -> str:
:param _key: 回调接收的查找键
:return: 测试存储中的指定键
"""
- return state['version']
+ return str(version)
async def incr(_key: str) -> None:
"""
@@ -28,7 +30,8 @@ async def incr(_key: str) -> None:
:param _key: 回调接收的查找键
"""
- state['version'] = str(int(state['version']) + 1)
+ nonlocal version
+ version += 1
async def load() -> tuple[str, ...]:
"""
@@ -36,22 +39,20 @@ async def load() -> tuple[str, ...]:
:return: 为当前测试准备的密钥
"""
- return state['origins']
+ return origins
redis = SimpleNamespace(get=get, incr=incr)
- worker_a = SimpleNamespace(state=SimpleNamespace(redis=redis))
- worker_b = SimpleNamespace(state=SimpleNamespace(redis=redis))
+ worker_a, worker_b = FastAPI(), FastAPI()
monkeypatch.setattr(OidcRuntimeService, 'load_cors_origins', load)
for app in (worker_a, worker_b):
+ app.state.redis = redis
await OidcRuntimeService.ensure_cors_snapshot(app)
- state['origins'] = ('https://new.example',)
+ origins = ('https://new.example',)
await OidcRuntimeService.cors_snapshot_callback(worker_a)()
await OidcRuntimeService.ensure_cors_snapshot(worker_b)
- assert (
- worker_a.state.oidc_registered_cors_origins == worker_b.state.oidc_registered_cors_origins == state['origins']
- )
+ assert worker_a.state.oidc_registered_cors_origins == worker_b.state.oidc_registered_cors_origins == origins
# 有时限的缓存兜底无需依赖变更通知
- state['origins'] = ()
+ origins = ()
worker_b.state.oidc_cors_loaded_at = 0
await OidcRuntimeService.ensure_cors_snapshot(worker_b)
assert worker_b.state.oidc_registered_cors_origins == ()
diff --git a/ruoyi-fastapi-backend/tests/server/test_oidc_runtime.py b/ruoyi-fastapi-backend/tests/server/test_oidc_runtime.py
index 504b76ca1..30aba4a3c 100644
--- a/ruoyi-fastapi-backend/tests/server/test_oidc_runtime.py
+++ b/ruoyi-fastapi-backend/tests/server/test_oidc_runtime.py
@@ -1,10 +1,12 @@
import asyncio
-from collections.abc import AsyncGenerator
+from collections.abc import AsyncGenerator, Coroutine
from contextlib import asynccontextmanager
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import pytest
+from fastapi import FastAPI
+from redis.asyncio import Redis
from module_identity.service.key_service import KeyServiceError
from module_identity.service.runtime_service import OidcRuntimeService
@@ -31,7 +33,8 @@ async def test_oidc_runtime_validation_is_a_noop_when_disabled() -> None:
@pytest.mark.asyncio
async def test_cors_snapshot_callback_fails_closed_without_raising() -> None:
"""管理提交后的 CORS 刷新失败时运行时快照必须进入拒绝态。"""
- app = SimpleNamespace(state=SimpleNamespace(oidc_registered_cors_origins=('https://old.example',)))
+ app = FastAPI()
+ app.state.oidc_registered_cors_origins = ('https://old.example',)
with patch.object(OidcRuntimeService, 'refresh_cors_snapshot', new=AsyncMock(side_effect=RuntimeError('db down'))):
await OidcRuntimeService.cors_snapshot_callback(app)()
assert app.state.oidc_registered_cors_origins == ()
@@ -62,6 +65,7 @@ async def session() -> AsyncGenerator[object, None]:
await OidcRuntimeService.validate_runtime()
get_signing_key.assert_awaited_once()
+ assert get_signing_key.await_args is not None
assert get_signing_key.await_args.args == (db,)
@@ -96,12 +100,14 @@ async def session() -> AsyncGenerator[object, None]:
@pytest.mark.asyncio
async def test_background_loops_wait_in_both_leader_and_follower() -> None:
"""Leader 和 Follower 都启动循环,由每轮当前租约决定是否执行业务。"""
- app = SimpleNamespace(state=SimpleNamespace(redis=object(), application_leader=True))
+ app = FastAPI()
+ app.state.redis = object()
+ app.state.application_leader = True
fake_key_task = object()
fake_retry_task = object()
created: list[object] = []
- def create_task(coro: object) -> object:
+ def create_task(coro: Coroutine) -> object:
"""
创建测试任务并将其交给调用方。
@@ -170,9 +176,11 @@ async def session() -> AsyncGenerator[SimpleNamespace, None]:
pytest.raises(asyncio.CancelledError),
):
if loop == 'key':
- await OidcRuntimeService.key_lifecycle_loop(SimpleNamespace(state=SimpleNamespace(redis=object())))
+ app = FastAPI()
+ app.state.redis = object()
+ await OidcRuntimeService.key_lifecycle_loop(app)
else:
- await OidcRuntimeService.backchannel_retry_loop(object())
+ await OidcRuntimeService.backchannel_retry_loop(AsyncMock(spec=Redis))
expected_leader_periods = 2
assert (activate if loop == 'key' else consume).await_count == expected_leader_periods
@@ -180,10 +188,11 @@ async def session() -> AsyncGenerator[SimpleNamespace, None]:
@pytest.mark.asyncio
async def test_server_background_task_setup_delegates_oidc_runtime() -> None:
"""应用入口只负责装配通用任务和认证中心运行时。"""
- app = SimpleNamespace(state=SimpleNamespace(redis=object()))
+ app = FastAPI()
+ app.state.redis = object()
log_task = object()
- def create_task(coro: object) -> object:
+ def create_task(coro: Coroutine) -> object:
"""
创建测试任务并将其交给调用方。
diff --git a/ruoyi-fastapi-backend/tests/server/test_plugin_runtime.py b/ruoyi-fastapi-backend/tests/server/test_plugin_runtime.py
index 77b328a94..31d4e6790 100644
--- a/ruoyi-fastapi-backend/tests/server/test_plugin_runtime.py
+++ b/ruoyi-fastapi-backend/tests/server/test_plugin_runtime.py
@@ -1,8 +1,8 @@
from collections.abc import Awaitable, Callable
-from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, call, patch
import pytest
+from fastapi import FastAPI
from config.database import DataSourceRegistry
from config.env import AppConfig
@@ -69,6 +69,7 @@ async def test_initialize_application_runtime_delegates_plugin_steps() -> None:
log_success_enabled=True,
)
startup_call = fake_plugin_runtime.startup.await_args
+ assert startup_call is not None
assert startup_call.args == (fake_app,)
create_plugin_entity_tables = startup_call.kwargs['create_tables']
await create_plugin_entity_tables()
@@ -138,7 +139,7 @@ async def run_as_plugin_writer(
@pytest.mark.asyncio
async def test_lifespan_only_application_leader_outputs_banner_and_addresses() -> None:
"""校验仅Application leader输出横幅、成功摘要和访问地址。"""
- app = SimpleNamespace(state=SimpleNamespace())
+ app = FastAPI()
redis = MagicMock()
fake_logger = MagicMock()
fake_logger.complete = AsyncMock()
@@ -182,7 +183,7 @@ async def test_lifespan_only_application_leader_outputs_banner_and_addresses() -
@pytest.mark.asyncio
async def test_lifespan_non_leader_runs_local_initialization_without_display_logs() -> None:
"""校验非leader执行本地初始化,但不输出leader专属展示日志。"""
- app = SimpleNamespace(state=SimpleNamespace())
+ app = FastAPI()
redis = MagicMock()
fake_logger = MagicMock()
fake_logger.complete = AsyncMock()
@@ -215,7 +216,7 @@ async def test_lifespan_non_leader_runs_local_initialization_without_display_log
@pytest.mark.asyncio
async def test_lifespan_non_leader_initialization_error_propagates_and_still_cleans_up() -> None:
"""校验非leader初始化异常不被门禁吞掉,并继续执行finally清理。"""
- app = SimpleNamespace(state=SimpleNamespace())
+ app = FastAPI()
fake_logger = MagicMock()
fake_logger.complete = AsyncMock()
@@ -244,7 +245,7 @@ async def test_lifespan_non_leader_initialization_error_propagates_and_still_cle
@pytest.mark.asyncio
async def test_lifespan_skips_database_initialization_when_redis_creation_fails() -> None:
"""校验Redis前置初始化失败时不创建数据库资源,并执行幂等清理。"""
- app = SimpleNamespace(state=SimpleNamespace())
+ app = FastAPI()
database_registry = MagicMock()
database_registry.initialize = AsyncMock()
database_registry.dispose_all = AsyncMock()
@@ -271,7 +272,7 @@ async def test_lifespan_skips_database_initialization_when_redis_creation_fails(
@pytest.mark.asyncio
async def test_lifespan_database_initialization_failure_releases_redis_and_database_resources() -> None:
"""校验Redis和租约创建后数据库初始化失败仍走统一关闭流程。"""
- app = SimpleNamespace(state=SimpleNamespace())
+ app = FastAPI()
redis = MagicMock()
database_registry = MagicMock()
database_registry.initialize = AsyncMock(side_effect=RuntimeError('database unavailable'))
@@ -295,12 +296,9 @@ async def test_lifespan_database_initialization_failure_releases_redis_and_datab
async def test_shutdown_application_runtime_preserves_cleanup_order() -> None:
"""校验插件关闭先执行,随后按Scheduler、Redis、数据库顺序释放资源。"""
events: list[str] = []
- app = SimpleNamespace(
- state=SimpleNamespace(
- plugin_application_runtime_started=True,
- redis=object(),
- )
- )
+ app = FastAPI()
+ app.state.plugin_application_runtime_started = True
+ app.state.redis = object()
plugin_runtime = MagicMock()
async def record_plugin_shutdown(_app: object) -> None:
@@ -355,7 +353,8 @@ async def record_log_complete() -> None:
@pytest.mark.asyncio
async def test_shutdown_application_runtime_releases_resources_when_plugin_hook_fails() -> None:
"""校验插件关闭钩子失败时仍执行基础设施清理。"""
- app = SimpleNamespace(state=SimpleNamespace(plugin_application_runtime_started=True))
+ app = FastAPI()
+ app.state.plugin_application_runtime_started = True
plugin_runtime = MagicMock()
plugin_runtime.shutdown = AsyncMock(side_effect=RuntimeError('shutdown hook failed'))
@@ -374,7 +373,8 @@ async def test_shutdown_application_runtime_releases_resources_when_plugin_hook_
@pytest.mark.asyncio
async def test_stop_background_tasks_closes_redis_and_database_when_scheduler_close_fails() -> None:
"""校验Scheduler释放异常不会跳过Redis和数据库清理。"""
- app = SimpleNamespace(state=SimpleNamespace(redis=object()))
+ app = FastAPI()
+ app.state.redis = object()
with (
patch(
diff --git a/ruoyi-fastapi-backend/tests/sql/test_plugin_release_schema.py b/ruoyi-fastapi-backend/tests/sql/test_plugin_release_schema.py
index 8ac39b857..dbf04dd12 100644
--- a/ruoyi-fastapi-backend/tests/sql/test_plugin_release_schema.py
+++ b/ruoyi-fastapi-backend/tests/sql/test_plugin_release_schema.py
@@ -4,6 +4,7 @@
import pytest
from sqlalchemy import CheckConstraint
from sqlalchemy.dialects import mysql, postgresql
+from sqlalchemy.engine import Dialect
from sqlalchemy.schema import CreateTable
from plugins.core.lifecycle.script import PluginLifecycleScriptHelper
@@ -23,7 +24,7 @@ def test_initial_release_schema_matches_models(initial: str, time_type: str) ->
"""初始发布表结构与模型一致。"""
initialization = (SQL_ROOT / initial).read_text(encoding='utf-8')
statements = PluginLifecycleScriptHelper.split_sql_statements(initialization)
- for table in (SysPluginArtifact.__table__, SysPluginRelease.__table__, SysPluginWorker.__table__):
+ for table in (SysPluginArtifact.get_table(), SysPluginRelease.get_table(), SysPluginWorker.get_table()):
table_statements = [
statement
for statement in statements
@@ -49,9 +50,9 @@ def test_initial_release_schema_matches_models(initial: str, time_type: str) ->
@pytest.mark.parametrize('dialect', [mysql.dialect(), postgresql.dialect()])
-def test_release_orm_schema_compiles_for_supported_database_dialects(dialect: object) -> None:
+def test_release_orm_schema_compiles_for_supported_database_dialects(dialect: Dialect) -> None:
"""发布 ORM 结构可在支持的数据库方言中编译。"""
for model in (SysPluginArtifact, SysPluginRelease, SysPluginWorker):
- ddl = str(CreateTable(model.__table__).compile(dialect=dialect))
+ ddl = str(CreateTable(model.get_table()).compile(dialect=dialect))
assert model.__tablename__ in ddl
assert 'PRIMARY KEY' in ddl
diff --git a/ruoyi-fastapi-backend/tests/test_api_docs_auth.py b/ruoyi-fastapi-backend/tests/test_api_docs_auth.py
index b02f00faf..cff9dea5d 100644
--- a/ruoyi-fastapi-backend/tests/test_api_docs_auth.py
+++ b/ruoyi-fastapi-backend/tests/test_api_docs_auth.py
@@ -2,7 +2,7 @@
from collections.abc import AsyncIterator, Iterator
from copy import deepcopy
from types import SimpleNamespace
-from typing import Annotated
+from typing import TYPE_CHECKING, Annotated
from unittest.mock import AsyncMock
from uuid import UUID
@@ -12,7 +12,7 @@
from fastapi.security import APIKeyHeader, OAuth2PasswordBearer
from common.aspect.db_session import get_db_session_provider
-from common.aspect.pre_auth import CurrentUserDependency, PreAuthDependency
+from common.aspect.pre_auth import CurrentUserDependency, PreAuth, PreAuthDependency
from common.context import RequestContext
from config.env import AppConfig
from exceptions.exception import AuthException
@@ -22,6 +22,9 @@
from module_admin.service.login_service import LoginService, oauth2_scheme
from utils.server_util import APIDocsUtil
+if TYPE_CHECKING:
+ from common.auth_policy import ExcludeRoute
+
LOGIN_SECURITY = {'OAuth2PasswordBearer': []}
AUTHORIZATION = {'Authorization': 'Bearer valid'}
@@ -70,7 +73,7 @@ async def authenticate(request: Request, token: str, db: object, *, refresh_sess
current_user = CurrentUserModel(
permissions=['demo:read'],
roles=['reader'],
- user=UserInfoModel(userId=2, userName='reader'),
+ user=UserInfoModel(user_id=2, user_name='reader'),
)
RequestContext.set_current_user(current_user)
return current_user
@@ -446,7 +449,7 @@ async def test_public_login_exclusion_preserves_other_required_security(
) -> None:
"""排除登录要求时保留其他安全要求。"""
path = '/key/{name}' if conditional else '/key'
- rule = {'path': '/key/free' if conditional else path}
+ rule: ExcludeRoute = {'path': '/key/free' if conditional else path}
api_key = APIKeyHeader(name='X-API-Key', scheme_name='ServiceKey')
@docs_app.app.get(
@@ -636,7 +639,7 @@ async def test_duplicate_path_with_different_convertors_preserves_native_securit
docs_app: SimpleNamespace, public_first: bool, include_first: bool
) -> None:
"""同一路径使用不同转换器时保留原生安全要求。"""
- rule = {'path': '/duplicate-convertor/{value}'}
+ rule: ExcludeRoute = {'path': '/duplicate-convertor/{value}'}
@docs_app.app.get(
'/duplicate-convertor/{value:int}',
@@ -858,7 +861,7 @@ async def test_overlapping_public_values_respect_each_pre_auth_exception(
docs_app: SimpleNamespace, reallow: bool
) -> None:
"""公开值重叠时遵循每个预认证依赖的例外。"""
- rules = [{'path': '/overlap/{name}', 'ignore_paths': ['/overlap/free']}]
+ rules: list[ExcludeRoute] = [{'path': '/overlap/{name}', 'ignore_paths': ['/overlap/free']}]
if reallow:
rules.append({'path': '/overlap/free'})
@@ -935,6 +938,7 @@ async def mutable(name: str) -> dict:
assert before['description'].startswith(description)
assert before['x-login-auth']['mode'] == 'conditional'
original_cache = docs_app.app.openapi_schema
+ assert isinstance(pre_auth.dependency, PreAuth)
pre_auth.dependency.exclude_patterns.clear()
after = docs_app.app.openapi()['paths']['/mutable/{name}']['get']
assert docs_app.app.openapi_schema is original_cache
diff --git a/ruoyi-fastapi-backend/tests/test_audit_time_delegation.py b/ruoyi-fastapi-backend/tests/test_audit_time_delegation.py
index 333c838cc..b31cb58ef 100644
--- a/ruoyi-fastapi-backend/tests/test_audit_time_delegation.py
+++ b/ruoyi-fastapi-backend/tests/test_audit_time_delegation.py
@@ -10,11 +10,11 @@ def test_plugin_persistence_payload_ignores_client_audit_times() -> None:
now = datetime(2026, 8, 21, 12, 0, 0, tzinfo=UTC)
payload = PluginDao.dump_plugin_persistence_payload(
PluginModel(
- pluginId='demo',
- pluginName='Demo',
+ plugin_id='demo',
+ plugin_name='Demo',
version='1.0.0',
- createTime=now,
- updateTime=now,
+ create_time=now,
+ update_time=now,
)
)
@@ -26,10 +26,10 @@ def test_existing_migration_update_uses_onupdate_not_external_time() -> None:
"""迁移更新通过 onupdate 生成时间。"""
now = datetime(2026, 8, 21, 12, 0, 0, tzinfo=UTC)
payload = PluginMigrationModel(
- pluginId='demo',
- migrationPath='migrations/001.sql',
- migrationChecksum='checksum',
- updateTime=datetime(2000, 1, 1, tzinfo=UTC),
+ plugin_id='demo',
+ migration_path='migrations/001.sql',
+ migration_checksum='checksum',
+ update_time=datetime(2000, 1, 1, tzinfo=UTC),
).model_dump(exclude_unset=True)
PluginDao._apply_migration_observability_payload(payload, SysPluginMigration(), now)
diff --git a/ruoyi-fastapi-backend/tests/test_entity_time_columns.py b/ruoyi-fastapi-backend/tests/test_entity_time_columns.py
index 66527bd87..90afc9ea0 100644
--- a/ruoyi-fastapi-backend/tests/test_entity_time_columns.py
+++ b/ruoyi-fastapi-backend/tests/test_entity_time_columns.py
@@ -134,7 +134,7 @@
}
-def _column_default(model: type, field_name: str, attribute: str) -> object | None:
+def _column_default(model: type[Base], field_name: str, attribute: str) -> object | None:
"""
读取指定 ORM 列的默认值。
@@ -160,7 +160,7 @@ def test_audit_time_columns_preserve_nullability_and_migration_semantics() -> No
assert model.__table__.c.create_time.nullable is (model not in REQUIRED_CREATE_TIME_MODELS)
assert model.__table__.c.create_time.server_default is None
- assert SysPluginMigration.__table__.c.create_time.comment == '执行时间'
+ assert SysPluginMigration.get_table().c.create_time.comment == '执行时间'
def test_all_update_time_columns_use_callable_defaults_and_onupdate() -> None:
@@ -210,7 +210,7 @@ async def test_core_model_time_defaults_are_evaluated_per_insert_and_core_update
try:
async with engine.begin() as connection:
- await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.__table__])
+ await connection.run_sync(Base.metadata.create_all, tables=[SysPlugin.get_table()])
async with session_maker() as session:
first = SysPlugin(plugin_id='time-first', plugin_name='First', version='1.0.0')
@@ -232,6 +232,7 @@ async def test_core_model_time_defaults_are_evaluated_per_insert_and_core_update
update(SysPlugin).where(SysPlugin.plugin_id == first.plugin_id).values(version='1.1.0')
)
await session.refresh(first)
+ assert first.update_time is not None and first_update_time is not None
assert first.update_time > first_update_time
await asyncio.sleep(0.001)
@@ -240,6 +241,7 @@ async def test_core_model_time_defaults_are_evaluated_per_insert_and_core_update
[{'plugin_id': second.plugin_id, 'version': '1.1.0'}],
)
await session.refresh(second)
+ assert second.update_time is not None and second_update_time is not None
assert second.update_time > second_update_time
finally:
await engine.dispose()
diff --git a/ruoyi-fastapi-backend/tests/utils/test_application_leader_lease.py b/ruoyi-fastapi-backend/tests/utils/test_application_leader_lease.py
index 945dddf60..3ff4d0a2a 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_application_leader_lease.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_application_leader_lease.py
@@ -2,6 +2,7 @@
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from redis.asyncio import Redis
from utils.server_util import StartupUtil
@@ -46,7 +47,7 @@ async def get(self, key: str) -> str | None:
"""
return self.values.get(key)
- async def eval(self, script: str, _key_count: int, key: str, *args: object) -> int:
+ async def eval(self, script: str, _key_count: int, key: str, *args: str | int) -> int:
"""
模拟compare-and-expire和compare-and-delete脚本。
@@ -102,7 +103,8 @@ def test_application_lock_owner_token_is_stable_in_process_and_unique_between_pr
@pytest.mark.asyncio
async def test_application_leader_lease_only_accepts_current_owner() -> None:
"""校验不同owner token无法同时获得同一Application leader租约。"""
- redis = FakeLeaseRedis()
+ lease = FakeLeaseRedis()
+ redis = MagicMock(spec=Redis, wraps=lease)
first_acquired = await StartupUtil.acquire_application_leader(redis, 'app:leader', 'owner-1', 60)
repeated_acquired = await StartupUtil.acquire_application_leader(redis, 'app:leader', 'owner-1', 60)
@@ -116,9 +118,10 @@ async def test_application_leader_lease_only_accepts_current_owner() -> None:
@pytest.mark.asyncio
async def test_application_leader_renew_and_release_are_owner_safe() -> None:
"""校验非owner不能续期或删除已换主的Application leader租约。"""
- redis = FakeLeaseRedis()
- redis.values['app:leader'] = 'owner-2'
- redis.expires['app:leader'] = 60
+ lease = FakeLeaseRedis()
+ redis = MagicMock(spec=Redis, wraps=lease)
+ lease.values['app:leader'] = 'owner-2'
+ lease.expires['app:leader'] = 60
stale_renewed = await StartupUtil.renew_application_leader(
redis,
@@ -137,19 +140,20 @@ async def test_application_leader_renew_and_release_are_owner_safe() -> None:
assert stale_renewed is False
assert stale_released is False
assert owner_renewed is True
- assert redis.expires['app:leader'] == RENEWED_LEASE_SECONDS
+ assert lease.expires['app:leader'] == RENEWED_LEASE_SECONDS
owner_released = await StartupUtil.release_application_leader(redis, 'app:leader', 'owner-2')
assert owner_released is True
- assert 'app:leader' not in redis.values
+ assert 'app:leader' not in lease.values
@pytest.mark.asyncio
async def test_application_leader_renewal_reports_lock_loss() -> None:
"""校验owner不再匹配时续期任务会退出并通知Scheduler降级。"""
- redis = FakeLeaseRedis()
- redis.values['app:leader'] = 'new-owner'
+ lease = FakeLeaseRedis()
+ redis = MagicMock(spec=Redis, wraps=lease)
+ lease.values['app:leader'] = 'new-owner'
on_lock_lost = MagicMock()
renewal_task = StartupUtil.start_application_leader_renewal(
diff --git a/ruoyi-fastapi-backend/tests/utils/test_current_user_cache_util.py b/ruoyi-fastapi-backend/tests/utils/test_current_user_cache_util.py
index 57ef06a9f..abb9f7317 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_current_user_cache_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_current_user_cache_util.py
@@ -80,14 +80,28 @@ def user_model(user_id: int = USER_ID, permission: str = 'demo:read') -> Current
return CurrentUserModel(
permissions=[permission],
roles=['reader'],
- user=UserInfoModel(userId=user_id, userName='reader', status='0', delFlag='0'),
- appTimezone='Asia/Shanghai',
- pwdChrtype='2',
- isDefaultModifyPwd=True,
- isPasswordExpired=True,
+ user=UserInfoModel(user_id=user_id, user_name='reader', status='0', del_flag='0'),
+ app_timezone='Asia/Shanghai',
+ pwd_chrtype='2',
+ is_default_modify_pwd=True,
+ is_password_expired=True,
)
+async def read_miss_ticket(redis: Redis, user_id: int = USER_ID) -> CurrentUserCacheTicket:
+ """
+ 读取空缓存并确认本次查询取得了可用于回填的票据。
+
+ :param redis: 当前用例的隔离 Redis 客户端
+ :param user_id: 要读取的用户标识
+ :return: 本次缓存未命中时生成的票据
+ """
+ cached, ticket = await CurrentUserCacheUtil.read(redis, NAMESPACE, user_id, TTL_SECONDS)
+ assert cached is None
+ assert ticket is not None
+ return ticket
+
+
async def prime_cache(redis: Redis, user_id: int = USER_ID) -> CurrentUserModel:
"""
为指定用户预先填充测试缓存。
@@ -97,9 +111,7 @@ async def prime_cache(redis: Redis, user_id: int = USER_ID) -> CurrentUserModel:
:return: 当前操作对应的用户
"""
user = user_model(user_id)
- cached, ticket = await CurrentUserCacheUtil.read(redis, NAMESPACE, user_id, TTL_SECONDS)
- assert cached is None
- assert ticket is not None
+ ticket = await read_miss_ticket(redis, user_id)
assert await CurrentUserCacheUtil.write(redis, NAMESPACE, user_id, user, ticket)
return user
@@ -119,9 +131,11 @@ async def test_round_trip_isolates_models_and_omits_password_and_dynamic_fields(
cached.permissions.clear()
cached.user.nick_name = 'changed'
second, _ = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
+ assert second is not None
assert second.permissions == original.permissions
assert second.user.nick_name is None
snapshot = await cache_redis.hget(CurrentUserCacheUtil._keys(NAMESPACE, USER_ID)[2], 'payload')
+ assert snapshot is not None
payload = json.loads(snapshot)
assert set(payload) == {'permissions', 'roles', 'user'}
assert 'password' not in payload['user']
@@ -130,14 +144,16 @@ async def test_round_trip_isolates_models_and_omits_password_and_dynamic_fields(
@pytest.mark.asyncio
async def test_password_hash_is_never_serialized(cache_redis: Redis) -> None:
"""密码哈希不参与序列化。"""
- _, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
+ ticket = await read_miss_ticket(cache_redis)
user = user_model()
user.user.password = 'secret-hash'
assert await CurrentUserCacheUtil.write(cache_redis, NAMESPACE, USER_ID, user, ticket)
payload = await cache_redis.hget(CurrentUserCacheUtil._keys(NAMESPACE, USER_ID)[2], 'payload')
+ assert isinstance(payload, str)
assert 'secret-hash' not in payload
assert 'password' not in json.loads(payload)['user']
cached, _ = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
+ assert cached is not None
assert cached.user.password is None
@@ -145,11 +161,12 @@ async def test_password_hash_is_never_serialized(cache_redis: Redis) -> None:
@pytest.mark.parametrize('shared', [False, True])
async def test_invalidation_rejects_old_query_results(cache_redis: Redis, shared: bool) -> None:
"""缓存失效后拒绝旧查询结果。"""
- _, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
+ ticket = await read_miss_ticket(cache_redis)
assert await CurrentUserCacheUtil.invalidate(cache_redis, NAMESPACE, None if shared else {USER_ID})
assert not await CurrentUserCacheUtil.write(cache_redis, NAMESPACE, USER_ID, user_model(), ticket)
cached, replacement = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
assert cached is None
+ assert replacement is not None
assert (replacement.global_epoch, replacement.user_epoch) != (ticket.global_epoch, ticket.user_epoch)
@@ -167,7 +184,7 @@ async def query_and_fill() -> bool:
:return: 是否使用读取票据回填用户缓存
"""
- _, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
+ ticket = await read_miss_ticket(cache_redis)
prepared.append(ticket)
if len(prepared) == query_count:
all_started.set()
@@ -216,7 +233,7 @@ async def test_missing_epoch_never_restores_existing_snapshot(cache_redis: Redis
@pytest.mark.asyncio
async def test_fixed_deadline_is_not_extended_by_slow_fill_or_reads(cache_redis: Redis) -> None:
"""慢速写入或读取不会延长固定截止时间。"""
- _, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
+ ticket = await read_miss_ticket(cache_redis)
await asyncio.sleep(0.03)
assert await CurrentUserCacheUtil.write(cache_redis, NAMESPACE, USER_ID, user_model(), ticket)
snapshot_key = CurrentUserCacheUtil._keys(NAMESPACE, USER_ID)[2]
@@ -257,7 +274,7 @@ async def test_invalidation_expires_user_epochs_but_keeps_global_epoch(cache_red
@pytest.mark.asyncio
async def test_query_past_its_original_deadline_cannot_fill(cache_redis: Redis) -> None:
"""查询超过初始截止时间后不能回填。"""
- _, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
+ ticket = await read_miss_ticket(cache_redis)
expired = replace(ticket, created_at_ms=ticket.created_at_ms - TTL_MS, deadline_ms=ticket.created_at_ms - 1)
assert not await CurrentUserCacheUtil.write(cache_redis, NAMESPACE, USER_ID, user_model(), expired)
assert await cache_redis.exists(CurrentUserCacheUtil._keys(NAMESPACE, USER_ID)[2]) == 0
@@ -266,18 +283,19 @@ async def test_query_past_its_original_deadline_cannot_fill(cache_redis: Redis)
@pytest.mark.asyncio
async def test_late_older_query_cannot_replace_newer_snapshot(cache_redis: Redis) -> None:
"""迟到的旧查询不能替换较新的快照。"""
- _, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
+ ticket = await read_miss_ticket(cache_redis)
older = replace(ticket, created_at_ms=ticket.created_at_ms - 100)
assert await CurrentUserCacheUtil.write(cache_redis, NAMESPACE, USER_ID, user_model(permission='new'), ticket)
assert not await CurrentUserCacheUtil.write(cache_redis, NAMESPACE, USER_ID, user_model(permission='old'), older)
cached, _ = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
+ assert cached is not None
assert cached.permissions == ['new']
@pytest.mark.asyncio
async def test_shorter_configured_ttl_does_not_accept_previously_longer_snapshot(cache_redis: Redis) -> None:
"""缩短配置有效期后拒绝原先寿命更长的快照。"""
- _, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
+ ticket = await read_miss_ticket(cache_redis)
old = replace(ticket, created_at_ms=ticket.created_at_ms - TTL_MS)
assert await CurrentUserCacheUtil.write(cache_redis, NAMESPACE, USER_ID, user_model(), old)
assert (await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS * 2))[0] is not None
@@ -295,17 +313,21 @@ async def test_restored_expired_payload_is_not_accepted_even_if_redis_key_has_ne
@pytest.mark.asyncio
-@pytest.mark.parametrize('damage', ['json', 'user_id', 'password', 'disabled', 'deleted', 'null'])
+@pytest.mark.parametrize('damage', ['json', 'user_id', 'missing_user_name', 'password', 'disabled', 'deleted', 'null'])
async def test_damaged_snapshot_is_not_used(cache_redis: Redis, damage: str) -> None:
"""损坏的快照不可使用。"""
await prime_cache(cache_redis)
key = CurrentUserCacheUtil._keys(NAMESPACE, USER_ID)[2]
- payload = json.loads(await cache_redis.hget(key, 'payload'))
+ snapshot = await cache_redis.hget(key, 'payload')
+ assert snapshot is not None
+ payload = json.loads(snapshot)
if damage == 'json':
serialized = '{'
else:
if damage == 'user_id':
payload['user']['userId'] = OTHER_USER_ID
+ elif damage == 'missing_user_name':
+ del payload['user']['userName']
elif damage == 'password':
payload['user']['password'] = 'unwanted-hash'
elif damage == 'disabled':
@@ -355,7 +377,7 @@ async def test_cache_failure_returns_to_database_without_claiming_success(error_
async def test_malformed_redis_response_falls_back_to_database(result: object) -> None:
"""Redis 返回格式错误时回退到数据库。"""
redis = AsyncMock(spec=Redis)
- redis.eval.return_value = result
+ redis.eval = AsyncMock(return_value=result)
assert await CurrentUserCacheUtil.read(redis, NAMESPACE, USER_ID, TTL_SECONDS) == (None, None)
@@ -365,7 +387,7 @@ async def test_slow_cache_operation_is_bounded_and_cancelled(
cache_redis: Redis, operation: str, monkeypatch: pytest.MonkeyPatch
) -> None:
"""限制慢缓存操作的等待时间并取消操作。"""
- _, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
+ ticket = await read_miss_ticket(cache_redis)
stopped = asyncio.Event()
async def slow_eval(*args: object) -> None:
@@ -395,7 +417,7 @@ async def slow_eval(*args: object) -> None:
@pytest.mark.parametrize('operation', ['read', 'write', 'invalidate'])
async def test_cancellation_is_propagated(cache_redis: Redis, operation: str) -> None:
"""取消信号向调用方传播。"""
- _, ticket = await CurrentUserCacheUtil.read(cache_redis, NAMESPACE, USER_ID, TTL_SECONDS)
+ ticket = await read_miss_ticket(cache_redis)
redis = AsyncMock(spec=Redis)
redis.eval.side_effect = asyncio.CancelledError
with pytest.raises(asyncio.CancelledError):
diff --git a/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py b/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py
index 16d70ee53..c1ce9b991 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py
@@ -2,7 +2,6 @@
import json
from collections.abc import Iterator
from datetime import UTC, datetime
-from types import SimpleNamespace
from unittest.mock import patch
import pytest
@@ -205,29 +204,19 @@ def test_sanitize_text_returns_original_when_mask_disabled() -> None:
def test_build_json_payload_sanitizes_exception_and_extra() -> None:
"""构造 JSON 日志时对异常和附加字段脱敏。"""
initializer = LoggerInitializer()
+ outputs = []
+ test_logger = _logger.patch(initializer._patch_record)
+ handler = test_logger.add(
+ lambda message: outputs.append(initializer._build_json_payload(message.record)),
+ filter=initializer._filter,
+ )
try:
raise ValueError('token=abc.def')
- except ValueError as exc:
- exception = SimpleNamespace(
- type=type(exc),
- value=exc,
- traceback=exc.__traceback__,
- )
- record = {
- 'time': datetime(2026, 4, 20, 12, 0, 0),
- 'level': SimpleNamespace(name='ERROR'),
- 'message': 'password=123456',
- 'name': 'test_logger',
- 'module': 'test_module',
- 'function': 'test_function',
- 'line': 1,
- 'extra': {'authorization': 'Bearer abc.def', 'trace_id': 'trace-1'},
- 'exception': exception,
- }
-
- initializer._patch_record(record)
- initializer._filter(record)
- payload = initializer._build_json_payload(record)
+ except ValueError:
+ test_logger.bind(authorization='Bearer abc.def', trace_id='trace-1').exception('password=123456')
+ finally:
+ test_logger.remove(handler)
+ (payload,) = outputs
assert '123456' not in payload['message']
assert 'abc.def' not in payload['exception']['value']
diff --git a/ruoyi-fastapi-backend/tests/utils/test_page_util.py b/ruoyi-fastapi-backend/tests/utils/test_page_util.py
new file mode 100644
index 000000000..05aae9c68
--- /dev/null
+++ b/ruoyi-fastapi-backend/tests/utils/test_page_util.py
@@ -0,0 +1,55 @@
+import pytest
+from sqlalchemy import literal, select, union_all
+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
+
+from module_admin.entity.do.dept_do import SysDept
+from module_admin.entity.do.user_do import SysUser
+from utils.page_util import PageUtil
+
+
+@pytest.mark.asyncio
+async def test_column_projection_keeps_keys_and_nulls_across_pages() -> None:
+ """投影查询在列表和分页中都应保留列名与空值,超出最后一页仍返回总数。"""
+ engine = create_async_engine('sqlite+aiosqlite:///:memory:')
+ records = union_all(
+ select(literal(1).label('file_id'), literal(None).label('file_name')),
+ select(literal(2), literal('文件')),
+ ).subquery()
+ query = select(records.c.file_id, records.c.file_name).order_by(records.c.file_id)
+ expected = [{'fileId': 1, 'fileName': None}, {'fileId': 2, 'fileName': '文件'}]
+ try:
+ async with AsyncSession(engine) as db:
+ assert await PageUtil.paginate(db, query, 1, 1, as_mappings=True) == expected
+ for page_num in (1, 2, 3):
+ page = await PageUtil.paginate(db, query, page_num, 1, True, as_mappings=True)
+ assert page.rows == expected[page_num - 1 : page_num]
+ assert page.total == len(expected)
+ assert page.has_next == (page_num < len(expected))
+
+ single_column = select(records.c.file_id).order_by(records.c.file_id)
+ assert await PageUtil.paginate(db, single_column, 1, 2, as_mappings=True) == [{'fileId': 1}, {'fileId': 2}]
+ finally:
+ await engine.dispose()
+
+
+@pytest.mark.asyncio
+async def test_joined_entities_keep_missing_department_in_both_page_modes() -> None:
+ """外连接缺少部门时,完整结果和分页结果都应保留用户和空部门。"""
+ engine = create_async_engine('sqlite+aiosqlite:///:memory:')
+ try:
+ async with engine.begin() as conn:
+ await conn.run_sync(SysUser.get_table().create)
+ await conn.run_sync(SysDept.get_table().create)
+ async with AsyncSession(engine) as db:
+ db.add(SysUser(user_id=1, user_name='reader', nick_name='Reader'))
+ await db.commit()
+ query = select(SysUser, SysDept).outerjoin(SysDept, SysUser.dept_id == SysDept.dept_id)
+ rows = await PageUtil.paginate(db, query, 1, 10, False)
+ page = await PageUtil.paginate(db, query, 1, 10, True)
+ assert isinstance(rows, list)
+ assert page.rows == rows
+ user, dept = rows[0]
+ assert user is not None and user['userName'] == 'reader'
+ assert dept is None
+ finally:
+ await engine.dispose()
diff --git a/ruoyi-fastapi-backend/tests/utils/test_response_timezone.py b/ruoyi-fastapi-backend/tests/utils/test_response_timezone.py
index fff3c0a61..658fd63d5 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_response_timezone.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_response_timezone.py
@@ -9,7 +9,7 @@
def test_response_util_serializes_nested_datetimes_as_fixed_utc_rfc3339() -> None:
"""响应中的嵌套日期时间统一序列化为 UTC 的 RFC 3339 格式。"""
response = ResponseUtil.success(data={'createdAt': datetime(2026, 8, 28, 10, 30, 0, 123456, tzinfo=UTC)})
- payload = json.loads(response.body)
+ payload = json.loads(bytes(response.body))
assert payload['data']['createdAt'] == '2026-08-28T10:30:00.123Z'
assert payload['time'].endswith('Z')
diff --git a/ruoyi-fastapi-backend/tests/utils/test_startup_log_filter.py b/ruoyi-fastapi-backend/tests/utils/test_startup_log_filter.py
index a94c3f3da..c26c96571 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_startup_log_filter.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_startup_log_filter.py
@@ -1,41 +1,38 @@
import asyncio
-from types import SimpleNamespace
+from typing import TYPE_CHECKING
import pytest
from loguru import logger
from utils.log_util import LoggerInitializer
+if TYPE_CHECKING:
+ from loguru import Record
-def build_log_record(*, level: str, level_no: int, extra: dict[str, object]) -> dict[str, object]:
+
+def build_log_record(*, level: str, extra: dict[str, object]) -> 'Record':
"""
- 构建 Logger filter 所需的最小日志记录。
+ 从 Loguru 捕获指定级别和附加字段的日志记录。
:param level: 日志或结果使用的级别
- :param level_no: 日志级别的数值
:param extra: 添加到默认数据上的额外字段
:return: Logger filter 所需的最小日志记录
"""
- return {
- 'level': SimpleNamespace(name=level, no=level_no),
- 'extra': dict(extra),
- }
-
-
-@pytest.mark.parametrize(
- ('level', 'level_no'),
- [
- ('INFO', 20),
- ('WARNING', 30),
- ('ERROR', 40),
- ],
-)
-def test_startup_worker_role_never_suppresses_log_records(level: str, level_no: int) -> None:
+ records: list[Record] = []
+ handler = logger.add(lambda message: records.append(message.record), level=level)
+ try:
+ logger.bind(**extra).log(level, '启动日志过滤测试')
+ finally:
+ logger.remove(handler)
+ return records[0]
+
+
+@pytest.mark.parametrize('level', ['INFO', 'WARNING', 'ERROR'])
+def test_startup_worker_role_never_suppresses_log_records(level: str) -> None:
"""校验启动标签和非 leader 标记不再充当日志访问控制。"""
initializer = LoggerInitializer()
record = build_log_record(
level=level,
- level_no=level_no,
extra={
'startup_phase': 'application_startup',
'startup_log_enabled': False,
@@ -52,12 +49,10 @@ def test_startup_worker_role_never_suppresses_info_or_error_file_records() -> No
initializer = LoggerInitializer()
info_record = build_log_record(
level='INFO',
- level_no=20,
extra={'startup_phase': 'application_startup', 'startup_log_enabled': False},
)
error_record = build_log_record(
level='ERROR',
- level_no=40,
extra={'startup_phase': 'application_startup', 'startup_log_enabled': False},
)
diff --git a/ruoyi-fastapi-backend/tests/utils/test_template_util.py b/ruoyi-fastapi-backend/tests/utils/test_template_util.py
index 0994ec916..a80b84dc7 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_template_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_template_util.py
@@ -27,47 +27,47 @@ def _gen_table(
"""
columns = [
GenTableColumnModel(
- columnName='item_id',
- columnComment='编号',
- columnType='bigint',
- pythonType='int',
- pythonField='itemId',
- isPk='1',
- isList='1',
- htmlType='input',
+ column_name='item_id',
+ column_comment='编号',
+ column_type='bigint',
+ python_type='int',
+ python_field='itemId',
+ is_pk='1',
+ is_list='1',
+ html_type='input',
),
GenTableColumnModel(
- columnName='item_name',
- columnComment='名称(展示名称)',
- columnType='varchar(100)',
- pythonType='str',
- pythonField='itemName',
- isList='1',
- htmlType='input',
+ column_name='item_name',
+ column_comment='名称(展示名称)',
+ column_type='varchar(100)',
+ python_type='str',
+ python_field='itemName',
+ is_list='1',
+ html_type='input',
),
GenTableColumnModel(
- columnName='status',
- columnComment='状态',
- columnType='char(1)',
- pythonType='str',
- pythonField='status',
- isList='1',
- htmlType='select',
- dictType='sys_normal_disable',
+ column_name='status',
+ column_comment='状态',
+ column_type='char(1)',
+ python_type='str',
+ python_field='status',
+ is_list='1',
+ html_type='select',
+ dict_type='sys_normal_disable',
),
]
return GenTableModel(
- tableName='gen_item',
- tableComment='生成测试',
- className='GenItem',
- tplCategory=tpl_category,
- tplWebType=tpl_web_type,
- packageName='module_test',
- moduleName='test',
- businessName='item',
- functionName='测试项',
- functionAuthor='RuoYi',
- formColNum=2,
+ table_name='gen_item',
+ table_comment='生成测试',
+ class_name='GenItem',
+ tpl_category=tpl_category,
+ tpl_web_type=tpl_web_type,
+ package_name='module_test',
+ module_name='test',
+ business_name='item',
+ function_name='测试项',
+ function_author='RuoYi',
+ form_col_num=2,
options=json.dumps(
{
'genView': gen_view,
@@ -78,7 +78,7 @@ def _gen_table(
}
),
columns=columns,
- pkColumn=columns[0],
+ pk_column=columns[0],
)
@@ -106,7 +106,7 @@ def test_get_gen_view_supports_stored_option_formats(value: object, expected: bo
@pytest.mark.parametrize(('value', 'expected'), [('1', True), ('0', False)])
def test_gen_table_params_accepts_frontend_string_switch(value: str, expected: bool) -> None:
"""生成表参数接受前端字符串开关。"""
- assert GenTableParamsModel(genView=value).gen_view is expected
+ assert GenTableParamsModel(gen_view=value).gen_view is expected
@pytest.mark.parametrize(
@@ -207,58 +207,58 @@ def test_python_templates_handle_audit_timestamps_by_exact_column_name() -> None
"""Python 模板按确切列名处理审计时间。"""
columns = [
GenTableColumnModel(
- columnName='item_id',
- columnComment='编号',
- columnType='bigint',
- pythonType='int',
- pythonField='itemId',
- isPk='1',
- isInsert='1',
+ column_name='item_id',
+ column_comment='编号',
+ column_type='bigint',
+ python_type='int',
+ python_field='itemId',
+ is_pk='1',
+ is_insert='1',
),
GenTableColumnModel(
- columnName='create_by',
- columnComment='创建者',
- columnType='varchar(64)',
- pythonType='str',
- pythonField='createBy',
- isInsert='1',
- isEdit='0',
+ column_name='create_by',
+ column_comment='创建者',
+ column_type='varchar(64)',
+ python_type='str',
+ python_field='createBy',
+ is_insert='1',
+ is_edit='0',
),
GenTableColumnModel(
- columnName='update_by',
- columnComment='更新者',
- columnType='varchar(64)',
- pythonType='str',
- pythonField='updateBy',
- isInsert='1',
- isEdit='1',
+ column_name='update_by',
+ column_comment='更新者',
+ column_type='varchar(64)',
+ python_type='str',
+ python_field='updateBy',
+ is_insert='1',
+ is_edit='1',
),
GenTableColumnModel(
- columnName='create_time',
- columnComment='创建时间',
- columnType='datetime',
- pythonType='datetime',
- pythonField='createTime',
- isInsert='1',
- isEdit='0',
+ column_name='create_time',
+ column_comment='创建时间',
+ column_type='datetime',
+ python_type='datetime',
+ python_field='createTime',
+ is_insert='1',
+ is_edit='0',
),
GenTableColumnModel(
- columnName='update_time',
- columnComment='更新时间',
- columnType='datetime',
- pythonType='datetime',
- pythonField='updateTime',
- isInsert='1',
- isEdit='1',
+ column_name='update_time',
+ column_comment='更新时间',
+ column_type='datetime',
+ python_type='datetime',
+ python_field='updateTime',
+ is_insert='1',
+ is_edit='1',
),
GenTableColumnModel(
- columnName='created_time',
- columnComment='其他时间',
- columnType='datetime',
- pythonType='datetime',
- pythonField='createdTime',
- isInsert='1',
- isEdit='1',
+ column_name='created_time',
+ column_comment='其他时间',
+ column_type='datetime',
+ python_type='datetime',
+ python_field='createdTime',
+ is_insert='1',
+ is_edit='1',
),
]
gen_table = _gen_table(gen_view=False)
@@ -297,21 +297,21 @@ def test_dao_audit_filter_uses_a_set_for_a_single_timestamp() -> None:
"""DAO 过滤单一审计时间时仍使用集合。"""
columns = [
GenTableColumnModel(
- columnName='item_id',
- columnComment='编号',
- columnType='bigint',
- pythonType='int',
- pythonField='itemId',
- isPk='1',
- isInsert='1',
+ column_name='item_id',
+ column_comment='编号',
+ column_type='bigint',
+ python_type='int',
+ python_field='itemId',
+ is_pk='1',
+ is_insert='1',
),
GenTableColumnModel(
- columnName='create_time',
- columnComment='创建时间',
- columnType='datetime',
- pythonType='datetime',
- pythonField='createTime',
- isInsert='1',
+ column_name='create_time',
+ column_comment='创建时间',
+ column_type='datetime',
+ python_type='datetime',
+ python_field='createTime',
+ is_insert='1',
),
]
gen_table = _gen_table(gen_view=False)
@@ -335,20 +335,20 @@ def test_do_template_supports_required_update_time_only_mixin() -> None:
"""数据对象模板支持仅要求更新时间的混入类。"""
columns = [
GenTableColumnModel(
- columnName='item_id',
- columnComment='编号',
- columnType='bigint',
- pythonType='int',
- pythonField='itemId',
- isPk='1',
+ column_name='item_id',
+ column_comment='编号',
+ column_type='bigint',
+ python_type='int',
+ python_field='itemId',
+ is_pk='1',
),
GenTableColumnModel(
- columnName='update_time',
- columnComment='最后修改时间',
- columnType='datetime',
- pythonType='datetime',
- pythonField='updateTime',
- isRequired='1',
+ column_name='update_time',
+ column_comment='最后修改时间',
+ column_type='datetime',
+ python_type='datetime',
+ python_field='updateTime',
+ is_required='1',
),
]
gen_table = _gen_table(gen_view=False)
@@ -372,45 +372,46 @@ def test_sub_table_entity_template_uses_required_nullable_semantics() -> None:
gen_table.sub_table_name = 'gen_item_detail'
gen_table.sub_table_fk_name = 'item_id'
gen_table.sub_table = GenTableModel(
- tableName='gen_item_detail',
- tableComment='生成测试明细',
- className='GenItemDetail',
+ table_name='gen_item_detail',
+ table_comment='生成测试明细',
+ class_name='GenItemDetail',
columns=[
GenTableColumnModel(
- columnName='required_value',
- columnComment='必填值',
- columnType='varchar(100)',
- pythonType='str',
- pythonField='requiredValue',
- isRequired='1',
+ column_name='required_value',
+ column_comment='必填值',
+ column_type='varchar(100)',
+ python_type='str',
+ python_field='requiredValue',
+ is_required='1',
),
GenTableColumnModel(
- columnName='optional_value',
- columnComment='可选值',
- columnType='varchar(100)',
- pythonType='str',
- pythonField='optionalValue',
- isRequired='0',
+ column_name='optional_value',
+ column_comment='可选值',
+ column_type='varchar(100)',
+ python_type='str',
+ python_field='optionalValue',
+ is_required='0',
),
GenTableColumnModel(
- columnName='create_time',
- columnComment='创建时间',
- columnType='datetime',
- pythonType='datetime',
- pythonField='createTime',
- isRequired='1',
+ column_name='create_time',
+ column_comment='创建时间',
+ column_type='datetime',
+ python_type='datetime',
+ python_field='createTime',
+ is_required='1',
),
GenTableColumnModel(
- columnName='update_time',
- columnComment='更新时间',
- columnType='datetime',
- pythonType='datetime',
- pythonField='updateTime',
+ column_name='update_time',
+ column_comment='更新时间',
+ column_type='datetime',
+ python_type='datetime',
+ python_field='updateTime',
),
],
- businessName='itemDetail',
- functionName='生成测试明细',
+ business_name='itemDetail',
+ function_name='生成测试明细',
)
+ assert gen_table.sub_table.columns
gen_table.sub_table.pk_column = gen_table.sub_table.columns[0]
context = TemplateUtils.prepare_context(gen_table)
diff --git a/ruoyi-fastapi-backend/tests/utils/test_time_util.py b/ruoyi-fastapi-backend/tests/utils/test_time_util.py
index 8d4c66ec6..99af119ea 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_time_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_time_util.py
@@ -1,4 +1,4 @@
-from datetime import UTC, date, datetime
+from datetime import UTC, date, datetime, timedelta
import pytest
@@ -11,7 +11,7 @@ def test_utc_now_returns_aware_utc_datetime() -> None:
now = TimezoneUtil.utc_now()
assert now.tzinfo is UTC
- assert now.utcoffset().total_seconds() == 0
+ assert now.utcoffset() == timedelta(0)
def test_naive_datetime_is_rejected() -> None:
@@ -92,6 +92,7 @@ def test_time_with_timezone_requires_an_explicit_storage_decision(self, column_t
with pytest.raises(ServiceWarning) as error:
GenTimeUtil.get_time_semantics(column_type, 'postgresql')
+ assert error.value.message is not None
assert 'TIME WITHOUT TIME ZONE' in error.value.message
@pytest.mark.parametrize('db_type', ['mysql', 'postgresql'])
diff --git a/ruoyi-fastapi-backend/ty.toml b/ruoyi-fastapi-backend/ty.toml
new file mode 100644
index 000000000..8198b1807
--- /dev/null
+++ b/ruoyi-fastapi-backend/ty.toml
@@ -0,0 +1,15 @@
+[environment]
+python-platform = "all"
+python-version = "3.11"
+
+[rules]
+blanket-ignore-comment = "error"
+disjoint-cast = "error"
+mismatched-enum-name = "error"
+mismatched-namedtuple-name = "error"
+mismatched-sentinel-name = "error"
+unsound-return = "error"
+unsound-yield = "error"
+
+[terminal]
+error-on-warning = true
diff --git a/ruoyi-fastapi-backend/utils/api_annotation_util.py b/ruoyi-fastapi-backend/utils/api_annotation_util.py
index 7cfa36283..972d9a59a 100644
--- a/ruoyi-fastapi-backend/utils/api_annotation_util.py
+++ b/ruoyi-fastapi-backend/utils/api_annotation_util.py
@@ -1,6 +1,6 @@
import inspect
from collections.abc import Awaitable, Callable, Sequence
-from typing import ParamSpec, TypeVar
+from typing import ParamSpec, TypeVar, cast
from fastapi import Request
from redis import asyncio as aioredis
@@ -29,7 +29,7 @@ def get_request(cls, func: Callable[P, Awaitable[R]], *args: P.args, **kwargs: P
bound_arguments = signature.bind_partial(*args, **kwargs)
for argument in bound_arguments.arguments.values():
if isinstance(argument, Request):
- return argument
+ return cast('Request', argument)
return None
@@ -46,7 +46,7 @@ def get_redis_client(cls, request: Request, skip_message: str) -> aioredis.Redis
if redis is None:
logger.warning(skip_message)
- return redis
+ return cast('aioredis.Redis | None', redis)
@classmethod
def resolve_request_redis(
diff --git a/ruoyi-fastapi-backend/utils/cache_util.py b/ruoyi-fastapi-backend/utils/cache_util.py
index 1645e9fc8..e93d3d427 100644
--- a/ruoyi-fastapi-backend/utils/cache_util.py
+++ b/ruoyi-fastapi-backend/utils/cache_util.py
@@ -2,11 +2,11 @@
import hashlib
import uuid
from dataclasses import dataclass
-from typing import Any
import anyio
from redis.asyncio import Redis
from redis.exceptions import RedisError
+from redis.typing import EncodableT
from sqlalchemy.engine import Connection, Engine
from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine
@@ -171,8 +171,7 @@ async def read(
try:
current_user = CurrentUserModel.model_validate_json(result[4])
if (
- current_user.user is None
- or current_user.user.user_id != user_id
+ current_user.user.user_id != user_id
or current_user.user.password is not None
or current_user.user.status not in (None, '0')
or current_user.user.del_flag not in (None, '0')
@@ -202,7 +201,7 @@ async def write(
:param ticket: 查询开始前取得的版本和有效期
:return: 是否写入成功
"""
- if current_user.user is None or current_user.user.user_id != user_id:
+ if current_user.user.user_id != user_id:
return False
try:
payload = current_user.model_dump_json(
@@ -246,20 +245,21 @@ async def invalidate(cls, redis: Redis, namespace: str, user_ids: set[int] | Non
else [cls._keys(namespace, user_id)[1] for user_id in sorted(user_ids)]
)
try:
- return await cls._eval(
+ invalidated = await cls._eval(
redis,
cls._INVALIDATE_SCRIPT,
len(keys),
*keys,
*(uuid.uuid4().hex for _ in keys),
cls._USER_EPOCH_TTL_SECONDS if user_ids is not None else 0,
- ) == len(keys)
+ )
+ return invalidated == len(keys)
except (RedisError, TimeoutError):
logger.warning('当前用户缓存失效失败,等待快照硬过期')
return False
@classmethod
- async def _eval(cls, redis: Redis, script: str, key_count: int, *args: object) -> Any:
+ async def _eval(cls, redis: Redis, script: str, key_count: int, *args: EncodableT) -> object:
"""
限时执行Redis脚本,取消后等待连接归还。
diff --git a/ruoyi-fastapi-backend/utils/common_util.py b/ruoyi-fastapi-backend/utils/common_util.py
index f63a02ffc..d90981a3c 100644
--- a/ruoyi-fastapi-backend/utils/common_util.py
+++ b/ruoyi-fastapi-backend/utils/common_util.py
@@ -11,7 +11,7 @@
from openpyxl.worksheet.datavalidation import DataValidation
from sqlalchemy.engine.row import Row
from sqlalchemy.orm.collections import InstrumentedList
-from sqlalchemy.sql.expression import TextClause, null
+from sqlalchemy.sql.expression import Null, null
from config.database import Base
from config.env import CachePathConfig
@@ -152,7 +152,7 @@ def serialize_result(
return result
@classmethod
- def get_server_default_null(cls, dialect_name: str, need_explicit_null: bool = True) -> TextClause | None:
+ def get_server_default_null(cls, dialect_name: str, need_explicit_null: bool = True) -> Null | None:
"""
根据数据库方言动态返回值为null的server_default。
@@ -373,8 +373,8 @@ def get_excel_template(header_list: list, selector_header_list: list, option_lis
# 创建数据有效性规则
header_option = []
for option in options:
- if option.get(selector_header):
- header_option = option.get(selector_header)
+ if values := option.get(selector_header):
+ header_option = values
dv = DataValidation(type='list', formula1=f'"{",".join(header_option)}"')
# 设置数据有效性规则的起始单元格和结束单元格
dv.add(
diff --git a/ruoyi-fastapi-backend/utils/cron_util.py b/ruoyi-fastapi-backend/utils/cron_util.py
index 3674db57d..05a2d5ffd 100644
--- a/ruoyi-fastapi-backend/utils/cron_util.py
+++ b/ruoyi-fastapi-backend/utils/cron_util.py
@@ -1,6 +1,6 @@
import re
from calendar import monthrange
-from datetime import UTC, datetime
+from datetime import UTC, datetime, tzinfo
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.cron.expressions import AllExpression
@@ -116,7 +116,7 @@ def get_next_fire_time(self, previous_fire_time: datetime | None, now: datetime)
:return: 下一次执行时刻,无未来结果时返回None
"""
candidate = super().get_next_fire_time(previous_fire_time, now)
- while candidate is not None:
+ while isinstance(candidate, datetime):
normalized = candidate.astimezone(UTC).astimezone(self.timezone)
if candidate.isoformat() == normalized.isoformat() and candidate.fold == 0:
return candidate
@@ -124,12 +124,12 @@ def get_next_fire_time(self, previous_fire_time: datetime | None, now: datetime)
return None
@classmethod
- def from_crontab(cls, expr: str, timezone: str) -> 'MyCronTrigger':
+ def from_crontab(cls, expr: str, timezone: str | tzinfo | None = None) -> 'MyCronTrigger':
"""
根据Quartz表达式和任务时区创建触发器。
:param expr: 包含6或7个字段的Quartz表达式
- :param timezone: 任务IANA时区名称
+ :param timezone: 任务时区对象或 IANA 时区名称,省略时沿用调度器默认时区
:return: 配置完成的Cron触发器
:raises ValueError: 字段数不为六或七,或按周指定日期时日字段未使用问号或星号
"""
@@ -168,7 +168,7 @@ def from_crontab(cls, expr: str, timezone: str) -> 'MyCronTrigger':
month=month,
day_of_week=day_of_week,
year=year,
- timezone=TimezoneUtil.get_timezone(timezone),
+ timezone=TimezoneUtil.get_timezone(timezone) if isinstance(timezone, str) else timezone,
)
@classmethod
@@ -335,7 +335,7 @@ def validate_year(cls, year: str, timezone: str) -> bool:
校验年值是否正确。
:param year: 年值
- :param timezone: 任务IANA时区名称,用于确定当前业务年份
+ :param timezone: 任务时区对象或 IANA 时区名称,省略时沿用调度器默认时区,用于确定当前业务年份
:return: 校验结果
"""
current_year = TimezoneUtil.to_business_time(TimezoneUtil.utc_now(), timezone).year
@@ -360,7 +360,7 @@ def validate_cron_expression(cls, cron_expression: str, timezone: str) -> bool:
校验Cron表达式是否正确。
:param cron_expression: Cron表达式
- :param timezone: 任务IANA时区名称
+ :param timezone: 任务时区对象或 IANA 时区名称,省略时沿用调度器默认时区
:return: 校验结果
"""
try:
diff --git a/ruoyi-fastapi-backend/utils/crypto_util.py b/ruoyi-fastapi-backend/utils/crypto_util.py
index 886f9329c..3c0674e66 100644
--- a/ruoyi-fastapi-backend/utils/crypto_util.py
+++ b/ruoyi-fastapi-backend/utils/crypto_util.py
@@ -14,7 +14,7 @@ class CryptoUtil:
:cvar _cipher_suite: 对配置内容执行加解密的密码套件
"""
- _cipher_suite = None
+ _cipher_suite: Fernet | None = None
@classmethod
def _get_cipher_suite(cls) -> Fernet:
diff --git a/ruoyi-fastapi-backend/utils/dependency_util.py b/ruoyi-fastapi-backend/utils/dependency_util.py
index a8825499e..e6e075823 100644
--- a/ruoyi-fastapi-backend/utils/dependency_util.py
+++ b/ruoyi-fastapi-backend/utils/dependency_util.py
@@ -18,8 +18,8 @@ def get_request_path(cls, request: Request) -> str:
"""
scope = getattr(request, 'scope', {})
# 使用路由匹配的ASGI路径,避免URL解析截断或丢弃路径字符。
- path = scope.get('path')
- if path is None:
+ path: object = scope.get('path')
+ if not isinstance(path, str):
path = request.url.path
root_path = (scope.get('root_path') or '').rstrip('/')
if not root_path and scope.get('route') is None:
diff --git a/ruoyi-fastapi-backend/utils/excel_util.py b/ruoyi-fastapi-backend/utils/excel_util.py
index 82eaadea1..6c15580da 100644
--- a/ruoyi-fastapi-backend/utils/excel_util.py
+++ b/ruoyi-fastapi-backend/utils/excel_util.py
@@ -134,8 +134,8 @@ def get_excel_template(
# 创建数据有效性规则
header_option = []
for option in options:
- if option.get(selector_header):
- header_option = option.get(selector_header)
+ if values := option.get(selector_header):
+ header_option = values
dv = DataValidation(type='list', formula1=f'"{",".join(header_option)}"')
# 设置数据有效性规则的起始单元格和结束单元格
dv.add(
diff --git a/ruoyi-fastapi-backend/utils/file_util.py b/ruoyi-fastapi-backend/utils/file_util.py
index aae3be9dd..6f809a6c3 100644
--- a/ruoyi-fastapi-backend/utils/file_util.py
+++ b/ruoyi-fastapi-backend/utils/file_util.py
@@ -4,7 +4,7 @@
import shutil
import time
import uuid
-from collections.abc import AsyncGenerator, Iterator
+from collections.abc import AsyncGenerator, Iterator, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Protocol
@@ -307,7 +307,7 @@ def get_value(snake_name: str, camel_name: str) -> Any:
return 'invalid'
@classmethod
- def stage_file_deletions(cls, file_infos: list[FileStorageInfo]) -> list[StagedFile]:
+ def stage_file_deletions(cls, file_infos: Sequence[FileStorageInfo]) -> list[StagedFile]:
"""
将待删除文件移入回收区。
@@ -376,7 +376,7 @@ def restore_staged_files(cls, staged_files: list[StagedFile]) -> None:
logger.error(f'文件删除回滚失败: {exc}')
@classmethod
- def prepare_deleted_files_for_restore(cls, file_infos: list[FileStorageInfo]) -> list[StagedFile]:
+ def prepare_deleted_files_for_restore(cls, file_infos: Sequence[FileStorageInfo]) -> list[StagedFile]:
"""
校验待恢复文件并生成暂存信息。
@@ -396,7 +396,7 @@ def prepare_deleted_files_for_restore(cls, file_infos: list[FileStorageInfo]) ->
return staged_files
@classmethod
- def prepare_deleted_files_for_purge(cls, file_infos: list[FileStorageInfo]) -> list[StagedFile]:
+ def prepare_deleted_files_for_purge(cls, file_infos: Sequence[FileStorageInfo]) -> list[StagedFile]:
"""
校验待永久清理文件并生成暂存信息。
diff --git a/ruoyi-fastapi-backend/utils/gen_i18n_util.py b/ruoyi-fastapi-backend/utils/gen_i18n_util.py
index fee47aa7c..1d9b384dc 100644
--- a/ruoyi-fastapi-backend/utils/gen_i18n_util.py
+++ b/ruoyi-fastapi-backend/utils/gen_i18n_util.py
@@ -2,6 +2,7 @@
import json
import re
from pathlib import Path
+from typing import Never
from babel import Locale, UnknownLocaleError
from babel.messages.catalog import Catalog
@@ -93,7 +94,7 @@ def __init__(self, table: GenTableModel) -> None:
):
self.invalid_configuration()
self.namespace = f'generated.{table.module_name}.{table.business_name}'
- if not self.KEY_PATTERN.fullmatch(self.namespace):
+ if not table.module_name or not table.business_name or not self.KEY_PATTERN.fullmatch(self.namespace):
self.invalid_configuration()
self.frontend = {locale: {} for locale in self.locales}
self.backend = {locale: {} for locale in self.locales}
@@ -113,7 +114,7 @@ def __init__(self, table: GenTableModel) -> None:
self.text(suffix, source)
@staticmethod
- def invalid_configuration() -> None:
+ def invalid_configuration() -> Never:
"""
拒绝无法安全注册或插值的生成参数。
@@ -155,6 +156,19 @@ def text(self, suffix: str, source: str, english: str | None = None) -> str:
self.frontend[locale][suffix] = value
return key
+ @classmethod
+ def _field_label(cls, column: GenTableColumnModel) -> str:
+ """
+ 从列描述或列名提取用于翻译的字段标签。
+
+ :param column: 待生成语言资源的字段
+ :return: 去除括号说明的字段标签
+ """
+ label = column.column_comment or column.column_name
+ if not label:
+ cls.invalid_configuration()
+ return label.split('(', 1)[0]
+
def field_key(self, column: GenTableColumnModel, suffix: str = 'label') -> str:
"""
根据代码字段生成标签、占位符或必填提示。
@@ -163,7 +177,7 @@ def field_key(self, column: GenTableColumnModel, suffix: str = 'label') -> str:
:param suffix: label、input、select 或 required
:return: 完整前端字段消息标识
"""
- label = (column.column_comment or column.column_name).split('(')[0]
+ label = self._field_label(column)
source = {'label': label, 'input': f'请输入{label}', 'select': f'请选择{label}', 'required': f'{label}不能为空'}
if suffix not in source:
self.invalid_configuration()
@@ -199,7 +213,7 @@ def backend_field_key(self, column: GenTableColumnModel, suffix: str = 'label')
:param suffix: label 或 required
:return: 完整后端字段消息标识
"""
- label = (column.column_comment or column.column_name).split('(')[0]
+ label = self._field_label(column)
if suffix not in {'label', 'required'}:
self.invalid_configuration()
prefix = self.field_prefixes.get(id(column), 'fields')
diff --git a/ruoyi-fastapi-backend/utils/gen_util.py b/ruoyi-fastapi-backend/utils/gen_util.py
index 7e9686b28..0145e4eb5 100644
--- a/ruoyi-fastapi-backend/utils/gen_util.py
+++ b/ruoyi-fastapi-backend/utils/gen_util.py
@@ -2,6 +2,7 @@
from common.constant import GenConstant
from config.env import DataBaseConfig, GenConfig
+from exceptions.exception import ServiceWarning
from module_generator.entity.vo.gen_vo import GenTableColumnModel, GenTableModel
from utils.string_util import StringUtil
from utils.time_util import GenTimeUtil
@@ -16,6 +17,19 @@ class GenUtils:
TEXTAREA_COLUMN_LENGTH = 500
+ @staticmethod
+ def require_metadata(value: str | None) -> str:
+ """
+ 获取代码生成所需的非空元数据。
+
+ :param value: 表、字段或生成配置中的元数据值
+ :return: 已填写的元数据值
+ :raises ServiceWarning: 缺少生成所需的元数据
+ """
+ if not value:
+ raise ServiceWarning(message='请先完善生成配置信息', msg_key='generator.configurationRequired')
+ return value
+
@classmethod
def init_table(cls, gen_table: GenTableModel, oper_name: str) -> None:
"""
@@ -24,11 +38,12 @@ def init_table(cls, gen_table: GenTableModel, oper_name: str) -> None:
:param gen_table: 业务表对象
:param oper_name: 操作人
"""
- gen_table.class_name = cls.convert_class_name(gen_table.table_name)
+ table_name = cls.require_metadata(gen_table.table_name)
+ gen_table.class_name = cls.convert_class_name(table_name)
gen_table.package_name = GenConfig.package_name
gen_table.module_name = cls.get_module_name(GenConfig.package_name)
- gen_table.business_name = cls.get_business_name(gen_table.table_name)
- gen_table.function_name = cls.replace_text(gen_table.table_comment)
+ gen_table.business_name = cls.get_business_name(table_name)
+ gen_table.function_name = cls.replace_text(gen_table.table_comment or '')
gen_table.function_author = GenConfig.author
gen_table.create_by = oper_name
gen_table.update_by = oper_name
@@ -41,7 +56,8 @@ def init_column_field(cls, column: GenTableColumnModel, table: GenTableModel) ->
:param column: 业务表字段对象
:param table: 业务表对象
"""
- data_type = cls.get_db_type(column.column_type).lower()
+ column_type = cls.require_metadata(column.column_type)
+ data_type = cls.get_db_type(column_type).lower()
source_config = DataBaseConfig.get_source(table.data_source_name)
db_type = source_config.db_type
python_mapping = GenConstant.DB_TO_PYTHON_TYPE_MAPPING[db_type]
@@ -49,7 +65,7 @@ def init_column_field(cls, column: GenTableColumnModel, table: GenTableModel) ->
text_types = GenConstant.COLUMNTYPE_TEXT[db_type]
time_types = GenConstant.COLUMNTYPE_TIME[db_type]
number_types = GenConstant.COLUMNTYPE_NUMBER[db_type]
- column_name = column.column_name
+ column_name = cls.require_metadata(column.column_name)
column.table_id = table.table_id
column.create_by = table.create_by
# 设置Python字段名
@@ -60,7 +76,7 @@ def init_column_field(cls, column: GenTableColumnModel, table: GenTableModel) ->
if data_type in string_types or data_type in text_types:
# 字符串长度超过500设置为文本域
- column_length = cls.get_column_length(column.column_type)
+ column_length = cls.get_column_length(column_type)
html_type = (
GenConstant.HTML_TEXTAREA
if column_length >= cls.TEXTAREA_COLUMN_LENGTH or data_type in text_types
diff --git a/ruoyi-fastapi-backend/utils/import_util.py b/ruoyi-fastapi-backend/utils/import_util.py
index 154fd290f..91cad9282 100644
--- a/ruoyi-fastapi-backend/utils/import_util.py
+++ b/ruoyi-fastapi-backend/utils/import_util.py
@@ -4,7 +4,7 @@
import sys
from functools import lru_cache
from pathlib import Path
-from typing import Any
+from typing import TypeGuard
from sqlalchemy import inspect as sa_inspect
@@ -29,7 +29,7 @@ def find_project_root(cls) -> Path:
return Path(__file__).resolve().parent
@classmethod
- def is_valid_model(cls, obj: Any, base_class: Base) -> bool:
+ def is_valid_model(cls, obj: object, base_class: type[Base]) -> TypeGuard[type[Base]]:
"""
验证是否为有效的SQLAlchemy模型类。
@@ -53,7 +53,7 @@ def is_valid_model(cls, obj: Any, base_class: Base) -> bool:
@classmethod
@lru_cache(maxsize=256)
- def find_models(cls, base_class: Base) -> list[Base]:
+ def find_models(cls, base_class: type[Base]) -> list[type[Base]]:
"""
查找并过滤有效的模型类,避免重复和无效定义。
diff --git a/ruoyi-fastapi-backend/utils/jwt_util.py b/ruoyi-fastapi-backend/utils/jwt_util.py
index dbe114b8c..6e1239233 100644
--- a/ruoyi-fastapi-backend/utils/jwt_util.py
+++ b/ruoyi-fastapi-backend/utils/jwt_util.py
@@ -2,6 +2,7 @@
import jwt
from jwt.exceptions import PyJWTError
+from jwt.types import Options
from config.env import JwtConfig
from exceptions.exception import AuthException
@@ -27,7 +28,7 @@ def encode(cls, payload: dict[str, Any]) -> str:
raise AuthException(data='', message='用户token生成失败', msg_key='auth.tokenGenerationFailed') from exc
@classmethod
- def decode(cls, token: str | bytes, options: dict[str, Any] | None = None) -> dict[str, Any]:
+ def decode(cls, token: str | bytes, options: Options | None = None) -> dict[str, Any]:
"""
解析JWT并将PyJWT异常转换为认证异常。
diff --git a/ruoyi-fastapi-backend/utils/log_util.py b/ruoyi-fastapi-backend/utils/log_util.py
index 3d77fb491..9f9b65c03 100644
--- a/ruoyi-fastapi-backend/utils/log_util.py
+++ b/ruoyi-fastapi-backend/utils/log_util.py
@@ -7,15 +7,20 @@
import traceback
from collections.abc import Mapping, Sequence
from datetime import UTC
-from typing import Any
+from typing import TYPE_CHECKING, Any
from loguru import logger as _logger
-from loguru._logger import Logger
from config.env import AppConfig, LogConfig
from middlewares.trace_middleware import TraceCtx
from utils.server_util import WorkerIdUtil
+if TYPE_CHECKING:
+ from loguru import Logger, Record
+else:
+ Logger = type(_logger)
+ Record = dict
+
def _split_field_tokens(field_name: str) -> tuple[str, ...]:
"""
@@ -456,7 +461,7 @@ def _ensure_log_directory_exists(self) -> None:
if self._log_base_dir and not os.path.exists(self._log_base_dir):
os.makedirs(self._log_base_dir, exist_ok=True)
- def _filter(self, record: dict) -> bool:
+ def _filter(self, record: 'Record') -> bool:
"""
注入 Trace 上下文并执行日志扩展字段脱敏。
@@ -507,7 +512,7 @@ def _get_exception_traceback_text(self, exception: Any) -> str | None:
traceback_text = str(exception.traceback)
return LogSanitizer.sanitize_text(traceback_text.rstrip())
- def _build_plain_exception_suffix(self, record: dict) -> str:
+ def _build_plain_exception_suffix(self, record: 'Record') -> str:
"""
构建普通文本日志使用的异常后缀。
@@ -517,7 +522,7 @@ def _build_plain_exception_suffix(self, record: dict) -> str:
exception_text = self._get_exception_traceback_text(record.get('exception'))
return f'\n{exception_text}' if exception_text else ''
- def _build_json_payload(self, record: dict) -> dict:
+ def _build_json_payload(self, record: 'Record') -> dict:
"""
构建统一的 JSON 日志结构。
@@ -551,7 +556,7 @@ def _build_json_payload(self, record: dict) -> dict:
'extra': {key: value for key, value in record['extra'].items() if key != 'json_payload'},
}
- def _json_log_formatter(self, record: dict) -> str:
+ def _json_log_formatter(self, record: 'Record') -> str:
"""
将 Loguru 日志记录格式化为 JSON 文本。
@@ -561,7 +566,7 @@ def _json_log_formatter(self, record: dict) -> str:
record['extra']['json_payload'] = json.dumps(self._build_json_payload(record), ensure_ascii=False, default=str)
return '{extra[json_payload]}\n'
- def _plain_log_formatter(self, record: dict) -> str:
+ def _plain_log_formatter(self, record: 'Record') -> str:
"""
将 Loguru 日志记录格式化为普通文本,并追加脱敏后的异常堆栈。
@@ -580,18 +585,16 @@ def _plain_log_formatter(self, record: dict) -> str:
'{message} {extra[sanitized_exception]}\n'
)
- def _patch_record(self, record: dict) -> dict:
+ def _patch_record(self, record: 'Record') -> None:
"""
在日志落地前统一脱敏。
:param record: Loguru 日志记录字典
- :return: 脱敏后的日志记录字典
"""
record['message'] = LogSanitizer.sanitize_text(record['message'])
record['time'] = record['time'].astimezone(UTC)
- return record
- def _info_file_filter(self, record: dict) -> bool:
+ def _info_file_filter(self, record: 'Record') -> bool:
"""
仅输出 INFO 级别日志到 info 文件。
@@ -600,7 +603,7 @@ def _info_file_filter(self, record: dict) -> bool:
"""
return self._filter(record) and record['level'].name == 'INFO'
- def _error_file_filter(self, record: dict) -> bool:
+ def _error_file_filter(self, record: 'Record') -> bool:
"""
输出 WARNING 及以上日志到 error 文件。
@@ -618,7 +621,7 @@ def _configure_logging(self) -> None:
for logger_name in ('LiteLLM', 'litellm'):
logging.getLogger(logger_name).setLevel(logging.WARNING)
- def init_log(self) -> Logger:
+ def init_log(self) -> 'Logger':
"""
初始化 Loguru 输出与标准 logging 配置。
diff --git a/ruoyi-fastapi-backend/utils/oidc_util.py b/ruoyi-fastapi-backend/utils/oidc_util.py
index 495d181d7..16e2202f8 100644
--- a/ruoyi-fastapi-backend/utils/oidc_util.py
+++ b/ruoyi-fastapi-backend/utils/oidc_util.py
@@ -9,7 +9,7 @@
import secrets
from collections.abc import Collection, Iterable, Mapping, Sequence
from datetime import datetime
-from typing import Any
+from typing import Any, TypeGuard
from urllib.parse import parse_qsl, unquote_plus, urlencode, urlsplit, urlunsplit
from uuid import RFC_4122, UUID
@@ -602,7 +602,7 @@ def validate_path_identifier(value: str, field_name: str) -> str:
return value
@classmethod
- def is_valid_kid(cls, value: Any) -> bool:
+ def is_valid_kid(cls, value: object) -> TypeGuard[str]:
"""
检查签名密钥标识的字符集和长度。
@@ -1281,15 +1281,11 @@ def normalize_public_jwk(
raise ValueError('签名密钥标识 kid 包含不允许的字符')
if record_kid is not None and kid != record_kid:
raise ValueError('公开 JWK 的 kid 与数据库密钥标识不匹配')
- result = {field: value.get(field) for field in ('kty', 'use', 'kid', 'alg', 'n', 'e')}
- result.update({'kty': 'RSA', 'use': 'sig', 'kid': kid, 'alg': 'RS256'})
- if (
- not isinstance(result.get('n'), str)
- or not result['n']
- or not isinstance(result.get('e'), str)
- or not result['e']
- ):
+ n = value.get('n')
+ e = value.get('e')
+ if not isinstance(n, str) or not n or not isinstance(e, str) or not e:
raise ValueError('公开 JWK 必须包含 n 和 e')
+ result = {'kty': 'RSA', 'use': 'sig', 'kid': kid, 'alg': 'RS256', 'n': n, 'e': e}
try:
n_bytes = base64.urlsafe_b64decode(result['n'] + '=' * (-len(result['n']) % 4))
e_bytes = base64.urlsafe_b64decode(result['e'] + '=' * (-len(result['e']) % 4))
diff --git a/ruoyi-fastapi-backend/utils/openapi_util.py b/ruoyi-fastapi-backend/utils/openapi_util.py
index 4f93e8e49..5f7400ea7 100644
--- a/ruoyi-fastapi-backend/utils/openapi_util.py
+++ b/ruoyi-fastapi-backend/utils/openapi_util.py
@@ -9,6 +9,7 @@
from starlette.routing import BaseRoute
from common.auth_policy import AuthPolicy, AuthRule
+from common.context import CompiledExcludeRoute
from module_admin.service.login_service import LoginService, oauth2_scheme
@@ -38,10 +39,16 @@ def adjust_security(cls, schema: dict[str, Any], routes: Sequence[BaseRoute]) ->
:return: 调整后的OpenAPI文档
"""
for route, method in cls._iter_auth_routes(routes):
- requirements = list(
- AuthPolicy.iter_auth_dependencies(route.dependant, (LoginService.get_current_user, oauth2_scheme))
- )
- if not requirements or any(item is None for item in requirements):
+ requirements: list[AuthRule] = []
+ for rule in AuthPolicy.iter_auth_dependencies(
+ route.dependant, (LoginService.get_current_user, oauth2_scheme)
+ ):
+ if rule is None:
+ # 显式登录依赖要求认证,保留原有安全声明。
+ requirements.clear()
+ break
+ requirements.append(rule)
+ if not requirements:
continue
# 同名的其他安全依赖仍可能要求凭证,不能随宿主登录声明一起移除。
if cls._has_external_login_scheme(route.dependant):
@@ -226,7 +233,7 @@ def _has_template_coverage(cls, route: Any, method: str, pre_auth: AuthRule) ->
return any(re.sub(r'\{[^}]+\}', '{}', rule['original_path']) == skeleton for rule in rules)
@staticmethod
- def _method_rules(pre_auth: AuthRule, method: str) -> list[dict[str, Any]]:
+ def _method_rules(pre_auth: AuthRule, method: str) -> list[CompiledExcludeRoute]:
"""
获取适用于当前HTTP方法的排除规则。
@@ -382,12 +389,14 @@ def _get_candidate_path(
:param ignored_paths: 例外路径
:return: 用于检查规则交集的实际路径
"""
- values = list(segments)
+ values: list[str] = []
ignored_segments = [path.split('/') for path in ignored_paths]
- for index, convertor in convertors.items():
- if values[index] is not None:
+ for index, segment in enumerate(segments):
+ if segment is not None:
+ values.append(segment)
continue
- excluded = {parts[index] for parts in ignored_segments if len(parts) == len(values)}
+ convertor = convertors[index]
+ excluded = {parts[index] for parts in ignored_segments if len(parts) == len(segments)}
for number in range(len(excluded) + 1):
if convertor.regex == StringConvertor.regex:
candidate = f'__openapi_{number}__'
@@ -396,6 +405,6 @@ def _get_candidate_path(
else:
candidate = str(number)
if candidate not in excluded:
- values[index] = candidate
+ values.append(candidate)
break
return '/'.join(values)
diff --git a/ruoyi-fastapi-backend/utils/page_util.py b/ruoyi-fastapi-backend/utils/page_util.py
index a4c2ded14..d4992159d 100644
--- a/ruoyi-fastapi-backend/utils/page_util.py
+++ b/ruoyi-fastapi-backend/utils/page_util.py
@@ -1,12 +1,18 @@
import math
-from typing import Any
+from typing import Any, Literal, TypeVar, overload
-from sqlalchemy import Row, Select, func, select
+from sqlalchemy import Select, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
+from config.database import Base
from utils.common_util import CamelCaseUtil
+_Entity = TypeVar('_Entity', bound=Base)
+_JoinedEntity = TypeVar('_JoinedEntity', bound=Base)
+_EntityPairs = list[list[dict[str, Any] | None]]
+_Rows = list[dict[str, Any] | list[dict[Any, Any]]] | list[dict[str, Any]] | _EntityPairs
+
class PageUtil:
"""分页工具类。"""
@@ -30,15 +36,71 @@ def get_page_obj(cls, data_list: list, page_num: int, page_size: int) -> PageMod
has_next = math.ceil(len(data_list) / page_size) > page_num
result = PageModel[Any](
- rows=paginated_data, pageNum=page_num, pageSize=page_size, total=len(data_list), hasNext=has_next
+ rows=paginated_data, page_num=page_num, page_size=page_size, total=len(data_list), has_next=has_next
)
return result
@classmethod
+ @overload
+ async def paginate(
+ cls,
+ db: AsyncSession,
+ query: Select,
+ page_num: int,
+ page_size: int,
+ is_page: Literal[True],
+ *,
+ as_mappings: bool = False,
+ ) -> PageModel: ...
+
+ @classmethod
+ @overload
+ async def paginate(
+ cls,
+ db: AsyncSession,
+ query: Select,
+ page_num: int,
+ page_size: int,
+ is_page: bool = False,
+ *,
+ as_mappings: Literal[True],
+ ) -> PageModel | list[dict[str, Any]]: ...
+
+ @classmethod
+ @overload
+ async def paginate(
+ cls,
+ db: AsyncSession,
+ query: Select[_Entity, _JoinedEntity],
+ page_num: int,
+ page_size: int,
+ is_page: bool = False,
+ ) -> PageModel | _EntityPairs: ...
+
+ @classmethod
+ @overload
+ async def paginate(
+ cls, db: AsyncSession, query: Select[_Entity], page_num: int, page_size: int, is_page: bool = False
+ ) -> PageModel | list[dict[str, Any]]: ...
+
+ @classmethod
+ @overload
async def paginate(
cls, db: AsyncSession, query: Select, page_num: int, page_size: int, is_page: bool = False
- ) -> PageModel | list[dict[str, Any] | list[dict[Any, Any]]]:
+ ) -> PageModel | _Rows: ...
+
+ @classmethod
+ async def paginate(
+ cls,
+ db: AsyncSession,
+ query: Select,
+ page_num: int,
+ page_size: int,
+ is_page: bool = False,
+ *,
+ as_mappings: bool = False,
+ ) -> PageModel | _Rows:
"""
输入查询语句和分页信息,返回分页数据列表结果。
@@ -47,36 +109,28 @@ async def paginate(
:param page_num: 当前页码
:param page_size: 当前页面数据量
:param is_page: 是否开启分页
- :return: 分页数据对象
+ :param as_mappings: 按投影列名返回字典,并将列名转换为小驼峰格式
+ :return: 分页对象,关闭分页时返回全部结果行
"""
if is_page:
- total = (await db.execute(select(func.count('*')).select_from(query.subquery()))).scalar()
- query_result = await db.execute(query.offset((page_num - 1) * page_size).limit(page_size))
- paginated_data: list[Row] = []
- for row in query_result:
- if row and len(row) == 1:
- paginated_data.append(row[0])
- else:
- paginated_data.append(row)
- has_next = math.ceil(total / page_size) > page_num
- result = PageModel[Any](
- rows=CamelCaseUtil.transform_result(paginated_data),
- pageNum=page_num,
- pageSize=page_size,
- total=total,
- hasNext=has_next,
- )
+ total = (await db.execute(select(func.count('*')).select_from(query.subquery()))).scalar_one()
+ query = query.offset((page_num - 1) * page_size).limit(page_size)
else:
- query_result = await db.execute(query)
- no_paginated_data: list[Row] = []
- for row in query_result:
- if row and len(row) == 1:
- no_paginated_data.append(row[0])
- else:
- no_paginated_data.append(row)
- result = CamelCaseUtil.transform_result(no_paginated_data)
-
- return result
+ total = None
+ result = await db.execute(query)
+ if as_mappings:
+ rows = [CamelCaseUtil.transform_result(dict(row)) for row in result.mappings()]
+ else:
+ rows = [CamelCaseUtil.transform_result(row[0] if len(row) == 1 else row) for row in result]
+ if total is None:
+ return rows
+ return PageModel[Any](
+ rows=rows,
+ page_num=page_num,
+ page_size=page_size,
+ total=total,
+ has_next=math.ceil(total / page_size) > page_num,
+ )
def get_page_obj(data_list: list, page_num: int, page_size: int) -> PageModel:
@@ -97,7 +151,7 @@ def get_page_obj(data_list: list, page_num: int, page_size: int) -> PageModel:
has_next = math.ceil(len(data_list) / page_size) > page_num
result = PageModel[Any](
- rows=paginated_data, pageNum=page_num, pageSize=page_size, total=len(data_list), hasNext=has_next
+ rows=paginated_data, page_num=page_num, page_size=page_size, total=len(data_list), has_next=has_next
)
return result
diff --git a/ruoyi-fastapi-backend/utils/pwd_util.py b/ruoyi-fastapi-backend/utils/pwd_util.py
index 00c0e8405..f3794d3e0 100644
--- a/ruoyi-fastapi-backend/utils/pwd_util.py
+++ b/ruoyi-fastapi-backend/utils/pwd_util.py
@@ -5,7 +5,7 @@ class PwdUtil:
"""密码工具类。"""
@classmethod
- def verify_password(cls, plain_password: str, hashed_password: str) -> bool:
+ def verify_password(cls, plain_password: str, hashed_password: str) -> bool | None:
"""
工具方法:校验当前输入的密码与数据库存储的密码是否一致。
diff --git a/ruoyi-fastapi-backend/utils/server_util.py b/ruoyi-fastapi-backend/utils/server_util.py
index 94a2e8ef5..2608b740a 100644
--- a/ruoyi-fastapi-backend/utils/server_util.py
+++ b/ruoyi-fastapi-backend/utils/server_util.py
@@ -5,6 +5,7 @@
import uuid
from collections.abc import Callable
from copy import deepcopy
+from functools import partial
from typing import Any
import psutil
@@ -71,7 +72,7 @@ def docs_url(cls) -> str:
return cls._DOCS_URL
@classmethod
- def proxy_docs_url(cls) -> str:
+ def proxy_docs_url(cls) -> str | None:
"""
代理文档URL。
@@ -89,7 +90,7 @@ def redoc_url(cls) -> str:
return cls._REDOC_URL
@classmethod
- def proxy_redoc_url(cls) -> str:
+ def proxy_redoc_url(cls) -> str | None:
"""
代理ReDoc文档URL。
@@ -98,7 +99,7 @@ def proxy_redoc_url(cls) -> str:
return cls._PROXY_REDOC_URL if not AppConfig.app_disable_redoc else None
@classmethod
- def proxy_oauth2_redirect_url(cls) -> str:
+ def proxy_oauth2_redirect_url(cls) -> str | None:
"""
代理OAuth2重定向URL。
@@ -124,40 +125,15 @@ def setup_docs_static_resources(
:param swagger_css_url: 用于加载Swagger UI CSS的URL
:param swagger_favicon_url: Swagger UI要使用的favicon的URL
"""
-
- def redoc_monkey_patch(*args, **kwargs) -> HTMLResponse:
- """
- 使用本地静态资源生成 ReDoc 页面。
-
- :param args: 传给被调用对象的位置参数
- :param kwargs: 传给被调用对象的关键字参数
- :return: 引用本地静态资源的 ReDoc 响应
- """
- return get_redoc_html(
- *args,
- **kwargs,
- redoc_js_url=redoc_js_url,
- redoc_favicon_url=redoc_favicon_url,
- )
-
- def swagger_ui_monkey_patch(*args, **kwargs) -> HTMLResponse:
- """
- 使用本地静态资源生成 Swagger UI 页面。
-
- :param args: 传给被调用对象的位置参数
- :param kwargs: 传给被调用对象的关键字参数
- :return: 引用本地静态资源的 Swagger UI 响应
- """
- return get_swagger_ui_html(
- *args,
- **kwargs,
- swagger_js_url=swagger_js_url,
- swagger_css_url=swagger_css_url,
- swagger_favicon_url=swagger_favicon_url,
- )
-
- applications.get_redoc_html = redoc_monkey_patch
- applications.get_swagger_ui_html = swagger_ui_monkey_patch
+ applications.get_redoc_html = partial(
+ get_redoc_html, redoc_js_url=redoc_js_url, redoc_favicon_url=redoc_favicon_url
+ )
+ applications.get_swagger_ui_html = partial(
+ get_swagger_ui_html,
+ swagger_js_url=swagger_js_url,
+ swagger_css_url=swagger_css_url,
+ swagger_favicon_url=swagger_favicon_url,
+ )
@classmethod
def custom_api_docs_router(
@@ -610,7 +586,7 @@ def get_local_ip(cls) -> str:
for snics in psutil.net_if_addrs().values():
for snic in snics:
if snic.family == socket.AF_INET and snic.address.startswith('127.'):
- return snic.address
+ return str(snic.address)
except Exception:
pass
@@ -623,7 +599,7 @@ def get_network_ips(cls) -> list[str]:
:return: 本机Network IP列表
"""
- network_ips = []
+ network_ips: list[str] = []
try:
# 获取网卡状态
stats = psutil.net_if_stats()
diff --git a/ruoyi-fastapi-backend/utils/string_util.py b/ruoyi-fastapi-backend/utils/string_util.py
index ac18f3d73..60da15c00 100644
--- a/ruoyi-fastapi-backend/utils/string_util.py
+++ b/ruoyi-fastapi-backend/utils/string_util.py
@@ -40,14 +40,14 @@ def is_not_empty(cls, string: str) -> bool:
return not cls.is_empty(string)
@classmethod
- def is_http(cls, link: str) -> bool:
+ def is_http(cls, link: str | None) -> bool:
"""
判断是否为http(s)://开头。
:param link: 链接
:return: 是否为http(s)://开头
"""
- return link.startswith((CommonConstant.HTTP, CommonConstant.HTTPS))
+ return bool(link and link.startswith((CommonConstant.HTTP, CommonConstant.HTTPS)))
@classmethod
def contains_ignore_case(cls, search_str: str, compare_str: str) -> bool:
@@ -89,7 +89,7 @@ def equals_ignore_case(cls, search_str: str, compare_str: str) -> bool:
return False
@classmethod
- def equals_any_ignore_case(cls, search_str: str, compare_str_list: list[str]) -> bool:
+ def equals_any_ignore_case(cls, search_str: str | None, compare_str_list: list[str]) -> bool:
"""
比较指定字符串是否与指定字符串列表中的任意一个字符串相等同时忽略大小写。
diff --git a/ruoyi-fastapi-backend/utils/template_util.py b/ruoyi-fastapi-backend/utils/template_util.py
index 943462694..93596a048 100644
--- a/ruoyi-fastapi-backend/utils/template_util.py
+++ b/ruoyi-fastapi-backend/utils/template_util.py
@@ -11,6 +11,7 @@
from module_generator.entity.vo.gen_vo import GenTableColumnModel, GenTableModel
from utils.common_util import CamelCaseUtil, SnakeCaseUtil
from utils.gen_i18n_util import GenI18nUtil
+from utils.gen_util import GenUtils
from utils.string_util import StringUtil
from utils.time_util import GenTimeUtil, TimezoneUtil
@@ -88,10 +89,10 @@ def prepare_context(cls, gen_table: GenTableModel) -> dict[str, Any]:
column.column_name, f'字段 {column.column_name}'
)
cls.prepare_time_columns(gen_table)
- class_name = gen_table.class_name
- module_name = gen_table.module_name
- business_name = gen_table.business_name
- package_name = gen_table.package_name
+ class_name = GenUtils.require_metadata(gen_table.class_name)
+ module_name = GenUtils.require_metadata(gen_table.module_name)
+ business_name = GenUtils.require_metadata(gen_table.business_name)
+ package_name = GenUtils.require_metadata(gen_table.package_name)
tpl_category = gen_table.tpl_category
function_name = gen_table.function_name
@@ -102,7 +103,7 @@ def prepare_context(cls, gen_table: GenTableModel) -> dict[str, Any]:
'tplCategory': tpl_category,
'tableName': gen_table.table_name,
'tableComment': gen_table.table_comment,
- 'functionName': function_name if StringUtil.is_not_empty(function_name) else '【请填写功能名称】',
+ 'functionName': function_name or '【请填写功能名称】',
'ClassName': class_name,
'className': class_name.lower(),
'moduleName': module_name,
@@ -196,8 +197,9 @@ def prepare_time_columns(cls, gen_table: GenTableModel) -> None:
continue
for column in table.columns or []:
try:
- semantics = GenTimeUtil.get_time_semantics(column.column_type, db_type)
- GenTimeUtil.validate_time_control(column.column_type, db_type, column.html_type)
+ column_type = GenUtils.require_metadata(column.column_type)
+ semantics = GenTimeUtil.get_time_semantics(column_type, db_type)
+ GenTimeUtil.validate_time_control(column_type, db_type, column.html_type)
except ServiceWarning as exc:
raise ServiceWarning(message=f'{table.table_name}.{column.column_name}: {exc.message}') from exc
column.vo_type = column.python_type
@@ -226,8 +228,7 @@ def set_menu_context(cls, context: dict, gen_table: GenTableModel) -> None:
:param context: 模板上下文字典
:param gen_table: 生成表的配置信息
"""
- options = gen_table.options
- params_obj = json.loads(options)
+ params_obj = json.loads(gen_table.options or '{}')
context['parentMenuId'] = cls.get_parent_menu_id(params_obj)
@classmethod
@@ -238,8 +239,7 @@ def set_tree_context(cls, context: dict, gen_table: GenTableModel) -> None:
:param context: 模板上下文字典
:param gen_table: 生成表的配置信息
"""
- options = gen_table.options
- params_obj = json.loads(options)
+ params_obj = json.loads(gen_table.options or '{}')
context['treeCode'] = cls.get_tree_code(params_obj)
context['treeParentCode'] = cls.get_tree_parent_code(params_obj)
context['treeName'] = cls.get_tree_name(params_obj)
@@ -252,11 +252,16 @@ def set_sub_context(cls, context: dict, gen_table: GenTableModel) -> None:
:param context: 模板上下文字典
:param gen_table: 生成表的配置信息
+ :raises ServiceWarning: 缺少关联子表或外键名
"""
sub_table = gen_table.sub_table
sub_table_name = gen_table.sub_table_name
+ if sub_table is None:
+ raise ServiceWarning(message='关联子表的表名不能为空', msg_key='generator.childTableRequired')
sub_table_fk_name = gen_table.sub_table_fk_name
- sub_class_name = sub_table.class_name
+ if not sub_table_fk_name:
+ raise ServiceWarning(message='子表关联的外键名不能为空', msg_key='generator.childForeignKeyRequired')
+ sub_class_name = GenUtils.require_metadata(sub_table.class_name)
sub_table_fk_class_name = StringUtil.convert_to_camel_case(sub_table_fk_name)
context['subTable'] = sub_table
context['subTableName'] = sub_table_name
@@ -312,9 +317,9 @@ def get_file_name(cls, template: str, gen_table: GenTableModel) -> str:
:param gen_table: 生成表的配置信息
:return: 模板生成文件名
"""
- package_name = gen_table.package_name
- module_name = gen_table.module_name
- business_name = gen_table.business_name
+ package_name = GenUtils.require_metadata(gen_table.package_name)
+ module_name = GenUtils.require_metadata(gen_table.module_name)
+ business_name = GenUtils.require_metadata(gen_table.business_name)
vue_path = cls.FRONTEND_PROJECT_PATH
python_path = f'{cls.BACKEND_PROJECT_PATH}/{package_name.replace(".", "/")}'
@@ -364,16 +369,13 @@ def get_vo_import_list(cls, gen_table: GenTableModel) -> list[str]:
if table is None:
continue
for column in table.columns or []:
- semantics = GenTimeUtil.get_time_semantics(column.column_type, db_type)
+ semantics = GenTimeUtil.get_time_semantics(GenUtils.require_metadata(column.column_type), db_type)
if semantics:
import_list.add(f'from common.types import {semantics.vo_type}')
+ if table is gen_table and column.query_type == 'BETWEEN':
+ import_list.add('from common.types import BusinessDate')
elif column.python_type == GenConstant.TYPE_DECIMAL:
import_list.add('from decimal import Decimal')
- if any(
- column.query_type == 'BETWEEN' and GenTimeUtil.get_time_semantics(column.column_type, db_type)
- for column in gen_table.columns or []
- ):
- import_list.add('from common.types import BusinessDate')
return cls.merge_same_imports(sorted(import_list), 'from common.types import')
@classmethod
@@ -391,7 +393,9 @@ def get_do_import_list(cls, gen_table: GenTableModel) -> list[str]:
if table is None:
continue
for column in table.columns or []:
- sqlalchemy_type = cls.get_sqlalchemy_type(column.column_type, gen_table.data_source_name)
+ sqlalchemy_type = cls.get_sqlalchemy_type(
+ GenUtils.require_metadata(column.column_type), gen_table.data_source_name
+ )
if sqlalchemy_type == 'DbUtcDateTime':
if column.column_name not in {'create_time', 'update_time'}:
import_list.add('from common.types import DbUtcDateTime')
@@ -449,10 +453,10 @@ def get_dicts(cls, gen_table: GenTableModel) -> str:
:return: 字典列表
"""
columns = gen_table.columns or []
- dicts = set()
+ dicts: set[str] = set()
cls.add_dicts(dicts, columns)
if gen_table.sub_table is not None:
- cls.add_dicts(dicts, gen_table.sub_table.columns)
+ cls.add_dicts(dicts, gen_table.sub_table.columns or [])
return ', '.join(dicts)
@classmethod
@@ -466,7 +470,7 @@ def add_dicts(cls, dicts: set[str], columns: list[GenTableColumnModel]) -> None:
for column in columns:
if (
not column.super_column
- and StringUtil.is_not_empty(column.dict_type)
+ and column.dict_type
and StringUtil.equals_any_ignore_case(
column.html_type, [GenConstant.HTML_SELECT, GenConstant.HTML_RADIO, GenConstant.HTML_CHECKBOX]
)
@@ -495,15 +499,16 @@ def get_col_span(cls, form_col_num: int | None) -> str:
return cls.FORM_COL_SPAN_MAP.get(form_col_num, '24')
@classmethod
- def get_parent_menu_id(cls, params_obj: dict) -> str:
+ def get_parent_menu_id(cls, params_obj: dict) -> int | str:
"""
获取上级菜单ID。
:param params_obj: 菜单参数字典
:return: 上级菜单ID
"""
- if params_obj and params_obj.get(GenConstant.PARENT_MENU_ID):
- return params_obj.get(GenConstant.PARENT_MENU_ID)
+ parent_id = params_obj.get(GenConstant.PARENT_MENU_ID)
+ if isinstance(parent_id, (int, str)) and parent_id:
+ return parent_id
return cls.DEFAULT_PARENT_MENU_ID
@classmethod
@@ -531,8 +536,8 @@ def get_tree_code(cls, params_obj: dict) -> str:
:param params_obj: 菜单参数字典
:return: 树编码
"""
- if GenConstant.TREE_CODE in params_obj:
- return cls.to_camel_case(params_obj.get(GenConstant.TREE_CODE))
+ if value := params_obj.get(GenConstant.TREE_CODE):
+ return cls.to_camel_case(value)
return ''
@classmethod
@@ -543,8 +548,8 @@ def get_tree_parent_code(cls, params_obj: dict) -> str:
:param params_obj: 菜单参数字典
:return: 树父编码
"""
- if GenConstant.TREE_PARENT_CODE in params_obj:
- return cls.to_camel_case(params_obj.get(GenConstant.TREE_PARENT_CODE))
+ if value := params_obj.get(GenConstant.TREE_PARENT_CODE):
+ return cls.to_camel_case(value)
return ''
@classmethod
@@ -555,8 +560,8 @@ def get_tree_name(cls, params_obj: dict) -> str:
:param params_obj: 菜单参数字典
:return: 树名称
"""
- if GenConstant.TREE_NAME in params_obj:
- return cls.to_camel_case(params_obj.get(GenConstant.TREE_NAME))
+ if value := params_obj.get(GenConstant.TREE_NAME):
+ return cls.to_camel_case(value)
return ''
@classmethod
@@ -567,8 +572,7 @@ def get_expand_column(cls, gen_table: GenTableModel) -> int:
:param gen_table: 生成表的配置信息
:return: 展开列
"""
- options = gen_table.options
- params_obj = json.loads(options)
+ params_obj = json.loads(gen_table.options or '{}')
tree_name = params_obj.get(GenConstant.TREE_NAME)
num = 0
for column in gen_table.columns or []:
@@ -610,7 +614,8 @@ def get_sqlalchemy_type(cls, column_type: str, source_name: str | None = None) -
return semantics.sqlalchemy_type
type_mapping = GenConstant.DB_TO_SQLALCHEMY_TYPE_MAPPING[source_config.db_type]
sqlalchemy_type = StringUtil.get_mapping_value_by_key_ignore_case(type_mapping, base) or 'String'
- if '(' in normalized and sqlalchemy_type in {'String', 'CHAR', 'Numeric', 'DECIMAL'}:
- precision = re.search(r'\(([^)]*)\)', normalized).group(1)
- return f'{sqlalchemy_type}({precision})'
+ if sqlalchemy_type in {'String', 'CHAR', 'Numeric', 'DECIMAL'} and (
+ precision := re.search(r'\(([^)]*)\)', normalized)
+ ):
+ return f'{sqlalchemy_type}({precision[1]})'
return sqlalchemy_type
diff --git a/ruoyi-fastapi-backend/utils/transport_crypto_util.py b/ruoyi-fastapi-backend/utils/transport_crypto_util.py
index 327afef66..812055e29 100644
--- a/ruoyi-fastapi-backend/utils/transport_crypto_util.py
+++ b/ruoyi-fastapi-backend/utils/transport_crypto_util.py
@@ -6,10 +6,10 @@
from dataclasses import dataclass
from datetime import UTC, datetime
from threading import Lock
-from typing import Any
+from typing import Any, cast
from cryptography.hazmat.primitives import hashes, serialization
-from cryptography.hazmat.primitives.asymmetric import padding
+from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from fastapi import FastAPI, Request
from redis import asyncio as aioredis
@@ -156,12 +156,20 @@ def get_current_key_pair(cls) -> TransportKeyPair:
:return: 当前启用的密钥对
"""
+ return cls._get_key_pairs()[TransportCryptoConfig.transport_crypto_kid]
+
+ @classmethod
+ def _get_key_pairs(cls) -> dict[str, TransportKeyPair]:
+ """
+ 首次读取时加载当前和历史密钥对。
+
+ :return: 按版本索引的密钥对
+ """
if cls._key_pairs is None:
with cls._lock:
if cls._key_pairs is None:
cls._key_pairs = cls._build_key_pairs()
-
- return cls._key_pairs[TransportCryptoConfig.transport_crypto_kid]
+ return cls._key_pairs
@classmethod
def get_current_kid(cls) -> str:
@@ -202,11 +210,7 @@ def get_key_pair(cls, kid: str | None = None) -> TransportKeyPair:
:raises TransportKeyError: 密钥版本不存在
"""
target_kid = kid or cls.get_current_kid()
- if cls._key_pairs is None:
- with cls._lock:
- if cls._key_pairs is None:
- cls._key_pairs = cls._build_key_pairs()
- key_pair = cls._key_pairs.get(target_kid)
+ key_pair = cls._get_key_pairs().get(target_kid)
if key_pair is None:
raise TransportKeyError('密钥版本不存在', msg_key='transport.keyExpired')
return key_pair
@@ -218,9 +222,7 @@ def get_supported_kids(cls) -> tuple[str, ...]:
:return: 当前支持解密的密钥版本元组
"""
- if cls._key_pairs is None:
- cls.get_current_key_pair()
- return tuple(cls._key_pairs.keys())
+ return tuple(cls._get_key_pairs())
@classmethod
def _build_key_pairs(cls) -> dict[str, TransportKeyPair]:
@@ -470,6 +472,8 @@ def decrypt_request_key(cls, envelope: dict[str, Any]) -> bytes:
kid = str(envelope['kid'])
private_key_pem = TransportKeyProvider.get_private_key_pem(kid)
private_key = serialization.load_pem_private_key(private_key_pem.encode('utf-8'), password=None)
+ if not isinstance(private_key, rsa.RSAPrivateKey):
+ raise TransportKeyError('请求密钥解密失败', msg_key='transport.decryptFailed')
encrypted_key = _urlsafe_b64decode(str(envelope['ek']))
try:
return private_key.decrypt(
@@ -512,15 +516,19 @@ def encrypt_response_body(
return json.dumps(encrypted_payload, ensure_ascii=False).encode('utf-8')
@classmethod
- def decode_query_envelope(cls, encrypted_query: str) -> dict[str, Any]:
+ def decode_query_envelope(cls, encrypted_query: str) -> dict[str, object]:
"""
解码查询参数中的加密信封。
:param encrypted_query: 查询参数中的加密信封字符串
:return: 解码后的信封字典
+ :raises ValueError: 解码后的查询参数不是 JSON 对象
"""
decoded_query = _urlsafe_b64decode(encrypted_query).decode('utf-8')
- return json.loads(decoded_query)
+ payload = json.loads(decoded_query)
+ if not isinstance(payload, dict):
+ raise ValueError('加密查询参数格式不合法')
+ return cast('dict[str, object]', payload)
@classmethod
def build_public_key_payload(cls) -> dict[str, Any]:
@@ -1197,7 +1205,7 @@ def _get_redis_client(cls, app: FastAPI | None) -> aioredis.Redis | None:
"""
if app is None:
return None
- return getattr(app.state, 'redis', None)
+ return cast('aioredis.Redis | None', getattr(app.state, 'redis', None))
@classmethod
def _increase_kid_counter_local(cls, kid: str | None, counter_name: str) -> None:
diff --git a/ruoyi-fastapi-backend/utils/upload_util.py b/ruoyi-fastapi-backend/utils/upload_util.py
index 949636212..a9ebad2e2 100644
--- a/ruoyi-fastapi-backend/utils/upload_util.py
+++ b/ruoyi-fastapi-backend/utils/upload_util.py
@@ -7,7 +7,7 @@
from typing import TYPE_CHECKING
from urllib.parse import quote
-import aiofiles
+import anyio
from fastapi import UploadFile
from config.env import UploadConfig
@@ -264,7 +264,7 @@ async def generate_file(
"""
if start < 0 or (length is not None and length < 0):
raise ValueError('文件读取范围不合法')
- async with aiofiles.open(filepath, 'rb') as response_file:
+ async with await anyio.open_file(filepath, 'rb') as response_file:
await response_file.seek(start)
remaining = length
while remaining is None or remaining > 0:
diff --git a/ruoyi-fastapi-backend/utils/user_import_util.py b/ruoyi-fastapi-backend/utils/user_import_util.py
index c545e4c5e..154a07185 100644
--- a/ruoyi-fastapi-backend/utils/user_import_util.py
+++ b/ruoyi-fastapi-backend/utils/user_import_util.py
@@ -1,4 +1,7 @@
+from collections.abc import Sequence
+from math import trunc
from numbers import Real
+from typing import SupportsInt
from exceptions.exception import ServiceException
@@ -27,7 +30,7 @@ class UserImportUtil:
}
@classmethod
- def normalize_headers(cls, headers: list[object]) -> list[str]:
+ def normalize_headers(cls, headers: Sequence[object]) -> list[str]:
"""
独立于界面语言识别已发布模板,拒绝歧义或缺失的必需列。
@@ -77,7 +80,7 @@ def normalize_value(cls, field: str, value: object) -> str:
:raises ServiceException: 导入字段的显示名称或枚举码值无效
"""
if isinstance(value, Real) and not isinstance(value, bool) and float(value).is_integer():
- value = int(value)
+ value = int(value) if isinstance(value, SupportsInt) else trunc(value)
normalized = str(value).strip().casefold()
for code, aliases in cls.VALUE_ALIASES[field].items():
if normalized in {code, *(alias.casefold() for alias in aliases)}:
diff --git a/ruoyi-fastapi-test/common/base_page_test.py b/ruoyi-fastapi-test/common/base_page_test.py
index ae5a76b00..bf823b5e8 100644
--- a/ruoyi-fastapi-test/common/base_page_test.py
+++ b/ruoyi-fastapi-test/common/base_page_test.py
@@ -1,24 +1,28 @@
+from __future__ import annotations
+
import re
+from typing import TYPE_CHECKING
-from playwright.async_api import Locator
+if TYPE_CHECKING:
+ from playwright.async_api import BrowserContext, ElementHandle, Locator, Page
-from common.browser_harness import BrowserHarness
+ from common.browser_harness import BrowserHarness
class BasePageTest:
"""
为页面端到端测试提供通用的浏览器和登录操作。
- :cvar harness: 为端到端测试管理资源的夹具
- :cvar context: 当前操作所需的上下文
- :cvar page: 浏览器页面或要查询的页码
- :cvar token: 用于身份验证或授权的令牌
+ :ivar harness: 为当前用例管理资源的浏览器夹具
+ :ivar context: 当前用例独立的浏览器上下文
+ :ivar page: 在当前上下文中创建的测试页面
+ :ivar token: 当前用例的登录令牌
"""
- harness = None
- context = None
- page = None
- token = None
+ harness: BrowserHarness
+ context: BrowserContext
+ page: Page
+ token: str
async def setup(self, harness: BrowserHarness) -> None:
"""
@@ -75,12 +79,12 @@ async def wait_for_selector(self, selector: str, timeout_ms: int = 10000) -> Non
"""
await self.page.wait_for_selector(selector, timeout=timeout_ms)
- async def query_selector(self, selector: str) -> any:
+ async def query_selector(self, selector: str) -> ElementHandle | None:
"""
查询选择器元素。
:param selector: 定位页面元素的选择器
- :return: 选择器元素
+ :return: 首个匹配的元素,未匹配时返回 ``None``
"""
return await self.page.query_selector(selector)
@@ -91,6 +95,7 @@ async def click_button(self, button_text: str) -> None:
:param button_text: 目标按钮显示的文字
"""
button = await self.page.wait_for_selector(f'text="{button_text}"', timeout=5000)
+ assert button is not None, f'未找到按钮:{button_text}'
await button.click()
async def fill_input(self, selector: str, value: str) -> None:
@@ -102,12 +107,12 @@ async def fill_input(self, selector: str, value: str) -> None:
"""
await self.page.fill(selector, value)
- async def get_text_content(self, selector: str) -> str:
+ async def get_text_content(self, selector: str) -> str | None:
"""
获取元素文本内容。
:param selector: 定位页面元素的选择器
- :return: 元素文本内容
+ :return: 匹配元素的文本,元素或文本不存在时返回 ``None``
"""
element = await self.page.query_selector(selector)
if element:
@@ -123,6 +128,6 @@ async def get_table_total_rows(self) -> int:
element = self.page.locator('span.el-pagination__total').first
text = await element.text_content()
- # 提取数字
- number = re.search(r'\d+', text).group()
- return int(number)
+ match = re.search(r'\d+', text or '')
+ assert match is not None, f'分页总数缺少数字:{text!r}'
+ return int(match.group())
diff --git a/ruoyi-fastapi-test/common/browser_harness.py b/ruoyi-fastapi-test/common/browser_harness.py
index 2225ab707..88d9b5303 100644
--- a/ruoyi-fastapi-test/common/browser_harness.py
+++ b/ruoyi-fastapi-test/common/browser_harness.py
@@ -4,6 +4,7 @@
import hashlib
import json
import re
+from functools import partial
from http import HTTPStatus
from typing import TYPE_CHECKING
from urllib.parse import urlparse
@@ -13,7 +14,16 @@
if TYPE_CHECKING:
from pathlib import Path
- from playwright.async_api import APIRequestContext, APIResponse, Browser, BrowserContext, Page, Playwright, Response
+ from playwright.async_api import (
+ APIRequestContext,
+ APIResponse,
+ Browser,
+ BrowserContext,
+ Page,
+ Playwright,
+ Response,
+ ViewportSize,
+ )
_API_TIMEOUT_MS = 15000
_LOGIN_MAX_ATTEMPTS = 3
@@ -48,7 +58,7 @@ async def _login_token(response: APIResponse | Response) -> str:
assert response.ok, f'登录 HTTP 状态异常:{response.status}'
payload = await response.json()
token = payload.get('token') or (payload.get('data') or {}).get('token')
- assert token, f'登录未返回令牌:{payload.get("msg", "未知错误")}'
+ assert isinstance(token, str) and token, f'登录未返回令牌:{payload.get("msg", "未知错误")}'
return token
@@ -166,9 +176,9 @@ async def new_context(self, *, token: str | None = None, **options) -> BrowserCo
:param options: 调用方按名称传入的附加选项
:return: 当前操作所需的上下文
"""
- context = await self.browser.new_context(
- **{'base_url': Config.frontend_url, 'viewport': {'width': 1440, 'height': 1000}, **options}
- )
+ viewport: ViewportSize = {'width': 1440, 'height': 1000}
+ create_context = partial(self.browser.new_context, base_url=Config.frontend_url, viewport=viewport)
+ context = await create_context(**options)
self.contexts.append(context)
context.set_default_timeout(15000)
context.set_default_navigation_timeout(30000)
diff --git a/ruoyi-fastapi-test/common/login_helper.py b/ruoyi-fastapi-test/common/login_helper.py
index 6b6b8f1a1..8e3883680 100644
--- a/ruoyi-fastapi-test/common/login_helper.py
+++ b/ruoyi-fastapi-test/common/login_helper.py
@@ -47,7 +47,7 @@ def login(self, username: str = 'admin', password: str = 'admin123', max_retries
if not token:
token = result.get('data', {}).get('token') # 在data对象内
- if token:
+ if isinstance(token, str) and token:
print('登录成功')
return token
print(f'登录失败: 响应中未找到token - {result}')
diff --git a/ruoyi-fastapi-test/conftest.py b/ruoyi-fastapi-test/conftest.py
index ba6a1e63b..895dd0e52 100644
--- a/ruoyi-fastapi-test/conftest.py
+++ b/ruoyi-fastapi-test/conftest.py
@@ -19,18 +19,21 @@
from playwright.async_api import Browser, Playwright
-@pytest.hookimpl(hookwrapper=True)
-def pytest_runtest_makereport(item: pytest.Item, call: pytest.CallInfo) -> Generator:
+@pytest.hookimpl(wrapper=True)
+def pytest_runtest_makereport(
+ item: pytest.Item, call: pytest.CallInfo
+) -> Generator[None, pytest.TestReport, pytest.TestReport]:
"""
在浏览器 fixture 回收前保存调用结果,确保断言失败仍能导出诊断。
:param item: 当前要处理的条目
:param call: 需要执行或验证的调用
:yield: 上下文就绪后将控制权交给调用方
+ :return: 当前测试阶段生成的报告
"""
- result = yield
- report = result.get_result()
+ report = yield
setattr(item, f'rep_{report.when}', report)
+ return report
@pytest_asyncio.fixture(scope='session', loop_scope='session')
@@ -68,8 +71,8 @@ async def browser_harness(
yield harness
finally:
failed = any(
- getattr(request.node, f'rep_{phase}', None).failed
+ report.failed
for phase in ('setup', 'call')
- if hasattr(request.node, f'rep_{phase}')
+ if (report := getattr(request.node, f'rep_{phase}', None)) is not None
)
await harness.finish(failed=failed)
diff --git a/ruoyi-fastapi-test/monitor/test_job_management.py b/ruoyi-fastapi-test/monitor/test_job_management.py
index ec35eb1c5..623cedb71 100644
--- a/ruoyi-fastapi-test/monitor/test_job_management.py
+++ b/ruoyi-fastapi-test/monitor/test_job_management.py
@@ -237,6 +237,7 @@ async def run_job_once(self, job_name: str) -> str:
confirm = dialog.get_by_role('button', name=button_name('确定'))
execution = await self.submit(confirm.click, 'PUT', '/monitor/job/run')
execution_id = execution['executionId']
+ assert isinstance(execution_id, str)
result = await self.poll_api(
f'/monitor/job/execution/{execution_id}',
lambda payload: payload['data']['status'] not in ('pending', 'submitted', 'running'),
diff --git a/ruoyi-fastapi-test/requirements.txt b/ruoyi-fastapi-test/requirements.txt
index 7e7d5f95f..66db1e689 100644
--- a/ruoyi-fastapi-test/requirements.txt
+++ b/ruoyi-fastapi-test/requirements.txt
@@ -4,3 +4,4 @@ pytest-asyncio==1.5.0
pytest-playwright==0.10.0
requests==2.34.2
ruff==0.17.6
+ty==0.0.108
diff --git a/ruoyi-fastapi-test/system/page.py b/ruoyi-fastapi-test/system/page.py
index c178c90b5..f484df707 100644
--- a/ruoyi-fastapi-test/system/page.py
+++ b/ruoyi-fastapi-test/system/page.py
@@ -238,7 +238,7 @@ async def payload(response: Response) -> dict:
assert payload.get('code') == HTTPStatus.OK, f'{response.url}: {payload}'
return payload
- async def action(self, trigger: Callable[[], Awaitable[None]], path: str, method: str = 'GET') -> dict:
+ async def action(self, trigger: Callable[[], Awaitable[object]], path: str, method: str = 'GET') -> dict:
"""
先监听目标响应,再执行点击,避免固定睡眠和遗漏快速响应。
diff --git a/ruoyi-fastapi-test/system/test_plugin_management.py b/ruoyi-fastapi-test/system/test_plugin_management.py
index 81e97a364..f771d7e9b 100644
--- a/ruoyi-fastapi-test/system/test_plugin_management.py
+++ b/ruoyi-fastapi-test/system/test_plugin_management.py
@@ -13,7 +13,7 @@
from system.page import SystemPage
if TYPE_CHECKING:
- from playwright.async_api import Locator, Request, Response
+ from playwright.async_api import APIRequestContext, Locator, Request, Response
from common.browser_harness import BrowserHarness
@@ -207,15 +207,15 @@ async def close_dialog(view: SystemPage) -> None:
await view.close_dialog()
-async def assert_unchanged(view: SystemPage, before: dict) -> None:
+async def assert_unchanged(api: APIRequestContext, before: dict) -> None:
"""
计划查看不能修改插件的安装版本、启用设置或状态。
- :param view: 通过真实界面操作与真实接口结果同步系统管理测试
+ :param api: 查询插件状态的 API 客户端
:param before: 变更前取得的状态
"""
# 只读核验允许连接被重置后重建一次;HTTP 和业务错误仍由下方断言报告。
- response = await view.api.get(f'{RESOURCE}/{PLUGIN_ID}', max_retries=1)
+ response = await api.get(f'{RESOURCE}/{PLUGIN_ID}', max_retries=1)
assert response.ok
payload = await response.json()
assert payload['code'] == HTTPStatus.OK, payload
@@ -296,7 +296,7 @@ async def test_plugin_search_detail_and_metrics(browser_harness: BrowserHarness)
await verify_manifest_tabs(view, detail)
await verify_metrics(view)
await close_dialog(view)
- await assert_unchanged(view, plugin)
+ await assert_unchanged(view.api, plugin)
async def request_dependency_preview(view: SystemPage, endpoint: str) -> dict:
@@ -424,7 +424,7 @@ async def test_plugin_dependency_report_and_plan(browser_harness: BrowserHarness
assert urlsplit(writes[0].url).path.endswith(f'{endpoint}/install')
assert parse_qs(urlsplit(writes[0].url).query)['dryRun'] == ['true']
await close_dialog(view)
- await assert_unchanged(view, plugin)
+ await assert_unchanged(view.api, plugin)
async def test_plugin_install_plan(browser_harness: BrowserHarness) -> None:
@@ -460,7 +460,7 @@ async def test_plugin_install_plan(browser_harness: BrowserHarness) -> None:
await verify_install_plan_dialog(view, payload)
await close_dialog(view)
assert writes == [], '查看拓扑计划不得发出插件写请求'
- await assert_unchanged(view, plugin)
+ await assert_unchanged(view.api, plugin)
async def verify_install_plan_dialog(view: SystemPage, payload: dict) -> None:
diff --git a/ruoyi-fastapi-test/test_browser_harness.py b/ruoyi-fastapi-test/test_browser_harness.py
index 8afca80bd..6bd86153d 100644
--- a/ruoyi-fastapi-test/test_browser_harness.py
+++ b/ruoyi-fastapi-test/test_browser_harness.py
@@ -13,6 +13,7 @@
from prepare_e2e_compose import isolate_compose
if TYPE_CHECKING:
+ from collections.abc import Sequence
from pathlib import Path
from playwright.async_api import Browser, Playwright
@@ -37,7 +38,7 @@ def login_response(status: HTTPStatus, *, retry_after: str | None = None, payloa
)
-def login_harness(tmp_path: Path, responses: list[object]) -> tuple[BrowserHarness, AsyncMock]:
+def login_harness(tmp_path: Path, responses: Sequence[object]) -> tuple[BrowserHarness, AsyncMock]:
"""
仅替换网络边界,直接运行实际登录重试逻辑。
diff --git a/ruoyi-fastapi-test/test_code_gen_harness.py b/ruoyi-fastapi-test/test_code_gen_harness.py
index b056d0dba..23ac9b2bb 100644
--- a/ruoyi-fastapi-test/test_code_gen_harness.py
+++ b/ruoyi-fastapi-test/test_code_gen_harness.py
@@ -86,7 +86,9 @@ async def respond(route: Route) -> None:
:param route: 当前请求匹配的路由
"""
if route.request.method == 'PUT':
- saved.update(route.request.post_data_json)
+ submitted = route.request.post_data_json
+ assert isinstance(submitted, dict), submitted
+ saved.update(submitted)
await route.fulfill(json={'code': 200})
elif route.request.url.endswith('/tool/gen/list'):
await route.fulfill(json={'code': 200, 'rows': [saved]})
diff --git a/ruoyi-fastapi-test/test_pages.py b/ruoyi-fastapi-test/test_pages.py
index 7b0d28479..d120f0222 100644
--- a/ruoyi-fastapi-test/test_pages.py
+++ b/ruoyi-fastapi-test/test_pages.py
@@ -24,9 +24,10 @@ def builtin_routes(routes: list[dict[str, Any]], parent: str = '') -> set[str]:
:param parent: 用于判断路径从属关系的父目录
:return: 服务端真实返回的内置页面
"""
- paths = set()
+ paths: set[str] = set()
for route in routes:
segment = route['path']
+ assert isinstance(segment, str)
if segment.startswith(('http://', 'https://')):
continue
path = segment if segment.startswith('/') else f'{parent}/{segment}'
@@ -51,10 +52,10 @@ async def test_every_builtin_menu_has_a_page_case(browser_harness: BrowserHarnes
async def test_builtin_menu_loads_data_and_content(browser_harness: BrowserHarness, case: PageCase) -> None:
"""每个真实菜单都必须加载业务内容及成功的后端响应,而不是只显示导航标题。"""
page = await browser_harness.new_page(authenticated=True)
- if case.api:
+ if api_path := case.api:
async with page.expect_response(
lambda response: (
- urlparse(response.url).path.endswith(case.api)
+ urlparse(response.url).path.endswith(api_path)
and response.request.method == 'GET'
and response.request.resource_type in {'xhr', 'fetch'}
)
diff --git a/ruoyi-fastapi-test/test_plugin_network_harness.py b/ruoyi-fastapi-test/test_plugin_network_harness.py
index dc87c2d20..03999b01b 100644
--- a/ruoyi-fastapi-test/test_plugin_network_harness.py
+++ b/ruoyi-fastapi-test/test_plugin_network_harness.py
@@ -2,7 +2,6 @@
import asyncio
import json
-from types import SimpleNamespace
from typing import TYPE_CHECKING
import pytest
@@ -53,12 +52,11 @@ async def respond(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) ->
port = server.sockets[0].getsockname()[1]
api = await e2e_browser[0].request.new_context(base_url=f'http://127.0.0.1:{port}')
try:
- view = SimpleNamespace(api=api)
if scenario == 'reset_once':
- await assert_unchanged(view, before)
+ await assert_unchanged(api, before)
else:
with pytest.raises(Error if scenario == 'reset_always' else AssertionError):
- await assert_unchanged(view, before)
+ await assert_unchanged(api, before)
finally:
await api.dispose()
assert len(requests) == (2 if scenario.startswith('reset_') else 1)
diff --git a/ruoyi-fastapi-test/tool/test_code_gen.py b/ruoyi-fastapi-test/tool/test_code_gen.py
index 901e2ecee..20d09ab0d 100644
--- a/ruoyi-fastapi-test/tool/test_code_gen.py
+++ b/ruoyi-fastapi-test/tool/test_code_gen.py
@@ -119,6 +119,7 @@ async def edit_table(self) -> None:
await self.page.get_by_role('button', name=button_name('提交')).click()
response = await pending.value
submitted = response.request.post_data_json
+ assert isinstance(submitted, dict), submitted
assert submitted['tableComment'] == self.table_comment, submitted
await self.payload(response)
await self.page.wait_for_url(re.compile(r'/tool/gen(?:\?.*)?$'))
@@ -220,7 +221,7 @@ async def delete_table(self) -> None:
available = await api.get('/tool/gen/db/list', params={'tableName': self.table_name})
assert any(row['tableName'] == self.table_name for row in (await available.json())['rows'])
- async def cleanup(self) -> None:
+ async def cleanup_imported_table(self) -> None:
"""失败时仍只清理由本次导入取得 ID 的元数据。"""
if self.table_id is not None:
api = await self.harness.api_context(self.token)
@@ -241,4 +242,4 @@ async def test_gen_table_page(browser_harness: BrowserHarness) -> None:
await test.preview_and_download()
await test.delete_table()
finally:
- await test.cleanup()
+ await test.cleanup_imported_table()
diff --git a/ruoyi-fastapi-test/ty.toml b/ruoyi-fastapi-test/ty.toml
new file mode 100644
index 000000000..8198b1807
--- /dev/null
+++ b/ruoyi-fastapi-test/ty.toml
@@ -0,0 +1,15 @@
+[environment]
+python-platform = "all"
+python-version = "3.11"
+
+[rules]
+blanket-ignore-comment = "error"
+disjoint-cast = "error"
+mismatched-enum-name = "error"
+mismatched-namedtuple-name = "error"
+mismatched-sentinel-name = "error"
+unsound-return = "error"
+unsound-yield = "error"
+
+[terminal]
+error-on-warning = true
diff --git a/ty.toml b/ty.toml
new file mode 100644
index 000000000..11157d890
--- /dev/null
+++ b/ty.toml
@@ -0,0 +1,16 @@
+[environment]
+root = ["ruoyi-fastapi-backend", "ruoyi-fastapi-test", ".github"]
+python-platform = "all"
+python-version = "3.11"
+
+[rules]
+blanket-ignore-comment = "error"
+disjoint-cast = "error"
+mismatched-enum-name = "error"
+mismatched-namedtuple-name = "error"
+mismatched-sentinel-name = "error"
+unsound-return = "error"
+unsound-yield = "error"
+
+[terminal]
+error-on-warning = true
From 30058c70c9ca26f0585c7bad3b55dabce4382f41 Mon Sep 17 00:00:00 2001
From: insistence <3055204202@qq.com>
Date: Thu, 26 Nov 2026 11:23:35 +0800
Subject: [PATCH 5/9] =?UTF-8?q?refactor:=20=E5=90=AF=E7=94=A8=20ty=20?=
=?UTF-8?q?=E7=9A=84=20missing-type-argument=20=E8=A7=84=E5=88=99=E5=B9=B6?=
=?UTF-8?q?=E8=A1=A5=E5=85=A8=E6=B3=9B=E5=9E=8B=E5=8F=82=E6=95=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.github/ty.toml | 1 +
.../.x18n/scan_python_domains.py | 2 +-
.../cli/runtime/plugin/scaffold/locales.py | 4 +-
.../common/annotation/log_annotation.py | 16 ++--
.../common/aspect/interface_auth.py | 8 +-
ruoyi-fastapi-backend/common/auth_policy.py | 8 +-
ruoyi-fastapi-backend/common/context.py | 12 +--
ruoyi-fastapi-backend/common/vo.py | 6 +-
ruoyi-fastapi-backend/config/database.py | 2 +-
.../config/scheduler/executors.py | 4 +-
.../config/scheduler/manager.py | 12 +--
ruoyi-fastapi-backend/exceptions/exception.py | 12 +--
ruoyi-fastapi-backend/i18n/message.py | 6 +-
ruoyi-fastapi-backend/i18n/translation.py | 8 +-
ruoyi-fastapi-backend/i18n/translator.py | 10 +--
.../transport_crypto_middleware.py | 4 +-
.../controller/dept_controller.py | 14 ++--
.../controller/file_controller.py | 58 ++++++-------
.../controller/role_controller.py | 22 ++---
.../controller/user_controller.py | 32 ++++----
.../module_admin/dao/config_dao.py | 6 +-
.../module_admin/dao/dept_dao.py | 13 +--
.../module_admin/dao/dict_dao.py | 12 +--
.../module_admin/dao/file_access_dao.py | 14 ++--
.../module_admin/dao/file_business_dao.py | 18 +++--
.../module_admin/dao/file_info_dao.py | 28 +++----
.../module_admin/dao/job_dao.py | 6 +-
.../module_admin/dao/job_log_dao.py | 4 +-
.../module_admin/dao/job_runtime_dao.py | 4 +-
.../module_admin/dao/log_dao.py | 10 +--
.../module_admin/dao/menu_dao.py | 3 +-
.../module_admin/dao/notice_dao.py | 8 +-
.../module_admin/dao/post_dao.py | 6 +-
.../module_admin/dao/role_dao.py | 12 ++-
.../module_admin/dao/user_dao.py | 24 +++---
.../module_admin/entity/vo/cache_vo.py | 4 +-
.../module_admin/entity/vo/login_vo.py | 2 +-
.../module_admin/entity/vo/role_vo.py | 9 ++-
.../module_admin/entity/vo/user_vo.py | 14 ++--
.../module_admin/service/common_service.py | 2 +-
.../module_admin/service/config_service.py | 6 +-
.../module_admin/service/dept_service.py | 10 +--
.../module_admin/service/dict_service.py | 12 +--
.../service/file_access_service.py | 24 +++---
.../service/file_business_service.py | 24 +++---
.../module_admin/service/file_service.py | 52 ++++++------
.../module_admin/service/job_log_service.py | 6 +-
.../module_admin/service/job_service.py | 12 +--
.../module_admin/service/log_service.py | 16 ++--
.../module_admin/service/login_service.py | 4 +-
.../module_admin/service/notice_service.py | 8 +-
.../module_admin/service/post_service.py | 6 +-
.../module_admin/service/role_service.py | 26 +++---
.../module_admin/service/user_service.py | 18 ++---
.../module_generator/dao/gen_dao.py | 16 ++--
.../module_generator/service/gen_service.py | 16 ++--
.../templates/python/dao.py.jinja2 | 8 +-
.../templates/python/service.py.jinja2 | 4 +-
.../dao/oauth_access_policy_dao.py | 2 +-
.../module_identity/dao/oauth_audit_dao.py | 4 +-
.../controller/plugin_browser_controller.py | 2 +-
.../controller/plugin_controller.py | 48 +++++------
.../controller/plugin_metrics_controller.py | 4 +-
.../controller/plugin_release_controller.py | 6 +-
.../ai/controller/ai_chat_controller.py | 2 +-
.../ai/controller/ai_model_controller.py | 10 +--
.../plugins/ai/dao/ai_chat_dao.py | 4 +-
.../plugins/ai/dao/ai_model_dao.py | 12 ++-
.../plugins/ai/entity/vo/ai_chat_vo.py | 6 +-
.../plugins/ai/service/ai_model_service.py | 12 +--
.../plugins/core/deployment/worker.py | 2 +-
.../plugins/core/management/dao/dao.py | 14 ++--
.../core/management/service/service.py | 18 +++--
.../plugins/core/runtime/diagnostics_store.py | 2 +-
.../core/runtime/service/lifecycle_lock.py | 12 +--
.../scripts/verify_timezone_database.py | 11 +--
.../tests/cli/completion/test_providers.py | 10 +--
.../tests/cli/root/test_contract_app_ops.py | 41 +++++-----
.../tests/cli/root/test_contract_cli.py | 9 ++-
.../tests/cli/root/test_contract_config.py | 3 +-
.../cli/root/test_contract_db_cache_dev.py | 15 ++--
.../tests/cli/root/test_contract_job_gen.py | 21 ++---
.../cli/root/test_plugin_sdk_commands.py | 3 +-
.../plugin/test_runtime_scaffold_v2.py | 5 +-
.../tests/common/test_auth_policy.py | 8 +-
.../tests/common/test_data_scope.py | 8 +-
.../tests/common/test_pre_auth.py | 56 ++++++-------
.../tests/common/test_query_time.py | 4 +-
.../tests/common/test_request_timezone.py | 5 +-
.../test_scheduler_execution_coordination.py | 3 +-
.../tests/config/test_scheduler_executor.py | 2 +-
.../tests/config/test_scheduler_fields.py | 4 +-
.../tests/config/test_scheduler_job_sync.py | 2 +-
.../config/test_scheduler_leader_lease.py | 7 +-
.../tests/config/test_scheduler_runtime.py | 9 ++-
.../tests/i18n/test_catalog_domains.py | 3 +-
.../tests/i18n/test_dict_cache_publication.py | 6 +-
.../tests/i18n/test_translations.py | 3 +-
.../tests/i18n/test_validation_messages.py | 4 +-
.../controller/test_user_controller.py | 4 +-
.../test_current_user_cache_integration.py | 2 +-
.../service/test_current_user_resolution.py | 8 +-
.../module_admin/service/test_job_service.py | 3 +-
.../service/test_login_service.py | 2 +-
.../module_admin/service/test_user_service.py | 6 +-
.../module_generator/test_gen_service.py | 6 +-
.../module_generator/test_generated_i18n.py | 11 +--
.../test_generated_time_contract.py | 4 +-
.../module_generator/test_react_templates.py | 2 +-
.../services/test_review_completion.py | 5 +-
.../controller/test_plugin_controller.py | 7 +-
.../core/deployment/test_convergence.py | 40 +++++----
.../plugins/core/lifecycle/test_migration.py | 2 +-
.../core/management/test_menu_installer.py | 3 +-
.../runtime/service/test_artifact_guards.py | 11 ++-
.../core/runtime/service/test_catalog.py | 6 +-
.../core/runtime/test_browser_session.py | 2 +-
.../core/runtime/test_bundle_events.py | 5 +-
.../core/runtime/test_bundle_transport.py | 5 +-
.../core/runtime/test_configuration.py | 2 +-
.../core/runtime/test_connection_sessions.py | 2 +-
.../plugins/core/runtime/test_connections.py | 4 +-
.../plugins/core/runtime/test_diagnostics.py | 8 +-
.../core/runtime/test_diagnostics_query.py | 7 +-
.../plugins/core/runtime/test_startup.py | 4 +-
.../core/validation/test_manifest_v2.py | 3 +-
ruoyi-fastapi-backend/tests/redis_helpers.py | 4 +-
.../tests/scheduler_helpers.py | 7 +-
.../tests/scripts/test_check_docstrings.py | 64 +++++++++------
.../tests/scripts/test_migrate_job_fields.py | 2 +-
.../tests/server/test_oidc_runtime.py | 5 +-
.../tests/test_api_docs_auth.py | 81 ++++++++++---------
.../tests/utils/test_log_sanitize_util.py | 6 +-
ruoyi-fastapi-backend/ty.toml | 1 +
ruoyi-fastapi-backend/utils/common_util.py | 46 +++++++----
ruoyi-fastapi-backend/utils/cron_util.py | 5 +-
ruoyi-fastapi-backend/utils/excel_util.py | 40 ++++++---
ruoyi-fastapi-backend/utils/gen_i18n_util.py | 6 +-
ruoyi-fastapi-backend/utils/log_util.py | 2 +-
ruoyi-fastapi-backend/utils/openapi_util.py | 8 +-
ruoyi-fastapi-backend/utils/page_util.py | 80 ++++++++++++------
ruoyi-fastapi-backend/utils/response_util.py | 24 +++---
ruoyi-fastapi-backend/utils/server_util.py | 10 ++-
ruoyi-fastapi-backend/utils/template_util.py | 18 ++---
ruoyi-fastapi-test/conftest.py | 2 +-
.../monitor/test_job_management.py | 7 +-
.../monitor/test_transport_crypto.py | 3 +-
ruoyi-fastapi-test/prepare_e2e_compose.py | 3 +-
ruoyi-fastapi-test/system/page.py | 24 +++---
.../system/test_file_management.py | 3 +-
.../system/test_log_management.py | 3 +-
.../system/test_menu_management.py | 3 +-
.../system/test_plugin_management.py | 28 +++----
ruoyi-fastapi-test/test_browser_harness.py | 4 +-
.../test_plugin_response_contract.py | 9 ++-
ruoyi-fastapi-test/tool/test_code_gen.py | 3 +-
ruoyi-fastapi-test/ty.toml | 1 +
ty.toml | 1 +
158 files changed, 978 insertions(+), 799 deletions(-)
diff --git a/.github/ty.toml b/.github/ty.toml
index 8198b1807..11c711b38 100644
--- a/.github/ty.toml
+++ b/.github/ty.toml
@@ -8,6 +8,7 @@ disjoint-cast = "error"
mismatched-enum-name = "error"
mismatched-namedtuple-name = "error"
mismatched-sentinel-name = "error"
+missing-type-argument = "error"
unsound-return = "error"
unsound-yield = "error"
diff --git a/ruoyi-fastapi-backend/.x18n/scan_python_domains.py b/ruoyi-fastapi-backend/.x18n/scan_python_domains.py
index d8d3ab948..f892b5df3 100644
--- a/ruoyi-fastapi-backend/.x18n/scan_python_domains.py
+++ b/ruoyi-fastapi-backend/.x18n/scan_python_domains.py
@@ -3,7 +3,7 @@
import sys
-def scan(source: dict) -> dict:
+def scan(source: dict[str, str]) -> dict[str, object]:
"""
提取静态消息标识和显式 domain,位置使用 JavaScript UTF-16 偏移。
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/locales.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/locales.py
index 82c9b9213..dcb05f37f 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/locales.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/locales.py
@@ -1,6 +1,6 @@
import json
from pathlib import Path
-from typing import ClassVar
+from typing import Any, ClassVar
class PluginLocaleScaffoldBuilder:
@@ -143,7 +143,7 @@ def build_files(cls, plugin_id: str, plugin_root: Path, frontend_root: Path) ->
return files
@classmethod
- def load_metadata(cls, frontend_root: Path) -> dict:
+ def load_metadata(cls, frontend_root: Path) -> dict[str, Any]:
"""
读取目标应用语言配置,独立测试目录使用模板默认配置。
diff --git a/ruoyi-fastapi-backend/common/annotation/log_annotation.py b/ruoyi-fastapi-backend/common/annotation/log_annotation.py
index b2f4d9b36..b471f6323 100644
--- a/ruoyi-fastapi-backend/common/annotation/log_annotation.py
+++ b/ruoyi-fastapi-backend/common/annotation/log_annotation.py
@@ -334,7 +334,7 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | Response:
return wrapper
- def _get_decorator_func_path(self, func: Callable) -> str:
+ def _get_decorator_func_path(self, func: Callable[..., object]) -> str:
"""
获取被装饰函数所在路径。
@@ -968,8 +968,8 @@ def _get_mapping_keys(payload: Any) -> list[str]:
return []
def _get_login_log(
- self, user_agent: Any, oper_ip: str, oper_location: str, oper_time: datetime, origin_kwargs: dict
- ) -> dict:
+ self, user_agent: Any, oper_ip: str, oper_location: str, oper_time: datetime, origin_kwargs: dict[str, Any]
+ ) -> dict[str, Any]:
"""
获取登录日志信息。
@@ -1000,7 +1000,7 @@ def _get_login_log(
return login_log
- def _set_login_data(self, login_log: dict, origin_kwargs: dict) -> None:
+ def _set_login_data(self, login_log: dict[str, Any], origin_kwargs: dict[str, Any]) -> None:
"""
设置登录日志数据。
@@ -1010,7 +1010,7 @@ def _set_login_data(self, login_log: dict, origin_kwargs: dict) -> None:
if 'form_data' in origin_kwargs:
origin_kwargs['form_data'].login_info = login_log
- def _get_status_and_error_msg(self, result_dict: dict) -> tuple[Literal[0, 1], str | None]:
+ def _get_status_and_error_msg(self, result_dict: dict[str, Any]) -> tuple[Literal[0, 1], str | None]:
"""
获取操作状态和错误信息。
@@ -1047,7 +1047,7 @@ def _is_request_from_swagger_or_redoc(self, request: Request) -> tuple[bool, boo
referer = request.headers.get('referer', '')
return referer.endswith('docs'), referer.endswith('redoc')
- def _get_result_dict(self, result: Any, request_from_swagger: bool, request_from_redoc: bool) -> dict:
+ def _get_result_dict(self, result: Any, request_from_swagger: bool, request_from_redoc: bool) -> dict[str, Any]:
"""
获取操作结果字典。
@@ -1093,7 +1093,7 @@ async def get_ip_location(oper_ip: str) -> str:
return oper_location
-def get_function_parameters_name_by_type(func: Callable, param_type: Any) -> list:
+def get_function_parameters_name_by_type(func: Callable[..., object], param_type: Any) -> list[str]:
"""
获取函数指定类型的参数名称。
@@ -1121,7 +1121,7 @@ def get_function_parameters_name_by_type(func: Callable, param_type: Any) -> lis
return parameters_name_list
-def get_function_parameters_value_by_name(func: Callable, name: str, *args, **kwargs) -> Any:
+def get_function_parameters_value_by_name(func: Callable[..., object], name: str, *args, **kwargs) -> Any:
"""
获取函数指定参数的值。
diff --git a/ruoyi-fastapi-backend/common/aspect/interface_auth.py b/ruoyi-fastapi-backend/common/aspect/interface_auth.py
index 45b36504e..cf00b22e8 100644
--- a/ruoyi-fastapi-backend/common/aspect/interface_auth.py
+++ b/ruoyi-fastapi-backend/common/aspect/interface_auth.py
@@ -13,7 +13,7 @@ class CheckUserInterfaceAuth:
:ivar is_strict: 当传入的权限标识是list类型时,是否开启严格模式,开启表示会校验列表中的每一个权限标识,所有的校验结果都需要为True才会通过
"""
- def __init__(self, perm: str | list, is_strict: bool = False) -> None:
+ def __init__(self, perm: str | list[str], is_strict: bool = False) -> None:
"""
校验当前用户是否具有相应的接口权限。
@@ -57,7 +57,7 @@ class CheckRoleInterfaceAuth:
:ivar is_strict: 当传入的角色标识是list类型时,是否开启严格模式,开启表示会校验列表中的每一个角色标识,所有的校验结果都需要为True才会通过
"""
- def __init__(self, role_key: str | list, is_strict: bool = False) -> None:
+ def __init__(self, role_key: str | list[str], is_strict: bool = False) -> None:
"""
根据角色校验当前用户是否具有相应的接口权限。
@@ -91,7 +91,7 @@ def __call__(self, request: Request) -> bool:
raise PermissionException(data='', message='该用户无此接口权限', msg_key='auth.apiForbidden')
-def UserInterfaceAuthDependency(perm: str | list, is_strict: bool = False) -> params.Depends: # noqa: N802
+def UserInterfaceAuthDependency(perm: str | list[str], is_strict: bool = False) -> params.Depends: # noqa: N802
"""
根据权限标识校验当前用户接口权限依赖。
@@ -102,7 +102,7 @@ def UserInterfaceAuthDependency(perm: str | list, is_strict: bool = False) -> pa
return params.Depends(CheckUserInterfaceAuth(perm, is_strict))
-def RoleInterfaceAuthDependency(role_key: str | list, is_strict: bool = False) -> params.Depends: # noqa: N802
+def RoleInterfaceAuthDependency(role_key: str | list[str], is_strict: bool = False) -> params.Depends: # noqa: N802
"""
根据角色校验当前用户接口权限依赖。
diff --git a/ruoyi-fastapi-backend/common/auth_policy.py b/ruoyi-fastapi-backend/common/auth_policy.py
index 6bd36805c..ef0a73a1f 100644
--- a/ruoyi-fastapi-backend/common/auth_policy.py
+++ b/ruoyi-fastapi-backend/common/auth_policy.py
@@ -68,7 +68,7 @@ def __init__(self, exclude_routes: list[ExcludeRoute] | None = None) -> None:
}
)
- def _compile_path_pattern(self, path: str) -> re.Pattern:
+ def _compile_path_pattern(self, path: str) -> re.Pattern[str]:
"""
将FastAPI路径转换为正则表达式模式。
@@ -124,8 +124,8 @@ class AuthPolicy:
def iter_auth_dependencies(
cls,
dependant: Dependant,
- auth_dependencies: tuple[Callable, ...],
- overrides: dict[Callable, Callable] | None = None,
+ auth_dependencies: tuple[Callable[..., object], ...],
+ overrides: dict[Callable[..., object], Callable[..., object]] | None = None,
) -> Iterator[AuthRule | None]:
"""
遍历实际生效的登录认证声明。
@@ -169,7 +169,7 @@ def visit(dependency: Dependant, rule: AuthRule | None = None) -> Iterator[AuthR
@classmethod
def get_auth_mode(
- cls, request: Request, auth_dependencies: tuple[Callable, ...]
+ cls, request: Request, auth_dependencies: tuple[Callable[..., object], ...]
) -> Literal['pre_auth', 'current_user', 'excluded']:
"""
根据路由的依赖声明确定登录认证方式。
diff --git a/ruoyi-fastapi-backend/common/context.py b/ruoyi-fastapi-backend/common/context.py
index 0bdc81df0..2dca50f16 100644
--- a/ruoyi-fastapi-backend/common/context.py
+++ b/ruoyi-fastapi-backend/common/context.py
@@ -56,7 +56,7 @@ class RequestContext:
@staticmethod
def set_current_exclude_patterns(
exclude_patterns: list[CompiledExcludeRoute],
- ) -> Token:
+ ) -> Token[list[CompiledExcludeRoute] | None]:
"""
设置当前请求的编译后的排除路由模式列表。
@@ -78,7 +78,7 @@ def get_current_exclude_patterns() -> list[CompiledExcludeRoute]:
return _exclude_patterns
@staticmethod
- def set_current_user(user: 'CurrentUserModel') -> Token:
+ def set_current_user(user: 'CurrentUserModel') -> Token['CurrentUserModel | None']:
"""
设置当前用户信息。
@@ -103,7 +103,7 @@ def get_current_user() -> 'CurrentUserModel':
return _current_user
@staticmethod
- def reset_current_exclude_patterns(token: Token) -> None:
+ def reset_current_exclude_patterns(token: Token[list[CompiledExcludeRoute] | None]) -> None:
"""
重置当前请求的编译后的排除路由模式列表。
@@ -112,7 +112,7 @@ def reset_current_exclude_patterns(token: Token) -> None:
current_exclude_patterns.reset(token)
@staticmethod
- def reset_current_user(token: Token) -> None:
+ def reset_current_user(token: Token['CurrentUserModel | None']) -> None:
"""
重置当前用户信息。
@@ -121,7 +121,7 @@ def reset_current_user(token: Token) -> None:
current_user.reset(token)
@staticmethod
- def set_current_timezone(timezone_name: str | None) -> Token:
+ def set_current_timezone(timezone_name: str | None) -> Token[str | None]:
"""
保存中间件已校验的请求时区。
@@ -131,7 +131,7 @@ def set_current_timezone(timezone_name: str | None) -> Token:
return current_timezone.set(timezone_name)
@staticmethod
- def reset_current_timezone(token: Token) -> None:
+ def reset_current_timezone(token: Token[str | None]) -> None:
"""
恢复请求进入前的时区,避免并发请求之间串用。
diff --git a/ruoyi-fastapi-backend/common/vo.py b/ruoyi-fastapi-backend/common/vo.py
index 611effe02..45e9ca50f 100644
--- a/ruoyi-fastapi-backend/common/vo.py
+++ b/ruoyi-fastapi-backend/common/vo.py
@@ -25,7 +25,7 @@ class CrudResponseModel(BaseModel):
message: str = Field(description='响应信息')
result: Any | None = Field(default=None, description='响应结果')
msg_key: str | None = Field(default=None, description='国际化消息标识')
- msg_params: dict | None = Field(default=None, description='国际化消息插值参数')
+ msg_params: dict[str, object] | None = Field(default=None, description='国际化消息插值参数')
domain: str = Field(default='core', description='已注册的国际化词库域')
count: int | None = Field(default=None, description='复数消息数量')
plural_key: str | None = Field(default=None, description='复数消息标识')
@@ -55,7 +55,7 @@ class ResponseBaseModel(CamelModel):
code: int = Field(default=HttpStatusConstant.SUCCESS, description='响应码')
msg: str = Field(default='操作成功', description='响应信息')
msg_key: str | None = Field(default=None, description='国际化消息标识')
- msg_params: dict | None = Field(default=None, description='国际化消息插值参数')
+ msg_params: dict[str, object] | None = Field(default=None, description='国际化消息插值参数')
msg_domain: str | None = Field(default=None, description='国际化插件词库域')
msg_count: int | None = Field(default=None, description='复数消息数量')
msg_plural_key: str | None = Field(default=None, description='复数消息标识')
@@ -99,7 +99,7 @@ class PageModel(CamelModel, Generic[T]):
has_next: bool = Field(description='是否有下一页')
-class PageResponseModel(PageModel, ResponseBaseModel, Generic[T]):
+class PageResponseModel(PageModel[T], ResponseBaseModel, Generic[T]):
"""分页响应模型。"""
diff --git a/ruoyi-fastapi-backend/config/database.py b/ruoyi-fastapi-backend/config/database.py
index 7b1dfd0f8..df09073a4 100644
--- a/ruoyi-fastapi-backend/config/database.py
+++ b/ruoyi-fastapi-backend/config/database.py
@@ -634,7 +634,7 @@ def create_async_session_factory(engine: AsyncEngine) -> async_sessionmaker[Asyn
)
-def create_sync_session_factory(engine: Engine) -> sessionmaker:
+def create_sync_session_factory(engine: Engine) -> sessionmaker[Session]:
"""
创建同步Session工厂。
diff --git a/ruoyi-fastapi-backend/config/scheduler/executors.py b/ruoyi-fastapi-backend/config/scheduler/executors.py
index 76c7eee37..56471f4fb 100644
--- a/ruoyi-fastapi-backend/config/scheduler/executors.py
+++ b/ruoyi-fastapi-backend/config/scheduler/executors.py
@@ -332,7 +332,7 @@ def _do_submit_job(self, job: Job, run_times: list[datetime]) -> None:
"""
snapshot = JobSnapshot.from_job(job, managed=self._submission.manage_executions)
- def callback(future: Future) -> None:
+ def callback(future: Future[list[TimedJobExecutionEvent]]) -> None:
"""
将任务执行结果交回APScheduler处理。
@@ -398,7 +398,7 @@ def _do_submit_job(self, job: Job, run_times: list[datetime]) -> None:
"""
snapshot = JobSnapshot.from_job(job, managed=self._submission.manage_executions)
- def callback(future: Future) -> None:
+ def callback(future: Future[list[TimedJobExecutionEvent]]) -> None:
"""
将任务执行结果交回APScheduler处理。
diff --git a/ruoyi-fastapi-backend/config/scheduler/manager.py b/ruoyi-fastapi-backend/config/scheduler/manager.py
index 30d5c56f0..24e035497 100644
--- a/ruoyi-fastapi-backend/config/scheduler/manager.py
+++ b/ruoyi-fastapi-backend/config/scheduler/manager.py
@@ -61,12 +61,12 @@ class SchedulerManager:
_is_leader: bool = False
_worker_id: str = WorkerIdUtil.get_worker_id(LogConfig.log_worker_id)
_application_lock_owner_token: str = StartupUtil.get_application_lock_owner_token(_worker_id)
- _application_lock_renewal_task: asyncio.Task | None = None
+ _application_lock_renewal_task: asyncio.Task[None] | None = None
_redis: aioredis.Redis | None = None
_sync_channel: str = 'scheduler:sync:request'
- _sync_listener_task: asyncio.Task | None = None
- _lock_lost_task: asyncio.Task | None = None
- _sync_task: asyncio.Task | None = None
+ _sync_listener_task: asyncio.Task[None] | None = None
+ _lock_lost_task: asyncio.Task[None] | None = None
+ _sync_task: asyncio.Task[None] | None = None
_sync_pending: bool = False
_sync_full_pending: bool = False
_sync_pending_ids: set[int] = set()
@@ -74,7 +74,7 @@ class SchedulerManager:
_last_sync_at: float | None = None
_sync_debounce_seconds: float = 0.5
_sync_min_interval_seconds: float = 2.0
- _reacquire_task: asyncio.Task | None = None
+ _reacquire_task: asyncio.Task[None] | None = None
_reacquire_interval_seconds: float = 5.0
_reacquire_jitter_seconds: float = 1.0
_is_closing: bool = False
@@ -139,7 +139,7 @@ def is_application_leader(cls) -> bool:
return cls._is_leader
@classmethod
- def start_application_lock_renewal(cls, redis: aioredis.Redis) -> asyncio.Task:
+ def start_application_lock_renewal(cls, redis: aioredis.Redis) -> asyncio.Task[None]:
"""
启动或复用当前进程的Application leader租约续期任务。
diff --git a/ruoyi-fastapi-backend/exceptions/exception.py b/ruoyi-fastapi-backend/exceptions/exception.py
index 3a211a2c3..9af9649b0 100644
--- a/ruoyi-fastapi-backend/exceptions/exception.py
+++ b/ruoyi-fastapi-backend/exceptions/exception.py
@@ -18,7 +18,7 @@ def __init__(
message: str | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
@@ -65,7 +65,7 @@ def __init__(
message: str | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
@@ -275,7 +275,7 @@ def __init__(
message: str | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
@@ -322,7 +322,7 @@ def __init__(
message: str | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
@@ -369,7 +369,7 @@ def __init__(
message: str | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
@@ -432,7 +432,7 @@ def __init__(
message: str | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
diff --git a/ruoyi-fastapi-backend/i18n/message.py b/ruoyi-fastapi-backend/i18n/message.py
index 7ffaf9fe9..ee1c982fe 100644
--- a/ruoyi-fastapi-backend/i18n/message.py
+++ b/ruoyi-fastapi-backend/i18n/message.py
@@ -24,7 +24,7 @@ class I18nMessage(str):
"""
msg_key: str
- msg_params: dict | None
+ msg_params: dict[str, object] | None
domain: str
plural_count: int | None
plural_key: str | None
@@ -34,7 +34,7 @@ def __new__(
message: str,
*,
msg_key: str,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str = 'core',
count: int | None = None,
plural_key: str | None = None,
@@ -68,7 +68,7 @@ def __setstate__(self, state: dict[str, object]) -> None:
self.__dict__.update(state)
self.__dict__.pop('count', None)
- def __getnewargs_ex__(self) -> tuple[tuple[str], dict]:
+ def __getnewargs_ex__(self) -> tuple[tuple[str], dict[str, object]]:
"""
复制或序列化时保留消息元数据。
diff --git a/ruoyi-fastapi-backend/i18n/translation.py b/ruoyi-fastapi-backend/i18n/translation.py
index bba620f22..bc64929f9 100644
--- a/ruoyi-fastapi-backend/i18n/translation.py
+++ b/ruoyi-fastapi-backend/i18n/translation.py
@@ -1,9 +1,11 @@
-from typing import Any
+from typing import Any, TypeVar
from common.context import RequestContext
from config.env import I18nConfig
from i18n.registry import LocaleRegistry
+_SourceText = TypeVar('_SourceText', bound=str | None)
+
class TranslationUtil:
"""菜单和字典译文工具类。"""
@@ -56,7 +58,9 @@ def merge(current: dict[str, str] | None, patch: dict[str, str | None]) -> dict[
return result
@staticmethod
- def resolve(original: str, translations: dict[str, str] | None, *, locale: str | None = None) -> str:
+ def resolve(
+ original: _SourceText, translations: dict[str, str] | None, *, locale: str | None = None
+ ) -> str | _SourceText:
"""
按当前请求语言和回退链解析数据库译文。
diff --git a/ruoyi-fastapi-backend/i18n/translator.py b/ruoyi-fastapi-backend/i18n/translator.py
index c328d8d4e..c129bae90 100644
--- a/ruoyi-fastapi-backend/i18n/translator.py
+++ b/ruoyi-fastapi-backend/i18n/translator.py
@@ -44,7 +44,7 @@ def _translate_catalog_message(
cls,
code: str,
msg_key: str,
- params: dict | None,
+ params: dict[str, object] | None,
*,
domain: str = 'core',
count: int | None = None,
@@ -85,7 +85,7 @@ def _translate_catalog_message(
def translate(
cls,
msg_key: str,
- params: dict | None = None,
+ params: dict[str, object] | None = None,
*,
locale: str | None = None,
domain: str = 'core',
@@ -130,13 +130,13 @@ def message_fields(
msg: str | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
default_key: str = 'common.error',
context: LocaleContext | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
- ) -> dict:
+ ) -> dict[str, object]:
"""
根据请求语言和消息标识生成响应消息字段。
@@ -185,7 +185,7 @@ def message_fields(
def t(
msg_key: str,
- params: dict | None = None,
+ params: dict[str, object] | None = None,
*,
locale: str | None = None,
domain: str = 'core',
diff --git a/ruoyi-fastapi-backend/middlewares/transport_crypto_middleware.py b/ruoyi-fastapi-backend/middlewares/transport_crypto_middleware.py
index ee4d2d0c7..680231640 100644
--- a/ruoyi-fastapi-backend/middlewares/transport_crypto_middleware.py
+++ b/ruoyi-fastapi-backend/middlewares/transport_crypto_middleware.py
@@ -551,7 +551,7 @@ def _extract_request_kid(self, scope: Scope, headers: Headers, body: bytes) -> s
return str(envelope['kid'])
@staticmethod
- def _loads_json_mapping(payload: str) -> dict:
+ def _loads_json_mapping(payload: str) -> dict[str, object]:
"""
将JSON字符串解析为字典,并限制结果必须为JSON对象。
@@ -562,7 +562,7 @@ def _loads_json_mapping(payload: str) -> dict:
json_payload = json.loads(payload)
if not isinstance(json_payload, dict):
raise ValueError('解密后的请求载荷必须为JSON对象')
- return json_payload
+ return cast('dict[str, object]', json_payload)
@staticmethod
async def _read_body(receive: Receive) -> bytes:
diff --git a/ruoyi-fastapi-backend/module_admin/controller/dept_controller.py b/ruoyi-fastapi-backend/module_admin/controller/dept_controller.py
index 58015b9b7..d470adb25 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/dept_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/dept_controller.py
@@ -39,7 +39,7 @@ async def get_system_dept_tree_for_edit_option(
request: Request,
dept_id: Annotated[int, Path(description='部门id')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
dept_query = DeptModel(dept_id=dept_id)
dept_query_result = await DeptService.get_dept_for_edit_option_services(query_db, dept_query, data_scope_sql)
@@ -60,7 +60,7 @@ async def get_system_dept_list(
request: Request,
dept_query: Annotated[DeptQueryModel, Query()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
dept_query_result = await DeptService.get_dept_list_services(query_db, dept_query, data_scope_sql)
logger.info('获取成功')
@@ -83,7 +83,7 @@ async def add_system_dept(
add_dept: DeptModel,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
if not current_user.user.admin:
await DeptService.check_dept_data_scope_services(query_db, add_dept.parent_id, data_scope_sql)
@@ -110,7 +110,7 @@ async def edit_system_dept(
edit_dept: DeptModel,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
if not current_user.user.admin:
await DeptService.check_dept_data_scope_services(query_db, edit_dept.dept_id, data_scope_sql)
@@ -138,7 +138,7 @@ async def update_system_dept_sort(
dept_sort: DeptSortModel,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
update_sort_result = await DeptService.update_dept_sort_services(
query_db,
@@ -164,7 +164,7 @@ async def delete_system_dept(
dept_ids: Annotated[str, Path(description='需要删除的部门id')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
dept_id_list = dept_ids.split(',') if dept_ids else []
if dept_id_list:
@@ -192,7 +192,7 @@ async def query_detail_system_dept(
dept_id: Annotated[int, Path(description='部门id')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
if not current_user.user.admin:
await DeptService.check_dept_data_scope_services(query_db, dept_id, data_scope_sql)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/file_controller.py b/ruoyi-fastapi-backend/module_admin/controller/file_controller.py
index 30136f9be..9dfb57255 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/file_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/file_controller.py
@@ -83,7 +83,7 @@ async def get_system_file_list(
file_page_query: Annotated[FileInfoPageQueryModel, Query()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -110,7 +110,7 @@ async def get_system_file_stats(
file_page_query: Annotated[FileInfoPageQueryModel, Query()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -359,7 +359,7 @@ async def get_system_file_retention_reminder_list(
reminder_page_query: Annotated[FileRetentionNoticePageQueryModel, Query()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -390,7 +390,7 @@ async def scan_system_file_retention_reminder(
request: Request,
query_db: Annotated[AsyncSession, DBSessionDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -422,7 +422,7 @@ async def read_system_file_retention_reminder(
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -456,7 +456,7 @@ async def extend_system_file_retention(
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -489,7 +489,7 @@ async def dispose_system_expired_file(
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -517,8 +517,8 @@ async def search_system_file_acl_subjects(
request: Request,
subject_type: Annotated[Literal['user', 'role', 'dept'], Query(alias='subjectType')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
- user_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
- dept_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ user_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
+ dept_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
keyword: Annotated[str | None, Query(max_length=50)] = None,
limit: Annotated[int, Query(ge=1, le=50)] = 20,
) -> Response:
@@ -545,7 +545,7 @@ async def search_system_file_acl_subjects(
async def get_system_file_acl_dept_tree(
request: Request,
query_db: Annotated[AsyncSession, DBSessionDependency()],
- dept_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ dept_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
dept_tree_result = await FileAclService.get_file_acl_dept_tree_services(query_db, dept_data_scope_sql)
logger.info('文件授权部门树获取成功')
@@ -568,11 +568,11 @@ async def batch_save_system_file_acl(
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
- user_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
- dept_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ user_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
+ dept_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
save_file_acl_result = await FileAclService.batch_save_file_acl_services(
query_db,
@@ -600,11 +600,11 @@ async def get_system_file_acl_list(
file_id: UUID,
query_db: Annotated[AsyncSession, DBSessionDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
- user_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
- dept_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ user_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
+ dept_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
file_acl_list_result = await FileAclService.get_file_acl_list_services(
query_db,
@@ -634,11 +634,11 @@ async def save_system_file_acl(
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
- user_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
- dept_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ user_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
+ dept_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
save_file_acl_result = await FileAclService.save_file_acl_services(
query_db,
@@ -667,7 +667,7 @@ async def get_system_file_reference_list(
file_id: UUID,
query_db: Annotated[AsyncSession, DBSessionDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -694,7 +694,7 @@ async def get_system_file_access_log_list(
access_log_page_query: Annotated[FileAccessLogPageQueryModel, Query()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -736,7 +736,7 @@ async def download_system_file(
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -779,11 +779,11 @@ async def transfer_system_file(
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
- user_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
- dept_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ user_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
+ dept_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
transfer_file_result = await FileTransferService.transfer_file_services(
query_db,
@@ -815,7 +815,7 @@ async def delete_system_file(
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -846,7 +846,7 @@ async def restore_system_file(
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -877,7 +877,7 @@ async def purge_system_file(
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
@@ -905,7 +905,7 @@ async def get_system_file_detail(
file_id: UUID,
query_db: Annotated[AsyncSession, DBSessionDependency()],
file_data_scope_sql: Annotated[
- ColumnElement,
+ ColumnElement[bool],
DataScopeDependency(SysFileInfo, user_alias='owner_user_id', dept_alias='dept_id'),
],
) -> Response:
diff --git a/ruoyi-fastapi-backend/module_admin/controller/role_controller.py b/ruoyi-fastapi-backend/module_admin/controller/role_controller.py
index 36fe10c80..0f17541ff 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/role_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/role_controller.py
@@ -57,7 +57,7 @@ async def get_system_role_dept_tree(
request: Request,
role_id: Annotated[int, Path(description='角色ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
dept_query_result = await DeptService.get_dept_tree_services(query_db, DeptModel(), data_scope_sql)
role_dept_query_result = await RoleService.get_role_dept_tree_services(query_db, role_id)
@@ -79,7 +79,7 @@ async def get_system_role_list(
request: Request,
role_page_query: Annotated[RolePageQueryModel, Query()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
role_page_query_result = await RoleService.get_role_list_services(
query_db, role_page_query, data_scope_sql, is_page=True
@@ -128,7 +128,7 @@ async def edit_system_role(
edit_role: AddRoleModel,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
await RoleService.check_role_allowed_services(edit_role)
if not current_user.user.admin:
@@ -154,7 +154,7 @@ async def edit_system_role_datascope(
role_data_scope: AddRoleModel,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
await RoleService.check_role_allowed_services(role_data_scope)
if not current_user.user.admin:
@@ -186,7 +186,7 @@ async def delete_system_role(
role_ids: Annotated[str, Path(description='需要删除的角色ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
role_id_list = role_ids.split(',') if role_ids else []
if role_id_list:
@@ -214,7 +214,7 @@ async def query_detail_system_role(
role_id: Annotated[int, Path(description='角色ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
if not current_user.user.admin:
await RoleService.check_role_data_scope_services(query_db, str(role_id), data_scope_sql)
@@ -245,7 +245,7 @@ async def export_system_role_list(
request: Request,
role_page_query: Annotated[RolePageQueryModel, Form()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
# 获取全量数据
role_query_result = await RoleService.get_role_list_services(
@@ -271,7 +271,7 @@ async def reset_system_role_status(
change_role: AddRoleModel,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
await RoleService.check_role_allowed_services(change_role)
if not current_user.user.admin:
@@ -300,7 +300,7 @@ async def get_system_allocated_user_list(
request: Request,
user_role: Annotated[UserRolePageQueryModel, Query()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
) -> Response:
role_user_allocated_page_query_result = await RoleService.get_role_user_allocated_list_services(
query_db, user_role, data_scope_sql, is_page=True
@@ -322,7 +322,7 @@ async def get_system_unallocated_user_list(
request: Request,
user_role: Annotated[UserRolePageQueryModel, Query()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
) -> Response:
role_user_unallocated_page_query_result = await RoleService.get_role_user_unallocated_list_services(
query_db, user_role, data_scope_sql, is_page=True
@@ -347,7 +347,7 @@ async def add_system_role_user(
add_role_user: Annotated[CrudUserRoleModel, Query()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
if not current_user.user.admin:
await RoleService.check_role_data_scope_services(query_db, str(add_role_user.role_id), data_scope_sql)
diff --git a/ruoyi-fastapi-backend/module_admin/controller/user_controller.py b/ruoyi-fastapi-backend/module_admin/controller/user_controller.py
index 45bf6de38..ad382ab65 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/user_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/user_controller.py
@@ -70,7 +70,7 @@
async def get_system_dept_tree(
request: Request,
query_db: Annotated[AsyncSession, DBSessionDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
dept_query_result = await DeptService.get_dept_tree_services(query_db, DeptModel(), data_scope_sql)
logger.info('获取成功')
@@ -90,7 +90,7 @@ async def get_system_user_list(
request: Request,
user_page_query: Annotated[UserPageQueryModel, Query()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
) -> Response:
# 获取分页数据
user_page_query_result = await UserService.get_user_list_services(
@@ -116,8 +116,8 @@ async def add_system_user(
add_user: AddUserModel,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- dept_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
- role_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ dept_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
+ role_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
if not current_user.user.admin:
await DeptService.check_dept_data_scope_services(query_db, add_user.dept_id, dept_data_scope_sql)
@@ -149,9 +149,9 @@ async def edit_system_user(
edit_user: EditUserModel,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- user_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
- dept_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
- role_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ user_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
+ dept_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
+ role_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
# 普通编辑只接收管理表单字段,密码与内部操作类型由专用接口处理。
edit_user = EditUserModel(
@@ -200,7 +200,7 @@ async def delete_system_user(
user_ids: Annotated[str, Path(description='需要删除的用户ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
) -> Response:
user_id_list = user_ids.split(',') if user_ids else []
if user_id_list:
@@ -233,7 +233,7 @@ async def reset_system_user_pwd(
reset_user: EditUserModel,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
) -> Response:
await UserService.check_user_allowed_services(reset_user)
if not current_user.user.admin:
@@ -268,7 +268,7 @@ async def change_system_user_status(
change_user: EditUserModel,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
) -> Response:
await UserService.check_user_allowed_services(change_user)
if not current_user.user.admin:
@@ -322,7 +322,7 @@ async def query_detail_system_user(
request: Request,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
user_id: int | Literal[''] | None = '',
) -> Response:
if user_id and not current_user.user.admin:
@@ -513,8 +513,8 @@ async def batch_import_system_user(
update_support: Annotated[bool, Query(alias='updateSupport')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- user_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
- dept_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ user_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
+ dept_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
batch_import_result = await UserService.batch_import_user_services(
request, query_db, file, update_support, current_user, user_data_scope_sql, dept_data_scope_sql
@@ -569,7 +569,7 @@ async def export_system_user_list(
request: Request,
user_page_query: Annotated[UserPageQueryModel, Form()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
) -> Response:
# 获取全量数据
user_query_result = await UserService.get_user_list_services(
@@ -617,8 +617,8 @@ async def update_system_role_user(
role_ids: Annotated[str, Query(alias='roleIds')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- user_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysUser)],
- role_data_scope_sql: Annotated[ColumnElement, DataScopeDependency(SysDept)],
+ user_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
+ role_data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(SysDept)],
) -> Response:
if not current_user.user.admin:
await UserService.check_user_data_scope_services(query_db, user_id, user_data_scope_sql)
diff --git a/ruoyi-fastapi-backend/module_admin/dao/config_dao.py b/ruoyi-fastapi-backend/module_admin/dao/config_dao.py
index 7a5021624..7a04f47b2 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/config_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/config_dao.py
@@ -53,7 +53,7 @@ async def get_config_detail_by_info(cls, db: AsyncSession, config: ConfigModel)
@classmethod
async def get_config_list(
cls, db: AsyncSession, query_object: ConfigPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取参数配置列表信息。
@@ -77,7 +77,7 @@ async def get_config_list(
.order_by(SysConfig.config_id)
.distinct()
)
- config_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ config_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -99,7 +99,7 @@ async def add_config_dao(cls, db: AsyncSession, config: ConfigModel) -> SysConfi
return db_config
@classmethod
- async def edit_config_dao(cls, db: AsyncSession, config: dict) -> None:
+ async def edit_config_dao(cls, db: AsyncSession, config: dict[str, Any]) -> None:
"""
编辑参数配置数据库操作。
diff --git a/ruoyi-fastapi-backend/module_admin/dao/dept_dao.py b/ruoyi-fastapi-backend/module_admin/dao/dept_dao.py
index cf0f940c3..b06db7d34 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/dept_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/dept_dao.py
@@ -1,4 +1,5 @@
from collections.abc import Sequence
+from typing import Any
from sqlalchemy import ColumnElement, bindparam, func, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
@@ -71,7 +72,7 @@ async def get_dept_detail_by_info(cls, db: AsyncSession, dept: DeptModel) -> Sys
@classmethod
async def get_dept_info_for_edit_option(
- cls, db: AsyncSession, dept_info: DeptModel, data_scope_sql: ColumnElement
+ cls, db: AsyncSession, dept_info: DeptModel, data_scope_sql: ColumnElement[bool]
) -> Sequence[SysDept]:
"""
获取部门编辑对应的在用部门列表信息。
@@ -121,7 +122,7 @@ async def get_children_dept_dao(cls, db: AsyncSession, dept_id: int) -> Sequence
@classmethod
async def get_dept_list_for_tree(
- cls, db: AsyncSession, dept_info: DeptModel, data_scope_sql: ColumnElement
+ cls, db: AsyncSession, dept_info: DeptModel, data_scope_sql: ColumnElement[bool]
) -> Sequence[SysDept]:
"""
获取所有在用部门列表信息。
@@ -153,7 +154,7 @@ async def get_dept_list_for_tree(
@classmethod
async def get_dept_list(
- cls, db: AsyncSession, page_object: DeptModel, data_scope_sql: ColumnElement
+ cls, db: AsyncSession, page_object: DeptModel, data_scope_sql: ColumnElement[bool]
) -> Sequence[SysDept]:
"""
根据查询参数获取部门列表信息。
@@ -200,7 +201,7 @@ async def add_dept_dao(cls, db: AsyncSession, dept: DeptModel) -> SysDept:
return db_dept
@classmethod
- async def edit_dept_dao(cls, db: AsyncSession, dept: dict) -> None:
+ async def edit_dept_dao(cls, db: AsyncSession, dept: dict[str, Any]) -> None:
"""
编辑部门数据库操作。
@@ -213,7 +214,7 @@ async def edit_dept_dao(cls, db: AsyncSession, dept: dict) -> None:
)
@classmethod
- async def update_dept_children_dao(cls, db: AsyncSession, update_dept: list) -> None:
+ async def update_dept_children_dao(cls, db: AsyncSession, update_dept: list[dict[str, int | str]]) -> None:
"""
更新子部门信息。
@@ -250,7 +251,7 @@ async def update_dept_sort_dao(cls, db: AsyncSession, dept_sort_list: list[dict[
)
@classmethod
- async def update_dept_status_normal_dao(cls, db: AsyncSession, dept_id_list: list) -> None:
+ async def update_dept_status_normal_dao(cls, db: AsyncSession, dept_id_list: list[int]) -> None:
"""
批量更新部门状态为正常。
diff --git a/ruoyi-fastapi-backend/module_admin/dao/dict_dao.py b/ruoyi-fastapi-backend/module_admin/dao/dict_dao.py
index b5acc5ecd..652d070ce 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/dict_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/dict_dao.py
@@ -67,7 +67,7 @@ async def get_all_dict_type(cls, db: AsyncSession) -> list[Any]:
@classmethod
async def get_dict_type_list(
cls, db: AsyncSession, query_object: DictTypePageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取字典类型列表信息。
@@ -91,7 +91,7 @@ async def get_dict_type_list(
.order_by(SysDictType.dict_id)
.distinct()
)
- dict_type_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ dict_type_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -114,7 +114,7 @@ async def add_dict_type_dao(cls, db: AsyncSession, dict_type: DictTypeModel) ->
return db_dict_type
@classmethod
- async def edit_dict_type_dao(cls, db: AsyncSession, dict_type: dict) -> None:
+ async def edit_dict_type_dao(cls, db: AsyncSession, dict_type: dict[str, Any]) -> None:
"""
编辑字典类型数据库操作。
@@ -188,7 +188,7 @@ async def get_dict_data_detail_by_info(cls, db: AsyncSession, dict_data: DictDat
@classmethod
async def get_dict_data_list(
cls, db: AsyncSession, query_object: DictDataPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取字典数据列表信息。
@@ -207,7 +207,7 @@ async def get_dict_data_list(
.order_by(SysDictData.dict_sort)
.distinct()
)
- dict_data_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ dict_data_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -260,7 +260,7 @@ async def add_dict_data_dao(cls, db: AsyncSession, dict_data: DictDataModel) ->
return db_data_type
@classmethod
- async def edit_dict_data_dao(cls, db: AsyncSession, dict_data: dict) -> None:
+ async def edit_dict_data_dao(cls, db: AsyncSession, dict_data: dict[str, Any]) -> None:
"""
编辑字典数据数据库操作。
diff --git a/ruoyi-fastapi-backend/module_admin/dao/file_access_dao.py b/ruoyi-fastapi-backend/module_admin/dao/file_access_dao.py
index edabdbaf3..68d017e53 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/file_access_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/file_access_dao.py
@@ -73,7 +73,7 @@ async def get_file_acl_list(cls, db: AsyncSession, file_id: str) -> list[SysFile
)
@classmethod
- async def get_acl_dept_list(cls, db: AsyncSession, dept_data_scope_sql: ColumnElement) -> list[SysDept]:
+ async def get_acl_dept_list(cls, db: AsyncSession, dept_data_scope_sql: ColumnElement[bool]) -> list[SysDept]:
"""
获取文件授权可选部门列表。
@@ -131,8 +131,8 @@ async def get_acl_subject_name_map(
cls,
db: AsyncSession,
subject_ids: dict[str, set[int]],
- user_data_scope_sql: ColumnElement,
- dept_data_scope_sql: ColumnElement,
+ user_data_scope_sql: ColumnElement[bool],
+ dept_data_scope_sql: ColumnElement[bool],
) -> dict[tuple[str, int], str]:
"""
获取访问控制主体名称映射。
@@ -200,8 +200,8 @@ async def search_acl_subjects(
subject_type: str,
keyword: str | None,
limit: int,
- user_data_scope_sql: ColumnElement,
- dept_data_scope_sql: ColumnElement,
+ user_data_scope_sql: ColumnElement[bool],
+ dept_data_scope_sql: ColumnElement[bool],
) -> list[dict[str, Any]]:
"""
查询访问控制主体选项。
@@ -263,7 +263,7 @@ async def _filter_role_rows_by_data_scope(
cls,
db: AsyncSession,
role_rows: Sequence[Row[int, str] | tuple[int, str]],
- user_data_scope_sql: ColumnElement,
+ user_data_scope_sql: ColumnElement[bool],
) -> list[tuple[int, str]]:
"""
过滤包含数据权限范围外成员的角色。
@@ -337,7 +337,7 @@ async def get_file_access_log_list(
file_id: str,
query_object: FileAccessLogPageQueryModel,
is_page: bool = False,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取文件访问审计列表。
diff --git a/ruoyi-fastapi-backend/module_admin/dao/file_business_dao.py b/ruoyi-fastapi-backend/module_admin/dao/file_business_dao.py
index 26decc269..67c5da0b2 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/file_business_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/file_business_dao.py
@@ -217,7 +217,7 @@ async def _refresh_file_expire_times(
).where(SysFileReference.file_id.in_(file_ids))
)
).all()
- retention_map: dict[str, list] = {file_id: [] for file_id in file_ids}
+ retention_map: dict[str, list[datetime | None]] = {file_id: [] for file_id in file_ids}
for file_id, retention_expire_time in rows:
retention_map[str(file_id)].append(retention_expire_time)
@@ -230,7 +230,9 @@ async def _refresh_file_expire_times(
if has_legacy_reference or any(expire_time is None for expire_time in retention_expire_times):
file_info.expire_time = None
else:
- file_info.expire_time = max(retention_expire_times, default=None)
+ file_info.expire_time = max(
+ (expiry for expiry in retention_expire_times if expiry is not None), default=None
+ )
await FileRetentionNoticeDao.invalidate_changed_expire_time_notices(
db,
file_id,
@@ -303,7 +305,7 @@ async def edit_file_retention_policy(
cls,
db: AsyncSession,
business_type: str,
- policy: dict,
+ policy: dict[str, object],
) -> None:
"""
修改文件业务保留策略。
@@ -340,7 +342,7 @@ async def get_missing_notice_candidates(
current_time: datetime,
reminder_deadline: datetime,
batch_size: int,
- file_data_scope_sql: ColumnElement | bool = True,
+ file_data_scope_sql: ColumnElement[bool] | bool = True,
) -> list[SysFileInfo]:
"""
获取尚未生成当前到期提醒的文件。
@@ -464,9 +466,9 @@ async def get_file_retention_notice_list(
cls,
db: AsyncSession,
query_object: FileRetentionNoticePageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
is_page: bool = False,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取文件保留期限提醒列表。
@@ -535,7 +537,7 @@ async def get_file_retention_notice_context_for_update(
cls,
db: AsyncSession,
notice_id: int,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
) -> tuple[SysFileRetentionNotice, SysFileInfo] | None:
"""
锁定数据权限范围内的有效提醒和文件。
@@ -568,7 +570,7 @@ async def get_notice_ids_in_data_scope_for_update(
cls,
db: AsyncSession,
notice_ids: list[int],
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
) -> list[int]:
"""
锁定数据权限范围内的有效提醒。
diff --git a/ruoyi-fastapi-backend/module_admin/dao/file_info_dao.py b/ruoyi-fastapi-backend/module_admin/dao/file_info_dao.py
index 60d3e925d..3c435d976 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/file_info_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/file_info_dao.py
@@ -57,7 +57,7 @@ async def get_file_info_by_id(
cls,
db: AsyncSession,
file_id: str,
- file_data_scope_sql: ColumnElement | None = None,
+ file_data_scope_sql: ColumnElement[bool] | None = None,
) -> SysFileInfo | None:
"""
根据文件ID获取有效文件信息。
@@ -147,7 +147,7 @@ async def get_reconcile_run_list(
db: AsyncSession,
query_object: FileReconcileRunPageQueryModel,
is_page: bool = True,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取文件存储对账任务列表。
@@ -361,7 +361,7 @@ async def get_reconcile_issue_list(
db: AsyncSession,
query_object: FileReconcileIssuePageQueryModel,
is_page: bool = True,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取文件存储对账异常列表。
@@ -549,7 +549,7 @@ async def get_file_info_detail_by_id(
cls,
db: AsyncSession,
file_id: str,
- file_data_scope_sql: ColumnElement | None = None,
+ file_data_scope_sql: ColumnElement[bool] | None = None,
) -> SysFileInfo | None:
"""
根据文件ID获取文件详细信息。
@@ -577,7 +577,7 @@ async def get_file_info_by_id_for_update(
cls,
db: AsyncSession,
file_id: str,
- file_data_scope_sql: ColumnElement | None = None,
+ file_data_scope_sql: ColumnElement[bool] | None = None,
) -> SysFileInfo | None:
"""
根据文件ID锁定有效文件信息。
@@ -609,7 +609,7 @@ async def get_file_infos_by_ids_for_update(
cls,
db: AsyncSession,
file_ids: list[str],
- file_data_scope_sql: ColumnElement | None = None,
+ file_data_scope_sql: ColumnElement[bool] | None = None,
) -> list[SysFileInfo]:
"""
根据文件ID列表锁定有效文件信息。
@@ -642,7 +642,7 @@ async def get_deleted_file_infos_by_ids_for_update(
cls,
db: AsyncSession,
file_ids: list[str],
- file_data_scope_sql: ColumnElement | None = None,
+ file_data_scope_sql: ColumnElement[bool] | None = None,
) -> list[SysFileInfo]:
"""
根据文件ID列表锁定已删除文件信息。
@@ -675,7 +675,7 @@ async def get_purgeable_file_infos_by_ids_for_update(
cls,
db: AsyncSession,
file_ids: list[str],
- file_data_scope_sql: ColumnElement | None = None,
+ file_data_scope_sql: ColumnElement[bool] | None = None,
) -> list[SysFileInfo]:
"""
根据文件ID列表锁定可永久清理的文件信息。
@@ -751,9 +751,9 @@ async def get_file_info_list(
cls,
db: AsyncSession,
query_object: FileInfoPageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
is_page: bool = False,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取文件信息列表。
@@ -801,7 +801,7 @@ async def get_file_management_detail_by_id(
cls,
db: AsyncSession,
file_id: str,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
) -> dict[str, Any] | None:
"""
获取包含管理展示字段的文件详情。
@@ -851,7 +851,7 @@ async def get_file_stats(
cls,
db: AsyncSession,
query_object: FileInfoPageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
) -> FileStatsModel:
"""
获取文件管理统计信息。
@@ -1093,7 +1093,7 @@ async def get_transfer_user_by_id(
cls,
db: AsyncSession,
user_id: int,
- user_data_scope_sql: ColumnElement,
+ user_data_scope_sql: ColumnElement[bool],
) -> SysUser | None:
"""
获取数据权限范围内的文件转移目标用户。
@@ -1125,7 +1125,7 @@ async def get_transfer_dept_by_id(
cls,
db: AsyncSession,
dept_id: int,
- dept_data_scope_sql: ColumnElement,
+ dept_data_scope_sql: ColumnElement[bool],
) -> SysDept | None:
"""
获取数据权限范围内的文件转移目标部门。
diff --git a/ruoyi-fastapi-backend/module_admin/dao/job_dao.py b/ruoyi-fastapi-backend/module_admin/dao/job_dao.py
index 570db4879..fa10e2dce 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/job_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/job_dao.py
@@ -53,7 +53,7 @@ async def get_job_detail_by_info(cls, db: AsyncSession, job: JobModel) -> SysJob
@classmethod
async def get_job_list(
cls, db: AsyncSession, query_object: JobPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取定时任务列表信息。
@@ -71,7 +71,7 @@ async def get_job_list(
)
.order_by(SysJob.job_id)
)
- job_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ job_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -132,7 +132,7 @@ async def add_job_dao(cls, db: AsyncSession, job: JobModel) -> SysJob:
return db_job
@classmethod
- async def edit_job_dao(cls, db: AsyncSession, job: dict, old_job: JobModel) -> None:
+ async def edit_job_dao(cls, db: AsyncSession, job: dict[str, Any], old_job: JobModel) -> None:
"""
编辑定时任务数据库操作。
diff --git a/ruoyi-fastapi-backend/module_admin/dao/job_log_dao.py b/ruoyi-fastapi-backend/module_admin/dao/job_log_dao.py
index 59b87f0af..bc8f2cd75 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/job_log_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/job_log_dao.py
@@ -17,7 +17,7 @@ class JobLogDao:
@classmethod
async def get_job_log_list(
cls, db: AsyncSession, query_object: JobLogPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取定时任务日志列表信息。
@@ -42,7 +42,7 @@ async def get_job_log_list(
)
.order_by(desc(SysJobLog.create_time))
)
- job_log_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ job_log_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
diff --git a/ruoyi-fastapi-backend/module_admin/dao/job_runtime_dao.py b/ruoyi-fastapi-backend/module_admin/dao/job_runtime_dao.py
index 95c39712b..6fb48e0b8 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/job_runtime_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/job_runtime_dao.py
@@ -230,7 +230,7 @@ async def get_execution(db: AsyncSession, execution_id: str) -> SysJobExecution
return await db.get(SysJobExecution, execution_id)
@staticmethod
- async def execution_page(db: AsyncSession, query: JobExecutionQueryModel) -> PageModel:
+ async def execution_page(db: AsyncSession, query: JobExecutionQueryModel) -> PageModel[dict[str, Any]]:
"""
分页查询执行状态,排除配置参数和内部占用凭据。
@@ -267,7 +267,7 @@ async def execution_page(db: AsyncSession, query: JobExecutionQueryModel) -> Pag
return await PageUtil.paginate(db, statement, query.page_num, query.page_size, is_page=True)
@staticmethod
- async def sync_page(db: AsyncSession, query: JobSyncQueryModel) -> PageModel:
+ async def sync_page(db: AsyncSession, query: JobSyncQueryModel) -> PageModel[dict[str, Any]]:
"""
分页查询同步状态,删除任务后仍能查看结果和发起重试。
diff --git a/ruoyi-fastapi-backend/module_admin/dao/log_dao.py b/ruoyi-fastapi-backend/module_admin/dao/log_dao.py
index 23751b59d..230207d49 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/log_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/log_dao.py
@@ -15,7 +15,7 @@ def _log_order(
table: Table,
query: OperLogPageQueryModel | LoginLogPageQueryModel,
time_column: str,
-) -> ColumnElement:
+) -> ColumnElement[Any]:
"""
根据查询参数选择日志排序列,缺少有效排序条件时按日志时间倒序。
@@ -37,7 +37,7 @@ class OperationLogDao:
@classmethod
async def get_operation_log_list(
cls, db: AsyncSession, query_object: OperLogPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取操作日志列表信息。
@@ -63,7 +63,7 @@ async def get_operation_log_list(
.distinct()
.order_by(order_by_column)
)
- operation_log_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ operation_log_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -110,7 +110,7 @@ class LoginLogDao:
@classmethod
async def get_login_log_list(
cls, db: AsyncSession, query_object: LoginLogPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取登录日志列表信息。
@@ -135,7 +135,7 @@ async def get_login_log_list(
.distinct()
.order_by(order_by_column)
)
- login_log_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ login_log_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
diff --git a/ruoyi-fastapi-backend/module_admin/dao/menu_dao.py b/ruoyi-fastapi-backend/module_admin/dao/menu_dao.py
index 27d485e5c..8dacba356 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/menu_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/menu_dao.py
@@ -1,4 +1,5 @@
from collections.abc import Sequence
+from typing import Any
from sqlalchemy import and_, bindparam, delete, func, or_, select, true, update
from sqlalchemy.ext.asyncio import AsyncSession
@@ -211,7 +212,7 @@ async def add_menu_dao(cls, db: AsyncSession, menu: MenuModel) -> SysMenu:
return db_menu
@classmethod
- async def edit_menu_dao(cls, db: AsyncSession, menu: dict) -> None:
+ async def edit_menu_dao(cls, db: AsyncSession, menu: dict[str, Any]) -> None:
"""
编辑菜单数据库操作。
diff --git a/ruoyi-fastapi-backend/module_admin/dao/notice_dao.py b/ruoyi-fastapi-backend/module_admin/dao/notice_dao.py
index 1be505bf8..d380a9234 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/notice_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/notice_dao.py
@@ -59,7 +59,7 @@ async def get_notice_detail_by_info(cls, db: AsyncSession, notice: NoticeModel)
@classmethod
async def get_notice_list(
cls, db: AsyncSession, query_object: NoticePageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取通知公告列表信息。
@@ -83,7 +83,7 @@ async def get_notice_list(
.order_by(SysNotice.notice_id.desc())
.distinct()
)
- notice_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ notice_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -144,7 +144,7 @@ async def get_unread_count(cls, db: AsyncSession, user_id: int) -> int:
@classmethod
async def get_notice_read_user_list(
cls, db: AsyncSession, query_object: NoticeReadUserPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
查询已阅读指定公告的用户列表。
@@ -262,7 +262,7 @@ async def add_notice_dao(cls, db: AsyncSession, notice: NoticeModel) -> SysNotic
return db_notice
@classmethod
- async def edit_notice_dao(cls, db: AsyncSession, notice: dict) -> None:
+ async def edit_notice_dao(cls, db: AsyncSession, notice: dict[str, Any]) -> None:
"""
编辑通知公告数据库操作。
diff --git a/ruoyi-fastapi-backend/module_admin/dao/post_dao.py b/ruoyi-fastapi-backend/module_admin/dao/post_dao.py
index bc3b500f3..b20189487 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/post_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/post_dao.py
@@ -71,7 +71,7 @@ async def get_post_detail_by_info(cls, db: AsyncSession, post: PostModel) -> Sys
@classmethod
async def get_post_list(
cls, db: AsyncSession, query_object: PostPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取岗位列表信息。
@@ -90,7 +90,7 @@ async def get_post_list(
.order_by(SysPost.post_sort)
.distinct()
)
- post_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ post_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -112,7 +112,7 @@ async def add_post_dao(cls, db: AsyncSession, post: PostModel) -> SysPost:
return db_post
@classmethod
- async def edit_post_dao(cls, db: AsyncSession, post: dict) -> None:
+ async def edit_post_dao(cls, db: AsyncSession, post: dict[str, Any]) -> None:
"""
编辑岗位数据库操作。
diff --git a/ruoyi-fastapi-backend/module_admin/dao/role_dao.py b/ruoyi-fastapi-backend/module_admin/dao/role_dao.py
index 786844b40..f3080f7a5 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/role_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/role_dao.py
@@ -129,8 +129,12 @@ async def get_role_select_option_dao(cls, db: AsyncSession) -> Sequence[SysRole]
@classmethod
async def get_role_list(
- cls, db: AsyncSession, query_object: RolePageQueryModel, data_scope_sql: ColumnElement, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ cls,
+ db: AsyncSession,
+ query_object: RolePageQueryModel,
+ data_scope_sql: ColumnElement[bool],
+ is_page: bool = False,
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取角色列表信息。
@@ -161,7 +165,7 @@ async def get_role_list(
.order_by(SysRole.role_sort)
.distinct()
)
- role_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ role_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -183,7 +187,7 @@ async def add_role_dao(cls, db: AsyncSession, role: RoleModel) -> SysRole:
return db_role
@classmethod
- async def edit_role_dao(cls, db: AsyncSession, role: dict) -> None:
+ async def edit_role_dao(cls, db: AsyncSession, role: dict[str, Any]) -> None:
"""
编辑角色数据库操作。
diff --git a/ruoyi-fastapi-backend/module_admin/dao/user_dao.py b/ruoyi-fastapi-backend/module_admin/dao/user_dao.py
index e18c0593a..29a5a55e2 100644
--- a/ruoyi-fastapi-backend/module_admin/dao/user_dao.py
+++ b/ruoyi-fastapi-backend/module_admin/dao/user_dao.py
@@ -298,8 +298,12 @@ async def get_user_detail_by_id(cls, db: AsyncSession, user_id: int) -> UserDeta
@classmethod
async def get_user_list(
- cls, db: AsyncSession, query_object: UserPageQueryModel, data_scope_sql: ColumnElement, is_page: bool = False
- ) -> PageModel | list[list[dict[str, Any] | None]]:
+ cls,
+ db: AsyncSession,
+ query_object: UserPageQueryModel,
+ data_scope_sql: ColumnElement[bool],
+ is_page: bool = False,
+ ) -> PageModel[list[dict[str, Any] | None]] | list[list[dict[str, Any] | None]]:
"""
根据查询参数获取用户列表信息。
@@ -343,7 +347,7 @@ async def get_user_list(
.order_by(SysUser.user_id)
.distinct()
)
- user_list: PageModel | list[list[dict[str, Any] | None]] = await PageUtil.paginate(
+ user_list: PageModel[list[dict[str, Any] | None]] | list[list[dict[str, Any] | None]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -365,7 +369,7 @@ async def add_user_dao(cls, db: AsyncSession, user: UserModel) -> SysUser:
return db_user
@classmethod
- async def edit_user_dao(cls, db: AsyncSession, user: dict) -> dict[str, str] | None:
+ async def edit_user_dao(cls, db: AsyncSession, user: dict[str, Any]) -> dict[str, str] | None:
"""
编辑用户数据库操作。
@@ -444,9 +448,9 @@ async def get_user_role_allocated_list_by_role_id(
cls,
db: AsyncSession,
query_object: UserRolePageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: bool = False,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据角色id获取已分配的用户列表信息。
@@ -470,7 +474,7 @@ async def get_user_role_allocated_list_by_role_id(
)
.distinct()
)
- allocated_user_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ allocated_user_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -481,9 +485,9 @@ async def get_user_role_unallocated_list_by_role_id(
cls,
db: AsyncSession,
query_object: UserRolePageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: bool = False,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据角色id获取未分配的用户列表信息。
@@ -515,7 +519,7 @@ async def get_user_role_unallocated_list_by_role_id(
)
.distinct()
)
- unallocated_user_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ unallocated_user_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/cache_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/cache_vo.py
index 5b3a14ef7..3cf913d8f 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/cache_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/cache_vo.py
@@ -8,9 +8,9 @@
class CacheMonitorModel(CamelModel):
"""缓存监控信息对应pydantic模型。"""
- command_stats: list | None = Field(default=[], description='命令统计')
+ command_stats: list[dict[str, str]] | None = Field(default=[], description='命令统计')
db_size: int | None = Field(default=None, description='Key数量')
- info: dict | None = Field(default={}, description='Redis信息')
+ info: dict[str, object] | None = Field(default={}, description='Redis信息')
class CacheInfoModel(CamelModel):
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/login_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/login_vo.py
index 267e66837..53a9d35d0 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/login_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/login_vo.py
@@ -14,7 +14,7 @@ class UserLogin(CamelModel):
password: str = Field(description='用户密码')
code: str | None = Field(default=None, description='验证码')
uuid: str | None = Field(default=None, description='会话编号')
- login_info: dict | None = Field(default=None, description='登录信息,前端无需传递')
+ login_info: dict[str, object] | None = Field(default=None, description='登录信息,前端无需传递')
captcha_enabled: bool | None = Field(default=None, description='是否启用验证码,前端无需传递')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/role_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/role_vo.py
index a65a80325..56d5a2232 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/role_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/role_vo.py
@@ -7,6 +7,7 @@
from common.types import ApiUtcDateTime
from common.vo import CamelModel
from i18n.message import I18nMessage
+from module_admin.entity.vo.menu_vo import MenuTreeModel
class RoleModel(CamelModel):
@@ -146,22 +147,22 @@ class RolePageQueryModel(RoleQueryModel):
class RoleMenuQueryModel(CamelModel):
"""角色菜单查询模型。"""
- menus: list = Field(default=[], description='菜单信息')
+ menus: list[MenuTreeModel] = Field(default=[], description='菜单信息')
checked_keys: list[int] = Field(default=[], description='已选择的菜单ID信息')
class RoleDeptQueryModel(CamelModel):
"""角色部门查询模型。"""
- depts: list = Field(default=[], description='部门信息')
+ depts: list[dict[str, object]] = Field(default=[], description='部门信息')
checked_keys: list[int] = Field(default=[], description='已选择的部门ID信息')
class AddRoleModel(RoleModel):
"""新增角色模型。"""
- dept_ids: list = Field(default=[], description='部门ID信息')
- menu_ids: list = Field(default=[], description='菜单ID信息')
+ dept_ids: list[int] = Field(default=[], description='部门ID信息')
+ menu_ids: list[int] = Field(default=[], description='菜单ID信息')
type: str | None = Field(default=None, description='操作类型')
diff --git a/ruoyi-fastapi-backend/module_admin/entity/vo/user_vo.py b/ruoyi-fastapi-backend/module_admin/entity/vo/user_vo.py
index 70f8b895e..7805a6290 100644
--- a/ruoyi-fastapi-backend/module_admin/entity/vo/user_vo.py
+++ b/ruoyi-fastapi-backend/module_admin/entity/vo/user_vo.py
@@ -277,8 +277,8 @@ def validate_locale(cls, value: str) -> str:
class CurrentUserModel(CamelModel):
"""当前已认证用户及其权限信息。"""
- permissions: list = Field(description='权限信息')
- roles: list = Field(description='角色信息')
+ permissions: list[str] = Field(description='权限信息')
+ roles: list[str] = Field(description='角色信息')
user: UserInfoModel = Field(description='用户信息')
app_timezone: str = Field(default='UTC', description='业务时区(IANA)')
pwd_chrtype: str = Field(default='0', description='密码字符范围')
@@ -290,9 +290,9 @@ class UserDetailModel(CamelModel):
"""获取用户详情信息响应模型。"""
data: UserInfoModel | None = Field(default=None, description='用户信息')
- post_ids: list | None = Field(default=None, description='岗位ID信息')
+ post_ids: list[int] | None = Field(default=None, description='岗位ID信息')
posts: list[PostModel | None] = Field(description='岗位信息')
- role_ids: list | None = Field(default=None, description='角色ID信息')
+ role_ids: list[int] | None = Field(default=None, description='角色ID信息')
roles: list[RoleModel | None] = Field(description='角色信息')
@@ -327,15 +327,15 @@ class UserPageQueryModel(UserQueryModel):
class AddUserModel(UserModel):
"""新增用户模型。"""
- role_ids: list | None = Field(default=[], description='角色ID信息')
- post_ids: list | None = Field(default=[], description='岗位ID信息')
+ role_ids: list[int] | None = Field(default=[], description='角色ID信息')
+ post_ids: list[int] | None = Field(default=[], description='岗位ID信息')
type: str | None = Field(default=None, description='操作类型')
class EditUserModel(AddUserModel):
"""编辑用户模型。"""
- role: list | None = Field(default=[], description='角色信息')
+ role: list[RoleModel | None] | None = Field(default=[], description='角色信息')
class ResetPasswordModel(CamelModel):
diff --git a/ruoyi-fastapi-backend/module_admin/service/common_service.py b/ruoyi-fastapi-backend/module_admin/service/common_service.py
index 21b0f4a60..01837c610 100644
--- a/ruoyi-fastapi-backend/module_admin/service/common_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/common_service.py
@@ -195,7 +195,7 @@ async def download_managed_file_services(
current_user: CurrentUserModel,
file_id: str,
enforce_owner_permission: bool = True,
- file_data_scope_sql: ColumnElement | None = None,
+ file_data_scope_sql: ColumnElement[bool] | None = None,
range_header: str | None = None,
) -> FileDownloadResult:
"""
diff --git a/ruoyi-fastapi-backend/module_admin/service/config_service.py b/ruoyi-fastapi-backend/module_admin/service/config_service.py
index fe6b8eaf1..9de6c69b6 100644
--- a/ruoyi-fastapi-backend/module_admin/service/config_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/config_service.py
@@ -22,7 +22,7 @@ class ConfigService:
@overload
async def get_config_list_services(
cls, query_db: AsyncSession, query_object: ConfigPageQueryModel, is_page: Literal[True]
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -33,7 +33,7 @@ async def get_config_list_services(
@classmethod
async def get_config_list_services(
cls, query_db: AsyncSession, query_object: ConfigPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取参数配置列表信息service。
@@ -220,7 +220,7 @@ async def config_detail_services(cls, query_db: AsyncSession, config_id: int | N
return result
@staticmethod
- async def export_config_list_services(config_list: list) -> bytes:
+ async def export_config_list_services(config_list: list[dict[str, Any]]) -> bytes:
"""
导出参数配置信息service。
diff --git a/ruoyi-fastapi-backend/module_admin/service/dept_service.py b/ruoyi-fastapi-backend/module_admin/service/dept_service.py
index 7bd81769c..deb5af2a7 100644
--- a/ruoyi-fastapi-backend/module_admin/service/dept_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/dept_service.py
@@ -18,7 +18,7 @@ class DeptService:
@classmethod
async def get_dept_tree_services(
- cls, query_db: AsyncSession, page_object: DeptModel, data_scope_sql: ColumnElement
+ cls, query_db: AsyncSession, page_object: DeptModel, data_scope_sql: ColumnElement[bool]
) -> list[dict[str, Any]]:
"""
获取部门树信息service。
@@ -36,7 +36,7 @@ async def get_dept_tree_services(
@classmethod
async def get_dept_for_edit_option_services(
- cls, query_db: AsyncSession, page_object: DeptModel, data_scope_sql: ColumnElement
+ cls, query_db: AsyncSession, page_object: DeptModel, data_scope_sql: ColumnElement[bool]
) -> list[dict[str, Any]]:
"""
获取部门编辑部门树信息service。
@@ -52,7 +52,7 @@ async def get_dept_for_edit_option_services(
@classmethod
async def get_dept_list_services(
- cls, query_db: AsyncSession, page_object: DeptModel, data_scope_sql: ColumnElement
+ cls, query_db: AsyncSession, page_object: DeptModel, data_scope_sql: ColumnElement[bool]
) -> list[dict[str, Any]]:
"""
获取部门列表信息service。
@@ -68,7 +68,7 @@ async def get_dept_list_services(
@classmethod
async def check_dept_data_scope_services(
- cls, query_db: AsyncSession, dept_id: int | None, data_scope_sql: ColumnElement
+ cls, query_db: AsyncSession, dept_id: int | None, data_scope_sql: ColumnElement[bool]
) -> CrudResponseModel:
"""
校验部门是否有数据权限service。
@@ -212,7 +212,7 @@ async def update_dept_sort_services(
cls,
query_db: AsyncSession,
page_object: DeptSortModel,
- data_scope_sql: ColumnElement | None = None,
+ data_scope_sql: ColumnElement[bool] | None = None,
) -> CrudResponseModel:
"""
批量保存部门显示顺序。
diff --git a/ruoyi-fastapi-backend/module_admin/service/dict_service.py b/ruoyi-fastapi-backend/module_admin/service/dict_service.py
index 28c89fc37..2c7970ece 100644
--- a/ruoyi-fastapi-backend/module_admin/service/dict_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/dict_service.py
@@ -34,7 +34,7 @@ class DictTypeService:
@overload
async def get_dict_type_list_services(
cls, query_db: AsyncSession, query_object: DictTypePageQueryModel, is_page: Literal[True]
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -45,7 +45,7 @@ async def get_dict_type_list_services(
@classmethod
async def get_dict_type_list_services(
cls, query_db: AsyncSession, query_object: DictTypePageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取字典类型列表信息service。
@@ -216,7 +216,7 @@ async def dict_type_detail_services(cls, query_db: AsyncSession, dict_id: int |
return result
@staticmethod
- async def export_dict_type_list_services(dict_type_list: list) -> bytes:
+ async def export_dict_type_list_services(dict_type_list: list[dict[str, Any]]) -> bytes:
"""
导出字典类型信息service。
@@ -268,7 +268,7 @@ class DictDataService:
@overload
async def get_dict_data_list_services(
cls, query_db: AsyncSession, query_object: DictDataPageQueryModel, is_page: Literal[True]
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -279,7 +279,7 @@ async def get_dict_data_list_services(
@classmethod
async def get_dict_data_list_services(
cls, query_db: AsyncSession, query_object: DictDataPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取字典数据列表信息service。
@@ -504,7 +504,7 @@ async def dict_data_detail_services(cls, query_db: AsyncSession, dict_code: int
return result
@staticmethod
- async def export_dict_data_list_services(dict_data_list: list) -> bytes:
+ async def export_dict_data_list_services(dict_data_list: list[dict[str, Any]]) -> bytes:
"""
导出字典数据信息service。
diff --git a/ruoyi-fastapi-backend/module_admin/service/file_access_service.py b/ruoyi-fastapi-backend/module_admin/service/file_access_service.py
index cc16f23c4..80ab9721d 100644
--- a/ruoyi-fastapi-backend/module_admin/service/file_access_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/file_access_service.py
@@ -38,9 +38,9 @@ async def get_file_acl_list_services(
cls,
query_db: AsyncSession,
file_id: str,
- file_data_scope_sql: ColumnElement,
- user_data_scope_sql: ColumnElement,
- dept_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
+ user_data_scope_sql: ColumnElement[bool],
+ dept_data_scope_sql: ColumnElement[bool],
) -> FileAclListModel:
"""
获取文件访问控制列表service。
@@ -168,8 +168,8 @@ async def search_file_acl_subjects_services(
subject_type: str,
keyword: str | None,
limit: int,
- user_data_scope_sql: ColumnElement,
- dept_data_scope_sql: ColumnElement,
+ user_data_scope_sql: ColumnElement[bool],
+ dept_data_scope_sql: ColumnElement[bool],
) -> list[FileAclSubjectOptionModel]:
"""
查询文件访问控制主体选项service。
@@ -196,7 +196,7 @@ async def search_file_acl_subjects_services(
async def get_file_acl_dept_tree_services(
cls,
query_db: AsyncSession,
- dept_data_scope_sql: ColumnElement,
+ dept_data_scope_sql: ColumnElement[bool],
) -> list[DeptTreeModel]:
"""
获取文件授权部门树service。
@@ -215,9 +215,9 @@ async def save_file_acl_services(
current_user: CurrentUserModel,
file_id: str,
save_file_acl: SaveFileAclModel,
- file_data_scope_sql: ColumnElement,
- user_data_scope_sql: ColumnElement,
- dept_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
+ user_data_scope_sql: ColumnElement[bool],
+ dept_data_scope_sql: ColumnElement[bool],
request: Request | None = None,
) -> CrudResponseModel:
"""
@@ -339,9 +339,9 @@ async def batch_save_file_acl_services(
query_db: AsyncSession,
current_user: CurrentUserModel,
batch_save_file_acl: BatchSaveFileAclModel,
- file_data_scope_sql: ColumnElement,
- user_data_scope_sql: ColumnElement,
- dept_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
+ user_data_scope_sql: ColumnElement[bool],
+ dept_data_scope_sql: ColumnElement[bool],
request: Request | None = None,
) -> CrudResponseModel:
"""
diff --git a/ruoyi-fastapi-backend/module_admin/service/file_business_service.py b/ruoyi-fastapi-backend/module_admin/service/file_business_service.py
index 7c4c88b41..b2c83131e 100644
--- a/ruoyi-fastapi-backend/module_admin/service/file_business_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/file_business_service.py
@@ -43,7 +43,7 @@ async def get_file_reference_list_services(
cls,
query_db: AsyncSession,
file_id: str,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
) -> list[FileReferenceModel]:
"""
获取文件业务引用列表service。
@@ -82,7 +82,7 @@ async def replace_business_file_references_services(
business_id: str,
file_ids: list[str],
create_by: str,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
business_name: str | None = None,
) -> None:
"""
@@ -173,7 +173,7 @@ async def remove_business_file_references_services(
async def get_file_reference_count_map_services(
cls,
query_db: AsyncSession,
- file_infos: list[SysFileInfo] | list[dict],
+ file_infos: list[SysFileInfo] | list[dict[str, object]],
) -> dict[str, int]:
"""
获取包含兼容字段的文件业务引用数量映射service。
@@ -251,7 +251,7 @@ def _normalize_text(value: str | None, field_name: str, max_length: int, require
return normalized_value
@staticmethod
- def _get_value(item: SysFileInfo | dict, snake_name: str, camel_name: str) -> Any:
+ def _get_value(item: SysFileInfo | dict[str, object], snake_name: str, camel_name: str) -> Any:
"""
兼容读取ORM对象和查询字典。
@@ -458,7 +458,7 @@ async def scan_file_retention_notices_services(
query_db: AsyncSession,
remind_days: int = DEFAULT_REMIND_DAYS,
batch_size: int = 500,
- file_data_scope_sql: ColumnElement | None = None,
+ file_data_scope_sql: ColumnElement[bool] | None = None,
) -> FileRetentionScanModel:
"""
扫描并生成文件保留期限提醒service。
@@ -525,9 +525,9 @@ async def get_file_retention_notice_list_services(
cls,
query_db: AsyncSession,
query_object: FileRetentionNoticePageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
is_page: Literal[True] = True,
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -535,18 +535,18 @@ async def get_file_retention_notice_list_services(
cls,
query_db: AsyncSession,
query_object: FileRetentionNoticePageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
is_page: Literal[False],
- ) -> list[dict]: ...
+ ) -> list[dict[str, object]]: ...
@classmethod
async def get_file_retention_notice_list_services(
cls,
query_db: AsyncSession,
query_object: FileRetentionNoticePageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
is_page: bool = True,
- ) -> PageModel | list[dict]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, object]]:
"""
获取文件保留期限提醒列表service。
@@ -569,7 +569,7 @@ async def mark_file_retention_notices_read_services(
query_db: AsyncSession,
notice_ids: str,
read_by: str,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
) -> CrudResponseModel:
"""
标记文件保留期限提醒为已读service。
diff --git a/ruoyi-fastapi-backend/module_admin/service/file_service.py b/ruoyi-fastapi-backend/module_admin/service/file_service.py
index 605455274..ac01f4171 100644
--- a/ruoyi-fastapi-backend/module_admin/service/file_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/file_service.py
@@ -70,7 +70,7 @@ async def extend_file_retention_services(
current_user: CurrentUserModel,
notice_id: int,
extend_retention: ExtendFileRetentionModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
request: Request | None = None,
) -> CrudResponseModel:
"""
@@ -216,7 +216,7 @@ async def dispose_expired_file_services(
current_user: CurrentUserModel,
notice_id: int,
dispose_file: DisposeExpiredFileModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
request: Request | None = None,
) -> CrudResponseModel:
"""
@@ -437,7 +437,7 @@ async def delete_file_services(
query_db: AsyncSession,
current_user: CurrentUserModel,
delete_file: DeleteFileModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
request: Request | None = None,
) -> CrudResponseModel:
"""
@@ -553,7 +553,7 @@ async def purge_file_services(
query_db: AsyncSession,
current_user: CurrentUserModel,
file_ids: str,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
request: Request | None = None,
) -> CrudResponseModel:
"""
@@ -756,7 +756,7 @@ async def restore_file_services(
query_db: AsyncSession,
current_user: CurrentUserModel,
file_ids: str,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
request: Request | None = None,
) -> CrudResponseModel:
"""
@@ -960,9 +960,9 @@ async def get_file_list_services(
cls,
query_db: AsyncSession,
query_object: FileInfoPageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
is_page: Literal[True] = True,
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -970,7 +970,7 @@ async def get_file_list_services(
cls,
query_db: AsyncSession,
query_object: FileInfoPageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
is_page: Literal[False],
) -> list[dict[str, Any]]: ...
@@ -979,9 +979,9 @@ async def get_file_list_services(
cls,
query_db: AsyncSession,
query_object: FileInfoPageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
is_page: bool = True,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取文件信息列表service。
@@ -1003,7 +1003,7 @@ async def get_file_stats_services(
cls,
query_db: AsyncSession,
query_object: FileInfoPageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
) -> FileStatsModel:
"""
获取文件管理统计信息service。
@@ -1020,7 +1020,7 @@ async def file_detail_services(
cls,
query_db: AsyncSession,
file_id: str,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
) -> FileInfoDisplayModel:
"""
获取文件详细信息service。
@@ -1046,9 +1046,9 @@ async def get_file_access_log_list_services(
query_db: AsyncSession,
file_id: str,
query_object: FileAccessLogPageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
is_page: Literal[True] = True,
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -1057,7 +1057,7 @@ async def get_file_access_log_list_services(
query_db: AsyncSession,
file_id: str,
query_object: FileAccessLogPageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
is_page: Literal[False],
) -> list[dict[str, Any]]: ...
@@ -1067,9 +1067,9 @@ async def get_file_access_log_list_services(
query_db: AsyncSession,
file_id: str,
query_object: FileAccessLogPageQueryModel,
- file_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
is_page: bool = True,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取文件访问审计列表service。
@@ -1108,9 +1108,9 @@ async def transfer_file_services(
current_user: CurrentUserModel,
file_ids: str,
transfer_file: TransferFileModel,
- file_data_scope_sql: ColumnElement,
- user_data_scope_sql: ColumnElement,
- dept_data_scope_sql: ColumnElement,
+ file_data_scope_sql: ColumnElement[bool],
+ user_data_scope_sql: ColumnElement[bool],
+ dept_data_scope_sql: ColumnElement[bool],
request: Request | None = None,
) -> CrudResponseModel:
"""
@@ -1388,7 +1388,7 @@ async def get_reconcile_run_list_services(
current_user: CurrentUserModel,
query_object: FileReconcileRunPageQueryModel,
is_page: Literal[True] = True,
- ) -> PageModel: ...
+ ) -> PageModel[FileReconcileRunModel]: ...
@classmethod
@overload
@@ -1407,7 +1407,7 @@ async def get_reconcile_run_list_services(
current_user: CurrentUserModel,
query_object: FileReconcileRunPageQueryModel,
is_page: bool = True,
- ) -> PageModel | list[FileReconcileRunModel]:
+ ) -> PageModel[FileReconcileRunModel] | list[FileReconcileRunModel]:
"""
获取文件存储对账任务列表。
@@ -1420,7 +1420,7 @@ async def get_reconcile_run_list_services(
cls._require_admin(current_user)
run_list = await FileInfoDao.get_reconcile_run_list(query_db, query_object, is_page)
if isinstance(run_list, PageModel):
- return PageModel.model_validate(
+ return PageModel[FileReconcileRunModel].model_validate(
{
'rows': [FileReconcileRunModel.model_validate(row, by_name=True) for row in run_list.rows],
'page_num': run_list.page_num,
@@ -1440,7 +1440,7 @@ async def get_reconcile_issue_list_services(
current_user: CurrentUserModel,
query_object: FileReconcileIssuePageQueryModel,
is_page: Literal[True] = True,
- ) -> PageModel: ...
+ ) -> PageModel[FileReconcileIssueModel]: ...
@classmethod
@overload
@@ -1459,7 +1459,7 @@ async def get_reconcile_issue_list_services(
current_user: CurrentUserModel,
query_object: FileReconcileIssuePageQueryModel,
is_page: bool = True,
- ) -> PageModel | list[FileReconcileIssueModel]:
+ ) -> PageModel[FileReconcileIssueModel] | list[FileReconcileIssueModel]:
"""
获取文件存储对账异常列表。
@@ -1478,7 +1478,7 @@ async def get_reconcile_issue_list_services(
issue_model.available_actions = cls._get_available_actions(issue_model)
issue_models.append(issue_model)
if isinstance(issue_list, PageModel):
- return PageModel.model_validate(
+ return PageModel[FileReconcileIssueModel].model_validate(
{
'rows': issue_models,
'page_num': issue_list.page_num,
diff --git a/ruoyi-fastapi-backend/module_admin/service/job_log_service.py b/ruoyi-fastapi-backend/module_admin/service/job_log_service.py
index 127552f32..95b599511 100644
--- a/ruoyi-fastapi-backend/module_admin/service/job_log_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/job_log_service.py
@@ -21,7 +21,7 @@ class JobLogService:
@overload
async def get_job_log_list_services(
cls, query_db: AsyncSession, query_object: JobLogPageQueryModel, is_page: Literal[True]
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -32,7 +32,7 @@ async def get_job_log_list_services(
@classmethod
async def get_job_log_list_services(
cls, query_db: AsyncSession, query_object: JobLogPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取定时任务日志列表信息service。
@@ -108,7 +108,7 @@ async def clear_job_log_services(cls, query_db: AsyncSession) -> CrudResponseMod
return result
@staticmethod
- async def export_job_log_list_services(request: Request, job_log_list: list) -> bytes:
+ async def export_job_log_list_services(request: Request, job_log_list: list[dict[str, Any]]) -> bytes:
"""
导出定时任务日志信息service。
diff --git a/ruoyi-fastapi-backend/module_admin/service/job_service.py b/ruoyi-fastapi-backend/module_admin/service/job_service.py
index 56bb61643..90d9bddf2 100644
--- a/ruoyi-fastapi-backend/module_admin/service/job_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/job_service.py
@@ -95,7 +95,7 @@ async def _after_commit(cls, states: list[dict[str, Any]], action: str) -> CrudR
@overload
async def get_job_list_services(
cls, query_db: AsyncSession, query_object: JobPageQueryModel, is_page: Literal[True]
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -106,7 +106,7 @@ async def get_job_list_services(
@classmethod
async def get_job_list_services(
cls, query_db: AsyncSession, query_object: JobPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取定时任务列表信息service。
@@ -369,7 +369,9 @@ async def execution_detail_services(cls, query_db: AsyncSession, execution_id: s
return JobRuntimeDao.execution_result(execution)
@staticmethod
- async def execution_list_services(query_db: AsyncSession, query: JobExecutionQueryModel) -> PageModel:
+ async def execution_list_services(
+ query_db: AsyncSession, query: JobExecutionQueryModel
+ ) -> PageModel[dict[str, Any]]:
"""
查询任务执行记录及未执行原因。
@@ -380,7 +382,7 @@ async def execution_list_services(query_db: AsyncSession, query: JobExecutionQue
return await JobRuntimeDao.execution_page(query_db, query)
@staticmethod
- async def sync_list_services(query_db: AsyncSession, query: JobSyncQueryModel) -> PageModel:
+ async def sync_list_services(query_db: AsyncSession, query: JobSyncQueryModel) -> PageModel[dict[str, Any]]:
"""
查询配置和删除操作的调度应用状态。
@@ -406,7 +408,7 @@ async def retry_sync_services(cls, query_db: AsyncSession, job_id: int) -> CrudR
return await cls._after_commit([states[job_id]], '同步')
@staticmethod
- async def export_job_list_services(request: Request, job_list: list) -> bytes:
+ async def export_job_list_services(request: Request, job_list: list[dict[str, Any]]) -> bytes:
"""
导出定时任务信息service。
diff --git a/ruoyi-fastapi-backend/module_admin/service/log_service.py b/ruoyi-fastapi-backend/module_admin/service/log_service.py
index f00af99bf..4d651fdda 100644
--- a/ruoyi-fastapi-backend/module_admin/service/log_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/log_service.py
@@ -44,7 +44,7 @@ class OperationLogService:
@overload
async def get_operation_log_list_services(
cls, query_db: AsyncSession, query_object: OperLogPageQueryModel, is_page: Literal[True]
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -55,7 +55,7 @@ async def get_operation_log_list_services(
@classmethod
async def get_operation_log_list_services(
cls, query_db: AsyncSession, query_object: OperLogPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取操作日志列表信息service。
@@ -130,7 +130,9 @@ async def clear_operation_log_services(cls, query_db: AsyncSession) -> CrudRespo
raise e
@classmethod
- async def export_operation_log_list_services(cls, request: Request, operation_log_list: list) -> bytes:
+ async def export_operation_log_list_services(
+ cls, request: Request, operation_log_list: list[dict[str, Any]]
+ ) -> bytes:
"""
导出操作日志信息service。
@@ -189,7 +191,7 @@ class LoginLogService:
@overload
async def get_login_log_list_services(
cls, query_db: AsyncSession, query_object: LoginLogPageQueryModel, is_page: Literal[True]
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -200,7 +202,7 @@ async def get_login_log_list_services(
@classmethod
async def get_login_log_list_services(
cls, query_db: AsyncSession, query_object: LoginLogPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取登录日志列表信息service。
@@ -291,7 +293,7 @@ async def unlock_user_services(cls, request: Request, unlock_user: UnlockUser) -
raise ServiceException(message='该用户未锁定', msg_key='log.userNotLocked')
@staticmethod
- async def export_login_log_list_services(login_log_list: list) -> bytes:
+ async def export_login_log_list_services(login_log_list: list[dict[str, Any]]) -> bytes:
"""
导出登录日志信息service。
@@ -340,7 +342,7 @@ def _build_event_id(cls, request_id: str, log_type: str, source: str) -> str:
return hashlib.md5(base.encode('utf-8')).hexdigest()
@classmethod
- async def _xadd_event(cls, redis: aioredis.Redis, event_type: str, payload: dict, source: str) -> None:
+ async def _xadd_event(cls, redis: aioredis.Redis, event_type: str, payload: dict[str, object], source: str) -> None:
"""
写入日志事件到Redis Streams。
diff --git a/ruoyi-fastapi-backend/module_admin/service/login_service.py b/ruoyi-fastapi-backend/module_admin/service/login_service.py
index 16e38c1e4..820afe41f 100644
--- a/ruoyi-fastapi-backend/module_admin/service/login_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/login_service.py
@@ -201,7 +201,7 @@ async def unlock_screen_services(
return True
@classmethod
- async def create_access_token(cls, data: dict, expires_delta: timedelta | None = None) -> str:
+ async def create_access_token(cls, data: dict[str, object], expires_delta: timedelta | None = None) -> str:
"""
根据登录信息创建当前用户token。
@@ -379,7 +379,7 @@ async def _get_current_user_from_db(cls, query_db: AsyncSession, user_id: int) -
current_user = CurrentUserModel(
permissions=['*:*:*']
if any(role.role_id == 1 for role in roles)
- else [menu.perms for menu in query_user.get('user_menu_info') or []],
+ else [menu.perms for menu in query_user.get('user_menu_info') or [] if menu.perms is not None],
roles=[role.role_key for role in roles],
user=UserInfoModel(
**user_info,
diff --git a/ruoyi-fastapi-backend/module_admin/service/notice_service.py b/ruoyi-fastapi-backend/module_admin/service/notice_service.py
index ff04f3225..d2383ded3 100644
--- a/ruoyi-fastapi-backend/module_admin/service/notice_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/notice_service.py
@@ -31,7 +31,7 @@ class NoticeService:
@overload
async def get_notice_list_services(
cls, query_db: AsyncSession, query_object: NoticePageQueryModel, is_page: Literal[True] = True
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -42,7 +42,7 @@ async def get_notice_list_services(
@classmethod
async def get_notice_list_services(
cls, query_db: AsyncSession, query_object: NoticePageQueryModel, is_page: bool = True
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取通知公告列表信息service。
@@ -78,7 +78,7 @@ async def get_notice_top_services(cls, query_db: AsyncSession, user_id: int) ->
@overload
async def get_notice_read_user_list_services(
cls, query_db: AsyncSession, query_object: NoticeReadUserPageQueryModel, is_page: Literal[True] = True
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -89,7 +89,7 @@ async def get_notice_read_user_list_services(
@classmethod
async def get_notice_read_user_list_services(
cls, query_db: AsyncSession, query_object: NoticeReadUserPageQueryModel, is_page: bool = True
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取公告已读用户列表。
diff --git a/ruoyi-fastapi-backend/module_admin/service/post_service.py b/ruoyi-fastapi-backend/module_admin/service/post_service.py
index 9c247bcb1..bb0a407f6 100644
--- a/ruoyi-fastapi-backend/module_admin/service/post_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/post_service.py
@@ -19,7 +19,7 @@ class PostService:
@overload
async def get_post_list_services(
cls, query_db: AsyncSession, query_object: PostPageQueryModel, is_page: Literal[True]
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -30,7 +30,7 @@ async def get_post_list_services(
@classmethod
async def get_post_list_services(
cls, query_db: AsyncSession, query_object: PostPageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取岗位列表信息service。
@@ -188,7 +188,7 @@ async def post_detail_services(cls, query_db: AsyncSession, post_id: int | None)
return result
@staticmethod
- async def export_post_list_services(post_list: list) -> bytes:
+ async def export_post_list_services(post_list: list[dict[str, Any]]) -> bytes:
"""
导出岗位信息service。
diff --git a/ruoyi-fastapi-backend/module_admin/service/role_service.py b/ruoyi-fastapi-backend/module_admin/service/role_service.py
index 6c9ffc01d..d82f80868 100644
--- a/ruoyi-fastapi-backend/module_admin/service/role_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/role_service.py
@@ -61,9 +61,9 @@ async def get_role_list_services(
cls,
query_db: AsyncSession,
query_object: RolePageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: Literal[True],
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -71,7 +71,7 @@ async def get_role_list_services(
cls,
query_db: AsyncSession,
query_object: RolePageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: Literal[False] = False,
) -> list[dict[str, Any]]: ...
@@ -80,9 +80,9 @@ async def get_role_list_services(
cls,
query_db: AsyncSession,
query_object: RolePageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: bool = False,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取角色列表信息service。
@@ -111,7 +111,7 @@ async def check_role_allowed_services(cls, check_role: RoleModel) -> CrudRespons
@classmethod
async def check_role_data_scope_services(
- cls, query_db: AsyncSession, role_ids: str, data_scope_sql: ColumnElement
+ cls, query_db: AsyncSession, role_ids: str, data_scope_sql: ColumnElement[bool]
) -> None:
"""
校验角色是否有数据权限service。
@@ -402,7 +402,7 @@ async def role_detail_services(cls, query_db: AsyncSession, role_id: int | None)
return result
@staticmethod
- async def export_role_list_services(role_list: list) -> bytes:
+ async def export_role_list_services(role_list: list[dict[str, Any]]) -> bytes:
"""
导出角色列表信息service。
@@ -438,7 +438,7 @@ async def get_role_user_allocated_list_services(
cls,
query_db: AsyncSession,
page_object: UserRolePageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: Literal[True],
) -> PageModel[UserInfoModel]: ...
@@ -448,7 +448,7 @@ async def get_role_user_allocated_list_services(
cls,
query_db: AsyncSession,
page_object: UserRolePageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: Literal[False] = False,
) -> list[UserInfoModel]: ...
@@ -457,7 +457,7 @@ async def get_role_user_allocated_list_services(
cls,
query_db: AsyncSession,
page_object: UserRolePageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: bool = False,
) -> PageModel[UserInfoModel] | list[UserInfoModel]:
"""
@@ -482,7 +482,7 @@ async def get_role_user_unallocated_list_services(
cls,
query_db: AsyncSession,
page_object: UserRolePageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: Literal[True],
) -> PageModel[UserInfoModel]: ...
@@ -492,7 +492,7 @@ async def get_role_user_unallocated_list_services(
cls,
query_db: AsyncSession,
page_object: UserRolePageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: Literal[False] = False,
) -> list[UserInfoModel]: ...
@@ -501,7 +501,7 @@ async def get_role_user_unallocated_list_services(
cls,
query_db: AsyncSession,
page_object: UserRolePageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: bool = False,
) -> PageModel[UserInfoModel] | list[UserInfoModel]:
"""
diff --git a/ruoyi-fastapi-backend/module_admin/service/user_service.py b/ruoyi-fastapi-backend/module_admin/service/user_service.py
index 58f4b44c5..80e994c82 100644
--- a/ruoyi-fastapi-backend/module_admin/service/user_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/user_service.py
@@ -128,7 +128,7 @@ async def get_user_list_services(
cls,
query_db: AsyncSession,
query_object: UserPageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: Literal[True],
) -> PageModel[UserRowModel]: ...
@@ -138,7 +138,7 @@ async def get_user_list_services(
cls,
query_db: AsyncSession,
query_object: UserPageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: Literal[False] = False,
) -> list[dict[str, Any]]: ...
@@ -147,7 +147,7 @@ async def get_user_list_services(
cls,
query_db: AsyncSession,
query_object: UserPageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: bool = False,
) -> PageModel[UserRowModel] | list[dict[str, Any]]:
"""
@@ -186,7 +186,7 @@ async def check_user_allowed_services(cls, check_user: UserModel) -> CrudRespons
@classmethod
async def check_user_data_scope_services(
- cls, query_db: AsyncSession, user_id: int | None, data_scope_sql: ColumnElement
+ cls, query_db: AsyncSession, user_id: int | None, data_scope_sql: ColumnElement[bool]
) -> CrudResponseModel:
"""
校验用户数据权限service。
@@ -651,8 +651,8 @@ async def batch_import_user_services(
file: UploadFile,
update_support: bool,
current_user: CurrentUserModel,
- user_data_scope_sql: ColumnElement,
- dept_data_scope_sql: ColumnElement,
+ user_data_scope_sql: ColumnElement[bool],
+ dept_data_scope_sql: ColumnElement[bool],
) -> CrudResponseModel:
"""
批量导入用户service。
@@ -790,7 +790,7 @@ async def get_user_import_template_services() -> bytes:
I18nMessage('用户性别', msg_key='export.userGender'),
I18nMessage('帐号状态', msg_key='export.accountStatus'),
]
- option_list = [
+ option_list: list[dict[str, list[str]]] = [
{
I18nMessage('用户性别', msg_key='export.userGender'): [
I18nMessage('男', msg_key='export.male'),
@@ -812,7 +812,7 @@ async def get_user_import_template_services() -> bytes:
return binary_data
@staticmethod
- async def export_user_list_services(user_list: list) -> bytes:
+ async def export_user_list_services(user_list: list[dict[str, Any]]) -> bytes:
"""
导出用户信息service。
@@ -837,7 +837,7 @@ async def export_user_list_services(user_list: list) -> bytes:
}
for item in user_list:
- item['deptName'] = item.get('dept').get('deptName')
+ item['deptName'] = (item.get('dept') or {}).get('deptName')
if item.get('status') == '0':
item['status'] = I18nMessage('正常', msg_key='export.active')
else:
diff --git a/ruoyi-fastapi-backend/module_generator/dao/gen_dao.py b/ruoyi-fastapi-backend/module_generator/dao/gen_dao.py
index 4bf536a41..5fbf1a203 100644
--- a/ruoyi-fastapi-backend/module_generator/dao/gen_dao.py
+++ b/ruoyi-fastapi-backend/module_generator/dao/gen_dao.py
@@ -231,7 +231,7 @@ async def create_table_by_sql_dao(
@classmethod
async def get_gen_table_list(
cls, db: AsyncSession, query_object: GenTablePageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取代码生成业务表列表信息。
@@ -257,7 +257,7 @@ async def get_gen_table_list(
)
.distinct()
)
- gen_table_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ gen_table_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -286,7 +286,7 @@ async def get_gen_db_table_list(
*,
excluded_table_names: set[str] | None = None,
source_config: DataSourceSettings | None = None,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取数据库列表信息。
@@ -332,7 +332,7 @@ async def get_gen_db_table_list(
if excluded_table_names:
statement = statement.bindparams(bindparam('excluded_table_names', expanding=True))
query = select(statement.bindparams(**query_params))
- gen_db_table_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ gen_db_table_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -341,7 +341,7 @@ async def get_gen_db_table_list(
@classmethod
async def get_gen_db_table_list_by_names(
cls, db: AsyncSession, table_names: list[str], source_config: DataSourceSettings | None = None
- ) -> Sequence[Row]:
+ ) -> Sequence[Row[*tuple[Any, ...]]]:
"""
根据业务表名称组获取数据库列表信息。
@@ -377,7 +377,7 @@ async def add_gen_table_dao(cls, db: AsyncSession, gen_table: GenTableModel) ->
return db_gen_table
@classmethod
- async def edit_gen_table_dao(cls, db: AsyncSession, gen_table: dict) -> None:
+ async def edit_gen_table_dao(cls, db: AsyncSession, gen_table: dict[str, Any]) -> None:
"""
编辑业务表数据库操作。
@@ -427,7 +427,7 @@ async def get_gen_table_column_list_by_table_id(cls, db: AsyncSession, table_id:
@classmethod
async def get_gen_db_table_columns_by_name(
cls, db: AsyncSession, table_name: str, source_config: DataSourceSettings | None = None
- ) -> Sequence[Row]:
+ ) -> Sequence[Row[*tuple[Any, ...]]]:
"""
根据业务表名称获取业务表字段列表信息。
@@ -463,7 +463,7 @@ async def add_gen_table_column_dao(cls, db: AsyncSession, gen_table_column: GenT
return db_gen_table_column
@classmethod
- async def edit_gen_table_column_dao(cls, db: AsyncSession, gen_table_column: dict) -> None:
+ async def edit_gen_table_column_dao(cls, db: AsyncSession, gen_table_column: dict[str, Any]) -> None:
"""
编辑业务表字段数据库操作。
diff --git a/ruoyi-fastapi-backend/module_generator/service/gen_service.py b/ruoyi-fastapi-backend/module_generator/service/gen_service.py
index 46b112f9e..d8e968931 100644
--- a/ruoyi-fastapi-backend/module_generator/service/gen_service.py
+++ b/ruoyi-fastapi-backend/module_generator/service/gen_service.py
@@ -31,6 +31,8 @@
from utils.gen_util import GenUtils
from utils.template_util import TemplateInitializer, TemplateUtils
+RenderInfo = tuple[list[str], list[str], dict[str, Any], GenTableModel]
+
class GenTableService:
"""代码生成业务表服务层。"""
@@ -62,7 +64,7 @@ def _source_name(source_name: str | None) -> str:
@overload
async def get_gen_table_list_services(
cls, query_db: AsyncSession, query_object: GenTablePageQueryModel, is_page: Literal[True]
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -73,7 +75,7 @@ async def get_gen_table_list_services(
@classmethod
async def get_gen_table_list_services(
cls, query_db: AsyncSession, query_object: GenTablePageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取代码生成业务表列表信息service。
@@ -90,7 +92,7 @@ async def get_gen_table_list_services(
@overload
async def get_gen_db_table_list_services(
cls, query_db: AsyncSession, query_object: GenTablePageQueryModel, is_page: Literal[True]
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -104,7 +106,7 @@ async def get_gen_db_table_list_services(
query_db: AsyncSession,
query_object: GenTablePageQueryModel,
is_page: bool = False,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取数据库列表信息service。
@@ -482,7 +484,7 @@ async def batch_gen_code_services(
return zip_data
@classmethod
- def _render_files(cls, env: Environment, render_info: list) -> dict[str, str]:
+ def _render_files(cls, env: Environment, render_info: RenderInfo) -> dict[str, str]:
"""
渲染源码后收集模板登记的独立语言资源。
@@ -542,7 +544,7 @@ def _get_output_root(gen_table: GenTableModel) -> Path:
return root
@classmethod
- async def __get_gen_render_info(cls, query_db: AsyncSession, table_name: str, source_name: str) -> list:
+ async def __get_gen_render_info(cls, query_db: AsyncSession, table_name: str, source_name: str) -> RenderInfo:
"""
获取生成代码渲染模板相关信息。
@@ -566,7 +568,7 @@ async def __get_gen_render_info(cls, query_db: AsyncSession, table_name: str, so
template_list = TemplateUtils.get_template_list(gen_table)
output_files = [TemplateUtils.get_file_name(template, gen_table) for template in template_list]
- return [template_list, output_files, context, gen_table]
+ return template_list, output_files, context, gen_table
@classmethod
async def sync_db_services(
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/dao.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/dao.py.jinja2
index 8f8c926b4..e36ed290d 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/dao.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/dao.py.jinja2
@@ -125,7 +125,7 @@ class {{ BusinessName }}Dao:
@classmethod
async def get_{{ businessName }}_list(
cls, db: AsyncSession, query_object: {{ BusinessName }}PageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取{{ functionName }}列表信息。
@@ -180,7 +180,7 @@ class {{ BusinessName }}Dao:
.order_by({{ ClassName }}.{{ pk_field }})
.distinct()
)
- {{ businessName }}_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ {{ businessName }}_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -202,7 +202,7 @@ class {{ BusinessName }}Dao:
return db_{{ businessName }}
@classmethod
- async def edit_{{ businessName }}_dao(cls, db: AsyncSession, {{ businessName }}: dict) -> None:
+ async def edit_{{ businessName }}_dao(cls, db: AsyncSession, {{ businessName }}: dict[str, Any]) -> None:
"""
编辑{{ functionName }}数据库操作。
@@ -242,7 +242,7 @@ class {{ BusinessName }}Dao:
return db_{{ subTable.business_name }}
@classmethod
- async def edit_{{ subTable.business_name }}_dao(cls, db: AsyncSession, {{ subTable.business_name }}: dict) -> None:
+ async def edit_{{ subTable.business_name }}_dao(cls, db: AsyncSession, {{ subTable.business_name }}: dict[str, Any]) -> None:
"""
编辑{{ subTable.function_name }}数据库操作。
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2
index 7cab9b033..f2fc3e12f 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2
@@ -31,7 +31,7 @@ class {{ BusinessName }}Service:
@classmethod
async def get_{{ businessName }}_list_services(
cls, query_db: AsyncSession, query_object: {{ BusinessName }}PageQueryModel, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取{{ functionName }}列表信息service。
@@ -198,7 +198,7 @@ class {{ BusinessName }}Service:
return result
@staticmethod
- async def export_{{ businessName }}_list_services({% if dicts %}request: Request, {% endif %}{{ businessName }}_list: list) -> bytes:
+ async def export_{{ businessName }}_list_services({% if dicts %}request: Request, {% endif %}{{ businessName }}_list: list[dict[str, Any]]) -> bytes:
"""
导出{{ functionName }}信息service。
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oauth_access_policy_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oauth_access_policy_dao.py
index 38830f9bc..bd0ae3cf8 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oauth_access_policy_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oauth_access_policy_dao.py
@@ -111,7 +111,7 @@ async def list_for_grants(db: AsyncSession, targets: list[tuple[int, int]]) -> l
return list(result.scalars().all())
@staticmethod
- def _query(query: AccessPolicyPageQueryModel) -> Select:
+ def _query(query: AccessPolicyPageQueryModel) -> Select[SysOAuthAccessPolicy, str, str, str]:
"""
构建独立访问策略查询,不依赖用户已有授权记录。
diff --git a/ruoyi-fastapi-backend/module_identity/dao/oauth_audit_dao.py b/ruoyi-fastapi-backend/module_identity/dao/oauth_audit_dao.py
index 1278f0ca5..84c44285c 100644
--- a/ruoyi-fastapi-backend/module_identity/dao/oauth_audit_dao.py
+++ b/ruoyi-fastapi-backend/module_identity/dao/oauth_audit_dao.py
@@ -2,7 +2,7 @@
from datetime import datetime
from typing import TypedDict, Unpack
-from sqlalchemy import delete, func, select
+from sqlalchemy import ColumnElement, delete, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from module_identity.entity.do.oauth_audit_do import SysOAuthAuditArchive, SysOAuthAuditLog
@@ -113,7 +113,7 @@ def _conditions(
risk_level: str | None = None,
start_time: datetime | None = None,
end_time: datetime | None = None,
- ) -> list:
+ ) -> list[ColumnElement[bool]]:
"""
构造 OAuth Audit 查询条件。
diff --git a/ruoyi-fastapi-backend/module_plugin/controller/plugin_browser_controller.py b/ruoyi-fastapi-backend/module_plugin/controller/plugin_browser_controller.py
index 143cfc531..bf4842027 100644
--- a/ruoyi-fastapi-backend/module_plugin/controller/plugin_browser_controller.py
+++ b/ruoyi-fastapi-backend/module_plugin/controller/plugin_browser_controller.py
@@ -21,7 +21,7 @@
'/{plugin_id}/session',
summary='创建插件浏览器会话接口',
description='用于为当前登录用户创建插件页面访问会话,并返回访问地址和防跨站请求令牌',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
)
async def create_plugin_browser_session(
request: Request,
diff --git a/ruoyi-fastapi-backend/module_plugin/controller/plugin_controller.py b/ruoyi-fastapi-backend/module_plugin/controller/plugin_controller.py
index b8bfb1196..4a8d4084f 100644
--- a/ruoyi-fastapi-backend/module_plugin/controller/plugin_controller.py
+++ b/ruoyi-fastapi-backend/module_plugin/controller/plugin_controller.py
@@ -60,7 +60,7 @@ def _public_plugin_payload(payload: Mapping[str, object]) -> dict[str, object]:
return public_payload
-def _plugin_operation_response(payload: dict, default_message: str) -> Response:
+def _plugin_operation_response(payload: Mapping[str, object], default_message: str) -> Response:
"""
按插件运行时 payload ok 字段统一构造操作响应。
@@ -77,7 +77,7 @@ def _plugin_operation_response(payload: dict, default_message: str) -> Response:
async def _execute_plugin_operation(
- operation: Callable[[], Awaitable[dict]],
+ operation: Callable[[], Awaitable[dict[str, object]]],
default_message: str,
) -> Response:
"""
@@ -123,7 +123,7 @@ async def get_system_plugin_list(
'/plan',
summary='生成插件批量操作计划接口',
description='用于生成批量安装、启用或升级插件的拓扑排序计划',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:query')],
)
async def plan_system_plugins(
@@ -143,7 +143,7 @@ async def plan_system_plugins(
'/{plugin_id}/precheck',
summary='执行插件操作预检接口',
description='用于在安装、启用、升级、卸载或清理前执行统一预检',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:query')],
)
async def precheck_system_plugin(
@@ -164,7 +164,7 @@ async def precheck_system_plugin(
'/batch',
summary='批量执行插件操作接口',
description='用于按插件依赖拓扑顺序批量安装、启用或升级插件',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:edit')],
)
@Log(title='插件管理', business_type=BusinessType.UPDATE)
@@ -285,7 +285,7 @@ async def query_detail_system_plugin_operation_log(
'/{plugin_id}/migrations',
summary='获取插件 migration 历史接口',
description='用于获取指定插件的 migration 执行历史',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:query')],
)
async def list_system_plugin_migrations(
@@ -308,7 +308,7 @@ async def list_system_plugin_migrations(
'/{plugin_id}/migrations/mark-success',
summary='人工标记插件 migration 成功接口',
description='用于人工确认指定 migration 已执行成功并更新历史状态',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:edit')],
)
@Log(title='插件管理', business_type=BusinessType.UPDATE)
@@ -333,7 +333,7 @@ async def mark_system_plugin_migration_success(
'/{plugin_id}/migrations/mark-failed',
summary='人工标记插件 migration 失败接口',
description='用于人工确认指定 migration 未完成并更新历史状态为可重试失败',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:edit')],
)
@Log(title='插件管理', business_type=BusinessType.UPDATE)
@@ -379,7 +379,7 @@ async def query_detail_system_plugin(
'/{plugin_id}/enable',
summary='启用插件接口',
description='用于启用指定插件',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:edit')],
)
@Log(title='插件管理', business_type=BusinessType.UPDATE)
@@ -398,7 +398,7 @@ async def enable_system_plugin(
'/{plugin_id}/disable',
summary='停用插件接口',
description='用于停用指定插件',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:edit')],
)
@Log(title='插件管理', business_type=BusinessType.UPDATE)
@@ -416,7 +416,7 @@ async def disable_system_plugin(
'/{plugin_id}/check',
summary='检查插件接口',
description='用于检查指定插件的目录结构、依赖和菜单冲突',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:query')],
)
async def check_system_plugin(
@@ -435,7 +435,7 @@ async def check_system_plugin(
'/{plugin_id}/health',
summary='执行插件健康检查接口',
description='用于执行指定插件声明的只读健康检查',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:query')],
)
async def health_system_plugin(
@@ -454,7 +454,7 @@ async def health_system_plugin(
'/{plugin_id}/diagnose',
summary='生成插件诊断包接口',
description='用于生成指定插件的只读诊断信息,包含详情、检查结果、配置脱敏快照和审计预留信息',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:query')],
)
async def diagnose_system_plugin(
@@ -490,7 +490,7 @@ async def diagnose_system_plugin(
'/{plugin_id}/docs',
summary='生成插件文档接口',
description='用于根据 plugin.yaml 生成插件 Markdown 文档片段',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:query')],
)
async def generate_system_plugin_docs(
@@ -509,7 +509,7 @@ async def generate_system_plugin_docs(
'/{plugin_id}/install',
summary='安装插件接口',
description='用于安装指定插件',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:edit')],
)
@Log(title='插件管理', business_type=BusinessType.INSERT)
@@ -533,7 +533,7 @@ async def install_system_plugin(
'/{plugin_id}/upgrade',
summary='升级插件接口',
description='用于升级指定插件',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:edit')],
)
@Log(title='插件管理', business_type=BusinessType.UPDATE)
@@ -557,7 +557,7 @@ async def upgrade_system_plugin(
'/{plugin_id}/uninstall',
summary='安全卸载插件接口',
description='用于安全卸载指定插件,第一阶段等价于停用插件和菜单',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:edit')],
)
@Log(title='插件管理', business_type=BusinessType.UPDATE)
@@ -581,7 +581,7 @@ async def uninstall_system_plugin(
'/{plugin_id}/purge',
summary='物理清理插件接口',
description='用于物理清理指定插件的平台元数据,默认不删除源码目录',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:remove')],
)
@Log(title='插件管理', business_type=BusinessType.DELETE)
@@ -605,7 +605,7 @@ async def purge_system_plugin(
'/{plugin_id}/config',
summary='获取插件配置接口',
description='用于获取指定插件的配置项',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:query')],
)
async def query_system_plugin_config(
@@ -624,7 +624,7 @@ async def query_system_plugin_config(
'/{plugin_id}/config',
summary='更新插件配置接口',
description='用于更新指定插件的配置项',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:edit')],
)
@Log(title='插件管理', business_type=BusinessType.UPDATE)
@@ -646,7 +646,7 @@ async def update_system_plugin_config(
'/{plugin_id}/config/export',
summary='导出插件配置接口',
description='用于导出指定插件的配置快照,默认敏感配置保持脱敏',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:export')],
)
async def export_system_plugin_config(
@@ -671,7 +671,7 @@ async def export_system_plugin_config(
'/{plugin_id}/config/import',
summary='导入插件配置接口',
description='用于导入指定插件的配置快照',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:edit')],
)
@Log(title='插件管理', business_type=BusinessType.UPDATE)
@@ -693,7 +693,7 @@ async def import_system_plugin_config(
'/{plugin_id}/dependencies',
summary='检查插件依赖接口',
description='用于检查指定插件的 Python 和 npm 依赖',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:query')],
)
async def check_system_plugin_dependencies(
@@ -712,7 +712,7 @@ async def check_system_plugin_dependencies(
'/{plugin_id}/dependencies/install',
summary='插件依赖安装计划接口',
description='用于生成指定插件的依赖安装计划,Web 第一版仅支持 dry-run',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
dependencies=[UserInterfaceAuthDependency('system:plugin:query')],
)
async def install_system_plugin_dependencies(
diff --git a/ruoyi-fastapi-backend/module_plugin/controller/plugin_metrics_controller.py b/ruoyi-fastapi-backend/module_plugin/controller/plugin_metrics_controller.py
index d859eaba1..7e33f0246 100644
--- a/ruoyi-fastapi-backend/module_plugin/controller/plugin_metrics_controller.py
+++ b/ruoyi-fastapi-backend/module_plugin/controller/plugin_metrics_controller.py
@@ -23,7 +23,7 @@
'/runtime/metrics',
summary='获取插件运行指标接口',
description='用于查询显式插件的请求与任务累计指标,按实际加载版本和可观测worker分组',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
)
async def get_plugin_runtime_metrics(
request: Request,
@@ -43,7 +43,7 @@ async def get_plugin_runtime_metrics(
'/{plugin_id}/config/status',
summary='获取插件配置生效状态接口',
description='比较数据库配置与已观测进程的启动快照;按需读取版本仅表示读取完成,不代表业务设置已经应用',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
)
async def get_plugin_config_status(
request: Request,
diff --git a/ruoyi-fastapi-backend/module_plugin/controller/plugin_release_controller.py b/ruoyi-fastapi-backend/module_plugin/controller/plugin_release_controller.py
index 1edbddc83..755059ff7 100644
--- a/ruoyi-fastapi-backend/module_plugin/controller/plugin_release_controller.py
+++ b/ruoyi-fastapi-backend/module_plugin/controller/plugin_release_controller.py
@@ -57,7 +57,7 @@ async def _read_release_payload(operation: Callable[[], Awaitable[dict[str, Any]
'/artifacts/list',
summary='获取已验证插件制品列表接口',
description='用于获取已验证的插件制品列表,支持按插件ID筛选',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
)
async def list_plugin_artifacts(
plugin_id: Annotated[
@@ -71,7 +71,7 @@ async def list_plugin_artifacts(
'/release/status',
summary='获取插件发布状态接口',
description='用于查询插件发布目标及各工作进程的实际状态,支持按插件ID筛选',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
)
async def get_plugin_release_status(
plugin_id: Annotated[
@@ -85,7 +85,7 @@ async def get_plugin_release_status(
'/release/plan',
summary='获取插件发布预检计划接口',
description='用于根据插件ID和制品摘要获取维护发布前的静态预检计划',
- response_model=DataResponseModel[dict],
+ response_model=DataResponseModel[dict[str, object]],
)
async def plan_plugin_release(
plugin_id: Annotated[str, Query(alias='pluginId', description='插件ID', pattern=r'^[a-z][a-z0-9_]{1,63}$')],
diff --git a/ruoyi-fastapi-backend/plugins/ai/controller/ai_chat_controller.py b/ruoyi-fastapi-backend/plugins/ai/controller/ai_chat_controller.py
index 9a0c7d1d8..5677126c8 100644
--- a/ruoyi-fastapi-backend/plugins/ai/controller/ai_chat_controller.py
+++ b/ruoyi-fastapi-backend/plugins/ai/controller/ai_chat_controller.py
@@ -58,7 +58,7 @@ async def send_chat_message(
chat_req: AiChatRequestModel,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(AiModels)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(AiModels)],
) -> StreamingResponse:
user_id = current_user.user.user_id if current_user and current_user.user else 1
if not current_user.user.admin:
diff --git a/ruoyi-fastapi-backend/plugins/ai/controller/ai_model_controller.py b/ruoyi-fastapi-backend/plugins/ai/controller/ai_model_controller.py
index 1923cdf42..f73890e39 100644
--- a/ruoyi-fastapi-backend/plugins/ai/controller/ai_model_controller.py
+++ b/ruoyi-fastapi-backend/plugins/ai/controller/ai_model_controller.py
@@ -42,7 +42,7 @@ async def get_ai_model_list(
request: Request,
ai_model_page_query: Annotated[AiModelPageQueryModel, Query()],
query_db: Annotated[AsyncSession, DBSessionDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(AiModels)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(AiModels)],
) -> Response:
# 获取分页数据
result = await AiModelService.get_ai_model_list_services(
@@ -63,7 +63,7 @@ async def get_ai_model_list(
async def get_ai_model_all(
request: Request,
query_db: Annotated[AsyncSession, DBSessionDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(AiModels)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(AiModels)],
) -> Response:
# 获取不分页数据
ai_model_page_query = AiModelPageQueryModel(status='0')
@@ -126,7 +126,7 @@ async def edit_ai_model(
edit_ai_model: AiModelModel,
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(AiModels)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(AiModels)],
) -> Response:
if not current_user.user.admin:
await AiModelService.check_ai_model_data_scope_services(query_db, edit_ai_model.model_id, data_scope_sql)
@@ -151,7 +151,7 @@ async def delete_ai_model(
model_ids: Annotated[str, Path(description='需要删除的模型ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(AiModels)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(AiModels)],
) -> Response:
model_id_list = model_ids.split(',')
for model_id in model_id_list:
@@ -177,7 +177,7 @@ async def get_ai_model_detail(
model_id: Annotated[int, Path(description='模型ID')],
query_db: Annotated[AsyncSession, DBSessionDependency()],
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope_sql: Annotated[ColumnElement, DataScopeDependency(AiModels)],
+ data_scope_sql: Annotated[ColumnElement[bool], DataScopeDependency(AiModels)],
) -> Response:
if not current_user.user.admin:
await AiModelService.check_ai_model_data_scope_services(query_db, model_id, data_scope_sql)
diff --git a/ruoyi-fastapi-backend/plugins/ai/dao/ai_chat_dao.py b/ruoyi-fastapi-backend/plugins/ai/dao/ai_chat_dao.py
index 772bfa96c..d87299649 100644
--- a/ruoyi-fastapi-backend/plugins/ai/dao/ai_chat_dao.py
+++ b/ruoyi-fastapi-backend/plugins/ai/dao/ai_chat_dao.py
@@ -1,3 +1,5 @@
+from typing import Any
+
from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession
@@ -41,7 +43,7 @@ async def add_chat_config_dao(cls, db: AsyncSession, chat_config: AiChatConfigMo
return db_chat_config
@classmethod
- async def edit_chat_config_dao(cls, db: AsyncSession, chat_config: dict) -> None:
+ async def edit_chat_config_dao(cls, db: AsyncSession, chat_config: dict[str, Any]) -> None:
"""
编辑对话配置数据库操作。
diff --git a/ruoyi-fastapi-backend/plugins/ai/dao/ai_model_dao.py b/ruoyi-fastapi-backend/plugins/ai/dao/ai_model_dao.py
index 77644552d..b72b7b383 100644
--- a/ruoyi-fastapi-backend/plugins/ai/dao/ai_model_dao.py
+++ b/ruoyi-fastapi-backend/plugins/ai/dao/ai_model_dao.py
@@ -27,8 +27,12 @@ async def get_ai_model_detail_by_id(cls, db: AsyncSession, model_id: int) -> AiM
@classmethod
async def get_ai_model_list(
- cls, db: AsyncSession, query_object: AiModelPageQueryModel, data_scope_sql: ColumnElement, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]:
+ cls,
+ db: AsyncSession,
+ query_object: AiModelPageQueryModel,
+ data_scope_sql: ColumnElement[bool],
+ is_page: bool = False,
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取AI模型列表信息。
@@ -50,7 +54,7 @@ async def get_ai_model_list(
)
.order_by(AiModels.model_sort)
)
- ai_model_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ ai_model_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db, query, query_object.page_num, query_object.page_size, is_page
)
@@ -72,7 +76,7 @@ async def add_ai_model_dao(cls, db: AsyncSession, ai_model: AiModelModel) -> AiM
return db_model
@classmethod
- async def edit_ai_model_dao(cls, db: AsyncSession, ai_model: dict) -> None:
+ async def edit_ai_model_dao(cls, db: AsyncSession, ai_model: dict[str, Any]) -> None:
"""
编辑AI模型数据库操作。
diff --git a/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_chat_vo.py b/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_chat_vo.py
index 27344457d..35cf586b3 100644
--- a/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_chat_vo.py
+++ b/ruoyi-fastapi-backend/plugins/ai/entity/vo/ai_chat_vo.py
@@ -68,10 +68,10 @@ class SessionMetricsModel(CamelModel):
input_tokens: int | None = Field(default=None, description='输入Token数量')
total_tokens: int | None = Field(default=None, description='总Token数量')
output_tokens: int | None = Field(default=None, description='输出Token数量')
- provider_metrics: dict | None = Field(default=None, description='提供者指标')
+ provider_metrics: dict[str, object] | None = Field(default=None, description='提供者指标')
reasoning_tokens: int | None = Field(default=None, description='推理Token数量')
cache_read_tokens: int | None = Field(default=None, description='缓存读取Token数量')
- additional_metrics: dict | None = Field(default=None, description='其他指标')
+ additional_metrics: dict[str, object] | None = Field(default=None, description='其他指标')
audio_input_tokens: int | None = Field(default=None, description='音频输入Token数量')
audio_total_tokens: int | None = Field(default=None, description='音频总Token数量')
cache_write_tokens: int | None = Field(default=None, description='缓存写入Token数量')
@@ -82,7 +82,7 @@ class SessionMetricsModel(CamelModel):
class SessionDataModel(CamelModel):
"""对话会话数据模型。"""
- session_state: dict | None = Field(default=None, description='会话状态')
+ session_state: dict[str, object] | None = Field(default=None, description='会话状态')
session_metrics: SessionMetricsModel | None = Field(default=None, description='会话指标')
diff --git a/ruoyi-fastapi-backend/plugins/ai/service/ai_model_service.py b/ruoyi-fastapi-backend/plugins/ai/service/ai_model_service.py
index d8e78e03d..700e7227d 100644
--- a/ruoyi-fastapi-backend/plugins/ai/service/ai_model_service.py
+++ b/ruoyi-fastapi-backend/plugins/ai/service/ai_model_service.py
@@ -20,9 +20,9 @@ async def get_ai_model_list_services(
cls,
query_db: AsyncSession,
query_object: AiModelPageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: Literal[True],
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -30,7 +30,7 @@ async def get_ai_model_list_services(
cls,
query_db: AsyncSession,
query_object: AiModelPageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: Literal[False] = False,
) -> list[dict[str, Any]]: ...
@@ -39,9 +39,9 @@ async def get_ai_model_list_services(
cls,
query_db: AsyncSession,
query_object: AiModelPageQueryModel,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
is_page: bool = False,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取AI模型列表信息service。
@@ -65,7 +65,7 @@ async def check_ai_model_data_scope_services(
cls,
query_db: AsyncSession,
model_id: int | None,
- data_scope_sql: ColumnElement,
+ data_scope_sql: ColumnElement[bool],
) -> CrudResponseModel:
"""
校验用户是否有AI模型数据权限service。
diff --git a/ruoyi-fastapi-backend/plugins/core/deployment/worker.py b/ruoyi-fastapi-backend/plugins/core/deployment/worker.py
index 871de6d2d..9e0e4ec96 100644
--- a/ruoyi-fastapi-backend/plugins/core/deployment/worker.py
+++ b/ruoyi-fastapi-backend/plugins/core/deployment/worker.py
@@ -80,7 +80,7 @@ def __init__(
self.versions: dict[str, str] = {}
self.errors: dict[str, str] = {}
self.state = 'starting'
- self.task: asyncio.Task | None = None
+ self.task: asyncio.Task[None] | None = None
self.app: Any = None
self.registered = False
diff --git a/ruoyi-fastapi-backend/plugins/core/management/dao/dao.py b/ruoyi-fastapi-backend/plugins/core/management/dao/dao.py
index 5f24f0e9c..bdd9cf628 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/dao/dao.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/dao/dao.py
@@ -79,7 +79,7 @@ async def get_plugin_page_list(
db: AsyncSession,
query_object: PluginPageQueryModel,
is_page: bool = False,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取插件列表。
@@ -100,7 +100,7 @@ async def get_plugin_page_list(
.order_by(SysPlugin.plugin_id)
.distinct()
)
- plugin_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ plugin_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db,
query,
query_object.page_num,
@@ -139,7 +139,7 @@ def dump_plugin_persistence_payload(plugin: PluginModel) -> dict[str, Any]:
)
@classmethod
- async def update_plugin(cls, db: AsyncSession, plugin: dict) -> None:
+ async def update_plugin(cls, db: AsyncSession, plugin: dict[str, Any]) -> None:
"""
更新插件。
@@ -603,7 +603,7 @@ async def add_plugin_config(cls, db: AsyncSession, plugin_config: PluginConfigMo
return db_plugin_config
@classmethod
- async def update_plugin_config(cls, db: AsyncSession, plugin_config: dict) -> None:
+ async def update_plugin_config(cls, db: AsyncSession, plugin_config: dict[str, Any]) -> None:
"""
更新插件配置。
@@ -642,7 +642,7 @@ async def get_plugin_operation_log_page_list(
db: AsyncSession,
query_object: PluginOperationLogPageQueryModel,
is_page: bool = False,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
根据查询参数获取插件批量操作审计日志列表。
@@ -654,7 +654,7 @@ async def get_plugin_operation_log_page_list(
query = (
cls._build_operation_log_query(query_object).order_by(SysPluginOperationLog.operation_id.desc()).distinct()
)
- operation_log_list: PageModel | list[dict[str, Any]] = await PageUtil.paginate(
+ operation_log_list: PageModel[dict[str, Any]] | list[dict[str, Any]] = await PageUtil.paginate(
db,
query,
query_object.page_num,
@@ -929,7 +929,7 @@ async def add_sys_menu(cls, db: AsyncSession, menu: MenuModel) -> SysMenu:
return db_menu
@classmethod
- async def update_sys_menu(cls, db: AsyncSession, menu: dict) -> None:
+ async def update_sys_menu(cls, db: AsyncSession, menu: dict[str, Any]) -> None:
"""
更新系统菜单。
diff --git a/ruoyi-fastapi-backend/plugins/core/management/service/service.py b/ruoyi-fastapi-backend/plugins/core/management/service/service.py
index eaccfd3ff..bb5142991 100644
--- a/ruoyi-fastapi-backend/plugins/core/management/service/service.py
+++ b/ruoyi-fastapi-backend/plugins/core/management/service/service.py
@@ -86,7 +86,7 @@ async def get_plugin_page_list_services(
*,
backend_root: Path | None = None,
frontend_root: Path | None = None,
- ) -> PageModel: ...
+ ) -> PageModel[dict[str, Any]]: ...
@classmethod
@overload
@@ -109,7 +109,7 @@ async def get_plugin_page_list_services(
*,
backend_root: Path | None = None,
frontend_root: Path | None = None,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]:
"""
获取插件分页列表。
@@ -547,7 +547,7 @@ async def get_plugin_operation_log_page_list_services(
query_db: AsyncSession,
query_object: PluginOperationLogPageQueryModel,
is_page: Literal[True] = True,
- ) -> PageModel: ...
+ ) -> PageModel[PluginOperationLogDetailModel]: ...
@classmethod
@overload
@@ -564,7 +564,7 @@ async def get_plugin_operation_log_page_list_services(
query_db: AsyncSession,
query_object: PluginOperationLogPageQueryModel,
is_page: bool = True,
- ) -> PageModel | list[dict[str, Any]]:
+ ) -> PageModel[PluginOperationLogDetailModel] | list[dict[str, Any]]:
"""
获取插件批量操作审计日志分页列表。
@@ -577,9 +577,13 @@ async def get_plugin_operation_log_page_list_services(
if not isinstance(page_result, PageModel):
return page_result
- page_result.rows = [PluginOperationLogBuilder.build_detail(row) for row in page_result.rows]
-
- return page_result
+ return PageModel[PluginOperationLogDetailModel](
+ rows=[PluginOperationLogBuilder.build_detail(row) for row in page_result.rows],
+ page_num=page_result.page_num,
+ page_size=page_result.page_size,
+ total=page_result.total,
+ has_next=page_result.has_next,
+ )
@classmethod
async def get_plugin_operation_log_export_list_services(
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics_store.py b/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics_store.py
index 7f9ca0179..e2976453f 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics_store.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/diagnostics_store.py
@@ -183,7 +183,7 @@ def __init__(self, snapshot_provider: Callable[[], PluginRuntimeDiagnosticSnapsh
self.worker_id = worker_id
self.redis: Any = None
self.namespace = ''
- self.task: asyncio.Task | None = None
+ self.task: asyncio.Task[None] | None = None
self.publication_failed = False
self._stopping = False
diff --git a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle_lock.py b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle_lock.py
index 5389a024c..958c0e6a9 100644
--- a/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle_lock.py
+++ b/ruoyi-fastapi-backend/plugins/core/runtime/service/lifecycle_lock.py
@@ -117,7 +117,7 @@ async def lock(self, plugin_id: str, operation: str) -> AsyncGenerator[PluginLif
lock_key = self._build_lock_key()
lock_value = f'{plugin_id}:{operation}:{uuid4()}'
acquired = False
- renewal_task: asyncio.Task | None = None
+ renewal_task: asyncio.Task[None] | None = None
body_failed = False
try:
try:
@@ -170,8 +170,8 @@ def _start_lock_renewal(
redis: aioredis.Redis,
lock_key: str,
lock_value: str,
- owner_task: asyncio.Task | None = None,
- ) -> asyncio.Task:
+ owner_task: asyncio.Task[object] | None = None,
+ ) -> asyncio.Task[None]:
"""
启动生命周期锁续期任务。
@@ -188,7 +188,7 @@ async def _renew_lock_loop(
redis: aioredis.Redis,
lock_key: str,
lock_value: str,
- owner_task: asyncio.Task | None = None,
+ owner_task: asyncio.Task[object] | None = None,
) -> None:
"""
周期性续期生命周期锁。
@@ -218,7 +218,7 @@ async def _renew_lock_loop(
raise PluginLifecycleLockLost(data='', message=message) from exc
@staticmethod
- def _get_renewal_error(renewal_task: asyncio.Task | None) -> PluginLifecycleLockLost | None:
+ def _get_renewal_error(renewal_task: asyncio.Task[None] | None) -> PluginLifecycleLockLost | None:
"""
获取续期任务失败原因。
@@ -233,7 +233,7 @@ def _get_renewal_error(renewal_task: asyncio.Task | None) -> PluginLifecycleLock
return None
return exc if isinstance(exc, PluginLifecycleLockLost) else None
- async def _stop_lock_renewal(self, renewal_task: asyncio.Task) -> PluginLifecycleLockLost | None:
+ async def _stop_lock_renewal(self, renewal_task: asyncio.Task[None]) -> PluginLifecycleLockLost | None:
"""
停止锁续期任务并返回续期失败原因。
diff --git a/ruoyi-fastapi-backend/scripts/verify_timezone_database.py b/ruoyi-fastapi-backend/scripts/verify_timezone_database.py
index f799052ef..c1ee5f884 100644
--- a/ruoyi-fastapi-backend/scripts/verify_timezone_database.py
+++ b/ruoyi-fastapi-backend/scripts/verify_timezone_database.py
@@ -6,6 +6,7 @@
import sys
from datetime import UTC, datetime, timedelta, timezone
from pathlib import Path
+from typing import Any
from uuid import uuid4
from dotenv import dotenv_values
@@ -45,7 +46,7 @@ def load_source(args: argparse.Namespace) -> DataSourceSettings:
return DataSourceSettings.model_validate(sources[args.source or values['DB_DEFAULT_SOURCE']])
-def initialize(source: DataSourceSettings, report: dict) -> DataSourceSettings: # noqa: PLR0915
+def initialize(source: DataSourceSettings, report: dict[str, Any]) -> DataSourceSettings: # noqa: PLR0915
"""
创建隔离测试库并验证UTC种子数据。
@@ -123,7 +124,7 @@ def initialize(source: DataSourceSettings, report: dict) -> DataSourceSettings:
return target
-def inspect_schema(source: DataSourceSettings, report: dict) -> None:
+def inspect_schema(source: DataSourceSettings, report: dict[str, Any]) -> None:
"""
逐列核对实际数据库和ORM的时间类型约定。
@@ -187,7 +188,7 @@ def inspect_schema(source: DataSourceSettings, report: dict) -> None:
engine.dispose()
-async def verify_drivers(source: DataSourceSettings, report: dict) -> None:
+async def verify_drivers(source: DataSourceSettings, report: dict[str, Any]) -> None:
"""
验证同步和异步驱动的UTC会话、精度及重连行为。
@@ -237,7 +238,7 @@ async def verify_drivers(source: DataSourceSettings, report: dict) -> None:
await async_engine.dispose()
-async def verify_generator(source: DataSourceSettings, report: dict) -> None:
+async def verify_generator(source: DataSourceSettings, report: dict[str, Any]) -> None:
"""
使用真实数据库验证普通表、树表和主子表生成代码。
@@ -267,7 +268,7 @@ async def verify_generator(source: DataSourceSettings, report: dict) -> None:
engine.dispose()
-async def verify_metadata_and_scheduler(source: DataSourceSettings, report: dict) -> None:
+async def verify_metadata_and_scheduler(source: DataSourceSettings, report: dict[str, Any]) -> None:
"""
验证数据库元数据时间及持久化调度行为。
diff --git a/ruoyi-fastapi-backend/tests/cli/completion/test_providers.py b/ruoyi-fastapi-backend/tests/cli/completion/test_providers.py
index 4a1f1d443..5a7ba039b 100644
--- a/ruoyi-fastapi-backend/tests/cli/completion/test_providers.py
+++ b/ruoyi-fastapi-backend/tests/cli/completion/test_providers.py
@@ -123,7 +123,7 @@ class ConfigRuntime:
"""模拟配置运行时服务对象。"""
@staticmethod
- def list_configs(**kwargs: str) -> dict:
+ def list_configs(**kwargs: str) -> dict[str, str]:
"""
模拟配置列表查询入口。
@@ -168,7 +168,7 @@ class GenRuntime:
"""模拟代码生成运行时服务对象。"""
@staticmethod
- def list_gen_tables(**kwargs: str) -> dict:
+ def list_gen_tables(**kwargs: str) -> dict[str, str]:
"""
模拟业务表列表查询入口。
@@ -178,7 +178,7 @@ def list_gen_tables(**kwargs: str) -> dict:
return kwargs
@staticmethod
- def list_gen_db_tables(**kwargs: str) -> dict:
+ def list_gen_db_tables(**kwargs: str) -> dict[str, str]:
"""
模拟数据库物理表列表查询入口。
@@ -279,7 +279,7 @@ class JobRuntime:
"""模拟任务运行时服务对象。"""
@staticmethod
- def list_jobs(**kwargs: str) -> dict:
+ def list_jobs(**kwargs: str) -> dict[str, str]:
"""
模拟任务列表查询入口。
@@ -322,7 +322,7 @@ class JobRuntime:
"""模拟任务运行时服务对象。"""
@staticmethod
- def list_jobs(**kwargs: str) -> dict:
+ def list_jobs(**kwargs: str) -> dict[str, str]:
"""
模拟任务列表查询入口。
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_contract_app_ops.py b/ruoyi-fastapi-backend/tests/cli/root/test_contract_app_ops.py
index e46dc091d..9d1a7dcb3 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_contract_app_ops.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_contract_app_ops.py
@@ -4,6 +4,7 @@
from collections.abc import Callable
from pathlib import Path
from textwrap import dedent
+from typing import Any
import pytest
@@ -16,7 +17,7 @@
def test_app_config_json_output_is_pure_json(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""应用配置命令只输出 JSON。"""
completed = run_cli_command('app', 'config', '--env=dev', '--output=json')
@@ -89,8 +90,8 @@ def test_app_doctor_text_output_has_stable_check_structure(
def test_app_doctor_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
- assert_check_payload_contract: Callable[[dict, bool], None],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
+ assert_check_payload_contract: Callable[[dict[str, Any], bool], None],
) -> None:
"""应用诊断按约定输出 JSON。"""
completed = run_cli_command('app', 'doctor', '--env=dev', '--output=json')
@@ -109,7 +110,7 @@ def test_app_doctor_json_output_has_stable_contract(
def test_app_env_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""环境信息按约定输出 JSON。"""
completed = run_cli_command('app', 'env', '--env=dev', '--output=json')
@@ -138,7 +139,7 @@ def test_app_env_json_output_has_stable_contract(
def test_app_routes_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""路由列表按约定输出 JSON。"""
completed = run_cli_command('app', 'routes', '--env=dev', '--output=json')
@@ -233,8 +234,8 @@ def test_ops_deps_text_output_has_stable_structure(
def test_ops_health_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
- assert_check_payload_contract: Callable[[dict, bool], None],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
+ assert_check_payload_contract: Callable[[dict[str, Any], bool], None],
) -> None:
"""健康检查按约定输出 JSON。"""
completed = run_cli_command('ops', 'health', '--env=dev', '--output=json')
@@ -251,7 +252,7 @@ def test_ops_health_json_output_has_stable_contract(
def test_ops_deps_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""依赖检查按约定输出 JSON。"""
completed = run_cli_command('ops', 'deps', '--env=dev', '--output=json')
@@ -276,7 +277,7 @@ def test_ops_deps_json_output_has_stable_contract(
def test_ops_server_info_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""服务器信息按约定输出 JSON。"""
completed = run_cli_command('ops', 'server-info', '--env=dev', '--output=json')
@@ -338,7 +339,7 @@ def test_ops_server_info_json_output_has_stable_contract(
def test_plugin_list_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""插件列表按约定输出 JSON。"""
completed = run_cli_command('plugin', 'list', '--env=dev', '--output=json')
@@ -357,7 +358,7 @@ def test_plugin_list_json_output_has_stable_contract(
def test_plugin_check_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""插件检查按约定输出 JSON。"""
completed = run_cli_command('plugin', 'check', '--env=dev', '--output=json')
@@ -386,7 +387,7 @@ def test_plugin_check_json_output_has_stable_contract(
def test_plugin_check_deps_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""插件依赖检查按约定输出 JSON。"""
completed = run_cli_command('plugin', 'check-deps', 'ai', '--env=dev', '--output=json')
@@ -408,7 +409,7 @@ def test_plugin_check_deps_json_output_has_stable_contract(
def test_plugin_install_deps_dry_run_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""插件依赖安装预演按约定输出 JSON。"""
completed = run_cli_command('plugin', 'install-deps', 'ai', '--dry-run', '--yes', '--env=dev', '--output=json')
@@ -424,7 +425,7 @@ def test_plugin_install_deps_dry_run_json_output_has_stable_contract(
def test_plugin_plan_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""插件操作计划按约定输出 JSON。"""
completed = run_cli_command('plugin', 'plan', 'install', 'ai', '--env=dev', '--output=json')
@@ -451,7 +452,7 @@ def test_plugin_plan_rejects_invalid_operation_at_cli_boundary(
def test_plugin_batch_dry_run_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""批量插件操作预演按约定输出 JSON。"""
completed = run_cli_command('plugin', 'batch', 'install', 'ai', '--dry-run', '--yes', '--env=dev', '--output=json')
@@ -482,7 +483,7 @@ def test_plugin_list_text_output_has_stable_structure(
def test_plugin_create_dry_run_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""创建插件的预演按约定输出 JSON。"""
completed = run_cli_command('plugin', 'create', 'contract_demo', '--dry-run', '--env=dev', '--output=json')
@@ -506,7 +507,7 @@ def test_plugin_create_dry_run_json_output_has_stable_contract(
def test_plugin_create_optional_parts_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""创建插件时在 JSON 中列出可选组件。"""
completed = run_cli_command(
@@ -536,7 +537,7 @@ def test_plugin_create_optional_parts_json_output_has_stable_contract(
def test_plugin_create_frontend_framework_override_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""创建插件时在 JSON 中反映指定的前端框架。"""
completed = run_cli_command(
@@ -588,7 +589,7 @@ def test_plugin_create_rejects_removed_frontend_version_option(
def test_plugin_install_dry_run_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""安装插件的预演按约定输出 JSON。"""
completed = run_cli_command(
@@ -604,7 +605,7 @@ def test_plugin_install_dry_run_json_output_has_stable_contract(
def test_plugin_upgrade_dry_run_json_output_has_stable_contract(
backend_dir: Path,
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""升级插件的预演按约定输出 JSON。"""
# 成功契约需要已确认的目录插件来源;CI 不应连接宿主数据库来决定测试结果。
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_contract_cli.py b/ruoyi-fastapi-backend/tests/cli/root/test_contract_cli.py
index d877d2c3f..e8c1e3428 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_contract_cli.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_contract_cli.py
@@ -1,6 +1,7 @@
import subprocess
from collections.abc import Callable
from pathlib import Path
+from typing import Any
import pytest
@@ -30,7 +31,7 @@ def test_root_help_shows_commands_without_completion_options(
def test_oidc_key_bootstrap_dry_run_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""OIDC 初始化命令支持不连接基础设施的部署预演。"""
completed = run_cli_command(
@@ -114,7 +115,7 @@ def test_powershell_completion_protocol_returns_candidates_without_not_supported
def test_completion_doctor_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""补全诊断按约定输出 JSON。"""
completed = run_cli_command('completion', 'doctor', '--output=json')
@@ -149,7 +150,7 @@ def test_completion_doctor_json_output_has_stable_contract(
def test_completion_install_json_output_has_stable_contract(
tmp_path: Path,
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""安装补全脚本按约定输出 JSON。"""
target_file = tmp_path / 'ruoyi.bash'
@@ -203,7 +204,7 @@ def test_completion_install_json_output_has_stable_contract(
def test_completion_install_powershell_json_output_has_stable_contract(
tmp_path: Path,
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""安装 PowerShell 补全时按约定输出 JSON。"""
target_file = tmp_path / 'ruoyi.ps1'
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_contract_config.py b/ruoyi-fastapi-backend/tests/cli/root/test_contract_config.py
index bbe2f5c4e..d0f914b71 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_contract_config.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_contract_config.py
@@ -1,5 +1,6 @@
import subprocess
from collections.abc import Callable
+from typing import Any
import pytest
@@ -10,7 +11,7 @@
def test_config_doctor_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""配置诊断按约定输出 JSON。"""
completed = run_cli_command('config', 'doctor', '--env=dev', '--output=json')
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_contract_db_cache_dev.py b/ruoyi-fastapi-backend/tests/cli/root/test_contract_db_cache_dev.py
index f33d4e5d7..de78f48ec 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_contract_db_cache_dev.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_contract_db_cache_dev.py
@@ -1,6 +1,7 @@
import subprocess
from collections.abc import Callable
from pathlib import Path
+from typing import Any
import pytest
@@ -12,7 +13,7 @@
def test_dangerous_command_is_rejected_without_yes_in_non_interactive_mode(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""非交互执行危险命令时必须显式确认。"""
completed = run_cli_command('db', 'revision', '--env=dev', '--message=test-contract', '--output=json')
@@ -26,7 +27,7 @@ def test_dangerous_command_is_rejected_without_yes_in_non_interactive_mode(
def test_prod_dangerous_command_is_rejected_without_allow_prod(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""生产环境的危险命令需要显式授权。"""
completed = run_cli_command('db', 'revision', '--env=prod', '--message=test-contract', '--output=json')
@@ -42,7 +43,7 @@ def test_prod_dangerous_command_is_rejected_without_allow_prod(
def test_dry_run_command_returns_structured_preview_payload(
backend_dir: Path,
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""命令预演返回结构化预览。"""
completed = run_cli_command(
@@ -66,7 +67,7 @@ def test_dry_run_command_returns_structured_preview_payload(
def test_db_heads_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""数据库迁移头按约定输出 JSON。"""
completed = run_cli_command('db', 'heads', '--env=dev', '--output=json')
@@ -96,7 +97,7 @@ def test_db_heads_json_output_has_stable_contract(
def test_db_history_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""数据库迁移历史按约定输出 JSON。"""
completed = run_cli_command(
@@ -125,7 +126,7 @@ def test_db_history_json_output_has_stable_contract(
def test_cache_ttl_json_output_has_stable_contract_for_missing_key_or_redis_error(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""缓存键缺失或 Redis 报错时仍按约定输出 TTL 信息。"""
completed = run_cli_command(
@@ -192,7 +193,7 @@ def test_dry_run_text_output_contains_preview_command_and_workdir(
def test_dev_lint_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""代码检查按约定输出 JSON。"""
completed = run_cli_command(
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_contract_job_gen.py b/ruoyi-fastapi-backend/tests/cli/root/test_contract_job_gen.py
index 7d82c1253..9f76c81e1 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_contract_job_gen.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_contract_job_gen.py
@@ -1,5 +1,6 @@
import subprocess
from collections.abc import Callable
+from typing import Any
import pytest
@@ -14,7 +15,7 @@
def test_job_detail_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""任务详情按约定输出 JSON。"""
list_completed = run_cli_command('job', 'list', '--env=dev', '--output=json')
@@ -49,7 +50,7 @@ def test_job_detail_json_output_has_stable_contract(
def test_job_logs_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""任务日志按约定输出 JSON。"""
completed = run_cli_command('job', 'logs', '--env=dev', '--output=json')
@@ -76,7 +77,7 @@ def test_job_logs_json_output_has_stable_contract(
def test_gen_list_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""生成表列表按约定输出 JSON。"""
completed = run_cli_command('gen', 'list', '--env=dev', '--output=json')
@@ -103,7 +104,7 @@ def test_gen_list_json_output_has_stable_contract(
def test_gen_db_list_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""数据库表列表按约定输出 JSON。"""
completed = run_cli_command('gen', 'db-list', '--env=dev', '--output=json')
@@ -129,7 +130,7 @@ def test_gen_db_list_json_output_has_stable_contract(
def test_gen_detail_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""生成表详情按约定输出 JSON。"""
list_completed = run_cli_command('gen', 'list', '--env=dev', '--output=json')
@@ -169,7 +170,7 @@ def test_gen_detail_json_output_has_stable_contract(
def test_gen_sync_db_is_rejected_without_yes_in_non_interactive_mode(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""非交互同步数据库表前必须显式确认。"""
completed = run_cli_command('gen', 'sync-db', 'demo_table', '--env=dev', '--output=json')
@@ -209,7 +210,7 @@ def test_gen_export_dry_run_text_output_has_stable_structure(
def test_gen_export_dry_run_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""导出预演按约定输出 JSON。"""
completed = run_cli_command(
@@ -262,7 +263,7 @@ def test_gen_create_table_dry_run_text_output_has_stable_structure(
def test_gen_create_table_dry_run_json_output_has_stable_contract(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""建表预演按约定输出 JSON。"""
completed = run_cli_command(
@@ -310,7 +311,7 @@ def test_gen_create_table_rejects_non_create_sql_in_text_output(
def test_gen_create_table_rejects_non_create_sql_in_json_output(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""JSON 模式拒绝非建表 SQL。"""
completed = run_cli_command(
@@ -359,7 +360,7 @@ def test_gen_create_table_rejects_conflicting_sql_inputs_in_text_output(
def test_gen_create_table_rejects_conflicting_sql_inputs_in_json_output(
run_cli_command: Callable[..., subprocess.CompletedProcess[str]],
- parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict],
+ parse_json_stdout: Callable[[subprocess.CompletedProcess[str]], dict[str, Any]],
) -> None:
"""JSON 模式拒绝冲突的 SQL 输入。"""
completed = run_cli_command(
diff --git a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_sdk_commands.py b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_sdk_commands.py
index 9f42e78b5..73a0df550 100644
--- a/ruoyi-fastapi-backend/tests/cli/root/test_plugin_sdk_commands.py
+++ b/ruoyi-fastapi-backend/tests/cli/root/test_plugin_sdk_commands.py
@@ -3,6 +3,7 @@
import subprocess
import sys
from pathlib import Path
+from typing import Any
import pytest
import typer
@@ -38,7 +39,7 @@ def project(untracked_bundle_project: Path) -> Path:
return untracked_bundle_project
-def invoke_sdk(operation: str, project: Path, *options: str) -> tuple[int, dict]:
+def invoke_sdk(operation: str, project: Path, *options: str) -> tuple[int, dict[str, Any]]:
"""
使用真实离线 SDK 服务执行命令并解析结构化结果。
diff --git a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold_v2.py b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold_v2.py
index 613489be1..4fe7108c5 100644
--- a/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold_v2.py
+++ b/ruoyi-fastapi-backend/tests/cli/runtime/plugin/test_runtime_scaffold_v2.py
@@ -8,6 +8,7 @@
from collections.abc import Sequence
from pathlib import Path
from types import SimpleNamespace
+from typing import Any
import pytest
@@ -25,7 +26,7 @@
TEMPLATES = ('python-asgi', 'python-bundle', 'rust-asgi', 'rust-bundle')
-def generate(tmp_path: Path, template: str, *, dry_run: bool = False, test: bool = True) -> tuple[dict, Path]:
+def generate(tmp_path: Path, template: str, *, dry_run: bool = False, test: bool = True) -> tuple[dict[str, Any], Path]:
"""
在临时宿主目录中生成指定 v2 模板。
@@ -301,7 +302,7 @@ def test_v2_python_templates_describe_explicit_release_files(tmp_path: Path, tem
],
)
def test_v2_templates_reject_incompatible_legacy_options(
- tmp_path: Path, template: str, options: dict, error: str
+ tmp_path: Path, template: str, options: dict[str, Any], error: str
) -> None:
"""验证 v2 模板拒绝不兼容的旧版选项。"""
payload = build_runtime(tmp_path / 'backend', frontend_root=FRONTEND_ROOT).create_plugin(
diff --git a/ruoyi-fastapi-backend/tests/common/test_auth_policy.py b/ruoyi-fastapi-backend/tests/common/test_auth_policy.py
index 5821fece9..ceb7c8f79 100644
--- a/ruoyi-fastapi-backend/tests/common/test_auth_policy.py
+++ b/ruoyi-fastapi-backend/tests/common/test_auth_policy.py
@@ -190,7 +190,7 @@ async def database() -> AsyncIterator[object]:
description='允许匿名访问并返回公开状态。',
dependencies=[PreAuthDependency([{'path': '/public'}])],
)
- async def public() -> dict:
+ async def public() -> dict[str, bool]:
return {'public': True}
@app.get(
@@ -199,7 +199,7 @@ async def public() -> dict:
description='认证成功后返回当前用户的标识。',
dependencies=[PreAuthDependency()],
)
- async def protected(current_user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict:
+ async def protected(current_user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict[str, object]:
return {'userId': current_user.user.user_id}
try:
@@ -258,7 +258,7 @@ async def __call__(self, user: Annotated[str | None, Depends(authenticate)]) ->
@router.get(
'/public', summary='访问独立认证示例', description='返回公开状态,用于验证单独注册的依赖所采用的认证策略。'
)
- async def public() -> dict:
+ async def public() -> dict[str, bool]:
return {'public': True}
app.include_router(router, prefix='/plain')
@@ -324,7 +324,7 @@ async def replacement(value: Annotated[str, Depends(resource, scope='function')]
description='返回依赖提供的值,用于检查覆盖依赖后的生命周期。',
dependencies=[PreAuthDependency([{'path': '/scope'}] if public else [])],
)
- async def endpoint(value: Annotated[str, Depends(original, scope='function')]) -> dict:
+ async def endpoint(value: Annotated[str, Depends(original, scope='function')]) -> dict[str, object]:
events.append('endpoint')
return {'value': value}
diff --git a/ruoyi-fastapi-backend/tests/common/test_data_scope.py b/ruoyi-fastapi-backend/tests/common/test_data_scope.py
index b09a5d826..0a2f47732 100644
--- a/ruoyi-fastapi-backend/tests/common/test_data_scope.py
+++ b/ruoyi-fastapi-backend/tests/common/test_data_scope.py
@@ -31,7 +31,7 @@
],
)
def test_data_scope_filters_real_query(
- monkeypatch: pytest.MonkeyPatch, roles: list[tuple], admin: bool, expected: list[int]
+ monkeypatch: pytest.MonkeyPatch, roles: list[tuple[str | None, str, str]], admin: bool, expected: list[int]
) -> None:
"""数据权限范围过滤实际查询。"""
metadata = MetaData()
@@ -93,17 +93,19 @@ class Record:
],
)
def test_incomplete_data_scope_grants_no_rows(
- monkeypatch: pytest.MonkeyPatch, user: dict | None, user_alias: str | None, dept_alias: str | None
+ monkeypatch: pytest.MonkeyPatch, user: dict[str, object] | None, user_alias: str | None, dept_alias: str | None
) -> None:
"""用户、角色、本人标识或所需列缺失时,限制条件应拒绝全部记录。"""
# 绕过认证依赖,验证数据权限对异常上下文的防御行为。
profile = None
if user is not None:
+ roles = user['role']
+ assert isinstance(roles, list)
profile = SimpleNamespace(
admin=False,
user_id=user.get('userId'),
dept_id=user.get('deptId'),
- role=[RoleModel.model_validate(role) if role else None for role in user['role']],
+ role=[RoleModel.model_validate(role) if role else None for role in roles],
)
current = SimpleNamespace(user=profile)
monkeypatch.setattr(RequestContext, 'get_current_user', lambda: current)
diff --git a/ruoyi-fastapi-backend/tests/common/test_pre_auth.py b/ruoyi-fastapi-backend/tests/common/test_pre_auth.py
index 85631dfbc..b842ad00b 100644
--- a/ruoyi-fastapi-backend/tests/common/test_pre_auth.py
+++ b/ruoyi-fastapi-backend/tests/common/test_pre_auth.py
@@ -106,7 +106,7 @@ async def authenticate(request: Request, token: str, db: object, *, refresh_sess
async def both(
user: Annotated[CurrentUserModel, CurrentUserDependency()],
same_user: Annotated[CurrentUserModel, CurrentUserDependency()],
- ) -> dict:
+ ) -> dict[str, object]:
await asyncio.sleep(0)
return {
'userId': user.user.user_id,
@@ -116,7 +116,7 @@ async def both(
}
@app.get('/current', summary='读取当前用户标识', description='通过当前用户依赖返回已登录用户的标识。')
- async def current(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict:
+ async def current(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict[str, object]:
return {'userId': user.user.user_id}
@app.get(
@@ -128,7 +128,7 @@ async def current(user: Annotated[CurrentUserModel, CurrentUserDependency()]) ->
async def direct(
user: Annotated[CurrentUserModel, CurrentUserDependency()],
direct_user: Annotated[CurrentUserModel, Depends(LoginService.get_current_user)],
- ) -> dict:
+ ) -> dict[str, object]:
return {'userId': user.user.user_id, 'sameUser': user is direct_user}
@app.get(
@@ -137,7 +137,7 @@ async def direct(
description='从当前请求上下文返回已通过预认证的用户标识。',
dependencies=[PreAuthDependency()],
)
- async def pre() -> dict:
+ async def pre() -> dict[str, object]:
return {'userId': RequestContext.get_current_user().user.user_id}
excluded = PreAuthDependency([{'path': '/public/{name}', 'methods': ['GET'], 'ignore_paths': ['/public/private']}])
@@ -149,7 +149,7 @@ async def pre() -> dict:
methods=['GET', 'POST'],
dependencies=[excluded],
)
- async def public(name: str) -> dict:
+ async def public(name: str) -> dict[str, object]:
return {'name': name}
@app.get(
@@ -158,7 +158,7 @@ async def public(name: str) -> dict:
description='即使路径命中预认证排除项,仍从显式依赖读取当前用户。',
dependencies=[PreAuthDependency([{'path': '/excluded-current'}])],
)
- async def excluded_current(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict:
+ async def excluded_current(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict[str, object]:
return {'userId': user.user.user_id}
try:
@@ -360,7 +360,7 @@ async def override() -> CurrentUserModel:
async def overridden(
current_user: Annotated[CurrentUserModel, CurrentUserDependency()],
direct_user: Annotated[CurrentUserModel, Depends(LoginService.get_current_user)],
- ) -> dict:
+ ) -> dict[str, object]:
"""
返回含 ``userId``, ``contextUserId``, ``sameUser`` 的测试数据。
@@ -457,7 +457,7 @@ async def test_use_cache_false_reauthenticates_after_pre_auth(auth_app: SimpleNa
async def fresh(
first: Annotated[CurrentUserModel, CurrentUserDependency()],
current: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
- ) -> dict:
+ ) -> dict[str, object]:
"""
返回含 ``sameUser``, ``userId``, ``currentContext`` 的测试数据。
@@ -489,7 +489,7 @@ async def test_use_cache_false_does_not_fall_back_to_previous_success(auth_app:
)
async def fresh_denied(
current: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
- ) -> dict:
+ ) -> dict[str, object]:
"""
模拟此操作抛出 AssertionError 的情形。
@@ -548,7 +548,7 @@ async def revoked_permissions(
another: Annotated[CurrentUserModel, PreAuthDependency()],
observed: Annotated[None, Depends(observe_context)],
permitted: Annotated[bool, UserInterfaceAuthDependency(f'user:{USER_IDS["bob"]}:read')],
- ) -> dict:
+ ) -> dict[str, object]:
"""
模拟此操作抛出 AssertionError 的情形。
@@ -610,7 +610,7 @@ async def identity(user: Annotated[CurrentUserModel, Depends(LoginService.get_cu
description='从嵌套的当前用户依赖返回用户标识。',
dependencies=[PreAuthDependency([{'path': '/nested'}])],
)
- async def nested(user_id: Annotated[int, Depends(identity)]) -> dict:
+ async def nested(user_id: Annotated[int, Depends(identity)]) -> dict[str, object]:
"""
返回含 ``userId`` 的测试数据。
@@ -656,7 +656,7 @@ async def authenticated_identity(user: Annotated[CurrentUserModel, CurrentUserDe
description='从覆盖后的依赖读取用户,验证额外认证要求生效。',
dependencies=[PreAuthDependency([{'path': '/override-nested'}])],
)
- async def nested(user_id: Annotated[int, Depends(identity)]) -> dict:
+ async def nested(user_id: Annotated[int, Depends(identity)]) -> dict[str, object]:
"""
返回含 ``userId`` 的测试数据。
@@ -699,7 +699,7 @@ async def test_excluded_pre_auth_cannot_cancel_another_auth_requirement(
description='返回当前用户标识,用于验证多个依赖中仍生效的认证要求。',
dependencies=dependencies,
)
- async def mixed() -> dict:
+ async def mixed() -> dict[str, object]:
"""
返回含 ``userId`` 的测试数据。
@@ -729,7 +729,7 @@ async def test_multiple_excluded_pre_auth_dependencies_do_not_require_login(auth
PreAuthDependency([{'path': '/all-public', 'methods': ['GET']}]),
],
)
- async def public() -> dict:
+ async def public() -> dict[str, bool]:
"""
返回含 ``public`` 的测试数据。
@@ -759,7 +759,7 @@ async def test_first_required_dependency_keeps_missing_token_response(
description='按注册顺序执行认证依赖,用于验证缺少令牌时的响应。',
dependencies=dependencies,
)
- async def ordered() -> dict:
+ async def ordered() -> dict[str, bool]:
"""
返回含 ``ok`` 的测试数据。
@@ -836,8 +836,8 @@ async def test_interface_role_and_data_permissions_are_still_checked(auth_app: S
)
async def scope(
user: Annotated[CurrentUserModel, CurrentUserDependency()],
- data_scope: Annotated[ColumnElement, DataScopeDependency(SysUser)],
- ) -> dict:
+ data_scope: Annotated[ColumnElement[bool], DataScopeDependency(SysUser)],
+ ) -> dict[str, object]:
"""
返回含 ``userId``, ``scope`` 的测试数据。
@@ -859,7 +859,7 @@ async def scope(
description='尝试访问需要指定角色的资源,用于检查拒绝响应。',
dependencies=[PreAuthDependency(), RoleInterfaceAuthDependency('administrator')],
)
- async def forbidden() -> dict:
+ async def forbidden() -> dict[str, object]:
"""
模拟此操作抛出 AssertionError 的情形。
@@ -920,7 +920,7 @@ async def test_explicit_oauth_dependency_returns_bare_token_and_still_requires_l
description='从显式 OAuth 依赖读取并返回请求携带的令牌。',
dependencies=[PreAuthDependency(exclude_routes)],
)
- async def token_endpoint(token: Annotated[str, Depends(oauth2_scheme)]) -> dict:
+ async def token_endpoint(token: Annotated[str, Depends(oauth2_scheme)]) -> dict[str, object]:
"""
返回含 ``token`` 的测试数据。
@@ -963,7 +963,7 @@ async def translated_language() -> str:
@router.get(
'/public', summary='读取公开语言配置', description='返回语言依赖提供的值,用于检查无关依赖覆盖后的公开访问。'
)
- async def public(locale: Annotated[str, Depends(language)]) -> dict:
+ async def public(locale: Annotated[str, Depends(language)]) -> dict[str, object]:
return {'locale': locale}
auth_app.app.include_router(router, prefix='/translated')
@@ -1001,7 +1001,7 @@ async def require_user(user: Annotated[CurrentUserModel, CurrentUserDependency()
router = APIRouter(dependencies=[PreAuthDependency([{'path': path}])])
@router.get('/profile', summary='访问父路由保护的资料', description='验证子路由挂载后仍执行父路由的认证依赖。')
- async def profile() -> dict:
+ async def profile() -> dict[str, bool]:
return {'protected': True}
if nested:
@@ -1038,7 +1038,7 @@ async def require_user(user: Annotated[CurrentUserModel, CurrentUserDependency()
@router.get(
'/info', summary='查询挂载路由状态', description='返回可用状态,用于比对同一路由在不同挂载位置的认证要求。'
)
- async def info() -> dict:
+ async def info() -> dict[str, bool]:
return {'available': True}
auth_app.app.include_router(router, prefix='/open')
@@ -1074,7 +1074,7 @@ async def authenticated_identity(user: Annotated[CurrentUserModel, CurrentUserDe
router = APIRouter(dependencies=[PreAuthDependency([{'path': '/overridden/public'}])])
@router.get('/public', summary='验证父级依赖覆盖', description='访问子路由以检查父级新增的认证要求。')
- async def public() -> dict:
+ async def public() -> dict[str, bool]:
return {'available': True}
auth_app.app.include_router(router, prefix='/overridden', dependencies=[Depends(identity)])
@@ -1098,7 +1098,7 @@ async def test_business_prefix_is_not_removed_as_a_deployment_prefix(
@router.get('/public', summary='访问带业务前缀的公开资源', description='按带前缀的公开路径检查匿名访问。')
@router.get('/private', summary='访问带业务前缀的受保护资源', description='按带前缀的受保护路径检查登录要求。')
- async def endpoint() -> dict:
+ async def endpoint() -> dict[str, bool]:
return {'available': True}
auth_app.app.include_router(router)
@@ -1127,7 +1127,7 @@ async def test_deployment_prefix_requires_a_path_segment_boundary(
description='访问与部署前缀相近的业务路径,确认按完整路径段匹配。',
dependencies=[PreAuthDependency([{'path': '/api-extra/public'}])],
)
- async def public() -> dict:
+ async def public() -> dict[str, bool]:
"""
返回含 ``available`` 的测试数据。
@@ -1169,7 +1169,7 @@ async def test_permission_dependencies_use_the_same_excluded_application_path(
description='在公开路径上运行业务权限依赖,核对排除规则使用的路径。',
)
@router.get('/private-scope', summary='检查受限路径的数据范围', description='在受保护路径上执行业务权限检查。')
- async def endpoint() -> dict:
+ async def endpoint() -> dict[str, bool]:
return {'available': True}
auth_app.app.include_router(router)
@@ -1206,7 +1206,7 @@ async def test_encoded_path_separators_cannot_expand_public_routes(
description='回显已匹配的路径参数,用于验证编码分隔符的访问边界。',
dependencies=[PreAuthDependency([rule])],
)
- async def endpoint(name: str) -> dict:
+ async def endpoint(name: str) -> dict[str, object]:
"""
返回含 ``name`` 的测试数据。
@@ -1247,7 +1247,7 @@ async def test_permission_check_uses_the_full_decoded_path(
UserInterfaceAuthDependency(f'user:{USER_IDS["bob"]}:read'),
],
)
- async def endpoint(name: str) -> dict:
+ async def endpoint(name: str) -> dict[str, object]:
"""
返回含 ``name`` 的测试数据。
diff --git a/ruoyi-fastapi-backend/tests/common/test_query_time.py b/ruoyi-fastapi-backend/tests/common/test_query_time.py
index a5573ca32..2681af7ef 100644
--- a/ruoyi-fastapi-backend/tests/common/test_query_time.py
+++ b/ruoyi-fastapi-backend/tests/common/test_query_time.py
@@ -1,5 +1,5 @@
from datetime import UTC, datetime
-from typing import Annotated
+from typing import Annotated, Any
from unittest.mock import AsyncMock
import pytest
@@ -36,7 +36,7 @@ def test_http_boundaries_return_validation_errors() -> None:
@app.get(
'/query', summary='校验日期查询参数', description='返回通过校验的日期查询条件,错误参数触发 HTTP 校验响应。'
)
- def date_query(query: Annotated[ConfigPageQueryModel, Query()]) -> dict:
+ def date_query(query: Annotated[ConfigPageQueryModel, Query()]) -> dict[str, Any]:
return query.model_dump()
with TestClient(app, raise_server_exceptions=False) as client:
diff --git a/ruoyi-fastapi-backend/tests/common/test_request_timezone.py b/ruoyi-fastapi-backend/tests/common/test_request_timezone.py
index 4b6a692db..f85be9867 100644
--- a/ruoyi-fastapi-backend/tests/common/test_request_timezone.py
+++ b/ruoyi-fastapi-backend/tests/common/test_request_timezone.py
@@ -1,6 +1,7 @@
import asyncio
from datetime import UTC, datetime
from io import BytesIO
+from typing import Any
import httpx
import pytest
@@ -33,7 +34,7 @@ def timezone_app(monkeypatch: pytest.MonkeyPatch) -> FastAPI:
app = FastAPI()
add_context_cleanup_middleware(app)
- async def capture_query(db: object, query: Select, *args: object) -> list[dict]:
+ async def capture_query(db: object, query: Select[*tuple[Any, ...]], *args: object) -> list[dict[str, object]]:
"""
提取 SQL 语句的绑定参数。
@@ -49,7 +50,7 @@ async def capture_query(db: object, query: Select, *args: object) -> list[dict]:
@app.get(
'/range', summary='查询请求时区的日期边界', description='按本次请求的时区计算日期区间,并返回归一化的边界。'
)
- async def date_range(request: Request, preference: str = 'auto') -> dict:
+ async def date_range(request: Request, preference: str = 'auto') -> dict[str, object]:
RequestContext.set_current_user(
CurrentUserModel(
permissions=[], roles=[], user=UserInfoModel(user_id=1, user_name='reader', time_zone=preference)
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py
index 4024073b5..8baa4a553 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_execution_coordination.py
@@ -4,6 +4,7 @@
from concurrent.futures import ProcessPoolExecutor
from datetime import timedelta
from pathlib import Path
+from typing import Any
from uuid import uuid4
import pytest
@@ -48,7 +49,7 @@ async def test_two_processes_atomically_enforce_logical_job_limit(runtime: Runti
assert sorted(row.status for row in rows) == ['rejected', 'running']
-async def wait_for_process_file(path: Path, executor: TimedProcessPoolExecutor) -> dict:
+async def wait_for_process_file(path: Path, executor: TimedProcessPoolExecutor) -> dict[str, Any]:
"""
等待真实进程进入业务函数。
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py
index 466adf339..23d8b79d2 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_executor.py
@@ -169,7 +169,7 @@ def receive(event: SchedulerEvent) -> None:
scheduler.add_job(pow, args=[2, 3])
original_run_in_executor = loop.run_in_executor
- def use_single_worker(executor: object, function: Callable, *args) -> asyncio.Future:
+ def use_single_worker(executor: object, function: Callable[..., object], *args) -> asyncio.Future[object]:
"""
将执行任务提交给指定的工作线程池。
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_fields.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_fields.py
index 226330212..2a59c89cf 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_fields.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_fields.py
@@ -40,10 +40,10 @@
{'concurrent': '0'},
],
)
-def test_job_fields_reject_ambiguous_or_invalid_configuration(change: dict) -> None:
+def test_job_fields_reject_ambiguous_or_invalid_configuration(change: dict[str, object]) -> None:
"""任务字段拒绝有歧义或无效的配置。"""
with pytest.raises(ValidationError):
- JobModel(**change)
+ JobModel.model_validate(change)
@pytest.mark.asyncio
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py
index 3fed8cda8..cc48b30c0 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_job_sync.py
@@ -127,7 +127,7 @@ async def test_immediate_sync_stops_local_updates_if_lease_is_lost_during_read(
await SchedulerManager._sync_jobs_from_database()
original = runtime.scheduler.get_job('42')
- async def read_jobs(_session: object) -> list:
+ async def read_jobs(_session: object) -> list[object]:
"""
模拟调度工作进程读取任务列表。
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_leader_lease.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_leader_lease.py
index 3430de240..2e45c2f08 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_leader_lease.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_leader_lease.py
@@ -1,5 +1,6 @@
import asyncio
from collections.abc import Coroutine
+from typing import Any
from unittest.mock import AsyncMock, MagicMock, call, patch
import pytest
@@ -82,7 +83,7 @@ async def test_non_leader_scheduler_starts_reacquire_task() -> None:
SchedulerManager._reacquire_task = None
SchedulerManager._is_closing = False
- def create_task(coroutine: Coroutine) -> MagicMock:
+ def create_task(coroutine: Coroutine[Any, Any, None]) -> MagicMock:
"""
创建测试任务并将其交给调用方。
@@ -174,7 +175,7 @@ async def test_scheduler_close_releases_owner_lease_before_forgetting_redis() ->
SchedulerManager._is_closing = False
SchedulerManager._sync_listener_task = None
SchedulerManager._sync_task = None
- reacquire_task = asyncio.create_task(asyncio.Event().wait())
+ reacquire_task = asyncio.create_task(asyncio.sleep(3600))
SchedulerManager._reacquire_task = reacquire_task
SchedulerManager._lock_lost_task = None
@@ -222,7 +223,7 @@ def test_scheduler_lock_lost_callback_revokes_leader_state() -> None:
original_lock_lost_task = SchedulerManager._lock_lost_task
scheduled_task = MagicMock()
- def create_task(coroutine: Coroutine) -> MagicMock:
+ def create_task(coroutine: Coroutine[Any, Any, None]) -> MagicMock:
"""
创建测试任务并将其交给调用方。
diff --git a/ruoyi-fastapi-backend/tests/config/test_scheduler_runtime.py b/ruoyi-fastapi-backend/tests/config/test_scheduler_runtime.py
index f68c16c96..0636eda58 100644
--- a/ruoyi-fastapi-backend/tests/config/test_scheduler_runtime.py
+++ b/ruoyi-fastapi-backend/tests/config/test_scheduler_runtime.py
@@ -1,5 +1,6 @@
import asyncio
from datetime import timedelta
+from typing import Any
from unittest.mock import AsyncMock
import pytest
@@ -32,7 +33,7 @@
{'jobArgs': [1, 2]},
],
)
-async def test_invalid_configuration_is_rejected_before_save(runtime: Runtime, change: dict) -> None:
+async def test_invalid_configuration_is_rejected_before_save(runtime: Runtime, change: dict[str, Any]) -> None:
"""保存前拒绝无效配置。"""
async with runtime.sessions() as db:
with pytest.raises((ServiceException, ValidationError)):
@@ -271,7 +272,7 @@ async def test_overlapping_edits_and_late_notifications_apply_latest_version(
both_committed = asyncio.Event()
sync = SchedulerManager.request_scheduler_sync
- async def delayed_notification(job_ids: set[int], *, immediate: bool) -> dict:
+ async def delayed_notification(job_ids: set[int], *, immediate: bool) -> dict[str, Any]:
"""
在指定版本提交后推迟调度通知。
@@ -285,7 +286,7 @@ async def delayed_notification(job_ids: set[int], *, immediate: bool) -> dict:
await asyncio.wait_for(both_committed.wait(), timeout=5)
return await sync(job_ids, immediate=immediate)
- async def edit(change: dict) -> dict:
+ async def edit(change: dict[str, Any]) -> dict[str, Any]:
"""
在测试会话中修改调度记录。
@@ -293,7 +294,7 @@ async def edit(change: dict) -> dict:
:return: 执行当前操作得到的结果
"""
async with runtime.sessions() as db:
- response = await JobService.edit_job_services(db, EditJobModel(job_id=42, **change))
+ response = await JobService.edit_job_services(db, EditJobModel.model_validate({'job_id': 42, **change}))
assert isinstance(response.result, dict)
return response.result
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_catalog_domains.py b/ruoyi-fastapi-backend/tests/i18n/test_catalog_domains.py
index 48debbdf0..c9b6eff54 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_catalog_domains.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_catalog_domains.py
@@ -3,6 +3,7 @@
from collections.abc import Generator
from pathlib import Path
from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock, create_autospec
import pytest
@@ -115,7 +116,7 @@ def test_plugin_plural_rules_and_domain_isolation(tmp_path: Path, count: int, ex
@pytest.mark.parametrize('options', [{'count': 2}, {'plural_key': 'many'}, {'count': True, 'plural_key': 'many'}])
-def test_plural_contract_requires_explicit_pair(options: dict) -> None:
+def test_plural_contract_requires_explicit_pair(options: dict[str, Any]) -> None:
"""验证调用方必须同时提供数量和复数消息标识。"""
with pytest.raises(ValueError):
t('one', **options)
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_dict_cache_publication.py b/ruoyi-fastapi-backend/tests/i18n/test_dict_cache_publication.py
index af1a9e9a8..d94e05460 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_dict_cache_publication.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_dict_cache_publication.py
@@ -30,15 +30,15 @@
async def test_late_dict_refresh_cannot_overwrite_a_newer_publication(
cache_redis: Redis, # noqa: F811
monkeypatch: pytest.MonkeyPatch,
- latest: list[dict | None],
+ latest: list[dict[str, object] | None],
) -> None:
"""在旧查询读完后发布新值,确认重试使用新的数据库会话。"""
- rows: list[dict | None] = [{'dictLabel': '红', 'dictLabelI18n': {'en-US': 'Red'}}]
+ rows: list[dict[str, object] | None] = [{'dictLabel': '红', 'dictLabelI18n': {'en-US': 'Red'}}]
old_read = asyncio.Event()
resume_refresh = asyncio.Event()
read_sessions: list[AsyncSession] = []
- async def query(db: AsyncSession, name: str) -> list[dict | None]:
+ async def query(db: AsyncSession, name: str) -> list[dict[str, object] | None]:
"""
模拟读取数据库快照并记录查询状态。
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_translations.py b/ruoyi-fastapi-backend/tests/i18n/test_translations.py
index 9b427491b..06f7ac61c 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_translations.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_translations.py
@@ -1,5 +1,6 @@
from collections.abc import Awaitable, Callable
from copy import deepcopy
+from typing import Any
from unittest.mock import AsyncMock
import pytest
@@ -71,7 +72,7 @@ def test_query_models_do_not_expose_translation_objects_as_query_parameters() ->
)
async def test_updates_merge_languages_and_preserve_maps_from_old_clients(
model: type[Base],
- dao: Callable[[AsyncSession, dict], Awaitable[None]],
+ dao: Callable[[AsyncSession, dict[str, Any]], Awaitable[None]],
primary_key: str,
field: str,
attributes: dict[str, str],
diff --git a/ruoyi-fastapi-backend/tests/i18n/test_validation_messages.py b/ruoyi-fastapi-backend/tests/i18n/test_validation_messages.py
index 5edc7ea18..a5f4c0ac1 100644
--- a/ruoyi-fastapi-backend/tests/i18n/test_validation_messages.py
+++ b/ruoyi-fastapi-backend/tests/i18n/test_validation_messages.py
@@ -51,7 +51,7 @@ def catalogs() -> None:
],
)
def test_explicit_type_messages_preserve_only_public_constraints(
- error: dict[str, Any], key: str, params: dict, text: str
+ error: dict[str, Any], key: str, params: dict[str, object], text: str
) -> None:
"""验证错误类型映射仅公开该类型声明的约束参数。"""
token = RequestContext.set_current_locale(LocaleContext('en-US'))
@@ -96,7 +96,7 @@ async def test_real_422_handles_json_and_custom_validation_without_echoing_input
add_locale_middleware(app)
@app.post('/validate', summary='校验请求字段', description='校验请求体中的名称和查询参数中的数量,并返回有效值。')
- async def validate(body: ValidationBody, count: Annotated[int, Query(ge=1)]) -> dict:
+ async def validate(body: ValidationBody, count: Annotated[int, Query(ge=1)]) -> dict[str, object]:
return {'name': body.name, 'count': count}
@app.get(
diff --git a/ruoyi-fastapi-backend/tests/module_admin/controller/test_user_controller.py b/ruoyi-fastapi-backend/tests/module_admin/controller/test_user_controller.py
index 032bd74e2..b14493598 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/controller/test_user_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/controller/test_user_controller.py
@@ -66,10 +66,10 @@ async def test_admin_reset_password_uses_front_end_default_rule() -> None:
{'createBy': 'attacker'},
],
)
-def test_update_user_profile_model_rejects_management_fields(management_field: dict) -> None:
+def test_update_user_profile_model_rejects_management_fields(management_field: dict[str, object]) -> None:
"""用户资料模型拒绝管理字段。"""
with pytest.raises(ValidationError):
- UpdateUserProfileModel(nick_name='普通用户', **management_field)
+ UpdateUserProfileModel.model_validate({'nick_name': '普通用户', **management_field})
@pytest.mark.asyncio
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py
index f615d0927..a01873857 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py
@@ -205,7 +205,7 @@ async def test_use_cache_false_reauthenticates_even_when_both_calls_hit_cache(ca
async def revalidate(
first: Annotated[CurrentUserModel, CurrentUserDependency()],
second: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
- ) -> dict:
+ ) -> dict[str, object]:
"""
返回含 ``sameUser``, ``contextIsFresh`` 的测试数据。
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py
index dffe209c6..dad6d6e08 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py
@@ -13,7 +13,7 @@
from redis.exceptions import ConnectionError as RedisConnectionError
from redis.exceptions import NoPermissionError, RedisError
from redis.exceptions import TimeoutError as RedisTimeoutError
-from sqlalchemy import delete, event, update
+from sqlalchemy import delete, event, null, update
from sqlalchemy.dialects.mysql import TINYINT
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.ext.compiler import compiles
@@ -122,12 +122,14 @@ async def resolution_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Asy
SysPost(post_id=USER_ID, post_name='Developer', post_code='dev', post_sort=1, status='0'),
SysMenu(menu_id=USER_ID, menu_name='Read', perms='demo:read', status='0'),
SysMenu(menu_id=USER_ID + 1, menu_name='Disabled', perms='demo:disabled', status='1'),
+ SysMenu(menu_id=USER_ID + 2, menu_name='Directory', perms=null(), status='0'),
SysUserRole(user_id=ADMIN_ID, role_id=ADMIN_ID),
SysUserRole(user_id=USER_ID, role_id=USER_ID),
SysUserPost(user_id=ADMIN_ID, post_id=USER_ID),
SysUserPost(user_id=USER_ID, post_id=USER_ID),
SysRoleMenu(role_id=USER_ID, menu_id=USER_ID),
SysRoleMenu(role_id=USER_ID, menu_id=USER_ID + 1),
+ SysRoleMenu(role_id=USER_ID, menu_id=USER_ID + 2),
]
)
statements = []
@@ -243,7 +245,7 @@ async def test_use_cache_false_queries_and_renews_again_in_the_same_request(reso
async def revalidate(
first: Annotated[CurrentUserModel, CurrentUserDependency()],
second: Annotated[CurrentUserModel, Depends(LoginService.get_current_user, use_cache=False)],
- ) -> dict:
+ ) -> dict[str, object]:
"""
返回含 ``sameUser``, ``permissions``, ``contextIsFresh`` 的测试数据。
@@ -470,7 +472,7 @@ async def test_redis_failure_rejects_protected_requests_and_recovers_without_rel
description='返回服务健康状态,用于检查缓存服务故障时的公开访问。',
dependencies=[PreAuthDependency([{'path': '/public-health'}])],
)
- async def public_health() -> dict:
+ async def public_health() -> dict[str, object]:
"""
返回含 ``status`` 的测试数据。
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_job_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_job_service.py
index 72bb11421..674872591 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_job_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_job_service.py
@@ -1,4 +1,5 @@
from functools import partial
+from typing import Any
from unittest.mock import AsyncMock
import pytest
@@ -42,7 +43,7 @@ async def committing() -> None:
raise RuntimeError('transaction failed')
await commit()
- async def sync(job_ids: set[int], *, immediate: bool) -> dict:
+ async def sync(job_ids: set[int], *, immediate: bool) -> dict[str, Any]:
"""
验证提交顺序后执行调度同步。
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_service.py
index d37b9fc1a..e0a847895 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_login_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_login_service.py
@@ -145,7 +145,7 @@ async def test_register_uses_front_end_default_password_rule() -> None:
@pytest.mark.parametrize('profile', [None, {}, {'userId': 1}, {'userName': 'reader'}])
-def test_current_user_requires_identity(profile: dict | None) -> None:
+def test_current_user_requires_identity(profile: dict[str, object] | None) -> None:
"""受保护操作应拒绝缺少用户资料的快照。"""
with pytest.raises(ValidationError):
CurrentUserModel.model_validate({'permissions': [], 'roles': [], 'user': profile})
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_user_service.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_user_service.py
index b80e09c7c..b262d6949 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_user_service.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_user_service.py
@@ -20,10 +20,12 @@
@pytest.mark.asyncio
@pytest.mark.parametrize('readonly_fields', [{}, {'role': [{'roleId': 2}]}], ids=['react-form', 'vue-form'])
async def test_edit_user_accepts_form_without_readonly_roles(
- monkeypatch: pytest.MonkeyPatch, readonly_fields: dict
+ monkeypatch: pytest.MonkeyPatch, readonly_fields: dict[str, object]
) -> None:
"""编辑表单可以省略只读角色详情,用户字段与角色/岗位关联仍全部保存。"""
- user = EditUserModel(user_id=2, user_name='tester', sex='1', role_ids=[2], post_ids=[1], **readonly_fields)
+ user = EditUserModel.model_validate(
+ {'user_id': 2, 'user_name': 'tester', 'sex': '1', 'role_ids': [2], 'post_ids': [1], **readonly_fields}
+ )
database = make_query_db()
monkeypatch.setattr(UserService, 'user_detail_services', AsyncMock(return_value=SimpleNamespace(data=user)))
monkeypatch.setattr(UserService, 'check_user_name_unique_services', AsyncMock(return_value=True))
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_gen_service.py b/ruoyi-fastapi-backend/tests/module_generator/test_gen_service.py
index c42cf089b..6a894a078 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_gen_service.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_gen_service.py
@@ -31,7 +31,7 @@ async def test_primary_keys_use_marked_column_or_first_child_column() -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('columns', [None, []])
-async def test_primary_key_requires_columns_or_an_existing_key(columns: list | None) -> None:
+async def test_primary_key_requires_columns_or_an_existing_key(columns: list[GenTableColumnModel] | None) -> None:
"""缺少字段时返回配置错误,已有的主键配置仍然有效。"""
table = GenTableModel(columns=columns)
with pytest.raises(ServiceException) as exc:
@@ -178,7 +178,9 @@ async def test_edit_gen_table_services_preserves_alias_fields_for_both_daos() ->
({'tplCategory': 'sub', 'subTableName': 'detail'}, 'generator.childForeignKeyRequired'),
],
)
-async def test_validate_edit_reports_missing_template_fields(configuration: dict, expected_key: str) -> None:
+async def test_validate_edit_reports_missing_template_fields(
+ configuration: dict[str, object], expected_key: str
+) -> None:
"""树表和主子表缺少必填配置时返回对应的错误消息。"""
with pytest.raises(ServiceException) as error:
await GenTableService.validate_edit(EditGenTableModel.model_validate(configuration))
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_generated_i18n.py b/ruoyi-fastapi-backend/tests/module_generator/test_generated_i18n.py
index 136cd96ec..51a8f9a63 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_generated_i18n.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_generated_i18n.py
@@ -18,12 +18,12 @@
from exceptions.exception import ServiceException, ServiceWarning
from i18n.translator import I18nUtil
from module_generator.entity.vo.gen_vo import GenTableModel, GenTableParamsModel
-from module_generator.service.gen_service import GenTableService
+from module_generator.service.gen_service import GenTableService, RenderInfo
from utils.gen_i18n_util import GenI18nUtil
from utils.template_util import TemplateInitializer, TemplateUtils
-def render_info(table: GenTableModel) -> list[Any]:
+def render_info(table: GenTableModel) -> RenderInfo:
"""
根据表定义生成模板预览内容。
@@ -32,10 +32,10 @@ def render_info(table: GenTableModel) -> list[Any]:
"""
context = TemplateUtils.prepare_context(table)
templates = TemplateUtils.get_template_list(table)
- return [templates, [TemplateUtils.get_file_name(name, table) for name in templates], context, table]
+ return templates, [TemplateUtils.get_file_name(name, table) for name in templates], context, table
-def render_files(table: GenTableModel) -> tuple[list[Any], dict[str, str]]:
+def render_files(table: GenTableModel) -> tuple[RenderInfo, dict[str, str]]:
"""
使用测试上下文渲染代码生成文件。
@@ -48,7 +48,7 @@ def render_files(table: GenTableModel) -> tuple[list[Any], dict[str, str]]:
return info, GenTableService._render_files(env, info)
-def flatten(value: dict, prefix: str = '') -> dict:
+def flatten(value: dict[str, object], prefix: str = '') -> dict[str, str]:
"""
将嵌套翻译资源展开为键值映射。
@@ -62,6 +62,7 @@ def flatten(value: dict, prefix: str = '') -> dict:
if isinstance(entry, dict):
result.update(flatten(entry, full))
else:
+ assert isinstance(entry, str)
result[full] = entry
return result
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py b/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
index 612f4f8cc..2d1b1ba2c 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
@@ -191,7 +191,9 @@ def test_generated_frontend_contains_business_files_and_reuses_project_time_modu
assert '@/api/login' not in page
-def import_generated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, rendered: dict[str, str]) -> tuple:
+def import_generated(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, rendered: dict[str, str]
+) -> tuple[type[DeclarativeBase], *tuple[ModuleType, ...]]:
"""
加载已渲染的 Python 模块以测试生成代码。
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_react_templates.py b/ruoyi-fastapi-backend/tests/module_generator/test_react_templates.py
index 0dda4363c..136e3d68c 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_react_templates.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_react_templates.py
@@ -70,7 +70,7 @@ def test_react_preview_preserves_unicode_and_safe_string_literals(category: str,
environment = TemplateInitializer.init_jinja2()
templates = TemplateUtils.get_template_list(table)
filenames = [TemplateUtils.get_file_name(name, table) for name in templates]
- files = GenTableService._render_files(environment, [templates, filenames, context, table])
+ files = GenTableService._render_files(environment, (templates, filenames, context, table))
namespace = context['i18nNamespace']
resource = files[f'frontend/src/i18n/locales/zh-CN/{namespace}.json']
assert '中文名称「测试」😀' in resource
diff --git a/ruoyi-fastapi-backend/tests/module_identity/services/test_review_completion.py b/ruoyi-fastapi-backend/tests/module_identity/services/test_review_completion.py
index 7f13599f0..eff067ef8 100644
--- a/ruoyi-fastapi-backend/tests/module_identity/services/test_review_completion.py
+++ b/ruoyi-fastapi-backend/tests/module_identity/services/test_review_completion.py
@@ -20,6 +20,7 @@
from module_identity.controller.oauth_session_controller import oauth_grant_controller
from module_identity.dao.sso_session_dao import SsoSessionDao
from module_identity.entity.do.oauth_grant_do import SysOAuthGrant, SysSsoSessionClient
+from module_identity.entity.vo.oauth_client_vo import ClientSecretResponseModel
from module_identity.entity.vo.oauth_session_vo import (
AccessPolicyPageQueryModel,
GrantPageQueryModel,
@@ -34,7 +35,7 @@
from module_identity.service.oauth_session_management_service import OAuthSessionManagementService
from module_identity.service.session_service import LogoutService, SsoSessionService
from module_identity.service.token_protocol_service import IntrospectionService, RevocationService
-from module_identity.service.token_service import TokenService
+from module_identity.service.token_service import TokenResult, TokenService
from tests.module_identity.services.test_authentication_regressions import (
_PEPPER,
_VERIFIER,
@@ -61,7 +62,7 @@ def _basic(client_id: str, secret: str) -> str:
return 'Basic ' + base64.b64encode(f'{quote_plus(client_id)}:{quote_plus(secret)}'.encode()).decode()
-async def _confidential_token(flow: SimpleNamespace) -> tuple:
+async def _confidential_token(flow: SimpleNamespace) -> tuple[TokenResult, ClientSecretResponseModel, str]:
"""
通过机密客户端的真实授权码流程签发离线令牌。
diff --git a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py
index 5ab25af79..8d0cc0f93 100644
--- a/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py
+++ b/ruoyi-fastapi-backend/tests/module_plugin/controller/test_plugin_controller.py
@@ -1,6 +1,7 @@
import json
from collections.abc import Generator
from datetime import UTC, datetime
+from typing import Any
import pytest
from fastapi import Request
@@ -58,7 +59,7 @@ async def receive() -> Message:
)
-def load_response_body(response: Response) -> dict:
+def load_response_body(response: Response) -> dict[str, Any]:
"""
解析测试响应体。
@@ -323,7 +324,7 @@ async def test_enable_system_plugin_returns_runtime_payload_when_not_ok(monkeypa
class FakePluginRuntimeService:
"""测试用插件运行时服务。"""
- async def set_plugin_enabled(self, plugin_id: str, *, enabled: bool, dry_run: bool = False) -> dict:
+ async def set_plugin_enabled(self, plugin_id: str, *, enabled: bool, dry_run: bool = False) -> dict[str, Any]:
"""
返回失败启用结果。
@@ -358,7 +359,7 @@ async def test_disable_system_plugin_delegates_runtime_service(monkeypatch: pyte
class FakePluginRuntimeService:
"""测试用插件运行时服务。"""
- async def set_plugin_enabled(self, plugin_id: str, *, enabled: bool, dry_run: bool = False) -> dict:
+ async def set_plugin_enabled(self, plugin_id: str, *, enabled: bool, dry_run: bool = False) -> dict[str, Any]:
"""
记录插件启停参数。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py
index 9e5682552..6b7f8b769 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/deployment/test_convergence.py
@@ -20,7 +20,7 @@
EXPECTED_WORKERS = 2
-def worker(worker_id: str, plugin_id: str = '__runtime__', **changes: object) -> dict:
+def worker(worker_id: str, plugin_id: str = '__runtime__', **changes: object) -> dict[str, Any]:
"""
创建与数据库只读 status 一致的宿主或插件报告。
@@ -42,7 +42,7 @@ def worker(worker_id: str, plugin_id: str = '__runtime__', **changes: object) ->
}
-def ready(*worker_ids: str) -> list[dict]:
+def ready(*worker_ids: str) -> list[dict[str, Any]]:
"""
生成指定 worker 的宿主与插件配对就绪报告。
@@ -53,13 +53,13 @@ def ready(*worker_ids: str) -> list[dict]:
def payload(
- reports: list[dict] | None = None,
+ reports: list[dict[str, Any]] | None = None,
*,
digest: str | None = DIGEST,
generation: str = GENERATION,
expected: int = 2,
enabled: bool = True,
-) -> dict:
+) -> dict[str, Any]:
"""
使用既有聚合器生成读取时刻的摘要,后续测试单独推进返回时刻。
@@ -143,7 +143,7 @@ def clock(monkeypatch: pytest.MonkeyPatch) -> Clock:
return value
-async def wait(reader: Callable[[str], Awaitable[dict[str, Any]]], **changes: object) -> dict:
+async def wait(reader: Callable[[str], Awaitable[dict[str, Any]]], **changes: object) -> dict[str, Any]:
"""
使用固定身份调用被测等待器,同时允许单项参数边界覆盖。
@@ -218,7 +218,9 @@ async def test_wait_reads_new_snapshots_until_all_workers_converge(clock: Clock)
[*ready(WORKER, OTHER), worker(EXTRA), worker(EXTRA, PLUGIN_ID, generation='f' * 32)],
],
)
-async def test_assertion_rejects_short_capacity_orphans_and_extra_mismatched_live_worker(reports: list[dict]) -> None:
+async def test_assertion_rejects_short_capacity_orphans_and_extra_mismatched_live_worker(
+ reports: list[dict[str, Any]],
+) -> None:
"""验收拒绝容量不足、孤立进程及不匹配的额外进程。"""
result = await wait(AsyncMock(return_value=payload(reports)), timeout_seconds=0)
assert result['reason'] == 'not_converged' and result['ok'] is False
@@ -233,7 +235,9 @@ async def test_assertion_rejects_short_capacity_orphans_and_extra_mismatched_liv
{'expected': 3},
],
)
-async def test_changed_target_generation_or_recorded_capacity_is_never_followed(changes: dict, clock: Clock) -> None:
+async def test_changed_target_generation_or_recorded_capacity_is_never_followed(
+ changes: dict[str, Any], clock: Clock
+) -> None:
"""目标代次或记录容量改变时不追随新值。"""
reader = AsyncMock(side_effect=[payload(**changes), payload(ready(WORKER, OTHER))])
result = await wait(reader)
@@ -245,7 +249,7 @@ async def test_changed_target_generation_or_recorded_capacity_is_never_followed(
@pytest.mark.asyncio
@pytest.mark.parametrize('state', [{'ok': True, 'releases': [], 'workers': []}, payload(digest=None)])
-async def test_missing_release_or_target_stops_immediately(state: dict) -> None:
+async def test_missing_release_or_target_stops_immediately(state: dict[str, Any]) -> None:
"""发布或目标缺失时立即停止。"""
result = await wait(AsyncMock(return_value=state))
assert result['reason'] == 'target_missing' and result['attempts'] == 1
@@ -338,7 +342,7 @@ async def test_polling_stops_on_total_deadline_and_sleep_never_overshoots(clock:
async def test_active_result_returned_after_deadline_is_still_timeout(clock: Clock) -> None:
"""超过截止时间才返回的启用结果仍视为超时。"""
- async def reader(plugin_id: str) -> dict:
+ async def reader(plugin_id: str) -> dict[str, Any]:
"""
推进测试时钟并返回工作进程状态。
@@ -366,7 +370,9 @@ async def test_read_timeout_is_bounded_and_classified_by_budget_source(
) -> None:
"""按预算来源限制并归类读取超时。"""
- def time_out(tasks: set, *, timeout: float) -> tuple[set, set]:
+ def time_out(
+ tasks: set[asyncio.Task[object]], *, timeout: float
+ ) -> tuple[set[asyncio.Task[object]], set[asyncio.Task[object]]]:
"""
推进测试时钟以模拟读取超时。
@@ -391,7 +397,7 @@ async def test_timer_before_monotonic_deadline_cannot_become_unavailable_or_late
"""单调时钟截止前触发计时器不会误报不可用或迟到成功。"""
cleaned = asyncio.Event()
- async def reader(plugin_id: str) -> dict:
+ async def reader(plugin_id: str) -> dict[str, Any]:
"""
推进测试时钟并返回工作进程状态。
@@ -400,7 +406,7 @@ async def reader(plugin_id: str) -> dict:
:raises asyncio.CancelledError: 异步操作被取消时
"""
try:
- return await asyncio.Future[dict]()
+ return await asyncio.Future[dict[str, Any]]()
except asyncio.CancelledError:
if swallow_cancel:
return payload(ready(WORKER, OTHER))
@@ -433,7 +439,7 @@ async def test_cancellation_propagates_and_does_not_continue_polling(
entered = asyncio.Event()
finished = asyncio.Event()
- async def blocked(value: object) -> dict:
+ async def blocked(value: object) -> dict[str, Any]:
"""
将调用保持在等待状态以验证取消行为。
@@ -442,7 +448,7 @@ async def blocked(value: object) -> dict:
"""
entered.set()
try:
- return await asyncio.Future[dict]()
+ return await asyncio.Future[dict[str, Any]]()
finally:
finished.set()
@@ -475,7 +481,7 @@ async def blocked(value: object) -> dict:
{'poll_interval_seconds': float('inf')},
],
)
-async def test_invalid_pins_or_time_limits_do_not_query(changes: dict) -> None:
+async def test_invalid_pins_or_time_limits_do_not_query(changes: dict[str, Any]) -> None:
"""无效的固定目标或时间限制不会触发查询。"""
reader = AsyncMock()
with pytest.raises(ValueError):
@@ -500,7 +506,7 @@ async def test_invalid_pins_or_time_limits_do_not_query(changes: dict) -> None:
{'expectedWorkers': False},
],
)
-async def test_contradictory_or_malformed_summary_never_becomes_success(changes: dict) -> None:
+async def test_contradictory_or_malformed_summary_never_becomes_success(changes: dict[str, Any]) -> None:
"""矛盾或格式错误的摘要无法通过验收。"""
state = payload(ready(WORKER, OTHER))
state['releases'][0].update(changes)
@@ -549,7 +555,7 @@ async def test_missing_raw_worker_fields_cannot_pass_via_summary(field: str) ->
{'pluginId': 'other_demo'},
],
)
-async def test_invalid_worker_state_identity_or_naive_time_is_fail_closed(changes: dict) -> None:
+async def test_invalid_worker_state_identity_or_naive_time_is_fail_closed(changes: dict[str, Any]) -> None:
"""无效进程状态、身份或无时区时刻导致验收失败。"""
state = payload(ready(WORKER, OTHER))
state['workers'][0].update(changes)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/lifecycle/test_migration.py b/ruoyi-fastapi-backend/tests/plugins/core/lifecycle/test_migration.py
index 197a24197..998827c81 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/lifecycle/test_migration.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/lifecycle/test_migration.py
@@ -13,7 +13,7 @@
)
-class FakeManagedMigrationSession(list):
+class FakeManagedMigrationSession(list[object]):
"""
测试用托管 migration 执行 session。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/management/test_menu_installer.py b/ruoyi-fastapi-backend/tests/plugins/core/management/test_menu_installer.py
index 1c6f3ed05..843025fdc 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/management/test_menu_installer.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/management/test_menu_installer.py
@@ -1,4 +1,5 @@
from types import SimpleNamespace
+from typing import Any
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
@@ -166,7 +167,7 @@ async def add_sys_menu(cls, db: object, menu: MenuModel) -> SimpleNamespace:
return sys_menu
@classmethod
- async def update_sys_menu(cls, db: object, menu: dict) -> None:
+ async def update_sys_menu(cls, db: object, menu: dict[str, Any]) -> None:
"""
更新系统菜单。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_artifact_guards.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_artifact_guards.py
index 4e4b2dd94..e0d190c24 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_artifact_guards.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_artifact_guards.py
@@ -5,7 +5,8 @@
import pytest
from plugins.core.discovery.scanner import DiscoveredPlugin
-from plugins.core.management.entity.vo.schemas import PluginModel
+from plugins.core.management.entity.vo.schemas import PluginConfigValueModel, PluginModel
+from plugins.core.types import PluginConfigValue
from plugins.core.validation.dependency_policy import DependencyInstallPolicyConfig
from tests.plugins.core.runtime.fakes import (
FakePluginRuntimeGateway,
@@ -87,7 +88,9 @@ async def get_selected_artifact_plugin(self, plugin_id: str, backend_root: Path)
assert backend_root == tmp_path / 'backend'
return selected
- async def get_plugin_config(self, discovered_plugin: DiscoveredPlugin, *, reveal_secret: bool = False) -> list:
+ async def get_plugin_config(
+ self, discovered_plugin: DiscoveredPlugin, *, reveal_secret: bool = False
+ ) -> list[PluginConfigValueModel]:
"""
检查插件选择和配置读取参数。
@@ -99,7 +102,9 @@ async def get_plugin_config(self, discovered_plugin: DiscoveredPlugin, *, reveal
assert reveal_secret is False
return []
- async def set_plugin_config(self, discovered_plugin: DiscoveredPlugin, values: dict, **kwargs: object) -> list:
+ async def set_plugin_config(
+ self, discovered_plugin: DiscoveredPlugin, values: dict[str, PluginConfigValue], **kwargs: object
+ ) -> list[PluginConfigValueModel]:
"""
校验写入配置的目标插件及字段值。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_catalog.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_catalog.py
index 424626e99..f9df6ecac 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_catalog.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/service/test_catalog.py
@@ -6,7 +6,7 @@
import pytest
import plugins.core.runtime.service.context as runtime_context_module
-from plugins.core.discovery.scanner import PluginDiscoveryResult
+from plugins.core.discovery.scanner import DiscoveredPlugin, PluginDiscoveryResult
from plugins.core.environment import PluginRuntimeEnvironmentService
from plugins.core.management.entity.vo.schemas import PluginModel
from plugins.core.runtime.service import PluginRuntimeService
@@ -243,7 +243,7 @@ def __init__(self, plugins_root: Path) -> None:
scanner_roots.append(plugins_root)
@staticmethod
- def discover() -> list:
+ def discover() -> list[DiscoveredPlugin]:
"""
返回测试插件列表。
@@ -390,7 +390,7 @@ def test_plugin_runtime_lists_plugins_with_database_state(tmp_path: Path) -> Non
def test_plugin_runtime_query_entrypoints_delegate_to_query_use_case(
tmp_path: Path,
entrypoint: str,
- expected_payload: dict,
+ expected_payload: dict[str, object],
) -> None:
"""校验插件查询入口委托给组合式查询 use case。"""
runtime = build_runtime(tmp_path / 'backend')
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_browser_session.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_browser_session.py
index 1e9ba8e83..e6a1991b1 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_browser_session.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_browser_session.py
@@ -201,7 +201,7 @@ async def session() -> AsyncGenerator[object, None]:
app.include_router(plugin_browser_controller)
@app.get('/system/private', summary='检查宿主私有端点', description='检查请求携带的令牌并返回认证状态。')
- async def private(token_value: Annotated[str, Depends(oauth2_scheme)]) -> dict:
+ async def private(token_value: Annotated[str, Depends(oauth2_scheme)]) -> dict[str, object]:
return {'authenticated': bool(token_value)}
app.add_middleware(TransportCryptoMiddleware)
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_events.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_events.py
index e1171bf8e..adc8c1cda 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_events.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_events.py
@@ -5,6 +5,7 @@
import pytest
from starlette import status
from starlette.middleware.gzip import GZipMiddleware
+from starlette.types import Message
from config.env import TransportCryptoConfig
from plugins.examples.python.bundle_demo.events import register_event_routes
@@ -25,12 +26,12 @@ async def test_authenticated_events_are_incremental_and_disconnect_stops_respons
issued = await issue(browser)
cookie = issued.headers['set-cookie'].split(';')[0]
count = 20
- incoming: asyncio.Queue = asyncio.Queue()
+ incoming: asyncio.Queue[Message] = asyncio.Queue()
await incoming.put({'type': 'http.request', 'body': b'', 'more_body': False})
first_event = asyncio.Event()
chunks = []
- async def send(message: dict) -> None:
+ async def send(message: Message) -> None:
"""
保存实际 ASGI 响应片段并通知首条事件已到达。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_transport.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_transport.py
index ab5eebfe8..30a0b88f3 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_transport.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_bundle_transport.py
@@ -4,6 +4,7 @@
import secrets
import time
from types import SimpleNamespace
+from typing import Any
import httpx
import pytest
@@ -85,7 +86,7 @@ def crypto(browser: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> SimpleN
return SimpleNamespace(public_key=public_key, kid=settings['transport_crypto_kid'])
-def _envelope(crypto: SimpleNamespace, method: str, path: str, payload: object) -> tuple[dict, bytes]:
+def _envelope(crypto: SimpleNamespace, method: str, path: str, payload: object) -> tuple[dict[str, Any], bytes]:
"""
按浏览器协议构造信封,每个请求使用独立 AES key、IV 和防重放 nonce。
@@ -114,7 +115,7 @@ def _envelope(crypto: SimpleNamespace, method: str, path: str, payload: object)
}, aes_key
-def _decrypt_response(response: httpx.Response, aes_key: bytes, *, method: str, path: str) -> dict:
+def _decrypt_response(response: httpx.Response, aes_key: bytes, *, method: str, path: str) -> dict[str, Any]:
"""
校验并解密测试响应的传输信封。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_configuration.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_configuration.py
index 90f9c35c0..9cd3223b9 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_configuration.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_configuration.py
@@ -205,7 +205,7 @@ async def session() -> AsyncGenerator[object, None]:
finally:
closed.append(True)
- async def read(*args: object, **kwargs: object) -> list:
+ async def read(*args: object, **kwargs: object) -> list[object]:
"""
控制测试读取操作的完成或失败。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py
index 6cffe590c..07462c256 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py
@@ -94,7 +94,7 @@ async def test_websocket_cookie_origin_and_live_login_revocation(
loaded.gateway.connections.recheck_interval = 0.01
opened = asyncio.Event()
messages = []
- incoming: asyncio.Queue = asyncio.Queue()
+ incoming: asyncio.Queue[Message] = asyncio.Queue()
@loaded.lifespan.app.websocket('/ws/events')
async def events(websocket: WebSocket) -> None:
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connections.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connections.py
index 5643783c5..9f82928de 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connections.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connections.py
@@ -287,7 +287,9 @@ async def authorize(scope: Scope) -> PluginRequestContext:
await manager.shutdown()
-async def _cancel_or_drain_request(task: asyncio.Task, gateway: PluginGatewayASGI, external_cancel: bool) -> None:
+async def _cancel_or_drain_request(
+ task: asyncio.Task[object], gateway: PluginGatewayASGI, external_cancel: bool
+) -> None:
"""
触发外部取消或网关排空,并等待请求任务结束。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py
index 3f50ec4d6..e96a66535 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics.py
@@ -4,6 +4,7 @@
from copy import deepcopy
from pathlib import Path
from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock
import pytest
@@ -237,7 +238,7 @@ async def application(scope: Scope, receive: Receive, send: Send) -> None:
opened[scope['type']].set()
await release.wait()
- async def receive() -> dict:
+ async def receive() -> dict[str, Any]:
"""
为下游 ASGI 应用提供待接收的测试消息。
@@ -400,7 +401,7 @@ def test_wire_snapshot_requires_every_nested_serialized_field(tmp_path: Path) ->
('plugins', 0, 'lastError'),
]
- def object_at(document: dict, path: tuple[str | int, ...]) -> dict:
+ def object_at(document: dict[str, Any], path: tuple[str | int, ...]) -> dict[str, Any]:
"""
沿字段名和数组下标定位待验证的协议对象。
@@ -412,9 +413,10 @@ def object_at(document: dict, path: tuple[str | int, ...]) -> dict:
for key in path:
if isinstance(key, int):
assert isinstance(node, list)
+ node = node[key]
else:
assert isinstance(node, dict)
- node = node[key]
+ node = node[key]
assert isinstance(node, dict)
return node
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_query.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_query.py
index c0c65575c..046aa70ca 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_query.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_diagnostics_query.py
@@ -1,5 +1,6 @@
from datetime import UTC, datetime
from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock
import pytest
@@ -13,7 +14,7 @@
DIGEST = 'd' * 64
-def snapshot(worker_id: str = WORKER, **overrides: object) -> dict:
+def snapshot(worker_id: str = WORKER, **overrides: object) -> dict[str, Any]:
"""
构造真正加载但尚无请求的运行快照。
@@ -45,7 +46,7 @@ def snapshot(worker_id: str = WORKER, **overrides: object) -> dict:
}
-def report(*workers: dict, **overrides: object) -> dict:
+def report(*workers: dict[str, Any], **overrides: object) -> dict[str, Any]:
"""
构造已通过报告器校验的集群观测结果。
@@ -67,7 +68,7 @@ def report(*workers: dict, **overrides: object) -> dict:
}
-def release(*worker_ids: str, expected: int = 1) -> dict:
+def release(*worker_ids: str, expected: int = 1) -> dict[str, Any]:
"""
构造当前发布目标,故意与实际运行摘要不同以检验身份边界。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_startup.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_startup.py
index deceaa877..7b591738b 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_startup.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_startup.py
@@ -15,7 +15,7 @@
BACKEND_ROOT = Path(__file__).resolve().parents[4]
-def patch_startup_get_db(fake_get_db: Any) -> AbstractContextManager:
+def patch_startup_get_db(fake_get_db: Any) -> AbstractContextManager[Any]:
"""
替换启动管理器方法使用的默认数据源会话。
@@ -29,7 +29,7 @@ def patch_startup_get_db(fake_get_db: Any) -> AbstractContextManager:
)
-def patch_startup_global(name: str, value: object) -> AbstractContextManager:
+def patch_startup_global(name: str, value: object) -> AbstractContextManager[Any]:
"""
替换启动管理器方法使用的模块全局引用。
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest_v2.py b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest_v2.py
index c2f002c47..7ea86d654 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest_v2.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/validation/test_manifest_v2.py
@@ -1,5 +1,6 @@
from copy import deepcopy
from pathlib import Path
+from typing import Any
import pytest
import yaml
@@ -12,7 +13,7 @@
from plugins.core.validation.structure import PluginStructureChecker
-def manifest_data(*, native: bool = False, asgi: bool = False, bundle: bool = False) -> dict:
+def manifest_data(*, native: bool = False, asgi: bool = False, bundle: bool = False) -> dict[str, Any]:
"""
按后端类型准备插件清单字段。
diff --git a/ruoyi-fastapi-backend/tests/redis_helpers.py b/ruoyi-fastapi-backend/tests/redis_helpers.py
index eab46eb10..fec5a1c3e 100644
--- a/ruoyi-fastapi-backend/tests/redis_helpers.py
+++ b/ruoyi-fastapi-backend/tests/redis_helpers.py
@@ -44,7 +44,7 @@ class IsolatedRedisServer:
:ivar run_id: 任务ID
"""
- process: subprocess.Popen
+ process: subprocess.Popen[bytes]
connection: dict[str, Any]
run_id: str
@@ -92,7 +92,7 @@ def available_loopback_port() -> int:
return port
-def stop_redis_process(process: subprocess.Popen) -> None:
+def stop_redis_process(process: subprocess.Popen[bytes]) -> None:
"""
回收测试子进程,超时后强制结束并等待退出。
diff --git a/ruoyi-fastapi-backend/tests/scheduler_helpers.py b/ruoyi-fastapi-backend/tests/scheduler_helpers.py
index 2589c68c5..d6d2ff947 100644
--- a/ruoyi-fastapi-backend/tests/scheduler_helpers.py
+++ b/ruoyi-fastapi-backend/tests/scheduler_helpers.py
@@ -7,6 +7,7 @@
from datetime import UTC
from pathlib import Path
from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock
import pytest
@@ -66,7 +67,7 @@ def held_process_job(directory: str) -> int:
return os.getpid()
-def claim_in_process(execution_id: str, job: dict) -> bool:
+def claim_in_process(execution_id: str, job: dict[str, Any]) -> bool:
"""
不同进程同时尝试占用同一任务,保留占用供父进程断言。
@@ -155,7 +156,7 @@ async def save(self, job: JobModel | None = None) -> JobModel:
await db.commit()
return JobAdapter.from_record(row)
- async def execution(self, execution_id: str) -> dict:
+ async def execution(self, execution_id: str) -> dict[str, Any]:
"""
读取当前执行状态。
@@ -167,7 +168,7 @@ async def execution(self, execution_id: str) -> dict:
assert result is not None, execution_id
return JobRuntimeDao.execution_result(result)
- async def wait_execution(self, execution_id: str, expected: set[str]) -> dict:
+ async def wait_execution(self, execution_id: str, expected: set[str]) -> dict[str, Any]:
"""
等待执行进入预期状态,失败时打印最后观察到的状态。
diff --git a/ruoyi-fastapi-backend/tests/scripts/test_check_docstrings.py b/ruoyi-fastapi-backend/tests/scripts/test_check_docstrings.py
index f94c4e237..c02f6b16f 100644
--- a/ruoyi-fastapi-backend/tests/scripts/test_check_docstrings.py
+++ b/ruoyi-fastapi-backend/tests/scripts/test_check_docstrings.py
@@ -2,9 +2,10 @@
import json
import subprocess
import sys
-from collections.abc import Callable, Iterator
+from collections.abc import Iterator
from pathlib import Path
from textwrap import indent
+from typing import Protocol
import pytest
@@ -18,8 +19,21 @@
)
+class SourceChecker(Protocol):
+ """检查指定路径的 Python 源码并返回行号和诊断消息。"""
+
+ def __call__(self, source: str, path: Path = ...) -> list[tuple[int, str]]:
+ """
+ 收集源码中的文档格式问题。
+
+ :param source: 待检查的 Python 源码
+ :param path: 用于解析导入及匹配检查范围的文件路径
+ :return: 含行号与消息的诊断列表
+ """
+
+
@pytest.fixture(scope='module')
-def check() -> Iterator[Callable[..., list[tuple[int, str]]]]:
+def check() -> Iterator[SourceChecker]:
"""
为源码样例提供共享的 Sphinx 检查环境。
@@ -69,14 +83,14 @@ def parse(source: str, path: Path = Path('sample.py')) -> list[tuple[int, str]]:
'请使用``convert``转换。',
],
)
-def test_rejects_non_rest_and_invalid_fields(body: str, check: Callable) -> None:
+def test_rejects_non_rest_and_invalid_fields(body: str, check: SourceChecker) -> None:
"""拒绝非 reST 标记和无效字段。"""
source = 'async def convert(value):\n """\n 转换输入。\n\n' + indent(body, ' ') + '\n """'
assert any('缺少 :param 描述' not in error for _, error in check(source))
@pytest.mark.parametrize('prefix', ['class Example:\n', 'def example():\n', 'async def example():\n'])
-def test_checks_each_docstring_owner(prefix: str, check: Callable) -> None:
+def test_checks_each_docstring_owner(prefix: str, check: SourceChecker) -> None:
"""逐一校验类、同步函数和异步函数的文档。"""
doc = '"""示例。\n\nArgs:\n value: 输入值\n"""'
source = prefix + indent(doc, ' ')
@@ -91,13 +105,13 @@ def test_checks_each_docstring_owner(prefix: str, check: Callable) -> None:
(':param value: 输入值\n未缩进的说明。\n:return: 转换结果', 6),
],
)
-def test_reports_source_line_for_misplaced_markup(body: str, line: int, check: Callable) -> None:
+def test_reports_source_line_for_misplaced_markup(body: str, line: int, check: SourceChecker) -> None:
"""标记放错位置时报告实际源码行号。"""
source = 'def example(value):\n' + indent('"""说明。\n\n' + body + '\n"""', ' ')
assert line in [lineno for lineno, _ in check(source)]
-def test_allows_rest_fields_roles_and_examples(check: Callable) -> None:
+def test_allows_rest_fields_roles_and_examples(check: SourceChecker) -> None:
"""接受合法的 reST 字段、角色和示例。"""
source = '''
def convert(value, /, *items, flag=True, **options):
@@ -138,14 +152,14 @@ def convert(value, /, *items, flag=True, **options):
assert not check(source)
-def test_checks_summary_punctuation_and_constructor_signature(check: Callable) -> None:
+def test_checks_summary_punctuation_and_constructor_signature(check: SourceChecker) -> None:
"""校验摘要标点和构造函数签名。"""
assert check('def example():\n """缺少句号"""') == [(2, '请以句末标点结束文档摘要')]
source = 'class Example:\n """示例。\n\n :param typo: 输入\n """\n def __init__(self, value):\n """保存输入值。"""'
assert check(source) == [(4, '文档参数 typo 不在函数签名中'), (7, '参数 value 缺少 :param 描述')]
-def test_file_header_boundary(check: Callable) -> None:
+def test_file_header_boundary(check: SourceChecker) -> None:
"""验证文件头边界,并保留解释器声明和代码内部注释。"""
assert [line for line, _ in check('\n# 说明\n"""模块文档。"""\n')] == [2, 3]
assert check('#!/usr/bin/env python3\n# coding: utf-8\nimport os # 行尾注释\n# 内部注释') == []
@@ -153,13 +167,13 @@ def test_file_header_boundary(check: Callable) -> None:
assert check('description = """普通字符串。"""') == []
-def test_missing_private_nested_and_async_docs(check: Callable) -> None:
+def test_missing_private_nested_and_async_docs(check: SourceChecker) -> None:
"""检查类、特殊方法、私有函数和嵌套异步函数的覆盖范围。"""
source = 'class _Type:\n def __init__(self):\n async def _inner(): pass\n\ndef _helper(): pass'
assert sorted(line for line, _ in check(source)) == [1, 2, 3, 5]
-def test_overload_uses_implementation_documentation(check: Callable) -> None:
+def test_overload_uses_implementation_documentation(check: SourceChecker) -> None:
"""验证类型重载共用实现文档,并要求实现存在。"""
stub = 'from typing import overload as signature\n@signature\ndef f(x: int) -> int: ...\n'
assert check(stub)
@@ -169,7 +183,7 @@ def test_overload_uses_implementation_documentation(check: Callable) -> None:
)
-def test_requires_parameter_descriptions(check: Callable) -> None:
+def test_requires_parameter_descriptions(check: SourceChecker) -> None:
"""验证各类显式参数必须有描述,类型字段和代码块不能代替参数说明。"""
source = '''
class Factory:
@@ -193,7 +207,7 @@ async def create(self, /, *items, mode, **options):
assert {message for _, message in check(source)} == {'参数 self 缺少 :param 描述', '参数 options 缺少 :param 描述'}
-def test_requires_class_and_instance_attribute_descriptions(check: Callable) -> None:
+def test_requires_class_and_instance_attribute_descriptions(check: SourceChecker) -> None:
"""验证声明、解包赋值和实例属性的覆盖,排除局部变量与其他对象的属性。"""
source = '''
class Result:
@@ -217,7 +231,7 @@ def __init__(self):
assert [message for _, message in check(slots)] == ['属性 count 缺少 :ivar 或 :cvar 描述']
-def test_model_exemption_follows_imports_without_running_model_code(tmp_path: Path, check: Callable) -> None:
+def test_model_exemption_follows_imports_without_running_model_code(tmp_path: Path, check: SourceChecker) -> None:
"""验证单文件检查能沿导入和别名识别模型,同时检查普通类和模型方法。"""
(tmp_path / 'base_types.py').write_text(
'from pydantic import BaseModel as Schema\nfrom sqlalchemy.orm import registry\n'
@@ -248,7 +262,7 @@ class BaseModel:
}
-def test_pydantic_fields_require_descriptions(check: Callable) -> None:
+def test_pydantic_fields_require_descriptions(check: SourceChecker) -> None:
"""校验有效的字段说明,覆盖别名、类型元数据、计算字段及类变量。"""
source = '''
from typing import Annotated, ClassVar as Shared
@@ -288,7 +302,7 @@ def count(self):
}
-def test_sqlalchemy_columns_require_comments(check: Callable) -> None:
+def test_sqlalchemy_columns_require_comments(check: SourceChecker) -> None:
"""检查实际映射列、复用类型和显式表定义,仅对关系属性免除列说明。"""
source = '''
import sqlalchemy as sa
@@ -326,7 +340,7 @@ def stamp(cls):
}
-def test_routes_and_test_functions_have_distinct_requirements(tmp_path: Path, check: Callable) -> None:
+def test_routes_and_test_functions_have_distinct_requirements(tmp_path: Path, check: SourceChecker) -> None:
"""验证装饰器、显式注册及 pytest 例外的边界。"""
source = '''
from fastapi import APIRouter as Router
@@ -351,7 +365,9 @@ def ordinary(key): pass
}
-def test_every_http_registration_requires_chinese_summary_and_description(check: Callable) -> None:
+def test_every_http_registration_requires_chinese_summary_and_description(
+ check: SourceChecker,
+) -> None:
"""验证同一端点的每次注册、隐藏操作和外部回调各自声明中文元数据。"""
source = '''
from fastapi import APIRouter as Router
@@ -381,7 +397,9 @@ def events(socket): pass
]
-def test_programmatic_routes_and_factory_router_share_the_http_rules(check: Callable) -> None:
+def test_programmatic_routes_and_factory_router_share_the_http_rules(
+ check: SourceChecker,
+) -> None:
"""验证直接注册路径操作对象及通过工厂取得的路由器都逐条检查。"""
source = '''
from fastapi import APIRouter
@@ -404,14 +422,14 @@ def handler(): pass
]
-def test_preserves_alembic_and_only_the_original_router_class(check: Callable) -> None:
+def test_preserves_alembic_and_only_the_original_router_class(check: SourceChecker) -> None:
"""验证特例按源文件和类定位,同一文件的其他定义继续受检。"""
source = 'class APIRouterPro:\n def __init__(self): pass\nclass RouterRegister: pass'
assert not check(source, ALEMBIC_ENV)
assert check(source, ROUTER_MODULE) == [(3, 'RouterRegister 缺少 Sphinx/reST docstring')]
-def test_generator_documents_each_observable_outcome(check: Callable) -> None:
+def test_generator_documents_each_observable_outcome(check: SourceChecker) -> None:
"""生成器应分别说明生成值、最终返回值和传给调用方的异常。"""
source = '''
def stream(value):
@@ -441,7 +459,7 @@ def stream(value):
assert not check(documented)
-def test_async_generator_and_reraised_exception(check: Callable) -> None:
+def test_async_generator_and_reraised_exception(check: SourceChecker) -> None:
"""异步生成器记录生成值及重新抛出的异常,嵌套函数单独校验。"""
source = '''
async def stream():
@@ -461,7 +479,7 @@ def helper():
assert not check('def finish():\n """结束会话。"""\n return None')
-def test_test_functions_only_describe_intent(check: Callable) -> None:
+def test_test_functions_only_describe_intent(check: SourceChecker) -> None:
"""测试用例拒绝普通函数可用的参数字段和返回值字段。"""
source = (
'def test_value(x):\n """\n 检查数值。\n\n :param x: 输入值\n :return: 数值\n """\n return x'
@@ -473,7 +491,7 @@ def test_test_functions_only_describe_intent(check: Callable) -> None:
assert not check(fixture, Path('test_value.py'))
-def test_chinese_prose_and_class_field_overlap(check: Callable) -> None:
+def test_chinese_prose_and_class_field_overlap(check: SourceChecker) -> None:
"""中英文可混用,英文段落、字段描述、普通注释及重复属性说明会被识别。"""
source = 'class Item:\n """保存 ID。\n\n :param id: 标识\n :ivar id: Identifier\n """\n id: int'
errors = [message for _, message in check(source)]
diff --git a/ruoyi-fastapi-backend/tests/scripts/test_migrate_job_fields.py b/ruoyi-fastapi-backend/tests/scripts/test_migrate_job_fields.py
index de379730c..fd58499eb 100644
--- a/ruoyi-fastapi-backend/tests/scripts/test_migrate_job_fields.py
+++ b/ruoyi-fastapi-backend/tests/scripts/test_migrate_job_fields.py
@@ -26,7 +26,7 @@
('{"a": 1}', [{'a': 1}]),
],
)
-def test_legacy_args_keep_the_old_execution_meaning(value: str | None, expected: list) -> None:
+def test_legacy_args_keep_the_old_execution_meaning(value: str | None, expected: list[object]) -> None:
"""旧版参数保留原执行语义。"""
assert parse_legacy_args(value) == expected
diff --git a/ruoyi-fastapi-backend/tests/server/test_oidc_runtime.py b/ruoyi-fastapi-backend/tests/server/test_oidc_runtime.py
index 30aba4a3c..c9ea0e3be 100644
--- a/ruoyi-fastapi-backend/tests/server/test_oidc_runtime.py
+++ b/ruoyi-fastapi-backend/tests/server/test_oidc_runtime.py
@@ -2,6 +2,7 @@
from collections.abc import AsyncGenerator, Coroutine
from contextlib import asynccontextmanager
from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock, patch
import pytest
@@ -107,7 +108,7 @@ async def test_background_loops_wait_in_both_leader_and_follower() -> None:
fake_retry_task = object()
created: list[object] = []
- def create_task(coro: Coroutine) -> object:
+ def create_task(coro: Coroutine[Any, Any, None]) -> object:
"""
创建测试任务并将其交给调用方。
@@ -192,7 +193,7 @@ async def test_server_background_task_setup_delegates_oidc_runtime() -> None:
app.state.redis = object()
log_task = object()
- def create_task(coro: Coroutine) -> object:
+ def create_task(coro: Coroutine[Any, Any, None]) -> object:
"""
创建测试任务并将其交给调用方。
diff --git a/ruoyi-fastapi-backend/tests/test_api_docs_auth.py b/ruoyi-fastapi-backend/tests/test_api_docs_auth.py
index cff9dea5d..c4bab6aee 100644
--- a/ruoyi-fastapi-backend/tests/test_api_docs_auth.py
+++ b/ruoyi-fastapi-backend/tests/test_api_docs_auth.py
@@ -10,6 +10,7 @@
import pytest
from fastapi import APIRouter, Depends, FastAPI, Request, status
from fastapi.security import APIKeyHeader, OAuth2PasswordBearer
+from pydantic import TypeAdapter
from common.aspect.db_session import get_db_session_provider
from common.aspect.pre_auth import CurrentUserDependency, PreAuth, PreAuthDependency
@@ -88,7 +89,7 @@ async def authenticate(request: Request, token: str, db: object, *, refresh_sess
description='返回公开状态,用于核对匿名接口的 OpenAPI 安全声明。',
dependencies=[PreAuthDependency([{'path': '/public'}])],
)
- async def public() -> dict:
+ async def public() -> dict[str, bool]:
return {'public': True}
@app.get(
@@ -97,7 +98,7 @@ async def public() -> dict:
description='从预认证上下文读取并返回用户标识。',
dependencies=[PreAuthDependency()],
)
- async def protected() -> dict:
+ async def protected() -> dict[str, object]:
return {'userId': RequestContext.get_current_user().user.user_id}
@app.api_route(
@@ -107,7 +108,7 @@ async def protected() -> dict:
methods=['GET', 'POST'],
dependencies=[PreAuthDependency([{'path': '/method', 'methods': ['GET']}])],
)
- async def method() -> dict:
+ async def method() -> dict[str, bool]:
return {'ok': True}
@app.get(
@@ -116,7 +117,7 @@ async def method() -> dict:
description='回显条目名称,用于核对路径参数对应的认证规则。',
dependencies=[PreAuthDependency([{'path': '/items/{name}'}])],
)
- async def items(name: str) -> dict:
+ async def items(name: str) -> dict[str, object]:
return {'name': name}
@app.get(
@@ -125,7 +126,7 @@ async def items(name: str) -> dict:
description='回显路径参数,用于核对部分名称可匿名访问时的文档说明。',
dependencies=[PreAuthDependency([{'path': '/mixed/{name}', 'ignore_paths': ['/mixed/private']}])],
)
- async def mixed(name: str) -> dict:
+ async def mixed(name: str) -> dict[str, object]:
return {'name': name}
@app.get(
@@ -134,7 +135,7 @@ async def mixed(name: str) -> dict:
description='回显名称,用于验证带例外路径的匿名访问规则。',
dependencies=[PreAuthDependency([{'path': '/partial/free'}])],
)
- async def partial(name: str) -> dict:
+ async def partial(name: str) -> dict[str, object]:
return {'name': name}
try:
@@ -143,7 +144,7 @@ async def partial(name: str) -> dict:
RequestContext.clear_all()
-def _security(app: FastAPI, path: str, method: str = 'get') -> list[dict]:
+def _security(app: FastAPI, path: str, method: str = 'get') -> list[dict[str, list[str]]]:
"""
读取指定 OpenAPI 操作的安全要求。
@@ -152,7 +153,9 @@ def _security(app: FastAPI, path: str, method: str = 'get') -> list[dict]:
:param method: 当前请求的 HTTP 方法
:return: 指定 OpenAPI 操作的安全要求
"""
- return app.openapi()['paths'][path][method].get('security', [])
+ return TypeAdapter(list[dict[str, list[str]]]).validate_python(
+ app.openapi()['paths'][path][method].get('security', [])
+ )
@pytest.mark.asyncio
@@ -263,7 +266,7 @@ async def identity(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -
description='返回当前用户标识,用于验证公开路径上显式声明的认证依赖。',
dependencies=dependencies,
)
- async def current(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict:
+ async def current(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> dict[str, object]:
"""
返回含 ``userId`` 的测试数据。
@@ -280,7 +283,7 @@ async def current(user: Annotated[CurrentUserModel, CurrentUserDependency()]) ->
description='从嵌套依赖获取用户标识,用于核对公开路径的安全声明。',
dependencies=dependencies,
)
- async def nested(user_id: Annotated[int, Depends(identity)]) -> dict:
+ async def nested(user_id: Annotated[int, Depends(identity)]) -> dict[str, object]:
"""
返回含 ``userId`` 的测试数据。
@@ -297,7 +300,7 @@ async def nested(user_id: Annotated[int, Depends(identity)]) -> dict:
description='从 OAuth 依赖读取令牌,用于核对公开路径的认证要求。',
dependencies=dependencies,
)
- async def token(value: Annotated[str, Depends(oauth2_scheme)]) -> dict:
+ async def token(value: Annotated[str, Depends(oauth2_scheme)]) -> dict[str, object]:
"""
返回含 ``token`` 的测试数据。
@@ -312,7 +315,7 @@ async def token(value: Annotated[str, Depends(oauth2_scheme)]) -> dict:
@router.get(
path, summary='访问有认证要求的插件路由', description='返回插件状态,用于验证挂载路由显式声明的认证要求。'
)
- async def plugin() -> dict:
+ async def plugin() -> dict[str, bool]:
return {'ok': True}
dependency = identity if declaration == 'plugin' else LoginService.get_current_user
@@ -343,7 +346,7 @@ async def test_all_pre_auth_dependencies_must_exclude_the_route(docs_app: Simple
description='组合排除规则并返回成功状态,用于验证匿名访问范围。',
dependencies=dependencies,
)
- async def multiple() -> dict:
+ async def multiple() -> dict[str, bool]:
"""
返回含 ``ok`` 的测试数据。
@@ -373,7 +376,7 @@ async def test_disjoint_exclusions_do_not_make_a_parameterized_route_public(docs
PreAuthDependency([{'path': '/disjoint/second'}]),
],
)
- async def disjoint(name: str) -> dict:
+ async def disjoint(name: str) -> dict[str, object]:
"""
返回含 ``name`` 的测试数据。
@@ -400,7 +403,7 @@ def test_fixed_route_honors_wildcard_exclusion_and_ignore_paths(docs_app: Simple
description='在固定路径返回成功状态,用于核对通配规则及例外路径。',
dependencies=[PreAuthDependency([{'path': '/fixed/{name}', 'ignore_paths': ['/fixed/private']}])],
)
- async def fixed() -> dict:
+ async def fixed() -> dict[str, bool]:
"""
返回含 ``ok`` 的测试数据。
@@ -430,7 +433,7 @@ def test_irrelevant_or_reallowed_exceptions_do_not_make_fully_public_routes_cond
)
],
)
- async def reallowed(name: str) -> dict:
+ async def reallowed(name: str) -> dict[str, object]:
"""
返回含 ``name`` 的测试数据。
@@ -458,7 +461,7 @@ async def test_public_login_exclusion_preserves_other_required_security(
description='返回依赖解析的凭证,用于确认登录排除后仍保留其他安全要求。',
dependencies=[PreAuthDependency([rule])],
)
- async def key(value: Annotated[str, Depends(api_key)]) -> dict:
+ async def key(value: Annotated[str, Depends(api_key)]) -> dict[str, object]:
"""
返回含 ``key`` 的测试数据。
@@ -492,7 +495,7 @@ async def test_independent_oauth_scheme_with_the_same_name_remains_required(docs
description='返回独立 OAuth 方案解析的令牌,用于核对安全声明。',
dependencies=[PreAuthDependency([{'path': '/independent'}])],
)
- async def independent_token(token: Annotated[str, Depends(independent)]) -> dict:
+ async def independent_token(token: Annotated[str, Depends(independent)]) -> dict[str, object]:
"""
返回含 ``token`` 的测试数据。
@@ -522,7 +525,7 @@ async def test_nested_router_prefix_and_root_path_match_runtime_rules(
@child.get(
'/public', summary='访问嵌套的公开路由', description='返回成功状态,用于核对嵌套前缀与部署路径的认证规则。'
)
- async def public() -> dict:
+ async def public() -> dict[str, bool]:
return {'ok': True}
parent = APIRouter(prefix='/api')
@@ -559,7 +562,7 @@ def test_schema_adjustment_is_idempotent_and_tracks_late_router_registration(doc
@router.get(
'/public', summary='访问后注册的公开路由', description='在初次生成文档后注册公开接口,用于检查文档刷新。'
)
- async def public() -> dict:
+ async def public() -> dict[str, bool]:
return {'ok': True}
@router.get(
@@ -567,7 +570,7 @@ async def public() -> dict:
summary='访问后注册的受保护路由',
description='在初次生成文档后注册受保护接口,用于检查安全声明刷新。',
)
- async def protected() -> dict:
+ async def protected() -> dict[str, bool]:
return {'ok': True}
docs_app.app.include_router(router)
@@ -597,7 +600,7 @@ async def test_duplicate_route_preserves_native_security(
dependencies=[PreAuthDependency([{'path': path}] if public_first else [])],
include_in_schema=include_first,
)
- async def first() -> dict:
+ async def first() -> dict[str, str]:
"""
返回含 ``route`` 的测试数据。
@@ -611,7 +614,7 @@ async def first() -> dict:
description='声明第二个处理函数,用于验证重复注册时保留的安全要求。',
dependencies=[PreAuthDependency([] if public_first else [{'path': path}])],
)
- async def second() -> dict:
+ async def second() -> dict[str, str]:
"""
返回含 ``route`` 的测试数据。
@@ -648,7 +651,7 @@ async def test_duplicate_path_with_different_convertors_preserves_native_securit
dependencies=[PreAuthDependency([rule] if public_first else [])],
include_in_schema=include_first,
)
- async def integer(value: int) -> dict:
+ async def integer(value: int) -> dict[str, object]:
"""
返回含 ``route``, ``value`` 的测试数据。
@@ -663,7 +666,7 @@ async def integer(value: int) -> dict:
description='返回通过字符串路径转换器解析的值。',
dependencies=[PreAuthDependency([] if public_first else [rule])],
)
- async def string(value: str) -> dict:
+ async def string(value: str) -> dict[str, object]:
"""
返回含 ``route``, ``value`` 的测试数据。
@@ -721,7 +724,7 @@ async def test_duplicate_route_with_other_authentication_preserves_native_securi
description='返回首个处理函数的标记,用于比对同路径上的不同认证方案。',
dependencies=dependencies[first_auth],
)
- async def first() -> dict:
+ async def first() -> dict[str, str]:
"""
返回含 ``route`` 的测试数据。
@@ -735,7 +738,7 @@ async def first() -> dict:
description='返回后注册处理函数的标记,用于比对同路径上的不同认证方案。',
dependencies=dependencies[second_auth],
)
- async def second() -> dict:
+ async def second() -> dict[str, str]:
"""
返回含 ``route`` 的测试数据。
@@ -768,7 +771,7 @@ def test_unrelated_schema_details_and_security_schemes_are_preserved(docs_app: S
tags=['外部接口'],
openapi_extra={'x-external': {'enabled': True}},
)
- async def external(key: Annotated[str, Depends(api_key)]) -> dict:
+ async def external(key: Annotated[str, Depends(api_key)]) -> dict[str, object]:
"""
返回含 ``key`` 的测试数据。
@@ -780,7 +783,7 @@ async def external(key: Annotated[str, Depends(api_key)]) -> dict:
@docs_app.app.get(
'/plain-public', summary='访问无认证的公开路由', description='返回成功状态,用于确认公开接口的安全要求为空。'
)
- async def plain_public() -> dict:
+ async def plain_public() -> dict[str, bool]:
"""
返回含 ``ok`` 的测试数据。
@@ -832,7 +835,7 @@ async def test_parameter_convertors_exclude_impossible_public_values(
description='回显转换后的值,用于排除无法由路径转换器匹配的公开规则。',
dependencies=[PreAuthDependency([{'path': f'/converted/{excluded_value}'}])],
)
- async def converted(value: int | UUID) -> dict:
+ async def converted(value: int | UUID) -> dict[str, object]:
"""
返回含 ``value`` 的测试数据。
@@ -871,7 +874,7 @@ async def test_overlapping_public_values_respect_each_pre_auth_exception(
description='回显名称,用于核对多组公开规则和例外的交集。',
dependencies=[PreAuthDependency(rules), PreAuthDependency([{'path': '/overlap/free'}])],
)
- async def overlap(name: str) -> dict:
+ async def overlap(name: str) -> dict[str, object]:
"""
返回含 ``name`` 的测试数据。
@@ -924,7 +927,7 @@ async def test_changed_exclusion_rules_restore_native_security_and_description(d
description = '原有接口描述必须保留。'
@docs_app.app.get('/mutable/{name}', summary='验证可变的认证规则', dependencies=[pre_auth], description=description)
- async def mutable(name: str) -> dict:
+ async def mutable(name: str) -> dict[str, object]:
"""
返回含 ``name`` 的测试数据。
@@ -961,7 +964,7 @@ def test_compound_security_from_openapi_extra_is_preserved(docs_app: SimpleNames
)
async def security_definitions(
gateway_key: Annotated[str, Depends(gateway)], audit_key: Annotated[str, Depends(audit)]
- ) -> dict:
+ ) -> dict[str, object]:
"""
返回含 ``gateway``, ``audit`` 的测试数据。
@@ -982,7 +985,7 @@ async def security_definitions(
description=description,
openapi_extra={'security': [{**LOGIN_SECURITY, **additional_security}], 'x-gateway': {'required': True}},
)
- async def compound() -> dict:
+ async def compound() -> dict[str, bool]:
"""
返回含 ``ok`` 的测试数据。
@@ -1023,7 +1026,7 @@ async def test_embedded_parameters_and_literal_dots_preserve_full_exclusion(
description='回显路径中的名称,用于核对嵌入参数和字面点号的匹配。',
dependencies=[PreAuthDependency([{'path': path, 'ignore_paths': ignored_paths}])],
)
- async def embedded(name: str) -> dict:
+ async def embedded(name: str) -> dict[str, object]:
"""
返回含 ``name`` 的测试数据。
@@ -1063,7 +1066,7 @@ async def test_modifying_documented_rules_cannot_change_runtime_authentication(d
)
],
)
- async def documented(name: str) -> dict:
+ async def documented(name: str) -> dict[str, object]:
"""
返回含 ``name`` 的测试数据。
@@ -1100,7 +1103,7 @@ async def test_explicit_anonymous_security_for_optional_api_key_is_preserved(doc
dependencies=[PreAuthDependency([{'path': '/optional-key'}])],
openapi_extra={'security': [{}]},
)
- async def optional(key: Annotated[str | None, Depends(optional_key)]) -> dict:
+ async def optional(key: Annotated[str | None, Depends(optional_key)]) -> dict[str, object]:
"""
返回含 ``key`` 的测试数据。
@@ -1131,7 +1134,7 @@ async def test_complex_rule_cannot_override_a_proven_empty_public_intersection(d
PreAuthDependency([{'path': '/complex/c'}]),
],
)
- async def complex_rule(name: str) -> dict:
+ async def complex_rule(name: str) -> dict[str, object]:
"""
返回含 ``name`` 的测试数据。
@@ -1157,7 +1160,7 @@ async def test_unresolved_complex_rules_do_not_add_an_unproven_anonymous_alterna
description='回显路径参数,用于验证复杂匹配规则的认证声明。',
dependencies=[PreAuthDependency([{'path': '/unresolved/(a|b)'}])],
)
- async def unresolved(name: str) -> dict:
+ async def unresolved(name: str) -> dict[str, object]:
"""
返回含 ``name`` 的测试数据。
diff --git a/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py b/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py
index c1ce9b991..384892952 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_log_sanitize_util.py
@@ -320,7 +320,7 @@ def test_plain_log_formatter_separates_consecutive_records() -> None:
def test_get_request_params_returns_structured_payload() -> None:
"""读取请求参数时返回结构化数据。"""
- async def receive() -> dict:
+ async def receive() -> dict[str, object]:
"""
提供下游 ASGI 应用读取的 HTTP 请求体消息。
@@ -354,7 +354,7 @@ async def receive() -> dict:
def test_get_request_params_falls_back_to_raw_body_when_json_invalid() -> None:
"""无效 JSON 请求体回退为原始内容。"""
- async def receive() -> dict:
+ async def receive() -> dict[str, object]:
"""
提供下游 ASGI 应用读取的 HTTP 请求体消息。
@@ -391,7 +391,7 @@ async def receive() -> dict:
def test_get_request_params_decodes_non_utf8_body_without_raising() -> None:
"""非 UTF-8 请求体可以安全解码。"""
- async def receive() -> dict:
+ async def receive() -> dict[str, object]:
"""
提供下游 ASGI 应用读取的 HTTP 请求体消息。
diff --git a/ruoyi-fastapi-backend/ty.toml b/ruoyi-fastapi-backend/ty.toml
index 8198b1807..11c711b38 100644
--- a/ruoyi-fastapi-backend/ty.toml
+++ b/ruoyi-fastapi-backend/ty.toml
@@ -8,6 +8,7 @@ disjoint-cast = "error"
mismatched-enum-name = "error"
mismatched-namedtuple-name = "error"
mismatched-sentinel-name = "error"
+missing-type-argument = "error"
unsound-return = "error"
unsound-yield = "error"
diff --git a/ruoyi-fastapi-backend/utils/common_util.py b/ruoyi-fastapi-backend/utils/common_util.py
index d90981a3c..9d4ee07c8 100644
--- a/ruoyi-fastapi-backend/utils/common_util.py
+++ b/ruoyi-fastapi-backend/utils/common_util.py
@@ -51,8 +51,10 @@ class SqlalchemyUtil:
@classmethod
def base_to_dict(
- cls, obj: Base | dict, transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case'
- ) -> dict:
+ cls,
+ obj: Base | dict[Any, Any],
+ transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case',
+ ) -> dict[Any, Any]:
"""
将sqlalchemy模型对象转换为字典。
@@ -84,13 +86,15 @@ def serialize_result(
@classmethod
@overload
def serialize_result(
- cls, result: dict, transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case'
+ cls, result: dict[Any, Any], transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case'
) -> dict[Any, Any]: ...
@classmethod
@overload
def serialize_result(
- cls, result: Row, transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case'
+ cls,
+ result: Row[*tuple[Any, ...]],
+ transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case',
) -> dict[str, Any] | list[dict[Any, Any]]: ...
@classmethod
@@ -102,13 +106,17 @@ def serialize_result(
@classmethod
@overload
def serialize_result(
- cls, result: Sequence[dict], transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case'
+ cls,
+ result: Sequence[dict[Any, Any]],
+ transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case',
) -> list[dict[Any, Any]]: ...
@classmethod
@overload
def serialize_result(
- cls, result: Sequence[Row], transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case'
+ cls,
+ result: Sequence[Row[*tuple[Any, ...]]],
+ transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case',
) -> list[dict[str, Any] | list[dict[Any, Any]]]: ...
@classmethod
@@ -187,11 +195,11 @@ def transform_result(cls, result: Base) -> dict[str, Any]: ...
@classmethod
@overload
- def transform_result(cls, result: dict) -> dict[Any, Any]: ...
+ def transform_result(cls, result: dict[Any, Any]) -> dict[Any, Any]: ...
@classmethod
@overload
- def transform_result(cls, result: Row) -> dict[str, Any] | list[dict[Any, Any]]: ...
+ def transform_result(cls, result: Row[*tuple[Any, ...]]) -> dict[str, Any] | list[dict[Any, Any]]: ...
@classmethod
@overload
@@ -199,11 +207,13 @@ def transform_result(cls, result: Sequence[Base]) -> list[dict[str, Any]]: ...
@classmethod
@overload
- def transform_result(cls, result: Sequence[dict]) -> list[dict[Any, Any]]: ...
+ def transform_result(cls, result: Sequence[dict[Any, Any]]) -> list[dict[Any, Any]]: ...
@classmethod
@overload
- def transform_result(cls, result: Sequence[Row]) -> list[dict[str, Any] | list[dict[Any, Any]]]: ...
+ def transform_result(
+ cls, result: Sequence[Row[*tuple[Any, ...]]]
+ ) -> list[dict[str, Any] | list[dict[Any, Any]]]: ...
@classmethod
@overload
@@ -245,11 +255,11 @@ def transform_result(cls, result: Base) -> dict[str, Any]: ...
@classmethod
@overload
- def transform_result(cls, result: dict) -> dict[Any, Any]: ...
+ def transform_result(cls, result: dict[Any, Any]) -> dict[Any, Any]: ...
@classmethod
@overload
- def transform_result(cls, result: Row) -> dict[str, Any] | list[dict[Any, Any]]: ...
+ def transform_result(cls, result: Row[*tuple[Any, ...]]) -> dict[str, Any] | list[dict[Any, Any]]: ...
@classmethod
@overload
@@ -257,11 +267,13 @@ def transform_result(cls, result: Sequence[Base]) -> list[dict[str, Any]]: ...
@classmethod
@overload
- def transform_result(cls, result: Sequence[dict]) -> list[dict[Any, Any]]: ...
+ def transform_result(cls, result: Sequence[dict[str, object]]) -> list[dict[Any, Any]]: ...
@classmethod
@overload
- def transform_result(cls, result: Sequence[Row]) -> list[dict[str, Any] | list[dict[Any, Any]]]: ...
+ def transform_result(
+ cls, result: Sequence[Row[*tuple[Any, ...]]]
+ ) -> list[dict[str, Any] | list[dict[Any, Any]]]: ...
@classmethod
@overload
@@ -318,7 +330,7 @@ def bytes2file_response(bytes_info: bytes) -> Generator[bytes]:
yield bytes_info
-def export_list2excel(list_data: list) -> bytes:
+def export_list2excel(list_data: list[dict[str, Any]]) -> bytes:
"""
工具方法:将需要导出的list数据转化为对应excel的二进制数据。
@@ -333,7 +345,9 @@ def export_list2excel(list_data: list) -> bytes:
return binary_data
-def get_excel_template(header_list: list, selector_header_list: list, option_list: list[dict]) -> bytes:
+def get_excel_template(
+ header_list: list[str], selector_header_list: list[str], option_list: list[dict[str, list[str]]]
+) -> bytes:
"""
工具方法:将需要导出的list数据转化为对应excel的二进制数据。
diff --git a/ruoyi-fastapi-backend/utils/cron_util.py b/ruoyi-fastapi-backend/utils/cron_util.py
index 05a2d5ffd..c75ff1b07 100644
--- a/ruoyi-fastapi-backend/utils/cron_util.py
+++ b/ruoyi-fastapi-backend/utils/cron_util.py
@@ -1,6 +1,7 @@
import re
from calendar import monthrange
from datetime import UTC, datetime, tzinfo
+from typing import Any
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.cron.expressions import AllExpression
@@ -88,7 +89,7 @@ class MyCronTrigger(CronTrigger):
WEEKDAYS = ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
NUMERIC_FIELD = re.compile(r'(?:\*|\d+(?:-\d+)?)(?:/\d+)?(?:,(?:\*|\d+(?:-\d+)?)(?:/\d+)?)*')
- def __getstate__(self) -> dict:
+ def __getstate__(self) -> dict[str, Any]:
"""
序列化Cron规则及业务分组快照。
@@ -96,7 +97,7 @@ def __getstate__(self) -> dict:
"""
return {**super().__getstate__(), 'task_job_group': getattr(self, 'task_job_group', 'default')}
- def __setstate__(self, state: dict) -> None:
+ def __setstate__(self, state: dict[str, Any]) -> None:
"""
恢复Cron规则及业务分组快照。
diff --git a/ruoyi-fastapi-backend/utils/excel_util.py b/ruoyi-fastapi-backend/utils/excel_util.py
index 6c15580da..d8e7039ed 100644
--- a/ruoyi-fastapi-backend/utils/excel_util.py
+++ b/ruoyi-fastapi-backend/utils/excel_util.py
@@ -1,5 +1,7 @@
import io
+from collections.abc import Mapping, Sequence
from datetime import datetime
+from typing import Any, overload
import pandas as pd
from openpyxl import Workbook
@@ -18,8 +20,12 @@ class ExcelUtil:
@classmethod
def __mapping_list(
- cls, list_data: list, mapping_dict: dict, timezone_name: str, locale_context: LocaleContext
- ) -> list[dict]:
+ cls,
+ list_data: list[dict[str, Any]],
+ mapping_dict: Mapping[str, str],
+ timezone_name: str,
+ locale_context: LocaleContext,
+ ) -> list[dict[str, object]]:
"""
按导出语言生成表头和单元格文本,并按导出时区转换日期时间。
@@ -30,17 +36,17 @@ def __mapping_list(
:return: 映射后的数据列表
"""
datetime_keys = {key for key in mapping_dict if any(isinstance(item.get(key), datetime) for item in list_data)}
- mapping_dict = {key: cls._display_value(value, locale_context) for key, value in mapping_dict.items()}
+ translated_headers = {key: cls._display_value(value, locale_context) for key, value in mapping_dict.items()}
display_mapping = {
key: (f'{header} ({timezone_name})' if key in datetime_keys else header)
- for key, header in mapping_dict.items()
+ for key, header in translated_headers.items()
}
mapping_data = [
{
- display_mapping.get(key): (
- TimezoneUtil.to_business_time(item.get(key), timezone_name).replace(tzinfo=None)
- if isinstance(item.get(key), datetime)
- else cls._display_value(item.get(key), locale_context)
+ display_mapping[key]: (
+ TimezoneUtil.to_business_time(value, timezone_name).replace(tzinfo=None)
+ if isinstance(value := item.get(key), datetime)
+ else cls._display_value(value, locale_context)
)
for key in display_mapping
}
@@ -52,8 +58,8 @@ def __mapping_list(
@classmethod
def export_list2excel(
cls,
- list_data: list,
- mapping_dict: dict,
+ list_data: list[dict[str, Any]],
+ mapping_dict: Mapping[str, str],
timezone_name: str | None = None,
locale_context: LocaleContext | None = None,
) -> bytes:
@@ -79,9 +85,9 @@ def export_list2excel(
@classmethod
def get_excel_template(
cls,
- header_list: list,
- selector_header_list: list,
- option_list: list[dict],
+ header_list: Sequence[str],
+ selector_header_list: Sequence[str],
+ option_list: list[dict[str, list[str]]],
locale_context: LocaleContext | None = None,
) -> bytes:
"""
@@ -154,6 +160,14 @@ def get_excel_template(
return excel_data
+ @staticmethod
+ @overload
+ def _display_value(value: str, context: LocaleContext) -> str: ...
+
+ @staticmethod
+ @overload
+ def _display_value(value: object, context: LocaleContext) -> object: ...
+
@staticmethod
def _display_value(value: object, context: LocaleContext) -> object:
"""
diff --git a/ruoyi-fastapi-backend/utils/gen_i18n_util.py b/ruoyi-fastapi-backend/utils/gen_i18n_util.py
index 1d9b384dc..a3d688459 100644
--- a/ruoyi-fastapi-backend/utils/gen_i18n_util.py
+++ b/ruoyi-fastapi-backend/utils/gen_i18n_util.py
@@ -2,7 +2,7 @@
import json
import re
from pathlib import Path
-from typing import Never
+from typing import Any, Never
from babel import Locale, UnknownLocaleError
from babel.messages.catalog import Catalog
@@ -221,7 +221,7 @@ def backend_field_key(self, column: GenTableColumnModel, suffix: str = 'label')
return self.backend_text(f'{prefix}.{column.python_field}.{suffix}', source)
@staticmethod
- def nest(values: dict[str, str]) -> dict:
+ def nest(values: dict[str, str]) -> dict[str, Any]:
"""
将稳定点路径转换为独立命名空间内的嵌套字典。
@@ -238,7 +238,7 @@ def nest(values: dict[str, str]) -> dict:
return result
@classmethod
- def merge_json(cls, existing: dict, generated: dict) -> dict:
+ def merge_json(cls, existing: dict[str, Any], generated: dict[str, Any]) -> dict[str, Any]:
"""
只补充缺失键,不覆盖已有人工文案或删除旧键。
diff --git a/ruoyi-fastapi-backend/utils/log_util.py b/ruoyi-fastapi-backend/utils/log_util.py
index 9f9b65c03..6ca2be563 100644
--- a/ruoyi-fastapi-backend/utils/log_util.py
+++ b/ruoyi-fastapi-backend/utils/log_util.py
@@ -522,7 +522,7 @@ def _build_plain_exception_suffix(self, record: 'Record') -> str:
exception_text = self._get_exception_traceback_text(record.get('exception'))
return f'\n{exception_text}' if exception_text else ''
- def _build_json_payload(self, record: 'Record') -> dict:
+ def _build_json_payload(self, record: 'Record') -> dict[str, object]:
"""
构建统一的 JSON 日志结构。
diff --git a/ruoyi-fastapi-backend/utils/openapi_util.py b/ruoyi-fastapi-backend/utils/openapi_util.py
index 5f7400ea7..fef63cfd1 100644
--- a/ruoyi-fastapi-backend/utils/openapi_util.py
+++ b/ruoyi-fastapi-backend/utils/openapi_util.py
@@ -244,7 +244,7 @@ def _method_rules(pre_auth: AuthRule, method: str) -> list[CompiledExcludeRoute]
return [rule for rule in pre_auth.exclude_patterns if not rule['methods'] or method in rule['methods']]
@staticmethod
- def _get_path_shape(route: Any) -> tuple[tuple[str | None, ...], dict[int, Convertor]] | None:
+ def _get_path_shape(route: Any) -> tuple[tuple[str | None, ...], dict[int, Convertor[Any]]] | None:
"""
将普通路径模板拆分为固定段和单段参数。
@@ -274,7 +274,7 @@ def _get_rule_constraints(
pre_auth: AuthRule,
method: str,
segments: tuple[str | None, ...],
- convertors: dict[int, Convertor],
+ convertors: dict[int, Convertor[Any]],
) -> tuple[list[tuple[str | None, ...]], bool]:
"""
将排除规则转换为路径参数的取值约束。
@@ -315,7 +315,7 @@ def _get_rule_constraints(
def _has_public_path(
cls,
segments: tuple[str | None, ...],
- convertors: dict[int, Convertor],
+ convertors: dict[int, Convertor[Any]],
groups: list[tuple[list[tuple[str | None, ...]], bool]],
ignored_paths: set[str],
requirements: list[AuthRule],
@@ -379,7 +379,7 @@ def visit(index: int, values: tuple[str | None, ...]) -> bool:
@staticmethod
def _get_candidate_path(
- segments: tuple[str | None, ...], convertors: dict[int, Convertor], ignored_paths: set[str]
+ segments: tuple[str | None, ...], convertors: dict[int, Convertor[Any]], ignored_paths: set[str]
) -> str:
"""
为未固定的参数选择不落入有限例外列表的值。
diff --git a/ruoyi-fastapi-backend/utils/page_util.py b/ruoyi-fastapi-backend/utils/page_util.py
index d4992159d..f7661a705 100644
--- a/ruoyi-fastapi-backend/utils/page_util.py
+++ b/ruoyi-fastapi-backend/utils/page_util.py
@@ -8,6 +8,7 @@
from config.database import Base
from utils.common_util import CamelCaseUtil
+_Item = TypeVar('_Item')
_Entity = TypeVar('_Entity', bound=Base)
_JoinedEntity = TypeVar('_JoinedEntity', bound=Base)
_EntityPairs = list[list[dict[str, Any] | None]]
@@ -18,7 +19,7 @@ class PageUtil:
"""分页工具类。"""
@classmethod
- def get_page_obj(cls, data_list: list, page_num: int, page_size: int) -> PageModel:
+ def get_page_obj(cls, data_list: list[_Item], page_num: int, page_size: int) -> PageModel[_Item]:
"""
输入数据列表data_list和分页信息,返回分页数据列表结果。
@@ -35,7 +36,7 @@ def get_page_obj(cls, data_list: list, page_num: int, page_size: int) -> PageMod
paginated_data = data_list[start:end]
has_next = math.ceil(len(data_list) / page_size) > page_num
- result = PageModel[Any](
+ result: PageModel[_Item] = PageModel(
rows=paginated_data, page_num=page_num, page_size=page_size, total=len(data_list), has_next=has_next
)
@@ -46,26 +47,65 @@ def get_page_obj(cls, data_list: list, page_num: int, page_size: int) -> PageMod
async def paginate(
cls,
db: AsyncSession,
- query: Select,
+ query: Select[*tuple[Any, ...]],
+ page_num: int,
+ page_size: int,
+ is_page: Literal[True],
+ *,
+ as_mappings: Literal[True],
+ ) -> PageModel[dict[str, Any]]: ...
+
+ @classmethod
+ @overload
+ async def paginate(
+ cls,
+ db: AsyncSession,
+ query: Select[_Entity, _JoinedEntity],
+ page_num: int,
+ page_size: int,
+ is_page: Literal[True],
+ *,
+ as_mappings: Literal[False] = False,
+ ) -> PageModel[list[dict[str, Any] | None]]: ...
+
+ @classmethod
+ @overload
+ async def paginate(
+ cls,
+ db: AsyncSession,
+ query: Select[_Entity],
+ page_num: int,
+ page_size: int,
+ is_page: Literal[True],
+ *,
+ as_mappings: Literal[False] = False,
+ ) -> PageModel[dict[str, Any]]: ...
+
+ @classmethod
+ @overload
+ async def paginate(
+ cls,
+ db: AsyncSession,
+ query: Select[*tuple[Any, ...]],
page_num: int,
page_size: int,
is_page: Literal[True],
*,
as_mappings: bool = False,
- ) -> PageModel: ...
+ ) -> PageModel[Any]: ...
@classmethod
@overload
async def paginate(
cls,
db: AsyncSession,
- query: Select,
+ query: Select[*tuple[Any, ...]],
page_num: int,
page_size: int,
is_page: bool = False,
*,
as_mappings: Literal[True],
- ) -> PageModel | list[dict[str, Any]]: ...
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]: ...
@classmethod
@overload
@@ -76,31 +116,31 @@ async def paginate(
page_num: int,
page_size: int,
is_page: bool = False,
- ) -> PageModel | _EntityPairs: ...
+ ) -> PageModel[list[dict[str, Any] | None]] | _EntityPairs: ...
@classmethod
@overload
async def paginate(
cls, db: AsyncSession, query: Select[_Entity], page_num: int, page_size: int, is_page: bool = False
- ) -> PageModel | list[dict[str, Any]]: ...
+ ) -> PageModel[dict[str, Any]] | list[dict[str, Any]]: ...
@classmethod
@overload
async def paginate(
- cls, db: AsyncSession, query: Select, page_num: int, page_size: int, is_page: bool = False
- ) -> PageModel | _Rows: ...
+ cls, db: AsyncSession, query: Select[*tuple[Any, ...]], page_num: int, page_size: int, is_page: bool = False
+ ) -> PageModel[Any] | _Rows: ...
@classmethod
async def paginate(
cls,
db: AsyncSession,
- query: Select,
+ query: Select[*tuple[Any, ...]],
page_num: int,
page_size: int,
is_page: bool = False,
*,
as_mappings: bool = False,
- ) -> PageModel | _Rows:
+ ) -> PageModel[Any] | _Rows:
"""
输入查询语句和分页信息,返回分页数据列表结果。
@@ -133,7 +173,7 @@ async def paginate(
)
-def get_page_obj(data_list: list, page_num: int, page_size: int) -> PageModel:
+def get_page_obj(data_list: list[_Item], page_num: int, page_size: int) -> PageModel[_Item]:
"""
输入数据列表data_list和分页信息,返回分页数据列表结果。
@@ -142,16 +182,4 @@ def get_page_obj(data_list: list, page_num: int, page_size: int) -> PageModel:
:param page_size: 当前页面数据量
:return: 分页数据对象
"""
- # 计算起始索引和结束索引
- start = (page_num - 1) * page_size
- end = page_num * page_size
-
- # 根据计算得到的起始索引和结束索引对数据列表进行切片
- paginated_data = data_list[start:end]
- has_next = math.ceil(len(data_list) / page_size) > page_num
-
- result = PageModel[Any](
- rows=paginated_data, page_num=page_num, page_size=page_size, total=len(data_list), has_next=has_next
- )
-
- return result
+ return PageUtil.get_page_obj(data_list, page_num, page_size)
diff --git a/ruoyi-fastapi-backend/utils/response_util.py b/ruoyi-fastapi-backend/utils/response_util.py
index 127866616..42e7e8d76 100644
--- a/ruoyi-fastapi-backend/utils/response_util.py
+++ b/ruoyi-fastapi-backend/utils/response_util.py
@@ -41,14 +41,14 @@ def success( # noqa: PLR0913 - 保留已有位置参数,扩展语义仅允许
msg: str | None = None,
data: Any | None = None,
rows: Any | None = None,
- dict_content: dict | None = None,
+ dict_content: dict[str, object] | None = None,
model_content: BaseModel | None = None,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
@@ -110,14 +110,14 @@ def failure( # noqa: PLR0913 - 保留已有位置参数,扩展语义仅允许
msg: str | None = None,
data: Any | None = None,
rows: Any | None = None,
- dict_content: dict | None = None,
+ dict_content: dict[str, object] | None = None,
model_content: BaseModel | None = None,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
@@ -179,14 +179,14 @@ def unauthorized( # noqa: PLR0913 - 保留已有位置参数,扩展语义仅
msg: str | None = None,
data: Any | None = None,
rows: Any | None = None,
- dict_content: dict | None = None,
+ dict_content: dict[str, object] | None = None,
model_content: BaseModel | None = None,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
@@ -248,14 +248,14 @@ def forbidden( # noqa: PLR0913 - 保留已有位置参数,扩展语义仅允
msg: str | None = None,
data: Any | None = None,
rows: Any | None = None,
- dict_content: dict | None = None,
+ dict_content: dict[str, object] | None = None,
model_content: BaseModel | None = None,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
@@ -317,14 +317,14 @@ def error( # noqa: PLR0913 - 保留已有位置参数,扩展语义仅允许
msg: str | None = None,
data: Any | None = None,
rows: Any | None = None,
- dict_content: dict | None = None,
+ dict_content: dict[str, object] | None = None,
model_content: BaseModel | None = None,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
@@ -386,14 +386,14 @@ def too_many_requests( # noqa: PLR0913 - 保留已有位置参数,扩展语
msg: str | None = None,
data: Any | None = None,
rows: Any | None = None,
- dict_content: dict | None = None,
+ dict_content: dict[str, object] | None = None,
model_content: BaseModel | None = None,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
*,
msg_key: str | None = None,
- msg_params: dict | None = None,
+ msg_params: dict[str, object] | None = None,
domain: str | None = None,
count: int | None = None,
plural_key: str | None = None,
diff --git a/ruoyi-fastapi-backend/utils/server_util.py b/ruoyi-fastapi-backend/utils/server_util.py
index 2608b740a..5ce248b85 100644
--- a/ruoyi-fastapi-backend/utils/server_util.py
+++ b/ruoyi-fastapi-backend/utils/server_util.py
@@ -3,7 +3,7 @@
import os
import socket
import uuid
-from collections.abc import Callable
+from collections.abc import Awaitable, Callable
from copy import deepcopy
from functools import partial
from typing import Any
@@ -342,7 +342,11 @@ def _get_disabled_html_content(title: str, name: str, favicon_url: str) -> HTMLR
@classmethod
def _register_docs_routes(
- cls, app: FastAPI, swagger_handler: Callable, redirect_handler: Callable, redoc_handler: Callable
+ cls,
+ app: FastAPI,
+ swagger_handler: Callable[[Request], Awaitable[HTMLResponse]],
+ redirect_handler: Callable[[Request], Awaitable[HTMLResponse]],
+ redoc_handler: Callable[[Request], Awaitable[HTMLResponse]],
) -> None:
"""
注册文档路由。
@@ -494,7 +498,7 @@ def start_application_leader_renewal(
lock_expire_seconds: int,
interval_seconds: int,
on_lock_lost: Callable[[], None] | None = None,
- ) -> asyncio.Task:
+ ) -> asyncio.Task[None]:
"""
启动Application leader租约续期任务。
diff --git a/ruoyi-fastapi-backend/utils/template_util.py b/ruoyi-fastapi-backend/utils/template_util.py
index 93596a048..e2395fd9d 100644
--- a/ruoyi-fastapi-backend/utils/template_util.py
+++ b/ruoyi-fastapi-backend/utils/template_util.py
@@ -210,7 +210,7 @@ def prepare_time_columns(cls, gen_table: GenTableModel) -> None:
column.html_type = semantics.control
@classmethod
- def set_extensions_context(cls, context: dict, gen_table: GenTableModel) -> None:
+ def set_extensions_context(cls, context: dict[str, Any], gen_table: GenTableModel) -> None:
"""
设置扩展功能上下文。
@@ -221,7 +221,7 @@ def set_extensions_context(cls, context: dict, gen_table: GenTableModel) -> None
context['genView'] = cls.get_gen_view(params_obj)
@classmethod
- def set_menu_context(cls, context: dict, gen_table: GenTableModel) -> None:
+ def set_menu_context(cls, context: dict[str, Any], gen_table: GenTableModel) -> None:
"""
设置菜单上下文。
@@ -232,7 +232,7 @@ def set_menu_context(cls, context: dict, gen_table: GenTableModel) -> None:
context['parentMenuId'] = cls.get_parent_menu_id(params_obj)
@classmethod
- def set_tree_context(cls, context: dict, gen_table: GenTableModel) -> None:
+ def set_tree_context(cls, context: dict[str, Any], gen_table: GenTableModel) -> None:
"""
设置树形结构上下文。
@@ -246,7 +246,7 @@ def set_tree_context(cls, context: dict, gen_table: GenTableModel) -> None:
context['expandColumn'] = cls.get_expand_column(gen_table)
@classmethod
- def set_sub_context(cls, context: dict, gen_table: GenTableModel) -> None:
+ def set_sub_context(cls, context: dict[str, Any], gen_table: GenTableModel) -> None:
"""
设置子表上下文。
@@ -499,7 +499,7 @@ def get_col_span(cls, form_col_num: int | None) -> str:
return cls.FORM_COL_SPAN_MAP.get(form_col_num, '24')
@classmethod
- def get_parent_menu_id(cls, params_obj: dict) -> int | str:
+ def get_parent_menu_id(cls, params_obj: dict[str, Any]) -> int | str:
"""
获取上级菜单ID。
@@ -512,7 +512,7 @@ def get_parent_menu_id(cls, params_obj: dict) -> int | str:
return cls.DEFAULT_PARENT_MENU_ID
@classmethod
- def get_gen_view(cls, params_obj: dict | None) -> bool:
+ def get_gen_view(cls, params_obj: dict[str, Any] | None) -> bool:
"""
获取是否生成详情页。
@@ -529,7 +529,7 @@ def get_gen_view(cls, params_obj: dict | None) -> bool:
return str(value).lower() in {'1', 'true', 'yes', 'y'}
@classmethod
- def get_tree_code(cls, params_obj: dict) -> str:
+ def get_tree_code(cls, params_obj: dict[str, Any]) -> str:
"""
获取树编码。
@@ -541,7 +541,7 @@ def get_tree_code(cls, params_obj: dict) -> str:
return ''
@classmethod
- def get_tree_parent_code(cls, params_obj: dict) -> str:
+ def get_tree_parent_code(cls, params_obj: dict[str, Any]) -> str:
"""
获取树父编码。
@@ -553,7 +553,7 @@ def get_tree_parent_code(cls, params_obj: dict) -> str:
return ''
@classmethod
- def get_tree_name(cls, params_obj: dict) -> str:
+ def get_tree_name(cls, params_obj: dict[str, Any]) -> str:
"""
获取树名称。
diff --git a/ruoyi-fastapi-test/conftest.py b/ruoyi-fastapi-test/conftest.py
index 895dd0e52..7e1e8a915 100644
--- a/ruoyi-fastapi-test/conftest.py
+++ b/ruoyi-fastapi-test/conftest.py
@@ -21,7 +21,7 @@
@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(
- item: pytest.Item, call: pytest.CallInfo
+ item: pytest.Item, call: pytest.CallInfo[None]
) -> Generator[None, pytest.TestReport, pytest.TestReport]:
"""
在浏览器 fixture 回收前保存调用结果,确保断言失败仍能导出诊断。
diff --git a/ruoyi-fastapi-test/monitor/test_job_management.py b/ruoyi-fastapi-test/monitor/test_job_management.py
index 623cedb71..8ecb1aca6 100644
--- a/ruoyi-fastapi-test/monitor/test_job_management.py
+++ b/ruoyi-fastapi-test/monitor/test_job_management.py
@@ -3,6 +3,7 @@
from collections.abc import Awaitable, Callable
from http import HTTPStatus
from time import monotonic
+from typing import Any
from urllib.parse import parse_qs, urlparse
from uuid import uuid4
@@ -49,7 +50,7 @@ def job_actions(self, job_name: str) -> Locator:
rows = self.job_row(job_name)
return rows.locator('td:last-child').get_by_role('button')
- async def submit(self, action: Callable[[], Awaitable], method: str, path: str) -> dict:
+ async def submit(self, action: Callable[[], Awaitable[object]], method: str, path: str) -> dict[str, Any]:
"""
等待本次操作的响应,不依赖短暂提示或固定延时。
@@ -68,7 +69,7 @@ async def submit(self, action: Callable[[], Awaitable], method: str, path: str)
assert payload['code'] == HTTPStatus.OK, payload
return payload['data']
- async def poll_api(self, path: str, ready: Callable[[dict], bool], **params) -> dict:
+ async def poll_api(self, path: str, ready: Callable[[dict[str, Any]], bool], **params) -> dict[str, Any]:
"""
轮询异步结果,超时时保留最后一次响应以便诊断。
@@ -92,7 +93,7 @@ async def poll_api(self, path: str, ready: Callable[[dict], bool], **params) ->
assert monotonic() < deadline, f'{path} 未达到预期状态: {payload}'
await asyncio.sleep(0.25)
- async def wait_for_sync(self, mutation: dict) -> None:
+ async def wait_for_sync(self, mutation: dict[str, Any]) -> None:
"""
已保存后,还要确认本次配置版本已由调度器应用。
diff --git a/ruoyi-fastapi-test/monitor/test_transport_crypto.py b/ruoyi-fastapi-test/monitor/test_transport_crypto.py
index aee0da9df..8ddd065bd 100644
--- a/ruoyi-fastapi-test/monitor/test_transport_crypto.py
+++ b/ruoyi-fastapi-test/monitor/test_transport_crypto.py
@@ -1,5 +1,6 @@
import re
from http import HTTPStatus
+from typing import Any
from urllib.parse import urlparse
import pytest
@@ -12,7 +13,7 @@
pytestmark = pytest.mark.e2e
-async def assert_monitor_snapshot(page: Page, payload: dict) -> None:
+async def assert_monitor_snapshot(page: Page, payload: dict[str, Any]) -> None:
"""
核对同一响应中的启用状态、计数及环境配置。
diff --git a/ruoyi-fastapi-test/prepare_e2e_compose.py b/ruoyi-fastapi-test/prepare_e2e_compose.py
index 575c15e72..8fae7ee6f 100644
--- a/ruoyi-fastapi-test/prepare_e2e_compose.py
+++ b/ruoyi-fastapi-test/prepare_e2e_compose.py
@@ -7,9 +7,10 @@
import re
import subprocess
from pathlib import Path
+from typing import Any
-def isolate_compose(config: dict, project: str, python_version: str) -> dict:
+def isolate_compose(config: dict[str, Any], project: str, python_version: str) -> dict[str, Any]:
"""
从已解析的测试配置生成独立项目,保留应用和数据库的真实配置。
diff --git a/ruoyi-fastapi-test/system/page.py b/ruoyi-fastapi-test/system/page.py
index f484df707..87785f6c2 100644
--- a/ruoyi-fastapi-test/system/page.py
+++ b/ruoyi-fastapi-test/system/page.py
@@ -2,7 +2,7 @@
import re
from http import HTTPStatus
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from urllib.parse import urlsplit
from playwright.async_api import expect
@@ -226,7 +226,7 @@ def matches(response: Response, path: str, method: str) -> bool:
return response.request.method == method and urlsplit(response.url).path.rstrip('/').endswith(path)
@staticmethod
- async def payload(response: Response) -> dict:
+ async def payload(response: Response) -> dict[str, Any]:
"""
HTTP 与应用状态都必须成功,不让 200 包装的业务错误通过测试。
@@ -238,7 +238,7 @@ async def payload(response: Response) -> dict:
assert payload.get('code') == HTTPStatus.OK, f'{response.url}: {payload}'
return payload
- async def action(self, trigger: Callable[[], Awaitable[object]], path: str, method: str = 'GET') -> dict:
+ async def action(self, trigger: Callable[[], Awaitable[object]], path: str, method: str = 'GET') -> dict[str, Any]:
"""
先监听目标响应,再执行点击,避免固定睡眠和遗漏快速响应。
@@ -260,7 +260,7 @@ async def rendered(self) -> None:
await expect(self.page.locator(f'.app-main {loading}:visible')).to_have_count(0)
await expect(self.page.locator(f'.app-main {table}:visible').first).to_be_visible()
- async def open(self, route: str, list_path: str) -> dict:
+ async def open(self, route: str, list_path: str) -> dict[str, Any]:
"""
打开真实管理页面并核对首个列表响应。
@@ -273,7 +273,7 @@ async def open(self, route: str, list_path: str) -> dict:
await self.rendered()
return payload
- async def search(self, fields: dict[str, str] | None = None) -> dict:
+ async def search(self, fields: dict[str, str] | None = None) -> dict[str, Any]:
"""
按界面查询并返回真实响应。
@@ -287,7 +287,7 @@ async def search(self, fields: dict[str, str] | None = None) -> dict:
await self.rendered()
return payload
- async def reset(self) -> dict:
+ async def reset(self) -> dict[str, Any]:
"""
通过重置按钮恢复查询条件。
@@ -325,7 +325,7 @@ async def edit(self, identity: str, resource: str, record_id: int) -> Locator:
await expect(self.dialog).to_be_visible()
return self.dialog
- async def save(self, resource: str, method: str) -> dict:
+ async def save(self, resource: str, method: str) -> dict[str, Any]:
"""
保存表单,要求写请求、列表刷新和弹窗关闭全部完成。
@@ -341,7 +341,7 @@ async def save(self, resource: str, method: str) -> dict:
await self.rendered()
return payload
- async def delete(self, identity: str, resource: str, record_id: int) -> dict:
+ async def delete(self, identity: str, resource: str, record_id: int) -> dict[str, Any]:
"""
删除本用例创建的目标行,并核对其消失。
@@ -405,7 +405,7 @@ async def toggle_status(self, identity: str, resource: str, record_id: int) -> N
await expect(confirmation).to_have_count(0)
await self.persisted(resource, record_id, {'status': status})
- async def confirm_refresh(self, path: str, method: str = 'DELETE') -> dict:
+ async def confirm_refresh(self, path: str, method: str = 'DELETE') -> dict[str, Any]:
"""
确认危险操作,并等待操作及其列表刷新均成功。
@@ -422,7 +422,7 @@ async def confirm_refresh(self, path: str, method: str = 'DELETE') -> dict:
await self.rendered()
return payload
- async def persisted(self, resource: str, record_id: int, expected: dict) -> dict:
+ async def persisted(self, resource: str, record_id: int, expected: dict[str, Any]) -> dict[str, Any]:
"""
从真实后端重读已保存数据,防止仅验证成功提示或前端本地状态。
@@ -441,7 +441,7 @@ async def persisted(self, resource: str, record_id: int, expected: dict) -> dict
return record
@staticmethod
- def records(payload: dict) -> list[dict]:
+ def records(payload: dict[str, Any]) -> list[dict[str, Any]]:
"""
兼容分页 rows 与树形列表 data 的真实响应格式。
@@ -453,7 +453,7 @@ def records(payload: dict) -> list[dict]:
return rows
@classmethod
- def record(cls, payload: dict, field: str, value: str) -> dict:
+ def record(cls, payload: dict[str, Any], field: str, value: str) -> dict[str, Any]:
"""
查询必须返回且仅返回一个目标记录。
diff --git a/ruoyi-fastapi-test/system/test_file_management.py b/ruoyi-fastapi-test/system/test_file_management.py
index 359a0ce60..096cd1ce2 100644
--- a/ruoyi-fastapi-test/system/test_file_management.py
+++ b/ruoyi-fastapi-test/system/test_file_management.py
@@ -2,6 +2,7 @@
import hashlib
from http import HTTPStatus
from pathlib import Path
+from typing import Any
from uuid import uuid4
import pytest
@@ -89,7 +90,7 @@ async def verify_file_details_and_download(view: SystemPage, name: str, file_id:
assert await asyncio.to_thread(Path(download_path).read_bytes) == contents
-async def upload_fixture(view: SystemPage, access_type: str) -> tuple[dict, str, bytes]:
+async def upload_fixture(view: SystemPage, access_type: str) -> tuple[dict[str, Any], str, bytes]:
"""
文件管理页没有上传控件,使用真实公共上传接口准备唯一文件。
diff --git a/ruoyi-fastapi-test/system/test_log_management.py b/ruoyi-fastapi-test/system/test_log_management.py
index 5eecdfb52..157ecf182 100644
--- a/ruoyi-fastapi-test/system/test_log_management.py
+++ b/ruoyi-fastapi-test/system/test_log_management.py
@@ -1,6 +1,7 @@
import asyncio
import re
from http import HTTPStatus
+from typing import Any
import pytest
from playwright.async_api import expect
@@ -11,7 +12,7 @@
pytestmark = pytest.mark.e2e
-async def wait_for_audit(view: SystemPage, path: str) -> dict:
+async def wait_for_audit(view: SystemPage, path: str) -> dict[str, Any]:
"""
日志经 Redis Stream 异步入库,轮询真实查询直到目标事件可见。
diff --git a/ruoyi-fastapi-test/system/test_menu_management.py b/ruoyi-fastapi-test/system/test_menu_management.py
index fdbc350aa..d7e827b5a 100644
--- a/ruoyi-fastapi-test/system/test_menu_management.py
+++ b/ruoyi-fastapi-test/system/test_menu_management.py
@@ -1,3 +1,4 @@
+from typing import Any
from uuid import uuid4
import pytest
@@ -9,7 +10,7 @@
pytestmark = pytest.mark.e2e
-async def add_menu_button(view: SystemPage, parent_name: str, expected: dict) -> dict:
+async def add_menu_button(view: SystemPage, parent_name: str, expected: dict[str, Any]) -> dict[str, Any]:
"""
在真实父菜单下创建按钮,并校验其原文、译文与权限的保存结果。
diff --git a/ruoyi-fastapi-test/system/test_plugin_management.py b/ruoyi-fastapi-test/system/test_plugin_management.py
index f771d7e9b..2d8fd955a 100644
--- a/ruoyi-fastapi-test/system/test_plugin_management.py
+++ b/ruoyi-fastapi-test/system/test_plugin_management.py
@@ -2,7 +2,7 @@
import re
from http import HTTPStatus
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from urllib.parse import parse_qs, urlsplit
from uuid import uuid4
@@ -23,7 +23,7 @@
PLUGIN_WARNING = 601
-def validate_operation_envelope(payload: dict) -> dict:
+def validate_operation_envelope(payload: dict[str, Any]) -> dict[str, Any]:
"""
601 是明确的业务阻断;异常状态、缺失数据和不一致的成功标志均不能通过。
@@ -39,7 +39,7 @@ def validate_operation_envelope(payload: dict) -> dict:
return data
-async def plugin_payload(response: Response) -> dict:
+async def plugin_payload(response: Response) -> dict[str, Any]:
"""
业务成功和业务阻断都必须是 HTTP 200,并进一步验证具体操作契约。
@@ -50,7 +50,7 @@ async def plugin_payload(response: Response) -> dict:
return validate_operation_envelope(await response.json())
-def validate_capability(capability: dict, operation: str) -> bool:
+def validate_capability(capability: dict[str, Any], operation: str) -> bool:
"""
以源码 AI 插件的运行模式验证阻断来源,不能把任意失败当作生产模式限制。
@@ -79,7 +79,7 @@ def validate_capability(capability: dict, operation: str) -> bool:
return blocked
-def validate_dependency_report(report: dict) -> None:
+def validate_dependency_report(report: dict[str, Any]) -> None:
"""
失败必须由实际缺失或版本不满足的依赖解释,而不是接口异常或空数据。
@@ -103,7 +103,7 @@ def validate_dependency_report(report: dict) -> None:
assert report['message'] == ('插件依赖已满足' if report['ok'] else '插件依赖存在问题')
-def validate_install_plan(payload: dict, capability: dict) -> bool:
+def validate_install_plan(payload: dict[str, Any], capability: dict[str, Any]) -> bool:
"""
AI 无插件间依赖;只有明确的环境能力限制可以阻断其拓扑计划。
@@ -160,7 +160,7 @@ def table_rows(scope: Locator) -> Locator:
return scope.locator('.el-table__body-wrapper:visible .el-table__row, .ant-table-row:visible')
-async def open_plugins(browser_harness: BrowserHarness) -> tuple[SystemPage, dict]:
+async def open_plugins(browser_harness: BrowserHarness) -> tuple[SystemPage, dict[str, Any]]:
"""
使用真实登录和列表,定位项目自带的 AI 插件。
@@ -207,7 +207,7 @@ async def close_dialog(view: SystemPage) -> None:
await view.close_dialog()
-async def assert_unchanged(api: APIRequestContext, before: dict) -> None:
+async def assert_unchanged(api: APIRequestContext, before: dict[str, Any]) -> None:
"""
计划查看不能修改插件的安装版本、启用设置或状态。
@@ -223,7 +223,7 @@ async def assert_unchanged(api: APIRequestContext, before: dict) -> None:
assert payload['data'].get(key) == before.get(key), key
-async def verify_manifest_tabs(view: SystemPage, detail: dict) -> None:
+async def verify_manifest_tabs(view: SystemPage, detail: dict[str, Any]) -> None:
"""
逐项核对清单声明,不能只验证标签页标题存在。
@@ -299,7 +299,7 @@ async def test_plugin_search_detail_and_metrics(browser_harness: BrowserHarness)
await assert_unchanged(view.api, plugin)
-async def request_dependency_preview(view: SystemPage, endpoint: str) -> dict:
+async def request_dependency_preview(view: SystemPage, endpoint: str) -> dict[str, Any]:
"""
只点击生成计划,并强制核对实际请求携带 dryRun=true。
@@ -316,7 +316,7 @@ async def request_dependency_preview(view: SystemPage, endpoint: str) -> dict:
return await plugin_payload(response)
-def validate_blocked_preview(preview: dict, capability: dict) -> None:
+def validate_blocked_preview(preview: dict[str, Any], capability: dict[str, Any]) -> None:
"""
服务模式的预演拒绝也必须有结构化能力依据,不接受普通 601 异常。
@@ -333,7 +333,7 @@ def validate_blocked_preview(preview: dict, capability: dict) -> None:
assert not preview.get('plan') and not preview.get('results')
-async def verify_dependency_preview(view: SystemPage, preview: dict, report: dict) -> None:
+async def verify_dependency_preview(view: SystemPage, preview: dict[str, Any], report: dict[str, Any]) -> None:
"""
开发模式必须完整展示真实预演报告,并且保持实际安装不可执行。
@@ -364,7 +364,7 @@ async def verify_dependency_preview(view: SystemPage, preview: dict, report: dic
)
-async def verify_dependency_report_dialog(view: SystemPage, report: dict) -> None:
+async def verify_dependency_report_dialog(view: SystemPage, report: dict[str, Any]) -> None:
"""
Vue2 的 601 拒绝值是 error,但警告 toast 必须展示真实依赖异常信息。
@@ -463,7 +463,7 @@ async def test_plugin_install_plan(browser_harness: BrowserHarness) -> None:
await assert_unchanged(view.api, plugin)
-async def verify_install_plan_dialog(view: SystemPage, payload: dict) -> None:
+async def verify_install_plan_dialog(view: SystemPage, payload: dict[str, Any]) -> None:
"""
可操作环境展示拓扑细节,但用例始终不点击实际执行入口。
diff --git a/ruoyi-fastapi-test/test_browser_harness.py b/ruoyi-fastapi-test/test_browser_harness.py
index 6bd86153d..49bf84645 100644
--- a/ruoyi-fastapi-test/test_browser_harness.py
+++ b/ruoyi-fastapi-test/test_browser_harness.py
@@ -21,7 +21,9 @@
pytestmark = pytest.mark.harness
-def login_response(status: HTTPStatus, *, retry_after: str | None = None, payload: dict | None = None) -> MagicMock:
+def login_response(
+ status: HTTPStatus, *, retry_after: str | None = None, payload: dict[str, object] | None = None
+) -> MagicMock:
"""
构造登录协议响应,保留 HTTP 状态、响应头和异步 JSON 读取语义。
diff --git a/ruoyi-fastapi-test/test_plugin_response_contract.py b/ruoyi-fastapi-test/test_plugin_response_contract.py
index e9a7c1ab5..10bdf8921 100644
--- a/ruoyi-fastapi-test/test_plugin_response_contract.py
+++ b/ruoyi-fastapi-test/test_plugin_response_contract.py
@@ -2,6 +2,7 @@
from copy import deepcopy
from http import HTTPStatus
+from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -20,7 +21,7 @@
pytestmark = pytest.mark.harness
-def capability(frontend: str = 'built', backend: str = 'service') -> dict:
+def capability(frontend: str = 'built', backend: str = 'service') -> dict[str, Any]:
"""
构造与 CI 中源码 AI 插件一致的能力报告。
@@ -49,7 +50,7 @@ def capability(frontend: str = 'built', backend: str = 'service') -> dict:
}
-def dependency_report(*, installed: bool, satisfied: bool, skipped: bool = False) -> dict:
+def dependency_report(*, installed: bool, satisfied: bool, skipped: bool = False) -> dict[str, Any]:
"""
缺失、版本不满足与 built 模式跳过检查有不同且可验证的语义。
@@ -80,7 +81,7 @@ def dependency_report(*, installed: bool, satisfied: bool, skipped: bool = False
}
-def install_plan(runtime: dict) -> dict:
+def install_plan(runtime: dict[str, Any]) -> dict[str, Any]:
"""
有效拓扑与生产环境阻断分别保留,模拟已观测到的 CI 响应结构。
@@ -116,7 +117,7 @@ def install_plan(runtime: dict) -> dict:
}
-def envelope(data: dict) -> dict:
+def envelope(data: dict[str, Any]) -> dict[str, Any]:
"""
响应封装的成功字段必须与业务结果对应。
diff --git a/ruoyi-fastapi-test/tool/test_code_gen.py b/ruoyi-fastapi-test/tool/test_code_gen.py
index 20d09ab0d..837af9f1b 100644
--- a/ruoyi-fastapi-test/tool/test_code_gen.py
+++ b/ruoyi-fastapi-test/tool/test_code_gen.py
@@ -3,6 +3,7 @@
import re
from http import HTTPStatus
from pathlib import Path
+from typing import Any
from urllib.parse import urlparse
from uuid import uuid4
from zipfile import ZipFile
@@ -39,7 +40,7 @@ def table_row(self) -> Locator:
"""
return self.row(self.table_name)
- async def search_table(self) -> dict:
+ async def search_table(self) -> dict[str, Any]:
"""
等待搜索接口与表格完成,避免初始响应覆盖查询结果。
diff --git a/ruoyi-fastapi-test/ty.toml b/ruoyi-fastapi-test/ty.toml
index 8198b1807..11c711b38 100644
--- a/ruoyi-fastapi-test/ty.toml
+++ b/ruoyi-fastapi-test/ty.toml
@@ -8,6 +8,7 @@ disjoint-cast = "error"
mismatched-enum-name = "error"
mismatched-namedtuple-name = "error"
mismatched-sentinel-name = "error"
+missing-type-argument = "error"
unsound-return = "error"
unsound-yield = "error"
diff --git a/ty.toml b/ty.toml
index 11157d890..c0f46756c 100644
--- a/ty.toml
+++ b/ty.toml
@@ -9,6 +9,7 @@ disjoint-cast = "error"
mismatched-enum-name = "error"
mismatched-namedtuple-name = "error"
mismatched-sentinel-name = "error"
+missing-type-argument = "error"
unsound-return = "error"
unsound-yield = "error"
From ad9a8a2608119aef13d0453bfb66f2cac6469d12 Mon Sep 17 00:00:00 2001
From: insistence <3055204202@qq.com>
Date: Thu, 26 Nov 2026 11:50:49 +0800
Subject: [PATCH 6/9] =?UTF-8?q?refactor:=20=E7=BB=9F=E4=B8=80=E4=BB=A3?=
=?UTF-8?q?=E7=A0=81=E7=94=9F=E6=88=90=E6=A8=A1=E6=9D=BF=E5=92=8C=E6=8F=92?=
=?UTF-8?q?=E4=BB=B6=E8=84=9A=E6=89=8B=E6=9E=B6=E7=9A=84=20Python=20?=
=?UTF-8?q?=E7=B1=BB=E5=9E=8B=E4=B8=8E=E6=96=87=E6=A1=A3=E8=A7=84=E8=8C=83?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../scaffold/assets/test_plugin.py.tmpl | 8 +-
.../cli/runtime/plugin/scaffold/backend.py | 102 ++++-----
.../cli/runtime/plugin/scaffold/payload.py | 10 +-
.../module_generator/service/gen_service.py | 15 +-
.../templates/python/controller.py.jinja2 | 20 +-
.../templates/python/dao.py.jinja2 | 66 +++---
.../templates/python/do.py.jinja2 | 31 ++-
.../templates/python/service.py.jinja2 | 109 ++++++----
.../templates/python/vo.py.jinja2 | 17 +-
.../test_generated_time_contract.py | 196 ++++++++++++++----
.../tests/utils/test_template_util.py | 20 +-
ruoyi-fastapi-backend/utils/common_util.py | 26 +--
ruoyi-fastapi-backend/utils/gen_util.py | 32 +++
ruoyi-fastapi-backend/utils/page_util.py | 6 +-
ruoyi-fastapi-backend/utils/template_util.py | 58 ++++--
15 files changed, 473 insertions(+), 243 deletions(-)
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/test_plugin.py.tmpl b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/test_plugin.py.tmpl
index 93de870f4..b190a3b6c 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/test_plugin.py.tmpl
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/assets/test_plugin.py.tmpl
@@ -5,7 +5,7 @@ from pathlib import Path
import httpx
import pytest
-from fastapi import Request
+from fastapi import FastAPI, Request
from starlette import status
from starlette.responses import Response
@@ -34,7 +34,9 @@ async def test_plugin_contract_and_permission() -> None:
)
loader = PluginEntrypointLoader(plugin)
definition = loader.load(host)
+ assert definition.app_factory is not None
app = definition.app_factory(host)
+ assert isinstance(app, FastAPI)
permissions = set()
@app.middleware("http")
@@ -66,5 +68,7 @@ async def test_plugin_contract_and_permission() -> None:
assert response.status_code == status.HTTP_200_OK
assert response.json()["pluginId"] == "__PLUGIN_ID__"
assert response.json()["engine"] == "__RUNTIME__"
- health = loader.load_callable(plugin.manifest.backend.health.checker)
+ checker = plugin.manifest.backend.health.checker
+ assert checker is not None
+ health = loader.load_callable(checker)
assert await await_plugin_callback(health, host) is True
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/backend.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/backend.py
index 1e72b8c4f..8170ccc05 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/backend.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/backend.py
@@ -108,13 +108,12 @@ def build_controller(plugin_id: str) -> str:
"""
service_class_name = PluginScaffoldNaming.to_class_name(plugin_id)
return f"""from common.router import APIRouterPro
-
from plugins.{plugin_id}.service.{plugin_id}_service import {service_class_name}Service
router = APIRouterPro(prefix='/{plugin_id}', tags=['{plugin_id}'])
-@router.get('/ping')
+@router.get('/ping', summary='插件探活', description='检查插件服务能否正常响应')
async def ping() -> dict[str, str]:
return {service_class_name}Service.ping()
"""
@@ -128,34 +127,35 @@ def build_crud_controller(plugin_id: str) -> str:
:return: 后端 CRUD 控制器模板内容
"""
service_class_name = PluginScaffoldNaming.to_class_name(plugin_id)
- return f"""from common.router import APIRouterPro
+ return f"""from collections.abc import Mapping
+from common.router import APIRouterPro
from plugins.{plugin_id}.service.{plugin_id}_service import {service_class_name}Service
router = APIRouterPro(prefix='/{plugin_id}', tags=['{plugin_id}'])
-@router.get('/ping')
+@router.get('/ping', summary='插件探活', description='检查插件服务能否正常响应')
async def ping() -> dict[str, str]:
return {service_class_name}Service.ping()
-@router.get('/items')
-async def list_items(keyword: str = '') -> dict[str, object]:
+@router.get('/items', summary='查询示例数据', description='按名称关键字查询插件示例数据')
+async def list_items(keyword: str = '') -> Mapping[str, object]:
return {service_class_name}Service.list_items(keyword)
-@router.post('/items')
-async def create_item(payload: dict[str, object]) -> dict[str, object]:
+@router.post('/items', summary='创建示例数据', description='创建并返回插件示例记录')
+async def create_item(payload: dict[str, object]) -> Mapping[str, object]:
return {service_class_name}Service.create_item(payload)
-@router.put('/items/{{item_id}}')
-async def update_item(item_id: int, payload: dict[str, object]) -> dict[str, object]:
+@router.put('/items/{{item_id}}', summary='修改示例数据', description='按编号更新插件示例记录')
+async def update_item(item_id: int, payload: dict[str, object]) -> Mapping[str, object]:
return {service_class_name}Service.update_item(item_id, payload)
-@router.delete('/items/{{item_id}}')
+@router.delete('/items/{{item_id}}', summary='删除示例数据', description='按编号删除插件示例记录')
async def delete_item(item_id: int) -> dict[str, object]:
return {service_class_name}Service.delete_item(item_id)
"""
@@ -170,9 +170,7 @@ def build_service(plugin_id: str) -> str:
"""
service_class_name = PluginScaffoldNaming.to_class_name(plugin_id)
return f"""class {service_class_name}Service:
- \"\"\"
- {plugin_id} 插件服务。
- \"\"\"
+ \"\"\"{plugin_id} 插件服务。\"\"\"
@classmethod
def ping(cls) -> dict[str, str]:
@@ -193,14 +191,45 @@ def build_crud_service(plugin_id: str) -> str:
:return: 后端 CRUD 服务模板内容
"""
service_class_name = PluginScaffoldNaming.to_class_name(plugin_id)
- return f"""class {service_class_name}Service:
+ return f"""from typing import TypedDict
+
+
+class PluginItem(TypedDict):
+ \"\"\"
+ 插件示例记录。
+
+ :ivar itemId: 记录编号
+ :ivar itemName: 名称
+ :ivar status: 状态
+ :ivar remark: 备注
+ \"\"\"
+
+ itemId: int
+ itemName: str
+ status: str
+ remark: str
+
+
+class ItemPage(TypedDict):
+ \"\"\"
+ 插件示例分页结果。
+
+ :ivar rows: 当前页的示例记录
+ :ivar total: 符合条件的记录数
+ \"\"\"
+
+ rows: list[PluginItem]
+ total: int
+
+
+class {service_class_name}Service:
\"\"\"
{plugin_id} 插件 CRUD 示例服务。
- 第一版模板使用内存数据演示 controller/service 分层,实际业务可替换为 dao/entity 实现。
+ :cvar _items: 当前插件的内存示例记录
\"\"\"
- _items = [
+ _items: list[PluginItem] = [
{{'itemId': 1, 'itemName': '{plugin_id} 示例', 'status': '0', 'remark': '插件 CRUD 模板数据'}},
]
@@ -214,7 +243,7 @@ def ping(cls) -> dict[str, str]:
return {{'message': '{plugin_id} plugin ok'}}
@classmethod
- def list_items(cls, keyword: str = '') -> dict[str, object]:
+ def list_items(cls, keyword: str = '') -> ItemPage:
\"\"\"
查询示例数据列表。
@@ -229,15 +258,15 @@ def list_items(cls, keyword: str = '') -> dict[str, object]:
return {{'rows': rows, 'total': len(rows)}}
@classmethod
- def create_item(cls, payload: dict[str, object]) -> dict[str, object]:
+ def create_item(cls, payload: dict[str, object]) -> PluginItem:
\"\"\"
创建示例数据。
:param payload: 示例数据负载
:return: 创建后的示例数据
\"\"\"
- next_id = max([int(item['itemId']) for item in cls._items], default=0) + 1
- item = {{
+ next_id = max((item['itemId'] for item in cls._items), default=0) + 1
+ item: PluginItem = {{
'itemId': next_id,
'itemName': str(payload.get('itemName') or '未命名'),
'status': str(payload.get('status') or '0'),
@@ -247,7 +276,7 @@ def create_item(cls, payload: dict[str, object]) -> dict[str, object]:
return item
@classmethod
- def update_item(cls, item_id: int, payload: dict[str, object]) -> dict[str, object]:
+ def update_item(cls, item_id: int, payload: dict[str, object]) -> PluginItem:
\"\"\"
更新示例数据。
@@ -298,7 +327,6 @@ async def on_install(context: PluginHookContext) -> None:
插件安装生命周期钩子。
:param context: 插件生命周期钩子上下文
- :return: None
\"\"\"
logger.info('{plugin_id} plugin install hook executed')
@@ -308,7 +336,6 @@ async def on_upgrade(context: PluginHookContext) -> None:
插件升级生命周期钩子。
:param context: 插件生命周期钩子上下文
- :return: None
\"\"\"
logger.info('{plugin_id} plugin upgrade hook executed')
@@ -318,7 +345,6 @@ async def on_startup(context: PluginHookContext) -> None:
插件启动生命周期钩子。
:param context: 插件生命周期钩子上下文
- :return: None
\"\"\"
logger.info('{plugin_id} plugin startup hook executed')
@@ -328,7 +354,6 @@ async def on_shutdown(context: PluginHookContext) -> None:
插件关闭生命周期钩子。
:param context: 插件生命周期钩子上下文
- :return: None
\"\"\"
logger.info('{plugin_id} plugin shutdown hook executed')
@@ -338,7 +363,6 @@ async def on_purge(context: PluginHookContext) -> None:
插件物理清理生命周期钩子。
:param context: 插件生命周期钩子上下文
- :return: None
\"\"\"
logger.info('{plugin_id} plugin purge hook executed')
"""
@@ -355,11 +379,7 @@ def build_jobs(plugin_id: str) -> str:
def heartbeat() -> None:
- \"\"\"
- 插件心跳定时任务。
-
- :return: None
- \"\"\"
+ \"\"\"插件心跳定时任务。\"\"\"
logger.info('{plugin_id} plugin heartbeat job executed')
"""
@@ -400,11 +420,7 @@ def build_test(plugin_id: str) -> str:
def test_{plugin_id}_service_ping() -> None:
- \"\"\"
- 校验插件服务探活返回稳定负载。
-
- :return: None
- \"\"\"
+ \"\"\"校验插件服务探活返回稳定负载。\"\"\"
assert {service_class_name}Service.ping() == {{'message': '{plugin_id} plugin ok'}}
"""
@@ -421,20 +437,12 @@ def build_crud_test(plugin_id: str) -> str:
def test_{plugin_id}_service_ping() -> None:
- \"\"\"
- 校验插件服务探活返回稳定负载。
-
- :return: None
- \"\"\"
+ \"\"\"校验插件服务探活返回稳定负载。\"\"\"
assert {service_class_name}Service.ping() == {{'message': '{plugin_id} plugin ok'}}
def test_{plugin_id}_service_crud_flow() -> None:
- \"\"\"
- 校验插件 CRUD 示例服务返回稳定负载。
-
- :return: None
- \"\"\"
+ \"\"\"校验插件 CRUD 示例服务返回稳定负载。\"\"\"
created = {service_class_name}Service.create_item({{'itemName': '测试数据', 'status': '0'}})
listed = {service_class_name}Service.list_items('测试')
updated = {service_class_name}Service.update_item(created['itemId'], {{'itemName': '测试数据2'}})
diff --git a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/payload.py b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/payload.py
index 39151dddd..53922a0ec 100644
--- a/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/payload.py
+++ b/ruoyi-fastapi-backend/cli/runtime/plugin/scaffold/payload.py
@@ -1,10 +1,14 @@
from dataclasses import dataclass
+from importlib import import_module
from pathlib import Path
-from typing import Any
+from typing import TYPE_CHECKING, Any
from cli.exit_codes import RUNTIME_ERROR
from cli.utils import format_cli_path
+if TYPE_CHECKING:
+ from utils.gen_util import GenUtils
+
@dataclass(frozen=True)
class PluginScaffoldPlanPayload:
@@ -50,6 +54,8 @@ def to_payload(self) -> dict[str, object]:
:return: 插件模板写入计划负载
"""
+ gen_utils: type[GenUtils] = import_module('utils.gen_util').GenUtils
+ files = gen_utils.format_generated_python({path.as_posix(): content for path, content in self.files})
return {
'backend': self.backend,
'frontend': self.frontend,
@@ -64,7 +70,7 @@ def to_payload(self) -> dict[str, object]:
'frontendTest': self.frontend_test,
'frontendFramework': self.frontend_framework,
'targetDirs': [format_cli_path(path) for path in self.target_dirs],
- 'files': [{'path': path.as_posix(), 'content': content} for path, content in self.files],
+ 'files': [{'path': path, 'content': content} for path, content in files.items()],
'conflicts': self.conflicts,
}
diff --git a/ruoyi-fastapi-backend/module_generator/service/gen_service.py b/ruoyi-fastapi-backend/module_generator/service/gen_service.py
index d8e968931..6d6ccc44b 100644
--- a/ruoyi-fastapi-backend/module_generator/service/gen_service.py
+++ b/ruoyi-fastapi-backend/module_generator/service/gen_service.py
@@ -1,3 +1,4 @@
+import asyncio
import io
import json
import os
@@ -388,10 +389,7 @@ async def preview_code_services(cls, query_db: AsyncSession, table_id: int) -> d
env = TemplateInitializer.init_jinja2()
context = TemplateUtils.prepare_context(gen_table)
template_list = TemplateUtils.get_template_list(gen_table)
- preview_code_result = {}
- for template in template_list:
- render_content = env.get_template(template).render(**context)
- preview_code_result[template] = render_content
+ preview_code_result = await asyncio.to_thread(TemplateUtils.render_templates, env, template_list, context)
preview_code_result.update(context['generatedI18n'].artifacts())
return preview_code_result
@@ -414,7 +412,7 @@ async def generate_code_services(
render_info = await cls.__get_gen_render_info(query_db, table_name, source_name)
try:
output_root = cls._get_output_root(render_info[3])
- files = cls._render_files(env, render_info)
+ files = await asyncio.to_thread(cls._render_files, env, render_info)
output_paths = {name: cls.__get_output_path(output_root, name) for name in files}
# 全部词库解析、合并成功后才开始写入,避免无效资源造成半份产物。
for relative_path, content in files.items():
@@ -467,7 +465,7 @@ async def batch_gen_code_services(
for table_name in table_names:
env = TemplateInitializer.init_jinja2()
render_info = await cls.__get_gen_render_info(query_db, table_name, source_name)
- generated_files = cls._render_files(env, render_info)
+ generated_files = await asyncio.to_thread(cls._render_files, env, render_info)
generators.append(render_info[2]['generatedI18n'])
for path, content in generated_files.items():
files[path] = GenI18nUtil.merge_content(path, files[path], content) if path in files else content
@@ -492,8 +490,9 @@ def _render_files(cls, env: Environment, render_info: RenderInfo) -> dict[str, s
:param render_info: 模板、输出路径、上下文和业务表
:return: 生成包内相对路径及内容
"""
- files: dict[str, str] = {
- output_file: env.get_template(template).render(**render_info[2])
+ rendered = TemplateUtils.render_templates(env, render_info[0], render_info[2])
+ files = {
+ output_file: rendered[template]
for template, output_file in zip(render_info[0], render_info[1], strict=True)
}
files.update(render_info[2]['generatedI18n'].artifacts())
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/controller.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/controller.py.jinja2
index 7998645d7..08f3de0ca 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/controller.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/controller.py.jinja2
@@ -1,4 +1,3 @@
-{% set pkField = pkColumn.python_field %}
{% set pk_field = pkColumn.python_field | camel_to_snake %}
{% set pkParentheseIndex = pkColumn.column_comment.find("(") %}
{% set pk_field_comment = pkColumn.column_comment[:pkParentheseIndex] if pkParentheseIndex != -1 else pkColumn.column_comment %}
@@ -9,19 +8,22 @@ from fastapi.responses import StreamingResponse
from pydantic_validation_decorator import ValidateFields
from sqlalchemy.ext.asyncio import AsyncSession
+{% set project_imports %}
from common.annotation.log_annotation import Log
from common.aspect.db_session import DBSessionDependency
from common.aspect.interface_auth import UserInterfaceAuthDependency
from common.aspect.pre_auth import CurrentUserDependency, PreAuthDependency
from common.enums import BusinessType
from common.router import APIRouterPro
-from common.vo import DataResponseModel, PageResponseModel, ResponseBaseModel
+from common.vo import DataResponseModel, {% if not table.tree %}PageResponseModel, {% endif %}ResponseBaseModel
from module_admin.entity.vo.user_vo import CurrentUserModel
-from {{ packageName }}.entity.vo.{{ businessName }}_vo import Delete{{ BusinessName }}Model, {{ BusinessName }}Model, {{ BusinessName }}PageQueryModel
+from {{ packageName }}.entity.vo.{{ businessName }}_vo import {{ ['Delete' ~ BusinessName ~ 'Model', BusinessName ~ 'Key', BusinessName ~ 'Model', BusinessName ~ 'PageQueryModel'] | sort | join(', ') }}
from {{ packageName }}.service.{{ businessName }}_service import {{ BusinessName }}Service
from utils.common_util import bytes2file_response
from utils.log_util import logger
from utils.response_util import ResponseUtil
+{% endset %}
+{{ project_imports.strip().splitlines() | sort | join("\n") }}
{{ businessName }}_controller = APIRouterPro(
prefix='/{{ moduleName }}/{{ businessName }}', order_num=50, tags=['{{ functionName }}'], dependencies=[PreAuthDependency()]
@@ -30,9 +32,9 @@ from utils.response_util import ResponseUtil
@{{ businessName }}_controller.get(
'/list',
- summary='获取{{ functionName }}分页列表接口',
- description='用于获取{{ functionName }}分页列表',
- response_model=PageResponseModel[{{ BusinessName }}Model],
+ summary='获取{{ functionName }}{% if not table.tree %}分页{% endif %}列表接口',
+ description='用于获取{{ functionName }}{% if not table.tree %}分页{% endif %}列表',
+ response_model={% if table.tree %}DataResponseModel[list[{{ BusinessName }}Model]]{% else %}PageResponseModel[{{ BusinessName }}Model]{% endif %},
dependencies=[UserInterfaceAuthDependency('{{ permissionPrefix }}:list')],
)
async def get_{{ moduleName }}_{{ businessName }}_list(
@@ -121,7 +123,7 @@ async def delete_{{ moduleName }}_{{ businessName }}(
{{ pk_field }}s: Annotated[str, Path(description='需要删除的{{ pk_field_comment }}')],
query_db: Annotated[AsyncSession, {{ dbSessionDependency }}],
) -> Response:
- delete_{{ businessName }} = Delete{{ BusinessName }}Model({{ pkField }}s={{ pk_field }}s)
+ delete_{{ businessName }} = Delete{{ BusinessName }}Model({{ pk_field }}s={{ pk_field }}s)
delete_{{ businessName }}_result = await {{ BusinessName }}Service.delete_{{ businessName }}_services(query_db, delete_{{ businessName }})
logger.info(delete_{{ businessName }}_result.message)
@@ -137,7 +139,7 @@ async def delete_{{ moduleName }}_{{ businessName }}(
)
async def query_detail_{{ moduleName }}_{{ businessName }}(
request: Request,
- {{ pk_field }}: Annotated[{{ pkColumn.python_type }}, Path(description='{{ pk_field_comment }}')],
+ {{ pk_field }}: Annotated[{{ BusinessName }}Key, Path(description='{{ pk_field_comment }}')],
query_db: Annotated[AsyncSession, {{ dbSessionDependency }}],
) -> Response:
{{ businessName }}_detail_result = await {{ BusinessName }}Service.{{ businessName }}_detail_services(query_db, {{ pk_field }})
@@ -169,7 +171,7 @@ async def export_{{ moduleName }}_{{ businessName }}_list(
) -> Response:
# 获取全量数据
{{ businessName }}_query_result = await {{ BusinessName }}Service.get_{{ businessName }}_list_services(query_db, {{ businessName }}_page_query, is_page=False)
- {{ businessName }}_export_result = await {{ BusinessName }}Service.export_{{ businessName }}_list_services({% if dicts %}request, {% endif %}{{ businessName }}_query_result)
+ {{ businessName }}_export_result = await {{ BusinessName }}Service.export_{{ businessName }}_list_services({% if exportDictTypes %}request, {% endif %}{{ businessName }}_query_result)
logger.info('导出成功')
return ResponseUtil.streaming(data=bytes2file_response({{ businessName }}_export_result))
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/dao.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/dao.py.jinja2
index e36ed290d..8d6514f65 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/dao.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/dao.py.jinja2
@@ -1,4 +1,3 @@
-{% set pkField = pkColumn.python_field %}
{% set pk_field = pkColumn.python_field | camel_to_snake %}
{% set pkParentheseIndex = pkColumn.column_comment.find("(") %}
{% set pk_field_comment = pkColumn.column_comment[:pkParentheseIndex] if pkParentheseIndex != -1 else pkColumn.column_comment %}
@@ -19,10 +18,6 @@
{% set edit_audit_fields.fields = edit_audit_fields.fields + [column.column_name] %}
{% endif %}
{% endfor %}
-{% set edit_audit_values = namespace(value='') %}
-{% for field in edit_audit_fields.fields %}
-{% set edit_audit_values.value = edit_audit_values.value ~ "'" ~ field ~ "'" ~ (", " if not loop.last else "") %}
-{% endfor %}
{% set sub_edit_audit_fields = namespace(fields=[]) %}
{% if table.sub %}
{% for column in subTable.columns %}
@@ -31,10 +26,6 @@
{% endif %}
{% endfor %}
{% endif %}
-{% set sub_edit_audit_values = namespace(value='') %}
-{% for field in sub_edit_audit_fields.fields %}
-{% set sub_edit_audit_values.value = sub_edit_audit_values.value ~ "'" ~ field ~ "'" ~ (", " if not loop.last else "") %}
-{% endfor %}
{% set has_datetime_range = namespace(value=False) %}
{% for column in columns %}
{% if column.query and column.time_kind == "instant" and column.query_type == "BETWEEN" %}
@@ -43,31 +34,38 @@
{% endfor %}
from typing import Any
-from sqlalchemy import delete, select, update
+{% set filters = namespace(used=false) %}
+{% for column in columns if column.unique or (column.query and (column.query_type in ['EQ', 'NE', 'GT', 'GTE', 'LT', 'LTE', 'LIKE'] or (column.time_kind and column.query_type == 'BETWEEN'))) %}
+{% set filters.used = true %}
+{% endfor %}
+from sqlalchemy import delete, select, {% if filters.used %}true, {% endif %}update
from sqlalchemy.ext.asyncio import AsyncSession
{% if table.sub %}
from sqlalchemy.orm import selectinload
{% endif %}
+{% set project_imports %}
from common.vo import PageModel
{% if table.sub %}
from {{ packageName }}.entity.do.{{ businessName }}_do import {{ [ClassName, subClassName] | sort | join(', ') }}
-from {{ packageName }}.entity.vo.{{ businessName }}_vo import {{ [BusinessName ~ 'Model', BusinessName ~ 'PageQueryModel', (subTable.business_name | capitalize) ~ 'Model'] | sort | join(', ') }}
+from {{ packageName }}.entity.vo.{{ businessName }}_vo import {{ [BusinessName ~ 'Key', BusinessName ~ 'Model', BusinessName ~ 'PageQueryModel', (subTable.business_name | capitalize) ~ 'Model'] | sort | join(', ') }}
{% else %}
from {{ packageName }}.entity.do.{{ businessName }}_do import {{ ClassName }}
-from {{ packageName }}.entity.vo.{{ businessName }}_vo import {{ BusinessName }}Model, {{ BusinessName }}PageQueryModel
+from {{ packageName }}.entity.vo.{{ businessName }}_vo import {{ BusinessName }}Key, {{ BusinessName }}Model, {{ BusinessName }}PageQueryModel
{% endif %}
from utils.page_util import PageUtil
{% if has_datetime_range.value %}
from utils.time_util import TimezoneUtil
{% endif %}
+{% endset %}
+{{ project_imports.strip().splitlines() | sort | join("\n") }}
class {{ BusinessName }}Dao:
"""{{ functionName }}模块数据库操作层。"""
@classmethod
- async def get_{{ businessName }}_detail_by_id(cls, db: AsyncSession, {{ pk_field }}: int) -> {{ ClassName }} | None:
+ async def get_{{ businessName }}_detail_by_id(cls, db: AsyncSession, {{ pk_field }}: {{ BusinessName }}Key) -> {{ ClassName }} | None:
"""
根据{{ pk_field_comment }}获取{{ functionName }}详细信息。
@@ -110,7 +108,7 @@ class {{ BusinessName }}Dao:
select({{ ClassName }}).where(
{% for column in columns %}
{% if column.unique %}
- {{ ClassName }}.{{ column.python_field | camel_to_snake }} == {{ businessName }}.{{ column.python_field | camel_to_snake }} if {{ businessName }}.{{ column.python_field | camel_to_snake }} else True,
+ {{ ClassName }}.{{ column.python_field | camel_to_snake }} == {{ businessName }}.{{ column.python_field | camel_to_snake }} if {{ businessName }}.{{ column.python_field | camel_to_snake }} else true(),
{% endif %}
{% endfor %}
)
@@ -154,25 +152,25 @@ class {{ BusinessName }}Dao:
{% set field = column.python_field | camel_to_snake %}
{% if column.query %}
{% if column.query_type == "EQ" %}
- {{ ClassName }}.{{ field }} == query_object.{{ field }} if query_object.{{ field }} else True,
+ {{ ClassName }}.{{ field }} == query_object.{{ field }} if query_object.{{ field }} else true(),
{% elif column.query_type == "NE" %}
- {{ ClassName }}.{{ field }} != query_object.{{ field }} if query_object.{{ field }} else True,
+ {{ ClassName }}.{{ field }} != query_object.{{ field }} if query_object.{{ field }} else true(),
{% elif column.query_type == "GT" %}
- {{ ClassName }}.{{ field }} > query_object.{{ field }} if query_object.{{ field }} else True,
+ {{ ClassName }}.{{ field }} > query_object.{{ field }} if query_object.{{ field }} else true(),
{% elif column.query_type == "GTE" %}
- {{ ClassName }}.{{ field }} >= query_object.{{ field }} if query_object.{{ field }} else True,
+ {{ ClassName }}.{{ field }} >= query_object.{{ field }} if query_object.{{ field }} else true(),
{% elif column.query_type == "LT" %}
- {{ ClassName }}.{{ field }} < query_object.{{ field }} if query_object.{{ field }} else True,
+ {{ ClassName }}.{{ field }} < query_object.{{ field }} if query_object.{{ field }} else true(),
{% elif column.query_type == "LTE" %}
- {{ ClassName }}.{{ field }} <= query_object.{{ field }} if query_object.{{ field }} else True,
+ {{ ClassName }}.{{ field }} <= query_object.{{ field }} if query_object.{{ field }} else true(),
{% elif column.query_type == "LIKE" %}
- {{ ClassName }}.{{ field }}.like(f'%{% raw %}{{% endraw %}query_object.{{ field }}{% raw %}}{% endraw %}%') if query_object.{{ field }} else True,
+ {{ ClassName }}.{{ field }}.like(f'%{% raw %}{{% endraw %}query_object.{{ field }}{% raw %}}{% endraw %}%') if query_object.{{ field }} else true(),
{% elif column.time_kind in ['date', 'time'] and column.query_type == "BETWEEN" %}
- {{ ClassName }}.{{ field }} >= query_object.begin_{{ column.column_name }} if query_object.begin_{{ column.column_name }} is not None else True,
- {{ ClassName }}.{{ field }} <= query_object.end_{{ column.column_name }} if query_object.end_{{ column.column_name }} is not None else True,
+ {{ ClassName }}.{{ field }} >= query_object.begin_{{ column.column_name }} if query_object.begin_{{ column.column_name }} is not None else true(),
+ {{ ClassName }}.{{ field }} <= query_object.end_{{ column.column_name }} if query_object.end_{{ column.column_name }} is not None else true(),
{% elif column.time_kind == "instant" and column.query_type == "BETWEEN" %}
- {{ ClassName }}.{{ field }} >= {{ column.column_name }}_range[0] if {{ column.column_name }}_range and {{ column.column_name }}_range[0] is not None else True,
- {{ ClassName }}.{{ field }} < {{ column.column_name }}_range[1] if {{ column.column_name }}_range and {{ column.column_name }}_range[1] is not None else True,
+ {{ ClassName }}.{{ field }} >= {{ column.column_name }}_range[0] if {{ column.column_name }}_range and {{ column.column_name }}_range[0] is not None else true(),
+ {{ ClassName }}.{{ field }} < {{ column.column_name }}_range[1] if {{ column.column_name }}_range and {{ column.column_name }}_range[1] is not None else true(),
{% endif %}
{% endif %}
{% endfor %}
@@ -195,7 +193,7 @@ class {{ BusinessName }}Dao:
:param {{ businessName }}: {{ functionName }}对象
:return: 新增的{{ functionName }}记录
"""
- db_{{ businessName }} = {{ ClassName }}(**{{ businessName }}.model_dump(exclude={% raw %}{{% endraw %}{% for field in add_exclude_fields.fields %}'{{ field }}'{% if not loop.last %}, {% endif %}{% endfor %}{% raw %}}{% endraw %}))
+ db_{{ businessName }} = {{ ClassName }}(**{{ businessName }}.model_dump({% if add_exclude_fields.fields %}exclude={{ '{' }}{{ add_exclude_fields.fields | map('python_literal') | join(', ') }}{{ '}' }}{% endif %}))
db.add(db_{{ businessName }})
await db.flush()
@@ -209,11 +207,16 @@ class {{ BusinessName }}Dao:
:param db: orm对象
:param {{ businessName }}: 需要更新的{{ functionName }}字典
"""
+ {% if edit_audit_fields.fields %}
safe_{{ businessName }} = {
key: value
for key, value in {{ businessName }}.items()
- if key not in {% if edit_audit_values.value %}{{ "{" }}{{ edit_audit_values.value }}{{ "}" }}{% else %}set(){% endif %}{{ "\n" }} }
+ if key not in {{ "{" }}{{ edit_audit_fields.fields | map('python_literal') | join(', ') }}{{ "}" }}
+ }
await db.execute(update({{ ClassName }}), [safe_{{ businessName }}])
+ {% else %}
+ await db.execute(update({{ ClassName }}), [{{ businessName }}])
+ {% endif %}
@classmethod
async def delete_{{ businessName }}_dao(cls, db: AsyncSession, {{ businessName }}: {{ BusinessName }}Model) -> None:
@@ -235,7 +238,7 @@ class {{ BusinessName }}Dao:
:param {{ subTable.business_name }}: {{ subTable.function_name }}对象
:return: 新增的{{ subTable.function_name }}记录
"""
- db_{{ subTable.business_name }} = {{ subClassName }}(**{{ subTable.business_name }}.model_dump(exclude={% raw %}{{% endraw %}{% for field in sub_edit_audit_fields.fields %}'{{ field }}'{% if not loop.last %}, {% endif %}{% endfor %}{% raw %}}{% endraw %}))
+ db_{{ subTable.business_name }} = {{ subClassName }}(**{{ subTable.business_name }}.model_dump({% if sub_edit_audit_fields.fields %}exclude={{ '{' }}{{ sub_edit_audit_fields.fields | map('python_literal') | join(', ') }}{{ '}' }}{% endif %}))
db.add(db_{{ subTable.business_name }})
await db.flush()
@@ -249,11 +252,16 @@ class {{ BusinessName }}Dao:
:param db: orm对象
:param {{ subTable.business_name }}: 需要更新的{{ subTable.function_name }}字典
"""
+ {% if sub_edit_audit_fields.fields %}
safe_{{ subTable.business_name }} = {
key: value
for key, value in {{ subTable.business_name }}.items()
- if key not in {% if sub_edit_audit_values.value %}{{ "{" }}{{ sub_edit_audit_values.value }}{{ "}" }}{% else %}set(){% endif %}{{ "\n" }} }
+ if key not in {{ "{" }}{{ sub_edit_audit_fields.fields | map('python_literal') | join(', ') }}{{ "}" }}
+ }
await db.execute(update({{ subClassName }}), [safe_{{ subTable.business_name }}])
+ {% else %}
+ await db.execute(update({{ subClassName }}), [{{ subTable.business_name }}])
+ {% endif %}
@classmethod
async def delete_{{ subTable.business_name }}_dao(cls, db: AsyncSession, {{ subTable.business_name }}: {{ subTable.business_name | capitalize }}Model) -> None:
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/do.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/do.py.jinja2
index 8747af194..24fcbf921 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/do.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/do.py.jinja2
@@ -26,14 +26,20 @@
{% if (main_time.update and not main_time.create) or (sub_time.update and not sub_time.create) %}
{% set time_mixin_imports.names = time_mixin_imports.names + ['UpdateTimeMixin'] %}
{% endif %}
-{% for do_import in doImportList | sort %}
-{% if not do_import.startswith('from common.') %}
-{{ do_import }}
+{% for stmt in doImportList if stmt.startswith(('from datetime ', 'from decimal ')) %}
+{{ stmt }}
+{% if loop.last and dataSourceName == defaultDataSourceName %}
+
{% endif %}
{% endfor %}
-{% if table.sub %}
-from sqlalchemy.orm import relationship
+{% if dataSourceName != defaultDataSourceName %}
+from typing import TYPE_CHECKING
+
{% endif %}
+{% for stmt in doImportList if stmt.startswith(('from geoalchemy2 ', 'from sqlalchemy')) %}
+{{ stmt }}
+{% endfor %}
+from sqlalchemy.orm import Mapped, mapped_column{{ ', relationship' if table.sub else '' }}
{% if time_mixin_imports.names %}
from common.mixin import {{ time_mixin_imports.names | join(', ') }}
@@ -46,10 +52,13 @@ from common.mixin import {{ time_mixin_imports.names | join(', ') }}
{% if dataSourceName == defaultDataSourceName %}
from config.database import Base
{% else %}
-from config.database import get_data_source_base
+if TYPE_CHECKING:
+ from sqlalchemy.orm import DeclarativeBase as DataSourceBase
+else:
+ from config.database import get_data_source_base
-DataSourceBase = get_data_source_base('{{ dataSourceName }}')
+ DataSourceBase = get_data_source_base({{ dataSourceName | python_literal }})
{% endif %}
@@ -73,12 +82,12 @@ class {{ ClassName }}({% if main_time.create and main_time.update %}AuditTimeMix
{% for column in columns %}
{% if not (column.column_name in ["create_time", "update_time"] and column.time_kind == "instant") %}
- {{ column.column_name }} = Column({% if column.time_kind == "instant" %}DbUtcDateTime(){% else %}{{ column.column_type | get_sqlalchemy_type(dataSourceName) }}{% endif %}, {% if column.pk %}primary_key=True, {% endif %}{% if column.increment %}autoincrement=True, {% endif %}{% if column.required or column.pk %}nullable=False{% else %}nullable=True{% endif %}, comment={{ column.column_comment | model_field_label | python_literal }})
+ {{ column.column_name }}: Mapped[{{ column.python_type }}{% if not (column.pk or column.required) %} | None{% endif %}] = mapped_column({% if column.time_kind == "instant" %}DbUtcDateTime(){% else %}{{ column.column_type | get_sqlalchemy_type(dataSourceName) }}{% endif %}, {% if column.pk %}primary_key=True, {% endif %}{% if column.increment %}autoincrement=True, {% endif %}{% if column.required or column.pk %}nullable=False{% else %}nullable=True{% endif %}, comment={{ column.column_comment | model_field_label | python_literal }})
{% endif %}
{% endfor %}
{% if table.sub %}
- {{ subclassName }}_list = relationship('{{ subClassName }}', back_populates='{{ businessName }}')
+ {{ subclassName }}_list: Mapped[list['{{ subClassName }}']] = relationship('{{ subClassName }}', back_populates='{{ businessName }}')
{% endif %}
@@ -102,11 +111,11 @@ class {{ subClassName }}({% if sub_time.create and sub_time.update %}AuditTimeMi
{% for column in subTable.columns %}
{% if not (column.column_name in ["create_time", "update_time"] and column.time_kind == "instant") %}
- {{ column.column_name }} = Column({% if column.time_kind == "instant" %}DbUtcDateTime(){% else %}{{ column.column_type | get_sqlalchemy_type(dataSourceName) }}{% endif %}, {% if column.column_name == subTableFkName %}ForeignKey('{{ tableName }}.{{ pkColumn.column_name }}'), {% endif %}{% if column.pk %}primary_key=True, {% endif %}{% if column.increment %}autoincrement=True, {% endif %}{% if column.required or column.pk %}nullable=False{% else %}nullable=True{% endif %}, comment={{ column.column_comment | model_field_label | python_literal }})
+ {{ column.column_name }}: Mapped[{{ column.python_type }}{% if not (column.pk or column.required) %} | None{% endif %}] = mapped_column({% if column.time_kind == "instant" %}DbUtcDateTime(){% else %}{{ column.column_type | get_sqlalchemy_type(dataSourceName) }}{% endif %}, {% if column.column_name == subTableFkName %}ForeignKey('{{ tableName }}.{{ pkColumn.column_name }}'), {% endif %}{% if column.pk %}primary_key=True, {% endif %}{% if column.increment %}autoincrement=True, {% endif %}{% if column.required or column.pk %}nullable=False{% else %}nullable=True{% endif %}, comment={{ column.column_comment | model_field_label | python_literal }})
{% endif %}
{% endfor %}
{% if table.sub %}
- {{ businessName }} = relationship('{{ ClassName }}', back_populates='{{ subclassName }}_list')
+ {{ businessName }}: Mapped[{{ ClassName }}{% if not (subTable.columns | selectattr('column_name', 'equalto', subTableFkName) | selectattr('required') | list) %} | None{% endif %}] = relationship('{{ ClassName }}', back_populates='{{ subclassName }}_list')
{% endif %}
{% endif %}
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2
index f2fc3e12f..24d6d8aaa 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/service.py.jinja2
@@ -1,33 +1,51 @@
{% set pk_field = pkColumn.python_field | camel_to_snake %}
{% set pkParentheseIndex = pkColumn.column_comment.find("(") %}
{% set pk_field_comment = pkColumn.column_comment[:pkParentheseIndex] if pkParentheseIndex != -1 else pkColumn.column_comment %}
-from typing import Any
+from typing import Any, Literal, overload
-{% if dicts %}
+{% if exportDictTypes %}
from fastapi import Request
{% endif %}
+from pydantic import TypeAdapter
from sqlalchemy.ext.asyncio import AsyncSession
+{% set project_imports %}
+{% if columns | selectattr("unique") | list %}
from common.constant import CommonConstant
+{% endif %}
from common.context import RequestContext
from common.vo import CrudResponseModel, PageModel
from exceptions.exception import ServiceException
from i18n.message import I18nMessage
-{% if dicts %}
+{% if exportDictTypes %}
from i18n.translation import TranslationUtil
{% endif %}
from {{ packageName }}.dao.{{ businessName }}_dao import {{ BusinessName }}Dao
-from {{ packageName }}.entity.vo.{{ businessName }}_vo import Delete{{ BusinessName }}Model, {{ BusinessName }}Model, {{ BusinessName }}PageQueryModel
-{% if dicts %}
+from {{ packageName }}.entity.vo.{{ businessName }}_vo import {{ ['Delete' ~ BusinessName ~ 'Model', BusinessName ~ 'Key', BusinessName ~ 'Model', BusinessName ~ 'PageQueryModel'] | sort | join(', ') }}
+{% if exportDictTypes %}
from module_admin.service.dict_service import DictDataService
{% endif %}
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil
+{% endset %}
+{{ project_imports.strip().splitlines() | sort | join("\n") }}
class {{ BusinessName }}Service:
"""{{ functionName }}模块服务层。"""
+ @classmethod
+ @overload
+ async def get_{{ businessName }}_list_services(
+ cls, query_db: AsyncSession, query_object: {{ BusinessName }}PageQueryModel, is_page: Literal[True]
+ ) -> PageModel[dict[str, Any]]: ...
+
+ @classmethod
+ @overload
+ async def get_{{ businessName }}_list_services(
+ cls, query_db: AsyncSession, query_object: {{ BusinessName }}PageQueryModel, is_page: Literal[False] = False
+ ) -> list[dict[str, Any]]: ...
+
@classmethod
async def get_{{ businessName }}_list_services(
cls, query_db: AsyncSession, query_object: {{ BusinessName }}PageQueryModel, is_page: bool = False
@@ -57,9 +75,8 @@ class {{ BusinessName }}Service:
:param page_object: {{ functionName }}对象
:return: 校验结果
"""
- {{ pk_field }} = -1 if page_object.{{ pk_field }} is None else page_object.{{ pk_field }}
{{ businessName }} = await {{ BusinessName }}Dao.get_{{ businessName }}_detail_by_info(query_db, {{ BusinessName }}Model({{ column.python_field | camel_to_snake }}=page_object.{{ column.python_field | camel_to_snake }}))
- if {{ businessName }} and {{ businessName }}.{{ pk_field }} != {{ pk_field }}:
+ if {{ businessName }} and {{ businessName }}.{{ pk_field }} != page_object.{{ pk_field }}:
return CommonConstant.NOT_UNIQUE
return CommonConstant.UNIQUE
{% if not loop.last %}{{ "\n" }}{% endif %}
@@ -93,10 +110,10 @@ class {{ BusinessName }}Service:
{% endfor %}
try:
{% if table.sub %}
- add_{{ businessName }} = await {{ BusinessName }}Dao.add_{{ businessName }}_dao(query_db, page_object)
- if add_{{ businessName }}:
- for sub_table in page_object.{{ subclassName }}_list:
- await {{ BusinessName }}Dao.add_{{ subTable.business_name }}_dao(query_db, sub_table)
+ parent = await {{ BusinessName }}Dao.add_{{ businessName }}_dao(query_db, page_object)
+ for sub_table in page_object.{{ subclassName }}_list or []:
+ sub_table.{{ subTableFkName }} = parent.{{ pk_field }}
+ await {{ BusinessName }}Dao.add_{{ subTable.business_name }}_dao(query_db, sub_table)
{% else %}
await {{ BusinessName }}Dao.add_{{ businessName }}_dao(query_db, page_object)
{% endif %}
@@ -117,9 +134,17 @@ class {{ BusinessName }}Service:
:raises ServiceException: 目标记录不存在或唯一字段冲突
:raises Exception: 更新失败,事务回滚后重新抛出原异常
"""
- edit_{{ businessName }} = page_object.model_dump(exclude_unset=True, exclude={% raw %}{{% endraw %}{% if table.sub %}'{{ subclassName }}_list', {% endif %}{% for column in columns %}{% if not column.edit and not column.pk and column.column_name not in column_not_edit_show %}'{{ column.python_field | camel_to_snake }}'{% if not loop.last %}, {% endif %}{% endif %}{% endfor %}{% raw %}}{% endraw %})
- {{ businessName }}_info = await cls.{{ businessName }}_detail_services(query_db, page_object.{{ pk_field }})
- if {{ businessName }}_info.{{ pk_field }}:
+ {% set excluded = namespace(fields=[subclassName ~ '_list'] if table.sub else []) %}
+ {% for column in columns if not column.edit and not column.pk and column.column_name not in column_not_edit_show %}
+ {% set excluded.fields = excluded.fields + [column.python_field | camel_to_snake] %}
+ {% endfor %}
+ edit_{{ businessName }} = page_object.model_dump(exclude_unset=True{% if excluded.fields %}, exclude={{ '{' }}{{ excluded.fields | map('python_literal') | join(', ') }}{{ '}' }}{% endif %})
+ {{ businessName }}_info = (
+ await cls.{{ businessName }}_detail_services(query_db, page_object.{{ pk_field }})
+ if page_object.{{ pk_field }} is not None
+ else None
+ )
+ if {{ businessName }}_info is not None and {{ businessName }}_info.{{ pk_field }} is not None:
{% for column in columns %}
{% set parentheseIndex = column.column_comment.find("(") %}
{% set comment = column.column_comment[:parentheseIndex] if parentheseIndex != -1 else column.column_comment %}
@@ -135,10 +160,12 @@ class {{ BusinessName }}Service:
try:
await {{ BusinessName }}Dao.edit_{{ businessName }}_dao(query_db, edit_{{ businessName }})
{% if table.sub %}
- for sub_table in {{ businessName }}_info.{{ subclassName }}_list:
- await {{ BusinessName }}Dao.delete_{{ subTable.business_name }}_dao(query_db, sub_table)
- for sub_table in page_object.{{ subclassName }}_list:
- await {{ BusinessName }}Dao.add_{{ subTable.business_name }}_dao(query_db, sub_table)
+ if page_object.{{ subclassName }}_list is not None:
+ for sub_table in {{ businessName }}_info.{{ subclassName }}_list or []:
+ await {{ BusinessName }}Dao.delete_{{ subTable.business_name }}_dao(query_db, sub_table)
+ for sub_table in page_object.{{ subclassName }}_list:
+ sub_table.{{ subTableFkName }} = {{ businessName }}_info.{{ pk_field }}
+ await {{ BusinessName }}Dao.add_{{ subTable.business_name }}_dao(query_db, sub_table)
{% endif %}
await query_db.commit()
return CrudResponseModel(is_success=True, message='更新成功', msg_key='common.updated')
@@ -163,12 +190,12 @@ class {{ BusinessName }}Service:
:raises Exception: 删除失败,事务回滚后重新抛出原异常
"""
if page_object.{{ pk_field }}s:
- {{ pk_field }}_list = page_object.{{ pk_field }}s.split(',')
+ {{ pk_field }}_list = TypeAdapter(list[{{ BusinessName }}Key]).validate_python(page_object.{{ pk_field }}s.split(','))
try:
for {{ pk_field }} in {{ pk_field }}_list:
{% if table.sub %}
- {{ businessName }} = await cls.{{ businessName }}_detail_services(query_db, int({{ pk_field }}))
- for sub_table in {{ businessName }}.{{ subclassName }}_list:
+ {{ businessName }} = await cls.{{ businessName }}_detail_services(query_db, {{ pk_field }})
+ for sub_table in {{ businessName }}.{{ subclassName }}_list or []:
await {{ BusinessName }}Dao.delete_{{ subTable.business_name }}_dao(query_db, sub_table)
{% endif %}
await {{ BusinessName }}Dao.delete_{{ businessName }}_dao(query_db, {{ BusinessName }}Model({{ pk_field }}={{ pk_field }}))
@@ -184,7 +211,7 @@ class {{ BusinessName }}Service:
)
@classmethod
- async def {{ businessName }}_detail_services(cls, query_db: AsyncSession, {{ pk_field }}: int) -> {{ BusinessName }}Model:
+ async def {{ businessName }}_detail_services(cls, query_db: AsyncSession, {{ pk_field }}: {{ BusinessName }}Key) -> {{ BusinessName }}Model:
"""
获取{{ functionName }}详细信息service。
@@ -198,11 +225,11 @@ class {{ BusinessName }}Service:
return result
@staticmethod
- async def export_{{ businessName }}_list_services({% if dicts %}request: Request, {% endif %}{{ businessName }}_list: list[dict[str, Any]]) -> bytes:
+ async def export_{{ businessName }}_list_services({% if exportDictTypes %}request: Request, {% endif %}{{ businessName }}_list: list[dict[str, Any]]) -> bytes:
"""
导出{{ functionName }}信息service。
- {% if dicts %}
+ {% if exportDictTypes %}
:param request: 读取字典标签时使用的当前 HTTP 请求
{% endif %}
:param {{ businessName }}_list: {{ functionName }}信息列表
@@ -220,30 +247,20 @@ class {{ BusinessName }}Service:
),
{% endfor %}
}
- {% if dicts %}
- {% for dict_type in dicts.split(", ") %}
- {{ dict_type[1:-1] }}_list = await DictDataService.query_dict_data_list_from_cache_services(
- request.app.state.redis, dict_type={{ dict_type }}
- )
- {{ dict_type[1:-1] }}_option = [
- {
- 'label': TranslationUtil.resolve(
- item.get('dictLabel'),
- item.get('dictLabelI18n'),
- locale=locale_context.locale,
- ),
- 'value': item.get('dictValue'),
+ {% if exportDictTypes %}
+ labels_by_type = {}
+ for dict_type in {{ exportDictTypes | python_literal }}:
+ options = await DictDataService.query_dict_data_list_from_cache_services(request.app.state.redis, dict_type)
+ labels_by_type[dict_type] = {
+ option.get('dictValue'): TranslationUtil.resolve(
+ option.get('dictLabel'), option.get('dictLabelI18n'), locale=locale_context.locale
+ )
+ for option in options
}
- for item in {{ dict_type[1:-1] }}_list
- ]
- {{ dict_type[1:-1] }}_option_dict = {item.get('value'): item for item in {{ dict_type[1:-1] }}_option}
- {% endfor %}
for item in {{ businessName }}_list:
- {% for column in columns %}
- {% if column.dict_type %}
- if str(item.get('{{ column.python_field }}')) in {{ column.dict_type }}_option_dict:
- item['{{ column.python_field }}'] = {{ column.dict_type }}_option_dict.get(str(item.get('{{ column.python_field }}'))).get('label')
- {% endif %}
+ {% for column in columns if column.dict_type %}
+ if (label := labels_by_type[{{ column.dict_type | python_literal }}].get(str(item.get('{{ column.python_field }}')))) is not None:
+ item['{{ column.python_field }}'] = label
{% endfor %}
{% endif %}
binary_data = ExcelUtil.export_list2excel({{ businessName }}_list, mapping_dict, locale_context=locale_context)
diff --git a/ruoyi-fastapi-backend/module_generator/templates/python/vo.py.jinja2 b/ruoyi-fastapi-backend/module_generator/templates/python/vo.py.jinja2
index ec4588b84..c6b67afb1 100644
--- a/ruoyi-fastapi-backend/module_generator/templates/python/vo.py.jinja2
+++ b/ruoyi-fastapi-backend/module_generator/templates/python/vo.py.jinja2
@@ -1,4 +1,3 @@
-{% set pkField = pkColumn.python_field %}
{% set pk_field = pkColumn.python_field | camel_to_snake %}
{% set pkParentheseIndex = pkColumn.column_comment.find("(") %}
{% set pk_field_comment = pkColumn.column_comment[:pkParentheseIndex] if pkParentheseIndex != -1 else pkColumn.column_comment %}
@@ -26,7 +25,9 @@
{% endif %}
{% endfor %}
{% if vo_field_daterange.has_daterange %}
-from typing import ClassVar
+from typing import ClassVar, TypeAlias
+{% else %}
+from typing import TypeAlias
{% endif %}
from pydantic import ConfigDict, Field
@@ -47,10 +48,12 @@ from common.vo import CamelModel
from i18n.message import I18nMessage
{% endif %}
+{{ BusinessName }}Key: TypeAlias = {{ pkColumn.vo_type or pkColumn.python_type }}
+
{% if table.sub %}
class {{ BusinessName }}BaseModel(CamelModel):
- """{{ functionName }}表对应pydantic模型。"""
+ """{{ functionName }}表对应的 Pydantic 模型。"""
model_config = ConfigDict(from_attributes=True)
@@ -93,7 +96,8 @@ class {{ BusinessName }}BaseModel(CamelModel):
{% endif %}
class {{ BusinessName }}Model({% if table.sub %}{{ BusinessName }}BaseModel{% else %}CamelModel{% endif %}):
- """{{ functionName }}表对应pydantic模型。"""
+ """{{ functionName }}表对应的 Pydantic 模型。"""
+
{% if not table.sub %}
model_config = ConfigDict(from_attributes=True)
@@ -142,7 +146,7 @@ class {{ BusinessName }}Model({% if table.sub %}{{ BusinessName }}BaseModel{% el
{% if table.sub %}
class {{ subTable.business_name | capitalize }}Model(CamelModel):
- """{{ subTable.function_name }}表对应pydantic模型。"""
+ """{{ subTable.function_name }}表对应的 Pydantic 模型。"""
model_config = ConfigDict(from_attributes=True)
@@ -187,6 +191,7 @@ class {{ subTable.business_name | capitalize }}Model(CamelModel):
class {{ BusinessName }}QueryModel({% if vo_field_daterange.has_daterange %}GeneratedTimeRangeQueryMixin, {% endif %}{% if table.sub %}{{ BusinessName }}BaseModel{% else %}{{ BusinessName }}Model{% endif %}):
"""{{ functionName }}不分页查询模型。"""
{% if vo_field_daterange.has_daterange %}
+
time_range_fields: ClassVar[dict[str, str]] = {
{% for column in columns %}
{% if column.time_kind and column.query_type == 'BETWEEN' %}
@@ -201,8 +206,6 @@ class {{ BusinessName }}QueryModel({% if vo_field_daterange.has_daterange %}Gene
end_{{ column.column_name }}: {% if column.time_kind == 'time' %}BusinessTime{% else %}BusinessDate{% endif %} | None = Field(default=None, description={{ ('结束' ~ column.column_comment) | tojson }})
{% endif %}
{% endfor %}
- {% else %}
- pass
{% endif %}
diff --git a/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py b/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
index 2d1b1ba2c..46c4a08ca 100644
--- a/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
+++ b/ruoyi-fastapi-backend/tests/module_generator/test_generated_time_contract.py
@@ -1,6 +1,6 @@
-import ast
import importlib.util
import json
+import shutil
import subprocess
import sys
from datetime import UTC, date, time
@@ -13,12 +13,13 @@
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
+from cli.runtime.plugin.scaffold.builder import PluginScaffoldBuilder
from config import database
from config.env import AppConfig
from exceptions.exception import ServiceWarning
from module_generator.entity.vo.gen_vo import GenTableColumnModel, GenTableModel
-from scripts.check_docstrings import BACKEND, sphinx_settings, violations
-from utils import common_util
+from scripts import check_docstrings
+from scripts.check_docstrings import BACKEND
from utils.template_util import TemplateInitializer, TemplateUtils
@@ -118,51 +119,126 @@ def make_table(db_type: str, category: str, web_type: str) -> GenTableModel:
return table
-def render_case(db_type: str, category: str, web_type: str, *, field_constraints: bool = False) -> dict[str, str]:
+def render_table(table: GenTableModel, db_type: str) -> dict[str, str]:
+ """
+ 使用指定数据库的表配置渲染所有模板。
+
+ :param table: 主表及其关联子表的配置
+ :param db_type: 生成代码使用的数据库方言
+ :return: 按模板名索引的生成代码
+ """
+ with patch.object(type(database.DataBaseConfig), 'get_source', return_value=SimpleNamespace(db_type=db_type)):
+ context = TemplateUtils.prepare_context(table)
+ environment = TemplateInitializer.init_jinja2()
+ return TemplateUtils.render_templates(environment, TemplateUtils.get_template_list(table), context)
+
+
+def render_case(db_type: str, category: str, web_type: str) -> dict[str, str]:
"""
使用样表实际渲染所选模板。
:param db_type: 数据库类型
:param category: 测试的模板或记录类别
:param web_type: 渲染模板的前端类型
- :param field_constraints: 是否生成必填字段校验方法和唯一性检查
:return: 按模板名索引的生成代码
"""
- with patch.object(type(database.DataBaseConfig), 'get_source', return_value=SimpleNamespace(db_type=db_type)):
- table = make_table(db_type, category, web_type)
- if field_constraints:
- assert table.columns
+ return render_table(make_table(db_type, category, web_type), db_type)
+
+
+def test_generated_python_quality(tmp_path: Path) -> None:
+ """按真实包路径检查生成代码的完整 ty、Ruff 和中文 reST 规则。"""
+ sources: dict[Path, str] = {}
+ for category in ('crud', 'tree', 'sub'):
+ db_type = 'postgresql' if category == 'tree' else 'mysql'
+ table = make_table(db_type, category, 'element-plus')
+ table.package_name = f'module_generated_{category}'
+ assert table.columns and table.pk_column
+ if category == 'tree':
+ table.data_source_name = 'reporting'
+ table.pk_column.column_type = table.columns[0].column_type = 'varchar(64)'
+ table.pk_column.python_type = table.columns[0].python_type = 'str'
+ table.columns.append(column('metadata_json', 'jsonb', 'dict'))
+ table.columns.append(column('amount', 'numeric(10,2)', 'Decimal'))
+ if category == 'crud':
+ table.columns = table.columns[:2]
+ else:
table.columns[1].unique = table.columns[1].required = True
- if table.sub_table:
- assert table.sub_table.columns
- table.sub_table.columns[1].required = True
- context = TemplateUtils.prepare_context(table)
- environment = TemplateInitializer.init_jinja2()
- return {
- name: environment.get_template(name).render(**context) for name in TemplateUtils.get_template_list(table)
- }
-
-
-def test_generated_python_docstrings(tmp_path: Path) -> None:
- """检查各类生成模板及插件脚手架输出的中文接口说明和多行摘要布局。"""
- sources = {
- f'{category}_{Path(name).stem}': source
- for category in ('crud', 'tree', 'sub')
- for name, source in render_case('mysql', category, 'element-plus', field_constraints=True).items()
- if name.endswith('.py.jinja2')
- }
- assert ':raises ServiceException:' in sources['crud_service.py']
- assert '校验子表的必填字段' in sources['sub_vo.py']
- assets = BACKEND / 'cli/runtime/plugin/scaffold/assets'
- for path in assets.rglob('*.py.tmpl'):
- sources[f'{path.parent.name}_{path.stem}'] = path.read_text(encoding='utf-8')
- with sphinx_settings() as settings:
- for name, source in sources.items():
- target = tmp_path / name
- target.write_text(source, encoding='utf-8')
- assert not list(violations(ast.parse(source), settings, target)), name
+ table.columns[1].dict_type = 'sys_test'
+ table.columns[1].html_type = 'select'
+ if table.sub_table:
+ assert table.sub_table.columns
+ table.sub_table.columns[1].required = True
+ table.sub_table.columns.append(column('values_json', 'json', 'list'))
+ for name, source in render_table(table, db_type).items():
+ if name.endswith('.py.jinja2'):
+ path = Path(TemplateUtils.get_file_name(name, table)).relative_to('backend')
+ sources[path] = source
+
+ # 将旧版插件装入临时宿主包,让插件间的绝对导入与部署时一致。
+ shutil.copytree(BACKEND / 'plugins/core', tmp_path / 'plugins/core', ignore=shutil.ignore_patterns('__pycache__'))
+ shutil.copyfile(BACKEND / 'plugins/__init__.py', tmp_path / 'plugins/__init__.py')
+ builder = PluginScaffoldBuilder(tmp_path, tmp_path / 'frontend')
+ for template in ('scheduled-job', 'crud-page', 'python-asgi', 'rust-asgi'):
+ plan = builder.build_plan(template.replace('-', '_'), template=template, backend=True, frontend=False)
+ for entry in plan['files']:
+ path = Path(entry['path'])
+ if path.suffix == '.py':
+ sources[path.relative_to(tmp_path)] = entry['content']
+
+ paths = []
+ for path, source in sources.items():
+ target = tmp_path / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(source, encoding='utf-8')
+ paths.append(str(target))
+ assert check_docstrings.main(paths) == 0
subprocess.run(
- [sys.executable, '-m', 'ruff', 'check', '--no-cache', '--select', 'D213', str(tmp_path)],
+ [
+ sys.executable,
+ '-m',
+ 'ty',
+ 'check',
+ '--project',
+ str(tmp_path),
+ '--config-file',
+ str(BACKEND / 'ty.toml'),
+ '--extra-search-path',
+ str(BACKEND),
+ '--python',
+ sys.executable,
+ '--python-version',
+ f'{sys.version_info.major}.{sys.version_info.minor}',
+ *paths,
+ ],
+ check=True,
+ )
+ subprocess.run(
+ [
+ sys.executable,
+ '-m',
+ 'ruff',
+ 'check',
+ '--no-cache',
+ '--config',
+ str(BACKEND / 'ruff.toml'),
+ '--config',
+ f'src={json.dumps([BACKEND.as_posix(), tmp_path.as_posix()])}',
+ *paths,
+ ],
+ check=True,
+ )
+ subprocess.run(
+ [
+ sys.executable,
+ '-m',
+ 'ruff',
+ 'format',
+ '--check',
+ '--no-cache',
+ '--config',
+ str(BACKEND / 'ruff.toml'),
+ *paths,
+ ],
check=True,
)
@@ -207,19 +283,21 @@ class TestBase(DeclarativeBase):
"""为生成模块提供独立的 ORM 模型基类。"""
monkeypatch.setattr(database, 'Base', TestBase)
- monkeypatch.setattr(common_util, 'Base', TestBase)
for name in [
'module_generated_time',
'module_generated_time.entity',
'module_generated_time.entity.do',
'module_generated_time.entity.vo',
'module_generated_time.dao',
+ 'module_generated_time.service',
]:
package = ModuleType(name)
package.__path__ = [str(tmp_path)]
monkeypatch.setitem(sys.modules, name, package)
modules = []
- for kind, folder in [('do', 'entity.do'), ('vo', 'entity.vo'), ('dao', 'dao')]:
+ for kind, folder in [('do', 'entity.do'), ('vo', 'entity.vo'), ('dao', 'dao'), ('service', 'service')]:
+ if f'python/{kind}.py.jinja2' not in rendered:
+ continue
name = f'module_generated_time.{folder}.item_{kind}'
path = tmp_path / f'item_{kind}.py'
path.write_text(rendered[f'python/{kind}.py.jinja2'], encoding='utf-8')
@@ -268,7 +346,9 @@ async def test_generated_import_crud_and_query(
db_type: str, category: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""验证生成模块的导入、增删改查和查询。"""
- base, _do, vo, dao = import_generated(tmp_path, monkeypatch, render_case(db_type, category, 'element-plus'))
+ base, _do, vo, dao, _service = import_generated(
+ tmp_path, monkeypatch, render_case(db_type, category, 'element-plus')
+ )
monkeypatch.setattr(AppConfig, 'app_timezone', 'America/New_York')
engine = create_async_engine('sqlite+aiosqlite:///:memory:')
try:
@@ -328,6 +408,40 @@ async def test_generated_import_crud_and_query(
await engine.dispose()
+@pytest.mark.asyncio
+async def test_generated_secondary_service_updates_children(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证具名数据源、字符串主键和主子表编辑的实际读写行为。"""
+ table = make_table('mysql', 'sub', 'element-plus')
+ table.data_source_name = 'generated_contract'
+ assert table.columns and table.pk_column and table.sub_table and table.sub_table.columns
+ for key in (table.columns[0], table.pk_column, table.sub_table.columns[1]):
+ key.python_type = 'str'
+ key.column_type = 'varchar(64)'
+ with patch.object(type(database.DataBaseConfig), 'get_source', return_value=SimpleNamespace(db_type='mysql')):
+ default_base, orm, vo, _, service = import_generated(tmp_path, monkeypatch, render_table(table, 'mysql'))
+ assert orm.TimeItem.metadata is not default_base.metadata
+ engine = create_async_engine('sqlite+aiosqlite:///:memory:')
+ try:
+ async with engine.begin() as connection:
+ await connection.run_sync(orm.TimeItem.metadata.create_all)
+ sessions = async_sessionmaker(engine)
+ async with sessions() as session:
+ await service.ItemService.add_item_services(
+ session, vo.ItemModel(item_id='A-01', timedetail_list=[vo.DetailModel(detail_id=1)])
+ )
+ await service.ItemService.edit_item_services(session, vo.ItemModel(item_id='A-01', item_name='已更新'))
+ page = await service.ItemService.get_item_list_services(session, vo.ItemPageQueryModel(), is_page=True)
+ assert page.rows[0]['itemName'] == '已更新'
+ assert page.rows[0]['timedetailList'][0]['parentItemId'] == 'A-01'
+ await service.ItemService.edit_item_services(session, vo.ItemModel(item_id='A-01', timedetail_list=[]))
+ rows = await service.ItemService.get_item_list_services(session, vo.ItemPageQueryModel())
+ assert rows[0]['timedetailList'] == []
+ await service.ItemService.delete_item_services(session, vo.DeleteItemModel(item_ids='A-01'))
+ assert await service.ItemService.get_item_list_services(session, vo.ItemPageQueryModel()) == []
+ finally:
+ await engine.dispose()
+
+
@pytest.mark.parametrize('column_type', ['timestamp(3) without time zone', 'timestamp', 'TIMESTAMP(6)'])
def test_rejects_postgres_ambiguous_timestamp(column_type: str) -> None:
"""拒绝 PostgreSQL 有歧义的时间戳。"""
diff --git a/ruoyi-fastapi-backend/tests/utils/test_template_util.py b/ruoyi-fastapi-backend/tests/utils/test_template_util.py
index a80b84dc7..2c93d15d5 100644
--- a/ruoyi-fastapi-backend/tests/utils/test_template_util.py
+++ b/ruoyi-fastapi-backend/tests/utils/test_template_util.py
@@ -198,7 +198,7 @@ def test_secondary_source_templates_use_named_dependency_and_isolated_metadata(
assert 'from common.mixin import' not in entity
compile(entity, '', 'exec')
dao = env.get_template('python/dao.py.jinja2').render(**context)
- assert 'if key not in set()' in dao
+ assert 'await db.execute(update(GenItem), [item])' in dao
compile(dao, '', 'exec')
compile(controller, '', 'exec')
@@ -271,13 +271,13 @@ def test_python_templates_handle_audit_timestamps_by_exact_column_name() -> None
dao = env.get_template('python/dao.py.jinja2').render(**context)
controller = env.get_template('python/controller.py.jinja2').render(**context)
- assert 'from datetime import datetime' not in entity
+ assert 'from datetime import datetime' in entity
assert 'from common.mixin import AuditTimeMixin' in entity
assert 'class GenItem(AuditTimeMixin, Base):' in entity
- assert 'create_time = Column(' not in entity
- assert 'update_time = Column(' not in entity
+ assert 'create_time: Mapped[' not in entity
+ assert 'update_time: Mapped[' not in entity
assert 'from common.types import DbUtcDateTime' in entity
- assert 'created_time = Column(DbUtcDateTime(), nullable=True, comment=' in entity
+ assert 'created_time: Mapped[datetime | None] = mapped_column(DbUtcDateTime(), nullable=True, comment=' in entity
assert "model_dump(exclude={'create_time', 'update_time'})" in dao
assert "if key not in {'create_time', 'update_time'}" in dao
assert 'create_time = datetime.now()' not in controller
@@ -325,7 +325,7 @@ def test_dao_audit_filter_uses_a_set_for_a_single_timestamp() -> None:
assert 'from common.mixin import CreateTimeMixin' in entity
assert 'class GenItem(CreateTimeMixin, Base):' in entity
- assert 'create_time = Column(' not in entity
+ assert 'create_time: Mapped[' not in entity
assert "if key not in {'create_time'}" in dao
compile(entity, '', 'exec')
compile(dao, '', 'exec')
@@ -419,13 +419,13 @@ def test_sub_table_entity_template_uses_required_nullable_semantics() -> None:
entity = env.get_template('python/do.py.jinja2').render(**context)
dao = env.get_template('python/dao.py.jinja2').render(**context)
- assert "required_value = Column(String(100), nullable=False, comment='必填值')" in entity
- assert "optional_value = Column(String(100), nullable=True, comment='可选值')" in entity
+ assert "required_value: Mapped[str] = mapped_column(String(100), nullable=False, comment='必填值')" in entity
+ assert "optional_value: Mapped[str | None] = mapped_column(String(100), nullable=True, comment='可选值')" in entity
assert 'from common.mixin import AuditTimeMixin' in entity
assert 'class GenItemDetail(AuditTimeMixin, Base):' in entity
assert '__create_time_nullable__ = False' in entity
- assert 'create_time = Column(' not in entity
- assert 'update_time = Column(' not in entity
+ assert 'create_time: Mapped[' not in entity
+ assert 'update_time: Mapped[' not in entity
assert "model_dump(exclude={'create_time', 'update_time'})" in dao
assert "if key not in {'create_time', 'update_time'}" in dao
compile(entity, '', 'exec')
diff --git a/ruoyi-fastapi-backend/utils/common_util.py b/ruoyi-fastapi-backend/utils/common_util.py
index 9d4ee07c8..6dfc5ce21 100644
--- a/ruoyi-fastapi-backend/utils/common_util.py
+++ b/ruoyi-fastapi-backend/utils/common_util.py
@@ -10,10 +10,10 @@
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.datavalidation import DataValidation
from sqlalchemy.engine.row import Row
+from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm.collections import InstrumentedList
from sqlalchemy.sql.expression import Null, null
-from config.database import Base
from config.env import CachePathConfig
from utils.log_util import logger
@@ -52,7 +52,7 @@ class SqlalchemyUtil:
@classmethod
def base_to_dict(
cls,
- obj: Base | dict[Any, Any],
+ obj: DeclarativeBase | dict[Any, Any],
transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case',
) -> dict[Any, Any]:
"""
@@ -62,7 +62,7 @@ def base_to_dict(
:param transform_case: 转换得到的结果形式,可选的有'no_case'(不转换)、'snake_to_camel'(下划线转小驼峰)、'camel_to_snake'(小驼峰转下划线),默认为'no_case'
:return: 字典结果
"""
- if isinstance(obj, Base):
+ if isinstance(obj, DeclarativeBase):
base_dict = obj.__dict__.copy()
base_dict.pop('_sa_instance_state', None)
for name, value in base_dict.items():
@@ -80,7 +80,7 @@ def base_to_dict(
@classmethod
@overload
def serialize_result(
- cls, result: Base, transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case'
+ cls, result: DeclarativeBase, transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case'
) -> dict[str, Any]: ...
@classmethod
@@ -100,7 +100,9 @@ def serialize_result(
@classmethod
@overload
def serialize_result(
- cls, result: Sequence[Base], transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case'
+ cls,
+ result: Sequence[DeclarativeBase],
+ transform_case: Literal['no_case', 'snake_to_camel', 'camel_to_snake'] = 'no_case',
) -> list[dict[str, Any]]: ...
@classmethod
@@ -142,14 +144,14 @@ def serialize_result(
:param transform_case: 转换得到的结果形式,可选的有'no_case'(不转换)、'snake_to_camel'(下划线转小驼峰)、'camel_to_snake'(小驼峰转下划线),默认为'no_case'
:return: 序列化结果
"""
- if isinstance(result, (Base, dict)):
+ if isinstance(result, (DeclarativeBase, dict)):
return cls.base_to_dict(result, transform_case)
if isinstance(result, list):
return [cls.serialize_result(row, transform_case) for row in result]
if isinstance(result, Row):
- if all(isinstance(row, Base) for row in result):
+ if all(isinstance(row, DeclarativeBase) for row in result):
return [cls.base_to_dict(row, transform_case) for row in result]
- if any(isinstance(row, Base) for row in result):
+ if any(isinstance(row, DeclarativeBase) for row in result):
return [cls.serialize_result(row, transform_case) for row in result]
result_dict = result._asdict()
if transform_case == 'snake_to_camel':
@@ -191,7 +193,7 @@ def snake_to_camel(cls, snake_str: str) -> str:
@classmethod
@overload
- def transform_result(cls, result: Base) -> dict[str, Any]: ...
+ def transform_result(cls, result: DeclarativeBase) -> dict[str, Any]: ...
@classmethod
@overload
@@ -203,7 +205,7 @@ def transform_result(cls, result: Row[*tuple[Any, ...]]) -> dict[str, Any] | lis
@classmethod
@overload
- def transform_result(cls, result: Sequence[Base]) -> list[dict[str, Any]]: ...
+ def transform_result(cls, result: Sequence[DeclarativeBase]) -> list[dict[str, Any]]: ...
@classmethod
@overload
@@ -251,7 +253,7 @@ def camel_to_snake(cls, camel_str: str) -> str:
@classmethod
@overload
- def transform_result(cls, result: Base) -> dict[str, Any]: ...
+ def transform_result(cls, result: DeclarativeBase) -> dict[str, Any]: ...
@classmethod
@overload
@@ -263,7 +265,7 @@ def transform_result(cls, result: Row[*tuple[Any, ...]]) -> dict[str, Any] | lis
@classmethod
@overload
- def transform_result(cls, result: Sequence[Base]) -> list[dict[str, Any]]: ...
+ def transform_result(cls, result: Sequence[DeclarativeBase]) -> list[dict[str, Any]]: ...
@classmethod
@overload
diff --git a/ruoyi-fastapi-backend/utils/gen_util.py b/ruoyi-fastapi-backend/utils/gen_util.py
index 0145e4eb5..cc402f137 100644
--- a/ruoyi-fastapi-backend/utils/gen_util.py
+++ b/ruoyi-fastapi-backend/utils/gen_util.py
@@ -1,4 +1,8 @@
import re
+import subprocess
+import sys
+from pathlib import Path
+from tempfile import TemporaryDirectory
from common.constant import GenConstant
from config.env import DataBaseConfig, GenConfig
@@ -17,6 +21,34 @@ class GenUtils:
TEXTAREA_COLUMN_LENGTH = 500
+ @staticmethod
+ def format_generated_python(files: dict[str, str]) -> dict[str, str]:
+ """
+ 使用后端 Ruff 配置批量排版一组生成文件中的 Python 源码。
+
+ :param files: 以模板名或输出路径为键的生成内容
+ :return: 保持原有文件顺序的排版结果
+ """
+ names = [name for name, source in files.items() if name.endswith(('.py', '.py.jinja2')) and source]
+ if not names:
+ return files
+ formatted = files.copy()
+ config = Path(__file__).resolve().parents[1] / 'ruff.toml'
+ with TemporaryDirectory() as directory:
+ # 仅使用内部编号创建临时文件,生成配置中的路径不参与磁盘寻址。
+ paths = [Path(directory) / f'{index}.py' for index in range(len(names))]
+ for name, path in zip(names, paths, strict=True):
+ path.write_text(files[name], encoding='utf-8')
+ subprocess.run(
+ [sys.executable, '-m', 'ruff', 'format', '--no-cache', '--config', str(config), *paths],
+ check=True,
+ cwd=directory,
+ stdout=subprocess.DEVNULL,
+ )
+ for name, path in zip(names, paths, strict=True):
+ formatted[name] = path.read_text(encoding='utf-8')
+ return formatted
+
@staticmethod
def require_metadata(value: str | None) -> str:
"""
diff --git a/ruoyi-fastapi-backend/utils/page_util.py b/ruoyi-fastapi-backend/utils/page_util.py
index f7661a705..8b0f0b556 100644
--- a/ruoyi-fastapi-backend/utils/page_util.py
+++ b/ruoyi-fastapi-backend/utils/page_util.py
@@ -3,14 +3,14 @@
from sqlalchemy import Select, func, select
from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import DeclarativeBase
from common.vo import PageModel
-from config.database import Base
from utils.common_util import CamelCaseUtil
_Item = TypeVar('_Item')
-_Entity = TypeVar('_Entity', bound=Base)
-_JoinedEntity = TypeVar('_JoinedEntity', bound=Base)
+_Entity = TypeVar('_Entity', bound=DeclarativeBase)
+_JoinedEntity = TypeVar('_JoinedEntity', bound=DeclarativeBase)
_EntityPairs = list[list[dict[str, Any] | None]]
_Rows = list[dict[str, Any] | list[dict[Any, Any]]] | list[dict[str, Any]] | _EntityPairs
diff --git a/ruoyi-fastapi-backend/utils/template_util.py b/ruoyi-fastapi-backend/utils/template_util.py
index e2395fd9d..a972b61ba 100644
--- a/ruoyi-fastapi-backend/utils/template_util.py
+++ b/ruoyi-fastapi-backend/utils/template_util.py
@@ -88,7 +88,7 @@ def prepare_context(cls, gen_table: GenTableModel) -> dict[str, Any]:
column.column_comment = {'create_time': '创建时间', 'update_time': '更新时间'}.get(
column.column_name, f'字段 {column.column_name}'
)
- cls.prepare_time_columns(gen_table)
+ cls.prepare_column_types(gen_table)
class_name = GenUtils.require_metadata(gen_table.class_name)
module_name = GenUtils.require_metadata(gen_table.module_name)
business_name = GenUtils.require_metadata(gen_table.business_name)
@@ -136,6 +136,7 @@ def prepare_context(cls, gen_table: GenTableModel) -> dict[str, Any]:
else [],
'table': gen_table,
'dicts': cls.get_dicts(gen_table),
+ 'exportDictTypes': sorted({col.dict_type for col in gen_table.columns or [] if col.dict_type}),
'dbType': source_config.db_type,
'dataSourceName': source_name,
'defaultDataSourceName': default_source_name,
@@ -182,9 +183,9 @@ def model_field_label(comment: str) -> str:
return comment if re.search(r'[\u3400-\u9fff\U00020000-\U0002fa1f]', comment) else f'字段 {comment}'
@classmethod
- def prepare_time_columns(cls, gen_table: GenTableModel) -> None:
+ def prepare_column_types(cls, gen_table: GenTableModel) -> None:
"""
- 规范化模板副本中的主表和子表时间字段。
+ 准备主表、子表及主键的 Python 类型和时间字段语义。
只处理模板副本,不改写数据库中保存的生成配置。
@@ -195,13 +196,20 @@ def prepare_time_columns(cls, gen_table: GenTableModel) -> None:
for table in [gen_table, gen_table.sub_table]:
if table is None:
continue
- for column in table.columns or []:
+ columns = list(table.columns or [])
+ if table.pk_column is not None:
+ columns.append(table.pk_column)
+ for column in columns:
try:
column_type = GenUtils.require_metadata(column.column_type)
semantics = GenTimeUtil.get_time_semantics(column_type, db_type)
GenTimeUtil.validate_time_control(column_type, db_type, column.html_type)
except ServiceWarning as exc:
raise ServiceWarning(message=f'{table.table_name}.{column.column_name}: {exc.message}') from exc
+ if column.python_type == 'dict':
+ column.python_type = 'dict[str, object]'
+ elif column.python_type == 'list':
+ column.python_type = 'list[object]'
column.vo_type = column.python_type
if semantics:
column.time_kind = semantics.kind
@@ -308,6 +316,18 @@ def get_template_list(cls, gen_table: GenTableModel) -> list[str]:
templates.append(f'{use_web_type}/view.{extension}.jinja2')
return templates
+ @staticmethod
+ def render_templates(env: Environment, templates: list[str], context: dict[str, Any]) -> dict[str, str]:
+ """
+ 使用同一份上下文渲染模板,并按项目规则排版 Python 产物。
+
+ :param env: 代码生成模板环境
+ :param templates: 已选择的模板名称
+ :param context: 当前表的渲染上下文
+ :return: 按模板名索引的生成文件内容
+ """
+ return GenUtils.format_generated_python({name: env.get_template(name).render(**context) for name in templates})
+
@classmethod
def get_file_name(cls, template: str, gen_table: GenTableModel) -> str:
"""
@@ -372,8 +392,10 @@ def get_vo_import_list(cls, gen_table: GenTableModel) -> list[str]:
semantics = GenTimeUtil.get_time_semantics(GenUtils.require_metadata(column.column_type), db_type)
if semantics:
import_list.add(f'from common.types import {semantics.vo_type}')
- if table is gen_table and column.query_type == 'BETWEEN':
+ if table is gen_table and column.query_type == 'BETWEEN' and semantics.kind == 'instant':
import_list.add('from common.types import BusinessDate')
+ elif column.python_type == 'timedelta':
+ import_list.add('from datetime import timedelta')
elif column.python_type == GenConstant.TYPE_DECIMAL:
import_list.add('from decimal import Decimal')
return cls.merge_same_imports(sorted(import_list), 'from common.types import')
@@ -386,19 +408,20 @@ def get_do_import_list(cls, gen_table: GenTableModel) -> list[str]:
:param gen_table: 生成表配置信息
:return: 已合并同源导入的语句列表
"""
- import_list = {'from sqlalchemy import Column'}
- if gen_table.sub:
- import_list.add('from sqlalchemy import ForeignKey')
- for table in [gen_table, gen_table.sub_table]:
- if table is None:
- continue
+ import_list = {'from sqlalchemy import ForeignKey'} if gen_table.sub else set()
+ for table in filter(None, (gen_table, gen_table.sub_table)):
for column in table.columns or []:
sqlalchemy_type = cls.get_sqlalchemy_type(
GenUtils.require_metadata(column.column_type), gen_table.data_source_name
)
+ if sqlalchemy_type == 'DbUtcDateTime' and column.column_name in {'create_time', 'update_time'}:
+ continue
+ if column.python_type in [*GenConstant.TYPE_DATE, 'timedelta']:
+ import_list.add(f'from datetime import {column.python_type}')
+ elif column.python_type == GenConstant.TYPE_DECIMAL:
+ import_list.add('from decimal import Decimal')
if sqlalchemy_type == 'DbUtcDateTime':
- if column.column_name not in {'create_time', 'update_time'}:
- import_list.add('from common.types import DbUtcDateTime')
+ import_list.add('from common.types import DbUtcDateTime')
elif sqlalchemy_type == 'Geometry':
import_list.add('from geoalchemy2 import Geometry')
elif sqlalchemy_type.startswith('TIME('):
@@ -408,7 +431,10 @@ def get_do_import_list(cls, gen_table: GenTableModel) -> list[str]:
import_list.add(f'from sqlalchemy.dialects.postgresql import {sqlalchemy_type}')
else:
import_list.add(f'from sqlalchemy import {sqlalchemy_type.split("(", 1)[0]}')
- return cls.merge_same_imports(sorted(import_list), 'from sqlalchemy import')
+ imports = sorted(import_list)
+ for prefix in ('from datetime import', 'from sqlalchemy import', 'from sqlalchemy.dialects.postgresql import'):
+ imports = cls.merge_same_imports(imports, prefix)
+ return sorted(imports)
@classmethod
def get_db_type(cls, column_type: str) -> str:
@@ -439,8 +465,8 @@ def merge_same_imports(cls, imports: list[str], import_start: str) -> list[str]:
merged_imports.append(import_stmt)
if _imports:
- merged_datetime_import = f'{import_start} {", ".join(_imports)}'
- merged_imports.append(merged_datetime_import)
+ _imports.sort(key=lambda name: (not name.isupper(), name.lower()))
+ merged_imports.append(f'{import_start} {", ".join(_imports)}')
return merged_imports
From 692f69fed27641d9a0759900574f85acfb035825 Mon Sep 17 00:00:00 2001
From: insistence <3055204202@qq.com>
Date: Thu, 26 Nov 2026 12:01:02 +0800
Subject: [PATCH 7/9] =?UTF-8?q?refactor:=20=E5=90=AF=E7=94=A8=20ty=20?=
=?UTF-8?q?=E7=9A=84=20dynamic-function-decorator-return=20=E8=A7=84?=
=?UTF-8?q?=E5=88=99=E5=B9=B6=E4=BF=AE=E5=A4=8D=E6=B5=8B=E8=AF=95=E7=B1=BB?=
=?UTF-8?q?=E5=9E=8B?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.github/ty.toml | 1 +
ruoyi-fastapi-backend/requirements-pg.txt | 2 +-
ruoyi-fastapi-backend/requirements.txt | 2 +-
ruoyi-fastapi-backend/tests/auth_helpers.py | 17 ++++
.../tests/common/test_pre_auth.py | 76 +++++++--------
.../test_current_user_cache_integration.py | 94 ++++++++++++-------
.../service/test_current_user_resolution.py | 70 ++++++++++----
.../core/runtime/test_connection_sessions.py | 6 +-
.../plugins/integration/test_network_smoke.py | 9 +-
.../tests/test_api_docs_auth.py | 73 +++++++-------
ruoyi-fastapi-backend/ty.toml | 1 +
ruoyi-fastapi-test/ty.toml | 1 +
ty.toml | 1 +
13 files changed, 223 insertions(+), 130 deletions(-)
create mode 100644 ruoyi-fastapi-backend/tests/auth_helpers.py
diff --git a/.github/ty.toml b/.github/ty.toml
index 11c711b38..38706c274 100644
--- a/.github/ty.toml
+++ b/.github/ty.toml
@@ -5,6 +5,7 @@ python-version = "3.11"
[rules]
blanket-ignore-comment = "error"
disjoint-cast = "error"
+dynamic-function-decorator-return = "error"
mismatched-enum-name = "error"
mismatched-namedtuple-name = "error"
mismatched-sentinel-name = "error"
diff --git a/ruoyi-fastapi-backend/requirements-pg.txt b/ruoyi-fastapi-backend/requirements-pg.txt
index 447ad4138..d3a5d24ca 100644
--- a/ruoyi-fastapi-backend/requirements-pg.txt
+++ b/ruoyi-fastapi-backend/requirements-pg.txt
@@ -16,7 +16,7 @@ Pillow==13.0.0
psutil==7.2.2
psycopg2==2.9.13
pydantic==2.14.4
-pydantic-validation-decorator==0.1.5
+pydantic-validation-decorator==0.2.0
PyJWT[crypto]==2.15.1
redis==8.1.0
ruff==0.17.6
diff --git a/ruoyi-fastapi-backend/requirements.txt b/ruoyi-fastapi-backend/requirements.txt
index 3f0201ce6..84a7bd1f5 100644
--- a/ruoyi-fastapi-backend/requirements.txt
+++ b/ruoyi-fastapi-backend/requirements.txt
@@ -15,7 +15,7 @@ pandas==3.1.1
Pillow==13.0.0
psutil==7.2.2
pydantic==2.14.4
-pydantic-validation-decorator==0.1.5
+pydantic-validation-decorator==0.2.0
PyJWT[crypto]==2.15.1
PyMySQL==1.2.4
redis==8.1.0
diff --git a/ruoyi-fastapi-backend/tests/auth_helpers.py b/ruoyi-fastapi-backend/tests/auth_helpers.py
new file mode 100644
index 000000000..bc56ff74f
--- /dev/null
+++ b/ruoyi-fastapi-backend/tests/auth_helpers.py
@@ -0,0 +1,17 @@
+from dataclasses import dataclass
+from unittest.mock import AsyncMock
+
+from fastapi import FastAPI
+
+
+@dataclass
+class AuthTestApp:
+ """
+ 使用模拟认证服务的 FastAPI 测试应用。
+
+ :ivar app: 注册路由和认证依赖的应用
+ :ivar resolver: 记录当前用户解析调用的异步替身
+ """
+
+ app: FastAPI
+ resolver: AsyncMock
diff --git a/ruoyi-fastapi-backend/tests/common/test_pre_auth.py b/ruoyi-fastapi-backend/tests/common/test_pre_auth.py
index b842ad00b..183cbd976 100644
--- a/ruoyi-fastapi-backend/tests/common/test_pre_auth.py
+++ b/ruoyi-fastapi-backend/tests/common/test_pre_auth.py
@@ -23,6 +23,7 @@
from module_admin.entity.vo.role_vo import RoleModel
from module_admin.entity.vo.user_vo import CurrentUserModel, UserInfoModel
from module_admin.service.login_service import LoginService, oauth2_scheme
+from tests.auth_helpers import AuthTestApp
from utils.dependency_util import DependencyUtil
if TYPE_CHECKING:
@@ -52,7 +53,7 @@ def _user(user_id: int) -> CurrentUserModel:
@pytest.fixture
-def auth_app(monkeypatch: pytest.MonkeyPatch) -> Iterator[SimpleNamespace]:
+def auth_app(monkeypatch: pytest.MonkeyPatch) -> Iterator[AuthTestApp]:
"""
构建带认证依赖和异常处理的测试应用。
@@ -162,14 +163,14 @@ async def excluded_current(user: Annotated[CurrentUserModel, CurrentUserDependen
return {'userId': user.user.user_id}
try:
- yield SimpleNamespace(app=app, resolver=resolver)
+ yield AuthTestApp(app=app, resolver=resolver)
finally:
RequestContext.clear_all()
@pytest.mark.asyncio
@pytest.mark.parametrize('path', ['/both', '/current', '/pre', '/direct'])
-async def test_request_authentication_runs_once(auth_app: SimpleNamespace, path: str) -> None:
+async def test_request_authentication_runs_once(auth_app: AuthTestApp, path: str) -> None:
"""单个请求只认证一次。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
response = await client.get(path, headers={'Authorization': 'Bearer alice'})
@@ -182,7 +183,7 @@ async def test_request_authentication_runs_once(auth_app: SimpleNamespace, path:
@pytest.mark.asyncio
-async def test_new_requests_reauthenticate_even_with_the_same_token(auth_app: SimpleNamespace) -> None:
+async def test_new_requests_reauthenticate_even_with_the_same_token(auth_app: AuthTestApp) -> None:
"""同一令牌发起新请求仍需重新认证。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
for _ in range(2):
@@ -194,7 +195,7 @@ async def test_new_requests_reauthenticate_even_with_the_same_token(auth_app: Si
@pytest.mark.asyncio
-async def test_parallel_requests_keep_user_and_context_separate(auth_app: SimpleNamespace) -> None:
+async def test_parallel_requests_keep_user_and_context_separate(auth_app: AuthTestApp) -> None:
"""并发请求隔离用户及上下文。"""
tokens = ['alice', 'bob', 'alice', 'bob']
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -210,7 +211,7 @@ async def test_parallel_requests_keep_user_and_context_separate(auth_app: Simple
@pytest.mark.asyncio
-async def test_excluded_route_keeps_path_method_and_ignore_rules(auth_app: SimpleNamespace) -> None:
+async def test_excluded_route_keeps_path_method_and_ignore_rules(auth_app: AuthTestApp) -> None:
"""排除路由时同时考虑路径、方法和忽略规则。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
response = await client.get('/public/free')
@@ -226,7 +227,7 @@ async def test_excluded_route_keeps_path_method_and_ignore_rules(auth_app: Simpl
@pytest.mark.asyncio
@pytest.mark.parametrize('path', ['/both', '/current', '/pre'])
-async def test_missing_token_preserves_existing_auth_response(auth_app: SimpleNamespace, path: str) -> None:
+async def test_missing_token_preserves_existing_auth_response(auth_app: AuthTestApp, path: str) -> None:
"""缺少令牌时返回约定的认证响应。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
response = await client.get(path)
@@ -242,7 +243,7 @@ async def test_missing_token_preserves_existing_auth_response(auth_app: SimpleNa
@pytest.mark.parametrize('authorization', ['Bearer invalid', 'Basic alice', 'Bearer'])
@pytest.mark.parametrize('path', ['/both', '/current', '/pre'])
async def test_invalid_token_and_header_cannot_reuse_authentication(
- auth_app: SimpleNamespace, authorization: str, path: str
+ auth_app: AuthTestApp, authorization: str, path: str
) -> None:
"""无效令牌或请求头无法复用认证结果。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -252,7 +253,7 @@ async def test_invalid_token_and_header_cannot_reuse_authentication(
assert denied.json()['code'] == status.HTTP_401_UNAUTHORIZED
-def test_current_user_dependency_keeps_original_oauth_token_url(auth_app: SimpleNamespace) -> None:
+def test_current_user_dependency_keeps_original_oauth_token_url(auth_app: AuthTestApp) -> None:
"""当前用户依赖保留原 OAuth 令牌地址。"""
security = auth_app.app.openapi()['components']['securitySchemes']['OAuth2PasswordBearer']
assert security['flows']['password']['tokenUrl'] == 'login'
@@ -323,7 +324,7 @@ async def blocked(*args: object, **kwargs: object) -> CurrentUserModel:
@pytest.mark.asyncio
async def test_excluded_route_matches_configured_root_path(
- auth_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+ auth_app: AuthTestApp, monkeypatch: pytest.MonkeyPatch
) -> None:
"""排除规则能匹配配置的根路径。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '/dev-api')
@@ -337,7 +338,7 @@ async def test_excluded_route_matches_configured_root_path(
@pytest.mark.asyncio
-async def test_original_dependency_override_applies_to_both_declarations(auth_app: SimpleNamespace) -> None:
+async def test_original_dependency_override_applies_to_both_declarations(auth_app: AuthTestApp) -> None:
"""原依赖覆盖对两处声明同时生效。"""
user = _user(USER_IDS['bob'])
override_calls = []
@@ -445,7 +446,7 @@ async def protected() -> None:
@pytest.mark.asyncio
-async def test_use_cache_false_reauthenticates_after_pre_auth(auth_app: SimpleNamespace) -> None:
+async def test_use_cache_false_reauthenticates_after_pre_auth(auth_app: AuthTestApp) -> None:
"""禁用缓存后在预认证完成时重新认证。"""
@auth_app.app.get(
@@ -478,7 +479,7 @@ async def fresh(
@pytest.mark.asyncio
-async def test_use_cache_false_does_not_fall_back_to_previous_success(auth_app: SimpleNamespace) -> None:
+async def test_use_cache_false_does_not_fall_back_to_previous_success(auth_app: AuthTestApp) -> None:
"""禁用缓存后无法沿用上次成功结果。"""
@auth_app.app.get(
@@ -508,7 +509,7 @@ async def fresh_denied(
@pytest.mark.asyncio
async def test_later_pre_auth_cannot_restore_permissions_before_forced_authentication(
- auth_app: SimpleNamespace,
+ auth_app: AuthTestApp,
) -> None:
"""后续预认证无法在强制认证前恢复权限。"""
initial_user = _user(USER_IDS['bob'])
@@ -570,7 +571,7 @@ async def revoked_permissions(
@pytest.mark.asyncio
@pytest.mark.parametrize('authorization', [None, 'Bearer alice', 'Bearer invalid', 'Basic invalid'])
-async def test_public_route_never_authenticates(auth_app: SimpleNamespace, authorization: str | None) -> None:
+async def test_public_route_never_authenticates(auth_app: AuthTestApp, authorization: str | None) -> None:
"""公开路由无需认证。"""
headers = {'Authorization': authorization} if authorization is not None else {}
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -581,7 +582,7 @@ async def test_public_route_never_authenticates(auth_app: SimpleNamespace, autho
@pytest.mark.asyncio
-async def test_explicit_current_user_still_authenticates_on_excluded_route(auth_app: SimpleNamespace) -> None:
+async def test_explicit_current_user_still_authenticates_on_excluded_route(auth_app: AuthTestApp) -> None:
"""排除路由中显式请求当前用户仍触发认证。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
response = await client.get('/excluded-current', headers={'Authorization': 'Bearer bob'})
@@ -592,7 +593,7 @@ async def test_explicit_current_user_still_authenticates_on_excluded_route(auth_
@pytest.mark.asyncio
-async def test_nested_current_user_dependency_requires_login_on_excluded_route(auth_app: SimpleNamespace) -> None:
+async def test_nested_current_user_dependency_requires_login_on_excluded_route(auth_app: AuthTestApp) -> None:
"""排除路由中嵌套的当前用户依赖仍要求登录。"""
async def identity(user: Annotated[CurrentUserModel, Depends(LoginService.get_current_user)]) -> int:
@@ -629,7 +630,7 @@ async def nested(user_id: Annotated[int, Depends(identity)]) -> dict[str, object
@pytest.mark.asyncio
async def test_override_cannot_add_authentication_to_an_excluded_dependency_without_login(
- auth_app: SimpleNamespace,
+ auth_app: AuthTestApp,
) -> None:
"""覆盖排除的依赖时不能绕开登录而追加认证。"""
@@ -686,7 +687,7 @@ async def test_direct_call_without_a_token_requires_login() -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize('excluded_first', [True, False])
async def test_excluded_pre_auth_cannot_cancel_another_auth_requirement(
- auth_app: SimpleNamespace, excluded_first: bool
+ auth_app: AuthTestApp, excluded_first: bool
) -> None:
"""排除一处预认证不能取消其他认证要求。"""
dependencies = [PreAuthDependency([{'path': '/mixed'}]), PreAuthDependency()]
@@ -717,7 +718,7 @@ async def mixed() -> dict[str, object]:
@pytest.mark.asyncio
-async def test_multiple_excluded_pre_auth_dependencies_do_not_require_login(auth_app: SimpleNamespace) -> None:
+async def test_multiple_excluded_pre_auth_dependencies_do_not_require_login(auth_app: AuthTestApp) -> None:
"""多个被排除的预认证依赖不要求登录。"""
@auth_app.app.get(
@@ -746,7 +747,7 @@ async def public() -> dict[str, bool]:
@pytest.mark.asyncio
@pytest.mark.parametrize('pre_auth_first', [True, False])
async def test_first_required_dependency_keeps_missing_token_response(
- auth_app: SimpleNamespace, pre_auth_first: bool
+ auth_app: AuthTestApp, pre_auth_first: bool
) -> None:
"""由首个强制认证依赖决定缺少令牌的响应。"""
dependencies = [PreAuthDependency(), CurrentUserDependency()]
@@ -776,7 +777,7 @@ async def ordered() -> dict[str, bool]:
@pytest.mark.asyncio
-async def test_failed_request_does_not_reuse_a_previous_authentication(auth_app: SimpleNamespace) -> None:
+async def test_failed_request_does_not_reuse_a_previous_authentication(auth_app: AuthTestApp) -> None:
"""失败请求无法复用先前认证。"""
authenticate = auth_app.resolver.side_effect
auth_app.resolver.side_effect = AuthException(message='认证失败')
@@ -790,7 +791,7 @@ async def test_failed_request_does_not_reuse_a_previous_authentication(auth_app:
@pytest.mark.asyncio
-async def test_cancelled_request_does_not_affect_following_authentication(auth_app: SimpleNamespace) -> None:
+async def test_cancelled_request_does_not_affect_following_authentication(auth_app: AuthTestApp) -> None:
"""取消请求后不影响后续认证。"""
authenticate = auth_app.resolver.side_effect
entered = asyncio.Event()
@@ -821,7 +822,7 @@ async def blocked(*args: object, **kwargs: object) -> CurrentUserModel:
@pytest.mark.asyncio
-async def test_interface_role_and_data_permissions_are_still_checked(auth_app: SimpleNamespace) -> None:
+async def test_interface_role_and_data_permissions_are_still_checked(auth_app: AuthTestApp) -> None:
"""接口权限、角色和数据权限均被检查。"""
@auth_app.app.get(
@@ -880,7 +881,7 @@ async def forbidden() -> dict[str, object]:
@pytest.mark.parametrize('path', ['/pre', '/both', '/current'])
@pytest.mark.parametrize('scheme', ['Bearer', 'bearer', 'BEARER'])
async def test_authentication_accepts_standard_bearer_scheme_case_insensitively(
- auth_app: SimpleNamespace, path: str, scheme: str
+ auth_app: AuthTestApp, path: str, scheme: str
) -> None:
"""Bearer 认证方案忽略大小写。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -888,6 +889,7 @@ async def test_authentication_accepts_standard_bearer_scheme_case_insensitively(
assert response.status_code == status.HTTP_200_OK
assert response.json()['userId'] == USER_IDS['alice']
auth_app.resolver.assert_awaited_once()
+ assert auth_app.resolver.await_args is not None
assert auth_app.resolver.await_args.args[1] == 'alice'
@@ -895,7 +897,7 @@ async def test_authentication_accepts_standard_bearer_scheme_case_insensitively(
@pytest.mark.parametrize('path', ['/pre', '/both', '/current'])
@pytest.mark.parametrize('authorization', ['alice', 'Basic alice'])
async def test_authentication_rejects_non_bearer_authorization(
- auth_app: SimpleNamespace, path: str, authorization: str
+ auth_app: AuthTestApp, path: str, authorization: str
) -> None:
"""认证拒绝非 Bearer 授权头。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=auth_app.app), base_url='http://test') as client:
@@ -909,7 +911,7 @@ async def test_authentication_rejects_non_bearer_authorization(
@pytest.mark.asyncio
@pytest.mark.parametrize('excluded', [False, True])
async def test_explicit_oauth_dependency_returns_bare_token_and_still_requires_login(
- auth_app: SimpleNamespace, excluded: bool
+ auth_app: AuthTestApp, excluded: bool
) -> None:
"""显式 OAuth 依赖返回纯令牌并要求登录。"""
exclude_routes: list[ExcludeRoute] | None = [{'path': '/token'}] if excluded else None
@@ -939,7 +941,7 @@ async def token_endpoint(token: Annotated[str, Depends(oauth2_scheme)]) -> dict[
@pytest.mark.asyncio
-async def test_unrelated_override_keeps_an_excluded_route_public(auth_app: SimpleNamespace) -> None:
+async def test_unrelated_override_keeps_an_excluded_route_public(auth_app: AuthTestApp) -> None:
"""无关依赖覆盖后排除路由仍可公开访问。"""
async def language() -> str:
@@ -979,7 +981,7 @@ async def public(locale: Annotated[str, Depends(language)]) -> dict[str, object]
@pytest.mark.parametrize('nested', [False, True])
@pytest.mark.parametrize('requirement', ['current_user', 'pre_auth', 'oauth'])
async def test_parent_router_authentication_cannot_be_excluded_by_child(
- auth_app: SimpleNamespace, nested: bool, requirement: str
+ auth_app: AuthTestApp, nested: bool, requirement: str
) -> None:
"""子路由无法排除父路由的认证要求。"""
users = []
@@ -1022,7 +1024,7 @@ async def profile() -> dict[str, bool]:
@pytest.mark.asyncio
-async def test_router_inclusions_keep_their_own_authentication_requirements(auth_app: SimpleNamespace) -> None:
+async def test_router_inclusions_keep_their_own_authentication_requirements(auth_app: AuthTestApp) -> None:
"""分别挂载的路由保留各自的认证要求。"""
async def require_user(user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> None:
@@ -1056,7 +1058,7 @@ async def info() -> dict[str, bool]:
@pytest.mark.asyncio
-async def test_parent_override_added_authentication_is_required(auth_app: SimpleNamespace) -> None:
+async def test_parent_override_added_authentication_is_required(auth_app: AuthTestApp) -> None:
"""父级依赖覆盖增加的认证必须执行。"""
async def identity() -> None:
@@ -1090,7 +1092,7 @@ async def public() -> dict[str, bool]:
@pytest.mark.asyncio
@pytest.mark.parametrize('root_path', ['', '/api'])
async def test_business_prefix_is_not_removed_as_a_deployment_prefix(
- auth_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, root_path: str
+ auth_app: AuthTestApp, monkeypatch: pytest.MonkeyPatch, root_path: str
) -> None:
"""识别部署路径时保留业务前缀。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '/api')
@@ -1116,7 +1118,7 @@ async def endpoint() -> dict[str, bool]:
@pytest.mark.asyncio
@pytest.mark.parametrize('root_path', ['', '/api'])
async def test_deployment_prefix_requires_a_path_segment_boundary(
- auth_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, root_path: str
+ auth_app: AuthTestApp, monkeypatch: pytest.MonkeyPatch, root_path: str
) -> None:
"""部署前缀必须匹配完整路径段。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '/api')
@@ -1146,7 +1148,7 @@ async def public() -> dict[str, bool]:
@pytest.mark.parametrize('root_path', ['', '/api'])
@pytest.mark.parametrize('permission', ['interface', 'role', 'data_scope'])
async def test_permission_dependencies_use_the_same_excluded_application_path(
- auth_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, root_path: str, permission: str
+ auth_app: AuthTestApp, monkeypatch: pytest.MonkeyPatch, root_path: str, permission: str
) -> None:
"""权限依赖使用相同的应用内排除路径。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '/api')
@@ -1192,7 +1194,7 @@ async def endpoint() -> dict[str, bool]:
)
@pytest.mark.parametrize('ignore_path', [False, True])
async def test_encoded_path_separators_cannot_expand_public_routes(
- auth_app: SimpleNamespace, root_path: str, encoded: str, decoded: str, ignore_path: bool
+ auth_app: AuthTestApp, root_path: str, encoded: str, decoded: str, ignore_path: bool
) -> None:
"""编码后的分隔符无法扩大公开路由范围。"""
protected_path = f'/encoded/public{decoded}'
@@ -1234,7 +1236,7 @@ async def endpoint(name: str) -> dict[str, object]:
[('%23private', '#private'), ('%3Fprivate', '?private'), ('%0A', '\n'), ('%0D', '\r'), ('%09', '\t')],
)
async def test_permission_check_uses_the_full_decoded_path(
- auth_app: SimpleNamespace, root_path: str, encoded: str, decoded: str
+ auth_app: AuthTestApp, root_path: str, encoded: str, decoded: str
) -> None:
"""权限校验使用完整解码路径。"""
@@ -1272,7 +1274,7 @@ async def endpoint(name: str) -> dict[str, object]:
@pytest.mark.asyncio
async def test_mounted_application_uses_its_asgi_root_path(
- auth_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+ auth_app: AuthTestApp, monkeypatch: pytest.MonkeyPatch
) -> None:
"""挂载的应用使用自身 ASGI 根路径。"""
monkeypatch.setattr(AppConfig, 'app_root_path', '/api')
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py
index a01873857..baec3603b 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_cache_integration.py
@@ -1,6 +1,6 @@
import asyncio
from collections.abc import AsyncIterator
-from types import SimpleNamespace
+from dataclasses import dataclass
from typing import Annotated, Any
from unittest.mock import AsyncMock
@@ -34,6 +34,8 @@
REGULAR_QUERY_COUNT,
TWO_AUTHENTICATIONS,
USER_ID,
+ AuthenticationRedis,
+ UserResolutionEnv,
resolution_env, # noqa: F401
)
from tests.utils.test_current_user_cache_util import cache_redis, redis_socket # noqa: F401
@@ -43,19 +45,40 @@
FOUR_AUTHENTICATIONS = 4
+@dataclass
+class UserCacheEnv(UserResolutionEnv[Redis]):
+ """
+ 使用隔离 Redis 服务验证用户缓存的测试环境。
+
+ :ivar namespace: 当前数据库绑定的用户缓存命名空间
+ :ivar calls: 缓存客户端执行的 Lua 脚本
+ """
+
+ namespace: str
+ calls: list[str]
+
+ def renew_count(self) -> int:
+ """
+ 统计主登录会话的续期次数。
+
+ :return: 已执行的续期脚本数量
+ """
+ return self.calls.count(_SESSION_RENEW_SCRIPT)
+
+
@pytest_asyncio.fixture
async def cache_env(
- resolution_env: SimpleNamespace, # noqa: F811
+ resolution_env: UserResolutionEnv[AuthenticationRedis], # noqa: F811
cache_redis: Redis, # noqa: F811
monkeypatch: pytest.MonkeyPatch,
-) -> AsyncIterator[SimpleNamespace]:
+) -> AsyncIterator[UserCacheEnv]:
"""
复用真实鉴权路由和数据库,缓存及会话命令均由隔离Redis执行。
:param resolution_env: 为当前用户解析测试准备隔离环境
:param cache_redis: 测试使用的 Redis 缓存客户端
:param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
- :yield: ``SimpleNamespace`` 实例
+ :yield: 包含 Redis 会话与脚本记录的缓存测试环境
"""
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', True)
monkeypatch.setattr(AppConfig, 'app_current_user_cache_ttl_seconds', 5)
@@ -95,20 +118,20 @@ async def session_dependency() -> AsyncIterator[AsyncSession]:
RedisUtil, 'create_redis_pool', AsyncMock(side_effect=AssertionError('应用会话应复用已有Redis客户端'))
)
resolution_env.app.dependency_overrides[get_db_session_provider(None)] = session_dependency
- yield SimpleNamespace(
- **{
- **vars(resolution_env),
- 'redis': cache_redis,
- 'sessions': sessions,
- 'namespace': namespace,
- 'calls': calls,
- 'renew_count': lambda: calls.count(_SESSION_RENEW_SCRIPT),
- }
+ yield UserCacheEnv(
+ app=resolution_env.app,
+ client=resolution_env.client,
+ redis=cache_redis,
+ sessions=sessions,
+ headers=resolution_env.headers,
+ statements=resolution_env.statements,
+ namespace=namespace,
+ calls=calls,
)
@pytest.mark.asyncio
-async def test_cache_hit_avoids_sql_and_still_renews_the_session(cache_env: SimpleNamespace) -> None:
+async def test_cache_hit_avoids_sql_and_still_renews_the_session(cache_env: UserCacheEnv) -> None:
"""缓存命中时跳过 SQL 查询并续期会话。"""
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
assert first.status_code == HttpStatusConstant.SUCCESS
@@ -122,13 +145,13 @@ async def test_cache_hit_avoids_sql_and_still_renews_the_session(cache_env: Simp
assert len(cache_env.statements) == REGULAR_QUERY_COUNT
assert cache_env.renew_count() == TWO_AUTHENTICATIONS
assert await cache_env.redis.hget(snapshot_key, 'deadline') == deadline
- assert 'private-password-hash' not in await cache_env.redis.hget(snapshot_key, 'payload')
+ payload = await cache_env.redis.hget(snapshot_key, 'payload')
+ assert isinstance(payload, str)
+ assert 'private-password-hash' not in payload
@pytest.mark.asyncio
-async def test_cache_hit_recomputes_password_policy(
- cache_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
-) -> None:
+async def test_cache_hit_recomputes_password_policy(cache_env: UserCacheEnv, monkeypatch: pytest.MonkeyPatch) -> None:
"""缓存命中时重新计算密码策略。"""
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
assert not first.json()['isPasswordExpired']
@@ -151,7 +174,7 @@ async def test_cache_hit_recomputes_password_policy(
@pytest.mark.asyncio
-async def test_concurrent_cache_hits_keep_users_and_context_separate(cache_env: SimpleNamespace) -> None:
+async def test_concurrent_cache_hits_keep_users_and_context_separate(cache_env: UserCacheEnv) -> None:
"""并发命中缓存时隔离用户和上下文。"""
for user_id in (ADMIN_ID, USER_ID):
await cache_env.client.get('/profile', headers=cache_env.headers[user_id])
@@ -173,7 +196,7 @@ async def test_concurrent_cache_hits_keep_users_and_context_separate(cache_env:
@pytest.mark.asyncio
@pytest.mark.parametrize('replacement', [None, 'new-login-token'])
async def test_cache_hit_never_accepts_revoked_or_replaced_token(
- cache_env: SimpleNamespace, replacement: str | None
+ cache_env: UserCacheEnv, replacement: str | None
) -> None:
"""缓存命中时仍拒绝已撤销或被替换的令牌。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
@@ -192,7 +215,7 @@ async def test_cache_hit_never_accepts_revoked_or_replaced_token(
@pytest.mark.asyncio
-async def test_use_cache_false_reauthenticates_even_when_both_calls_hit_cache(cache_env: SimpleNamespace) -> None:
+async def test_use_cache_false_reauthenticates_even_when_both_calls_hit_cache(cache_env: UserCacheEnv) -> None:
"""两次命中缓存时禁用依赖缓存仍会重新认证。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
@@ -223,7 +246,7 @@ async def revalidate(
@pytest.mark.asyncio
-async def test_cached_use_cache_false_rejects_session_revoked_between_dependencies(cache_env: SimpleNamespace) -> None:
+async def test_cached_use_cache_false_rejects_session_revoked_between_dependencies(cache_env: UserCacheEnv) -> None:
"""禁用依赖缓存后拒绝在两次依赖调用间被撤销的会话。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
@@ -260,7 +283,7 @@ async def revalidate(
@pytest.mark.asyncio
async def test_cached_use_cache_false_applies_permission_change_between_dependencies(
- cache_env: SimpleNamespace,
+ cache_env: UserCacheEnv,
) -> None:
"""禁用依赖缓存后应用两次依赖调用间的权限变更。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
@@ -304,7 +327,7 @@ async def revalidate(
@pytest.mark.asyncio
-async def test_plugin_cache_hit_does_not_renew_host_session(cache_env: SimpleNamespace) -> None:
+async def test_plugin_cache_hit_does_not_renew_host_session(cache_env: UserCacheEnv) -> None:
"""插件命中缓存时不续期宿主会话。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
token_key = f'access_token:session-{USER_ID}'
@@ -325,7 +348,7 @@ async def test_plugin_cache_hit_does_not_renew_host_session(cache_env: SimpleNam
@pytest.mark.asyncio
@pytest.mark.parametrize('change', ['disable_user', 'delete_user', 'remove_role', 'disable_role', 'remove_menu'])
async def test_committed_permission_changes_invalidate_cached_authentication(
- cache_env: SimpleNamespace, change: str
+ cache_env: UserCacheEnv, change: str
) -> None:
"""提交权限变更后使认证缓存失效。"""
await cache_env.client.get('/permitted', headers=cache_env.headers[USER_ID])
@@ -351,7 +374,7 @@ async def test_committed_permission_changes_invalidate_cached_authentication(
@pytest.mark.asyncio
@pytest.mark.parametrize('change', ['department', 'data_scope', 'post', 'menu'])
-async def test_shared_changes_refresh_all_authorization_fields(cache_env: SimpleNamespace, change: str) -> None:
+async def test_shared_changes_refresh_all_authorization_fields(cache_env: UserCacheEnv, change: str) -> None:
"""共享数据变更后刷新全部授权字段。"""
await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
async with cache_env.sessions.begin() as db:
@@ -380,7 +403,7 @@ async def test_shared_changes_refresh_all_authorization_fields(cache_env: Simple
@pytest.mark.asyncio
async def test_existing_transaction_bypasses_cache_without_publishing_uncommitted_permissions(
- cache_env: SimpleNamespace,
+ cache_env: UserCacheEnv,
) -> None:
"""已有事务绕过缓存且不发布未提交权限。"""
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
@@ -399,7 +422,7 @@ async def test_existing_transaction_bypasses_cache_without_publishing_uncommitte
@pytest.mark.asyncio
-async def test_external_connection_transaction_cannot_publish_uncommitted_user(cache_env: SimpleNamespace) -> None:
+async def test_external_connection_transaction_cannot_publish_uncommitted_user(cache_env: UserCacheEnv) -> None:
"""外部连接事务不能发布未提交的用户数据。"""
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
engine = cache_env.sessions.kw['bind']
@@ -424,7 +447,7 @@ async def test_external_connection_transaction_cannot_publish_uncommitted_user(c
@pytest.mark.asyncio
@pytest.mark.parametrize('default_bind', [False, True])
async def test_multi_bind_sessions_keep_original_database_resolution(
- cache_env: SimpleNamespace, default_bind: bool, monkeypatch: pytest.MonkeyPatch
+ cache_env: UserCacheEnv, default_bind: bool, monkeypatch: pytest.MonkeyPatch
) -> None:
"""多绑定会话保留原数据库解析行为。"""
engine = cache_env.sessions.kw['bind']
@@ -450,7 +473,7 @@ async def test_multi_bind_sessions_keep_original_database_resolution(
@pytest.mark.asyncio
async def test_concurrent_permission_commit_prevents_old_query_refilling_cache(
- cache_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+ cache_env: UserCacheEnv, monkeypatch: pytest.MonkeyPatch
) -> None:
"""并发提交权限变更后阻止旧查询回填缓存。"""
loaded = asyncio.Event()
@@ -493,12 +516,13 @@ async def delayed(query_db: AsyncSession, user_id: int) -> CurrentUserModel:
@pytest.mark.asyncio
-async def test_direct_orm_user_change_invalidates_only_affected_user(cache_env: SimpleNamespace) -> None:
+async def test_direct_orm_user_change_invalidates_only_affected_user(cache_env: UserCacheEnv) -> None:
"""直接修改 ORM 用户只使受影响用户缓存失效。"""
for user_id in (ADMIN_ID, USER_ID):
await cache_env.client.get('/profile', headers=cache_env.headers[user_id])
async with cache_env.sessions.begin() as db:
user = await db.get(SysUser, USER_ID)
+ assert user is not None
user.nick_name = 'Changed reader'
cache_env.statements.clear()
@@ -511,7 +535,7 @@ async def test_direct_orm_user_change_invalidates_only_affected_user(cache_env:
@pytest.mark.asyncio
-async def test_corrupt_cached_payload_falls_back_to_database(cache_env: SimpleNamespace) -> None:
+async def test_corrupt_cached_payload_falls_back_to_database(cache_env: UserCacheEnv) -> None:
"""缓存内容损坏时回退到数据库。"""
first = await cache_env.client.get('/profile', headers=cache_env.headers[USER_ID])
key = CurrentUserCacheUtil._keys(cache_env.namespace, USER_ID)[2]
@@ -526,7 +550,7 @@ async def test_corrupt_cached_payload_falls_back_to_database(cache_env: SimpleNa
@pytest.mark.asyncio
async def test_cache_failure_can_fall_back_without_bypassing_session_check(
- cache_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+ cache_env: UserCacheEnv, monkeypatch: pytest.MonkeyPatch
) -> None:
"""缓存故障时回退且继续校验会话。"""
original = cache_env.redis.eval
@@ -563,7 +587,7 @@ async def cache_failure(script: str, *args: Any) -> Any:
@pytest.mark.asyncio
@pytest.mark.parametrize('stage', ['read', 'write'])
async def test_cache_cancellation_propagates_without_renewal_or_context(
- cache_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, stage: str
+ cache_env: UserCacheEnv, monkeypatch: pytest.MonkeyPatch, stage: str
) -> None:
"""缓存操作被取消时传播取消信号且不续期或写入上下文。"""
original = cache_env.redis.eval
@@ -594,7 +618,7 @@ async def cancel(script: str, *args: Any) -> Any:
@pytest.mark.asyncio
async def test_cache_disabled_keeps_database_authentication(
- cache_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+ cache_env: UserCacheEnv, monkeypatch: pytest.MonkeyPatch
) -> None:
"""禁用缓存时使用数据库认证。"""
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', False)
diff --git a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py
index dad6d6e08..ae56ca96c 100644
--- a/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py
+++ b/ruoyi-fastapi-backend/tests/module_admin/service/test_current_user_resolution.py
@@ -1,9 +1,9 @@
import asyncio
from collections.abc import AsyncIterator
+from dataclasses import dataclass
from datetime import timedelta
from pathlib import Path
-from types import SimpleNamespace
-from typing import Annotated
+from typing import Annotated, Generic, TypeVar
from unittest.mock import AsyncMock
import pytest
@@ -84,14 +84,40 @@ async def set(self, key: str, value: str, *, ex: int) -> None:
await super().set(key, value, ex=ex)
+_RedisT = TypeVar('_RedisT')
+
+
+@dataclass
+class UserResolutionEnv(Generic[_RedisT]):
+ """
+ 通过真实路由和数据库验证当前用户解析的测试环境。
+
+ :ivar app: 挂载鉴权依赖的 FastAPI 应用
+ :ivar client: 向测试应用发送请求的客户端
+ :ivar redis: 保存用户会话和系统配置的缓存客户端
+ :ivar sessions: 连接测试数据库的异步会话工厂
+ :ivar headers: 按用户编号索引的认证请求头
+ :ivar statements: 测试中执行的查询语句
+ """
+
+ app: FastAPI
+ client: AsyncClient
+ redis: _RedisT
+ sessions: async_sessionmaker[AsyncSession]
+ headers: dict[int, dict[str, str]]
+ statements: list[str]
+
+
@pytest_asyncio.fixture
-async def resolution_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[SimpleNamespace]:
+async def resolution_env(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> AsyncIterator[UserResolutionEnv[AuthenticationRedis]]:
"""
为当前用户解析测试准备隔离环境。
:param tmp_path: pytest 为当前用例创建的临时目录
:param monkeypatch: 用于临时替换环境变量、模块或对象属性的 pytest 夹具
- :yield: ``SimpleNamespace`` 实例
+ :yield: 包含应用、会话工厂和缓存替身的测试环境
"""
monkeypatch.setattr(AppConfig, 'app_same_time_login', True)
monkeypatch.setattr(AppConfig, 'app_current_user_cache_enabled', False)
@@ -188,7 +214,7 @@ async def profile(current_user: Annotated[CurrentUserModel, CurrentUserDependenc
RequestContext.clear_all()
try:
async with AsyncClient(transport=ASGITransport(app=app), base_url='http://test') as client:
- yield SimpleNamespace(
+ yield UserResolutionEnv(
app=app, client=client, redis=redis, sessions=sessions, headers=headers, statements=statements
)
finally:
@@ -197,7 +223,9 @@ async def profile(current_user: Annotated[CurrentUserModel, CurrentUserDependenc
@pytest.mark.asyncio
-async def test_double_auth_declaration_queries_and_renews_once_per_request(resolution_env: SimpleNamespace) -> None:
+async def test_double_auth_declaration_queries_and_renews_once_per_request(
+ resolution_env: UserResolutionEnv[AuthenticationRedis],
+) -> None:
"""重复声明认证时单个请求只查询和续期一次。"""
first = await resolution_env.client.get('/profile', headers=resolution_env.headers[USER_ID])
assert first.status_code == HttpStatusConstant.SUCCESS
@@ -221,7 +249,9 @@ async def test_double_auth_declaration_queries_and_renews_once_per_request(resol
@pytest.mark.asyncio
-async def test_admin_does_not_load_menus_for_authentication(resolution_env: SimpleNamespace) -> None:
+async def test_admin_does_not_load_menus_for_authentication(
+ resolution_env: UserResolutionEnv[AuthenticationRedis],
+) -> None:
"""管理员认证不加载菜单。"""
response = await resolution_env.client.get('/permitted', headers=resolution_env.headers[ADMIN_ID])
assert response.json()['permissions'] == ['*:*:*']
@@ -233,7 +263,9 @@ async def test_admin_does_not_load_menus_for_authentication(resolution_env: Simp
@pytest.mark.asyncio
-async def test_use_cache_false_queries_and_renews_again_in_the_same_request(resolution_env: SimpleNamespace) -> None:
+async def test_use_cache_false_queries_and_renews_again_in_the_same_request(
+ resolution_env: UserResolutionEnv[AuthenticationRedis],
+) -> None:
"""禁用依赖缓存后同一请求再次查询并续期。"""
@resolution_env.app.get(
@@ -268,7 +300,9 @@ async def revalidate(
@pytest.mark.asyncio
-async def test_use_cache_false_rejects_a_session_revoked_in_the_same_request(resolution_env: SimpleNamespace) -> None:
+async def test_use_cache_false_rejects_a_session_revoked_in_the_same_request(
+ resolution_env: UserResolutionEnv[AuthenticationRedis],
+) -> None:
"""禁用依赖缓存后拒绝在同一请求中撤销的会话。"""
async def revoke_session(current_user: Annotated[CurrentUserModel, CurrentUserDependency()]) -> None:
@@ -307,7 +341,7 @@ async def revalidate(
@pytest.mark.asyncio
@pytest.mark.parametrize('change', ['remove_menu', 'disable_role'])
async def test_use_cache_false_applies_permission_changes_in_the_same_request(
- resolution_env: SimpleNamespace, change: str
+ resolution_env: UserResolutionEnv[AuthenticationRedis], change: str
) -> None:
"""禁用依赖缓存后同一请求可读取权限变更。"""
@@ -359,7 +393,7 @@ async def revalidate(
@pytest.mark.asyncio
@pytest.mark.parametrize('change', [{'status': '1'}, {'del_flag': '2'}])
async def test_disabled_or_deleted_user_is_rejected_on_next_request(
- resolution_env: SimpleNamespace, change: dict[str, str]
+ resolution_env: UserResolutionEnv[AuthenticationRedis], change: dict[str, str]
) -> None:
"""后续请求拒绝已禁用或删除的用户。"""
first = await resolution_env.client.get('/profile', headers=resolution_env.headers[USER_ID])
@@ -375,7 +409,9 @@ async def test_disabled_or_deleted_user_is_rejected_on_next_request(
@pytest.mark.asyncio
@pytest.mark.parametrize('change', ['remove', 'disable', 'delete'])
-async def test_role_revocation_applies_to_next_request(resolution_env: SimpleNamespace, change: str) -> None:
+async def test_role_revocation_applies_to_next_request(
+ resolution_env: UserResolutionEnv[AuthenticationRedis], change: str
+) -> None:
"""后续请求应用角色撤销结果。"""
first = await resolution_env.client.get('/permitted', headers=resolution_env.headers[USER_ID])
assert first.json()['permissions'] == ['demo:read']
@@ -397,7 +433,7 @@ async def test_role_revocation_applies_to_next_request(resolution_env: SimpleNam
@pytest.mark.asyncio
async def test_password_policy_changes_are_recomputed_on_next_request(
- resolution_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+ resolution_env: UserResolutionEnv[AuthenticationRedis], monkeypatch: pytest.MonkeyPatch
) -> None:
"""后续请求重新计算已变更的密码策略。"""
first = await resolution_env.client.get('/profile', headers=resolution_env.headers[USER_ID])
@@ -424,7 +460,7 @@ async def test_password_policy_changes_are_recomputed_on_next_request(
@pytest.mark.asyncio
async def test_password_expiry_advances_between_requests(
- resolution_env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+ resolution_env: UserResolutionEnv[AuthenticationRedis], monkeypatch: pytest.MonkeyPatch
) -> None:
"""两次请求之间按时间推进密码有效期。"""
now = TimezoneUtil.utc_now()
@@ -440,7 +476,9 @@ async def test_password_expiry_advances_between_requests(
@pytest.mark.asyncio
-async def test_concurrent_requests_keep_user_identity_and_permissions_separate(resolution_env: SimpleNamespace) -> None:
+async def test_concurrent_requests_keep_user_identity_and_permissions_separate(
+ resolution_env: UserResolutionEnv[AuthenticationRedis],
+) -> None:
"""并发请求隔离用户身份和权限。"""
admin, reader = await asyncio.gather(
resolution_env.client.get('/profile', headers=resolution_env.headers[ADMIN_ID]),
@@ -458,7 +496,7 @@ async def test_concurrent_requests_keep_user_identity_and_permissions_separate(r
@pytest.mark.parametrize('operation', ['get', 'eval'])
@pytest.mark.parametrize('failure', [RedisConnectionError, RedisTimeoutError, NoPermissionError])
async def test_redis_failure_rejects_protected_requests_and_recovers_without_relogin(
- resolution_env: SimpleNamespace,
+ resolution_env: UserResolutionEnv[AuthenticationRedis],
monkeypatch: pytest.MonkeyPatch,
operation: str,
failure: type[RedisError],
diff --git a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py
index 07462c256..245272727 100644
--- a/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py
+++ b/ruoyi-fastapi-backend/tests/plugins/core/runtime/test_connection_sessions.py
@@ -5,7 +5,7 @@
from unittest.mock import AsyncMock
import pytest
-from fastapi import WebSocket
+from fastapi import FastAPI, WebSocket
from starlette import status
from starlette.types import Message
@@ -92,11 +92,13 @@ async def test_websocket_cookie_origin_and_live_login_revocation(
"""WebSocket 保留精确 Origin 门禁,已握手的连接在主登录失效后关闭。"""
loaded = browser.runtime.loaded['browser_test']
loaded.gateway.connections.recheck_interval = 0.01
+ plugin_app = loaded.lifespan.app
+ assert isinstance(plugin_app, FastAPI)
opened = asyncio.Event()
messages = []
incoming: asyncio.Queue[Message] = asyncio.Queue()
- @loaded.lifespan.app.websocket('/ws/events')
+ @plugin_app.websocket('/ws/events')
async def events(websocket: WebSocket) -> None:
"""
接受插件事件连接并处理测试消息。
diff --git a/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py b/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py
index 857718c38..d66f6516e 100644
--- a/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py
+++ b/ruoyi-fastapi-backend/tests/plugins/integration/test_network_smoke.py
@@ -19,7 +19,7 @@
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
-from fastapi import WebSocket
+from fastapi import FastAPI, WebSocket
from starlette import status
from plugins.examples.python.bundle_demo.events import register_event_routes
@@ -102,14 +102,17 @@ def prepare_network_host(fixture: SimpleNamespace) -> None:
:param fixture: 使用生产门禁及会话协议的隔离运行时
"""
app = fixture.app
+ assert isinstance(app, FastAPI)
loaded = fixture.runtime.loaded['browser_test']
loaded.gateway.connections.recheck_interval = 0.1
- register_event_routes(loaded.lifespan.app, permission='browser_test:view', interval=1.0)
+ plugin_app = loaded.lifespan.app
+ assert isinstance(plugin_app, FastAPI)
+ register_event_routes(plugin_app, permission='browser_test:view', interval=1.0)
bundle = fixture.plugin.backend_path / 'web' / 'dist'
shutil.copyfile(Path(__file__).with_name('network_bundle.html'), bundle / 'index.html')
shutil.copyfile(frontend_root() / 'src/utils/pluginBridge.js', bundle / 'assets/bridge.js')
- @loaded.lifespan.app.websocket('/ws/events')
+ @plugin_app.websocket('/ws/events')
async def events(websocket: WebSocket) -> None:
"""
接受插件事件连接并处理测试消息。
diff --git a/ruoyi-fastapi-backend/tests/test_api_docs_auth.py b/ruoyi-fastapi-backend/tests/test_api_docs_auth.py
index c4bab6aee..eb5f5db68 100644
--- a/ruoyi-fastapi-backend/tests/test_api_docs_auth.py
+++ b/ruoyi-fastapi-backend/tests/test_api_docs_auth.py
@@ -1,7 +1,6 @@
import json
from collections.abc import AsyncIterator, Iterator
from copy import deepcopy
-from types import SimpleNamespace
from typing import TYPE_CHECKING, Annotated
from unittest.mock import AsyncMock
from uuid import UUID
@@ -21,6 +20,7 @@
from middlewares.context_middleware import add_context_cleanup_middleware
from module_admin.entity.vo.user_vo import CurrentUserModel, UserInfoModel
from module_admin.service.login_service import LoginService, oauth2_scheme
+from tests.auth_helpers import AuthTestApp
from utils.server_util import APIDocsUtil
if TYPE_CHECKING:
@@ -31,7 +31,7 @@
@pytest.fixture
-def docs_app(monkeypatch: pytest.MonkeyPatch) -> Iterator[SimpleNamespace]:
+def docs_app(monkeypatch: pytest.MonkeyPatch) -> Iterator[AuthTestApp]:
"""
构建启用文档端点的测试应用。
@@ -139,7 +139,7 @@ async def partial(name: str) -> dict[str, object]:
return {'name': name}
try:
- yield SimpleNamespace(app=app, resolver=resolver)
+ yield AuthTestApp(app=app, resolver=resolver)
finally:
RequestContext.clear_all()
@@ -161,7 +161,7 @@ def _security(app: FastAPI, path: str, method: str = 'get') -> list[dict[str, li
@pytest.mark.asyncio
@pytest.mark.parametrize('server_urls', [[], ['https://api.example.test'], ['/gateway']])
async def test_proxy_schema_does_not_add_deployment_prefix_to_direct_schema(
- docs_app: SimpleNamespace, server_urls: list[str]
+ docs_app: AuthTestApp, server_urls: list[str]
) -> None:
"""代理文档的部署前缀不会写入直连文档。"""
servers = [{'url': url} for url in server_urls]
@@ -176,12 +176,13 @@ async def test_proxy_schema_does_not_add_deployment_prefix_to_direct_schema(
assert direct.json().get('servers', []) == servers
assert proxy.json()['paths'] == direct.json()['paths']
assert docs_app.app.servers == servers
+ assert docs_app.app.openapi_schema is not None
assert docs_app.app.openapi_schema.get('servers', []) == servers
@pytest.mark.asyncio
@pytest.mark.parametrize('path', ['/public', '/items/{name}'])
-async def test_fully_excluded_route_has_no_login_security(docs_app: SimpleNamespace, path: str) -> None:
+async def test_fully_excluded_route_has_no_login_security(docs_app: AuthTestApp, path: str) -> None:
"""完全排除的路由无需在文档中声明登录认证。"""
assert _security(docs_app.app, path) == []
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=docs_app.app), base_url='http://test') as client:
@@ -192,7 +193,7 @@ async def test_fully_excluded_route_has_no_login_security(docs_app: SimpleNamesp
@pytest.mark.asyncio
-async def test_protected_route_keeps_login_security(docs_app: SimpleNamespace) -> None:
+async def test_protected_route_keeps_login_security(docs_app: AuthTestApp) -> None:
"""受保护路由保留登录安全要求。"""
assert _security(docs_app.app, '/protected') == [LOGIN_SECURITY]
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=docs_app.app), base_url='http://test') as client:
@@ -204,7 +205,7 @@ async def test_protected_route_keeps_login_security(docs_app: SimpleNamespace) -
@pytest.mark.asyncio
-async def test_security_is_classified_per_http_method(docs_app: SimpleNamespace) -> None:
+async def test_security_is_classified_per_http_method(docs_app: AuthTestApp) -> None:
"""按 HTTP 方法分别判定安全要求。"""
assert _security(docs_app.app, '/method', 'get') == []
assert _security(docs_app.app, '/method', 'post') == [LOGIN_SECURITY]
@@ -224,7 +225,7 @@ async def test_security_is_classified_per_http_method(docs_app: SimpleNamespace)
],
)
async def test_parameter_dependent_authentication_is_documented_as_conditional(
- docs_app: SimpleNamespace, path: str, public_path: str, protected_path: str, documented_rule: str
+ docs_app: AuthTestApp, path: str, public_path: str, protected_path: str, documented_rule: str
) -> None:
"""依赖参数的认证在文档中标为有条件。"""
operation = docs_app.app.openapi()['paths'][path]['get']
@@ -243,7 +244,7 @@ async def test_parameter_dependent_authentication_is_documented_as_conditional(
@pytest.mark.asyncio
@pytest.mark.parametrize('declaration', ['current', 'nested', 'token', 'plugin', 'included'])
async def test_explicit_authentication_cannot_be_removed_from_public_route_schema(
- docs_app: SimpleNamespace, declaration: str
+ docs_app: AuthTestApp, declaration: str
) -> None:
"""公开路由中显式声明的认证仍保留在文档中。"""
path = f'/explicit-{declaration}'
@@ -332,7 +333,7 @@ async def plugin() -> dict[str, bool]:
@pytest.mark.asyncio
@pytest.mark.parametrize('required', [False, True])
-async def test_all_pre_auth_dependencies_must_exclude_the_route(docs_app: SimpleNamespace, required: bool) -> None:
+async def test_all_pre_auth_dependencies_must_exclude_the_route(docs_app: AuthTestApp, required: bool) -> None:
"""全部预认证依赖均排除时才放行路由。"""
path = '/multiple'
dependencies = [
@@ -364,7 +365,7 @@ async def multiple() -> dict[str, bool]:
@pytest.mark.asyncio
-async def test_disjoint_exclusions_do_not_make_a_parameterized_route_public(docs_app: SimpleNamespace) -> None:
+async def test_disjoint_exclusions_do_not_make_a_parameterized_route_public(docs_app: AuthTestApp) -> None:
"""不相交的排除范围不会使参数化路由公开。"""
@docs_app.app.get(
@@ -393,7 +394,7 @@ async def disjoint(name: str) -> dict[str, object]:
@pytest.mark.parametrize('name', ['public', 'private'])
-def test_fixed_route_honors_wildcard_exclusion_and_ignore_paths(docs_app: SimpleNamespace, name: str) -> None:
+def test_fixed_route_honors_wildcard_exclusion_and_ignore_paths(docs_app: AuthTestApp, name: str) -> None:
"""固定路由遵循通配符和忽略路径。"""
path = f'/fixed/{name}'
@@ -416,7 +417,7 @@ async def fixed() -> dict[str, bool]:
@pytest.mark.parametrize('ignore_path', ['/elsewhere/private', '/reallowed/private'])
def test_irrelevant_or_reallowed_exceptions_do_not_make_fully_public_routes_conditional(
- docs_app: SimpleNamespace, ignore_path: str
+ docs_app: AuthTestApp, ignore_path: str
) -> None:
"""无关或已重新放行的例外不会让公开路由变为有条件认证。"""
@@ -448,7 +449,7 @@ async def reallowed(name: str) -> dict[str, object]:
@pytest.mark.asyncio
@pytest.mark.parametrize('conditional', [False, True])
async def test_public_login_exclusion_preserves_other_required_security(
- docs_app: SimpleNamespace, conditional: bool
+ docs_app: AuthTestApp, conditional: bool
) -> None:
"""排除登录要求时保留其他安全要求。"""
path = '/key/{name}' if conditional else '/key'
@@ -485,7 +486,7 @@ async def key(value: Annotated[str, Depends(api_key)]) -> dict[str, object]:
@pytest.mark.asyncio
-async def test_independent_oauth_scheme_with_the_same_name_remains_required(docs_app: SimpleNamespace) -> None:
+async def test_independent_oauth_scheme_with_the_same_name_remains_required(docs_app: AuthTestApp) -> None:
"""同名的独立 OAuth 方案仍是必需项。"""
independent = OAuth2PasswordBearer(tokenUrl='independent-login', scheme_name='OAuth2PasswordBearer')
@@ -515,7 +516,7 @@ async def independent_token(token: Annotated[str, Depends(independent)]) -> dict
@pytest.mark.asyncio
@pytest.mark.parametrize('root_path', ['/gateway', '/api'])
async def test_nested_router_prefix_and_root_path_match_runtime_rules(
- docs_app: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, root_path: str
+ docs_app: AuthTestApp, monkeypatch: pytest.MonkeyPatch, root_path: str
) -> None:
"""嵌套路由前缀及根路径遵循运行时规则。"""
monkeypatch.setattr(AppConfig, 'app_root_path', root_path)
@@ -539,7 +540,7 @@ async def public() -> dict[str, bool]:
@pytest.mark.asyncio
-async def test_schema_urls_and_direct_schema_share_security_and_servers(docs_app: SimpleNamespace) -> None:
+async def test_schema_urls_and_direct_schema_share_security_and_servers(docs_app: AuthTestApp) -> None:
"""代理文档与直连文档共享安全要求和服务器信息。"""
direct = docs_app.app.openapi()
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=docs_app.app), base_url='http://test') as client:
@@ -553,7 +554,7 @@ async def test_schema_urls_and_direct_schema_share_security_and_servers(docs_app
docs_app.resolver.assert_not_awaited()
-def test_schema_adjustment_is_idempotent_and_tracks_late_router_registration(docs_app: SimpleNamespace) -> None:
+def test_schema_adjustment_is_idempotent_and_tracks_late_router_registration(docs_app: AuthTestApp) -> None:
"""重复调整文档结果一致且能跟踪后注册的路由。"""
initial = deepcopy(docs_app.app.openapi())
assert docs_app.app.openapi() == initial
@@ -588,7 +589,7 @@ async def protected() -> dict[str, bool]:
@pytest.mark.parametrize('public_first', [False, True])
@pytest.mark.parametrize('include_first', [False, True])
async def test_duplicate_route_preserves_native_security(
- docs_app: SimpleNamespace, public_first: bool, include_first: bool
+ docs_app: AuthTestApp, public_first: bool, include_first: bool
) -> None:
"""重复路由保留原生安全要求。"""
path = '/duplicate'
@@ -623,6 +624,7 @@ async def second() -> dict[str, str]:
return {'route': 'second'}
operation = docs_app.app.openapi()['paths'][path]['get']
+ assert docs_app.app.openapi_schema is not None
assert operation == docs_app.app.openapi_schema['paths'][path]['get']
assert operation['security'] == [LOGIN_SECURITY]
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=docs_app.app), base_url='http://test') as client:
@@ -639,7 +641,7 @@ async def second() -> dict[str, str]:
@pytest.mark.parametrize('public_first', [False, True])
@pytest.mark.parametrize('include_first', [False, True])
async def test_duplicate_path_with_different_convertors_preserves_native_security(
- docs_app: SimpleNamespace, public_first: bool, include_first: bool
+ docs_app: AuthTestApp, public_first: bool, include_first: bool
) -> None:
"""同一路径使用不同转换器时保留原生安全要求。"""
rule: ExcludeRoute = {'path': '/duplicate-convertor/{value}'}
@@ -678,6 +680,7 @@ async def string(value: str) -> dict[str, object]:
path = '/duplicate-convertor/{value}'
operation = docs_app.app.openapi()['paths'][path]['get']
# 相同OpenAPI路径可对应不同的实际匹配范围,不能将其中一条的排除规则用于整条声明。
+ assert docs_app.app.openapi_schema is not None
assert operation['security'] == docs_app.app.openapi_schema['paths'][path]['get']['security'] == [LOGIN_SECURITY]
assert 'x-login-auth' not in operation
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=docs_app.app), base_url='http://test') as client:
@@ -705,7 +708,7 @@ async def string(value: str) -> dict[str, object]:
],
)
async def test_duplicate_route_with_other_authentication_preserves_native_security(
- docs_app: SimpleNamespace, first_auth: str, second_auth: str
+ docs_app: AuthTestApp, first_auth: str, second_auth: str
) -> None:
"""重复路由带有其他认证时保留原生安全要求。"""
path = '/duplicate-security'
@@ -747,6 +750,7 @@ async def second() -> dict[str, str]:
return {'route': 'second'}
operation = docs_app.app.openapi()['paths'][path]['get']
+ assert docs_app.app.openapi_schema is not None
assert operation == docs_app.app.openapi_schema['paths'][path]['get']
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=docs_app.app), base_url='http://test') as client:
anonymous = await client.get(path)
@@ -760,7 +764,7 @@ async def second() -> dict[str, str]:
assert authenticated.json() == {'route': 'first'}
-def test_unrelated_schema_details_and_security_schemes_are_preserved(docs_app: SimpleNamespace) -> None:
+def test_unrelated_schema_details_and_security_schemes_are_preserved(docs_app: AuthTestApp) -> None:
"""保留无关的文档细节和安全方案。"""
api_key = APIKeyHeader(name='X-External-Key', scheme_name='ExternalKey')
@@ -825,7 +829,7 @@ async def plain_public() -> dict[str, bool]:
],
)
async def test_parameter_convertors_exclude_impossible_public_values(
- docs_app: SimpleNamespace, converter: str, first_value: str, second_value: str, excluded_value: str
+ docs_app: AuthTestApp, converter: str, first_value: str, second_value: str, excluded_value: str
) -> None:
"""路径转换器排除不可能公开的值。"""
@@ -860,9 +864,7 @@ async def converted(value: int | UUID) -> dict[str, object]:
@pytest.mark.asyncio
@pytest.mark.parametrize('reallow', [False, True])
-async def test_overlapping_public_values_respect_each_pre_auth_exception(
- docs_app: SimpleNamespace, reallow: bool
-) -> None:
+async def test_overlapping_public_values_respect_each_pre_auth_exception(docs_app: AuthTestApp, reallow: bool) -> None:
"""公开值重叠时遵循每个预认证依赖的例外。"""
rules: list[ExcludeRoute] = [{'path': '/overlap/{name}', 'ignore_paths': ['/overlap/free']}]
if reallow:
@@ -896,10 +898,11 @@ async def overlap(name: str) -> dict[str, object]:
assert second.json()['code'] == status.HTTP_401_UNAUTHORIZED
-def test_adjusted_schema_never_mutates_the_native_cache(docs_app: SimpleNamespace) -> None:
+def test_adjusted_schema_never_mutates_the_native_cache(docs_app: AuthTestApp) -> None:
"""调整文档不会修改原生缓存。"""
adjusted = docs_app.app.openapi()
native = docs_app.app.openapi_schema
+ assert native is not None
assert native is not adjusted
assert native['paths']['/public']['get']['security'] == [LOGIN_SECURITY]
assert native['paths']['/mixed/{name}']['get']['security'] == [LOGIN_SECURITY]
@@ -913,7 +916,7 @@ def test_adjusted_schema_never_mutates_the_native_cache(docs_app: SimpleNamespac
assert '由调用者修改的文档' not in regenerated['paths']['/mixed/{name}']['get']['description']
-def test_registering_docs_again_does_not_duplicate_conditional_authentication_notes(docs_app: SimpleNamespace) -> None:
+def test_registering_docs_again_does_not_duplicate_conditional_authentication_notes(docs_app: AuthTestApp) -> None:
"""重复注册文档不会重复追加条件认证说明。"""
before = deepcopy(docs_app.app.openapi())
APIDocsUtil.custom_api_docs_router(docs_app.app)
@@ -921,7 +924,7 @@ def test_registering_docs_again_does_not_duplicate_conditional_authentication_no
@pytest.mark.asyncio
-async def test_changed_exclusion_rules_restore_native_security_and_description(docs_app: SimpleNamespace) -> None:
+async def test_changed_exclusion_rules_restore_native_security_and_description(docs_app: AuthTestApp) -> None:
"""更改排除规则后恢复原生安全要求和说明。"""
pre_auth = PreAuthDependency([{'path': '/mutable/free'}])
description = '原有接口描述必须保留。'
@@ -954,7 +957,7 @@ async def mutable(name: str) -> dict[str, object]:
@pytest.mark.parametrize('conditional', [False, True])
-def test_compound_security_from_openapi_extra_is_preserved(docs_app: SimpleNamespace, conditional: bool) -> None:
+def test_compound_security_from_openapi_extra_is_preserved(docs_app: AuthTestApp, conditional: bool) -> None:
"""保留 OpenAPI 扩展声明的组合安全要求。"""
gateway = APIKeyHeader(name='X-Gateway-Key', scheme_name='GatewayKey')
audit = APIKeyHeader(name='X-Audit-Key', scheme_name='AuditKey')
@@ -1015,7 +1018,7 @@ async def compound() -> dict[str, bool]:
)
@pytest.mark.parametrize('ignore', ['none', 'matching', 'unrelated'])
async def test_embedded_parameters_and_literal_dots_preserve_full_exclusion(
- docs_app: SimpleNamespace, path: str, public_path: str, private_path: str, unmatched_ignore: str, ignore: str
+ docs_app: AuthTestApp, path: str, public_path: str, private_path: str, unmatched_ignore: str, ignore: str
) -> None:
"""嵌入路径参数及字面点号保留完全排除效果。"""
ignored_paths = [] if ignore == 'none' else [private_path if ignore == 'matching' else unmatched_ignore]
@@ -1052,7 +1055,7 @@ async def embedded(name: str) -> dict[str, object]:
@pytest.mark.asyncio
-async def test_modifying_documented_rules_cannot_change_runtime_authentication(docs_app: SimpleNamespace) -> None:
+async def test_modifying_documented_rules_cannot_change_runtime_authentication(docs_app: AuthTestApp) -> None:
"""修改文档规则不能改变运行时认证。"""
@docs_app.app.api_route(
@@ -1092,7 +1095,7 @@ async def documented(name: str) -> dict[str, object]:
@pytest.mark.asyncio
-async def test_explicit_anonymous_security_for_optional_api_key_is_preserved(docs_app: SimpleNamespace) -> None:
+async def test_explicit_anonymous_security_for_optional_api_key_is_preserved(docs_app: AuthTestApp) -> None:
"""可选 API 密钥保留显式匿名访问声明。"""
optional_key = APIKeyHeader(name='X-Optional-Key', scheme_name='OptionalKey', auto_error=False)
@@ -1122,7 +1125,7 @@ async def optional(key: Annotated[str | None, Depends(optional_key)]) -> dict[st
@pytest.mark.asyncio
-async def test_complex_rule_cannot_override_a_proven_empty_public_intersection(docs_app: SimpleNamespace) -> None:
+async def test_complex_rule_cannot_override_a_proven_empty_public_intersection(docs_app: AuthTestApp) -> None:
"""复杂规则无法覆盖已证明为空的公开范围交集。"""
@docs_app.app.get(
@@ -1151,7 +1154,7 @@ async def complex_rule(name: str) -> dict[str, object]:
@pytest.mark.asyncio
-async def test_unresolved_complex_rules_do_not_add_an_unproven_anonymous_alternative(docs_app: SimpleNamespace) -> None:
+async def test_unresolved_complex_rules_do_not_add_an_unproven_anonymous_alternative(docs_app: AuthTestApp) -> None:
"""未能解析的复杂规则不会引入未经确认的匿名选项。"""
@docs_app.app.get(
diff --git a/ruoyi-fastapi-backend/ty.toml b/ruoyi-fastapi-backend/ty.toml
index 11c711b38..38706c274 100644
--- a/ruoyi-fastapi-backend/ty.toml
+++ b/ruoyi-fastapi-backend/ty.toml
@@ -5,6 +5,7 @@ python-version = "3.11"
[rules]
blanket-ignore-comment = "error"
disjoint-cast = "error"
+dynamic-function-decorator-return = "error"
mismatched-enum-name = "error"
mismatched-namedtuple-name = "error"
mismatched-sentinel-name = "error"
diff --git a/ruoyi-fastapi-test/ty.toml b/ruoyi-fastapi-test/ty.toml
index 11c711b38..38706c274 100644
--- a/ruoyi-fastapi-test/ty.toml
+++ b/ruoyi-fastapi-test/ty.toml
@@ -5,6 +5,7 @@ python-version = "3.11"
[rules]
blanket-ignore-comment = "error"
disjoint-cast = "error"
+dynamic-function-decorator-return = "error"
mismatched-enum-name = "error"
mismatched-namedtuple-name = "error"
mismatched-sentinel-name = "error"
diff --git a/ty.toml b/ty.toml
index c0f46756c..976518dd7 100644
--- a/ty.toml
+++ b/ty.toml
@@ -6,6 +6,7 @@ python-version = "3.11"
[rules]
blanket-ignore-comment = "error"
disjoint-cast = "error"
+dynamic-function-decorator-return = "error"
mismatched-enum-name = "error"
mismatched-namedtuple-name = "error"
mismatched-sentinel-name = "error"
From f84521aa6fefb020532aeb55367dba0b53258a17 Mon Sep 17 00:00:00 2001
From: insistence <3055204202@qq.com>
Date: Thu, 26 Nov 2026 13:09:08 +0800
Subject: [PATCH 8/9] =?UTF-8?q?fix:=20=E7=A7=BB=E9=99=A4=20http=5Frequest?=
=?UTF-8?q?=20=E5=B1=9E=E6=80=A7=E5=B9=B6=E6=81=A2=E5=A4=8D=E6=8F=92?=
=?UTF-8?q?=E4=BB=B6=E7=A4=BA=E4=BE=8B=E4=BD=BF=E7=94=A8=20context.request?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../docs/plugin_development.md | 4 ++-
.../plugins/core/sdk/context.py | 14 +-------
.../examples/python/asgi_demo/__init__.py | 4 ++-
.../examples/python/task_demo/__init__.py | 35 +++++++++++++------
4 files changed, 32 insertions(+), 25 deletions(-)
diff --git a/ruoyi-fastapi-backend/docs/plugin_development.md b/ruoyi-fastapi-backend/docs/plugin_development.md
index 6c00e4ca7..ed51a69de 100644
--- a/ruoyi-fastapi-backend/docs/plugin_development.md
+++ b/ruoyi-fastapi-backend/docs/plugin_development.md
@@ -904,7 +904,9 @@ class MessageBody(BaseModel):
message: str = Field(min_length=1, max_length=200)
-async def echo(context: PluginRequestContext) -> dict:
+async def echo(context: PluginRequestContext) -> dict[str, object]:
+ if context.request is None:
+ raise RuntimeError('当前插件上下文缺少 HTTP 请求快照')
return {**context.request.to_payload(), 'requestId': context.request_id}
diff --git a/ruoyi-fastapi-backend/plugins/core/sdk/context.py b/ruoyi-fastapi-backend/plugins/core/sdk/context.py
index a05628abc..c99f9ff37 100644
--- a/ruoyi-fastapi-backend/plugins/core/sdk/context.py
+++ b/ruoyi-fastapi-backend/plugins/core/sdk/context.py
@@ -97,7 +97,7 @@ class PluginRequestContext:
:ivar permissions: 当前用户的接口权限集合
:ivar request_id: 宿主提供的请求关联标识
:ivar query_db: 显式事务块内有效的数据库会话,不得跨任务共享
- :ivar request: SDK 接口适配器提供的 HTTP 请求数据快照
+ :ivar request: SDK 接口适配器填入的 HTTP 请求快照,未经适配时为 None
:ivar _transaction: 宿主内部的会话所有权记录,业务代码不应自行构造
"""
@@ -109,18 +109,6 @@ class PluginRequestContext:
request: PluginHttpRequest | None = None
_transaction: '_PluginTransactionState | None' = field(default=None, repr=False, compare=False)
- @property
- def http_request(self) -> PluginHttpRequest:
- """
- 获取当前 HTTP 接口的请求快照。
-
- :return: 宿主已解析的 HTTP 请求
- :raises RuntimeError: 当前上下文不属于 HTTP 接口
- """
- if self.request is None:
- raise RuntimeError('当前插件上下文缺少 HTTP 请求快照')
- return self.request
-
def require_permission(self, permission: str) -> None:
"""
执行接口权限检查;数据权限由具体服务按当前用户处理。
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/__init__.py b/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/__init__.py
index 4e8e8bdaa..ce09d0a6b 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/__init__.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/asgi_demo/__init__.py
@@ -15,7 +15,9 @@ class EchoBody(BaseModel):
async def echo(context: PluginRequestContext) -> dict[str, Any]:
- return {**context.http_request.to_payload(), 'requestId': context.request_id}
+ if context.request is None:
+ raise RuntimeError('当前插件上下文缺少 HTTP 请求快照')
+ return {**context.request.to_payload(), 'requestId': context.request_id}
def create_plugin(host: PluginHostContext) -> PluginDefinition:
diff --git a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/__init__.py b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/__init__.py
index 7504f350d..7db79b8d1 100644
--- a/ruoyi-fastapi-backend/plugins/examples/python/task_demo/__init__.py
+++ b/ruoyi-fastapi-backend/plugins/examples/python/task_demo/__init__.py
@@ -6,7 +6,7 @@
from sqlalchemy import select
from plugins.core.runtime.health import PluginHealthContext
-from plugins.core.sdk import PluginDefinition, PluginHostContext, PluginRequestContext
+from plugins.core.sdk import PluginDefinition, PluginHostContext, PluginHttpRequest, PluginRequestContext
from plugins.core.sdk.asgi import plugin_endpoint
from . import service
@@ -37,14 +37,27 @@ def _validate(model: type[_Model], values: dict[str, Any]) -> _Model:
) from exc
-def _task_id(context: PluginRequestContext) -> str:
+def _request(context: PluginRequestContext) -> PluginHttpRequest:
+ """
+ 读取任务接口的请求快照。
+
+ :param context: 宿主传入的插件上下文
+ :return: 接口适配器填入的 HTTP 请求快照
+ :raises RuntimeError: 插件上下文缺少请求快照
+ """
+ if context.request is None:
+ raise RuntimeError('当前插件上下文缺少 HTTP 请求快照')
+ return context.request
+
+
+def _task_id(request: PluginHttpRequest) -> str:
"""
读取 SDK 已提取的任务路径参数。
- :param context: 含 HTTP 请求快照的宿主上下文
+ :param request: 含任务标识的 HTTP 请求快照
:return: 已校验的任务标识
"""
- return _validate(TaskIdentifier, {'id': context.http_request.path_params['task_id']}).id
+ return _validate(TaskIdentifier, {'id': request.path_params['task_id']}).id
async def info(context: PluginRequestContext) -> dict[str, Any]:
@@ -52,26 +65,28 @@ async def info(context: PluginRequestContext) -> dict[str, Any]:
async def list_tasks(context: PluginRequestContext) -> dict[str, Any]:
- if any(len(values) != 1 for values in context.http_request.query.values()):
+ params = _request(context).query
+ if any(len(values) != 1 for values in params.values()):
raise HTTPException(status_code=422, detail='查询参数不能重复')
- query = _validate(TaskQuery, {key: values[0] for key, values in context.http_request.query.items()})
+ query = _validate(TaskQuery, {key: values[0] for key, values in params.items()})
return await service.list_tasks(context, query)
async def get_task(context: PluginRequestContext) -> dict[str, Any]:
- return await service.get_task(context, _task_id(context))
+ return await service.get_task(context, _task_id(_request(context)))
async def create_task(context: PluginRequestContext) -> dict[str, Any]:
- return await service.create_task(context, context.http_request.body)
+ return await service.create_task(context, _request(context).body)
async def update_task(context: PluginRequestContext) -> dict[str, Any]:
- return await service.update_task(context, _task_id(context), context.http_request.body)
+ request = _request(context)
+ return await service.update_task(context, _task_id(request), request.body)
async def delete_task(context: PluginRequestContext) -> dict[str, bool]:
- return await service.delete_task(context, _task_id(context))
+ return await service.delete_task(context, _task_id(_request(context)))
def create_plugin(host: PluginHostContext) -> PluginDefinition:
From e8ed122a25666c58b3cc52695682be6de43922bf Mon Sep 17 00:00:00 2001
From: insistence <3055204202@qq.com>
Date: Thu, 26 Nov 2026 13:21:58 +0800
Subject: [PATCH 9/9] =?UTF-8?q?chore:=20=E5=90=8E=E7=AB=AF=E5=90=AF?=
=?UTF-8?q?=E7=94=A8=20Ruff=20D=20=E7=B3=BB=E5=88=97=E8=A7=84=E5=88=99?=
=?UTF-8?q?=E5=B9=B6=E7=BB=9F=E4=B8=80=E9=85=8D=E7=BD=AE=E8=AF=B4=E6=98=8E?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.github/ruff.toml | 2 +-
ruoyi-fastapi-backend/ruff.toml | 12 +++++++-----
ruoyi-fastapi-test/ruff.toml | 6 +++---
3 files changed, 11 insertions(+), 9 deletions(-)
diff --git a/.github/ruff.toml b/.github/ruff.toml
index 3c59e39a7..c8f6e81ae 100644
--- a/.github/ruff.toml
+++ b/.github/ruff.toml
@@ -1,2 +1,2 @@
-# CI 脚本和测试与后端使用相同的 Python 风格。
+# CI scripts and tests follow the backend's Python style.
extend = "../ruoyi-fastapi-backend/ruff.toml"
diff --git a/ruoyi-fastapi-backend/ruff.toml b/ruoyi-fastapi-backend/ruff.toml
index c7ef22486..7a75c886b 100644
--- a/ruoyi-fastapi-backend/ruff.toml
+++ b/ruoyi-fastapi-backend/ruff.toml
@@ -12,10 +12,8 @@ select = [
"A", # flake8-builtins
"COM", # flake8-commas
"C4", # flake8-comprehensions
- "D2", # docstring layout; dev lint checks presence with route and model context
- "D213", # 多行文档字符串的摘要从第二行开始
- "D3", # docstring quotation marks
- "D4", # docstring content
+ "D", # pydocstyle
+ "D213", # Start multiline docstring summaries on the second line.
"ISC", # flake8-implicit-str-concat
"ICN", # flake8-import-conventions
"PIE", # flake8-pie
@@ -41,6 +39,10 @@ ignore = [
"ANN401", # dynamically typed expressions (typing.Any) are disallowed in {name}
"B008", # do not perform function calls in argument defaults
"COM812", # trailing comma missing
+ "D100", # The project forbids module docstrings.
+ "D102", # The project checks method docstrings and exempts route handlers.
+ "D103", # The project checks function docstrings and exempts route handlers.
+ "D104", # The module docstring ban also applies to package __init__.py files.
"D400", # dev lint checks terminal punctuation in both Chinese and English
"RET504", # unnecessary assignment to {name} before return statement
"SIM105", # use contextlib.suppress({exception}) instead of try-except-pass
@@ -56,7 +58,7 @@ ignore = [
[lint.per-file-ignores]
"alembic/env.py" = ["D"] # Preserve Alembic's original documentation.
-"common/router.py" = ["D205"] # APIRouterPro retains the original FastAPI example.
+"common/router.py" = ["D107", "D205"] # Preserve the original APIRouterPro constructor and documentation.
[lint.flake8-type-checking]
runtime-evaluated-base-classes = ["pydantic.BaseModel", "sqlalchemy.orm.DeclarativeBase"]
diff --git a/ruoyi-fastapi-test/ruff.toml b/ruoyi-fastapi-test/ruff.toml
index 7d0ab2b85..b1a103e12 100644
--- a/ruoyi-fastapi-test/ruff.toml
+++ b/ruoyi-fastapi-test/ruff.toml
@@ -13,7 +13,7 @@ select = [
"COM", # flake8-commas
"C4", # flake8-comprehensions
"D", # pydocstyle
- "D213", # 多行文档字符串的摘要从第二行开始
+ "D213", # Start multiline docstring summaries on the second line.
"ISC", # flake8-implicit-str-concat
"ICN", # flake8-import-conventions
"PIE", # flake8-pie
@@ -39,8 +39,8 @@ ignore = [
"ANN401", # dynamically typed expressions (typing.Any) are disallowed in {name}
"B008", # do not perform function calls in argument defaults
"COM812", # trailing comma missing
- "D100", # dev lint forbids module docstrings
- "D104", # the same file-header rule applies to packages
+ "D100", # The project forbids module docstrings.
+ "D104", # The module docstring ban also applies to package __init__.py files.
"D400", # dev lint checks terminal punctuation in both Chinese and English
"RET504", # unnecessary assignment to {name} before return statement
"SIM105", # use contextlib.suppress({exception}) instead of try-except-pass