|
| 1 | +// Copyright 2014, 2017 The Rust Project Developers. See the COPYRIGHT |
| 2 | +// file at the top-level directory of this distribution and at |
| 3 | +// http://rust-lang.org/COPYRIGHT. |
| 4 | +// |
| 5 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 7 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 8 | +// option. This file may not be copied, modified, or distributed |
| 9 | +// except according to those terms. |
| 10 | + |
| 11 | +// ignore-emscripten |
| 12 | + |
| 13 | +use std::process::Command; |
| 14 | +use std::env; |
| 15 | + |
| 16 | +#[cfg(all(unix, not(target_os="android")))] |
| 17 | +pub fn env_cmd() -> Command { |
| 18 | + Command::new("env") |
| 19 | +} |
| 20 | +#[cfg(target_os="android")] |
| 21 | +pub fn env_cmd() -> Command { |
| 22 | + let mut cmd = Command::new("/system/bin/sh"); |
| 23 | + cmd.arg("-c").arg("set"); |
| 24 | + cmd |
| 25 | +} |
| 26 | + |
| 27 | +#[cfg(windows)] |
| 28 | +pub fn env_cmd() -> Command { |
| 29 | + let mut cmd = Command::new("cmd"); |
| 30 | + cmd.arg("/c").arg("set"); |
| 31 | + cmd |
| 32 | +} |
| 33 | + |
| 34 | +fn main() { |
| 35 | + // save original environment |
| 36 | + let old_env = env::var_os("RUN_TEST_NEW_ENV"); |
| 37 | + |
| 38 | + env::set_var("RUN_TEST_NEW_ENV", "123"); |
| 39 | + |
| 40 | + // create filtered environment vector |
| 41 | + let filtered_env : Vec<(String, String)> = |
| 42 | + env::vars().filter(|&(ref k, _)| k == "PATH").collect(); |
| 43 | + |
| 44 | + let mut cmd = env_cmd() |
| 45 | + .env_clear() |
| 46 | + .envs(&filtered_env); |
| 47 | + |
| 48 | + // restore original environment |
| 49 | + match old_env { |
| 50 | + None => env::remove_var("RUN_TEST_NEW_ENV"), |
| 51 | + Some(val) => env::set_var("RUN_TEST_NEW_ENV", &val) |
| 52 | + } |
| 53 | + |
| 54 | + let prog = cmd.spawn().unwrap(); |
| 55 | + let result = prog.wait_with_output().unwrap(); |
| 56 | + let output = String::from_utf8_lossy(&result.stdout); |
| 57 | + |
| 58 | + assert!(!output.contains("RUN_TEST_NEW_ENV"), |
| 59 | + "found RUN_TEST_NEW_ENV inside of:\n\n{}", output); |
| 60 | +} |
0 commit comments