Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion test_support/src/path_guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
//! Provides a guard that resets the environment variable on drop so tests do
//! not pollute global state.

use std::ffi::OsString;
use std::ffi::{OsStr, OsString};

use crate::env_guard::{EnvGuard, Environment, StdEnv};
use crate::env_lock::EnvLock;

/// Environment abstraction for setting variables.
pub trait Env: Environment {}
Expand Down Expand Up @@ -65,4 +66,28 @@ impl<E: Env> PathGuard<E> {
pub fn env_mut(&mut self) -> &mut E {
self.inner.env_mut()
}

/// Set `PATH` to `value` through the guard's environment.
///
/// Safe wrapper around the `unsafe` [`Environment::set_var`] operation:
/// the global [`EnvLock`] serialises the mutation and the guard restores
/// the original value on drop, so the unsafety stays encapsulated here
/// rather than leaking `unsafe` blocks into consumer code.
///
/// # Examples
///
/// ```rust,no_run
/// use std::ffi::OsStr;
/// use test_support::PathGuard;
///
/// let mut guard = PathGuard::capture();
/// guard.set_path(OsStr::new("/stub/bin"));
/// // The captured PATH is restored when `guard` drops.
/// ```
pub fn set_path(&mut self, value: &OsStr) {
let _lock = EnvLock::acquire();
// SAFETY: `EnvLock` serialises the mutation and the guard restores
// the captured value on drop.
unsafe { self.inner.env_mut().set_var("PATH", value) };
}
}
8 changes: 3 additions & 5 deletions tests/path_guard_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ fn restores_path_without_touching_real_env() {
.return_const(());
{
let mut guard = PathGuard::with_env(Some("/orig".into()), env);
unsafe {
guard.env_mut().set_var("PATH", OsStr::new("/tmp"));
}
guard.set_path(OsStr::new("/tmp"));
}
}

Expand All @@ -45,8 +43,8 @@ fn restores_path_without_touching_real_env() {
fn capture_snapshots_and_restores_real_path() -> Result<()> {
let original = std::env::var_os("PATH");
{
let _guard = PathGuard::capture();
test_support::env::set_var("PATH", OsStr::new("/netsuke-capture-test"));
let mut guard = PathGuard::capture();
guard.set_path(OsStr::new("/netsuke-capture-test"));
let mutated = std::env::var_os("PATH").context("PATH should be set after mutation")?;
ensure!(
mutated == OsStr::new("/netsuke-capture-test"),
Expand Down
Loading