Debian Codegraph @

debian/rust-vendor/inotify/tests/main.rs

raw
1 #![deny(warnings)]
2
3 // This test suite is incomplete and doesn't cover all available functionality.
4 // Contributions to improve test coverage would be highly appreciated!
5
6 #[cfg(feature = "stream")]
7 use inotify::StreamExt;
8 use inotify::{EventMask, Inotify, WatchMask};
9 use std::fs::File;
10 use std::io::{ErrorKind, Write};
11 #[cfg(feature = "stream")]
12 use std::mem;
13 use std::os::fd::AsFd;
14 use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
15 use std::path::PathBuf;
16 use tempfile::TempDir;
17
18 #[cfg(feature = "stream")]
19 use futures_util::FutureExt;
20 #[cfg(feature = "stream")]
21 use maplit::hashmap;
22 #[cfg(feature = "stream")]
23 use rand::{prelude::SliceRandom, thread_rng};
24 #[cfg(feature = "stream")]
25 use std::sync::{Arc, Mutex};
26
27 #[test]
28 fn it_should_watch_a_file() {
29 let mut testdir = TestDir::new();
30 let (path, mut file) = testdir.new_file();
31
32 let mut inotify = Inotify::init().unwrap();
33 let watch = inotify.watches().add(&path, WatchMask::MODIFY).unwrap();
34
35 write_to(&mut file);
36
37 let mut buffer = [0; 1024];
38 let events = inotify.read_events_blocking(&mut buffer).unwrap();
39
40 let mut num_events = 0;
41 for event in events {
42 assert_eq!(watch, event.wd);
43 num_events += 1;
44 }
45 assert!(num_events > 0);
46 }
47
48 #[cfg(feature = "stream")]
49 #[tokio::test]
50 async fn it_should_watch_a_file_async() {
51 let mut testdir = TestDir::new();
52 let (path, mut file) = testdir.new_file();
53
54 let inotify = Inotify::init().unwrap();
55
56 // Hold ownership of `watches` for this test, so that the underlying file descriptor has
57 // at least one reference to keep it alive, and we can inspect the WatchDescriptors below.
58 // Otherwise the `Weak<FdGuard>` contained in the WatchDescriptors will be invalidated
59 // when `inotify` is consumed by `into_event_stream()` and the EventStream is dropped
60 // during `await`.
61 let mut watches = inotify.watches();
62
63 let watch = watches.add(&path, WatchMask::MODIFY).unwrap();
64
65 write_to(&mut file);
66
67 let mut buffer = [0; 1024];
68
69 let events = inotify
70 .into_event_stream(&mut buffer[..])
71 .unwrap()
72 .take(1)
73 .collect::<Vec<_>>()
74 .await;
75
76 let mut num_events = 0;
77 for event in events.into_iter().flatten() {
78 assert_eq!(watch, event.wd);
79 num_events += 1;
80 }
81 assert!(num_events > 0);
82 }
83
84 #[cfg(feature = "stream")]
85 #[tokio::test]
86 async fn it_should_watch_a_file_from_eventstream_watches() {
87 let mut testdir = TestDir::new();
88 let (path, mut file) = testdir.new_file();
89
90 let inotify = Inotify::init().unwrap();
91
92 let mut buffer = [0; 1024];
93
94 let stream = inotify.into_event_stream(&mut buffer[..]).unwrap();
95
96 // Hold ownership of `watches` for this test, so that the underlying file descriptor has
97 // at least one reference to keep it alive, and we can inspect the WatchDescriptors below.
98 // Otherwise the `Weak<FdGuard>` contained in the WatchDescriptors will be invalidated
99 // when `stream` is dropped during `await`.
100 let mut watches = stream.watches();
101
102 let watch = watches.add(&path, WatchMask::MODIFY).unwrap();
103 write_to(&mut file);
104
105 let events = stream.take(1).collect::<Vec<_>>().await;
106
107 let mut num_events = 0;
108 for event in events.into_iter().flatten() {
109 assert_eq!(watch, event.wd);
110 num_events += 1;
111 }
112 assert!(num_events > 0);
113 }
114
115 #[cfg(feature = "stream")]
116 #[tokio::test]
117 async fn it_should_watch_a_file_after_converting_back_from_eventstream() {
118 let mut testdir = TestDir::new();
119 let (path, mut file) = testdir.new_file();
120
121 let inotify = Inotify::init().unwrap();
122
123 let mut buffer = [0; 1024];
124 let stream = inotify.into_event_stream(&mut buffer[..]).unwrap();
125 let mut inotify = stream.into_inotify();
126
127 let watch = inotify.watches().add(&path, WatchMask::MODIFY).unwrap();
128
129 write_to(&mut file);
130
131 let events = inotify.read_events_blocking(&mut buffer).unwrap();
132
133 let mut num_events = 0;
134 for event in events {
135 assert_eq!(watch, event.wd);
136 num_events += 1;
137 }
138 assert!(num_events > 0);
139 }
140
141 #[test]
142 fn it_should_return_immediately_if_no_events_are_available() {
143 let mut inotify = Inotify::init().unwrap();
144
145 let mut buffer = [0; 1024];
146 assert_eq!(
147 inotify.read_events(&mut buffer).unwrap_err().kind(),
148 ErrorKind::WouldBlock
149 );
150 }
151
152 #[test]
153 fn it_should_convert_the_name_into_an_os_str() {
154 let mut testdir = TestDir::new();
155 let (path, mut file) = testdir.new_file();
156
157 let mut inotify = Inotify::init().unwrap();
158 inotify
159 .watches()
160 .add(path.parent().unwrap(), WatchMask::MODIFY)
161 .unwrap();
162
163 write_to(&mut file);
164
165 let mut buffer = [0; 1024];
166 let mut events = inotify.read_events_blocking(&mut buffer).unwrap();
167
168 if let Some(event) = events.next() {
169 assert_eq!(path.file_name(), event.name);
170 } else {
171 panic!("Expected inotify event");
172 }
173 }
174
175 #[test]
176 fn it_should_set_name_to_none_if_it_is_empty() {
177 let mut testdir = TestDir::new();
178 let (path, mut file) = testdir.new_file();
179
180 let mut inotify = Inotify::init().unwrap();
181 inotify.watches().add(&path, WatchMask::MODIFY).unwrap();
182
183 write_to(&mut file);
184
185 let mut buffer = [0; 1024];
186 let mut events = inotify.read_events_blocking(&mut buffer).unwrap();
187
188 if let Some(event) = events.next() {
189 assert_eq!(event.name, None);
190 } else {
191 panic!("Expected inotify event");
192 }
193 }
194
195 #[test]
196 fn it_should_not_accept_watchdescriptors_from_other_instances() {
197 let mut testdir = TestDir::new();
198 let (path, _) = testdir.new_file();
199
200 let inotify = Inotify::init().unwrap();
201 let _ = inotify.watches().add(&path, WatchMask::ACCESS).unwrap();
202
203 let second_inotify = Inotify::init().unwrap();
204 let wd2 = second_inotify
205 .watches()
206 .add(&path, WatchMask::ACCESS)
207 .unwrap();
208
209 assert_eq!(
210 inotify.watches().remove(wd2).unwrap_err().kind(),
211 ErrorKind::InvalidInput
212 );
213 }
214
215 #[test]
216 fn watch_descriptors_from_different_inotify_instances_should_not_be_equal() {
217 let mut testdir = TestDir::new();
218 let (path, _) = testdir.new_file();
219
220 let inotify_1 = Inotify::init().unwrap();
221 let inotify_2 = Inotify::init().unwrap();
222
223 let wd_1 = inotify_1.watches().add(&path, WatchMask::ACCESS).unwrap();
224 let wd_2 = inotify_2.watches().add(&path, WatchMask::ACCESS).unwrap();
225
226 // As far as inotify is concerned, watch descriptors are just integers that
227 // are scoped per inotify instance. This means that multiple instances will
228 // produce the same watch descriptor number, a case we want inotify-rs to
229 // detect.
230 assert!(wd_1 != wd_2);
231 }
232
233 #[test]
234 fn watch_descriptor_equality_should_not_be_confused_by_reused_fds() {
235 let mut testdir = TestDir::new();
236 let (path, _) = testdir.new_file();
237
238 // When a new inotify instance is created directly after closing another
239 // one, it is possible that the file descriptor is reused immediately, and
240 // we end up with a new instance that has the same file descriptor as the
241 // old one.
242 // This is quite likely, but it doesn't happen every time. Therefore we may
243 // need a few tries until we find two instances where that is the case.
244 let (wd_1, inotify_2) = loop {
245 let inotify_1 = Inotify::init().unwrap();
246
247 let wd_1 = inotify_1.watches().add(&path, WatchMask::ACCESS).unwrap();
248 let fd_1 = inotify_1.as_raw_fd();
249
250 inotify_1.close().unwrap();
251 let inotify_2 = Inotify::init().unwrap();
252
253 if fd_1 == inotify_2.as_raw_fd() {
254 break (wd_1, inotify_2);
255 }
256 };
257
258 let wd_2 = inotify_2.watches().add(&path, WatchMask::ACCESS).unwrap();
259
260 // The way we engineered this situation, both `WatchDescriptor` instances
261 // have the same fields. They still come from different inotify instances
262 // though, so they shouldn't be equal.
263 assert!(wd_1 != wd_2);
264
265 inotify_2.close().unwrap();
266
267 // A little extra gotcha: If both inotify instances are closed, and the `Eq`
268 // implementation naively compares the weak pointers, both will be `None`,
269 // making them equal. Let's make sure this isn't the case.
270 assert!(wd_1 != wd_2);
271 }
272
273 #[test]
274 fn it_should_implement_raw_fd_traits_correctly() {
275 let fd = Inotify::init()
276 .expect("Failed to initialize inotify instance")
277 .into_raw_fd();
278
279 // If `IntoRawFd` has been implemented naively, `Inotify`'s `Drop`
280 // implementation will have closed the inotify instance at this point. Let's
281 // make sure this didn't happen.
282 let mut inotify = unsafe { <Inotify as FromRawFd>::from_raw_fd(fd) };
283
284 let mut buffer = [0; 1024];
285 if let Err(error) = inotify.read_events(&mut buffer) {
286 if error.kind() != ErrorKind::WouldBlock {
287 panic!("Failed to add watch: {}", error);
288 }
289 }
290 }
291
292 #[test]
293 fn it_should_watch_correctly_with_a_watches_clone() {
294 let mut testdir = TestDir::new();
295 let (path, mut file) = testdir.new_file();
296
297 let mut inotify = Inotify::init().unwrap();
298 let mut watches1 = inotify.watches();
299 let mut watches2 = watches1.clone();
300 let watch1 = watches1.add(&path, WatchMask::MODIFY).unwrap();
301 let watch2 = watches2.add(&path, WatchMask::MODIFY).unwrap();
302
303 // same path and same Inotify should return same descriptor
304 assert_eq!(watch1, watch2);
305
306 write_to(&mut file);
307
308 let mut buffer = [0; 1024];
309 let events = inotify.read_events_blocking(&mut buffer).unwrap();
310
311 let mut num_events = 0;
312 for event in events {
313 assert_eq!(watch2, event.wd);
314 num_events += 1;
315 }
316 assert!(num_events > 0);
317 }
318
319 #[test]
320 fn watch_descriptor_equality_should_work_for_multiple_fds_of_same_instance() {
321 let mut testdir = TestDir::new();
322 let (path, _) = testdir.new_file();
323 let inotify = Inotify::init().unwrap();
324 // Clone the fd of the inotify instance to create a second reference to the same instance
325 let second_inotify_reference = Inotify::from(
326 inotify
327 .as_fd()
328 .try_clone_to_owned()
329 .expect("failed to clone fd of inotify"),
330 );
331 // Since both descriptors point to the same inotify instance, attempting to add a watch twice
332 // should return the same watch descriptor
333 let first_watch = inotify.watches().add(&path, WatchMask::MODIFY).unwrap();
334 let second_watch = second_inotify_reference
335 .watches()
336 .add(&path, WatchMask::MODIFY)
337 .unwrap();
338 assert_eq!(
339 first_watch, second_watch,
340 "first and second watch descriptors should be equal"
341 );
342 }
343
344 #[cfg(feature = "stream")]
345 #[tokio::test]
346 /// Testing if two files with the same name but different directories
347 /// (e.g. "file_a" and "another_dir/file_a") are distinguished when _randomly_
348 /// triggering a DELETE_SELF for the two files.
349 async fn it_should_distinguish_event_for_files_with_same_name() {
350 let mut testdir = TestDir::new();
351 let testdir_path = testdir.dir.path().to_owned();
352 let file_order = Arc::new(Mutex::new(vec!["file_a", "another_dir/file_a"]));
353 file_order.lock().unwrap().shuffle(&mut thread_rng());
354 let file_order_clone = file_order.clone();
355
356 let inotify = Inotify::init().expect("Failed to initialize inotify instance");
357
358 // creating file_a inside `TestDir.dir`
359 let (path_1, _) = testdir.new_file_with_name("file_a");
360 // creating a directory inside `TestDir.dir`
361 testdir.new_directory_with_name("another_dir");
362 // creating a file inside `TestDir.dir/another_dir`
363 let (path_2, _) = testdir.new_file_in_directory_with_name("another_dir", "file_a");
364
365 // watching both files for `DELETE_SELF`
366 let wd_1 = inotify
367 .watches()
368 .add(&path_1, WatchMask::DELETE_SELF)
369 .unwrap();
370 let wd_2 = inotify
371 .watches()
372 .add(&path_2, WatchMask::DELETE_SELF)
373 .unwrap();
374
375 let expected_ids = hashmap! {
376 wd_1.get_watch_descriptor_id() => "file_a",
377 wd_2.get_watch_descriptor_id() => "another_dir/file_a"
378 };
379 let mut buffer = [0; 1024];
380
381 let file_removal_handler = tokio::spawn(async move {
382 for file in file_order.lock().unwrap().iter() {
383 testdir.delete_file(file);
384 }
385 });
386
387 let event_handle = tokio::spawn(async move {
388 let mut events = inotify.into_event_stream(&mut buffer).unwrap();
389 while let Some(Ok(event)) = events.next().await {
390 if event.mask == EventMask::DELETE_SELF {
391 let id = event.wd.get_watch_descriptor_id();
392 let file = expected_ids.get(&id).unwrap();
393 let full_path = testdir_path.join(*file);
394 println!("file {:?} was deleted", full_path);
395 file_order_clone.lock().unwrap().retain(|&x| x != *file);
396
397 if file_order_clone.lock().unwrap().is_empty() {
398 break;
399 }
400 }
401 }
402 });
403
404 let () = event_handle.await.unwrap();
405 let () = file_removal_handler.await.unwrap();
406 }
407
408 #[cfg(feature = "stream")]
409 #[tokio::test]
410 async fn it_should_yield_all_events_with_small_buffer() {
411 let testdir = TestDir::new();
412 let dir_path = testdir.dir.path().to_owned();
413
414 let inotify = Inotify::init().expect("Failed to initialize inotify instance");
415
416 inotify
417 .watches()
418 .add(&dir_path, WatchMask::CREATE)
419 .expect("Failed to add watch");
420
421 let num_files = 3usize;
422 for i in 0..num_files {
423 let file_path = dir_path.join(format!("{}", i));
424 File::create(&file_path).expect("Failed to create file");
425 }
426
427 let event_struct_size = mem::size_of::<inotify_sys::inotify_event>();
428 let name_len_padded = 4; // "0\0" padded to 4-byte alignment
429 let single_event_size = event_struct_size + name_len_padded;
430
431 // Use a buffer that can fit exactly one event but not two.
432 let buffer_size = single_event_size + (single_event_size - 1); // 20 + 19 = 39 bytes
433 let mut buffer = vec![0u8; buffer_size];
434 let mut stream = inotify.into_event_stream(&mut buffer[..]).unwrap();
435
436 // Await one event to ensure that everything has settled.
437 let first_event = stream.next().await.unwrap().unwrap();
438 assert!(first_event.mask.contains(EventMask::CREATE));
439
440 // Each call should yield one event since the buffer only fits one.
441 let mut events = vec![first_event];
442 while let Some(result) = stream.next().now_or_never() {
443 match result {
444 Some(Ok(event)) => {
445 assert!(event.mask.contains(EventMask::CREATE));
446 events.push(event);
447 }
448 Some(Err(e)) => panic!("Error reading event: {}", e),
449 None => break, // Stream ended
450 }
451 }
452
453 assert_eq!(
454 events.len(),
455 num_files,
456 "All events should yield with now_or_never"
457 );
458 }
459
460 struct TestDir {
461 dir: TempDir,
462 counter: u32,
463 }
464
465 impl TestDir {
466 fn new() -> TestDir {
467 TestDir {
468 dir: TempDir::new().unwrap(),
469 counter: 0,
470 }
471 }
472
473 #[cfg(feature = "stream")]
474 fn new_file_with_name(&mut self, file_name: &str) -> (PathBuf, File) {
475 self.counter += 1;
476
477 let path = self.dir.path().join(file_name);
478 let file = File::create(&path)
479 .unwrap_or_else(|error| panic!("Failed to create temporary file: {}", error));
480
481 (path, file)
482 }
483
484 #[cfg(feature = "stream")]
485 fn delete_file(&mut self, relative_path_to_file: &str) {
486 let path = &self.dir.path().join(relative_path_to_file);
487 std::fs::remove_file(path).unwrap();
488 }
489
490 #[cfg(feature = "stream")]
491 fn new_file_in_directory_with_name(
492 &mut self,
493 dir_name: &str,
494 file_name: &str,
495 ) -> (PathBuf, File) {
496 self.counter += 1;
497
498 let path = self.dir.path().join(dir_name).join(file_name);
499 let file = File::create(&path)
500 .unwrap_or_else(|error| panic!("Failed to create temporary file: {}", error));
501
502 (path, file)
503 }
504
505 #[cfg(feature = "stream")]
506 fn new_directory_with_name(&mut self, dir_name: &str) -> PathBuf {
507 let path = self.dir.path().join(dir_name);
508 let () = std::fs::create_dir(&path).unwrap();
509 path.to_path_buf()
510 }
511
512 fn new_file(&mut self) -> (PathBuf, File) {
513 let id = self.counter;
514 self.counter += 1;
515
516 let path = self.dir.path().join("file-".to_string() + &id.to_string());
517 let file = File::create(&path)
518 .unwrap_or_else(|error| panic!("Failed to create temporary file: {}", error));
519
520 (path, file)
521 }
522 }
523
524 #[test]
525 fn it_should_receive_delete_event_when_file_is_deleted() {
526 let mut testdir = TestDir::new();
527 let (path, _file) = testdir.new_file();
528
529 let mut inotify = Inotify::init().unwrap();
530 let _watch = inotify
531 .watches()
532 .add(path.parent().unwrap(), WatchMask::DELETE)
533 .unwrap();
534
535 std::fs::remove_file(&path).unwrap();
536
537 let mut buffer = [0; 1024];
538 let mut events = inotify.read_events_blocking(&mut buffer).unwrap();
539 match events.next() {
540 Some(event) => assert_eq!(event.mask, EventMask::DELETE),
541 None => panic!("Expected event, got none."),
542 }
543 }
544
545 #[test]
546 fn it_should_receive_delete_event_watchee_is_deleted() {
547 let testdir = TestDir::new();
548 let path = testdir.dir.path();
549
550 let mut inotify = Inotify::init().unwrap();
551 let _watch = inotify.watches().add(path, WatchMask::DELETE_SELF).unwrap();
552
553 std::fs::remove_dir(path).unwrap();
554
555 let mut buffer = [0; 1024];
556 let mut events = inotify.read_events_blocking(&mut buffer).unwrap();
557 match events.next() {
558 Some(event) => assert!(event.mask.contains(EventMask::DELETE_SELF)),
559 None => panic!("Expected event, got none."),
560 }
561 }
562
563 #[cfg(feature = "stream")]
564 #[tokio::test]
565 async fn it_should_receive_delete_event_when_file_is_deleted_async() {
566 use std::time::Duration;
567 use tokio::time::timeout;
568
569 let mut testdir = TestDir::new();
570 let (path, _file) = testdir.new_file();
571
572 let inotify = Inotify::init().unwrap();
573 // Watch the parent directory, not the file itself, to receive DELETE events
574 let _watch = inotify
575 .watches()
576 .add(path.parent().unwrap(), WatchMask::DELETE)
577 .unwrap();
578
579 let mut buffer = [0; 1024];
580 let mut stream = inotify.into_event_stream(&mut buffer).unwrap();
581
582 std::fs::remove_file(&path).unwrap();
583
584 let event = timeout(Duration::from_secs(2), stream.next())
585 .await
586 .unwrap() // Timeout
587 .unwrap() // End of stream
588 .unwrap(); // Stream error
589 assert_eq!(event.mask, EventMask::DELETE);
590 }
591
592 fn write_to(file: &mut File) {
593 file.write_all(b"This should trigger an inotify event.")
594 .unwrap_or_else(|error| panic!("Failed to write to file: {}", error));
595 }