PayrollManagementSystem/backend/tests/unit/test_tplus_connection_file.py

122 lines
3.6 KiB
Python
Raw Normal View History

"""显式连接文件不应污染应用配置,也不能启用未授权的数据源。"""
import json
import pytest
from app.core.config import Settings
from app.core.tplus_db import resolve_tplus_settings
def test_未开启连接时不读取配置文件(tmp_path):
settings = Settings(
_env_file=None,
app_secret_key="x" * 32,
t_plus_connection_file=str(tmp_path / "missing.json"),
)
with pytest.raises(RuntimeError, match="未启用"):
resolve_tplus_settings(settings)
def test_文件连接只覆盖源字段且原Settings不变(tmp_path):
path = tmp_path / "reader.json"
path.write_text(
json.dumps(
{
"host": "127.0.0.1",
"port": 1433,
"database": "UFTData",
"user": "reader",
"password": "test-only-value",
"driver": "SQL Server",
}
),
encoding="utf-8",
)
settings = Settings(
_env_file=None,
app_secret_key="x" * 32,
t_plus_enabled=True,
t_plus_connection_file=str(path),
)
resolved = resolve_tplus_settings(settings)
assert resolved.t_plus_database == "UFTData"
assert resolved.mysql_database == settings.mysql_database
assert settings.t_plus_password == ""
assert "test-only-value" not in str(resolved.t_plus_database_url)
def test_连接文件不接受sa或应用配置覆盖(tmp_path):
path = tmp_path / "bad.json"
path.write_text(
json.dumps(
{
"host": "127.0.0.1",
"port": 1433,
"database": "UFTData",
"user": "sa",
"password": "test-only-value",
"driver": "SQL Server",
"app_secret_key": "bad",
}
),
encoding="utf-8",
)
settings = Settings(
_env_file=None,
app_secret_key="x" * 32,
t_plus_enabled=True,
t_plus_connection_file=str(path),
)
with pytest.raises(RuntimeError):
resolve_tplus_settings(settings)
def test_生产连接文件允许显式授权的管理员账号(tmp_path):
path = tmp_path / "reader.json"
path.write_text(
json.dumps({
"host": "127.0.0.1", "port": 1433, "database": "test_source",
"user": "sa", "password": "test-only-value", "driver": "test_driver",
}),
encoding="utf-8",
)
settings = Settings(
_env_file=None,
app_secret_key="x" * 32,
app_env="prod",
t_plus_enabled=True,
t_plus_allow_admin_account=True,
t_plus_connection_file=str(path),
)
assert resolve_tplus_settings(settings).t_plus_user == "sa"
@pytest.mark.parametrize(
("environment", "allowed", "admin_allowed", "accepted"),
[
("dev", False, False, False),
("prod", True, False, False),
("dev", True, False, True),
("prod", False, True, True),
("prod", False, False, False),
],
)
def test_sa仅允许显式授权(environment, allowed, admin_allowed, accepted):
settings = Settings(
_env_file=None,
app_secret_key="x" * 32,
app_env=environment,
t_plus_enabled=True,
t_plus_user="sa",
t_plus_database="test_source",
t_plus_odbc_driver="test_driver",
t_plus_allow_dev_sa=allowed,
t_plus_allow_admin_account=admin_allowed,
)
if accepted:
assert resolve_tplus_settings(settings).t_plus_user == "sa"
else:
with pytest.raises(RuntimeError, match="管理员账号未获授权"):
resolve_tplus_settings(settings)