xyz-rust 0.4.10

One definition, three interfaces(CLI / HTTP / MCP)— a command toolkit for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
// httpapi 测试(Go httpapi_test.go 对应物):绑定合并、错误映射、healthz、
// openapi、Bearer/CORS 中间件。用 tower::ServiceExt::oneshot 直接调
// Router,不真起端口。

use std::sync::Arc;

use axum::body::Body;
use axum::http::Request;
use axum::response::Response;
use tower::ServiceExt;

use crate::Ctx;
use crate::errors;
use crate::httpapi;
use crate::registry::Registry;
use crate::spec::command::{Command, HTTPHints};
use xyz_rust::XyzArgs;

#[derive(XyzArgs)]
struct AddHTTPArgs {
    #[xyz(desc = "用户名", required, validate = "min=2", http = "path")]
    name: String,
    #[xyz(desc = "年龄", default = "18", http = "query")]
    age: i32,
    #[xyz(desc = "令牌", skip, http = "header", http_name = "X-Token")]
    token: String,
}

fn add_user(_: &Ctx, in_: &AddHTTPArgs) -> errors::Result<String> {
    Ok(format!("{}:{}:{}", in_.name, in_.age, in_.token))
}

async fn resp_body(resp: Response) -> (u16, String) {
    let status = resp.status().as_u16();
    let body = resp.into_body();
    let bytes = axum::body::to_bytes(body, 1 << 20).await.unwrap();
    (status, String::from_utf8_lossy(&bytes).into_owned())
}

async fn call(router: axum::routing::Router, req: Request<Body>) -> (u16, String) {
    let resp = router.oneshot(req).await.unwrap();
    resp_body(resp).await
}

fn add_reg() -> Registry {
    let reg = Registry::new();
    Command::new("user.add", add_user)
        .summary("加用户")
        .http(HTTPHints {
            method: "POST".into(),
            path: "/users/{name}".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    reg
}

#[tokio::test(flavor = "current_thread")]
async fn binding_merges_body_path_query_header() {
    let reg = add_reg();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    let body = serde_json::json!({"age": 9}).to_string();
    let req = Request::builder()
        .method("POST")
        .uri("/users/alice?age=7")
        .header("X-Token", "tk")
        .header("content-type", "application/json")
        .body(Body::from(body))
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 200);
    // query 显式提供优先于 body 基底(body 先铺底,query 后覆盖——Go 同序)
    assert_eq!(out.trim(), "\"alice:7:tk\"");
}

#[tokio::test(flavor = "current_thread")]
async fn invalid_declared_json_body_is_400() {
    let reg = add_reg();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    // 显式声明 application/json 且解析失败 → 严格 400
    let req = Request::builder()
        .method("POST")
        .uri("/users/alice")
        .header("content-type", "application/json")
        .body(Body::from("{nope".to_string()))
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 400);
    assert!(out.contains("invalid JSON body"), "{out}");
}

#[tokio::test(flavor = "current_thread")]
async fn undeclared_body_is_not_rejected_as_json() {
    // 非 JSON 声明的不可解析体(如表单体)不提前判死:交给 form 绑定/其余字段。
    let reg = Registry::new();

    #[derive(XyzArgs)]
    struct F {
        #[xyz(desc = "n", http = "form")]
        note: String,
    }
    fn fh(_: &Ctx, in_: &F) -> errors::Result<String> {
        Ok(format!("note={}", in_.note))
    }
    Command::new("f.submit", fh)
        .http(HTTPHints {
            method: "POST".into(),
            path: "/f".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    // 无 Content-Type 的 form 体可以解出,不落 400
    let req = Request::builder()
        .method("POST")
        .uri("/f")
        .body(Body::from("note=hello%20form".to_string()))
        .unwrap();
    let (status, out) = call(router.clone(), req).await;
    assert_eq!(status, 200);
    assert_eq!(out.trim(), "\"note=hello form\"");
    // form 值只取请求体,不混入 query(与上游 v0.2.2 一致)
    let req = Request::builder()
        .method("POST")
        .uri("/f?note=fromquery")
        .body(Body::from("note=frombody".to_string()))
        .unwrap();
    let (_, out) = call(router, req).await;
    assert_eq!(out.trim(), "\"note=frombody\"");
}

#[tokio::test(flavor = "current_thread")]
async fn validation_error_maps_to_400() {
    let reg = add_reg();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    let req = Request::builder()
        .method("POST")
        .uri("/users/a") // min=2 失败
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 400);
    assert!(
        out.contains("invalid value for field \\\"name\\\": min"),
        "{out}"
    );
}

#[tokio::test(flavor = "current_thread")]
async fn business_error_maps_to_404_with_error_body() {
    let reg = Registry::new();

    #[derive(XyzArgs)]
    struct N {
        #[xyz(desc = "n")]
        n: String,
    }
    fn nh(_: &Ctx, _: &N) -> errors::Result<String> {
        Err(errors::new(errors::Kind::NotFound, "no such user"))
    }
    Command::new("n.hit", nh)
        .http(HTTPHints {
            method: "GET".into(),
            path: "/n".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    let req = Request::builder()
        .method("GET")
        .uri("/n")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 404);
    // §8.6 共享错误体:扁平 error 键保留,kind 纯增量。
    assert_eq!(
        out.trim(),
        "{\"error\":\"no such user\",\"kind\":\"not_found\"}"
    );
}

#[tokio::test(flavor = "current_thread")]
async fn rich_error_body_and_status_override() {
    use crate::errors;
    let reg = Registry::new();
    #[derive(xyz_rust::XyzArgs)]
    struct RichArgs {
        #[xyz(desc = "n")]
        n: String,
    }
    fn rich(_: &Ctx, _: &RichArgs) -> errors::Result<String> {
        Err(errors::new(errors::Kind::Conflict, "dup")
            .with_code("DUPLICATE")
            .with_detail("name", serde_json::json!("alice"))
            .with_status(410))
    }
    Command::new("n.rich", rich)
        .http(HTTPHints {
            method: "GET".into(),
            path: "/n/rich".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    let req = Request::builder()
        .method("GET")
        .uri("/n/rich")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    // §8.5 status 覆盖优先于 Kind 推导(Conflict → 409 被 410 覆盖)。
    assert_eq!(status, 410);
    let v: serde_json::Value = serde_json::from_str(out.trim()).unwrap();
    assert_eq!(v["error"], "dup");
    assert_eq!(v["kind"], "conflict");
    assert_eq!(v["code"], "DUPLICATE");
    assert_eq!(v["detail"]["name"], "alice");
}

#[tokio::test(flavor = "current_thread")]
async fn healthz_and_openapi() {
    let reg = add_reg();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    let req = Request::builder()
        .method("GET")
        .uri("/healthz")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router.clone(), req).await;
    assert_eq!(status, 200);
    assert_eq!(out, "{\"status\":\"ok\"}\n");
    let req = Request::builder()
        .method("GET")
        .uri("/openapi.json")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 200);
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(v["openapi"], "3.0.3");
    let path = v["paths"]["/users/{name}"]["post"].clone();
    assert_eq!(path["summary"], "加用户");
    // 参数表:path 里的 name + requestBody
    let params = path["parameters"].as_array().unwrap();
    assert!(
        params
            .iter()
            .any(|p| p["name"] == "name" && p["in"] == "path"),
        "{params:?}"
    );
    assert!(path["requestBody"]["content"]["application/json"]["schema"]["type"] == "object");
}

#[test]
fn conflicting_routes_rejected() {
    let reg = Registry::new();

    #[derive(XyzArgs)]
    struct X {}
    fn xh(_: &Ctx, _: &X) -> errors::Result<String> {
        Ok(String::new())
    }
    Command::new("x.one", xh)
        .http(HTTPHints {
            method: "GET".into(),
            path: "/dup".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    Command::new("x.two", xh)
        .http(HTTPHints {
            method: "GET".into(),
            path: "/dup".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    let err = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap_err();
    assert!(err.to_string().contains("conflicts"), "{err}");
    // 同路径不同方法不冲突
    let reg2 = Registry::new();
    Command::new("x.one", xh)
        .http(HTTPHints {
            method: "GET".into(),
            path: "/d".into(),
            ..Default::default()
        })
        .register(&reg2)
        .unwrap();
    Command::new("x.two", xh)
        .http(HTTPHints {
            method: "POST".into(),
            path: "/d".into(),
            ..Default::default()
        })
        .register(&reg2)
        .unwrap();
    assert!(httpapi::router(&reg2, Arc::new(Ctx::new())).is_ok());
}

#[tokio::test(flavor = "current_thread")]
async fn handler_for_binds_one_entry() {
    let reg = add_reg();
    let entry = reg.get("user.add").unwrap();
    let h = httpapi::handler_for(entry);
    let router: axum::routing::Router =
        axum::routing::Router::new().route("/users/{name}", axum::routing::post(h));
    let req = Request::builder()
        .method("POST")
        .uri("/users/some?age=3")
        .header("X-Token", "z")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 200);
    assert_eq!(out.trim(), "\"some:3:z\""); // 挂载点沿用原路由模板,path 参数才能被摘出(Go HandlerFor 同契约)
}

#[tokio::test(flavor = "current_thread")]
async fn bearer_and_cors_middleware() {
    let reg = add_reg();
    let mut router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    router = crate::httpapi::middleware::apply(
        router,
        vec!["s3cret".into()],
        vec!["http://app.local".into()],
        std::time::Duration::ZERO,
    );
    // 无凭据 401 + WWW-Authenticate
    let req = Request::builder()
        .method("GET")
        .uri("/nope")
        .body(Body::empty())
        .unwrap();
    let resp = router.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status().as_u16(), 401);
    assert_eq!(resp.headers().get("www-authenticate").unwrap(), "Bearer");
    // 带凭据进入路由(404 因为 /nope 无路由——鉴权已通过)
    let req = Request::builder()
        .method("GET")
        .uri("/nope")
        .header("Authorization", "Bearer s3cret")
        .body(Body::empty())
        .unwrap();
    let resp = router.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status().as_u16(), 404);
    // CORS 预检(无凭据)在鉴权之前应答 204——顺序锁死
    let req = Request::builder()
        .method("OPTIONS")
        .uri("/nope")
        .header("Origin", "http://app.local")
        .body(Body::empty())
        .unwrap();
    let resp = router.oneshot(req).await.unwrap();
    assert_eq!(resp.status().as_u16(), 204);
}

#[tokio::test(flavor = "current_thread")]
async fn gzip_compresses_when_asked() {
    let reg = add_reg();
    let mut router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    router = crate::httpapi::middleware::apply(router, vec![], vec![], std::time::Duration::ZERO);
    let req = Request::builder()
        .method("GET")
        .uri("/healthz")
        .header("Accept-Encoding", "gzip")
        .body(Body::empty())
        .unwrap();
    let resp = router.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status().as_u16(), 200);
    assert_eq!(resp.headers().get("content-encoding").unwrap(), "gzip");
}

#[test]
fn normalize_addr_port_shorthand() {
    use crate::httpapi::normalize_addr;
    assert_eq!(normalize_addr(":8080"), "0.0.0.0:8080");
    assert_eq!(normalize_addr("127.0.0.1:8080"), "127.0.0.1:8080");
    assert_eq!(normalize_addr("0.0.0.0:9090"), "0.0.0.0:9090");
    // IPv6 缩写不得被误当端口简写。
    assert_eq!(normalize_addr("::"), "::");
    assert_eq!(normalize_addr("[::1]:8080"), "[::1]:8080");
}

#[tokio::test(flavor = "current_thread")]
async fn server_context_headers_on_all_responses() {
    use axum::middleware::from_fn;
    use tower::ServiceExt;

    let router = httpapi::router(&add_reg(), Arc::new(Ctx::new())).unwrap();
    let with_ctx = router.layer(from_fn(crate::httpapi::middleware::server_context_mw(
        "appt".to_string(),
        "9.9".to_string(),
        vec![("X-Custom".to_string(), "c".to_string())],
        true,
    )));
    // 404(无路由)也带头:身份头全路由。
    let req = Request::builder()
        .method("GET")
        .uri("/nowhere")
        .body(Body::empty())
        .unwrap();
    let resp = with_ctx.oneshot(req).await.unwrap();
    let h = resp.headers();
    assert_eq!(h.get("x-app-name").unwrap(), "appt");
    assert_eq!(h.get("x-app-version").unwrap(), "9.9");
    assert_eq!(h.get("x-xyz-version").unwrap(), crate::version::SDK_VERSION);
    assert_eq!(h.get("x-custom").unwrap(), "c");

    // 关闭开关:自动头消失,自定义头保留。
    let router = httpapi::router(&add_reg(), Arc::new(Ctx::new())).unwrap();
    let no_auto = router
        .clone()
        .layer(from_fn(crate::httpapi::middleware::server_context_mw(
            "appt".to_string(),
            "9.9".to_string(),
            vec![("X-Custom".to_string(), "c".to_string())],
            false,
        )));
    let req = Request::builder()
        .method("GET")
        .uri("/nowhere")
        .body(Body::empty())
        .unwrap();
    let resp = no_auto.oneshot(req).await.unwrap();
    let h = resp.headers();
    assert!(h.get("x-app-name").is_none());
    assert_eq!(h.get("x-custom").unwrap(), "c");

    // 每路由头:命中真实命令时带 command/duration。
    let req = Request::builder()
        .method("GET")
        .uri("/users/alice?age=3")
        .body(Body::empty())
        .unwrap();
    let resp = router.oneshot(req).await.unwrap();
    assert!(resp.headers().get("x-xyz-command").is_none()); // 无 mw 时不留
}

#[tokio::test(flavor = "current_thread")]
async fn accept_language_localizes_and_reaches_handler() {
    use crate::lang::{XyzLang, parse_accept_language};
    // 解析器(spec §11.7):q 择优 + 前缀匹配 + 不受支持回退 None。
    assert_eq!(
        parse_accept_language("zh-CN,zh;q=0.9,en;q=0.8"),
        Some(XyzLang::ZhCn)
    );
    assert_eq!(parse_accept_language("en-US,en;q=0.9"), Some(XyzLang::En));
    assert_eq!(parse_accept_language("fr,de;q=0.9"), None);
    assert_eq!(
        parse_accept_language("en;q=0.3,zh;q=0.9"),
        Some(XyzLang::ZhCn)
    );

    // handler 经 language_from_ctx 读请求语言。
    let reg = Registry::new();
    #[derive(xyz_rust::XyzArgs)]
    struct MArgs {
        #[xyz(desc = "n")]
        n: String,
    }
    fn who(_: &Ctx, _: &MArgs) -> errors::Result<String> {
        Ok(String::new())
    }
    // 换成读 ctx 的版本。
    struct CtxLang;
    fn lang_of(ctx: &Ctx, _: &MArgs) -> errors::Result<String> {
        let _ = CtxLang;
        Ok(xyz_rust::language_from_ctx(ctx))
    }
    Command::new("m.lang", lang_of)
        .http(HTTPHints {
            method: "GET".into(),
            path: "/m/lang".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    let _ = who;
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    let req = Request::builder()
        .method("GET")
        .uri("/m/lang")
        .header("Accept-Language", "zh-CN,en;q=0.5")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router.clone(), req).await;
    assert_eq!(status, 200);
    assert_eq!(out.trim(), "\"zh-CN\"");
    // 无 header:回退进程语言。
    let req = Request::builder()
        .method("GET")
        .uri("/m/lang")
        .body(Body::empty())
        .unwrap();
    let (_, out) = call(router, req).await;
    assert_eq!(
        out.trim(),
        format!("\"{}\"", crate::lang::current().as_str())
    );

    // 框架消息本地化:坏 JSON body 的 400 用请求语言(需 POST 路由)。
    Command::new("m.post", lang_of)
        .http(HTTPHints {
            method: "POST".into(),
            path: "/m/post".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    let req = Request::builder()
        .method("POST")
        .uri("/m/post")
        .header("Content-Type", "application/json")
        .header("Accept-Language", "zh-CN")
        .body(Body::from("{not json"))
        .unwrap();
    let (status, out) = call(httpapi::router(&reg, Arc::new(Ctx::new())).unwrap(), req).await;
    assert_eq!(status, 400);
    assert!(out.contains("无效的 JSON 请求体"), "{out}");
}

#[tokio::test(flavor = "current_thread")]
async fn missing_route_is_localized_json_404() {
    let router = httpapi::router(&add_reg(), Arc::new(Ctx::new())).unwrap();
    // 无 header:JSON 错误体(进程语言文本非空)。
    let req = Request::builder()
        .method("GET")
        .uri("/no/such/route")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router.clone(), req).await;
    assert_eq!(status, 404);
    let v: serde_json::Value = serde_json::from_str(out.trim()).unwrap();
    assert!(v["error"].as_str().is_some_and(|s| !s.is_empty()));

    // 带 zh-CN:本地化文案确定性断言。
    let req = Request::builder()
        .method("GET")
        .uri("/no/such/route")
        .header("Accept-Language", "zh-CN")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 404);
    let v: serde_json::Value = serde_json::from_str(out.trim()).unwrap();
    assert_eq!(v["error"], "未找到");
}

#[tokio::test(flavor = "current_thread")]
async fn default_get_post_and_multi_method() {
    use crate::registry::Registry;
    use crate::spec::command::Command;

    #[derive(xyz_rust::XyzArgs)]
    struct DArgs {
        #[xyz(desc = "值")]
        v: i64,
    }
    fn echo(_: &Ctx, a: &DArgs) -> errors::Result<i64> {
        Ok(a.v)
    }
    let reg = Registry::new();
    // 空 method → 默认 GET+POST(spec §11.1)。
    Command::new("d.echo", echo)
        .http(HTTPHints {
            method: String::new(),
            path: "/d/echo".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    // 逗号分隔多方法。
    Command::new("d.multi", echo)
        .http(HTTPHints {
            method: "GET,POST,PUT".into(),
            path: "/d/multi".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();

    // 默认:GET(query)与 POST(body)都可达同一 handler。
    let req = Request::builder()
        .method("GET")
        .uri("/d/echo?v=7")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router.clone(), req).await;
    assert_eq!(status, 200);
    assert_eq!(out.trim(), "7");
    let req = Request::builder()
        .method("POST")
        .uri("/d/echo")
        .header("Content-Type", "application/json")
        .body(Body::from("{\"v\":9}"))
        .unwrap();
    let (status, out) = call(router.clone(), req).await;
    assert_eq!(status, 200);
    assert_eq!(out.trim(), "9");

    // 多方法:PUT 也可达(原只认单方法时会 405)。
    for m in ["GET", "POST", "PUT"] {
        let req = Request::builder()
            .method(m)
            .uri("/d/multi?v=1")
            .body(Body::empty())
            .unwrap();
        let (status, _) = call(router.clone(), req).await;
        assert_eq!(status, 200, "method {m}");
    }
}

#[tokio::test(flavor = "current_thread")]
async fn openapi_is_rich() {
    use crate::registry::Registry;
    use crate::spec::command::Command;

    #[derive(xyz_rust::XyzArgs)]
    struct RArgs {
        #[xyz(desc = "目标名", required, http = "path")]
        name: String,
        #[xyz(desc = "模式", enum = "fast,slow", default = "fast", http = "query")]
        mode: String,
        #[xyz(desc = "令牌", http = "header", http_name = "X-Token")]
        token: String,
        // 未标注 http location:运行期按 query 绑定,文档必须同口径
        // 收录(否则 openapi.json 漏掉全部默认字段)。
        #[xyz(desc = "数量上限", default = "10")]
        limit: i32,
    }
    fn get(_: &Ctx, a: &RArgs) -> errors::Result<String> {
        Ok(a.name.clone())
    }
    let reg = Registry::new();
    Command::new("r.get", get)
        .summary("读取资源")
        .description("更长的说明")
        .http(HTTPHints {
            method: String::new(),
            path: "/r/{name}".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();

    let doc_handler = crate::httpapi::openapi::openapi_handler(&reg, "appt", "9.9");
    let router =
        axum::routing::Router::new().route("/openapi.json", axum::routing::get(doc_handler));
    let req = Request::builder()
        .method("GET")
        .uri("/openapi.json")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 200);
    let doc: serde_json::Value = serde_json::from_str(out.trim()).unwrap();

    // info 身份 = 应用身份(spec §11.3)。
    assert_eq!(doc["info"]["title"], "appt");
    assert_eq!(doc["info"]["version"], "9.9");

    // 默认 GET+POST → 两个 operation;仅 post 带 requestBody。
    let ops = &doc["paths"]["/r/{name}"];
    assert!(ops["get"].is_object(), "{ops}");
    assert!(ops["post"].is_object(), "{ops}");
    assert!(ops["get"].get("requestBody").is_none());
    assert!(ops["post"]["requestBody"]["content"]["application/json"]["schema"].is_object());
    // summary + description。
    assert_eq!(ops["get"]["summary"], "读取资源");
    assert_eq!(ops["get"]["description"], "更长的说明");

    // parameters:path 恒 required + query 富 schema(enum/default)+ header。
    let params = ops["get"]["parameters"].as_array().unwrap();
    let by = |name: &str| {
        params
            .iter()
            .find(|p| p["name"] == name)
            .unwrap_or_else(|| panic!("param {name} missing in {params:?}"))
    };
    let path_p = by("name");
    assert_eq!(path_p["in"], "path");
    assert_eq!(path_p["required"], true);
    assert_eq!(path_p["description"], "目标名");
    let mode_p = by("mode");
    assert_eq!(mode_p["in"], "query");
    assert_eq!(mode_p["schema"]["type"], "string");
    assert_eq!(
        mode_p["schema"]["enum"],
        serde_json::json!(["fast", "slow"])
    );
    assert_eq!(mode_p["schema"]["default"], "fast");
    // 未标注字段:文档位置 = query(与运行期绑定同口径)。
    let limit_p = by("limit");
    assert_eq!(limit_p["in"], "query");
    assert_eq!(limit_p["schema"]["type"], "integer");
    assert_eq!(limit_p["schema"]["default"], 10);
    let token_p = by("X-Token");
    assert_eq!(token_p["in"], "header");
    assert_eq!(token_p["description"], "令牌");
}

#[tokio::test(flavor = "current_thread")]
async fn lowercase_methods_and_route_conflict_becomes_error() {
    use crate::registry::Registry;
    use crate::spec::command::Command;

    #[derive(xyz_rust::XyzArgs)]
    struct LArgs {
        #[xyz(desc = "值")]
        v: i64,
    }
    fn echo(_: &Ctx, a: &LArgs) -> errors::Result<i64> {
        Ok(a.v)
    }
    // 小写方法名归一为大写(对齐 Go ToUpper)。
    let reg = Registry::new();
    Command::new("l.c", echo)
        .http(HTTPHints {
            method: "get".into(),
            path: "/l/c".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    let req = Request::builder()
        .method("GET")
        .uri("/l/c?v=3")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 200);
    assert_eq!(out.trim(), "3");

    // 占用内置路由(/healthz)→ 注册期错误而不是进程 panic。
    let reg2 = Registry::new();
    Command::new("bad.hz", echo)
        .http(HTTPHints {
            method: "GET".into(),
            path: "/healthz".into(),
            ..Default::default()
        })
        .register(&reg2)
        .unwrap();
    let err = httpapi::router(&reg2, Arc::new(Ctx::new())).unwrap_err();
    assert!(
        err.to_string().contains("conflict"),
        "want conflict error, got: {err}"
    );
}