Debian Codegraph @

tests/by-util/test_cat.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 NOFILE nonewline cmdline setrlimit ELOOP
7
8 #[cfg(any(target_os = "linux", target_os = "android"))]
9 use rlimit::Resource;
10 #[cfg(unix)]
11 use std::fs::File;
12 use std::fs::OpenOptions;
13 use std::fs::read_to_string;
14 use std::process::Stdio;
15 use uutests::at_and_ucmd;
16 use uutests::new_ucmd;
17 use uutests::util::TestScenario;
18 #[cfg(not(windows))]
19 use uutests::util::vec_of_size;
20 use uutests::util_name;
21
22 #[cfg(unix)]
23 // Verify cat handles a broken pipe on stdout without hanging or crashing and exits nonzero
24 #[test]
25 fn test_cat_broken_pipe_nonzero_and_message() {
26 use uutests::new_ucmd;
27 let (read, write) = std::io::pipe().expect("Failed to create pipe");
28 // Close the read end to simulate a broken pipe on stdout
29 drop(read);
30 let content = (0..10000).map(|_| "x").collect::<String>();
31
32 // On Unix, SIGPIPE should lead to a non-zero exit; ensure process exits and fails
33 new_ucmd!()
34 .set_stdout(write)
35 .pipe_in(content.as_bytes())
36 .fails();
37 }
38
39 #[test]
40 fn test_output_simple() {
41 new_ucmd!()
42 .args(&["alpha.txt"])
43 .succeeds()
44 .stdout_only("abcde\nfghij\nklmno\npqrst\nuvwxyz\n"); // spell-checker:disable-line
45 }
46
47 #[test]
48 fn test_no_options() {
49 for fixture in ["empty.txt", "alpha.txt", "nonewline.txt"] {
50 // Give fixture through command line file argument
51 new_ucmd!()
52 .args(&[fixture])
53 .succeeds()
54 .stdout_is_fixture(fixture);
55 // Give fixture through stdin
56 new_ucmd!()
57 .pipe_in_fixture(fixture)
58 .succeeds()
59 .stdout_is_fixture(fixture);
60 }
61 }
62
63 #[test]
64 #[cfg(any(target_vendor = "apple", target_os = "linux", target_os = "android"))]
65 fn test_no_options_big_input() {
66 for n in [
67 0,
68 1,
69 42,
70 16 * 1024 - 7,
71 16 * 1024 - 1,
72 16 * 1024,
73 16 * 1024 + 1,
74 16 * 1024 + 3,
75 32 * 1024,
76 64 * 1024,
77 80 * 1024,
78 96 * 1024,
79 112 * 1024,
80 128 * 1024,
81 ] {
82 let data = vec_of_size(n);
83 let data2 = data.clone();
84 assert_eq!(data.len(), data2.len());
85 new_ucmd!().pipe_in(data).succeeds().stdout_is_bytes(&data2);
86 }
87 }
88
89 #[test]
90 #[cfg(unix)]
91 #[cfg_attr(wasi_runner, ignore = "WASI: no FIFO/mkfifo support")]
92 fn test_fifo_symlink() {
93 use std::io::Write;
94 use std::thread;
95
96 let s = TestScenario::new(util_name!());
97 s.fixtures.mkdir("dir");
98 s.fixtures.mkfifo("dir/pipe");
99 assert!(s.fixtures.is_fifo("dir/pipe"));
100
101 // Make cat read the pipe through a symlink
102 s.fixtures.symlink_file("dir/pipe", "sympipe"); // spell-checker:disable-line
103 let proc = s.ucmd().args(&["sympipe"]).run_no_wait(); // spell-checker:disable-line
104
105 let data = vec_of_size(128 * 1024);
106 let data2 = data.clone();
107
108 let pipe_path = s.fixtures.plus("dir/pipe");
109 let thread = thread::spawn(move || {
110 let mut pipe = OpenOptions::new()
111 .write(true)
112 .create(false)
113 .open(pipe_path)
114 .unwrap();
115 pipe.write_all(&data).unwrap();
116 });
117
118 proc.wait().unwrap().stdout_only_bytes(data2);
119 thread.join().unwrap();
120 }
121
122 #[test]
123 // TODO(#7542): Re-enable on Android once we figure out why setting limit is broken.
124 // #[cfg(any(target_os = "linux", target_os = "android"))]
125 #[cfg(target_os = "linux")]
126 #[cfg_attr(wasi_runner, ignore = "WASI: rlimit/setrlimit not supported")]
127 fn test_closes_file_descriptors() {
128 // Each file creates a pipe, which has two file descriptors.
129 // If they are not closed then five is certainly too many.
130 new_ucmd!()
131 .args(&[
132 "alpha.txt",
133 "alpha.txt",
134 "alpha.txt",
135 "alpha.txt",
136 "alpha.txt",
137 ])
138 .limit(Resource::NOFILE, 9, 9)
139 .succeeds();
140 }
141
142 #[test]
143 #[cfg(unix)]
144 #[cfg_attr(wasi_runner, ignore = "WASI: no pipe/signal support")]
145 fn test_broken_pipe() {
146 let mut cmd = new_ucmd!();
147 let mut child = cmd
148 .set_stdin(Stdio::from(File::open("/dev/zero").unwrap()))
149 .set_stdout(Stdio::piped())
150 .run_no_wait();
151 // Dropping the stdout should not lead to an error.
152 // The "Broken pipe" error should be silently ignored.
153 child.close_stdout();
154 child.wait().unwrap().fails_silently();
155 }
156
157 #[test]
158 #[cfg(unix)]
159 fn test_piped_to_regular_file() {
160 use std::fs::read_to_string;
161
162 for append in [true, false] {
163 let s = TestScenario::new(util_name!());
164 let file_path = s.fixtures.plus("file.txt");
165
166 {
167 let file = OpenOptions::new()
168 .create_new(true)
169 .write(true)
170 .append(append)
171 .open(&file_path)
172 .unwrap();
173
174 s.ucmd()
175 .set_stdout(file)
176 .pipe_in_fixture("alpha.txt")
177 .succeeds();
178 }
179 let contents = read_to_string(&file_path).unwrap();
180 assert_eq!(contents, "abcde\nfghij\nklmno\npqrst\nuvwxyz\n"); // spell-checker:disable-line
181 }
182 }
183
184 #[test]
185 #[cfg(unix)]
186 fn test_piped_to_dev_null() {
187 for append in [true, false] {
188 let s = TestScenario::new(util_name!());
189 {
190 let dev_null = OpenOptions::new()
191 .write(true)
192 .append(append)
193 .open("/dev/null")
194 .unwrap();
195
196 s.ucmd()
197 .set_stdout(dev_null)
198 .pipe_in_fixture("alpha.txt")
199 .succeeds();
200 }
201 }
202 }
203
204 #[test]
205 #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "netbsd"))]
206 fn test_piped_to_dev_full() {
207 for append in [true, false] {
208 let s = TestScenario::new(util_name!());
209 {
210 let dev_full = OpenOptions::new()
211 .write(true)
212 .append(append)
213 .open("/dev/full")
214 .unwrap();
215
216 s.ucmd()
217 .set_stdout(dev_full)
218 .pipe_in_fixture("alpha.txt")
219 .ignore_stdin_write_error()
220 .fails()
221 .stderr_contains("No space left on device");
222 }
223 }
224 }
225
226 #[test]
227 fn test_directory() {
228 let s = TestScenario::new(util_name!());
229 s.fixtures.mkdir("test_directory");
230 s.ucmd()
231 .args(&["test_directory"])
232 .fails()
233 .stderr_is("cat: test_directory: Is a directory\n");
234 }
235
236 #[test]
237 fn test_directory_and_file() {
238 let s = TestScenario::new(util_name!());
239 s.fixtures.mkdir("test_directory2");
240 for fixture in ["empty.txt", "alpha.txt", "nonewline.txt"] {
241 s.ucmd()
242 .args(&["test_directory2", fixture])
243 .fails()
244 .stderr_is("cat: test_directory2: Is a directory\n")
245 .stdout_is_fixture(fixture);
246 }
247 }
248
249 #[test]
250 #[cfg(unix)]
251 fn test_three_directories_and_file_and_stdin() {
252 let s = TestScenario::new(util_name!());
253 s.fixtures.mkdir("test_directory3");
254 s.fixtures.mkdir("test_directory3/test_directory4");
255 s.fixtures.mkdir("test_directory3/test_directory5");
256 s.ucmd()
257 .args(&[
258 "test_directory3/test_directory4",
259 "alpha.txt",
260 "-",
261 "file_which_does_not_exist.txt",
262 "nonewline.txt",
263 "test_directory3/test_directory5",
264 "test_directory3/../test_directory3/test_directory5",
265 "test_directory3",
266 ])
267 .pipe_in("stdout bytes")
268 .ignore_stdin_write_error()
269 .fails()
270 .stderr_is_fixture("three_directories_and_file_and_stdin.stderr.expected")
271 .stdout_is(
272 "abcde\nfghij\nklmno\npqrst\nuvwxyz\nstdout bytestext without a trailing newline", // spell-checker:disable-line
273 );
274 }
275
276 #[test]
277 fn test_output_multi_files_print_all_chars() {
278 // spell-checker:disable
279 new_ucmd!()
280 .args(&["alpha.txt", "256.txt", "-A", "-n"])
281 .succeeds()
282 .stdout_only(
283 " 1\tabcde$\n 2\tfghij$\n 3\tklmno$\n 4\tpqrst$\n \
284 5\tuvwxyz$\n 6\t^@^A^B^C^D^E^F^G^H^I$\n \
285 7\t^K^L^M^N^O^P^Q^R^S^T^U^V^W^X^Y^Z^[^\\^]^^^_ \
286 !\"#$%&\'()*+,-./0123456789:;\
287 <=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~^?M-^@M-^AM-^\
288 BM-^CM-^DM-^EM-^FM-^GM-^HM-^IM-^JM-^KM-^LM-^MM-^NM-^OM-^PM-^QM-^RM-^SM-^TM-^UM-^V\
289 M-^WM-^XM-^YM-^ZM-^[M-^\\M-^]M-^^M-^_M- \
290 M-!M-\"M-#M-$M-%M-&M-\'M-(M-)M-*M-+M-,M--M-.M-/M-0M-1M-2M-3M-4M-5M-6M-7M-8M-9M-:\
291 M-;M-<M-=M->M-?M-@M-AM-BM-CM-DM-EM-FM-GM-HM-IM-JM-KM-LM-MM-NM-OM-PM-QM-RM-SM-TM-U\
292 M-VM-WM-XM-YM-ZM-[M-\\M-]M-^M-_M-`M-aM-bM-cM-dM-eM-fM-gM-hM-iM-jM-kM-lM-mM-nM-oM-\
293 pM-qM-rM-sM-tM-uM-vM-wM-xM-yM-zM-{M-|M-}M-~M-^?",
294 );
295 // spell-checker:enable
296 }
297
298 #[test]
299 fn test_output_multi_files_print_all_chars_repeated() {
300 // spell-checker:disable
301 new_ucmd!()
302 .args(&["alpha.txt", "256.txt", "-A", "-n", "-A", "-n"])
303 .succeeds()
304 .stdout_only(
305 " 1\tabcde$\n 2\tfghij$\n 3\tklmno$\n 4\tpqrst$\n \
306 5\tuvwxyz$\n 6\t^@^A^B^C^D^E^F^G^H^I$\n \
307 7\t^K^L^M^N^O^P^Q^R^S^T^U^V^W^X^Y^Z^[^\\^]^^^_ \
308 !\"#$%&\'()*+,-./0123456789:;\
309 <=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~^?M-^@M-^AM-^\
310 BM-^CM-^DM-^EM-^FM-^GM-^HM-^IM-^JM-^KM-^LM-^MM-^NM-^OM-^PM-^QM-^RM-^SM-^TM-^UM-^V\
311 M-^WM-^XM-^YM-^ZM-^[M-^\\M-^]M-^^M-^_M- \
312 M-!M-\"M-#M-$M-%M-&M-\'M-(M-)M-*M-+M-,M--M-.M-/M-0M-1M-2M-3M-4M-5M-6M-7M-8M-9M-:\
313 M-;M-<M-=M->M-?M-@M-AM-BM-CM-DM-EM-FM-GM-HM-IM-JM-KM-LM-MM-NM-OM-PM-QM-RM-SM-TM-U\
314 M-VM-WM-XM-YM-ZM-[M-\\M-]M-^M-_M-`M-aM-bM-cM-dM-eM-fM-gM-hM-iM-jM-kM-lM-mM-nM-oM-\
315 pM-qM-rM-sM-tM-uM-vM-wM-xM-yM-zM-{M-|M-}M-~M-^?",
316 );
317 // spell-checker:enable
318 }
319
320 #[test]
321 fn test_numbered_lines_no_trailing_newline() {
322 // spell-checker:disable
323 new_ucmd!()
324 .args(&["nonewline.txt", "alpha.txt", "-n"])
325 .succeeds()
326 .stdout_only(
327 " 1\ttext without a trailing newlineabcde\n 2\tfghij\n \
328 3\tklmno\n 4\tpqrst\n 5\tuvwxyz\n",
329 );
330 // spell-checker:enable
331 }
332
333 #[test]
334 fn test_numbered_lines_with_crlf() {
335 new_ucmd!()
336 .args(&["-n"])
337 .pipe_in("Hello\r\nWorld")
338 .succeeds()
339 .stdout_only(" 1\tHello\r\n 2\tWorld");
340 }
341
342 #[test]
343 fn test_stdin_show_nonprinting() {
344 for same_param in ["-v", "-vv", "--show-nonprinting", "--show-non"] {
345 new_ucmd!()
346 .args(&[same_param])
347 .pipe_in("\t\0\n")
348 .succeeds()
349 .stdout_only("\t^@\n");
350 }
351 }
352
353 #[test]
354 fn test_stdin_show_tabs() {
355 for same_param in ["-T", "-TT", "--show-tabs", "--show-ta"] {
356 new_ucmd!()
357 .args(&[same_param])
358 .pipe_in("\t\0\n")
359 .succeeds()
360 .stdout_only("^I\0\n");
361 }
362 }
363
364 #[test]
365 fn test_stdin_show_ends() {
366 for same_param in ["-E", "-EE", "--show-ends", "--show-e"] {
367 new_ucmd!()
368 .args(&[same_param, "-"])
369 .pipe_in("\t\0\n\t")
370 .succeeds()
371 .stdout_only("\t\0$\n\t");
372 }
373 }
374
375 #[test]
376 fn test_squeeze_all_files() {
377 // empty lines at the end of a file are "squeezed" together with empty lines at the beginning
378 let (at, mut ucmd) = at_and_ucmd!();
379 at.write("input1", "a\n\n");
380 at.write("input2", "\n\nb");
381 ucmd.args(&["input1", "input2", "-s"])
382 .succeeds()
383 .stdout_only("a\n\nb");
384 }
385
386 #[test]
387 fn test_squeeze_all_files_repeated() {
388 // empty lines at the end of a file are "squeezed" together with empty lines at the beginning
389 let (at, mut ucmd) = at_and_ucmd!();
390 at.write("input1", "a\n\n");
391 at.write("input2", "\n\nb");
392 ucmd.args(&["-s", "input1", "input2", "-s"])
393 .succeeds()
394 .stdout_only("a\n\nb");
395 }
396
397 #[test]
398 fn test_show_ends_crlf() {
399 new_ucmd!()
400 .arg("-E")
401 .pipe_in("a\nb\r\n\rc\n\r\n\r")
402 .succeeds()
403 .stdout_only("a$\nb^M$\n\rc$\n^M$\n\r");
404 }
405
406 #[test]
407 fn test_stdin_show_all() {
408 for same_param in ["-A", "--show-all", "--show-a"] {
409 new_ucmd!()
410 .args(&[same_param])
411 .pipe_in("\t\0\n")
412 .succeeds()
413 .stdout_only("^I^@$\n");
414 }
415 }
416
417 #[test]
418 fn test_stdin_nonprinting_and_endofline() {
419 new_ucmd!()
420 .args(&["-e"])
421 .pipe_in("\t\0\n")
422 .succeeds()
423 .stdout_only("\t^@$\n");
424 }
425
426 #[test]
427 fn test_stdin_nonprinting_and_endofline_repeated() {
428 new_ucmd!()
429 .args(&["-ee", "-e"])
430 .pipe_in("\t\0\n")
431 .succeeds()
432 .stdout_only("\t^@$\n");
433 }
434
435 #[test]
436 fn test_stdin_nonprinting_and_tabs() {
437 new_ucmd!()
438 .args(&["-t"])
439 .pipe_in("\t\0\n")
440 .succeeds()
441 .stdout_only("^I^@\n");
442 }
443
444 #[test]
445 fn test_stdin_nonprinting_and_tabs_repeated() {
446 new_ucmd!()
447 .args(&["-tt", "-t"])
448 .pipe_in("\t\0\n")
449 .succeeds()
450 .stdout_only("^I^@\n");
451 }
452
453 #[test]
454 fn test_stdin_tabs_no_newline() {
455 new_ucmd!()
456 .args(&["-T"])
457 .pipe_in("\ta")
458 .succeeds()
459 .stdout_only("^Ia");
460 }
461
462 #[test]
463 fn test_stdin_squeeze_blank() {
464 for same_param in ["-s", "--squeeze-blank", "--squeeze"] {
465 new_ucmd!()
466 .arg(same_param)
467 .pipe_in("\n\na\n\n\n\n\nb\n\n\n")
468 .succeeds()
469 .stdout_only("\na\n\nb\n\n");
470 }
471 }
472
473 #[test]
474 fn test_stdin_number_non_blank() {
475 // spell-checker:disable-next-line
476 for same_param in ["-b", "-bb", "--number-nonblank", "--number-non"] {
477 new_ucmd!()
478 .arg(same_param)
479 .arg("-")
480 .pipe_in("\na\nb\n\n\nc")
481 .succeeds()
482 .stdout_only("\n 1\ta\n 2\tb\n\n\n 3\tc");
483 }
484 }
485
486 #[test]
487 fn test_non_blank_overrides_number() {
488 // spell-checker:disable-next-line
489 for same_param in ["-b", "--number-nonblank"] {
490 new_ucmd!()
491 .args(&[same_param, "-"])
492 .pipe_in("\na\nb\n\n\nc")
493 .succeeds()
494 .stdout_only("\n 1\ta\n 2\tb\n\n\n 3\tc");
495 }
496 }
497
498 #[test]
499 fn test_non_blank_overrides_number_even_when_present() {
500 new_ucmd!()
501 .args(&["-n", "-b", "-n"])
502 .pipe_in("\na\nb\n\n\nc")
503 .succeeds()
504 .stdout_only("\n 1\ta\n 2\tb\n\n\n 3\tc");
505 }
506
507 #[test]
508 fn test_squeeze_blank_before_numbering() {
509 for same_param in ["-s", "--squeeze-blank"] {
510 new_ucmd!()
511 .args(&[same_param, "-n", "-"])
512 .pipe_in("a\n\n\nb")
513 .succeeds()
514 .stdout_only(" 1\ta\n 2\t\n 3\tb");
515 }
516 }
517
518 /// This tests reading from Unix character devices
519 #[test]
520 #[cfg(unix)]
521 #[cfg_attr(wasi_runner, ignore = "WASI sandbox: host paths not visible")]
522 fn test_dev_random() {
523 #[cfg(any(target_os = "linux", target_os = "android"))]
524 const DEV_RANDOM: &str = "/dev/urandom";
525
526 #[cfg(not(any(target_os = "linux", target_os = "android")))]
527 const DEV_RANDOM: &str = "/dev/random";
528
529 let mut proc = new_ucmd!()
530 .set_stdout(Stdio::piped())
531 .args(&[DEV_RANDOM])
532 .run_no_wait();
533
534 proc.make_assertion_with_delay(100).is_alive();
535 let buf = proc.stdout_exact_bytes(2048);
536 let num_zeroes = buf.iter().fold(0, |mut acc, &n| {
537 if n == 0 {
538 acc += 1;
539 }
540 acc
541 });
542 // The probability of more than 512 zero bytes is essentially zero if the
543 // output is truly random.
544 assert!(num_zeroes < 512);
545 proc.kill();
546 }
547
548 /// Reading from /dev/full should return an infinite amount of zero bytes.
549 /// Wikipedia says there is support on Linux, FreeBSD, and `NetBSD`.
550 #[test]
551 #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "netbsd"))]
552 #[cfg_attr(wasi_runner, ignore = "WASI sandbox: host paths not visible")]
553 fn test_dev_full() {
554 let mut proc = new_ucmd!()
555 .set_stdout(Stdio::piped())
556 .args(&["/dev/full"])
557 .run_no_wait();
558 let expected = [0; 2048];
559 proc.make_assertion_with_delay(100)
560 .is_alive()
561 .with_exact_output(2048, 0)
562 .stdout_only_bytes(expected);
563 proc.kill();
564 }
565
566 #[test]
567 #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "netbsd"))]
568 #[cfg_attr(wasi_runner, ignore = "WASI sandbox: host paths not visible")]
569 fn test_dev_full_show_all() {
570 let buf_len = 2048;
571 let mut proc = new_ucmd!()
572 .set_stdout(Stdio::piped())
573 .args(&["-A", "/dev/full"])
574 .run_no_wait();
575 let expected: Vec<u8> = (0..buf_len)
576 .map(|n| if n & 1 == 0 { b'^' } else { b'@' })
577 .collect();
578
579 proc.make_assertion_with_delay(100)
580 .is_alive()
581 .with_exact_output(buf_len, 0)
582 .stdout_only_bytes(expected);
583 proc.kill();
584 }
585
586 // For some reason splice() on first of those files fails, resulting in
587 // fallback inside `write_fast`, the other splice succeeds, in effect
588 // without additional flush output gets reversed.
589 #[test]
590 #[cfg(target_os = "linux")]
591 #[cfg_attr(wasi_runner, ignore = "WASI sandbox: host paths not visible")]
592 fn test_write_fast_fallthrough_uses_flush() {
593 const PROC_INIT_CMDLINE: &str = "/proc/1/cmdline";
594 let cmdline = read_to_string(PROC_INIT_CMDLINE).unwrap();
595
596 new_ucmd!()
597 .args(&[PROC_INIT_CMDLINE, "alpha.txt"])
598 .succeeds()
599 .stdout_only(format!("{cmdline}abcde\nfghij\nklmno\npqrst\nuvwxyz\n")); // spell-checker:disable-line
600 }
601
602 #[test]
603 #[cfg(unix)]
604 #[cfg_attr(wasi_runner, ignore = "WASI: no Unix domain socket support")]
605 fn test_domain_socket() {
606 use std::os::unix::net::UnixListener;
607
608 let s = TestScenario::new(util_name!());
609 let socket_path = s.fixtures.plus("sock");
610 let _ = UnixListener::bind(&socket_path).expect("failed to create socket");
611
612 s.ucmd()
613 .args(&[socket_path])
614 .fails()
615 .stderr_contains("No such device or address");
616 }
617
618 #[test]
619 fn test_write_to_self_empty() {
620 // it's ok if the input file is also the output file if it's empty
621 let s = TestScenario::new(util_name!());
622 let file_path = s.fixtures.plus("file.txt");
623
624 let file = OpenOptions::new()
625 .create_new(true)
626 .append(true)
627 .open(&file_path)
628 .unwrap();
629
630 s.ucmd().set_stdout(file).arg("file.txt").succeeds();
631 }
632
633 #[test]
634 #[cfg_attr(wasi_runner, ignore = "WASI: cannot detect unsafe overwrite")]
635 fn test_write_to_self() {
636 let s = TestScenario::new(util_name!());
637 let file_path = s.fixtures.plus("first_file");
638 s.fixtures.write("second_file", "second_file_content.");
639
640 let file = OpenOptions::new()
641 .create_new(true)
642 .append(true)
643 .open(file_path)
644 .unwrap();
645
646 s.fixtures.append("first_file", "first_file_content.");
647
648 s.ucmd()
649 .set_stdout(file)
650 .arg("first_file")
651 .arg("first_file")
652 .arg("second_file")
653 .fails_with_code(1)
654 .stderr_only("cat: first_file: input file is output file\ncat: first_file: input file is output file\n");
655
656 assert_eq!(
657 s.fixtures.read("first_file"),
658 "first_file_content.second_file_content."
659 );
660 }
661
662 /// Test that cat handles self-referential input gracefully.
663 ///
664 /// `cat fxy2 fy 1<>fxy2`
665 // TODO: make this work on windows
666 #[test]
667 #[cfg(unix)]
668 fn test_cat_rw_self_succeeds() {
669 let (at, mut ucmd) = at_and_ucmd!();
670 at.write("extra", "world");
671 at.write("combined", "hello");
672
673 // Open `rw_file` as both stdin and stdout (read/write)
674 let combined_file_path = at.plus("combined");
675 let combined_file = OpenOptions::new()
676 .read(true)
677 .write(true)
678 .open(&combined_file_path)
679 .unwrap();
680 ucmd.args(&["combined", "extra"])
681 .set_stdout(combined_file)
682 .succeeds();
683
684 // The contents of `combined` and `extra` files should be merged
685 let combined_contents = read_to_string(combined_file_path).unwrap();
686 assert_eq!(combined_contents, "helloworld");
687 }
688
689 /// Test that cat handles self-referential input gracefully.
690 ///
691 /// `cat fx fx3 1<>fx3`
692 #[test]
693 #[cfg_attr(wasi_runner, ignore = "WASI: cannot detect unsafe overwrite")]
694 fn test_cat_rw_self_conflict_fails() {
695 let (at, mut ucmd) = at_and_ucmd!();
696 at.write("source", "a");
697 at.write("dest", "bcde");
698
699 // Open `rw_file` as both stdin and stdout (read/write)
700 let dest_file_path = at.plus("dest");
701 let dest_file = OpenOptions::new()
702 .read(true)
703 .write(true)
704 .open(&dest_file_path)
705 .unwrap();
706 ucmd.args(&["source", "dest"])
707 .set_stdout(dest_file)
708 .fails_with_code(1)
709 .stderr_only("cat: dest: input file is output file\n");
710
711 // The contents of `source` should have overwritten the beginning of `dest`
712 let dest_contents = read_to_string(dest_file_path).unwrap();
713 assert_eq!(dest_contents, "acde");
714 }
715
716 #[test]
717 #[cfg(unix)]
718 #[cfg(not(target_os = "openbsd"))]
719 #[cfg_attr(
720 wasi_runner,
721 ignore = "WASI: symlink loop traversal does not surface ELOOP ('Too many levels of symbolic links')"
722 )]
723 fn test_error_loop() {
724 let (at, mut ucmd) = at_and_ucmd!();
725 at.symlink_file("2", "1");
726 at.symlink_file("3", "2");
727 at.symlink_file("1", "3");
728 ucmd.arg("1")
729 .fails()
730 .stderr_is("cat: 1: Too many levels of symbolic links\n");
731 }
732
733 #[test]
734 fn test_exit_code_is_one_regardless_of_error_count() {
735 // cat's exit code must always be 1 when errors occur, matching GNU cat.
736 // Counting is problematic, since process exit codes are truncated mod 256 by the OS
737 let missing_files: Vec<String> = (0..256).map(|i| format!("missing-{i}")).collect();
738
739 new_ucmd!().args(&missing_files).fails_with_code(1);
740 }
741
742 #[test]
743 fn test_u_ignored() {
744 for same_param in ["-u", "-uu"] {
745 new_ucmd!()
746 .arg(same_param)
747 .pipe_in("hello")
748 .succeeds()
749 .stdout_only("hello");
750 }
751 }
752
753 #[test]
754 #[cfg(unix)]
755 #[cfg_attr(wasi_runner, ignore = "WASI: errno/error-message mismatches")]
756 fn test_write_fast_read_error() {
757 use std::os::unix::fs::PermissionsExt;
758
759 let (at, mut ucmd) = at_and_ucmd!();
760
761 // Create a file with content
762 at.write("foo", "content");
763
764 // Remove read permissions to cause a read error
765 let file_path = at.plus_as_string("foo");
766 let mut perms = std::fs::metadata(&file_path).unwrap().permissions();
767 perms.set_mode(0o000); // No permissions
768 std::fs::set_permissions(&file_path, perms).unwrap();
769
770 // Test that cat fails with permission denied
771 ucmd.arg("foo").fails().stderr_contains("Permission denied");
772 }
773
774 #[test]
775 #[cfg(target_os = "linux")]
776 #[cfg_attr(wasi_runner, ignore = "WASI: argv/filenames must be valid UTF-8")]
777 fn test_cat_non_utf8_paths() {
778 use std::ffi::OsStr;
779 use std::os::unix::ffi::OsStrExt;
780
781 let scene = TestScenario::new(util_name!());
782 let at = &scene.fixtures;
783
784 // Create a test file with non-UTF-8 bytes in the name
785 let non_utf8_bytes = b"test_\xFF\xFE.txt";
786 let non_utf8_name = OsStr::from_bytes(non_utf8_bytes);
787
788 // Create the actual file with some content
789 std::fs::write(at.plus(non_utf8_name), "Hello, non-UTF-8 world!\n").unwrap();
790
791 // Test that cat handles non-UTF-8 file names without crashing
792 let result = scene.ucmd().arg(non_utf8_name).succeeds();
793
794 // The result should contain the file content
795 let output = result.stdout_str_lossy();
796 assert_eq!(output, "Hello, non-UTF-8 world!\n");
797 }
798
799 #[test]
800 #[cfg(unix)]
801 #[cfg_attr(wasi_runner, ignore = "WASI: cannot detect unsafe overwrite")]
802 fn test_appending_same_input_output() {
803 let (at, mut ucmd) = at_and_ucmd!();
804
805 at.write("foo", "content");
806 let foo_file = at.plus_as_string("foo");
807
808 let file_read = File::open(&foo_file).unwrap();
809 let file_write = OpenOptions::new().append(true).open(&foo_file).unwrap();
810
811 ucmd.set_stdin(file_read);
812 ucmd.set_stdout(file_write);
813
814 ucmd.fails()
815 .no_stdout()
816 .stderr_contains("input file is output file");
817 }
818
819 #[cfg(unix)]
820 #[test]
821 fn test_uchild_when_no_capture_reading_from_infinite_source() {
822 use regex::Regex;
823
824 let ts = TestScenario::new("cat");
825
826 let expected_stdout = b"\0".repeat(12345);
827 let mut child = ts
828 .ucmd()
829 .set_stdin(Stdio::from(File::open("/dev/zero").unwrap()))
830 .set_stdout(Stdio::piped())
831 .run_no_wait();
832
833 child
834 .make_assertion()
835 .with_exact_output(12345, 0)
836 .stdout_only_bytes(expected_stdout);
837
838 child
839 .kill()
840 .make_assertion()
841 .with_current_output()
842 .stdout_matches(&Regex::new("[\0].*").unwrap())
843 .no_stderr();
844 }
845
846 #[test]
847 fn test_child_when_pipe_in() {
848 let ts = TestScenario::new("cat");
849 let mut child = ts.ucmd().set_stdin(Stdio::piped()).run_no_wait();
850 child.pipe_in("content");
851 child.wait().unwrap().stdout_only("content").success();
852
853 ts.ucmd().pipe_in("content").run().stdout_is("content");
854 }
855
856 /// Regression test for GitHub issue #9769
857 /// https://github.com/uutils/coreutils/issues/9769
858 ///
859 /// Bug: Utilities panic when output is redirected to /dev/full
860 /// Location: src/uucore/src/lib/mods/error.rs:751 - `.unwrap()` causes panic
861 ///
862 /// This test verifies that cat handles write errors to /dev/full gracefully
863 /// instead of panicking with exit code 134 (SIGABRT).
864 ///
865 /// Expected behavior with current BUGGY code:
866 /// - Test WILL FAIL (cat panics with exit code 134)
867 ///
868 /// Expected behavior after fix:
869 /// - Test SHOULD PASS (cat exits gracefully with error code 1)
870 // Regression test for issue #9769: graceful error handling when writing to /dev/full
871 #[test]
872 #[cfg(target_os = "linux")]
873 #[ignore = "this works on the terminal as expected, but fails on cargo"]
874 fn test_write_error_handling() {
875 use std::fs::File;
876
877 let dev_full =
878 File::create("/dev/full").expect("Failed to open /dev/full - test must run on Linux");
879
880 new_ucmd!()
881 .pipe_in("test content that should cause write error to /dev/full")
882 .set_stdout(dev_full)
883 .fails()
884 .code_is(1)
885 .stderr_contains("No space left on device");
886 }
887
888 #[test]
889 #[cfg(target_os = "linux")]
890 fn test_version_help_dev_full() {
891 use std::fs::OpenOptions;
892
893 for option in ["--version", "--help"] {
894 let dev_full = OpenOptions::new().write(true).open("/dev/full").unwrap();
895
896 new_ucmd!()
897 .arg(option)
898 .set_stdout(dev_full)
899 .fails()
900 .stderr_contains("No space left on device");
901 }
902 }
903
904 #[test]
905 fn test_cat_eintr_handling() {
906 // Test that cat properly handles EINTR (ErrorKind::Interrupted) during I/O operations
907 // This verifies the signal interruption retry logic added in the EINTR handling fix
908 use std::io::{Error, ErrorKind, Read};
909 use std::sync::{Arc, Mutex};
910
911 // Create a mock reader that simulates EINTR interruptions
912 struct InterruptedReader {
913 data: Vec<u8>,
914 position: usize,
915 interrupt_count: Arc<Mutex<usize>>,
916 }
917
918 impl Read for InterruptedReader {
919 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
920 // Simulate interruption on first read attempt
921 if self.position < self.data.len() {
922 let mut count = self.interrupt_count.lock().unwrap();
923 if *count == 0 {
924 *count += 1;
925 return Err(Error::new(
926 ErrorKind::Interrupted,
927 "Simulated signal interruption",
928 ));
929 }
930 }
931
932 // Return actual data on subsequent attempts
933 if self.position >= self.data.len() {
934 return Ok(0);
935 }
936
937 let remaining = self.data.len() - self.position;
938 let to_copy = std::cmp::min(buf.len(), remaining);
939 buf[..to_copy].copy_from_slice(&self.data[self.position..self.position + to_copy]);
940 self.position += to_copy;
941 Ok(to_copy)
942 }
943 }
944
945 let test_data = b"Hello, World!\n";
946 let interrupt_count = Arc::new(Mutex::new(0));
947 let reader = InterruptedReader {
948 data: test_data.to_vec(),
949 position: 0,
950 interrupt_count: interrupt_count.clone(),
951 };
952
953 // Test that cat can handle the interrupted reader
954 let result = std::io::copy(&mut { reader }, &mut std::io::stdout());
955 assert!(result.is_ok());
956
957 // Verify that the interruption was encountered and handled
958 assert_eq!(*interrupt_count.lock().unwrap(), 1);
959 }