use std::ffi::OsString;
use std::path::{Path, PathBuf};
use wtf_string::Wtf16String;
use super::{DirectoryHandle, OpenFailure, VolumeIdentity};
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("clock")
.as_nanos();
let path = std::env::temp_dir().join(format!(
"windows-file-watcher-{label}-{}-{nonce}",
std::process::id()
));
std::fs::create_dir(&path).expect("create temp dir");
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
fn cleanup(self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[test]
fn opens_a_plain_directory() {
let dir = TempDir::new("open-plain");
assert!(DirectoryHandle::open(dir.path()).is_ok());
dir.cleanup();
}
#[test]
fn opens_the_system_temp_directory() {
assert!(DirectoryHandle::open(&std::env::temp_dir()).is_ok());
}
#[test]
fn opens_the_current_directory_by_relative_path() {
assert!(
DirectoryHandle::open(Path::new(".")).is_ok(),
"a relative path must be accepted; Win32 resolves it"
);
}
#[test]
fn opens_a_nested_directory() {
let dir = TempDir::new("open-nested");
let nested = dir.path().join("a").join("b");
std::fs::create_dir_all(&nested).expect("create nested");
assert!(DirectoryHandle::open(&nested).is_ok());
dir.cleanup();
}
#[test]
fn opens_a_directory_whose_name_is_not_ascii() {
let dir = TempDir::new("open-unicode");
let child = dir.path().join("caf\u{e9}-\u{1f600}-\u{10437}");
std::fs::create_dir(&child).expect("create unicode-named dir");
assert!(DirectoryHandle::open(&child).is_ok());
dir.cleanup();
}
#[test]
fn opens_a_directory_with_a_trailing_separator() {
let dir = TempDir::new("open-trailing");
let mut with_sep = dir.path().as_os_str().to_os_string();
with_sep.push("\\");
assert!(DirectoryHandle::open(Path::new(&with_sep)).is_ok());
dir.cleanup();
}
#[test]
fn opens_a_directory_containing_files() {
let dir = TempDir::new("open-populated");
for index in 0..8 {
std::fs::write(dir.path().join(format!("file-{index}.txt")), b"x").expect("write");
}
assert!(DirectoryHandle::open(dir.path()).is_ok());
dir.cleanup();
}
#[test]
fn the_handle_is_usable_and_reports_itself() {
let dir = TempDir::new("open-usable");
let handle = DirectoryHandle::open(dir.path()).expect("open");
assert!(!handle.as_raw().is_null(), "a live handle is never null");
assert!(
format!("{handle:?}").contains("DirectoryHandle"),
"Debug names the type"
);
dir.cleanup();
}
#[test]
fn the_share_mode_admits_a_second_watcher() {
let dir = TempDir::new("open-shared");
let first = DirectoryHandle::open(dir.path()).expect("first open");
let second = DirectoryHandle::open(dir.path()).expect("second open");
assert_ne!(
first.as_raw(),
second.as_raw(),
"the two opens are distinct handles"
);
dir.cleanup();
}
#[test]
fn the_share_mode_admits_writers_while_watching() {
let dir = TempDir::new("open-writable");
let handle = DirectoryHandle::open(dir.path()).expect("open");
std::fs::write(dir.path().join("created-while-open.txt"), b"data")
.expect("create a file while the directory handle is open");
drop(handle);
dir.cleanup();
}
#[test]
fn many_sequential_opens_do_not_exhaust_handles() {
let dir = TempDir::new("open-repeat");
for _ in 0..256 {
let handle = DirectoryHandle::open(dir.path()).expect("open");
drop(handle);
}
dir.cleanup();
}
#[test]
fn a_missing_leaf_classifies_as_not_found() {
let dir = TempDir::new("missing-leaf");
let missing = dir.path().join("does-not-exist");
let error = DirectoryHandle::open(&missing).expect_err("must fail");
assert_eq!(error.failure(), OpenFailure::NotFound);
assert!(
error.failure().is_retryable(),
"a path may legitimately appear later"
);
dir.cleanup();
}
#[test]
fn a_missing_intermediate_component_classifies_as_not_found() {
let dir = TempDir::new("missing-parent");
let missing = dir.path().join("absent-parent").join("leaf");
let error = DirectoryHandle::open(&missing).expect_err("must fail");
assert_eq!(error.failure(), OpenFailure::NotFound);
dir.cleanup();
}
#[test]
fn a_regular_file_classifies_as_not_a_directory() {
let dir = TempDir::new("not-a-dir");
let file = dir.path().join("regular.txt");
std::fs::write(&file, b"contents").expect("write file");
let error = DirectoryHandle::open(&file).expect_err("must fail");
assert_eq!(error.failure(), OpenFailure::NotADirectory);
assert!(
!error.failure().is_retryable(),
"a file will never become a directory"
);
dir.cleanup();
}
#[test]
fn an_interior_nul_classifies_as_invalid_path_without_calling_win32() {
let dir = TempDir::new("interior-nul");
assert!(DirectoryHandle::open(dir.path()).is_ok());
let mut poisoned = std::ffi::OsString::from(dir.path());
poisoned.push(unsafe_nul());
poisoned.push("trailing");
let error = DirectoryHandle::open(Path::new(&poisoned)).expect_err("must fail");
assert_eq!(error.failure(), OpenFailure::InvalidPath);
assert!(!error.failure().is_retryable());
dir.cleanup();
}
fn unsafe_nul() -> std::ffi::OsString {
use std::os::windows::ffi::OsStringExt;
std::ffi::OsString::from_wide(&[0u16])
}
#[test]
fn an_empty_path_fails_and_is_classified() {
let error = DirectoryHandle::open(Path::new("")).expect_err("must fail");
assert!(
matches!(
error.failure(),
OpenFailure::NotFound | OpenFailure::InvalidPath | OpenFailure::Retryable
),
"unexpected classification: {:?}",
error.failure()
);
}
#[test]
fn a_failure_preserves_the_underlying_os_error() {
let dir = TempDir::new("preserve-os-error");
let missing = dir.path().join("nope");
let error = DirectoryHandle::open(&missing).expect_err("must fail");
let underlying = std::error::Error::source(&error)
.and_then(|source| source.downcast_ref::<std::io::Error>())
.expect("the original error is kept as the source");
assert!(
underlying.raw_os_error().is_some(),
"the original OS error code is kept for diagnostics"
);
assert!(
format!("{error}").contains("NotFound"),
"Display names the classification"
);
dir.cleanup();
}
#[test]
fn every_failure_class_agrees_with_its_retry_policy() {
assert!(OpenFailure::NotFound.is_retryable());
assert!(OpenFailure::Unsupported.is_retryable());
assert!(OpenFailure::Retryable.is_retryable());
assert!(!OpenFailure::NotADirectory.is_retryable());
assert!(!OpenFailure::InvalidPath.is_retryable());
}
#[test]
fn canonical_path_reports_where_the_handle_actually_is() {
let dir = TempDir::new("canonical-basic");
let handle = DirectoryHandle::open(dir.path()).expect("open");
let reported = handle.canonical_path().expect("canonical path");
let expected = std::fs::canonicalize(dir.path()).expect("std canonicalize");
assert_eq!(
reported, expected,
"the reported path must name the same object the OS resolves this \
directory to"
);
drop(handle);
dir.cleanup();
}
#[test]
fn canonical_path_follows_a_rename_rather_than_reporting_the_opening_string() {
let dir = TempDir::new("canonical-rename");
let handle = DirectoryHandle::open(dir.path()).expect("open");
let before = handle.canonical_path().expect("canonical path before");
let renamed = dir.path().with_file_name(format!(
"windows-file-watcher-canonical-renamed-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&renamed);
std::fs::rename(dir.path(), &renamed).expect("rename the open directory");
let after = handle.canonical_path().expect("canonical path after");
assert_ne!(
before, after,
"a fresh query must notice the rename; an equal answer would mean the \
path had been cached at open"
);
assert_eq!(
after,
std::fs::canonicalize(&renamed).expect("std canonicalize"),
"and it must name where the object went, not merely differ"
);
drop(handle);
let _ = std::fs::remove_dir_all(&renamed);
dir.cleanup();
}
#[test]
fn volume_identity_equality_is_on_the_serial_alone() {
let a = VolumeIdentity::synthetic(1, "NTFS", "SAME-LABEL");
let b = VolumeIdentity::synthetic(1, "FAT32", "DIFFERENT-LABEL");
assert_eq!(
a, b,
"the same serial is the same volume, regardless of label/filesystem \
(a mere rename must not look like a media swap)"
);
let c = VolumeIdentity::synthetic(2, "NTFS", "SAME-LABEL");
assert_ne!(
a, c,
"a different serial is different media, even with an identical \
label/filesystem (media swapped for other media sharing a label \
must not go undetected)"
);
}
#[cfg(feature = "test-util")]
#[test]
fn volume_identity_for_test_is_the_public_synthetic_seam() {
let a = VolumeIdentity::for_test(0x1234, "NTFS", "System");
let b = VolumeIdentity::for_test(0x1234, "ReFS", "Data");
let c = VolumeIdentity::for_test(0x9999, "NTFS", "System");
assert_eq!(a.filesystem_name(), "NTFS");
assert_eq!(a.volume_label(), "System");
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn trim_nul_stops_at_the_first_nul() {
let units: Vec<u16> = "AB\0CD".encode_utf16().collect();
assert_eq!(
super::trim_nul(&units),
&"AB".encode_utf16().collect::<Vec<_>>()[..],
"the content before the first NUL is the string"
);
}
#[test]
fn trim_nul_keeps_a_slice_with_no_nul_whole() {
let units: Vec<u16> = "ABCD".encode_utf16().collect();
assert_eq!(super::trim_nul(&units), &units[..]);
}
#[test]
fn trim_nul_of_a_leading_nul_is_empty() {
let units = [0u16, 65, 66];
assert!(
super::trim_nul(&units).is_empty(),
"a buffer Win32 wrote nothing into is the empty string, not its residue"
);
}
#[test]
fn trim_nul_of_an_empty_slice_is_empty() {
assert!(super::trim_nul(&[]).is_empty());
}
#[test]
fn trim_nul_ignores_everything_after_the_first_nul() {
let units = [65u16, 0, 66, 0, 67];
assert_eq!(super::trim_nul(&units), &[65u16][..]);
}
#[test]
fn each_open_failure_code_classifies_to_its_own_outcome() {
use super::{OpenFailure, classify};
use windows_sys::Win32::Foundation::{
ERROR_DIRECTORY, ERROR_FILE_NOT_FOUND, ERROR_INVALID_FUNCTION, ERROR_INVALID_NAME,
ERROR_NOT_SUPPORTED, ERROR_PATH_NOT_FOUND,
};
let cases: [(u32, OpenFailure); 6] = [
(ERROR_FILE_NOT_FOUND, OpenFailure::NotFound),
(ERROR_PATH_NOT_FOUND, OpenFailure::NotFound),
(ERROR_DIRECTORY, OpenFailure::NotADirectory),
(ERROR_INVALID_FUNCTION, OpenFailure::Unsupported),
(ERROR_NOT_SUPPORTED, OpenFailure::Unsupported),
(ERROR_INVALID_NAME, OpenFailure::InvalidPath),
];
for (code, expected) in cases {
let error = std::io::Error::from_raw_os_error(code as i32);
assert_eq!(
classify(&error),
expected,
"error {code} must classify as {expected:?}"
);
}
}
#[test]
fn an_unrecognised_code_is_retryable() {
let error = std::io::Error::from_raw_os_error(0x0000_DEAD);
assert_eq!(super::classify(&error), OpenFailure::Retryable);
}
#[test]
fn an_error_with_no_os_code_is_retryable() {
let error = std::io::Error::other("no OS code behind this one");
assert_eq!(super::classify(&error), OpenFailure::Retryable);
}
#[test]
fn volume_identity_reports_the_descriptive_fields_it_was_built_with() {
let identity = VolumeIdentity::synthetic(0x1234, "ReFS", "Data");
assert_eq!(identity.filesystem_name(), "ReFS");
assert_eq!(identity.volume_label(), "Data");
}
#[test]
fn volume_identitys_two_descriptive_fields_do_not_alias() {
let identity = VolumeIdentity::synthetic(7, "NTFS", "System");
assert_ne!(identity.filesystem_name(), identity.volume_label());
assert_eq!(identity.filesystem_name(), "NTFS");
assert_eq!(identity.volume_label(), "System");
}
#[test]
fn volume_identity_accepts_empty_descriptive_fields() {
let identity = VolumeIdentity::synthetic(1, "", "");
assert_eq!(identity.filesystem_name(), "");
assert_eq!(identity.volume_label(), "");
}
#[test]
fn case_sensitivity_is_read_from_the_directory_rather_than_assumed() {
let insensitive = TempDir::new("case-insensitive");
let handle = DirectoryHandle::open(insensitive.path()).expect("opens");
assert!(
!handle.is_case_sensitive(),
"a directory with the flag clear must report insensitive"
);
let sensitive = TempDir::new("case-sensitive");
let marked = std::process::Command::new("fsutil.exe")
.arg("file")
.arg("setCaseSensitiveInfo")
.arg(sensitive.path())
.arg("enable")
.output();
let enabled = matches!(&marked, Ok(output) if output.status.success());
assert!(
enabled,
"could not mark a directory case-sensitive, so the positive half of \
this contract went untested: {marked:?}"
);
let handle = DirectoryHandle::open(sensitive.path()).expect("opens");
assert!(
handle.is_case_sensitive(),
"a directory with FILE_CS_FLAG_CASE_SENSITIVE_DIR set must report \
sensitive -- this is the half a hard-coded `false` passes"
);
}
fn identity_of(path: &Path) -> super::DirectoryId {
DirectoryHandle::open(path)
.expect("the plain absolute path must open")
.identity()
}
#[test]
fn forward_slashes_resolve_to_the_same_directory() {
let dir = TempDir::new("verbatim-slashes");
let expected = identity_of(dir.path());
let with_slashes = dir.path().to_string_lossy().replace('\\', "/");
let handle = DirectoryHandle::open(Path::new(&with_slashes))
.expect("a forward-slash spelling must open, because Win32 translates it");
assert_eq!(
handle.identity(),
expected,
"the forward-slash spelling must reach the same directory"
);
drop(handle);
dir.cleanup();
}
#[test]
fn a_dot_component_resolves_to_the_same_directory() {
let dir = TempDir::new("verbatim-dot");
let expected = identity_of(dir.path());
let with_dot = dir.path().join(".");
let handle = DirectoryHandle::open(&with_dot)
.expect("a `.` component must open, because Win32 resolves it");
assert_eq!(
handle.identity(),
expected,
"`.` must resolve to the directory itself"
);
drop(handle);
dir.cleanup();
}
#[test]
fn a_dot_dot_component_resolves_to_the_parent() {
let dir = TempDir::new("verbatim-dotdot");
let child = dir.path().join("child");
std::fs::create_dir(&child).expect("create the child directory");
let expected = identity_of(dir.path());
let up_again = child.join("..");
let handle = DirectoryHandle::open(&up_again)
.expect("a `..` component must open, because Win32 resolves it");
assert_eq!(
handle.identity(),
expected,
"`..` must resolve back to the parent, not open the child"
);
drop(handle);
dir.cleanup();
}
#[test]
fn a_caller_supplied_verbatim_prefix_is_forwarded_and_honoured() {
let dir = TempDir::new("verbatim-prefixed");
let expected = identity_of(dir.path());
let (prefixed, _) = verbatim(dir.path());
let handle = DirectoryHandle::open(Path::new(&prefixed))
.expect(r"a caller's own `\\?\` path must be forwarded unchanged and open");
assert_eq!(
handle.identity(),
expected,
"the verbatim spelling must reach the same directory"
);
drop(handle);
dir.cleanup();
}
#[test]
fn canonical_path_grows_its_buffer_when_the_path_does_not_fit() {
use std::os::windows::ffi::OsStrExt;
let dir = TempDir::new("canonical-long");
let mut deep = dir.path().to_path_buf();
while verbatim(&deep).1 < 560 {
deep.push("segment-0123456789abcdef");
}
let (prefixed, _) = verbatim(&deep);
std::fs::create_dir_all(&prefixed).expect("create the deep directory");
let handle = DirectoryHandle::open(Path::new(&prefixed))
.expect(r"a caller's own `\\?\` path opens past MAX_PATH (D-85)");
let reported = handle.canonical_path().expect("canonical path");
let units = reported.as_os_str().encode_wide().count();
assert!(
units > 512,
"the fixture must actually overflow the first buffer, got {units} units"
);
assert_eq!(
reported,
std::fs::canonicalize(&prefixed).expect("std canonicalize"),
"the grown buffer must carry the whole path, not a truncated one"
);
drop(handle);
let _ = std::fs::remove_dir_all(&prefixed);
dir.cleanup();
}
fn verbatim(path: &Path) -> (OsString, usize) {
let mut spelling = OsString::from(r"\\?\");
spelling.push(path.as_os_str());
let units = Wtf16String::from_os_str(&spelling).len();
(spelling, units)
}
#[test]
fn verbatim_counts_utf16_units_rather_than_bytes() {
let ascii = Path::new(r"C:\Temp\watch");
let (spelling, units) = verbatim(ascii);
assert_eq!(
units,
spelling.len(),
"the two counts must agree for ASCII, or the divergence below proves nothing"
);
assert_eq!(
units,
r"\\?\C:\Temp\watch".len(),
"the prefix is counted too"
);
for name in ["caf\u{00e9}", "\u{4e2d}\u{6587}"] {
let path = Path::new(r"C:\Temp").join(name);
let (spelling, units) = verbatim(&path);
assert!(
units < spelling.len(),
"{name} must expose the divergence: {units} units vs {} bytes",
spelling.len()
);
assert_eq!(
units,
r"\\?\C:\Temp\".chars().count() + name.chars().count(),
"every character here is one UTF-16 unit, so units equal characters"
);
}
}
#[test]
fn unprefixed_strips_the_verbatim_prefix_even_from_a_non_utf8_path() {
use std::os::windows::ffi::OsStringExt;
let mut units: Vec<u16> = r"\\?\C:\dir\".encode_utf16().collect();
units.push(0xD800);
let prefixed = PathBuf::from(OsString::from_wide(&units));
assert!(
prefixed.to_str().is_none(),
"the fixture must not be valid UTF-8, or it proves nothing"
);
let stripped = unprefixed(&prefixed);
let (round_tripped, _) = verbatim(&stripped);
assert_eq!(
Wtf16String::from_os_str(&round_tripped).as_units(),
&units[..],
"verbatim(unprefixed(p)) must reproduce p"
);
assert_eq!(
Wtf16String::from_os_str(stripped.as_os_str()).as_units(),
&units[4..],
"exactly the four prefix units are removed"
);
}
#[test]
fn unprefixed_leaves_a_path_that_has_no_prefix_alone() {
let plain = Path::new(r"C:\dir\file");
assert_eq!(unprefixed(plain), plain);
}
fn unprefixed(path: &Path) -> PathBuf {
const VERBATIM_PREFIX: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16];
let wide = Wtf16String::from_os_str(path.as_os_str());
match wide.as_units().strip_prefix(&VERBATIM_PREFIX[..]) {
Some(rest) => PathBuf::from(OsString::from(Wtf16String::from_wide(rest))),
None => path.to_path_buf(),
}
}
fn deep_dir_of_prefixed_len(base: &Path, target: usize) -> PathBuf {
let canonical = std::fs::canonicalize(base).expect("the base directory must exist");
let mut path = unprefixed(&canonical);
loop {
let (_, current) = verbatim(&path);
assert!(
current + 2 <= target,
"the base path is already too long to hit {target}"
);
let remaining = target - current - 1;
if remaining <= 200 {
path.push("x".repeat(remaining));
return path;
}
path.push("x".repeat(200));
}
}
#[test]
fn canonical_path_is_exact_on_both_sides_of_its_first_buffer() {
use std::os::windows::ffi::OsStrExt;
let dir = TempDir::new("canon-bound");
for target in 508..=516 {
let deep = deep_dir_of_prefixed_len(dir.path(), target);
let (prefixed, units) = verbatim(&deep);
assert_eq!(units, target, "the fixture must be exactly sized");
std::fs::create_dir_all(&prefixed).expect("create the sized directory");
let handle = DirectoryHandle::open(Path::new(&prefixed)).expect("open the sized directory");
let reported = handle.canonical_path().expect("canonical path");
assert_eq!(
reported.as_os_str().encode_wide().count(),
target,
"a {target}-unit path must be reported whole"
);
assert_eq!(
reported,
std::fs::canonicalize(&prefixed).expect("std canonicalize"),
"a {target}-unit path must be reported correctly"
);
drop(handle);
let _ = std::fs::remove_dir_all(&prefixed);
}
dir.cleanup();
}