1use nix::errno::Errno;
2use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify};
3use std::ffi::OsString;
4use std::fs::{rename, File};
5
6#[test]
7pub fn test_inotify() {
8    let instance = Inotify::init(InitFlags::IN_NONBLOCK).unwrap();
9    let tempdir = tempfile::tempdir().unwrap();
10
11    instance
12        .add_watch(tempdir.path(), AddWatchFlags::IN_ALL_EVENTS)
13        .unwrap();
14
15    let events = instance.read_events();
16    assert_eq!(events.unwrap_err(), Errno::EAGAIN);
17
18    File::create(tempdir.path().join("test")).unwrap();
19
20    let events = instance.read_events().unwrap();
21    assert_eq!(events[0].name, Some(OsString::from("test")));
22}
23
24#[test]
25pub fn test_inotify_multi_events() {
26    let instance = Inotify::init(InitFlags::IN_NONBLOCK).unwrap();
27    let tempdir = tempfile::tempdir().unwrap();
28
29    instance
30        .add_watch(tempdir.path(), AddWatchFlags::IN_ALL_EVENTS)
31        .unwrap();
32
33    let events = instance.read_events();
34    assert_eq!(events.unwrap_err(), Errno::EAGAIN);
35
36    File::create(tempdir.path().join("test")).unwrap();
37    rename(tempdir.path().join("test"), tempdir.path().join("test2")).unwrap();
38
39    // Now there should be 5 events in queue:
40    //   - IN_CREATE on test
41    //   - IN_OPEN on test
42    //   - IN_CLOSE_WRITE on test
43    //   - IN_MOVED_FROM on test with a cookie
44    //   - IN_MOVED_TO on test2 with the same cookie
45
46    let events = instance.read_events().unwrap();
47    assert_eq!(events.len(), 5);
48
49    assert_eq!(events[0].mask, AddWatchFlags::IN_CREATE);
50    assert_eq!(events[0].name, Some(OsString::from("test")));
51
52    assert_eq!(events[1].mask, AddWatchFlags::IN_OPEN);
53    assert_eq!(events[1].name, Some(OsString::from("test")));
54
55    assert_eq!(events[2].mask, AddWatchFlags::IN_CLOSE_WRITE);
56    assert_eq!(events[2].name, Some(OsString::from("test")));
57
58    assert_eq!(events[3].mask, AddWatchFlags::IN_MOVED_FROM);
59    assert_eq!(events[3].name, Some(OsString::from("test")));
60
61    assert_eq!(events[4].mask, AddWatchFlags::IN_MOVED_TO);
62    assert_eq!(events[4].name, Some(OsString::from("test2")));
63
64    assert_eq!(events[3].cookie, events[4].cookie);
65}
66