Debian Codegraph @

tests/by-util/test_sort.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 // spell-checker:ignore (words) ints (linux) NOFILE dfgi abmon avril
7 #![allow(clippy::cast_possible_wrap)]
8
9 use std::env;
10 use std::fmt::Write as FmtWrite;
11 #[cfg(unix)]
12 use std::process::Command;
13 use std::time::Duration;
14
15 use uutests::at_and_ucmd;
16 use uutests::new_ucmd;
17 use uutests::util::TestScenario;
18 #[cfg(unix)]
19 use uutests::util::is_locale_available;
20
21 fn test_helper(file_name: &str, possible_args: &[&str]) {
22 for args in possible_args {
23 new_ucmd!()
24 .arg(format!("{file_name}.txt"))
25 .args(&args.split_whitespace().collect::<Vec<&str>>())
26 .succeeds()
27 .stdout_is_fixture(format!("{file_name}.expected"));
28
29 new_ucmd!()
30 .arg(format!("{file_name}.txt"))
31 .arg("--debug")
32 .args(&args.split_whitespace().collect::<Vec<&str>>())
33 .succeeds()
34 .stdout_is_fixture(format!("{file_name}.expected.debug"));
35 }
36 }
37
38 #[test]
39 fn test_buffer_sizes() {
40 #[cfg(target_os = "linux")]
41 let buffer_sizes = ["0", "50K", "50k", "1M", "100M", "0%", "10%"];
42 // TODO Percentage sizes are not yet supported beyond Linux.
43 #[cfg(not(target_os = "linux"))]
44 let buffer_sizes = ["0", "50K", "50k", "1M", "100M"];
45 for buffer_size in &buffer_sizes {
46 new_ucmd!()
47 .arg("-n")
48 .arg("-S")
49 .arg(buffer_size)
50 .arg("ext_sort.txt")
51 .succeeds()
52 .stdout_is_fixture("ext_sort.expected");
53 }
54
55 #[cfg(not(target_pointer_width = "32"))]
56 {
57 let buffer_sizes = ["1000G", "10T"];
58 for buffer_size in &buffer_sizes {
59 new_ucmd!()
60 .arg("-n")
61 .arg("-S")
62 .arg(buffer_size)
63 .arg("ext_sort.txt")
64 .succeeds()
65 .stdout_is_fixture("ext_sort.expected");
66 }
67 }
68 }
69
70 #[test]
71 fn test_invalid_buffer_size() {
72 new_ucmd!()
73 .arg("-S")
74 .arg("asd")
75 .fails_with_code(2)
76 .stderr_only("sort: invalid --buffer-size argument 'asd'\n");
77
78 new_ucmd!()
79 .arg("-S")
80 .arg("100f")
81 .fails_with_code(2)
82 .stderr_only("sort: invalid suffix in --buffer-size argument '100f'\n");
83
84 // TODO Percentage sizes are not yet supported beyond Linux.
85 #[cfg(target_os = "linux")]
86 new_ucmd!()
87 .arg("-S")
88 .arg("0x123%")
89 .fails_with_code(2)
90 .stderr_only("sort: invalid --buffer-size argument '0x123%'\n");
91
92 // A percentage can fit in a u128 while its product with the total
93 // physical memory does not; the parser must report it as too large
94 // rather than panicking or silently wrapping.
95 #[cfg(target_os = "linux")]
96 new_ucmd!()
97 .arg("-S")
98 .arg("340282366920938463463374607431768211455%")
99 .fails_with_code(2)
100 .stderr_only(
101 "sort: --buffer-size argument '340282366920938463463374607431768211455%' too large\n",
102 );
103
104 new_ucmd!()
105 .arg("-n")
106 .arg("-S")
107 .arg("1Y")
108 .arg("ext_sort.txt")
109 .fails_with_code(2)
110 .stderr_only("sort: --buffer-size argument '1Y' too large\n");
111
112 #[cfg(target_pointer_width = "32")]
113 {
114 let buffer_sizes = ["1000G", "10T"];
115 for buffer_size in &buffer_sizes {
116 new_ucmd!()
117 .arg("-n")
118 .arg("-S")
119 .arg(buffer_size)
120 .arg("ext_sort.txt")
121 .fails_with_code(2)
122 .stderr_only(format!(
123 "sort: --buffer-size argument '{buffer_size}' too large\n"
124 ));
125 }
126 }
127 }
128
129 #[test]
130 fn test_legacy_plus_minus_accepts_when_modern_posix2() {
131 let size_max = usize::MAX;
132 let (at, mut ucmd) = at_and_ucmd!();
133 at.write("input.txt", "aa\nbb\n");
134
135 ucmd.env("_POSIX2_VERSION", "200809")
136 .arg(format!("+0.{size_max}R"))
137 .arg("input.txt")
138 .succeeds()
139 .stdout_is("aa\nbb\n");
140 }
141
142 #[test]
143 fn test_legacy_plus_minus_accepts_with_size_max() {
144 let size_max = usize::MAX;
145 let (at, mut ucmd) = at_and_ucmd!();
146 at.write("input.txt", "aa\nbb\n");
147
148 ucmd.env("_POSIX2_VERSION", "200809")
149 .arg("+1")
150 .arg(format!("-1.{size_max}R"))
151 .arg("input.txt")
152 .succeeds()
153 .stdout_is("aa\nbb\n");
154 }
155
156 #[test]
157 fn test_ext_sort_stable() {
158 new_ucmd!()
159 .arg("-n")
160 .arg("--stable")
161 .arg("-S")
162 .arg("0M")
163 .arg("ext_stable.txt")
164 .succeeds()
165 .stdout_only_fixture("ext_stable.expected");
166 }
167
168 #[test]
169 fn test_ext_sort_zero_terminated() {
170 new_ucmd!()
171 .arg("-z")
172 .arg("-S")
173 .arg("10K")
174 .arg("zero-terminated.txt")
175 .succeeds()
176 .stdout_is_fixture("zero-terminated.expected");
177 }
178
179 #[test]
180 fn test_months_whitespace() {
181 test_helper(
182 "months-whitespace",
183 &[
184 "-M",
185 "--month-sort",
186 "--sort=month",
187 "--sort=mont",
188 "--sort=m",
189 ],
190 );
191 }
192
193 #[test]
194 fn test_version_empty_lines() {
195 test_helper("version-empty-lines", &["-V", "--version-sort"]);
196 }
197
198 #[test]
199 fn test_parallel_invalid() {
200 // clap provided stderr
201 new_ucmd!().arg("--parallel=0").fails().code_is(2);
202 new_ucmd!().arg("--parallel=NaN").fails().code_is(2);
203 }
204
205 #[test]
206 fn test_version_sort_unstable() {
207 new_ucmd!()
208 .arg("--sort=version")
209 .pipe_in("0.1\n0.02\n0.2\n0.002\n0.3\n")
210 .succeeds()
211 .stdout_is("0.1\n0.002\n0.02\n0.2\n0.3\n");
212 new_ucmd!()
213 .arg("--sort=versio") // spell-checker:disable-line
214 .pipe_in("0.1\n0.02\n0.2\n0.002\n0.3\n")
215 .succeeds()
216 .stdout_is("0.1\n0.002\n0.02\n0.2\n0.3\n");
217 new_ucmd!()
218 .arg("--sort=v")
219 .pipe_in("0.1\n0.02\n0.2\n0.002\n0.3\n")
220 .succeeds()
221 .stdout_is("0.1\n0.002\n0.02\n0.2\n0.3\n");
222 }
223
224 #[test]
225 fn test_version_sort_stable() {
226 new_ucmd!()
227 .arg("--stable")
228 .arg("--sort=version")
229 .pipe_in("0.1\n0.02\n0.2\n0.002\n0.3\n")
230 .succeeds()
231 .stdout_is("0.1\n0.02\n0.2\n0.002\n0.3\n");
232 }
233
234 #[test]
235 fn test_ignore_case_orders_punctuation_after_letters() {
236 new_ucmd!()
237 .arg("-f")
238 .pipe_in("A\na\n_\n")
239 .succeeds()
240 .stdout_is("A\na\n_\n");
241 }
242
243 #[test]
244 fn test_ignore_case_unique_orders_punctuation_after_letters() {
245 new_ucmd!()
246 .arg("-fu")
247 .pipe_in("a\n_\n")
248 .succeeds()
249 .stdout_is("a\n_\n");
250 }
251
252 #[test]
253 fn test_human_numeric_whitespace() {
254 test_helper(
255 "human-numeric-whitespace",
256 &[
257 "-h",
258 "--human-numeric-sort",
259 "--sort=human-numeric",
260 "--sort=human-numeri", // spell-checker:disable-line
261 "--sort=human",
262 "--sort=h",
263 ],
264 );
265 }
266
267 // This tests where serde often fails when reading back JSON
268 // if it finds a null value
269 #[test]
270 fn test_ext_sort_as64_bailout() {
271 new_ucmd!()
272 .arg("-g")
273 .arg("-S 5K")
274 .arg("multiple_decimals_general.txt")
275 .succeeds()
276 .stdout_is_fixture("multiple_decimals_general.expected");
277 }
278
279 #[test]
280 fn test_multiple_decimals_general() {
281 test_helper(
282 "multiple_decimals_general",
283 &[
284 "-g",
285 "--general-numeric-sort",
286 "--sort=general-numeric",
287 "--sort=general-numeri", // spell-checker:disable-line
288 "--sort=general",
289 "--sort=g",
290 ],
291 );
292 }
293
294 #[test]
295 fn test_multiple_decimals_numeric() {
296 test_helper(
297 "multiple_decimals_numeric",
298 &["-n", "--numeric-sort", "--sort=numeric", "--sort=n"],
299 );
300 }
301
302 #[test]
303 fn test_multiple_groupings_numeric() {
304 test_helper(
305 "multiple_groupings_numeric",
306 &["-n", "--numeric-sort", "--sort=numeric", "--sort=n"],
307 );
308 }
309
310 #[test]
311 fn test_numeric_with_trailing_invalid_chars() {
312 test_helper(
313 "numeric_trailing_chars",
314 &["-n", "--numeric-sort", "--sort=numeric"],
315 );
316 }
317
318 #[test]
319 fn test_numeric_sort_rejects_leading_plus_sign() {
320 // GNU sort -n does not treat '+' as a number sign; lines sort lexicographically.
321 new_ucmd!()
322 .arg("-n")
323 .pipe_in("+1\n+10\n+2\n")
324 .succeeds()
325 .stdout_is("+1\n+10\n+2\n");
326 }
327
328 #[test]
329 fn test_numeric_sort_uses_the_key_not_the_whole_line() {
330 // `-n` compares a number parsed from the line as a whole, which only
331 // stands for the key when the key is the whole line.
332
333 // Character offset: the key is "9" and "1", so 21 comes first. Comparing
334 // the lines instead puts 19 first.
335 new_ucmd!()
336 .args(&["-n", "-k1.2"])
337 .pipe_in("19\n21\n")
338 .succeeds()
339 .stdout_is("21\n19\n");
340
341 // Field: with '.' as the separator the key is "9" and "1" again, while
342 // both lines parse as numbers on their own.
343 new_ucmd!()
344 .args(&["-n", "-t.", "-k2"])
345 .pipe_in("1.9\n2.1\n")
346 .succeeds()
347 .stdout_is("2.1\n1.9\n");
348
349 // A key that reverses on its own: the shortcut only knows the global
350 // ordering, so it has to go the long way.
351 new_ucmd!()
352 .args(&["-n", "-k1r"])
353 .pipe_in("19\n21\n3\n")
354 .succeeds()
355 .stdout_is("3\n21\n19\n");
356
357 // Equal keys fall back to comparing the lines byte by byte, not
358 // numerically.
359 new_ucmd!()
360 .args(&["-n", "-k1.2"])
361 .pipe_in("1\n10\n2\n20\n3\n")
362 .succeeds()
363 .stdout_is("1\n10\n2\n20\n3\n");
364
365 // The whole-line cases keep working.
366 new_ucmd!()
367 .arg("-n")
368 .pipe_in("19\n21\n3\n")
369 .succeeds()
370 .stdout_is("3\n19\n21\n");
371 new_ucmd!()
372 .args(&["-n", "-k1"])
373 .pipe_in("19\n21\n3\n")
374 .succeeds()
375 .stdout_is("3\n19\n21\n");
376 }
377
378 #[test]
379 fn test_check_zero_terminated_failure() {
380 new_ucmd!()
381 .arg("-z")
382 .arg("-c")
383 .arg("zero-terminated.txt")
384 .fails()
385 .stderr_only("sort: zero-terminated.txt:2: disorder: ../../fixtures/du\n");
386 }
387
388 #[test]
389 fn test_check_zero_terminated_success() {
390 new_ucmd!()
391 .arg("-z")
392 .arg("-c")
393 .arg("zero-terminated.expected")
394 .succeeds();
395 }
396
397 #[test]
398 fn test_random_shuffle_len() {
399 // check whether output is the same length as the input
400 const FILE: &str = "default_unsorted_ints.expected";
401 let (at, _ucmd) = at_and_ucmd!();
402 let result = new_ucmd!().arg("-R").arg(FILE).succeeds().stdout_move_str();
403 let expected = at.read(FILE);
404
405 assert_ne!(result, expected);
406 assert_eq!(result.len(), expected.len());
407 }
408
409 #[test]
410 fn test_random_shuffle_contains_all_lines() {
411 // check whether lines of input are all in output
412 const FILE: &str = "default_unsorted_ints.expected";
413 let (at, _ucmd) = at_and_ucmd!();
414 let result = new_ucmd!().arg("-R").arg(FILE).succeeds().stdout_move_str();
415 let expected = at.read(FILE);
416 let result_sorted = new_ucmd!()
417 .pipe_in(result.clone())
418 .succeeds()
419 .stdout_move_str();
420
421 assert_ne!(result, expected);
422 assert_eq!(result_sorted, expected);
423 }
424
425 #[test]
426 fn test_random_shuffle_two_runs_not_the_same() {
427 for arg in ["-R", "-k1,1R"] {
428 // check to verify that two random shuffles are not equal; this has the
429 // potential to fail in the very unlikely event that the random order is the same
430 // as the starting order, or if both random sorts end up having the same order.
431 const FILE: &str = "default_unsorted_ints.expected";
432 let (at, _ucmd) = at_and_ucmd!();
433 let result = new_ucmd!().arg(arg).arg(FILE).succeeds().stdout_move_str();
434 let expected = at.read(FILE);
435 let unexpected = new_ucmd!().arg(arg).arg(FILE).succeeds().stdout_move_str();
436
437 assert_ne!(result, expected);
438 assert_ne!(result, unexpected);
439 }
440 }
441
442 #[test]
443 fn test_random_source_shorter_than_the_salt() {
444 // GNU wants 128 bits out of the source and reports end of file below that,
445 // instead of shuffling with whatever it could read.
446 for len in [0, 1, 15] {
447 let (at, mut ucmd) = at_and_ucmd!();
448 at.write_bytes("source", &vec![b'x'; len]);
449 at.write("input", "b\na\nc\n");
450
451 ucmd.args(&["-R", "--random-source=source", "input"])
452 .fails_with_code(2)
453 .no_stdout()
454 .stderr_is("sort: 'source': end of file\n");
455 }
456 }
457
458 #[test]
459 fn test_random_source_of_exactly_the_salt_length() {
460 use uutests::util_name;
461
462 let ts = TestScenario::new(util_name!());
463 ts.fixtures.write_bytes("source", &[b'x'; 16]);
464 ts.fixtures.write("input", "b\na\nc\n");
465
466 let first = ts
467 .ucmd()
468 .args(&["-R", "--random-source=source", "input"])
469 .succeeds()
470 .stdout_move_str();
471 let second = ts
472 .ucmd()
473 .args(&["-R", "--random-source=source", "input"])
474 .succeeds()
475 .stdout_move_str();
476
477 assert_eq!(first, second);
478 assert_eq!(first.lines().count(), 3);
479 }
480
481 #[test]
482 fn test_random_source_is_not_read_without_random_sort() {
483 let (at, mut ucmd) = at_and_ucmd!();
484 at.write_bytes("source", b"");
485 at.write("input", "b\na\nc\n");
486
487 ucmd.args(&["--random-source=source", "input"])
488 .succeeds()
489 .stdout_is("a\nb\nc\n");
490 }
491
492 #[test]
493 fn test_random_ignore_case() {
494 let input = "ABC\nABc\nAbC\nAbc\naBC\naBc\nabC\nabc\n";
495 new_ucmd!()
496 .args(&["-fR"])
497 .pipe_in(input)
498 .succeeds()
499 .stdout_is(input);
500 }
501
502 #[test]
503 fn test_numeric_floats_and_ints() {
504 test_helper(
505 "numeric_floats_and_ints",
506 &["-n", "--numeric-sort", "--sort=numeric"],
507 );
508 }
509
510 #[test]
511 fn test_numeric_floats() {
512 test_helper(
513 "numeric_floats",
514 &["-n", "--numeric-sort", "--sort=numeric"],
515 );
516 }
517
518 #[test]
519 fn test_numeric_floats_with_nan() {
520 test_helper(
521 "numeric_floats_with_nan",
522 &["-n", "--numeric-sort", "--sort=numeric"],
523 );
524 }
525
526 #[test]
527 fn test_numeric_unfixed_floats() {
528 test_helper(
529 "numeric_unfixed_floats",
530 &["-n", "--numeric-sort", "--sort=numeric"],
531 );
532 }
533
534 #[test]
535 fn test_numeric_fixed_floats() {
536 test_helper(
537 "numeric_fixed_floats",
538 &["-n", "--numeric-sort", "--sort=numeric"],
539 );
540 }
541
542 #[test]
543 fn test_numeric_unsorted_ints() {
544 test_helper(
545 "numeric_unsorted_ints",
546 &["-n", "--numeric-sort", "--sort=numeric"],
547 );
548 }
549
550 #[test]
551 fn test_human_block_sizes() {
552 test_helper(
553 "human_block_sizes",
554 &["-h", "--human-numeric-sort", "--sort=human-numeric"],
555 );
556 }
557
558 #[test]
559 fn test_month_default() {
560 test_helper("month_default", &["-M", "--month-sort", "--sort=month"]);
561 }
562
563 #[test]
564 fn test_month_stable() {
565 test_helper("month_stable", &["-Ms"]);
566 }
567
568 #[test]
569 fn test_default_unsorted_ints() {
570 test_helper("default_unsorted_ints", &[""]);
571 }
572
573 #[test]
574 fn test_numeric_unique_ints() {
575 test_helper("numeric_unsorted_ints_unique", &["-nu"]);
576 }
577
578 #[test]
579 fn test_version() {
580 test_helper("version", &["-V"]);
581 }
582
583 #[test]
584 fn test_ignore_case() {
585 test_helper("ignore_case", &["-f"]);
586 }
587
588 #[test]
589 fn test_dictionary_order() {
590 test_helper("dictionary_order", &["-d"]);
591 }
592
593 #[test]
594 fn test_dictionary_order2() {
595 new_ucmd!()
596 .pipe_in("a👦🏻aa\tb\naaaa\tb") // spell-checker:disable-line
597 .arg("-d")
598 .succeeds()
599 .stdout_only("a👦🏻aa\tb\naaaa\tb\n"); // spell-checker:disable-line
600 }
601
602 #[test]
603 fn test_non_printing_chars() {
604 new_ucmd!()
605 .pipe_in("a👦🏻aa\naaaa") // spell-checker:disable-line
606 .arg("-i")
607 .succeeds()
608 .stdout_only("a👦🏻aa\naaaa\n"); // spell-checker:disable-line
609 }
610
611 #[test]
612 fn test_exponents_general() {
613 test_helper("exponents_general", &["-g"]);
614 }
615
616 #[test]
617 fn test_exponents_positive_general() {
618 new_ucmd!()
619 .pipe_in("1\n2e3\n1e-5")
620 .arg("-g")
621 .succeeds()
622 .stdout_only("1e-5\n1\n2e3\n");
623 }
624
625 #[test]
626 fn test_exponents_positive_numeric() {
627 test_helper(
628 "exponents-positive-numeric",
629 &["-n", "--numeric-sort", "--sort=numeric"],
630 );
631 }
632
633 #[test]
634 fn test_months_dedup() {
635 test_helper("months-dedup", &["-Mu"]);
636 }
637
638 #[test]
639 fn test_mixed_floats_ints_chars_numeric() {
640 test_helper(
641 "mixed_floats_ints_chars_numeric",
642 &["-n", "--numeric-sort", "--sort=numeric"],
643 );
644 }
645
646 #[test]
647 fn test_mixed_floats_ints_chars_numeric_unique() {
648 test_helper("mixed_floats_ints_chars_numeric_unique", &["-nu"]);
649 }
650
651 #[test]
652 fn test_words_unique() {
653 test_helper("words_unique", &["-u"]);
654 }
655
656 #[test]
657 fn test_numeric_unique() {
658 test_helper("numeric_unique", &["-nu"]);
659 }
660
661 #[test]
662 fn test_mixed_floats_ints_chars_numeric_reverse() {
663 test_helper("mixed_floats_ints_chars_numeric_unique_reverse", &["-nur"]);
664 }
665
666 #[test]
667 fn test_mixed_floats_ints_chars_numeric_stable() {
668 test_helper("mixed_floats_ints_chars_numeric_stable", &["-ns"]);
669 }
670
671 #[test]
672 fn test_numeric_floats_and_ints2() {
673 for numeric_sort_param in ["-n", "--numeric-sort"] {
674 let input = "1.444\n8.013\n1\n-8\n1.04\n-1";
675 new_ucmd!()
676 .arg(numeric_sort_param)
677 .pipe_in(input)
678 .succeeds()
679 .stdout_only("-8\n-1\n1\n1.04\n1.444\n8.013\n");
680 }
681 }
682
683 #[test]
684 fn test_numeric_floats2() {
685 for numeric_sort_param in ["-n", "--numeric-sort"] {
686 let input = "1.444\n8.013\n1.58590\n-8.90880\n1.040000000\n-.05";
687 new_ucmd!()
688 .arg(numeric_sort_param)
689 .pipe_in(input)
690 .succeeds()
691 .stdout_only("-8.90880\n-.05\n1.040000000\n1.444\n1.58590\n8.013\n");
692 }
693 }
694
695 #[test]
696 fn test_numeric_floats_with_nan2() {
697 test_helper(
698 "numeric-floats-with-nan2",
699 &["-n", "--numeric-sort", "--sort=numeric"],
700 );
701 }
702
703 #[test]
704 fn test_human_block_sizes2() {
705 for human_numeric_sort_param in ["-h", "--human-numeric-sort", "--sort=human-numeric"] {
706 let input = "8981K\n909991M\n-8T\n21G\n0.8M";
707 new_ucmd!()
708 .arg(human_numeric_sort_param)
709 .pipe_in(input)
710 .succeeds()
711 .stdout_only("-8T\n8981K\n0.8M\n909991M\n21G\n");
712 }
713 }
714
715 #[test]
716 fn test_human_numeric_zero_stable() {
717 let input = "0M\n0K\n-0K\n-P\n-0M\n";
718 new_ucmd!()
719 .arg("-hs")
720 .pipe_in(input)
721 .succeeds()
722 .stdout_only(input);
723 }
724
725 #[test]
726 fn test_month_default2() {
727 for month_sort_param in ["-M", "--month-sort", "--sort=month"] {
728 let input = "JAn\nMAY\n000may\nJun\nFeb";
729 new_ucmd!()
730 .arg(month_sort_param)
731 .pipe_in(input)
732 .succeeds()
733 .stdout_only("000may\nJAn\nFeb\nMAY\nJun\n");
734 }
735 }
736
737 /// Query the system for abbreviated month names via `locale abmon`.
738 /// Returns a vector of 12 month abbreviations in order (Jan..Dec),
739 /// or None if the command fails or returns unexpected output.
740 #[cfg(any(
741 target_vendor = "apple",
742 target_os = "dragonfly",
743 target_os = "freebsd",
744 target_os = "netbsd",
745 target_os = "openbsd"
746 ))]
747 fn get_system_abmon(locale: &str) -> Option<Vec<String>> {
748 let output = Command::new("locale")
749 .env("LC_ALL", locale)
750 .arg("abmon")
751 .output()
752 .ok()
753 .filter(|s| s.status.success())?;
754 let text = String::from_utf8(output.stdout).ok()?;
755 let months: Vec<String> = text
756 .trim()
757 .split(';')
758 .map(String::from)
759 .filter(|m| !m.is_empty())
760 .collect();
761 if months.len() == 12 {
762 Some(months)
763 } else {
764 None
765 }
766 }
767
768 /// Build shuffled input and sorted expected output from month names.
769 #[cfg(any(
770 target_vendor = "apple",
771 target_os = "dragonfly",
772 target_os = "freebsd",
773 target_os = "netbsd",
774 target_os = "openbsd"
775 ))]
776 fn month_sort_input_expected(months: &[String]) -> (String, String) {
777 // Shuffled order: May, Dec, Jan, Jun, Feb, Mar, Apr, Jul, Aug, Sep, Oct, Nov
778 let shuffle_order = [4, 11, 0, 5, 1, 2, 3, 6, 7, 8, 9, 10];
779 let input = shuffle_order
780 .iter()
781 .map(|&i| months[i].as_str())
782 .collect::<Vec<_>>()
783 .join("\n")
784 + "\n";
785 let expected = months.join("\n") + "\n";
786 (input, expected)
787 }
788
789 #[test]
790 #[cfg(unix)]
791 fn test_month_sort_french_locale() {
792 let locale = "fr_FR.UTF-8";
793 if !is_locale_available(locale) {
794 return;
795 }
796 // spell-checker:disable
797 // On BSD-like, abbreviated month names vary across OS versions (different CLDR data),
798 // so we query the system dynamically. On other platforms, glibc values are stable.
799 #[cfg(any(
800 target_vendor = "apple",
801 target_os = "dragonfly",
802 target_os = "freebsd",
803 target_os = "netbsd",
804 target_os = "openbsd"
805 ))]
806 let (input, expected) = {
807 let Some(months) = get_system_abmon(locale) else {
808 return;
809 };
810 month_sort_input_expected(&months)
811 };
812 #[cfg(not(any(
813 target_vendor = "apple",
814 target_os = "dragonfly",
815 target_os = "freebsd",
816 target_os = "netbsd",
817 target_os = "openbsd"
818 )))]
819 let (input, expected) = (
820 "mai\ndéc.\njanv.\njuin\nfévr.\nmars\navril\njuil.\naoût\nsept.\noct.\nnov.\n".to_string(),
821 "janv.\nfévr.\nmars\navril\nmai\njuin\njuil.\naoût\nsept.\noct.\nnov.\ndéc.\n".to_string(),
822 );
823 // spell-checker:enable
824 new_ucmd!()
825 .env("LC_ALL", locale)
826 .arg("-M")
827 .pipe_in(input)
828 .succeeds()
829 .stdout_is(expected);
830 }
831
832 #[test]
833 #[cfg(unix)]
834 fn test_month_sort_hungarian_locale() {
835 let locale = "hu_HU.UTF-8";
836 if !is_locale_available(locale) {
837 return;
838 }
839 // spell-checker:disable
840 #[cfg(any(
841 target_vendor = "apple",
842 target_os = "dragonfly",
843 target_os = "freebsd",
844 target_os = "netbsd",
845 target_os = "openbsd"
846 ))]
847 let (input, expected) = {
848 let Some(months) = get_system_abmon(locale) else {
849 return;
850 };
851 month_sort_input_expected(&months)
852 };
853 #[cfg(not(any(
854 target_vendor = "apple",
855 target_os = "dragonfly",
856 target_os = "freebsd",
857 target_os = "netbsd",
858 target_os = "openbsd"
859 )))]
860 let (input, expected) = (
861 "máj\ndec\njan\njún\nfebr\nmárc\nápr\njúl\naug\nszept\nokt\nnov\n".to_string(),
862 "jan\nfebr\nmárc\nápr\nmáj\njún\njúl\naug\nszept\nokt\nnov\ndec\n".to_string(),
863 );
864 // spell-checker:enable
865 new_ucmd!()
866 .env("LC_ALL", locale)
867 .arg("-M")
868 .pipe_in(input)
869 .succeeds()
870 .stdout_is(expected);
871 }
872
873 /// Test that embedded blanks in month names cause a non-match (GNU compat).
874 /// E.g. "av ril" should NOT match "avril" — GNU treats it as unknown.
875 #[test]
876 #[cfg(unix)]
877 fn test_month_sort_french_embedded_blanks() {
878 let locale = "fr_FR.UTF-8";
879 if !is_locale_available(locale) {
880 return;
881 }
882 // spell-checker:disable
883 // Pick three locale months (indices 2=March, 3=April, 5=June) and verify
884 // that inserting blanks into April's name causes a non-match.
885 // On glibc these are "mars", "avril", "juin"; on other systems they vary.
886 #[cfg(any(
887 target_vendor = "apple",
888 target_os = "dragonfly",
889 target_os = "freebsd",
890 target_os = "netbsd",
891 target_os = "openbsd"
892 ))]
893 let months = {
894 let Some(m) = get_system_abmon(locale) else {
895 return;
896 };
897 m
898 };
899 #[cfg(not(any(
900 target_vendor = "apple",
901 target_os = "dragonfly",
902 target_os = "freebsd",
903 target_os = "netbsd",
904 target_os = "openbsd"
905 )))]
906 let months = vec![
907 "janv.", "févr.", "mars", "avril", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.",
908 "déc.",
909 ]
910 .into_iter()
911 .map(String::from)
912 .collect::<Vec<_>>();
913
914 let march = &months[2];
915 let april = &months[3];
916 let june = &months[5];
917
918 // Build a mangled version of April with embedded spaces: e.g. "avril" -> "av ril"
919 // Insert spaces after the second byte.
920 if april.len() < 3 {
921 // Month name too short to meaningfully insert blanks; skip.
922 return;
923 }
924 let mangled = format!("{} {}", &april[..2], &april[2..]);
925
926 // Input: june, mangled-april, march
927 let input = format!("{june}\n{mangled}\n{march}\n");
928 // Expected: mangled sorts as unknown (first), then march (3), then june (6)
929 let expected = format!("{mangled}\n{march}\n{june}\n");
930 // spell-checker:enable
931 new_ucmd!()
932 .env("LC_ALL", locale)
933 .arg("-M")
934 .pipe_in(input)
935 .succeeds()
936 .stdout_is(expected);
937 }
938
939 #[test]
940 #[cfg(unix)]
941 fn test_month_sort_japanese_locale() {
942 let locale = "ja_JP.UTF-8";
943 if !is_locale_available(locale) {
944 return;
945 }
946 // On BSD-like, abbreviated month names may differ, so query dynamically.
947 #[cfg(any(
948 target_vendor = "apple",
949 target_os = "dragonfly",
950 target_os = "freebsd",
951 target_os = "netbsd",
952 target_os = "openbsd"
953 ))]
954 let (input, expected) = {
955 let Some(months) = get_system_abmon(locale) else {
956 return;
957 };
958 month_sort_input_expected(&months)
959 };
960 // Japanese abbreviated months are numeric (1月..12月) on glibc
961 #[cfg(not(any(
962 target_vendor = "apple",
963 target_os = "dragonfly",
964 target_os = "freebsd",
965 target_os = "netbsd",
966 target_os = "openbsd"
967 )))]
968 let (input, expected) = (
969 "5月\n12月\n1月\n6月\n2月\n3月\n4月\n7月\n8月\n9月\n10月\n11月\n".to_string(),
970 "1月\n2月\n3月\n4月\n5月\n6月\n7月\n8月\n9月\n10月\n11月\n12月\n".to_string(),
971 );
972 new_ucmd!()
973 .env("LC_ALL", locale)
974 .arg("-M")
975 .pipe_in(input)
976 .succeeds()
977 .stdout_is(expected);
978 }
979
980 #[test]
981 fn test_default_unsorted_ints2() {
982 let input = "9\n1909888\n000\n1\n2";
983 new_ucmd!()
984 .pipe_in(input)
985 .succeeds()
986 .stdout_only("000\n1\n1909888\n2\n9\n");
987 }
988
989 #[test]
990 fn test_numeric_unique_ints2() {
991 let input = "9\n9\n8\n1\n";
992 new_ucmd!()
993 .arg("-nu")
994 .pipe_in(input)
995 .succeeds()
996 .stdout_only("1\n8\n9\n");
997 }
998
999 #[test]
1000 fn test_keys_open_ended() {
1001 test_helper("keys_open_ended", &["-k 2.3"]);
1002 }
1003
1004 #[test]
1005 fn test_keys_closed_range() {
1006 test_helper("keys_closed_range", &["-k 2.2,2.2"]);
1007 }
1008
1009 #[test]
1010 fn test_keys_multiple_ranges() {
1011 test_helper("keys_multiple_ranges", &["-k 2,2 -k 3,3"]);
1012 }
1013
1014 #[test]
1015 fn test_keys_no_field_match() {
1016 test_helper("keys_no_field_match", &["-k 4,4"]);
1017 }
1018
1019 #[test]
1020 fn test_keys_no_char_match() {
1021 test_helper("keys_no_char_match", &["-k 1.2"]);
1022 }
1023
1024 #[test]
1025 fn test_keys_custom_separator() {
1026 test_helper("keys_custom_separator", &["-k 2.2,2.2 -t x"]);
1027 }
1028
1029 #[test]
1030 fn test_keys_invalid_field() {
1031 new_ucmd!()
1032 .args(&["-k", "1."])
1033 .fails()
1034 .stderr_only("sort: invalid number after '.': invalid count at start of ''\n");
1035 }
1036
1037 #[test]
1038 fn test_keys_invalid_field_option() {
1039 new_ucmd!()
1040 .args(&["-k", "1.1x"])
1041 .fails()
1042 .stderr_only("sort: stray character in field spec: invalid field specification '1.1x'\n");
1043 }
1044
1045 #[test]
1046 fn test_keys_invalid_field_zero() {
1047 new_ucmd!()
1048 .args(&["-k", "0.1"])
1049 .fails()
1050 .stderr_only("sort: field number is zero: invalid field specification '0.1'\n");
1051 }
1052
1053 #[test]
1054 fn test_keys_invalid_char_zero() {
1055 new_ucmd!()
1056 .args(&["-k", "1.0"])
1057 .fails()
1058 .stderr_only("sort: character offset is zero: invalid field specification '1.0'\n");
1059 }
1060
1061 #[test]
1062 fn test_keys_invalid_number_formats() {
1063 new_ucmd!()
1064 .args(&["-k", "0"])
1065 .fails_with_code(2)
1066 .stderr_only("sort: field number is zero: invalid field specification '0'\n");
1067
1068 new_ucmd!()
1069 .args(&["-k", "2.,3"])
1070 .fails_with_code(2)
1071 .stderr_only("sort: invalid number after '.': invalid count at start of ',3'\n");
1072
1073 new_ucmd!()
1074 .args(&["-k", "2,"])
1075 .fails_with_code(2)
1076 .stderr_only("sort: invalid number after ',': invalid count at start of ''\n");
1077
1078 new_ucmd!()
1079 .args(&["-k", "1.1,-k0"])
1080 .fails_with_code(2)
1081 .stderr_only("sort: invalid number after ',': invalid count at start of '-k0'\n");
1082 }
1083
1084 #[test]
1085 fn test_incompatible_options() {
1086 new_ucmd!()
1087 .arg("-hn")
1088 .fails_with_code(2)
1089 .stderr_only("sort: options '-hn' are incompatible\n");
1090
1091 new_ucmd!()
1092 .arg("-in")
1093 .fails_with_code(2)
1094 .stderr_only("sort: options '-in' are incompatible\n");
1095
1096 new_ucmd!()
1097 .arg("-nR")
1098 .fails_with_code(2)
1099 .stderr_only("sort: options '-nR' are incompatible\n");
1100
1101 new_ucmd!()
1102 .arg("-dfgiMnR")
1103 .fails_with_code(2)
1104 .stderr_only("sort: options '-dfgMnR' are incompatible\n");
1105
1106 new_ucmd!()
1107 .args(&["--sort=random", "-n"])
1108 .fails_with_code(2)
1109 .stderr_only("sort: options '-nR' are incompatible\n");
1110
1111 new_ucmd!()
1112 .args(&["-c", "-o", "out"])
1113 .fails_with_code(2)
1114 .stderr_only("sort: options '-co' are incompatible\n");
1115
1116 new_ucmd!()
1117 .args(&["-C", "-o", "out"])
1118 .fails_with_code(2)
1119 .stderr_only("sort: options '-Co' are incompatible\n");
1120
1121 new_ucmd!()
1122 .args(&["-c", "-C"])
1123 .fails_with_code(2)
1124 .stderr_only("sort: options '-cC' are incompatible\n");
1125 }
1126
1127 #[test]
1128 fn test_keys_with_options() {
1129 let input = "aa 3 cc\ndd 1 ff\ngg 2 cc\n";
1130 for param in [
1131 &["-k", "2,2n"][..],
1132 &["-k", "2n,2"][..],
1133 &["-k", "2,2", "-n"][..],
1134 ] {
1135 new_ucmd!()
1136 .args(param)
1137 .pipe_in(input)
1138 .succeeds()
1139 .stdout_only("dd 1 ff\ngg 2 cc\naa 3 cc\n");
1140 }
1141 }
1142
1143 #[test]
1144 fn test_keys_with_options_blanks_start() {
1145 let input = "aa 3 cc\ndd 1 ff\ngg 2 cc\n";
1146 for param in [&["-k", "2b,2"][..], &["-k", "2,2", "-b"][..]] {
1147 new_ucmd!()
1148 .args(param)
1149 .pipe_in(input)
1150 .succeeds()
1151 .stdout_only("dd 1 ff\ngg 2 cc\naa 3 cc\n");
1152 }
1153 }
1154
1155 #[test]
1156 fn test_keys_blanks_with_char_idx() {
1157 test_helper("keys_blanks", &["-k 1.2b"]);
1158 }
1159
1160 #[test]
1161 fn test_keys_with_options_blanks_end() {
1162 let input = "a b
1163 a b
1164 a b
1165 ";
1166 new_ucmd!()
1167 .args(&["-k", "1,2.1b", "-s"])
1168 .pipe_in(input)
1169 .succeeds()
1170 .stdout_only(
1171 "a b
1172 a b
1173 a b
1174 ",
1175 );
1176 }
1177
1178 #[test]
1179 fn test_keys_stable() {
1180 let input = "a b
1181 a b
1182 a b
1183 ";
1184 new_ucmd!()
1185 .args(&["-k", "1,2.1", "-s"])
1186 .pipe_in(input)
1187 .succeeds()
1188 .stdout_only(
1189 "a b
1190 a b
1191 a b
1192 ",
1193 );
1194 }
1195
1196 #[test]
1197 fn test_keys_empty_match() {
1198 let input = "a a a a
1199 aaaa
1200 ";
1201 new_ucmd!()
1202 .args(&["-k", "1,1", "-t", "a"])
1203 .pipe_in(input)
1204 .succeeds()
1205 .stdout_only(input);
1206 }
1207
1208 #[test]
1209 fn test_keys_negative_size_match() {
1210 // If the end of a field is before its start, we should not crash.
1211 // Debug output should report "no match for key" at the start position (i.e. the later position).
1212 test_helper("keys_negative_size", &["-k 3,1"]);
1213 }
1214
1215 #[test]
1216 fn test_keys_ignore_flag() {
1217 test_helper("keys_ignore_flag", &["-k 1n -b"]);
1218 }
1219
1220 #[test]
1221 fn test_does_not_inherit_key_settings() {
1222 let input = " 1
1223 2
1224 10
1225 ";
1226 new_ucmd!()
1227 .args(&["-k", "1b", "-n"])
1228 .pipe_in(input)
1229 .succeeds()
1230 .stdout_only(
1231 " 1
1232 10
1233 2
1234 ",
1235 );
1236 }
1237
1238 #[test]
1239 fn test_inherits_key_settings() {
1240 let input = " 1
1241 2
1242 10
1243 ";
1244 new_ucmd!()
1245 .args(&["-k", "1", "-n"])
1246 .pipe_in(input)
1247 .succeeds()
1248 .stdout_only(
1249 " 1
1250 2
1251 10
1252 ",
1253 );
1254 }
1255
1256 #[test]
1257 fn test_zero_terminated() {
1258 test_helper("zero-terminated", &["-z"]);
1259 }
1260
1261 #[test]
1262 fn test_multiple_files() {
1263 new_ucmd!()
1264 .arg("-n")
1265 .arg("multiple_files1.txt")
1266 .arg("multiple_files2.txt")
1267 .succeeds()
1268 .stdout_only_fixture("multiple_files.expected");
1269 }
1270
1271 /// A file that does not end with a separator must not be fused onto the next file.
1272 #[test]
1273 fn test_unterminated_file_not_fused_across_chunk_boundary() {
1274 // "a\nb\nc" is 5 bytes, so `-S 5b` puts the chunk boundary exactly at its EOF.
1275 for buffer_size in ["1b", "2b", "3b", "4b", "5b", "6b", "7b", "8b", "16b"] {
1276 let (at, mut ucmd) = at_and_ucmd!();
1277 at.write("first.txt", "a\nb\nc");
1278 at.write("second.txt", "z\n");
1279 ucmd.args(&["-S", buffer_size, "first.txt", "second.txt"])
1280 .succeeds()
1281 .stdout_only("a\nb\nc\nz\n");
1282 }
1283 }
1284
1285 #[test]
1286 fn test_merge_interleaved() {
1287 new_ucmd!()
1288 .arg("-m")
1289 .arg("merge_ints_interleaved_1.txt")
1290 .arg("merge_ints_interleaved_2.txt")
1291 .arg("merge_ints_interleaved_3.txt")
1292 .succeeds()
1293 .stdout_only_fixture("merge_ints_interleaved.expected");
1294 }
1295
1296 #[test]
1297 fn test_merge_preserves_long_lines() {
1298 use std::fmt::Write;
1299
1300 const N_ROWS: usize = 3;
1301 const LINE_LEN: usize = 32_000;
1302 const LINE_VALUES: [&str; N_ROWS] = ["a", "b", "c"];
1303 // Exercise merge reads where long lines span internal chunk boundaries.
1304 let input = LINE_VALUES.into_iter().fold(
1305 String::with_capacity(N_ROWS * (LINE_LEN + 1)),
1306 |mut acc, value| {
1307 writeln!(acc, "{}", value.repeat(LINE_LEN)).unwrap();
1308 acc
1309 },
1310 );
1311
1312 let (at, mut ucmd) = at_and_ucmd!();
1313 at.write("long-lines.txt", &input);
1314
1315 let result = ucmd.arg("-m").arg("long-lines.txt").succeeds();
1316 result.no_stderr();
1317
1318 let stdout = result.stdout_move_bytes();
1319 assert_eq!(bytecount::count(&stdout, b'\n'), N_ROWS);
1320 assert_eq!(stdout.len(), input.len());
1321 assert_eq!(stdout.as_slice(), input.as_bytes());
1322 }
1323
1324 // Regression test: a failing write must not take the merge reader thread down with it.
1325 // The write error used to propagate straight out of `write_all_to`, dropping the chunk
1326 // receivers while the reader was still sending, and `chunks::read` unwraps that send.
1327 #[test]
1328 #[cfg(target_os = "linux")]
1329 fn test_merge_write_error_does_not_panic() {
1330 use std::fs::File;
1331
1332 // The inputs have to be long enough that the reader is still feeding us chunks when
1333 // the write fails, otherwise it has already finished and there is nothing to race.
1334 const LINES: usize = 100_000;
1335 let mut input = String::with_capacity(LINES * 7);
1336 for line in 0..LINES {
1337 writeln!(input, "{line:06}").unwrap();
1338 }
1339
1340 let ts = TestScenario::new("sort");
1341 ts.fixtures.write("a.txt", &input);
1342 ts.fixtures.write("b.txt", &input);
1343
1344 // Whether the reader is mid-send when the write fails is a race, so repeat: a single
1345 // attempt reproduced the panic only about a quarter of the time. With the fix the
1346 // reader is always shut down in an orderly fashion, so this cannot fail spuriously.
1347 for _ in 0..20 {
1348 let dev_full = File::create("/dev/full").expect("Failed to open /dev/full");
1349 ts.ucmd()
1350 .args(&["-m", "a.txt", "b.txt"])
1351 .set_stdout(dev_full)
1352 .fails()
1353 .code_is(1)
1354 .stderr_contains("No space left on device")
1355 .stderr_does_not_contain("panicked");
1356 }
1357 }
1358
1359 // A read error must be reported with context and without the raw io::Error suffix.
1360 // It used to print `sort: Input/output error (os error 5)`.
1361 #[test]
1362 #[cfg(target_os = "linux")]
1363 #[cfg_attr(wasi_runner, ignore)]
1364 fn test_read_error_message() {
1365 // Reading /proc/self/mem from offset 0 fails with EIO.
1366 let result = new_ucmd!().arg("/proc/self/mem").fails_with_code(2);
1367 result.no_stdout();
1368 // The strerror text for EIO differs between C libraries: glibc says
1369 // "Input/output error" while musl says "I/O error".
1370 let stderr = result.stderr_str();
1371 assert!(
1372 stderr == "sort: read failed: Input/output error\n"
1373 || stderr == "sort: read failed: I/O error\n",
1374 "unexpected stderr: {stderr}"
1375 );
1376 }
1377
1378 #[test]
1379 fn test_merge_unique() {
1380 new_ucmd!()
1381 .arg("-m")
1382 .arg("--unique")
1383 .arg("merge_ints_interleaved_1.txt")
1384 .arg("merge_ints_interleaved_2.txt")
1385 .arg("merge_ints_interleaved_3.txt")
1386 .arg("merge_ints_interleaved_3.txt")
1387 .arg("merge_ints_interleaved_2.txt")
1388 .arg("merge_ints_interleaved_1.txt")
1389 .succeeds()
1390 .stdout_only_fixture("merge_ints_interleaved.expected");
1391 }
1392
1393 #[test]
1394 fn test_merge_stable() {
1395 new_ucmd!()
1396 .arg("-m")
1397 .arg("--stable")
1398 .arg("-n")
1399 .arg("merge_stable_1.txt")
1400 .arg("merge_stable_2.txt")
1401 .succeeds()
1402 .stdout_only_fixture("merge_stable.expected");
1403 }
1404
1405 #[test]
1406 fn test_merge_reversed() {
1407 new_ucmd!()
1408 .arg("-m")
1409 .arg("--reverse")
1410 .arg("merge_ints_reversed_1.txt")
1411 .arg("merge_ints_reversed_2.txt")
1412 .arg("merge_ints_reversed_3.txt")
1413 .succeeds()
1414 .stdout_only_fixture("merge_ints_reversed.expected");
1415 }
1416
1417 #[test]
1418 fn test_pipe() {
1419 // TODO: issue 1608 reports a panic when we attempt to read from stdin,
1420 // which was closed by the other side of the pipe. This test does not
1421 // protect against regressions in that case; we should add one at some
1422 // point.
1423 new_ucmd!()
1424 .pipe_in("one\ntwo\nfour")
1425 .succeeds()
1426 .stdout_only("four\none\ntwo\n");
1427 }
1428
1429 #[test]
1430 fn test_check() {
1431 for diagnose_arg in [
1432 "-c",
1433 "--check",
1434 "--check=diagnose-first",
1435 "--check=diagnose",
1436 "--check=d",
1437 ] {
1438 new_ucmd!()
1439 .arg(diagnose_arg)
1440 .arg("check_fail.txt")
1441 .arg("--buffer-size=10b")
1442 .fails()
1443 .stderr_only("sort: check_fail.txt:6: disorder: 5\n");
1444
1445 new_ucmd!()
1446 .arg(diagnose_arg)
1447 .arg("multiple_files.expected")
1448 .succeeds()
1449 .no_output();
1450 }
1451 }
1452
1453 #[test]
1454 fn test_check_disorder_echoes_line_verbatim() {
1455 // The line reported in a "disorder" diagnostic is the raw offending input line.
1456 // It must never be reinterpreted/reformatted as a number, even though it looks
1457 // like one (GNU sort echoes it verbatim too).
1458 new_ucmd!()
1459 .args(&["-n", "-c"])
1460 .pipe_in("2\n1.10\n")
1461 .fails()
1462 .stderr_only("sort: -:2: disorder: 1.10\n");
1463
1464 new_ucmd!()
1465 .args(&["-n", "-c"])
1466 .pipe_in("5\nnan\n")
1467 .fails()
1468 .stderr_only("sort: -:2: disorder: nan\n");
1469
1470 new_ucmd!()
1471 .args(&["-g", "-c"])
1472 .pipe_in("1e10\n1e5\n")
1473 .fails()
1474 .stderr_only("sort: -:2: disorder: 1e5\n");
1475 }
1476
1477 #[test]
1478 fn test_check_silent() {
1479 for silent_arg in [
1480 "-C",
1481 "--check=silent",
1482 "--check=quiet",
1483 "--check=silen", // spell-checker:disable-line
1484 "--check=quie", // spell-checker:disable-line
1485 "--check=s",
1486 "--check=q",
1487 ] {
1488 new_ucmd!()
1489 .arg(silent_arg)
1490 .arg("check_fail.txt")
1491 .fails()
1492 .no_output();
1493 new_ucmd!()
1494 .arg(silent_arg)
1495 .arg("empty.txt")
1496 .succeeds()
1497 .no_output();
1498 }
1499 }
1500
1501 #[test]
1502 fn test_check_stops_early_without_panicking() {
1503 // `--check` returns as soon as it finds the first disorder. That used to drop the
1504 // channel while the reader thread was still sending chunks, so the reader panicked
1505 // on a `SendError`. Under `panic = "abort"` (our release profile) that aborts the
1506 // whole process instead of exiting 1.
1507 //
1508 // The disorder sits midway through an input that is large relative to the buffer
1509 // size, so the reader is certain to be blocked on a full channel when we stop.
1510 // Note this cannot fail spuriously: once the receiver outlives the reader, no
1511 // panic is possible.
1512 const LINES_BEFORE: usize = 20_000;
1513 let mut input = "c\n".repeat(LINES_BEFORE);
1514 input.push_str("a\n");
1515 input.push_str(&"c\n".repeat(LINES_BEFORE));
1516
1517 let (at, mut ucmd) = at_and_ucmd!();
1518 at.write("disorder.txt", &input);
1519
1520 ucmd.args(&["-c", "--buffer-size=1K", "disorder.txt"])
1521 .fails_with_code(1)
1522 .stderr_only(format!(
1523 "sort: disorder.txt:{}: disorder: a\n",
1524 LINES_BEFORE + 1
1525 ));
1526 }
1527
1528 #[test]
1529 fn test_check_unique() {
1530 new_ucmd!()
1531 .args(&["-c", "-u"])
1532 .pipe_in("A\nA\n")
1533 .fails_with_code(1)
1534 .stderr_only("sort: -:2: disorder: A\n");
1535 }
1536
1537 #[test]
1538 fn test_check_unique_combined() {
1539 new_ucmd!()
1540 .args(&["-cu"])
1541 .pipe_in("A\nA\n")
1542 .fails_with_code(1)
1543 .stderr_only("sort: -:2: disorder: A\n");
1544 }
1545
1546 #[test]
1547 fn test_dictionary_and_nonprinting_conflicts() {
1548 let conflicting_args = ["n", "h", "g", "M"];
1549 for restricted_arg in ["d", "i"] {
1550 for conflicting_arg in &conflicting_args {
1551 new_ucmd!()
1552 .arg(format!("-{restricted_arg}{conflicting_arg}"))
1553 .fails();
1554 }
1555 for conflicting_arg in &conflicting_args {
1556 new_ucmd!()
1557 .args(&[
1558 format!("-{restricted_arg}").as_str(),
1559 "-k",
1560 format!("1,1{conflicting_arg}").as_str(),
1561 ])
1562 .succeeds();
1563 }
1564 for conflicting_arg in &conflicting_args {
1565 new_ucmd!()
1566 .args(&["-k", &format!("1{restricted_arg},1{conflicting_arg}")])
1567 .fails();
1568 }
1569 }
1570 }
1571
1572 #[test]
1573 fn test_trailing_separator() {
1574 new_ucmd!()
1575 .args(&["-t", "x", "-k", "1,1"])
1576 .pipe_in("aax\naaa\n")
1577 .succeeds()
1578 .stdout_is("aax\naaa\n");
1579 }
1580
1581 #[test]
1582 fn test_nonexistent_file() {
1583 new_ucmd!()
1584 .arg("nonexistent.txt")
1585 .fails_with_code(2)
1586 .stderr_only(
1587 #[cfg(not(windows))]
1588 "sort: cannot read: nonexistent.txt: No such file or directory\n",
1589 #[cfg(windows)]
1590 "sort: cannot read: nonexistent.txt: The system cannot find the file specified.\n",
1591 );
1592 }
1593
1594 #[test]
1595 fn test_blanks() {
1596 test_helper("blanks", &["-b", "--ignore-leading-blanks"]);
1597 }
1598
1599 #[test]
1600 fn sort_multiple() {
1601 new_ucmd!()
1602 .args(&["no_trailing_newline1.txt", "no_trailing_newline2.txt"])
1603 .succeeds()
1604 .stdout_is("a\nb\nb\n");
1605 }
1606
1607 #[test]
1608 fn sort_empty_chunk() {
1609 new_ucmd!()
1610 .args(&["-S", "40b"])
1611 .pipe_in("a\na\n")
1612 .succeeds()
1613 .stdout_is("a\na\n");
1614 }
1615
1616 #[test]
1617 #[cfg(any(target_os = "linux", target_os = "android"))]
1618 fn test_compress() {
1619 new_ucmd!()
1620 .args(&[
1621 "ext_sort.txt",
1622 "-n",
1623 "--compress-program",
1624 "gzip",
1625 "-S",
1626 "10",
1627 ])
1628 .succeeds()
1629 .stdout_only_fixture("ext_sort.expected");
1630 }
1631
1632 #[test]
1633 #[cfg(any(target_os = "linux", target_os = "android"))]
1634 fn test_compress_merge() {
1635 new_ucmd!()
1636 .args(&[
1637 "--compress-program",
1638 "gzip",
1639 "-S",
1640 "10",
1641 "--batch-size=2",
1642 "-m",
1643 "--unique",
1644 "merge_ints_interleaved_1.txt",
1645 "merge_ints_interleaved_2.txt",
1646 "merge_ints_interleaved_3.txt",
1647 "merge_ints_interleaved_3.txt",
1648 "merge_ints_interleaved_2.txt",
1649 "merge_ints_interleaved_1.txt",
1650 ])
1651 .succeeds()
1652 .stdout_only_fixture("merge_ints_interleaved.expected");
1653 }
1654
1655 #[test]
1656 #[cfg(not(target_os = "android"))]
1657 fn test_compress_fail() {
1658 let result = new_ucmd!()
1659 .args(&[
1660 "ext_sort.txt",
1661 "-n",
1662 "--compress-program",
1663 "nonexistent-program",
1664 "-S",
1665 "10",
1666 ])
1667 .succeeds();
1668
1669 #[cfg(not(windows))]
1670 result.stderr_contains(
1671 "sort: could not run compress program 'nonexistent-program': No such file or directory",
1672 );
1673
1674 #[cfg(windows)]
1675 result.stderr_contains("could not run compress program");
1676
1677 // Check that it still produces correct sorted output to stdout
1678 let expected = new_ucmd!()
1679 .args(&["ext_sort.txt", "-n"])
1680 .succeeds()
1681 .stdout_move_str();
1682 assert_eq!(result.stdout_str(), expected);
1683 }
1684
1685 #[test]
1686 fn test_merge_batches() {
1687 new_ucmd!()
1688 .timeout(Duration::from_secs(120))
1689 .args(&["ext_sort.txt", "-n", "-S", "150b"])
1690 .succeeds()
1691 .stdout_only_fixture("ext_sort.expected");
1692 }
1693
1694 #[test]
1695 fn test_batch_size_invalid() {
1696 new_ucmd!()
1697 .arg("--batch-size=0")
1698 .fails_with_code(2)
1699 .stderr_contains("sort: invalid --batch-size argument '0'")
1700 .stderr_contains("sort: minimum --batch-size argument is '2'");
1701
1702 // with -m, the error path is a bit different
1703 new_ucmd!()
1704 .args(&["-m", "--batch-size=a"])
1705 .fails_with_code(2)
1706 .stderr_contains("sort: invalid --batch-size argument 'a'");
1707 }
1708
1709 #[test]
1710 fn test_batch_size_too_large() {
1711 let large_batch_size = "18446744073709551616";
1712 new_ucmd!()
1713 .arg(format!("--batch-size={large_batch_size}"))
1714 .fails_with_code(2)
1715 .stderr_contains(format!(
1716 "--batch-size argument '{large_batch_size}' too large"
1717 ));
1718
1719 #[cfg(target_os = "linux")]
1720 new_ucmd!()
1721 .arg(format!("--batch-size={large_batch_size}"))
1722 .fails_with_code(2)
1723 .stderr_contains("maximum --batch-size argument with current rlimit is");
1724 }
1725
1726 #[test]
1727 fn test_merge_batch_size() {
1728 new_ucmd!()
1729 .arg("--batch-size=2")
1730 .arg("-m")
1731 .arg("--unique")
1732 .arg("merge_ints_interleaved_1.txt")
1733 .arg("merge_ints_interleaved_2.txt")
1734 .arg("merge_ints_interleaved_3.txt")
1735 .arg("merge_ints_interleaved_3.txt")
1736 .arg("merge_ints_interleaved_2.txt")
1737 .arg("merge_ints_interleaved_1.txt")
1738 .succeeds()
1739 .stdout_only_fixture("merge_ints_interleaved.expected");
1740 }
1741
1742 #[test]
1743 // TODO(#7542): Re-enable on Android once we figure out why setting limit is broken.
1744 // #[cfg(any(target_os = "linux", target_os = "android"))]
1745 #[cfg(target_os = "linux")]
1746 fn test_merge_batch_size_with_limit() {
1747 use rlimit::Resource;
1748 // Currently need...
1749 // 3 descriptors for stdin, stdout, stderr
1750 // 2 descriptors for CTRL+C handling logic (to be reworked at some point)
1751 // 2 descriptors for the input files (i.e. batch-size of 2).
1752 let limit_fd = 3 + 2 + 2;
1753 new_ucmd!()
1754 .limit(Resource::NOFILE, limit_fd, limit_fd)
1755 .arg("--batch-size=2")
1756 .arg("-m")
1757 .arg("--unique")
1758 .arg("merge_ints_interleaved_1.txt")
1759 .arg("merge_ints_interleaved_2.txt")
1760 .arg("merge_ints_interleaved_3.txt")
1761 .arg("merge_ints_interleaved_3.txt")
1762 .arg("merge_ints_interleaved_2.txt")
1763 .arg("merge_ints_interleaved_1.txt")
1764 .succeeds()
1765 .stdout_only_fixture("merge_ints_interleaved.expected");
1766 }
1767
1768 #[test]
1769 // TODO(#7542): Re-enable on Android once we figure out why setting limit is broken.
1770 #[cfg(target_os = "linux")]
1771 fn test_batch_size_above_fd_limit_is_rejected() {
1772 use rlimit::Resource;
1773 // Only stdin, stdout and stderr are unavailable for merge inputs, so the
1774 // largest acceptable --batch-size is the soft limit minus 3, here 27 - 3.
1775 let limit_fd = 27;
1776 let (at, mut ucmd) = at_and_ucmd!();
1777 at.write("gamma.txt", "delta\nalpha\n");
1778 ucmd.limit(Resource::NOFILE, limit_fd, limit_fd)
1779 .arg("--batch-size=31")
1780 .arg("gamma.txt")
1781 .fails_with_code(2)
1782 .stderr_contains("--batch-size argument '31' too large")
1783 // 24 is forced by the limit above: 27 - 3 reserved descriptors.
1784 .stderr_contains("maximum --batch-size argument with current rlimit is 24");
1785 }
1786
1787 #[test]
1788 #[cfg(target_os = "linux")]
1789 fn test_batch_size_at_fd_limit_is_accepted() {
1790 use rlimit::Resource;
1791 let limit_fd = 27;
1792 let (at, mut ucmd) = at_and_ucmd!();
1793 at.write("gamma.txt", "delta\nalpha\n");
1794 // 24 is the largest value the limit above allows, and sorting must still happen.
1795 ucmd.limit(Resource::NOFILE, limit_fd, limit_fd)
1796 .arg("--batch-size=24")
1797 .arg("gamma.txt")
1798 .succeeds()
1799 .stdout_only("alpha\ndelta\n");
1800 }
1801
1802 #[test]
1803 #[cfg(target_os = "linux")]
1804 fn test_merge_more_files_than_fd_limit() {
1805 use rlimit::Resource;
1806 let (at, mut ucmd) = at_and_ucmd!();
1807 // 40 single-line files cannot all be open at once with a soft limit of 24,
1808 // so sort has to merge them in several batches through temporary files.
1809 let count = 40;
1810 let mut names = Vec::new();
1811 for i in 0..count {
1812 let name = format!("fdlimit_{i:02}.txt");
1813 at.write(&name, &format!("{i:02}\n"));
1814 names.push(name);
1815 }
1816 let mut expected = String::new();
1817 for i in 0..count {
1818 writeln!(expected, "{i:02}").unwrap();
1819 }
1820 let limit_fd = 24;
1821 ucmd.limit(Resource::NOFILE, limit_fd, limit_fd)
1822 .arg("-m")
1823 .args(&names)
1824 .succeeds()
1825 .stdout_only(expected);
1826 }
1827
1828 #[test]
1829 #[cfg(target_os = "linux")]
1830 fn test_more_files_than_fd_limit() {
1831 use rlimit::Resource;
1832 let (at, mut ucmd) = at_and_ucmd!();
1833 // The inputs are read one after another, so sorting must not need more open
1834 // file descriptors than the soft limit allows, no matter how many inputs there are.
1835 let count = 40;
1836 let mut names = Vec::new();
1837 for i in 0..count {
1838 let name = format!("fdlimit_{i:02}.txt");
1839 at.write(&name, &format!("{:02}\n", count - 1 - i));
1840 names.push(name);
1841 }
1842 let mut expected = String::new();
1843 for i in 0..count {
1844 writeln!(expected, "{i:02}").unwrap();
1845 }
1846 let limit_fd = 24;
1847 ucmd.limit(Resource::NOFILE, limit_fd, limit_fd)
1848 .args(&names)
1849 .succeeds()
1850 .stdout_only(expected);
1851 }
1852
1853 #[test]
1854 fn test_sigpipe_panic() {
1855 let mut cmd = new_ucmd!();
1856 let mut child = cmd.args(&["ext_sort.txt"]).run_no_wait();
1857 // Dropping the stdout should not lead to an error.
1858 // The "Broken pipe" error should be silently ignored.
1859 child.close_stdout();
1860 child.wait().unwrap().no_stderr();
1861 }
1862
1863 #[test]
1864 #[cfg(unix)]
1865 fn test_fifo_without_trailing_newline() {
1866 let (at, mut ucmd) = at_and_ucmd!();
1867 at.mkfifo("FIFO");
1868
1869 let mut child = ucmd.arg("FIFO").run_no_wait();
1870 let fifo = at.plus("FIFO");
1871 let writer = std::thread::spawn(move || std::fs::write(fifo, "hello").unwrap());
1872 writer.join().unwrap();
1873
1874 for _ in 0..50 {
1875 if child.is_not_alive() {
1876 break;
1877 }
1878 child.delay(100);
1879 }
1880 if child.is_alive() {
1881 child.kill();
1882 panic!("sort did not exit after the FIFO writer closed");
1883 }
1884 child.wait().unwrap().success().stdout_is("hello\n");
1885 }
1886
1887 #[test]
1888 fn test_conflict_check_out() {
1889 let cases = [
1890 ("-c=silent", "sort: options '-Co' are incompatible\n"),
1891 ("-c=quiet", "sort: options '-Co' are incompatible\n"),
1892 (
1893 "-c=diagnose-first",
1894 "sort: options '-co' are incompatible\n",
1895 ),
1896 ("-c", "sort: options '-co' are incompatible\n"),
1897 ("-C", "sort: options '-Co' are incompatible\n"),
1898 ];
1899 for (check_flag, expected) in &cases {
1900 new_ucmd!()
1901 .arg(check_flag)
1902 .arg("-o=/dev/null")
1903 .fails()
1904 .stderr_contains(expected);
1905 }
1906 }
1907
1908 #[test]
1909 fn test_key_takes_one_arg() {
1910 new_ucmd!()
1911 .args(&["-k", "2.3", "keys_open_ended.txt"])
1912 .succeeds()
1913 .stdout_is_fixture("keys_open_ended.expected");
1914 }
1915
1916 #[test]
1917 fn test_verifies_out_file() {
1918 let inputs = ["" /* no input */, "some input"];
1919 for &input in &inputs {
1920 new_ucmd!()
1921 .args(&["-o", "nonexistent_dir/nonexistent_file"])
1922 .pipe_in(input)
1923 .ignore_stdin_write_error()
1924 .fails_with_code(2)
1925 .stderr_only(
1926 #[cfg(not(windows))]
1927 "sort: open failed: nonexistent_dir/nonexistent_file: No such file or directory\n",
1928 #[cfg(windows)]
1929 "sort: open failed: nonexistent_dir/nonexistent_file: The system cannot find the path specified.\n",
1930 );
1931 }
1932 }
1933
1934 #[test]
1935 fn test_verifies_files_after_keys() {
1936 new_ucmd!()
1937 .args(&[
1938 "-o",
1939 "nonexistent_dir/nonexistent_file",
1940 "-k",
1941 "0",
1942 "nonexistent_dir/input_file",
1943 ])
1944 .fails_with_code(2)
1945 .stderr_contains("invalid field specification '0'");
1946 }
1947
1948 #[test]
1949 #[cfg(unix)]
1950 fn test_verifies_input_files() {
1951 new_ucmd!()
1952 .args(&["/dev/random", "nonexistent_file"])
1953 .fails_with_code(2)
1954 .stderr_is("sort: cannot read: nonexistent_file: No such file or directory\n");
1955 }
1956
1957 #[test]
1958 #[cfg(unix)]
1959 fn test_verifies_input_files_without_opening_them() {
1960 // Opening a FIFO blocks until a writer shows up, so if the input check opened
1961 // the inputs, the missing second file would never be reported.
1962 let (at, mut ucmd) = at_and_ucmd!();
1963 at.mkfifo("FIFO");
1964 ucmd.args(&["FIFO", "nonexistent_file"])
1965 .fails_with_code(2)
1966 .stderr_only("sort: cannot read: nonexistent_file: No such file or directory\n");
1967 }
1968
1969 #[test]
1970 fn test_separator_null() {
1971 new_ucmd!()
1972 .args(&["-k1,1", "-k3,3", "-t", "\\0"])
1973 .pipe_in("z\0a\0b\nz\0b\0a\na\0z\0z\n")
1974 .succeeds()
1975 .stdout_only("a\0z\0z\nz\0b\0a\nz\0a\0b\n");
1976 }
1977
1978 #[test]
1979 fn test_separator_attached_equals() {
1980 // `-t=` must select `=` itself as the separator (clap strips a leading
1981 // `=` from attached short-option values), matching GNU sort. #14120
1982 new_ucmd!()
1983 .args(&["-t=", "-k", "2"])
1984 .pipe_in("a=b=c\nb=a=d\n")
1985 .succeeds()
1986 .stdout_only("b=a=d\na=b=c\n");
1987 }
1988
1989 #[test]
1990 fn test_separator_attached_equals_double() {
1991 // `-t==` selects the two-character separator `==`, which GNU rejects.
1992 new_ucmd!()
1993 .args(&["-t==", "-k", "2"])
1994 .pipe_in("")
1995 .fails()
1996 .stderr_contains("separator must be exactly one character long: '=='");
1997 }
1998
1999 #[test]
2000 fn test_separator_attached_equals_multi_char() {
2001 // `-t=a` selects the two-character separator `=a`, which GNU rejects.
2002 new_ucmd!()
2003 .args(&["-t=a", "-k", "2"])
2004 .pipe_in("")
2005 .fails()
2006 .stderr_contains("separator must be exactly one character long: '=a'");
2007 }
2008
2009 #[test]
2010 fn test_output_is_input() {
2011 let input = "a\nb\nc\n";
2012 let (at, mut ucmd) = at_and_ucmd!();
2013
2014 at.touch("file");
2015 at.append("file", input);
2016
2017 ucmd.args(&["-m", "-u", "-o", "file", "file", "file", "file"])
2018 .succeeds();
2019 assert_eq!(at.read("file"), input);
2020 }
2021
2022 #[test]
2023 fn test_output_file_is_truncated() {
2024 // The output file is opened without O_TRUNC (so it can also be an input),
2025 // then truncated before writing: no leftover bytes may survive the sort.
2026 let (at, mut ucmd) = at_and_ucmd!();
2027 at.write(
2028 "shrinking",
2029 "zzz-leftover-one\nzzz-leftover-two\nzzz-leftover-three\n",
2030 );
2031
2032 ucmd.args(&["-o", "shrinking"])
2033 .pipe_in("kiwi\napple\n")
2034 .succeeds()
2035 .no_output();
2036
2037 assert_eq!(at.read("shrinking"), "apple\nkiwi\n");
2038 }
2039
2040 #[test]
2041 fn test_merge_output_file_is_truncated() {
2042 let (at, mut ucmd) = at_and_ucmd!();
2043 at.write("pears", "damson\nquince\n");
2044 at.write(
2045 "merged",
2046 "zzz-leftover-one\nzzz-leftover-two\nzzz-leftover-three\n",
2047 );
2048
2049 ucmd.args(&["-m", "-o", "merged", "pears"])
2050 .succeeds()
2051 .no_output();
2052
2053 assert_eq!(at.read("merged"), "damson\nquince\n");
2054 }
2055
2056 #[test]
2057 #[cfg(unix)]
2058 fn test_output_device() {
2059 new_ucmd!()
2060 .args(&["-o", "/dev/null"])
2061 .pipe_in("input")
2062 .succeeds();
2063 }
2064
2065 #[test]
2066 fn test_merge_empty_input() {
2067 new_ucmd!()
2068 .args(&["-m", "empty.txt"])
2069 .succeeds()
2070 .no_output();
2071 }
2072
2073 #[test]
2074 fn test_no_error_for_version() {
2075 new_ucmd!()
2076 .arg("--version")
2077 .succeeds()
2078 .stdout_contains("sort");
2079 }
2080
2081 #[test]
2082 fn test_wrong_args_exit_code() {
2083 new_ucmd!()
2084 .arg("--misspelled")
2085 .fails_with_code(2)
2086 .stderr_contains("--misspelled");
2087 }
2088
2089 #[test]
2090 #[cfg(unix)]
2091 fn test_tmp_files_deleted_on_sigint() {
2092 use rand::{RngExt as _, SeedableRng, rngs::SmallRng};
2093 use rustix::process::{Pid, Signal, kill_process};
2094 use std::{fs::read_dir, time::Duration};
2095
2096 let (at, mut ucmd) = at_and_ucmd!();
2097 at.mkdir("tmp_dir");
2098 let file_name = "big_file_to_sort.txt";
2099 {
2100 use std::io::Write;
2101 let mut file = at.make_file(file_name);
2102 // approximately 20 MB
2103 for _ in 0..40 {
2104 let lines = SmallRng::seed_from_u64(123)
2105 .sample_iter(rand::distr::uniform::Uniform::new(0, 10000).unwrap())
2106 .take(100_000)
2107 .map(|x| x.to_string() + "\n")
2108 .collect::<String>();
2109 file.write_all(lines.as_bytes()).unwrap();
2110 }
2111 }
2112 ucmd.args(&[
2113 file_name,
2114 "--buffer-size=1", // with a small buffer size `sort` will be forced to create a temporary directory very soon.
2115 "--temporary-directory=tmp_dir",
2116 ]);
2117 let child = ucmd.run_no_wait();
2118 // wait a short amount of time so that `sort` can create a temporary directory.
2119 let mut timeout = Duration::from_millis(100);
2120 for _ in 0..5 {
2121 std::thread::sleep(timeout);
2122 if read_dir(at.plus("tmp_dir")).unwrap().next().is_some() {
2123 break;
2124 }
2125 timeout *= 2;
2126 }
2127 // `sort` should have created a temporary directory.
2128 assert!(read_dir(at.plus("tmp_dir")).unwrap().next().is_some());
2129 // kill sort with SIGINT
2130 kill_process(Pid::from_raw(child.id() as i32).unwrap(), Signal::INT).unwrap();
2131 // wait for `sort` to exit
2132 child.wait().unwrap().code_is(2);
2133 // `sort` should have deleted the temporary directory again.
2134 assert!(read_dir(at.plus("tmp_dir")).unwrap().next().is_none());
2135 }
2136
2137 #[test]
2138 #[cfg(unix)]
2139 fn test_tmp_files_are_private() {
2140 use rustix::process::{Pid, Signal, kill_process};
2141 use std::os::unix::fs::PermissionsExt as _;
2142 use std::{fs::read_dir, time::Duration};
2143
2144 let (at, mut ucmd) = at_and_ucmd!();
2145 at.mkdir("scratch");
2146 let input = (0..200_000)
2147 .map(|i| (i * 7919 % 200_003).to_string())
2148 .collect::<Vec<_>>()
2149 .join("\n");
2150 at.write("unsorted.txt", &input);
2151 // A one byte buffer forces `sort` to spill its chunks to disk immediately.
2152 let child = ucmd
2153 .args(&["unsorted.txt", "-S", "1", "-T", "scratch"])
2154 .umask(0o002)
2155 .run_no_wait();
2156
2157 let mut modes = Vec::new();
2158 for i in 0..6 {
2159 std::thread::sleep(Duration::from_millis(50 << i));
2160 if let Some(dir) = read_dir(at.plus("scratch")).unwrap().flatten().next() {
2161 modes = read_dir(dir.path())
2162 .unwrap()
2163 .flatten()
2164 .map(|f| f.metadata().unwrap().permissions().mode() & 0o777)
2165 .collect();
2166 if !modes.is_empty() {
2167 assert_eq!(dir.metadata().unwrap().permissions().mode() & 0o777, 0o700);
2168 break;
2169 }
2170 }
2171 }
2172 assert!(!modes.is_empty(), "sort did not spill any chunk to disk");
2173 assert!(
2174 modes.iter().all(|&m| m == 0o600),
2175 "chunks are readable: {modes:?}"
2176 );
2177
2178 kill_process(Pid::from_raw(child.id() as i32).unwrap(), Signal::INT).unwrap();
2179 child.wait().unwrap().code_is(2);
2180 }
2181
2182 #[test]
2183 fn test_same_sort_mode_twice() {
2184 new_ucmd!().args(&["-k", "2n,2n", "empty.txt"]).succeeds();
2185 }
2186
2187 #[test]
2188 fn test_args_override() {
2189 new_ucmd!().args(&["-f", "-f"]).pipe_in("foo").succeeds();
2190 }
2191
2192 #[test]
2193 fn test_k_overflow() {
2194 let input = "2\n1\n";
2195 let output = "1\n2\n";
2196 new_ucmd!()
2197 .args(&["-k", "18446744073709551616"])
2198 .pipe_in(input)
2199 .succeeds()
2200 .stdout_is(output);
2201 }
2202
2203 #[test]
2204 fn test_human_blocks_r_and_q() {
2205 let input = "1Q\n1R\n";
2206 let output = "1R\n1Q\n";
2207 new_ucmd!()
2208 .args(&["-h"])
2209 .pipe_in(input)
2210 .succeeds()
2211 .stdout_is(output);
2212 }
2213
2214 #[test]
2215 fn test_args_check_conflict() {
2216 new_ucmd!().arg("-c").arg("-C").fails();
2217 }
2218
2219 #[cfg(target_os = "linux")]
2220 #[test]
2221 fn test_failed_write_is_reported() {
2222 new_ucmd!()
2223 .pipe_in("hello")
2224 .set_stdout(std::fs::File::create("/dev/full").unwrap())
2225 .fails()
2226 .stderr_is("sort: write failed: 'standard output': No space left on device\n");
2227 }
2228
2229 #[test]
2230 // Test sort with output file (o2)
2231 fn test_error_on_multiple_output_flags() {
2232 new_ucmd!()
2233 .args(&["-o", "alpha", "-o", "beta"])
2234 .fails_with_code(2)
2235 .stderr_is("sort: multiple output files specified\n");
2236 }
2237
2238 #[test]
2239 // Test sort with output file (o3)
2240 fn test_same_output_flag_twice_ok() {
2241 new_ucmd!()
2242 .args(&["-o", "output", "-o", "output"])
2243 .pipe_in("")
2244 .succeeds()
2245 .no_stderr();
2246 }
2247
2248 #[test]
2249 fn test_output_file_with_leading_dash() {
2250 let test_cases = [
2251 (
2252 ["--output", "--dash-file"],
2253 "banana\napple\ncherry\n",
2254 "apple\nbanana\ncherry\n",
2255 ),
2256 (
2257 ["-o", "--another-dash-file"],
2258 "zebra\nxray\nyak\n",
2259 "xray\nyak\nzebra\n",
2260 ),
2261 ];
2262
2263 for (args, input, expected) in test_cases {
2264 let (at, mut ucmd) = at_and_ucmd!();
2265 ucmd.args(&args).pipe_in(input).succeeds().no_stdout();
2266
2267 assert_eq!(at.read(args[1]), expected);
2268 }
2269 }
2270
2271 #[test]
2272 // Test files0-from with extra argument
2273 fn test_files0_from_rejects_extra_positional() {
2274 new_ucmd!()
2275 .args(&["--files0-from", "-", "foo"])
2276 .fails_with_code(2)
2277 .stderr_contains(
2278 "sort: extra operand 'foo'\nfile operands cannot be combined with --files0-from\n",
2279 )
2280 .no_stdout();
2281 }
2282
2283 #[test]
2284 // Test files0-from with missing file
2285 fn test_files0_from_nonexistent_file_fails() {
2286 new_ucmd!()
2287 .args(&["--files0-from", "missing_file"])
2288 .fails_with_code(2)
2289 .stderr_only(
2290 #[cfg(not(windows))]
2291 "sort: open failed: missing_file: No such file or directory\n",
2292 #[cfg(windows)]
2293 "sort: open failed: missing_file: The system cannot find the file specified.\n",
2294 );
2295 }
2296
2297 #[test]
2298 // Test files0-from reading from stdin
2299 fn test_files0_from_reads_stdin_via_dash() {
2300 new_ucmd!()
2301 .args(&["--files0-from", "-"])
2302 .pipe_in("-")
2303 .fails_with_code(2)
2304 .stderr_only(
2305 "sort: when reading file names from standard input, no file name of '-' allowed\n",
2306 );
2307 }
2308
2309 #[test]
2310 // Test files0-from with empty file
2311 fn test_files0_from_empty_input_file() {
2312 let (at, mut ucmd) = at_and_ucmd!();
2313
2314 at.touch("file");
2315
2316 ucmd.args(&["--files0-from", "file"])
2317 .fails_with_code(2)
2318 .stderr_only("sort: no input from 'file'\n");
2319 }
2320
2321 #[test]
2322 #[cfg(unix)]
2323 fn test_files0_from_non_utf8_filename() {
2324 new_ucmd!()
2325 .args(&["--files0-from", "-"])
2326 .pipe_in(vec![0xff_u8])
2327 .fails_with_code(2)
2328 .stderr_contains("sort: cannot read");
2329 }
2330
2331 #[test]
2332 #[cfg(unix)]
2333 fn test_files0_from_unreadable_source() {
2334 new_ucmd!()
2335 .args(&["--files0-from", "."])
2336 .fails_with_code(2)
2337 .stderr_only("sort: cannot read: .: Is a directory\n");
2338 }
2339
2340 #[cfg(unix)]
2341 #[test]
2342 // Test files0-from with non-regular empty file
2343 fn test_files0_from_dev_null_is_empty() {
2344 new_ucmd!()
2345 .args(&["--files0-from", "/dev/null"])
2346 .fails_with_code(2)
2347 .stderr_only("sort: no input from '/dev/null'\n");
2348 }
2349
2350 #[test]
2351 // Test files0-from with NUL-separated input (case 1)
2352 fn test_files0_from_single_nul_is_invalid() {
2353 new_ucmd!()
2354 .args(&["--files0-from", "-"])
2355 .pipe_in("\0")
2356 .fails_with_code(2)
2357 .stderr_only("sort: -:1: invalid zero-length file name\n");
2358 }
2359
2360 #[test]
2361 // Test files0-from with NUL-separated input (case 2)
2362 fn test_files0_from_double_nul_is_invalid() {
2363 new_ucmd!()
2364 .args(&["--files0-from", "-"])
2365 .pipe_in("\0\0")
2366 .fails_with_code(2)
2367 .stderr_only("sort: -:1: invalid zero-length file name\n");
2368 }
2369
2370 #[test]
2371 // Test files0-from basic single file
2372 fn test_files0_from_single_entry() {
2373 let (at, mut ucmd) = at_and_ucmd!();
2374
2375 at.touch("words");
2376 at.append("words", "mango\nkiwi");
2377
2378 ucmd.args(&["--files0-from", "-"])
2379 .pipe_in("words")
2380 .succeeds()
2381 .stdout_only("kiwi\nmango\n");
2382 }
2383
2384 #[test]
2385 // Test files0-from basic single file variant
2386 fn test_files0_from_single_entry_trailing_nul() {
2387 let (at, mut ucmd) = at_and_ucmd!();
2388
2389 at.touch("words");
2390 at.append("words", "mango\nkiwi");
2391
2392 ucmd.args(&["--files0-from", "-"])
2393 .pipe_in("words\0")
2394 .succeeds()
2395 .stdout_only("kiwi\nmango\n");
2396 }
2397
2398 #[test]
2399 // Test files0-from with two files
2400 fn test_files0_from_two_entries() {
2401 let (at, mut ucmd) = at_and_ucmd!();
2402
2403 at.touch("words");
2404 at.append("words", "mango\nkiwi");
2405
2406 ucmd.args(&["--files0-from", "-"])
2407 .pipe_in("words\0words")
2408 .succeeds()
2409 .stdout_only("kiwi\nkiwi\nmango\nmango\n");
2410 }
2411
2412 #[test]
2413 // Test files0-from with two files variant
2414 fn test_files0_from_two_entries_trailing_nul() {
2415 let (at, mut ucmd) = at_and_ucmd!();
2416
2417 at.touch("words");
2418 at.append("words", "mango\nkiwi");
2419
2420 ucmd.args(&["--files0-from", "-"])
2421 .pipe_in("words\0words\0")
2422 .succeeds()
2423 .stdout_only("kiwi\nkiwi\nmango\nmango\n");
2424 }
2425
2426 #[test]
2427 // Test files0-from with non-UTF-8 filenames
2428 #[cfg(all(unix, not(target_vendor = "apple")))]
2429 fn test_files0_from_non_utf8_content() {
2430 use std::os::unix::ffi::OsStringExt;
2431 let (at, mut ucmd) = at_and_ucmd!();
2432
2433 // non-UTF-8 bytes (0xFF)
2434 let filename = std::ffi::OsString::from_vec(b"a\xffb".into());
2435 std::fs::write(at.plus(&filename), b"20\n10\n").unwrap();
2436
2437 let list_contents = vec![b'a', 0xFF, b'b', 0];
2438 at.write_bytes("list0", &list_contents);
2439
2440 ucmd.args(&["--files0-from", "list0"])
2441 .succeeds()
2442 .stdout_only("10\n20\n");
2443 }
2444
2445 #[test]
2446 // Test files0-from with zero-length filename
2447 fn test_files0_from_zero_length_entry_fails() {
2448 new_ucmd!()
2449 .args(&["--files0-from", "-"])
2450 .pipe_in("x\0\0y\0\0")
2451 .fails_with_code(2)
2452 .stderr_only("sort: -:2: invalid zero-length file name\n");
2453 }
2454
2455 #[test]
2456 // Test sort with floating point numbers
2457 fn test_sort_general_numeric_extremes() {
2458 let input = "0\n-1.7976931348623157e+308\n1.7976931348623157e+308\n";
2459 let output = "-1.7976931348623157e+308\n0\n1.7976931348623157e+308\n";
2460 new_ucmd!()
2461 .args(&["-g"])
2462 .pipe_in(input)
2463 .succeeds()
2464 .stdout_is(output);
2465 }
2466
2467 #[test]
2468 fn test_g_float_locale_decimal_separator() {
2469 let Ok(locale_fr_utf8) = env::var("LOCALE_FR_UTF8") else {
2470 return;
2471 };
2472 if locale_fr_utf8 == "none" {
2473 return;
2474 }
2475
2476 let ts = TestScenario::new("sort");
2477
2478 ts.ucmd()
2479 .env("LC_ALL", &locale_fr_utf8)
2480 .args(&["-g", "--stable"])
2481 .pipe_in("1,9\n1,10\n")
2482 .succeeds()
2483 .stdout_is("1,10\n1,9\n");
2484
2485 ts.ucmd()
2486 .env("LC_ALL", &locale_fr_utf8)
2487 .args(&["-g", "--stable"])
2488 .pipe_in("1.9\n1.10\n")
2489 .succeeds()
2490 .stdout_is("1.10\n1.9\n");
2491 }
2492
2493 #[test]
2494 #[cfg(unix)]
2495 fn test_human_numeric_blank_thousands_sep_locale() {
2496 fn thousands_sep_for(locale: &str) -> Option<String> {
2497 let output = Command::new("locale")
2498 .arg("thousands_sep")
2499 .env("LC_ALL", locale)
2500 .output()
2501 .ok()
2502 .filter(|s| s.status.success())?;
2503 let sep = String::from_utf8_lossy(&output.stdout);
2504 let sep = sep.trim_end_matches(&['\n', '\r'][..]);
2505 if sep.is_empty() || sep.len() != 1 || !sep.chars().all(char::is_whitespace) {
2506 return None;
2507 }
2508 Some(sep.to_string())
2509 }
2510
2511 let candidates = ["sv_SE.UTF-8", "sv_SE"];
2512 let mut selected_locale = None;
2513 let mut thousands_sep = None;
2514 for candidate in candidates {
2515 if let Some(sep) = thousands_sep_for(candidate) {
2516 selected_locale = Some(candidate.to_string());
2517 thousands_sep = Some(sep);
2518 break;
2519 }
2520 }
2521
2522 let (Some(locale), Some(sep)) = (selected_locale, thousands_sep) else {
2523 return;
2524 };
2525
2526 let line1 = format!("1 1k 1 M 4{sep}003 1M");
2527 let line2 = format!("2k 2M 2 k 4{sep}002 2");
2528 let line3 = format!("3M 3 3 G 4{sep}001 3k");
2529 let input = format!("{line1}\n{line2}\n{line3}\n");
2530
2531 let ts = TestScenario::new("sort");
2532 ts.fixtures.write("blank-thousands.txt", &input);
2533
2534 let cases = [
2535 (1, format!("{line1}\n{line2}\n{line3}\n")),
2536 (2, format!("{line3}\n{line1}\n{line2}\n")),
2537 (3, format!("{line1}\n{line2}\n{line3}\n")),
2538 (5, format!("{line3}\n{line2}\n{line1}\n")),
2539 ];
2540
2541 for (key, expected) in cases {
2542 let key_str = key.to_string();
2543 ts.ucmd()
2544 .env("LC_ALL", &locale)
2545 .arg("-h")
2546 .arg("-k")
2547 .arg(&key_str)
2548 .arg("blank-thousands.txt")
2549 .succeeds()
2550 .stdout_is(expected);
2551 }
2552 }
2553
2554 #[test]
2555 // Test misc numbers ("'a" is not interpreted as literal, trailing text is ignored...)
2556 fn test_g_misc() {
2557 let input = "1\n100\n90\n'a\n85hello\n";
2558 let output = "'a\n1\n85hello\n90\n100\n";
2559 new_ucmd!()
2560 .args(&["-g"])
2561 .pipe_in(input)
2562 .succeeds()
2563 .stdout_is(output);
2564 }
2565
2566 #[test]
2567 // Test numbers with a large number of digits, where only the last digit is different.
2568 // We use scientific notation to make sure string sorting does not correctly order them.
2569 fn test_g_arbitrary() {
2570 let input = [
2571 // GNU coreutils doesn't handle those correctly as they don't fit exactly in long double
2572 "3",
2573 "3.000000000000000000000000000000000000000000000000000000000000000004",
2574 "0.3000000000000000000000000000000000000000000000000000000000000000002e1",
2575 "0.03000000000000000000000000000000000000000000000000000000000000000003e2",
2576 "0.003000000000000000000000000000000000000000000000000000000000000000001e3",
2577 // GNU coreutils does handle those correctly though
2578 "10",
2579 "10.000000000000004",
2580 "1.0000000000000002e1",
2581 "0.10000000000000003e2",
2582 "0.010000000000000001e3",
2583 ]
2584 .join("\n");
2585 let output = [
2586 "3",
2587 "0.003000000000000000000000000000000000000000000000000000000000000000001e3",
2588 "0.3000000000000000000000000000000000000000000000000000000000000000002e1",
2589 "0.03000000000000000000000000000000000000000000000000000000000000000003e2",
2590 "3.000000000000000000000000000000000000000000000000000000000000000004",
2591 "10",
2592 "0.010000000000000001e3",
2593 "1.0000000000000002e1",
2594 "0.10000000000000003e2",
2595 "10.000000000000004",
2596 ]
2597 .join("\n")
2598 + "\n";
2599 new_ucmd!()
2600 .args(&["-g"])
2601 .pipe_in(input)
2602 .succeeds()
2603 .stdout_is(output);
2604 }
2605
2606 #[test]
2607 // Test hexadecimal numbers (and hex floats)
2608 fn test_g_float_hex() {
2609 let input = "0x123\n0x0\n0x2p10\n0x9p-10\n";
2610 let output = "0x0\n0x9p-10\n0x123\n0x2p10\n";
2611 new_ucmd!()
2612 .args(&["-g"])
2613 .pipe_in(input)
2614 .succeeds()
2615 .stdout_is(output);
2616 }
2617
2618 /* spell-checker: disable */
2619 #[test]
2620 fn test_french_translations() {
2621 // Test that French translations work for clap error messages
2622 // Set LANG to French and test with an invalid argument
2623 let result = new_ucmd!()
2624 .env("LANG", "fr_FR.UTF-8")
2625 .env("LC_ALL", "fr_FR.UTF-8")
2626 .arg("--invalid-arg")
2627 .fails();
2628
2629 let stderr = result.stderr_str();
2630 assert!(stderr.contains("erreur"));
2631 assert!(stderr.contains("argument inattendu"));
2632 assert!(stderr.contains("trouvé"));
2633 }
2634
2635 #[test]
2636 fn test_argument_suggestion() {
2637 let test_cases = vec![
2638 ("en_US.UTF-8", vec!["tip", "similar", "--reverse"]),
2639 ("fr_FR.UTF-8", vec!["conseil", "similaire", "--reverse"]),
2640 ];
2641
2642 for (locale, expected_strings) in test_cases {
2643 let result = new_ucmd!()
2644 .env("LANG", locale)
2645 .env("LC_ALL", locale)
2646 .arg("--revrse") // Typo
2647 .fails();
2648
2649 let stderr = result.stderr_str();
2650 for expected in expected_strings {
2651 assert!(stderr.contains(expected));
2652 }
2653 }
2654 }
2655
2656 #[test]
2657 fn test_clap_localization_unknown_argument() {
2658 let test_cases = vec![
2659 (
2660 "en_US.UTF-8",
2661 vec![
2662 "error: unexpected argument '--unknown-option' found",
2663 "Usage:",
2664 "For more information, try '--help'.",
2665 ],
2666 ),
2667 (
2668 "fr_FR.UTF-8",
2669 vec![
2670 "erreur : argument inattendu '--unknown-option' trouvé",
2671 "Utilisation:",
2672 "Pour plus d'informations, essayez '--help'.",
2673 ],
2674 ),
2675 ];
2676
2677 for (locale, expected_strings) in test_cases {
2678 let result = new_ucmd!()
2679 .env("LANG", locale)
2680 .env("LC_ALL", locale)
2681 .arg("--unknown-option")
2682 .fails();
2683
2684 result.code_is(2); // sort uses exit code 2 for invalid options
2685 let stderr = result.stderr_str();
2686 for expected in expected_strings {
2687 assert!(stderr.contains(expected));
2688 }
2689 }
2690 }
2691
2692 #[test]
2693 fn test_clap_localization_help_message() {
2694 // Test help message in English
2695 let result_en = new_ucmd!()
2696 .env("LANG", "en_US.UTF-8")
2697 .env("LC_ALL", "en_US.UTF-8")
2698 .arg("--help")
2699 .succeeds();
2700
2701 let stdout_en = result_en.stdout_str();
2702 assert!(stdout_en.contains("Usage:"));
2703 assert!(stdout_en.contains("Options:"));
2704
2705 // Test help message in French
2706 let result_fr = new_ucmd!()
2707 .env("LANG", "fr_FR.UTF-8")
2708 .env("LC_ALL", "fr_FR.UTF-8")
2709 .arg("--help")
2710 .succeeds();
2711
2712 let stdout_fr = result_fr.stdout_str();
2713 assert!(stdout_fr.contains("Utilisation:"));
2714 assert!(stdout_fr.contains("Options:"));
2715 }
2716
2717 #[test]
2718 fn test_clap_localization_missing_required_argument() {
2719 // Test missing required argument
2720 let result_en = new_ucmd!().env("LC_ALL", "en_US.UTF-8").arg("-k").fails();
2721
2722 let stderr_en = result_en.stderr_str();
2723 assert!(stderr_en.contains(" a value is required for '--key <key>' but none was supplied"));
2724 assert!(stderr_en.contains("-k"));
2725 }
2726
2727 #[test]
2728 fn test_clap_localization_invalid_value() {
2729 let test_cases = vec![
2730 (
2731 "en_US.UTF-8",
2732 "sort: invalid number at field start: invalid count at start of 'invalid'",
2733 ),
2734 (
2735 "fr_FR.UTF-8",
2736 "sort: nombre invalide au début du champ: nombre invalide au début de 'invalid'",
2737 ),
2738 ];
2739
2740 for (locale, expected_message) in test_cases {
2741 let result = new_ucmd!()
2742 .env("LANG", locale)
2743 .env("LC_ALL", locale)
2744 .arg("-k")
2745 .arg("invalid")
2746 .fails();
2747
2748 let stderr = result.stderr_str();
2749 assert!(stderr.contains(expected_message));
2750 }
2751 }
2752
2753 #[test]
2754 fn test_help_colors_enabled() {
2755 // Test that help messages have ANSI color codes when colors are forced
2756 let test_cases = vec![("en_US.UTF-8", "Usage"), ("fr_FR.UTF-8", "Utilisation")];
2757
2758 for (locale, usage_word) in test_cases {
2759 let result = new_ucmd!()
2760 .env("LANG", locale)
2761 .env("LC_ALL", locale)
2762 .env("CLICOLOR_FORCE", "1")
2763 .arg("--help")
2764 .succeeds();
2765
2766 let stdout = result.stdout_str();
2767
2768 // Check for ANSI bold+underline codes around the usage header
2769 let expected_pattern = format!("\x1b[1m\x1b[4m{usage_word}:\x1b[0m");
2770 assert!(
2771 stdout.contains(&expected_pattern),
2772 "Expected bold+underline '{usage_word}:' in locale {locale}, got: {}",
2773 stdout.lines().take(10).collect::<Vec<_>>().join("\\n")
2774 );
2775 }
2776 }
2777
2778 #[test]
2779 fn test_help_colors_disabled() {
2780 // Test that help messages don't have ANSI color codes when colors are disabled
2781 let test_cases = vec![("en_US.UTF-8", "Usage"), ("fr_FR.UTF-8", "Utilisation")];
2782
2783 for (locale, usage_word) in test_cases {
2784 let result = new_ucmd!()
2785 .env("LANG", locale)
2786 .env("LC_ALL", locale)
2787 .env("NO_COLOR", "1")
2788 .arg("--help")
2789 .succeeds();
2790
2791 let stdout = result.stdout_str();
2792
2793 // Check that we have the usage word but no ANSI codes
2794 assert!(stdout.contains(&format!("{usage_word}:")));
2795 assert!(
2796 !stdout.contains("\x1b["),
2797 "Found ANSI escape codes when colors should be disabled in locale {locale}"
2798 );
2799 }
2800 }
2801
2802 #[test]
2803 fn test_error_colors_enabled() {
2804 // Test that error messages have ANSI color codes when colors are forced
2805 let test_cases = vec![
2806 ("en_US.UTF-8", "error", "tip"),
2807 ("fr_FR.UTF-8", "erreur", "conseil"),
2808 ];
2809
2810 for (locale, error_word, tip_word) in test_cases {
2811 let result = new_ucmd!()
2812 .env("LANG", locale)
2813 .env("LC_ALL", locale)
2814 .env("CLICOLOR_FORCE", "1")
2815 .arg("--numerc") // Typo to trigger suggestion for --numeric-sort
2816 .fails();
2817
2818 let stderr = result.stderr_str();
2819
2820 // Check for colored error word (red)
2821 let colored_error = format!("\x1b[31m{error_word}\x1b[0m");
2822 assert!(
2823 stderr.contains(&colored_error),
2824 "Expected red '{error_word}' in locale {locale}, got: {}",
2825 stderr.lines().take(5).collect::<Vec<_>>().join("\\n")
2826 );
2827
2828 // Check for colored tip word (green)
2829 let colored_tip = format!("\x1b[32m{tip_word}\x1b[0m");
2830 assert!(
2831 stderr.contains(&colored_tip),
2832 "Expected green '{tip_word}' in locale {locale}, got: {}",
2833 stderr.lines().take(5).collect::<Vec<_>>().join("\\n")
2834 );
2835 }
2836 }
2837
2838 #[test]
2839 fn test_error_colors_disabled() {
2840 // Test that error messages don't have ANSI color codes when colors are disabled
2841 let test_cases = vec![
2842 ("en_US.UTF-8", "error", "tip"),
2843 ("fr_FR.UTF-8", "erreur", "conseil"),
2844 ];
2845
2846 for (locale, error_word, tip_word) in test_cases {
2847 let result = new_ucmd!()
2848 .env("LANG", locale)
2849 .env("LC_ALL", locale)
2850 .env("NO_COLOR", "1")
2851 .arg("--numerc") // Typo to trigger suggestion for --numeric-sort
2852 .fails();
2853
2854 let stderr = result.stderr_str();
2855
2856 // Check that we have the error and tip words but no ANSI codes
2857 assert!(stderr.contains(error_word));
2858 assert!(stderr.contains(tip_word));
2859 assert!(
2860 !stderr.contains("\x1b["),
2861 "Found ANSI escape codes when colors should be disabled in locale {locale}"
2862 );
2863 }
2864 }
2865
2866 #[test]
2867 fn test_argument_suggestion_colors_enabled() {
2868 // Test that argument suggestions have colors
2869 let test_cases = vec![
2870 ("en_US.UTF-8", "tip", "--reverse"),
2871 ("fr_FR.UTF-8", "conseil", "--reverse"),
2872 ];
2873
2874 for (locale, _tip_word, suggestion) in test_cases {
2875 let result = new_ucmd!()
2876 .env("LANG", locale)
2877 .env("LC_ALL", locale)
2878 .env("CLICOLOR_FORCE", "1")
2879 .arg("--revrse") // Typo to trigger suggestion
2880 .fails();
2881
2882 let stderr = result.stderr_str();
2883
2884 // Check for colored invalid argument (yellow)
2885 let colored_invalid = "\x1b[33m--revrse\x1b[0m";
2886 assert!(
2887 stderr.contains(colored_invalid),
2888 "Expected yellow '--revrse' in locale {locale}, got: {}",
2889 stderr.lines().take(10).collect::<Vec<_>>().join("\\n")
2890 );
2891
2892 // Check for colored suggestion (green)
2893 let colored_suggestion = format!("\x1b[32m{suggestion}\x1b[0m");
2894 assert!(
2895 stderr.contains(&colored_suggestion),
2896 "Expected green '{suggestion}' in locale {locale}, got: {}",
2897 stderr.lines().take(10).collect::<Vec<_>>().join("\\n")
2898 );
2899 }
2900 }
2901
2902 #[test]
2903 fn test_debug_key_annotations() {
2904 let ts = TestScenario::new("sort");
2905 let output = debug_key_annotation_output(&ts);
2906
2907 assert_eq!(output, EXPECTED_DEBUG_KEY_ANNOTATION);
2908 }
2909
2910 #[test]
2911 fn test_debug_key_annotations_locale() {
2912 let ts = TestScenario::new("sort");
2913
2914 if let Ok(locale_fr_utf8) = env::var("LOCALE_FR_UTF8")
2915 && locale_fr_utf8 != "none"
2916 {
2917 let probe = ts
2918 .ucmd()
2919 .args(&["-g", "--debug", "/dev/null"])
2920 .env("LC_NUMERIC", &locale_fr_utf8)
2921 .env("LC_MESSAGES", "C")
2922 .run();
2923 if probe
2924 .stderr_str()
2925 .contains("numbers use .*,.* as a decimal point")
2926 {
2927 let mut locale_output = String::new();
2928 locale_output.push_str(
2929 &ts.ucmd()
2930 .env("LC_ALL", "C")
2931 .args(&["--debug", "-k2g", "-k1b,1"])
2932 .pipe_in(" 1²---++3 1,234 Mi\n")
2933 .succeeds()
2934 .stdout_move_str(),
2935 );
2936 locale_output.push_str(
2937 &ts.ucmd()
2938 .env("LC_ALL", &locale_fr_utf8)
2939 .args(&["--debug", "-k2g", "-k1b,1"])
2940 .pipe_in(" 1²---++3 1,234 Mi\n")
2941 .succeeds()
2942 .stdout_move_str(),
2943 );
2944 locale_output.push_str(
2945 &ts.ucmd()
2946 .env("LC_ALL", &locale_fr_utf8)
2947 .args(&[
2948 "--debug", "-k1,1n", "-k1,1g", "-k1,1h", "-k2,2n", "-k2,2g", "-k2,2h",
2949 "-k3,3n", "-k3,3g", "-k3,3h",
2950 ])
2951 .pipe_in("+1234 1234Gi 1,234M\n")
2952 .succeeds()
2953 .stdout_move_str(),
2954 );
2955
2956 let normalized = locale_output
2957 .lines()
2958 .map(|line| {
2959 if line.starts_with("^^ ") {
2960 "^ no match for key".to_string()
2961 } else {
2962 line.to_string()
2963 }
2964 })
2965 .collect::<Vec<_>>()
2966 .join("\n")
2967 + "\n";
2968
2969 assert_eq!(normalized, EXPECTED_DEBUG_KEY_ANNOTATION_LOCALE);
2970 }
2971 }
2972 }
2973
2974 fn debug_key_annotation_output(ts: &TestScenario) -> String {
2975 let number = |input: &str| -> String {
2976 let mut out = String::new();
2977 for (idx, line) in input.split_terminator('\n').enumerate() {
2978 // build efficiently without collecting intermediary Strings
2979 writeln!(&mut out, "{}\t{line}", idx + 1).unwrap();
2980 }
2981 out
2982 };
2983
2984 let run_sort = |args: &[&str], input: &str| -> String {
2985 ts.ucmd()
2986 .args(args)
2987 .pipe_in(input)
2988 .succeeds()
2989 .stdout_move_str()
2990 };
2991
2992 let mut output = String::new();
2993 for mode in ["n", "h", "g"] {
2994 output.push_str(&run_sort(
2995 &["-s", &format!("-k2{mode}"), "--debug"],
2996 "1\n\n44\n33\n2\n",
2997 ));
2998 output.push_str(&run_sort(
2999 &["-s", &format!("-k1.3{mode}"), "--debug"],
3000 "1\n\n44\n33\n2\n",
3001 ));
3002 output.push_str(&run_sort(
3003 &["-s", &format!("-k1{mode}"), "--debug"],
3004 "1\n\n44\n33\n2\n",
3005 ));
3006 output.push_str(&run_sort(&["-s", "-k2g", "--debug"], &number("2\n\n1\n")));
3007 }
3008
3009 output.push_str(&run_sort(&["-s", "-k1M", "--debug"], "FEB\n\nJAN\n"));
3010 output.push_str(&run_sort(&["-s", "-k2,2M", "--debug"], "FEB\n\nJAN\n"));
3011 output.push_str(&run_sort(&["-s", "-k1M", "--debug"], "FEB\nJAZZ\n\nJAN\n"));
3012 output.push_str(&run_sort(
3013 &["-s", "-k2,2M", "--debug"],
3014 &number("FEB\nJAZZ\n\nJAN\n"),
3015 ));
3016 output.push_str(&run_sort(&["-s", "-k1M", "--debug"], "FEB\nJANZ\n\nJAN\n"));
3017 output.push_str(&run_sort(
3018 &["-s", "-k2,2M", "--debug"],
3019 &number("FEB\nJANZ\n\nJAN\n"),
3020 ));
3021
3022 output.push_str(&run_sort(
3023 &["-s", "-g", "--debug"],
3024 " 1.2ignore\n 1.1e4ignore\n",
3025 ));
3026 output.push_str(&run_sort(&["-s", "-d", "--debug"], "\tb\n\t\ta\n"));
3027 output.push_str(&run_sort(&["-s", "-k2,2", "--debug"], "a\n\n"));
3028 output.push_str(&run_sort(&["-s", "-k1", "--debug"], "b\na\n"));
3029 output.push_str(&run_sort(
3030 &["-s", "--debug", "-k1,1h"],
3031 "-0\n1\n-2\n--Mi-1\n-3\n-0\n",
3032 ));
3033 output.push_str(&run_sort(&["-b", "--debug"], " 1\n1\n"));
3034 output.push_str(&run_sort(&["-s", "-b", "--debug"], " 1\n1\n"));
3035 output.push_str(&run_sort(&["--debug"], " 1\n1\n"));
3036 output.push_str(&run_sort(&["-s", "-k1n", "--debug"], "2,5\n2.4\n"));
3037 output.push_str(&run_sort(&["-s", "-k1n", "--debug"], "2.,,3\n2.4\n"));
3038 output.push_str(&run_sort(&["-s", "-k1n", "--debug"], "2,,3\n2.4\n"));
3039 output.push_str(&run_sort(
3040 &["-s", "-n", "-z", "--debug"],
3041 concat!("1a\0", "2b\0"),
3042 ));
3043
3044 let mut zero_mix = ts
3045 .ucmd()
3046 .args(&["-s", "-k2b,2", "--debug"])
3047 .pipe_in("\0\ta\n")
3048 .succeeds()
3049 .stdout_move_bytes();
3050 zero_mix.retain(|b| *b != 0);
3051 output.push_str(&String::from_utf8(zero_mix).unwrap());
3052
3053 output.push_str(&run_sort(
3054 &["-s", "-k2.4b,2.3n", "--debug"],
3055 "A\tchr10\nB\tchr1\n",
3056 ));
3057 output.push_str(&run_sort(&["-s", "-k1.2b", "--debug"], "1 2\n1 3\n"));
3058
3059 output
3060 }
3061
3062 const EXPECTED_DEBUG_KEY_ANNOTATION: &str = r"1
3063 ^ no match for key
3064
3065 ^ no match for key
3066 44
3067 ^ no match for key
3068 33
3069 ^ no match for key
3070 2
3071 ^ no match for key
3072 1
3073 ^ no match for key
3074
3075 ^ no match for key
3076 44
3077 ^ no match for key
3078 33
3079 ^ no match for key
3080 2
3081 ^ no match for key
3082
3083 ^ no match for key
3084 1
3085 _
3086 2
3087 _
3088 33
3089 __
3090 44
3091 __
3092 2>
3093 ^ no match for key
3094 3>1
3095 _
3096 1>2
3097 _
3098 1
3099 ^ no match for key
3100
3101 ^ no match for key
3102 44
3103 ^ no match for key
3104 33
3105 ^ no match for key
3106 2
3107 ^ no match for key
3108 1
3109 ^ no match for key
3110
3111 ^ no match for key
3112 44
3113 ^ no match for key
3114 33
3115 ^ no match for key
3116 2
3117 ^ no match for key
3118
3119 ^ no match for key
3120 1
3121 _
3122 2
3123 _
3124 33
3125 __
3126 44
3127 __
3128 2>
3129 ^ no match for key
3130 3>1
3131 _
3132 1>2
3133 _
3134 1
3135 ^ no match for key
3136
3137 ^ no match for key
3138 44
3139 ^ no match for key
3140 33
3141 ^ no match for key
3142 2
3143 ^ no match for key
3144 1
3145 ^ no match for key
3146
3147 ^ no match for key
3148 44
3149 ^ no match for key
3150 33
3151 ^ no match for key
3152 2
3153 ^ no match for key
3154
3155 ^ no match for key
3156 1
3157 _
3158 2
3159 _
3160 33
3161 __
3162 44
3163 __
3164 2>
3165 ^ no match for key
3166 3>1
3167 _
3168 1>2
3169 _
3170
3171 ^ no match for key
3172 JAN
3173 ___
3174 FEB
3175 ___
3176 FEB
3177 ^ no match for key
3178
3179 ^ no match for key
3180 JAN
3181 ^ no match for key
3182 JAZZ
3183 ^ no match for key
3184
3185 ^ no match for key
3186 JAN
3187 ___
3188 FEB
3189 ___
3190 2>JAZZ
3191 ^ no match for key
3192 3>
3193 ^ no match for key
3194 4>JAN
3195 ___
3196 1>FEB
3197 ___
3198
3199 ^ no match for key
3200 JANZ
3201 ___
3202 JAN
3203 ___
3204 FEB
3205 ___
3206 3>
3207 ^ no match for key
3208 2>JANZ
3209 ___
3210 4>JAN
3211 ___
3212 1>FEB
3213 ___
3214 1.2ignore
3215 ___
3216 1.1e4ignore
3217 _____
3218 >>a
3219 ___
3220 >b
3221 __
3222 a
3223 ^ no match for key
3224
3225 ^ no match for key
3226 a
3227 _
3228 b
3229 _
3230 -3
3231 __
3232 -2
3233 __
3234 -0
3235 __
3236 --Mi-1
3237 ^ no match for key
3238 -0
3239 __
3240 1
3241 _
3242 1
3243 _
3244 __
3245 1
3246 _
3247 _
3248 1
3249 _
3250 1
3251 _
3252 1
3253 __
3254 1
3255 _
3256 2,5
3257 _
3258 2.4
3259 ___
3260 2.,,3
3261 __
3262 2.4
3263 ___
3264 2,,3
3265 _
3266 2.4
3267 ___
3268 1a
3269 _
3270 2b
3271 _
3272 >a
3273 _
3274 A>chr10
3275 ^ no match for key
3276 B>chr1
3277 ^ no match for key
3278 1 2
3279 __
3280 1 3
3281 __
3282 ";
3283
3284 const EXPECTED_DEBUG_KEY_ANNOTATION_LOCALE: &str = r" 1²---++3 1,234 Mi
3285 _
3286 _________
3287 ________________________
3288 1²---++3 1,234 Mi
3289 _____
3290 ________
3291 _______________________
3292 +1234 1234Gi 1,234M
3293 ^ no match for key
3294 _____
3295 ^ no match for key
3296 ____
3297 ____
3298 _____
3299 _____
3300 _____
3301 ______
3302 ___________________
3303 ";
3304
3305 #[test]
3306 fn test_color_environment_variables() {
3307 // Test different color environment variable combinations
3308 let test_env_vars = vec![
3309 // Colors should be enabled
3310 (vec![("CLICOLOR_FORCE", "1")], true, "CLICOLOR_FORCE=1"),
3311 // Colors should be disabled
3312 (vec![("NO_COLOR", "1")], false, "NO_COLOR=1"),
3313 (
3314 vec![("NO_COLOR", "1"), ("CLICOLOR_FORCE", "1")],
3315 false,
3316 "NO_COLOR overrides CLICOLOR_FORCE",
3317 ),
3318 ];
3319
3320 for (env_vars, should_have_colors, description) in test_env_vars {
3321 let mut cmd = new_ucmd!();
3322 cmd.env("LANG", "en_US.UTF-8");
3323
3324 for (key, value) in env_vars {
3325 cmd.env(key, value);
3326 }
3327
3328 let result = cmd.arg("--help").succeeds();
3329 let stdout = result.stdout_str();
3330
3331 let has_ansi_codes = stdout.contains("\x1b[");
3332 assert_eq!(
3333 has_ansi_codes, should_have_colors,
3334 "Color test failed for {description}: expected colors={should_have_colors}, found ANSI codes={has_ansi_codes}"
3335 );
3336 }
3337 }
3338
3339 #[test]
3340 fn test_start_buffer() {
3341 // Test that a file with the exact same size as the start buffer is handled correctly
3342 const FILE_B: &[u8] = &[b'b'; 8_000];
3343 const FILE_A: &[u8] = b"aaa";
3344
3345 let mut expected = FILE_A.to_vec();
3346 expected.push(b'\n');
3347 expected.extend_from_slice(FILE_B);
3348 expected.push(b'\n');
3349
3350 let (at, mut ucmd) = at_and_ucmd!();
3351
3352 at.write_bytes("b", FILE_B);
3353 at.write_bytes("a", FILE_A);
3354
3355 ucmd.args(&["b", "a"])
3356 .succeeds()
3357 .stdout_only_bytes(&expected);
3358 }
3359
3360 #[test]
3361 fn test_locale_collation_c_locale() {
3362 // C locale uses byte order - this is deterministic and tests the fix for #9148
3363 // Accented characters (UTF-8 multibyte) sort after ASCII letters
3364 let input = "é\ne\nE\na\nA\nz\n";
3365 // C locale byte order: A=0x41, E=0x45, a=0x61, e=0x65, z=0x7A, é=0xC3 0xA9
3366 let expected = "A\nE\na\ne\nz\né\n";
3367
3368 new_ucmd!()
3369 .env("LC_ALL", "C")
3370 .pipe_in(input)
3371 .succeeds()
3372 .stdout_is(expected);
3373 }
3374
3375 #[test]
3376 fn test_locale_collation_utf8() {
3377 // Test French UTF-8 locale handling - behavior depends on i18n-collator feature
3378 // With feature: locale-aware collation (é sorts near e)
3379 // Without feature: byte order (é after z, since 0xC3A9 > 0x7A)
3380 let input = "z\né\ne\na\n";
3381
3382 let result = new_ucmd!()
3383 .env("LC_ALL", "fr_FR.UTF-8")
3384 .pipe_in(input)
3385 .succeeds();
3386
3387 let output = result.stdout_str();
3388 let lines: Vec<&str> = output.lines().collect();
3389
3390 assert_eq!(lines.len(), 4, "Expected 4 sorted lines");
3391 assert_eq!(lines[0], "a", "'a' (0x61) should always sort first");
3392
3393 // Validate based on which collation mode is active
3394 if lines[3] == "é" {
3395 // Byte order mode: é (0xC3A9) > z (0x7A)
3396 assert_eq!(
3397 lines,
3398 vec!["a", "e", "z", "é"],
3399 "Byte order mode: expected a < e < z < é"
3400 );
3401 } else {
3402 // Locale collation mode: é sorts with base letter e
3403 assert_eq!(lines[3], "z", "Locale mode: 'z' should sort last");
3404 let z_pos = lines.iter().position(|&x| x == "z").unwrap();
3405 let e_pos = lines.iter().position(|&x| x == "e").unwrap();
3406 let e_accent_pos = lines.iter().position(|&x| x == "é").unwrap();
3407 assert!(
3408 e_pos < z_pos && e_accent_pos < z_pos,
3409 "Locale mode: 'e' ({e_pos}) and 'é' ({e_accent_pos}) should sort before 'z' ({z_pos})"
3410 );
3411 }
3412 }
3413
3414 #[test]
3415 fn test_locale_interleaved_en_us_utf8() {
3416 // Test case for issue: locale-based collation support
3417 // In en_US.UTF-8, lowercase and uppercase letters should interleave
3418 // Expected: a, A, b, B (locale-aware)
3419 // Not: A, B, a, b (ASCII byte order)
3420 new_ucmd!()
3421 .env("LC_ALL", "en_US.UTF-8")
3422 .pipe_in("a\nA\nb\nB\n")
3423 .succeeds()
3424 .stdout_is("a\nA\nb\nB\n");
3425 }
3426
3427 #[test]
3428 fn test_locale_c_byte_order() {
3429 // Test case for issue: C locale should use ASCII byte order
3430 // In C locale: A < B < a < b (uppercase before lowercase)
3431 new_ucmd!()
3432 .env("LC_ALL", "C")
3433 .pipe_in("a\nA\nb\nB\n")
3434 .succeeds()
3435 .stdout_is("A\nB\na\nb\n");
3436 }
3437
3438 #[test]
3439 fn test_locale_posix_byte_order() {
3440 // POSIX locale should behave like C locale
3441 new_ucmd!()
3442 .env("LC_ALL", "POSIX")
3443 .pipe_in("a\nA\nb\nB\n")
3444 .succeeds()
3445 .stdout_is("A\nB\na\nb\n");
3446 }
3447
3448 #[test]
3449 fn test_locale_with_ignore_case_flag() {
3450 // When -f (ignore case) is used, the comparison uses custom_str_cmp
3451 // which converts to uppercase for comparison. With -f flag, all letters
3452 // are treated as equivalent regardless of case, so original order is preserved
3453 // for equal keys (stable sort behavior within equal elements).
3454 // Note: This may differ slightly from GNU in tie-breaking behavior.
3455 let result = new_ucmd!()
3456 .env("LC_ALL", "en_US.UTF-8")
3457 .arg("-f")
3458 .pipe_in("a\nA\nb\nB\n")
3459 .succeeds();
3460
3461 // Verify that a/A come before b/B (case-insensitive grouping works)
3462 let output = result.stdout_str();
3463 let lines: Vec<&str> = output.lines().collect();
3464 assert_eq!(lines.len(), 4);
3465 // a and A should come before b and B
3466 let a_positions: Vec<usize> = lines
3467 .iter()
3468 .enumerate()
3469 .filter(|(_, l)| **l == "a" || **l == "A")
3470 .map(|(i, _)| i)
3471 .collect();
3472 let b_positions: Vec<usize> = lines
3473 .iter()
3474 .enumerate()
3475 .filter(|(_, l)| **l == "b" || **l == "B")
3476 .map(|(i, _)| i)
3477 .collect();
3478 assert!(
3479 a_positions
3480 .iter()
3481 .all(|&a| b_positions.iter().all(|&b| a < b)),
3482 "All 'a'/'A' should come before 'b'/'B' with -f flag"
3483 );
3484 }
3485
3486 #[test]
3487 fn test_locale_complex_utf8_sorting() {
3488 // More complex test with mixed case and special characters
3489 // In en_US.UTF-8, should respect locale collation rules
3490 // Locale collation is case-insensitive by default, with lowercase < uppercase for same base letter
3491 let input = "zebra\nApple\napple\nBanana\nbanana\nZebra\n";
3492
3493 new_ucmd!()
3494 .env("LC_ALL", "en_US.UTF-8")
3495 .pipe_in(input)
3496 .succeeds()
3497 .stdout_is("apple\nApple\nbanana\nBanana\nzebra\nZebra\n");
3498 }
3499
3500 #[test]
3501 fn test_locale_posix_sort_debug_message() {
3502 new_ucmd!()
3503 .env("LC_ALL", "C")
3504 .arg("--debug")
3505 .pipe_in("a\nA\nb\nB\n")
3506 .succeeds()
3507 .stderr_contains("text ordering performed using simple byte comparison");
3508 }
3509
3510 #[test]
3511 fn test_locale_utf8_sort_debug_message() {
3512 new_ucmd!()
3513 .env("LC_ALL", "en_US.UTF-8")
3514 .arg("--debug")
3515 .pipe_in("a\nA\nb\nB\n")
3516 .succeeds()
3517 .stderr_contains("text ordering performed using ‘en_US.UTF-8’ sorting rules");
3518 }
3519
3520 #[test]
3521 #[cfg(unix)]
3522 fn test_failed_to_set_locale_debug_message() {
3523 let result = new_ucmd!()
3524 .env("LC_ALL", "not-valid-locale")
3525 .arg("--debug")
3526 .pipe_in("a\nA\nb\nB\n")
3527 .succeeds();
3528
3529 result.stderr_contains("text ordering performed using simple byte comparison");
3530
3531 #[cfg(all(target_os = "linux", target_env = "gnu"))]
3532 result.stderr_contains("failed to set locale");
3533 }
3534
3535 #[test]
3536 fn test_locale_utf8_with_key_field() {
3537 // Regression test for issue #10909
3538 // Sort should not panic when using -k flag with UTF-8 locale
3539 // The bug occurred when rayon worker threads tried to access an uninitialized collator
3540 let input = "a b 5433 down data path1 path2 path3 path4 path5
3541 c d 5435 down data path1 path2 path3 path4 path5
3542 e f 5436 down data path1 path2 path3 path4 path5\n";
3543
3544 new_ucmd!()
3545 .env("LANG", "en_US.utf8")
3546 .arg("-k3")
3547 .pipe_in(input)
3548 .succeeds()
3549 .stdout_is(input);
3550 }
3551
3552 #[test]
3553 fn test_consistent_sorting_with_i18n_collate() {
3554 // Regression test for issue #11980
3555 // Lexicographic fallback sorting for equal sorting keys for 01 and 0_1
3556 let expected_output = "0_1\n0_1\n01\n01\n02\n02\n";
3557 new_ucmd!()
3558 .env("LC_ALL", "en_US.UTF-8")
3559 .arg("fix_i18n_collate_inconsistency_1.txt")
3560 .arg("fix_i18n_collate_inconsistency_2.txt")
3561 .succeeds()
3562 .stdout_is(expected_output);
3563
3564 let expected_output = "01\n01\n02\n02\n0_1\n0_1\n";
3565 new_ucmd!()
3566 .env("LC_ALL", "C")
3567 .arg("fix_i18n_collate_inconsistency_1.txt")
3568 .arg("fix_i18n_collate_inconsistency_2.txt")
3569 .succeeds()
3570 .stdout_is(expected_output);
3571 }
3572
3573 #[test]
3574 fn test_sort_locale_punctuation() {
3575 // Punctuation gets a distinguishing collation weight, so lines differing
3576 // only by punctuation sort in a stable order (issue #12542) and are never
3577 // merged by -u. This holds across the plain, explicit-key and stable paths,
3578 // and in both locales. The wildcard-domain case comes from dehydrated, which
3579 // relied on -u keeping a `*.domain.com` alias distinct from the bare domain.
3580 // (input, expected, [(locale, args)...])
3581 let cases = [
3582 (
3583 "file10\nfile-10\n",
3584 "file-10\nfile10\n",
3585 &[("en_US.UTF-8", &[][..]), ("C", &[][..])][..],
3586 ),
3587 (
3588 "EU\nE.U\nE-U\n",
3589 "E-U\nE.U\nEU\n",
3590 &[
3591 ("en_US.UTF-8", &["-u"][..]),
3592 ("C", &["-u"][..]),
3593 ("en_US.UTF-8", &["-u", "-k1,1"][..]),
3594 ("en_US.UTF-8", &["-s", "-k1,1"][..]),
3595 ][..],
3596 ),
3597 (
3598 "domain.com\n*.domain.com\ndomain.com\n",
3599 "*.domain.com\ndomain.com\n",
3600 &[("en_US.UTF-8", &["-u"][..]), ("C", &["-u"][..])][..],
3601 ),
3602 ];
3603
3604 for (input, expected, runs) in cases {
3605 for (locale, args) in runs {
3606 new_ucmd!()
3607 .env("LC_ALL", *locale)
3608 .args(args)
3609 .pipe_in(input)
3610 .succeeds()
3611 .stdout_is(expected);
3612 }
3613 }
3614 }
3615
3616 #[cfg(all(feature = "feat_diagnostics", not(wasi_runner)))]
3617 mod diagnostics {
3618 use super::*;
3619
3620 #[cfg(unix)]
3621 #[test]
3622 fn test_snippet_points_at_the_stray_character() {
3623 let result = new_ucmd!()
3624 .terminal_sim_stderr()
3625 .args(&["-k2.3q", "/dev/null"])
3626 .fails_with_code(2);
3627
3628 // The whole report: the `sort: ` prefix of the plain form, the key
3629 // echoed back inside the option it was glued to, a caret on the `q`
3630 // rather than on the whole `-k2.3q`, and the key syntax advice.
3631 assert_eq!(
3632 result.stderr_as_displayed(),
3633 "\
3634 sort: stray character in field spec: invalid field specification '2.3q'
3635 ╭─[ sort:1:11 ]
3636 │
3637 1 │ sort -k2.3q /dev/null
3638 │ ─
3639 │
3640 │ Help: a key is FIELD[.CHAR][OPTS][,FIELD[.CHAR][OPTS]], as in -k2.3,4nr
3641 ───╯"
3642 );
3643 }
3644
3645 #[cfg(unix)]
3646 #[test]
3647 fn test_snippet_points_inside_a_detached_key() {
3648 let result = new_ucmd!()
3649 .terminal_sim_stderr()
3650 .args(&["-k", "1.4,2w", "/dev/null"])
3651 .fails_with_code(2);
3652
3653 // `-k 1.4,2w` puts the key in its own argument; the caret still lands
3654 // on the offending character.
3655 assert_eq!(
3656 result.stderr_as_displayed(),
3657 "\
3658 sort: stray character in field spec: invalid field specification '1.4,2w'
3659 ╭─[ sort:1:14 ]
3660 │
3661 1 │ sort -k 1.4,2w /dev/null
3662 │ ─
3663 │
3664 │ Help: a key is FIELD[.CHAR][OPTS][,FIELD[.CHAR][OPTS]], as in -k2.3,4nr
3665 ───╯"
3666 );
3667 }
3668
3669 #[cfg(unix)]
3670 #[test]
3671 fn test_snippet_points_at_a_zero_character_offset() {
3672 let result = new_ucmd!()
3673 .terminal_sim_stderr()
3674 .args(&["-k3.0", "/dev/null"])
3675 .fails_with_code(2);
3676
3677 // No syntax advice here: the label already says where counting starts.
3678 assert_eq!(
3679 result.stderr_as_displayed(),
3680 "\
3681 sort: character offset is zero: invalid field specification '3.0'
3682 ╭─[ sort:1:10 ]
3683 │
3684 1 │ sort -k3.0 /dev/null
3685 │ ┬
3686 │ ╰── counting starts at 1
3687 ───╯"
3688 );
3689 }
3690
3691 #[cfg(unix)]
3692 #[test]
3693 fn test_snippet_points_at_a_missing_number() {
3694 let result = new_ucmd!()
3695 .terminal_sim_stderr()
3696 .args(&["-kw", "/dev/null"])
3697 .fails_with_code(2);
3698
3699 assert_eq!(
3700 result.stderr_as_displayed(),
3701 "\
3702 sort: invalid number at field start: invalid count at start of 'w'
3703 ╭─[ sort:1:8 ]
3704 │
3705 1 │ sort -kw /dev/null
3706 │ ┬
3707 │ ╰── expected a number here
3708 │
3709 │ Help: a key is FIELD[.CHAR][OPTS][,FIELD[.CHAR][OPTS]], as in -k2.3,4nr
3710 ───╯"
3711 );
3712 }
3713
3714 #[cfg(unix)]
3715 #[test]
3716 fn test_snippet_reports_contradicting_ordering_options() {
3717 let result = new_ucmd!()
3718 .terminal_sim_stderr()
3719 .args(&["-k1hV", "/dev/null"])
3720 .fails_with_code(2);
3721
3722 // The caret covers the ordering options, not the field number.
3723 assert_eq!(
3724 result.stderr_as_displayed(),
3725 "\
3726 sort: options '-hV' are incompatible
3727 ╭─[ sort:1:9 ]
3728 │
3729 1 │ sort -k1hV /dev/null
3730 │ ──
3731 ───╯"
3732 );
3733 }
3734
3735 #[cfg(unix)]
3736 #[test]
3737 fn test_snippet_ignores_a_file_that_ends_like_the_key() {
3738 let (at, mut ucmd) = at_and_ucmd!();
3739 at.touch("data.2.3q");
3740
3741 // The input file's name ends with the key's text; the caret must stay
3742 // on the `-k` operand, not drift onto the file.
3743 let result = ucmd
3744 .terminal_sim_stderr()
3745 .args(&["data.2.3q", "-k2.3q"])
3746 .fails_with_code(2);
3747
3748 assert_eq!(
3749 result.stderr_as_displayed(),
3750 "\
3751 sort: stray character in field spec: invalid field specification '2.3q'
3752 ╭─[ sort:1:21 ]
3753 │
3754 1 │ sort data.2.3q -k2.3q
3755 │ ─
3756 │
3757 │ Help: a key is FIELD[.CHAR][OPTS][,FIELD[.CHAR][OPTS]], as in -k2.3,4nr
3758 ───╯"
3759 );
3760 }
3761
3762 #[cfg(unix)]
3763 #[test]
3764 fn test_snippet_ignores_the_program_name_as_a_key() {
3765 // A key spelled exactly like the program name must not pull the caret
3766 // onto `sort` itself at the start of the line.
3767 let result = new_ucmd!()
3768 .terminal_sim_stderr()
3769 .args(&["-k", "sort", "/dev/null"])
3770 .fails_with_code(2);
3771
3772 assert_eq!(
3773 result.stderr_as_displayed(),
3774 "\
3775 sort: invalid number at field start: invalid count at start of 'sort'
3776 ╭─[ sort:1:9 ]
3777 │
3778 1 │ sort -k sort /dev/null
3779 │ ──┬─
3780 │ ╰─── expected a number here
3781 │
3782 │ Help: a key is FIELD[.CHAR][OPTS][,FIELD[.CHAR][OPTS]], as in -k2.3,4nr
3783 ───╯"
3784 );
3785 }
3786
3787 #[cfg(unix)]
3788 #[test]
3789 fn test_snippet_points_at_the_unknown_unit_of_a_buffer_size() {
3790 let result = new_ucmd!()
3791 .terminal_sim_stderr()
3792 .args(&["-S", "8zz", "/dev/null"])
3793 .fails_with_code(2);
3794
3795 // The number parsed; only the unit did not.
3796 assert_eq!(
3797 result.stderr_as_displayed(),
3798 "\
3799 sort: invalid suffix in --buffer-size argument '8zz'
3800 ╭─[ sort:1:10 ]
3801 │
3802 1 │ sort -S 8zz /dev/null
3803 │ ─┬
3804 │ ╰── not a known unit
3805 │
3806 │ Help: a size is a number and an optional unit: K, M, G and so on for 1024, KB, MB, GB for 1000
3807 ───╯"
3808 );
3809 }
3810
3811 #[test]
3812 fn test_plain_message_when_stderr_is_not_a_terminal() {
3813 // The test harness pipes stderr, so the report must not appear.
3814 new_ucmd!()
3815 .args(&["-k2.3q", "/dev/null"])
3816 .fails_with_code(2)
3817 .stderr_only(
3818 "sort: stray character in field spec: invalid field specification '2.3q'\n",
3819 );
3820 new_ucmd!()
3821 .args(&["-S", "8zz", "/dev/null"])
3822 .fails_with_code(2)
3823 .stderr_only("sort: invalid suffix in --buffer-size argument '8zz'\n");
3824 }
3825 }
3826
3827 /* spell-checker: enable */