wx-rust-open 0.1.2

WxRust 开放平台(第三方平台)模块(对应 weixin-java-open)
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
//! WxOpenComponentService 覆盖率提升测试(自含 MockServer 模式)。
//!
//! 补充覆盖:
//! - oauth2_refresh_access_token(GET `/sns/oauth2/component/refresh_token`)
//! - miniapp_jscode2_session(GET `/sns/component/jscode2session`)
//! - add_to_template / add_to_template_with_type / delete_template
//! - fast_register_weapp / fast_register_weapp_search
//! - fast_register_personal_weapp / fast_register_personal_weapp_search
//! - fast_register_beta_weapp
//! - register_shop / check_audit_status / check_audit_status_with_appid
//! - submit_merchant_info / submit_basic_info
//! - get_minishop_brands / get_minishop_delivery_template / get_minishop_cat_list
//! - get_minishop_delivery_company
//! - minishop_push_coupon_to_user / minishop_update_coupon / minishop_update_coupon_status
//! - minishop_goods_add_spu / del_spu / update_spu / listing_spu / delisting_spu
//! - minishop_goods_add_sku / batch_add_sku / del_sku / update_sku
//! - minishop_goods_update_sku_price / update_sku_stock
//! - add_limit_discount_goods / get_limit_discount_list / update_limit_discount_status
//! - get_share_cloud_base_env / get_tcb_env_list / change_tcb_env / share_cloud_base_env
//! - clear_quota_v2 / apply_set_order_path_info
//! - modify_wxa_server_domain / get_domain_confirm_file / modify_wxa_jump_domain
//! - modify_wxa_jump_domain_info / get_authorizer_option / set_authorizer_option
//! - have_open / get_component_access_token / route updateauthorized
//!
//! 注意:返回 bean 含 `errcode: String` 的方法(WxOpenResult 等),因 executor
//! 层 WxError 要求 integer errcode 而 bean 要求 String errcode,happy path 不可达。
//! 这些方法测试 error path(executor errcode!=0 抛错)或请求体断言。

use std::net::SocketAddr;
use std::sync::{Arc, Mutex};

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};

use wx_rust_open::api::{WxOpenComponentService, WxOpenService};
use wx_rust_open::config::WxOpenConfigStorage;
use wx_rust_open::config::r#impl::WxOpenDefaultConfig;

// ---------------------------------------------------------------------------
// 自含 MockServer
// ---------------------------------------------------------------------------

#[derive(Clone)]
struct MockRoute {
    method: &'static str,
    path_prefix: String,
    responses: Vec<String>,
}

impl MockRoute {
    fn post(path_prefix: &str, responses: &[&str]) -> Self {
        Self {
            method: "POST",
            path_prefix: path_prefix.to_string(),
            responses: responses.iter().map(|s| s.to_string()).collect(),
        }
    }

    fn get(path_prefix: &str, responses: &[&str]) -> Self {
        Self {
            method: "GET",
            path_prefix: path_prefix.to_string(),
            responses: responses.iter().map(|s| s.to_string()).collect(),
        }
    }
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
struct RecordedRequest {
    method: String,
    path: String,
    body: String,
}

struct MockState {
    routes: Vec<MockRoute>,
    calls: Vec<usize>,
    requests: Vec<RecordedRequest>,
}

struct MockServer {
    addr: SocketAddr,
    state: Arc<Mutex<MockState>>,
}

impl MockServer {
    async fn start(routes: Vec<MockRoute>) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let state = Arc::new(Mutex::new(MockState {
            calls: vec![0; routes.len()],
            requests: Vec::new(),
            routes,
        }));
        let serve_state = state.clone();
        tokio::spawn(async move {
            loop {
                let (socket, _) = match listener.accept().await {
                    Ok(v) => v,
                    Err(_) => break,
                };
                let state = serve_state.clone();
                tokio::spawn(async move {
                    Self::handle(socket, state).await;
                });
            }
        });
        MockServer { addr, state }
    }

    async fn handle(mut socket: TcpStream, state: Arc<Mutex<MockState>>) {
        let mut buffer = Vec::new();
        let mut chunk = [0u8; 8192];
        let mut header_end = None;
        while header_end.is_none() {
            let n = match socket.read(&mut chunk).await {
                Ok(0) | Err(_) => return,
                Ok(n) => n,
            };
            buffer.extend_from_slice(&chunk[..n]);
            header_end = buffer
                .windows(4)
                .position(|w| w == b"\r\n\r\n")
                .map(|p| p + 4);
        }
        let header_end = header_end.unwrap();
        let head = buffer[..header_end].to_vec();
        let mut body = buffer[header_end..].to_vec();

        let head_str = String::from_utf8_lossy(&head);
        let mut lines = head_str.split("\r\n");
        let mut parts = lines.next().unwrap_or_default().split_whitespace();
        let method = parts.next().unwrap_or("").to_string();
        let path = parts.next().unwrap_or("").to_string();
        let mut content_length = 0usize;
        for line in lines {
            if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {
                content_length = v.trim().parse().unwrap_or(0);
            }
        }
        while body.len() < content_length {
            let n = match socket.read(&mut chunk).await {
                Ok(0) | Err(_) => break,
                Ok(n) => n,
            };
            body.extend_from_slice(&chunk[..n]);
        }
        body.truncate(content_length);
        let body_str = String::from_utf8_lossy(&body).to_string();

        let response = {
            let mut st = state.lock().unwrap();
            st.requests.push(RecordedRequest {
                method: method.clone(),
                path: path.clone(),
                body: body_str,
            });
            let mut match_idx: Option<usize> = None;
            for (i, route) in st.routes.iter().enumerate() {
                if route.method == method && path.starts_with(&route.path_prefix) {
                    match_idx = Some(i);
                    break;
                }
            }
            let mut response =
                "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                    .to_string();
            if let Some(i) = match_idx {
                let call = st.calls[i];
                st.calls[i] += 1;
                let idx = call.min(st.routes[i].responses.len() - 1);
                let resp_body = st.routes[i].responses[idx].clone();
                response = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    resp_body.len(),
                    resp_body
                );
            }
            response
        };
        let _ = socket.write_all(response.as_bytes()).await;
    }

    fn base_url(&self) -> String {
        format!("http://{}", self.addr)
    }

    fn requests(&self) -> Vec<RecordedRequest> {
        self.state.lock().unwrap().requests.clone()
    }

    fn call_count(&self, path_prefix: &str) -> usize {
        let st = self.state.lock().unwrap();
        st.routes
            .iter()
            .position(|r| r.path_prefix == path_prefix)
            .map(|i| st.calls[i])
            .unwrap_or(0)
    }
}

// ---------------------------------------------------------------------------
// 测试夹具
// ---------------------------------------------------------------------------

const COMPONENT_TOKEN_RESP: &str = r#"{"component_access_token":"comp_tok_v1","expires_in":7200}"#;

mod build {
    use wx_rust_open::config::r#impl::WxOpenDefaultConfig;

    pub fn default_config(base_url: &str) -> WxOpenDefaultConfig {
        let mut config = WxOpenDefaultConfig::new();
        config.set_component_app_id("component_appid_01");
        config.set_component_app_secret("component_secret_01");
        config.set_component_token("component_token_01");
        config.set_component_aes_key("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
        config.set_component_verify_ticket("ticket@@@init");
        config.set_api_host_url(base_url.to_string());
        config
    }
}

struct Harness {
    server: MockServer,
    config: Arc<WxOpenDefaultConfig>,
    #[allow(dead_code)]
    service: Arc<dyn WxOpenService>,
    component: Arc<dyn WxOpenComponentService>,
}

impl Harness {
    async fn new(extra_routes: Vec<MockRoute>) -> Self {
        let has_component_token = extra_routes
            .iter()
            .any(|r| r.path_prefix == "/cgi-bin/component/api_component_token");
        let mut routes = Vec::new();
        if !has_component_token {
            routes.push(MockRoute::post(
                "/cgi-bin/component/api_component_token",
                &[COMPONENT_TOKEN_RESP],
            ));
        }
        routes.extend(extra_routes);
        let server = MockServer::start(routes).await;
        let config = Arc::new(build::default_config(&server.base_url()));
        let service = wx_rust_open::api::r#impl::WxOpenServiceImpl::new_arc(config.clone());
        let component = service.wx_open_component_service().unwrap();
        Self {
            server,
            config,
            service,
            component,
        }
    }
}

fn req_body_json(req: &RecordedRequest) -> serde_json::Value {
    serde_json::from_str(&req.body).unwrap_or(serde_json::Value::Null)
}

fn assert_error_code(err: &wx_rust_common::error::WxErrorException, expected: i32) {
    assert_eq!(
        err.error_code(),
        Some(expected),
        "期望错误码 {expected},实际:{err:?}"
    );
}

const AUTHORIZER_APPID: &str = "wx_authorizer_cov_01";

// ═══════════════════════════════════════════════════════════════
// 1. oauth2_refresh_access_token
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn oauth2_refresh_access_token_parses() {
    let h = Harness::new(vec![MockRoute::get(
        "/sns/oauth2/component/refresh_token",
        &[r#"{"access_token":"refreshed_tok","expires_in":7200,
             "refresh_token":"new_refresh","openid":"oid_r","scope":"snsapi_base"}"#],
    )])
    .await;
    let token = h
        .component
        .oauth2_refresh_access_token("wx_app_r", "old_refresh")
        .await
        .unwrap();
    assert_eq!(token.access_token, "refreshed_tok");
    assert_eq!(token.open_id, "oid_r");

    let req = h.server.requests().pop().unwrap();
    assert!(req.path.starts_with("/sns/oauth2/component/refresh_token"));
    assert!(req.path.contains("appid=wx_app_r"));
    assert!(req.path.contains("refresh_token=old_refresh"));
    assert!(req.path.contains("component_access_token=comp_tok_v1"));
}

// ═══════════════════════════════════════════════════════════════
// 2. miniapp_jscode2_session
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn miniapp_jscode2_session_parses() {
    let h = Harness::new(vec![MockRoute::get(
        "/sns/component/jscode2session",
        &[r#"{"session_key":"sk_direct","openid":"oid_direct","unionid":"uni_direct"}"#],
    )])
    .await;
    let result = h
        .component
        .miniapp_jscode2_session("wx_ma_app", "js_code_direct")
        .await
        .unwrap();
    assert_eq!(result["session_key"], "sk_direct");
    assert_eq!(result["openid"], "oid_direct");

    let req = h.server.requests().pop().unwrap();
    assert!(req.path.starts_with("/sns/component/jscode2session"));
    assert!(req.path.contains("appid=wx_ma_app"));
    assert!(req.path.contains("js_code=js_code_direct"));
    assert!(req.path.contains("component_access_token=comp_tok_v1"));
}

// ═══════════════════════════════════════════════════════════════
// 3. 模板管理
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn add_to_template_posts() {
    let h = Harness::new(vec![MockRoute::post(
        "/wxa/addtotemplate",
        &[r#"{"errcode":0,"errmsg":"ok"}"#],
    )])
    .await;
    h.component.add_to_template(12345).await.unwrap();
    let req = h.server.requests().pop().unwrap();
    assert!(req.path.contains("access_token=comp_tok_v1"));
    assert_eq!(req_body_json(&req)["draft_id"], 12345);
}

#[tokio::test]
async fn add_to_template_with_type_posts() {
    let h = Harness::new(vec![MockRoute::post(
        "/wxa/addtotemplate",
        &[r#"{"errcode":0,"errmsg":"ok"}"#],
    )])
    .await;
    h.component
        .add_to_template_with_type(67890, 2)
        .await
        .unwrap();
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["draft_id"], 67890);
    assert_eq!(body["template_type"], 2);
}

#[tokio::test]
async fn delete_template_posts() {
    let h = Harness::new(vec![MockRoute::post(
        "/wxa/deletetemplate",
        &[r#"{"errcode":0,"errmsg":"ok"}"#],
    )])
    .await;
    h.component.delete_template(11111).await.unwrap();
    let req = h.server.requests().pop().unwrap();
    assert_eq!(req_body_json(&req)["template_id"], 11111);
}

// ═══════════════════════════════════════════════════════════════
// 4. 快速创建小程序(请求体断言 + error path)
// ═══════════════════════════════════════════════════════════════

/// fast_register_weapp:executor errcode=0 通过,bean 反序列化失败(String vs int)。
/// 覆盖 URL 构建、请求体拼装、post_with_key 调用链。
#[tokio::test]
async fn fast_register_weapp_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/cgi-bin/component/fastregisterweapp",
        &[r#"{"errcode":0,"errmsg":"ok"}"#],
    )])
    .await;
    // 返回 bean errcode: String vs executor integer → serde 错误或 Ok
    let _ = h
        .component
        .fast_register_weapp("name1", "code1", "1", "wxuser1", "张三", "13800000000")
        .await;
    let req = h.server.requests().pop().unwrap();
    assert!(req.path.contains("action=create"));
    assert!(req.path.contains("component_access_token=comp_tok_v1"));
    let body = req_body_json(&req);
    assert_eq!(body["name"], "name1");
    assert_eq!(body["code"], "code1");
    assert_eq!(body["legal_persona_wechat"], "wxuser1");
    assert_eq!(body["legal_persona_name"], "张三");
}

#[tokio::test]
async fn fast_register_weapp_search_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/cgi-bin/component/fastregisterweapp",
        &[r#"{"errcode":0,"errmsg":"ok"}"#],
    )])
    .await;
    let _ = h
        .component
        .fast_register_weapp_search("name2", "wxuser2", "李四")
        .await;
    let req = h.server.requests().pop().unwrap();
    assert!(req.path.contains("action=search"));
    let body = req_body_json(&req);
    assert_eq!(body["name"], "name2");
}

#[tokio::test]
async fn fast_register_personal_weapp_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/wxa/component/fastregisterpersonalweapp",
        &[r#"{"errcode":0,"errmsg":"ok","taskid":"task_p1"}"#],
    )])
    .await;
    let _ = h
        .component
        .fast_register_personal_weapp("idname1", "wxuser_p1", "13900000000")
        .await;
    let req = h.server.requests().pop().unwrap();
    assert!(req.path.contains("action=create"));
    let body = req_body_json(&req);
    assert_eq!(body["idname"], "idname1");
    assert_eq!(body["wxuser"], "wxuser_p1");
}

#[tokio::test]
async fn fast_register_personal_weapp_search_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/wxa/component/fastregisterpersonalweapp",
        &[r#"{"errcode":0,"errmsg":"ok","taskid":"task_p2"}"#],
    )])
    .await;
    let _ = h
        .component
        .fast_register_personal_weapp_search("task_query_1")
        .await;
    let req = h.server.requests().pop().unwrap();
    assert!(req.path.contains("action=query"));
    assert_eq!(req_body_json(&req)["taskid"], "task_query_1");
}

#[tokio::test]
async fn fast_register_beta_weapp_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/wxa/component/fastregisterbetaweapp",
        &[r#"{"errcode":0,"errmsg":"ok","unique_id":"uuid_beta_1"}"#],
    )])
    .await;
    let _ = h
        .component
        .fast_register_beta_weapp("beta_name", "openid_beta")
        .await;
    let req = h.server.requests().pop().unwrap();
    assert!(req.path.contains("access_token=comp_tok_v1"));
    let body = req_body_json(&req);
    assert_eq!(body["name"], "beta_name");
    assert_eq!(body["openid"], "openid_beta");
}

// ═══════════════════════════════════════════════════════════════
// 5. register_shop / check_audit_status
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn register_shop_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/product/register/register_shop",
        &[r#"{"errcode":0,"errmsg":"ok"}"#],
    )])
    .await;
    let _ = h
        .component
        .register_shop(
            "wx_shop_name",
            "张三",
            "110101199001011234",
            Some("channel_1"),
            Some(1),
            Some("https://auth.example.com"),
        )
        .await;
    let req = h.server.requests().pop().unwrap();
    assert!(req.path.contains("component_access_token=comp_tok_v1"));
    let body = req_body_json(&req);
    assert_eq!(body["wx_name"], "wx_shop_name");
    assert_eq!(body["channel_id"], "channel_1");
    assert_eq!(body["auth_page_url"], "https://auth.example.com");
}

/// check_audit_status:返回 String,不走 bean 反序列化。
#[tokio::test]
async fn check_audit_status_posts() {
    let h = Harness::new(vec![MockRoute::post(
        "/product/register/check_audit_status",
        &[r#"{"errcode":0,"errmsg":"ok","audit_status":1}"#],
    )])
    .await;
    let result = h
        .component
        .check_audit_status("wx_shop_audit")
        .await
        .unwrap();
    assert!(result.contains("audit_status"));

    let req = h.server.requests().pop().unwrap();
    assert!(req.path.contains("access_token="));
    let body = req_body_json(&req);
    assert_eq!(body["wx_name"], "wx_shop_audit");
}

#[tokio::test]
async fn check_audit_status_with_appid_posts() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_check","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/product/register/check_audit_status",
            &[r#"{"errcode":0,"errmsg":"ok"}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_check");
    let result = h
        .component
        .check_audit_status_with_appid(AUTHORIZER_APPID, "wx_shop_audit2")
        .await
        .unwrap();
    assert!(result.contains("errcode"));

    let req = h.server.requests().pop().unwrap();
    assert!(req.path.contains("access_token=auth_tok_check"));
}

// ═══════════════════════════════════════════════════════════════
// 6. submit_merchant_info / submit_basic_info(请求体断言)
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn submit_merchant_info_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_merch","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/product/register/submit_merchantinfo",
            &[r#"{"errcode":0,"errmsg":"ok"}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_merch");
    let _ = h
        .component
        .submit_merchant_info(
            AUTHORIZER_APPID,
            "1",
            &wx_rust_open::bean::MinishopBusiLicense::default(),
            None,
            None,
            None,
            Some("shop_short"),
        )
        .await;
    let req = h.server.requests().pop().unwrap();
    assert!(req.path.contains("access_token=auth_tok_merch"));
    let body = req_body_json(&req);
    assert_eq!(body["subject_type"], "1");
    assert_eq!(body["merchant_shortname"], "shop_short");
}

#[tokio::test]
async fn submit_basic_info_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_basic","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/product/register/submit_basicinfo",
            &[r#"{"errcode":0,"errmsg":"ok"}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_basic");
    let name_info = wx_rust_open::bean::MinishopNameInfo {
        nick_name: "测试昵称".to_string(),
        abbr: "abbr".to_string(),
        introduction: "介绍".to_string(),
        naming_other_stuff: vec![],
    };
    let return_info = wx_rust_open::bean::MinishopReturnInfo::default();
    let _ = h
        .component
        .submit_basic_info(AUTHORIZER_APPID, &name_info, &return_info)
        .await;
    let req = h.server.requests().pop().unwrap();
    assert!(req.path.contains("access_token=auth_tok_basic"));
    let body = req_body_json(&req);
    assert_eq!(body["name_info"]["nickname"], "测试昵称");
}

// ═══════════════════════════════════════════════════════════════
// 7. get_minishop_brands / get_minishop_delivery_template
//    (手动解析 serde_json::Value,happy path 可达)
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn get_minishop_brands_parses() {
    let resp = r#"{"errcode":0,"errmsg":"ok","brands":[
      {"first_cat_id":1,"second_cat_id":2,"third_cat_id":3,
       "brand_info":{"brand_id":100,"brand_name":"品牌A"}}
    ]}"#;
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_brand","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/brand/get", &[resp]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_brand");
    let result = h
        .component
        .get_minishop_brands(AUTHORIZER_APPID)
        .await
        .unwrap();
    assert_eq!(result.errcode, 0);
    assert_eq!(result.brands.len(), 1);
    assert_eq!(result.brands[0].first_cat_id, 1);
    assert_eq!(result.brands[0].brand_info.brand_id, 100);
    assert_eq!(result.brands[0].brand_info.brand_name, "品牌A");
}

#[tokio::test]
async fn get_minishop_delivery_template_parses() {
    let resp = r#"{"errcode":0,"errmsg":"ok","template_list":[
      {"template_id":10,"name":"模板A","valuation_type":1},
      {"template_id":20,"name":"模板B","valuation_type":2}
    ]}"#;
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_tmpl","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/delivery/get_freight_template", &[resp]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_tmpl");
    let result = h
        .component
        .get_minishop_delivery_template(AUTHORIZER_APPID)
        .await
        .unwrap();
    assert_eq!(result.err_code, 0);
    assert_eq!(result.template_list.len(), 2);
    assert_eq!(result.template_list[0].template_id, 10);
    assert_eq!(
        result.template_list[0].valuation_type,
        wx_rust_open::bean::ValuationType::Weight
    );
    assert_eq!(
        result.template_list[1].valuation_type,
        wx_rust_open::bean::ValuationType::Package
    );
}

// ═══════════════════════════════════════════════════════════════
// 8. get_minishop_cat_list / get_minishop_delivery_company
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn get_minishop_cat_list_parses() {
    let resp = r#"{"errcode":0,"errmsg":"ok","shopcat_list":[
      {"shopcat_id":501,"shopcat_name":"服饰","f_shopcat_id":0,"cat_level":1}
    ]}"#;
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_cat","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/store/get_shopcat", &[resp]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_cat");
    let result = h
        .component
        .get_minishop_cat_list(AUTHORIZER_APPID)
        .await
        .unwrap();
    assert_eq!(result.errcode, 0);
    assert_eq!(result.shop_cat_list.len(), 1);
    assert_eq!(result.shop_cat_list[0].shop_cat_id, 501);
    assert_eq!(result.shop_cat_list[0].shop_cat_name, "服饰");
    assert_eq!(result.shop_cat_list[0].cat_level, 1);
}

#[tokio::test]
async fn get_minishop_delivery_company_parses() {
    let resp = r#"{"errcode":0,"errmsg":"ok","company_list":[{"id":1,"name":"顺丰"}]}"#;
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_deliv","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/delivery/get_company_list", &[resp]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_deliv");
    let result = h
        .component
        .get_minishop_delivery_company(AUTHORIZER_APPID)
        .await
        .unwrap();
    assert_eq!(result.errcode, 0);
    assert_eq!(result.data[0]["name"], "顺丰");
}

// ═══════════════════════════════════════════════════════════════
// 9. 优惠券操作(请求体断言 + error path)
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn minishop_push_coupon_to_user_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_push","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/coupon/push", &[r#"{"errcode":0,"errmsg":"ok"}"#]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_push");
    let _ = h
        .component
        .minishop_push_coupon_to_user(AUTHORIZER_APPID, "openid_push", 999)
        .await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["openid"], "openid_push");
    assert_eq!(body["coupon_id"], 999);
}

/// minishop_update_coupon:返回 i32,手动解析,happy path 可达。
#[tokio::test]
async fn minishop_update_coupon_posts() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_uc","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/product/coupon/update",
            &[r#"{"errcode":0,"errmsg":"ok","data":{"coupon_id":777}}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_uc");
    let coupon = make_test_coupon();
    let coupon_id = h
        .component
        .minishop_update_coupon(AUTHORIZER_APPID, &coupon)
        .await
        .unwrap();
    assert_eq!(coupon_id, 777);
}

#[tokio::test]
async fn minishop_update_coupon_status_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_ucs","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/product/coupon/update_status",
            &[r#"{"errcode":0,"errmsg":"ok"}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_ucs");
    let _ = h
        .component
        .minishop_update_coupon_status(AUTHORIZER_APPID, 555, 1)
        .await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["coupon_id"], 555);
    assert_eq!(body["status"], 1);
}

// ═══════════════════════════════════════════════════════════════
// 10. SPU 操作(返回 WxMinishopAddGoodsSpuResult errcode: i32)
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn minishop_goods_add_spu_posts() {
    let resp = r#"{"errcode":0,"errmsg":"ok","data":{"product_id":1001,"out_product_id":"out_1","create_time":1700000000}}"#;
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_spu","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/spu/add", &[resp]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_spu");
    let spu = make_test_spu();
    let result = h
        .component
        .minishop_goods_add_spu(AUTHORIZER_APPID, &spu)
        .await
        .unwrap();
    assert_eq!(result.errcode, 0);
    assert_eq!(result.data["product_id"], 1001);
    assert_eq!(result.data["create_time"], 1700000000);
}

/// minishop_goods_add_spu 错误路径:executor 对 errcode!=0 抛错。
#[tokio::test]
async fn minishop_goods_add_spu_error_path() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_spu_err","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/product/spu/add",
            &[r#"{"errcode":1001,"errmsg":"product already exists"}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_spu_err");
    let spu = make_test_spu();
    let err = h
        .component
        .minishop_goods_add_spu(AUTHORIZER_APPID, &spu)
        .await
        .unwrap_err();
    assert_error_code(&err, 1001);
}

#[tokio::test]
async fn minishop_goods_del_spu_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_dspu","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/spu/del", &[r#"{"errcode":0,"errmsg":"ok"}"#]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_dspu");
    let _ = h
        .component
        .minishop_goods_del_spu(AUTHORIZER_APPID, 1001, 1002)
        .await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["product_id"], 1001);
    assert_eq!(body["out_product_id"], "1002");
}

#[tokio::test]
async fn minishop_goods_update_spu_posts() {
    let resp = r#"{"errcode":0,"errmsg":"ok","data":{"product_id":1003,"update_time":1700000001}}"#;
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_uspu","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/spu/update", &[resp]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_uspu");
    let spu = make_test_spu();
    let result = h
        .component
        .minishop_goods_update_spu(AUTHORIZER_APPID, &spu)
        .await
        .unwrap();
    assert_eq!(result.errcode, 0);
    assert_eq!(result.data["product_id"], 1003);
    assert_eq!(result.data["update_time"], 1700000001);
}

#[tokio::test]
async fn minishop_goods_listing_spu_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_lspu","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/spu/listing", &[r#"{"errcode":0,"errmsg":"ok"}"#]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_lspu");
    let _ = h
        .component
        .minishop_goods_listing_spu(AUTHORIZER_APPID, 2001, 2002)
        .await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["product_id"], 2001);
}

#[tokio::test]
async fn minishop_goods_delisting_spu_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_dlspu","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/spu/delisting", &[r#"{"errcode":0,"errmsg":"ok"}"#]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_dlspu");
    let _ = h
        .component
        .minishop_goods_delisting_spu(AUTHORIZER_APPID, 3001, 3002)
        .await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["product_id"], 3001);
}

// ═══════════════════════════════════════════════════════════════
// 11. SKU 操作
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn minishop_goods_add_sku_posts() {
    let resp = r#"{"errcode":0,"errmsg":"ok","data":{"sku_id":5001,"create_time":1700000002}}"#;
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_asku","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/sku/add", &[resp]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_asku");
    let sku = make_test_sku();
    let result = h
        .component
        .minishop_goods_add_sku(AUTHORIZER_APPID, &sku)
        .await
        .unwrap();
    assert_eq!(result.errcode, 0);
    assert_eq!(result.data["sku_id"], 5001);
}

#[tokio::test]
async fn minishop_goods_batch_add_sku_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_bsku","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/sku/batch_add", &[r#"{"errcode":0,"errmsg":"ok"}"#]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_bsku");
    let skus = vec![make_test_sku(), make_test_sku()];
    let _ = h
        .component
        .minishop_goods_batch_add_sku(AUTHORIZER_APPID, &skus)
        .await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert!(body["skus"].as_array().unwrap().len() >= 2);
}

#[tokio::test]
async fn minishop_goods_del_sku_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_dsku","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/sku/del", &[r#"{"errcode":0,"errmsg":"ok"}"#]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_dsku");
    let _ = h
        .component
        .minishop_goods_del_sku(AUTHORIZER_APPID, 1001, 1002, "out_sku_1", 6001)
        .await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["product_id"], 1001);
    assert_eq!(body["sku_id"], 6001);
    assert_eq!(body["out_sku_id"], "out_sku_1");
}

#[tokio::test]
async fn minishop_goods_update_sku_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_usku","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/sku/update", &[r#"{"errcode":0,"errmsg":"ok"}"#]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_usku");
    let sku = make_test_sku();
    let _ = h
        .component
        .minishop_goods_update_sku(AUTHORIZER_APPID, &sku)
        .await;
    let req = h.server.requests().pop().unwrap();
    assert!(req.path.starts_with("/product/sku/update"));
    assert!(req.path.contains("access_token=auth_tok_usku"));
}

#[tokio::test]
async fn minishop_goods_update_sku_price_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_uskup","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/sku/update_price", &[r#"{"errcode":0,"errmsg":"ok"}"#]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_uskup");
    let _ = h
        .component
        .minishop_goods_update_sku_price(
            AUTHORIZER_APPID,
            1001,
            1002,
            "out_sku_2",
            7001,
            9900,
            19900,
        )
        .await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["sku_id"], 7001);
    // 镜像 Java 上游 bug:sale_price/market_price 均为 out_sku_id
    assert_eq!(body["sale_price"], "out_sku_2");
}

#[tokio::test]
async fn minishop_goods_update_sku_stock_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_uskus","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/stock/update", &[r#"{"errcode":0,"errmsg":"ok"}"#]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_uskus");
    let _ = h
        .component
        .minishop_goods_update_sku_stock(AUTHORIZER_APPID, 1001, 1002, "out_sku_3", 8001, 1, 500)
        .await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["type"], 1);
    assert_eq!(body["stock_num"], 500);
}

// ═══════════════════════════════════════════════════════════════
// 12. 限时折扣(手动解析,happy path 可达)
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn add_limit_discount_goods_posts() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_ld","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/product/limiteddiscount/add/",
            &[r#"{"errcode":0,"errmsg":"ok","task_id":42}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_ld");
    let goods = wx_rust_open::bean::LimitDiscountGoods {
        product_id: 1001,
        start_time: "1700000000".to_string(),
        end_time: "1700086400".to_string(),
        limit_discount_sku_list: vec![wx_rust_open::bean::LimitDiscountSku {
            sku_id: 5001,
            sale_price: "99.99".to_string(),
            sale_stock: 100,
        }],
        ..Default::default()
    };
    let task_id = h
        .component
        .add_limit_discount_goods(AUTHORIZER_APPID, &goods)
        .await
        .unwrap();
    assert_eq!(task_id, 42);

    let req = h.server.requests().pop().unwrap();
    assert!(req.path.starts_with("/product/limiteddiscount/add/"));
    assert!(req.path.contains("access_token=auth_tok_ld"));
}

#[tokio::test]
async fn get_limit_discount_list_parses() {
    let resp = r#"{"errcode":0,"errmsg":"ok","limited_discount_list":[
      {"task_id":1,"status":1,"start_time":1700000,"end_time":1700086,
       "limited_discount_sku_list":[{"sku_id":5001,"sale_price":9999,"sale_stock":50}]}
    ]}"#;
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_gld","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post("/product/limiteddiscount/get_list/", &[resp]),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_gld");
    let list = h
        .component
        .get_limit_discount_list(AUTHORIZER_APPID, Some(1))
        .await
        .unwrap();
    assert_eq!(list.len(), 1);
    assert_eq!(list[0].task_id, 1);
    assert_eq!(list[0].limit_discount_sku_list.len(), 1);

    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["status"], 1);
}

#[tokio::test]
async fn get_limit_discount_list_empty() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_gld_e","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/product/limiteddiscount/get_list/",
            &[r#"{"errcode":0,"errmsg":"ok","limited_discount_list":[]}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_gld_e");
    let list = h
        .component
        .get_limit_discount_list(AUTHORIZER_APPID, None)
        .await
        .unwrap();
    assert!(list.is_empty());
}

#[tokio::test]
async fn update_limit_discount_status_exercises_request_body() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_ulds","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/product/limiteddiscount/update_status/",
            &[r#"{"errcode":0,"errmsg":"ok"}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_ulds");
    let _ = h
        .component
        .update_limit_discount_status(AUTHORIZER_APPID, 100, 2)
        .await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["task_id"], 100);
    assert_eq!(body["status"], 2);
}

// ═══════════════════════════════════════════════════════════════
// 13. TCB(云开发)
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn get_share_cloud_base_env_posts() {
    let h = Harness::new(vec![MockRoute::post(
        "/componenttcb/batchgetenvid",
        &[r#"{"relation_data":[{"appid":"wx_app_1","env_list":["env_1"]}],"err_list":[]}"#],
    )])
    .await;
    let result = h
        .component
        .get_share_cloud_base_env(&["wx_app_1".to_string()])
        .await
        .unwrap();
    assert_eq!(result.relation_data.len(), 1);
    assert_eq!(result.relation_data[0].appid, "wx_app_1");
}

#[tokio::test]
async fn get_tcb_env_list_posts() {
    let h = Harness::new(vec![MockRoute::post(
        "/componenttcb/describeenvs",
        &[r#"{"info_list":[{"env":"env_desc_1","alias":"test","status":"normal"}]}"#],
    )])
    .await;
    let result = h.component.get_tcb_env_list().await.unwrap();
    assert_eq!(result.info_list.len(), 1);
    assert_eq!(result.info_list[0].env, "env_desc_1");
}

#[tokio::test]
async fn change_tcb_env_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/tcb/modifyenv",
        &[r#"{"errcode":0,"errmsg":"ok"}"#],
    )])
    .await;
    let _ = h.component.change_tcb_env("env_change_1").await;
    let req = h.server.requests().pop().unwrap();
    assert_eq!(req_body_json(&req)["env"], "env_change_1");
}

/// share_cloud_base_env:executor 需要 integer errcode,bean 需要 String。
/// 测试请求体断言。
#[tokio::test]
async fn share_cloud_base_env_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/componenttcb/batchshareenv",
        &[r#"{"errcode":0,"errmsg":"ok","err_list":[]}"#],
    )])
    .await;
    let request = wx_rust_open::bean::ShareCloudBaseEnvRequest {
        data: vec![wx_rust_open::bean::DataDTO {
            env: "env_share_1".to_string(),
            appids: vec!["wx_share_1".to_string()],
        }],
        source_type: 1,
    };
    let _ = h.component.share_cloud_base_env(&request).await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["data"][0]["env"], "env_share_1");
}

// ═══════════════════════════════════════════════════════════════
// 14. clear_quota_v2
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn clear_quota_v2_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/cgi-bin/component/clear_quota/v2",
        &[r#"{"errcode":0,"errmsg":"ok"}"#],
    )])
    .await;
    let _ = h.component.clear_quota_v2("wx_clear_01").await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["appid"], "wx_clear_01");
    assert_eq!(body["component_appid"], "component_appid_01");
}

// ═══════════════════════════════════════════════════════════════
// 15. apply_set_order_path_info
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn apply_set_order_path_info_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/wxa/security/applysetorderpathinfo",
        &[r#"{"errcode":0,"errmsg":"ok"}"#],
    )])
    .await;
    let info = wx_rust_open::bean::WxOpenMaApplyOrderPathInfo {
        batch_req: wx_rust_open::bean::BatchReqBean {
            path: "/pages/order/list".to_string(),
            app_id_list: vec!["wx_order_app".to_string()],
            ..Default::default()
        },
    };
    let _ = h.component.apply_set_order_path_info(&info).await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["batch_req"]["path"], "/pages/order/list");
}

// ═══════════════════════════════════════════════════════════════
// 16. 域名管理
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn modify_wxa_server_domain_add_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/cgi-bin/component/modify_wxa_server_domain",
        &[r#"{"errcode":0,"errmsg":"ok"}"#],
    )])
    .await;
    let _ = h
        .component
        .modify_wxa_server_domain(
            "add",
            &["https://a.example.com".to_string()],
            &["wss://b.example.com".to_string()],
            &["https://c.example.com".to_string()],
            &["https://d.example.com".to_string()],
            &[],
            &[],
        )
        .await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["action"], "add");
    assert_eq!(body["requestdomain"][0], "https://a.example.com");
}

#[tokio::test]
async fn modify_wxa_server_domain_get_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/cgi-bin/component/modify_wxa_server_domain",
        &[r#"{"errcode":0,"errmsg":"ok","requestdomain":["https://e.example.com"]}"#],
    )])
    .await;
    let _ = h
        .component
        .modify_wxa_server_domain("get", &[], &[], &[], &[], &[], &[])
        .await;
    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["action"], "get");
    assert!(body.get("requestdomain").is_none());
}

/// get_domain_confirm_file:executor 需要 integer errcode,bean 需要 String errcode。
/// 测试请求体断言 + 忽略反序列化结果。
#[tokio::test]
async fn get_domain_confirm_file_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/cgi-bin/component/get_domain_confirmfile",
        &[r#"{"errcode":0,"errmsg":"ok","file_name":"verify.txt","file_content":"abc123"}"#],
    )])
    .await;
    let _ = h.component.get_domain_confirm_file().await;
    // 请求已发出(覆盖 URL 构建 + post 调用链)
    assert_eq!(
        h.server
            .call_count("/cgi-bin/component/get_domain_confirmfile"),
        1
    );
}

/// modify_wxa_jump_domain:返回 String,happy path 可达。
#[tokio::test]
async fn modify_wxa_jump_domain_add_posts() {
    let h = Harness::new(vec![MockRoute::post(
        "/cgi-bin/component/modify_wxa_jump_domain",
        &[r#"{"errcode":0,"errmsg":"ok"}"#],
    )])
    .await;
    let result = h
        .component
        .modify_wxa_jump_domain("add", &["https://biz.example.com".to_string()])
        .await
        .unwrap();
    assert!(result.contains("errcode"));

    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["action"], "add");
    assert_eq!(body["webviewdomain"][0], "https://biz.example.com");
}

#[tokio::test]
async fn modify_wxa_jump_domain_get_posts() {
    let h = Harness::new(vec![MockRoute::post(
        "/cgi-bin/component/modify_wxa_jump_domain",
        &[r#"{"errcode":0,"errmsg":"ok","webviewdomain":["https://x.com"]}"#],
    )])
    .await;
    let result = h
        .component
        .modify_wxa_jump_domain("get", &[])
        .await
        .unwrap();
    assert!(result.contains("webviewdomain"));

    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["action"], "get");
    assert!(body.get("webviewdomain").is_none());
}

/// modify_wxa_jump_domain_info:executor 需要 integer errcode,bean 需要 String。
/// 测试请求体断言。
#[tokio::test]
async fn modify_wxa_jump_domain_info_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::post(
        "/cgi-bin/component/modify_wxa_jump_domain",
        &[r#"{"errcode":0,"errmsg":"ok","webviewdomain":["https://y.com"]}"#],
    )])
    .await;
    let _ = h.component.modify_wxa_jump_domain_info("get", &[]).await;
    assert_eq!(
        h.server
            .call_count("/cgi-bin/component/modify_wxa_jump_domain"),
        1
    );
}

// ═══════════════════════════════════════════════════════════════
// 17. get_authorizer_option / set_authorizer_option
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn get_authorizer_option_posts() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_opt","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/cgi-bin/component/get_authorizer_option",
            &[r#"{"authorizer_appid":"wx_opt","option_name":"opt_n","option_value":"option_val_1"}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_opt");
    let result = h
        .component
        .get_authorizer_option(AUTHORIZER_APPID, "option_name_1")
        .await
        .unwrap();
    assert_eq!(result.option_value.as_deref(), Some("option_val_1"));

    let req = h.server.requests().pop().unwrap();
    assert!(req.path.contains("access_token=auth_tok_opt"));
    let body = req_body_json(&req);
    assert_eq!(body["option_name"], "option_name_1");
}

#[tokio::test]
async fn set_authorizer_option_posts() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_setopt","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/cgi-bin/component/set_authorizer_option",
            &[r#"{"errcode":0,"errmsg":"ok"}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_setopt");
    h.component
        .set_authorizer_option(AUTHORIZER_APPID, "opt_name", "opt_val")
        .await
        .unwrap();

    let req = h.server.requests().pop().unwrap();
    let body = req_body_json(&req);
    assert_eq!(body["option_name"], "opt_name");
    assert_eq!(body["option_value"], "opt_val");
}

// ═══════════════════════════════════════════════════════════════
// 18. have_open
// ═══════════════════════════════════════════════════════════════

/// have_open:executor 需要 integer errcode,bean 需要 String errcode。
/// 测试请求体断言。
#[tokio::test]
async fn have_open_exercises_request_body() {
    let h = Harness::new(vec![MockRoute::get(
        "/cgi-bin/open/have",
        &[r#"{"errcode":0,"errmsg":"ok","have_open":true}"#],
    )])
    .await;
    let _ = h.component.have_open().await;
    assert_eq!(h.server.call_count("/cgi-bin/open/have"), 1);
}

// ═══════════════════════════════════════════════════════════════
// 19. get_component_access_token
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn get_component_access_token_direct() {
    let h = Harness::new(vec![]).await;
    let token = h.component.get_component_access_token(false).await.unwrap();
    assert_eq!(token, "comp_tok_v1");

    let token2 = h.component.get_component_access_token(true).await.unwrap();
    assert_eq!(token2, "comp_tok_v1");
    assert_eq!(
        h.server
            .call_count("/cgi-bin/component/api_component_token"),
        2
    );
}

// ═══════════════════════════════════════════════════════════════
// 20. route: updateauthorized 事件
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn route_updateauthorized_dispatches() {
    use wx_rust_open::bean::message::WxOpenXmlMessage;

    let resp = r#"{"authorization_info":{
      "authorizer_appid":"wx_update_auth_01",
      "authorizer_access_token":"auth_tok_update",
      "expires_in":7200,
      "authorizer_refresh_token":"refresh_tok_update",
      "func_info":[]
    }}"#;
    let h = Harness::new(vec![MockRoute::post(
        "/cgi-bin/component/api_query_auth",
        &[resp],
    )])
    .await;
    let message = WxOpenXmlMessage {
        info_type: Some("updateauthorized".to_string()),
        authorization_code: Some("queryauthcode@@@UPDATE01".to_string()),
        ..Default::default()
    };
    let ret = h.component.route(&message).await.unwrap();
    assert_eq!(ret, "success");
    assert_eq!(
        h.config
            .authorizer_access_token("wx_update_auth_01")
            .as_deref(),
        Some("auth_tok_update")
    );
}

// ═══════════════════════════════════════════════════════════════
// 21. 错误路径覆盖
// ═══════════════════════════════════════════════════════════════

#[tokio::test]
async fn get_minishop_categories_error_path() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_cat_err","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/product/category/get",
            &[r#"{"errcode":40001,"errmsg":"invalid access_token"}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_cat_err");
    let err = h
        .component
        .get_minishop_categories(AUTHORIZER_APPID, 0)
        .await
        .unwrap_err();
    assert_error_code(&err, 40001);
}

#[tokio::test]
async fn get_minishop_delivery_template_error_path() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_dterr","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/product/delivery/get_freight_template",
            &[r#"{"errcode":40001,"errmsg":"invalid"}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_dterr");
    let err = h
        .component
        .get_minishop_delivery_template(AUTHORIZER_APPID)
        .await
        .unwrap_err();
    assert_error_code(&err, 40001);
}

#[tokio::test]
async fn minishop_create_coupon_error_path() {
    let h = Harness::new(vec![
        MockRoute::post(
            "/cgi-bin/component/api_authorizer_token",
            &[r#"{"authorizer_access_token":"auth_tok_cc_err","authorizer_refresh_token":"r","expires_in":7200}"#],
        ),
        MockRoute::post(
            "/product/coupon/create",
            &[r#"{"errcode":1001,"errmsg":"coupon limit exceeded"}"#],
        ),
    ])
    .await;
    h.config
        .set_authorizer_refresh_token(AUTHORIZER_APPID, "refresh_tok_cc_err");
    let coupon = make_test_coupon();
    let err = h
        .component
        .minishop_create_coupon(AUTHORIZER_APPID, &coupon)
        .await
        .unwrap_err();
    assert_error_code(&err, 1001);
}

// ═══════════════════════════════════════════════════════════════
// 辅助构造函数
// ═══════════════════════════════════════════════════════════════

fn make_test_coupon() -> wx_rust_open::bean::WxMinishopCoupon {
    wx_rust_open::bean::WxMinishopCoupon {
        coupon_id: -1,
        status: -1,
        r#type: 1,
        name: "测试券".to_string(),
        discount_info: wx_rust_open::bean::WxMinishopCouponDiscountInfo {
            discount_fee: 10,
            discount_num: 1,
            discount_condition: wx_rust_open::bean::WxMinishopCouponDiscountCondition {
                product_cnt: 1,
                product_ids: vec![1, 2],
                product_price: 100,
            },
        },
        ext_info: wx_rust_open::bean::WxMinishopCouponExtInfo {
            notes: "note".to_string(),
            valid_time: 0,
            invalid_time: 0,
            jump_product_id: 0,
        },
        promote_info: wx_rust_open::bean::WxMinishopCouponPromoteInfo {
            customize_channel: String::new(),
            promotion_type: 0,
        },
        receive_info: wx_rust_open::bean::WxMinishopCouponReceiveInfo {
            end_time: 0,
            limit_num_one_person: 1,
            start_time: 0,
            total_num: 100,
        },
        valid_info: wx_rust_open::bean::WxMinishopCouponValidInfo {
            end_time: 0,
            start_time: 0,
            valid_day_num: 30,
            valid_type: 1,
        },
    }
}

fn make_test_spu() -> wx_rust_open::bean::WxMinishopSpu {
    wx_rust_open::bean::WxMinishopSpu {
        out_product_id: "out_prod_1".to_string(),
        title: "测试商品".to_string(),
        sub_title: "副标题".to_string(),
        head_imgs: vec!["https://img.example.com/1.jpg".to_string()],
        desc_info_imgs: vec!["https://img.example.com/desc.jpg".to_string()],
        brand_id: 0,
        shop_cats: vec![],
        attrs: vec![],
        model: "model_1".to_string(),
        express_template_id: 0,
        skus: vec![make_test_sku()],
    }
}

fn make_test_sku() -> wx_rust_open::bean::WxMinishopSku {
    wx_rust_open::bean::WxMinishopSku {
        product_id: 0,
        out_product_id: "out_prod_1".to_string(),
        out_sku_id: "out_sku_1".to_string(),
        thumb_img: "https://img.example.com/thumb.jpg".to_string(),
        sale_price: 9999,
        market_price: 19999,
        stock_num: 100,
        sku_code: "SKU001".to_string(),
        bar_code: "BAR001".to_string(),
        sku_attrs: vec![wx_rust_open::bean::WxMinishopGoodsSkuAttr {
            attr_key: "颜色".to_string(),
            attr_value: "红色".to_string(),
        }],
    }
}