1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
use fd_lock::RwLock;
use std::fs::File;
use std::io::ErrorKind;
use tempfile::tempdir;
#[test]
fn double_read_lock() {
let dir = tempdir().unwrap();
let path = dir.path().join("lockfile");
let l0 = RwLock::new(File::create(&path).unwrap());
let l1 = RwLock::new(File::open(path).unwrap());
let _g0 = l0.try_read().unwrap();
let _g1 = l1.try_read().unwrap();
}
#[test]
fn double_write_lock() {
let dir = tempdir().unwrap();
let path = dir.path().join("lockfile");
let mut l0 = RwLock::new(File::create(&path).unwrap());
let mut l1 = RwLock::new(File::open(path).unwrap());
let g0 = l0.try_write().unwrap();
let err = l1.try_write().unwrap_err();
assert!(matches!(err.kind(), ErrorKind::WouldBlock));
drop(g0);
}
#[test]
fn read_and_write_lock() {
let dir = tempdir().unwrap();
let path = dir.path().join("lockfile");
let l0 = RwLock::new(File::create(&path).unwrap());
let mut l1 = RwLock::new(File::open(path).unwrap());
let g0 = l0.try_read().unwrap();
let err = l1.try_write().unwrap_err();
assert!(matches!(err.kind(), ErrorKind::WouldBlock));
drop(g0);
}
#[test]
fn write_and_read_lock() {
let dir = tempdir().unwrap();
let path = dir.path().join("lockfile");
let mut l0 = RwLock::new(File::create(&path).unwrap());
let l1 = RwLock::new(File::open(path).unwrap());
let g0 = l0.try_write().unwrap();
let err = l1.try_read().unwrap_err();
assert!(matches!(err.kind(), ErrorKind::WouldBlock));
drop(g0);
}
#[cfg(windows)]
mod windows {
use super::*;
use std::os::windows::fs::OpenOptionsExt;
#[test]
fn try_lock_error() {
let dir = tempdir().unwrap();
let path = dir.path().join("lockfile");
// On Windows, opening with an access_mode as 0 will prevent all locking operations from succeeding, simulating an I/O error.
let mut l0 = RwLock::new(
File::options()
.create(true)
.read(true)
.write(true)
.access_mode(0)
.open(path)
.unwrap(),
);
let err1 = l0.try_read().unwrap_err();
assert!(matches!(err1.kind(), ErrorKind::PermissionDenied));
let err2 = l0.try_write().unwrap_err();
assert!(matches!(err2.kind(), ErrorKind::PermissionDenied));
}
}
|