"""获准隔离 PG 后验证模板保护、独立提交与角色,不使用共享事务替身。""" import psycopg import pytest from psycopg.conninfo import conninfo_to_dict, make_conninfo from muse.共享.调用身份 import 用途 pytestmark = pytest.mark.数据库 @pytest.mark.case_id("NC-database-baseline-pg-01") def test_克隆保留真实提交且后例没有前例数据(数据库底座, tmp_path): with 数据库底座.借库(tmp_path / "first", (1,)) as 一: with 一[用途.维护].连接() as 连: 连.execute("CREATE TABLE public.clone_probe (id serial PRIMARY KEY, value text)") 连.execute("INSERT INTO public.clone_probe(value) VALUES ('first')") with 一[用途.维护].连接() as 连: assert 连.execute("SELECT id, value FROM public.clone_probe").fetchone() == (1, "first") 第一库 = 连.info.dbname with 数据库底座.借库(tmp_path / "second", (1,)) as 二: with 二[用途.维护].连接() as 连: assert 连.info.dbname != 第一库 assert 连.execute("SELECT to_regclass('public.clone_probe')").fetchone() == (None,) 连.execute("CREATE TABLE public.clone_probe (id serial PRIMARY KEY, value text)") assert 连.execute( "INSERT INTO public.clone_probe(value) VALUES ('second') RETURNING id" ).fetchone() == (1,) for 用途值, 角色 in [(用途.生产, "muse_app"), (用途.评测, "muse_eval")]: with 二[用途值].连接() as 连: assert 连.execute("SELECT current_user").fetchone() == (角色,) # 此基线本 session 无论消费多少例都只执行一轮,clone 不再执行迁移。 模板 = 数据库底座.基线((1,)) assert ( len([e for e in 数据库底座.事件 if e["action"] == "ddl" and e["database"] == 模板.名称]) == 1 ) @pytest.mark.case_id("NC-database-baseline-pg-02") def test_封存模板拒绝直接连接且失败用例精确清理(数据库底座, 隔离数据库URL, tmp_path): 模板 = 数据库底座.基线((1,)) 参数 = conninfo_to_dict(隔离数据库URL) 参数.update(dbname=模板.名称, connect_timeout="2") with pytest.raises(psycopg.OperationalError): psycopg.connect(make_conninfo(**参数)) 库名 = None with pytest.raises(ValueError), 数据库底座.借库(tmp_path / "failed", (1,)) as 工厂: with 工厂[用途.维护].连接() as 连: 库名 = 连.info.dbname raise ValueError("模拟测试失败") with psycopg.connect(隔离数据库URL) as 连: assert ( 连.execute("SELECT 1 FROM pg_database WHERE datname = %s", (库名,)).fetchone() is None )