Skip to content

Commit dc0f280

Browse files
committed
test: isolate env exec runtime cache
1 parent 9f1cbad commit dc0f280

1 file changed

Lines changed: 35 additions & 1 deletion

File tree

  • crates/vite_global_cli/src/commands/env

crates/vite_global_cli/src/commands/env/exec.rs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,10 +193,43 @@ fn exit_status(code: i32) -> ExitStatus {
193193

194194
#[cfg(test)]
195195
mod tests {
196+
use std::ffi::OsString;
197+
196198
use serial_test::serial;
199+
use tempfile::TempDir;
197200

198201
use super::*;
199202

203+
struct VpHomeGuard {
204+
original_vp_home: Option<OsString>,
205+
_temp_dir: TempDir,
206+
}
207+
208+
impl VpHomeGuard {
209+
fn new() -> Self {
210+
let temp_dir = TempDir::new().unwrap();
211+
let original_vp_home = std::env::var_os(env_vars::VP_HOME);
212+
// SAFETY: This test helper is only used from serial tests and restores the
213+
// process-global environment before dropping.
214+
unsafe {
215+
std::env::set_var(env_vars::VP_HOME, temp_dir.path());
216+
}
217+
Self { original_vp_home, _temp_dir: temp_dir }
218+
}
219+
}
220+
221+
impl Drop for VpHomeGuard {
222+
fn drop(&mut self) {
223+
// SAFETY: We restore the original process-global environment captured in new().
224+
unsafe {
225+
match &self.original_vp_home {
226+
Some(value) => std::env::set_var(env_vars::VP_HOME, value),
227+
None => std::env::remove_var(env_vars::VP_HOME),
228+
}
229+
}
230+
}
231+
}
232+
200233
#[tokio::test]
201234
async fn test_execute_missing_command() {
202235
let result = execute(Some("20.18.0"), None, &[]).await;
@@ -208,10 +241,11 @@ mod tests {
208241
#[tokio::test]
209242
#[serial]
210243
async fn test_execute_node_version() {
244+
let _guard = VpHomeGuard::new();
211245
// Run 'node --version' with a specific Node.js version
212246
let command = vec!["node".to_string(), "--version".to_string()];
213247
let result = execute(Some("20.18.0"), None, &command).await;
214-
assert!(result.is_ok());
248+
assert!(result.is_ok(), "{result:?}");
215249
let status = result.unwrap();
216250
assert!(status.success());
217251
}

0 commit comments

Comments
 (0)