Files
ssw-platform/crates/tests/tests/batch14_it.rs
T
admin acf076df5a refactor: 内核瘦身 —— 示例搬成业务包 + 装配/测试各归其位
- 内核只有 lib:启动装配 → crates/sspf-admin(bin sspf-admin);37 个集成测试 → crates/tests(package sspf-tests)。
- demo/shop/books 的 spec/菜单/DDL/面 B 路由搬进 packs/{demo,shop,books};内核 modules/*.rs 只剩「面 A 适配器 + pub use」⇒ 内核零业务知识,示例可整目录搬走。面 A 与前端零改动。
- 示例表 DDL 按平台规则补 f_tenant_id + 复合主键(spec 不加 ⇒ JSON 键与响应逐字不变)。
- 修 is_builtin_table 只认 schema.sql 的漏洞:包表(含 asset_data_resource)此前可被建模页删除/改;现为「平台 DDL ∪ 包表」。
- sspf-compat-online_dev → onlinedev(包名/模块/文件/路由别名同步);6 个 5 行转发壳合并为 forward.rs。
- 新增 AR16 闸门 + lib.rs「30 秒地图」+ src/backend/README.md;pack-sync 补两处判据(module_key=None 的 urlAddress、apiFile 查存在性)。
- 回归:704 tests / 6 道静态闸门全绿;health 181 表;四个包面 A/面 B 运行时全部 200。
2026-11-04 14:46:12 +08:00

629 lines
22 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.
//! 批次 14(**数据中心五族 + 数据同步**)集成测试:
//! `BasicDataType`(4) + `DataTypeMapping`(6) + `DataBase`(5) + `DataTypeRelation`(5)
//! + `CommonFields`(4) + `DataSync`(4) + `DataInterfaceVariate`(1) = 29 端点,
//! 4 张表(`base_data_type_mapping` / `base_data_base` / `base_data_type_relation` /
//! `base_data_interface_variate`)。
//!
//! 🔴 **钉住的契约点**(每条都是「照抄官方会翻车 / 不照抄也会翻车」的地方):
//! ① `BasicDataType` 是 **`enCode` 与 `fullName` 双判重** —— 只判一个就能造出
//! 「同码不同名」的影子类型,前端下拉按 enCode 反查会拿到两行。
//! ② `type` **不进写白名单**:官方 `DataTypeForm` 里没有这个字段。允许 PUT 改它
//! = 允许把自定义类型伪装成内置(`type=1`),而内置是**删不掉**的。
//! ③ 删除保护两层:内置(`type=1`)拒;被控件映射 / 字段类型映射 / 常用字段引用拒。
//! ④ 🔴 **控件映射与字段类型映射的列表把 `typeId` 覆盖成「名字」**,而
//! `GET /{id}` 返回**真 id**(官方 `DataTypeMappingController:60-68`)——
//! 这是官方最反直觉的一处:同一字段,列表里是 `字符串名称`,详情里是 `id`。
//! ⑤ `DataTypeRelation` 的判重是**二元组 `enCode + baseId`**:同一个 enCode
//! 在不同目标库下可以各有一条(只按 enCode 判重会让第二个库配不了)。
//! ⑥ 常用字段先挡 **SQL/Java 保留字**(列名要拿去建表),再判 `field + category`。
//! ⑦ 数据同步四条**一律明确业务失败**(`code=400`)—— 本仓是内嵌单实例 PG,
//! 没有驱动层。**不能返回成功**:那会让用户以为数据搬过去了。
//! ⑧ 接口变量下拉是**两级树**:数据集 `type=0` / 变量 `type=1`,
//! 变量的 `fullName` 是 `数据集enCode.变量名`(前端拿它当表达式引用)。
//!
//! 🔴 pglite-rs 是**进程级全局标志** ⇒ 全文件共用一个临时库 + 一把互斥锁。
//! 断言一律按 id 定位,不数「列表里有几条」—— 同一个库里还有别的用例造的行。
use std::path::PathBuf;
use std::sync::Arc;
use serde_json::{json, Value};
use ssw_platform::bootstrap::ensure_base;
use sspf_core::config::Config;
use sspf_core::db::Db;
use sspf_core::seed::first_seed;
use sspf_core::session::{SessionStore, TicketStore};
use sspf_core::state::AppState;
use ssw_platform::routes::build_app;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::sync::{Mutex, OnceCell};
static DB: OnceCell<Db> = OnceCell::const_new();
static LOCK: Mutex<()> = Mutex::const_new(());
async fn db() -> &'static Db {
DB.get_or_init(|| async {
let db = Db::open_temp().await.expect("打开 pglite 临时库失败");
ssw_platform::bootstrap::ensure_schema_all(&db)
.await
.expect("ensure_schema_all 失败");
ensure_base(&db).await.expect("ensure_base 失败");
first_seed(&db, "123456").await.expect("first_seed 失败");
db
})
.await
}
async fn serve(state: AppState) -> u16 {
let listener = tokio::net::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, build_app(state)).await;
});
tokio::task::yield_now().await;
std::mem::forget(server);
port
}
async fn call(
port: u16,
method: &str,
path: &str,
token: &str,
body: Option<&str>,
) -> (String, Value) {
let mut stream = TcpStream::connect(("127.0.0.1", port)).await.expect("连接失败");
let payload = body.unwrap_or("");
let req = format!(
"{method} {path} HTTP/1.1\r\n\
Host: 127.0.0.1\r\n\
Vue-Version: 3\r\n\
App-Code: mainSystem\r\n\
Authorization: {token}\r\n\
Content-Type: application/json\r\n\
Content-Length: {}\r\n\
Connection: close\r\n\r\n{payload}",
payload.len()
);
stream.write_all(req.as_bytes()).await.expect("写请求失败");
let mut buf = Vec::new();
tokio::time::timeout(std::time::Duration::from_secs(15), 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().unwrap_or_default().to_string();
let json: Value = serde_json::from_str(body.trim()).unwrap_or(Value::Null);
(status, json)
}
async fn login(port: u16) -> String {
let enc = sspf_core::cipher::encrypt_password("123456");
let payload = format!("account=admin&password={enc}");
let mut stream = TcpStream::connect(("127.0.0.1", port)).await.expect("连接失败");
let req = format!(
"POST /api/oauth/Login HTTP/1.1\r\n\
Host: 127.0.0.1\r\n\
Vue-Version: 3\r\n\
App-Code: mainSystem\r\n\
Content-Type: application/x-www-form-urlencoded\r\n\
Content-Length: {}\r\n\
Connection: close\r\n\r\n{payload}",
payload.len()
);
stream.write_all(req.as_bytes()).await.expect("写请求失败");
let mut buf = Vec::new();
tokio::time::timeout(std::time::Duration::from_secs(15), stream.read_to_end(&mut buf))
.await
.expect("读响应超时")
.expect("读响应失败");
let text = String::from_utf8_lossy(&buf).to_string();
let (_, body) = text.split_once("\r\n\r\n").expect("响应必须有头体分隔");
let json: Value = serde_json::from_str(body.trim()).expect("登录响应必须是 JSON");
json["data"]["token"].as_str().expect("登录必须返回 token").to_string()
}
fn new_state(db: &Db) -> AppState {
AppState {
config: Arc::new(Config::from_env(PathBuf::from("/tmp/ssw-platform-batch14-it"))),
db: Arc::new(db.clone()),
sessions: Arc::new(SessionStore::default()),
tickets: Arc::new(TicketStore::default()),
}
}
/// 按表 + 列取值(`create` 返 `null` ⇒ 拿不到 id,只能查库)。
async fn id_of(table: &str, column: &str, value: &str) -> String {
let v = value.to_string();
let sql = format!("SELECT f_id AS \"id\" FROM {table} WHERE {column} = $1::text LIMIT 1");
let rows = Db::query_json_params(db().await, &sql, &[&v])
.await
.expect("查 id 失败");
assert_eq!(rows.len(), 1, "库里应恰有一行 {table}.{column}={value}");
rows[0]["id"].as_str().expect("必须有 id").to_string()
}
/// 起服务 + 登录,返回 (port, token)。
async fn boot() -> (u16, String) {
let state = new_state(db().await);
let port = serve(state).await;
let token = login(port).await;
(port, token)
}
// ---------------------------------------------------------------- 基准数据类型
/// ① 双判重 + ② `type` 不可改 + ③ 删除保护。
#[tokio::test]
async fn basic_data_type_double_unique_and_type_is_immutable() {
let _guard = LOCK.lock().await;
let (port, token) = boot().await;
// 建一条自定义类型。
let (_, res) = call(
port,
"POST",
"/api/system/BasicDataType",
&token,
Some(r#"{"fullName":"B14类型甲","enCode":"b14_type_a","jnpfKey":"input"}"#),
)
.await;
assert_eq!(res["code"], 200, "新建应成功: {res}");
let id = id_of("base_data_type", "f_en_code", "b14_type_a").await;
// ① 同 enCode 不同名 ⇒ 拒(报编码)。
let (_, res) = call(
port,
"POST",
"/api/system/BasicDataType",
&token,
Some(r#"{"fullName":"B14类型乙","enCode":"b14_type_a","jnpfKey":"input"}"#),
)
.await;
assert_eq!(res["code"], 400, "同 enCode 必须拒: {res}");
assert!(
res["msg"].as_str().unwrap_or_default().contains("编码"),
"应报「编码已存在」: {res}"
);
// ① 同名不同 enCode ⇒ 也拒(报名称)。
let (_, res) = call(
port,
"POST",
"/api/system/BasicDataType",
&token,
Some(r#"{"fullName":"B14类型甲","enCode":"b14_type_b","jnpfKey":"input"}"#),
)
.await;
assert_eq!(res["code"], 400, "同名必须拒: {res}");
assert!(
res["msg"].as_str().unwrap_or_default().contains("名称"),
"应报「名称已存在」: {res}"
);
// 新建恒为自定义(type=2)。
let (_, info) = call(port, "GET", &format!("/api/system/BasicDataType/{id}"), &token, None).await;
assert_eq!(info["code"], 200, "详情应成功: {info}");
assert_eq!(info["data"]["type"], 2, "新建必须落成自定义(2): {info}");
// ② PUT 带 type=1 也不生效(type 不在写白名单里)。
let (_, res) = call(
port,
"PUT",
&format!("/api/system/BasicDataType/{id}"),
&token,
Some(r#"{"fullName":"B14类型甲改","enCode":"b14_type_a","jnpfKey":"input","type":1}"#),
)
.await;
assert_eq!(res["code"], 200, "更新应成功: {res}");
let rows = Db::query_json_params(
db().await,
"SELECT COALESCE(f_type, 0)::bigint AS \"type\" FROM base_data_type WHERE f_id = $1::text",
&[&id],
)
.await
.expect("查 type 失败");
assert_eq!(rows[0]["type"], 2, "type 必须仍是 2(白名单挡住)");
// ③ 被控件映射引用 ⇒ 拒删。
let (_, res) = call(
port,
"POST",
"/api/system/DataTypeMapping",
&token,
Some(&format!(
r#"{{"jnpfKey":"b14_key_x","typeId":"{id}","sortCode":1}}"#
)),
)
.await;
assert_eq!(res["code"], 200, "建映射应成功: {res}");
let (_, res) = call(
port,
"DELETE",
&format!("/api/system/BasicDataType/{id}"),
&token,
None,
)
.await;
assert_eq!(res["code"], 400, "被引用必须拒删: {res}");
assert!(
res["msg"].as_str().unwrap_or_default().contains("已被使用"),
"应报「已被使用」: {res}"
);
}
// ---------------------------------------------------------------- 控件映射
/// ④ 列表 `typeId` 是**名称**、详情 `typeId` 是**真 id**;⑤ getKeyList 分组。
#[tokio::test]
async fn data_type_mapping_list_shows_name_but_info_returns_id() {
let _guard = LOCK.lock().await;
let (port, token) = boot().await;
let (_, res) = call(
port,
"POST",
"/api/system/BasicDataType",
&token,
Some(r#"{"fullName":"B14映射类型","enCode":"b14_map_type","jnpfKey":"input"}"#),
)
.await;
assert_eq!(res["code"], 200, "建基准类型失败: {res}");
let type_id = id_of("base_data_type", "f_en_code", "b14_map_type").await;
let (_, res) = call(
port,
"POST",
"/api/system/DataTypeMapping",
&token,
Some(&format!(
r#"{{"jnpfKey":"b14_widget","typeId":"{type_id}","sortCode":7}}"#
)),
)
.await;
assert_eq!(res["code"], 200, "建映射失败: {res}");
let mapping_id = id_of("base_data_type_mapping", "f_type_id", &type_id).await;
// ④ 列表:typeId 被覆盖成「名称」。
let (_, list) = call(port, "GET", "/api/system/DataTypeMapping", &token, None).await;
assert_eq!(list["code"], 200, "列表失败: {list}");
let row = list["data"]["list"]
.as_array()
.expect("必须是 ListVO")
.iter()
.find(|r| r["id"] == json!(mapping_id))
.expect("列表里应有刚建的那条");
assert_eq!(
row["typeId"], "B14映射类型",
"列表里的 typeId 必须是**名称**(官方 :60-68 覆盖): {row}"
);
// ④ 详情:typeId 是**真 id**(编辑表单靠这条)。
let (_, info) = call(
port,
"GET",
&format!("/api/system/DataTypeMapping/{mapping_id}"),
&token,
None,
)
.await;
assert_eq!(info["code"], 200, "详情失败: {info}");
assert_eq!(
info["data"]["typeId"], type_id,
"详情里的 typeId 必须是**真 id**: {info}"
);
// ⑤ getKeyList:按基准类型聚合,jnpfKey 在数组里。
let (_, keys) = call(
port,
"GET",
"/api/system/DataTypeMapping/getKeyList",
&token,
None,
)
.await;
assert_eq!(keys["code"], 200, "getKeyList 失败: {keys}");
let group = keys["data"]
.as_array()
.expect("必须是数组")
.iter()
.find(|g| g["dataType"] == "b14_map_type")
.expect("应有刚建类型的分组");
assert!(
group["jnpfKeyList"]
.as_array()
.expect("jnpfKeyList 必须是数组")
.contains(&json!("b14_widget")),
"分组里应含 b14_widget: {group}"
);
}
// ---------------------------------------------------------------- 数据库管理
/// ⑥ `dbType` 单列判重;列表**登录即可**(官方 list 无权限注解)。
#[tokio::test]
async fn data_base_unique_by_db_type() {
let _guard = LOCK.lock().await;
let (port, token) = boot().await;
let (_, res) = call(
port,
"POST",
"/api/system/DataBase",
&token,
Some(
r#"{"fullName":"B14库甲","icon":"icon-a","dbType":"b14_dbtype","dbDrive":"org.postgresql.Driver","dbUrl":"jdbc:postgresql://h/db"}"#,
),
)
.await;
assert_eq!(res["code"], 200, "建库失败: {res}");
// 同 dbType、改名也不行(判重只看 dbType)。
let (_, res) = call(
port,
"POST",
"/api/system/DataBase",
&token,
Some(
r#"{"fullName":"B14库乙","icon":"icon-b","dbType":"b14_dbtype","dbDrive":"x","dbUrl":"y"}"#,
),
)
.await;
assert_eq!(res["code"], 400, "同 dbType 必须拒: {res}");
assert!(
res["msg"].as_str().unwrap_or_default().contains("数据库类型"),
"应报「数据库类型已存在」: {res}"
);
// 列表能查到(登录即可,返回 ListVO)。
let (_, list) = call(port, "GET", "/api/system/DataBase", &token, None).await;
assert_eq!(list["code"], 200, "列表失败: {list}");
assert!(
list["data"]["list"]
.as_array()
.expect("必须是 ListVO")
.iter()
.any(|r| r["dbType"] == "b14_dbtype"),
"列表里应有刚建的库: {list}"
);
}
// ---------------------------------------------------------------- 字段类型映射
/// ⑦ 判重是**二元组 enCode+baseId**(同 enCode 换库 ⇒ 允许);列表分页。
#[tokio::test]
async fn data_type_relation_unique_is_pair_en_code_and_base_id() {
let _guard = LOCK.lock().await;
let (port, token) = boot().await;
for (db_type, name) in [("b14_rel_db1", "B14关系库一"), ("b14_rel_db2", "B14关系库二")] {
let (_, res) = call(
port,
"POST",
"/api/system/DataBase",
&token,
Some(&format!(
r#"{{"fullName":"{name}","icon":"i","dbType":"{db_type}","dbDrive":"d","dbUrl":"u"}}"#
)),
)
.await;
assert_eq!(res["code"], 200, "建库失败: {res}");
}
let base1 = id_of("base_data_base", "f_db_type", "b14_rel_db1").await;
let base2 = id_of("base_data_base", "f_db_type", "b14_rel_db2").await;
// 库 1 建一条 enCode=b14_col。
let (_, res) = call(
port,
"POST",
"/api/system/DataTypeRelation",
&token,
Some(&format!(
r#"{{"baseId":"{base1}","enCode":"b14_col","type":1,"lengthDefault":64,"lengthMax":255,"lengthMin":1}}"#
)),
)
.await;
assert_eq!(res["code"], 200, "库1建映射失败: {res}");
// 库 1 再建同 enCode ⇒ 拒。
let (_, res) = call(
port,
"POST",
"/api/system/DataTypeRelation",
&token,
Some(&format!(
r#"{{"baseId":"{base1}","enCode":"b14_col","type":2}}"#
)),
)
.await;
assert_eq!(res["code"], 400, "同库同 enCode 必须拒: {res}");
// 库 2 建同 enCode ⇒ **允许**(二元组判重)。
let (_, res) = call(
port,
"POST",
"/api/system/DataTypeRelation",
&token,
Some(&format!(
r#"{{"baseId":"{base2}","enCode":"b14_col","type":3}}"#
)),
)
.await;
assert_eq!(res["code"], 200, "换库同 enCode 必须放行: {res}");
// 列表是 PageListVO(有 pagination)。
let (_, page) = call(
port,
"GET",
&format!("/api/system/DataTypeRelation?baseId={base1}&currentPage=1&pageSize=10"),
&token,
None,
)
.await;
assert_eq!(page["code"], 200, "列表失败: {page}");
assert!(
page["data"]["pagination"].is_object(),
"必须是 PageListVO(带 pagination): {page}"
);
assert_eq!(
page["data"]["pagination"]["total"], 1,
"库1应有 1 条: {page}"
);
}
// ---------------------------------------------------------------- 常用字段
/// ⑧ 保留字先挡(列名要建表);判重是 field+category。
#[tokio::test]
async fn common_fields_rejects_reserved_words() {
let _guard = LOCK.lock().await;
let (port, token) = boot().await;
// 保留字 ⇒ 拒(大小写不敏感)。
let (_, res) = call(
port,
"POST",
"/api/system/CommonFields",
&token,
Some(r#"{"fieldName":"生僻","field":" select ","dataType":"varchar","dataLength":"50","category":"b14_cat","type":2}"#),
)
.await;
assert_eq!(res["code"], 400, "保留字必须拒: {res}");
assert!(
res["msg"].as_str().unwrap_or_default().contains("保留字"),
"应报保留字: {res}"
);
// 正常列名 ⇒ 成功。
let (_, res) = call(
port,
"POST",
"/api/system/CommonFields",
&token,
Some(r#"{"fieldName":"B14列","field":"b14_col","dataType":"varchar","dataLength":"50","category":"b14_cat","type":2}"#),
)
.await;
assert_eq!(res["code"], 200, "正常列名应成功: {res}");
let id = id_of("base_common_fields", "f_field", "b14_col").await;
// 同 category 同 field ⇒ 拒。
let (_, res) = call(
port,
"POST",
"/api/system/CommonFields",
&token,
Some(r#"{"fieldName":"B14列2","field":"b14_col","dataType":"varchar","dataLength":"50","category":"b14_cat","type":2}"#),
)
.await;
assert_eq!(res["code"], 400, "同分组同列名必须拒: {res}");
// 换分组 ⇒ 允许。
let (_, res) = call(
port,
"POST",
"/api/system/CommonFields",
&token,
Some(r#"{"fieldName":"B14列3","field":"b14_col","dataType":"varchar","dataLength":"50","category":"b14_cat2","type":2}"#),
)
.await;
assert_eq!(res["code"], 200, "换分组应放行: {res}");
// 详情带 dataTypeName(联合基准类型取名称)。
let (_, info) = call(
port,
"GET",
&format!("/api/system/CommonFields/{id}"),
&token,
None,
)
.await;
assert_eq!(info["code"], 200, "详情失败: {info}");
assert_eq!(info["data"]["field"], "b14_col", "详情字段不对: {info}");
}
// ---------------------------------------------------------------- 数据同步
/// ⑦ 四条一律**明确失败**(不能返回 200 假装同步成功)。
#[tokio::test]
async fn data_sync_endpoints_refuse_explicitly() {
let _guard = LOCK.lock().await;
let (port, token) = boot().await;
for path in [
"/api/system/DataSync",
"/api/system/DataSync/Actions/checkDbLink",
"/api/system/DataSync/Actions/Execute",
"/api/system/DataSync/Actions/batchExecute",
] {
let (status, res) = call(port, "POST", path, &token, Some("{}")).await;
assert!(
status.contains("200"),
"{path} 的业务失败必须是 HTTP 200(信封决定成败): {status}"
);
assert_eq!(
res["code"], 400,
"{path} 必须明确失败(否则用户以为数据搬过去了): {res}"
);
assert!(
res["msg"].as_str().unwrap_or_default().contains("跨库"),
"{path} 的错误文案要说明是「跨库不支持」: {res}"
);
}
}
// ---------------------------------------------------------------- 接口变量下拉
/// ⑧ 两级树:数据集 type=0 / 变量 type=1,变量 fullName = `enCode.变量名`。
#[tokio::test]
async fn data_interface_variate_selector_is_two_level_tree() {
let _guard = LOCK.lock().await;
let (port, token) = boot().await;
// 直接写库造一条数据集 + 两条变量(本批次不补 DataSet 的增删改,它早就有)。
let set_id = "b14-set-0001";
let sql = format!(
"INSERT INTO base_data_set (f_id, f_full_name, f_en_code, f_enabled_mark, f_delete_mark, f_tenant_id) \
VALUES ('{set_id}', 'B14数据集', 'b14Dataset', 1, 0, '0')"
);
Db::exec_params(db().await, &sql, &[]).await.expect("造数据集失败");
for (vid, name) in [("b14-var-0001", "变量甲"), ("b14-var-0002", "变量乙")] {
let sql = format!(
"INSERT INTO base_data_interface_variate \
(f_id, f_interface_id, f_full_name, f_field, f_delete_mark, f_sort_code, f_tenant_id) \
VALUES ('{vid}', '{set_id}', '{name}', 'f_{vid}', 0, 1, '0')"
);
Db::exec_params(db().await, &sql, &[]).await.expect("造变量失败");
}
let (_, res) = call(
port,
"GET",
"/api/system/DataInterfaceVariate/Selector",
&token,
None,
)
.await;
assert_eq!(res["code"], 200, "下拉失败: {res}");
let node = res["data"]
.as_array()
.expect("必须是数组")
.iter()
.find(|n| n["id"] == json!(set_id))
.expect("应有刚造的数据集节点");
assert_eq!(node["type"], 0, "数据集节点 type=0: {node}");
assert_eq!(node["parentId"], "-1", "数据集 parentId=-1: {node}");
let kids = node["children"].as_array().expect("必须有 children");
assert_eq!(kids.len(), 2, "应有 2 个变量: {node}");
let first = &kids[0];
assert_eq!(first["type"], 1, "变量 type=1: {first}");
assert_eq!(first["parentId"], set_id, "变量 parentId=数据集 id: {first}");
assert_eq!(
first["fullName"], "b14Dataset.变量甲",
"变量 fullName 必须是 `enCode.变量名`: {first}"
);
}