Skip to content
Merged
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
57 changes: 18 additions & 39 deletions crates/socket-patch-core/src/api/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3293,9 +3293,9 @@ mod tests {
#[serial_test::serial]
async fn binary_url_uses_the_resolved_proxy_when_org_resolution_fails() {
const HASH: &str = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
let _env = OrgResolutionEnvGuard::isolate();
let saved_proxy = std::env::var("SOCKET_PROXY_URL").ok();
std::env::set_var("SOCKET_PROXY_URL", "http://env-proxy.test:9999/");
let _env = isolate_org_resolution_env();
let _proxy =
crate::test_env::EnvGuard::set("SOCKET_PROXY_URL", "http://env-proxy.test:9999/");

let (client, use_public_proxy) = get_api_client_with_overrides(ApiClientEnvOverrides {
api_url: Some("http://127.0.0.1:1".into()),
Expand All @@ -3309,44 +3309,23 @@ mod tests {
std::env::remove_var("SOCKET_PROXY_URL");
let (url, use_auth) = client.binary_url("blob", HASH);

match saved_proxy {
Some(v) => std::env::set_var("SOCKET_PROXY_URL", v),
None => std::env::remove_var("SOCKET_PROXY_URL"),
}

assert!(use_public_proxy);
assert!(client.api_token().is_none(), "a proxy client has no bearer");
assert_eq!(url, format!("http://env-proxy.test:9999/patch/blob/{HASH}"));
assert!(!use_auth, "the bearer must never target the proxy");
}

/// Guard that snapshots the env vars that can short-circuit org
/// auto-resolution, forces the "no ambient slug / offline flag /
/// socket-cli config" state, and restores the snapshot on drop (panic
/// included). Keeps the resolution tests below honest on a dev machine
/// with `socket login` state or ambient SOCKET_* vars.
struct OrgResolutionEnvGuard {
saved: Vec<(&'static str, Option<String>)>,
}
impl OrgResolutionEnvGuard {
fn isolate() -> Self {
let names = ["SOCKET_ORG_SLUG", "SOCKET_OFFLINE", "SOCKET_NO_CONFIG"];
let saved = names.iter().map(|&n| (n, std::env::var(n).ok())).collect();
std::env::remove_var("SOCKET_ORG_SLUG");
std::env::remove_var("SOCKET_OFFLINE");
std::env::set_var("SOCKET_NO_CONFIG", "1");
Self { saved }
}
}
impl Drop for OrgResolutionEnvGuard {
fn drop(&mut self) {
for (name, value) in self.saved.drain(..) {
match value {
Some(v) => std::env::set_var(name, v),
None => std::env::remove_var(name),
}
}
}
/// Forces the "no ambient slug / offline flag / socket-cli config"
/// state for the env vars that can short-circuit org auto-resolution;
/// the returned guard restores them on drop (panic included). Keeps
/// the resolution tests below honest on a dev machine with `socket
/// login` state or ambient SOCKET_* vars.
fn isolate_org_resolution_env() -> crate::test_env::EnvGuard {
crate::test_env::EnvGuard::many([
("SOCKET_ORG_SLUG", None),
("SOCKET_OFFLINE", None),
("SOCKET_NO_CONFIG", Some("1")),
])
}

/// The network half of `resolve_org_slug`: `GET /v0/organizations`
Expand All @@ -3360,7 +3339,7 @@ mod tests {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

let _env = OrgResolutionEnvGuard::isolate();
let _env = isolate_org_resolution_env();
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/v0/organizations"))
Expand Down Expand Up @@ -3403,7 +3382,7 @@ mod tests {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

let _env = OrgResolutionEnvGuard::isolate();
let _env = isolate_org_resolution_env();
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/v0/organizations"))
Expand Down Expand Up @@ -3445,7 +3424,7 @@ mod tests {

const HASH: &str = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
const UUID: &str = "11111111-2222-4333-8444-555555555555";
let _env = OrgResolutionEnvGuard::isolate();
let _env = isolate_org_resolution_env();
let token = format!("sktsec_{}_api", "x".repeat(44));
let proxy = "http://proxy.example.test";

Expand Down Expand Up @@ -4207,7 +4186,7 @@ mod tests {
#[tokio::test]
#[serial_test::serial]
async fn vendor_package_url_after_failed_org_resolution_targets_proxy_host() {
let _env = OrgResolutionEnvGuard::isolate();
let _env = isolate_org_resolution_env();
let (client, _) = get_api_client_with_overrides(ApiClientEnvOverrides {
api_url: Some("http://127.0.0.1:1".into()),
api_token: Some("sktsec_x_api".into()),
Expand Down
32 changes: 4 additions & 28 deletions crates/socket-patch-core/src/crawlers/deno_crawler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,7 @@ mod tests {
let deno_home = tempfile::tempdir().unwrap();
let jsr = deno_home.path().join("npm").join("jsr.io");
stage(&jsr, "@std", "path", "0.220.0").await;
let _g = EnvGuard::set("DENO_DIR", deno_home.path().to_str().unwrap());
let _g = EnvGuard::set("DENO_DIR", deno_home.path());

let crawler = DenoCrawler;
let opts = CrawlerOptions {
Expand All @@ -719,7 +719,7 @@ mod tests {
stage(&jsr, "@std", "path", "0.220.0").await;
stage(&jsr, "@std", "fs", "1.0.0").await;
stage(&jsr, "@other", "x", "2.0.0").await;
let _g = EnvGuard::set("DENO_DIR", deno_home.path().to_str().unwrap());
let _g = EnvGuard::set("DENO_DIR", deno_home.path());

let opts = CrawlerOptions {
cwd: project.path().to_path_buf(),
Expand Down Expand Up @@ -810,7 +810,7 @@ mod tests {
let jsr = deno_home.path().join("npm").join("jsr.io");
stage(&jsr, "@std", "path", "0.220.0").await;
stage(&jsr, "@std", "fs", "1.0.0").await;
let _g = EnvGuard::set("DENO_DIR", deno_home.path().to_str().unwrap());
let _g = EnvGuard::set("DENO_DIR", deno_home.path());
let opts = CrawlerOptions {
cwd: project.path().to_path_buf(),
global: false,
Expand Down Expand Up @@ -943,31 +943,7 @@ mod tests {

// ── deno_dir / cache-root resolution ───────────────────────────

/// Save and restore an env var around a closure body.
struct EnvGuard {
key: &'static str,
prev: Option<String>,
}
impl EnvGuard {
fn set(key: &'static str, value: &str) -> Self {
let prev = std::env::var(key).ok();
std::env::set_var(key, value);
Self { key, prev }
}
fn unset(key: &'static str) -> Self {
let prev = std::env::var(key).ok();
std::env::remove_var(key);
Self { key, prev }
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
match &self.prev {
Some(v) => std::env::set_var(self.key, v),
None => std::env::remove_var(self.key),
}
}
}
use crate::test_env::EnvGuard;

/// #444: only Deno's `bin/.<tool>/node_modules` whose config leaves
/// `nodeModulesDir` unset (or `none`/`false`), with no `package.json`,
Expand Down
38 changes: 7 additions & 31 deletions crates/socket-patch-core/src/crawlers/go_crawler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1216,7 +1216,7 @@ mod tests {
mkdir(&cache);
write(&project.join("go.mod"), "module example.com/app\n");
let env = (
EnvGuard::set("GOMODCACHE", cache.to_str().unwrap()),
EnvGuard::set("GOMODCACHE", &cache),
EnvGuard::unset("GOWORK"),
);
Fixture {
Expand Down Expand Up @@ -1412,7 +1412,7 @@ mod tests {
// GOWORK naming a file elsewhere (absolute on every platform:
// `/x` has no drive on Windows, so go rejects it as relative).
let elsewhere = f.project.parent().unwrap().join("elsewhere/go.work");
let _gowork = EnvGuard::set("GOWORK", &elsewhere.to_string_lossy());
let _gowork = EnvGuard::set("GOWORK", &elsewhere);
assert_eq!(f.crawl().await, walked);
}

Expand Down Expand Up @@ -1498,31 +1498,7 @@ mod tests {

// ---- get_gomodcache env tests ----

/// Save and restore an env var around a test body.
struct EnvGuard {
key: &'static str,
prev: Option<String>,
}
impl EnvGuard {
fn set(key: &'static str, value: &str) -> Self {
let prev = std::env::var(key).ok();
std::env::set_var(key, value);
Self { key, prev }
}
fn unset(key: &'static str) -> Self {
let prev = std::env::var(key).ok();
std::env::remove_var(key);
Self { key, prev }
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
match &self.prev {
Some(v) => std::env::set_var(self.key, v),
None => std::env::remove_var(self.key),
}
}
}
use crate::test_env::EnvGuard;

#[test]
#[serial_test::serial]
Expand All @@ -1547,7 +1523,7 @@ mod tests {
let _userprofile = EnvGuard::unset("USERPROFILE");
let first_a =
std::env::join_paths([gopath_a.path().as_os_str(), home_b.path().as_os_str()]).unwrap();
let _gopath = EnvGuard::set("GOPATH", first_a.to_str().unwrap());
let _gopath = EnvGuard::set("GOPATH", &first_a);
assert_eq!(
GoCrawler::get_gomodcache(),
Some(gopath_a.path().join("pkg").join("mod")),
Expand All @@ -1568,7 +1544,7 @@ mod tests {
// Case B: GOMODCACHE and GOPATH both set-but-empty fall all the way
// through to the $HOME/go/pkg/mod default.
let _gopath_empty = EnvGuard::set("GOPATH", "");
let _home_b = EnvGuard::set("HOME", home_b.path().to_str().unwrap());
let _home_b = EnvGuard::set("HOME", home_b.path());
assert_eq!(
GoCrawler::get_gomodcache(),
Some(home_b.path().join("go").join("pkg").join("mod")),
Expand Down Expand Up @@ -1602,7 +1578,7 @@ mod tests {
let gopath = dir.path().join("gopath");
let _gomodcache = EnvGuard::unset("GOMODCACHE");
let _gopath = EnvGuard::unset("GOPATH");
let _goenv = EnvGuard::set("GOENV", file.to_str().unwrap());
let _goenv = EnvGuard::set("GOENV", &file);

std::fs::write(&file, format!("GOMODCACHE={}\n", cache.display())).unwrap();
assert_eq!(GoCrawler::get_gomodcache(), Some(cache.clone()));
Expand All @@ -1614,7 +1590,7 @@ mod tests {
);

let env_cache = dir.path().join("env-cache");
let _env = EnvGuard::set("GOMODCACHE", env_cache.to_str().unwrap());
let _env = EnvGuard::set("GOMODCACHE", &env_cache);
assert_eq!(GoCrawler::get_gomodcache(), Some(env_cache));
}

Expand Down
34 changes: 5 additions & 29 deletions crates/socket-patch-core/src/crawlers/maven_crawler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2506,31 +2506,7 @@ mod tests {

// ---- m2_repo_path env tests ----

/// Save and restore an env var around a test body.
struct EnvGuard {
key: &'static str,
prev: Option<String>,
}
impl EnvGuard {
fn set(key: &'static str, value: &str) -> Self {
let prev = std::env::var(key).ok();
std::env::set_var(key, value);
Self { key, prev }
}
fn unset(key: &'static str) -> Self {
let prev = std::env::var(key).ok();
std::env::remove_var(key);
Self { key, prev }
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
match &self.prev {
Some(v) => std::env::set_var(self.key, v),
None => std::env::remove_var(self.key),
}
}
}
use crate::test_env::EnvGuard;

/// B66: with no usable home the default used to be the literal
/// RELATIVE `~/.m2/repository`, which resolves against the working
Expand Down Expand Up @@ -2584,7 +2560,7 @@ mod tests {
let _args = EnvGuard::unset("MAVEN_ARGS");
let _opts = EnvGuard::set(
"MAVEN_OPTS",
&format!("-Dmaven.repo.local={}", repo_local.path().display()),
format!("-Dmaven.repo.local={}", repo_local.path().display()),
);

let repo = MavenCrawler::m2_repo_path();
Expand Down Expand Up @@ -2612,8 +2588,8 @@ mod tests {
// Point the home directory at an empty dir so a developer's own
// `~/.m2/settings.xml` <localRepository> can't change the result.
let home = tempfile::tempdir().unwrap();
let _home = EnvGuard::set("HOME", home.path().to_str().unwrap());
let _profile = EnvGuard::set("USERPROFILE", home.path().to_str().unwrap());
let _home = EnvGuard::set("HOME", home.path());
let _profile = EnvGuard::set("USERPROFILE", home.path());

let repo = MavenCrawler::m2_repo_path();
assert_ne!(
Expand Down Expand Up @@ -2871,7 +2847,7 @@ mod tests {
.await
.unwrap();
let missing = project.path().join("no-such-m2-repo");
let _local = EnvGuard::set("MAVEN_REPO_LOCAL", missing.to_str().unwrap());
let _local = EnvGuard::set("MAVEN_REPO_LOCAL", &missing);

let crawler = MavenCrawler::new();
let options = CrawlerOptions {
Expand Down
23 changes: 1 addition & 22 deletions crates/socket-patch-core/src/crawlers/npm_crawler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5903,29 +5903,8 @@ mod tests {
}
}

/// Save and restore an env var around a test body (drop-safe).
#[cfg(target_os = "macos")]
struct EnvGuard {
key: &'static str,
prev: Option<String>,
}
#[cfg(target_os = "macos")]
impl EnvGuard {
fn set(key: &'static str, value: &std::ffi::OsStr) -> Self {
let prev = std::env::var(key).ok();
std::env::set_var(key, value);
Self { key, prev }
}
}
#[cfg(target_os = "macos")]
impl Drop for EnvGuard {
fn drop(&mut self) {
match &self.prev {
Some(v) => std::env::set_var(self.key, v),
None => std::env::remove_var(self.key),
}
}
}
use crate::test_env::EnvGuard;

/// Pins the literal volta (`.volta/tools/image/node/*/lib/
/// node_modules`) and fnm (`.fnm/node-versions/*/installation/lib/
Expand Down
Loading
Loading