2 use std::ffi::{OsStr, OsString};
3 use std::path::PathBuf;
5 use rand::distributions::Alphanumeric;
6 use rand::{thread_rng, Rng};
8 fn make_rand_name() -> OsString {
9 let rng = thread_rng();
10 let n = format!("TEST{}", rng.sample_iter(&Alphanumeric).take(10).collect::<String>());
11 let n = OsString::from(n);
12 assert!(var_os(&n).is_none());
16 fn eq(a: Option<OsString>, b: Option<&str>) {
17 assert_eq!(a.as_ref().map(|s| &**s), b.map(OsStr::new).map(|s| &*s));
22 let n = make_rand_name();
24 eq(var_os(&n), Some("VALUE"));
28 fn test_remove_var() {
29 let n = make_rand_name();
36 fn test_set_var_overwrite() {
37 let n = make_rand_name();
40 eq(var_os(&n), Some("2"));
42 eq(var_os(&n), Some(""));
46 #[cfg_attr(target_os = "emscripten", ignore)]
48 let mut s = "".to_string();
51 s.push_str("aaaaaaaaaa");
54 let n = make_rand_name();
56 eq(var_os(&n), Some(&s));
60 #[cfg_attr(target_os = "emscripten", ignore)]
61 fn test_env_set_get_huge() {
62 let n = make_rand_name();
63 let s = "x".repeat(10000);
65 eq(var_os(&n), Some(&s));
71 fn test_env_set_var() {
72 let n = make_rand_name();
74 let mut e = vars_os();
76 assert!(!e.any(|(k, v)| { &*k == &*n && &*v == "VALUE" }));
78 assert!(vars_os().any(|(k, v)| { &*k == &*n && &*v == "VALUE" }));
82 #[cfg_attr(any(target_os = "emscripten", target_env = "sgx"), ignore)]
85 fn var_to_os_string(var: Result<String, VarError>) -> Option<OsString> {
87 Ok(var) => Some(OsString::from(var)),
88 Err(VarError::NotUnicode(var)) => Some(var),
95 let oldhome = var_to_os_string(var("HOME"));
97 set_var("HOME", "/home/MountainView");
98 assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView")));
101 if cfg!(target_os = "android") {
102 assert!(home_dir().is_none());
104 // When HOME is not set, some platforms return `None`,
105 // but others return `Some` with a default.
106 // Just check that it is not "/home/MountainView".
107 assert_ne!(home_dir(), Some(PathBuf::from("/home/MountainView")));
110 if let Some(oldhome) = oldhome { set_var("HOME", oldhome); }
111 } else if #[cfg(windows)] {
112 let oldhome = var_to_os_string(var("HOME"));
113 let olduserprofile = var_to_os_string(var("USERPROFILE"));
116 remove_var("USERPROFILE");
118 assert!(home_dir().is_some());
120 set_var("HOME", "/home/MountainView");
121 assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView")));
125 set_var("USERPROFILE", "/home/MountainView");
126 assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView")));
128 set_var("HOME", "/home/MountainView");
129 set_var("USERPROFILE", "/home/PaloAlto");
130 assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView")));
133 remove_var("USERPROFILE");
135 if let Some(oldhome) = oldhome { set_var("HOME", oldhome); }
136 if let Some(olduserprofile) = olduserprofile { set_var("USERPROFILE", olduserprofile); }