reserve 0.5.1

Check domain name availability across grouped extensions, straight from the registry
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
//! End-to-end checks that run the built binary and read stdout, stderr, and the exit code together.

#![allow(
    clippy::expect_used,
    reason = "clippy.toml exempts test modules, and an integration test is a separate crate it cannot reach"
)]

use assert_cmd::Command;
use predicates::prelude::*;

/// @docgen Every test here must answer offline, so only the subcommands that never open a socket are exercised.
fn reserve() -> Command {
    let mut command = Command::cargo_bin("reserve").expect("the binary is built for the test run");
    command.env_remove("RESERVE_CONCURRENCY");
    command.env_remove("RESERVE_TIMEOUT");
    command.env_remove("RESERVE_WIDTH");
    command.env_remove("RESERVE_NO_INPUT");
    // @docgen An exported COLUMNS or TERM would quietly hand the test a different renderer than the one CI runs.
    command.env_remove("COLUMNS");
    command.env_remove("LINES");
    command.env("TERM", "xterm-256color");
    command.env("NO_COLOR", "1");
    // @docgen These decide whether the run thinks it is on a build agent, so leaving them read gives one answer here and another in CI.
    for marker in [
        "CI",
        "GITHUB_ACTIONS",
        "CONTINUOUS_INTEGRATION",
        "GITLAB_CI",
        "BUILDKITE",
        "TEAMCITY_VERSION",
        "TF_BUILD",
    ] {
        command.env_remove(marker);
    }
    for forced in ["FORCE_COLOR", "CLICOLOR", "CLICOLOR_FORCE", "RUST_LOG"] {
        command.env_remove(forced);
    }
    for proxy in ["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"] {
        command.env_remove(proxy);
    }
    // @docgen Otherwise `doctor` and `config path` resolve the developer's own directories, and a cached list could be written there.
    let home = home_for_tests();
    command.env("HOME", &home);
    command.env("XDG_CONFIG_HOME", home.join("config"));
    command.env("XDG_CACHE_HOME", home.join("cache"));
    command.env("XDG_DATA_HOME", home.join("data"));
    // @docgen Windows reads none of the four above, so without these the isolation is silently nothing there.
    command.env("USERPROFILE", &home);
    command.env("APPDATA", home.join("config"));
    command.env("LOCALAPPDATA", home.join("cache"));
    command.current_dir(&home);
    command
}

/// @docgen One directory for the whole run, kept alive for the process, so no test reads or writes the real home.
fn home_for_tests() -> std::path::PathBuf {
    use std::sync::OnceLock;
    static HOME: OnceLock<tempfile::TempDir> = OnceLock::new();
    HOME.get_or_init(|| tempfile::tempdir().expect("a temporary home"))
        .path()
        .to_path_buf()
}

#[test]
fn help_goes_to_stdout_and_exits_zero() {
    reserve()
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("Check one or more names"))
        .stdout(predicate::str::contains("EXAMPLES:"));
}

#[test]
fn version_goes_to_stdout_and_exits_zero() {
    reserve()
        .arg("--version")
        .assert()
        .success()
        .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION")));
}

#[test]
fn every_subcommand_answers_its_own_help() {
    for command in ["groups", "extensions", "config", "doctor", "completions"] {
        reserve().args([command, "--help"]).assert().success();
    }
}

#[test]
fn an_unknown_flag_is_a_usage_error() {
    reserve()
        .arg("--not-a-real-flag")
        .assert()
        .code(2)
        .stderr(predicate::str::contains("--not-a-real-flag"));
}

#[test]
fn a_missing_name_is_refused_before_any_lookup_starts() {
    reserve()
        .assert()
        .code(2)
        .stderr(predicate::str::contains("name.list_empty"));
}

#[test]
fn an_unattended_run_never_waits_for_an_answer() {
    // A prompt belongs to a person at a terminal. Everywhere else the run must
    // fail fast rather than hang forever waiting for input that cannot arrive.
    for extra in [vec!["--no-input"], vec!["--json"], vec![]] {
        let mut command = reserve();
        command.args(&extra);
        command
            .timeout(std::time::Duration::from_secs(20))
            .assert()
            .code(2)
            .stderr(predicate::str::contains("name.list_empty"));
    }

    reserve()
        .env("CI", "true")
        .timeout(std::time::Duration::from_secs(20))
        .assert()
        .code(2)
        .stderr(predicate::str::contains("name.list_empty"));
}

#[test]
fn conflicting_flags_are_refused_by_the_parser() {
    reserve()
        .args(["--no-input", "--interactive", "example"])
        .assert()
        .code(2);
}

#[test]
fn an_unknown_group_names_the_value_and_carries_its_error_id() {
    reserve()
        .args(["extensions", "--group", "definitely-not-a-group"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("group.unknown"));
}

#[test]
fn the_machine_readable_mode_emits_one_json_document_on_stdout() {
    let output = reserve()
        .args(["groups", "--json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let parsed: serde_json::Value =
        serde_json::from_slice(&output).expect("the json mode emits one complete document");
    assert!(
        parsed.as_array().is_some_and(|rows| !rows.is_empty()),
        "the group listing is a non-empty array"
    );
}

#[test]
fn a_piped_run_carries_no_escape_codes_and_no_progress_line() {
    let output = reserve()
        .args(["extensions", "--group", "popular"])
        .assert()
        .success()
        .get_output()
        .clone();

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        !stdout.contains('\u{1b}'),
        "piped output must stay parseable, with no styling"
    );
    assert!(
        !output.stderr.contains(&b'\r'),
        "the progress line must never render when stderr is not a terminal"
    );
}

#[test]
fn the_boolean_environment_fallback_accepts_how_a_script_spells_true() {
    for spelling in ["1", "true", "yes", "on"] {
        reserve()
            .env("RESERVE_NO_INPUT", spelling)
            .args(["groups"])
            .assert()
            .success();
    }
}

#[test]
fn the_completion_script_is_written_for_every_shell_offered() {
    for shell in ["bash", "elvish", "fish", "powershell", "zsh"] {
        reserve()
            .args(["completions", shell])
            .assert()
            .success()
            .stdout(predicate::str::contains("reserve"));
    }
}

#[test]
fn the_diagnostic_command_reports_in_both_forms() {
    reserve().arg("doctor").assert().success();

    let output = reserve()
        .args(["doctor", "--json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let parsed: serde_json::Value =
        serde_json::from_slice(&output).expect("the diagnostic json mode parses");
    assert!(parsed.get("version").is_some(), "the build is identified");
}

#[test]
fn the_resolved_settings_are_reported_with_where_each_came_from() {
    reserve()
        .args(["config", "show"])
        .assert()
        .success()
        .stdout(predicate::str::contains("timeout"))
        .stdout(predicate::str::contains("built-in default"));

    // A value that came from the environment must not be reported as a default.
    reserve()
        .env("RESERVE_TIMEOUT", "60")
        .args(["config", "show"])
        .assert()
        .success()
        .stdout(predicate::str::contains("60"))
        .stdout(predicate::str::contains("environment"));

    // And one that came from the command line must say so. Only the global
    // flags reach a subcommand, so width is the one to check here.
    reserve()
        .args(["config", "show", "--width", "100"])
        .assert()
        .success()
        .stdout(predicate::str::contains("100"))
        .stdout(predicate::str::contains("flag"));

    reserve().args(["config", "path"]).assert().success();
}

#[test]
fn the_diagnostic_names_where_the_registry_list_comes_from() {
    reserve()
        .arg("doctor")
        .assert()
        .success()
        .stdout(predicate::str::contains("Network"))
        .stdout(predicate::str::contains("data.iana.org"));

    let output = reserve()
        .args(["doctor", "--json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let parsed: serde_json::Value =
        serde_json::from_slice(&output).expect("the diagnostic json mode parses");
    assert!(
        parsed.get("network").is_some(),
        "the json form carries the network block the help promises"
    );
    assert!(
        parsed.get("paths").is_some(),
        "the json form carries the paths the text form prints"
    );
}

#[test]
fn append_cannot_start_a_write_on_its_own() {
    reserve()
        .args(["--append", "example", "--tld", "com"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("append"));
}

#[test]
fn cautious_composes_with_a_pacing_flag_instead_of_refusing_it() {
    reserve()
        .args(["extensions", "--group", "popular"])
        .env("RESERVE_CONCURRENCY", "8")
        .assert()
        .success();
}

#[test]
fn a_setting_reports_the_source_that_really_supplied_it() {
    reserve()
        .env("RESERVE_TIMEOUT", "45")
        .args(["config", "show"])
        .assert()
        .success()
        .stdout(predicate::str::contains("45").and(predicate::str::contains("environment")));

    reserve()
        .env("RESERVE_TIMEOUT", "45")
        .args(["--timeout", "7", "config", "show"])
        .assert()
        .success()
        .stdout(predicate::str::contains("7").and(predicate::str::contains("flag")));
}

#[test]
fn an_exported_preference_never_stands_in_for_a_flag() {
    reserve()
        .env("RESERVE_NO_INPUT", "1")
        .args(["--interactive", "groups"])
        .assert()
        .success();
}

#[test]
fn the_machine_readable_flag_reaches_a_subcommand_from_either_side() {
    for argv in [
        vec!["--json", "groups"],
        vec!["groups", "--json"],
        vec!["--json", "doctor"],
        vec!["doctor", "--json"],
        vec!["--json", "config", "show"],
        vec!["config", "show", "--json"],
    ] {
        let output = reserve()
            .args(&argv)
            .assert()
            .success()
            .get_output()
            .clone();
        let stdout = String::from_utf8_lossy(&output.stdout);
        let first = stdout.trim_start().chars().next().unwrap_or(' ');
        assert!(
            first == '[' || first == '{',
            "{argv:?} did not produce JSON, it produced: {}",
            stdout.lines().next().unwrap_or_default()
        );
    }
}

#[test]
fn a_page_past_the_end_never_counts_backwards() {
    let output = reserve()
        .args(["extensions", "--group", "classic", "--page", "9"])
        .assert()
        .success()
        .get_output()
        .clone();
    let stdout = String::from_utf8_lossy(&output.stdout);
    let footer = stdout
        .lines()
        .find(|line| line.contains("extensions ·"))
        .unwrap_or_default();
    let range = footer.split_whitespace().next().unwrap_or_default();
    let (first, last) = range.split_once('-').unwrap_or(("0", "0"));
    let first: usize = first.parse().unwrap_or(0);
    let last: usize = last.parse().unwrap_or(0);
    assert!(
        first <= last,
        "the footer read `{range}`, which counts backwards"
    );
}

#[test]
fn a_byte_order_mark_does_not_make_the_first_name_look_reshaped() {
    let dir = tempfile::tempdir().expect("a temporary directory");
    let list = dir.path().join("names.txt");
    std::fs::write(&list, "\u{feff}example\n").expect("the list is written");

    reserve()
        .args(["--names-from"])
        .arg(&list)
        .args(["extensions", "--group", "classic"])
        .assert()
        .success()
        .stderr(predicate::str::contains("is not a name a registry can hold").not());
}

#[test]
fn a_bad_selection_flag_is_refused_whether_or_not_the_target_carries_a_dot() {
    for target in ["shop", "shop.com"] {
        reserve()
            .args([target, "--group", "definitely-not-a-group", "--no-input"])
            .assert()
            .code(2)
            .stderr(predicate::str::contains("group.unknown"));
    }
}

/// @docgen Every flag is run through the built binary, because parsing a flag and honouring it are different things.
const OFFLINE_FLAGS: &[&[&str]] = &[
    &["--group", "popular"],
    &["--tld", "com,net"],
    &["--exclude", "com"],
    &[
        "--group",
        "everything",
        "--search",
        "bank",
        "--include-restricted",
    ],
    &["--industry", "finance"],
    &["--region", "south-asia"],
    &["--cctld"],
    &["--depth", "second"],
    &["--group", "everything", "--depth", "third"],
    &["--length", "2-3"],
    &["--include-restricted"],
    &["--sort", "name"],
    &["--sort", "popularity"],
    &["--sort", "length"],
    &["--sort", "name", "--order", "asc"],
    &["--sort", "name", "--order", "desc"],
    &["--page", "2"],
    &["--page-size", "5"],
    &["--all-pages"],
    &["--json"],
    &["--color", "never"],
    &["--color", "always"],
    &["--width", "60"],
    &["--no-input"],
    &["-v"],
    &["-q"],
];

#[test]
fn every_offline_flag_is_honoured_by_the_built_binary() {
    for flag in OFFLINE_FLAGS {
        let mut argv = vec!["extensions"];
        argv.extend_from_slice(flag);
        let outcome = reserve().args(&argv).output().expect("the binary runs");
        assert!(
            outcome.status.success(),
            "`reserve {}` failed: {}",
            argv.join(" "),
            String::from_utf8_lossy(&outcome.stderr)
        );
        assert!(
            !outcome.stdout.is_empty(),
            "`reserve {}` produced nothing",
            argv.join(" ")
        );
    }
}

#[test]
fn a_flag_before_the_subcommand_and_one_after_it_are_both_honoured() {
    // @docgen The nesting seam is where a flag was silently dropped, so both halves are exercised together.
    let both = reserve()
        .args([
            "--group",
            "everything",
            "extensions",
            "--cctld",
            "--sort",
            "name",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let after_only = reserve()
        .args([
            "extensions",
            "--group",
            "everything",
            "--cctld",
            "--sort",
            "name",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert_eq!(
        String::from_utf8_lossy(&both),
        String::from_utf8_lossy(&after_only),
        "a flag before the subcommand must reach it exactly as one after it does"
    );
}

#[test]
fn a_flag_given_on_both_sides_of_the_subcommand_lets_the_nearer_one_win() {
    let output = reserve()
        .args([
            "--sort",
            "popularity",
            "extensions",
            "--sort",
            "name",
            "--group",
            "classic",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rendered = String::from_utf8_lossy(&output);
    let first = rendered.lines().nth(1).unwrap_or_default();
    assert!(
        first.starts_with("biz"),
        "the flag nearer the subcommand decides, so this should be alphabetical: {first}"
    );
}

#[test]
fn a_directory_that_cannot_be_written_reports_the_io_class() {
    // @docgen A file where a directory has to go fails the same way on every platform, and fails before any lookup.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let blocked = dir.path().join("not-a-directory");
    std::fs::write(&blocked, "").expect("a plain file sits where the directory would go");

    reserve()
        .args(["example", "--tld", "com", "--no-input", "--out"])
        .arg(blocked.join("results"))
        .assert()
        .code(5)
        .stderr(predicate::str::contains("output.unwritable"));
}

#[test]
fn a_dry_run_asked_for_json_answers_in_json_and_names_the_file_already_there() {
    let dir = tempfile::tempdir().expect("a temporary directory");
    // @docgen `--json` saves JSON too, so the file the run would meet carries that extension.
    std::fs::write(dir.path().join("example-unknown.json"), "").expect("an earlier run's file");

    let run = reserve()
        .args([
            "example",
            "--tld",
            "com,net",
            "--dry-run",
            "--json",
            "--no-input",
            "--out",
        ])
        .arg(dir.path())
        .assert()
        .success();
    let body = String::from_utf8(run.get_output().stdout.clone()).expect("utf-8 on stdout");

    let plan: serde_json::Value = serde_json::from_str(&body).expect("--json must answer in JSON");
    assert_eq!(plan["lookups"], 2);
    assert_eq!(plan["names"][0], "example");
    assert_eq!(plan["asked_any_registry"], false);
    assert_eq!(
        plan["writes"].as_array().expect("a list of files").len(),
        3,
        "all three result files are named"
    );
    assert_eq!(
        plan["already_there"]
            .as_array()
            .expect("a list of files")
            .len(),
        1,
        "the file left by the earlier run is called out"
    );
}

#[test]
fn every_subcommand_that_prints_data_answers_in_json_both_ways() {
    for argv in [
        vec!["groups", "--json"],
        vec!["--json", "groups"],
        vec!["extensions", "--json"],
        vec!["--json", "extensions"],
        vec!["config", "show", "--json"],
        vec!["--json", "config", "show"],
        vec!["config", "path", "--json"],
        vec!["--json", "config", "path"],
    ] {
        let run = reserve().args(&argv).assert().success();
        let body = run.get_output().stdout.clone();
        serde_json::from_slice::<serde_json::Value>(&body)
            .unwrap_or_else(|_| panic!("{argv:?} must answer in JSON"));
    }
}

#[test]
fn an_extension_list_read_from_standard_input_reaches_the_run() {
    let planned = reserve()
        .args([
            "example",
            "--tlds-from",
            "-",
            "--no-input",
            "--dry-run",
            "--json",
        ])
        .write_stdin("io\ndev\n# a comment\n\n")
        .assert()
        .success();
    let plan: serde_json::Value =
        serde_json::from_slice(&planned.get_output().stdout).expect("a JSON plan");
    let extensions: Vec<&str> = plan["extensions"]
        .as_array()
        .expect("a list")
        .iter()
        .map(|value| value.as_str().expect("a string"))
        .collect();
    assert_eq!(extensions, ["io", "dev"], "the list is read once and used");
    assert_eq!(plan["lookups"], 2);
}

#[test]
fn a_flag_typed_after_a_subcommand_beats_the_same_flag_typed_before_it() {
    // @docgen The value alone cannot say this, because the flag typed below may carry the very value that is also the default.
    let run = reserve()
        .args([
            "--sort",
            "name",
            "extensions",
            "--json",
            "--all-pages",
            "--sort",
            "popularity",
        ])
        .assert()
        .success();
    let listed: serde_json::Value =
        serde_json::from_slice(&run.get_output().stdout).expect("a JSON array");
    let first = listed[0]["suffix"].as_str().expect("a suffix");
    assert_eq!(
        first, "com",
        "the sort typed after the subcommand decides the order"
    );
}

#[test]
fn a_directory_that_cannot_be_written_is_refused_before_the_sweep_even_with_append() {
    let dir = tempfile::tempdir().expect("a temporary directory");
    let blocked = dir.path().join("not-a-directory");
    std::fs::write(&blocked, "").expect("a plain file sits where the directory would go");

    // @docgen Appending skips the occupancy refusal, and it used to skip the directory proof with it.
    // The unreadable server list fails inside the engine, so it says which of the two ran first.
    for extra in [vec!["--append"], Vec::new()] {
        let mut argv = vec![
            "example",
            "--tld",
            "com",
            "--no-input",
            "--registry-servers",
            "/nonexistent/servers.json",
        ];
        argv.extend(extra.iter().copied());
        argv.push("--out");
        reserve()
            .args(&argv)
            .arg(blocked.join("results"))
            .assert()
            .code(5)
            .stderr(predicate::str::contains("output.unwritable"))
            .stderr(predicate::str::contains("file.unreadable").not());
    }
}

#[cfg(unix)]
#[test]
fn a_directory_that_exists_but_cannot_be_written_is_refused_before_the_sweep() {
    use std::os::unix::fs::PermissionsExt;

    let dir = tempfile::tempdir().expect("a temporary directory");
    let out = dir.path().join("readonly");
    std::fs::create_dir(&out).expect("the directory is made");
    std::fs::set_permissions(&out, std::fs::Permissions::from_mode(0o555))
        .expect("it is made read-only");

    // @docgen Existing is not the same as writable, and finding that out after the sweep costs every lookup.
    let run = reserve()
        .args([
            "example",
            "--tld",
            "com",
            "--no-input",
            "--registry-servers",
            "/nonexistent/servers.json",
            "--out",
        ])
        .arg(&out)
        .assert()
        .code(5);
    let complaint = String::from_utf8(run.get_output().stderr.clone()).expect("utf-8");
    assert!(
        complaint.contains("output.unwritable"),
        "a read-only directory has to be refused before the engine is built: {complaint}"
    );

    let _ = std::fs::set_permissions(&out, std::fs::Permissions::from_mode(0o755));
}

#[test]
fn a_results_directory_the_tool_makes_is_for_its_owner_only() {
    let dir = tempfile::tempdir().expect("a temporary directory");
    let out = dir.path().join("results");

    reserve()
        .args([
            "example",
            "--tld",
            "com",
            "--no-input",
            "--dry-run",
            "--out",
        ])
        .arg(&out)
        .assert()
        .success();
    assert!(!out.exists(), "a dry run must not create anything");

    reserve()
        .args([
            "example",
            "--tld",
            "com",
            "--no-input",
            "--registry-servers",
            "/nonexistent/servers.json",
            "--out",
        ])
        .arg(&out)
        // @docgen The unreadable server list stops the run inside the engine, which is after the directory was proved.
        .assert()
        .code(2);
    assert!(
        out.is_dir(),
        "the real run proves the directory before it reaches the network"
    );

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(&out)
            .expect("it is there")
            .permissions()
            .mode();
        assert_eq!(
            mode & 0o077,
            0,
            "the file names alone say what was searched for, so nobody else may read them"
        );
    }
}

#[test]
fn something_that_is_not_a_file_in_the_way_is_not_offered_a_merge() {
    let dir = tempfile::tempdir().expect("a temporary directory");
    std::fs::create_dir(dir.path().join("example-available.txt")).expect("a directory in the way");

    reserve()
        .args(["example", "--tld", "com", "--no-input", "--out"])
        .arg(dir.path())
        .assert()
        .code(5)
        .stderr(predicate::str::contains("not a plain file"))
        .stderr(predicate::str::contains("--append").not());
}

#[test]
fn the_screen_format_and_the_file_format_can_be_chosen_apart() {
    let dir = tempfile::tempdir().expect("a temporary directory");

    let planned = reserve()
        .args([
            "example",
            "--tld",
            "com",
            "--no-input",
            "--dry-run",
            "--save-json",
            "--out",
        ])
        .arg(dir.path())
        .assert()
        .success();
    let text = String::from_utf8(planned.get_output().stdout.clone()).expect("utf-8");
    assert!(
        text.contains("Dry run"),
        "--save-json must leave the screen as a table"
    );
    assert!(
        text.contains("example-available.json"),
        "and it must decide the file format: {text}"
    );

    reserve()
        .args(["example", "--tld", "com", "--no-input", "--save-json"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("--out"));
}

#[test]
fn a_shell_window_size_does_not_reach_a_pipe() {
    // @docgen A shell exports COLUMNS for its own window, and letting it cut piped values would corrupt them for a script.
    let narrow = reserve()
        .env("COLUMNS", "30")
        .args(["extensions", "--page-size", "3"])
        .assert()
        .success();
    let body = String::from_utf8(narrow.get_output().stdout.clone()).expect("utf-8");
    assert!(
        !body.contains('\u{2026}'),
        "a value was cut for a reader that is not a terminal:\n{body}"
    );

    let asked = reserve()
        .args(["extensions", "--page-size", "3", "--width", "30"])
        .assert()
        .success();
    let body = String::from_utf8(asked.get_output().stdout.clone()).expect("utf-8");
    for line in body.lines() {
        assert!(
            line.chars().count() <= 30,
            "--width is what the reader asked for, so it still applies: {line}"
        );
    }
}

#[test]
fn a_name_or_a_group_key_quoted_back_carries_no_escape_and_no_reversing_mark() {
    // @docgen These reach the terminal in an error message, so a list from someone else must not be able to steer it.
    for argv in [
        vec!["--group", "te\u{202e}ch\u{1b}[2K", "example", "--no-input"],
        vec!["--tld", "te\u{202e}ch\u{1b}[2K", "example", "--no-input"],
        vec!["\u{202e}bad\u{1b}[2Kname", "--tld", "com", "--no-input"],
        vec![
            "--industry",
            "no\u{202e}pe\u{1b}[2K",
            "example",
            "--no-input",
        ],
        vec!["--region", "no\u{202e}pe\u{1b}[2K", "example", "--no-input"],
    ] {
        let run = reserve().args(&argv).assert().failure();
        let complaint = String::from_utf8(run.get_output().stderr.clone()).expect("utf-8");
        // @docgen `[2K` on its own is ordinary text; it is the escape in front of it that makes a terminal act on it.
        assert!(
            !complaint.contains('\u{202e}'),
            "{argv:?} echoed a mark that reverses the line: {complaint:?}"
        );
        assert!(
            !complaint.contains('\u{1b}'),
            "{argv:?} echoed an escape the terminal would act on: {complaint:?}"
        );
    }
}

#[test]
fn a_setting_the_run_would_clamp_is_reported_clamped() {
    // @docgen These two commands exist to say what the run will do, so a number the pacer would lower has to be shown lowered.
    let shown = reserve()
        .args(["--cautious", "--rate", "500", "-c", "100", "config", "show"])
        .assert()
        .success();
    let text = String::from_utf8(shown.get_output().stdout.clone()).expect("utf-8");
    for (key, wrong) in [("rate", "500"), ("concurrency", "100")] {
        let line = text
            .lines()
            .find(|line| line.trim_start().starts_with(key))
            .unwrap_or_else(|| panic!("`{key}` has to be reported"));
        assert!(
            !line.contains(wrong),
            "`{key}` reports {wrong}, which the cautious setting would lower: {line}"
        );
    }

    let planned = reserve()
        .args([
            "example",
            "--tld",
            "com",
            "--no-input",
            "--cautious",
            "--rate",
            "500",
            "--dry-run",
            "--json",
        ])
        .assert()
        .success();
    let plan: serde_json::Value =
        serde_json::from_slice(&planned.get_output().stdout).expect("a JSON plan");
    assert_ne!(
        plan["per_second"].as_u64(),
        Some(500),
        "the dry run must not promise a pace the sweep will not keep"
    );
}

#[test]
fn a_length_no_label_can_have_is_refused_where_it_was_typed() {
    for bad in ["0", "0-0", "999", "64", "1-999"] {
        reserve()
            .args(["example", "--tld", "com", "--no-input", "--length", bad])
            .assert()
            .code(2)
            .stderr(predicate::str::contains("filter.invalid"));
    }
    // @docgen A bound a label can have is accepted; whether it matches anything is a different question from whether it is usable.
    for good in ["2", "3", "2-4", "2-"] {
        reserve()
            .args(["example", "--no-input", "--dry-run", "--length", good])
            .assert()
            .success();
    }
    // @docgen `-3` is a documented form, so it has to work written the way the help writes it.
    for spaced in ["-4", "-3"] {
        reserve()
            .args(["example", "--no-input", "--dry-run", "--length", spaced])
            .assert()
            .success();
    }
    reserve()
        .args(["example", "--no-input", "--dry-run", "--length=-4"])
        .assert()
        .success();
}

#[test]
fn a_number_outside_its_range_is_refused_where_it_was_typed() {
    // @docgen The run used to clamp these in silence, so the number obeyed was not the number given.
    for (flag, value) in [
        ("--width", "0"),
        ("--rate", "99999"),
        ("--timeout", "0"),
        ("--page", "0"),
        ("--concurrency", "5000"),
        ("--per-registry", "0"),
    ] {
        reserve()
            .args([
                "example",
                "--tld",
                "com",
                "--no-input",
                "--dry-run",
                flag,
                value,
            ])
            .assert()
            .code(2)
            .stderr(predicate::str::contains("is not in"));
    }
}

#[test]
fn a_bad_environment_value_names_the_variable_that_carries_it() {
    // @docgen These reach every command, so one bad value stopped `reserve groups` too, blaming a flag nobody typed.
    for (name, value, wanted) in [
        ("RESERVE_TIMEOUT", "abc", "not a whole number"),
        ("RESERVE_WIDTH", "0", "--width takes 1 to 10000"),
        (
            "RESERVE_CONCURRENCY",
            "5000",
            "--concurrency takes 1 to 1024",
        ),
    ] {
        let run = reserve().env(name, value).args(["groups"]).assert().code(2);
        let complaint = String::from_utf8(run.get_output().stderr.clone()).expect("utf-8");
        assert!(
            complaint.contains(name) && complaint.contains(wanted),
            "{name}={value} has to name itself: {complaint}"
        );
    }
}

#[test]
fn a_piped_run_carries_no_colour_unless_it_was_asked_for() {
    // @docgen The harness normally sets NO_COLOR, which would hide whether the terminal check works at all.
    let plain = reserve()
        .env_remove("NO_COLOR")
        .args(["extensions", "--page-size", "2"])
        .assert()
        .success();
    let body = String::from_utf8(plain.get_output().stdout.clone()).expect("utf-8");
    assert!(
        !body.contains('\u{1b}'),
        "output that is not going to a terminal must carry no escape codes: {body:?}"
    );

    for forced in ["CLICOLOR_FORCE", "FORCE_COLOR"] {
        let coloured = reserve()
            .env_remove("NO_COLOR")
            .env(forced, "1")
            .args(["extensions", "--page-size", "2"])
            .assert()
            .success();
        let body = String::from_utf8(coloured.get_output().stdout.clone()).expect("utf-8");
        assert!(
            body.contains('\u{1b}'),
            "{forced} asks for colour through a pipe, so it has to arrive"
        );
    }

    let asked = reserve()
        .env_remove("NO_COLOR")
        .args(["extensions", "--page-size", "2", "--color", "always"])
        .assert()
        .success();
    let body = String::from_utf8(asked.get_output().stdout.clone()).expect("utf-8");
    assert!(body.contains('\u{1b}'), "--color always means always");
}

#[test]
fn browsing_the_catalog_reaches_every_extension_not_just_the_popular_ones() {
    let listed = reserve()
        .args(["extensions", "--json", "--all-pages"])
        .assert()
        .success();
    let all: serde_json::Value =
        serde_json::from_slice(&listed.get_output().stdout).expect("a JSON array");
    let all = all.as_array().expect("a JSON array").len();

    let popular = reserve()
        .args(["extensions", "--json", "--all-pages", "--group", "popular"])
        .assert()
        .success();
    let popular: serde_json::Value =
        serde_json::from_slice(&popular.get_output().stdout).expect("a JSON array");
    let popular = popular.as_array().expect("a JSON array").len();

    assert!(
        all > popular * 4,
        "browsing must show the catalog ({all}), not the short popular list ({popular})"
    );

    // A zone well past the popular list has to be findable by extension, country, and region.
    for needle in ["bd", "bangladesh", "south-asia"] {
        reserve()
            .args(["extensions", "--search", needle])
            .assert()
            .success()
            .stdout(predicate::str::contains("Bangladesh"));
    }
}

#[test]
fn a_sweep_with_nothing_named_still_checks_only_the_popular_list() {
    let listed = reserve()
        .args(["extensions", "--json", "--all-pages", "--group", "popular"])
        .assert()
        .success();
    let popular: serde_json::Value =
        serde_json::from_slice(&listed.get_output().stdout).expect("a JSON array");
    let popular = popular.as_array().expect("a JSON array").len();

    let planned = reserve()
        .args(["example", "--dry-run", "--json", "--no-input"])
        .assert()
        .success();
    let plan: serde_json::Value =
        serde_json::from_slice(&planned.get_output().stdout).expect("a JSON plan");
    assert_eq!(
        plan["lookups"].as_u64(),
        Some(popular as u64),
        "a sweep must not widen to the whole catalog"
    );
}

#[test]
fn a_result_file_already_there_is_refused_before_any_lookup_is_spent() {
    let dir = tempfile::tempdir().expect("temp dir");
    std::fs::write(dir.path().join("example-available.txt"), "").expect("the earlier run's file");

    // An unreadable server list fails inside the engine, so it says which of the two ran first.
    reserve()
        .args([
            "example",
            "--tld",
            "com",
            "--no-input",
            "--registry-servers",
            "/nonexistent/servers.json",
            "--out",
        ])
        .arg(dir.path())
        .assert()
        .code(5)
        .stderr(predicate::str::contains("output.unwritable"))
        .stderr(predicate::str::contains("already exists"))
        .stderr(predicate::str::contains("file.unreadable").not());
}

#[test]
fn both_list_flags_cannot_read_standard_input_at_once() {
    reserve()
        .args(["--names-from", "-", "--tlds-from", "-", "--no-input"])
        .write_stdin("example\n")
        .assert()
        .code(2)
        .stderr(predicate::str::contains("standard input"));
}

#[test]
fn every_declared_conflict_is_refused_by_the_built_binary() {
    // @docgen A declaration that is never exercised can be deleted without a single test failing.
    for argv in [
        vec!["example", "--full", "--details"],
        vec!["example", "--full", "--responder"],
        vec!["example", "--full", "--dns"],
        vec!["example", "--full", "--where-to-buy"],
        vec!["extensions", "--all-pages", "--page", "2"],
        vec!["example", "--save", "--out", "results"],
        vec!["example", "--no-input", "--interactive"],
        vec!["example", "--append"],
    ] {
        reserve().args(&argv).assert().code(2);
    }
}

#[test]
fn the_manual_answers_for_the_tool_and_for_one_command() {
    reserve()
        .args(["man"])
        .assert()
        .success()
        .stdout(predicate::str::contains(".TH"));

    reserve()
        .args(["man", "extensions"])
        .assert()
        .success()
        .stdout(predicate::str::contains(".TH reserve-extensions"));

    // @docgen A packager installs `reserve-config-show.1`, so the page the tool prints has to carry that same name.
    reserve()
        .args(["man", "config", "show"])
        .assert()
        .success()
        .stdout(predicate::str::contains(".TH reserve-config-show"));

    reserve()
        .args(["man", "config", "nope"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("show, path"));

    // The environment and the exit codes belong on the page a reader has offline.
    reserve()
        .args(["man"])
        .assert()
        .success()
        .stdout(predicate::str::contains("RESERVE_PLAIN"))
        .stdout(predicate::str::contains("EXIT CODES"));

    reserve()
        .args(["man", "not-a-command"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("is not a usable command"))
        // @docgen It must leave through the one error path, which is what prints an id a script can read.
        .stderr(predicate::str::contains("code:"))
        .stderr(predicate::str::contains("groups, extensions"));

    reserve().args(["man", "--help"]).assert().success();
}

#[test]
fn a_dry_run_says_what_would_happen_and_asks_no_registry() {
    let dir = tempfile::tempdir().expect("a temporary directory");
    reserve()
        .args([
            "example",
            "--tld",
            "com,net,org",
            "--dry-run",
            "--no-input",
            "--out",
        ])
        .arg(dir.path())
        .assert()
        .success()
        .stdout(
            predicate::str::contains("Dry run")
                .and(predicate::str::contains("lookups"))
                .and(predicate::str::contains("3"))
                .and(predicate::str::contains("pacing"))
                .and(predicate::str::contains("example-available.txt"))
                .and(predicate::str::contains("example-taken.txt"))
                .and(predicate::str::contains("example-unknown.txt"))
                .and(predicate::str::contains("no registry was asked")),
        );

    assert!(
        std::fs::read_dir(dir.path())
            .expect("the directory reads")
            .next()
            .is_none(),
        "a dry run must not write a single file"
    );
}

#[test]
fn a_dry_run_needs_no_network_even_for_a_whole_group() {
    reserve()
        .args([
            "example",
            "--group",
            "everything",
            "--dry-run",
            "--no-input",
        ])
        .timeout(std::time::Duration::from_secs(20))
        .assert()
        .success()
        .stdout(predicate::str::contains("Dry run"));
}