Debian Codegraph @

tests/daemon_tests.rs

raw symbols SCIP
1 //! Daemon-specific integration tests
2 //!
3 //! This module tests the `daemon()` function which creates a detached background process.
4 //! These tests verify:
5 //! - Process detachment and proper PID management
6 //! - Directory handling (chdir vs nochdir)
7 //! - Process group and session management
8 //! - File descriptor handling (noclose option)
9 //! - Command execution in daemon context
10 //! - Absence of controlling terminal
11 //!
12 //! Note: These tests fork twice (the daemon pattern) so they run in separate
13 //! processes to avoid terminating the test runner when `daemon()` calls `exit(0)`.
14
15 #![allow(clippy::expect_used)]
16 #![allow(clippy::unwrap_used)]
17 #![allow(clippy::panic)]
18 #![allow(clippy::match_wild_err_arm)]
19 #![allow(clippy::similar_names)]
20 #![allow(clippy::uninlined_format_args)]
21 #![allow(clippy::indexing_slicing)]
22
23 mod common;
24
25 use std::{
26 env, fs,
27 process::{Command, exit},
28 };
29
30 use fork::{Fork, daemon, fork};
31
32 use common::{get_unique_test_dir, setup_test_dir, wait_for_file};
33
34 #[test]
35 fn test_daemon_creates_detached_process() {
36 // Tests that daemon() successfully creates a detached background process
37 // Expected behavior:
38 // 1. Parent process forks
39 // 2. First child creates new session and forks again
40 // 3. First child exits (daemon() calls exit(0))
41 // 4. Grandchild (daemon) is detached and writes its PID
42 // 5. Daemon changes to root directory (nochdir=false)
43 // 6. Daemon has valid PID > 0
44 let test_dir = setup_test_dir(get_unique_test_dir("daemon_creates_detached"));
45 let marker_file = test_dir.join("daemon.marker");
46
47 // Fork the test to avoid daemon() calling exit(0) on parent
48 match fork().expect("Failed to fork") {
49 Fork::Parent(_) => {
50 // Parent waits for marker file to be created
51 assert!(
52 wait_for_file(&marker_file, 500),
53 "Daemon should have created marker file"
54 );
55
56 // Read PID from marker file
57 let content = fs::read_to_string(&marker_file).expect("Failed to read marker file");
58 let daemon_pid: i32 = content.trim().parse().expect("Failed to parse PID");
59 assert!(daemon_pid > 0, "Daemon PID should be positive");
60
61 // Cleanup
62 let _ = fs::remove_dir_all(&test_dir);
63 }
64 Fork::Child => {
65 // Child calls daemon()
66 if let Ok(Fork::Child) = daemon(false, true) {
67 // This is the daemon process
68 // Write our PID to marker file
69 let pid = unsafe { libc::getpid() };
70 fs::write(&marker_file, format!("{}", pid)).expect("Failed to write marker file");
71
72 // Verify we're in root directory
73 let current = env::current_dir().expect("Failed to get current dir");
74 assert_eq!(current.to_str(), Some("/"));
75
76 exit(0);
77 }
78 // Parent of daemon exits (daemon() calls exit(0) for us)
79 }
80 }
81 }
82
83 #[test]
84 fn test_daemon_with_nochdir() {
85 // Tests that daemon(nochdir=true) preserves the current working directory
86 // Expected behavior:
87 // 1. Test changes to a specific directory before calling daemon()
88 // 2. daemon(true, true) is called (nochdir=true, noclose=true)
89 // 3. Daemon process should remain in the same directory (not /)
90 // 4. Daemon writes current directory to file for verification
91 let test_dir = setup_test_dir(get_unique_test_dir("daemon_nochdir"));
92 let marker_file = test_dir.join("nochdir.marker");
93
94 // Change to test directory
95 env::set_current_dir(&test_dir).expect("Failed to change directory");
96
97 match fork().expect("Failed to fork") {
98 Fork::Parent(_) => {
99 assert!(
100 wait_for_file(&marker_file, 500),
101 "Daemon should have created marker file"
102 );
103
104 // Cleanup
105 let _ = fs::remove_dir_all(&test_dir);
106 }
107 Fork::Child => {
108 if let Ok(Fork::Child) = daemon(true, true) {
109 // Daemon with nochdir=true should preserve directory
110 let current = env::current_dir().expect("Failed to get current dir");
111
112 // Write confirmation to marker file
113 fs::write(&marker_file, format!("{}", current.display()))
114 .expect("Failed to write marker file");
115
116 // Directory should still be test_dir, not root
117 assert_ne!(current.to_str(), Some("/"));
118
119 exit(0);
120 }
121 }
122 }
123 }
124
125 #[test]
126 fn test_daemon_process_group() {
127 // Tests that daemon creates proper process group structure
128 // Expected behavior:
129 // 1. daemon() performs double-fork pattern
130 // 2. After double-fork, daemon is NOT a session leader (PID != PGID)
131 // 3. This prevents daemon from acquiring a controlling terminal
132 // 4. Both PID and PGID are positive values
133 // 5. Daemon writes PID,PGID to file for verification
134 let test_dir = setup_test_dir(get_unique_test_dir("daemon_process_group"));
135 let marker_file = test_dir.join("pgid.marker");
136
137 match fork().expect("Failed to fork") {
138 Fork::Parent(_) => {
139 assert!(
140 wait_for_file(&marker_file, 500),
141 "Daemon should have created marker file"
142 );
143
144 // Read and verify process group info
145 let content = fs::read_to_string(&marker_file).expect("Failed to read marker file");
146 let parts: Vec<&str> = content.trim().split(',').collect();
147 assert_eq!(parts.len(), 2);
148
149 let pid: i32 = parts[0].parse().expect("Failed to parse PID");
150 let pgid: i32 = parts[1].parse().expect("Failed to parse PGID");
151
152 // Daemon (after double-fork) should NOT be session leader
153 // but should be in a new process group
154 assert!(pid > 0, "PID should be positive");
155 assert!(pgid > 0, "PGID should be positive");
156 assert_ne!(
157 pid, pgid,
158 "Daemon (after double-fork) should NOT be session leader"
159 );
160
161 // Cleanup
162 let _ = fs::remove_dir_all(&test_dir);
163 }
164 Fork::Child => {
165 if let Ok(Fork::Child) = daemon(false, true) {
166 let pid = unsafe { libc::getpid() };
167 let pgid = unsafe { libc::getpgrp() };
168
169 fs::write(&marker_file, format!("{},{}", pid, pgid))
170 .expect("Failed to write marker file");
171
172 exit(0);
173 }
174 }
175 }
176 }
177
178 #[test]
179 fn test_daemon_with_command_execution() {
180 // Tests that daemon can execute commands successfully
181 // Expected behavior:
182 // 1. Daemon process is created
183 // 2. Daemon executes a shell command
184 // 3. Command output is written to a file
185 // 4. Parent can verify command executed correctly
186 // 5. Tests real-world daemon usage pattern
187 let test_dir = setup_test_dir(get_unique_test_dir("daemon_command_exec"));
188 let output_file = test_dir.join("command.output");
189
190 match fork().expect("Failed to fork") {
191 Fork::Parent(_) => {
192 assert!(
193 wait_for_file(&output_file, 500),
194 "Command output file should exist"
195 );
196
197 let content = fs::read_to_string(&output_file).expect("Failed to read output file");
198 assert!(
199 content.contains("hello from daemon"),
200 "Output should contain expected text"
201 );
202
203 // Cleanup
204 let _ = fs::remove_dir_all(&test_dir);
205 }
206 Fork::Child => {
207 if let Ok(Fork::Child) = daemon(false, true) {
208 // Execute a command in the daemon
209 Command::new("sh")
210 .arg("-c")
211 .arg(format!(
212 "echo 'hello from daemon' > {}",
213 output_file.display()
214 ))
215 .output()
216 .expect("Failed to execute command");
217
218 exit(0);
219 }
220 }
221 }
222 }
223
224 #[test]
225 fn test_daemon_no_controlling_terminal() {
226 // Tests that daemon has no controlling terminal
227 // Expected behavior:
228 // 1. Daemon process is created
229 // 2. Daemon calls 'tty' command to check for terminal
230 // 3. tty command should return "not a tty" or similar error
231 // 4. This confirms daemon is properly detached from terminal
232 // 5. Critical for background service behavior
233 let test_dir = setup_test_dir(get_unique_test_dir("daemon_no_tty"));
234 let tty_file = test_dir.join("tty.info");
235
236 match fork().expect("Failed to fork") {
237 Fork::Parent(_) => {
238 assert!(wait_for_file(&tty_file, 500), "TTY info file should exist");
239
240 let content = fs::read_to_string(&tty_file).expect("Failed to read tty file");
241 // When daemon has no controlling terminal, tty command should fail or return "not a tty"
242 assert!(
243 content.contains("not a tty") || content.contains("No such"),
244 "Daemon should have no controlling terminal, got: {}",
245 content
246 );
247
248 // Cleanup
249 let _ = fs::remove_dir_all(&test_dir);
250 }
251 Fork::Child => {
252 if let Ok(Fork::Child) = daemon(false, true) {
253 // Check if we have a controlling terminal
254 let output = Command::new("tty")
255 .output()
256 .expect("Failed to run tty command");
257
258 let tty_output = if output.stdout.is_empty() {
259 String::from_utf8_lossy(&output.stderr).to_string()
260 } else {
261 String::from_utf8_lossy(&output.stdout).to_string()
262 };
263
264 fs::write(&tty_file, tty_output).expect("Failed to write tty file");
265
266 exit(0);
267 }
268 }
269 }
270 }