182 lines
8.3 KiB
Python
182 lines
8.3 KiB
Python
"""seed 与清理脚本一起守着的那两个账号:内置超管 + 本地应急管理员。
|
||
|
||
应急管理员必须是 seed 的一部分,而不是"谁记得就手动建一个":清库脚本会清 ``accounts``,
|
||
重建库也会把它抹掉,而最需要它的恰恰是刚清完库、Hub 又配错、谁都进不去门的那一刻。
|
||
这次翻过一次车,所以三条都钉住:seed 建得出、删了能长回来、它的口令绝不送去 Hub。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import pytest
|
||
|
||
from app.config import settings
|
||
|
||
DB_READY = True
|
||
try:
|
||
from app.db import ensure_database, get_engine
|
||
|
||
ensure_database()
|
||
with get_engine().connect() as _probe:
|
||
_probe.exec_driver_sql("SELECT 1")
|
||
except Exception: # pragma: no cover
|
||
DB_READY = False
|
||
|
||
needs_db = pytest.mark.skipif(not DB_READY, reason="测试库连不上")
|
||
|
||
|
||
def test_built_in_accounts_are_local_only_without_being_configured(monkeypatch):
|
||
"""``local_only_accounts`` 写空也算数:内置的本地账号永远不去问 Hub。"""
|
||
monkeypatch.setattr(settings.seed, "admin_account", "seedadmin", raising=False)
|
||
monkeypatch.setattr(settings.seed, "emergency_account", "seedbackup", raising=False)
|
||
monkeypatch.setattr(settings.hub, "local_only_accounts", "", raising=False)
|
||
assert {"seedadmin", "seedbackup"} <= settings.hub.local_only_account_set
|
||
|
||
|
||
def test_the_second_door_is_off_by_default(monkeypatch):
|
||
"""默认只有一把本地门:``emergency_account`` 留空或跟超管同名,都不该多出第二个账号。"""
|
||
monkeypatch.setattr(settings.seed, "emergency_account", "", raising=False)
|
||
assert settings.seed.emergency_account == ""
|
||
monkeypatch.setattr(settings.seed, "admin_account", "localadmin", raising=False)
|
||
monkeypatch.setattr(settings.seed, "emergency_account", "localadmin", raising=False)
|
||
from app.seed import _seed_emergency_admin # 同名时不该建号,也不该报错
|
||
|
||
assert _seed_emergency_admin(_NullSession()) == 0
|
||
|
||
|
||
class _NullSession:
|
||
"""同名那条分支在查库之前就返回,所以不需要真会话。"""
|
||
|
||
def execute(self, *_a, **_kw):
|
||
raise AssertionError("账号名与内置超管相同时,不该去查库")
|
||
|
||
|
||
def test_clean_script_protects_the_built_in_accounts(monkeypatch):
|
||
"""清理脚本留着的账号必须跟 seed 建的是同一批,否则清一次库门就没了。"""
|
||
import sys
|
||
from pathlib import Path as _Path
|
||
|
||
sys.path.insert(0, str(_Path(__file__).resolve().parent.parent / "scripts"))
|
||
import clean_demo_data
|
||
|
||
monkeypatch.setattr(settings.seed, "admin_account", "seedadmin", raising=False)
|
||
monkeypatch.setattr(settings.seed, "emergency_account", "seedbackup", raising=False)
|
||
assert set(clean_demo_data._protected_accounts()) == {"seedadmin", "seedbackup"}
|
||
|
||
# 第二把门关着时就只剩一个,且不会漏出空字符串
|
||
monkeypatch.setattr(settings.seed, "emergency_account", "", raising=False)
|
||
assert clean_demo_data._protected_accounts() == ("seedadmin",)
|
||
|
||
|
||
@needs_db
|
||
def test_seed_creates_the_emergency_admin_when_the_library_lacks_it(client, monkeypatch):
|
||
"""库里没有这个账号时 seed 要能把它建出来:在编、系统管理员、本地口令可用。
|
||
|
||
故意换一个探针名字来验"从零建号",不去删真账号——真账号可能被业务单据引用
|
||
(``biz_revision.creator_id`` 是 RESTRICT),删它等于把用例变成清理现场。
|
||
"""
|
||
from datetime import datetime
|
||
|
||
from sqlalchemy import delete, select
|
||
|
||
from app.db import SessionFactory
|
||
from app.models import Account, PermAccountRole, Status
|
||
from app.security import verify_password
|
||
from app.seed import seed_all
|
||
|
||
probe = f"seedprobe{datetime.now():%H%M%S%f}"
|
||
password = settings.seed.emergency_password or "Probe@12345"
|
||
monkeypatch.setattr(settings.seed, "emergency_account", probe, raising=False)
|
||
monkeypatch.setattr(settings.seed, "emergency_password", password, raising=False)
|
||
|
||
assert seed_all()["emergency"] == 1, "库里没有应急账号时 seed 必须把它建出来"
|
||
assert seed_all()["emergency"] == 0, "已经有了就不该重复建号"
|
||
|
||
with SessionFactory()() as db:
|
||
row = db.execute(select(Account).where(Account.account == probe)).scalars().first()
|
||
assert row is not None, "seed 报了建号却没落库"
|
||
assert row.is_system_admin, "应急管理员得是全权限"
|
||
assert row.source == "local" and row.status == Status.ACTIVE
|
||
assert row.hub_user_id is None, "本地应急账号不该带统一身份主键"
|
||
assert verify_password(password, row.password_hash)
|
||
assert not verify_password(f"{password}-不对", row.password_hash)
|
||
db.execute(delete(PermAccountRole).where(PermAccountRole.account_id == row.id))
|
||
db.delete(row)
|
||
db.commit()
|
||
|
||
|
||
@needs_db
|
||
def test_local_admin_password_never_leaves_the_system(client, monkeypatch):
|
||
"""内置本地账号的口令只在本系统校验——就算整档是 ``login_mode = hub``。
|
||
|
||
这是本地门的全部意义:Hub 密钥配错、应用没登记的时候还得进得去门。这条一旦破功,
|
||
"应急入口"就跟着 Hub 一起挂掉了。
|
||
"""
|
||
from app.api import auth as auth_api
|
||
from app.service import hub_api
|
||
|
||
def boom(*args, **kwargs):
|
||
raise AssertionError("内置本地账号的口令不该被送去统一身份")
|
||
|
||
monkeypatch.setattr(auth_api.settings.hub, "login_mode", "hub", raising=False)
|
||
monkeypatch.setattr(hub_api, "login_with_password", boom)
|
||
|
||
names = [settings.seed.admin_account, settings.seed.emergency_account]
|
||
for name in [n for n in names if n]:
|
||
password = (settings.seed.admin_password if name == settings.seed.admin_account
|
||
else settings.seed.emergency_password)
|
||
if not password:
|
||
continue # 随机口令的部署拿不来登,交给 seed 那条用例验
|
||
response = client.post("/api/v1/auth/login", json={"account": name, "password": password})
|
||
assert response.status_code == 200, f"{name} 登不上:{response.text}"
|
||
data = response.json()["data"]
|
||
assert data["via"] == "local"
|
||
assert data["user"]["isSystemAdmin"] == 1
|
||
|
||
|
||
@needs_db
|
||
def test_legacy_duplicate_configs_merge_into_calc_then_disappear():
|
||
"""两条"界面上有、内核从不读"的重复参数只能留一套口径。
|
||
|
||
搬完还得承认人在界面上存过的值,同时不能把口径页上后来改的值盖掉。用例整个跑在
|
||
一个回滚掉的事务里——这是台共用的开发库。
|
||
"""
|
||
from sqlalchemy import select
|
||
|
||
from app.db import SessionFactory
|
||
from app.models import SystemConfig
|
||
from app.seed import _seed_configs
|
||
from app.service.calc import rules
|
||
|
||
spec = rules.SPECS_BY_CODE["calc.company_manage_fee_rate"]
|
||
session = SessionFactory()()
|
||
try:
|
||
target = session.execute(select(SystemConfig).where(
|
||
SystemConfig.code == spec.code)).scalars().first()
|
||
assert target is not None, "startup seed 该把 calc.* 补齐"
|
||
original_value = target.value
|
||
original_type = target.value_type
|
||
|
||
session.add(SystemConfig(code="finance.company_manage_fee_rate",
|
||
name="公司管理费用率(%)", value="3.5", value_type="number",
|
||
group="calc", remark="旧参数"))
|
||
session.flush() # sessionmaker 关着 autoflush,不 flush 这条旧参数查不出来
|
||
# 假装新编码从没被改过,看看旧值搬不搬得过来
|
||
target.value = spec.default_text
|
||
assert _seed_configs(session) >= 0
|
||
session.flush()
|
||
|
||
assert target.value == "3.5", "界面上存过的值必须在迁移时被承认"
|
||
assert session.execute(select(SystemConfig).where(
|
||
SystemConfig.code == "finance.company_manage_fee_rate")).scalars().first() is None, \
|
||
"旧参数合并完就该删掉,别留两处口径"
|
||
assert session.execute(select(SystemConfig).where(
|
||
SystemConfig.code == "budget.travel_business_limit_rate")).scalars().first() is None
|
||
|
||
# 再跑一次不该重复插,也不该把值改回去
|
||
assert _seed_configs(session) == 0
|
||
assert target.value == "3.5"
|
||
finally:
|
||
session.rollback()
|
||
session.close()
|
||
assert original_value is not None and original_type == "number"
|