• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use nix::dir::{Dir, Type};
2 use nix::fcntl::OFlag;
3 use nix::sys::stat::Mode;
4 use std::fs::File;
5 use tempfile::tempdir;
6 
7 
8 #[cfg(test)]
flags() -> OFlag9 fn flags() -> OFlag {
10     #[cfg(target_os = "illumos")]
11     let f = OFlag::O_RDONLY | OFlag::O_CLOEXEC;
12 
13     #[cfg(not(target_os = "illumos"))]
14     let f = OFlag::O_RDONLY | OFlag::O_CLOEXEC | OFlag::O_DIRECTORY;
15 
16     f
17 }
18 
19 #[test]
20 #[allow(clippy::unnecessary_sort_by)]   // False positive
read()21 fn read() {
22     let tmp = tempdir().unwrap();
23     File::create(&tmp.path().join("foo")).unwrap();
24     ::std::os::unix::fs::symlink("foo", tmp.path().join("bar")).unwrap();
25     let mut dir = Dir::open(tmp.path(), flags(), Mode::empty()).unwrap();
26     let mut entries: Vec<_> = dir.iter().map(|e| e.unwrap()).collect();
27     entries.sort_by(|a, b| a.file_name().cmp(b.file_name()));
28     let entry_names: Vec<_> = entries
29         .iter()
30         .map(|e| e.file_name().to_str().unwrap().to_owned())
31         .collect();
32     assert_eq!(&entry_names[..], &[".", "..", "bar", "foo"]);
33 
34     // Check file types. The system is allowed to return DT_UNKNOWN (aka None here) but if it does
35     // return a type, ensure it's correct.
36     assert!(&[Some(Type::Directory), None].contains(&entries[0].file_type())); // .: dir
37     assert!(&[Some(Type::Directory), None].contains(&entries[1].file_type())); // ..: dir
38     assert!(&[Some(Type::Symlink), None].contains(&entries[2].file_type())); // bar: symlink
39     assert!(&[Some(Type::File), None].contains(&entries[3].file_type())); // foo: regular file
40 }
41 
42 #[test]
rewind()43 fn rewind() {
44     let tmp = tempdir().unwrap();
45     let mut dir = Dir::open(tmp.path(), flags(), Mode::empty()).unwrap();
46     let entries1: Vec<_> = dir.iter().map(|e| e.unwrap().file_name().to_owned()).collect();
47     let entries2: Vec<_> = dir.iter().map(|e| e.unwrap().file_name().to_owned()).collect();
48     let entries3: Vec<_> = dir.into_iter().map(|e| e.unwrap().file_name().to_owned()).collect();
49     assert_eq!(entries1, entries2);
50     assert_eq!(entries2, entries3);
51 }
52 
53 #[test]
ebadf()54 fn ebadf() {
55     assert_eq!(Dir::from_fd(-1).unwrap_err(), nix::Error::EBADF);
56 }
57