refactor: refactor of backend

This commit is contained in:
sophie committed 2026-09-28 14:52:28 +08:00
1 parent d4cb8c5def
commit 14e5af0c9c
55 files changed
+2251 -1805

No files matched your search

@@ -0,0 +1,101 @@
"""
backend/tests/test_env_settings_refresh_cache.py
用途:验证 app_settings 进程内 TTL 缓存,避免 before_request 每请求打库。
依赖:pytest、env_persistence、Flask app fixture。
逻辑:断言 TTL 内二次 apply 不读库;force / invalidate / TTL=0 强制重载;persist 后失效缓存。
"""
from __future__ import annotations
from app.core.config import env_persistence
def test_apply_env_settings_reuses_cache_within_ttl(app, monkeypatch):
"""TTL 内第二次 apply 不应再调用 _load_from_db。"""
env_persistence.invalidate_env_settings_cache()
monkeypatch.setitem(app.config, 'APP_SETTINGS_REFRESH_SECONDS', 60)
calls = {'db': 0, 'file': 0}
def _fake_db(prefixes):
calls['db'] += 1
return {'WECOM_CORP_ID': 'corp-cached'}
def _fake_file(prefixes):
calls['file'] += 1
return {}
monkeypatch.setattr(env_persistence, '_load_from_db', _fake_db)
monkeypatch.setattr(env_persistence, '_load_from_env_file', _fake_file)
with app.app_context():
first = env_persistence.apply_env_settings(force=True)
second = env_persistence.apply_env_settings()
assert first['WECOM_CORP_ID'] == 'corp-cached'
assert second['WECOM_CORP_ID'] == 'corp-cached'
assert calls['db'] == 1
assert calls['file'] == 1
def test_apply_env_settings_force_bypasses_ttl(app, monkeypatch):
"""force=True 即使在 TTL 内也重新读库。"""
env_persistence.invalidate_env_settings_cache()
monkeypatch.setitem(app.config, 'APP_SETTINGS_REFRESH_SECONDS', 60)
calls = {'db': 0}
def _fake_db(prefixes):
calls['db'] += 1
return {'WECOM_CORP_ID': f'corp-{calls["db"]}'}
monkeypatch.setattr(env_persistence, '_load_from_db', _fake_db)
monkeypatch.setattr(env_persistence, '_load_from_env_file', lambda prefixes: {})
with app.app_context():
env_persistence.apply_env_settings(force=True)
env_persistence.apply_env_settings(force=True)
assert calls['db'] == 2
def test_persist_env_settings_invalidates_cache(app, monkeypatch):
"""persist 后缓存失效,下一次 apply 会重新读库。"""
env_persistence.invalidate_env_settings_cache()
monkeypatch.setitem(app.config, 'APP_SETTINGS_REFRESH_SECONDS', 60)
calls = {'db': 0}
def _fake_db(prefixes):
calls['db'] += 1
return {'WECOM_CORP_ID': f'corp-{calls["db"]}'}
monkeypatch.setattr(env_persistence, '_load_from_db', _fake_db)
monkeypatch.setattr(env_persistence, '_load_from_env_file', lambda prefixes: {})
monkeypatch.setattr(env_persistence, '_persist_to_db', lambda values: True)
monkeypatch.setattr(env_persistence, '_persist_to_env_file', lambda values: True)
with app.app_context():
env_persistence.apply_env_settings(force=True)
assert calls['db'] == 1
env_persistence.persist_env_settings({'WECOM_CORP_ID': 'corp-new'})
env_persistence.apply_env_settings()
assert calls['db'] == 2
def test_ttl_zero_reloads_every_time(app, monkeypatch):
"""APP_SETTINGS_REFRESH_SECONDS=0 时每次强制读库。"""
env_persistence.invalidate_env_settings_cache()
monkeypatch.setitem(app.config, 'APP_SETTINGS_REFRESH_SECONDS', 0)
calls = {'db': 0}
def _fake_db(prefixes):
calls['db'] += 1
return {'WECOM_CORP_ID': 'x'}
monkeypatch.setattr(env_persistence, '_load_from_db', _fake_db)
monkeypatch.setattr(env_persistence, '_load_from_env_file', lambda prefixes: {})
with app.app_context():
env_persistence.apply_env_settings()
env_persistence.apply_env_settings()
assert calls['db'] == 2
+15 -15
View File
@@ -300,7 +300,7 @@ def test_file_check_tool_accepts_any_valid_task(app, client, monkeypatch):
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
monkeypatch.setattr('app.api.tools.file_check.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
@@ -388,7 +388,7 @@ def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkey
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
monkeypatch.setattr('app.api.tools.file_check.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -432,7 +432,7 @@ def test_file_check_tool_no_data_creates_bound_completed_run_with_full_progress(
task_id = task.id
before_count = ScheduleRun.query.filter_by(schedule_task_id=task_id).count()
monkeypatch.setattr('app.api.file_check_tools._precheck_no_data', lambda _task: {
monkeypatch.setattr('app.api.tools.file_check._precheck_no_data', lambda _task: {
'ok': False,
'error_code': 'no_data_to_check',
'message': '目前没有资料需要检核',
@@ -494,7 +494,7 @@ def test_file_check_tool_no_data_keeps_existing_running_conflict_priority(app, c
db.session.commit()
task_id = task.id
monkeypatch.setattr('app.api.file_check_tools._precheck_no_data', lambda _task: {
monkeypatch.setattr('app.api.tools.file_check._precheck_no_data', lambda _task: {
'ok': False,
'error_code': 'no_data_to_check',
'message': '目前没有资料需要检核',
@@ -553,11 +553,11 @@ def test_file_check_tool_precheck_data_source_unavailable_on_runtime_error(app,
data_source = None
monkeypatch.setattr(
'app.api.file_check_tools.get_schedule_sql_config_by_task_id',
'app.api.tools.file_check.get_schedule_sql_config_by_task_id',
lambda _task_id: _SqlConfig(),
)
monkeypatch.setattr(
'app.api.file_check_tools._build_srm_conn_str',
'app.api.tools.file_check._build_srm_conn_str',
lambda: (_ for _ in ()).throw(RuntimeError('SRM_SQLSERVER_HOST is not configured')),
)
@@ -588,15 +588,15 @@ def test_file_check_tool_precheck_data_source_unavailable_on_pyodbc_error(app, c
data_source = None
monkeypatch.setattr(
'app.api.file_check_tools.get_schedule_sql_config_by_task_id',
'app.api.tools.file_check.get_schedule_sql_config_by_task_id',
lambda _task_id: _SqlConfig(),
)
monkeypatch.setattr(
'app.api.file_check_tools._build_srm_conn_str',
'app.api.tools.file_check._build_srm_conn_str',
lambda: 'DRIVER={SQL Server};SERVER=127.0.0.1;DATABASE=test;UID=u;PWD=p',
)
monkeypatch.setattr(
'app.api.file_check_tools._fetch_records',
'app.api.tools.file_check._fetch_records',
lambda *_args, **_kwargs: (_ for _ in ()).throw(pyodbc.InterfaceError('IM002', 'driver not found')),
)
@@ -628,7 +628,7 @@ def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
monkeypatch.setattr('app.api.tools.file_check.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
@@ -1167,7 +1167,7 @@ def test_file_check_tool_excel_download_works_without_tool_api_key(app, client):
with app.app_context():
run = db.session.get(ScheduleRun, run_id)
from app.api.file_check_tools import _build_excel_download_url
from app.api.tools.file_check import _build_excel_download_url
download_url = _build_excel_download_url(run)
download_path = download_url[download_url.index('/api/file-check'):]
@@ -1239,7 +1239,7 @@ def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeyp
enqueued.append({"args": args, "kwargs": kwargs})
return 1
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
monkeypatch.setattr('app.api.tools.file_check.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -1262,7 +1262,7 @@ def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeyp
def test_serialize_file_judgement_reads_file_key():
from app.api.workspace_file_check import serialize_file_judgement
from app.api.workspace.file_check import serialize_file_judgement
payload = {
"response_summary_json": {
@@ -1823,7 +1823,7 @@ def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, mo
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
monkeypatch.setattr('app.api.tools.file_check.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -2008,7 +2008,7 @@ def _stub_file_check_thread(monkeypatch):
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
monkeypatch.setattr('app.api.tools.file_check.enqueue', _enqueue)
def _file_check_agent_proxy(task_id: int):
@@ -119,7 +119,7 @@ def test_stp_auto_create_failed_commit_must_raise():
def test_tool_payload_strips_forged_actor_fields(app):
"""Tool API 请求体中的操作人字段必须被剥离,不得进入服务层。"""
from app.api.shipping_notice_tools import _payload
from app.api.tools.shipping_notice import _payload
with app.test_request_context(
'/api/shipping-notice/tools/confirm_inventory_source',