Merge pull request #9837 from dotCooCoo/fix/prefs-dir-font-scans-own-root

Tests: app tests that share process-wide state pass under cargo test
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-28 02:21:40 -08:00
commit a9c0ceca00
6 files changed
+144 -38

No files matched your search

+9
View File
@@ -629,6 +629,15 @@ struct StartFile {
record: StartRecord,
}
impl Drop for StartFile {
/// Frees the lock when the start releases the file. A child process that any thread starts holds
/// a copy of the file's handle until it runs its program, and the lock is only freed by closing
/// every copy or by unlocking.
fn drop(&mut self) {
let _ = self.file.unlock();
}
}
impl StartFile {
/// Open `dir`'s [`START_FILE`], with the record the last start left in it (`None` when there is
/// none or it can't be read). `Ok(None)` when another copy of the app holds it.
+23 -12
View File
@@ -613,9 +613,7 @@ fn a_normal_exit_or_another_failure_does_not_restart() {
assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into()));
}
/// A log folder of its own for each test, and the guard that keeps other tests from starting a
/// program while it runs: the test releases the start file's lock and takes it again, and a child
/// starting meanwhile would keep it held (`crate::no_spawns`).
/// A log folder of its own for each test.
struct TestDir(tempfile::TempDir);
impl std::ops::Deref for TestDir {
@@ -632,10 +630,23 @@ impl AsRef<std::path::Path> for TestDir {
}
}
fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) {
let spawns = crate::no_spawns();
let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap();
(TestDir(dir), spawns)
fn start_dir(tag: &str) -> TestDir {
TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap())
}
/// A start that ends frees the start file even while another handle to it is open, as a child
/// process that is starting holds one: the next start reads the file instead of taking it for
/// another copy of the app that is starting.
#[test]
fn an_ended_start_frees_the_start_file_while_a_copy_of_its_handle_is_open() {
let dir = start_dir("copy");
let starting = Startup::default();
starting.track(&dir, None, false);
let copy = starting.start.lock().unwrap().as_ref().map(|start| start.file.try_clone().unwrap());
assert!(copy.is_some(), "the start holds the file");
starting.ended();
assert!(StartFile::open(&dir).unwrap().is_some(), "an ended start frees the start file");
drop(copy);
}
/// What a start in `dir` leaves out; it then ends without crashing.
@@ -661,7 +672,7 @@ fn issue_2243() -> Vec<Candidate> {
/// it, without a status-bar note.
#[test]
fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
let (dir, _spawns) = start_dir("crash");
let dir = start_dir("crash");
let c = issue_2243();
let first = Startup::default();
assert_eq!(first.track(&dir, None, false), LeftOut::default());
@@ -691,7 +702,7 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
/// an error, a restart on another adapter), leaves nothing out of the next.
#[test]
fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
let (dir, _spawns) = start_dir("shown");
let dir = start_dir("shown");
let c = issue_2243();
for end in [Startup::presented as fn(&Startup), Startup::ended] {
let first = Startup::default();
@@ -714,7 +725,7 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
/// macOS, where wgpu has none.
#[test]
fn a_crash_while_listing_lists_opengl_alone() {
let (dir, _spawns) = start_dir("listing");
let dir = start_dir("listing");
let first = Startup::default();
first.track(&dir, None, false);
drop(first);
@@ -740,7 +751,7 @@ fn a_crash_while_listing_lists_opengl_alone() {
/// start shows its first frame on the adapter that crashed, the adapter counts again.
#[test]
fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
let (dir, _spawns) = start_dir("explicit");
let dir = start_dir("explicit");
let c = issue_2243();
let first = Startup::default();
first.track(&dir, None, false);
@@ -760,7 +771,7 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
/// are ignored: the start goes on with nothing left out.
#[test]
fn a_damaged_or_unreadable_start_file_is_ignored() {
let (dir, _spawns) = start_dir("damaged");
let dir = start_dir("damaged");
std::fs::create_dir_all(&dir).unwrap();
let damaged: [&[u8]; 9] = [
b"",
-14
View File
@@ -1034,19 +1034,5 @@ fn main() -> std::process::ExitCode {
}
}
/// Tests only: while a test starts another program, the child briefly holds a copy of every file
/// this process has open, until it runs that program. A file lock held through such a copy outlives
/// its own handle, so a GPU start test that released the start file and opened it again found it
/// still locked, as if another copy of the app were running, and failed. A test that starts a
/// program holds its write side; a test that depends on the start file's lock holds [`no_spawns`].
#[cfg(all(test, feature = "wgpu"))]
static CHILD_SPAWN: std::sync::RwLock<()> = std::sync::RwLock::new(());
/// Held by a test that releases a locked file and opens it again (see [`CHILD_SPAWN`]).
#[cfg(all(test, feature = "wgpu"))]
fn no_spawns() -> std::sync::RwLockReadGuard<'static, ()> {
CHILD_SPAWN.read().unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg(all(test, feature = "wgpu"))]
mod tests;
+83 -10
View File
@@ -16,12 +16,38 @@ static SESSION: Mutex<Option<Session>> = Mutex::new(None);
static NOTICE_SHOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub struct Session {
_lease: File,
_lease: Lease,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
/// The profile's [`LEASE`], open and locked.
struct Lease(File);
impl Lease {
/// Lock `root`'s [`LEASE`]: `None` when another window of the same profile holds it.
fn take(root: &Path) -> io::Result<Option<Self>> {
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => Ok(Some(Self(lease))),
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
Err(std::fs::TryLockError::Error(error)) => Err(error),
}
}
}
impl Drop for Lease {
/// Frees the lease when the session ends, or when a session could not be started after the lock
/// was taken. A child process that any thread starts holds a copy of the lease's handle until it
/// runs its program, and the lock is only freed by closing every copy or by unlocking.
fn drop(&mut self) {
let _ = self.0.unlock();
}
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
@@ -73,14 +99,13 @@ impl Session {
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let Some(lease) = Lease::take(root)? else { return Ok(None) };
Self::record(lease, root, version, commit).map(Some)
}
/// Write this launch's record while `lease` is held. On an error `lease` is dropped, which
/// unlocks it.
fn record(lease: Lease, root: &Path, version: &str, commit: Option<&str>) -> io::Result<Self> {
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
@@ -90,7 +115,7 @@ impl Session {
"commit": commit.filter(|value| !value.is_empty()),
}))?;
atomic_write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
Ok(Self { _lease: lease, path, own_record, previous_unclean })
}
pub fn previous_unclean(&self) -> bool {
@@ -258,6 +283,54 @@ mod tests {
assert!(!fixture.0.join(RECORD).exists(), "a controlled return clears its record");
}
#[test]
fn an_ended_session_frees_the_lease_while_a_copy_of_its_handle_is_open() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", None).unwrap().unwrap();
// A child process that is starting holds such a copy.
let first_copy = first._lease.0.try_clone().unwrap();
first.complete().unwrap();
let second = Session::begin(Some(&fixture.0), "second", None).unwrap();
assert!(second.is_some(), "a completed session frees the lease");
let second_copy = second.as_ref().map(|session| session._lease.0.try_clone().unwrap());
drop(second);
assert!(Session::begin(Some(&fixture.0), "third", None).unwrap().is_some(), "a dropped session frees the lease");
drop((first_copy, second_copy));
}
/// `root`'s lease, locked as [`Session::begin`] locks it, and a copy of its handle such as a
/// child process that is starting holds.
fn locked_with_a_copy(root: &Path) -> (Lease, File) {
let lease = Lease::take(root).unwrap().unwrap();
let copy = lease.0.try_clone().unwrap();
(lease, copy)
}
#[test]
fn a_session_that_cannot_check_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() {
let fixture = Fixture::new();
std::fs::create_dir(fixture.0.join(RECORD)).unwrap();
let (lease, copy) = locked_with_a_copy(&fixture.0);
assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "a folder is not a record");
std::fs::remove_dir(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to check its record frees the lease");
drop(copy);
}
#[test]
fn a_session_that_cannot_write_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() {
let fixture = Fixture::new();
// A folder at the temporary file's name makes the write fail after the record was checked.
let temporary = fixture.0.join(format!(".{RECORD}.{}.tmp", std::process::id()));
std::fs::create_dir(&temporary).unwrap();
let (lease, copy) = locked_with_a_copy(&fixture.0);
assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "the record cannot be written");
assert!(!fixture.0.join(RECORD).exists());
std::fs::remove_dir(&temporary).unwrap();
assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to write its record frees the lease");
drop(copy);
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
+2
View File
@@ -145,6 +145,8 @@ mod tests {
#[test]
fn the_font_scans_read_the_fonts_folder_next_to_the_settings() {
// No test installs a launch's root in this process, so the settings folder stays the same here.
assert_eq!(profile::data_root(), None, "a test installed a launch's root beside the others");
install_fonts();
let fonts = prefs_dir().map(|dir| dir.join("Fonts"));
assert!(fonts.is_some(), "a home folder to keep the settings in");
+27 -2
View File
@@ -457,10 +457,35 @@ mod tests {
}
}
/// Installs the process-wide root: the one test that may, since a `OnceLock` is set once per
/// process (nextest gives every test its own).
/// Runs the test `name` of this module again in a child process of the test binary → whether
/// this is that child. For a test that installs the process-wide root, which every test running
/// beside it would then read as the settings folder.
fn in_own_process(name: &str) -> bool {
const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS";
if std::env::var_os(CHILD).is_some() {
return true;
}
// The test's path without the crate's name: the desktop app and `vectorcraft-cli` both build this file.
let module = module_path!().split_once("::").map_or(module_path!(), |(_, path)| path);
let path = format!("{module}::{name}");
let output =
std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", &path, "--nocapture"]).env(CHILD, "1").output().unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"{path} failed in its own process:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
false
}
/// Installs the process-wide root, which a `OnceLock` holds once per process, so the test runs in
/// a process of its own.
#[test]
fn the_installed_root_is_used_once_and_must_be_absolute() {
if !in_own_process("the_installed_root_is_used_once_and_must_be_absolute") {
return;
}
let dir = temp("installed-root");
assert!(install_data_root(PathBuf::from("relative/root")).is_err(), "a relative root is refused");
install_data_root(dir.to_path_buf()).unwrap();