Files
tdc-rs/tests/sspf_platform_package.rs
T
admin d10480abb6 feat(p2): 接入 sspf v0.3.0,单进程/单库/单端口双契约装配
- main.rs 改两阶段 assemble/finish,共用平台 PGlite;业务 Router 优先 + 平台兜底嵌套(绕开 6 条撞车路径)
- 新增 tdc/schema.rs 共库建表:跳过多条同源 base_* DDL,剥前导注释后按动词+对象名精确判定
- health 的 baseTables 按 migrate.sql 声明清单计数,共库后仍为 3
- on_ready 清理平台单-md5 admin 种子,由业务账号层按官方双 md5 重新引导
- 新增 check-dual-contract.sh 附加尺子(10 断言)与 CLAUDE.md 架构同步
- 验收:285 测试 / 五把尺子全绿 / 双契约 10-10
2026-11-04 20:29:15 +08:00

183 lines
7.3 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! P1 接入探针 —— 业务仓只靠 `sspf` 门面就能起一个「单端口 + 单库」的服务。
//!
//! 🔴 pglite 是**进程级单例** ⇒ 本文件只允许一个 `#[tokio::test]`。
//! 想加断言就加在这一个函数里,别新开测试(第二个 `PGlite::open()` 会直接失败)。
//!
//! 🔴 这条测试**不改** tdc 自研装配(`src/main.rs` 仍走老链),验的是「平台包在
//! 业务仓里可用」:`Platform` builder 能编译、能开库、能注入 tdc 风格的 DDL 与
//! 自定义路由、面 B 全套仍在、示例业务包不会跟着进门。这是 P1 换装配的前置判据。
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use axum::routing::get;
use serde_json::Value;
use sspf::{Config, Db, Platform};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
/// 注入的业务建表 SQL(tdc 风格列名)。走 `Platform::ddl` 建进**同一个 `Db`**。
const PROBE_DDL: &str = r#"
CREATE TABLE IF NOT EXISTS p1_probe_item (
f_id VARCHAR(36) NOT NULL,
f_title VARCHAR(200),
f_tenant_id VARCHAR(36) DEFAULT '0' NOT NULL,
PRIMARY KEY (f_id, f_tenant_id)
)
"#;
/// 模拟 tdc 的一条自定义业务端点(不依赖平台状态)。
async fn ping() -> &'static str {
"pong"
}
/// 起一个监听,返回端口。
async fn serve(app: axum::Router) -> u16 {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("绑定本地端口失败");
let port = listener.local_addr().expect("取本地地址失败").port();
let server = tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
tokio::task::yield_now().await;
// 🔴 服务要活到测试结束(drop JoinHandle 会 abort 掉 task)。
std::mem::forget(server);
port
}
/// 发一次请求,返回 `(状态码, JSON body)`。`body` 为空 ⇒ GET。
async fn http(port: u16, method: &str, path: &str, body: &str) -> (u16, Value) {
let req = if body.is_empty() {
format!("{method} {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")
} else {
format!(
"{method} {path} HTTP/1.1\r\n\
Host: 127.0.0.1\r\n\
Content-Type: application/x-www-form-urlencoded\r\n\
Content-Length: {}\r\n\
Connection: close\r\n\r\n{body}",
body.len()
)
};
let mut stream = TcpStream::connect(("127.0.0.1", port))
.await
.expect("连接失败");
stream.write_all(req.as_bytes()).await.expect("写请求失败");
let mut buf = Vec::new();
tokio::time::timeout(std::time::Duration::from_secs(20), stream.read_to_end(&mut buf))
.await
.expect("读响应超时")
.expect("读响应失败");
let text = String::from_utf8_lossy(&buf).to_string();
let (head, body) = text.split_once("\r\n\r\n").expect("响应必须有头体分隔");
let status = head
.lines()
.next()
.and_then(|l| l.split_whitespace().nth(1))
.and_then(|s| s.parse::<u16>().ok())
.expect("响应首行必须是 HTTP/1.1 <code> ...");
(status, serde_json::from_str(body.trim()).unwrap_or(Value::Null))
}
/// 某张表在 `public` schema 里存在吗(走平台自己的 `Db`,不新开库)。
async fn table_exists(db: &Db, table: &str) -> bool {
let sql = format!(
"SELECT count(*) FROM information_schema.tables \
WHERE table_schema = 'public' AND table_name = '{table}'"
);
match db.scalar_text(&sql).await.ok().flatten() {
Some(n) => n.trim() != "0",
None => false,
}
}
#[tokio::test]
async fn platform_package_boots_one_port_with_one_db() {
// 门面版本必须与业务仓 Cargo.toml 锁的 tag 对得上。
assert_eq!(sspf::VERSION, "0.3.0", "业务仓锁的是 sspf v0.3.0");
// ---- 配置:临时库(进程级单例 ⇒ 全文件只有这一个测试)----
let mut config = Config::from_env(PathBuf::from("/tmp/tdc-p1-platform-probe"));
config.pg_dir = PathBuf::from("memory://");
config.seed_admin_password = "123456".to_string();
// `on_ready` 是业务仓拿 `AppState`(同一个库)的唯一公开途径。
let slot: Arc<Mutex<Option<Db>>> = Arc::new(Mutex::new(None));
let slot_in_hook = slot.clone();
let app = Platform::new()
.config(config)
.ddl("p1_probe_item", PROBE_DDL)
// tdc 的 132 条自定义端点将来就从这里整体注入(形状 `/api/ssw/tdc/**`)。
.router(axum::Router::new().route("/api/ssw/tdc/P1Probe", get(ping)))
.on_ready(move |state| {
let slot = slot_in_hook.clone();
async move {
*slot.lock().expect("钩子里的锁不该中毒") = Some((*state.db).clone());
Ok(())
}
})
.build_app()
.await
.expect("业务仓必须能只靠 sspf 起一个 app");
let port = serve(app).await;
// ---- ① 平台端点活着,平台表已建(不是空库)----
let (status, health) = http(port, "GET", "/api/health", "").await;
assert_eq!(status, 200, "GET /api/health 必须 200");
assert_eq!(health["ok"], true, "health 必须 ok: {health}");
let tables = health["tables"].as_u64().expect("health 必须带 tables");
assert!(tables > 100, "平台表没建起来(tables={tables})");
// ---- ② 注入的业务 DDL 建进了**同一个库** ----
let db = slot
.lock()
.expect("锁不该中毒")
.clone()
.expect("on_ready 必须跑过(拿不到 Db ⇒ 启动钩子没执行)");
assert!(
table_exists(&db, "p1_probe_item").await,
"Platform::ddl 建的表必须落在同一个库里"
);
// ---- ③ 平台包里零业务:示例包的表与路由都不该出现 ----
for table in ["demo_item", "shop_product", "book_shop_book", "asset_data_resource"] {
assert!(
!table_exists(&db, table).await,
"示例包的表 {table} 不该存在 —— 门面默认不注入任何业务包"
);
}
let (status, body) = http(port, "GET", "/api/demo/DemoItem", "").await;
assert_eq!(status, 404, "示例包的路由不该注册: {body}");
// ---- ④ JNPF 兼容面(面 B)仍在:官方登录形状必须 200 ----
let enc = sspf::cipher::encrypt_password("123456");
let (status, body) = http(
port,
"POST",
"/api/oauth/Login",
&format!("account=admin&password={enc}"),
)
.await;
assert_eq!(status, 200, "面 B 登录必须 200: {body}");
assert_eq!(body["code"], 200, "登录必须成功(种子 admin 已就位): {body}");
assert!(
body["data"]["token"].as_str().is_some_and(|t| !t.is_empty()),
"登录必须返回 token: {body}"
);
// ---- ⑤ 注入的业务端点与平台端点**同一个端口** ----
let (status, body) = http(port, "GET", "/api/ssw/tdc/P1Probe", "").await;
assert_eq!(status, 200, "注入的业务端点必须 200: {body}");
// ---- ⑥ 表数不随请求变化(同一个库、同一个装配)----
let (_, again) = http(port, "GET", "/api/health", "").await;
assert_eq!(
again["tables"].as_u64().expect("health 必须带 tables"),
tables,
"表数不该随请求变化"
);
}