Debian Codegraph @

.cargo/vendor/which/tests/basic.rs

raw
1 extern crate which;
2
3 #[cfg(all(unix, feature = "regex"))]
4 use regex::Regex;
5 use std::ffi::{OsStr, OsString};
6 use std::fs;
7 use std::io;
8 use std::path::{Path, PathBuf};
9 use std::{env, vec};
10 use tempfile::TempDir;
11
12 #[derive(Debug)]
13 struct TestFixture {
14 /// Temp directory.
15 pub tempdir: TempDir,
16 /// $PATH
17 pub paths: OsString,
18 /// Binaries created in $PATH
19 pub bins: Vec<PathBuf>,
20 }
21
22 const SUBDIRS: &[&str] = &["a", "b", "c"];
23 const BIN_NAME: &str = "bin";
24
25 #[allow(clippy::unnecessary_cast)]
26 #[cfg(unix)]
27 fn mk_bin(dir: &Path, path: &str, extension: &str) -> io::Result<PathBuf> {
28 use std::os::unix::fs::OpenOptionsExt;
29 let bin = dir.join(path).with_extension(extension);
30
31 #[cfg(any(target_os = "macos", target_os = "linux"))]
32 let mode = rustix::fs::Mode::XUSR.bits() as u32;
33 let mode = 0o666 | mode;
34 fs::OpenOptions::new()
35 .write(true)
36 .create(true)
37 .mode(mode)
38 .open(&bin)
39 .and_then(|_f| bin.canonicalize())
40 }
41
42 fn touch(dir: &Path, path: &str, extension: &str) -> io::Result<PathBuf> {
43 let b = dir.join(path).with_extension(extension);
44 fs::File::create(&b).and_then(|_f| b.canonicalize())
45 }
46
47 #[cfg(windows)]
48 fn mk_bin(dir: &Path, path: &str, extension: &str) -> io::Result<PathBuf> {
49 touch(dir, path, extension)
50 }
51
52 impl TestFixture {
53 // tmp/a/bin
54 // tmp/a/bin.exe
55 // tmp/a/bin.cmd
56 // tmp/b/bin
57 // tmp/b/bin.exe
58 // tmp/b/bin.cmd
59 // tmp/c/bin
60 // tmp/c/bin.exe
61 // tmp/c/bin.cmd
62 pub fn new() -> TestFixture {
63 let tempdir = tempfile::tempdir().unwrap();
64 let mut builder = fs::DirBuilder::new();
65 builder.recursive(true);
66 let mut paths = vec![];
67 let mut bins = vec![];
68 for d in SUBDIRS.iter() {
69 let p = tempdir.path().join(d);
70 builder.create(&p).unwrap();
71 bins.push(mk_bin(&p, BIN_NAME, "").unwrap());
72 bins.push(mk_bin(&p, BIN_NAME, "exe").unwrap());
73 bins.push(mk_bin(&p, BIN_NAME, "cmd").unwrap());
74 paths.push(p);
75 }
76 let p = tempdir.path().join("win-bin");
77 builder.create(&p).unwrap();
78 bins.push(mk_bin(&p, "win-bin", "exe").unwrap());
79 paths.push(p);
80 TestFixture {
81 tempdir,
82 paths: env::join_paths(paths).unwrap(),
83 bins,
84 }
85 }
86
87 #[cfg(unix)]
88 pub fn new_with_tilde_path() -> TestFixture {
89 let tempdir = tempfile::tempdir().unwrap();
90 let mut builder = fs::DirBuilder::new();
91 builder.recursive(true);
92 let mut paths = vec![];
93 let mut bins = vec![];
94 for d in SUBDIRS.iter() {
95 let p = PathBuf::from("~").join(d);
96 let p_bin = tempdir.path().join(d);
97 builder.create(&p_bin).unwrap();
98 bins.push(mk_bin(&p_bin, BIN_NAME, "").unwrap());
99 bins.push(mk_bin(&p_bin, BIN_NAME, "exe").unwrap());
100 bins.push(mk_bin(&p_bin, BIN_NAME, "cmd").unwrap());
101 paths.push(p);
102 }
103 let p = tempdir.path().join("win-bin");
104 builder.create(&p).unwrap();
105 bins.push(mk_bin(&p, "win-bin", "exe").unwrap());
106 paths.push(p);
107 TestFixture {
108 tempdir,
109 paths: env::join_paths(paths).unwrap(),
110 bins,
111 }
112 }
113
114 #[allow(dead_code)]
115 pub fn touch(&self, path: &str, extension: &str) -> io::Result<PathBuf> {
116 touch(self.tempdir.path(), path, extension)
117 }
118
119 pub fn mk_bin(&self, path: &str, extension: &str) -> io::Result<PathBuf> {
120 mk_bin(self.tempdir.path(), path, extension)
121 }
122 }
123
124 fn _which<T: AsRef<OsStr>>(f: &TestFixture, path: T) -> which::Result<which::CanonicalPath> {
125 which::CanonicalPath::new_in(path, Some(f.paths.clone()), f.tempdir.path())
126 }
127
128 fn _which_all<'a, T: AsRef<OsStr> + 'a>(
129 f: &'a TestFixture,
130 path: T,
131 ) -> which::Result<impl Iterator<Item = which::Result<which::CanonicalPath>> + '_> {
132 which::CanonicalPath::all_in(path, Some(f.paths.clone()), f.tempdir.path())
133 }
134
135 #[test]
136 #[cfg(unix)]
137 fn it_works() {
138 use std::process::Command;
139 let result = which::Path::new("rustc");
140 assert!(result.is_ok());
141
142 let which_result = Command::new("which").arg("rustc").output();
143
144 assert_eq!(
145 String::from(result.unwrap().to_str().unwrap()),
146 String::from_utf8(which_result.unwrap().stdout)
147 .unwrap()
148 .trim()
149 );
150 }
151
152 #[test]
153 #[cfg(unix)]
154 fn test_which() {
155 let f = TestFixture::new();
156 assert_eq!(_which(&f, BIN_NAME).unwrap(), f.bins[0])
157 }
158
159 #[test]
160 #[cfg(windows)]
161 fn test_which() {
162 let f = TestFixture::new();
163 assert_eq!(_which(&f, BIN_NAME).unwrap(), f.bins[1])
164 }
165
166 #[test]
167 #[cfg(unix)]
168 fn test_which_tilde() {
169 let old_home = env::var_os("HOME");
170 let f = TestFixture::new_with_tilde_path();
171 env::set_var("HOME", f.tempdir.path().as_os_str());
172 assert_eq!(_which(&f, BIN_NAME).unwrap(), f.bins[0]);
173 if let Some(old_home) = old_home {
174 env::set_var("HOME", old_home);
175 } else {
176 env::remove_var("HOME");
177 }
178 }
179
180 // Windows test_which_tilde intentionally omitted because
181 // we don't want to pollute the home directory.
182 // It's non-trivial to adjust which directory Windows thinks
183 // is the home directory. At this time, tilde expansion has
184 // no Windows specific behavior. It works as normal on Windows.
185
186 #[test]
187 #[cfg(all(unix, feature = "regex"))]
188 fn test_which_re_in_with_matches() {
189 let f = TestFixture::new();
190 f.mk_bin("a/bin_0", "").unwrap();
191 f.mk_bin("b/bin_1", "").unwrap();
192 let re = Regex::new(r"bin_\d").unwrap();
193
194 let result: Vec<PathBuf> = which::which_re_in(re, Some(f.paths)).unwrap().collect();
195
196 let temp = f.tempdir;
197
198 assert_eq!(
199 result,
200 vec![temp.path().join("a/bin_0"), temp.path().join("b/bin_1")]
201 )
202 }
203
204 #[test]
205 #[cfg(all(unix, feature = "regex"))]
206 fn test_which_re_in_without_matches() {
207 let f = TestFixture::new();
208 let re = Regex::new(r"bi[^n]").unwrap();
209
210 let result: Vec<PathBuf> = which::which_re_in(re, Some(f.paths)).unwrap().collect();
211
212 assert_eq!(result, Vec::<PathBuf>::new())
213 }
214
215 #[test]
216 #[cfg(all(unix, feature = "regex"))]
217 fn test_which_re_accepts_owned_and_borrow() {
218 which::which_re(Regex::new(r".").unwrap())
219 .unwrap()
220 .for_each(drop);
221 which::which_re(&Regex::new(r".").unwrap())
222 .unwrap()
223 .for_each(drop);
224 which::which_re_in(Regex::new(r".").unwrap(), Some("pth"))
225 .unwrap()
226 .for_each(drop);
227 which::which_re_in(&Regex::new(r".").unwrap(), Some("pth"))
228 .unwrap()
229 .for_each(drop);
230 }
231
232 #[test]
233 #[cfg(unix)]
234 fn test_which_extension() {
235 let f = TestFixture::new();
236 let b = Path::new(&BIN_NAME).with_extension("");
237 assert_eq!(_which(&f, b).unwrap(), f.bins[0])
238 }
239
240 #[test]
241 #[cfg(windows)]
242 fn test_which_extension() {
243 let f = TestFixture::new();
244 let b = Path::new(&BIN_NAME).with_extension("cmd");
245 assert_eq!(_which(&f, b).unwrap(), f.bins[2])
246 }
247
248 #[test]
249 #[cfg(windows)]
250 fn test_which_no_extension() {
251 let f = TestFixture::new();
252 let b = Path::new("win-bin");
253 let which_result = which::which_in(b, Some(&f.paths), ".").unwrap();
254 // Make sure the extension is the correct case.
255 assert_eq!(which_result.extension(), f.bins[9].extension());
256 assert_eq!(fs::canonicalize(&which_result).unwrap(), f.bins[9])
257 }
258
259 #[test]
260 fn test_which_not_found() {
261 let f = TestFixture::new();
262 assert!(_which(&f, "a").is_err());
263 }
264
265 #[test]
266 fn test_which_second() {
267 let f = TestFixture::new();
268 let b = f.mk_bin("b/another", env::consts::EXE_EXTENSION).unwrap();
269 assert_eq!(_which(&f, "another").unwrap(), b);
270 }
271
272 #[test]
273 fn test_which_all() {
274 let f = TestFixture::new();
275 let actual = _which_all(&f, BIN_NAME)
276 .unwrap()
277 .map(|c| c.unwrap())
278 .collect::<Vec<_>>();
279 let mut expected = f
280 .bins
281 .iter()
282 .map(|p| p.canonicalize().unwrap())
283 .collect::<Vec<_>>();
284 #[cfg(windows)]
285 {
286 expected.retain(|p| p.file_stem().unwrap() == BIN_NAME);
287 expected.retain(|p| p.extension().map(|ext| ext == "exe" || ext == "cmd") == Some(true));
288 }
289 #[cfg(not(windows))]
290 {
291 expected.retain(|p| p.file_name().unwrap() == BIN_NAME);
292 }
293 assert_eq!(actual, expected);
294 }
295
296 #[test]
297 #[cfg(unix)]
298 fn test_which_absolute() {
299 let f = TestFixture::new();
300 assert_eq!(
301 _which(&f, &f.bins[3]).unwrap(),
302 f.bins[3].canonicalize().unwrap()
303 );
304 }
305
306 #[test]
307 #[cfg(windows)]
308 fn test_which_absolute() {
309 let f = TestFixture::new();
310 assert_eq!(
311 _which(&f, &f.bins[4]).unwrap(),
312 f.bins[4].canonicalize().unwrap()
313 );
314 }
315
316 #[test]
317 #[cfg(windows)]
318 fn test_which_absolute_path_case() {
319 // Test that an absolute path with an uppercase extension
320 // is accepted.
321 let f = TestFixture::new();
322 let p = &f.bins[4];
323 assert_eq!(_which(&f, p).unwrap(), f.bins[4].canonicalize().unwrap());
324 }
325
326 #[test]
327 #[cfg(unix)]
328 fn test_which_absolute_extension() {
329 let f = TestFixture::new();
330 // Don't append EXE_EXTENSION here.
331 let b = f.bins[3].parent().unwrap().join(BIN_NAME);
332 assert_eq!(_which(&f, b).unwrap(), f.bins[3].canonicalize().unwrap());
333 }
334
335 #[test]
336 #[cfg(windows)]
337 fn test_which_absolute_extension() {
338 let f = TestFixture::new();
339 // Don't append EXE_EXTENSION here.
340 let b = f.bins[4].parent().unwrap().join(BIN_NAME);
341 assert_eq!(_which(&f, b).unwrap(), f.bins[4].canonicalize().unwrap());
342 }
343
344 #[test]
345 #[cfg(unix)]
346 fn test_which_relative() {
347 let f = TestFixture::new();
348 assert_eq!(
349 _which(&f, "b/bin").unwrap(),
350 f.bins[3].canonicalize().unwrap()
351 );
352 }
353
354 #[test]
355 #[cfg(windows)]
356 fn test_which_relative() {
357 let f = TestFixture::new();
358 assert_eq!(
359 _which(&f, "b/bin").unwrap(),
360 f.bins[4].canonicalize().unwrap()
361 );
362 }
363
364 #[test]
365 #[cfg(unix)]
366 fn test_which_relative_extension() {
367 // test_which_relative tests a relative path without an extension,
368 // so test a relative path with an extension here.
369 let f = TestFixture::new();
370 let b = Path::new("b/bin").with_extension(env::consts::EXE_EXTENSION);
371 assert_eq!(_which(&f, b).unwrap(), f.bins[3].canonicalize().unwrap());
372 }
373
374 #[test]
375 #[cfg(windows)]
376 fn test_which_relative_extension() {
377 // test_which_relative tests a relative path without an extension,
378 // so test a relative path with an extension here.
379 let f = TestFixture::new();
380 let b = Path::new("b/bin").with_extension("cmd");
381 assert_eq!(_which(&f, b).unwrap(), f.bins[5].canonicalize().unwrap());
382 }
383
384 #[test]
385 #[cfg(windows)]
386 fn test_which_relative_extension_case() {
387 // Test that a relative path with an uppercase extension
388 // is accepted.
389 let f = TestFixture::new();
390 let b = Path::new("b/bin").with_extension("EXE");
391 assert_eq!(_which(&f, b).unwrap(), f.bins[4].canonicalize().unwrap());
392 }
393
394 #[test]
395 #[cfg(unix)]
396 fn test_which_relative_leading_dot() {
397 let f = TestFixture::new();
398 assert_eq!(
399 _which(&f, "./b/bin").unwrap(),
400 f.bins[3].canonicalize().unwrap()
401 );
402 }
403
404 #[test]
405 #[cfg(windows)]
406 fn test_which_relative_leading_dot() {
407 let f = TestFixture::new();
408 assert_eq!(
409 _which(&f, "./b/bin").unwrap(),
410 f.bins[4].canonicalize().unwrap()
411 );
412 }
413
414 #[test]
415 #[cfg(unix)]
416 fn test_which_non_executable() {
417 // Shouldn't return non-executable files.
418 let f = TestFixture::new();
419 f.touch("b/another", "").unwrap();
420 assert!(_which(&f, "another").is_err());
421 }
422
423 #[test]
424 #[cfg(unix)]
425 fn test_which_absolute_non_executable() {
426 // Shouldn't return non-executable files, even if given an absolute path.
427 let f = TestFixture::new();
428 let b = f.touch("b/another", "").unwrap();
429 assert!(_which(&f, b).is_err());
430 }
431
432 #[test]
433 #[cfg(unix)]
434 fn test_which_relative_non_executable() {
435 // Shouldn't return non-executable files.
436 let f = TestFixture::new();
437 f.touch("b/another", "").unwrap();
438 assert!(_which(&f, "b/another").is_err());
439 }
440
441 #[test]
442 fn test_failure() {
443 let f = TestFixture::new();
444
445 let run = || -> which::Result<PathBuf> {
446 let p = _which(&f, "./b/bin")?;
447 Ok(p.into_path_buf())
448 };
449
450 let _ = run();
451 }