summaryrefslogtreecommitdiffstats
path: root/library/std/src/process/tests.rs
blob: 955ad68916c216ae5fc7493cbca3781309b1e6fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use crate::io::prelude::*;

use super::{Command, Output, Stdio};
use crate::io::ErrorKind;
use crate::str;

fn known_command() -> Command {
    if cfg!(windows) { Command::new("help") } else { Command::new("echo") }
}

#[cfg(target_os = "android")]
fn shell_cmd() -> Command {
    Command::new("/system/bin/sh")
}

#[cfg(not(target_os = "android"))]
fn shell_cmd() -> Command {
    Command::new("/bin/sh")
}

#[test]
#[cfg_attr(any(target_os = "vxworks"), ignore)]
fn smoke() {
    let p = if cfg!(target_os = "windows") {
        Command::new("cmd").args(&["/C", "exit 0"]).spawn()
    } else {
        shell_cmd().arg("-c").arg("true").spawn()
    };
    assert!(p.is_ok());
    let mut p = p.unwrap();
    assert!(p.wait().unwrap().success());
}

#[test]
#[cfg_attr(target_os = "android", ignore)]
fn smoke_failure() {
    match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
        Ok(..) => panic!(),
        Err(..) => {}
    }
}

#[test]
#[cfg_attr(any(target_os = "vxworks"), ignore)]
fn exit_reported_right() {
    let p = if cfg!(target_os = "windows") {
        Command::new("cmd").args(&["/C", "exit 1"]).spawn()
    } else {
        shell_cmd().arg("-c").arg("false").spawn()
    };
    assert!(p.is_ok());
    let mut p = p.unwrap();
    assert!(p.wait().unwrap().code() == Some(1));
    drop(p.wait());
}

#[test]
#[cfg(unix)]
#[cfg_attr(any(target_os = "vxworks"), ignore)]
fn signal_reported_right() {
    use crate::os::unix::process::ExitStatusExt;

    let mut p = shell_cmd().arg("-c").arg("read a").stdin(Stdio::piped()).spawn().unwrap();
    p.kill().unwrap();
    match p.wait().unwrap().signal() {
        Some(9) => {}
        result => panic!("not terminated by signal 9 (instead, {result:?})"),
    }
}

pub fn run_output(mut cmd: Command) -> String {
    let p = cmd.spawn();
    assert!(p.is_ok());
    let mut p = p.unwrap();
    assert!(p.stdout.is_some());
    let mut ret = String::new();
    p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
    assert!(p.wait().unwrap().success());
    return ret;
}

#[test]
#[cfg_attr(any(target_os = "vxworks"), ignore)]
fn stdout_works() {
    if cfg!(target_os = "windows") {
        let mut cmd = Command::new("cmd");
        cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
        assert_eq!(run_output(cmd), "foobar\r\n");
    } else {
        let mut cmd = shell_cmd();
        cmd.arg("-c").arg("echo foobar").stdout(Stdio::piped());
        assert_eq!(run_output(cmd), "foobar\n");
    }
}

#[test]
#[cfg_attr(any(windows, target_os = "vxworks"), ignore)]
fn set_current_dir_works() {
    let mut cmd = shell_cmd();
    cmd.arg("-c").arg("pwd").current_dir("/").stdout(Stdio::piped());
    assert_eq!(run_output(cmd), "/\n");
}

#[test]
#[cfg_attr(any(windows, target_os = "vxworks"), ignore)]
fn stdin_works() {
    let mut p = shell_cmd()
        .arg("-c")
        .arg("read line; echo $line")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
    drop(p.stdin.take());
    let mut out = String::new();
    p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
    assert!(p.wait().unwrap().success());
    assert_eq!(out, "foobar\n");
}

#[test]
#[cfg_attr(any(target_os = "vxworks"), ignore)]
fn test_process_status() {
    let mut status = if cfg!(target_os = "windows") {
        Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
    } else {
        shell_cmd().arg("-c").arg("false").status().unwrap()
    };
    assert!(status.code() == Some(1));

    status = if cfg!(target_os = "windows") {
        Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
    } else {
        shell_cmd().arg("-c").arg("true").status().unwrap()
    };
    assert!(status.success());
}

#[test]
fn test_process_output_fail_to_start() {
    match Command::new("/no-binary-by-this-name-should-exist").output() {
        Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
        Ok(..) => panic!(),
    }
}

#[test]
#[cfg_attr(any(target_os = "vxworks"), ignore)]
fn test_process_output_output() {
    let Output { status, stdout, stderr } = if cfg!(target_os = "windows") {
        Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
    } else {
        shell_cmd().arg("-c").arg("echo hello").output().unwrap()
    };
    let output_str = str::from_utf8(&stdout).unwrap();

    assert!(status.success());
    assert_eq!(output_str.trim().to_string(), "hello");
    assert_eq!(stderr, Vec::new());
}

#[test]
#[cfg_attr(any(target_os = "vxworks"), ignore)]
fn test_process_output_error() {
    let Output { status, stdout, stderr } = if cfg!(target_os = "windows") {
        Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
    } else {
        Command::new("mkdir").arg("./").output().unwrap()
    };

    assert!(status.code().is_some());
    assert!(status.code() != Some(0));
    assert_eq!(stdout, Vec::new());
    assert!(!stderr.is_empty());
}

#[test]
#[cfg_attr(any(target_os = "vxworks"), ignore)]
fn test_finish_once() {
    let mut prog = if cfg!(target_os = "windows") {
        Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
    } else {
        shell_cmd().arg("-c").arg("false").spawn().unwrap()
    };
    assert!(prog.wait().unwrap().code() == Some(1));
}

#[test]
#[cfg_attr(any(target_os = "vxworks"), ignore)]
fn test_finish_twice() {
    let mut prog = if cfg!(target_os = "windows") {
        Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
    } else {
        shell_cmd().arg("-c").arg("false").spawn().unwrap()
    };
    assert!(prog.wait().unwrap().code() == Some(1));
    assert!(prog.wait().unwrap().code() == Some(1));
}

#[test]
#[cfg_attr(any(target_os = "vxworks"), ignore)]
fn test_wait_with_output_once() {
    let prog = if cfg!(target_os = "windows") {
        Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
    } else {
        shell_cmd().arg("-c").arg("echo hello").stdout(Stdio::piped()).spawn().unwrap()
    };

    let Output { status, stdout, stderr } = prog.wait_with_output().unwrap();
    let output_str = str::from_utf8(&stdout).unwrap();

    assert!(status.success());
    assert_eq!(output_str.trim().to_string(), "hello");
    assert_eq!(stderr, Vec::new());
}

#[cfg(all(unix, not(target_os = "android")))]
pub fn env_cmd() -> Command {
    Command::new("env")
}
#[cfg(target_os = "android")]
pub fn env_cmd() -> Command {
    let mut cmd = Command::new("/system/bin/sh");
    cmd.arg("-c").arg("set");
    cmd
}

#[cfg(windows)]
pub fn env_cmd() -> Command {
    let mut cmd = Command::new("cmd");
    cmd.arg("/c").arg("set");
    cmd
}

#[test]
#[cfg_attr(target_os = "vxworks", ignore)]
fn test_override_env() {
    use crate::env;

    // In some build environments (such as chrooted Nix builds), `env` can
    // only be found in the explicitly-provided PATH env variable, not in
    // default places such as /bin or /usr/bin. So we need to pass through
    // PATH to our sub-process.
    let mut cmd = env_cmd();
    cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
    if let Some(p) = env::var_os("PATH") {
        cmd.env("PATH", &p);
    }
    let result = cmd.output().unwrap();
    let output = String::from_utf8_lossy(&result.stdout).to_string();

    assert!(
        output.contains("RUN_TEST_NEW_ENV=123"),
        "didn't find RUN_TEST_NEW_ENV inside of:\n\n{output}",
    );
}

#[test]
#[cfg_attr(target_os = "vxworks", ignore)]
fn test_add_to_env() {
    let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
    let output = String::from_utf8_lossy(&result.stdout).to_string();

    assert!(
        output.contains("RUN_TEST_NEW_ENV=123"),
        "didn't find RUN_TEST_NEW_ENV inside of:\n\n{output}"
    );
}

#[test]
#[cfg_attr(target_os = "vxworks", ignore)]
fn test_capture_env_at_spawn() {
    use crate::env;

    let mut cmd = env_cmd();
    cmd.env("RUN_TEST_NEW_ENV1", "123");

    // This variable will not be present if the environment has already
    // been captured above.
    env::set_var("RUN_TEST_NEW_ENV2", "456");
    let result = cmd.output().unwrap();
    env::remove_var("RUN_TEST_NEW_ENV2");

    let output = String::from_utf8_lossy(&result.stdout).to_string();

    assert!(
        output.contains("RUN_TEST_NEW_ENV1=123"),
        "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{output}"
    );
    assert!(
        output.contains("RUN_TEST_NEW_ENV2=456"),
        "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{output}"
    );
}

// Regression tests for #30858.
#[test]
fn test_interior_nul_in_progname_is_error() {
    match Command::new("has-some-\0\0s-inside").spawn() {
        Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
        Ok(_) => panic!(),
    }
}

#[test]
fn test_interior_nul_in_arg_is_error() {
    match known_command().arg("has-some-\0\0s-inside").spawn() {
        Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
        Ok(_) => panic!(),
    }
}

#[test]
fn test_interior_nul_in_args_is_error() {
    match known_command().args(&["has-some-\0\0s-inside"]).spawn() {
        Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
        Ok(_) => panic!(),
    }
}

#[test]
fn test_interior_nul_in_current_dir_is_error() {
    match known_command().current_dir("has-some-\0\0s-inside").spawn() {
        Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
        Ok(_) => panic!(),
    }
}

// Regression tests for #30862.
#[test]
#[cfg_attr(target_os = "vxworks", ignore)]
fn test_interior_nul_in_env_key_is_error() {
    match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
        Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
        Ok(_) => panic!(),
    }
}

#[test]
#[cfg_attr(target_os = "vxworks", ignore)]
fn test_interior_nul_in_env_value_is_error() {
    match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
        Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
        Ok(_) => panic!(),
    }
}

/// Tests that process creation flags work by debugging a process.
/// Other creation flags make it hard or impossible to detect
/// behavioral changes in the process.
#[test]
#[cfg(windows)]
fn test_creation_flags() {
    use crate::os::windows::process::CommandExt;
    use crate::sys::c::{BOOL, DWORD, INFINITE};
    #[repr(C, packed)]
    struct DEBUG_EVENT {
        pub event_code: DWORD,
        pub process_id: DWORD,
        pub thread_id: DWORD,
        // This is a union in the real struct, but we don't
        // need this data for the purposes of this test.
        pub _junk: [u8; 164],
    }

    extern "system" {
        fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
        fn ContinueDebugEvent(
            dwProcessId: DWORD,
            dwThreadId: DWORD,
            dwContinueStatus: DWORD,
        ) -> BOOL;
    }

    const DEBUG_PROCESS: DWORD = 1;
    const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
    const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x80010001;

    let mut child =
        Command::new("cmd").creation_flags(DEBUG_PROCESS).stdin(Stdio::piped()).spawn().unwrap();
    child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
    let mut events = 0;
    let mut event = DEBUG_EVENT { event_code: 0, process_id: 0, thread_id: 0, _junk: [0; 164] };
    loop {
        if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
            panic!("WaitForDebugEvent failed!");
        }
        events += 1;

        if event.event_code == EXIT_PROCESS_DEBUG_EVENT {
            break;
        }

        if unsafe {
            ContinueDebugEvent(event.process_id, event.thread_id, DBG_EXCEPTION_NOT_HANDLED)
        } == 0
        {
            panic!("ContinueDebugEvent failed!");
        }
    }
    assert!(events > 0);
}

#[test]
fn test_command_implements_send_sync() {
    fn take_send_sync_type<T: Send + Sync>(_: T) {}
    take_send_sync_type(Command::new(""))
}

// Ensure that starting a process with no environment variables works on Windows.
// This will fail if the environment block is ill-formed.
#[test]
#[cfg(windows)]
fn env_empty() {
    let p = Command::new("cmd").args(&["/C", "exit 0"]).env_clear().spawn();
    assert!(p.is_ok());
}

// See issue #91991
#[test]
#[cfg(windows)]
fn run_bat_script() {
    let tempdir = crate::sys_common::io::test::tmpdir();
    let script_path = tempdir.join("hello.cmd");

    crate::fs::write(&script_path, "@echo Hello, %~1!").unwrap();
    let output = Command::new(&script_path)
        .arg("fellow Rustaceans")
        .stdout(crate::process::Stdio::piped())
        .spawn()
        .unwrap()
        .wait_with_output()
        .unwrap();
    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "Hello, fellow Rustaceans!");
}

// See issue #95178
#[test]
#[cfg(windows)]
fn run_canonical_bat_script() {
    let tempdir = crate::sys_common::io::test::tmpdir();
    let script_path = tempdir.join("hello.cmd");

    crate::fs::write(&script_path, "@echo Hello, %~1!").unwrap();

    // Try using a canonical path
    let output = Command::new(&script_path.canonicalize().unwrap())
        .arg("fellow Rustaceans")
        .stdout(crate::process::Stdio::piped())
        .spawn()
        .unwrap()
        .wait_with_output()
        .unwrap();
    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "Hello, fellow Rustaceans!");
}