lychee 0.16.0

A fast, async link checker
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
#[cfg(test)]
mod cli {
    use std::{
        collections::{HashMap, HashSet},
        error::Error,
        fs::{self, File},
        io::Write,
        path::{Path, PathBuf},
    };

    use assert_cmd::Command;
    use assert_json_diff::assert_json_include;
    use http::StatusCode;
    use lychee_lib::{InputSource, ResponseBody};
    use predicates::{
        prelude::predicate,
        str::{contains, is_empty},
    };
    use pretty_assertions::assert_eq;
    use regex::Regex;
    use serde::Serialize;
    use serde_json::Value;
    use tempfile::NamedTempFile;
    use uuid::Uuid;
    use wiremock::{matchers::basic_auth, Mock, ResponseTemplate};

    type Result<T> = std::result::Result<T, Box<dyn Error>>;

    // The lychee cache file name is used for some tests.
    // Since it is currently static and can't be overwritten, declare it as a
    // constant.
    const LYCHEE_CACHE_FILE: &str = ".lycheecache";

    /// Helper macro to create a mock server which returns a custom status code.
    macro_rules! mock_server {
        ($status:expr $(, $func:tt ($($arg:expr),*))*) => {{
            let mock_server = wiremock::MockServer::start().await;
            let response_template = wiremock::ResponseTemplate::new(http::StatusCode::from($status));
            let template = response_template$(.$func($($arg),*))*;
            wiremock::Mock::given(wiremock::matchers::method("GET")).respond_with(template).mount(&mock_server).await;
            mock_server
        }};
    }

    /// Helper macro to create a mock server which returns a 200 OK and a custom response body.
    macro_rules! mock_response {
        ($body:expr) => {{
            let mock_server = wiremock::MockServer::start().await;
            let template = wiremock::ResponseTemplate::new(200).set_body_string($body);
            wiremock::Mock::given(wiremock::matchers::method("GET"))
                .respond_with(template)
                .mount(&mock_server)
                .await;
            mock_server
        }};
    }

    /// Gets the "main" binary name (e.g. `lychee`)
    fn main_command() -> Command {
        Command::cargo_bin(env!("CARGO_PKG_NAME")).expect("Couldn't get cargo package name")
    }

    /// Helper function to get the root path of the project.
    fn root_path() -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .to_path_buf()
    }

    /// Helper function to get the path to the fixtures directory.
    fn fixtures_path() -> PathBuf {
        root_path().join("fixtures")
    }

    #[derive(Default, Serialize)]
    struct MockResponseStats {
        detailed_stats: bool,
        total: usize,
        successful: usize,
        unknown: usize,
        unsupported: usize,
        timeouts: usize,
        redirects: usize,
        excludes: usize,
        errors: usize,
        cached: usize,
        success_map: HashMap<InputSource, HashSet<ResponseBody>>,
        fail_map: HashMap<InputSource, HashSet<ResponseBody>>,
        suggestion_map: HashMap<InputSource, HashSet<ResponseBody>>,
        excluded_map: HashMap<InputSource, HashSet<ResponseBody>>,
    }

    /// Helper macro to test the output of the JSON format.
    macro_rules! test_json_output {
        ($test_file:expr, $expected:expr $(, $arg:expr)*) => {{
            let mut cmd = main_command();
            let test_path = fixtures_path().join($test_file);
            let outfile = format!("{}.json", uuid::Uuid::new_v4());

            cmd$(.arg($arg))*.arg("--output").arg(&outfile).arg("--format").arg("json").arg(test_path).assert().success();

            let output = std::fs::read_to_string(&outfile)?;
            std::fs::remove_file(outfile)?;

            let actual: Value = serde_json::from_str(&output)?;
            let expected: Value = serde_json::to_value(&$expected)?;

            assert_json_include!(actual: actual, expected: expected);
            Ok(())
        }};
    }

    /// JSON-formatted output should always be valid JSON.
    /// Additional hints and error messages should be printed to `stderr`.
    /// See https://github.com/lycheeverse/lychee/issues/1355
    #[test]
    fn test_valid_json_output_to_stdout_on_error() -> Result<()> {
        let test_path = fixtures_path().join("TEST_GITHUB_404.md");

        let mut cmd = main_command();
        cmd.arg("--format")
            .arg("json")
            .arg(test_path)
            .assert()
            .failure()
            .code(2);

        let output = cmd.output()?;

        // Check that the output is valid JSON
        assert!(serde_json::from_slice::<Value>(&output.stdout).is_ok());
        Ok(())
    }

    #[test]
    fn test_detailed_json_output_on_error() -> Result<()> {
        let test_path = fixtures_path().join("TEST_DETAILED_JSON_OUTPUT_ERROR.md");

        let mut cmd = main_command();
        cmd.arg("--format")
            .arg("json")
            .arg(&test_path)
            .assert()
            .failure()
            .code(2);

        let output = cmd.output()?;

        // Check that the output is valid JSON
        assert!(serde_json::from_slice::<Value>(&output.stdout).is_ok());

        // Parse site error status from the fail_map
        let output_json = serde_json::from_slice::<Value>(&output.stdout).unwrap();
        let site_error_status = &output_json["fail_map"][&test_path.to_str().unwrap()][0]["status"];

        assert_eq!(
            "error sending request for url (https://expired.badssl.com/)",
            site_error_status["details"]
        );
        Ok(())
    }

    #[test]
    fn test_exclude_all_private() -> Result<()> {
        test_json_output!(
            "TEST_ALL_PRIVATE.md",
            MockResponseStats {
                total: 7,
                excludes: 7,
                ..MockResponseStats::default()
            },
            "--exclude-all-private"
        )
    }

    #[test]
    fn test_email() -> Result<()> {
        test_json_output!(
            "TEST_EMAIL.md",
            MockResponseStats {
                total: 5,
                excludes: 0,
                successful: 5,
                ..MockResponseStats::default()
            },
            "--include-mail"
        )
    }

    #[test]
    fn test_exclude_email_by_default() -> Result<()> {
        test_json_output!(
            "TEST_EMAIL.md",
            MockResponseStats {
                total: 5,
                excludes: 3,
                successful: 2,
                ..MockResponseStats::default()
            }
        )
    }

    #[test]
    fn test_email_html_with_subject() -> Result<()> {
        let mut cmd = main_command();
        let input = fixtures_path().join("TEST_EMAIL_QUERY_PARAMS.html");

        cmd.arg("--dump")
            .arg(input)
            .arg("--include-mail")
            .assert()
            .success()
            .stdout(contains("hello@example.org?subject=%5BHello%5D"));

        Ok(())
    }

    #[test]
    fn test_email_markdown_with_subject() -> Result<()> {
        let mut cmd = main_command();
        let input = fixtures_path().join("TEST_EMAIL_QUERY_PARAMS.md");

        cmd.arg("--dump")
            .arg(input)
            .arg("--include-mail")
            .assert()
            .success()
            .stdout(contains("hello@example.org?subject=%5BHello%5D"));

        Ok(())
    }

    /// Test that a GitHub link can be checked without specifying the token.
    #[test]
    fn test_check_github_no_token() -> Result<()> {
        test_json_output!(
            "TEST_GITHUB.md",
            MockResponseStats {
                total: 1,
                successful: 1,
                ..MockResponseStats::default()
            }
        )
    }

    /// Test unsupported URI schemes
    #[test]
    fn test_unsupported_uri_schemes_are_ignored() {
        let mut cmd = main_command();
        let test_schemes_path = fixtures_path().join("TEST_SCHEMES.txt");

        // Exclude file link because it doesn't exist on the filesystem.
        // (File URIs are absolute paths, which we don't have.)
        // Nevertheless, the `file` scheme should be recognized.
        cmd.arg(test_schemes_path)
            .arg("--exclude")
            .arg("file://")
            .env_clear()
            .assert()
            .success()
            .stdout(contains("3 Total"))
            .stdout(contains("1 OK"))
            .stdout(contains("1 Excluded"));
    }

    #[test]
    fn test_resolve_paths() {
        let mut cmd = main_command();
        let offline_dir = fixtures_path().join("offline");

        cmd.arg("--offline")
            .arg("--base")
            .arg(&offline_dir)
            .arg(offline_dir.join("index.html"))
            .env_clear()
            .assert()
            .success()
            .stdout(contains("4 Total"))
            .stdout(contains("4 OK"));
    }

    #[test]
    fn test_youtube_quirk() {
        let url = "https://www.youtube.com/watch?v=NlKuICiT470&list=PLbWDhxwM_45mPVToqaIZNbZeIzFchsKKQ&index=7";

        main_command()
            .write_stdin(url)
            .arg("--verbose")
            .arg("--no-progress")
            .arg("-")
            .assert()
            .success()
            .stdout(contains("1 Total"))
            .stdout(contains("1 OK"));
    }

    #[test]
    fn test_crates_io_quirk() {
        let url = "https://crates.io/crates/lychee";

        main_command()
            .write_stdin(url)
            .arg("--verbose")
            .arg("--no-progress")
            .arg("-")
            .assert()
            .success()
            .stdout(contains("1 Total"))
            .stdout(contains("1 OK"));
    }

    #[test]
    // Exclude Twitter links because they require login to view tweets.
    // https://techcrunch.com/2023/06/30/twitter-now-requires-an-account-to-view-tweets/
    // https://github.com/zedeus/nitter/issues/919
    fn test_ignored_hosts() {
        let url = "https://twitter.com/zarfeblong/status/1339742840142872577";

        main_command()
            .write_stdin(url)
            .arg("--verbose")
            .arg("--no-progress")
            .arg("-")
            .assert()
            .success()
            .stdout(contains("1 Total"))
            .stdout(contains("1 Excluded"));
    }

    #[tokio::test]
    async fn test_failure_404_link() -> Result<()> {
        let mock_server = mock_server!(StatusCode::NOT_FOUND);
        let dir = tempfile::tempdir()?;
        let file_path = dir.path().join("test.txt");
        let mut file = File::create(&file_path)?;
        writeln!(file, "{}", mock_server.uri())?;

        let mut cmd = main_command();
        cmd.arg(file_path)
            .write_stdin(mock_server.uri())
            .assert()
            .failure()
            .code(2);

        Ok(())
    }

    #[test]
    fn test_schemes() {
        let mut cmd = main_command();
        let test_schemes_path = fixtures_path().join("TEST_SCHEMES.md");

        cmd.arg(test_schemes_path)
            .arg("--scheme")
            .arg("https")
            .arg("--scheme")
            .arg("http")
            .env_clear()
            .assert()
            .success()
            .stdout(contains("3 Total"))
            .stdout(contains("2 OK"))
            .stdout(contains("1 Excluded"));
    }

    #[test]
    fn test_caching_single_file() {
        let mut cmd = main_command();
        // Repetitions in one file shall all be checked and counted only once.
        let test_schemes_path_1 = fixtures_path().join("TEST_REPETITION_1.txt");

        cmd.arg(&test_schemes_path_1)
            .env_clear()
            .assert()
            .success()
            .stdout(contains("1 Total"))
            .stdout(contains("1 OK"));
    }

    #[test]
    // Test that two identical requests don't get executed twice.
    fn test_caching_across_files() -> Result<()> {
        // Repetitions across multiple files shall all be checked only once.
        let repeated_uris = fixtures_path().join("TEST_REPETITION_*.txt");

        test_json_output!(
            repeated_uris,
            MockResponseStats {
                total: 2,
                cached: 1,
                successful: 2,
                excludes: 0,
                ..MockResponseStats::default()
            },
            // Two requests to the same URI may be executed in parallel. As a
            // result, the response might not be cached and the test would be
            // flaky. Therefore limit the concurrency to one request at a time.
            "--max-concurrency",
            "1"
        )
    }

    #[test]
    fn test_failure_github_404_no_token() {
        let mut cmd = main_command();
        let test_github_404_path = fixtures_path().join("TEST_GITHUB_404.md");

        cmd.arg(test_github_404_path)
            .arg("--no-progress")
            .env_clear()
            .assert()
            .failure()
            .code(2)
            .stdout(contains(
                "[404] https://github.com/mre/idiomatic-rust-doesnt-exist-man"
            ))
            .stderr(contains(
                "There were issues with GitHub URLs. You could try setting a GitHub token and running lychee again.",
            ));
    }

    #[tokio::test]
    async fn test_stdin_input() {
        let mut cmd = main_command();
        let mock_server = mock_server!(StatusCode::OK);

        cmd.arg("-")
            .write_stdin(mock_server.uri())
            .assert()
            .success();
    }

    #[tokio::test]
    async fn test_stdin_input_failure() {
        let mut cmd = main_command();
        let mock_server = mock_server!(StatusCode::INTERNAL_SERVER_ERROR);

        cmd.arg("-")
            .write_stdin(mock_server.uri())
            .assert()
            .failure()
            .code(2);
    }

    #[tokio::test]
    async fn test_stdin_input_multiple() {
        let mut cmd = main_command();
        let mock_server_a = mock_server!(StatusCode::OK);
        let mock_server_b = mock_server!(StatusCode::OK);

        // this behavior (treating multiple `-` as separate inputs) is the same as most CLI tools
        // that accept `-` as stdin, e.g. `cat`, `bat`, `grep` etc.
        cmd.arg("-")
            .arg("-")
            .write_stdin(mock_server_a.uri())
            .write_stdin(mock_server_b.uri())
            .assert()
            .success();
    }

    #[test]
    fn test_missing_file_ok_if_skip_missing() {
        let mut cmd = main_command();
        let filename = format!("non-existing-file-{}", uuid::Uuid::new_v4());

        cmd.arg(&filename).arg("--skip-missing").assert().success();
    }

    #[test]
    fn test_skips_hidden_files_by_default() {
        main_command()
            .arg(fixtures_path().join("hidden/"))
            .assert()
            .success()
            .stdout(contains("0 Total"));
    }

    #[test]
    fn test_include_hidden_file() {
        main_command()
            .arg(fixtures_path().join("hidden/"))
            .arg("--hidden")
            .assert()
            .success()
            .stdout(contains("1 Total"));
    }

    #[test]
    fn test_skips_ignored_files_by_default() {
        main_command()
            .arg(fixtures_path().join("ignore/"))
            .assert()
            .success()
            .stdout(contains("0 Total"));
    }

    #[test]
    fn test_include_ignored_file() {
        main_command()
            .arg(fixtures_path().join("ignore/"))
            .arg("--no-ignore")
            .assert()
            .success()
            .stdout(contains("1 Total"));
    }

    #[tokio::test]
    async fn test_glob() -> Result<()> {
        // using Result to be able to use `?`
        let mut cmd = main_command();

        let dir = tempfile::tempdir()?;
        let mock_server_a = mock_server!(StatusCode::OK);
        let mock_server_b = mock_server!(StatusCode::OK);
        let mut file_a = File::create(dir.path().join("a.md"))?;
        let mut file_b = File::create(dir.path().join("b.md"))?;

        writeln!(file_a, "{}", mock_server_a.uri().as_str())?;
        writeln!(file_b, "{}", mock_server_b.uri().as_str())?;

        cmd.arg(dir.path().join("*.md"))
            .arg("--verbose")
            .assert()
            .success()
            .stdout(contains("2 Total"));

        Ok(())
    }

    #[cfg(target_os = "linux")] // MacOS and Windows have case-insensitive filesystems
    #[tokio::test]
    async fn test_glob_ignore_case() -> Result<()> {
        let mut cmd = main_command();

        let dir = tempfile::tempdir()?;
        let mock_server_a = mock_server!(StatusCode::OK);
        let mock_server_b = mock_server!(StatusCode::OK);
        let mut file_a = File::create(dir.path().join("README.md"))?;
        let mut file_b = File::create(dir.path().join("readme.md"))?;

        writeln!(file_a, "{}", mock_server_a.uri().as_str())?;
        writeln!(file_b, "{}", mock_server_b.uri().as_str())?;

        cmd.arg(dir.path().join("[r]eadme.md"))
            .arg("--verbose")
            .arg("--glob-ignore-case")
            .assert()
            .success()
            .stdout(contains("2 Total"));

        Ok(())
    }

    #[tokio::test]
    async fn test_glob_recursive() -> Result<()> {
        let mut cmd = main_command();

        let dir = tempfile::tempdir()?;
        let subdir_level_1 = tempfile::tempdir_in(&dir)?;
        let subdir_level_2 = tempfile::tempdir_in(&subdir_level_1)?;

        let mock_server = mock_server!(StatusCode::OK);
        let mut file = File::create(subdir_level_2.path().join("test.md"))?;

        writeln!(file, "{}", mock_server.uri().as_str())?;

        // ** should be a recursive glob
        cmd.arg(dir.path().join("**/*.md"))
            .arg("--verbose")
            .assert()
            .success()
            .stdout(contains("1 Total"));

        Ok(())
    }

    /// Test formatted file output
    #[test]
    fn test_formatted_file_output() -> Result<()> {
        test_json_output!(
            "TEST.md",
            MockResponseStats {
                total: 12,
                successful: 10,
                excludes: 2,
                ..MockResponseStats::default()
            }
        )
    }

    /// Test writing output of `--dump` command to file
    #[test]
    fn test_dump_to_file() -> Result<()> {
        let mut cmd = main_command();
        let test_path = fixtures_path().join("TEST.md");
        let outfile = format!("{}", Uuid::new_v4());

        cmd.arg("--output")
            .arg(&outfile)
            .arg("--dump")
            .arg("--include-mail")
            .arg(test_path)
            .assert()
            .success();

        let output = fs::read_to_string(&outfile)?;

        // We expect 11 links in the test file
        // Running the command from the command line will print 9 links,
        // because the actual `--dump` command filters out the two
        // http(s)://example.com links
        assert_eq!(output.lines().count(), 12);
        fs::remove_file(outfile)?;
        Ok(())
    }

    /// Test excludes
    #[test]
    fn test_exclude_wildcard() -> Result<()> {
        let mut cmd = main_command();
        let test_path = fixtures_path().join("TEST.md");

        cmd.arg(test_path)
            .arg("--exclude")
            .arg(".*")
            .assert()
            .success()
            .stdout(contains("12 Excluded"));

        Ok(())
    }

    #[test]
    fn test_exclude_multiple_urls() -> Result<()> {
        let mut cmd = main_command();
        let test_path = fixtures_path().join("TEST.md");

        cmd.arg(test_path)
            .arg("--exclude")
            .arg("https://en.wikipedia.org/*")
            .arg("--exclude")
            .arg("https://ldra.com/")
            .assert()
            .success()
            .stdout(contains("4 Excluded"));

        Ok(())
    }

    #[tokio::test]
    async fn test_empty_config() -> Result<()> {
        let mock_server = mock_server!(StatusCode::OK);
        let config = fixtures_path().join("configs").join("empty.toml");
        let mut cmd = main_command();
        cmd.arg("--config")
            .arg(config)
            .arg("-")
            .write_stdin(mock_server.uri())
            .env_clear()
            .assert()
            .success()
            .stdout(contains("1 Total"))
            .stdout(contains("1 OK"));

        Ok(())
    }

    #[tokio::test]
    async fn test_include_mail_config() -> Result<()> {
        let test_mail_address = "mailto:hello-test@testingabc.io";

        let mut config = NamedTempFile::new()?;
        writeln!(config, "include_mail = false")?;

        let mut cmd = main_command();
        cmd.arg("--config")
            .arg(config.path().to_str().unwrap())
            .arg("-")
            .write_stdin(test_mail_address)
            .env_clear()
            .assert()
            .success()
            .stdout(contains("1 Total"))
            .stdout(contains("1 Excluded"));

        let mut config = NamedTempFile::new()?;
        writeln!(config, "include_mail = true")?;

        let mut cmd = main_command();
        cmd.arg("--config")
            .arg(config.path().to_str().unwrap())
            .arg("-")
            .write_stdin(test_mail_address)
            .env_clear()
            .assert()
            .failure()
            .stdout(contains("1 Total"))
            .stdout(contains("1 Error"));

        Ok(())
    }

    #[tokio::test]
    async fn test_cache_config() -> Result<()> {
        let mock_server = mock_server!(StatusCode::OK);
        let config = fixtures_path().join("configs").join("cache.toml");
        let mut cmd = main_command();
        cmd.arg("--config")
            .arg(config)
            .arg("-")
            .write_stdin(mock_server.uri())
            .env_clear()
            .assert()
            .success()
            .stdout(contains("1 Total"))
            .stdout(contains("1 OK"));

        Ok(())
    }

    #[tokio::test]
    async fn test_invalid_config() {
        let config = fixtures_path().join("configs").join("invalid.toml");
        let mut cmd = main_command();
        cmd.arg("--config")
            .arg(config)
            .arg("-")
            .env_clear()
            .assert()
            .failure()
            .stderr(predicate::str::contains("Cannot load configuration file"))
            .stderr(predicate::str::contains("Failed to parse"))
            .stderr(predicate::str::contains("TOML parse error"))
            .stderr(predicate::str::contains("expected newline"));
    }

    #[tokio::test]
    async fn test_missing_config_error() {
        let mock_server = mock_server!(StatusCode::OK);
        let mut cmd = main_command();
        cmd.arg("--config")
            .arg("config.does.not.exist.toml")
            .arg("-")
            .write_stdin(mock_server.uri())
            .env_clear()
            .assert()
            .failure();
    }

    #[tokio::test]
    async fn test_config_example() {
        let mock_server = mock_server!(StatusCode::OK);
        let config = root_path().join("lychee.example.toml");
        let mut cmd = main_command();
        cmd.arg("--config")
            .arg(config)
            .arg("-")
            .write_stdin(mock_server.uri())
            .env_clear()
            .assert()
            .success();
    }

    #[tokio::test]
    async fn test_config_smoketest() {
        let mock_server = mock_server!(StatusCode::OK);
        let config = fixtures_path().join("configs").join("smoketest.toml");
        let mut cmd = main_command();
        cmd.arg("--config")
            .arg(config)
            .arg("-")
            .write_stdin(mock_server.uri())
            .env_clear()
            .assert()
            .success();
    }

    #[tokio::test]
    async fn test_config_accept() {
        let mock_server = mock_server!(StatusCode::OK);
        let config = fixtures_path().join("configs").join("accept.toml");
        let mut cmd = main_command();
        cmd.arg("--config")
            .arg(config)
            .arg("-")
            .write_stdin(mock_server.uri())
            .env_clear()
            .assert()
            .success();
    }

    #[test]
    fn test_lycheeignore_file() -> Result<()> {
        let mut cmd = main_command();
        let test_path = fixtures_path().join("lycheeignore");

        let cmd = cmd
            .current_dir(test_path)
            .arg("--dump")
            .arg("TEST.md")
            .assert()
            .stdout(contains("https://example.com"))
            .stdout(contains("https://example.com/bar"))
            .stdout(contains("https://example.net"));

        let output = cmd.get_output();
        let output = std::str::from_utf8(&output.stdout).unwrap();
        assert_eq!(output.lines().count(), 3);

        Ok(())
    }

    #[test]
    fn test_lycheeignore_and_exclude_file() -> Result<()> {
        let mut cmd = main_command();
        let test_path = fixtures_path().join("lycheeignore");
        let excludes_path = test_path.join("normal-exclude-file");

        cmd.current_dir(test_path)
            .arg("TEST.md")
            .arg("--exclude-file")
            .arg(excludes_path)
            .assert()
            .success()
            .stdout(contains("8 Total"))
            .stdout(contains("6 Excluded"));

        Ok(())
    }

    #[tokio::test]
    async fn test_lycheecache_file() -> Result<()> {
        let base_path = fixtures_path().join("cache");
        let cache_file = base_path.join(LYCHEE_CACHE_FILE);

        // Unconditionally remove cache file if it exists
        let _ = fs::remove_file(&cache_file);

        let mock_server_ok = mock_server!(StatusCode::OK);
        let mock_server_err = mock_server!(StatusCode::NOT_FOUND);
        let mock_server_exclude = mock_server!(StatusCode::OK);

        let dir = tempfile::tempdir()?;
        let mut file = File::create(dir.path().join("c.md"))?;

        writeln!(file, "{}", mock_server_ok.uri().as_str())?;
        writeln!(file, "{}", mock_server_err.uri().as_str())?;
        writeln!(file, "{}", mock_server_exclude.uri().as_str())?;

        let mut cmd = main_command();
        let test_cmd = cmd
            .current_dir(&base_path)
            .arg(dir.path().join("c.md"))
            .arg("--verbose")
            .arg("--no-progress")
            .arg("--cache")
            .arg("--exclude")
            .arg(mock_server_exclude.uri());

        assert!(
            !cache_file.exists(),
            "cache file should not exist before this test"
        );

        // run first without cache to generate the cache file
        test_cmd
            .assert()
            .stderr(contains(format!("[200] {}/\n", mock_server_ok.uri())))
            .stderr(contains(format!(
                "[404] {}/ | Failed: Network error: Not Found\n",
                mock_server_err.uri()
            )));

        // check content of cache file
        let data = fs::read_to_string(&cache_file)?;
        assert!(data.contains(&format!("{}/,200", mock_server_ok.uri())));
        assert!(data.contains(&format!("{}/,404", mock_server_err.uri())));

        // run again to verify cache behavior
        test_cmd
            .assert()
            .stderr(contains(format!(
                "[200] {}/ | Cached: OK (cached)\n",
                mock_server_ok.uri()
            )))
            .stderr(contains(format!(
                "[404] {}/ | Cached: Error (cached)\n",
                mock_server_err.uri()
            )));

        // clear the cache file
        fs::remove_file(&cache_file)?;

        Ok(())
    }

    #[tokio::test]
    async fn test_lycheecache_accept_custom_status_codes() -> Result<()> {
        let base_path = fixtures_path().join("cache_accept_custom_status_codes");
        let cache_file = base_path.join(LYCHEE_CACHE_FILE);

        // Unconditionally remove cache file if it exists
        let _ = fs::remove_file(&cache_file);

        let mock_server_ok = mock_server!(StatusCode::OK);
        let mock_server_teapot = mock_server!(StatusCode::IM_A_TEAPOT);
        let mock_server_server_error = mock_server!(StatusCode::INTERNAL_SERVER_ERROR);

        let dir = tempfile::tempdir()?;
        let mut file = File::create(dir.path().join("c.md"))?;

        writeln!(file, "{}", mock_server_ok.uri().as_str())?;
        writeln!(file, "{}", mock_server_teapot.uri().as_str())?;
        writeln!(file, "{}", mock_server_server_error.uri().as_str())?;

        let mut cmd = main_command();
        let test_cmd = cmd
            .current_dir(&base_path)
            .arg(dir.path().join("c.md"))
            .arg("--verbose")
            .arg("--cache");

        assert!(
            !cache_file.exists(),
            "cache file should not exist before this test"
        );

        // run first without cache to generate the cache file
        // ignore exit code
        test_cmd
            .assert()
            .failure()
            .code(2)
            .stdout(contains(format!(
                "[418] {}/ | Failed: Network error: I\'m a teapot",
                mock_server_teapot.uri()
            )))
            .stdout(contains(format!(
                "[500] {}/ | Failed: Network error: Internal Server Error",
                mock_server_server_error.uri()
            )));

        // check content of cache file
        let data = fs::read_to_string(&cache_file)?;
        assert!(data.contains(&format!("{}/,200", mock_server_ok.uri())));
        assert!(data.contains(&format!("{}/,418", mock_server_teapot.uri())));
        assert!(data.contains(&format!("{}/,500", mock_server_server_error.uri())));

        // run again to verify cache behavior
        // this time accept 418 and 500 as valid status codes
        test_cmd
            .arg("--no-progress")
            .arg("--accept")
            .arg("418,500")
            .assert()
            .success()
            .stderr(contains(format!(
                "[418] {}/ | Cached: OK (cached)",
                mock_server_teapot.uri()
            )))
            .stderr(contains(format!(
                "[500] {}/ | Cached: OK (cached)",
                mock_server_server_error.uri()
            )));

        // clear the cache file
        fs::remove_file(&cache_file)?;

        Ok(())
    }

    #[tokio::test]
    async fn test_skip_cache_unsupported() -> Result<()> {
        let base_path = fixtures_path().join("cache");
        let cache_file = base_path.join(LYCHEE_CACHE_FILE);

        // Unconditionally remove cache file if it exists
        let _ = fs::remove_file(&cache_file);

        let unsupported_url = "slack://user".to_string();
        let excluded_url = "https://example.com/";

        // run first without cache to generate the cache file
        main_command()
            .current_dir(&base_path)
            .write_stdin(format!("{unsupported_url}\n{excluded_url}"))
            .arg("--cache")
            .arg("--verbose")
            .arg("--no-progress")
            .arg("--exclude")
            .arg(excluded_url)
            .arg("--")
            .arg("-")
            .assert()
            .stderr(contains(format!(
                "[IGNORED] {unsupported_url} | Unsupported: Error creating request client"
            )))
            .stderr(contains(format!("[EXCLUDED] {excluded_url} | Excluded\n")));

        // The cache file should be empty, because the only checked URL is
        // unsupported and we don't want to cache that. It might be supported in
        // future versions.
        let buf = fs::read(&cache_file).unwrap();
        assert!(buf.is_empty());

        // clear the cache file
        fs::remove_file(&cache_file)?;

        Ok(())
    }

    /// Unknown status codes should be skipped and not cached by default
    /// The reason is that we don't know if they are valid or not
    /// and even if they are invalid, we don't know if they will be valid in the
    /// future.
    ///
    /// Since we cannot test this with our mock server (because hyper panics on
    /// invalid status codes) we use LinkedIn as a test target.
    ///
    /// Unfortunately, LinkedIn does not always return 999, so this is a flaky
    /// test. We only check that the cache file doesn't contain any invalid
    /// status codes.
    #[tokio::test]
    async fn test_skip_cache_unknown_status_code() -> Result<()> {
        let base_path = fixtures_path().join("cache");
        let cache_file = base_path.join(LYCHEE_CACHE_FILE);

        // Unconditionally remove cache file if it exists
        let _ = fs::remove_file(&cache_file);

        // https://linkedin.com returns 999 for unknown status codes
        // use this as a test target
        let unknown_url = "https://www.linkedin.com/company/corrode";

        // run first without cache to generate the cache file
        main_command()
            .current_dir(&base_path)
            .write_stdin(unknown_url.to_string())
            .arg("--cache")
            .arg("--verbose")
            .arg("--no-progress")
            .arg("--")
            .arg("-")
            .assert()
            // LinkedIn does not always return 999, so we cannot check for that
            // .stderr(contains(format!("[999] {unknown_url} | Unknown status")))
            ;

        // If the status code was 999, the cache file should be empty
        // because we do not want to cache unknown status codes
        let buf = fs::read(&cache_file).unwrap();
        if !buf.is_empty() {
            let data = String::from_utf8(buf)?;
            // The cache file should not contain any invalid status codes
            // In that case, we expect a single entry with status code 200
            assert!(!data.contains("999"));
            assert!(data.contains("200"));
        }

        // clear the cache file
        fs::remove_file(&cache_file)?;

        Ok(())
    }

    #[test]
    fn test_verbatim_skipped_by_default() -> Result<()> {
        let mut cmd = main_command();
        let input = fixtures_path().join("TEST_CODE_BLOCKS.md");

        cmd.arg(input)
            .arg("--dump")
            .assert()
            .success()
            .stdout(is_empty());

        Ok(())
    }

    #[test]
    fn test_include_verbatim() -> Result<()> {
        let mut cmd = main_command();
        let input = fixtures_path().join("TEST_CODE_BLOCKS.md");

        cmd.arg("--include-verbatim")
            .arg(input)
            .arg("--dump")
            .assert()
            .success()
            .stdout(contains("http://127.0.0.1/block"))
            .stdout(contains("http://127.0.0.1/inline"))
            .stdout(contains("http://127.0.0.1/bash"));

        Ok(())
    }
    #[tokio::test]
    async fn test_verbatim_skipped_by_default_via_file() -> Result<()> {
        let file = fixtures_path().join("TEST_VERBATIM.html");

        main_command()
            .arg("--dump")
            .arg(file)
            .assert()
            .success()
            .stdout(is_empty());

        Ok(())
    }

    #[tokio::test]
    async fn test_verbatim_skipped_by_default_via_remote_url() -> Result<()> {
        let mut cmd = main_command();
        let file = fixtures_path().join("TEST_VERBATIM.html");
        let body = fs::read_to_string(file)?;
        let mock_server = mock_response!(body);

        cmd.arg("--dump")
            .arg(mock_server.uri())
            .assert()
            .success()
            .stdout(is_empty());

        Ok(())
    }

    #[tokio::test]
    async fn test_include_verbatim_via_remote_url() -> Result<()> {
        let mut cmd = main_command();
        let file = fixtures_path().join("TEST_VERBATIM.html");
        let body = fs::read_to_string(file)?;
        let mock_server = mock_response!(body);

        cmd.arg("--include-verbatim")
            .arg("--dump")
            .arg(mock_server.uri())
            .assert()
            .success()
            .stdout(contains("http://www.example.com/pre"))
            .stdout(contains("http://www.example.com/code"))
            .stdout(contains("http://www.example.com/samp"))
            .stdout(contains("http://www.example.com/kbd"))
            .stdout(contains("http://www.example.com/var"))
            .stdout(contains("http://www.example.com/script"));
        Ok(())
    }

    #[test]
    fn test_require_https() -> Result<()> {
        let mut cmd = main_command();
        let test_path = fixtures_path().join("TEST_HTTP.html");
        cmd.arg(&test_path).assert().success();

        let mut cmd = main_command();
        cmd.arg("--require-https").arg(test_path).assert().failure();

        Ok(())
    }

    /// If base-dir is not set, don't throw an error in case we encounter
    /// an absolute local link within a file (e.g. `/about`).
    #[test]
    fn test_ignore_absolute_local_links_without_base() -> Result<()> {
        let mut cmd = main_command();

        let offline_dir = fixtures_path().join("offline");

        cmd.arg("--offline")
            .arg(offline_dir.join("index.html"))
            .env_clear()
            .assert()
            .success()
            .stdout(contains("0 Total"));

        Ok(())
    }

    #[test]
    fn test_inputs_without_scheme() -> Result<()> {
        let test_path = fixtures_path().join("TEST_HTTP.html");
        let mut cmd = main_command();

        cmd.arg("--dump")
            .arg("example.com")
            .arg(&test_path)
            .arg("https://example.org")
            .assert()
            .success();
        Ok(())
    }

    #[test]
    fn test_print_excluded_links_in_verbose_mode() -> Result<()> {
        let test_path = fixtures_path().join("TEST_DUMP_EXCLUDE.txt");
        let mut cmd = main_command();

        cmd.arg("--dump")
            .arg("--verbose")
            .arg("--exclude")
            .arg("example.com")
            .arg("--")
            .arg(&test_path)
            .assert()
            .success()
            .stdout(contains(format!(
                "https://example.com/ ({}) [excluded]",
                test_path.display()
            )))
            .stdout(contains(format!(
                "https://example.org/ ({})",
                test_path.display()
            )))
            .stdout(contains(format!(
                "https://example.com/foo/bar ({}) [excluded]",
                test_path.display()
            )));
        Ok(())
    }

    #[test]
    fn test_remap_uri() -> Result<()> {
        let mut cmd = main_command();

        cmd.arg("--dump")
            .arg("--remap")
            .arg("https://example.com http://127.0.0.1:8080")
            .arg("--remap")
            .arg("https://example.org https://staging.example.com")
            .arg("--")
            .arg("-")
            .write_stdin("https://example.com\nhttps://example.org\nhttps://example.net\n")
            .env_clear()
            .assert()
            .success()
            .stdout(contains("http://127.0.0.1:8080/"))
            .stdout(contains("https://staging.example.com/"))
            .stdout(contains("https://example.net/"));

        Ok(())
    }

    #[test]
    #[ignore = "Skipping test until https://github.com/robinst/linkify/pull/58 is merged"]
    fn test_remap_path() -> Result<()> {
        let mut cmd = main_command();

        cmd.arg("--dump")
            .arg("--remap")
            .arg("../../issues https://github.com/usnistgov/OSCAL/issues")
            .arg("--")
            .arg("-")
            .write_stdin("../../issues\n")
            .env_clear()
            .assert()
            .success()
            .stdout(contains("https://github.com/usnistgov/OSCAL/issues"));

        Ok(())
    }

    #[test]
    fn test_remap_capture() -> Result<()> {
        let mut cmd = main_command();

        cmd.arg("--dump")
            .arg("--remap")
            .arg("https://example.com/(.*) http://example.org/$1")
            .arg("--")
            .arg("-")
            .write_stdin("https://example.com/foo\n")
            .env_clear()
            .assert()
            .success()
            .stdout(contains("http://example.org/foo"));

        Ok(())
    }

    #[test]
    fn test_remap_named_capture() -> Result<()> {
        let mut cmd = main_command();

        cmd.arg("--dump")
            .arg("--remap")
            .arg("https://github.com/(?P<org>.*)/(?P<repo>.*) https://gitlab.com/$org/$repo")
            .arg("--")
            .arg("-")
            .write_stdin("https://github.com/lycheeverse/lychee\n")
            .env_clear()
            .assert()
            .success()
            .stdout(contains("https://gitlab.com/lycheeverse/lychee"));

        Ok(())
    }

    #[test]
    fn test_excluded_paths() -> Result<()> {
        let test_path = fixtures_path().join("exclude-path");

        let excluded_path1 = test_path.join("dir1");
        let excluded_path2 = test_path.join("dir2").join("subdir");
        let mut cmd = main_command();

        cmd.arg("--exclude-path")
            .arg(&excluded_path1)
            .arg("--exclude-path")
            .arg(&excluded_path2)
            .arg("--")
            .arg(&test_path)
            .assert()
            .success()
            // Links in excluded files are not taken into account in the total
            // number of links.
            .stdout(contains("1 Total"))
            .stdout(contains("1 OK"));

        Ok(())
    }

    #[test]
    fn test_handle_relative_paths_as_input() -> Result<()> {
        let test_path = fixtures_path();
        let mut cmd = main_command();

        cmd.current_dir(&test_path)
            .arg("--verbose")
            .arg("--exclude")
            .arg("example.*")
            .arg("--")
            .arg("./TEST_DUMP_EXCLUDE.txt")
            .assert()
            .success()
            .stdout(contains("3 Total"))
            .stdout(contains("3 Excluded"));

        Ok(())
    }

    #[test]
    fn test_handle_nonexistent_relative_paths_as_input() -> Result<()> {
        let test_path = fixtures_path();
        let mut cmd = main_command();

        cmd.current_dir(&test_path)
            .arg("--verbose")
            .arg("--exclude")
            .arg("example.*")
            .arg("--")
            .arg("./NOT-A-REAL-TEST-FIXTURE.md")
            .assert()
            .failure()
            .stderr(contains(
                "Cannot find local file ./NOT-A-REAL-TEST-FIXTURE.md",
            ));

        Ok(())
    }

    #[test]
    fn test_prevent_too_many_redirects() -> Result<()> {
        let mut cmd = main_command();
        let url = "https://httpstat.us/308";

        cmd.write_stdin(url)
            .arg("--max-redirects")
            .arg("0")
            .arg("-")
            .assert()
            .failure();

        Ok(())
    }

    #[test]
    #[ignore = "Skipping test because it is flaky"]
    fn test_suggests_url_alternatives() -> Result<()> {
        for _ in 0..3 {
            // This can be flaky. Try up to 3 times
            let mut cmd = main_command();
            let input = fixtures_path().join("INTERNET_ARCHIVE.md");

            cmd.arg("--no-progress").arg("--suggest").arg(input);

            // Run he command and check if the output contains the expected
            // suggestions
            let assert = cmd.assert();
            let output = assert.get_output();

            // We're looking for a suggestion that
            // - starts with http://web.archive.org/web/
            // - ends with google.com/jobs.html
            let re = Regex::new(r"http://web\.archive\.org/web/.*google\.com/jobs\.html").unwrap();
            if re.is_match(&String::from_utf8_lossy(&output.stdout)) {
                // Test passed
                return Ok(());
            } else {
                // Wait for a second before retrying
                std::thread::sleep(std::time::Duration::from_secs(1));
            }
        }

        // If we reached here, it means the test did not pass after multiple attempts
        Err("Did not get the expected command output after multiple attempts.".into())
    }

    #[tokio::test]
    async fn test_basic_auth() -> Result<()> {
        let username = "username";
        let password = "password123";

        let mock_server = wiremock::MockServer::start().await;
        Mock::given(basic_auth(username, password))
            .respond_with(ResponseTemplate::new(200))
            .mount(&mock_server)
            .await;

        // Configure the command to use the BasicAuthExtractor
        main_command()
            .arg("--verbose")
            .arg("--basic-auth")
            .arg(format!("{} {username}:{password}", mock_server.uri()))
            .arg("-")
            .write_stdin(mock_server.uri())
            .assert()
            .success()
            .stdout(contains("1 Total"))
            .stdout(contains("1 OK"));

        Ok(())
    }

    #[tokio::test]
    async fn test_multi_basic_auth() -> Result<()> {
        let username1 = "username";
        let password1 = "password123";
        let mock_server1 = wiremock::MockServer::start().await;
        Mock::given(basic_auth(username1, password1))
            .respond_with(ResponseTemplate::new(200))
            .mount(&mock_server1)
            .await;

        let username2 = "admin_user";
        let password2 = "admin_pw";
        let mock_server2 = wiremock::MockServer::start().await;

        Mock::given(basic_auth(username2, password2))
            .respond_with(ResponseTemplate::new(200))
            .mount(&mock_server2)
            .await;

        // Configure the command to use the BasicAuthExtractor
        main_command()
            .arg("--verbose")
            .arg("--basic-auth")
            .arg(format!("{} {username1}:{password1}", mock_server1.uri()))
            .arg("--basic-auth")
            .arg(format!("{} {username2}:{password2}", mock_server2.uri()))
            .arg("-")
            .write_stdin(format!("{}\n{}", mock_server1.uri(), mock_server2.uri()))
            .assert()
            .success()
            .stdout(contains("2 Total"))
            .stdout(contains("2 OK"));

        Ok(())
    }

    #[tokio::test]
    async fn test_cookie_jar() -> Result<()> {
        // Create a random cookie jar file
        let cookie_jar = NamedTempFile::new()?;

        let mut cmd = main_command();
        cmd.arg("--cookie-jar")
            .arg(cookie_jar.path().to_str().unwrap())
            .arg("-")
            // Using Google as a test target because I couldn't
            // get the mock server to work with the cookie jar
            .write_stdin("https://google.com/ncr")
            .assert()
            .success();

        // check that the cookie jar file contains the expected cookies
        let file = std::fs::File::open(cookie_jar.path()).map(std::io::BufReader::new)?;
        let cookie_store = reqwest_cookie_store::CookieStore::load_json(file).unwrap();
        let all_cookies = cookie_store.iter_any().collect::<Vec<_>>();

        assert!(!all_cookies.is_empty());
        assert!(all_cookies.iter().all(|c| c.domain() == Some("google.com")));

        Ok(())
    }

    #[test]
    fn test_dump_inputs_glob_md() -> Result<()> {
        let pattern = fixtures_path().join("**/*.md");

        let mut cmd = main_command();
        cmd.arg("--dump-inputs")
            .arg(pattern)
            .assert()
            .success()
            .stdout(contains("fixtures/dump_inputs/subfolder/file2.md"))
            .stdout(contains("fixtures/dump_inputs/markdown.md"));

        Ok(())
    }

    #[test]
    fn test_dump_inputs_glob_all() -> Result<()> {
        let pattern = fixtures_path().join("**/*");

        let mut cmd = main_command();
        cmd.arg("--dump-inputs")
            .arg(pattern)
            .assert()
            .success()
            .stdout(contains("fixtures/dump_inputs/subfolder/test.html"))
            .stdout(contains("fixtures/dump_inputs/subfolder/file2.md"))
            .stdout(contains("fixtures/dump_inputs/subfolder"))
            .stdout(contains("fixtures/dump_inputs/markdown.md"))
            .stdout(contains("fixtures/dump_inputs/subfolder/example.bin"))
            .stdout(contains("fixtures/dump_inputs/some_file.txt"));

        Ok(())
    }

    #[test]
    fn test_dump_inputs_url() -> Result<()> {
        let mut cmd = main_command();
        cmd.arg("--dump-inputs")
            .arg("https://example.com")
            .assert()
            .success()
            .stdout(contains("https://example.com"));

        Ok(())
    }

    #[test]
    fn test_dump_inputs_path() -> Result<()> {
        let mut cmd = main_command();
        cmd.arg("--dump-inputs")
            .arg("fixtures")
            .assert()
            .success()
            .stdout(contains("fixtures"));

        Ok(())
    }

    #[test]
    fn test_dump_inputs_stdin() -> Result<()> {
        let mut cmd = main_command();
        cmd.arg("--dump-inputs")
            .arg("-")
            .assert()
            .success()
            .stdout(contains("Stdin"));

        Ok(())
    }

    #[test]
    fn test_fragments() {
        let mut cmd = main_command();
        let input = fixtures_path().join("fragments");

        cmd.arg("--verbose")
            .arg("--include-fragments")
            .arg(input)
            .assert()
            .failure()
            .stderr(contains("fixtures/fragments/file1.md#fragment-1"))
            .stderr(contains("fixtures/fragments/file1.md#fragment-2"))
            .stderr(contains("fixtures/fragments/file1.md#code-heading"))
            .stderr(contains("fixtures/fragments/file2.md#custom-id"))
            .stderr(contains("fixtures/fragments/file1.md#missing-fragment"))
            .stderr(contains("fixtures/fragments/file2.md#fragment-1"))
            .stderr(contains("fixtures/fragments/file1.md#kebab-case-fragment"))
            .stderr(contains(
                "fixtures/fragments/file1.md#lets-wear-a-hat-%C3%AAtre",
            ))
            .stderr(contains("fixtures/fragments/file2.md#missing-fragment"))
            .stderr(contains("fixtures/fragments/empty_file#fragment"))
            .stderr(contains("fixtures/fragments/file.html#a-word"))
            .stderr(contains("fixtures/fragments/file.html#in-the-beginning"))
            .stderr(contains("fixtures/fragments/file.html#in-the-end"))
            .stderr(contains(
                "fixtures/fragments/file1.md#kebab-case-fragment-1",
            ))
            .stdout(contains("15 Total"))
            .stdout(contains("12 OK"))
            // 3 failures because of missing fragments
            .stdout(contains("3 Errors"));
    }

    #[test]
    fn test_fallback_extensions() {
        let mut cmd = main_command();
        let input = fixtures_path().join("fallback-extensions");

        cmd.arg("--verbose")
            .arg("--fallback-extensions=htm,html")
            .arg(input)
            .assert()
            .success()
            .stdout(contains("0 Errors"));
    }
}