Debian Codegraph @

tests/by-util/test_shuf.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 (ToDO) unwritable GHSA
7
8 use std::fmt::Write;
9
10 use uutests::at_and_ucmd;
11 use uutests::new_ucmd;
12
13 #[test]
14 fn test_invalid_arg() {
15 new_ucmd!().arg("--definitely-invalid").fails_with_code(1);
16 }
17
18 #[test]
19 fn test_output_is_random_permutation() {
20 let input_seq = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
21 let input = input_seq
22 .iter()
23 .map(ToString::to_string)
24 .collect::<Vec<String>>()
25 .join("\n");
26
27 let result = new_ucmd!().pipe_in(input.as_bytes()).succeeds();
28 result.no_stderr();
29
30 let mut result_seq: Vec<i32> = result
31 .stdout_str()
32 .split('\n')
33 .filter(|x| !x.is_empty())
34 .map(|x| x.parse().unwrap())
35 .collect();
36 result_seq.sort_unstable();
37 assert_ne!(result.stdout_str(), input, "Output is not randomized");
38 assert_eq!(result_seq, input_seq, "Output is not a permutation");
39 }
40
41 #[test]
42 fn test_explicit_stdin_file() {
43 let input_seq = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
44 let input = input_seq
45 .iter()
46 .map(ToString::to_string)
47 .collect::<Vec<String>>()
48 .join("\n");
49
50 let result = new_ucmd!().arg("-").pipe_in(input.as_bytes()).succeeds();
51 result.no_stderr();
52
53 let mut result_seq: Vec<i32> = result
54 .stdout_str()
55 .split('\n')
56 .filter(|x| !x.is_empty())
57 .map(|x| x.parse().unwrap())
58 .collect();
59 result_seq.sort_unstable();
60 assert_eq!(result_seq, input_seq, "Output is not a permutation");
61 }
62
63 #[test]
64 fn test_zero_termination() {
65 let input_seq = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
66 let result = new_ucmd!().arg("-z").arg("-i1-10").succeeds();
67 result.no_stderr();
68
69 let mut result_seq: Vec<i32> = result
70 .stdout_str()
71 .split('\0')
72 .filter(|x| !x.is_empty())
73 .map(|x| x.parse().unwrap())
74 .collect();
75 result_seq.sort_unstable();
76 assert_eq!(result_seq, input_seq, "Output is not a permutation");
77 }
78
79 #[test]
80 fn test_zero_termination_multi() {
81 let input_seq = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
82 let result = new_ucmd!().arg("-z").arg("-z").arg("-i1-10").succeeds();
83 result.no_stderr();
84
85 let mut result_seq: Vec<i32> = result
86 .stdout_str()
87 .split('\0')
88 .filter(|x| !x.is_empty())
89 .map(|x| x.parse().unwrap())
90 .collect();
91 result_seq.sort_unstable();
92 assert_eq!(result_seq, input_seq, "Output is not a permutation");
93 }
94
95 #[test]
96 fn test_very_large_range() {
97 let num_samples = 256;
98 let result = new_ucmd!()
99 .arg("-n")
100 .arg(num_samples.to_string())
101 .arg("-i1-100000000000")
102 .succeeds();
103 result.no_stderr();
104
105 let result_seq: Vec<u64> = result
106 .stdout_str()
107 .split('\n')
108 .filter(|x| !x.is_empty())
109 .map(|x| x.parse().unwrap())
110 .collect();
111 assert_eq!(result_seq.len(), num_samples, "Miscounted output length!");
112 assert!(
113 result_seq.iter().all(|x| (0..=100_000_000_000).contains(x)),
114 "Output includes element not from range: {}",
115 result.stdout_str()
116 );
117 }
118
119 #[test]
120 fn test_very_large_range_offset() {
121 let num_samples = 10;
122 let result = new_ucmd!()
123 .arg("-n")
124 .arg(num_samples.to_string())
125 .arg("-i1234567890-2147483647")
126 .succeeds();
127 result.no_stderr();
128
129 let result_seq: Vec<isize> = result
130 .stdout_str()
131 .split('\n')
132 .filter(|x| !x.is_empty())
133 .map(|x| x.parse().unwrap())
134 .collect();
135 assert_eq!(result_seq.len(), num_samples, "Miscounted output length!");
136 assert!(
137 result_seq
138 .iter()
139 .all(|x| (1_234_567_890..=2_147_483_647).contains(x)),
140 "Output includes element not from range: {}",
141 result.stdout_str()
142 );
143 }
144
145 #[test]
146 fn test_range_repeat_no_overflow_1_max() {
147 let upper_bound = usize::MAX;
148 let result = new_ucmd!()
149 .arg("-rn1")
150 .arg(format!("-i1-{upper_bound}"))
151 .succeeds();
152 result.no_stderr();
153
154 let result_seq: Vec<usize> = result
155 .stdout_str()
156 .split('\n')
157 .filter(|x| !x.is_empty())
158 .map(|x| x.parse().unwrap())
159 .collect();
160 assert_eq!(result_seq.len(), 1, "Miscounted output length!");
161 }
162
163 #[test]
164 fn test_range_repeat_no_overflow_0_max_minus_1() {
165 let upper_bound = usize::MAX - 1;
166 let result = new_ucmd!()
167 .arg("-rn1")
168 .arg(format!("-i0-{upper_bound}"))
169 .succeeds();
170 result.no_stderr();
171
172 let result_seq: Vec<usize> = result
173 .stdout_str()
174 .split('\n')
175 .filter(|x| !x.is_empty())
176 .map(|x| x.parse().unwrap())
177 .collect();
178 assert_eq!(result_seq.len(), 1, "Miscounted output length!");
179 }
180
181 #[test]
182 fn test_range_permute_no_overflow_1_max() {
183 let upper_bound = usize::MAX;
184 let result = new_ucmd!()
185 .arg("-n1")
186 .arg(format!("-i1-{upper_bound}"))
187 .succeeds();
188 result.no_stderr();
189
190 let result_seq: Vec<usize> = result
191 .stdout_str()
192 .split('\n')
193 .filter(|x| !x.is_empty())
194 .map(|x| x.parse().unwrap())
195 .collect();
196 assert_eq!(result_seq.len(), 1, "Miscounted output length!");
197 }
198
199 #[test]
200 fn test_range_permute_no_overflow_0_max_minus_1() {
201 let upper_bound = usize::MAX - 1;
202 let result = new_ucmd!()
203 .arg("-n1")
204 .arg(format!("-i0-{upper_bound}"))
205 .succeeds();
206 result.no_stderr();
207
208 let result_seq: Vec<usize> = result
209 .stdout_str()
210 .split('\n')
211 .filter(|x| !x.is_empty())
212 .map(|x| x.parse().unwrap())
213 .collect();
214 assert_eq!(result_seq.len(), 1, "Miscounted output length!");
215 }
216
217 #[test]
218 fn test_range_permute_no_overflow_0_max() {
219 // NOTE: This is different from GNU shuf!
220 // GNU shuf accepts -i0-MAX-1 and -i1-MAX, but not -i0-MAX.
221 // This feels like a bug in GNU shuf.
222 let upper_bound = usize::MAX;
223 let result = new_ucmd!()
224 .arg("-n1")
225 .arg(format!("-i0-{upper_bound}"))
226 .succeeds();
227 result.no_stderr();
228
229 let result_seq: Vec<usize> = result
230 .stdout_str()
231 .split('\n')
232 .filter(|x| !x.is_empty())
233 .map(|x| x.parse().unwrap())
234 .collect();
235 assert_eq!(result_seq.len(), 1, "Miscounted output length!");
236 }
237
238 #[test]
239 fn test_range_full_huge_no_head_count_memory_exhausted() {
240 // Repro for #12500: `shuf -i 1-huge` with no --head-count used to abort
241 // (hashbrown "Hash table capacity overflow" panic, or an allocator abort)
242 // because the sparse iterator reserved a map sized to the whole range.
243 // It must now fail cleanly, like GNU.
244 let upper_bound = usize::MAX;
245 new_ucmd!()
246 .arg(format!("-i1-{upper_bound}"))
247 .fails_with_code(1)
248 .stderr_only("shuf: memory exhausted\n");
249 }
250
251 #[test]
252 fn test_range_huge_head_count_memory_exhausted() {
253 // Repro for #12500: a large --head-count is just as unsatisfiable as no
254 // --head-count; both used to abort. Must now fail cleanly.
255 let upper_bound = usize::MAX;
256 new_ucmd!()
257 .arg(format!("-n{upper_bound}"))
258 .arg(format!("-i1-{upper_bound}"))
259 .fails_with_code(1)
260 .stderr_only("shuf: memory exhausted\n");
261 }
262
263 #[test]
264 fn test_very_high_range_full() {
265 let input_seq = vec![
266 2_147_483_641,
267 2_147_483_642,
268 2_147_483_643,
269 2_147_483_644,
270 2_147_483_645,
271 2_147_483_646,
272 2_147_483_647,
273 ];
274 let result = new_ucmd!().arg("-i2147483641-2147483647").succeeds();
275 result.no_stderr();
276
277 let mut result_seq: Vec<isize> = result
278 .stdout_str()
279 .split('\n')
280 .filter(|x| !x.is_empty())
281 .map(|x| x.parse().unwrap())
282 .collect();
283 result_seq.sort_unstable();
284 assert_eq!(result_seq, input_seq, "Output is not a permutation");
285 }
286
287 #[test]
288 fn test_range_repeat() {
289 let num_samples = 500;
290 let result = new_ucmd!()
291 .arg("-r")
292 .arg("-n")
293 .arg(num_samples.to_string())
294 .arg("-i12-34")
295 .succeeds();
296 result.no_stderr();
297
298 let result_seq: Vec<isize> = result
299 .stdout_str()
300 .split('\n')
301 .filter(|x| !x.is_empty())
302 .map(|x| x.parse().unwrap())
303 .collect();
304 assert_eq!(result_seq.len(), num_samples, "Miscounted output length!");
305 assert!(
306 result_seq.iter().all(|x| (12..=34).contains(x)),
307 "Output includes element not from range: {}",
308 result.stdout_str()
309 );
310 }
311
312 #[test]
313 fn test_empty_input() {
314 let result = new_ucmd!().pipe_in(vec![]).succeeds();
315 result.no_stderr();
316 result.no_stdout();
317 }
318
319 #[test]
320 fn test_echo() {
321 let input_seq = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
322 let result = new_ucmd!()
323 .arg("-e")
324 .args(
325 &input_seq
326 .iter()
327 .map(ToString::to_string)
328 .collect::<Vec<String>>(),
329 )
330 .succeeds();
331 result.no_stderr();
332
333 let mut result_seq: Vec<i32> = result
334 .stdout_str()
335 .split('\n')
336 .filter(|x| !x.is_empty())
337 .map(|x| x.parse().unwrap())
338 .collect();
339 result_seq.sort_unstable();
340 assert_eq!(result_seq, input_seq, "Output is not a permutation");
341 }
342
343 #[test]
344 fn test_echo_multi() {
345 let result = new_ucmd!()
346 .arg("-e")
347 .arg("a")
348 .arg("b")
349 .arg("-e")
350 .arg("c")
351 .succeeds();
352 result.no_stderr();
353
354 let mut result_seq: Vec<String> = result
355 .stdout_str()
356 .split('\n')
357 .filter(|x| !x.is_empty())
358 .map(Into::into)
359 .collect();
360 result_seq.sort_unstable();
361 assert_eq!(result_seq, ["a", "b", "c"], "Output is not a permutation");
362 }
363
364 #[test]
365 fn test_echo_postfix() {
366 let result = new_ucmd!().arg("a").arg("b").arg("c").arg("-e").succeeds();
367 result.no_stderr();
368
369 let mut result_seq: Vec<String> = result
370 .stdout_str()
371 .split('\n')
372 .filter(|x| !x.is_empty())
373 .map(Into::into)
374 .collect();
375 result_seq.sort_unstable();
376 assert_eq!(result_seq, ["a", "b", "c"], "Output is not a permutation");
377 }
378
379 #[test]
380 fn test_echo_short_collapsed_zero() {
381 let result = new_ucmd!().arg("-ez").arg("a").arg("b").arg("c").succeeds();
382 result.no_stderr();
383
384 let mut result_seq: Vec<String> = result
385 .stdout_str()
386 .split('\0')
387 .filter(|x| !x.is_empty())
388 .map(|x| x.parse().unwrap())
389 .collect();
390 result_seq.sort_unstable();
391 assert_eq!(result_seq, ["a", "b", "c"], "Output is not a permutation");
392 }
393
394 #[test]
395 fn test_echo_separators_in_arguments() {
396 // We used to split arguments themselves on newlines, but this was wrong.
397 // shuf should behave as though it's shuffling two arguments and therefore
398 // output all of them.
399 // (Note that arguments can't contain null bytes so we don't need to test that.)
400 let result = new_ucmd!()
401 .arg("-e")
402 .arg("-n2")
403 .arg("a\nb")
404 .arg("c\nd")
405 .succeeds();
406 result.no_stderr();
407 assert_eq!(result.stdout_str().len(), 8, "Incorrect output length");
408 }
409
410 #[cfg(unix)]
411 #[test]
412 #[cfg_attr(wasi_runner, ignore = "WASI: argv/filenames must be valid UTF-8")]
413 fn test_echo_invalid_unicode_in_arguments() {
414 use std::{ffi::OsStr, os::unix::ffi::OsStrExt};
415
416 let result = new_ucmd!()
417 .arg("-e")
418 .arg(OsStr::from_bytes(b"a\xFFb"))
419 .arg("ok")
420 .succeeds();
421 result.no_stderr();
422 assert!(result.stdout().contains(&b'\xFF'));
423 }
424
425 #[cfg(any(unix, target_os = "wasi"))]
426 #[cfg(not(target_vendor = "apple"))]
427 #[test]
428 #[cfg_attr(wasi_runner, ignore = "WASI: argv/filenames must be valid UTF-8")]
429 fn test_invalid_unicode_in_filename() {
430 use std::{ffi::OsStr, os::unix::ffi::OsStrExt};
431
432 let (at, mut ucmd) = at_and_ucmd!();
433 let filename = OsStr::from_bytes(b"a\xFFb");
434 at.append(filename, "foo\n");
435
436 let result = ucmd.arg(filename).succeeds();
437 result.no_stderr();
438 assert_eq!(result.stdout(), b"foo\n");
439 }
440
441 #[test]
442 fn test_head_count() {
443 let repeat_limit = 5;
444 let input_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
445 let input = input_seq
446 .iter()
447 .map(ToString::to_string)
448 .collect::<Vec<String>>()
449 .join("\n");
450
451 let result = new_ucmd!()
452 .args(&["-n", &repeat_limit.to_string()])
453 .pipe_in(input.as_bytes())
454 .succeeds();
455 result.no_stderr();
456
457 let mut result_seq: Vec<i32> = result
458 .stdout_str()
459 .split('\n')
460 .filter(|x| !x.is_empty())
461 .map(|x| x.parse().unwrap())
462 .collect();
463 result_seq.sort_unstable();
464 assert_eq!(result_seq.len(), repeat_limit, "Output is not limited");
465 assert!(
466 result_seq.iter().all(|x| input_seq.contains(x)),
467 "Output includes element not from input: {}",
468 result.stdout_str()
469 );
470 }
471
472 #[test]
473 fn test_zero_head_count_pipe() {
474 let result = new_ucmd!().arg("-n0").pipe_in(vec![]).succeeds();
475 // Output must be completely empty, not even a newline!
476 result.no_output();
477 }
478
479 #[test]
480 fn test_zero_head_count_pipe_explicit() {
481 let result = new_ucmd!().arg("-n0").arg("-").pipe_in(vec![]).succeeds();
482 result.no_output();
483 }
484
485 #[test]
486 fn test_zero_head_count_file_unreadable() {
487 new_ucmd!()
488 .arg("-n0")
489 .arg("/invalid/unreadable")
490 .pipe_in(vec![])
491 .succeeds()
492 .no_output();
493 }
494
495 #[test]
496 fn test_zero_head_count_file_touch_output_negative() {
497 new_ucmd!()
498 .arg("-n0")
499 .arg("-o")
500 .arg("/invalid/unwritable")
501 .pipe_in(vec![])
502 .fails()
503 .stderr_contains("failed to open '/invalid/unwritable' for writing:");
504 }
505
506 #[test]
507 fn test_zero_head_count_file_touch_output_positive_new() {
508 let (at, mut ucmd) = at_and_ucmd!();
509 ucmd.args(&["-n0", "-o", "file"]).succeeds().no_output();
510 assert_eq!(
511 at.read_bytes("file"),
512 Vec::new(),
513 "Output file must exist and be completely empty"
514 );
515 }
516
517 #[test]
518 fn test_zero_head_count_file_touch_output_positive_existing() {
519 let (at, mut ucmd) = at_and_ucmd!();
520 at.touch("file");
521 ucmd.args(&["-n0", "-o", "file"]).succeeds().no_output();
522 assert_eq!(
523 at.read_bytes("file"),
524 Vec::new(),
525 "Output file must exist and be completely empty"
526 );
527 }
528
529 #[test]
530 fn test_output_not_truncated_when_input_missing() {
531 // A failure to read the input must leave an existing -o file untouched
532 // instead of truncating it first (data-loss regression, GHSA-5g6r-45q4-3p5r).
533 let (at, mut ucmd) = at_and_ucmd!();
534 at.write("out", "keep me\n");
535 ucmd.args(&["-o", "out", "does-not-exist"])
536 .fails_with_code(1)
537 .stderr_contains("does-not-exist");
538 assert_eq!(at.read("out"), "keep me\n");
539 }
540
541 #[test]
542 fn test_output_not_truncated_when_random_source_missing() {
543 // Same guarantee when the random source can't be opened.
544 let (at, mut ucmd) = at_and_ucmd!();
545 at.write("out", "keep me\n");
546 at.write("in", "a\nb\nc\n");
547 ucmd.args(&["-o", "out", "--random-source=does-not-exist", "in"])
548 .fails_with_code(1);
549 assert_eq!(at.read("out"), "keep me\n");
550 }
551
552 #[test]
553 fn test_zero_head_count_echo() {
554 new_ucmd!()
555 .arg("-n0")
556 .arg("-e")
557 .arg("hello")
558 .pipe_in(vec![])
559 .succeeds()
560 .no_output();
561 }
562
563 #[test]
564 fn test_zero_head_count_range() {
565 new_ucmd!().arg("-n0").arg("-i4-8").succeeds().no_output();
566 }
567
568 #[test]
569 fn test_head_count_multi_big_then_small() {
570 let repeat_limit = 5;
571 let input_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
572 let input = input_seq
573 .iter()
574 .map(ToString::to_string)
575 .collect::<Vec<String>>()
576 .join("\n");
577
578 let result = new_ucmd!()
579 .arg("-n")
580 .arg((repeat_limit + 1).to_string())
581 .arg("-n")
582 .arg(repeat_limit.to_string())
583 .pipe_in(input.as_bytes())
584 .succeeds();
585 result.no_stderr();
586
587 let result_seq: Vec<i32> = result
588 .stdout_str()
589 .split('\n')
590 .filter(|x| !x.is_empty())
591 .map(|x| x.parse().unwrap())
592 .collect();
593 assert_eq!(result_seq.len(), repeat_limit, "Output is not limited");
594 assert!(
595 result_seq.iter().all(|x| input_seq.contains(x)),
596 "Output includes element not from input: {}",
597 result.stdout_str()
598 );
599 }
600
601 #[test]
602 fn test_head_count_multi_small_then_big() {
603 let repeat_limit = 5;
604 let input_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
605 let input = input_seq
606 .iter()
607 .map(ToString::to_string)
608 .collect::<Vec<String>>()
609 .join("\n");
610
611 let result = new_ucmd!()
612 .arg("-n")
613 .arg(repeat_limit.to_string())
614 .arg("-n")
615 .arg((repeat_limit + 1).to_string())
616 .pipe_in(input.as_bytes())
617 .succeeds();
618 result.no_stderr();
619
620 let result_seq: Vec<i32> = result
621 .stdout_str()
622 .split('\n')
623 .filter(|x| !x.is_empty())
624 .map(|x| x.parse().unwrap())
625 .collect();
626 assert_eq!(result_seq.len(), repeat_limit, "Output is not limited");
627 assert!(
628 result_seq.iter().all(|x| input_seq.contains(x)),
629 "Output includes element not from input: {}",
630 result.stdout_str()
631 );
632 }
633
634 #[test]
635 fn test_repeat() {
636 let repeat_limit = 15000;
637 let input_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
638 let input = input_seq
639 .iter()
640 .map(ToString::to_string)
641 .collect::<Vec<String>>()
642 .join("\n");
643
644 let result = new_ucmd!()
645 .arg("-r")
646 .args(&["-n", &repeat_limit.to_string()])
647 .pipe_in(input.as_bytes())
648 .succeeds();
649 result.no_stderr();
650
651 let result_seq: Vec<i32> = result
652 .stdout_str()
653 .split('\n')
654 .filter(|x| !x.is_empty())
655 .map(|x| x.parse().unwrap())
656 .collect();
657 assert_eq!(
658 result_seq.len(),
659 repeat_limit,
660 "Output is not repeating forever"
661 );
662 assert!(
663 result_seq.iter().all(|x| input_seq.contains(x)),
664 "Output includes element not from input: {:?}",
665 result_seq
666 .iter()
667 .filter(|x| !input_seq.contains(x))
668 .collect::<Vec<&i32>>()
669 );
670 }
671
672 #[test]
673 fn test_repeat_multi() {
674 let repeat_limit = 15000;
675 let input_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
676 let input = input_seq
677 .iter()
678 .map(ToString::to_string)
679 .collect::<Vec<String>>()
680 .join("\n");
681
682 let result = new_ucmd!()
683 .arg("-r")
684 .arg("-r") // The only difference to test_repeat()
685 .args(&["-n", &repeat_limit.to_string()])
686 .pipe_in(input.as_bytes())
687 .succeeds();
688 result.no_stderr();
689
690 let result_seq: Vec<i32> = result
691 .stdout_str()
692 .split('\n')
693 .filter(|x| !x.is_empty())
694 .map(|x| x.parse().unwrap())
695 .collect();
696 assert_eq!(
697 result_seq.len(),
698 repeat_limit,
699 "Output is not repeating forever"
700 );
701 assert!(
702 result_seq.iter().all(|x| input_seq.contains(x)),
703 "Output includes element not from input: {:?}",
704 result_seq
705 .iter()
706 .filter(|x| !input_seq.contains(x))
707 .collect::<Vec<&i32>>()
708 );
709 }
710
711 #[test]
712 fn test_file_input() {
713 let expected_seq = vec![11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
714
715 let result = new_ucmd!().arg("file_input.txt").succeeds();
716 result.no_stderr();
717
718 let mut result_seq: Vec<i32> = result
719 .stdout_str()
720 .split('\n')
721 .filter(|x| !x.is_empty())
722 .map(|x| x.parse().unwrap())
723 .collect();
724 result_seq.sort_unstable();
725 assert_eq!(result_seq, expected_seq, "Output is not a permutation");
726 }
727
728 #[test]
729 fn test_shuf_echo_and_input_range_not_allowed() {
730 new_ucmd!()
731 .args(&["-e", "0", "-i", "0-2"])
732 .fails()
733 .stderr_contains("cannot be used with");
734 }
735
736 #[test]
737 fn test_shuf_input_range_and_file_not_allowed() {
738 new_ucmd!()
739 .args(&["-i", "0-9", "file"])
740 .fails()
741 .stderr_contains("cannot be used with");
742 }
743
744 #[test]
745 fn test_shuf_invalid_input_range_one() {
746 new_ucmd!()
747 .args(&["-i", "0"])
748 .fails()
749 .stderr_contains("invalid value '0' for '--input-range <LO-HI>': missing '-'");
750 }
751
752 #[test]
753 fn test_shuf_invalid_input_range_two() {
754 new_ucmd!().args(&["-i", "a-9"]).fails().stderr_contains(
755 "invalid value 'a-9' for '--input-range <LO-HI>': invalid digit found in string",
756 );
757 }
758
759 #[test]
760 fn test_shuf_invalid_input_range_three() {
761 new_ucmd!().args(&["-i", "0-b"]).fails().stderr_contains(
762 "invalid value '0-b' for '--input-range <LO-HI>': invalid digit found in string",
763 );
764 }
765
766 #[test]
767 fn test_shuf_multiple_input_ranges() {
768 new_ucmd!()
769 .args(&["-i", "2-9", "-i", "2-9"])
770 .fails()
771 .stderr_contains("--input-range")
772 .stderr_contains("cannot be used multiple times");
773 }
774
775 #[test]
776 fn test_shuf_multiple_outputs() {
777 new_ucmd!()
778 .args(&["-o", "file_a", "-o", "file_b"])
779 .fails()
780 .stderr_contains("--output")
781 .stderr_contains("cannot be used multiple times");
782 }
783
784 #[test]
785 fn test_shuf_two_input_files() {
786 new_ucmd!()
787 .args(&["file_a", "file_b"])
788 .fails()
789 .stderr_contains("unexpected argument 'file_b' found");
790 }
791
792 #[test]
793 fn test_shuf_three_input_files() {
794 new_ucmd!()
795 .args(&["file_a", "file_b", "file_c"])
796 .fails()
797 .stderr_contains("unexpected argument 'file_b' found");
798 }
799
800 #[test]
801 fn test_shuf_invalid_input_line_count() {
802 new_ucmd!().args(&["-n", "a"]).fails().stderr_contains(
803 "invalid value 'a' for '--head-count <COUNT>': invalid digit found in string",
804 );
805 }
806
807 #[test]
808 fn test_shuf_multiple_input_line_count() {
809 let result = new_ucmd!()
810 .args(&["-i10-200", "-n", "10", "-n", "5"])
811 .succeeds();
812
813 result.no_stderr();
814
815 let result_count = result
816 .stdout_str()
817 .split('\n')
818 .filter(|x| !x.is_empty())
819 .count();
820 assert_eq!(result_count, 5, "Output should have 5 items");
821 }
822
823 #[test]
824 fn test_shuf_repeat_empty_range() {
825 new_ucmd!()
826 .arg("-ri4-3")
827 .fails()
828 .no_stdout()
829 .stderr_only("shuf: no lines to repeat\n");
830 }
831
832 #[test]
833 fn test_shuf_repeat_empty_echo() {
834 new_ucmd!()
835 .arg("-re")
836 .fails()
837 .no_stdout()
838 .stderr_only("shuf: no lines to repeat\n");
839 }
840
841 #[test]
842 fn test_shuf_repeat_empty_input() {
843 new_ucmd!()
844 .arg("-r")
845 .pipe_in("")
846 .fails()
847 .no_stdout()
848 .stderr_only("shuf: no lines to repeat\n");
849 }
850
851 #[test]
852 fn test_range_one_elem() {
853 new_ucmd!()
854 .arg("-i5-5")
855 .succeeds()
856 .no_stderr()
857 .stdout_only("5\n");
858 }
859
860 #[test]
861 fn test_range_empty() {
862 new_ucmd!().arg("-i5-4").succeeds().no_output();
863 }
864
865 #[test]
866 fn test_range_empty_minus_one() {
867 new_ucmd!()
868 .arg("-i5-3")
869 .fails()
870 .no_stdout()
871 .stderr_contains("invalid value '5-3' for '--input-range <LO-HI>': start exceeds end\n");
872 }
873
874 #[test]
875 fn test_range_repeat_one_elem() {
876 new_ucmd!()
877 .arg("-n1")
878 .arg("-ri5-5")
879 .succeeds()
880 .no_stderr()
881 .stdout_only("5\n");
882 }
883
884 #[test]
885 fn test_range_repeat_empty() {
886 new_ucmd!()
887 .arg("-n1")
888 .arg("-ri5-4")
889 .fails()
890 .no_stdout()
891 .stderr_only("shuf: no lines to repeat\n");
892 }
893
894 #[test]
895 fn test_range_repeat_empty_minus_one() {
896 new_ucmd!()
897 .arg("-n1")
898 .arg("-ri5-3")
899 .fails()
900 .no_stdout()
901 .stderr_contains("invalid value '5-3' for '--input-range <LO-HI>': start exceeds end\n");
902 }
903
904 // This test fails if we forget to flush the `BufWriter`.
905 #[test]
906 #[cfg(target_os = "linux")]
907 #[cfg_attr(wasi_runner, ignore = "WASI sandbox: host paths not visible")]
908 fn write_errors_are_reported() {
909 new_ucmd!()
910 .arg("-i1-10")
911 .arg("-o/dev/full")
912 .fails()
913 .no_stdout()
914 .stderr_is("shuf: write failed: No space left on device\n");
915 }
916
917 // On 32-bit platforms, if we cast carelessly, this will give no output.
918 #[test]
919 fn test_head_count_does_not_overflow_file() {
920 let (at, mut ucmd) = at_and_ucmd!();
921
922 at.append("input.txt", "hello\n");
923
924 ucmd.arg(format!("-n{}", u64::from(u32::MAX) + 1))
925 .arg("input.txt")
926 .succeeds()
927 .stdout_is("hello\n")
928 .no_stderr();
929 }
930
931 #[test]
932 fn test_head_count_does_not_overflow_args() {
933 new_ucmd!()
934 .arg(format!("-n{}", u64::from(u32::MAX) + 1))
935 .arg("-e")
936 .arg("goodbye")
937 .succeeds()
938 .stdout_is("goodbye\n")
939 .no_stderr();
940 }
941
942 #[test]
943 fn test_head_count_does_not_overflow_range() {
944 new_ucmd!()
945 .arg(format!("-n{}", u64::from(u32::MAX) + 1))
946 .arg("-i1-1")
947 .succeeds()
948 .stdout_is("1\n")
949 .no_stderr();
950 }
951
952 // Test reproducibility and compatibility of --random-source.
953 // These hard-coded results match those of GNU shuf. They should not be changed.
954
955 #[test]
956 fn test_gnu_compat_range_repeat() {
957 let (at, mut ucmd) = at_and_ucmd!();
958 at.append_bytes(
959 "random_bytes.bin",
960 b"\xfb\x83\x8f\x21\x9b\x3c\x2d\xc5\x73\xa5\x58\x6c\x54\x2f\x59\xf8",
961 );
962
963 ucmd.arg("--random-source=random_bytes.bin")
964 .arg("-r")
965 .arg("-i1-99")
966 .fails_with_code(1)
967 .stderr_is("shuf: end of random source\n")
968 .stdout_is("38\n30\n10\n26\n23\n61\n46\n99\n75\n43\n10\n89\n10\n44\n24\n59\n22\n51\n");
969 }
970
971 #[test]
972 fn test_gnu_compat_args_no_repeat() {
973 let (at, mut ucmd) = at_and_ucmd!();
974 at.append_bytes(
975 "random_bytes.bin",
976 b"\xd1\xfd\xb9\x9a\xf5\x81\x71\x42\xf9\x7a\x59\x79\xd4\x9c\x8c\x7d",
977 );
978
979 ucmd.arg("--random-source=random_bytes.bin")
980 .arg("-e")
981 .args(&["1", "2", "3", "4", "5", "6", "7"][..])
982 .succeeds()
983 .no_stderr()
984 .stdout_is("7\n1\n2\n5\n3\n4\n6\n");
985 }
986
987 #[test]
988 fn test_gnu_compat_from_stdin() {
989 let (at, mut ucmd) = at_and_ucmd!();
990 at.append_bytes(
991 "random_bytes.bin",
992 b"\xd1\xfd\xb9\x9a\xf5\x81\x71\x42\xf9\x7a\x59\x79\xd4\x9c\x8c\x7d",
993 );
994
995 at.append("input.txt", "1\n2\n3\n4\n5\n6\n7\n");
996
997 ucmd.arg("--random-source=random_bytes.bin")
998 .set_stdin(at.open("input.txt"))
999 .succeeds()
1000 .no_stderr()
1001 .stdout_is("7\n1\n2\n5\n3\n4\n6\n");
1002 }
1003
1004 #[test]
1005 fn test_gnu_compat_from_file() {
1006 let (at, mut ucmd) = at_and_ucmd!();
1007 at.append_bytes(
1008 "random_bytes.bin",
1009 b"\xd1\xfd\xb9\x9a\xf5\x81\x71\x42\xf9\x7a\x59\x79\xd4\x9c\x8c\x7d",
1010 );
1011
1012 at.append("input.txt", "1\n2\n3\n4\n5\n6\n7\n");
1013
1014 ucmd.arg("--random-source=random_bytes.bin")
1015 .arg("input.txt")
1016 .succeeds()
1017 .no_stderr()
1018 .stdout_is("7\n1\n2\n5\n3\n4\n6\n");
1019 }
1020
1021 #[test]
1022 fn test_gnu_compat_limited_from_file() {
1023 let (at, mut ucmd) = at_and_ucmd!();
1024 at.append_bytes(
1025 "random_bytes.bin",
1026 b"\xd1\xfd\xb9\x9a\xf5\x81\x71\x42\xf9\x7a\x59\x79\xd4\x9c\x8c\x7d",
1027 );
1028
1029 at.append("input.txt", "1\n2\n3\n4\n5\n6\n7\n");
1030
1031 ucmd.arg("--random-source=random_bytes.bin")
1032 .arg("-n5")
1033 .arg("input.txt")
1034 .succeeds()
1035 .no_stderr()
1036 .stdout_is("7\n1\n2\n5\n3\n");
1037 }
1038
1039 // This specific case causes GNU to give different results than other modes.
1040 #[ignore = "disabled until fixed"]
1041 #[test]
1042 fn test_gnu_compat_limited_from_stdin() {
1043 let (at, mut ucmd) = at_and_ucmd!();
1044 at.append_bytes(
1045 "random_bytes.bin",
1046 b"\xd1\xfd\xb9\x9a\xf5\x81\x71\x42\xf9\x7a\x59\x79\xd4\x9c\x8c\x7d",
1047 );
1048
1049 at.append("input.txt", "1\n2\n3\n4\n5\n6\n7\n");
1050
1051 ucmd.arg("--random-source=random_bytes.bin")
1052 .arg("-n7")
1053 .set_stdin(at.open("input.txt"))
1054 .succeeds()
1055 .no_stderr()
1056 .stdout_is("6\n5\n1\n3\n2\n7\n4\n");
1057 }
1058
1059 #[test]
1060 fn test_gnu_compat_range_no_repeat() {
1061 let (at, mut ucmd) = at_and_ucmd!();
1062 at.append_bytes(
1063 "random_bytes.bin",
1064 b"\xd1\xfd\xb9\x9a\xf5\x81\x71\x42\xf9\x7a\x59\x79\xd4\x9c\x8c\x7d",
1065 );
1066
1067 ucmd.arg("--random-source=random_bytes.bin")
1068 .arg("-i1-10")
1069 .succeeds()
1070 .no_stderr()
1071 .stdout_is("10\n2\n8\n7\n3\n9\n6\n5\n1\n4\n");
1072 }
1073
1074 // Test reproducibility of --random-seed.
1075 // These results are arbitrary but they should not change unless we choose to break compatibility.
1076
1077 #[test]
1078 fn test_seed_args_repeat() {
1079 new_ucmd!()
1080 .arg("--random-seed=🌱")
1081 .arg("-e")
1082 .arg("-r")
1083 .arg("-n10")
1084 .args(&["foo", "bar", "baz", "qux"])
1085 .succeeds()
1086 .no_stderr()
1087 .stdout_is("qux\nbar\nbaz\nfoo\nbaz\nqux\nqux\nfoo\nqux\nqux\n");
1088 }
1089
1090 #[test]
1091 fn test_seed_args_no_repeat() {
1092 new_ucmd!()
1093 .arg("--random-seed=🌱")
1094 .arg("-e")
1095 .args(&["foo", "bar", "baz", "qux"])
1096 .succeeds()
1097 .no_stderr()
1098 .stdout_is("qux\nbaz\nfoo\nbar\n");
1099 }
1100
1101 #[test]
1102 fn test_seed_range_repeat() {
1103 new_ucmd!()
1104 .arg("--random-seed=🦀")
1105 .arg("-r")
1106 .arg("-i1-99")
1107 .arg("-n10")
1108 .succeeds()
1109 .no_stderr()
1110 .stdout_is("60\n44\n38\n41\n63\n43\n31\n71\n46\n90\n");
1111 }
1112
1113 #[test]
1114 fn test_seed_range_no_repeat() {
1115 let expected = "8\n9\n1\n5\n2\n6\n4\n3\n10\n7\n";
1116
1117 new_ucmd!()
1118 .arg("--random-seed=12345")
1119 .arg("-i1-10")
1120 .succeeds()
1121 .no_stderr()
1122 .stdout_is(expected);
1123
1124 // Piping from e.g. seq gives identical results.
1125 new_ucmd!()
1126 .arg("--random-seed=12345")
1127 .pipe_in("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n")
1128 .succeeds()
1129 .no_stderr()
1130 .stdout_is(expected);
1131 }
1132
1133 // Test a longer input to exercise some more code paths in the sparse representation.
1134 #[test]
1135 fn test_seed_long_range_no_repeat() {
1136 let expected = "\
1137 1\n3\n35\n37\n36\n45\n72\n17\n18\n40\n67\n74\n81\n77\n14\n90\n\
1138 7\n12\n80\n54\n23\n61\n29\n41\n15\n56\n6\n32\n82\n76\n11\n2\n100\n\
1139 50\n60\n97\n73\n79\n91\n89\n85\n86\n66\n70\n22\n55\n8\n83\n39\n27\n";
1140
1141 new_ucmd!()
1142 .arg("--random-seed=67890")
1143 .arg("-i1-100")
1144 .arg("-n50")
1145 .succeeds()
1146 .no_stderr()
1147 .stdout_is(expected);
1148
1149 let mut test_input = String::new();
1150 for n in 1..=100 {
1151 writeln!(&mut test_input, "{n}").unwrap();
1152 }
1153
1154 new_ucmd!()
1155 .arg("--random-seed=67890")
1156 .pipe_in(test_input.as_bytes())
1157 .arg("-n50")
1158 .succeeds()
1159 .no_stderr()
1160 .stdout_is(expected);
1161 }
1162
1163 #[test]
1164 fn test_empty_range_no_repeat() {
1165 new_ucmd!().arg("-i4-3").succeeds().no_output();
1166 }