fix(routes): 请求体解析失败与方法不允许都回到业务信封
- 新增宽松 JSON 抽取器:畸形 body 不再返回 axum 默认的 text/plain 400,
改为 HTTP 200 + code 400 + 上游原文「请求体格式有误,请检查 JSON 结构与字段类型」
- 方法不允许返回 JSON(405 + code/msg),不再是空体
- /Detail 的查无文案逐实体对齐上游:Dataset 与 Resource 文案不同
- /Detail 路径改从注册表取,不再硬编码
- 补 HTTP 级用例覆盖 GET {id} / POST / PUT / DELETE 与聚合体子表
Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
1 parent
0f84fbdb83
commit
5d74354944
5 files changed
+441
-57
No files matched your search
+14
-1
@@ -880,6 +880,17 @@ fn child_tables(spec: &TableSpec) -> &'static [(&'static str, &'static str)] {
|
||||
}
|
||||
}
|
||||
|
||||
/// `/Detail` 聚合体的「查无」文案(逐字对齐上游)。
|
||||
///
|
||||
/// - `Dataset` ⇒ 「数据集不存在或资源已删除」(上游 `DatasetController#detailOf`,`:142`)
|
||||
/// - 其余 ⇒ 「记录不存在或已删除」(上游 `ResourceController#detailOf`,`:210`)
|
||||
fn detail_not_found_msg(api_name: &str) -> &'static str {
|
||||
match api_name {
|
||||
"Dataset" => "数据集不存在或资源已删除",
|
||||
_ => "记录不存在或已删除",
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /api/ssw/tdc/{Entity}/{id}/Detail` —— 上游 `ResourceController` / `DatasetController`
|
||||
/// 的**只读聚合体**(`ResourceService.withChildren`):资源行 + 两张子表。
|
||||
///
|
||||
@@ -911,7 +922,9 @@ pub async fn detail_aggregate(
|
||||
};
|
||||
let row = match rows.first() {
|
||||
Some(row) => row,
|
||||
None => return ActionResult::fail("记录不存在或已删除").into_response(),
|
||||
None => {
|
||||
return ActionResult::fail(detail_not_found_msg(spec.api_name)).into_response()
|
||||
}
|
||||
};
|
||||
let mut data = row_to_json(row);
|
||||
for (key, table) in children {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! 宽松 JSON 请求体:解析失败 ⇒ 业务信封(逐字对齐上游 `SswExceptionHandler`)。
|
||||
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::{FromRequest, Request};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::envelope::ActionResult;
|
||||
|
||||
/// 上游的原文拒因(`SswExceptionHandler#handleNotReadable`)。
|
||||
///
|
||||
/// 🔴 上游 `ActionResult.fail(String)` 的 `code` **恒为 400**
|
||||
/// (`jnpf.base.ActionResult` 字节码:`sipush 400`),且 Spring 给 **HTTP 200**
|
||||
/// ⇒ 业务失败 = HTTP 200 + `{code:400,msg:…}`。
|
||||
pub const BODY_FORMAT_ERROR: &str = "请求体格式有误,请检查 JSON 结构与字段类型";
|
||||
|
||||
/// 请求体(宽松 JSON)。
|
||||
///
|
||||
/// 🔴 **为什么不用 axum 的 `Json<T>`**:
|
||||
/// `Json<T>` 解析失败时返回 `JsonRejection` ⇒ axum 渲染成 **HTTP 400 + `text/plain`**,
|
||||
/// body 不是 JSON ⇒ 上游前端拦截器 `body.msg` 取不到(`body` 是字符串)
|
||||
/// ⇒ 用户看到 "Request failed with status code 400" 的英文兜底。
|
||||
/// 本抽取器把同类失败**如实回传成业务信封**,与上游逐字一致。
|
||||
///
|
||||
/// 🔴 **不校验 Content-Type** ⇒ 上游的 `HttpMediaTypeNotSupportedException`(415)在本仓**不发生**;
|
||||
/// 错误媒体类型会以「JSON 解析失败」的口径回报
|
||||
/// (上游的 415 落到 JNPF 全局兜底,形状未知 ⇒ 这是**已登记的刻意分歧**)。
|
||||
///
|
||||
/// ⚠️ **空 body ⇒ `None`**(保留既有语义:POST / PUT 允许不带 body ⇒ 引擎按缺省值走)。
|
||||
pub struct JsonBody(pub Option<Value>);
|
||||
|
||||
impl<S> FromRequest<S> for JsonBody
|
||||
where
|
||||
S: Send + Sync,
|
||||
{
|
||||
/// 🔴 拒绝 = **完整的业务信封响应**(不是 axum 的默认文本)⇒ 解析失败也走 HTTP 200 + code 400。
|
||||
type Rejection = Response;
|
||||
|
||||
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
|
||||
let bytes = Bytes::from_request(req, state)
|
||||
.await
|
||||
.map_err(|_| ActionResult::fail(BODY_FORMAT_ERROR).into_response())?;
|
||||
if bytes.is_empty() {
|
||||
return Ok(JsonBody(None));
|
||||
}
|
||||
match serde_json::from_slice::<Value>(&bytes) {
|
||||
Ok(v) => Ok(JsonBody(Some(v))),
|
||||
Err(_) => Err(ActionResult::fail(BODY_FORMAT_ERROR).into_response()),
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
-36
@@ -18,6 +18,7 @@ use axum::routing::get;
|
||||
use axum::Router;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::body::JsonBody;
|
||||
use crate::auth::Principal;
|
||||
use crate::crud;
|
||||
use crate::registry::{self, TableSpec};
|
||||
@@ -30,51 +31,61 @@ pub fn router() -> Router<AppState> {
|
||||
r = r
|
||||
.route(
|
||||
s.path,
|
||||
get(move |State(st): State<AppState>, q: RawQuery, p: Option<Extension<Principal>>| {
|
||||
let params = crud::parse_query(q.0.as_deref());
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::list(&st, s, ¶ms, principal.as_ref()).await }
|
||||
})
|
||||
get(
|
||||
move |State(st): State<AppState>,
|
||||
q: RawQuery,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let params = crud::parse_query(q.0.as_deref());
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::list(&st, s, ¶ms, principal.as_ref()).await }
|
||||
},
|
||||
)
|
||||
.post(
|
||||
move |State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>,
|
||||
b: Option<axum::Json<Value>>| {
|
||||
b: JsonBody| {
|
||||
let principal = p.map(|e| e.0);
|
||||
let body = b.map(|axum::Json(v)| v).unwrap_or(Value::Null);
|
||||
let body = b.0.unwrap_or(Value::Null);
|
||||
async move { crud::create(&st, s, &body, principal.as_ref()).await }
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{}/All", s.path),
|
||||
get(move |State(st): State<AppState>, q: RawQuery, p: Option<Extension<Principal>>| {
|
||||
let params = crud::parse_query(q.0.as_deref());
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::all(&st, s, ¶ms, principal.as_ref()).await }
|
||||
}),
|
||||
get(
|
||||
move |State(st): State<AppState>,
|
||||
q: RawQuery,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let params = crud::parse_query(q.0.as_deref());
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::all(&st, s, ¶ms, principal.as_ref()).await }
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{}/{{id}}", s.path),
|
||||
get(move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::detail(&st, s, &id, principal.as_ref()).await }
|
||||
})
|
||||
get(
|
||||
move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::detail(&st, s, &id, principal.as_ref()).await }
|
||||
},
|
||||
)
|
||||
.put(
|
||||
move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>,
|
||||
b: Option<axum::Json<Value>>| {
|
||||
b: JsonBody| {
|
||||
let principal = p.map(|e| e.0);
|
||||
let body = b.map(|axum::Json(v)| v).unwrap_or(Value::Null);
|
||||
let body = b.0.unwrap_or(Value::Null);
|
||||
async move { crud::update(&st, s, &id, &body, principal.as_ref()).await }
|
||||
},
|
||||
)
|
||||
.delete(
|
||||
move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::delete(&st, s, &id, principal.as_ref()).await }
|
||||
},
|
||||
@@ -95,22 +106,30 @@ pub fn router() -> Router<AppState> {
|
||||
registry::find("Dataset").expect("Dataset 必须在注册表里");
|
||||
r = r
|
||||
.route(
|
||||
"/api/ssw/tdc/Resource/{id}/Detail",
|
||||
get(move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::detail_aggregate(&st, res_spec, &id, principal.as_ref()).await }
|
||||
}),
|
||||
&format!("{}/{{id}}/Detail", res_spec.path),
|
||||
get(
|
||||
move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move {
|
||||
crud::detail_aggregate(&st, res_spec, &id, principal.as_ref()).await
|
||||
}
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/api/ssw/tdc/Dataset/{id}/Detail",
|
||||
get(move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::detail_aggregate(&st, ds_spec, &id, principal.as_ref()).await }
|
||||
}),
|
||||
&format!("{}/{{id}}/Detail", ds_spec.path),
|
||||
get(
|
||||
move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move {
|
||||
crud::detail_aggregate(&st, ds_spec, &id, principal.as_ref()).await
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
r
|
||||
|
||||
+22
-1
@@ -1,10 +1,14 @@
|
||||
//! 按域装配的 axum Router。
|
||||
|
||||
pub mod auth;
|
||||
pub mod body;
|
||||
pub mod crud;
|
||||
pub mod health;
|
||||
|
||||
use axum::Router;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::{Json, Router};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::state::AppState;
|
||||
|
||||
@@ -19,5 +23,22 @@ pub fn build_router(state: AppState) -> Router<AppState> {
|
||||
.merge(health::router())
|
||||
.merge(auth::router())
|
||||
.merge(crud::router())
|
||||
// 🔴 方法不允许 ⇒ JSON(axum 默认是**空体 405** ⇒ 前端拿不到 `msg`)
|
||||
.method_not_allowed_fallback(method_not_allowed)
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// 方法不允许 ⇒ JSON。
|
||||
///
|
||||
/// 🔴 形状:HTTP 405 + `{"code":405,"msg":"方法不被允许","data":null}`
|
||||
/// —— 前端 axios 的 error 分支读 `error.response.data.msg` ⇒ 能如实显示。
|
||||
///
|
||||
/// ⚠️ 上游(Spring)这条路径落到 JNPF 全局兜底,形状**未知**
|
||||
/// ⇒ 本仓取「保留 405 语义 + 补 JSON body」,是**已登记的刻意分歧**。
|
||||
async fn method_not_allowed() -> Response {
|
||||
(
|
||||
StatusCode::METHOD_NOT_ALLOWED,
|
||||
Json(json!({"code": 405, "msg": "方法不被允许", "data": null})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
+299
-19
@@ -32,8 +32,8 @@ async fn shared_db() -> Arc<PGlite> {
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// 构造一个带鉴权中间件的 router,并返回当前生效的内部令牌。
|
||||
async fn build() -> (Router, String) {
|
||||
/// 构造一个带鉴权中间件的 router,并返回当前生效的内部令牌与状态。
|
||||
async fn build() -> (Router, String, AppState) {
|
||||
let db = shared_db().await;
|
||||
let mut config = Config::from_env(std::env::current_dir().unwrap());
|
||||
config.identity_code = "TEST-CONNECTOR".to_string();
|
||||
@@ -59,9 +59,12 @@ async fn build() -> (Router, String) {
|
||||
// 必须再 `.with_state(state)` 一次把它落到 `Router<()>`。
|
||||
// ✅ 本仓已有可用样板:`tests/auth_flow.rs` 的 `build_app()`。
|
||||
let app: Router = build_router(state.clone())
|
||||
.layer(axum::middleware::from_fn_with_state(auth_state, auth_middleware))
|
||||
.with_state(state);
|
||||
(app, token)
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
auth_state,
|
||||
auth_middleware,
|
||||
))
|
||||
.with_state(state.clone());
|
||||
(app, token, state)
|
||||
}
|
||||
|
||||
fn get(uri: &str, token: Option<&str>) -> Request<Body> {
|
||||
@@ -72,6 +75,18 @@ fn get(uri: &str, token: Option<&str>) -> Request<Body> {
|
||||
b.body(Body::empty()).unwrap()
|
||||
}
|
||||
|
||||
/// 构造一个带 JSON body 的请求。
|
||||
fn json_req(method: &str, uri: &str, token: Option<&str>, body: &str) -> Request<Body> {
|
||||
let mut b = Request::builder()
|
||||
.method(method)
|
||||
.uri(uri)
|
||||
.header("Content-Type", "application/json");
|
||||
if let Some(t) = token {
|
||||
b = b.header("X-Internal-Token", t);
|
||||
}
|
||||
b.body(Body::from(body.to_string())).unwrap()
|
||||
}
|
||||
|
||||
async fn call(app: &Router, r: Request<Body>) -> (StatusCode, Value) {
|
||||
let resp = app.clone().oneshot(r).await.expect("请求失败");
|
||||
let status = resp.status();
|
||||
@@ -82,7 +97,7 @@ async fn call(app: &Router, r: Request<Body>) -> (StatusCode, Value) {
|
||||
|
||||
#[tokio::test]
|
||||
async fn crud_routes_are_guarded_and_use_the_business_envelope() {
|
||||
let (app, token) = build().await;
|
||||
let (app, token, _state) = build().await;
|
||||
|
||||
// ① 无凭证 ⇒ HTTP 401 + 裸三字段(无 data)
|
||||
let (status, body) = call(&app, get("/api/ssw/tdc/Product", None)).await;
|
||||
@@ -104,22 +119,49 @@ async fn crud_routes_are_guarded_and_use_the_business_envelope() {
|
||||
assert!(body["data"].is_array(), "/All 必须返回裸数组");
|
||||
|
||||
// ④ 18 个实体全部注册成功(随便挑几个含只读与审计的)
|
||||
for api in ["Dataset", "DeliveryTask", "AuditLog", "Identity", "PolicyTemplate"] {
|
||||
let (status, body) = call(&app, get(&format!("/api/ssw/tdc/{}", api), Some(token.as_str()))).await;
|
||||
for api in [
|
||||
"Dataset",
|
||||
"DeliveryTask",
|
||||
"AuditLog",
|
||||
"Identity",
|
||||
"PolicyTemplate",
|
||||
] {
|
||||
let (status, body) = call(
|
||||
&app,
|
||||
get(&format!("/api/ssw/tdc/{}", api), Some(token.as_str())),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "{} 列表应可用", api);
|
||||
assert_eq!(body["code"], 200, "{} 列表应返回业务信封", api);
|
||||
}
|
||||
|
||||
// ⑤ 资源侧只读聚合路由已注册(不是 404):无该 id ⇒ 业务失败 400
|
||||
for path in [
|
||||
"/api/ssw/tdc/Resource/R-NOT-EXIST/Detail",
|
||||
"/api/ssw/tdc/Dataset/R-NOT-EXIST/Detail",
|
||||
// 🔴 两条路由的「查无」文案**不同**(上游逐字对齐):
|
||||
// Dataset ⇒ 「数据集不存在或资源已删除」(DatasetController:142)
|
||||
// Resource ⇒ 「记录不存在或已删除」(ResourceController:210)
|
||||
for (path, want_msg) in [
|
||||
(
|
||||
"/api/ssw/tdc/Resource/R-NOT-EXIST/Detail",
|
||||
"记录不存在或已删除",
|
||||
),
|
||||
(
|
||||
"/api/ssw/tdc/Dataset/R-NOT-EXIST/Detail",
|
||||
"数据集不存在或资源已删除",
|
||||
),
|
||||
] {
|
||||
let (status, body) = call(&app, get(path, Some(token.as_str()))).await;
|
||||
assert_eq!(status, 200, "{} 必须已注册(404 说明路由没挂上):{:?}", path, body);
|
||||
assert_eq!(
|
||||
status, 200,
|
||||
"{} 必须已注册(404 说明路由没挂上):{:?}",
|
||||
path, body
|
||||
);
|
||||
assert_eq!(body["code"], 400, "{} 查无应是业务失败:{}", path, body);
|
||||
assert_eq!(body["msg"], "记录不存在或已删除");
|
||||
assert!(body["data"].is_null(), "业务失败的 data 为 null(信封恒带 data 键)");
|
||||
assert_eq!(body["msg"], want_msg, "{} 的查无文案与上游不符", path);
|
||||
assert_eq!(
|
||||
body.get("data"),
|
||||
Some(&Value::Null),
|
||||
"业务失败的 data 必须是 null(且**必须存在 data 键**)"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,13 +171,17 @@ async fn crud_routes_are_guarded_and_use_the_business_envelope() {
|
||||
/// 「HTTP 200 + `code=200` + `data.list` 是数组」。
|
||||
#[tokio::test]
|
||||
async fn every_registry_entity_has_a_working_list_route() {
|
||||
let (app, token) = build().await;
|
||||
let (app, token, _state) = build().await;
|
||||
let mut seen = 0usize;
|
||||
for spec in tdc_connector::registry::REGISTRY {
|
||||
seen += 1;
|
||||
let (status, body) = call(&app, get(spec.path, Some(token.as_str()))).await;
|
||||
assert_eq!(status, 200, "{} 列表路由未挂上:{:?}", spec.api_name, body);
|
||||
assert_eq!(body["code"], 200, "{} 列表应返回业务信封:{:?}", spec.api_name, body);
|
||||
assert_eq!(
|
||||
body["code"], 200,
|
||||
"{} 列表应返回业务信封:{:?}",
|
||||
spec.api_name, body
|
||||
);
|
||||
assert!(
|
||||
body["data"]["list"].is_array(),
|
||||
"{} 列表 data.list 必须是数组:{:?}",
|
||||
@@ -150,16 +196,24 @@ async fn every_registry_entity_has_a_working_list_route() {
|
||||
);
|
||||
|
||||
// /All 也要挂上(裸数组)
|
||||
let (status, body) = call(&app, get(&format!("{}/All", spec.path), Some(token.as_str()))).await;
|
||||
let (status, body) = call(
|
||||
&app,
|
||||
get(&format!("{}/All", spec.path), Some(token.as_str())),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "{}/All 路由未挂上:{:?}", spec.api_name, body);
|
||||
assert!(body["data"].is_array(), "{}/All 必须返回裸数组", spec.api_name);
|
||||
assert!(
|
||||
body["data"].is_array(),
|
||||
"{}/All 必须返回裸数组",
|
||||
spec.api_name
|
||||
);
|
||||
}
|
||||
assert_eq!(seen, 18, "注册表必须是 18 个实体,实际 {}", seen);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn incompatible_protocol_version_is_rejected_with_401() {
|
||||
let (app, token) = build().await;
|
||||
let (app, token, _state) = build().await;
|
||||
|
||||
let mut r = get("/api/ssw/tdc/Product", Some(token.as_str()));
|
||||
r.headers_mut()
|
||||
@@ -169,3 +223,229 @@ async fn incompatible_protocol_version_is_rejected_with_401() {
|
||||
assert_eq!(body["msg"], "跨端协议版本不兼容,请升级对端");
|
||||
assert!(body.get("data").is_none());
|
||||
}
|
||||
|
||||
/// 🔴 **每实体 6 条路由里另外 4 族(GET {id} / POST / PUT / DELETE)必须走一遍 HTTP**。
|
||||
///
|
||||
/// 评审变异 M4(删 PUT 路由)、M5(删整个 `/{id}` 路由块)曾**存活** ⇒ 本用例是它们的解药。
|
||||
#[tokio::test]
|
||||
async fn write_routes_work_over_http() {
|
||||
let (app, token, _state) = build().await;
|
||||
let t = token.as_str();
|
||||
|
||||
// ① POST 新增 ⇒ 业务信封 + data 是新 id
|
||||
let (status, body) = call(
|
||||
&app,
|
||||
json_req(
|
||||
"POST",
|
||||
"/api/ssw/tdc/PolicyTemplate",
|
||||
Some(t),
|
||||
r#"{"name":"冒烟策略模板"}"#,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "POST 应返回业务信封:{:?}", body);
|
||||
assert_eq!(body["code"], 200, "POST 应成功:{:?}", body);
|
||||
let id = body["data"]
|
||||
.as_str()
|
||||
.expect("新增成功后 data 必须是 id 字符串")
|
||||
.to_string();
|
||||
assert!(!id.is_empty(), "新增返回的 id 不得为空");
|
||||
|
||||
// ② GET {id} ⇒ 详情,且能看到刚建的 name
|
||||
let (status, body) = call(
|
||||
&app,
|
||||
get(&format!("/api/ssw/tdc/PolicyTemplate/{}", id), Some(t)),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "GET {id} 应返回业务信封:{:?}", body);
|
||||
assert_eq!(body["code"], 200, "GET {id} 应成功:{:?}", body);
|
||||
assert_eq!(body["data"]["id"], id, "详情必须回显同一个 id");
|
||||
assert_eq!(body["data"]["name"], "冒烟策略模板");
|
||||
|
||||
// ③ PUT {id} ⇒ 修改成功,且改完能读出来
|
||||
let (status, body) = call(
|
||||
&app,
|
||||
json_req(
|
||||
"PUT",
|
||||
&format!("/api/ssw/tdc/PolicyTemplate/{}", id),
|
||||
Some(t),
|
||||
r#"{"name":"改名后的策略模板"}"#,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "PUT 应返回业务信封:{:?}", body);
|
||||
assert_eq!(body["code"], 200, "PUT 应成功:{:?}", body);
|
||||
let (status, body) = call(
|
||||
&app,
|
||||
get(&format!("/api/ssw/tdc/PolicyTemplate/{}", id), Some(t)),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(
|
||||
body["data"]["name"], "改名后的策略模板",
|
||||
"PUT 的改动必须读得回来"
|
||||
);
|
||||
|
||||
// ④ DELETE {id} ⇒ 成功;再 GET ⇒ 业务失败(逻辑删除生效)
|
||||
let (status, body) = call(
|
||||
&app,
|
||||
json_req(
|
||||
"DELETE",
|
||||
&format!("/api/ssw/tdc/PolicyTemplate/{}", id),
|
||||
Some(t),
|
||||
"",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "DELETE 应返回业务信封:{:?}", body);
|
||||
assert_eq!(body["code"], 200, "DELETE 应成功:{:?}", body);
|
||||
let (status, body) = call(
|
||||
&app,
|
||||
get(&format!("/api/ssw/tdc/PolicyTemplate/{}", id), Some(t)),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(
|
||||
body["code"], 400,
|
||||
"逻辑删除后再查必须是业务失败:{:?}",
|
||||
body
|
||||
);
|
||||
}
|
||||
|
||||
/// 🔴 `/Detail` 必须是**聚合体**(带 `fieldRules` / `maskRules` 两张子表)。
|
||||
///
|
||||
/// 评审变异 M3(把 `detail_aggregate` 换成 `detail`)曾**存活** ⇒ 本用例是它的解药。
|
||||
/// 上游前端 `ResourceDetailModal.vue` / `ProductDetailModal.vue` / `MountDataDrawer.vue`
|
||||
/// 都依赖这两个字段。
|
||||
#[tokio::test]
|
||||
async fn resource_detail_returns_child_tables() {
|
||||
let (app, token, state) = build().await;
|
||||
|
||||
// 写入资源 + 两条子表行(🔴 所有 DB 访问必须持 `state.db_lock`)
|
||||
{
|
||||
let _g = state.db_lock.lock().await;
|
||||
state
|
||||
.db
|
||||
.exec(
|
||||
"INSERT INTO tdc_resource (f_id, f_resource_code, f_name) \
|
||||
VALUES ('R-AGG-1', 'RES-AGG-1', '聚合测试资源')",
|
||||
)
|
||||
.await
|
||||
.expect("插入资源失败");
|
||||
state
|
||||
.db
|
||||
.exec(
|
||||
"INSERT INTO tdc_resource_field (f_id, f_resource_id, f_field_name, f_field_type) \
|
||||
VALUES ('RF-AGG-1', 'R-AGG-1', 'id', 'varchar')",
|
||||
)
|
||||
.await
|
||||
.expect("插入字段说明失败");
|
||||
state
|
||||
.db
|
||||
.exec(
|
||||
"INSERT INTO tdc_resource_mask_rule \
|
||||
(f_id, f_resource_id, f_field_name, f_field_type, f_mask_type) \
|
||||
VALUES ('RM-AGG-1', 'R-AGG-1', 'name', 'varchar', 'HASH')",
|
||||
)
|
||||
.await
|
||||
.expect("插入脱敏规则失败");
|
||||
}
|
||||
|
||||
let (status, body) = call(
|
||||
&app,
|
||||
get("/api/ssw/tdc/Resource/R-AGG-1/Detail", Some(token.as_str())),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
status, 200,
|
||||
"/Resource/{{id}}/Detail 应返回业务信封:{:?}",
|
||||
body
|
||||
);
|
||||
assert_eq!(
|
||||
body["code"], 200,
|
||||
"/Resource/{{id}}/Detail 应成功:{:?}",
|
||||
body
|
||||
);
|
||||
assert_eq!(body["data"]["id"], "R-AGG-1");
|
||||
assert!(
|
||||
body["data"]["fieldRules"].is_array(),
|
||||
"/Detail 必须带 fieldRules 子表:{:?}",
|
||||
body
|
||||
);
|
||||
assert!(
|
||||
body["data"]["maskRules"].is_array(),
|
||||
"/Detail 必须带 maskRules 子表:{:?}",
|
||||
body
|
||||
);
|
||||
assert_eq!(body["data"]["fieldRules"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(body["data"]["maskRules"].as_array().unwrap().len(), 1);
|
||||
|
||||
// 同一资源走 Dataset 侧(同一张表)⇒ 同样能读到聚合体
|
||||
let (status, body) = call(
|
||||
&app,
|
||||
get("/api/ssw/tdc/Dataset/R-AGG-1/Detail", Some(token.as_str())),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(
|
||||
body["code"], 200,
|
||||
"/Dataset/{{id}}/Detail 应成功:{:?}",
|
||||
body
|
||||
);
|
||||
assert!(body["data"]["fieldRules"].is_array());
|
||||
assert!(body["data"]["maskRules"].is_array());
|
||||
}
|
||||
|
||||
/// 🔴 畸形 JSON / 错误媒体类型 ⇒ **业务信封**(不是 axum 默认的 `text/plain` 400)。
|
||||
///
|
||||
/// 上游 `SswExceptionHandler#handleNotReadable` 把 `HttpMessageNotReadableException`
|
||||
/// 映射成 `ActionResult.fail("请求体格式有误,请检查 JSON 结构与字段类型")`
|
||||
/// ⇒ HTTP 200 + `code=400`(`ActionResult.fail(String)` 的 code 恒为 400)。
|
||||
#[tokio::test]
|
||||
async fn malformed_json_returns_the_business_envelope() {
|
||||
let (app, token, _state) = build().await;
|
||||
let t = token.as_str();
|
||||
|
||||
let (status, body) = call(
|
||||
&app,
|
||||
json_req("POST", "/api/ssw/tdc/PolicyTemplate", Some(t), "{bad"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
status, 200,
|
||||
"畸形 JSON 也应是 HTTP 200 + 业务信封:{:?}",
|
||||
body
|
||||
);
|
||||
assert_eq!(body["code"], 400, "畸形 JSON 应是业务失败:{:?}", body);
|
||||
assert_eq!(body["msg"], "请求体格式有误,请检查 JSON 结构与字段类型");
|
||||
assert_eq!(body.get("data"), Some(&Value::Null));
|
||||
|
||||
// 错误媒体类型:body 不是 JSON ⇒ 同一口径(上游 415 由 JNPF 全局兜底,形状未知)
|
||||
let r = Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/ssw/tdc/PolicyTemplate")
|
||||
.header("Content-Type", "text/plain")
|
||||
.header("X-Internal-Token", t)
|
||||
.body(Body::from("这不是 JSON"))
|
||||
.unwrap();
|
||||
let (status, body) = call(&app, r).await;
|
||||
assert_eq!(status, 200, "错误媒体类型也应是业务信封:{:?}", body);
|
||||
assert_eq!(body["code"], 400, "错误媒体类型应是业务失败:{:?}", body);
|
||||
assert_eq!(body["msg"], "请求体格式有误,请检查 JSON 结构与字段类型");
|
||||
}
|
||||
|
||||
/// 方法不允许 ⇒ JSON(不是空体)。
|
||||
#[tokio::test]
|
||||
async fn method_not_allowed_returns_json() {
|
||||
let (app, token, _state) = build().await;
|
||||
let r = Request::builder()
|
||||
.method("PATCH")
|
||||
.uri("/api/ssw/tdc/PolicyTemplate")
|
||||
.header("X-Internal-Token", token.as_str())
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let (status, body) = call(&app, r).await;
|
||||
assert_eq!(status, 405, "方法不允许应是 405:{:?}", body);
|
||||
assert_eq!(body["code"], 405, "405 也要带 code:{:?}", body);
|
||||
assert_eq!(body["msg"], "方法不被允许");
|
||||
}
|
||||
Reference in new issue
Block a user