Debian Codegraph @

tests/by-util/test_tail.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) abcdefghijklmnopqrstuvwxyz efghijklmnopqrstuvwxyz vwxyz emptyfile file siette ocho nueve diez MULT
7 // spell-checker:ignore (libs) kqueue ELOOP EISDIR
8 // spell-checker:ignore (jargon) tailable untailable datasame runneradmin tmpi
9 // spell-checker:ignore (cmd) taskkill
10 #![allow(
11 clippy::unicode_not_nfc,
12 clippy::cast_lossless,
13 clippy::cast_possible_truncation
14 )]
15
16 use pretty_assertions::assert_eq;
17 use rand::distr::Alphanumeric;
18 use rstest::rstest;
19 #[cfg(all(not(target_os = "android"), not(target_os = "freebsd"), not(windows)))]
20 use rustix::process::{Pid, Signal, kill_process};
21 use std::char::from_digit;
22 use std::fs::File;
23 use std::io::Write;
24 use std::io::{Seek, SeekFrom};
25 #[cfg(all(
26 not(target_vendor = "apple"),
27 not(target_os = "android"),
28 not(target_os = "freebsd"),
29 not(target_os = "openbsd"),
30 not(windows)
31 ))]
32 use std::path::Path;
33 use std::process::Stdio;
34 use tail::chunks::BUFFER_SIZE as CHUNK_BUFFER_SIZE;
35 #[cfg(all(
36 not(target_vendor = "apple"),
37 not(target_os = "android"),
38 not(target_os = "freebsd"),
39 not(target_os = "openbsd"),
40 not(windows)
41 ))]
42 use tail::text;
43 use uutests::at_and_ucmd;
44 use uutests::new_ucmd;
45 use uutests::random::{AlphanumericNewline, RandomizedString};
46 #[cfg(unix)]
47 use uutests::unwrap_or_return;
48 use uutests::util::TestScenario;
49 #[cfg(unix)]
50 use uutests::util::expected_result;
51 #[cfg(unix)]
52 #[cfg(not(windows))]
53 use uutests::util::is_ci;
54 use uutests::util_name;
55
56 const FOOBAR_TXT: &str = "foobar.txt";
57 const FOOBAR_2_TXT: &str = "foobar2.txt";
58 const FOOBAR_WITH_NULL_TXT: &str = "foobar_with_null.txt";
59 #[allow(dead_code)]
60 const FOLLOW_NAME_TXT: &str = "follow_name.txt";
61 #[allow(dead_code)]
62 const FOLLOW_NAME_SHORT_EXP: &str = "follow_name_short.expected";
63 #[allow(dead_code)]
64 const FOLLOW_NAME_EXP: &str = "follow_name.expected";
65
66 #[cfg(target_vendor = "apple")]
67 const DEFAULT_SLEEP_INTERVAL_MILLIS: u64 = 1500;
68 #[cfg(not(target_vendor = "apple"))]
69 const DEFAULT_SLEEP_INTERVAL_MILLIS: u64 = 1000;
70
71 // The binary integer "10000000" is *not* a valid UTF-8 encoding
72 // of a character: https://en.wikipedia.org/wiki/UTF-8#Encoding
73 #[cfg(unix)]
74 const INVALID_UTF8: u8 = 0x80;
75 #[cfg(windows)]
76 const INVALID_UTF16: u16 = 0xD800;
77
78 #[test]
79 fn test_invalid_arg() {
80 new_ucmd!().arg("--definitely-invalid").fails_with_code(1);
81 }
82
83 #[test]
84 fn test_stdin_default() {
85 new_ucmd!()
86 .pipe_in_fixture(FOOBAR_TXT)
87 .succeeds()
88 .stdout_is_fixture("foobar_stdin_default.expected")
89 .no_stderr();
90 }
91
92 #[test]
93 fn test_stdin_explicit() {
94 new_ucmd!()
95 .pipe_in_fixture(FOOBAR_TXT)
96 .arg("-")
97 .succeeds()
98 .stdout_is_fixture("foobar_stdin_default.expected")
99 .no_stderr();
100 }
101
102 #[test]
103 fn test_stdin_redirect_file() {
104 // $ echo foo > f
105
106 // $ tail < f
107 // foo
108
109 // $ tail -v < f
110 // foo
111 //
112
113 let ts = TestScenario::new(util_name!());
114 let at = &ts.fixtures;
115 at.write("f", "foo");
116
117 ts.ucmd()
118 .set_stdin(File::open(at.plus("f")).unwrap())
119 .succeeds()
120 .stdout_is("foo");
121 ts.ucmd()
122 .set_stdin(File::open(at.plus("f")).unwrap())
123 .arg("-v")
124 .succeeds()
125 .stdout_only("==> standard input <==\nfoo");
126 }
127
128 #[test]
129 // FIXME: the -f test fails with: Assertion failed. Expected 'tail' to be running but exited with status=exit status: 0
130 #[ignore = "disabled until fixed"]
131 #[cfg(not(target_vendor = "apple"))] // FIXME: for currently not working platforms
132 fn test_stdin_redirect_file_follow() {
133 // $ echo foo > f
134
135 // $ tail -f < f
136 // foo
137 //
138
139 let (at, mut ucmd) = at_and_ucmd!();
140
141 at.write("f", "foo");
142
143 let mut p = ucmd
144 .arg("-f")
145 .set_stdin(File::open(at.plus("f")).unwrap())
146 .run_no_wait();
147
148 p.make_assertion_with_delay(500).is_alive();
149 p.kill()
150 .make_assertion()
151 .with_all_output()
152 .stdout_only("foo");
153 }
154
155 #[test]
156 fn test_stdin_redirect_offset() {
157 // Test following a file from the middle
158
159 let (at, mut ucmd) = at_and_ucmd!();
160
161 at.write("k", "1\n2\n");
162 let mut fh = File::open(at.plus("k")).unwrap();
163 fh.seek(SeekFrom::Start(2)).unwrap();
164
165 ucmd.set_stdin(fh).succeeds().stdout_only("2\n");
166 }
167
168 #[test]
169 fn test_stdin_redirect_offset2() {
170 // like test_stdin_redirect_offset but with multiple files
171
172 let (at, mut ucmd) = at_and_ucmd!();
173
174 at.write("k", "1\n2\n");
175 at.write("l", "3\n4\n");
176 at.write("m", "5\n6\n");
177 let mut fh = File::open(at.plus("k")).unwrap();
178 fh.seek(SeekFrom::Start(2)).unwrap();
179
180 ucmd.set_stdin(fh)
181 .args(&["k", "-", "l", "m"])
182 .succeeds()
183 .stdout_only(
184 "==> k <==\n1\n2\n\n==> standard input <==\n2\n\n==> l <==\n3\n4\n\n==> m <==\n5\n6\n",
185 );
186 }
187
188 #[test]
189 fn test_nc_0_wo_follow() {
190 // verify that -[nc]0 without -f, exit without reading
191
192 let ts = TestScenario::new(util_name!());
193 ts.ucmd().args(&["-n0", "missing"]).succeeds().no_output();
194 ts.ucmd().args(&["-c0", "missing"]).succeeds().no_output();
195 }
196
197 #[test]
198 fn test_zero_bytes_with_suffix() {
199 // "0K" must be 0 bytes, not 1KiB (bare suffix parses as 1)
200 let ts = TestScenario::new(util_name!());
201 ts.ucmd()
202 .args(&["-c0K"])
203 .pipe_in("qwerty")
204 .ignore_stdin_write_error()
205 .succeeds()
206 .no_output();
207 ts.ucmd()
208 .args(&["-c00K"])
209 .pipe_in("qwerty")
210 .ignore_stdin_write_error()
211 .succeeds()
212 .no_output();
213 ts.ucmd()
214 .args(&["-c+0K"])
215 .pipe_in("qwerty")
216 .succeeds()
217 .stdout_is("qwerty");
218 }
219
220 #[test]
221 #[cfg(all(unix, not(target_os = "freebsd")))]
222 fn test_nc_0_wo_follow2() {
223 use std::os::unix::fs::PermissionsExt;
224 // verify that -[nc]0 without -f, exit without reading
225
226 let ts = TestScenario::new(util_name!());
227 let at = &ts.fixtures;
228
229 at.make_file("unreadable")
230 .set_permissions(PermissionsExt::from_mode(0o000))
231 .unwrap();
232
233 ts.ucmd()
234 .args(&["-n0", "unreadable"])
235 .succeeds()
236 .no_output();
237 ts.ucmd()
238 .args(&["-c0", "unreadable"])
239 .succeeds()
240 .no_output();
241 }
242
243 #[test]
244 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
245 fn test_n0_with_follow() {
246 let (at, mut ucmd) = at_and_ucmd!();
247 let test_file = "test.txt";
248 // Create file with multiple lines
249 at.write(test_file, "line1\nline2\nline3\n");
250
251 let mut child = ucmd.arg("-n0").arg("-f").arg(test_file).run_no_wait();
252 child.make_assertion_with_delay(500).is_alive();
253
254 // Append a new line
255 at.append(test_file, "new\n");
256
257 // Should only print the newly appended line
258 child
259 .make_assertion_with_delay(DEFAULT_SLEEP_INTERVAL_MILLIS)
260 .with_current_output()
261 .stdout_only("new\n");
262 child.kill();
263 }
264
265 // TODO: Add similar test for windows
266 #[test]
267 #[cfg(unix)]
268 fn test_permission_denied() {
269 use std::os::unix::fs::PermissionsExt;
270
271 let ts = TestScenario::new(util_name!());
272 let at = &ts.fixtures;
273
274 at.make_file("unreadable")
275 .set_permissions(PermissionsExt::from_mode(0o000))
276 .unwrap();
277
278 let cmd = ts.ucmd().arg("unreadable").fails_with_code(1);
279 cmd.no_stdout();
280
281 if std::env::var("UUTESTS_WASM_RUNNER").is_ok() {
282 cmd.stderr_contains("tail: cannot open 'unreadable' for reading:");
283 } else {
284 cmd.stderr_is("tail: cannot open 'unreadable' for reading: Permission denied\n");
285 }
286 }
287
288 // TODO: Add similar test for windows
289 #[test]
290 #[cfg(unix)]
291 fn test_permission_denied_multiple() {
292 use std::os::unix::fs::PermissionsExt;
293
294 let (at, mut ucmd) = at_and_ucmd!();
295
296 at.touch("file1");
297 at.touch("file2");
298
299 at.make_file("unreadable")
300 .set_permissions(PermissionsExt::from_mode(0o000))
301 .unwrap();
302
303 let cmd = ucmd
304 .args(&["file1", "unreadable", "file2"])
305 .fails_with_code(1);
306 cmd.stdout_is("==> file1 <==\n\n==> file2 <==\n");
307
308 if std::env::var("UUTESTS_WASM_RUNNER").is_ok() {
309 cmd.stderr_contains("tail: cannot open 'unreadable' for reading:");
310 } else {
311 cmd.stderr_is("tail: cannot open 'unreadable' for reading: Permission denied\n");
312 }
313 }
314
315 #[test]
316 fn test_follow_redirect_stdin_name_retry() {
317 // $ touch f && tail -F - < f
318 // tail: cannot follow '-' by name
319 // NOTE: Not sure why GNU's tail doesn't just follow `f` in this case.
320
321 let ts = TestScenario::new(util_name!());
322 let at = &ts.fixtures;
323 at.touch("f");
324
325 let mut args = vec!["-F", "-"];
326 for _ in 0..2 {
327 ts.ucmd()
328 .set_stdin(File::open(at.plus("f")).unwrap())
329 .args(&args)
330 .fails_with_code(1)
331 .no_stdout()
332 .stderr_is("tail: cannot follow '-' by name\n");
333 args.pop();
334 }
335 }
336
337 #[test]
338 #[cfg(all(
339 not(target_vendor = "apple"),
340 not(target_os = "android"),
341 not(target_os = "freebsd"),
342 not(target_os = "openbsd"),
343 not(windows)
344 ))] // FIXME: for currently not working platforms
345 fn test_stdin_redirect_dir() {
346 // $ mkdir dir
347 // $ tail < dir, $ tail - < dir
348 // tail: error reading 'standard input': Is a directory
349
350 let ts = TestScenario::new(util_name!());
351 let at = &ts.fixtures;
352 at.mkdir("dir");
353
354 let expected = if std::env::var("UUTESTS_WASM_RUNNER").is_ok() {
355 "tail: Is a directory\n"
356 } else {
357 "tail: error reading 'standard input': Is a directory\n"
358 };
359
360 ts.ucmd()
361 .set_stdin(File::open(at.plus("dir")).unwrap())
362 .fails_with_code(1)
363 .no_stdout()
364 .stderr_is(expected);
365 ts.ucmd()
366 .set_stdin(File::open(at.plus("dir")).unwrap())
367 .arg("-")
368 .fails_with_code(1)
369 .no_stdout()
370 .stderr_is(expected);
371 }
372
373 // On macOS path.is_dir() can be false for directories if it was a redirect,
374 // e.g. `$ tail < DIR. The library feature to detect the
375 // std::io::ErrorKind::IsADirectory isn't stable so we currently show the a wrong
376 // error message.
377 // FIXME: If `std::io::ErrorKind::IsADirectory` becomes stable or macos handles
378 // redirected directories like linux show the correct message like in
379 // `test_stdin_redirect_dir`
380 #[test]
381 #[cfg(target_vendor = "apple")]
382 fn test_stdin_redirect_dir_when_target_os_is_macos() {
383 // $ mkdir dir
384 // $ tail < dir, $ tail - < dir
385 // tail: error reading 'standard input': Is a directory
386
387 let ts = TestScenario::new(util_name!());
388 let at = &ts.fixtures;
389 at.mkdir("dir");
390
391 ts.ucmd()
392 .set_stdin(File::open(at.plus("dir")).unwrap())
393 .fails_with_code(1)
394 .no_stdout()
395 .stderr_is("tail: cannot open 'standard input' for reading: No such file or directory\n");
396 ts.ucmd()
397 .set_stdin(File::open(at.plus("dir")).unwrap())
398 .arg("-")
399 .fails_with_code(1)
400 .no_stdout()
401 .stderr_is("tail: cannot open 'standard input' for reading: No such file or directory\n");
402 }
403
404 #[test]
405 #[cfg(unix)]
406 fn test_stdin_via_script_redirection_and_pipe() {
407 // $ touch file.txt
408 // $ echo line1 > file.txt
409 // $ echo line2 >> file.txt
410 // $ chmod +x test.sh
411 // $ ./test.sh < file.txt
412 // line1
413 // line2
414 // $ cat file.txt | ./test.sh
415 // line1
416 // line2
417 use std::os::unix::fs::PermissionsExt;
418
419 let scene = TestScenario::new(util_name!());
420 let at = &scene.fixtures;
421 let data = "line1\nline2\n";
422
423 at.write("file.txt", data);
424
425 let mut script = at.make_file("test.sh");
426 writeln!(script, "#!/usr/bin/env sh").unwrap();
427 writeln!(script, "tail").unwrap();
428 script
429 .set_permissions(PermissionsExt::from_mode(0o755))
430 .unwrap();
431
432 drop(script); // close the file handle to ensure file is not busy
433
434 // test with redirection
435 scene
436 .cmd("sh")
437 .current_dir(at.plus(""))
438 .arg("-c")
439 .arg("./test.sh < file.txt")
440 .succeeds()
441 .stdout_only(data);
442
443 // test with pipe
444 scene
445 .cmd("sh")
446 .current_dir(at.plus(""))
447 .arg("-c")
448 .arg("cat file.txt | ./test.sh")
449 .succeeds()
450 .stdout_only(data);
451 }
452
453 #[test]
454 fn test_follow_stdin_descriptor() {
455 let ts = TestScenario::new(util_name!());
456
457 let mut args = vec!["-f", "-"];
458 for _ in 0..2 {
459 let mut p = ts
460 .ucmd()
461 .set_stdin(Stdio::piped())
462 .args(&args)
463 .run_no_wait();
464 p.make_assertion_with_delay(500).is_alive();
465 p.kill().make_assertion().with_all_output().no_output();
466
467 args.pop();
468 }
469 }
470
471 #[test]
472 fn test_follow_stdin_name_retry() {
473 // $ tail -F -
474 // tail: cannot follow '-' by name
475 let mut args = vec!["-F", "-"];
476 for _ in 0..2 {
477 new_ucmd!()
478 .args(&args)
479 .fails_with_code(1)
480 .no_stdout()
481 .stderr_is("tail: cannot follow '-' by name\n");
482 args.pop();
483 }
484 }
485
486 #[test]
487 fn test_follow_bad_fd() {
488 // Provoke a "bad file descriptor" error by closing the fd
489 // Test following stdin
490
491 // `$ tail -f <&-` OR `$ tail -f - <&-`
492 // tail: cannot fstat 'standard input': Bad file descriptor
493 // tail: error reading 'standard input': Bad file descriptor
494 // tail: no files remaining
495 // tail: -: Bad file descriptor
496 //
497 // $ `tail <&-`
498 // tail: cannot fstat 'standard input': Bad file descriptor
499 // tail: -: Bad file descriptor
500
501 // WONT-FIX:
502 // see also: https://github.com/uutils/coreutils/issues/2873
503 }
504
505 #[test]
506 fn test_single_default() {
507 new_ucmd!()
508 .arg(FOOBAR_TXT)
509 .succeeds()
510 .stdout_is_fixture("foobar_single_default.expected");
511 }
512
513 #[test]
514 fn test_n_greater_than_number_of_lines() {
515 new_ucmd!()
516 .arg("-n")
517 .arg("99999999")
518 .arg(FOOBAR_TXT)
519 .succeeds()
520 .stdout_is_fixture(FOOBAR_TXT);
521 }
522
523 #[test]
524 fn test_null_default() {
525 new_ucmd!()
526 .arg("-z")
527 .arg(FOOBAR_WITH_NULL_TXT)
528 .succeeds()
529 .stdout_is_fixture("foobar_with_null_default.expected");
530 }
531
532 #[test]
533 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
534 fn test_follow_single() {
535 let (at, mut ucmd) = at_and_ucmd!();
536
537 let mut child = ucmd.arg("-f").arg(FOOBAR_TXT).run_no_wait();
538
539 let expected_fixture = "foobar_single_default.expected";
540
541 child
542 .make_assertion_with_delay(200)
543 .is_alive()
544 .with_current_output()
545 .stdout_only_fixture(expected_fixture);
546
547 // We write in a temporary copy of foobar.txt
548 let expected = "line1\nline2\n";
549 at.append(FOOBAR_TXT, expected);
550
551 child
552 .make_assertion_with_delay(DEFAULT_SLEEP_INTERVAL_MILLIS)
553 .is_alive();
554 child
555 .kill()
556 .make_assertion()
557 .with_current_output()
558 .stdout_only(expected);
559 }
560
561 #[test]
562 #[cfg(wasi_runner)]
563 fn test_follow_file_unsupported() {
564 new_ucmd!()
565 .arg("-f")
566 .arg(FOOBAR_TXT)
567 .fails_with_code(1)
568 .stdout_is_fixture("foobar_single_default.expected")
569 .stderr_is("tail: follow mode is not supported on this platform\n");
570 }
571
572 /// Test for following when bytes are written that are not valid UTF-8.
573 #[test]
574 #[cfg(not(windows))] // FIXME: test times out
575 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
576 fn test_follow_non_utf8_bytes() {
577 // Tail the test file and start following it.
578 let (at, mut ucmd) = at_and_ucmd!();
579 let mut child = ucmd.arg("-f").arg(FOOBAR_TXT).run_no_wait();
580
581 child
582 .make_assertion_with_delay(500)
583 .is_alive()
584 .with_current_output()
585 .stdout_only_fixture("foobar_single_default.expected");
586
587 // Now append some bytes that are not valid UTF-8.
588 //
589 // We also write the newline character because our implementation
590 // of `tail` is attempting to read a line of input, so the
591 // presence of a newline character will force the `follow()`
592 // function to conclude reading input bytes and start writing them
593 // to output. The newline character is not fundamental to this
594 // test, it is just a requirement of the current implementation.
595 let expected = [INVALID_UTF8, b'\n'];
596 at.append_bytes(FOOBAR_TXT, &expected);
597
598 child
599 .make_assertion_with_delay(DEFAULT_SLEEP_INTERVAL_MILLIS)
600 .with_current_output()
601 .stdout_only_bytes(expected);
602
603 child.make_assertion().is_alive();
604 child.kill();
605 }
606
607 #[test]
608 #[cfg(unix)]
609 fn test_permission_denied_is_not_reported_as_not_found() {
610 use std::fs;
611 use std::os::unix::fs::PermissionsExt;
612
613 if rustix::process::geteuid().is_root() {
614 return;
615 }
616
617 let (at, mut ucmd) = at_and_ucmd!();
618
619 at.mkdir("noexec");
620 at.touch("noexec/file");
621
622 let dir = at.plus("noexec");
623 fs::set_permissions(&dir, fs::Permissions::from_mode(0o000)).unwrap();
624
625 ucmd.arg("noexec/file")
626 .fails()
627 .stderr_contains("Permission denied");
628
629 fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
630 }
631
632 #[test]
633 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
634 fn test_follow_multiple() {
635 let (at, mut ucmd) = at_and_ucmd!();
636 let mut child = ucmd
637 .arg("-f")
638 .arg(FOOBAR_TXT)
639 .arg(FOOBAR_2_TXT)
640 .run_no_wait();
641
642 child
643 .make_assertion_with_delay(500)
644 .is_alive()
645 .with_current_output()
646 .stdout_only_fixture("foobar_follow_multiple.expected");
647
648 let first_append = "trois\n";
649 at.append(FOOBAR_2_TXT, first_append);
650
651 child
652 .make_assertion_with_delay(DEFAULT_SLEEP_INTERVAL_MILLIS)
653 .with_current_output()
654 .stdout_only(first_append);
655
656 let second_append = "twenty\nthirty\n";
657 at.append(FOOBAR_TXT, second_append);
658
659 child
660 .make_assertion_with_delay(DEFAULT_SLEEP_INTERVAL_MILLIS)
661 .with_current_output()
662 .stdout_only_fixture("foobar_follow_multiple_appended.expected");
663
664 child.make_assertion().is_alive();
665 child.kill();
666 }
667
668 #[test]
669 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
670 fn test_follow_name_multiple() {
671 // spell-checker:disable-next-line
672 for argument in ["--follow=name", "--follo=nam", "--f=n"] {
673 let (at, mut ucmd) = at_and_ucmd!();
674 let mut child = ucmd
675 .arg(argument)
676 .arg(FOOBAR_TXT)
677 .arg(FOOBAR_2_TXT)
678 .run_no_wait();
679
680 #[cfg(target_os = "linux")]
681 let delay = 100;
682 #[cfg(target_vendor = "apple")]
683 let delay = 2000;
684 #[cfg(not(any(target_vendor = "apple", target_os = "linux")))]
685 let delay = 1000;
686
687 child
688 .make_assertion_with_delay(delay)
689 .is_alive()
690 .with_all_output()
691 .stdout_only_fixture("foobar_follow_multiple.expected");
692
693 let first_append = "trois\n";
694 at.append(FOOBAR_2_TXT, first_append);
695
696 child
697 .make_assertion_with_delay(delay)
698 .with_current_output()
699 .stdout_only(first_append);
700
701 let second_append = "twenty\nthirty\n";
702 at.append(FOOBAR_TXT, second_append);
703
704 child
705 .make_assertion_with_delay(delay)
706 .with_current_output()
707 .stdout_only_fixture("foobar_follow_multiple_appended.expected");
708
709 child.make_assertion().is_alive();
710 child.kill();
711 }
712 }
713
714 #[test]
715 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
716 fn test_follow_multiple_untailable() {
717 // $ tail -f DIR1 DIR2
718 // ==> DIR1 <==
719 // tail: error reading 'DIR1': Is a directory
720 // tail: DIR1: cannot follow end of this type of file; giving up on this name
721 //
722 // ==> DIR2 <==
723 // tail: error reading 'DIR2': Is a directory
724 // tail: DIR2: cannot follow end of this type of file; giving up on this name
725 // tail: no files remaining
726
727 let expected_stdout = "==> DIR1 <==\n\n==> DIR2 <==\n";
728 let expected_stderr = "tail: error reading 'DIR1': Is a directory\n\
729 tail: DIR1: cannot follow end of this type of file; giving up on this name\n\
730 tail: error reading 'DIR2': Is a directory\n\
731 tail: DIR2: cannot follow end of this type of file; giving up on this name\n\
732 tail: no files remaining\n";
733
734 let (at, mut ucmd) = at_and_ucmd!();
735 at.mkdir("DIR1");
736 at.mkdir("DIR2");
737 ucmd.arg("-f")
738 .arg("DIR1")
739 .arg("DIR2")
740 .fails_with_code(1)
741 .stderr_is(expected_stderr)
742 .stdout_is(expected_stdout);
743 }
744
745 #[test]
746 fn test_follow_stdin_pipe() {
747 new_ucmd!()
748 .arg("-f")
749 .pipe_in_fixture(FOOBAR_TXT)
750 .succeeds()
751 .stdout_is_fixture("follow_stdin.expected")
752 .no_stderr();
753 }
754
755 #[test]
756 #[cfg(not(windows))] // FIXME: for currently not working platforms
757 fn test_follow_invalid_pid() {
758 let wasm = std::env::var("UUTESTS_WASM_RUNNER").is_ok();
759 let negative_pid_error = if wasm {
760 "tail: invalid PID: '-1234': invalid digit found in string\n"
761 } else {
762 "tail: invalid PID: '-1234'\n"
763 };
764
765 new_ucmd!()
766 .args(&["-f", "--pid=-1234"])
767 .fails_with_code(1)
768 .no_stdout()
769 .stderr_is(negative_pid_error);
770 new_ucmd!()
771 .args(&["-f", "--pid=abc"])
772 .fails()
773 .no_stdout()
774 .stderr_is("tail: invalid PID: 'abc': invalid digit found in string\n");
775
776 let max_pid = if wasm {
777 (u128::from(u64::MAX) + 1).to_string()
778 } else {
779 (i64::from(i32::MAX) + 1).to_string()
780 };
781 new_ucmd!()
782 .args(&["-f", "--pid", &max_pid])
783 .fails()
784 .no_stdout()
785 .stderr_is(format!(
786 "tail: invalid PID: '{max_pid}': number too large to fit in target type\n"
787 ));
788 }
789
790 // FixME: test PASSES for usual windows builds, but fails for coverage testing builds (likely related to the specific RUSTFLAGS '-Zpanic_abort_tests -Cpanic=abort') // spell-checker:disable-line
791 // FIXME: FreeBSD: See issue https://github.com/uutils/coreutils/issues/4306
792 // Fails intermittently in the CI, but couldn't reproduce the failure locally.
793 #[test]
794 #[cfg(all(
795 not(target_vendor = "apple"),
796 not(target_os = "android"),
797 not(target_os = "freebsd"),
798 not(windows)
799 ))] // FIXME: for currently not working platforms
800 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
801 fn test_follow_with_pid() {
802 use std::process::Command;
803
804 let (at, mut ucmd) = at_and_ucmd!();
805
806 let dummy_cmd = "sh";
807 let mut dummy = Command::new(dummy_cmd).spawn().unwrap();
808 let pid = dummy.id();
809
810 let mut child = ucmd
811 .arg("-f")
812 .arg(format!("--pid={pid}"))
813 .arg(FOOBAR_TXT)
814 .arg(FOOBAR_2_TXT)
815 .run_no_wait();
816
817 child
818 .make_assertion_with_delay(500)
819 .is_alive()
820 .with_current_output()
821 .stdout_only_fixture("foobar_follow_multiple.expected");
822
823 let first_append = "trois\n";
824 at.append(FOOBAR_2_TXT, first_append);
825
826 child
827 .make_assertion_with_delay(DEFAULT_SLEEP_INTERVAL_MILLIS)
828 .with_current_output()
829 .stdout_only(first_append);
830
831 let second_append = "twenty\nthirty\n";
832 at.append(FOOBAR_TXT, second_append);
833
834 child
835 .make_assertion_with_delay(DEFAULT_SLEEP_INTERVAL_MILLIS)
836 .is_alive()
837 .with_current_output()
838 .stdout_only_fixture("foobar_follow_multiple_appended.expected");
839
840 // kill the dummy process and give tail time to notice this
841 kill_process(
842 Pid::from_raw(i32::try_from(pid).unwrap()).unwrap(),
843 Signal::USR1,
844 )
845 .unwrap();
846 let _ = dummy.wait();
847
848 child.delay(DEFAULT_SLEEP_INTERVAL_MILLIS);
849
850 let third_append = "should\nbe\nignored\n";
851 at.append(FOOBAR_TXT, third_append);
852
853 child
854 .make_assertion_with_delay(DEFAULT_SLEEP_INTERVAL_MILLIS)
855 .is_not_alive()
856 .with_current_output()
857 .no_output()
858 .success();
859 }
860
861 #[test]
862 fn test_single_big_args() {
863 const FILE: &str = "single_big_args.txt";
864 const EXPECTED_FILE: &str = "single_big_args_expected.txt";
865 const LINES: usize = 1_000_000;
866 const N_ARG: usize = 100_000;
867
868 let (at, mut ucmd) = at_and_ucmd!();
869
870 let mut big_input = at.make_file(FILE);
871 for i in 0..LINES {
872 writeln!(big_input, "Line {i}").expect("Could not write to FILE");
873 }
874 big_input.flush().expect("Could not flush FILE");
875
876 let mut big_expected = at.make_file(EXPECTED_FILE);
877 for i in (LINES - N_ARG)..LINES {
878 writeln!(big_expected, "Line {i}").expect("Could not write to EXPECTED_FILE");
879 }
880 big_expected.flush().expect("Could not flush EXPECTED_FILE");
881
882 ucmd.arg(FILE).arg("-n").arg(format!("{N_ARG}")).succeeds();
883 // .stdout_is(at.read(EXPECTED_FILE));
884 }
885
886 #[test]
887 fn test_bytes_single() {
888 new_ucmd!()
889 .arg("-c")
890 .arg("10")
891 .arg(FOOBAR_TXT)
892 .succeeds()
893 .stdout_is_fixture("foobar_bytes_single.expected");
894 }
895
896 #[test]
897 fn test_bytes_stdin() {
898 new_ucmd!()
899 .pipe_in_fixture(FOOBAR_TXT)
900 .arg("-c")
901 .arg("13")
902 .succeeds()
903 .stdout_is_fixture("foobar_bytes_stdin.expected")
904 .no_stderr();
905 }
906
907 #[test]
908 fn test_bytes_big() {
909 const FILE: &str = "test_bytes_big.txt";
910 const EXPECTED_FILE: &str = "test_bytes_big_expected.txt";
911 const BYTES: usize = 1_000_000;
912 const N_ARG: usize = 100_000;
913
914 let (at, mut ucmd) = at_and_ucmd!();
915
916 let mut big_input = at.make_file(FILE);
917 for i in 0..BYTES {
918 let digit = from_digit((i % 10) as u32, 10).unwrap();
919 write!(big_input, "{digit}").expect("Could not write to FILE");
920 }
921 big_input.flush().expect("Could not flush FILE");
922
923 let mut big_expected = at.make_file(EXPECTED_FILE);
924 for i in (BYTES - N_ARG)..BYTES {
925 let digit = from_digit((i % 10) as u32, 10).unwrap();
926 write!(big_expected, "{digit}").expect("Could not write to EXPECTED_FILE");
927 }
928 big_expected.flush().expect("Could not flush EXPECTED_FILE");
929
930 let result = ucmd
931 .arg(FILE)
932 .arg("-c")
933 .arg(format!("{N_ARG}"))
934 .succeeds()
935 .stdout_move_str();
936 let expected = at.read(EXPECTED_FILE);
937
938 assert_eq!(result.len(), expected.len());
939 for (actual_char, expected_char) in result.chars().zip(expected.chars()) {
940 assert_eq!(actual_char, expected_char);
941 }
942 }
943
944 #[test]
945 fn test_lines_with_size_suffix() {
946 const FILE: &str = "test_lines_with_size_suffix.txt";
947 const EXPECTED_FILE: &str = "test_lines_with_size_suffix_expected.txt";
948 const LINES: usize = 3_000;
949 const N_ARG: usize = 2 * 1024;
950
951 let (at, mut ucmd) = at_and_ucmd!();
952
953 let mut big_input = at.make_file(FILE);
954 for i in 0..LINES {
955 writeln!(big_input, "Line {i}").expect("Could not write to FILE");
956 }
957 big_input.flush().expect("Could not flush FILE");
958
959 let mut big_expected = at.make_file(EXPECTED_FILE);
960 for i in (LINES - N_ARG)..LINES {
961 writeln!(big_expected, "Line {i}").expect("Could not write to EXPECTED_FILE");
962 }
963 big_expected.flush().expect("Could not flush EXPECTED_FILE");
964
965 ucmd.arg(FILE)
966 .arg("-n")
967 .arg("2K")
968 .succeeds()
969 .stdout_is_fixture(EXPECTED_FILE);
970 }
971
972 #[test]
973 fn test_multiple_input_files() {
974 new_ucmd!()
975 .arg(FOOBAR_TXT)
976 .arg(FOOBAR_2_TXT)
977 .succeeds()
978 .no_stderr()
979 .stdout_is_fixture("foobar_follow_multiple.expected");
980 }
981
982 #[test]
983 fn test_multiple_input_files_missing() {
984 new_ucmd!()
985 .arg(FOOBAR_TXT)
986 .arg("missing1")
987 .arg(FOOBAR_2_TXT)
988 .arg("missing2")
989 .fails()
990 .stdout_is_fixture("foobar_follow_multiple.expected")
991 .stderr_is(
992 "tail: cannot open 'missing1' for reading: No such file or directory\n\
993 tail: cannot open 'missing2' for reading: No such file or directory\n",
994 );
995 }
996
997 #[test]
998 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
999 fn test_follow_missing() {
1000 // Ensure that --follow=name does not imply --retry.
1001 // Ensure that --follow={descriptor,name} (without --retry) does *not wait* for the
1002 // file to appear.
1003 for follow_mode in &["--follow=descriptor", "--follow=name", "--fo=d", "--fo=n"] {
1004 new_ucmd!()
1005 .arg(follow_mode)
1006 .arg("missing")
1007 .fails_with_code(1)
1008 .no_stdout()
1009 .stderr_is(
1010 "tail: cannot open 'missing' for reading: No such file or directory\n\
1011 tail: no files remaining\n",
1012 );
1013 }
1014 }
1015
1016 #[test]
1017 fn test_follow_name_stdin() {
1018 let ts = TestScenario::new(util_name!());
1019 let at = &ts.fixtures;
1020 at.touch("FILE1");
1021 at.touch("FILE2");
1022 ts.ucmd()
1023 .arg("--follow=name")
1024 .arg("-")
1025 .fails_with_code(1)
1026 .stderr_is("tail: cannot follow '-' by name\n");
1027 ts.ucmd()
1028 .arg("--follow=name")
1029 .arg("FILE1")
1030 .arg("-")
1031 .arg("FILE2")
1032 .fails_with_code(1)
1033 .stderr_is("tail: cannot follow '-' by name\n");
1034 }
1035
1036 #[test]
1037 fn test_multiple_input_files_with_suppressed_headers() {
1038 new_ucmd!()
1039 .arg(FOOBAR_TXT)
1040 .arg(FOOBAR_2_TXT)
1041 .arg("-q")
1042 .succeeds()
1043 .stdout_is_fixture("foobar_multiple_quiet.expected");
1044 }
1045
1046 #[test]
1047 fn test_multiple_input_quiet_flag_overrides_verbose_flag_for_suppressing_headers() {
1048 new_ucmd!()
1049 .arg(FOOBAR_TXT)
1050 .arg(FOOBAR_2_TXT)
1051 .arg("-v")
1052 .arg("-q")
1053 .succeeds()
1054 .stdout_is_fixture("foobar_multiple_quiet.expected");
1055 }
1056
1057 #[test]
1058 fn test_dir() {
1059 let (at, mut ucmd) = at_and_ucmd!();
1060 at.mkdir("DIR");
1061 ucmd.arg("DIR")
1062 .fails_with_code(1)
1063 .stderr_is("tail: error reading 'DIR': Is a directory\n");
1064 }
1065
1066 #[test]
1067 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
1068 fn test_dir_follow() {
1069 let ts = TestScenario::new(util_name!());
1070 let at = &ts.fixtures;
1071 at.mkdir("DIR");
1072 for mode in &["--follow=descriptor", "--follow=name"] {
1073 ts.ucmd()
1074 .arg(mode)
1075 .arg("DIR")
1076 .fails_with_code(1)
1077 .no_stdout()
1078 .stderr_is(
1079 "tail: error reading 'DIR': Is a directory\n\
1080 tail: DIR: cannot follow end of this type of file; giving up on this name\n\
1081 tail: no files remaining\n",
1082 );
1083 }
1084 }
1085
1086 #[test]
1087 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
1088 fn test_dir_follow_retry() {
1089 let ts = TestScenario::new(util_name!());
1090 let at = &ts.fixtures;
1091 at.mkdir("DIR");
1092 ts.ucmd()
1093 .arg("--follow=descriptor")
1094 .arg("--retry")
1095 .arg("DIR")
1096 .fails_with_code(1)
1097 .stderr_is(
1098 "tail: warning: --retry only effective for the initial open\n\
1099 tail: error reading 'DIR': Is a directory\n\
1100 tail: DIR: cannot follow end of this type of file\n\
1101 tail: no files remaining\n",
1102 );
1103 }
1104
1105 #[test]
1106 fn test_negative_indexing() {
1107 let positive_lines_index = new_ucmd!().arg("-n").arg("5").arg(FOOBAR_TXT).succeeds();
1108
1109 let negative_lines_index = new_ucmd!().arg("-n").arg("-5").arg(FOOBAR_TXT).succeeds();
1110
1111 let positive_bytes_index = new_ucmd!().arg("-c").arg("20").arg(FOOBAR_TXT).succeeds();
1112
1113 let negative_bytes_index = new_ucmd!().arg("-c").arg("-20").arg(FOOBAR_TXT).succeeds();
1114
1115 assert_eq!(positive_lines_index.stdout(), negative_lines_index.stdout());
1116 assert_eq!(positive_bytes_index.stdout(), negative_bytes_index.stdout());
1117 }
1118
1119 #[test]
1120 fn test_sleep_interval() {
1121 new_ucmd!().arg("-s").arg("10").arg(FOOBAR_TXT).succeeds();
1122 new_ucmd!().arg("-s").arg(".1").arg(FOOBAR_TXT).succeeds();
1123 new_ucmd!().arg("-s.1").arg(FOOBAR_TXT).succeeds();
1124 new_ucmd!().arg("-s").arg("-1").arg(FOOBAR_TXT).fails();
1125 new_ucmd!()
1126 .arg("-s")
1127 .arg("1..1")
1128 .arg(FOOBAR_TXT)
1129 .fails_with_code(1)
1130 .stderr_contains("invalid number of seconds: '1..1'");
1131 }
1132
1133 /// Test for reading all but the first NUM bytes: `tail -c +3`.
1134 #[test]
1135 fn test_positive_bytes() {
1136 new_ucmd!()
1137 .args(&["-c", "+3"])
1138 .pipe_in("abcde")
1139 .succeeds()
1140 .stdout_is("cde");
1141 }
1142
1143 /// Test for reading all bytes, specified by `tail -c +0`.
1144 #[test]
1145 fn test_positive_zero_bytes() {
1146 let ts = TestScenario::new(util_name!());
1147 ts.ucmd()
1148 .args(&["-c", "+0"])
1149 .pipe_in("abcde")
1150 .succeeds()
1151 .stdout_is("abcde");
1152 ts.ucmd()
1153 .args(&["-c", "0"])
1154 .pipe_in("abcde")
1155 .ignore_stdin_write_error()
1156 .succeeds()
1157 .no_output();
1158 }
1159
1160 /// Test for reading all but the first NUM lines: `tail -n +3`.
1161 #[test]
1162 fn test_positive_lines() {
1163 new_ucmd!()
1164 .args(&["-n", "+3"])
1165 .pipe_in("a\nb\nc\nd\ne\n")
1166 .succeeds()
1167 .stdout_is("c\nd\ne\n");
1168 }
1169
1170 /// Test for reading all but the first NUM lines of a file: `tail -n +3 infile`.
1171 #[test]
1172 fn test_positive_lines_file() {
1173 new_ucmd!()
1174 .args(&["-n", "+7", "foobar.txt"])
1175 .succeeds()
1176 .stdout_is(
1177 "siette
1178 ocho
1179 nueve
1180 diez
1181 once
1182 ",
1183 );
1184 }
1185
1186 /// Test for reading all but the first NUM bytes of a file: `tail -c +3 infile`.
1187 #[test]
1188 fn test_positive_bytes_file() {
1189 new_ucmd!()
1190 .args(&["-c", "+42", "foobar.txt"])
1191 .succeeds()
1192 .stdout_is(
1193 "ho
1194 nueve
1195 diez
1196 once
1197 ",
1198 );
1199 }
1200
1201 /// Test for reading all but the first NUM lines: `tail -3`.
1202 #[test]
1203 fn test_obsolete_syntax_positive_lines() {
1204 new_ucmd!()
1205 .args(&["-3"])
1206 .pipe_in("a\nb\nc\nd\ne\n")
1207 .succeeds()
1208 .stdout_is("c\nd\ne\n");
1209 }
1210
1211 /// Test for reading all but the first NUM lines: `tail -n -10`.
1212 #[test]
1213 fn test_small_file() {
1214 new_ucmd!()
1215 .args(&["-n -10"])
1216 .pipe_in("a\nb\nc\nd\ne\n")
1217 .succeeds()
1218 .stdout_is("a\nb\nc\nd\ne\n");
1219 }
1220
1221 /// Test for reading all but the first NUM lines: `tail -10`.
1222 #[test]
1223 fn test_obsolete_syntax_small_file() {
1224 new_ucmd!()
1225 .args(&["-10"])
1226 .pipe_in("a\nb\nc\nd\ne\n")
1227 .succeeds()
1228 .stdout_is("a\nb\nc\nd\ne\n");
1229 }
1230
1231 /// Test for obsolete syntax `tail -0 FILE`: print nothing and exit cleanly.
1232 #[test]
1233 fn test_obsolete_syntax_zero_lines_file() {
1234 new_ucmd!()
1235 .args(&["-0", "foobar.txt"])
1236 .succeeds()
1237 .no_output();
1238 }
1239
1240 /// Test for reading all lines, specified by `tail -n +0`.
1241 #[test]
1242 fn test_positive_zero_lines() {
1243 let ts = TestScenario::new(util_name!());
1244 ts.ucmd()
1245 .args(&["-n", "+0"])
1246 .pipe_in("a\nb\nc\nd\ne\n")
1247 .succeeds()
1248 .stdout_is("a\nb\nc\nd\ne\n");
1249 ts.ucmd()
1250 .args(&["-n", "0"])
1251 .pipe_in("a\nb\nc\nd\ne\n")
1252 .ignore_stdin_write_error()
1253 .succeeds()
1254 .no_output();
1255 }
1256
1257 #[test]
1258 fn test_invalid_num() {
1259 new_ucmd!()
1260 .args(&["-c", "1024R", "emptyfile.txt"])
1261 .fails()
1262 .stderr_str()
1263 .starts_with("tail: invalid number of bytes: '1024R'");
1264 new_ucmd!()
1265 .args(&["-n", "1024R", "emptyfile.txt"])
1266 .fails()
1267 .stderr_str()
1268 .starts_with("tail: invalid number of lines: '1024R'");
1269 // 1Y overflows to u64::MAX (like GNU tail 9.9.x), so it succeeds
1270 new_ucmd!()
1271 .args(&["-c", "1Y"])
1272 .pipe_in("x")
1273 .succeeds()
1274 .stdout_is("x");
1275 new_ucmd!()
1276 .args(&["-n", "1Y"])
1277 .pipe_in("x\n")
1278 .succeeds()
1279 .stdout_is("x\n");
1280 new_ucmd!()
1281 .args(&["-c", "-³"])
1282 .fails()
1283 .stderr_str()
1284 .starts_with("tail: invalid number of bytes: '³'");
1285 }
1286
1287 #[test]
1288 fn test_lowercase_multiplier_suffixes_rejected() {
1289 // GNU accepts a lowercase suffix only for "k" and "m"; every other
1290 // multiplier must be uppercase. "b" is bare-only (no B/iB/D form).
1291 for suffix in ["g", "t", "p", "e", "z", "y", "r", "q"] {
1292 new_ucmd!()
1293 .args(&["-c", &format!("2{suffix}")])
1294 .fails()
1295 .stderr_str()
1296 .starts_with(&format!("tail: invalid number of bytes: '2{suffix}'"));
1297 new_ucmd!()
1298 .args(&["-n", &format!("2{suffix}")])
1299 .fails()
1300 .stderr_str()
1301 .starts_with(&format!("tail: invalid number of lines: '2{suffix}'"));
1302 }
1303 }
1304
1305 #[test]
1306 fn test_accepted_multiplier_suffixes() {
1307 for suffix in [
1308 "b", "k", "m", "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q", "kB", "KiB", "kD", "MiB",
1309 "GB",
1310 ] {
1311 new_ucmd!()
1312 .args(&["-c", &format!("1{suffix}")])
1313 .pipe_in("x")
1314 .ignore_stdin_write_error()
1315 .succeeds();
1316 }
1317 }
1318
1319 #[test]
1320 fn test_oversized_num() {
1321 const BIG: &str = "99999999999999999999999999999";
1322 const DATA: &str = "abcd";
1323 // -c <big> and -n <big>: output all (request more than available)
1324 new_ucmd!()
1325 .args(&["-c", BIG])
1326 .pipe_in(DATA)
1327 .succeeds()
1328 .stdout_is(DATA);
1329 new_ucmd!()
1330 .args(&["-n", BIG])
1331 .pipe_in("a\nb\n")
1332 .succeeds()
1333 .stdout_is("a\nb\n");
1334 // +<big>: skip beyond input (empty output)
1335 new_ucmd!()
1336 .args(&["-c", &format!("+{BIG}")])
1337 .pipe_in(DATA)
1338 .succeeds()
1339 .no_stdout();
1340 new_ucmd!()
1341 .args(&["-n", &format!("+{BIG}")])
1342 .pipe_in("a\nb\n")
1343 .succeeds()
1344 .no_stdout();
1345 // Obsolete syntax
1346 new_ucmd!()
1347 .arg(format!("+{BIG}c"))
1348 .pipe_in(DATA)
1349 .succeeds()
1350 .no_stdout();
1351 new_ucmd!()
1352 .arg(format!("-{BIG}c"))
1353 .pipe_in(DATA)
1354 .succeeds()
1355 .stdout_is(DATA);
1356 }
1357
1358 // `tail -c +N` on a seekable file larger than the block size seeks to byte
1359 // `N-1`. An offset past the largest seekable position must not abort the
1360 // process; it should behave like a start beyond the end of the file.
1361 #[test]
1362 fn test_positive_bytes_file_offset_past_seek_limit() {
1363 let (at, mut ucmd) = at_and_ucmd!();
1364 // Larger than tail's `sane_blksize` (~4 KiB) so the seek path is taken.
1365 at.write("big", &"a".repeat(8192));
1366 ucmd.args(&["-c", "+18446744073709551615", "big"])
1367 .succeeds()
1368 .no_stdout();
1369 }
1370
1371 #[test]
1372 fn test_num_with_undocumented_sign_bytes() {
1373 // tail: '-' is not documented (8.32 man pages)
1374 // head: '+' is not documented (8.32 man pages)
1375 const ALPHABET: &str = "abcdefghijklmnopqrstuvwxyz";
1376 new_ucmd!()
1377 .args(&["-c", "5"])
1378 .pipe_in(ALPHABET)
1379 .succeeds()
1380 .stdout_is("vwxyz");
1381 new_ucmd!()
1382 .args(&["-c", "-5"])
1383 .pipe_in(ALPHABET)
1384 .succeeds()
1385 .stdout_is("vwxyz");
1386 new_ucmd!()
1387 .args(&["-c", "+5"])
1388 .pipe_in(ALPHABET)
1389 .succeeds()
1390 .stdout_is("efghijklmnopqrstuvwxyz");
1391 }
1392
1393 #[test]
1394 #[cfg(unix)]
1395 #[cfg_attr(wasi_runner, ignore = "WASI sandbox: host paths not visible")]
1396 fn test_bytes_for_funny_unix_files() {
1397 // Test tail with byte count
1398 let ts = TestScenario::new(util_name!());
1399 let at = &ts.fixtures;
1400 for file in ["/proc/version", "/sys/kernel/profiling"] {
1401 if !at.file_exists(file) {
1402 continue;
1403 }
1404 let args = ["--bytes", "1", file];
1405 let exp_result = unwrap_or_return!(expected_result(&ts, &args));
1406 let result = ts.ucmd().args(&args).succeeds();
1407 result
1408 .stdout_is(exp_result.stdout_str())
1409 .stderr_is(exp_result.stderr_str());
1410 }
1411 }
1412
1413 #[test]
1414 fn test_retry_warn_without_follow() {
1415 // Test tail --retry behavior
1416 // Ensure --retry without --follow results in a warning.
1417
1418 let ts = TestScenario::new(util_name!());
1419 let at = &ts.fixtures;
1420 let file_name = "FILE";
1421 at.touch(file_name);
1422
1423 ts.ucmd()
1424 .arg(file_name)
1425 .arg("--retry")
1426 .succeeds()
1427 .stderr_is("tail: warning: --retry ignored; --retry is useful only when following\n")
1428 .code_is(0);
1429 }
1430
1431 #[test]
1432 fn test_retry_missing_file_error() {
1433 // Test tail --retry behavior
1434 // The same as test_retry2 with a missing file: expect error message and exit 1.
1435
1436 let ts = TestScenario::new(util_name!());
1437 let missing = "absent";
1438
1439 ts.ucmd()
1440 .arg(missing)
1441 .arg("--retry")
1442 .fails_with_code(1)
1443 .stderr_is(
1444 "tail: warning: --retry ignored; --retry is useful only when following\n\
1445 tail: cannot open 'absent' for reading: No such file or directory\n",
1446 );
1447 }
1448
1449 #[test]
1450 #[cfg(all(
1451 not(target_vendor = "apple"),
1452 not(target_os = "android"),
1453 not(target_os = "freebsd"),
1454 not(target_os = "openbsd"),
1455 not(windows)
1456 ))] // FIXME: for currently not working platforms
1457 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
1458 fn test_retry_follow_name_waits_for_creation() {
1459 // Test tail --retry behavior
1460 // Ensure that `tail --retry --follow=name` waits for the file to appear.
1461
1462 let ts = TestScenario::new(util_name!());
1463 let at = &ts.fixtures;
1464 let missing = "watchme";
1465
1466 let expected_stderr = "tail: cannot open 'watchme' for reading: No such file or directory\n\
1467 tail: 'watchme' has appeared; following new file\n";
1468 let expected_stdout = "hello\n";
1469
1470 let mut delay = 1500;
1471 let mut args = vec!["--follow=name", "--retry", missing, "--use-polling"];
1472 for _ in 0..2 {
1473 let mut p = ts.ucmd().args(&args).run_no_wait();
1474
1475 p.make_assertion_with_delay(delay).is_alive();
1476
1477 at.touch(missing);
1478 p.delay(delay);
1479
1480 at.truncate(missing, "hello\n");
1481 p.delay(delay);
1482
1483 p.kill()
1484 .make_assertion()
1485 .with_all_output()
1486 .stderr_is(expected_stderr)
1487 .stdout_is(expected_stdout);
1488
1489 at.remove(missing);
1490 args.pop();
1491 delay /= 3;
1492 }
1493 }
1494
1495 #[test]
1496 #[cfg(all(
1497 not(target_vendor = "apple"),
1498 not(target_os = "android"),
1499 not(target_os = "freebsd"),
1500 not(target_os = "openbsd"),
1501 not(windows)
1502 ))] // FIXME: for currently not working platforms
1503 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
1504 fn test_retry_descriptor_detects_truncation() {
1505 // Test tail --retry behavior
1506 // Ensure that `tail --retry --follow=descriptor` waits for the file to appear.
1507 // Ensure truncation is detected.
1508
1509 let ts = TestScenario::new(util_name!());
1510 let at = &ts.fixtures;
1511 let missing = "watchme";
1512
1513 let expected_stderr = "tail: warning: --retry only effective for the initial open\n\
1514 tail: cannot open 'watchme' for reading: No such file or directory\n\
1515 tail: 'watchme' has appeared; following new file\n\
1516 tail: watchme: file truncated\n";
1517 let expected_stdout = "greetings\nhi\n";
1518 let mut args = vec![
1519 "-s.1",
1520 "--max-unchanged-stats=1",
1521 "--follow=descriptor",
1522 "--retry",
1523 missing,
1524 "---disable-inotify",
1525 ];
1526 let mut delay = 150;
1527 for _ in 0..2 {
1528 let mut p = ts.ucmd().args(&args).run_no_wait();
1529
1530 p.make_assertion_with_delay(delay).is_alive();
1531
1532 at.touch(missing);
1533 p.delay(delay);
1534
1535 at.truncate(missing, "greetings\n");
1536 p.delay(delay);
1537
1538 // shorter than the previous content, so tail sees the shrink as a truncation
1539 at.truncate(missing, "hi\n");
1540 p.delay(delay);
1541
1542 p.make_assertion().is_alive();
1543 p.kill()
1544 .make_assertion()
1545 .with_all_output()
1546 .stderr_is(expected_stderr)
1547 .stdout_is(expected_stdout);
1548
1549 at.remove(missing);
1550 args.pop();
1551 delay /= 3;
1552 }
1553 }
1554
1555 #[test]
1556 #[cfg(all(
1557 not(target_vendor = "apple"),
1558 not(target_os = "android"),
1559 not(target_os = "freebsd"),
1560 not(target_os = "openbsd"),
1561 not(windows)
1562 ))] // FIXME: for currently not working platforms
1563 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
1564 fn test_retry_descriptor_gives_up_on_untailable() {
1565 // Test tail --retry behavior
1566 // Ensure that `tail --follow=descriptor --retry` exits when the file appears untailable.
1567
1568 let ts = TestScenario::new(util_name!());
1569 let at = &ts.fixtures;
1570 let missing = "watchme";
1571
1572 let expected_stderr = "tail: warning: --retry only effective for the initial open\n\
1573 tail: cannot open 'watchme' for reading: No such file or directory\n\
1574 tail: 'watchme' has been replaced with an untailable file; giving up on this name\n\
1575 tail: no files remaining\n";
1576
1577 let mut delay = 1500;
1578 let mut args = vec!["--follow=descriptor", "--retry", missing, "--use-polling"];
1579 for _ in 0..2 {
1580 let mut p = ts.ucmd().args(&args).run_no_wait();
1581
1582 p.make_assertion_with_delay(delay).is_alive();
1583
1584 at.mkdir(missing);
1585 p.delay(delay);
1586
1587 p.make_assertion()
1588 .is_not_alive()
1589 .with_all_output()
1590 .stderr_only(expected_stderr)
1591 .failure();
1592
1593 at.rmdir(missing);
1594 args.pop();
1595 delay /= 3;
1596 }
1597 }
1598
1599 // intermittent failures on android with diff
1600 // Diff < left / right > :
1601 // ==> existing <==
1602 // >X
1603 #[test]
1604 #[cfg(all(not(windows), not(target_os = "android")))] // FIXME: for currently not working platforms
1605 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
1606 fn test_descriptor_no_retry_skips_late_file() {
1607 // Test tail --retry behavior
1608 // Ensure that --follow=descriptor (without --retry) does *not* try
1609 // to open a file after an initial fail, even when there are other tailable files.
1610
1611 let ts = TestScenario::new(util_name!());
1612 let at = &ts.fixtures;
1613 let missing = "nofile";
1614 let existing = "active";
1615 at.touch(existing);
1616
1617 let expected_stderr = "tail: cannot open 'nofile' for reading: No such file or directory\n";
1618 let expected_stdout = "==> active <==\nhere\n";
1619
1620 let mut p = ts
1621 .ucmd()
1622 .arg("--follow=descriptor")
1623 .arg("nofile")
1624 .arg("active")
1625 .run_no_wait();
1626
1627 #[cfg(target_vendor = "apple")]
1628 let delay = 1500;
1629 #[cfg(not(target_vendor = "apple"))]
1630 let delay = 1000;
1631 p.make_assertion_with_delay(delay).is_alive();
1632
1633 at.truncate(missing, "gone\n");
1634 p.delay(delay);
1635
1636 at.truncate(existing, "here\n");
1637 p.delay(delay);
1638
1639 p.make_assertion().is_alive();
1640 p.kill()
1641 .make_assertion()
1642 .with_all_output()
1643 .stdout_is(expected_stdout)
1644 .stderr_is(expected_stderr);
1645 }
1646
1647 #[test]
1648 #[cfg(all(
1649 not(target_vendor = "apple"),
1650 not(target_os = "android"),
1651 not(target_os = "freebsd"),
1652 not(target_os = "openbsd"),
1653 not(windows)
1654 ))] // FIXME: for currently not working platforms
1655 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
1656 fn test_capital_f_recovers_after_dir_swap() {
1657 // Test tail --retry behavior
1658 // Ensure that `tail -F` retries when the file is initially untailable.
1659
1660 let ts = TestScenario::new(util_name!());
1661 let at = &ts.fixtures;
1662 let untailable = "dir_node";
1663
1664 let expected_stderr = "tail: error reading 'dir_node': Is a directory\n\
1665 tail: dir_node: cannot follow end of this type of file\n\
1666 tail: 'dir_node' has become accessible\n\
1667 tail: 'dir_node' has become inaccessible: No such file or directory\n\
1668 tail: 'dir_node' has been replaced with an untailable file\n\
1669 tail: 'dir_node' has become accessible\n";
1670 let expected_stdout = "alpha\nbeta\n";
1671
1672 let mut args = vec![
1673 "-s.1",
1674 "--max-unchanged-stats=1",
1675 "-F",
1676 untailable,
1677 "--use-polling",
1678 ];
1679
1680 let mut delay = 500;
1681 for _ in 0..2 {
1682 at.mkdir(untailable);
1683
1684 let mut p = ts.ucmd().args(&args).run_no_wait();
1685
1686 p.make_assertion_with_delay(delay).is_alive();
1687
1688 // tail: 'untailable' has become accessible
1689 // or (The first is the common case, "has appeared" arises with slow rmdir):
1690 // tail: 'untailable' has appeared; following new file
1691 at.rmdir(untailable);
1692 at.truncate(untailable, "alpha\n");
1693 p.delay(delay);
1694
1695 // NOTE: GNU's `tail` only shows "become inaccessible"
1696 // if there's a delay between rm and mkdir.
1697 // tail: 'dir_node' has become inaccessible: No such file or directory
1698 at.remove(untailable);
1699 p.delay(delay);
1700
1701 // tail: 'dir_node' has been replaced with an untailable file\n";
1702 at.mkdir(untailable);
1703 p.delay(delay);
1704
1705 // full circle, back to the beginning
1706 at.rmdir(untailable);
1707 at.truncate(untailable, "beta\n");
1708 p.delay(delay);
1709
1710 p.make_assertion().is_alive();
1711 p.kill()
1712 .make_assertion()
1713 .with_all_output()
1714 .stderr_is(expected_stderr)
1715 .stdout_is(expected_stdout);
1716
1717 args.pop();
1718 at.remove(untailable);
1719 delay /= 3;
1720 }
1721 }
1722
1723 /// Under `--follow=name`, a watched file replaced by a symlink must be reported
1724 /// as untailable, not silently followed to the link target (which would
1725 /// exfiltrate its contents).
1726 #[test]
1727 #[cfg(unix)]
1728 #[cfg(not(target_os = "android"))]
1729 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
1730 fn test_follow_name_replaced_by_symlink_is_untailable() {
1731 let ts = TestScenario::new(util_name!());
1732 let at = &ts.fixtures;
1733
1734 at.write("secret", "secret-must-not-leak\n");
1735 at.write("watched", "visible\n");
1736
1737 let mut p = ts
1738 .ucmd()
1739 .args(&[
1740 "-F",
1741 "-s.1",
1742 "--max-unchanged-stats=1",
1743 "--use-polling",
1744 "watched",
1745 ])
1746 .run_no_wait();
1747 p.make_assertion_with_delay(500).is_alive();
1748
1749 // Wait until tail's *initial* read of "watched" has actually completed
1750 // (i.e. the pre-existing content has been printed) before swapping it
1751 // for a symlink. Otherwise, under scheduler contention, tail's initial
1752 // open (which legitimately follows symlinks, like any other file open)
1753 // could race with the swap and open the symlink's target on its very
1754 // first read -- before the untailable-symlink guard (which only applies
1755 // to the follow loop) is even active. That would be a test timing bug,
1756 // not the vulnerability this test is meant to catch.
1757 for _ in 0..50 {
1758 if p.stdout_all().contains("visible") {
1759 break;
1760 }
1761 p.delay(20);
1762 }
1763
1764 // Swap the watched file for a symlink pointing at a secret file.
1765 // Create the symlink under a temporary name and rename it into place
1766 // atomically, so the poller never observes an intermediate state where
1767 // "watched" is missing (which would race with the poll interval and be
1768 // reported as "has become inaccessible" instead).
1769 at.symlink_file("secret", "watched.tmp");
1770 at.rename("watched.tmp", "watched");
1771 p.delay(1000);
1772
1773 p.kill()
1774 .make_assertion()
1775 .with_all_output()
1776 .stdout_does_not_contain("secret-must-not-leak")
1777 .stderr_contains("has been replaced with an untailable symbolic link");
1778 }
1779
1780 #[test]
1781 #[cfg(all(
1782 not(target_vendor = "apple"),
1783 not(target_os = "android"),
1784 not(target_os = "freebsd"),
1785 not(target_os = "openbsd"),
1786 not(windows)
1787 ))] // FIXME: for currently not working platforms
1788 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
1789 fn test_retry8() {
1790 // Ensure that inotify will switch to polling mode if directory
1791 // of the watched file was initially missing and later created.
1792 // This is similar to test_retry9, but without:
1793 // tail: directory containing watched file was removed\n\
1794 // tail: inotify cannot be used, reverting to polling\n\
1795
1796 let ts = TestScenario::new(util_name!());
1797 let at = &ts.fixtures;
1798 let watched_file = Path::new("watched_file");
1799 let parent_dir = Path::new("parent_dir");
1800 let user_path = parent_dir.join(watched_file);
1801 let parent_dir = parent_dir.to_str().unwrap();
1802 let user_path = user_path.to_str().unwrap();
1803
1804 let expected_stderr = "\
1805 tail: cannot open 'parent_dir/watched_file' for reading: No such file or directory\n\
1806 tail: 'parent_dir/watched_file' has appeared; following new file\n\
1807 tail: 'parent_dir/watched_file' has become inaccessible: No such file or directory\n\
1808 tail: 'parent_dir/watched_file' has appeared; following new file\n";
1809 let expected_stdout = "foo\nbar\n";
1810
1811 let delay = 1000;
1812
1813 let mut p = ts
1814 .ucmd()
1815 .arg("-F")
1816 .arg("-s.1")
1817 .arg("--max-unchanged-stats=1")
1818 .arg(user_path)
1819 .run_no_wait();
1820
1821 p.make_assertion_with_delay(delay).is_alive();
1822
1823 // 'parent_dir/watched_file' is orphan
1824 // tail: cannot open 'parent_dir/watched_file' for reading: No such file or directory\n\
1825
1826 // tail: 'parent_dir/watched_file' has appeared; following new file\n\
1827 at.mkdir(parent_dir); // not an orphan anymore
1828 at.append(user_path, "foo\n");
1829 p.delay(delay);
1830
1831 // tail: 'parent_dir/watched_file' has become inaccessible: No such file or directory\n\
1832 at.remove(user_path);
1833 at.rmdir(parent_dir); // 'parent_dir/watched_file' is orphan *again*
1834 p.delay(delay);
1835
1836 // Since 'parent_dir/watched_file' is orphan, this needs to be picked up by polling
1837 // tail: 'parent_dir/watched_file' has appeared; following new file\n";
1838 at.mkdir(parent_dir); // not an orphan anymore
1839 at.append(user_path, "bar\n");
1840 p.delay(delay);
1841
1842 p.make_assertion().is_alive();
1843 p.kill()
1844 .make_assertion()
1845 .with_all_output()
1846 .stderr_is(expected_stderr)
1847 .stdout_is(expected_stdout);
1848 }
1849
1850 #[test]
1851 #[cfg(all(
1852 not(target_vendor = "apple"),
1853 not(target_os = "android"),
1854 not(target_os = "freebsd"),
1855 not(target_os = "openbsd"),
1856 not(windows)
1857 ))] // FIXME: for currently not working platforms
1858 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
1859 fn test_retry9() {
1860 // Test inotify behavior when directory is recreated
1861 // Ensure that inotify will switch to polling mode if directory
1862 // of the watched file was removed and recreated.
1863
1864 use text::BACKEND;
1865
1866 let ts = TestScenario::new(util_name!());
1867 let at = &ts.fixtures;
1868 let watched_file = Path::new("watched_file");
1869 let parent_dir = Path::new("parent_dir");
1870 let user_path = parent_dir.join(watched_file);
1871 let parent_dir = parent_dir.to_str().unwrap();
1872 let user_path = user_path.to_str().unwrap();
1873
1874 let expected_stderr = format!(
1875 "\
1876 tail: 'parent_dir/watched_file' has become inaccessible: No such file or directory\n\
1877 tail: directory containing watched file was removed\n\
1878 tail: {BACKEND} cannot be used, reverting to polling\n\
1879 tail: 'parent_dir/watched_file' has appeared; following new file\n\
1880 tail: 'parent_dir/watched_file' has become inaccessible: No such file or directory\n\
1881 tail: 'parent_dir/watched_file' has appeared; following new file\n\
1882 tail: 'parent_dir/watched_file' has become inaccessible: No such file or directory\n\
1883 tail: 'parent_dir/watched_file' has appeared; following new file\n"
1884 );
1885 let expected_stdout = "foo\nbar\nfoo\nbar\n";
1886
1887 let delay = 400;
1888
1889 at.mkdir(parent_dir);
1890 at.truncate(user_path, "foo\n");
1891 let mut p = ts
1892 .ucmd()
1893 .arg("-F")
1894 .arg("-s.2")
1895 .arg("--max-unchanged-stats=1")
1896 .arg(user_path)
1897 .run_no_wait();
1898
1899 p.make_assertion_with_delay(delay).is_alive();
1900
1901 at.remove(user_path);
1902 at.rmdir(parent_dir);
1903 p.delay(delay);
1904
1905 at.mkdir(parent_dir);
1906 at.truncate(user_path, "bar\n");
1907 p.delay(delay);
1908
1909 at.remove(user_path);
1910 at.rmdir(parent_dir);
1911 p.delay(delay);
1912
1913 at.mkdir(parent_dir);
1914 at.truncate(user_path, "foo\n");
1915 p.delay(delay);
1916
1917 at.remove(user_path);
1918 at.rmdir(parent_dir);
1919 p.delay(delay);
1920
1921 at.mkdir(parent_dir);
1922 at.truncate(user_path, "bar\n");
1923 p.delay(delay);
1924
1925 p.make_assertion().is_alive();
1926 p.kill()
1927 .make_assertion()
1928 .with_all_output()
1929 .stderr_is(expected_stderr)
1930 .stdout_is(expected_stdout);
1931 }
1932
1933 #[test]
1934 #[cfg(all(
1935 not(target_vendor = "apple"),
1936 not(target_os = "android"),
1937 not(target_os = "freebsd"),
1938 not(target_os = "openbsd"),
1939 not(windows)
1940 ))] // FIXME: for currently not working platforms
1941 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
1942 fn test_follow_descriptor_vs_rename1() {
1943 // Test file descriptor behavior vs rename
1944 // $ ((rm -f A && touch A && sleep 1 && echo -n "A\n" >> A && sleep 1 && \
1945 // mv A B && sleep 1 && echo -n "B\n" >> B &)>/dev/null 2>&1 &) ; \
1946 // sleep 1 && target/debug/tail --follow=descriptor A ---disable-inotify
1947 // $ A
1948 // $ B
1949
1950 let ts = TestScenario::new(util_name!());
1951 let at = &ts.fixtures;
1952 let file_a = "FILE_A";
1953 let file_b = "FILE_B";
1954 let file_c = "FILE_C";
1955
1956 let mut args = vec![
1957 "--follow=descriptor",
1958 "-s.1",
1959 "--max-unchanged-stats=1",
1960 file_a,
1961 "---disable-inotify",
1962 ];
1963
1964 let mut delay = 100;
1965 for _ in 0..2 {
1966 at.touch(file_a);
1967
1968 let mut p = ts.ucmd().args(&args).run_no_wait();
1969
1970 p.make_assertion_with_delay(delay).is_alive();
1971
1972 at.append(file_a, "A\n");
1973 p.delay(delay);
1974
1975 at.rename(file_a, file_b);
1976 p.delay(delay);
1977
1978 at.append(file_b, "B\n");
1979 p.delay(delay);
1980
1981 at.rename(file_b, file_c);
1982 p.delay(delay);
1983
1984 at.append(file_c, "C\n");
1985 p.delay(delay);
1986
1987 p.make_assertion().is_alive();
1988 p.kill()
1989 .make_assertion()
1990 .with_all_output()
1991 .stdout_only("A\nB\nC\n");
1992
1993 args.pop();
1994 delay /= 3;
1995 }
1996 }
1997
1998 #[test]
1999 #[cfg(all(
2000 not(target_vendor = "apple"),
2001 not(target_os = "android"),
2002 not(target_os = "freebsd"),
2003 not(target_os = "openbsd"),
2004 not(windows)
2005 ))] // FIXME: for currently not working platforms
2006 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2007 fn test_follow_descriptor_vs_rename2() {
2008 // Ensure the headers are correct for --verbose.
2009 // NOTE: GNU's tail does not update the header from FILE_A to FILE_C after `mv FILE_A FILE_C`
2010
2011 let ts = TestScenario::new(util_name!());
2012 let at = &ts.fixtures;
2013 let file_a = "FILE_A";
2014 let file_b = "FILE_B";
2015 let file_c = "FILE_C";
2016
2017 let mut args = vec![
2018 "--follow=descriptor",
2019 "-s.1",
2020 "--max-unchanged-stats=1",
2021 file_a,
2022 file_b,
2023 "--verbose",
2024 "---disable-inotify",
2025 ];
2026
2027 let mut delay = 150;
2028 for _ in 0..2 {
2029 at.touch(file_a);
2030 at.touch(file_b);
2031 let mut p = ts.ucmd().args(&args).run_no_wait();
2032
2033 p.make_assertion_with_delay(delay).is_alive();
2034
2035 at.rename(file_a, file_c);
2036 p.delay(delay);
2037
2038 at.append(file_c, "X\n");
2039 p.delay(delay);
2040
2041 p.make_assertion().is_alive();
2042 p.kill()
2043 .make_assertion()
2044 .with_all_output()
2045 .stdout_only("==> FILE_A <==\n\n==> FILE_B <==\n\n==> FILE_A <==\nX\n");
2046
2047 args.pop();
2048 delay /= 3;
2049 }
2050 }
2051
2052 #[test]
2053 #[cfg(all(
2054 not(target_vendor = "apple"),
2055 not(target_os = "android"),
2056 not(target_os = "freebsd"),
2057 not(target_os = "openbsd"),
2058 not(windows)
2059 ))] // FIXME: for currently not working platforms
2060 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2061 fn test_follow_name_shows_headers_on_creation() {
2062 // Test -F flag with file headers
2063 // Ensure tail -F distinguishes output with the
2064 // correct headers for created/renamed files
2065
2066 /*
2067 $ tail --follow=descriptor -s.1 --max-unchanged-stats=1 -F log1 log2
2068 tail: cannot open 'log1' for reading: No such file or directory
2069 tail: cannot open 'log2' for reading: No such file or directory
2070 tail: 'log1' has appeared; following new file
2071 ==> log1 <==
2072 ping
2073 tail: 'log2' has appeared; following new file
2074
2075 ==> log2 <==
2076 pong
2077 */
2078
2079 let ts = TestScenario::new(util_name!());
2080 let at = &ts.fixtures;
2081 let file_a = "log1";
2082 let file_b = "log2";
2083
2084 let mut args = vec![
2085 "-F",
2086 "-s.1",
2087 "--max-unchanged-stats=1",
2088 file_a,
2089 file_b,
2090 "---disable-inotify",
2091 ];
2092
2093 let mut delay = 150;
2094 for _ in 0..2 {
2095 let mut p = ts.ucmd().args(&args).run_no_wait();
2096
2097 p.make_assertion_with_delay(delay).is_alive();
2098
2099 at.truncate(file_a, "ping\n");
2100 p.delay(delay);
2101
2102 at.truncate(file_b, "pong\n");
2103 p.delay(delay);
2104
2105 let expected_stderr = "tail: cannot open 'log1' for reading: No such file or directory\n\
2106 tail: cannot open 'log2' for reading: No such file or directory\n\
2107 tail: 'log1' has appeared; following new file\n\
2108 tail: 'log2' has appeared; following new file\n";
2109 let expected_stdout = "\n==> log1 <==\nping\n\n==> log2 <==\npong\n";
2110
2111 p.make_assertion().is_alive();
2112 p.kill()
2113 .make_assertion()
2114 .with_all_output()
2115 .stdout_is(expected_stdout)
2116 .stderr_is(expected_stderr);
2117
2118 at.remove(file_a);
2119 at.remove(file_b);
2120 args.pop();
2121 delay /= 3;
2122 }
2123 }
2124
2125 #[test]
2126 #[cfg(all(not(windows), not(target_os = "android")))] // FIXME: for currently not working platforms
2127 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2128 fn test_follow_name_remove() {
2129 // This test triggers a remove event while `tail --follow=name file` is running.
2130 // ((sleep 2 && rm file &)>/dev/null 2>&1 &) ; tail --follow=name file
2131
2132 let ts = TestScenario::new(util_name!());
2133 let at = &ts.fixtures;
2134
2135 let source = FOLLOW_NAME_TXT;
2136 let source_copy = "source_copy";
2137 at.copy(source, source_copy);
2138
2139 let expected_stdout = at.read(FOLLOW_NAME_SHORT_EXP);
2140 let expected_stderr = [
2141 format!(
2142 "{}: {source_copy}: No such file or directory\n{0}: no files remaining\n",
2143 ts.util_name,
2144 ),
2145 format!(
2146 "{}: {source_copy}: No such file or directory\n",
2147 ts.util_name,
2148 ),
2149 ];
2150
2151 let mut args = vec!["--follow=name", source_copy, "--use-polling"];
2152
2153 let mut delay = 1500;
2154 #[allow(clippy::needless_range_loop)]
2155 for i in 0..2 {
2156 at.copy(source, source_copy);
2157
2158 let mut p = ts.ucmd().args(&args).run_no_wait();
2159
2160 p.make_assertion_with_delay(delay).is_alive();
2161
2162 at.remove(source_copy);
2163 p.delay(delay);
2164
2165 if i == 0 {
2166 p.make_assertion()
2167 .is_not_alive()
2168 .with_all_output()
2169 .stdout_is(&expected_stdout)
2170 .stderr_is(&expected_stderr[i])
2171 .failure();
2172 } else {
2173 p.make_assertion().is_alive();
2174 p.kill()
2175 .make_assertion()
2176 .with_all_output()
2177 .stdout_is(&expected_stdout)
2178 .stderr_is(&expected_stderr[i]);
2179 }
2180
2181 args.pop();
2182 delay /= 3;
2183 }
2184 }
2185
2186 #[test]
2187 #[cfg(all(not(target_os = "android"), not(target_os = "freebsd")))] // FIXME: for currently not working platforms
2188 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2189 fn test_follow_name_truncate1() {
2190 // This test triggers a truncate event while `tail --follow=name file` is running.
2191 // $ cp file backup && head file > file && sleep 1 && cp backup file
2192
2193 let ts = TestScenario::new(util_name!());
2194 let at = &ts.fixtures;
2195
2196 let source = FOLLOW_NAME_TXT;
2197 let backup = "backup";
2198
2199 let expected_stdout = at.read(FOLLOW_NAME_EXP);
2200 // `expected_stdout` starts with tail's initial static output (the last 10 lines);
2201 // everything after that only appears once the truncate/restore below are observed.
2202 let initial_stdout = &expected_stdout[..expected_stdout.find("END(25)\n").unwrap() + 8];
2203 let expected_stderr = format!("{}: {source}: file truncated\n", ts.util_name);
2204
2205 let args = ["--follow=name", source];
2206 let mut p = ts.ucmd().args(&args).run_no_wait();
2207 let delay = 1000;
2208 p.make_assertion().is_alive();
2209
2210 // Wait for tail's initial read of `source` to finish before mutating it below.
2211 // Watch registration happens before this initial output is printed, so once it
2212 // appears the truncate/restore below are guaranteed to be observed as events.
2213 // A fixed delay isn't enough here: a slow-starting child process (observed on
2214 // macOS CI, see #12335) can otherwise race ahead of tail's own startup.
2215 for _ in 0..500 {
2216 if p.stdout_all() == initial_stdout {
2217 break;
2218 }
2219 p.delay(10);
2220 }
2221
2222 at.copy(source, backup);
2223 p.delay(delay);
2224
2225 at.touch(source); // trigger truncate
2226 p.delay(delay);
2227
2228 at.copy(backup, source);
2229 p.delay(delay);
2230
2231 p.make_assertion().is_alive();
2232 p.kill()
2233 .make_assertion()
2234 .with_all_output()
2235 .stderr_is(expected_stderr)
2236 .stdout_is(expected_stdout);
2237 }
2238
2239 #[test]
2240 #[cfg(all(not(target_os = "android"), not(target_os = "freebsd")))] // FIXME: for currently not working platforms
2241 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2242 fn test_follow_name_truncate2() {
2243 fn wait_for_output(
2244 child: &mut uutests::util::UChild,
2245 expected_stdout: &str,
2246 expected_stderr: &str,
2247 ) {
2248 for _ in 0..500 {
2249 if child.stdout_all() == expected_stdout && child.stderr_all() == expected_stderr {
2250 return;
2251 }
2252 child.delay(10);
2253 }
2254 child
2255 .make_assertion()
2256 .with_all_output()
2257 .stdout_is(expected_stdout)
2258 .stderr_is(expected_stderr);
2259 }
2260
2261 // This test triggers a truncate event while `tail --follow=name file` is running.
2262 // $ ((sleep 1 && echo -n "x\nx\nx\n" >> file && sleep 1 && \
2263 // echo -n "x\n" > file &)>/dev/null 2>&1 &) ; tail --follow=name file
2264
2265 let ts = TestScenario::new(util_name!());
2266 let at = &ts.fixtures;
2267
2268 let source = "file";
2269 at.touch(source);
2270
2271 let expected_stdout = "x\nx\nx\nx\n";
2272 let expected_stderr = format!("{}: {source}: file truncated\n", ts.util_name);
2273
2274 let args = ["--follow=name", source];
2275 let mut p = ts.ucmd().args(&args).run_no_wait();
2276
2277 p.make_assertion().is_alive();
2278
2279 at.append(source, "x\n");
2280 wait_for_output(&mut p, "x\n", "");
2281
2282 at.append(source, "x\n");
2283 wait_for_output(&mut p, "x\nx\n", "");
2284
2285 at.append(source, "x\n");
2286 wait_for_output(&mut p, "x\nx\nx\n", "");
2287
2288 at.truncate(source, "x\n");
2289 wait_for_output(&mut p, expected_stdout, &expected_stderr);
2290
2291 p.make_assertion().is_alive();
2292
2293 p.kill()
2294 .make_assertion()
2295 .with_all_output()
2296 .stderr_is(expected_stderr)
2297 .stdout_is(expected_stdout);
2298 }
2299
2300 #[test]
2301 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2302 fn test_follow_name_truncate3() {
2303 // Opening an empty file in truncate mode should not trigger a truncate event while
2304 // `tail --follow=name file` is running.
2305 // $ rm -f file && touch file
2306 // $ ((sleep 1 && echo -n "x\n" > file &)>/dev/null 2>&1 &) ; tail --follow=name file
2307
2308 let ts = TestScenario::new(util_name!());
2309 let at = &ts.fixtures;
2310
2311 let source = "file";
2312 at.touch(source);
2313
2314 let expected_stdout = "x\n";
2315
2316 let args = ["--follow=name", source];
2317 let mut p = ts.ucmd().args(&args).run_no_wait();
2318
2319 let delay = 1000;
2320 p.make_assertion_with_delay(delay).is_alive();
2321
2322 at.truncate(source, "x\n");
2323 p.delay(delay);
2324
2325 p.make_assertion().is_alive();
2326 p.kill()
2327 .make_assertion()
2328 .with_all_output()
2329 .stdout_only(expected_stdout);
2330 }
2331
2332 #[test]
2333 #[cfg(all(
2334 not(target_vendor = "apple"),
2335 not(windows),
2336 not(feature = "selinux") // flaky
2337 ))] // FIXME: for currently not working platforms
2338 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2339 fn test_follow_name_truncate4() {
2340 // Truncating a file with the same content it already has should not trigger a truncate event
2341
2342 let ts = TestScenario::new(util_name!());
2343 let at = &ts.fixtures;
2344
2345 let mut args = vec!["-s.1", "--max-unchanged-stats=1", "-F", "file"];
2346
2347 let mut delay = 500;
2348 for i in 0..2 {
2349 at.append("file", "foobar\n");
2350
2351 let mut p = ts.ucmd().args(&args).run_no_wait();
2352
2353 p.make_assertion_with_delay(delay).is_alive();
2354
2355 at.truncate("file", "foobar\n");
2356 p.delay(delay);
2357
2358 p.make_assertion().is_alive();
2359 p.kill()
2360 .make_assertion()
2361 .with_all_output()
2362 .stdout_only("foobar\n");
2363
2364 at.remove("file");
2365 if i == 0 {
2366 args.push("---disable-inotify");
2367 }
2368 delay *= 3;
2369 }
2370 }
2371
2372 #[test]
2373 #[cfg(not(windows))] // FIXME: for currently not working platforms
2374 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2375 fn test_follow_detects_file_truncation() {
2376 // Test tail behavior on file truncation
2377 // Ensure all logs are output upon file truncation
2378
2379 // This is similar to `test_follow_name_truncate1-3` but uses very short delays
2380 // to better mimic the tight timings used in the "truncate.sh" test.
2381 // This is here to test for "speed" only, all the logic is already covered by other tests.
2382
2383 if is_ci() {
2384 println!("TEST SKIPPED (too fast for CI)");
2385 return;
2386 }
2387
2388 let ts = TestScenario::new(util_name!());
2389 let at = &ts.fixtures;
2390
2391 let mut args = vec![
2392 "-s.1",
2393 "--max-unchanged-stats=1",
2394 "data",
2395 "---disable-inotify",
2396 ];
2397 let follow = vec!["-f", "-F"];
2398
2399 let mut delay = 1000;
2400 for _ in 0..2 {
2401 for mode in &follow {
2402 args.push(mode);
2403
2404 at.truncate("data", "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n");
2405
2406 let mut p = ts.ucmd().args(&args).run_no_wait();
2407 p.make_assertion_with_delay(delay).is_alive();
2408
2409 at.truncate("data", "11\n12\n13\n14\n15\n");
2410 p.delay(delay);
2411
2412 p.make_assertion().is_alive();
2413 p.kill()
2414 .make_assertion()
2415 .with_all_output()
2416 .stderr_is("tail: data: file truncated\n")
2417 .stdout_is("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n");
2418
2419 args.pop();
2420 }
2421 args.pop();
2422 delay = 250;
2423 }
2424 }
2425
2426 #[test]
2427 #[cfg(all(
2428 not(target_vendor = "apple"),
2429 not(target_os = "android"),
2430 not(target_os = "freebsd"),
2431 not(target_os = "openbsd"),
2432 not(windows)
2433 ))] // FIXME: for currently not working platforms
2434 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2435 fn test_follow_name_move_create1() {
2436 // This test triggers a move/create event while `tail --follow=name file` is running.
2437 // ((sleep 2 && mv file backup && sleep 2 && cp backup file &)>/dev/null 2>&1 &) ; tail --follow=name file
2438
2439 let ts = TestScenario::new(util_name!());
2440 let at = &ts.fixtures;
2441
2442 let source = FOLLOW_NAME_TXT;
2443 let backup = "backup";
2444
2445 #[cfg(target_os = "linux")]
2446 let expected_stdout = at.read(FOLLOW_NAME_EXP);
2447
2448 #[cfg(target_os = "linux")]
2449 let expected_stderr = format!(
2450 "{}: {source}: No such file or directory\n{0}: '{source}' has appeared; following new file\n",
2451 ts.util_name,
2452 );
2453
2454 // NOTE: We are less strict if not on Linux (inotify backend).
2455
2456 #[cfg(not(target_os = "linux"))]
2457 let expected_stdout = at.read(FOLLOW_NAME_SHORT_EXP);
2458
2459 #[cfg(not(target_os = "linux"))]
2460 let expected_stderr = format!("{}: {source}: No such file or directory\n", ts.util_name);
2461
2462 let delay = 500;
2463 let args = ["--follow=name", source];
2464
2465 let mut p = ts.ucmd().args(&args).run_no_wait();
2466
2467 p.make_assertion_with_delay(delay).is_alive();
2468
2469 at.rename(source, backup);
2470 p.delay(delay);
2471
2472 at.copy(backup, source);
2473 p.delay(delay);
2474
2475 p.make_assertion().is_alive();
2476 p.kill()
2477 .make_assertion()
2478 .with_all_output()
2479 .stderr_is(expected_stderr)
2480 .stdout_is(expected_stdout);
2481 }
2482
2483 #[test]
2484 #[cfg(all(
2485 not(target_vendor = "apple"),
2486 not(target_os = "android"),
2487 not(target_os = "freebsd"),
2488 not(target_os = "openbsd"),
2489 not(windows)
2490 ))] // FIXME: for currently not working platforms
2491 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2492 fn test_follow_name_hash_table_stress() {
2493 // Test inotify hash table under heavy file churn by watching 9 files simultaneously.
2494 // Exercises an abort-inducing flaw in inotify-enabled tail -F
2495
2496 let ts = TestScenario::new(util_name!());
2497 let at = &ts.fixtures;
2498
2499 for n in ["1", "2", "3", "4", "5", "6", "7", "8", "9"] {
2500 at.touch(n);
2501 }
2502
2503 let mut args = vec![
2504 "-s.1",
2505 "--max-unchanged-stats=1",
2506 "-q",
2507 "-F",
2508 "1",
2509 "2",
2510 "3",
2511 "4",
2512 "5",
2513 "6",
2514 "7",
2515 "8",
2516 "9",
2517 ];
2518
2519 let mut delay = 100;
2520 for i in 0..2 {
2521 let mut p = ts.ucmd().args(&args).run_no_wait();
2522
2523 p.make_assertion_with_delay(delay).is_alive();
2524
2525 at.truncate("9", "x\n");
2526 p.delay(delay);
2527
2528 at.rename("1", "moved");
2529 p.delay(delay);
2530
2531 at.truncate("1", "a\n");
2532 p.delay(delay);
2533
2534 // NOTE: Files used in the previous loop iteration are reused intentionally
2535 // during the first loop iteration, we also don't clear them to get the same side-effects.
2536 // Side-effects are truncating a file with the same content, see: test_follow_name_truncate4
2537 // at.remove("1");
2538 // at.touch("1");
2539 // at.remove("9");
2540 // at.touch("9");
2541 let expected_stdout = if args.len() == 14 {
2542 "a\nx\na\n"
2543 } else {
2544 "x\na\n"
2545 };
2546 let expected_stderr = "tail: '1' has become inaccessible: No such file or directory\n\
2547 tail: '1' has appeared; following new file\n";
2548
2549 p.make_assertion().is_alive();
2550 p.kill()
2551 .make_assertion()
2552 .with_all_output()
2553 .stderr_is(expected_stderr)
2554 .stdout_is(expected_stdout);
2555
2556 at.remove("moved");
2557 if i == 0 {
2558 args.push("---disable-inotify");
2559 }
2560 delay *= 3;
2561 }
2562 }
2563
2564 #[test]
2565 #[cfg(all(
2566 not(target_vendor = "apple"),
2567 not(target_os = "android"),
2568 not(target_os = "freebsd"),
2569 not(target_os = "openbsd"),
2570 not(windows)
2571 ))] // FIXME: for currently not working platforms
2572 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2573 fn test_follow_name_move1() {
2574 // This test triggers a move event while `tail --follow=name file` is running.
2575 // ((sleep 2 && mv file backup &)>/dev/null 2>&1 &) ; tail --follow=name file
2576 // NOTE: For `---disable-inotify` tail exits with "no file remaining", it stays open w/o it.
2577
2578 let ts = TestScenario::new(util_name!());
2579 let at = &ts.fixtures;
2580
2581 let source = FOLLOW_NAME_TXT;
2582 let backup = "backup";
2583
2584 let expected_stdout = at.read(FOLLOW_NAME_SHORT_EXP);
2585 let expected_stderr = [
2586 format!("{}: {source}: No such file or directory\n", ts.util_name),
2587 format!(
2588 "{}: {source}: No such file or directory\n{0}: no files remaining\n",
2589 ts.util_name,
2590 ),
2591 ];
2592
2593 let mut args = vec!["--follow=name", source];
2594
2595 let mut delay = 500;
2596 #[allow(clippy::needless_range_loop)]
2597 for i in 0..2 {
2598 let mut p = ts.ucmd().args(&args).run_no_wait();
2599
2600 p.make_assertion_with_delay(delay).is_alive();
2601
2602 at.rename(source, backup);
2603 p.delay(delay);
2604
2605 if i == 0 {
2606 p.make_assertion().is_alive();
2607 p.kill()
2608 .make_assertion()
2609 .with_all_output()
2610 .stderr_is(&expected_stderr[i])
2611 .stdout_is(&expected_stdout);
2612 } else {
2613 p.make_assertion()
2614 .is_not_alive()
2615 .with_all_output()
2616 .stderr_is(&expected_stderr[i])
2617 .stdout_is(&expected_stdout)
2618 .failure();
2619 }
2620
2621 at.rename(backup, source);
2622 args.push("--use-polling");
2623 delay *= 3;
2624 }
2625 }
2626
2627 #[test]
2628 #[cfg(all(
2629 not(target_vendor = "apple"),
2630 not(target_os = "android"),
2631 not(target_os = "freebsd"),
2632 not(target_os = "openbsd"),
2633 not(windows)
2634 ))] // FIXME: for currently not working platforms
2635 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2636 fn test_follow_name_move2() {
2637 // Like test_follow_name_move1, but move to a name that's already monitored.
2638
2639 // $ echo file1_content > file1; echo file2_content > file2; \
2640 // ((sleep 2 ; mv file1 file2 ; sleep 1 ; echo "more_file2_content" >> file2 ; sleep 1 ; \
2641 // echo "more_file1_content" >> file1 &)>/dev/null 2>&1 &) ; \
2642 // tail --follow=name file1 file2
2643 // ==> file1 <==
2644 // file1_content
2645 //
2646 // ==> file2 <==
2647 // file2_content
2648 // tail: file1: No such file or directory
2649 // tail: 'file2' has been replaced; following new file
2650 // file1_content
2651 // more_file2_content
2652 // tail: 'file1' has appeared; following new file
2653 //
2654 // ==> file1 <==
2655 // more_file1_content
2656
2657 let ts = TestScenario::new(util_name!());
2658 let at = &ts.fixtures;
2659
2660 let file1 = "file1";
2661 let file2 = "file2";
2662
2663 let expected_stdout = format!(
2664 "==> {file1} <==\n{file1}_content\n\n==> {file2} <==\n{file2}_content\n{file1}_content\n\
2665 more_{file2}_content\n\n==> {file1} <==\nmore_{file1}_content\n"
2666 );
2667 let mut expected_stderr = format!(
2668 "{0}: {1}: No such file or directory\n\
2669 {0}: '{2}' has been replaced; following new file\n\
2670 {0}: '{1}' has appeared; following new file\n",
2671 ts.util_name, file1, file2
2672 );
2673
2674 let mut args = vec!["--follow=name", file1, file2];
2675
2676 let mut delay = 500;
2677 for i in 0..2 {
2678 at.truncate(file1, "file1_content\n");
2679 at.truncate(file2, "file2_content\n");
2680
2681 let mut p = ts.ucmd().args(&args).run_no_wait();
2682 p.make_assertion_with_delay(delay).is_alive();
2683
2684 at.rename(file1, file2);
2685 p.delay(delay);
2686
2687 at.append(file2, "more_file2_content\n");
2688 p.delay(delay);
2689
2690 at.append(file1, "more_file1_content\n");
2691 p.delay(delay);
2692
2693 p.make_assertion().is_alive();
2694 p.kill()
2695 .make_assertion()
2696 .with_all_output()
2697 .stderr_is(&expected_stderr)
2698 .stdout_is(&expected_stdout);
2699
2700 if i == 0 {
2701 args.push("--use-polling");
2702 }
2703 delay *= 3;
2704 // NOTE: Switch the first and second line because the events come in this order from
2705 // `notify::PollWatcher`. However, for GNU's tail, the order between polling and not
2706 // polling does not change.
2707 expected_stderr = format!(
2708 "{0}: '{2}' has been replaced; following new file\n\
2709 {0}: {1}: No such file or directory\n\
2710 {0}: '{1}' has appeared; following new file\n",
2711 ts.util_name, file1, file2
2712 );
2713 }
2714 }
2715
2716 #[test]
2717 #[cfg(all(
2718 not(target_vendor = "apple"),
2719 not(target_os = "android"),
2720 not(target_os = "freebsd"),
2721 not(target_os = "openbsd"),
2722 not(windows)
2723 ))] // FIXME: for currently not working platforms
2724 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2725 fn test_follow_name_move_retry1() {
2726 // Similar to test_follow_name_move1 but with `--retry` (`-F`)
2727 // This test triggers two move/rename events while `tail --follow=name --retry file` is running.
2728
2729 let ts = TestScenario::new(util_name!());
2730 let at = &ts.fixtures;
2731
2732 let source = FOLLOW_NAME_TXT;
2733 let backup = "backup";
2734
2735 let expected_stderr = format!(
2736 "{0}: '{1}' has become inaccessible: No such file or directory\n\
2737 {0}: '{1}' has appeared; following new file\n",
2738 ts.util_name, source
2739 );
2740 let expected_stdout = "tailed\nnew content\n";
2741
2742 let mut args = vec!["--follow=name", "--retry", source, "--use-polling"];
2743
2744 let mut delay = 1500;
2745 for _ in 0..2 {
2746 at.touch(source);
2747 let mut p = ts.ucmd().args(&args).run_no_wait();
2748
2749 p.make_assertion_with_delay(delay).is_alive();
2750
2751 at.append(source, "tailed\n");
2752 p.delay(delay);
2753
2754 // with --follow=name, tail should stop monitoring the renamed file
2755 at.rename(source, backup);
2756 p.delay(delay);
2757 // overwrite backup while it's not monitored
2758 at.truncate(backup, "new content\n");
2759 p.delay(delay);
2760 // move back, tail should pick this up and print new content
2761 at.rename(backup, source);
2762 p.delay(delay);
2763
2764 p.make_assertion().is_alive();
2765 p.kill()
2766 .make_assertion()
2767 .with_all_output()
2768 .stderr_is(&expected_stderr)
2769 .stdout_is(expected_stdout);
2770
2771 at.remove(source);
2772 args.pop();
2773 delay /= 3;
2774 }
2775 }
2776
2777 #[test]
2778 #[cfg(all(
2779 not(target_vendor = "apple"),
2780 not(target_os = "android"),
2781 not(target_os = "freebsd"),
2782 not(target_os = "openbsd"),
2783 not(windows)
2784 ))] // FIXME: for currently not working platforms
2785 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2786 fn test_follow_name_rename_chain() {
2787 // Test -F flag behavior across file renames
2788 // Similar to test_follow_name_move2 (move to a name that's already monitored)
2789 // but with `--retry` (`-F`)
2790
2791 /*
2792 $ touch a b
2793 $ ((sleep 1; echo x > a; mv a b; echo x2 > a; echo y >> b; echo z >> a &)>/dev/null 2>&1 &) ; tail -F a b
2794 ==> a <==
2795
2796 ==> b <==
2797
2798 ==> a <==
2799 x
2800 tail: 'a' has become inaccessible: No such file or directory
2801 tail: 'b' has been replaced; following new file
2802
2803 ==> b <==
2804 x
2805 tail: 'a' has appeared; following new file
2806
2807 ==> a <==
2808 x2
2809
2810 ==> b <==
2811 y
2812
2813 ==> a <==
2814 z
2815 */
2816
2817 let ts = TestScenario::new(util_name!());
2818 let at = &ts.fixtures;
2819
2820 let file1 = "a";
2821 let file2 = "b";
2822
2823 let expected_stdout = format!(
2824 "==> {file1} <==\n\n==> {file2} <==\n\n==> {file1} <==\nx\n\n==> {file2} <==\
2825 \nx\n\n==> {file1} <==\nx2\n\n==> {file2} <==\ny\n\n==> {file1} <==\nz\n"
2826 );
2827 let mut expected_stderr = format!(
2828 "{0}: '{1}' has become inaccessible: No such file or directory\n\
2829 {0}: '{2}' has been replaced; following new file\n\
2830 {0}: '{1}' has appeared; following new file\n",
2831 ts.util_name, file1, file2
2832 );
2833
2834 let mut args = vec!["-s.1", "--max-unchanged-stats=1", "-F", file1, file2];
2835
2836 let mut delay = 60;
2837 for i in 0..2 {
2838 at.touch(file1);
2839 at.touch(file2);
2840
2841 let mut p = ts.ucmd().args(&args).run_no_wait();
2842 p.make_assertion_with_delay(delay).is_alive();
2843
2844 at.truncate(file1, "x\n");
2845 p.delay(delay);
2846
2847 at.rename(file1, file2);
2848 p.delay(delay);
2849
2850 at.truncate(file1, "x2\n");
2851 p.delay(delay);
2852
2853 at.append(file2, "y\n");
2854 p.delay(delay);
2855
2856 at.append(file1, "z\n");
2857 p.delay(delay);
2858
2859 p.make_assertion().is_alive();
2860 p.kill()
2861 .make_assertion()
2862 .with_all_output()
2863 .stderr_is(&expected_stderr)
2864 .stdout_is(&expected_stdout);
2865
2866 at.remove(file1);
2867 at.remove(file2);
2868 if i == 0 {
2869 args.push("--use-polling");
2870 }
2871 delay *= 3;
2872 // NOTE: Switch the first and second line because the events come in this order from
2873 // `notify::PollWatcher`. However, for GNU's tail, the order between polling and not
2874 // polling does not change.
2875 expected_stderr = format!(
2876 "{0}: '{2}' has been replaced; following new file\n\
2877 {0}: '{1}' has become inaccessible: No such file or directory\n\
2878 {0}: '{1}' has appeared; following new file\n",
2879 ts.util_name, file1, file2
2880 );
2881 }
2882 }
2883
2884 #[test]
2885 #[cfg(not(windows))] // FIXME: for currently not working platforms
2886 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
2887 fn test_follow_inotify_only_regular() {
2888 // The GNU test inotify-only-regular.sh uses strace to ensure that `tail -f`
2889 // doesn't make inotify syscalls and only uses inotify for regular files or fifos.
2890 // We just check if tailing a character device has the same behavior as GNU's tail.
2891
2892 let ts = TestScenario::new(util_name!());
2893
2894 let mut p = ts.ucmd().arg("-f").arg("/dev/null").run_no_wait();
2895
2896 p.make_assertion_with_delay(200).is_alive();
2897 p.kill().make_assertion().with_all_output().no_output();
2898 }
2899
2900 #[test]
2901 fn test_no_such_file() {
2902 new_ucmd!()
2903 .arg("missing")
2904 .fails_with_code(1)
2905 .stderr_is("tail: cannot open 'missing' for reading: No such file or directory\n")
2906 .no_stdout();
2907 }
2908
2909 #[test]
2910 fn test_no_trailing_newline() {
2911 new_ucmd!().pipe_in("x").succeeds().stdout_only("x");
2912 }
2913
2914 #[test]
2915 fn test_lines_zero_terminated() {
2916 new_ucmd!()
2917 .args(&["-z", "-n", "2"])
2918 .pipe_in("a\0b\0c\0d\0e\0")
2919 .succeeds()
2920 .stdout_only("d\0e\0");
2921 new_ucmd!()
2922 .args(&["-z", "-n", "+2"])
2923 .pipe_in("a\0b\0c\0d\0e\0")
2924 .succeeds()
2925 .stdout_only("b\0c\0d\0e\0");
2926 }
2927
2928 #[test]
2929 fn test_presume_input_pipe_default() {
2930 new_ucmd!()
2931 .arg("---presume-input-pipe")
2932 .pipe_in_fixture(FOOBAR_TXT)
2933 .succeeds()
2934 .stdout_is_fixture("foobar_stdin_default.expected")
2935 .no_stderr();
2936 }
2937
2938 #[test]
2939 #[cfg(not(windows))]
2940 fn test_fifo() {
2941 let ts = TestScenario::new(util_name!());
2942 let at = &ts.fixtures;
2943 at.mkfifo("FIFO");
2944
2945 let mut p = ts.ucmd().arg("FIFO").run_no_wait();
2946 p.make_assertion_with_delay(500).is_alive();
2947 p.kill().make_assertion().with_all_output().no_output();
2948
2949 for arg in ["-f", "-F"] {
2950 let mut p = ts.ucmd().arg(arg).arg("FIFO").run_no_wait();
2951 p.make_assertion_with_delay(500).is_alive();
2952 p.kill().make_assertion().with_all_output().no_output();
2953 }
2954 }
2955
2956 /// Test that tail with --pid exits when the monitored process dies, even with a FIFO.
2957 /// Without non-blocking FIFO open, tail would block forever waiting for a writer.
2958 #[test]
2959 #[cfg(all(
2960 not(target_os = "android"),
2961 not(target_os = "freebsd"),
2962 not(target_os = "openbsd"),
2963 not(windows)
2964 ))]
2965 #[cfg_attr(wasi_runner, ignore = "WASI: no FIFO/mkfifo support")]
2966 fn test_fifo_with_pid() {
2967 use std::process::{Command, Stdio};
2968
2969 let (at, mut ucmd) = at_and_ucmd!();
2970 at.mkfifo("FIFO");
2971
2972 let mut dummy = Command::new("sh").stdin(Stdio::null()).spawn().unwrap();
2973 let pid = dummy.id();
2974
2975 let mut child = ucmd
2976 .arg("-f")
2977 .arg(format!("--pid={pid}"))
2978 .arg("FIFO")
2979 .run_no_wait();
2980
2981 child.make_assertion_with_delay(500).is_alive();
2982
2983 kill_process(
2984 Pid::from_raw(i32::try_from(pid).unwrap()).unwrap(),
2985 Signal::USR1,
2986 )
2987 .unwrap();
2988 let _ = dummy.wait();
2989
2990 child
2991 .make_assertion_with_delay(DEFAULT_SLEEP_INTERVAL_MILLIS)
2992 .is_not_alive()
2993 .with_all_output()
2994 .no_output()
2995 .success();
2996 }
2997
2998 #[test]
2999 #[cfg(unix)]
3000 #[ignore = "disabled until fixed"]
3001 fn test_illegal_seek() {
3002 // This is here for reference only.
3003 // We don't call seek on fifos, so we don't hit this error case.
3004 // (Also see: https://github.com/coreutils/coreutils/pull/36)
3005
3006 let ts = TestScenario::new(util_name!());
3007 let at = &ts.fixtures;
3008 at.append("FILE", "foo\n");
3009 at.mkfifo("FIFO");
3010
3011 let mut p = ts.ucmd().arg("FILE").run_no_wait();
3012 p.make_assertion_with_delay(500).is_alive();
3013
3014 at.rename("FILE", "FIFO");
3015 p.delay(500);
3016
3017 p.make_assertion().is_alive();
3018 let expected_stderr = "tail: 'FILE' has been replaced; following new file\n\
3019 tail: FILE: cannot seek to offset 0: Illegal seek\n";
3020 p.kill()
3021 .make_assertion()
3022 .with_all_output()
3023 .stderr_is(expected_stderr)
3024 .stdout_is("foo\n")
3025 .code_is(1); // is this correct? after kill the code is not meaningful.
3026 }
3027
3028 #[test]
3029 fn test_pipe_when_lines_option_value_is_higher_than_contained_lines() {
3030 let test_string = "a\nb\n";
3031 new_ucmd!()
3032 .args(&["-n", "3"])
3033 .pipe_in(test_string)
3034 .ignore_stdin_write_error()
3035 .succeeds()
3036 .stdout_only(test_string);
3037
3038 new_ucmd!()
3039 .args(&["-n", "4"])
3040 .pipe_in(test_string)
3041 .ignore_stdin_write_error()
3042 .succeeds()
3043 .stdout_only(test_string);
3044
3045 new_ucmd!()
3046 .args(&["-n", "999"])
3047 .pipe_in(test_string)
3048 .ignore_stdin_write_error()
3049 .succeeds()
3050 .stdout_only(test_string);
3051
3052 new_ucmd!()
3053 .args(&["-n", "+3"])
3054 .pipe_in(test_string)
3055 .ignore_stdin_write_error()
3056 .succeeds()
3057 .no_output();
3058
3059 new_ucmd!()
3060 .args(&["-n", "+4"])
3061 .pipe_in(test_string)
3062 .ignore_stdin_write_error()
3063 .succeeds()
3064 .no_output();
3065
3066 new_ucmd!()
3067 .args(&["-n", "+999"])
3068 .pipe_in(test_string)
3069 .ignore_stdin_write_error()
3070 .succeeds()
3071 .no_output();
3072 }
3073
3074 #[test]
3075 fn test_pipe_when_negative_lines_option_given_no_newline_at_eof() {
3076 let test_string = "a\nb";
3077
3078 new_ucmd!()
3079 .args(&["-n", "0"])
3080 .pipe_in(test_string)
3081 .ignore_stdin_write_error()
3082 .succeeds()
3083 .no_output();
3084
3085 new_ucmd!()
3086 .args(&["-n", "1"])
3087 .pipe_in(test_string)
3088 .ignore_stdin_write_error()
3089 .succeeds()
3090 .stdout_only("b");
3091
3092 new_ucmd!()
3093 .args(&["-n", "2"])
3094 .pipe_in(test_string)
3095 .ignore_stdin_write_error()
3096 .succeeds()
3097 .stdout_only("a\nb");
3098 }
3099
3100 #[test]
3101 fn test_pipe_when_positive_lines_option_given_no_newline_at_eof() {
3102 let test_string = "a\nb";
3103
3104 new_ucmd!()
3105 .args(&["-n", "+0"])
3106 .pipe_in(test_string)
3107 .ignore_stdin_write_error()
3108 .succeeds()
3109 .stdout_only("a\nb");
3110
3111 new_ucmd!()
3112 .args(&["-n", "+1"])
3113 .pipe_in(test_string)
3114 .ignore_stdin_write_error()
3115 .succeeds()
3116 .stdout_only("a\nb");
3117
3118 new_ucmd!()
3119 .args(&["-n", "+2"])
3120 .pipe_in(test_string)
3121 .ignore_stdin_write_error()
3122 .succeeds()
3123 .stdout_only("b");
3124 }
3125
3126 #[test]
3127 fn test_pipe_when_lines_option_given_multibyte_utf8_characters() {
3128 // the test string consists of from left to right a 4-byte,3-byte,2-byte,1-byte utf-8 character
3129 let test_string = "š… \nā»\nʒ\na";
3130
3131 new_ucmd!()
3132 .args(&["-n", "+0"])
3133 .pipe_in(test_string)
3134 .ignore_stdin_write_error()
3135 .succeeds()
3136 .stdout_only(test_string);
3137
3138 new_ucmd!()
3139 .args(&["-n", "+2"])
3140 .pipe_in(test_string)
3141 .ignore_stdin_write_error()
3142 .succeeds()
3143 .stdout_only("ā»\nʒ\na");
3144
3145 new_ucmd!()
3146 .args(&["-n", "+3"])
3147 .pipe_in(test_string)
3148 .ignore_stdin_write_error()
3149 .succeeds()
3150 .stdout_only("ʒ\na");
3151
3152 new_ucmd!()
3153 .args(&["-n", "+4"])
3154 .pipe_in(test_string)
3155 .ignore_stdin_write_error()
3156 .succeeds()
3157 .stdout_only("a");
3158
3159 new_ucmd!()
3160 .args(&["-n", "+5"])
3161 .pipe_in(test_string)
3162 .ignore_stdin_write_error()
3163 .succeeds()
3164 .no_output();
3165
3166 new_ucmd!()
3167 .args(&["-n", "-4"])
3168 .pipe_in(test_string)
3169 .ignore_stdin_write_error()
3170 .succeeds()
3171 .stdout_only(test_string);
3172
3173 new_ucmd!()
3174 .args(&["-n", "-3"])
3175 .pipe_in(test_string)
3176 .ignore_stdin_write_error()
3177 .succeeds()
3178 .stdout_only("ā»\nʒ\na");
3179
3180 new_ucmd!()
3181 .args(&["-n", "-2"])
3182 .pipe_in(test_string)
3183 .ignore_stdin_write_error()
3184 .succeeds()
3185 .stdout_only("ʒ\na");
3186
3187 new_ucmd!()
3188 .args(&["-n", "-1"])
3189 .pipe_in(test_string)
3190 .ignore_stdin_write_error()
3191 .succeeds()
3192 .stdout_only("a");
3193
3194 new_ucmd!()
3195 .args(&["-n", "-0"])
3196 .pipe_in(test_string)
3197 .ignore_stdin_write_error()
3198 .succeeds()
3199 .no_output();
3200 }
3201
3202 #[test]
3203 fn test_pipe_when_lines_option_given_input_size_is_equal_to_buffer_size_no_newline_at_eof() {
3204 let total_lines = 1;
3205 let random_string = RandomizedString::generate_with_delimiter(
3206 Alphanumeric,
3207 b'\n',
3208 total_lines,
3209 false,
3210 CHUNK_BUFFER_SIZE,
3211 );
3212 let random_string = random_string.as_str();
3213 let lines = random_string.split_inclusive('\n');
3214
3215 let expected = lines.clone().skip(1).collect::<String>();
3216 new_ucmd!()
3217 .args(&["-n", "+2"])
3218 .pipe_in(random_string)
3219 .ignore_stdin_write_error()
3220 .succeeds()
3221 .stdout_only(expected);
3222
3223 let expected = lines.clone().skip(1).collect::<String>();
3224 new_ucmd!()
3225 .args(&["-n", "-1"])
3226 .pipe_in(random_string)
3227 .ignore_stdin_write_error()
3228 .succeeds()
3229 .stdout_only(expected);
3230 }
3231
3232 #[test]
3233 fn test_pipe_when_lines_option_given_input_size_is_equal_to_buffer_size() {
3234 let total_lines = 100;
3235 let random_string = RandomizedString::generate_with_delimiter(
3236 Alphanumeric,
3237 b'\n',
3238 total_lines,
3239 true,
3240 CHUNK_BUFFER_SIZE,
3241 );
3242 let random_string = random_string.as_str();
3243 let lines = random_string.split_inclusive('\n');
3244
3245 new_ucmd!()
3246 .args(&["-n", "+0"])
3247 .pipe_in(random_string)
3248 .ignore_stdin_write_error()
3249 .succeeds()
3250 .stdout_only(random_string);
3251
3252 let expected = lines.clone().skip(1).collect::<String>();
3253 new_ucmd!()
3254 .args(&["-n", "+2"])
3255 .pipe_in(random_string)
3256 .ignore_stdin_write_error()
3257 .succeeds()
3258 .stdout_only(expected);
3259
3260 new_ucmd!()
3261 .args(&["-n", "-0"])
3262 .pipe_in(random_string)
3263 .ignore_stdin_write_error()
3264 .succeeds()
3265 .no_output();
3266
3267 let expected = lines.clone().skip(total_lines - 1).collect::<String>();
3268 new_ucmd!()
3269 .args(&["-n", "-1"])
3270 .pipe_in(random_string)
3271 .ignore_stdin_write_error()
3272 .succeeds()
3273 .stdout_only(expected);
3274
3275 let expected = lines.clone().skip(1).collect::<String>();
3276 new_ucmd!()
3277 .args(&["-n", "-99"])
3278 .pipe_in(random_string)
3279 .ignore_stdin_write_error()
3280 .succeeds()
3281 .stdout_only(expected);
3282
3283 new_ucmd!()
3284 .args(&["-n", "-100"])
3285 .pipe_in(random_string)
3286 .ignore_stdin_write_error()
3287 .succeeds()
3288 .stdout_only(random_string);
3289 }
3290
3291 #[test]
3292 fn test_pipe_when_lines_option_given_input_size_is_one_byte_greater_than_buffer_size() {
3293 let total_lines = 100;
3294 let random_string = RandomizedString::generate_with_delimiter(
3295 Alphanumeric,
3296 b'\n',
3297 total_lines,
3298 true,
3299 CHUNK_BUFFER_SIZE + 1,
3300 );
3301 let random_string = random_string.as_str();
3302 let lines = random_string.split_inclusive('\n');
3303
3304 new_ucmd!()
3305 .args(&["-n", "+0"])
3306 .pipe_in(random_string)
3307 .ignore_stdin_write_error()
3308 .succeeds()
3309 .stdout_only(random_string);
3310
3311 let expected = lines.clone().skip(total_lines - 1).collect::<String>();
3312 new_ucmd!()
3313 .args(&["-n", "-1"])
3314 .pipe_in(random_string)
3315 .ignore_stdin_write_error()
3316 .succeeds()
3317 .stdout_only(expected);
3318
3319 let expected = lines.clone().skip(1).collect::<String>();
3320 new_ucmd!()
3321 .args(&["-n", "+2"])
3322 .pipe_in(random_string)
3323 .ignore_stdin_write_error()
3324 .succeeds()
3325 .stdout_only(expected);
3326
3327 let expected = lines.clone().skip(1).collect::<String>();
3328 new_ucmd!()
3329 .args(&["-n", "-99"])
3330 .pipe_in(random_string)
3331 .ignore_stdin_write_error()
3332 .succeeds()
3333 .stdout_only(expected);
3334 }
3335
3336 // FIXME: windows: this test failed with timeout in the CI. Running this test in
3337 // a Windows VirtualBox image produces no errors.
3338 #[test]
3339 #[cfg(not(windows))]
3340 fn test_pipe_when_lines_option_given_input_size_has_multiple_size_of_buffer_size() {
3341 let total_lines = 100;
3342 let random_string = RandomizedString::generate_with_delimiter(
3343 Alphanumeric,
3344 b'\n',
3345 total_lines,
3346 true,
3347 CHUNK_BUFFER_SIZE * 3 + 1,
3348 );
3349 let random_string = random_string.as_str();
3350 let lines = random_string.split_inclusive('\n');
3351
3352 new_ucmd!()
3353 .args(&["-n", "+0"])
3354 .pipe_in(random_string)
3355 .ignore_stdin_write_error()
3356 .succeeds()
3357 .stdout_only(random_string);
3358
3359 let expected = lines.clone().skip(1).collect::<String>();
3360 new_ucmd!()
3361 .args(&["-n", "+2"])
3362 .pipe_in(random_string)
3363 .ignore_stdin_write_error()
3364 .succeeds()
3365 .stdout_only(expected);
3366
3367 new_ucmd!()
3368 .args(&["-n", "-0"])
3369 .pipe_in(random_string)
3370 .ignore_stdin_write_error()
3371 .succeeds()
3372 .no_output();
3373
3374 let expected = lines.clone().skip(total_lines - 1).collect::<String>();
3375 new_ucmd!()
3376 .args(&["-n", "-1"])
3377 .pipe_in(random_string)
3378 .ignore_stdin_write_error()
3379 .succeeds()
3380 .stdout_only(expected);
3381
3382 let expected = lines.clone().skip(1).collect::<String>();
3383 new_ucmd!()
3384 .args(&["-n", "-99"])
3385 .pipe_in(random_string)
3386 .ignore_stdin_write_error()
3387 .succeeds()
3388 .stdout_only(expected);
3389
3390 new_ucmd!()
3391 .args(&["-n", "-100"])
3392 .pipe_in(random_string)
3393 .ignore_stdin_write_error()
3394 .succeeds()
3395 .stdout_only(random_string);
3396 }
3397
3398 #[test]
3399 fn test_pipe_when_bytes_option_value_is_higher_than_contained_bytes() {
3400 let test_string = "a\nb";
3401 new_ucmd!()
3402 .args(&["-c", "4"])
3403 .pipe_in(test_string)
3404 .ignore_stdin_write_error()
3405 .succeeds()
3406 .stdout_only(test_string);
3407
3408 new_ucmd!()
3409 .args(&["-c", "5"])
3410 .pipe_in(test_string)
3411 .ignore_stdin_write_error()
3412 .succeeds()
3413 .stdout_only(test_string);
3414
3415 new_ucmd!()
3416 .args(&["-c", "999"])
3417 .pipe_in(test_string)
3418 .ignore_stdin_write_error()
3419 .succeeds()
3420 .stdout_only(test_string);
3421
3422 new_ucmd!()
3423 .args(&["-c", "+4"])
3424 .pipe_in(test_string)
3425 .ignore_stdin_write_error()
3426 .succeeds()
3427 .no_output();
3428
3429 new_ucmd!()
3430 .args(&["-c", "+5"])
3431 .pipe_in(test_string)
3432 .ignore_stdin_write_error()
3433 .succeeds()
3434 .no_output();
3435
3436 new_ucmd!()
3437 .args(&["-c", "+999"])
3438 .pipe_in(test_string)
3439 .ignore_stdin_write_error()
3440 .succeeds()
3441 .no_output();
3442 }
3443
3444 #[test]
3445 fn test_pipe_when_bytes_option_given_multibyte_utf8_characters() {
3446 // the test string consists of from left to right a 4-byte,3-byte,2-byte,1-byte utf-8 character
3447 let test_string = "š… ā»Ę’a";
3448
3449 new_ucmd!()
3450 .args(&["-c", "+0"])
3451 .pipe_in(test_string)
3452 .ignore_stdin_write_error()
3453 .succeeds()
3454 .stdout_only(test_string);
3455
3456 new_ucmd!()
3457 .args(&["-c", "+2"])
3458 .pipe_in(test_string)
3459 .ignore_stdin_write_error()
3460 .succeeds()
3461 .stdout_only_bytes(&test_string.as_bytes()[1..]);
3462
3463 new_ucmd!()
3464 .args(&["-c", "+5"])
3465 .pipe_in(test_string)
3466 .ignore_stdin_write_error()
3467 .succeeds()
3468 .stdout_only("ā»Ę’a");
3469
3470 new_ucmd!()
3471 .args(&["-c", "+8"])
3472 .pipe_in(test_string)
3473 .ignore_stdin_write_error()
3474 .succeeds()
3475 .stdout_only("ʒa");
3476
3477 new_ucmd!()
3478 .args(&["-c", "+10"])
3479 .pipe_in(test_string)
3480 .ignore_stdin_write_error()
3481 .succeeds()
3482 .stdout_only("a");
3483
3484 new_ucmd!()
3485 .args(&["-c", "+11"])
3486 .pipe_in(test_string)
3487 .ignore_stdin_write_error()
3488 .succeeds()
3489 .no_output();
3490
3491 new_ucmd!()
3492 .args(&["-c", "-1"])
3493 .pipe_in(test_string)
3494 .ignore_stdin_write_error()
3495 .succeeds()
3496 .stdout_only("a");
3497
3498 new_ucmd!()
3499 .args(&["-c", "-2"])
3500 .pipe_in(test_string)
3501 .ignore_stdin_write_error()
3502 .succeeds()
3503 .stdout_only_bytes(&"ʒa".as_bytes()[1..]);
3504
3505 new_ucmd!()
3506 .args(&["-c", "-3"])
3507 .pipe_in(test_string)
3508 .ignore_stdin_write_error()
3509 .succeeds()
3510 .stdout_only("ʒa");
3511
3512 new_ucmd!()
3513 .args(&["-c", "-6"])
3514 .pipe_in(test_string)
3515 .ignore_stdin_write_error()
3516 .succeeds()
3517 .stdout_only("ā»Ę’a");
3518
3519 new_ucmd!()
3520 .args(&["-c", "-10"])
3521 .pipe_in(test_string)
3522 .ignore_stdin_write_error()
3523 .succeeds()
3524 .stdout_only(test_string);
3525 }
3526
3527 #[test]
3528 fn test_pipe_when_bytes_option_given_input_size_is_equal_to_buffer_size() {
3529 let random_string = RandomizedString::generate(AlphanumericNewline, CHUNK_BUFFER_SIZE);
3530 let random_string = random_string.as_str();
3531
3532 new_ucmd!()
3533 .args(&["-c", "+0"])
3534 .pipe_in(random_string)
3535 .ignore_stdin_write_error()
3536 .succeeds()
3537 .stdout_only(random_string);
3538
3539 let expected = &random_string.as_bytes()[1..];
3540 new_ucmd!()
3541 .args(&["-c", "+2"])
3542 .pipe_in(random_string)
3543 .ignore_stdin_write_error()
3544 .succeeds()
3545 .stdout_only_bytes(expected);
3546
3547 new_ucmd!()
3548 .args(&["-c", "-0"])
3549 .pipe_in(random_string)
3550 .ignore_stdin_write_error()
3551 .succeeds()
3552 .no_output();
3553
3554 let expected = &random_string.as_bytes()[1..];
3555 new_ucmd!()
3556 .args(&["-c", "-8191"])
3557 .pipe_in(random_string)
3558 .ignore_stdin_write_error()
3559 .succeeds()
3560 .stdout_only_bytes(expected);
3561
3562 new_ucmd!()
3563 .args(&["-c", "-8192"])
3564 .pipe_in(random_string)
3565 .ignore_stdin_write_error()
3566 .succeeds()
3567 .stdout_only_bytes(random_string);
3568
3569 new_ucmd!()
3570 .args(&["-c", "-8193"])
3571 .pipe_in(random_string)
3572 .ignore_stdin_write_error()
3573 .succeeds()
3574 .stdout_only_bytes(random_string);
3575
3576 let expected = &random_string.as_bytes()[CHUNK_BUFFER_SIZE - 1..];
3577 new_ucmd!()
3578 .args(&["-c", "-1"])
3579 .pipe_in(random_string)
3580 .ignore_stdin_write_error()
3581 .succeeds()
3582 .stdout_only_bytes(expected);
3583 }
3584
3585 #[test]
3586 fn test_pipe_when_bytes_option_given_input_size_is_one_byte_greater_than_buffer_size() {
3587 let random_string = RandomizedString::generate(AlphanumericNewline, CHUNK_BUFFER_SIZE + 1);
3588 let random_string = random_string.as_str();
3589
3590 new_ucmd!()
3591 .args(&["-c", "+0"])
3592 .pipe_in(random_string)
3593 .ignore_stdin_write_error()
3594 .succeeds()
3595 .stdout_only(random_string);
3596
3597 let expected = &random_string.as_bytes()[1..];
3598 new_ucmd!()
3599 .args(&["-c", "+2"])
3600 .pipe_in(random_string)
3601 .ignore_stdin_write_error()
3602 .succeeds()
3603 .stdout_only_bytes(expected);
3604
3605 new_ucmd!()
3606 .args(&["-c", "-0"])
3607 .pipe_in(random_string)
3608 .ignore_stdin_write_error()
3609 .succeeds()
3610 .no_output();
3611
3612 let expected = &random_string.as_bytes()[CHUNK_BUFFER_SIZE..];
3613 new_ucmd!()
3614 .args(&["-c", "-1"])
3615 .pipe_in(random_string)
3616 .ignore_stdin_write_error()
3617 .succeeds()
3618 .stdout_only_bytes(expected);
3619
3620 let expected = &random_string.as_bytes()[1..];
3621 new_ucmd!()
3622 .args(&["-c", "-8192"])
3623 .pipe_in(random_string)
3624 .ignore_stdin_write_error()
3625 .succeeds()
3626 .stdout_only_bytes(expected);
3627
3628 new_ucmd!()
3629 .args(&["-c", "-8193"])
3630 .pipe_in(random_string)
3631 .ignore_stdin_write_error()
3632 .succeeds()
3633 .stdout_only(random_string);
3634 }
3635
3636 // FIXME: windows: this test failed with timeout in the CI. Running this test in
3637 // a Windows VirtualBox image produces no errors.
3638 #[test]
3639 #[cfg(not(windows))]
3640 fn test_pipe_when_bytes_option_given_input_size_has_multiple_size_of_buffer_size() {
3641 let random_string = RandomizedString::generate(AlphanumericNewline, CHUNK_BUFFER_SIZE * 3);
3642 let random_string = random_string.as_str();
3643
3644 new_ucmd!()
3645 .args(&["-c", "+0"])
3646 .pipe_in(random_string)
3647 .ignore_stdin_write_error()
3648 .succeeds()
3649 .stdout_only(random_string);
3650
3651 new_ucmd!()
3652 .args(&["-c", "-0"])
3653 .pipe_in(random_string)
3654 .ignore_stdin_write_error()
3655 .succeeds()
3656 .no_output();
3657
3658 let expected = &random_string.as_bytes()[8192..];
3659 new_ucmd!()
3660 .args(&["-c", "+8193"])
3661 .pipe_in(random_string)
3662 .ignore_stdin_write_error()
3663 .succeeds()
3664 .stdout_only_bytes(expected);
3665
3666 let expected = &random_string.as_bytes()[8193..];
3667 new_ucmd!()
3668 .args(&["-c", "+8194"])
3669 .pipe_in(random_string)
3670 .ignore_stdin_write_error()
3671 .succeeds()
3672 .stdout_only_bytes(expected);
3673
3674 let expected = &random_string.as_bytes()[16384..];
3675 new_ucmd!()
3676 .args(&["-c", "+16385"])
3677 .pipe_in(random_string)
3678 .ignore_stdin_write_error()
3679 .succeeds()
3680 .stdout_only_bytes(expected);
3681
3682 let expected = &random_string.as_bytes()[16385..];
3683 new_ucmd!()
3684 .args(&["-c", "+16386"])
3685 .pipe_in(random_string)
3686 .ignore_stdin_write_error()
3687 .succeeds()
3688 .stdout_only_bytes(expected);
3689
3690 let expected = &random_string.as_bytes()[16384..];
3691 new_ucmd!()
3692 .args(&["-c", "-8192"])
3693 .pipe_in(random_string)
3694 .ignore_stdin_write_error()
3695 .succeeds()
3696 .stdout_only_bytes(expected);
3697
3698 let expected = &random_string.as_bytes()[16383..];
3699 new_ucmd!()
3700 .args(&["-c", "-8193"])
3701 .pipe_in(random_string)
3702 .ignore_stdin_write_error()
3703 .succeeds()
3704 .stdout_only_bytes(expected);
3705
3706 let expected = &random_string.as_bytes()[8192..];
3707 new_ucmd!()
3708 .args(&["-c", "-16384"])
3709 .pipe_in(random_string)
3710 .ignore_stdin_write_error()
3711 .succeeds()
3712 .stdout_only_bytes(expected);
3713
3714 let expected = &random_string.as_bytes()[8191..];
3715 new_ucmd!()
3716 .args(&["-c", "-16385"])
3717 .pipe_in(random_string)
3718 .ignore_stdin_write_error()
3719 .succeeds()
3720 .stdout_only_bytes(expected);
3721
3722 new_ucmd!()
3723 .args(&["-c", "-24576"])
3724 .pipe_in(random_string)
3725 .ignore_stdin_write_error()
3726 .succeeds()
3727 .stdout_only(random_string);
3728 }
3729
3730 #[test]
3731 fn test_seek_bytes_backward_outside_file() {
3732 new_ucmd!()
3733 .arg("-c")
3734 .arg("100")
3735 .arg(FOOBAR_TXT)
3736 .succeeds()
3737 .stdout_is_fixture(FOOBAR_TXT);
3738 }
3739
3740 #[test]
3741 fn test_seek_bytes_forward_outside_file() {
3742 new_ucmd!()
3743 .arg("-c")
3744 .arg("+100")
3745 .arg(FOOBAR_TXT)
3746 .succeeds()
3747 .no_output();
3748 }
3749
3750 // Some basic tests for ---presume-input-pipe. These tests build upon the
3751 // debug_assert in bounded tail to detect that we're using the bounded_tail in
3752 // case the option is given on command line.
3753 #[cfg(all(not(target_os = "android"), not(windows)))] // FIXME:
3754 #[test]
3755 fn test_args_when_presume_input_pipe_given_input_is_pipe() {
3756 let random_string = RandomizedString::generate(AlphanumericNewline, 1000);
3757 let random_string = random_string.as_str();
3758
3759 new_ucmd!()
3760 .args(&["---presume-input-pipe", "-c", "-0"])
3761 .pipe_in(random_string)
3762 .ignore_stdin_write_error()
3763 .succeeds()
3764 .no_output();
3765
3766 new_ucmd!()
3767 .args(&["---presume-input-pipe", "-c", "+0"])
3768 .pipe_in(random_string)
3769 .ignore_stdin_write_error()
3770 .succeeds()
3771 .stdout_only(random_string);
3772
3773 new_ucmd!()
3774 .args(&["---presume-input-pipe", "-n", "-0"])
3775 .pipe_in(random_string)
3776 .ignore_stdin_write_error()
3777 .succeeds()
3778 .no_output();
3779
3780 new_ucmd!()
3781 .args(&["---presume-input-pipe", "-n", "+0"])
3782 .pipe_in(random_string)
3783 .ignore_stdin_write_error()
3784 .succeeds()
3785 .stdout_only(random_string);
3786 }
3787
3788 #[test]
3789 fn test_args_when_presume_input_pipe_given_input_is_file() {
3790 let random_string = RandomizedString::generate(AlphanumericNewline, 1000);
3791 let random_string = random_string.as_str();
3792
3793 let ts = TestScenario::new(util_name!());
3794 let at = &ts.fixtures;
3795 at.write("data", random_string);
3796
3797 ts.ucmd()
3798 .args(&["---presume-input-pipe", "-c", "-0", "data"])
3799 .succeeds()
3800 .no_output();
3801
3802 ts.ucmd()
3803 .args(&["---presume-input-pipe", "-c", "+0", "data"])
3804 .succeeds()
3805 .stdout_only(random_string);
3806
3807 ts.ucmd()
3808 .args(&["---presume-input-pipe", "-n", "-0", "data"])
3809 .succeeds()
3810 .no_output();
3811
3812 ts.ucmd()
3813 .args(&["---presume-input-pipe", "-n", "+0", "data"])
3814 .succeeds()
3815 .stdout_only(random_string);
3816 }
3817
3818 #[test]
3819 #[ignore = "disabled until fixed"]
3820 // FIXME: currently missing in the error message is the last line >>tail: no files remaining<<
3821 fn test_when_follow_retry_given_redirected_stdin_from_directory_then_correct_error_message() {
3822 let ts = TestScenario::new(util_name!());
3823 let at = &ts.fixtures;
3824 at.mkdir("dir");
3825
3826 let expected = "tail: warning: --retry only effective for the initial open\n\
3827 tail: error reading 'standard input': Is a directory\n\
3828 tail: 'standard input': cannot follow end of this type of file\n\
3829 tail: no files remaining\n";
3830 ts.ucmd()
3831 .set_stdin(File::open(at.plus("dir")).unwrap())
3832 .args(&["-f", "--retry"])
3833 .fails_with_code(1)
3834 .stderr_only(expected);
3835 }
3836
3837 #[test]
3838 fn test_when_argument_file_is_a_directory() {
3839 let ts = TestScenario::new(util_name!());
3840 let at = &ts.fixtures;
3841 at.mkdir("dir");
3842
3843 let expected = "tail: error reading 'dir': Is a directory\n";
3844 ts.ucmd()
3845 .arg("dir")
3846 .fails_with_code(1)
3847 .stderr_only(expected);
3848 }
3849
3850 // TODO: make this work on windows
3851 #[test]
3852 #[cfg(unix)]
3853 fn test_when_argument_file_is_a_symlink() {
3854 let ts = TestScenario::new(util_name!());
3855 let at = &ts.fixtures;
3856
3857 let mut file = at.make_file("target");
3858
3859 at.relative_symlink_file("target", "link");
3860
3861 ts.ucmd().args(&["-c", "+0", "link"]).succeeds().no_output();
3862
3863 let random_string = RandomizedString::generate(AlphanumericNewline, 100);
3864 let result = file.write_all(random_string.as_bytes());
3865 assert!(result.is_ok());
3866
3867 ts.ucmd()
3868 .args(&["-c", "+0", "link"])
3869 .succeeds()
3870 .stdout_only(random_string);
3871 }
3872
3873 // TODO: make this work on windows
3874 #[test]
3875 #[cfg(unix)]
3876 fn test_when_argument_file_is_a_symlink_to_directory_then_error() {
3877 let ts = TestScenario::new(util_name!());
3878 let at = &ts.fixtures;
3879
3880 at.mkdir("dir");
3881 at.relative_symlink_file("dir", "dir_link");
3882
3883 ts.ucmd()
3884 .arg("dir_link")
3885 .fails_with_code(1)
3886 .stderr_only("tail: error reading 'dir_link': Is a directory\n");
3887 }
3888
3889 // TODO: make this work on windows
3890 #[test]
3891 #[cfg(unix)]
3892 #[ignore = "disabled until fixed"]
3893 fn test_when_argument_file_is_a_faulty_symlink_then_error() {
3894 let ts = TestScenario::new(util_name!());
3895 let at = &ts.fixtures;
3896
3897 at.symlink_file("self", "self");
3898
3899 #[cfg(all(not(target_env = "musl"), not(target_os = "android")))]
3900 let expected = "tail: cannot open 'self' for reading: Too many levels of symbolic links";
3901 #[cfg(all(not(target_env = "musl"), target_os = "android"))]
3902 let expected = "tail: cannot open 'self' for reading: Too many symbolic links encountered";
3903 #[cfg(all(target_env = "musl", not(target_os = "android")))]
3904 let expected = "tail: cannot open 'self' for reading: Symbolic link loop";
3905
3906 ts.ucmd()
3907 .arg("self")
3908 .fails_with_code(1)
3909 .stderr_only(expected);
3910
3911 at.symlink_file("missing", "broken");
3912
3913 let expected = "tail: cannot open 'broken' for reading: No such file or directory";
3914 ts.ucmd()
3915 .arg("broken")
3916 .fails_with_code(1)
3917 .stderr_only(expected);
3918 }
3919
3920 #[test]
3921 #[cfg(unix)]
3922 #[ignore = "disabled until fixed"]
3923 fn test_when_argument_file_is_non_existent_unix_socket_address_then_error() {
3924 use std::os::unix::net;
3925
3926 let ts = TestScenario::new(util_name!());
3927 let at = &ts.fixtures;
3928
3929 let socket = "socket";
3930
3931 // We only bind to create the socket file but do not listen
3932 let result = net::UnixListener::bind(at.plus(socket));
3933 assert!(result.is_ok());
3934
3935 #[cfg(not(any(target_vendor = "apple", target_os = "freebsd")))]
3936 let expected_stderr =
3937 format!("tail: cannot open '{socket}' for reading: No such device or address\n");
3938 #[cfg(target_os = "freebsd")]
3939 let expected_stderr =
3940 format!("tail: cannot open '{socket}' for reading: Operation not supported\n");
3941 #[cfg(target_vendor = "apple")]
3942 let expected_stderr =
3943 format!("tail: cannot open '{socket}' for reading: Operation not supported on socket\n");
3944
3945 ts.ucmd()
3946 .arg(socket)
3947 .fails_with_code(1)
3948 .stderr_only(&expected_stderr);
3949
3950 let path = "file";
3951 let mut file = at.make_file(path);
3952
3953 let random_string = RandomizedString::generate(AlphanumericNewline, 100);
3954 let result = file.write_all(random_string.as_bytes());
3955 assert!(result.is_ok());
3956
3957 let expected_stdout = [format!("==> {path} <=="), random_string].join("\n");
3958 ts.ucmd()
3959 .args(&["-c", "+0", path, socket])
3960 .fails_with_code(1)
3961 .stdout_is(&expected_stdout)
3962 .stderr_is(&expected_stderr);
3963
3964 // tail does not stop processing files when having encountered a "No such
3965 // device or address" error.
3966 ts.ucmd()
3967 .args(&["-c", "+0", socket, path])
3968 .fails()
3969 .stdout_is(&expected_stdout)
3970 .stderr_is(&expected_stderr);
3971 }
3972
3973 #[test]
3974 #[ignore = "disabled until fixed"]
3975 fn test_when_argument_files_are_simple_combinations_of_stdin_and_regular_file() {
3976 let scene = TestScenario::new(util_name!());
3977 let at = &scene.fixtures;
3978
3979 at.touch("empty");
3980 at.write("data", "file data");
3981 at.write("fifo", "fifo data");
3982
3983 let expected = "==> standard input <==\n\
3984 fifo data\n\
3985 ==> empty <==\n";
3986 scene
3987 .ucmd()
3988 .args(&["-c", "+0", "-", "empty"])
3989 .set_stdin(File::open(at.plus("fifo")).unwrap())
3990 .succeeds()
3991 .stdout_only(expected);
3992
3993 let expected = "==> standard input <==\n\
3994 \n\
3995 ==> empty <==\n";
3996 scene
3997 .ucmd()
3998 .args(&["-c", "+0", "-", "empty"])
3999 .pipe_in("")
4000 .succeeds()
4001 .stdout_only(expected);
4002
4003 let expected = "==> empty <==\n\
4004 \n\
4005 ==> standard input <==\n";
4006 scene
4007 .ucmd()
4008 .args(&["-c", "+0", "empty", "-"])
4009 .pipe_in("")
4010 .succeeds()
4011 .stdout_only(expected);
4012
4013 let expected = "==> empty <==\n\
4014 \n\
4015 ==> standard input <==\n\
4016 fifo data";
4017 scene
4018 .ucmd()
4019 .args(&["-c", "+0", "empty", "-"])
4020 .set_stdin(File::open(at.plus("fifo")).unwrap())
4021 .succeeds()
4022 .stdout_only(expected);
4023
4024 let expected = "==> standard input <==\n\
4025 pipe data\n\
4026 ==> data <==\n\
4027 file data";
4028 scene
4029 .ucmd()
4030 .args(&["-c", "+0", "-", "data"])
4031 .pipe_in("pipe data")
4032 .succeeds()
4033 .stdout_only(expected);
4034
4035 let expected = "==> data <==\n\
4036 file data\n\
4037 ==> standard input <==\n\
4038 pipe data";
4039 scene
4040 .ucmd()
4041 .args(&["-c", "+0", "data", "-"])
4042 .pipe_in("pipe data")
4043 .succeeds()
4044 .stdout_only(expected);
4045
4046 let expected = "==> standard input <==\n\
4047 pipe data\n\
4048 ==> standard input <==\n";
4049 scene
4050 .ucmd()
4051 .args(&["-c", "+0", "-", "-"])
4052 .pipe_in("pipe data")
4053 .succeeds()
4054 .stdout_only(expected);
4055
4056 let expected = "==> standard input <==\n\
4057 fifo data\n\
4058 ==> standard input <==\n";
4059 scene
4060 .ucmd()
4061 .args(&["-c", "+0", "-", "-"])
4062 .set_stdin(File::open(at.plus("fifo")).unwrap())
4063 .succeeds()
4064 .stdout_only(expected);
4065 }
4066
4067 #[test]
4068 #[ignore = "disabled until fixed"]
4069 fn test_when_argument_files_are_triple_combinations_of_fifo_pipe_and_regular_file() {
4070 let scene = TestScenario::new(util_name!());
4071 let at = &scene.fixtures;
4072
4073 at.touch("empty");
4074 at.write("data", "file data");
4075 at.write("fifo", "fifo data");
4076
4077 let expected = "==> standard input <==\n\
4078 \n\
4079 ==> empty <==\n\
4080 \n\
4081 ==> standard input <==\n";
4082
4083 scene
4084 .ucmd()
4085 .args(&["-c", "+0", "-", "empty", "-"])
4086 .set_stdin(File::open(at.plus("empty")).unwrap())
4087 .succeeds()
4088 .stdout_only(expected);
4089
4090 let expected = "==> standard input <==\n\
4091 \n\
4092 ==> empty <==\n\
4093 \n\
4094 ==> standard input <==\n";
4095 scene
4096 .ucmd()
4097 .args(&["-c", "+0", "-", "empty", "-"])
4098 .pipe_in("")
4099 .stderr_to_stdout()
4100 .succeeds()
4101 .stdout_only(expected);
4102
4103 let expected = "==> standard input <==\n\
4104 pipe data\n\
4105 ==> data <==\n\
4106 file data\n\
4107 ==> standard input <==\n";
4108 scene
4109 .ucmd()
4110 .args(&["-c", "+0", "-", "data", "-"])
4111 .pipe_in("pipe data")
4112 .succeeds()
4113 .stdout_only(expected);
4114
4115 // Correct behavior in a sh shell is to remember the file pointer for the fifo, so we don't
4116 // print the fifo twice. This matches the behavior, if only the pipe is present without fifo
4117 // (See test above). Note that for example a zsh shell prints the pipe data and has therefore
4118 // different output from the sh shell (or cmd shell on windows).
4119
4120 // windows: tail returns with success although there is an error message present (on some
4121 // windows systems). This error message comes from `echo` (the line ending `\r\n` indicates that
4122 // too) which cannot write to the pipe because tail finished before echo was able to write to
4123 // the pipe. Seems that windows `cmd` (like posix shells) ignores pipes when a fifo is present.
4124 // This is actually the wished behavior and the test therefore succeeds.
4125 #[cfg(windows)]
4126 let expected = "==> standard input <==\n\
4127 fifo data\n\
4128 ==> data <==\n\
4129 file data\n\
4130 ==> standard input <==\n\
4131 (The process tried to write to a nonexistent pipe.\r\n)?";
4132 #[cfg(unix)]
4133 let expected = "==> standard input <==\n\
4134 fifo data\n\
4135 ==> data <==\n\
4136 file data\n\
4137 ==> standard input <==\n";
4138
4139 #[cfg(windows)]
4140 let cmd = ["cmd", "/C"];
4141 #[cfg(unix)]
4142 let cmd = ["sh", "-c"];
4143
4144 scene
4145 .cmd(cmd[0])
4146 .arg(cmd[1])
4147 .arg(format!(
4148 "echo pipe data | {} tail -c +0 - data - < fifo",
4149 scene.bin_path.display(),
4150 ))
4151 .succeeds()
4152 .stdout_only(expected);
4153
4154 let expected = "==> standard input <==\n\
4155 fifo data\n\
4156 ==> data <==\n\
4157 file data\n\
4158 ==> standard input <==\n";
4159 scene
4160 .ucmd()
4161 .args(&["-c", "+0", "-", "data", "-"])
4162 .set_stdin(File::open(at.plus("fifo")).unwrap())
4163 .succeeds()
4164 .stdout_only(expected);
4165 }
4166
4167 // Bug description: The content of a file is not printed to stdout if the output data does not
4168 // contain newlines and --follow was given as arguments.
4169 //
4170 // This test is only formal on linux, since we currently do not detect this kind of error within the
4171 // test system. However, this behavior shows up on the command line and, at the time of writing this
4172 // description, with this test on macos and windows.
4173 #[test]
4174 #[ignore = "disabled until fixed"]
4175 fn test_when_follow_retry_then_initial_print_of_file_is_written_to_stdout() {
4176 let scene = TestScenario::new(util_name!());
4177 let at = &scene.fixtures;
4178
4179 let expected_stdout = "file data";
4180 at.write("data", expected_stdout);
4181
4182 let mut child = scene
4183 .ucmd()
4184 .args(&["--follow=name", "--retry", "data"])
4185 .run_no_wait();
4186
4187 child
4188 .delay(1500)
4189 .kill()
4190 .make_assertion()
4191 .with_current_output()
4192 .stdout_only(expected_stdout);
4193 }
4194
4195 // TODO: Add test for the warning `--pid=PID is not supported on this system`
4196 #[test]
4197 fn test_args_when_settings_check_warnings_then_shows_warnings() {
4198 let scene = TestScenario::new(util_name!());
4199 let at = &scene.fixtures;
4200
4201 let file_data = "file data\n";
4202 at.write("data", file_data);
4203
4204 let expected_stdout = format!(
4205 "tail: warning: --retry ignored; --retry is useful only when following\n\
4206 {file_data}"
4207 );
4208 scene
4209 .ucmd()
4210 .args(&["--retry", "data"])
4211 .stderr_to_stdout()
4212 .succeeds()
4213 .stdout_only(expected_stdout);
4214
4215 let expected_stdout = format!(
4216 "tail: warning: PID ignored; --pid=PID is useful only when following\n\
4217 {file_data}"
4218 );
4219 scene
4220 .ucmd()
4221 .args(&["--pid=0", "data"])
4222 .stderr_to_stdout()
4223 .succeeds()
4224 .stdout_only(expected_stdout);
4225
4226 let expected_stdout = format!(
4227 "tail: warning: --retry ignored; --retry is useful only when following\n\
4228 tail: warning: PID ignored; --pid=PID is useful only when following\n\
4229 {file_data}"
4230 );
4231 scene
4232 .ucmd()
4233 .args(&["--pid=1000", "--retry", "data"])
4234 .stderr_to_stdout()
4235 .succeeds()
4236 .stdout_only(&expected_stdout);
4237 scene
4238 .ucmd()
4239 .args(&["--pid=1000", "--pid=1000", "--retry", "data"])
4240 .stderr_to_stdout()
4241 .succeeds()
4242 .stdout_only(expected_stdout);
4243 }
4244
4245 #[test]
4246 fn test_args_when_settings_check_warnings_follow_retry() {
4247 let scene = TestScenario::new(util_name!());
4248 let file_data = "file data\n";
4249 scene.fixtures.write("data", file_data);
4250
4251 if std::env::var("UUTESTS_WASM_RUNNER").is_ok() {
4252 scene
4253 .ucmd()
4254 .args(&["--follow=descriptor", "--retry", "data"])
4255 .stderr_to_stdout()
4256 .fails_with_code(1)
4257 .stdout_only(format!(
4258 "tail: warning: --retry only effective for the initial open\n\
4259 {file_data}\
4260 tail: follow mode is not supported on this platform\n"
4261 ));
4262 return;
4263 }
4264
4265 let expected_stdout = format!(
4266 "tail: warning: --retry only effective for the initial open\n\
4267 {file_data}"
4268 );
4269 let mut child = scene
4270 .ucmd()
4271 .args(&["--follow=descriptor", "--retry", "data"])
4272 .stderr_to_stdout()
4273 .run_no_wait();
4274
4275 child
4276 .delay(500)
4277 .kill()
4278 .make_assertion()
4279 .with_current_output()
4280 .stdout_only(expected_stdout);
4281 }
4282
4283 /// TODO: Write similar tests for windows
4284 #[test]
4285 #[cfg(target_os = "linux")]
4286 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
4287 fn test_args_when_settings_check_warnings_follow_indefinitely_then_warning() {
4288 let scene = TestScenario::new(util_name!());
4289
4290 let file_data = "file data\n";
4291 scene.fixtures.write("data", file_data);
4292
4293 let expected_stdout = "==> standard input <==\n";
4294 let expected_stderr = "tail: warning: following standard input indefinitely is ineffective\n";
4295
4296 // `tail -f - data` (without any redirect) would also print this warning in a terminal but we're
4297 // not attached to a `tty` in the ci, so it's not possible to setup a test case for this
4298 // particular usage. However, setting stdin to a `tty` behaves equivalently and we're faking an
4299 // attached `tty` that way.
4300
4301 // testing here that the warning is printed to stderr
4302 // tail -f - data < /dev/ptmx
4303 let mut child = scene
4304 .ucmd()
4305 .args(&["--follow=descriptor", "-", "data"])
4306 .set_stdin(File::open(text::DEV_PTMX).unwrap())
4307 .run_no_wait();
4308
4309 child.make_assertion_with_delay(500).is_alive();
4310 child
4311 .kill()
4312 .make_assertion()
4313 .with_current_output()
4314 .stderr_is(expected_stderr)
4315 .stdout_is(expected_stdout);
4316
4317 let expected_stdout = "tail: warning: following standard input indefinitely is ineffective\n\
4318 ==> standard input <==\n";
4319 // same like above but this time the order of the output matters and we're redirecting stderr to
4320 // stdout
4321 // tail -f - data < /dev/ptmx
4322 let mut child = scene
4323 .ucmd()
4324 .args(&["--follow=descriptor", "-", "data"])
4325 .set_stdin(File::open(text::DEV_PTMX).unwrap())
4326 .stderr_to_stdout()
4327 .run_no_wait();
4328
4329 child.make_assertion_with_delay(500).is_alive();
4330 child
4331 .kill()
4332 .make_assertion()
4333 .with_current_output()
4334 .stdout_only(expected_stdout);
4335
4336 let expected_stdout = format!(
4337 "tail: warning: following standard input indefinitely is ineffective\n\
4338 ==> data <==\n\
4339 {file_data}\n\
4340 ==> standard input <==\n"
4341 );
4342 // tail -f data - < /dev/ptmx
4343 let mut child = scene
4344 .ucmd()
4345 .args(&["--follow=descriptor", "data", "-"])
4346 .set_stdin(File::open(text::DEV_PTMX).unwrap())
4347 .stderr_to_stdout()
4348 .run_no_wait();
4349
4350 child.make_assertion_with_delay(500).is_alive();
4351 child
4352 .kill()
4353 .make_assertion()
4354 .with_current_output()
4355 .stdout_only(expected_stdout);
4356
4357 let expected_stdout = "tail: warning: following standard input indefinitely is ineffective\n\
4358 ==> standard input <==\n";
4359 // tail -f - - < /dev/ptmx
4360 let mut child = scene
4361 .ucmd()
4362 .args(&["--follow=descriptor", "-", "-"])
4363 .set_stdin(File::open(text::DEV_PTMX).unwrap())
4364 .stderr_to_stdout()
4365 .run_no_wait();
4366
4367 child.make_assertion_with_delay(500).is_alive();
4368 child
4369 .kill()
4370 .make_assertion()
4371 .with_current_output()
4372 .stdout_only(expected_stdout);
4373
4374 let expected_stdout = "tail: warning: following standard input indefinitely is ineffective\n\
4375 ==> standard input <==\n";
4376 // tail -f - - data < /dev/ptmx
4377 let mut child = scene
4378 .ucmd()
4379 .args(&["--follow=descriptor", "-", "-", "data"])
4380 .set_stdin(File::open(text::DEV_PTMX).unwrap())
4381 .stderr_to_stdout()
4382 .run_no_wait();
4383
4384 child.make_assertion_with_delay(500).is_alive();
4385 child
4386 .kill()
4387 .make_assertion()
4388 .with_current_output()
4389 .stdout_only(expected_stdout);
4390
4391 let expected_stdout = "tail: warning: following standard input indefinitely is ineffective\n\
4392 ==> standard input <==\n";
4393 // tail --pid=100000 -f - data < /dev/ptmx
4394 let mut child = scene
4395 .ucmd()
4396 .args(&["--follow=descriptor", "--pid=100000", "-", "data"])
4397 .set_stdin(File::open(text::DEV_PTMX).unwrap())
4398 .stderr_to_stdout()
4399 .run_no_wait();
4400
4401 child.make_assertion_with_delay(500).is_alive();
4402 child
4403 .kill()
4404 .make_assertion()
4405 .with_current_output()
4406 .stdout_only(expected_stdout);
4407 }
4408
4409 #[test]
4410 #[cfg(unix)]
4411 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
4412 fn test_args_when_settings_check_warnings_follow_indefinitely_then_no_warning() {
4413 let scene = TestScenario::new(util_name!());
4414 let at = &scene.fixtures;
4415
4416 #[cfg(target_vendor = "apple")]
4417 let delay = 1000;
4418 #[cfg(not(target_vendor = "apple"))]
4419 let delay = 500;
4420
4421 let file_data = "file data\n";
4422 let fifo_data = "fifo data\n";
4423 let fifo_name = "fifo";
4424 let file_name = "data";
4425 at.write(file_name, file_data);
4426 at.write(fifo_name, fifo_data);
4427
4428 let pipe_data = "pipe data";
4429 let expected_stdout = format!(
4430 "==> standard input <==\n\
4431 {pipe_data}\n\
4432 ==> {file_name} <==\n\
4433 {file_data}"
4434 );
4435 let mut child = scene
4436 .ucmd()
4437 .args(&["--follow=descriptor", "-", file_name])
4438 .pipe_in(pipe_data)
4439 .stderr_to_stdout()
4440 .run_no_wait();
4441
4442 child.make_assertion_with_delay(delay).is_alive();
4443 child
4444 .kill()
4445 .make_assertion_with_delay(delay)
4446 .with_current_output()
4447 .stdout_only(expected_stdout);
4448
4449 // Test with regular file instead of /dev/tty
4450 // Fails currently on macos with
4451 // Diff < left / right > :
4452 // <tail: cannot open 'standard input' for reading: No such file or directory
4453 // >==> standard input <==
4454 // >fifo data
4455 // >
4456 // ==> data <==
4457 // file data
4458 #[cfg(not(target_vendor = "apple"))]
4459 {
4460 let expected_stdout = format!(
4461 "==> standard input <==\n\
4462 {fifo_data}\n\
4463 ==> {file_name} <==\n\
4464 {file_data}"
4465 );
4466 let mut child = scene
4467 .ucmd()
4468 .args(&["--follow=descriptor", "-", file_name])
4469 .set_stdin(File::open(at.plus(fifo_name)).unwrap())
4470 .stderr_to_stdout()
4471 .run_no_wait();
4472
4473 child.make_assertion_with_delay(delay).is_alive();
4474 child
4475 .kill()
4476 .make_assertion_with_delay(delay)
4477 .with_current_output()
4478 .stdout_only(expected_stdout);
4479
4480 let expected_stdout = format!(
4481 "==> standard input <==\n\
4482 {fifo_data}\n\
4483 ==> {file_name} <==\n\
4484 {file_data}"
4485 );
4486 let mut child = scene
4487 .ucmd()
4488 .args(&["--follow=descriptor", "--pid=0", "-", file_name])
4489 .set_stdin(File::open(at.plus(fifo_name)).unwrap())
4490 .stderr_to_stdout()
4491 .run_no_wait();
4492
4493 child.make_assertion_with_delay(delay).is_alive();
4494 child
4495 .kill()
4496 .make_assertion_with_delay(delay)
4497 .with_current_output()
4498 .stdout_only(expected_stdout);
4499 }
4500 }
4501
4502 /// The expected test outputs come from gnu's tail.
4503 #[test]
4504 #[ignore = "disabled until fixed"]
4505 fn test_follow_when_files_are_pointing_to_same_relative_file_and_data_is_appended() {
4506 let scene = TestScenario::new(util_name!());
4507 let at = &scene.fixtures;
4508
4509 let file_data = "file data";
4510 let relative_path_name = "data";
4511
4512 at.write(relative_path_name, file_data);
4513 let absolute_path = at.plus("data").canonicalize().unwrap();
4514
4515 // run with relative path first and then the absolute path
4516 let mut child = scene
4517 .ucmd()
4518 .args(&[
4519 "--follow=name",
4520 relative_path_name,
4521 absolute_path.to_str().unwrap(),
4522 ])
4523 .run_no_wait();
4524
4525 let more_data = "more data";
4526 child.delay(500);
4527
4528 at.append(relative_path_name, more_data);
4529
4530 let expected_stdout = format!(
4531 "==> {0} <==\n\
4532 {1}\n\
4533 ==> {2} <==\n\
4534 {1}\n\
4535 ==> {0} <==\n\
4536 {3}",
4537 relative_path_name,
4538 file_data,
4539 absolute_path.to_str().unwrap(),
4540 more_data
4541 );
4542
4543 child
4544 .make_assertion_with_delay(DEFAULT_SLEEP_INTERVAL_MILLIS)
4545 .is_alive();
4546 child
4547 .kill()
4548 .make_assertion()
4549 .with_current_output()
4550 .stderr_only(expected_stdout);
4551
4552 // run with absolute path first and then the relative path
4553 at.write(relative_path_name, file_data);
4554 let mut child = scene
4555 .ucmd()
4556 .args(&[
4557 "--follow=name",
4558 absolute_path.to_str().unwrap(),
4559 relative_path_name,
4560 ])
4561 .run_no_wait();
4562
4563 child.delay(500);
4564 let more_data = "more data";
4565 at.append(relative_path_name, more_data);
4566
4567 let expected_stdout = format!(
4568 "==> {0} <==\n\
4569 {1}\n\
4570 ==> {2} <==\n\
4571 {1}\n\
4572 ==> {0} <==\n\
4573 {3}",
4574 absolute_path.to_str().unwrap(),
4575 file_data,
4576 relative_path_name,
4577 more_data
4578 );
4579
4580 child
4581 .make_assertion_with_delay(DEFAULT_SLEEP_INTERVAL_MILLIS)
4582 .is_alive();
4583 child
4584 .kill()
4585 .make_assertion()
4586 .with_current_output()
4587 .stdout_only(expected_stdout);
4588 }
4589
4590 /// The expected test outputs come from gnu's tail.
4591 #[test]
4592 #[ignore = "disabled until fixed"]
4593 fn test_follow_when_files_are_pointing_to_same_relative_file_and_file_is_truncated() {
4594 let scene = TestScenario::new(util_name!());
4595 let at = &scene.fixtures;
4596
4597 let file_data = "file data";
4598 let relative_path_name = "data";
4599
4600 at.write(relative_path_name, file_data);
4601 let absolute_path = at.plus("data").canonicalize().unwrap();
4602
4603 let mut child = scene
4604 .ucmd()
4605 .args(&[
4606 "--follow=descriptor",
4607 "--max-unchanged-stats=1",
4608 "--sleep-interval=0.1",
4609 relative_path_name,
4610 absolute_path.to_str().unwrap(),
4611 ])
4612 .stderr_to_stdout()
4613 .run_no_wait();
4614
4615 child.delay(500);
4616 let less_data = "less";
4617 at.write(relative_path_name, "less");
4618
4619 let expected_stdout = format!(
4620 "==> {0} <==\n\
4621 {1}\n\
4622 ==> {2} <==\n\
4623 {1}{4}: {0}: file truncated\n\
4624 \n\
4625 ==> {0} <==\n\
4626 {3}",
4627 relative_path_name, // 0
4628 file_data, // 1
4629 absolute_path.to_str().unwrap(), // 2
4630 less_data, // 3
4631 scene.util_name // 4
4632 );
4633
4634 child.make_assertion_with_delay(500).is_alive();
4635 child
4636 .kill()
4637 .make_assertion()
4638 .with_current_output()
4639 .stdout_only(expected_stdout);
4640 }
4641
4642 /// The expected test outputs come from gnu's tail.
4643 #[test]
4644 #[cfg(unix)]
4645 #[ignore = "disabled until fixed"]
4646 fn test_follow_when_file_and_symlink_are_pointing_to_same_file_and_append_data() {
4647 let scene = TestScenario::new(util_name!());
4648 let at = &scene.fixtures;
4649
4650 let file_data = "file data";
4651 let path_name = "data";
4652 let link_name = "link";
4653
4654 at.write(path_name, file_data);
4655 at.symlink_file(path_name, link_name);
4656
4657 let mut child = scene
4658 .ucmd()
4659 .args(&[
4660 "--follow=descriptor",
4661 "--max-unchanged-stats=1",
4662 "--sleep-interval=0.1",
4663 path_name,
4664 link_name,
4665 ])
4666 .run_no_wait();
4667
4668 child.delay(500);
4669 let more_data = "more data";
4670 at.append(path_name, more_data);
4671
4672 let expected_stdout = format!(
4673 "==> {path_name} <==\n\
4674 {file_data}\n\
4675 ==> {link_name} <==\n\
4676 {file_data}\n\
4677 ==> {path_name} <==\n\
4678 {more_data}\n\
4679 ==> {link_name} <==\n\
4680 {more_data}"
4681 );
4682
4683 child.make_assertion_with_delay(500).is_alive();
4684 child
4685 .kill()
4686 .make_assertion()
4687 .with_current_output()
4688 .stdout_only(expected_stdout);
4689
4690 at.write(path_name, file_data);
4691 let mut child = scene
4692 .ucmd()
4693 .args(&[
4694 "--follow=descriptor",
4695 "--max-unchanged-stats=1",
4696 "--sleep-interval=0.1",
4697 link_name,
4698 path_name,
4699 ])
4700 .run_no_wait();
4701
4702 child.delay(500);
4703 let more_data = "more data";
4704 at.append(path_name, more_data);
4705
4706 let expected_stdout = format!(
4707 "==> {link_name} <==\n\
4708 {file_data}\n\
4709 ==> {path_name} <==\n\
4710 {file_data}\n\
4711 ==> {link_name} <==\n\
4712 {more_data}\n\
4713 ==> {path_name} <==\n\
4714 {more_data}"
4715 );
4716
4717 child.make_assertion_with_delay(500).is_alive();
4718 child
4719 .kill()
4720 .make_assertion()
4721 .with_current_output()
4722 .stdout_only(expected_stdout);
4723 }
4724
4725 #[test]
4726 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
4727 fn test_args_when_directory_given_shorthand_big_f_together_with_retry() {
4728 let scene = TestScenario::new(util_name!());
4729 let at = &scene.fixtures;
4730
4731 let dirname = "dir";
4732 at.mkdir(dirname);
4733 let expected_stderr = format!(
4734 "tail: error reading '{dirname}': Is a directory\n\
4735 tail: {dirname}: cannot follow end of this type of file\n"
4736 );
4737 let mut child = scene.ucmd().args(&["-F", "--retry", "dir"]).run_no_wait();
4738
4739 child.make_assertion_with_delay(500).is_alive();
4740 child
4741 .kill()
4742 .make_assertion()
4743 .with_current_output()
4744 .stderr_only(&expected_stderr);
4745
4746 let mut child = scene.ucmd().args(&["--retry", "-F", "dir"]).run_no_wait();
4747
4748 child.make_assertion_with_delay(500).is_alive();
4749 child
4750 .kill()
4751 .make_assertion()
4752 .with_current_output()
4753 .stderr_only(expected_stderr);
4754 }
4755
4756 /// Fails on macos sometimes with
4757 /// Diff < left / right > :
4758 /// ==> data <==
4759 /// file data
4760 /// ==> /absolute/path/to/data <==
4761 /// <file datasame data
4762 /// >file data
4763 ///
4764 /// Fails on windows with
4765 /// Diff < left / right > :
4766 // ==> data <==
4767 // file data
4768 // ==> \\?\C:\Users\runneradmin\AppData\Local\Temp\.tmpi6lNnX\data <==
4769 // >file data
4770 // <
4771 //
4772 // Fails on freebsd with
4773 // Diff < left / right > :
4774 // ==> data <==
4775 // file data
4776 // ==> /tmp/.tmpZPXPlS/data <==
4777 // >file data
4778 // <
4779 #[test]
4780 #[cfg(all(
4781 not(target_vendor = "apple"),
4782 not(windows),
4783 not(target_os = "freebsd"),
4784 not(target_os = "openbsd"),
4785 not(feature = "selinux") // flaky
4786 ))]
4787 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
4788 fn test_follow_when_files_are_pointing_to_same_relative_file_and_file_stays_same_size() {
4789 let scene = TestScenario::new(util_name!());
4790 let at = &scene.fixtures;
4791
4792 let file_data = "file data";
4793 let relative_path_name = "data";
4794
4795 at.write(relative_path_name, file_data);
4796 let absolute_path = scene.fixtures.plus("data").canonicalize().unwrap();
4797
4798 let mut child = scene
4799 .ucmd()
4800 .args(&[
4801 "--follow=descriptor",
4802 "--max-unchanged-stats=1",
4803 "--sleep-interval=0.1",
4804 relative_path_name,
4805 absolute_path.to_str().unwrap(),
4806 ])
4807 .run_no_wait();
4808
4809 child.delay(500);
4810 let same_data = "same data"; // equal size to file_data
4811 at.write(relative_path_name, same_data);
4812
4813 let expected_stdout = format!(
4814 "==> {0} <==\n\
4815 {1}\n\
4816 ==> {2} <==\n\
4817 {1}",
4818 relative_path_name, // 0
4819 file_data, // 1
4820 absolute_path.to_str().unwrap(), // 2
4821 );
4822
4823 child.make_assertion_with_delay(500).is_alive();
4824 child
4825 .kill()
4826 .make_assertion()
4827 .with_current_output()
4828 .stdout_only(expected_stdout);
4829 }
4830
4831 #[rstest]
4832 #[case::underscore_delimiter("1_000")]
4833 #[case::only_point(".")]
4834 #[case::space_in_primes("' '")]
4835 #[case::space(" ")]
4836 #[case::empty("")]
4837 #[case::comma_separator("0,0")]
4838 #[case::words_nominator_fract("one.zero")]
4839 #[case::words_fract(".zero")]
4840 #[case::words_nominator("one.")]
4841 #[case::two_points("0..0")]
4842 #[case::seconds_unit("1.0s")]
4843 #[case::circumflex_exponent("1.0e^1000")]
4844 fn test_args_sleep_interval_when_illegal_argument_then_usage_error(#[case] sleep_interval: &str) {
4845 new_ucmd!()
4846 .args(&["--sleep-interval", sleep_interval])
4847 .fails_with_code(1)
4848 .usage_error(format!("invalid number of seconds: '{sleep_interval}'"));
4849 }
4850
4851 #[test]
4852 fn test_tail_obsolete_plus_bytes() {
4853 let scene = TestScenario::new(util_name!());
4854 scene
4855 .ucmd()
4856 .arg("+2c")
4857 .pipe_in("wxyz")
4858 .succeeds()
4859 .stdout_only("xyz");
4860 scene
4861 .ucmd()
4862 .arg("+8c")
4863 .pipe_in("wxyz")
4864 .succeeds()
4865 .stdout_only("");
4866 scene
4867 .ucmd()
4868 .arg("+c")
4869 .pipe_in(format!("x{}z", "y".repeat(10)))
4870 .succeeds()
4871 .stdout_only("yyz");
4872 }
4873
4874 #[test]
4875 fn test_tail_obsolete_bytes() {
4876 let scene = TestScenario::new(util_name!());
4877 scene
4878 .ucmd()
4879 .arg("-1c")
4880 .pipe_in("wxyz")
4881 .succeeds()
4882 .stdout_only("z");
4883 scene
4884 .ucmd()
4885 .arg("-9c")
4886 .pipe_in("wxyz")
4887 .succeeds()
4888 .stdout_only("wxyz");
4889 scene
4890 .ucmd()
4891 .arg("-12c")
4892 .pipe_in(format!("x{}z", "y".repeat(12)))
4893 .succeeds()
4894 .stdout_only(format!("{}z", "y".repeat(11)));
4895 }
4896
4897 #[test]
4898 fn test_tail_obsolete_lines() {
4899 let scene = TestScenario::new(util_name!());
4900 scene
4901 .ucmd()
4902 .arg("-1l")
4903 .pipe_in("x")
4904 .succeeds()
4905 .stdout_only("x");
4906 scene
4907 .ucmd()
4908 .arg("-1l")
4909 .pipe_in("x\ny\n")
4910 .succeeds()
4911 .stdout_only("y\n");
4912 scene
4913 .ucmd()
4914 .arg("-1l")
4915 .pipe_in("x\ny")
4916 .succeeds()
4917 .stdout_only("y");
4918 scene
4919 .ucmd()
4920 .arg("-l")
4921 .pipe_in(format!("x{}z", "y\n".repeat(10)))
4922 .succeeds()
4923 .stdout_only(format!("{}z", "y\n".repeat(9)));
4924 }
4925
4926 #[test]
4927 fn test_tail_obsolete_plus_lines() {
4928 let scene = TestScenario::new(util_name!());
4929 scene
4930 .ucmd()
4931 .arg("+1l")
4932 .pipe_in("x\ny\n")
4933 .succeeds()
4934 .stdout_only("x\ny\n");
4935 scene
4936 .ucmd()
4937 .arg("+2l")
4938 .pipe_in("x\ny\n")
4939 .succeeds()
4940 .stdout_only("y\n");
4941 scene
4942 .ucmd()
4943 .arg("+l")
4944 .pipe_in(format!("x\n{}z", "y\n".repeat(10)))
4945 .succeeds()
4946 .stdout_only("y\ny\nz");
4947 }
4948
4949 #[test]
4950 fn test_tail_obsolete_number() {
4951 let scene = TestScenario::new(util_name!());
4952 scene
4953 .ucmd()
4954 .arg("-1")
4955 .pipe_in("x")
4956 .succeeds()
4957 .stdout_only("x");
4958 scene
4959 .ucmd()
4960 .arg("-1")
4961 .pipe_in("x\ny\n")
4962 .succeeds()
4963 .stdout_only("y\n");
4964 scene
4965 .ucmd()
4966 .arg("-1")
4967 .pipe_in("x\ny")
4968 .succeeds()
4969 .stdout_only("y");
4970 }
4971
4972 #[test]
4973 fn test_tail_obsolete_plus_number() {
4974 let scene = TestScenario::new(util_name!());
4975 scene
4976 .ucmd()
4977 .arg("+1")
4978 .pipe_in("x\ny\n")
4979 .succeeds()
4980 .stdout_only("x\ny\n");
4981 scene
4982 .ucmd()
4983 .arg("+2")
4984 .pipe_in("x\ny\n")
4985 .succeeds()
4986 .stdout_only("y\n");
4987 }
4988
4989 #[test]
4990 fn test_tail_obsolete_blocks() {
4991 let scene = TestScenario::new(util_name!());
4992 scene
4993 .ucmd()
4994 .arg("-b")
4995 .pipe_in("x\n".repeat(512 * 10 / 2 + 1))
4996 .succeeds()
4997 .stdout_only("x\n".repeat(512 * 10 / 2));
4998 }
4999
5000 #[test]
5001 fn test_tail_obsolete_error_cases() {
5002 let scene = TestScenario::new(util_name!());
5003 scene
5004 .ucmd()
5005 .arg("+cl")
5006 .fails_with_code(1)
5007 .no_stdout()
5008 .stderr_is("tail: cannot open '+cl' for reading: No such file or directory\n");
5009 scene
5010 .ucmd()
5011 .arg("-cl")
5012 .fails_with_code(1)
5013 .no_stdout()
5014 .stderr_is("tail: invalid number of bytes: 'l'\n");
5015 scene
5016 .ucmd()
5017 .arg("+2cz")
5018 .fails_with_code(1)
5019 .no_stdout()
5020 .stderr_is("tail: cannot open '+2cz' for reading: No such file or directory\n");
5021 scene
5022 .ucmd()
5023 .arg("-2cX")
5024 .fails_with_code(1)
5025 .no_stdout()
5026 .stderr_is("tail: option used in invalid context -- 2\n");
5027 scene
5028 .ucmd()
5029 .arg("-c99999999999999999999")
5030 .pipe_in("x")
5031 .succeeds()
5032 .stdout_is("x");
5033 scene
5034 .ucmd()
5035 .arg("-c --")
5036 .fails_with_code(1)
5037 .no_stdout()
5038 .stderr_is("tail: invalid number of bytes: '-'\n");
5039 scene
5040 .ucmd()
5041 .arg("-5cz")
5042 .fails_with_code(1)
5043 .no_stdout()
5044 .stderr_is("tail: option used in invalid context -- 5\n");
5045 // Large obsolete-syntax numbers clamp to u64::MAX
5046 scene
5047 .ucmd()
5048 .arg("-9999999999999999999b")
5049 .pipe_in("x")
5050 .succeeds()
5051 .stdout_is("x");
5052 scene
5053 .ucmd()
5054 .arg("-999999999999999999999b")
5055 .pipe_in("x")
5056 .succeeds()
5057 .stdout_is("x");
5058 }
5059
5060 #[test]
5061 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
5062 fn test_tail_obsolete_f_flag() {
5063 let scene = TestScenario::new(util_name!());
5064 let at = &scene.fixtures;
5065
5066 let source = "file";
5067 at.touch(source);
5068 let mut p = scene.ucmd().args(&["+f", source]).run_no_wait();
5069 p.make_assertion_with_delay(500).is_alive();
5070 p.kill().make_assertion().with_all_output().no_output();
5071
5072 let mut p = scene
5073 .ucmd()
5074 .set_stdin(Stdio::piped())
5075 .arg("+f")
5076 .run_no_wait();
5077 p.make_assertion_with_delay(500).is_alive();
5078 p.kill().make_assertion().with_all_output().no_output();
5079 }
5080
5081 #[test]
5082 #[cfg(unix)]
5083 #[cfg_attr(wasi_runner, ignore = "WASI: argv/filenames must be valid UTF-8")]
5084 fn test_obsolete_encoding_unix() {
5085 use std::ffi::OsStr;
5086 use std::os::unix::ffi::OsStrExt;
5087
5088 let scene = TestScenario::new(util_name!());
5089 let invalid_utf8_arg = OsStr::from_bytes(&[b'-', INVALID_UTF8, b'b']);
5090
5091 scene
5092 .ucmd()
5093 .arg(invalid_utf8_arg)
5094 .fails_with_code(1)
5095 .no_stdout()
5096 .stderr_is("tail: bad argument encoding: $'-\\x80'$'b'\n");
5097 }
5098
5099 #[test]
5100 #[cfg(windows)]
5101 fn test_obsolete_encoding_windows() {
5102 use std::ffi::OsString;
5103 use std::os::windows::ffi::OsStringExt;
5104
5105 let scene = TestScenario::new(util_name!());
5106 let invalid_utf16_arg = OsString::from_wide(&['-' as u16, INVALID_UTF16, 'b' as u16]);
5107
5108 scene
5109 .ucmd()
5110 .arg(&invalid_utf16_arg)
5111 .fails_with_code(1)
5112 .no_stdout()
5113 .stderr_is("tail: bad argument encoding: \"-`u{D800}b\"\n");
5114 }
5115
5116 #[test]
5117 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
5118 fn test_following_with_pid() {
5119 use std::process::Command;
5120
5121 let ts = TestScenario::new(util_name!());
5122
5123 #[cfg(not(windows))]
5124 let mut sleep_command = Command::new("sleep")
5125 .arg("999d")
5126 .spawn()
5127 .expect("failed to start sleep command");
5128 #[cfg(windows)]
5129 let mut sleep_command = Command::new("powershell")
5130 .arg("-Command")
5131 .arg("Start-Sleep -Seconds 999")
5132 .spawn()
5133 .expect("failed to start sleep command");
5134
5135 let sleep_pid = sleep_command.id();
5136
5137 let at = &ts.fixtures;
5138 at.touch("f");
5139 // when -f is specified, tail should die after
5140 // the pid from --pid also dies
5141 let mut child = ts
5142 .ucmd()
5143 .args(&[
5144 "--pid",
5145 &sleep_pid.to_string(),
5146 "-f",
5147 at.plus("f").to_str().unwrap(),
5148 ])
5149 .stderr_to_stdout()
5150 .run_no_wait();
5151 child.make_assertion_with_delay(2000).is_alive();
5152
5153 #[cfg(not(windows))]
5154 Command::new("kill")
5155 .arg("-9")
5156 .arg(sleep_pid.to_string())
5157 .output()
5158 .expect("failed to kill sleep command");
5159 #[cfg(windows)]
5160 Command::new("taskkill")
5161 .arg("/PID")
5162 .arg(sleep_pid.to_string())
5163 .arg("/F")
5164 .output()
5165 .expect("failed to kill sleep command");
5166
5167 let _ = sleep_command.wait();
5168
5169 child.make_assertion_with_delay(2000).is_not_alive();
5170
5171 child.kill();
5172 }
5173
5174 // This error was first detected when running tail so tail is used here but
5175 // should fail with any command that takes piped input.
5176 // See also https://github.com/uutils/coreutils/issues/3895
5177 #[test]
5178 #[cfg_attr(not(feature = "expensive_tests"), ignore = "")]
5179 fn test_when_piped_input_then_no_broken_pipe() {
5180 let ts = TestScenario::new("tail");
5181 for i in 0..10000 {
5182 dbg!(i);
5183 let test_string = "a\nb\n";
5184 ts.ucmd()
5185 .args(&["-n", "0"])
5186 .pipe_in(test_string)
5187 .succeeds()
5188 .no_output();
5189 }
5190 }
5191
5192 #[test]
5193 #[cfg(unix)]
5194 #[cfg_attr(
5195 wasi_runner,
5196 ignore = "WASI: closed stdout reports a generic I/O error rather than BrokenPipe"
5197 )]
5198 fn test_when_output_closed_then_no_broken_pipe() {
5199 let (at, mut cmd) = at_and_ucmd!();
5200 at.make_file("input").set_len(10_000_000).unwrap();
5201
5202 let mut child = cmd
5203 .args(&["-c", "10000000", "input"])
5204 .set_stdout(Stdio::piped())
5205 .run_no_wait();
5206 // Dropping the stdout should not lead to an error.
5207 // The "Broken pipe" error should be silently ignored.
5208 child.close_stdout();
5209 child.wait().unwrap().fails_silently();
5210 }
5211
5212 #[test]
5213 fn test_child_when_run_with_stderr_to_stdout() {
5214 let ts = TestScenario::new("tail");
5215 let at = &ts.fixtures;
5216
5217 at.write("data", "file data\n");
5218
5219 let expected_stdout = "==> data <==\n\
5220 file data\n\
5221 tail: cannot open 'missing' for reading: No such file or directory\n";
5222 ts.ucmd()
5223 .args(&["data", "missing"])
5224 .stderr_to_stdout()
5225 .fails()
5226 .stdout_only(expected_stdout);
5227 }
5228
5229 #[cfg(target_os = "linux")]
5230 #[test]
5231 fn test_failed_write_is_reported() {
5232 new_ucmd!()
5233 .pipe_in("hello")
5234 .set_stdout(File::create("/dev/full").unwrap())
5235 .fails()
5236 .stderr_is("tail: No space left on device\n");
5237 }
5238
5239 #[cfg(target_os = "linux")]
5240 #[test]
5241 fn test_failed_warning_write_is_reported() {
5242 new_ucmd!()
5243 .args(&["--pid=0", "/dev/null"])
5244 .set_stderr(File::create("/dev/full").unwrap())
5245 .fails_with_code(1);
5246 }
5247
5248 #[cfg(target_os = "linux")]
5249 #[test]
5250 fn test_failed_write_is_reported_on_seekable_input() {
5251 let ts = TestScenario::new("tail");
5252 let at = &ts.fixtures;
5253
5254 at.write("bigfile", &"x\n".repeat(1_100_000));
5255
5256 ts.ucmd()
5257 .arg("bigfile")
5258 .set_stdout(File::create("/dev/full").unwrap())
5259 .fails()
5260 .stderr_is("tail: No space left on device\n");
5261 }
5262
5263 #[test]
5264 #[cfg(unix)]
5265 #[cfg_attr(wasi_runner, ignore = "WASI sandbox: host paths not visible")]
5266 fn test_dev_zero() {
5267 new_ucmd!()
5268 .args(&["-c", "1", "/dev/zero"])
5269 .succeeds()
5270 .stdout_only("\0");
5271 }
5272
5273 #[test]
5274 fn tail_n_lines_with_emoji() {
5275 new_ucmd!()
5276 .args(&["-n", "1"])
5277 .pipe_in("a\nšŸ’\n")
5278 .succeeds()
5279 .stdout_only("šŸ’\n");
5280 }
5281
5282 #[test]
5283 fn test_tail_bytes_exceeds_file_size() {
5284 let ts = TestScenario::new(util_name!());
5285 let at = &ts.fixtures;
5286
5287 // Should be > 4096 bytes (block size can vary):
5288 at.write("test_file.txt", &"x".repeat(5000));
5289
5290 ts.ucmd()
5291 .arg("-c")
5292 .arg("1048576")
5293 .arg("test_file.txt")
5294 .succeeds()
5295 .stdout_only("x".repeat(5000));
5296 }
5297
5298 #[test]
5299 #[cfg(target_os = "linux")]
5300 fn test_follow_pipe_f() {
5301 new_ucmd!()
5302 .args(&["-f", "-c3", "-s.1", "--max-unchanged-stats=1"])
5303 .pipe_in("foo\n")
5304 .succeeds()
5305 .stdout_only("oo\n");
5306 }
5307
5308 #[test]
5309 #[cfg(target_os = "linux")]
5310 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
5311 fn test_follow_stdout_pipe_close() {
5312 let (at, mut ucmd) = at_and_ucmd!();
5313 at.write("f", "line1\nline2\n");
5314
5315 let mut child = ucmd
5316 .args(&["-f", "-s.1", "--max-unchanged-stats=1", "f"])
5317 .set_stdout(Stdio::piped())
5318 .run_no_wait();
5319
5320 child.stdout_exact_bytes(6); // read "line1\n"
5321 child.close_stdout();
5322 child.delay(2000).make_assertion().is_not_alive();
5323 }
5324
5325 #[test]
5326 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
5327 fn test_debug_flag_with_polling() {
5328 let ts = TestScenario::new(util_name!());
5329 let at = &ts.fixtures;
5330 at.touch("f");
5331
5332 let mut child = ts
5333 .ucmd()
5334 .args(&["--debug", "-f", "--use-polling", "f"])
5335 .run_no_wait();
5336
5337 child.make_assertion_with_delay(500).is_alive();
5338 child
5339 .kill()
5340 .make_assertion()
5341 .with_all_output()
5342 .stderr_contains("tail: using polling mode");
5343 }
5344
5345 #[test]
5346 #[cfg(target_os = "linux")]
5347 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
5348 fn test_debug_flag_with_inotify() {
5349 let ts = TestScenario::new(util_name!());
5350 let at = &ts.fixtures;
5351 at.touch("f");
5352
5353 let mut child = ts.ucmd().args(&["--debug", "-f", "f"]).run_no_wait();
5354
5355 child.make_assertion_with_delay(500).is_alive();
5356 child
5357 .kill()
5358 .make_assertion()
5359 .with_all_output()
5360 .stderr_contains("tail: using notification mode");
5361 }
5362
5363 #[test]
5364 #[cfg(target_os = "linux")]
5365 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
5366 fn test_follow_dangling_symlink() {
5367 let (at, mut ucmd) = at_and_ucmd!();
5368 at.symlink_file("target", "link");
5369 let mut p = ucmd
5370 .args(&["-s.1", "--max-unchanged-stats=1", "-F", "link"])
5371 .run_no_wait();
5372 p.delay(500);
5373 at.write("target", "X\n");
5374 p.delay(500);
5375 p.kill().make_assertion().with_all_output().stdout_is("X\n");
5376 }
5377
5378 #[test]
5379 #[cfg(target_os = "linux")]
5380 #[cfg_attr(wasi_runner, ignore = "WASI: tail follow mode disabled")]
5381 fn test_follow_symlink_target_change() {
5382 let (at, mut ucmd) = at_and_ucmd!();
5383 at.write("t1", "A\n");
5384 at.symlink_file("t1", "link");
5385 let mut p = ucmd
5386 .args(&["-s.1", "--max-unchanged-stats=1", "-F", "link"])
5387 .run_no_wait();
5388 p.delay(500);
5389 at.remove("link");
5390 at.symlink_file("t2", "link");
5391 p.delay(500);
5392 at.write("t2", "B\n");
5393 p.delay(500);
5394 p.kill()
5395 .make_assertion()
5396 .with_all_output()
5397 .stdout_contains("A\n")
5398 .stdout_contains("B\n");
5399 }
5400
5401 #[test]
5402 #[cfg(target_os = "linux")]
5403 fn test_no_skip_after_error() {
5404 let (at, mut ucmd) = at_and_ucmd!();
5405 at.write("f", "hello");
5406 ucmd.args(&["/proc/self/mem", "f"])
5407 .fails()
5408 .stdout_contains("hello");
5409 }
5410
5411 #[cfg(unix)]
5412 #[cfg(all(feature = "feat_diagnostics", not(wasi_runner)))]
5413 mod diagnostics {
5414 use super::*;
5415
5416 #[test]
5417 fn test_snippet_points_at_the_unknown_unit() {
5418 let result = new_ucmd!()
5419 .terminal_sim_stderr()
5420 .args(&["-c", "1fb", "/dev/null"])
5421 .fails_with_code(1);
5422 let stderr = result.stderr_as_displayed();
5423
5424 assert!(stderr.contains("tail:1:10"), "{stderr}");
5425 assert!(stderr.contains("not a known unit"), "{stderr}");
5426 }
5427
5428 #[test]
5429 fn test_plain_message_when_stderr_is_a_pipe() {
5430 new_ucmd!()
5431 .args(&["-n", "5QQ", "/dev/null"])
5432 .fails_with_code(1)
5433 .stderr_is("tail: invalid number of lines: '5QQ'\n");
5434 }
5435 }
5436
5437 #[test]
5438 fn test_invalid_count_keeps_its_leading_zeros() {
5439 // Leading zeros are stripped only so the count is read as decimal rather
5440 // than octal. That is internal, so GNU still names the argument as typed.
5441 new_ucmd!()
5442 .args(&["-c", "0fb", "/dev/null"])
5443 .fails_with_code(1)
5444 .stderr_is("tail: invalid number of bytes: '0fb'\n");
5445 new_ucmd!()
5446 .args(&["-n", "000ff", "/dev/null"])
5447 .fails_with_code(1)
5448 .stderr_is("tail: invalid number of lines: '000ff'\n");
5449 // The sign is not put back with them: GNU reports `-c-0fb` as '0fb'.
5450 new_ucmd!()
5451 .args(&["-c-0fb", "/dev/null"])
5452 .fails_with_code(1)
5453 .stderr_is("tail: invalid number of bytes: '0fb'\n");
5454 }