Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore: remove duplicate `_tests` suffix from test module names

Steven Enamakeldfa7a225de0d
diff --git a/crates/openhuman-core/src/channels/bus/delivery_tests.rs b/crates/openhuman-core/src/channels/bus/delivery_tests.rs
index 0240e0ab1a..790ba985ae 100644
--- a/crates/openhuman-core/src/channels/bus/delivery_tests.rs
+++ b/crates/openhuman-core/src/channels/bus/delivery_tests.rs
@@ -1,23 +1,5 @@
use super::*;
-
-struct WorkspaceEnvGuard(Option<std::ffi::OsString>);
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- Self(previous)
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- match self.0.take() {
- Some(path) => std::env::set_var("OPENHUMAN_WORKSPACE", path),
- None => std::env::remove_var("OPENHUMAN_WORKSPACE"),
- }
- }
-}
+use crate::config::test_env::EnvVarGuard;
#[test]
fn outbound_body_has_stable_idempotency_key() {
@@ -35,7 +17,7 @@ async fn sender_methods_report_unavailable_without_a_hosted_session() {
.lock()
.unwrap_or_else(|error| error.into_inner());
let workspace = tempfile::tempdir().expect("temporary workspace");
- let _workspace_env = WorkspaceEnvGuard::set(workspace.path());
+ let _workspace_env = EnvVarGuard::workspace_unlocked(workspace.path());
let sender = BackendProgressiveSender;
assert!(matches!(
diff --git a/crates/openhuman-core/src/config/workspace/ops_tests.rs b/crates/openhuman-core/src/config/workspace/ops_tests.rs
index ffe59eda7a..dac1456c9e 100644
--- a/crates/openhuman-core/src/config/workspace/ops_tests.rs
+++ b/crates/openhuman-core/src/config/workspace/ops_tests.rs
@@ -1,34 +1,7 @@
use super::*;
use crate::config::TEST_ENV_LOCK as ENV_LOCK;
use tempfile::tempdir;
-
-/// RAII guard for `OPENHUMAN_WORKSPACE`. Sets the env var on
-/// construction and clears it on drop so a panicking test doesn't
-/// leak the override into sibling tests. Must be constructed while
-/// holding `ENV_LOCK` — mutating process env vars concurrently is
-/// unsafe and the lock serialises every test in this module.
-struct WorkspaceEnvGuard;
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- // SAFETY: Caller holds `ENV_LOCK`, so no other thread in
- // this process is reading or mutating this env var.
- unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- }
- Self
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- // SAFETY: Same contract as `set()` — `ENV_LOCK` is held for
- // the whole test, so no concurrent env access is possible.
- unsafe {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- }
- }
-}
+use crate::config::test_env::EnvVarGuard;
// ── ensure_workspace_file ──────────────────────────────────────
@@ -101,7 +74,7 @@ fn bootstrap_files_contain_soul_and_identity() {
async fn init_workspace_creates_dirs_and_files_in_fresh_workspace() {
let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
let tmp = tempdir().unwrap();
- let _env = WorkspaceEnvGuard::set(tmp.path());
+ let _env = EnvVarGuard::workspace_unlocked(tmp.path());
let value = init_workspace(false)
.await
@@ -141,7 +114,7 @@ async fn init_workspace_creates_dirs_and_files_in_fresh_workspace() {
async fn init_workspace_reports_existing_entries_on_second_call_without_force() {
let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
let tmp = tempdir().unwrap();
- let _env = WorkspaceEnvGuard::set(tmp.path());
+ let _env = EnvVarGuard::workspace_unlocked(tmp.path());
// First call populates the workspace.
init_workspace(false).await.expect("first init ok");
@@ -175,7 +148,7 @@ async fn init_workspace_reports_existing_entries_on_second_call_without_force()
async fn init_workspace_with_force_overwrites_existing_bootstrap_files() {
let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
let tmp = tempdir().unwrap();
- let _env = WorkspaceEnvGuard::set(tmp.path());
+ let _env = EnvVarGuard::workspace_unlocked(tmp.path());
let first = init_workspace(false).await.expect("initial init");
// The config loader may place the workspace at a subpath of the
diff --git a/crates/openhuman-core/src/core/dispatch_tests.rs b/crates/openhuman-core/src/core/dispatch_tests.rs
index e2b0c8794c..8120cd2d6f 100644
--- a/crates/openhuman-core/src/core/dispatch_tests.rs
+++ b/crates/openhuman-core/src/core/dispatch_tests.rs
@@ -1,37 +1,7 @@
use super::*;
use serde_json::json;
use std::ffi::OsString;
-
-/// Holds the shared config-env lock while an RPC handler reads the active
-/// workspace. The controller path loads and may initialize config, so it
-/// cannot safely share another test's transient workspace.
-struct WorkspaceEnvGuard {
- _lock: std::sync::MutexGuard<'static, ()>,
- previous: Option<OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let lock = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- Self {
- _lock: lock,
- previous,
- }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- match self.previous.take() {
- Some(value) => std::env::set_var("OPENHUMAN_WORKSPACE", value),
- None => std::env::remove_var("OPENHUMAN_WORKSPACE"),
- }
- }
-}
+use crate::config::test_env::EnvVarGuard;
fn test_state() -> AppState {
AppState {
@@ -98,7 +68,7 @@ async fn dispatch_delegates_to_tier2_for_domain_method() {
// Tier 2 dispatcher handles `openhuman.security_policy_info`, so
// it must succeed and return a policy object.
let workspace = tempfile::tempdir().expect("temporary workspace");
- let _workspace_env = WorkspaceEnvGuard::set(workspace.path());
+ let _workspace_env = EnvVarGuard::workspace(workspace.path());
let out = dispatch(test_state(), "openhuman.security_policy_info", json!({}))
.await
.expect("security_policy_info should route via tier 2");
diff --git a/crates/openhuman-core/src/core/runtime/subscribers_tests.rs b/crates/openhuman-core/src/core/runtime/subscribers_tests.rs
index 819a01c619..249e025b92 100644
--- a/crates/openhuman-core/src/core/runtime/subscribers_tests.rs
+++ b/crates/openhuman-core/src/core/runtime/subscribers_tests.rs
@@ -4,6 +4,7 @@ use std::sync::MutexGuard;
use super::{
group_first_time_when_bus_ready, learning_first_time_when_bus_ready, DomainSubscriberPlan,
};
+use crate::config::test_env::EnvVarGuard;
// ---- domain-subscriber gating (#4796 DoD item 3) ----------------------------
// `register_domain_subscribers` registers on the process-global event bus behind
@@ -208,7 +209,7 @@ async fn tool_timeout_seeds_on_channelless_core_boot() {
// Clear the operator override behind a panic-safe RAII guard: if any assertion
// below panics, `Drop` still restores the previous value, so sibling tests that
// share `TEST_ENV_LOCK` never inherit the cleared var.
- let _env = EnvVarGuard::remove_many(vec!["OPENHUMAN_TOOL_TIMEOUT_SECS"]);
+ let _env = EnvVarGuard::locked_unset_many(&["OPENHUMAN_TOOL_TIMEOUT_SECS"]);
// Distinctive, in-range (1..=3600) value so the assertion can only pass on a
// real seed, never on the default. Channel-less: `channels_config` stays empty,
@@ -237,39 +238,3 @@ async fn tool_timeout_seeds_on_channelless_core_boot() {
"channel-less core boot must seed the tool-execution timeout from [agent].agent_timeout_secs"
);
}
-
-struct EnvVarGuard {
- old_values: Vec<(&'static str, Option<OsString>)>,
- _lock: MutexGuard<'static, ()>,
-}
-
-impl EnvVarGuard {
- /// Remove the named vars (capturing their prior values) for the guard's
- /// lifetime, restoring each on `Drop`.
- fn remove_many(keys: Vec<&'static str>) -> Self {
- let lock = crate::config::TEST_ENV_LOCK
- .lock()
- .expect("test env lock poisoned");
- let mut old_values = Vec::with_capacity(keys.len());
- for key in keys {
- let old = std::env::var_os(key);
- std::env::remove_var(key);
- old_values.push((key, old));
- }
- Self {
- old_values,
- _lock: lock,
- }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- for (key, old) in self.old_values.iter().rev() {
- match old {
- Some(value) => std::env::set_var(key, value),
- None => std::env::remove_var(key),
- }
- }
- }
-}
diff --git a/crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rs b/crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rs
index 60f9904e58..7e9cb51592 100644
--- a/crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rs
+++ b/crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::config::test_env::EnvVarGuard;
#[test]
fn cron_completed_produces_agents_notification() {
@@ -431,32 +432,6 @@ async fn an_outage_is_filed_under_its_own_workspace_not_the_bridge_s() {
// workspace the user has switched away from would raise a banner naming that
// workspace's server and its error inside the account they are in.
-/// RAII guard for `OPENHUMAN_WORKSPACE`, which is the first thing
-/// `config::active_workspace_dir` consults — so it is how a test says which
-/// workspace is the active one. Mirrors the guard in
-/// `config::workspace::ops_tests`; must be held with `TEST_ENV_LOCK`.
-struct ActiveWorkspaceEnvGuard;
-
-impl ActiveWorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- // SAFETY: caller holds `TEST_ENV_LOCK`, so no other thread in this
- // process is reading or mutating this env var.
- unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- }
- Self
- }
-}
-
-impl Drop for ActiveWorkspaceEnvGuard {
- fn drop(&mut self) {
- // SAFETY: same contract as `set` — the lock is held for the whole test.
- unsafe {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- }
- }
-}
-
#[tokio::test]
async fn the_active_workspace_s_outage_is_announced() {
// Held for the whole test. NOT dropped explicitly: `_guard` is declared
@@ -467,7 +442,7 @@ async fn the_active_workspace_s_outage_is_announced() {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let active = tempfile::TempDir::new().unwrap();
- let _guard = ActiveWorkspaceEnvGuard::set(active.path());
+ let _guard = EnvVarGuard::workspace_unlocked(active.path());
// Ask the resolver what it made of the override rather than assuming:
// `OPENHUMAN_WORKSPACE` names a *config* root, and which subdirectory of
@@ -496,7 +471,7 @@ async fn a_switched_away_workspace_s_outage_is_not_announced() {
.unwrap_or_else(|poisoned| poisoned.into_inner());
let active = tempfile::TempDir::new().unwrap();
let switched_away = tempfile::TempDir::new().unwrap();
- let _guard = ActiveWorkspaceEnvGuard::set(active.path());
+ let _guard = EnvVarGuard::workspace_unlocked(active.path());
let resolved = crate::config::active_workspace_dir()
.await
diff --git a/crates/openhuman-core/src/integrations/composio/action_tool_tests.rs b/crates/openhuman-core/src/integrations/composio/action_tool_tests.rs
index 7b093f76f4..9435491c55 100644
--- a/crates/openhuman-core/src/integrations/composio/action_tool_tests.rs
+++ b/crates/openhuman-core/src/integrations/composio/action_tool_tests.rs
@@ -1,35 +1,7 @@
use super::*;
use crate::agent::harness::with_current_sandbox_mode;
use std::path::Path;
-
-struct WorkspaceEnvGuard {
- previous: Option<std::ffi::OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &Path) -> Self {
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- Self::set_current(path);
- Self { previous }
- }
-
- fn set_current(path: &Path) {
- unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- unsafe {
- match self.previous.take() {
- Some(value) => std::env::set_var("OPENHUMAN_WORKSPACE", value),
- None => std::env::remove_var("OPENHUMAN_WORKSPACE"),
- }
- }
- }
-}
+use crate::config::test_env::EnvVarGuard;
/// Build a minimal `Arc<Config>` with `composio.mode = "backend"`
/// (the default). The sandbox gate runs *before* any HTTP call or
@@ -203,7 +175,7 @@ fn sandbox_unset_leaves_per_action_execute_to_downstream() {
let _env_guard = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().expect("tempdir");
- let _workspace_guard = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace_guard = EnvVarGuard::workspace_unlocked(tmp.path());
let mut config = Config::default();
config.config_path = tmp.path().join("config.toml");
@@ -259,7 +231,7 @@ fn contract_gate_surfaces_full_contract_then_proceeds_on_retry() {
);
let tmp = tempfile::tempdir().expect("tempdir");
- let _workspace_guard = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace_guard = EnvVarGuard::workspace_unlocked(tmp.path());
let mut config = Config::default();
config.config_path = tmp.path().join("config.toml");
config.workspace_dir = tmp.path().join("workspace");
@@ -392,7 +364,7 @@ fn mode_toggle_between_calls_is_observed() {
// ── Backend half ────────────────────────────────────────────
let tmp_backend = tempfile::tempdir().expect("tempdir backend");
- let _workspace_guard = WorkspaceEnvGuard::set(tmp_backend.path());
+ let _workspace_guard = EnvVarGuard::workspace_unlocked(tmp_backend.path());
let mut backend_config = Config::default();
backend_config.config_path = tmp_backend.path().join("config.toml");
backend_config.workspace_dir = tmp_backend.path().join("workspace");
@@ -422,7 +394,7 @@ fn mode_toggle_between_calls_is_observed() {
// ── Direct half ─────────────────────────────────────────────
let tmp_direct = tempfile::tempdir().expect("tempdir direct");
- WorkspaceEnvGuard::set_current(tmp_direct.path());
+ EnvVarGuard::set_current(tmp_direct.path());
let mut direct_config = Config::default();
direct_config.config_path = tmp_direct.path().join("config.toml");
direct_config.workspace_dir = tmp_direct.path().join("workspace");
@@ -492,7 +464,7 @@ fn deferred_instance_returns_live_config_for_redaction() {
);
let tmp = tempfile::tempdir().expect("tempdir");
- let _workspace_guard = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace_guard = EnvVarGuard::workspace_unlocked(tmp.path());
let mut config = Config::default();
config.config_path = tmp.path().join("config.toml");
config.workspace_dir = tmp.path().join("workspace");
diff --git a/crates/openhuman-core/src/integrations/composio/ops_tests.rs b/crates/openhuman-core/src/integrations/composio/ops_tests.rs
index c2c0e35e93..0223caed61 100644
--- a/crates/openhuman-core/src/integrations/composio/ops_tests.rs
+++ b/crates/openhuman-core/src/integrations/composio/ops_tests.rs
@@ -33,61 +33,7 @@ use chrono::{TimeZone, Utc};
use serde_json::{json, Value};
use std::collections::HashMap;
use tinymemory_api::chunks::{chunk_id, Chunk, Metadata, SourceKind, SourceRef};
-
-struct WorkspaceEnvGuard {
- previous: Option<std::ffi::OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- }
- Self { previous }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- match self.previous.take() {
- Some(prev) => unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", prev);
- },
- None => unsafe {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- },
- }
- }
-}
-
-struct EnvVarGuard {
- key: &'static str,
- previous: Option<std::ffi::OsString>,
-}
-
-impl EnvVarGuard {
- fn set(key: &'static str, value: &str) -> Self {
- let previous = std::env::var_os(key);
- unsafe {
- std::env::set_var(key, value);
- }
- Self { key, previous }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- match self.previous.take() {
- Some(prev) => unsafe {
- std::env::set_var(self.key, prev);
- },
- None => unsafe {
- std::env::remove_var(self.key);
- },
- }
- }
-}
+use crate::config::test_env::EnvVarGuard;
struct DirectAuthFailureGuard {
key_id: u64,
diff --git a/crates/openhuman-core/src/integrations/composio/tools_tests.rs b/crates/openhuman-core/src/integrations/composio/tools_tests.rs
index 90b7044caa..8db43bb44a 100644
--- a/crates/openhuman-core/src/integrations/composio/tools_tests.rs
+++ b/crates/openhuman-core/src/integrations/composio/tools_tests.rs
@@ -3,55 +3,7 @@ use std::path::Path;
use std::sync::Arc;
use tinytools::ToolResult;
-struct WorkspaceEnvGuard {
- previous: Option<std::ffi::OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &Path) -> Self {
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- }
- Self { previous }
- }
-}
-
-struct HomeEnvGuard {
- previous: Option<std::ffi::OsString>,
-}
-
-impl HomeEnvGuard {
- fn set(path: &Path) -> Self {
- let previous = std::env::var_os("HOME");
- unsafe {
- std::env::set_var("HOME", path);
- }
- Self { previous }
- }
-}
-
-impl Drop for HomeEnvGuard {
- fn drop(&mut self) {
- unsafe {
- match self.previous.take() {
- Some(value) => std::env::set_var("HOME", value),
- None => std::env::remove_var("HOME"),
- }
- }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- unsafe {
- match self.previous.take() {
- Some(value) => std::env::set_var("OPENHUMAN_WORKSPACE", value),
- None => std::env::remove_var("OPENHUMAN_WORKSPACE"),
- }
- }
- }
-}
+use crate::config::test_env::EnvVarGuard;
/// Minimal `Arc<Config>` for the agent-tool constructors. All five
/// composio agent tools now resolve their client per call through
diff --git a/crates/openhuman-core/src/memory/ops/documents_tests.rs b/crates/openhuman-core/src/memory/ops/documents_tests.rs
index 10fd070ef1..06ce37aba8 100644
--- a/crates/openhuman-core/src/memory/ops/documents_tests.rs
+++ b/crates/openhuman-core/src/memory/ops/documents_tests.rs
@@ -1,54 +1,15 @@
use serde_json::json;
use super::*;
-
-/// Pins `OPENHUMAN_WORKSPACE` to the shared memory workspace for a test's
-/// duration, holding [`crate::config::TEST_ENV_LOCK`] so sibling
-/// tests that mutate the env var (e.g. `config::ops`, `update::ops`,
-/// autonomy settings) cannot change it mid-run.
-///
-/// `documents` tests are the only `memory::ops` tests that resolve the
-/// workspace from the env var (`memory_init` → `current_workspace_dir` →
-/// `Config::load_or_init`), so without this pin they race those tests and
-/// `memory_init` intermittently fails — surfaced under `cargo-llvm-cov`
-/// timing. Lock order is `GLOBAL_MEMORY_TEST_LOCK` → `TEST_ENV_LOCK` (the
-/// test takes the memory lock first, then this guard takes the env lock); no
-/// code path takes them in the opposite order, so there is no deadlock.
-struct WorkspaceEnvGuard {
- _env_lock: std::sync::MutexGuard<'static, ()>,
- previous: Option<std::ffi::OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn pin(workspace: &std::path::Path) -> Self {
- let env_lock = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- std::env::set_var("OPENHUMAN_WORKSPACE", workspace);
- Self {
- _env_lock: env_lock,
- previous,
- }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- match self.previous.take() {
- Some(value) => std::env::set_var("OPENHUMAN_WORKSPACE", value),
- None => std::env::remove_var("OPENHUMAN_WORKSPACE"),
- }
- }
-}
+use crate::config::test_env::EnvVarGuard;
/// Bind the shared memory client and pin `OPENHUMAN_WORKSPACE` to its
-/// workspace for the test (see [`WorkspaceEnvGuard`]). Hold the returned
+/// workspace for the test (see [`EnvVarGuard`]). Hold the returned
/// guard for the whole test: `let _env = ensure_memory_client();`.
#[must_use]
-fn ensure_memory_client() -> WorkspaceEnvGuard {
+fn ensure_memory_client() -> EnvVarGuard {
let workspace = crate::memory::ops::shared_memory_test_workspace();
- WorkspaceEnvGuard::pin(&workspace)
+ EnvVarGuard::workspace(&workspace)
}
fn unique_namespace(prefix: &str) -> String {
diff --git a/crates/openhuman-core/src/memory/ops/files_tests.rs b/crates/openhuman-core/src/memory/ops/files_tests.rs
index 15f1fe2653..7c09fb0d72 100644
--- a/crates/openhuman-core/src/memory/ops/files_tests.rs
+++ b/crates/openhuman-core/src/memory/ops/files_tests.rs
@@ -4,32 +4,7 @@ use tempfile::TempDir;
use super::*;
use crate::config::TEST_ENV_LOCK;
-
-struct WorkspaceEnvGuard {
- previous: Option<OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- }
- Self { previous }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- unsafe {
- if let Some(previous) = self.previous.take() {
- std::env::set_var("OPENHUMAN_WORKSPACE", previous);
- } else {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- }
- }
- }
-}
+use crate::config::test_env::EnvVarGuard;
#[tokio::test]
async fn write_read_and_list_memory_files_roundtrip() {
@@ -37,7 +12,7 @@ async fn write_read_and_list_memory_files_roundtrip() {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let tmp = TempDir::new().expect("tempdir");
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace_unlocked(tmp.path());
let write = ai_write_memory_file(WriteMemoryFileRequest {
relative_path: "notes/today.md".to_string(),
@@ -92,7 +67,7 @@ async fn list_memory_files_skips_internal_sqlite_artifacts() {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let tmp = TempDir::new().expect("tempdir");
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace_unlocked(tmp.path());
let memory_root = super::super::helpers::resolve_existing_memory_path("")
.await
@@ -126,7 +101,7 @@ async fn list_memory_files_rejects_non_directory_target() {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let tmp = TempDir::new().expect("tempdir");
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace_unlocked(tmp.path());
tokio::fs::create_dir_all(tmp.path().join("memory"))
.await
@@ -152,7 +127,7 @@ async fn read_and_write_memory_files_reject_path_traversal() {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let tmp = TempDir::new().expect("tempdir");
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace_unlocked(tmp.path());
let write_err = ai_write_memory_file(WriteMemoryFileRequest {
relative_path: "../secrets.txt".to_string(),
@@ -176,7 +151,7 @@ async fn list_and_read_memory_files_reject_absolute_paths() {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let tmp = TempDir::new().expect("tempdir");
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace_unlocked(tmp.path());
let list_err = ai_list_memory_files(ListMemoryFilesRequest {
relative_dir: "/tmp".to_string(),
@@ -207,7 +182,7 @@ async fn read_memory_file_surfaces_missing_file_error() {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let tmp = TempDir::new().expect("tempdir");
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace_unlocked(tmp.path());
let err = ai_read_memory_file(ReadMemoryFileRequest {
relative_path: "missing.md".to_string(),
@@ -226,7 +201,7 @@ async fn read_memory_file_surfaces_invalid_utf8_error() {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let tmp = TempDir::new().expect("tempdir");
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace_unlocked(tmp.path());
let memory_root = super::super::helpers::resolve_existing_memory_path("")
.await
@@ -252,7 +227,7 @@ async fn write_memory_file_rejects_symlink_targets() {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let tmp = TempDir::new().expect("tempdir");
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace_unlocked(tmp.path());
let memory_root = super::super::helpers::resolve_existing_memory_path("")
.await
@@ -281,7 +256,7 @@ async fn list_memory_files_skips_symlink_entries() {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let tmp = TempDir::new().expect("tempdir");
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace_unlocked(tmp.path());
let memory_root = super::super::helpers::resolve_existing_memory_path("")
.await
diff --git a/crates/openhuman-core/src/memory/ops/learn_tests.rs b/crates/openhuman-core/src/memory/ops/learn_tests.rs
index ac01dca49c..316d65adf3 100644
--- a/crates/openhuman-core/src/memory/ops/learn_tests.rs
+++ b/crates/openhuman-core/src/memory/ops/learn_tests.rs
@@ -4,40 +4,12 @@ use serde_json::json;
use super::*;
use crate::memory::api::types::NamespaceDocumentInput;
+use crate::config::test_env::EnvVarGuard;
fn ensure_memory_client() {
crate::memory::ops::shared_memory_test_workspace();
}
-struct WorkspaceEnvGuard {
- _lock: std::sync::MutexGuard<'static, ()>,
- previous: Option<OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let lock = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- Self {
- _lock: lock,
- previous,
- }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- if let Some(previous) = self.previous.as_ref() {
- std::env::set_var("OPENHUMAN_WORKSPACE", previous);
- } else {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- }
- }
-}
-
/// Seed a document through the guard — the same door
/// [`memory_learn_all`] enumerates namespaces through.
///
diff --git a/crates/openhuman-core/src/memory/query/ingest_document_tests.rs b/crates/openhuman-core/src/memory/query/ingest_document_tests.rs
index 0699959a83..a04a0421ed 100644
--- a/crates/openhuman-core/src/memory/query/ingest_document_tests.rs
+++ b/crates/openhuman-core/src/memory/query/ingest_document_tests.rs
@@ -7,36 +7,10 @@ use crate::config::Config;
use crate::config::TEST_ENV_LOCK;
use serde_json::json;
use tinytools::Tool;
+use crate::config::test_env::EnvVarGuard;
-struct WorkspaceEnvGuard {
- _lock: std::sync::MutexGuard<'static, ()>,
- previous: Option<OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- Self {
- _lock: lock,
- previous,
- }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- if let Some(previous) = self.previous.as_ref() {
- std::env::set_var("OPENHUMAN_WORKSPACE", previous);
- } else {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- }
- }
-}
-
-async fn isolated_config(tmp: &TempDir) -> (WorkspaceEnvGuard, Config) {
- let guard = WorkspaceEnvGuard::set(tmp.path());
+async fn isolated_config(tmp: &TempDir) -> (EnvVarGuard, Config) {
+ let guard = EnvVarGuard::workspace(tmp.path());
let config = Config::load_or_init().await.expect("load config");
// `list_chunks_rpc` reads through the bound driver now, and a unit-test
// workspace binds the null one — which serves no Chunks family and
diff --git a/crates/openhuman-core/src/memory/sources/rpc_tests.rs b/crates/openhuman-core/src/memory/sources/rpc_tests.rs
index 3d35cb6a19..e33727de6e 100644
--- a/crates/openhuman-core/src/memory/sources/rpc_tests.rs
+++ b/crates/openhuman-core/src/memory/sources/rpc_tests.rs
@@ -22,6 +22,7 @@ use crate::memory::sources::types::MemorySourceEntry;
use crate::memory::api::provider::MemoryProvider;
use std::sync::Arc;
use tinymemory_api::null::{NullMemoryProvider, NULL_DRIVER_ID};
+use crate::config::test_env::EnvVarGuard;
/// The refusal always names the bound driver. That is the whole contract of
/// this message: an operator reading it has to be able to tell "no driver
@@ -184,39 +185,6 @@ fn composio_rows_dispatch_to_the_connector_and_everything_else_to_the_driver() {
// before now, which went with the engine (#6161) although none of this is the
// engine's (#6172).
-/// Pins `OPENHUMAN_WORKSPACE` for the duration, holding the crate's env lock so
-/// concurrent tests cannot observe the change. `add_rpc` writes through
-/// `registry::add_source`, which resolves its config with
-/// `load_config_with_timeout` — process-global, so the workspace has to be
-/// pinned rather than passed.
-struct WorkspaceEnvGuard {
- _env_lock: std::sync::MutexGuard<'static, ()>,
- previous: Option<std::ffi::OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn pin(workspace: &std::path::Path) -> Self {
- let env_lock = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- std::env::set_var("OPENHUMAN_WORKSPACE", workspace);
- Self {
- _env_lock: env_lock,
- previous,
- }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- match self.previous.take() {
- Some(value) => std::env::set_var("OPENHUMAN_WORKSPACE", value),
- None => std::env::remove_var("OPENHUMAN_WORKSPACE"),
- }
- }
-}
-
fn github_add_request() -> AddRequest {
AddRequest {
kind: tinymemory_sources::types::SourceKind::GithubRepo,
@@ -248,7 +216,7 @@ async fn add_generates_an_id_and_caps_a_request_that_left_its_limits_unset() {
let tmp = tempfile::TempDir::new().expect("tempdir");
let workspace = tmp.path().join("workspace");
std::fs::create_dir_all(&workspace).expect("workspace dir");
- let _env = WorkspaceEnvGuard::pin(&workspace);
+ let _env = EnvVarGuard::workspace(&workspace);
let added = add_rpc(github_add_request())
.await
diff --git a/crates/openhuman-core/src/memory/tools/goals_tests.rs b/crates/openhuman-core/src/memory/tools/goals_tests.rs
index 2a62c31cbb..a640b1377f 100644
--- a/crates/openhuman-core/src/memory/tools/goals_tests.rs
+++ b/crates/openhuman-core/src/memory/tools/goals_tests.rs
@@ -17,33 +17,7 @@ use tempfile::TempDir;
use crate::config::TEST_ENV_LOCK;
use tinytools::Tool;
-
-struct WorkspaceEnvGuard {
- _lock: std::sync::MutexGuard<'static, ()>,
- previous: Option<OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- Self {
- _lock: lock,
- previous,
- }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- if let Some(previous) = self.previous.as_ref() {
- std::env::set_var("OPENHUMAN_WORKSPACE", previous);
- } else {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- }
- }
-}
+use crate::config::test_env::EnvVarGuard;
/// Reset the shared goals document, and say why that has to happen at all.
///
@@ -70,7 +44,7 @@ async fn reset_shared_goals() {
async fn add_then_list_reflects_change() {
let _serial = crate::memory::ops::GLOBAL_MEMORY_TEST_LOCK.lock().await;
let tmp = TempDir::new().expect("tempdir");
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace(tmp.path());
reset_shared_goals().await;
let goals = GoalsTool::new(tmp.path().to_path_buf());
@@ -88,7 +62,7 @@ async fn add_then_list_reflects_change() {
async fn edit_and_delete_unknown_id_error() {
let _serial = crate::memory::ops::GLOBAL_MEMORY_TEST_LOCK.lock().await;
let tmp = TempDir::new().expect("tempdir");
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace(tmp.path());
reset_shared_goals().await;
let goals = GoalsTool::new(tmp.path().to_path_buf());
@@ -112,7 +86,7 @@ async fn edit_and_delete_unknown_id_error() {
async fn add_refuses_pii_bearing_text_with_the_specific_reason() {
let _serial = crate::memory::ops::GLOBAL_MEMORY_TEST_LOCK.lock().await;
let tmp = TempDir::new().expect("tempdir");
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace(tmp.path());
reset_shared_goals().await;
let add = GoalsTool::new(tmp.path().to_path_buf());
diff --git a/crates/openhuman-core/src/memory/tools/tool_memory/guard_tests.rs b/crates/openhuman-core/src/memory/tools/tool_memory/guard_tests.rs
index 7cda34a603..2a53bf7d41 100644
--- a/crates/openhuman-core/src/memory/tools/tool_memory/guard_tests.rs
+++ b/crates/openhuman-core/src/memory/tools/tool_memory/guard_tests.rs
@@ -20,6 +20,7 @@ use crate::security::policy::{AutonomyLevel, SecurityPolicy};
use serde_json::json;
use std::sync::Arc;
use tinytools::Tool;
+use crate::config::test_env::EnvVarGuard;
/// Install `autonomy` as the live policy for this test thread only. Same
/// shape `memory/guard/policy_tests.rs` uses; `#[tokio::test]`'s
@@ -36,35 +37,8 @@ fn scoped_tier(autonomy: AutonomyLevel) -> live_policy::TestPolicyGuard {
)
}
-struct WorkspaceEnvGuard {
- _lock: std::sync::MutexGuard<'static, ()>,
- previous: Option<OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- Self {
- _lock: lock,
- previous,
- }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- if let Some(previous) = self.previous.as_ref() {
- std::env::set_var("OPENHUMAN_WORKSPACE", previous);
- } else {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- }
- }
-}
-
-async fn isolated_config(tmp: &TempDir) -> (WorkspaceEnvGuard, Config) {
- let guard = WorkspaceEnvGuard::set(tmp.path());
+async fn isolated_config(tmp: &TempDir) -> (EnvVarGuard, Config) {
+ let guard = EnvVarGuard::workspace(tmp.path());
let config = Config::load_or_init().await.expect("load config");
(guard, config)
}
diff --git a/crates/openhuman-core/src/memory/tree/tree_runtime/cli_tests.rs b/crates/openhuman-core/src/memory/tree/tree_runtime/cli_tests.rs
index a432b2ad97..48de5c997f 100644
--- a/crates/openhuman-core/src/memory/tree/tree_runtime/cli_tests.rs
+++ b/crates/openhuman-core/src/memory/tree/tree_runtime/cli_tests.rs
@@ -6,67 +6,12 @@ use tempfile::TempDir;
use crate::config::TEST_ENV_LOCK;
use super::*;
+use crate::config::test_env::EnvVarGuard;
fn lock_env() -> std::sync::MutexGuard<'static, ()> {
TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner())
}
-struct WorkspaceEnvGuard {
- _lock: std::sync::MutexGuard<'static, ()>,
- previous: Option<OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let lock = lock_env();
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- Self {
- _lock: lock,
- previous,
- }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- if let Some(previous) = self.previous.as_ref() {
- std::env::set_var("OPENHUMAN_WORKSPACE", previous);
- } else {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- }
- }
-}
-
-struct EnvVarGuard {
- key: &'static str,
- previous: Option<OsString>,
-}
-
-impl EnvVarGuard {
- fn set(key: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {
- let previous = std::env::var_os(key);
- std::env::set_var(key, value);
- Self { key, previous }
- }
-
- fn remove(key: &'static str) -> Self {
- let previous = std::env::var_os(key);
- std::env::remove_var(key);
- Self { key, previous }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- if let Some(previous) = self.previous.as_ref() {
- std::env::set_var(self.key, previous);
- } else {
- std::env::remove_var(self.key);
- }
- }
-}
-
#[test]
fn is_help_matches_supported_aliases() {
assert!(is_help("-h"));
@@ -153,7 +98,7 @@ fn help_paths_for_subcommands_return_ok() {
#[test]
fn ingest_prefers_file_input_and_surfaces_read_errors() {
let tmp = TempDir::new().unwrap();
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace(tmp.path());
let missing = tmp.path().join("missing.txt");
let args = vec![
@@ -175,7 +120,7 @@ fn run_summarize_errors_cleanly_without_provider() {
// Users must enable local AI (Ollama) or set cloud_summarization_opt_in
// in config (or via OPENHUMAN_MEMORY_TREE_CLOUD_SUMMARIZATION=true).
let tmp = TempDir::new().unwrap();
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace(tmp.path());
let err = run_summarize(&["fresh-ns".to_string()])
.expect_err("should error without any summarization provider");
@@ -189,7 +134,7 @@ fn run_summarize_errors_cleanly_without_provider() {
#[test]
fn load_config_uses_isolated_workspace_and_env_overrides() {
let tmp = TempDir::new().unwrap();
- let _workspace = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace = EnvVarGuard::workspace(tmp.path());
let _model = EnvVarGuard::set("OPENHUMAN_MODEL", "custom-model");
let _language = EnvVarGuard::set("OPENHUMAN_OUTPUT_LANGUAGE", "fr-CA");
@@ -208,13 +153,13 @@ fn init_logging_sets_default_rust_log_only_when_needed() {
let _lock = lock_env();
{
- let _rust_log = EnvVarGuard::remove("RUST_LOG");
+ let _rust_log = EnvVarGuard::unset("RUST_LOG");
init_logging(false);
assert_eq!(std::env::var("RUST_LOG").ok().as_deref(), Some("warn"));
}
{
- let _rust_log = EnvVarGuard::remove("RUST_LOG");
+ let _rust_log = EnvVarGuard::unset("RUST_LOG");
init_logging(true);
assert!(std::env::var_os("RUST_LOG").is_none());
}
diff --git a/crates/openhuman-core/src/platform/update/ops_tests_2_tests.rs b/crates/openhuman-core/src/platform/update/ops_tests_2_tests.rs
index 82cfedcd08..d2e813cefe 100644
--- a/crates/openhuman-core/src/platform/update/ops_tests_2_tests.rs
+++ b/crates/openhuman-core/src/platform/update/ops_tests_2_tests.rs
@@ -1,6 +1,7 @@
use super::*;
use crate::config::TEST_ENV_LOCK;
use tempfile::TempDir;
+use crate::config::test_env::EnvVarGuard;
async fn write_update_policy(tmp: &TempDir, update: UpdateConfig) {
let mut cfg = crate::config::Config {
@@ -91,7 +92,7 @@ fn validate_asset_name_rejects_unprefixed_asset() {
// env var. Tests that don't lock against the disabled-mutations
// case can race with it: the disabled test sets the env var, the
// sibling test (running on another thread) clears or shadows it
-// between `WorkspaceEnvGuard::set` and the await inside
+// between `EnvVarGuard::set` and the await inside
// `update_apply`, and the disabled test then loads a default
// policy (where `rpc_mutations_enabled = true`), proceeds past the
// gate, and fails its `contains("rpc_mutations_enabled=false")`
@@ -129,24 +130,11 @@ async fn update_apply_rejects_unsafe_asset_name() {
.any(|l| l.contains("update_apply rejected")));
}
-struct WorkspaceEnvGuard;
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- Self
- }
-}
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- }
-}
-
#[tokio::test]
async fn update_apply_rejects_when_rpc_mutations_disabled() {
let _guard = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let tmp = TempDir::new().unwrap();
- let _workspace_guard = WorkspaceEnvGuard::set(tmp.path());
+ let _workspace_guard = EnvVarGuard::workspace_unlocked(tmp.path());
write_update_policy(
&tmp,
UpdateConfig {
diff --git a/crates/openhuman-core/src/security/credentials/openai_oauth/flow_tests.rs b/crates/openhuman-core/src/security/credentials/openai_oauth/flow_tests.rs
index 2b42fae982..346a2b0bc3 100644
--- a/crates/openhuman-core/src/security/credentials/openai_oauth/flow_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/openai_oauth/flow_tests.rs
@@ -21,6 +21,7 @@ use tinyinference_providers::oauth::{
};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
+use crate::config::test_env::EnvVarGuard;
fn tiny_oauth_config(config: &OAuthConfig, redirect_uri: &str) -> OAuthConfig {
let mut config = config.clone();
@@ -28,30 +29,6 @@ fn tiny_oauth_config(config: &OAuthConfig, redirect_uri: &str) -> OAuthConfig {
config
}
-struct EnvVarGuard {
- key: &'static str,
- previous: Option<std::ffi::OsString>,
-}
-
-impl EnvVarGuard {
- fn set(key: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {
- let previous = std::env::var_os(key);
- unsafe { std::env::set_var(key, value) };
- Self { key, previous }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- unsafe {
- match self.previous.take() {
- Some(value) => std::env::set_var(self.key, value),
- None => std::env::remove_var(self.key),
- }
- }
- }
-}
-
fn test_config(tmp: &tempfile::TempDir) -> Config {
Config {
config_path: tmp.path().join("config.toml"),
diff --git a/crates/openhuman-core/src/security/credentials/ops/boot_env_tests.rs b/crates/openhuman-core/src/security/credentials/ops/boot_env_tests.rs
index 7e288e7ce4..04bbfb2b59 100644
--- a/crates/openhuman-core/src/security/credentials/ops/boot_env_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/boot_env_tests.rs
@@ -1,6 +1,7 @@
use super::*;
use crate::config::Config;
use tempfile::TempDir;
+use crate::config::test_env::EnvVarGuard;
fn config_in(tmp: &TempDir) -> Config {
Config {
@@ -11,13 +12,6 @@ fn config_in(tmp: &TempDir) -> Config {
}
}
-struct EnvGuard(&'static str);
-impl Drop for EnvGuard {
- fn drop(&mut self) {
- unsafe { std::env::remove_var(self.0) };
- }
-}
-
#[test]
fn api_key_env_seeds_only_an_empty_store() {
let _lock = crate::config::TEST_ENV_LOCK
@@ -25,7 +19,7 @@ fn api_key_env_seeds_only_an_empty_store() {
.unwrap_or_else(|e| e.into_inner());
let tmp = TempDir::new().unwrap();
let config = config_in(&tmp);
- let _guard = EnvGuard(BACKEND_API_KEY_ENV);
+ let _guard = EnvVarGuard::unset(BACKEND_API_KEY_ENV);
unsafe { std::env::set_var(BACKEND_API_KEY_ENV, " ") };
seed_api_key_from_env(&config);
@@ -57,7 +51,7 @@ async fn session_env_is_ignored_without_a_subject_and_when_unset() {
.unwrap_or_else(|e| e.into_inner());
let tmp = TempDir::new().unwrap();
let config = config_in(&tmp);
- let _guard = EnvGuard(BACKEND_SESSION_TOKEN_ENV);
+ let _guard = EnvVarGuard::unset(BACKEND_SESSION_TOKEN_ENV);
unsafe { std::env::remove_var(BACKEND_SESSION_TOKEN_ENV) };
seed_session_from_env(&config).await;
diff --git a/crates/openhuman-core/src/security/credentials/ops_tests.rs b/crates/openhuman-core/src/security/credentials/ops_tests.rs
index 10153aa60e..5631aa9a06 100644
--- a/crates/openhuman-core/src/security/credentials/ops_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/ops_tests.rs
@@ -12,36 +12,7 @@ use base64::Engine;
use serde_json::json;
use tempfile::TempDir;
use tokio::net::TcpListener;
-
-struct EnvVarGuard {
- key: &'static str,
- previous: Option<std::ffi::OsString>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, path: &std::path::Path) -> Self {
- let previous = std::env::var_os(key);
- unsafe { std::env::set_var(key, path) };
- Self { key, previous }
- }
-
- fn set(key: &'static str, value: &str) -> Self {
- let previous = std::env::var_os(key);
- unsafe { std::env::set_var(key, value) };
- Self { key, previous }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- unsafe {
- match self.previous.take() {
- Some(value) => std::env::set_var(self.key, value),
- None => std::env::remove_var(self.key),
- }
- }
- }
-}
+use crate::config::test_env::EnvVarGuard;
fn test_config(tmp: &TempDir) -> Config {
let config = Config {
diff --git a/crates/openhuman-core/src/security/keyring/store_tests.rs b/crates/openhuman-core/src/security/keyring/store_tests.rs
index c09840083f..5c818cf69c 100644
--- a/crates/openhuman-core/src/security/keyring/store_tests.rs
+++ b/crates/openhuman-core/src/security/keyring/store_tests.rs
@@ -21,29 +21,7 @@ use super::test_scope::ScopedWorkspace;
use super::{resolve_workspace_dir, workspace_dir_for_file_backend};
use crate::config::TEST_ENV_LOCK;
use crate::security::keyring;
-
-/// Restores an env var to its prior value on drop.
-struct EnvVarGuard {
- key: &'static str,
- previous: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set(key: &'static str, value: &std::path::Path) -> Self {
- let previous = std::env::var(key).ok();
- std::env::set_var(key, value);
- Self { key, previous }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- match self.previous.take() {
- Some(value) => std::env::set_var(self.key, value),
- None => std::env::remove_var(self.key),
- }
- }
-}
+use crate::config::test_env::EnvVarGuard;
/// The root-cause pin: in test builds the keyring workspace must not be
/// steerable by a process-wide env var, because any test can set it while
diff --git a/crates/openhuman-core/src/security/ops_tests.rs b/crates/openhuman-core/src/security/ops_tests.rs
index 37849e4372..83fb534331 100644
--- a/crates/openhuman-core/src/security/ops_tests.rs
+++ b/crates/openhuman-core/src/security/ops_tests.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::config::test_env::EnvVarGuard;
#[test]
fn security_policy_info_returns_all_documented_fields() {
@@ -64,33 +65,6 @@ fn security_policy_info_reflects_configured_action_budget() {
assert_eq!(outcome.value["max_actions_per_hour"], json!(77));
}
-/// RAII guard that records the prior value of an env var, sets a new one
-/// for the duration of a test, and restores the prior value on drop —
-/// including across panics. Without this, a panicking assertion would
-/// leak `OPENHUMAN_MAX_ACTIONS_PER_HOUR` into later tests in the same
-/// process even though they share `TEST_ENV_LOCK`.
-struct EnvGuard {
- key: &'static str,
- prior: Option<String>,
-}
-
-impl EnvGuard {
- fn set(key: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {
- let prior = std::env::var(key).ok();
- std::env::set_var(key, value);
- Self { key, prior }
- }
-}
-
-impl Drop for EnvGuard {
- fn drop(&mut self) {
- match self.prior.take() {
- Some(v) => std::env::set_var(self.key, v),
- None => std::env::remove_var(self.key),
- }
- }
-}
-
/// Regression coverage for the chained env-overlay → load-with-timeout →
/// policy-info-payload path. The individual links are unit-tested
/// elsewhere (env overlay in `config/schema/load_tests.rs`, payload
@@ -113,8 +87,8 @@ async fn load_and_get_security_policy_info_reflects_env_overlay() {
// read (or mutate) the developer's real `~/.openhuman/` config.
// A fresh workspace per iteration keeps the two cases independent.
let workspace = tempfile::tempdir().expect("tempdir for OPENHUMAN_WORKSPACE");
- let _workspace_guard = EnvGuard::set("OPENHUMAN_WORKSPACE", workspace.path());
- let _budget_guard = EnvGuard::set("OPENHUMAN_MAX_ACTIONS_PER_HOUR", budget.to_string());
+ let _workspace_guard = EnvVarGuard::set("OPENHUMAN_WORKSPACE", workspace.path());
+ let _budget_guard = EnvVarGuard::set("OPENHUMAN_MAX_ACTIONS_PER_HOUR", budget.to_string());
let outcome = load_and_get_security_policy_info()
.await
diff --git a/crates/openhuman-core/src/threads/ops_tests.rs b/crates/openhuman-core/src/threads/ops_tests.rs
index f51581acee..87d3ad880f 100644
--- a/crates/openhuman-core/src/threads/ops_tests.rs
+++ b/crates/openhuman-core/src/threads/ops_tests.rs
@@ -13,28 +13,7 @@ use std::ffi::OsString;
use std::path::Path;
use tinyagents_harness::title::{build_title_prompt, THREAD_TITLE_SYSTEM_PROMPT};
use tinyagents_session::turn_state::TurnState;
-
-struct EnvVarGuard {
- key: &'static str,
- old: Option<OsString>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, value: &Path) -> Self {
- let old = std::env::var_os(key);
- std::env::set_var(key, value.as_os_str());
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- match &self.old {
- Some(value) => std::env::set_var(self.key, value),
- None => std::env::remove_var(self.key),
- }
- }
-}
+use crate::config::test_env::EnvVarGuard;
// ── thread_to_summary / message_to_record / record_to_message ─
diff --git a/crates/openhuman-core/src/threads/schemas_tests.rs b/crates/openhuman-core/src/threads/schemas_tests.rs
index fa9871ecf1..e7813f4554 100644
--- a/crates/openhuman-core/src/threads/schemas_tests.rs
+++ b/crates/openhuman-core/src/threads/schemas_tests.rs
@@ -1,5 +1,6 @@
use super::*;
use serde_json::json;
+use crate::config::test_env::EnvVarGuard;
const ALL_FUNCTIONS: &[&str] = &[
"list",
@@ -236,30 +237,3 @@ fn parse_empty_request_rejects_any_field() {
let err = parse::<EmptyRequest>(obj(json!({"x": 1}))).unwrap_err();
assert!(err.starts_with("invalid params:"), "prefix: {err}");
}
-
-struct WorkspaceEnvGuard {
- previous: Option<std::ffi::OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- }
- Self { previous }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- match self.previous.take() {
- Some(value) => unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", value);
- },
- None => unsafe {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- },
- }
- }
-}
diff --git a/crates/openhuman-core/src/tools/impl/system/shell_tests.rs b/crates/openhuman-core/src/tools/impl/system/shell_tests.rs
index 1b8f0e80d5..b78b788f1e 100644
--- a/crates/openhuman-core/src/tools/impl/system/shell_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell_tests.rs
@@ -1,6 +1,7 @@
use super::*;
use crate::agent::host_runtime::{NativeRuntime, RuntimeAdapter};
use crate::security::{AutonomyLevel, CommandClass, SecurityPolicy};
+use crate::config::test_env::EnvVarGuard;
fn test_security(autonomy: AutonomyLevel) -> Arc<SecurityPolicy> {
Arc::new(SecurityPolicy {
@@ -59,30 +60,6 @@ fn test_security_with_env_cmd() -> Arc<SecurityPolicy> {
})
}
-/// RAII guard that restores an environment variable to its original state on drop,
-/// ensuring cleanup even if the test panics.
-struct EnvGuard {
- key: &'static str,
- original: Option<String>,
-}
-
-impl EnvGuard {
- fn set(key: &'static str, value: &str) -> Self {
- let original = std::env::var(key).ok();
- std::env::set_var(key, value);
- Self { key, original }
- }
-}
-
-impl Drop for EnvGuard {
- fn drop(&mut self) {
- match &self.original {
- Some(val) => std::env::set_var(self.key, val),
- None => std::env::remove_var(self.key),
- }
- }
-}
-
#[path = "shell_tests_runtime_and_sandbox_tests.rs"]
mod runtime_and_sandbox_tests;
#[path = "shell_tests_schema_and_env_tests.rs"]
diff --git a/crates/openhuman-core/src/tools/registry/ops_tests.rs b/crates/openhuman-core/src/tools/registry/ops_tests.rs
index a70ace3df5..0d0daf5051 100644
--- a/crates/openhuman-core/src/tools/registry/ops_tests.rs
+++ b/crates/openhuman-core/src/tools/registry/ops_tests.rs
@@ -1,6 +1,7 @@
use super::*;
use crate::config::schema::{CapabilityProviderConfig, CapabilityProviderTrustState, Config};
use crate::core::{FieldSchema, TypeSchema};
+use crate::config::test_env::EnvVarGuard;
#[test]
fn registry_entries_include_mcp_and_controller_tools() {
@@ -91,7 +92,7 @@ async fn diagnostics_loads_active_capability_provider_config() {
.lock()
.unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().expect("tempdir");
- let _env = EnvRestore::set_path("OPENHUMAN_WORKSPACE", tmp.path());
+ let _env = EnvVarGuard::set("OPENHUMAN_WORKSPACE", tmp.path());
std::fs::write(
tmp.path().join("config.toml"),
r#"
@@ -390,25 +391,3 @@ fn the_write_audit_probe_reads_the_store_the_writer_wrote_to() {
);
assert!(after.enabled, "the log is enabled when it is readable");
}
-
-struct EnvRestore {
- key: &'static str,
- previous: Option<std::ffi::OsString>,
-}
-
-impl EnvRestore {
- fn set_path(key: &'static str, value: &std::path::Path) -> Self {
- let previous = std::env::var_os(key);
- std::env::set_var(key, value);
- Self { key, previous }
- }
-}
-
-impl Drop for EnvRestore {
- fn drop(&mut self) {
- match &self.previous {
- Some(value) => std::env::set_var(self.key, value),
- None => std::env::remove_var(self.key),
- }
- }
-}
diff --git a/crates/openhuman-core/src/voice/ops_tests.rs b/crates/openhuman-core/src/voice/ops_tests.rs
index c252088ba0..8e267865d2 100644
--- a/crates/openhuman-core/src/voice/ops_tests.rs
+++ b/crates/openhuman-core/src/voice/ops_tests.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::config::test_env::EnvVarGuard;
#[test]
fn normalize_extension_defaults_to_webm() {
@@ -48,27 +49,6 @@ async fn voice_status_returns_without_error() {
assert!(!status.tts_voice_id.is_empty());
}
-/// RAII guard that restores an env var on drop, even on panic.
-struct EnvGuard {
- key: &'static str,
- prev: Option<std::ffi::OsString>,
-}
-impl EnvGuard {
- fn set(key: &'static str, value: &str) -> Self {
- let prev = std::env::var_os(key);
- std::env::set_var(key, value);
- 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),
- }
- }
-}
-
#[tokio::test]
async fn voice_status_detects_stub_binaries() {
let tmp = tempfile::tempdir().expect("tempdir");
@@ -82,7 +62,7 @@ async fn voice_status_detects_stub_binaries() {
.expect("chmod");
}
- let _guard = EnvGuard::set("PIPER_BIN", &piper_stub.display().to_string());
+ let _guard = EnvVarGuard::set("PIPER_BIN", &piper_stub.display().to_string());
let mut config = Config::default();
config.workspace_dir = tmp.path().join("workspace");
diff --git a/crates/openhuman-core/src/web3/wallet/test_support.rs b/crates/openhuman-core/src/web3/wallet/test_support.rs
index b71a628b67..b125bb813b 100644
--- a/crates/openhuman-core/src/web3/wallet/test_support.rs
+++ b/crates/openhuman-core/src/web3/wallet/test_support.rs
@@ -18,6 +18,7 @@ use tempfile::TempDir;
use super::ops::{setup, WalletAccount, WalletChain, WalletSetupParams, WalletSetupSource};
use crate::config::rpc as config_rpc;
use crate::config::TEST_ENV_LOCK;
+use crate::config::test_env::EnvVarGuard;
pub(crate) static TEST_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
@@ -56,38 +57,6 @@ pub(crate) fn sample_account(chain: WalletChain) -> WalletAccount {
}
}
-/// RAII guard returned to callers so `OPENHUMAN_WORKSPACE` is restored when
-/// the test scope ends — prevents one test's tempdir from leaking into the
-/// next test in the same process. Drop the guard explicitly or let it fall
-/// out of scope at the end of the test.
-pub(crate) struct WorkspaceEnvGuard {
- prev: Option<std::ffi::OsString>,
- _env_lock: std::sync::MutexGuard<'static, ()>,
-}
-
-impl WorkspaceEnvGuard {
- pub(crate) fn set(path: impl AsRef<Path>) -> Self {
- // OPENHUMAN_WORKSPACE is process-global, so hold the shared config env
- // lock for the full lifetime of the test workspace override.
- let env_lock = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let prev = std::env::var_os("OPENHUMAN_WORKSPACE");
- std::env::set_var("OPENHUMAN_WORKSPACE", path.as_ref());
- Self {
- prev,
- _env_lock: env_lock,
- }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- match self.prev.take() {
- Some(v) => std::env::set_var("OPENHUMAN_WORKSPACE", v),
- None => std::env::remove_var("OPENHUMAN_WORKSPACE"),
- }
- }
-}
-
/// Every environment variable that overrides a wallet endpoint.
const WALLET_RPC_ENV_VARS: [&str; 9] = [
"OPENHUMAN_WALLET_RPC_EVM",
@@ -145,11 +114,11 @@ impl Drop for UnreachableRpcGuard {
}
}
-pub(crate) fn set_workspace_env_for_test(temp: &TempDir) -> WorkspaceEnvGuard {
- WorkspaceEnvGuard::set(temp.path())
+pub(crate) fn set_workspace_env_for_test(temp: &TempDir) -> EnvVarGuard {
+ EnvVarGuard::workspace(temp.path())
}
-pub(crate) async fn setup_wallet_in(temp: &TempDir) -> Result<WorkspaceEnvGuard, String> {
+pub(crate) async fn setup_wallet_in(temp: &TempDir) -> Result<EnvVarGuard, String> {
// Wallet state lookups rely on OPENHUMAN_WORKSPACE for the duration of
// each test. Return a guard so the tempdir path does not leak into later
// parallel tests after this test's TempDir has been dropped.