diff --git a/src/cli/self_update.rs b/src/cli/self_update.rs index ef1e0a950c..21026bf4d3 100644 --- a/src/cli/self_update.rs +++ b/src/cli/self_update.rs @@ -90,9 +90,9 @@ mod windows; #[cfg(windows)] pub use windows::complete_windows_uninstall; #[cfg(all(windows, feature = "test"))] -pub use windows::{RegistryGuard, RegistryValueId, USER_PATH, get_path}; +pub use windows::{RUSTUP_TEST_REGISTRY_UUID, RegistryGuard, RegistryValueId, USER_PATH, get_path}; #[cfg(windows)] -use windows::{do_add_to_path, do_remove_from_path}; +use windows::{do_add_to_path, do_add_to_programs, do_remove_from_path, do_remove_from_programs}; #[cfg(windows)] pub(crate) use windows::{run_update, self_replace}; @@ -323,7 +323,7 @@ impl SelfUpdateMode { let setup_path = prepare_update(dl_cfg).await?; if let Some(setup_path) = &setup_path { - return run_update(setup_path); + return run_update(setup_path, dl_cfg.process); } else { // Try again in case we emitted "tool `{}` is already installed" last time. install_proxies(dl_cfg.process)?; @@ -1009,6 +1009,9 @@ async fn maybe_install_rust(opts: InstallOpts<'_>, cfg: &mut Cfg<'_>) -> Result< do_add_to_path(cfg.process)?; } + #[cfg(windows)] + do_add_to_programs(cfg.process)?; + // If RUSTUP_HOME is not set, make sure it exists if cfg.process.var_os("RUSTUP_HOME").is_none() { let home = cfg @@ -1158,6 +1161,9 @@ fn clean_cargo_home(no_modify_path: bool, process: &Process) -> Result<()> { utils::remove_file("rustup_bin", &rustup_path)?; + #[cfg(windows)] + do_remove_from_programs(process)?; + let cargo_bin_display = cargo_bin.display(); info!("removing empty cargo bin directory `{cargo_bin_display}`"); @@ -1283,7 +1289,7 @@ pub(crate) async fn update(cfg: &Cfg<'_>) -> Result { PackageUpdate::Rustup, Ok(UpdateStatus::Updated(version)), ); - return run_update(&setup_path); + return run_update(&setup_path, cfg.process); } None => { let _ = common::show_channel_update( diff --git a/src/cli/self_update/unix.rs b/src/cli/self_update/unix.rs index 7edcd68b78..c68b231556 100644 --- a/src/cli/self_update/unix.rs +++ b/src/cli/self_update/unix.rs @@ -120,7 +120,7 @@ pub(crate) fn do_write_env_files(process: &Process) -> Result<()> { /// Tell the upgrader to replace the rustup bins, then delete /// itself. -pub(crate) fn run_update(setup_path: &Path) -> Result { +pub(crate) fn run_update(setup_path: &Path, _process: &Process) -> Result { let status = Command::new(setup_path) .arg("--self-replace") .status() diff --git a/src/cli/self_update/windows.rs b/src/cli/self_update/windows.rs index 84dad678d7..0333587c90 100644 --- a/src/cli/self_update/windows.rs +++ b/src/cli/self_update/windows.rs @@ -5,8 +5,6 @@ use std::io::Write; use std::os::windows::ffi::OsStrExt; use std::path::Path; use std::process::Command; -#[cfg(any(test, feature = "test"))] -use std::sync::{LockResult, Mutex, MutexGuard}; use anyhow::{Context, Result, anyhow}; use tracing::{info, warn}; @@ -449,11 +447,10 @@ pub(crate) fn wait_for_parent() -> Result<()> { pub(crate) fn do_add_to_path(process: &Process) -> Result<()> { let new_path = _with_path_cargo_home_bin(_add_to_path, process)?; - _apply_new_path(new_path)?; - do_add_to_programs(process) + _apply_new_path(new_path, process) } -fn _apply_new_path(new_path: Option) -> Result<()> { +fn _apply_new_path(new_path: Option, process: &Process) -> Result<()> { use std::ptr; use windows_sys::Win32::Foundation::{LPARAM, WPARAM}; use windows_sys::Win32::UI::WindowsAndMessaging::{ @@ -464,7 +461,7 @@ fn _apply_new_path(new_path: Option) -> Result<()> { return Ok(()); // No need to set the path }; - let environment = CURRENT_USER.create("Environment")?; + let environment = CURRENT_USER.create(registry_sub_key_path("Environment", process))?; if new_path.is_empty() { environment.remove_value("PATH")?; @@ -492,9 +489,9 @@ fn _apply_new_path(new_path: Option) -> Result<()> { // Get the windows PATH variable out of the registry as a String. If // this returns None then the PATH variable is not a string and we // should not mess with it. -fn get_windows_path_var() -> Result> { +fn get_windows_path_var(process: &Process) -> Result> { let environment = CURRENT_USER - .create("Environment") + .create(registry_sub_key_path("Environment", process)) .context("Failed opening Environment key")?; let reg_value = environment.get_hstring("PATH"); @@ -558,7 +555,7 @@ fn _with_path_cargo_home_bin(f: F, process: &Process) -> Result Option, { - let windows_path = get_windows_path_var()?; + let windows_path = get_windows_path_var(process)?; let mut path_str = process.cargo_home()?; path_str.push("bin"); Ok(windows_path.and_then(|old_path| f(old_path, HSTRING::from(path_str.as_path())))) @@ -566,20 +563,19 @@ where pub(crate) fn do_remove_from_path(process: &Process) -> Result<()> { let new_path = _with_path_cargo_home_bin(_remove_from_path, process)?; - _apply_new_path(new_path)?; - do_remove_from_programs() + _apply_new_path(new_path, process) } const RUSTUP_UNINSTALL_ENTRY: &str = r"Software\Microsoft\Windows\CurrentVersion\Uninstall\Rustup"; -fn rustup_uninstall_reg_key() -> Result { +fn rustup_uninstall_reg_key(process: &Process) -> Result { CURRENT_USER - .create(RUSTUP_UNINSTALL_ENTRY) + .create(registry_sub_key_path(RUSTUP_UNINSTALL_ENTRY, process)) .context("Failed creating uninstall key") } -pub(crate) fn do_update_programs_display_version(version: &str) -> Result<()> { - rustup_uninstall_reg_key()? +pub(crate) fn do_update_programs_display_version(version: &str, process: &Process) -> Result<()> { + rustup_uninstall_reg_key(process)? .set_string("DisplayVersion", version) .context("Failed to set `DisplayVersion`") } @@ -587,7 +583,7 @@ pub(crate) fn do_update_programs_display_version(version: &str) -> Result<()> { pub(crate) fn do_add_to_programs(process: &Process) -> Result<()> { use std::path::PathBuf; - let key = rustup_uninstall_reg_key()?; + let key = rustup_uninstall_reg_key(process)?; // Don't overwrite registry if Rustup is already installed let prev = key.get_hstring("UninstallString"); @@ -609,20 +605,20 @@ pub(crate) fn do_add_to_programs(process: &Process) -> Result<()> { .context("Failed to set `UninstallString`")?; key.set_string("DisplayName", "Rustup: the Rust toolchain installer") .context("Failed to set `DisplayName`")?; - do_update_programs_display_version(env!("CARGO_PKG_VERSION"))?; + do_update_programs_display_version(env!("CARGO_PKG_VERSION"), process)?; Ok(()) } -pub(crate) fn do_remove_from_programs() -> Result<()> { - match CURRENT_USER.remove_tree(RUSTUP_UNINSTALL_ENTRY) { +pub(crate) fn do_remove_from_programs(process: &Process) -> Result<()> { + match CURRENT_USER.remove_tree(registry_sub_key_path(RUSTUP_UNINSTALL_ENTRY, process)) { Ok(()) => Ok(()), Err(e) if e.code() == HRESULT::from_win32(ERROR_FILE_NOT_FOUND) => Ok(()), Err(e) => Err(anyhow!(e)), } } -pub(crate) fn run_update(setup_path: &Path) -> Result { +pub(crate) fn run_update(setup_path: &Path, process: &Process) -> Result { Command::new(setup_path) .arg("--self-replace") .spawn() @@ -632,7 +628,7 @@ pub(crate) fn run_update(setup_path: &Path) -> Result { warn!("failed to get the new rustup version in order to update `DisplayVersion`"); return Ok(utils::ExitCode(1)); }; - do_update_programs_display_version(&version)?; + do_update_programs_display_version(&version, process)?; Ok(utils::ExitCode(0)) } @@ -754,39 +750,79 @@ pub(crate) fn spawn_uninstall_gc(no_modify_path: bool, process: &Process) -> Res // so we use env var here, notifying it if we need to remove $CARGO_HOME/bin from $PATH const GC_MODIFY_PATH: &str = "RUSTUP_GC_MODIFY_PATH"; +/// Environment variable carrying the per-test registry UUID. +#[cfg(any(test, feature = "test"))] +pub const RUSTUP_TEST_REGISTRY_UUID: &str = "RUSTUP_TEST_REGISTRY_UUID"; + +/// Maps a real registry sub-key onto a per-test `RustupTest-{uuid}` subtree. #[cfg(any(test, feature = "test"))] -pub fn get_path() -> Result> { - USER_PATH.get() +fn map_sub_key(sub_key: &str, uuid: &str) -> String { + let root = format!(r"Software\Microsoft\Windows\CurrentVersion\Uninstall\RustupTest-{uuid}"); + if sub_key == RUSTUP_UNINSTALL_ENTRY { + format!(r"{root}\Programs") + } else if sub_key == "Environment" { + format!(r"{root}\Environment") + } else { + format!(r"{root}\{sub_key}") + } } +/// Resolves a registry sub-key, redirecting into the per-test subtree when the +/// process carries a [`RUSTUP_TEST_REGISTRY_UUID`]. In production builds this is +/// the identity function. #[cfg(any(test, feature = "test"))] -pub struct RegistryGuard<'a> { - _locked: LockResult>, - id: &'static RegistryValueId, - prev: Option, +fn registry_sub_key_path(sub_key: &str, process: &Process) -> String { + match process.var_opt(RUSTUP_TEST_REGISTRY_UUID) { + Ok(Some(uuid)) if !uuid.is_empty() => map_sub_key(sub_key, &uuid), + _ => sub_key.to_owned(), + } +} + +#[cfg(not(any(test, feature = "test")))] +fn registry_sub_key_path(sub_key: &str, _process: &Process) -> String { + sub_key.to_owned() } #[cfg(any(test, feature = "test"))] -impl RegistryGuard<'_> { - pub fn new(id: &'static RegistryValueId) -> Result { +pub fn get_path(uuid: &str) -> Result> { + USER_PATH.get(uuid) +} + +#[cfg(any(test, feature = "test"))] +fn random_uuid() -> String { + format!("{:032x}", rand::random::()) +} + +/// Guards a set of registry values for the duration of a test. +#[cfg(any(test, feature = "test"))] +pub struct RegistryGuard { + pub uuid: String, +} + +#[cfg(any(test, feature = "test"))] +impl RegistryGuard { + pub fn new(_ids: impl IntoIterator) -> Result { Ok(Self { - _locked: REGISTRY_LOCK.lock(), - id, - prev: id.get()?, + uuid: random_uuid(), }) } } #[cfg(any(test, feature = "test"))] -impl Drop for RegistryGuard<'_> { +impl Drop for RegistryGuard { fn drop(&mut self) { - self.id.set(self.prev.as_ref()).unwrap(); + let root = format!( + r"Software\Microsoft\Windows\CurrentVersion\Uninstall\RustupTest-{}", + self.uuid + ); + match CURRENT_USER.remove_tree(&root) { + Ok(()) => {} + Err(e) if e.code() == HRESULT::from_win32(ERROR_FILE_NOT_FOUND) => {} + Err(_) => {} + } } } -#[cfg(any(test, feature = "test"))] -static REGISTRY_LOCK: Mutex<()> = Mutex::new(()); - #[cfg(any(test, feature = "test"))] pub const USER_PATH: RegistryValueId = RegistryValueId { sub_key: "Environment", @@ -801,8 +837,12 @@ pub struct RegistryValueId { #[cfg(any(test, feature = "test"))] impl RegistryValueId { - pub fn get(&self) -> Result> { - let sub_key = CURRENT_USER.create(self.sub_key)?; + fn resolved_sub_key(&self, uuid: &str) -> windows_registry::Result { + CURRENT_USER.create(map_sub_key(self.sub_key, uuid)) + } + + pub fn get(&self, uuid: &str) -> Result> { + let sub_key = self.resolved_sub_key(uuid)?; match sub_key.get_value(self.value_name) { Ok(val) => Ok(Some(val)), Err(e) if e.code() == HRESULT::from_win32(ERROR_FILE_NOT_FOUND) => Ok(None), @@ -810,8 +850,8 @@ impl RegistryValueId { } } - pub fn set(&self, new: Option<&Value>) -> Result<()> { - let sub_key = CURRENT_USER.create(self.sub_key)?; + pub fn set(&self, new: Option<&Value>, uuid: &str) -> Result<()> { + let sub_key = self.resolved_sub_key(uuid)?; match new { Some(new) => Ok(sub_key.set_value(self.value_name, new)?), None => Ok(sub_key.remove_value(self.value_name)?), @@ -821,6 +861,7 @@ impl RegistryValueId { #[cfg(test)] mod tests { + use std::collections::HashMap; use std::os::windows::ffi::OsStringExt; use windows_registry::Type; @@ -828,6 +869,33 @@ mod tests { use super::*; use crate::process::TestProcess; + fn test_process(guard: &RegistryGuard) -> TestProcess { + let vars: HashMap = [ + ("HOME".to_string(), "/unused".to_string()), + ( + RUSTUP_TEST_REGISTRY_UUID.to_string(), + guard.uuid.to_string(), + ), + ] + .into_iter() + .collect(); + TestProcess::with_vars(vars) + } + + fn test_environment_key(guard: &RegistryGuard) -> Key { + CURRENT_USER + .create(map_sub_key("Environment", guard.uuid.as_str())) + .unwrap() + } + + fn clear_path(environment: &Key) { + match environment.remove_value("PATH") { + Ok(()) => {} + Err(e) if e.code() == HRESULT::from_win32(ERROR_FILE_NOT_FOUND) => {} + Err(e) => panic!("failed to clear PATH: {e}"), + } + } + #[test] fn windows_install_does_not_add_path_twice() { assert_eq!( @@ -864,16 +932,20 @@ mod tests { #[test] fn windows_path_regkey_type() { // per issue #261, setting PATH should use REG_EXPAND_SZ. - let _guard = RegistryGuard::new(&USER_PATH); - let environment = CURRENT_USER.create("Environment").unwrap(); - environment.remove_value("PATH").unwrap(); + let guard = RegistryGuard::new([&USER_PATH]).unwrap(); + let tp = test_process(&guard); + let environment = test_environment_key(&guard); + clear_path(&environment); { // Can't compare the Results as Eq isn't derived; thanks error-chain. #![allow(clippy::unit_cmp)] - assert_eq!((), _apply_new_path(Some(HSTRING::from("foo"))).unwrap()); + assert_eq!( + (), + _apply_new_path(Some(HSTRING::from("foo")), &tp.process).unwrap() + ); } - let environment = CURRENT_USER.create("Environment").unwrap(); + let environment = test_environment_key(&guard); let path = environment.get_value("PATH").unwrap(); let path_hstring = environment.get_hstring("PATH").unwrap(); assert_eq!(path.ty(), Type::ExpandString); @@ -884,8 +956,9 @@ mod tests { fn windows_path_delete_key_when_empty() { // during uninstall the PATH key may end up empty; if so we should // delete it. - let _guard = RegistryGuard::new(&USER_PATH); - let environment = CURRENT_USER.create("Environment").unwrap(); + let guard = RegistryGuard::new([&USER_PATH]).unwrap(); + let tp = test_process(&guard); + let environment = test_environment_key(&guard); environment .set_expand_hstring("PATH", &HSTRING::from("foo")) .unwrap(); @@ -893,7 +966,10 @@ mod tests { { // Can't compare the Results as Eq isn't derived; thanks error-chain. #![allow(clippy::unit_cmp)] - assert_eq!((), _apply_new_path(Some(HSTRING::new())).unwrap()); + assert_eq!( + (), + _apply_new_path(Some(HSTRING::new()), &tp.process).unwrap() + ); } let reg_value = environment.get_value("PATH"); match reg_value { @@ -905,16 +981,11 @@ mod tests { #[test] fn windows_doesnt_mess_with_a_non_string_path() { + let guard = RegistryGuard::new([&USER_PATH]).unwrap(); // This writes an error, so we want a sink for it. - let tp = TestProcess::with_vars( - [("HOME".to_string(), "/unused".to_string())] - .iter() - .cloned() - .collect(), - ); + let tp = test_process(&guard); - let _guard = RegistryGuard::new(&USER_PATH); - let environment = CURRENT_USER.create("Environment").unwrap(); + let environment = test_environment_key(&guard); environment .set_bytes("PATH", Type::Bytes, &[0x12, 0x34]) .unwrap(); @@ -934,11 +1005,15 @@ mod tests { #[test] fn windows_treat_missing_path_as_empty() { // during install the PATH key may be missing; treat it as empty - let _guard = RegistryGuard::new(&USER_PATH); - let environment = CURRENT_USER.create("Environment").unwrap(); - environment.remove_value("PATH").unwrap(); + let guard = RegistryGuard::new([&USER_PATH]).unwrap(); + let tp = test_process(&guard); + let environment = test_environment_key(&guard); + clear_path(&environment); - assert_eq!(Some(HSTRING::new()), get_windows_path_var().unwrap()); + assert_eq!( + Some(HSTRING::new()), + get_windows_path_var(&tp.process).unwrap() + ); } #[test] diff --git a/src/env_var.rs b/src/env_var.rs index 45b19c6389..5ec689843e 100644 --- a/src/env_var.rs +++ b/src/env_var.rs @@ -54,8 +54,6 @@ mod tests { use std::ffi::{OsStr, OsString}; use super::*; - #[cfg(windows)] - use crate::cli::self_update::{RegistryGuard, USER_PATH}; use crate::process::TestProcess; use crate::test::Env; @@ -67,8 +65,6 @@ mod tests { env::join_paths(["/home/a/.cargo/bin", "/home/b/.cargo/bin"].iter()).unwrap(), ); let tp = TestProcess::with_vars(vars); - #[cfg(windows)] - let _path_guard = RegistryGuard::new(&USER_PATH).unwrap(); let mut path_entries = vec![]; let mut cmd = Command::new("test"); @@ -115,8 +111,6 @@ mod tests { env::join_paths(["/home/a/.cargo/bin", "/home/b/.cargo/bin"].iter()).unwrap(), ); let tp = TestProcess::with_vars(vars); - #[cfg(windows)] - let _path_guard = RegistryGuard::new(&USER_PATH).unwrap(); #[track_caller] fn check(tp: &TestProcess, path_entries: Vec, append: &str, expected: &[&str]) { diff --git a/src/test.rs b/src/test.rs index 023d73aea4..c62f73701f 100644 --- a/src/test.rs +++ b/src/test.rs @@ -24,7 +24,9 @@ use crate::dist::TargetTuple; use crate::process::TestProcess; #[cfg(windows)] -pub use crate::cli::self_update::{RegistryGuard, RegistryValueId, USER_PATH, get_path}; +pub use crate::cli::self_update::{ + RUSTUP_TEST_REGISTRY_UUID, RegistryGuard, RegistryValueId, USER_PATH, get_path, +}; mod clitools; pub use clitools::{ diff --git a/src/test/clitools.rs b/src/test/clitools.rs index 2eb666ee92..ac7f0cf910 100644 --- a/src/test/clitools.rs +++ b/src/test/clitools.rs @@ -62,6 +62,9 @@ pub struct Config { pub workdir: RefCell, /// This is the test root for keeping stuff together test_root_dir: PathBuf, + /// Per-test Windows registry UUID. + #[cfg(windows)] + pub test_registry_uuid: Option, } /// Helper type to simplify assertions of a command's output. @@ -243,6 +246,11 @@ impl Config { self.workdir.borrow().clone() } + #[cfg(windows)] + pub fn set_registry_uuid(&mut self, uuid: &str) { + self.test_registry_uuid = Some(uuid.to_owned()); + } + pub fn cmd(&self, name: &str, args: I) -> Command where I: IntoIterator, @@ -322,6 +330,11 @@ impl Config { if let Some(root) = self.rustup_update_root.as_ref() { cmd.env("RUSTUP_UPDATE_ROOT", root); } + + #[cfg(windows)] + if let Some(uuid) = self.test_registry_uuid.as_ref() { + cmd.env(crate::cli::self_update::RUSTUP_TEST_REGISTRY_UUID, uuid); + } } /// Returns an [`Assert`] object to check the output of running the command @@ -810,6 +823,8 @@ async fn setup_test_state(test_dist_dir: TempDir) -> (TempDir, Config) { rustup_update_root: None, workdir: RefCell::new(workdir), test_root_dir: test_dir.path().to_path_buf(), + #[cfg(windows)] + test_registry_uuid: None, }; let build_path = built_exe_dir.join(format!("rustup-init{EXE_SUFFIX}")); @@ -879,6 +894,8 @@ async fn setup_test_state(test_dist_dir: TempDir) -> (TempDir, Config) { pub struct SelfUpdateTestContext { pub config: Config, _test_dir: TempDir, + #[cfg(windows)] + _registry_guard: crate::cli::self_update::RegistryGuard, self_dist_tmp: TempDir, } @@ -917,6 +934,8 @@ impl SelfUpdateTestContext { Self { config: cx.config, _test_dir: cx._test_dir, + #[cfg(windows)] + _registry_guard: cx._registry_guard, self_dist_tmp, } } @@ -929,6 +948,8 @@ impl SelfUpdateTestContext { pub struct CliTestContext { pub config: Config, _test_dir: TempDir, + #[cfg(windows)] + _registry_guard: crate::cli::self_update::RegistryGuard, } impl CliTestContext { @@ -947,7 +968,21 @@ impl CliTestContext { config.distdir = Some(config.test_dist_dir.path().to_path_buf()); } - Self { config, _test_dir } + #[cfg(windows)] + let registry_guard = { + let guard = + crate::cli::self_update::RegistryGuard::new([&crate::cli::self_update::USER_PATH]) + .unwrap(); + config.set_registry_uuid(&guard.uuid); + guard + }; + + Self { + config, + _test_dir, + #[cfg(windows)] + _registry_guard: registry_guard, + } } /// Move the dist server to the specified scenario and restore it diff --git a/tests/suite/cli_inst_interactive.rs b/tests/suite/cli_inst_interactive.rs index 9b75e951c4..d4cb900244 100644 --- a/tests/suite/cli_inst_interactive.rs +++ b/tests/suite/cli_inst_interactive.rs @@ -5,8 +5,6 @@ use std::io::Write; use std::process::Stdio; use rustup::test::{Assert, CliTestContext, Config, SanitizedOutput, Scenario, this_host_tuple}; -#[cfg(windows)] -use rustup::test::{RegistryGuard, USER_PATH}; use rustup::utils::raw; fn run_input(config: &Config, args: &[&str], input: &str) -> Assert { @@ -44,8 +42,6 @@ fn run_input_with_env(config: &Config, args: &[&str], input: &str, env: &[(&str, #[tokio::test] async fn update() { let cx = CliTestContext::new(Scenario::SimpleV2).await; - #[cfg(windows)] - let _path_guard = RegistryGuard::new(&USER_PATH).unwrap(); run_input(&cx.config, &["rustup-init"], "\n\n"); run_input(&cx.config, &["rustup-init"], "\n\n").is_ok(); @@ -100,8 +96,6 @@ Rust is installed now. Great! #[tokio::test] async fn smoke_case_install_with_path_install() { let cx = CliTestContext::new(Scenario::SimpleV2).await; - #[cfg(windows)] - let _path_guard = RegistryGuard::new(&USER_PATH).unwrap(); run_input(&cx.config, &["rustup-init"], "\n\n") .is_ok() diff --git a/tests/suite/cli_paths.rs b/tests/suite/cli_paths.rs index 65b6170aab..00e0420132 100644 --- a/tests/suite/cli_paths.rs +++ b/tests/suite/cli_paths.rs @@ -469,9 +469,12 @@ error: could not amend shell profile[..] #[cfg(windows)] mod windows { + use retry::delay::{Fibonacci, jitter}; + use retry::{OperationResult, retry}; + use super::INIT_NONE; use rustup::test::{CliTestContext, Scenario}; - use rustup::test::{RegistryGuard, USER_PATH, get_path}; + use rustup::test::{USER_PATH, get_path}; use windows_registry::{HSTRING, Value}; @@ -479,36 +482,41 @@ mod windows { /// Smoke test for end-to-end code connectivity of the installer path mgmt on windows. async fn install_uninstall_affect_path() { let cx = CliTestContext::new(Scenario::Empty).await; - let _guard = RegistryGuard::new(&USER_PATH).unwrap(); + let uuid = cx.config.test_registry_uuid.as_ref().unwrap().to_owned(); let cfg_path = cx.config.cargodir.join("bin").display().to_string(); - let get_path_ = || { - HSTRING::try_from(get_path().unwrap().unwrap()) - .unwrap() - .to_string() + let read_path = |uuid: &str| -> Option { + retry( + Fibonacci::from_millis(1).map(jitter).take(21), + || match get_path(uuid).unwrap() { + Some(v) => OperationResult::Ok(HSTRING::try_from(v).unwrap().to_string()), + None => OperationResult::Retry(()), + }, + ) + .ok() }; cx.config.expect(&INIT_NONE).await.is_ok(); + let after_install = read_path(&uuid).unwrap_or_default(); assert!( - get_path_().contains(cfg_path.trim_matches('"')), - "`{}` not in `{}`", - cfg_path, - get_path_() + after_install.contains(cfg_path.trim_matches('"')), + "`{cfg_path}` not in `{after_install}`", ); cx.config .expect(&["rustup", "self", "uninstall", "-y"]) .await .is_ok(); - assert!(!get_path_().contains(&cfg_path)); + let after_uninstall = read_path(&uuid).unwrap_or_default(); + assert!(!after_uninstall.contains(&cfg_path)); } #[tokio::test] async fn uninstall_keeps_path_when_cargo_bin_is_non_empty() { let cx = CliTestContext::new(Scenario::Empty).await; - let _guard = RegistryGuard::new(&USER_PATH).unwrap(); + let uuid = cx.config.test_registry_uuid.as_ref().unwrap().to_owned(); let cfg_path = cx.config.cargodir.join("bin").display().to_string(); let get_path_ = || { - HSTRING::try_from(get_path().unwrap().unwrap()) + HSTRING::try_from(get_path(&uuid).unwrap().unwrap()) .unwrap() .to_string() }; @@ -530,10 +538,10 @@ mod windows { #[tokio::test] async fn uninstall_doesnt_affect_path_with_no_modify_path() { let cx = CliTestContext::new(Scenario::Empty).await; - let _guard = RegistryGuard::new(&USER_PATH).unwrap(); + let uuid = cx.config.test_registry_uuid.as_ref().unwrap().to_owned(); let cfg_path = cx.config.cargodir.join("bin").display().to_string(); let get_path_ = || { - HSTRING::try_from(get_path().unwrap().unwrap()) + HSTRING::try_from(get_path(&uuid).unwrap().unwrap()) .unwrap() .to_string() }; @@ -556,10 +564,10 @@ mod windows { async fn install_uninstall_affect_path_with_non_unicode() { use std::os::windows::ffi::OsStrExt; - use windows_registry::{CURRENT_USER, Type}; + use windows_registry::Type; let cx = CliTestContext::new(Scenario::Empty).await; - let _guard = RegistryGuard::new(&USER_PATH).unwrap(); + let uuid = cx.config.test_registry_uuid.as_ref().unwrap().to_owned(); // Set up a non unicode PATH let mut reg_value = Value::from([ 0x00, 0xD8, // leading surrogate @@ -567,11 +575,7 @@ mod windows { 0x00, 0x00, // null ]); reg_value.set_ty(Type::ExpandString); - CURRENT_USER - .create("Environment") - .unwrap() - .set_value("PATH", ®_value) - .unwrap(); + USER_PATH.set(Some(®_value), &uuid).unwrap(); // compute expected path after installation let mut expected = Value::from( @@ -589,12 +593,12 @@ mod windows { expected.set_ty(Type::ExpandString); cx.config.expect(&INIT_NONE).await.is_ok(); - assert_eq!(get_path().unwrap().unwrap(), expected); + assert_eq!(get_path(&uuid).unwrap().unwrap(), expected); cx.config .expect(&["rustup", "self", "uninstall", "-y"]) .await .is_ok(); - assert_eq!(get_path().unwrap().unwrap(), reg_value); + assert_eq!(get_path(&uuid).unwrap().unwrap(), reg_value); } } diff --git a/tests/suite/cli_self_upd.rs b/tests/suite/cli_self_upd.rs index 5794f2df33..01865399c6 100644 --- a/tests/suite/cli_self_upd.rs +++ b/tests/suite/cli_self_upd.rs @@ -13,12 +13,12 @@ use retry::{ delay::{Fibonacci, jitter}, retry, }; +#[cfg(windows)] +use rustup::test::RegistryValueId; use rustup::test::{ CROSS_ARCH1, CliTestContext, Scenario, SelfUpdateTestContext, calc_hash, output_release_file, this_host_tuple, }; -#[cfg(windows)] -use rustup::test::{RegistryGuard, RegistryValueId, USER_PATH}; use rustup::utils::{self, raw}; use rustup::{DUP_TOOLS, TOOLS}; #[cfg(windows)] @@ -58,8 +58,6 @@ async fn setup_installed() -> CliTestContext { #[tokio::test] async fn install_bins_to_cargo_home() { let cx = CliTestContext::new(Scenario::SimpleV2).await; - #[cfg(windows)] - let _path_guard = RegistryGuard::new(&USER_PATH).unwrap(); cx.config .expect(["rustup-init", "-y"]) @@ -102,8 +100,6 @@ info: default toolchain set to stable-[HOST_TUPLE] #[tokio::test] async fn proxies_are_relative_symlinks() { let cx = CliTestContext::new(Scenario::SimpleV2).await; - #[cfg(windows)] - let _path_guard = RegistryGuard::new(&USER_PATH).unwrap(); cx.config .expect(["rustup-init", "-y"]) @@ -142,8 +138,6 @@ info: default toolchain set to stable-[HOST_TUPLE] #[tokio::test] async fn install_twice() { let cx = CliTestContext::new(Scenario::SimpleV2).await; - #[cfg(windows)] - let _path_guard = RegistryGuard::new(&USER_PATH).unwrap(); cx.config.expect(["rustup-init", "-y"]).await.is_ok(); cx.config.expect(["rustup-init", "-y"]).await.is_ok(); @@ -473,18 +467,18 @@ async fn update_overwrites_programs_display_version() { let version = env!("CARGO_PKG_VERSION"); let cx = SelfUpdateTestContext::new(TEST_VERSION).await; - let _guard = RegistryGuard::new(&USER_RUSTUP_VERSION).unwrap(); + let uuid = cx.config.test_registry_uuid.as_deref().unwrap(); cx.config .expect(["rustup-init", "-y", "--no-modify-path"]) .await .is_ok(); USER_RUSTUP_VERSION - .set(Some(&Value::from(PLACEHOLDER_VERSION))) + .set(Some(&Value::from(PLACEHOLDER_VERSION)), uuid) .unwrap(); cx.config.expect(["rustup", "self", "update"]).await.is_ok(); assert_eq!( - USER_RUSTUP_VERSION.get().unwrap().unwrap(), + USER_RUSTUP_VERSION.get(uuid).unwrap().unwrap(), Value::from(version) ); }