2 use std::ffi::{OsStr, OsString};
4 use rand::distributions::Alphanumeric;
5 use rand::{thread_rng, Rng};
7 fn make_rand_name() -> OsString {
8 let rng = thread_rng();
9 let n = format!("TEST{}", rng.sample_iter(&Alphanumeric).take(10).collect::<String>());
10 let n = OsString::from(n);
11 assert!(var_os(&n).is_none());
15 fn eq(a: Option<OsString>, b: Option<&str>) {
16 assert_eq!(a.as_ref().map(|s| &**s), b.map(OsStr::new).map(|s| &*s));
21 let n = make_rand_name();
23 eq(var_os(&n), Some("VALUE"));
27 fn test_remove_var() {
28 let n = make_rand_name();
35 fn test_set_var_overwrite() {
36 let n = make_rand_name();
39 eq(var_os(&n), Some("2"));
41 eq(var_os(&n), Some(""));
45 #[cfg_attr(target_os = "emscripten", ignore)]
47 let mut s = "".to_string();
50 s.push_str("aaaaaaaaaa");
53 let n = make_rand_name();
55 eq(var_os(&n), Some(&s));
59 #[cfg_attr(target_os = "emscripten", ignore)]
60 fn test_env_set_get_huge() {
61 let n = make_rand_name();
62 let s = "x".repeat(10000);
64 eq(var_os(&n), Some(&s));
70 fn test_env_set_var() {
71 let n = make_rand_name();
73 let mut e = vars_os();
75 assert!(!e.any(|(k, v)| { &*k == &*n && &*v == "VALUE" }));
77 assert!(vars_os().any(|(k, v)| { &*k == &*n && &*v == "VALUE" }));
81 #[cfg_attr(not(any(unix, windows)), ignore, allow(unused))]
84 use std::path::PathBuf;
86 fn var_to_os_string(var: Result<String, VarError>) -> Option<OsString> {
88 Ok(var) => Some(OsString::from(var)),
89 Err(VarError::NotUnicode(var)) => Some(var),
96 let oldhome = var_to_os_string(var("HOME"));
98 set_var("HOME", "/home/MountainView");
99 assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView")));
102 if cfg!(target_os = "android") {
103 assert!(home_dir().is_none());
105 // When HOME is not set, some platforms return `None`,
106 // but others return `Some` with a default.
107 // Just check that it is not "/home/MountainView".
108 assert_ne!(home_dir(), Some(PathBuf::from("/home/MountainView")));
111 if let Some(oldhome) = oldhome { set_var("HOME", oldhome); }
112 } else if #[cfg(windows)] {
113 let oldhome = var_to_os_string(var("HOME"));
114 let olduserprofile = var_to_os_string(var("USERPROFILE"));
117 remove_var("USERPROFILE");
119 assert!(home_dir().is_some());
121 set_var("HOME", "/home/MountainView");
122 assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView")));
126 set_var("USERPROFILE", "/home/MountainView");
127 assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView")));
129 set_var("HOME", "/home/MountainView");
130 set_var("USERPROFILE", "/home/PaloAlto");
131 assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView")));
134 remove_var("USERPROFILE");
136 if let Some(oldhome) = oldhome { set_var("HOME", oldhome); }
137 if let Some(olduserprofile) = olduserprofile { set_var("USERPROFILE", olduserprofile); }