crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with 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
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
1729
1730
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

use super::*;
use std::collections::HashMap;

#[test]
fn test_scrape_request_builder() {
    let request = ScrapeRequest::new("https://example.com")
        .needs_js()
        .needs_screenshot()
        .mobile()
        .timeout(Duration::from_secs(60));

    assert_eq!(request.url, "https://example.com");
    assert!(request.options.needs_js);
    assert!(request.options.needs_screenshot);
    assert!(request.options.mobile);
    assert_eq!(request.options.timeout, Duration::from_secs(60));
}

#[test]
fn test_scrape_options_builder() {
    let options = ScrapeOptions::builder()
        .needs_js(true)
        .needs_screenshot(true)
        .mobile(true)
        .timeout(Duration::from_secs(45))
        .proxy("http://proxy.example.com:8080")
        .build();

    assert!(options.needs_js);
    assert!(options.needs_screenshot);
    assert!(options.mobile);
    assert_eq!(options.timeout, Duration::from_secs(45));
    assert_eq!(
        options.proxy,
        Some("http://proxy.example.com:8080".to_string())
    );
}

#[test]
fn test_scrape_response_success() {
    let response = ScrapeResponse::new(200, "Hello World", "text/html");

    assert_eq!(response.status_code, 200);
    assert_eq!(response.content, "Hello World");
    assert_eq!(response.content_type, "text/html");
    assert!(response.is_success());
}

#[test]
fn test_engine_error_retryable() {
    assert!(EngineError::RequestFailed("connection refused".to_string()).is_retryable());
    assert!(EngineError::Timeout(Duration::from_secs(30)).is_retryable());
    assert!(!EngineError::InvalidUrl("invalid".to_string()).is_retryable());
    assert!(!EngineError::SsrfProtection("blocked".to_string()).is_retryable());
}

// ScrapeRequest tests

#[test]
fn test_scrape_request_new_default_options() {
    let request = ScrapeRequest::new("https://example.com");
    assert_eq!(request.url, "https://example.com");
    assert!(!request.options.needs_js);
    assert!(!request.options.needs_screenshot);
    assert!(!request.options.mobile);
    assert_eq!(request.options.timeout, Duration::from_secs(30));
    assert_eq!(request.options.method, HttpMethod::Get);
}

#[test]
fn test_scrape_request_with_options() {
    let options = ScrapeOptions::builder()
        .needs_js(true)
        .timeout(Duration::from_secs(120))
        .build();
    let request = ScrapeRequest::new("https://example.com").with_options(options);

    assert!(request.options.needs_js);
    assert_eq!(request.options.timeout, Duration::from_secs(120));
}

#[test]
fn test_scrape_request_chained_builders() {
    let request = ScrapeRequest::new("https://example.com")
        .needs_js()
        .needs_screenshot()
        .mobile()
        .timeout(Duration::from_secs(90));

    assert!(request.options.needs_js);
    assert!(request.options.needs_screenshot);
    assert!(request.options.mobile);
    assert_eq!(request.options.timeout, Duration::from_secs(90));
}

// ScrapeOptions tests

#[test]
fn test_scrape_options_default() {
    let options = ScrapeOptions::default();
    assert_eq!(options.method, HttpMethod::Get);
    assert!(!options.needs_js);
    assert!(!options.needs_screenshot);
    assert!(!options.mobile);
    assert_eq!(options.timeout, Duration::from_secs(30));
    assert!(options.body.is_none());
    assert_eq!(options.sync_wait_ms, 0);
    assert!(options.actions.is_empty());
    assert!(options.screenshot_config.is_none());
    assert!(options.proxy.is_none());
    assert!(!options.skip_tls_verification);
    assert!(options.headers.is_empty());
    assert!(!options.needs_tls_fingerprint);
    assert!(!options.use_fire_engine);
}

#[test]
fn test_scrape_options_builder_all_fields() {
    let mut headers = HashMap::new();
    headers.insert("X-Custom".to_string(), "value".to_string());

    let options = ScrapeOptions::builder()
        .method(HttpMethod::Post)
        .needs_js(true)
        .needs_screenshot(true)
        .mobile(true)
        .timeout(Duration::from_secs(60))
        .body("payload")
        .sync_wait_ms(500)
        .proxy("http://proxy:8080")
        .headers(headers.clone())
        .needs_tls_fingerprint(true)
        .use_fire_engine(true)
        .screenshot_config(ScreenshotConfig::default())
        .build();

    assert_eq!(options.method, HttpMethod::Post);
    assert!(options.needs_js);
    assert!(options.needs_screenshot);
    assert!(options.mobile);
    assert_eq!(options.timeout, Duration::from_secs(60));
    assert_eq!(options.body, Some("payload".to_string()));
    assert_eq!(options.sync_wait_ms, 500);
    assert_eq!(options.proxy, Some("http://proxy:8080".to_string()));
    assert_eq!(options.headers, headers);
    assert!(options.needs_tls_fingerprint);
    assert!(options.use_fire_engine);
    assert!(options.screenshot_config.is_some());
}

#[test]
fn test_scrape_options_builder_skip_tls_false() {
    // skip=false should not read env vars and just set the field
    let options = ScrapeOptions::builder()
        .skip_tls_verification(false)
        .build();
    assert!(!options.skip_tls_verification);
}

// HttpMethod tests

#[test]
fn test_http_method_default() {
    assert_eq!(HttpMethod::default(), HttpMethod::Get);
}

#[test]
fn test_http_method_equality() {
    assert_eq!(HttpMethod::Get, HttpMethod::Get);
    assert_eq!(HttpMethod::Post, HttpMethod::Post);
    assert_ne!(HttpMethod::Get, HttpMethod::Post);
}

// ScrollDirection tests

#[test]
fn test_scroll_direction_default() {
    assert_eq!(ScrollDirection::default(), ScrollDirection::Down);
}

#[test]
fn test_scroll_direction_equality() {
    assert_eq!(ScrollDirection::Down, ScrollDirection::Down);
    assert_eq!(ScrollDirection::Up, ScrollDirection::Up);
    assert_eq!(ScrollDirection::Bottom, ScrollDirection::Bottom);
    assert_eq!(ScrollDirection::Top, ScrollDirection::Top);
    assert_ne!(ScrollDirection::Down, ScrollDirection::Up);
    assert_ne!(ScrollDirection::Bottom, ScrollDirection::Top);
}

// ScreenshotConfig tests

#[test]
fn test_screenshot_config_default() {
    let config = ScreenshotConfig::default();
    assert!(config.full_page);
    assert!(config.selector.is_none());
    assert_eq!(config.quality, Some(80));
    assert_eq!(config.format, Some("jpeg".to_string()));
}

#[test]
fn test_screenshot_config_equality() {
    let c1 = ScreenshotConfig::default();
    let c2 = ScreenshotConfig::default();
    assert_eq!(c1, c2);

    let c3 = ScreenshotConfig {
        full_page: false,
        selector: None,
        quality: Some(90),
        format: Some("png".to_string()),
    };
    assert_ne!(c1, c3);
}

// ScrapeResponse tests

#[test]
fn test_scrape_response_new() {
    let response = ScrapeResponse::new(200, "content", "application/json");
    assert_eq!(response.status_code, 200);
    assert_eq!(response.content, "content");
    assert_eq!(response.content_type, "application/json");
    assert!(response.screenshot.is_none());
    assert!(response.headers.is_empty());
    assert_eq!(response.response_time_ms, 0);
    assert!(response.final_url.is_none());
}

#[test]
fn test_scrape_response_is_success_2xx() {
    assert!(ScrapeResponse::new(200, "", "").is_success());
    assert!(ScrapeResponse::new(201, "", "").is_success());
    assert!(ScrapeResponse::new(204, "", "").is_success());
    assert!(ScrapeResponse::new(299, "", "").is_success());
}

#[test]
fn test_scrape_response_is_success_non_2xx() {
    assert!(!ScrapeResponse::new(199, "", "").is_success());
    assert!(!ScrapeResponse::new(300, "", "").is_success());
    assert!(!ScrapeResponse::new(404, "", "").is_success());
    assert!(!ScrapeResponse::new(500, "", "").is_success());
}

// to_internal conversion tests

#[test]
fn test_to_internal_basic_fields() {
    let request = ScrapeRequest::new("https://example.com");
    let internal = request.to_internal().unwrap();

    assert_eq!(internal.url, "https://example.com");
    assert_eq!(internal.method, HttpMethod::Get);
    assert!(!internal.needs_js);
    assert!(!internal.needs_screenshot);
    assert!(!internal.mobile);
    assert_eq!(internal.timeout, Duration::from_secs(30));
    assert!(internal.body.is_none());
    assert_eq!(internal.sync_wait_ms, 0);
    assert!(internal.proxy.is_none());
    assert!(!internal.skip_tls_verification);
    assert!(!internal.needs_tls_fingerprint);
    assert!(!internal.use_fire_engine);
    assert!(internal.actions.is_empty());
    assert!(internal.screenshot_config.is_none());
    assert!(internal.headers.is_empty());
}

#[test]
fn test_to_internal_all_fields() {
    let mut headers = HashMap::new();
    headers.insert("X-Test".to_string(), "val".to_string());

    let request = ScrapeRequest::new("https://example.com").with_options(
        ScrapeOptions::builder()
            .method(HttpMethod::Post)
            .needs_js(true)
            .needs_screenshot(true)
            .mobile(true)
            .timeout(Duration::from_secs(60))
            .body("data")
            .sync_wait_ms(1000)
            .proxy("http://proxy:8080")
            .headers(headers.clone())
            .needs_tls_fingerprint(true)
            .use_fire_engine(true)
            .screenshot_config(ScreenshotConfig {
                full_page: false,
                selector: Some("#main".to_string()),
                quality: Some(90),
                format: Some("png".to_string()),
            })
            .build(),
    );

    let internal = request.to_internal().unwrap();
    assert_eq!(internal.url, "https://example.com");
    assert_eq!(internal.method, HttpMethod::Post);
    assert!(internal.needs_js);
    assert!(internal.needs_screenshot);
    assert!(internal.mobile);
    assert_eq!(internal.timeout, Duration::from_secs(60));
    assert_eq!(internal.body, Some("data".to_string()));
    assert_eq!(internal.sync_wait_ms, 1000);
    assert_eq!(internal.proxy, Some("http://proxy:8080".to_string()));
    assert_eq!(internal.headers, headers);
    assert!(internal.needs_tls_fingerprint);
    assert!(internal.use_fire_engine);
    assert!(internal.screenshot_config.is_some());
    let sc = internal.screenshot_config.unwrap();
    assert!(!sc.full_page);
    assert_eq!(sc.selector, Some("#main".to_string()));
    assert_eq!(sc.quality, Some(90));
    assert_eq!(sc.format, Some("png".to_string()));
}

#[test]
fn test_to_internal_page_actions() {
    let options = ScrapeOptions::builder().body("").build();
    // Manually add actions since there's no builder method for actions
    let mut options = options;
    options.actions = vec![
        PageAction::Wait { milliseconds: 500 },
        PageAction::Click {
            selector: "#button".to_string(),
        },
        PageAction::Scroll {
            direction: ScrollDirection::Down,
        },
        PageAction::Scroll {
            direction: ScrollDirection::Up,
        },
        PageAction::Scroll {
            direction: ScrollDirection::Bottom,
        },
        PageAction::Scroll {
            direction: ScrollDirection::Top,
        },
        PageAction::Input {
            selector: "#field".to_string(),
            text: "hello".to_string(),
        },
    ];

    let request = ScrapeRequest::new("https://example.com").with_options(options);
    let internal = request.to_internal().unwrap();

    assert_eq!(internal.actions.len(), 7);
    // Verify Wait action
    match &internal.actions[0] {
        InternalPageAction::Wait { milliseconds } => assert_eq!(*milliseconds, 500),
        other => panic!("Expected Wait, got {:?}", other),
    }
    // Verify Click action
    match &internal.actions[1] {
        InternalPageAction::Click { selector } => assert_eq!(selector, "#button"),
        other => panic!("Expected Click, got {:?}", other),
    }
    // Verify Scroll directions
    match &internal.actions[2] {
        InternalPageAction::Scroll { direction } => assert_eq!(direction, "down"),
        other => panic!("Expected Scroll down, got {:?}", other),
    }
    match &internal.actions[3] {
        InternalPageAction::Scroll { direction } => assert_eq!(direction, "up"),
        other => panic!("Expected Scroll up, got {:?}", other),
    }
    match &internal.actions[4] {
        InternalPageAction::Scroll { direction } => assert_eq!(direction, "bottom"),
        other => panic!("Expected Scroll bottom, got {:?}", other),
    }
    match &internal.actions[5] {
        InternalPageAction::Scroll { direction } => assert_eq!(direction, "top"),
        other => panic!("Expected Scroll top, got {:?}", other),
    }
    // Verify Input action
    match &internal.actions[6] {
        InternalPageAction::Input { selector, text } => {
            assert_eq!(selector, "#field");
            assert_eq!(text, "hello");
        }
        other => panic!("Expected Input, got {:?}", other),
    }
}

// InternalScrapeResponse::to_public tests

#[test]
fn test_to_internal_rejects_invalid_response_url_regex() {
    // 桥接层前置校验:非法 regex(未闭合分组)拒绝,请求不进入引擎
    let request = crate::engines::engine_client::ScrapeRequest::new("https://example.com")
        .with_options(
            crate::engines::engine_client::ScrapeOptions::builder()
                .wait_for(WaitFor::ResponseUrl("(".to_string()))
                .build(),
        );
    let result = request.to_internal();
    assert!(result.is_err(), "非法 regex 必须在桥接层报错");
    let err = result.unwrap_err();
    assert!(
        matches!(err, crate::engines::engine_client::EngineError::InvalidUrl(ref m) if m.contains("regex invalid")),
        "错误应为 InvalidUrl 且文案含 regex invalid,实际: {err:?}"
    );
}

#[test]
fn test_to_internal_passes_valid_response_variants() {
    // 合法 regex 与子串变体透传至引擎层
    let request = crate::engines::engine_client::ScrapeRequest::new("https://example.com")
        .with_options(
            crate::engines::engine_client::ScrapeOptions::builder()
                .wait_for(WaitFor::ResponseUrl(r"api/v\d+".to_string()))
                .build(),
        );
    let internal = request.to_internal().unwrap();
    assert_eq!(
        internal.wait_for,
        Some(WaitFor::ResponseUrl(r"api/v\d+".to_string()))
    );

    let request = crate::engines::engine_client::ScrapeRequest::new("https://example.com")
        .with_options(
            crate::engines::engine_client::ScrapeOptions::builder()
                .wait_for(WaitFor::ResponseBody("token".to_string()))
                .build(),
        );
    let internal = request.to_internal().unwrap();
    assert_eq!(
        internal.wait_for,
        Some(WaitFor::ResponseBody("token".to_string()))
    );
}

#[test]
fn test_to_internal_existing_variants_unchanged() {
    // 既有三变体桥接行为不变
    let base = crate::engines::engine_client::ScrapeRequest::new("https://example.com");
    assert_eq!(
        base.clone()
            .with_options(
                crate::engines::engine_client::ScrapeOptions::builder()
                    .wait_for(WaitFor::NetworkIdle)
                    .build(),
            )
            .to_internal()
            .unwrap()
            .wait_for,
        Some(WaitFor::NetworkIdle)
    );
    assert_eq!(
        base.with_options(
            crate::engines::engine_client::ScrapeOptions::builder()
                .wait_for(WaitFor::Selector("#x".to_string()))
                .build(),
        )
        .to_internal()
        .unwrap()
        .wait_for,
        Some(WaitFor::Selector("#x".to_string()))
    );
}

#[test]
fn test_internal_response_to_public() {
    let internal = InternalScrapeResponse {
        js_degraded: false,
        captured_responses: Vec::new(),
        status_code: 200,
        content: "body".to_string(),
        screenshot: Some("base64data".to_string()),
        content_type: "text/html".to_string(),
        headers: {
            let mut h = HashMap::new();
            h.insert("Server".to_string(), "nginx".to_string());
            h
        },
        response_time_ms: 42,
        final_url: None,
    };

    let public = internal.to_public("https://example.com/page");
    assert_eq!(public.status_code, 200);
    assert_eq!(public.content, "body");
    assert_eq!(public.screenshot, Some("base64data".to_string()));
    assert_eq!(public.content_type, "text/html");
    assert_eq!(public.headers.len(), 1);
    assert_eq!(public.headers.get("Server"), Some(&"nginx".to_string()));
    assert_eq!(public.response_time_ms, 42);
    assert!(public.final_url.is_none());
}

#[test]
fn test_internal_response_to_public_captures_passthrough() {
    // F6:捕获结果经 to_public 透传到公共响应
    let internal = InternalScrapeResponse {
        js_degraded: false,
        captured_responses: vec![InternalCapturedResponse {
            url: "https://example.com/api/data".to_string(),
            status: 200,
            mime_type: "application/json".to_string(),
            body: "{\"ok\":true}".to_string(),
        }],
        status_code: 200,
        content: "body".to_string(),
        screenshot: None,
        content_type: "text/html".to_string(),
        headers: HashMap::new(),
        response_time_ms: 42,
        final_url: None,
    };

    let public = internal.to_public("https://example.com/");
    assert_eq!(public.captured_responses.len(), 1);
    assert_eq!(
        public.captured_responses[0].url,
        "https://example.com/api/data"
    );
    assert_eq!(public.captured_responses[0].status, 200);
    assert_eq!(public.captured_responses[0].mime_type, "application/json");
    assert_eq!(public.captured_responses[0].body, "{\"ok\":true}");
}

#[test]
fn test_internal_response_default_captures_empty() {
    // 其余引擎(Default 构造)捕获为空,to_public 透传空 Vec
    let public = InternalScrapeResponse::default().to_public("https://example.com/");
    assert!(public.captured_responses.is_empty());
}

#[test]
fn test_scrape_response_captures_serde() {
    // F6:空 Vec 不出现在 JSON(skip_serializing_if),旧 JSON(无字段)可反序列化
    let response = ScrapeResponse::new(200, "x", "text/html");
    let json = serde_json::to_string(&response).unwrap();
    assert!(
        !json.contains("captured_responses"),
        "empty captures must be absent from JSON, got: {json}"
    );
    let restored: ScrapeResponse = serde_json::from_str(&json).unwrap();
    assert!(restored.captured_responses.is_empty());

    // 非空时字段完整
    let mut with_capture = ScrapeResponse::new(200, "x", "text/html");
    with_capture.captured_responses = vec![CapturedResponse {
        url: "https://example.com/api/data".to_string(),
        status: 200,
        mime_type: "application/json".to_string(),
        body: "{\"ok\":true}".to_string(),
    }];
    let json2 = serde_json::to_string(&with_capture).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json2).unwrap();
    let captures = parsed["captured_responses"].as_array().unwrap();
    assert_eq!(captures.len(), 1);
    assert_eq!(captures[0]["url"], "https://example.com/api/data");
    assert_eq!(captures[0]["status"], 200);
    assert_eq!(captures[0]["mime_type"], "application/json");
    assert_eq!(captures[0]["body"], "{\"ok\":true}");
}

// EngineError tests

#[test]
fn test_engine_error_all_retryable_variants() {
    assert!(EngineError::RequestFailed("err".to_string()).is_retryable());
    assert!(EngineError::Timeout(Duration::from_secs(10)).is_retryable());
    assert!(EngineError::BrowserError("crash".to_string()).is_retryable());
    assert!(EngineError::AntiBotDetected("Cloudflare challenge".to_string()).is_retryable());
    assert!(!EngineError::NoEnginesAvailable.is_retryable());
    assert!(!EngineError::InvalidUrl("bad".to_string()).is_retryable());
    assert!(!EngineError::SsrfProtection("blocked".to_string()).is_retryable());
    assert!(!EngineError::Internal("err".to_string()).is_retryable());
    assert!(!EngineError::AllEnginesFailed("all".to_string()).is_retryable());
    assert!(!EngineError::Expired.is_retryable());
    assert!(!EngineError::Other("err".to_string()).is_retryable());
}

#[test]
fn test_engine_error_from_string() {
    let err: EngineError = "something failed".to_string().into();
    match err {
        EngineError::RequestFailed(msg) => assert_eq!(msg, "something failed"),
        other => panic!("Expected RequestFailed, got {:?}", other),
    }
}

#[test]
fn test_engine_error_from_str() {
    let err: EngineError = "network error".into();
    match err {
        EngineError::RequestFailed(msg) => assert_eq!(msg, "network error"),
        other => panic!("Expected RequestFailed, got {:?}", other),
    }
}

#[test]
fn test_engine_error_from_anyhow() {
    let anyhow_err = anyhow::anyhow!("anyhow error");
    let err: EngineError = anyhow_err.into();
    match err {
        EngineError::Internal(msg) => assert_eq!(msg, "anyhow error"),
        other => panic!("Expected Internal, got {:?}", other),
    }
}

#[test]
fn test_engine_error_display() {
    assert_eq!(
        EngineError::Timeout(Duration::from_secs(30)).to_string(),
        "Request timed out after 30s"
    );
    assert_eq!(
        EngineError::NoEnginesAvailable.to_string(),
        "No engines available"
    );
    assert_eq!(EngineError::Expired.to_string(), "Request expired");
}

// EngineHealthStatus tests

#[test]
fn test_engine_health_status_default() {
    assert_eq!(EngineHealthStatus::default(), EngineHealthStatus::Healthy);
}

#[test]
fn test_engine_health_status_equality() {
    let degraded1 = EngineHealthStatus::Degraded {
        unhealthy_engines: vec!["e1".to_string()],
        message: "msg".to_string(),
    };
    let degraded2 = EngineHealthStatus::Degraded {
        unhealthy_engines: vec!["e1".to_string()],
        message: "msg".to_string(),
    };
    assert_eq!(degraded1, degraded2);

    let unavailable = EngineHealthStatus::Unavailable {
        message: "all down".to_string(),
    };
    assert_ne!(EngineHealthStatus::Healthy, unavailable);
}

// EngineClient tests

#[test]
fn test_engine_client_new() {
    let client = EngineClient::new();
    assert_eq!(client.engine_count(), 0);
    assert!(client.registered_engines().is_empty());
}

#[test]
fn test_engine_client_default() {
    let client = EngineClient::default();
    assert_eq!(client.engine_count(), 0);
}

#[tokio::test]
async fn test_engine_client_health_check_no_engines() {
    let client = EngineClient::new();
    let status = client.health_check().await;
    // With no engines, aggregate status is Healthy (no unhealthy engines found)
    assert_eq!(status, EngineHealthStatus::Healthy);
}

#[tokio::test]
async fn test_engine_client_scrape_rejects_ssrf() {
    let client = EngineClient::new();
    let request = ScrapeRequest::new("http://localhost");
    let result = client.scrape(&request).await;
    assert!(result.is_err());
    match result.unwrap_err() {
        EngineError::SsrfProtection(_) => {}
        other => panic!("Expected SsrfProtection, got {:?}", other),
    }
}

#[tokio::test]
async fn test_engine_client_scrape_rejects_private_ip() {
    let client = EngineClient::new();
    let request = ScrapeRequest::new("http://192.168.1.1");
    let result = client.scrape(&request).await;
    assert!(result.is_err());
    match result.unwrap_err() {
        EngineError::SsrfProtection(_) => {}
        other => panic!("Expected SsrfProtection, got {:?}", other),
    }
}

#[tokio::test]
async fn test_engine_client_scrape_rejects_invalid_scheme() {
    let client = EngineClient::new();
    let request = ScrapeRequest::new("file:///etc/passwd");
    let result = client.scrape(&request).await;
    assert!(result.is_err());
}

// convert_error tests

#[test]
fn test_convert_error_request_failed() {
    let err = convert_error(EngineError::RequestFailed("test".to_string()));
    match err {
        EngineError::RequestFailed(msg) => assert_eq!(msg, "test"),
        other => panic!("Expected RequestFailed, got {:?}", other),
    }
}

#[test]
fn test_convert_error_timeout() {
    let duration = Duration::from_secs(15);
    let err = convert_error(EngineError::Timeout(duration));
    match err {
        EngineError::Timeout(d) => assert_eq!(d, duration),
        other => panic!("Expected Timeout, got {:?}", other),
    }
}

#[test]
fn test_convert_error_all_engines_failed_with_no_suitable() {
    let err = convert_error(EngineError::AllEnginesFailed(
        "No suitable engines found".to_string(),
    ));
    match err {
        EngineError::NoEnginesAvailable => {}
        other => panic!("Expected NoEnginesAvailable, got {:?}", other),
    }
}

#[test]
fn test_convert_error_all_engines_failed_generic() {
    let err = convert_error(EngineError::AllEnginesFailed("all failed".to_string()));
    match err {
        EngineError::RequestFailed(msg) => assert_eq!(msg, "all failed"),
        other => panic!("Expected RequestFailed, got {:?}", other),
    }
}

#[test]
fn test_convert_error_ssrf_protection() {
    let err = convert_error(EngineError::SsrfProtection("blocked".to_string()));
    match err {
        EngineError::SsrfProtection(msg) => assert_eq!(msg, "blocked"),
        other => panic!("Expected SsrfProtection, got {:?}", other),
    }
}

#[test]
fn test_convert_error_browser_error() {
    let err = convert_error(EngineError::BrowserError("crash".to_string()));
    match err {
        EngineError::BrowserError(msg) => assert_eq!(msg, "crash"),
        other => panic!("Expected BrowserError, got {:?}", other),
    }
}

#[test]
fn test_convert_error_expired() {
    let err = convert_error(EngineError::Expired);
    match err {
        EngineError::Internal(msg) => assert_eq!(msg, "Request expired"),
        other => panic!("Expected Internal, got {:?}", other),
    }
}

#[test]
fn test_convert_error_other() {
    let err = convert_error(EngineError::Other("misc".to_string()));
    match err {
        EngineError::Internal(msg) => assert_eq!(msg, "misc"),
        other => panic!("Expected Internal, got {:?}", other),
    }
}

#[test]
fn test_convert_error_no_engines_available() {
    let err = convert_error(EngineError::NoEnginesAvailable);
    assert!(matches!(err, EngineError::NoEnginesAvailable));
}

#[test]
fn test_convert_error_invalid_url() {
    let err = convert_error(EngineError::InvalidUrl("bad url".to_string()));
    match err {
        EngineError::InvalidUrl(msg) => assert_eq!(msg, "bad url"),
        other => panic!("Expected InvalidUrl, got {:?}", other),
    }
}

#[test]
fn test_convert_error_internal() {
    let err = convert_error(EngineError::Internal("inner".to_string()));
    match err {
        EngineError::Internal(msg) => assert_eq!(msg, "inner"),
        other => panic!("Expected Internal, got {:?}", other),
    }
}

// PageAction tests

#[test]
fn test_page_action_variants() {
    let wait = PageAction::Wait { milliseconds: 1000 };
    let click = PageAction::Click {
        selector: "#btn".to_string(),
    };
    let scroll = PageAction::Scroll {
        direction: ScrollDirection::Down,
    };
    let input = PageAction::Input {
        selector: "#field".to_string(),
        text: "text".to_string(),
    };

    // Verify they can be cloned and match via pattern matching
    match wait.clone() {
        PageAction::Wait { milliseconds } => assert_eq!(milliseconds, 1000),
        other => panic!("Expected Wait, got {:?}", other),
    }
    match click.clone() {
        PageAction::Click { selector } => assert_eq!(selector, "#btn"),
        other => panic!("Expected Click, got {:?}", other),
    }
    match scroll.clone() {
        PageAction::Scroll { direction } => assert_eq!(direction, ScrollDirection::Down),
        other => panic!("Expected Scroll, got {:?}", other),
    }
    match input.clone() {
        PageAction::Input { selector, text } => {
            assert_eq!(selector, "#field");
            assert_eq!(text, "text");
        }
        other => panic!("Expected Input, got {:?}", other),
    }
}

// is_retryable comprehensive tests

#[test]
fn test_engine_error_is_retryable_all_variants() {
    assert!(EngineError::RequestFailed("err".to_string()).is_retryable());
    assert!(EngineError::Timeout(Duration::from_secs(10)).is_retryable());
    assert!(!EngineError::NoEnginesAvailable.is_retryable());
    assert!(!EngineError::InvalidUrl("bad".to_string()).is_retryable());
    assert!(!EngineError::SsrfProtection("blocked".to_string()).is_retryable());
    assert!(EngineError::BrowserError("err".to_string()).is_retryable());
    assert!(EngineError::AntiBotDetected("rate limited".to_string()).is_retryable());
    assert!(!EngineError::Internal("err".to_string()).is_retryable());
    assert!(!EngineError::AllEnginesFailed("all failed".to_string()).is_retryable());
    assert!(!EngineError::Expired.is_retryable());
    assert!(!EngineError::Other("err".to_string()).is_retryable());
}

// retry_reason tests

#[test]
fn test_retry_reason_antibot_detected_maps_to_antibot() {
    let err = EngineError::AntiBotDetected("Cloudflare challenge page".to_string());
    assert_eq!(err.retry_reason(), RetryReason::AntiBot);
}

#[test]
fn test_retry_reason_transient_errors_map_to_transient() {
    assert_eq!(
        EngineError::RequestFailed("conn refused".to_string()).retry_reason(),
        RetryReason::Transient
    );
    assert_eq!(
        EngineError::Timeout(Duration::from_secs(10)).retry_reason(),
        RetryReason::Transient
    );
    assert_eq!(
        EngineError::BrowserError("crash".to_string()).retry_reason(),
        RetryReason::Transient
    );
}

#[test]
fn test_retry_reason_non_retryable_errors_map_to_transient_placeholder() {
    // 不可重试错误返回 Transient 占位(调用方应先查 is_retryable)
    assert_eq!(
        EngineError::NoEnginesAvailable.retry_reason(),
        RetryReason::Transient
    );
    assert_eq!(
        EngineError::InvalidUrl("bad".to_string()).retry_reason(),
        RetryReason::Transient
    );
    assert_eq!(
        EngineError::SsrfProtection("blocked".to_string()).retry_reason(),
        RetryReason::Transient
    );
    assert_eq!(
        EngineError::Internal("err".to_string()).retry_reason(),
        RetryReason::Transient
    );
    assert_eq!(
        EngineError::AllEnginesFailed("all".to_string()).retry_reason(),
        RetryReason::Transient
    );
    assert_eq!(EngineError::Expired.retry_reason(), RetryReason::Transient);
    assert_eq!(
        EngineError::Other("err".to_string()).retry_reason(),
        RetryReason::Transient
    );
}

#[test]
fn test_antibot_detected_display_format() {
    let err = EngineError::AntiBotDetected("429 Too Many Requests".to_string());
    assert_eq!(err.to_string(), "Anti-bot detected: 429 Too Many Requests");
}

#[test]
fn test_convert_error_antibot_detected_passthrough() {
    let err = convert_error(EngineError::AntiBotDetected("WAF block".to_string()));
    match err {
        EngineError::AntiBotDetected(msg) => assert_eq!(msg, "WAF block"),
        other => panic!("Expected AntiBotDetected, got {:?}", other),
    }
}

// EngineError::FeatureToggle tests

#[test]
fn test_feature_toggle_is_retryable() {
    assert!(EngineError::FeatureToggle("chrome_degraded_to_http".to_string()).is_retryable());
}

#[test]
fn test_feature_toggle_retry_reason() {
    assert_eq!(
        EngineError::FeatureToggle("chrome_degraded_to_http".to_string()).retry_reason(),
        RetryReason::FeatureToggle
    );
}

#[test]
fn test_feature_toggle_display_format() {
    let err = EngineError::FeatureToggle("js_render_failed_fallback".to_string());
    assert_eq!(err.to_string(), "Feature toggle: js_render_failed_fallback");
}

#[test]
fn test_convert_error_feature_toggle_passthrough() {
    let err = convert_error(EngineError::FeatureToggle("engine_downgrade".to_string()));
    match err {
        EngineError::FeatureToggle(msg) => assert_eq!(msg, "engine_downgrade"),
        other => panic!("Expected FeatureToggle, got {:?}", other),
    }
}

/// FeatureToggle 与其他 reason 区分
#[test]
fn test_feature_toggle_distinct_from_other_reasons() {
    let ft_err = EngineError::FeatureToggle("test".to_string());
    let ab_err = EngineError::AntiBotDetected("test".to_string());
    let tr_err = EngineError::Timeout(Duration::from_secs(1));

    assert_eq!(ft_err.retry_reason(), RetryReason::FeatureToggle);
    assert_ne!(ft_err.retry_reason(), ab_err.retry_reason());
    assert_ne!(ft_err.retry_reason(), tr_err.retry_reason());
}

// to_public conversion tests

#[test]
fn test_to_public_basic_fields() {
    let internal = InternalScrapeResponse {
        js_degraded: false,
        captured_responses: Vec::new(),
        status_code: 200,
        content: "hello".to_string(),
        screenshot: None,
        content_type: "text/html".to_string(),
        headers: std::collections::HashMap::new(),
        response_time_ms: 150,
        final_url: None,
    };
    let public = internal.to_public("https://example.com");
    assert_eq!(public.status_code, 200);
    assert_eq!(public.content, "hello");
    assert!(public.screenshot.is_none());
    assert_eq!(public.content_type, "text/html");
    assert!(public.headers.is_empty());
    assert_eq!(public.response_time_ms, 150);
    assert!(public.final_url.is_none());
}

#[test]
fn test_to_public_with_screenshot_and_headers() {
    let mut headers = std::collections::HashMap::new();
    headers.insert("X-Custom".to_string(), "value".to_string());
    let internal = InternalScrapeResponse {
        js_degraded: false,
        captured_responses: Vec::new(),
        status_code: 404,
        content: "not found".to_string(),
        screenshot: Some("base64data".to_string()),
        content_type: "application/json".to_string(),
        headers,
        response_time_ms: 500,
        final_url: None,
    };
    let public = internal.to_public("https://test.com/page");
    assert_eq!(public.status_code, 404);
    assert_eq!(public.content, "not found");
    assert_eq!(public.screenshot, Some("base64data".to_string()));
    assert_eq!(public.content_type, "application/json");
    assert_eq!(public.headers.len(), 1);
    assert_eq!(public.response_time_ms, 500);
    assert!(public.final_url.is_none());
}

#[test]
fn test_to_public_empty_content() {
    let internal = InternalScrapeResponse {
        js_degraded: false,
        captured_responses: Vec::new(),
        status_code: 204,
        content: String::new(),
        screenshot: None,
        content_type: String::new(),
        headers: std::collections::HashMap::new(),
        response_time_ms: 0,
        final_url: None,
    };
    let public = internal.to_public("");
    assert_eq!(public.status_code, 204);
    assert!(public.content.is_empty());
    assert!(public.content_type.is_empty());
    assert!(public.final_url.is_none());
}

// EngineClient method tests

#[test]
fn test_engine_client_engine_count_zero() {
    let client = EngineClient::new();
    assert_eq!(client.engine_count(), 0);
}

#[test]
fn test_engine_client_registered_engines_empty() {
    let client = EngineClient::new();
    let engines = client.registered_engines();
    assert!(engines.is_empty());
}

// Mock EngineRouter for scrape/health_check tests

use crate::engines::router::EngineStats;
use async_trait::async_trait;

enum MockRouteResult {
    Success(InternalScrapeResponse),
    Timeout,
    AllEnginesFailed(String),
}

struct MockEngineRouter {
    result: MockRouteResult,
    engines: Vec<String>,
}

impl MockEngineRouter {
    fn new_success() -> Self {
        Self {
            result: MockRouteResult::Success(InternalScrapeResponse {
                js_degraded: false,
                captured_responses: Vec::new(),
                status_code: 200,
                content: "test content".to_string(),
                screenshot: None,
                content_type: "text/html".to_string(),
                headers: HashMap::new(),
                response_time_ms: 100,
                final_url: None,
            }),
            engines: vec!["mock-engine".to_string()],
        }
    }

    fn new_timeout() -> Self {
        Self {
            result: MockRouteResult::Timeout,
            engines: vec![],
        }
    }

    fn new_all_failed(msg: &str) -> Self {
        Self {
            result: MockRouteResult::AllEnginesFailed(msg.to_string()),
            engines: vec![],
        }
    }
}

#[async_trait]
impl EngineRouterTrait for MockEngineRouter {
    async fn route(
        &self,
        _request: &InternalScrapeRequest,
    ) -> Result<InternalScrapeResponse, EngineError> {
        match &self.result {
            MockRouteResult::Success(resp) => Ok(resp.clone()),
            MockRouteResult::Timeout => Err(EngineError::Timeout(Duration::from_secs(30))),
            MockRouteResult::AllEnginesFailed(msg) => {
                Err(EngineError::AllEnginesFailed(msg.clone()))
            }
        }
    }

    async fn aggregate(
        &self,
        request: &InternalScrapeRequest,
    ) -> Result<InternalScrapeResponse, EngineError> {
        self.route(request).await
    }

    fn get_engine_stats(&self) -> HashMap<String, EngineStats> {
        HashMap::new()
    }

    fn reset_engine_stats(&self, _engine_name: &str) {}

    fn registered_engines(&self) -> Vec<String> {
        self.engines.clone()
    }
}

// EngineClient::scrape success path

#[tokio::test]
async fn test_engine_client_scrape_success() {
    let router: Arc<dyn EngineRouterTrait> = Arc::new(MockEngineRouter::new_success());
    let client = EngineClient::with_router(router);

    let request = ScrapeRequest::new("https://example.com");
    let result = client.scrape(&request).await;

    assert!(result.is_ok());
    let response = result.unwrap();
    assert_eq!(response.status_code, 200);
    assert_eq!(response.content, "test content");
    assert_eq!(response.content_type, "text/html");
    assert_eq!(response.response_time_ms, 100);
    assert!(
        response.final_url.is_none(),
        "引擎未上报 final_url 时不得用请求 URL 伪造"
    );
}

// EngineClient::scrape SSRF rejection

#[tokio::test]
async fn test_engine_client_scrape_ssrf_rejected() {
    let router: Arc<dyn EngineRouterTrait> = Arc::new(MockEngineRouter::new_success());
    let client = EngineClient::with_router(router);

    // SSRF: localhost / private IP should be rejected by validate_url
    let request = ScrapeRequest::new("http://127.0.0.1:8080");
    let result = client.scrape(&request).await;

    assert!(result.is_err());
    match result.unwrap_err() {
        EngineError::SsrfProtection(_) => {}
        other => panic!("Expected SsrfProtection, got {:?}", other),
    }
}

// EngineClient::scrape router error propagation

/// 走 `client.scrape` 且需**通过 SSRF 校验**抵达 mock router 的用例统一使用该公网 IP
/// 字面量:SSRF 对 IP 直判公网、免 DNS 解析,避免 `example.com` 依赖活体 DNS 造成的
/// 间歇性假失败(覆盖率门禁要求测试确定性)。
const SSRF_SAFE_PUBLIC_URL: &str = "https://93.184.216.34";

#[tokio::test]
async fn test_engine_client_scrape_router_error() {
    let router: Arc<dyn EngineRouterTrait> = Arc::new(MockEngineRouter::new_timeout());
    let client = EngineClient::with_router(router);

    // 公网 IP 字面量过 SSRF(免 DNS),确保稳定抵达 mock router 的 Timeout 分支。
    let request = ScrapeRequest::new(SSRF_SAFE_PUBLIC_URL);
    let result = client.scrape(&request).await;

    assert!(result.is_err());
    match result.unwrap_err() {
        EngineError::Timeout(d) => assert_eq!(d, Duration::from_secs(30)),
        other => panic!("Expected Timeout, got {:?}", other),
    }
}

// EngineClient::scrape no engines available error

#[tokio::test]
async fn test_engine_client_scrape_no_engines_error() {
    let router: Arc<dyn EngineRouterTrait> = Arc::new(MockEngineRouter::new_all_failed(
        "No suitable engines available",
    ));
    let client = EngineClient::with_router(router);

    // 公网 IP 字面量过 SSRF(免 DNS),确保稳定抵达 mock router 的 NoEnginesAvailable 分支。
    let request = ScrapeRequest::new(SSRF_SAFE_PUBLIC_URL);
    let result = client.scrape(&request).await;

    assert!(result.is_err());
    match result.unwrap_err() {
        EngineError::NoEnginesAvailable => {}
        other => panic!("Expected NoEnginesAvailable, got {:?}", other),
    }
}

// EngineClient::with_engines

#[test]
fn test_engine_client_with_engines() {
    struct MockEngine;
    #[async_trait]
    impl ScraperEngine for MockEngine {
        async fn scrape(
            &self,
            _request: &InternalScrapeRequest,
        ) -> Result<InternalScrapeResponse, EngineError> {
            Ok(InternalScrapeResponse {
                js_degraded: false,
                captured_responses: Vec::new(),
                status_code: 200,
                content: "ok".to_string(),
                screenshot: None,
                content_type: "text/html".to_string(),
                headers: HashMap::new(),
                response_time_ms: 50,
                final_url: None,
            })
        }
        fn support_score(&self, _request: &InternalScrapeRequest) -> u8 {
            100
        }
        fn name(&self) -> &'static str {
            "mock-engine"
        }
    }

    let engines: Vec<Arc<dyn ScraperEngine>> = vec![Arc::new(MockEngine)];
    let client = EngineClient::with_engines(engines);
    assert_eq!(client.engine_count(), 1);
    assert_eq!(client.registered_engines(), vec!["mock-engine".to_string()]);
}

// EngineClientTrait trait impl tests

#[tokio::test]
async fn test_engine_client_trait_scrape_success() {
    let router: Arc<dyn EngineRouterTrait> = Arc::new(MockEngineRouter::new_success());
    let client: Arc<dyn EngineClientTrait> = Arc::new(EngineClient::with_router(router));

    // 公网 IP 字面量过 SSRF(免 DNS),确保稳定抵达 mock router 的成功分支。
    let request = ScrapeRequest::new(SSRF_SAFE_PUBLIC_URL);
    let result = client.scrape(&request).await;
    assert!(result.is_ok());
    let response = result.unwrap();
    assert_eq!(response.status_code, 200);
}

#[tokio::test]
async fn test_engine_client_trait_health_check_healthy() {
    let client = EngineClient::new();
    let status = client.health_check().await;
    // With no engines, health should be Healthy
    assert_eq!(status, EngineHealthStatus::Healthy);
}

#[tokio::test]
async fn test_engine_client_trait_health_check_with_router() {
    let router: Arc<dyn EngineRouterTrait> = Arc::new(MockEngineRouter::new_success());
    let client = EngineClient::with_router(router);
    let status = client.health_check().await;
    // health_monitor has no engines (with_router passes empty), so Healthy
    assert_eq!(status, EngineHealthStatus::Healthy);
}

#[test]
fn test_engine_client_trait_engine_count_and_registered_engines() {
    let router: Arc<dyn EngineRouterTrait> = Arc::new(MockEngineRouter::new_success());
    let client: Arc<dyn EngineClientTrait> = Arc::new(EngineClient::with_router(router));
    assert_eq!(client.engine_count(), 1);
    assert_eq!(client.registered_engines(), vec!["mock-engine".to_string()]);
}

// skip_tls_verification branch coverage
// Tests all branches: development (allow), production (deny), prod (deny), false (no-op).

#[test]
fn test_skip_tls_verification_all_branches() {
    // Branch 1: skip=false (no warning, sets to false)
    let options = ScrapeOptions::builder()
        .skip_tls_verification(false)
        .build();
    assert!(!options.skip_tls_verification);

    // Branch 2: skip=true in development (warning, sets to true)
    std::env::remove_var("APP_ENVIRONMENT");
    std::env::remove_var("CRAWLRS_ENV");
    let options = ScrapeOptions::builder().skip_tls_verification(true).build();
    assert!(
        options.skip_tls_verification,
        "skip_tls_verification should be true in development"
    );

    // Branch 3: skip=true in production (denied, remains false)
    std::env::set_var("APP_ENVIRONMENT", "production");
    let options = ScrapeOptions::builder().skip_tls_verification(true).build();
    assert!(
        !options.skip_tls_verification,
        "skip_tls_verification should be denied in production"
    );

    // Branch 4: skip=true in prod (denied, remains false)
    std::env::set_var("APP_ENVIRONMENT", "prod");
    let options = ScrapeOptions::builder().skip_tls_verification(true).build();
    assert!(
        !options.skip_tls_verification,
        "skip_tls_verification should be denied in prod"
    );

    // Branch 5: CRAWLRS_ENV also checked for production
    std::env::remove_var("APP_ENVIRONMENT");
    std::env::set_var("CRAWLRS_ENV", "production");
    let options = ScrapeOptions::builder().skip_tls_verification(true).build();
    assert!(
        !options.skip_tls_verification,
        "skip_tls_verification should be denied via CRAWLRS_ENV=production"
    );

    // Cleanup
    std::env::remove_var("APP_ENVIRONMENT");
    std::env::remove_var("CRAWLRS_ENV");
}

// ScrapeOptions builder with all remaining fields

#[test]
fn test_scrape_options_builder_body_sync_wait_tls_fingerprint() {
    let options = ScrapeOptions::builder()
        .body("request body")
        .sync_wait_ms(500)
        .needs_tls_fingerprint(true)
        .use_fire_engine(true)
        .build();

    assert_eq!(options.body, Some("request body".to_string()));
    assert_eq!(options.sync_wait_ms, 500);
    assert!(options.needs_tls_fingerprint);
    assert!(options.use_fire_engine);
}

// HttpMethod default test

#[test]
fn test_http_method_default_is_get() {
    assert_eq!(HttpMethod::default(), HttpMethod::Get);
}

// ScrollDirection tests

#[test]
fn test_scroll_direction_default_is_down() {
    assert_eq!(ScrollDirection::default(), ScrollDirection::Down);
}

#[test]
fn test_scroll_direction_variants() {
    assert_eq!(ScrollDirection::Down, ScrollDirection::Down);
    assert_eq!(ScrollDirection::Up, ScrollDirection::Up);
    assert_eq!(ScrollDirection::Bottom, ScrollDirection::Bottom);
    assert_eq!(ScrollDirection::Top, ScrollDirection::Top);
    assert_ne!(ScrollDirection::Down, ScrollDirection::Up);
}

// EngineClient Clone

#[test]
fn test_engine_client_clone() {
    let client = EngineClient::new();
    let cloned = client.clone();
    assert_eq!(client.engine_count(), cloned.engine_count());
    assert_eq!(client.registered_engines(), cloned.registered_engines());
}

// ScraperEngine trait default method coverage

#[test]
fn test_scraper_engine_default_supports_tls_fingerprint_returns_false() {
    // Cover lines 605-606: the ScraperEngine trait provides a default
    // implementation of `supports_tls_fingerprint` that returns false.
    // An engine that does NOT override it should report false.
    struct BasicEngine;
    #[async_trait]
    impl ScraperEngine for BasicEngine {
        async fn scrape(
            &self,
            _request: &InternalScrapeRequest,
        ) -> Result<InternalScrapeResponse, EngineError> {
            Ok(InternalScrapeResponse {
                js_degraded: false,
                captured_responses: Vec::new(),
                status_code: 200,
                content: "ok".to_string(),
                screenshot: None,
                content_type: "text/html".to_string(),
                headers: HashMap::new(),
                response_time_ms: 1,
                final_url: None,
            })
        }
        fn support_score(&self, _request: &InternalScrapeRequest) -> u8 {
            100
        }
        fn name(&self) -> &'static str {
            "basic"
        }
    }

    let engine = BasicEngine;
    assert!(
        !engine.supports_tls_fingerprint(),
        "default supports_tls_fingerprint should return false"
    );
}

// EngineClient::health_check Degraded/Unavailable branch coverage
// The public constructors (new / with_router / with_engines) all build the
// internal health_monitor with either an empty engine list or an empty
// health_monitor, so the Degraded/Unavailable branches of health_check
// are unreachable through the public API. We construct EngineClient
// directly here (test module has access to private fields) and inject a
// health_monitor that wraps real engines whose scrape outcomes we control.

/// Mock engine that always succeeds; used as the "healthy" engine in a
/// mixed-engine scenario to trigger AggregateHealthStatus::Degraded.
struct HealthyMockEngine {
    engine_name: &'static str,
}

#[async_trait]
impl ScraperEngine for HealthyMockEngine {
    async fn scrape(
        &self,
        _request: &InternalScrapeRequest,
    ) -> Result<InternalScrapeResponse, EngineError> {
        Ok(InternalScrapeResponse {
            js_degraded: false,
            captured_responses: Vec::new(),
            status_code: 200,
            content: "ok".to_string(),
            screenshot: None,
            content_type: "text/html".to_string(),
            headers: HashMap::new(),
            response_time_ms: 1,
            final_url: None,
        })
    }
    fn support_score(&self, _request: &InternalScrapeRequest) -> u8 {
        100
    }
    fn name(&self) -> &'static str {
        self.engine_name
    }
}

/// Mock engine that always fails; used to make the health monitor mark
/// the engine as Degraded (after 1 failure) or Unhealthy (after
/// `max_consecutive_failures` failures).
struct FailingMockEngine {
    engine_name: &'static str,
}

#[async_trait]
impl ScraperEngine for FailingMockEngine {
    async fn scrape(
        &self,
        _request: &InternalScrapeRequest,
    ) -> Result<InternalScrapeResponse, EngineError> {
        Err(EngineError::RequestFailed("connection refused".to_string()))
    }
    fn support_score(&self, _request: &InternalScrapeRequest) -> u8 {
        100
    }
    fn name(&self) -> &'static str {
        self.engine_name
    }
}

#[tokio::test]
async fn test_engine_client_health_check_returns_degraded() {
    // Cover lines 738-743: when health_monitor reports Degraded status
    // (some engines unhealthy but at least one healthy), EngineClient
    // should convert that into EngineHealthStatus::Degraded with the
    // unhealthy engine names and a "N engines degraded" message.
    let engines: Vec<Arc<dyn ScraperEngine>> = vec![
        Arc::new(HealthyMockEngine {
            engine_name: "healthy-engine",
        }),
        Arc::new(FailingMockEngine {
            engine_name: "failing-engine",
        }),
    ];

    // Construct EngineClient directly so we can inject a health_monitor
    // that actually owns the engines. with_router/with_engines leave the
    // monitor empty, which would always report Healthy.
    // auth 面:monitor 由 registry 检查项持有(EngineHealthCheck 内部写回状态表),
    // 经 health_registry 字段注入等效的检查集合。
    #[cfg(not(feature = "auth"))]
    let client = EngineClient {
        router: Arc::new(EngineRouter::new(engines.clone())),
        health_monitor: Arc::new(EngineHealthMonitor::new(engines)),
    };
    #[cfg(feature = "auth")]
    let client = EngineClient {
        router: Arc::new(EngineRouter::new(engines.clone())),
        health_registry: Arc::new(
            crate::engines::health_monitor::garrison_health::build_health_registry(&Arc::new(
                EngineHealthMonitor::new(engines),
            )),
        ),
    };

    let status = client.health_check().await;
    match status {
        EngineHealthStatus::Degraded {
            unhealthy_engines,
            message,
        } => {
            assert!(
                unhealthy_engines.contains(&"failing-engine".to_string()),
                "failing-engine should be listed as unhealthy: {:?}",
                unhealthy_engines
            );
            assert!(
                message.contains("engines degraded"),
                "message should mention 'engines degraded': {}",
                message
            );
        }
        other => panic!("Expected Degraded, got {:?}", other),
    }
}

#[tokio::test]
async fn test_engine_client_health_check_returns_unavailable() {
    // Cover lines 745-747: when health_monitor reports Unavailable
    // (all engines unhealthy), EngineClient should convert that into
    // EngineHealthStatus::Unavailable with the canonical message.
    use crate::engines::health_monitor::HealthCheckConfig;

    let engines: Vec<Arc<dyn ScraperEngine>> = vec![Arc::new(FailingMockEngine {
        engine_name: "failing-engine",
    })];

    // Configure max_consecutive_failures = 1 so a single health check
    // pass is enough to mark the engine Unhealthy (otherwise we'd need
    // three passes with the default config).
    let config = HealthCheckConfig {
        check_interval: Duration::from_secs(60),
        timeout: Duration::from_secs(10),
        max_consecutive_failures: 1,
        degraded_threshold_ms: 2000,
        unhealthy_threshold_ms: 5000,
        target_url: "https://example.com".to_string(),
    };

    #[cfg(not(feature = "auth"))]
    let client = EngineClient {
        router: Arc::new(EngineRouter::new(engines.clone())),
        health_monitor: Arc::new(EngineHealthMonitor::new_with_config(engines, config)),
    };
    #[cfg(feature = "auth")]
    let client = EngineClient {
        router: Arc::new(EngineRouter::new(engines.clone())),
        health_registry: Arc::new(
            crate::engines::health_monitor::garrison_health::build_health_registry(&Arc::new(
                EngineHealthMonitor::new_with_config(engines, config),
            )),
        ),
    };

    let status = client.health_check().await;
    match status {
        EngineHealthStatus::Unavailable { message } => {
            assert_eq!(
                message, "All engines unavailable",
                "Unavailable message should be canonical"
            );
        }
        other => panic!("Expected Unavailable, got {:?}", other),
    }
}

// session_id 校验测试

#[test]
fn test_validate_session_id_accepts_normal_string() {
    assert!(validate_session_id("session-123"));
    assert!(validate_session_id("abc"));
    assert!(validate_session_id("user_session_id_456"));
}

#[test]
fn test_validate_session_id_accepts_printable_ascii() {
    // 0x20-0x7E 范围内的所有可打印 ASCII 字符
    let printable: String = (0x20u8..=0x7E).map(|b| b as char).collect();
    assert!(
        validate_session_id(&printable),
        "all printable ASCII chars should be valid"
    );
}

#[test]
fn test_validate_session_id_accepts_max_length() {
    // 正好 128 字节
    let max_len = "a".repeat(MAX_SESSION_ID_LEN);
    assert!(
        validate_session_id(&max_len),
        "exactly MAX_SESSION_ID_LEN bytes should be valid"
    );
}

#[test]
fn test_validate_session_id_rejects_too_long() {
    // 129 字节 — 超过上限
    let too_long = "a".repeat(MAX_SESSION_ID_LEN + 1);
    assert!(
        !validate_session_id(&too_long),
        "string exceeding MAX_SESSION_ID_LEN should be rejected"
    );
}

#[test]
fn test_validate_session_id_rejects_control_chars() {
    // 控制字符(0x00-0x1F, 0x7F)应被拒绝
    assert!(!validate_session_id("session\n123"));
    assert!(!validate_session_id("session\t123"));
    assert!(!validate_session_id("session\r123"));
    assert!(!validate_session_id("session\x00123"));
    assert!(!validate_session_id("session\u{007F}123"));
}

#[test]
fn test_validate_session_id_rejects_empty_string() {
    // 空字符串:长度为 0,字符集检查为空(all 返回 true)
    // 空字符串在语义上无效(不能作为 session_id),但当前实现允许它
    // 因为空字符串不会导致 DoS 或日志注入,且 rr_pick 的回退行为是 RoundRobin
    // 这里测试当前行为(空字符串通过校验),如果未来需要拒绝空字符串可修改
    assert!(validate_session_id(""));
}

#[test]
fn test_validate_session_id_rejects_non_ascii() {
    // 非 ASCII 字符(UTF-8 多字节)应被拒绝
    assert!(!validate_session_id("session-中文"));
    assert!(!validate_session_id("session-é"));
    assert!(!validate_session_id("session-🎉"));
}

#[test]
fn test_session_id_builder_accepts_valid_input() {
    let options = ScrapeOptions::builder()
        .session_id("valid-session-123")
        .build();
    assert_eq!(options.session_id, Some("valid-session-123".to_string()));
}

#[test]
fn test_session_id_builder_rejects_too_long() {
    let too_long = "a".repeat(MAX_SESSION_ID_LEN + 1);
    let options = ScrapeOptions::builder()
        .session_id(too_long.clone())
        .build();
    assert!(
        options.session_id.is_none(),
        "too long session_id should be rejected by builder"
    );
}

#[test]
fn test_session_id_builder_rejects_control_chars() {
    let options = ScrapeOptions::builder().session_id("bad\nsession").build();
    assert!(
        options.session_id.is_none(),
        "session_id with control chars should be rejected by builder"
    );
}

#[test]
fn test_to_internal_validates_session_id() {
    // to_internal 应二次校验 session_id,拒绝非法值
    let options = ScrapeOptions {
        session_id: Some("bad\nsession".to_string()),
        ..ScrapeOptions::default()
    };
    let request = ScrapeRequest::new("https://example.com").with_options(options);
    let internal = request.to_internal().unwrap();
    assert!(
        internal.session_id.is_none(),
        "to_internal should reject invalid session_id (bypassing builder)"
    );
}

#[test]
fn test_to_internal_preserves_valid_session_id() {
    let options = ScrapeOptions {
        session_id: Some("valid-session".to_string()),
        ..ScrapeOptions::default()
    };
    let request = ScrapeRequest::new("https://example.com").with_options(options);
    let internal = request.to_internal().unwrap();
    assert_eq!(
        internal.session_id,
        Some("valid-session".to_string()),
        "to_internal should preserve valid session_id"
    );
}