影响:平台层不再认识业务类型(引导身份 / 本地账号库 / TDS 客户端 / 业务配置
全部移出 AppState);对外行为零变化(237 条测试全绿、冒烟断言数仍 75)。
改动:
- src/platform/state.rs:AppState 收敛为 {config, db, db_lock, sessions}
- src/tdc/state.rs(新):TdcState = platform + 业务配置 + 引导身份 + 账号库 + TDS 客户端
· Deref<Target = AppState> => 业务层字段访问(state.db 等)写法不变
· impl FromRef<TdcState> for AppState => axum 里 State<AppState> 仍可用
- src/main.rs:装配顺序改为 platform -> bootstrap_identity -> TdcState
- 控制器/服务/测试:入参一律换成 &TdcState(bootstrap_identity 仍是 &AppState,
它跑在装配期,那时 TdcState 还没造出来)
- scripts/check-boundary.sh:新增第 5 个接触点 CP5(平台层不得 use crate::tdc::),
专门盯这条反向依赖;CP1 只查表名/端点前缀,查不出模块引用
- CLAUDE.md / .workbuddy/memory/2026-10-26.md 同步
设计:FromRef 在 axum::extract(不是 axum::core::extract)=> 手写 impl。
920 lines
35 KiB
Rust
920 lines
35 KiB
Rust
//! CRUD 引擎端到端:新增 → 列表 → 关键字 → 过滤 → 修改 → 删除 → 各类拒因。
|
||
//!
|
||
//! ⚠️ 本测试二进制内共用一个 PGlite 实例(pglite-rs 每进程只允许一个)。
|
||
|
||
use std::collections::HashMap;
|
||
use std::sync::Arc;
|
||
|
||
use pglite::PGlite;
|
||
use serde_json::{json, Value};
|
||
use tdc_connector::platform::auth::Principal;
|
||
use tdc_connector::platform::config::Config;
|
||
use tdc_connector::tdc::service::crud;
|
||
use tdc_connector::tdc::entity;
|
||
use tdc_connector::platform::session::SessionStore;
|
||
use tdc_connector::platform::state::AppState;
|
||
use tdc_connector::tdc::config::TdcConfig;
|
||
use tdc_connector::tdc::state::{BootstrapIdentity, TdcState};
|
||
use tokio::sync::OnceCell;
|
||
|
||
static DB: OnceCell<Arc<PGlite>> = OnceCell::const_new();
|
||
|
||
/// 🔴 序列化「会写 `tdc_product` 的用例」。
|
||
///
|
||
/// 编码的序号基线是「**当日同前缀的行数**」⇒ 并行跑的用例会互相抬高基线 ⇒
|
||
/// 绝对值断言不可靠 ⇒ 需要一个进程内互斥量把写 `tdc_product` 的用例串起来。
|
||
///
|
||
/// ⚠️ 加锁顺序恒为 `PRODUCT_LOCK` → `db_lock`(`crud::*` 内部再拿 `db_lock`)⇒ 不会死锁。
|
||
static PRODUCT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
|
||
|
||
/// 数「当日同前缀」的行数(**含软删行** —— 与 Product/Resource 的基线口径一致:不带 `ALIVE`)。
|
||
async fn count_today_products(state: &tdc_connector::tdc::state::TdcState, pattern: &str) -> u64 {
|
||
let sql = "SELECT count(*)::text FROM tdc_product WHERE f_product_code LIKE CAST($1 AS text)";
|
||
let raw = {
|
||
let _g = state.db_lock.lock().await;
|
||
tdc_connector::platform::db::query_scalar_text(state.db.as_ref(), sql, &[&pattern])
|
||
.await
|
||
.expect("计数失败")
|
||
};
|
||
raw.and_then(|s| s.trim().parse::<u64>().ok()).unwrap_or(0)
|
||
}
|
||
|
||
async fn shared_db() -> Arc<PGlite> {
|
||
DB.get_or_init(|| async {
|
||
let db = Arc::new(PGlite::open_temp().await.expect("打开临时 PGlite 失败"));
|
||
tdc_connector::platform::db::ensure_schema(db.as_ref())
|
||
.await
|
||
.expect("建表失败");
|
||
db
|
||
})
|
||
.await
|
||
.clone()
|
||
}
|
||
|
||
async fn test_state() -> TdcState {
|
||
let db = shared_db().await;
|
||
let config = Config::from_env(std::env::current_dir().unwrap());
|
||
TdcState::new(
|
||
AppState::new(config, db, Arc::new(SessionStore::new())),
|
||
TdcConfig::default(),
|
||
BootstrapIdentity {
|
||
identity_id: "TEST-OP".to_string(),
|
||
identity_code: "TEST-CONNECTOR".to_string(),
|
||
issued_secret: None,
|
||
},
|
||
)
|
||
}
|
||
|
||
fn principal() -> Principal {
|
||
Principal::Session {
|
||
identity_id: "TEST-OP".to_string(),
|
||
identity_code: "TEST-CONNECTOR".to_string(),
|
||
}
|
||
}
|
||
|
||
async fn body_of(resp: axum::response::Response) -> Value {
|
||
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||
.await
|
||
.expect("读取响应体失败");
|
||
serde_json::from_slice(&bytes).expect("响应体不是 JSON")
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn product_crud_roundtrip() {
|
||
let state = test_state().await;
|
||
let _p = PRODUCT_LOCK.lock().await;
|
||
let spec = entity::find("Product").unwrap();
|
||
|
||
// 新增
|
||
let resp = crud::create(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "测试产品", "productCode": "P-001", "status": "ENABLED"}),
|
||
Some(&principal()),
|
||
)
|
||
.await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200);
|
||
assert_eq!(body["msg"], "新增成功");
|
||
let id = body["data"].as_str().expect("应返回 id").to_string();
|
||
assert!(!id.is_empty());
|
||
assert!(
|
||
id.chars().all(|c| c.is_ascii_digit()),
|
||
"id 应是雪花号十进制串"
|
||
);
|
||
|
||
// 列表(关键字)
|
||
let mut params = HashMap::new();
|
||
params.insert("keyword".to_string(), "测试产品".to_string());
|
||
let resp = crud::list(&state, spec, ¶ms, Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200);
|
||
assert_eq!(body["data"]["pagination"]["total"], 1);
|
||
let first = &body["data"]["list"][0];
|
||
assert_eq!(first["name"], "测试产品");
|
||
assert_eq!(first["productCode"], "P-001");
|
||
assert!(first.get("f_name").is_none(), "响应键必须是 camelCase");
|
||
|
||
// 过滤(category 命中不到 ⇒ total 0)
|
||
let mut params = HashMap::new();
|
||
params.insert("category".to_string(), "不存在的分类".to_string());
|
||
let resp = crud::list(&state, spec, ¶ms, Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["data"]["pagination"]["total"], 0);
|
||
|
||
// tenantId 拒因
|
||
let mut params = HashMap::new();
|
||
params.insert("tenantId".to_string(), "x".to_string());
|
||
let resp = crud::list(&state, spec, ¶ms, Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 400);
|
||
assert_eq!(
|
||
body["msg"],
|
||
"身份上下文不可由客户端指定(tenantId),请由固定实例/TDS 授权确定"
|
||
);
|
||
|
||
// 修改
|
||
let resp = crud::update(
|
||
&state,
|
||
spec,
|
||
&id,
|
||
&json!({"name": "改名后的产品"}),
|
||
Some(&principal()),
|
||
)
|
||
.await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200);
|
||
assert_eq!(body["msg"], "修改成功");
|
||
|
||
let resp = crud::detail(&state, spec, &id, Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["data"]["name"], "改名后的产品");
|
||
assert_eq!(body["data"]["productCode"], "P-001", "未传的字段保持原值");
|
||
|
||
// 删除(逻辑删除)
|
||
let resp = crud::delete(&state, spec, &id, Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200);
|
||
assert_eq!(body["msg"], "删除成功");
|
||
|
||
let resp = crud::detail(&state, spec, &id, Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 400);
|
||
assert_eq!(body["msg"], "记录不存在或已删除");
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn readonly_and_guarded_entities_reject_writes() {
|
||
let state = test_state().await;
|
||
|
||
// Dataset:派生态只读
|
||
let spec = entity::find("Dataset").unwrap();
|
||
let resp = crud::create(&state, spec, &json!({"name": "x"}), Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 400);
|
||
assert_eq!(body["msg"], "数据集为只读视图,不支持新增/编辑/删除");
|
||
|
||
// DeliveryTask:直建入口已废弃
|
||
let spec = entity::find("DeliveryTask").unwrap();
|
||
let resp = crud::create(&state, spec, &json!({"taskNo": "T-1"}), Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 400);
|
||
assert!(body["msg"]
|
||
.as_str()
|
||
.unwrap()
|
||
.starts_with("该入口已废弃:交付任务只能由发起方经平台发起"));
|
||
|
||
// AuditLog:允许写,但不许改/删
|
||
let spec = entity::find("AuditLog").unwrap();
|
||
let resp = crud::create(
|
||
&state,
|
||
spec,
|
||
&json!({"action": "LOGIN"}),
|
||
Some(&principal()),
|
||
)
|
||
.await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200, "审计日志允许 HTTP 写入:{}", body);
|
||
let id = body["data"].as_str().unwrap().to_string();
|
||
|
||
let resp = crud::update(
|
||
&state,
|
||
spec,
|
||
&id,
|
||
&json!({"action": "X"}),
|
||
Some(&principal()),
|
||
)
|
||
.await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 400);
|
||
assert_eq!(body["msg"], "审计日志不允许修改");
|
||
|
||
let resp = crud::delete(&state, spec, &id, Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 400);
|
||
assert_eq!(body["msg"], "审计日志不允许删除");
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn delivery_task_frozen_columns_cannot_be_changed() {
|
||
let state = test_state().await;
|
||
let spec = entity::find("DeliveryTask").unwrap();
|
||
|
||
// 写入口被上游废弃 ⇒ 测试里直接插一行
|
||
{
|
||
let _g = state.db_lock.lock().await;
|
||
state
|
||
.db
|
||
.query(
|
||
"INSERT INTO tdc_delivery_task (f_id, f_task_no, f_contract_id, f_status, f_creator_time) \
|
||
VALUES (CAST('T-1' AS character varying), CAST('TASK-1' AS character varying), \
|
||
CAST('C-1' AS character varying), CAST('READY' AS character varying), now())",
|
||
&[],
|
||
)
|
||
.await
|
||
.expect("插入测试行失败");
|
||
}
|
||
|
||
// 改冻结列(status)⇒ 拒
|
||
let resp = crud::update(
|
||
&state,
|
||
spec,
|
||
"T-1",
|
||
&json!({"status": "DONE"}),
|
||
Some(&principal()),
|
||
)
|
||
.await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 400);
|
||
assert_eq!(
|
||
body["msg"],
|
||
"不允许修改「任务状态」:该列由平台下发/本端服务写入,不得经编辑入口篡改"
|
||
);
|
||
|
||
// 原样回传(值没变)⇒ 放行
|
||
let resp = crud::update(
|
||
&state,
|
||
spec,
|
||
"T-1",
|
||
&json!({"status": "READY"}),
|
||
Some(&principal()),
|
||
)
|
||
.await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200, "值没变不应误伤:{}", body);
|
||
|
||
// 删 ⇒ 拒(审计证据)
|
||
let resp = crud::delete(&state, spec, "T-1", Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 400);
|
||
assert_eq!(body["msg"], "交付任务记录是审计证据,不允许删除");
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn resource_detail_aggregate_carries_field_rules_and_mask_rules() {
|
||
let state = test_state().await;
|
||
let spec = entity::find("Resource").unwrap();
|
||
|
||
{
|
||
let _g = state.db_lock.lock().await;
|
||
state
|
||
.db
|
||
.query(
|
||
"INSERT INTO tdc_resource (f_id, f_name, f_resource_code, f_mount_status) \
|
||
VALUES (CAST('R-1' AS character varying), CAST('测试资源' AS character varying), \
|
||
CAST('RC-1' AS character varying), CAST('MOUNTED' AS character varying))",
|
||
&[],
|
||
)
|
||
.await
|
||
.expect("插入资源失败");
|
||
state
|
||
.db
|
||
.query(
|
||
"INSERT INTO tdc_resource_field \
|
||
(f_id, f_resource_id, f_field_name, f_field_type, f_field_constraint, f_remark, f_sort_code) \
|
||
VALUES (CAST('RF-1' AS character varying), CAST('R-1' AS character varying), \
|
||
CAST('id_card' AS character varying), CAST('varchar' AS character varying), \
|
||
CAST('NOT NULL' AS character varying), CAST('身份证号' AS character varying), 1)",
|
||
&[],
|
||
)
|
||
.await
|
||
.expect("插入字段失败");
|
||
state
|
||
.db
|
||
.query(
|
||
"INSERT INTO tdc_resource_mask_rule \
|
||
(f_id, f_resource_id, f_field_name, f_field_type, f_mask_type, f_origin_value, f_replace_value, f_sort_code) \
|
||
VALUES (CAST('RM-1' AS character varying), CAST('R-1' AS character varying), \
|
||
CAST('id_card' AS character varying), CAST('STRING' AS character varying), \
|
||
CAST('MD5' AS character varying), CAST('13800000000' AS character varying), \
|
||
CAST('***' AS character varying), 1)",
|
||
&[],
|
||
)
|
||
.await
|
||
.expect("插入脱敏规则失败");
|
||
}
|
||
|
||
let resp = crud::detail_aggregate(&state, spec, "R-1", Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200, "聚合详情应成功:{}", body);
|
||
|
||
let data = &body["data"];
|
||
assert_eq!(data["id"], "R-1");
|
||
assert_eq!(data["name"], "测试资源");
|
||
|
||
let fields = data["fieldRules"].as_array().expect("应有 fieldRules 数组");
|
||
assert_eq!(fields.len(), 1, "字段子表条数:{}", body);
|
||
assert_eq!(fields[0]["fieldName"], "id_card");
|
||
assert_eq!(fields[0]["fieldType"], "varchar");
|
||
assert_eq!(fields[0]["fieldConstraint"], "NOT NULL");
|
||
assert_eq!(fields[0]["remark"], "身份证号");
|
||
|
||
let masks = data["maskRules"].as_array().expect("应有 maskRules 数组");
|
||
assert_eq!(masks.len(), 1, "脱敏子表条数:{}", body);
|
||
assert_eq!(masks[0]["fieldName"], "id_card");
|
||
assert_eq!(masks[0]["fieldType"], "STRING");
|
||
assert_eq!(masks[0]["maskType"], "MD5");
|
||
assert_eq!(masks[0]["originValue"], "13800000000");
|
||
assert_eq!(masks[0]["replaceValue"], "***");
|
||
|
||
// 查无 ⇒ 业务失败(HTTP 200 + code != 200)
|
||
let resp = crud::detail_aggregate(&state, spec, "R-NOT-EXIST", Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 400, "查无应是业务失败:{}", body);
|
||
}
|
||
|
||
/// 建一条实体并回读它的某个字段(简化测试样板)。
|
||
///
|
||
/// 返回 `(新记录 id, 字段值)` —— id 是 `create` 响应 `data` 里的**新记录 id**。
|
||
async fn create_and_read(
|
||
state: &tdc_connector::tdc::state::TdcState,
|
||
spec: &'static tdc_connector::tdc::entity::TableSpec,
|
||
body: &Value,
|
||
field: &str,
|
||
principal: &Principal,
|
||
) -> (String, String) {
|
||
let resp = crud::create(state, spec, body, Some(principal)).await;
|
||
let resp_body = body_of(resp).await;
|
||
assert_eq!(resp_body["code"], 200, "新建应成功:{}", resp_body);
|
||
let id = resp_body["data"].as_str().expect("应返回 id").to_string();
|
||
let resp = crud::detail(state, spec, &id, Some(principal)).await;
|
||
let resp_body = body_of(resp).await;
|
||
assert_eq!(resp_body["code"], 200, "详情应成功:{}", resp_body);
|
||
let value = resp_body["data"][field]
|
||
.as_str()
|
||
.unwrap_or_else(|| panic!("应有字段 {}:{}", field, resp_body))
|
||
.to_string();
|
||
(id, value)
|
||
}
|
||
|
||
/// 取编码里的**序号段**(第 4 段,索引 3)。
|
||
///
|
||
/// ⚠️ **只能相对比较**:序号基线是「当日同前缀行数」,同一测试库里别的用例当天建过
|
||
/// 同前缀记录就会让基线不是 0 ⇒ 绝不能断言它等于 `00000001`。
|
||
fn seq_of(code: &str, prefix: &str) -> u64 {
|
||
let parts: Vec<&str> = code.split('-').collect();
|
||
assert_eq!(parts.len(), 5, "编码应 5 段: {}", code);
|
||
assert_eq!(parts[0], prefix, "前缀应 {}: {}", prefix, code);
|
||
parts[3].parse::<u64>().expect("序号段应可解析为数字")
|
||
}
|
||
|
||
/// 🔴 上游前端新建 Product **不送** `productCode`,而该列 NOT NULL 且无 DEFAULT
|
||
/// ⇒ 服务端必须生成(上游 `TdcCodeUtil`,`PRO-yyyyMMdd-HHmmss-8位序号-8位随机`)。
|
||
#[tokio::test]
|
||
async fn product_code_is_generated_server_side() {
|
||
let state = test_state().await;
|
||
let _p = PRODUCT_LOCK.lock().await;
|
||
let spec = entity::find("Product").unwrap();
|
||
|
||
let (_id, code) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "编码生成产品甲"}),
|
||
"productCode",
|
||
&principal(),
|
||
)
|
||
.await;
|
||
let parts: Vec<&str> = code.split('-').collect();
|
||
assert_eq!(parts.len(), 5, "PRO 码应 5 段:{}", code);
|
||
assert_eq!(parts[0], "PRO");
|
||
assert_eq!(parts[1].len(), 8, "日期段 8 位:{}", code);
|
||
assert!(parts[1].chars().all(|c| c.is_ascii_digit()));
|
||
assert_eq!(parts[2].len(), 6, "时分秒段 6 位:{}", code);
|
||
assert!(parts[2].chars().all(|c| c.is_ascii_digit()));
|
||
assert_eq!(parts[3].len(), 8, "序号段补零到 8 位:{}", code);
|
||
assert!(parts[3].chars().all(|c| c.is_ascii_digit()));
|
||
assert_eq!(parts[4].chars().count(), 8, "随机尾 8 位:{}", code);
|
||
assert!(parts[4].chars().all(|c| c.is_ascii_alphanumeric()));
|
||
// 🔴 「两个码不相等」由 `product_code_sequence_starts_at_baseline_plus_one`
|
||
// 用**序号段的相对差**证明(那才是有鉴别力的断言)⇒ 这里不再写近乎恒真的弱断言。
|
||
}
|
||
|
||
/// 上游规则「**空值即生成;显式传入不覆盖**」⇒ body 显式给了码就保留 body 的。
|
||
#[tokio::test]
|
||
async fn explicit_product_code_is_not_overwritten() {
|
||
let state = test_state().await;
|
||
let _p = PRODUCT_LOCK.lock().await;
|
||
let spec = entity::find("Product").unwrap();
|
||
let (_id, code) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "固定码产品", "productCode": "FIXED-CODE"}),
|
||
"productCode",
|
||
&principal(),
|
||
)
|
||
.await;
|
||
assert_eq!(code, "FIXED-CODE", "显式传入的码不得被覆盖");
|
||
}
|
||
|
||
/// Datasource 用上游**另一套**生成器(`BizCodeUtil.of("DS")`):3 段、随机尾 6 位。
|
||
#[tokio::test]
|
||
async fn datasource_code_uses_the_six_char_tail_shape() {
|
||
let state = test_state().await;
|
||
let spec = entity::find("Datasource").unwrap();
|
||
let (_id, code) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "码生成数据源", "type": "MYSQL"}),
|
||
"datasourceCode",
|
||
&principal(),
|
||
)
|
||
.await;
|
||
let parts: Vec<&str> = code.split('-').collect();
|
||
assert_eq!(parts.len(), 3, "DS 码应 3 段:{}", code);
|
||
assert_eq!(parts[0], "DS");
|
||
assert_eq!(parts[1].len(), 8, "日期段 8 位:{}", code);
|
||
assert!(parts[1].chars().all(|c| c.is_ascii_digit()));
|
||
assert_eq!(parts[2].chars().count(), 6, "随机尾 6 位:{}", code);
|
||
assert!(parts[2].chars().all(|c| c.is_ascii_alphanumeric()));
|
||
}
|
||
|
||
/// 🔴 NOT NULL 违约 ⇒ **业务失败**(HTTP 200 + `code=400`),不是 500。
|
||
#[tokio::test]
|
||
async fn missing_required_field_is_a_business_failure_not_a_500() {
|
||
let state = test_state().await;
|
||
let _p = PRODUCT_LOCK.lock().await;
|
||
let spec = entity::find("Product").unwrap();
|
||
// 不给 `name`(`f_name` NOT NULL 无 DEFAULT)⇒ 23502
|
||
let resp = crud::create(&state, spec, &json!({}), Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 400, "应是业务失败而非 500:{}", body);
|
||
assert!(
|
||
body["msg"].as_str().unwrap().contains("必填"),
|
||
"msg 应说明必填缺失:{}",
|
||
body
|
||
);
|
||
// 🔴 `body["data"].is_null()` 对**缺失键**也恒真 ⇒ 必须显式断言「键存在且值为 null」
|
||
let obj = body.as_object().expect("响应体应是对象");
|
||
assert!(
|
||
obj.contains_key("data"),
|
||
"失败响应须带 data 键(值为 null)"
|
||
);
|
||
assert_eq!(
|
||
obj.get("data"),
|
||
Some(&Value::Null),
|
||
"失败响应的 data 应为 null"
|
||
);
|
||
}
|
||
|
||
/// 🔴 审计 actor 来自**登录主体**,不再恒为「系统(自动)」。
|
||
#[tokio::test]
|
||
async fn audit_actor_comes_from_the_login_principal() {
|
||
let state = test_state().await;
|
||
let spec = entity::find("AuditLog").unwrap();
|
||
|
||
// 本地账号 ⇒ USER / 账号 id / 账号名
|
||
let account = Principal::Account {
|
||
account_id: "U-1".to_string(),
|
||
account: "张三".to_string(),
|
||
};
|
||
let resp = crud::create(&state, spec, &json!({"action": "LOGIN"}), Some(&account)).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200, "{}", body);
|
||
let id = body["data"].as_str().unwrap().to_string();
|
||
let resp = crud::detail(&state, spec, &id, Some(&account)).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["data"]["actorType"], "USER");
|
||
assert_eq!(body["data"]["actorId"], "U-1");
|
||
assert_eq!(body["data"]["actorName"], "张三");
|
||
|
||
// 连接器身份会话 ⇒ CONNECTOR / 身份 id / 身份码
|
||
let resp = crud::create(
|
||
&state,
|
||
spec,
|
||
&json!({"action": "LOGIN"}),
|
||
Some(&principal()),
|
||
)
|
||
.await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200, "{}", body);
|
||
let id = body["data"].as_str().unwrap().to_string();
|
||
let resp = crud::detail(&state, spec, &id, Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["data"]["actorType"], "CONNECTOR");
|
||
assert_eq!(body["data"]["actorId"], "TEST-OP");
|
||
assert_eq!(body["data"]["actorName"], "TEST-CONNECTOR");
|
||
|
||
// 内部令牌但没有 operator ⇒ 回落 create_defaults 的兜底
|
||
let internal = Principal::Internal { operator: None };
|
||
let resp = crud::create(&state, spec, &json!({"action": "LOGIN"}), Some(&internal)).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200, "{}", body);
|
||
let id = body["data"].as_str().unwrap().to_string();
|
||
let resp = crud::detail(&state, spec, &id, Some(&internal)).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["data"]["actorType"], "CONNECTOR");
|
||
assert_eq!(body["data"]["actorName"], "系统(自动)");
|
||
}
|
||
|
||
/// 🔴 上游 `TdcCrudController#delete:250-266`:**先判存在性**(`getAlive` 为空 ⇒
|
||
/// 「记录不存在或已删除」)→ **之后**才走禁删守卫(`beforeDelete`)。
|
||
/// ⇒ 对**不存在**的 id,即使该实体受保护,也必须回「记录不存在或已删除」。
|
||
#[tokio::test]
|
||
async fn contract_delete_reports_missing_before_the_delete_guard() {
|
||
let state = test_state().await;
|
||
let spec = entity::find("Contract").unwrap();
|
||
|
||
// 不存在的 id ⇒ 「记录不存在或已删除」(**先于**禁删守卫)
|
||
let resp = crud::delete(&state, spec, "NO-SUCH-ID", Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 400, "不存在的 id ⇒ 业务失败:{}", body);
|
||
assert_eq!(
|
||
body["msg"], "记录不存在或已删除",
|
||
"存在性判定须先于禁删守卫"
|
||
);
|
||
|
||
// 存在的 Contract 行 ⇒ 禁删文案(上游原文,逐字)
|
||
{
|
||
let _g = state.db_lock.lock().await;
|
||
state
|
||
.db
|
||
.query(
|
||
"INSERT INTO tdc_contract (f_id, f_contract_code) \
|
||
VALUES (CAST('C-GUARD' AS character varying), CAST('CC-GUARD' AS character varying))",
|
||
&[],
|
||
)
|
||
.await
|
||
.expect("插入合约失败");
|
||
}
|
||
let resp = crud::delete(&state, spec, "C-GUARD", Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 400, "合约恒拒删:{}", body);
|
||
assert_eq!(
|
||
body["msg"], "本地合约副本不可删除(权威归档在平台,副本仅随空间/合约清退联动)",
|
||
"禁删文案须逐字等于上游原文"
|
||
);
|
||
}
|
||
|
||
/// 🔴 **注册表常量**层的哨兵:编码生成的**逐实体**参数(重试次数 / 失败文案)
|
||
/// 等于**上游原文**,且**逐实体不同**
|
||
/// (上游 Product/Resource 重试 5 次、DataInterface/Datasource 重试 3 次;文案也各不相同)。
|
||
///
|
||
/// ⚠️ **本用例只守「注册表常量」**(`entity::create_codes`),**不触引擎**。
|
||
/// 引擎真的读了 `retries` / `fail_msg`(含「重试耗尽」分支)由 `src/crud.rs` 里的
|
||
/// **单元测试**守(`code_generation_gives_up_after_the_entity_specific_retries`,
|
||
/// 它注入恒冲突候选 ⇒ 真的走到耗尽分支)。
|
||
/// 「重试耗尽」这条分支**无法在集成层稳定构造**:真实候选带 8 位(`DaySeqTail8`)或
|
||
/// 6 位(`DayTail6`)随机尾,撞中一次要枚举十亿级组合。
|
||
#[tokio::test]
|
||
async fn registry_declares_per_entity_code_retry_policy() {
|
||
let expected = [
|
||
("Product", 5u32, "产品编码生成失败(连续 5 次撞库),请重试"),
|
||
(
|
||
"Resource",
|
||
5u32,
|
||
"资源编码生成失败(连续 5 次撞库),请重试",
|
||
),
|
||
("DataInterface", 3u32, "接口编码生成失败(重试 3 次仍冲突)"),
|
||
(
|
||
"Datasource",
|
||
3u32,
|
||
"系统标识生成失败(连续 3 次撞库),请重试",
|
||
),
|
||
];
|
||
for (api, retries, fail_msg) in expected {
|
||
let codes = entity::create_codes(api);
|
||
assert_eq!(codes.len(), 1, "{} 应恰好一个编码列", api);
|
||
assert_eq!(codes[0].retries, retries, "{} 的重试次数", api);
|
||
assert_eq!(codes[0].fail_msg, fail_msg, "{} 的失败文案", api);
|
||
}
|
||
// 逐实体不同 ⇒ 引擎不可能再用「统一的 5 次 + 统一文案」
|
||
let msgs: Vec<&str> = expected.iter().map(|(_, _, m)| *m).collect();
|
||
let mut uniq = msgs.clone();
|
||
uniq.sort_unstable();
|
||
uniq.dedup();
|
||
assert_eq!(uniq.len(), 4, "四个实体的失败文案应各不相同:{:?}", msgs);
|
||
}
|
||
|
||
/// 🔴 **序号口径 `used + 1 + i` 的护栏**(评审 Important-1 / fix round 3 F-1)。
|
||
///
|
||
/// 上游 Product/Resource/DataInterface 三处都是 `used + 1 + i`(`used` = 当日同前缀行数)。
|
||
/// 变异实验:把它改成 `used + i` 后旧测试**全绿** ⇒ 零覆盖 ⇒ 这里补一条**相对**断言。
|
||
///
|
||
/// ⚠️ **必须相对断言**:基线 `used` 是「当日同前缀的行数」,同一测试库里别的用例当天建过
|
||
/// Product 就会让基线不是 0 ⇒ 绝不能断言序号段等于 `00000001`。
|
||
#[tokio::test]
|
||
async fn product_code_sequence_starts_at_baseline_plus_one() {
|
||
let state = test_state().await;
|
||
let _p = PRODUCT_LOCK.lock().await;
|
||
let spec = entity::find("Product").unwrap();
|
||
|
||
let (_id1, code1) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "序号口径产品"}),
|
||
"productCode",
|
||
&principal(),
|
||
)
|
||
.await;
|
||
// 顺带:两条 Product **同名**也能建(业务级「名称唯一」校验本轮不做 ⇒ 不该拦)
|
||
// 🔴 **绝对断言**(相对断言杀不掉 `used + i` 变异:两条码的基线各差 1,
|
||
// 偏移量在**差**里会互相抵消 ⇒ 变异后仍然 `seq2 == seq1 + 1`)。
|
||
// 这里数「当日同前缀的行数」(**建完第 1 条之后**的计数 = 基线 + 1):
|
||
// 序号必须**正好等于**它 ⇒ 把 `used + 1 + i` 的 `+1` 钉死。
|
||
// (`PRODUCT_LOCK` 保证此刻没有别的用例在写 `tdc_product` ⇒ 计数确定。)
|
||
let day = code1.split('-').nth(1).expect("编码应含日期段").to_string();
|
||
let count = count_today_products(&state, &format!("PRO-{}-%", day)).await;
|
||
assert_eq!(
|
||
seq_of(&code1, "PRO"),
|
||
count,
|
||
"序号必须等于「当日同前缀行数」(used + 1 ⇒ 建完后的计数)"
|
||
);
|
||
|
||
let (_id2, code2) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "序号口径产品"}),
|
||
"productCode",
|
||
&principal(),
|
||
)
|
||
.await;
|
||
|
||
assert_eq!(
|
||
seq_of(&code2, "PRO"),
|
||
seq_of(&code1, "PRO") + 1,
|
||
"序号应从基线 +1 递增(used + 1 + i)"
|
||
);
|
||
assert_ne!(code1, code2, "整体编码应不同(由序号段的差异解释)");
|
||
}
|
||
|
||
/// 🔴 **新建默认值对齐上游**(评审 Important-2 / fix round 3 F-2)。
|
||
///
|
||
/// 上游:Product 新建默认**未上架**(`status = DISABLED`,DDL 里是 `'ENABLED'` ⇒ 必须显式覆盖);
|
||
/// Resource 新建默认**停用** + `mountStatus = UNMOUNTED`;Datasource `testStatus = UNTESTED`。
|
||
#[tokio::test]
|
||
async fn new_rows_carry_the_upstream_creation_defaults() {
|
||
let state = test_state().await;
|
||
let _p = PRODUCT_LOCK.lock().await;
|
||
|
||
// Product:默认 DISABLED
|
||
let spec = entity::find("Product").unwrap();
|
||
let (_id, status) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "默认状态产品"}),
|
||
"status",
|
||
&principal(),
|
||
)
|
||
.await;
|
||
assert_eq!(status, "DISABLED", "Product 新建默认未上架");
|
||
|
||
// Resource:默认 DISABLED + UNMOUNTED
|
||
let spec = entity::find("Resource").unwrap();
|
||
let (_id, status) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "默认状态资源"}),
|
||
"status",
|
||
&principal(),
|
||
)
|
||
.await;
|
||
assert_eq!(status, "DISABLED", "Resource 新建默认停用");
|
||
let (_id, mount) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "默认状态资源"}),
|
||
"mountStatus",
|
||
&principal(),
|
||
)
|
||
.await;
|
||
assert_eq!(mount, "UNMOUNTED", "Resource 新建默认未挂载");
|
||
|
||
// Datasource:默认 UNTESTED
|
||
let spec = entity::find("Datasource").unwrap();
|
||
let (_id, test_status) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "默认测试态数据源", "type": "MYSQL"}),
|
||
"testStatus",
|
||
&principal(),
|
||
)
|
||
.await;
|
||
assert_eq!(test_status, "UNTESTED", "Datasource 新建默认未测试");
|
||
}
|
||
|
||
/// 🔴 `f_creator_user_id` 写**操作人 id**(上游 `safeUserId()` 返回 id,不是名字)。
|
||
#[tokio::test]
|
||
async fn creator_user_id_records_the_operator_id_not_the_account_name() {
|
||
let state = test_state().await;
|
||
let _p = PRODUCT_LOCK.lock().await;
|
||
let spec = entity::find("Product").unwrap();
|
||
let account = Principal::Account {
|
||
account_id: "U-9".to_string(),
|
||
account: "李四".to_string(),
|
||
};
|
||
let (_id, creator) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "归属口径产品"}),
|
||
"creatorUserId",
|
||
&account,
|
||
)
|
||
.await;
|
||
assert_eq!(creator, "U-9", "creator 列应写操作人 id");
|
||
assert_ne!(creator, "李四", "creator 列不得写账号名");
|
||
}
|
||
|
||
/// 🔴 body 显式 `null` **不得**抑制服务端默认值(上游:字段为 null ⇒ 照样补)。
|
||
///
|
||
/// `f_actor_type` 有 DB DEFAULT `'USER'`;「无主体 + body 显式 null」时,
|
||
/// 若引擎把 null 当成「业务已给」⇒ 兜底被静默吞掉 ⇒ 落库会是 DB 的 `'USER'`。
|
||
#[tokio::test]
|
||
async fn explicit_null_does_not_suppress_the_server_side_default() {
|
||
let state = test_state().await;
|
||
let spec = entity::find("AuditLog").unwrap();
|
||
// 无 operator 的内部令牌 ⇒ actor 推导不出来 ⇒ 走 `create_defaults` 的兜底
|
||
let internal = Principal::Internal { operator: None };
|
||
let (_id, actor_type) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"action": "LOGIN", "actorType": Value::Null}),
|
||
"actorType",
|
||
&internal,
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
actor_type, "CONNECTOR",
|
||
"显式 null 不得抑制服务端兜底(应落 CONNECTOR,而不是 DB 默认的 USER)"
|
||
);
|
||
}
|
||
|
||
/// 🔴 **DataInterface 的当日同前缀基线带 `ALIVE`**(上游 `countByCodePrefix:263-268`)。
|
||
///
|
||
/// 构造方式:建一条接口 → 软删它 → 再建一条 ⇒ 若基线带 `ALIVE`,软删行**不占基线**
|
||
/// ⇒ 第 2 条的序号与第 1 条**相同**;若不带,第 2 条的序号会 +1。
|
||
/// ⇒ 这条用例**真的走到引擎**(读的是引擎算出来的序号段,不是注册表常量)。
|
||
#[tokio::test]
|
||
async fn data_interface_baseline_ignores_soft_deleted_rows() {
|
||
let state = test_state().await;
|
||
let spec = entity::find("DataInterface").unwrap();
|
||
|
||
let (id1, code1) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "基线接口甲", "type": "API"}),
|
||
"interfaceCode",
|
||
&principal(),
|
||
)
|
||
.await;
|
||
// 软删第 1 条
|
||
let resp = crud::delete(&state, spec, &id1, Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200, "软删应成功:{}", body);
|
||
|
||
let (_id2, code2) = create_and_read(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "基线接口乙", "type": "API"}),
|
||
"interfaceCode",
|
||
&principal(),
|
||
)
|
||
.await;
|
||
|
||
assert_eq!(
|
||
seq_of(&code2, "API"),
|
||
seq_of(&code1, "API"),
|
||
"基线带 ALIVE ⇒ 软删行不占序号基线(上游 DataInterface 口径)"
|
||
);
|
||
}
|
||
|
||
/// 🔴 500 **不得回显数据库原文**(评审 Minor-7 / fix round 3 F-7)。
|
||
///
|
||
/// 构造:给 `f_price`(`numeric(18,4)`)送一个非数字串 ⇒ PG 报 `22P02`
|
||
/// (不在约束映射表里)⇒ 走 500 分支 ⇒ 客户端只能看到固定文案。
|
||
#[tokio::test]
|
||
async fn internal_errors_do_not_echo_the_database_message() {
|
||
let state = test_state().await;
|
||
let _p = PRODUCT_LOCK.lock().await;
|
||
let spec = entity::find("Product").unwrap();
|
||
let resp = crud::create(
|
||
&state,
|
||
spec,
|
||
&json!({"name": "脱敏产品", "price": "不是数字"}),
|
||
Some(&principal()),
|
||
)
|
||
.await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 500, "非约束类 DB 错误 ⇒ 500:{}", body);
|
||
assert_eq!(body["msg"], "服务异常,请稍后重试", "500 文案须是固定文案");
|
||
let msg = body["msg"].as_str().unwrap();
|
||
assert!(!msg.contains("tdc_product"), "不得回显表名:{}", msg);
|
||
assert!(!msg.contains("f_price"), "不得回显列名:{}", msg);
|
||
assert!(!msg.contains("numeric"), "不得回显数据库原文:{}", msg);
|
||
}
|
||
|
||
/// 🔴 **上游 `@JsonIgnore` 的属性:既不外泄、也不可写**(R10 回归)。
|
||
///
|
||
/// 上游 `IdentityEntity.f_secret_key` 标了 `@JsonIgnore`,注释明写「防 CRUD list/detail 泄露」。
|
||
/// Jackson 的 `@JsonIgnore` **既管序列化也管反序列化** ⇒
|
||
/// - 出参:**整条键不出现**(不是 null);
|
||
/// - 入参:**绑不上实体** ⇒ 客户端送什么都不会写库(是「当它不存在」,不是「报错」)。
|
||
///
|
||
/// 本仓此前 `crud.rs` 是 `SELECT *` + camelCase 直出 ⇒ `secretKey` 原样回显(= 泄漏)。
|
||
#[tokio::test]
|
||
async fn json_ignored_fields_are_neither_exposed_nor_writable() {
|
||
let state = test_state().await;
|
||
let spec = entity::find("Identity").unwrap();
|
||
|
||
// 读库里那一列(**只判空,不回显值** —— 免得把密钥写进 transcript)。
|
||
let read_secret = |id: &str| {
|
||
let state = state.clone();
|
||
let id = id.to_string();
|
||
async move {
|
||
let sql = "SELECT f_secret_key FROM tdc_identity WHERE f_id = CAST($1 AS text)";
|
||
let _g = state.db_lock.lock().await;
|
||
tdc_connector::platform::db::query_scalar_text(state.db.as_ref(), sql, &[&id])
|
||
.await
|
||
.expect("查询失败")
|
||
}
|
||
};
|
||
|
||
// ① 新建:请求体里带 secretKey ⇒ **静默忽略**(上游绑不上该属性)
|
||
let resp = crud::create(
|
||
&state,
|
||
spec,
|
||
&json!({
|
||
"identityCode": "REDACT-TEST-1",
|
||
"name": "去敏测试身份",
|
||
"secretKey": "SENTINEL-MUST-NOT-BE-STORED",
|
||
}),
|
||
Some(&principal()),
|
||
)
|
||
.await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200, "新建失败:{}", body["msg"]);
|
||
let id = body["data"].as_str().expect("应返回 id").to_string();
|
||
|
||
let stored = read_secret(&id).await;
|
||
assert!(
|
||
stored
|
||
.as_deref()
|
||
.map(|s| s.trim().is_empty())
|
||
.unwrap_or(true),
|
||
"客户端送的 secretKey 不应被写库"
|
||
);
|
||
|
||
// ② 详情:响应里**没有** secretKey 这个键
|
||
let resp = crud::detail(&state, spec, &id, Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200);
|
||
assert_eq!(body["data"]["identityCode"], "REDACT-TEST-1");
|
||
assert!(
|
||
body["data"].get("secretKey").is_none(),
|
||
"详情不得回显 secretKey(上游是 @JsonIgnore ⇒ 整条不出现)"
|
||
);
|
||
|
||
// ③ 列表:同样没有
|
||
let params = HashMap::new();
|
||
let resp = crud::list(&state, spec, ¶ms, Some(&principal())).await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200);
|
||
for row in body["data"]["list"].as_array().expect("list 应是数组") {
|
||
assert!(row.get("secretKey").is_none(), "列表不得回显 secretKey");
|
||
}
|
||
|
||
// ④ 修改:送 secretKey ⇒ 报「修改成功」但**不写**(上游:绑不上 ⇒ 等于没送)
|
||
let resp = crud::update(
|
||
&state,
|
||
spec,
|
||
&id,
|
||
&json!({
|
||
"name": "改名后的去敏测试身份",
|
||
"secretKey": "SENTINEL-SECOND",
|
||
}),
|
||
Some(&principal()),
|
||
)
|
||
.await;
|
||
let body = body_of(resp).await;
|
||
assert_eq!(body["code"], 200);
|
||
assert_eq!(body["msg"], "修改成功");
|
||
|
||
let stored = read_secret(&id).await;
|
||
assert!(
|
||
stored
|
||
.as_deref()
|
||
.map(|s| s.trim().is_empty())
|
||
.unwrap_or(true),
|
||
"修改也不应写 secretKey"
|
||
);
|
||
}
|