Debian Codegraph @

tests/by-util/test_nohup.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 winsize Openpty openpty xpixel ypixel ptyprocess
7 #[cfg(unix)]
8 use std::thread::sleep;
9 use uutests::new_ucmd;
10 #[cfg(unix)]
11 use uutests::{at_and_ucmd, util::TestScenario, util_name};
12
13 // General observation: nohup.out will not be created in tests run by cargo test
14 // because stdin/stdout is not attached to a TTY.
15 // All that can be tested is the side-effects.
16
17 #[test]
18 fn test_nohup_exit_codes() {
19 // No args: 125 default, 127 with POSIXLY_CORRECT
20 new_ucmd!().fails_with_code(125);
21 new_ucmd!().env("POSIXLY_CORRECT", "1").fails_with_code(127);
22
23 // Invalid arg: 125 default, 127 with POSIXLY_CORRECT
24 new_ucmd!().arg("--invalid").fails_with_code(125);
25 new_ucmd!()
26 .env("POSIXLY_CORRECT", "1")
27 .arg("--invalid")
28 .fails_with_code(127);
29 }
30
31 #[test]
32 #[cfg(any(
33 target_vendor = "apple",
34 target_os = "linux",
35 target_os = "android",
36 target_os = "freebsd",
37 target_os = "openbsd"
38 ))]
39 fn test_nohup_multiple_args_and_flags() {
40 let (at, mut ucmd) = at_and_ucmd!();
41
42 ucmd.args(&["touch", "-t", "1006161200", "file1", "file2"])
43 .succeeds();
44 sleep(std::time::Duration::from_millis(10));
45
46 assert!(at.file_exists("file1"));
47 assert!(at.file_exists("file2"));
48 }
49
50 #[test]
51 #[cfg(any(
52 target_vendor = "apple",
53 target_os = "linux",
54 target_os = "android",
55 target_os = "freebsd",
56 target_os = "openbsd"
57 ))]
58 fn test_nohup_with_pseudo_terminal_emulation_on_stdin_stdout_stderr_get_replaced() {
59 let ts = TestScenario::new(util_name!());
60 let result = ts
61 .ucmd()
62 .terminal_simulation(true)
63 .args(&["sh", "is_a_tty.sh"])
64 .succeeds();
65
66 assert_eq!(
67 String::from_utf8_lossy(result.stderr()).trim(),
68 "nohup: ignoring input and appending output to 'nohup.out'"
69 );
70
71 sleep(std::time::Duration::from_millis(10));
72
73 // this proves that nohup was exchanging the stdio file descriptors
74 assert_eq!(
75 std::fs::read_to_string(ts.fixtures.plus_as_string("nohup.out")).unwrap(),
76 "stdin is not a tty\nstdout is not a tty\nstderr is not a tty\n"
77 );
78 }
79
80 // Note: Testing stdin preservation is complex because nohup's behavior depends on
81 // whether stdin is a TTY. When stdin is a TTY, nohup redirects it to /dev/null.
82 // When stdin is not a TTY (e.g., a pipe), nohup preserves it.
83 // This behavior is already tested indirectly through other tests.
84
85 // Test that nohup creates nohup.out in current directory
86 #[test]
87 #[cfg(any(
88 target_vendor = "apple",
89 target_os = "linux",
90 target_os = "android",
91 target_os = "freebsd",
92 target_os = "openbsd"
93 ))]
94 fn test_nohup_creates_output_in_cwd() {
95 let ts = TestScenario::new(util_name!());
96 let at = &ts.fixtures;
97
98 ts.ucmd()
99 .terminal_simulation(true)
100 .args(&["echo", "test output"])
101 .succeeds()
102 .stderr_contains("nohup: ignoring input and appending output to 'nohup.out'");
103
104 sleep(std::time::Duration::from_millis(10));
105
106 // Check that nohup.out was created in cwd
107 assert!(at.file_exists("nohup.out"));
108 let content = std::fs::read_to_string(at.plus_as_string("nohup.out")).unwrap();
109 assert!(content.contains("test output"));
110 }
111
112 // Test that nohup appends to existing nohup.out
113 #[test]
114 #[cfg(any(
115 target_vendor = "apple",
116 target_os = "linux",
117 target_os = "android",
118 target_os = "freebsd",
119 target_os = "openbsd"
120 ))]
121 fn test_nohup_appends_to_existing_file() {
122 let ts = TestScenario::new(util_name!());
123 let at = &ts.fixtures;
124
125 // Create existing nohup.out with content
126 at.write("nohup.out", "existing content\n");
127
128 ts.ucmd()
129 .terminal_simulation(true)
130 .args(&["echo", "new output"])
131 .succeeds();
132
133 sleep(std::time::Duration::from_millis(10));
134
135 // Check that new output was appended
136 let content = std::fs::read_to_string(at.plus_as_string("nohup.out")).unwrap();
137 assert!(content.contains("existing content"));
138 assert!(content.contains("new output"));
139 }
140
141 // Test that nohup falls back to $HOME/nohup.out when cwd is not writable
142 // Skipped on macOS as the permissions test is unreliable
143 #[test]
144 #[cfg(any(
145 target_os = "linux",
146 target_os = "android",
147 target_os = "freebsd",
148 target_os = "openbsd"
149 ))]
150 fn test_nohup_fallback_to_home() {
151 use std::fs;
152 use std::os::unix::fs::PermissionsExt;
153
154 // Skip test when running as root (permissions bypassed via CAP_DAC_OVERRIDE)
155 // This is common in Docker/Podman containers but won't happen in CI
156 if rustix::process::geteuid().is_root() {
157 println!("Skipping test when running as root (file permissions bypassed)");
158 return;
159 }
160
161 let ts = TestScenario::new(util_name!());
162 let at = &ts.fixtures;
163
164 // Create a temporary HOME directory
165 at.mkdir("home");
166 let home_dir = at.plus_as_string("home");
167
168 // Create a read-only directory as working directory
169 at.mkdir("readonly_dir");
170 let readonly_path = at.plus("readonly_dir");
171
172 // Make readonly_dir actually read-only
173 let mut perms = fs::metadata(&readonly_path).unwrap().permissions();
174 perms.set_mode(0o555); // Changed from 0o444 to 0o555 (r-xr-xr-x)
175 fs::set_permissions(&readonly_path, perms).unwrap();
176
177 // Run nohup with the readonly directory as cwd and custom HOME
178 let result = ts
179 .ucmd()
180 .env("HOME", &home_dir)
181 .current_dir(&readonly_path)
182 .terminal_simulation(true)
183 .args(&["echo", "fallback test"])
184 .run(); // Use run() instead of succeeds() since it might fail
185
186 // Restore permissions for cleanup before any assertions
187 let mut perms = fs::metadata(&readonly_path).unwrap().permissions();
188 perms.set_mode(0o755);
189 fs::set_permissions(&readonly_path, perms).unwrap();
190
191 // Should mention HOME/nohup.out in stderr if it fell back
192 let stderr_str = String::from_utf8_lossy(result.stderr());
193 let home_nohup = format!("{home_dir}/nohup.out");
194
195 // Check either stderr mentions the HOME path or the file was created in HOME
196 sleep(std::time::Duration::from_millis(50));
197 assert!(
198 stderr_str.contains(&home_nohup) || std::path::Path::new(&home_nohup).exists(),
199 "nohup should fall back to HOME when cwd is not writable. stderr: {stderr_str}"
200 );
201 }
202
203 // Test that nohup exits with 127 when command is not found
204 // or 126 when command exists but is not executable
205 #[test]
206 fn test_nohup_command_not_found() {
207 let command = "this-command-definitely-does-not-exist-anywhere";
208 let result = new_ucmd!().arg(command).fails();
209
210 result.stderr_contains(format!("failed to run command '{command}'"));
211
212 // Accept either 126 (cannot execute) or 127 (command not found)
213 let code = result.try_exit_status().and_then(|s| s.code());
214 assert!(
215 code == Some(126) || code == Some(127),
216 "Expected exit code 126 or 127, got: {code:?}"
217 );
218 }
219
220 // Test stderr is redirected to stdout
221 #[test]
222 #[cfg(any(
223 target_vendor = "apple",
224 target_os = "linux",
225 target_os = "android",
226 target_os = "freebsd",
227 target_os = "openbsd"
228 ))]
229 fn test_nohup_stderr_to_stdout() {
230 let ts = TestScenario::new(util_name!());
231 let at = &ts.fixtures;
232
233 // Create a script that outputs to both stdout and stderr
234 at.write(
235 "both_streams.sh",
236 "#!/bin/bash\necho 'stdout message'\necho 'stderr message' >&2",
237 );
238 at.set_mode("both_streams.sh", 0o755);
239
240 ts.ucmd()
241 .terminal_simulation(true)
242 .args(&["sh", "both_streams.sh"])
243 .succeeds();
244
245 sleep(std::time::Duration::from_millis(10));
246
247 // Both stdout and stderr should be in nohup.out
248 let content = std::fs::read_to_string(at.plus_as_string("nohup.out")).unwrap();
249 assert!(content.contains("stdout message"));
250 assert!(content.contains("stderr message"));
251 }