Skip to content

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

chore(tests): add in-process e2e test files for core agent and memory features

Steven Enamakel3d3f860b40c6
diff --git a/tests/in_process/agent_approval_memory_coverage_e2e.rs b/tests/in_process/agent_approval_memory_coverage_e2e.rs
index 817c685fa7..b91215ad94 100644
--- a/tests/in_process/agent_approval_memory_coverage_e2e.rs
+++ b/tests/in_process/agent_approval_memory_coverage_e2e.rs
@@ -20,6 +20,9 @@
//! JSON-RPC router (`build_core_http_router`) and asserted on, so the number the
//! gate reports and the coverage that exists are the same thing.
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock;
+use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use std::path::Path;
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
@@ -29,61 +32,8 @@ use reqwest::StatusCode;
use serde_json::{json, Value};
use tempfile::{tempdir, TempDir};
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_rpc::server::build_core_http_router;
-const TEST_RPC_TOKEN: &str = "agent-approval-memory-coverage-e2e-token";
-
-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
-static AUTH_INIT: OnceLock<()> = OnceLock::new();
-
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- ENV_LOCK
- .get_or_init(|| Mutex::new(()))
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
-}
-
-/// Restores an environment variable to its prior value on drop so a harness
-/// cannot leak `HOME` into a sibling test in the same binary.
-struct EnvVarGuard {
- key: String,
- previous: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set(key: &str, value: &str) -> Self {
- let previous = std::env::var(key).ok();
- std::env::set_var(key, value);
- Self {
- key: key.to_string(),
- previous,
- }
- }
-
- fn set_to_path(key: &str, value: &Path) -> Self {
- Self::set(key, &value.to_string_lossy())
- }
-
- fn unset(key: &str) -> Self {
- let previous = std::env::var(key).ok();
- std::env::remove_var(key);
- Self {
- key: key.to_string(),
- 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),
- }
- }
-}
-
struct TestHarness {
_tmp: TempDir,
_guards: Vec<EnvVarGuard>,
@@ -91,14 +41,6 @@ struct TestHarness {
_rpc_join: tokio::task::JoinHandle<Result<(), std::io::Error>>,
}
-fn ensure_rpc_auth() {
- AUTH_INIT.get_or_init(|| {
- std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN);
- let token_dir = std::env::temp_dir().join("openhuman-agent-approval-memory-e2e-auth");
- init_rpc_token(&token_dir).expect("init rpc auth token");
- });
-}
-
async fn serve_rpc() -> (
std::net::SocketAddr,
tokio::task::JoinHandle<Result<(), std::io::Error>>,
@@ -185,7 +127,7 @@ async fn rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {
let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));
let response = client
.post(&url)
- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .header(AUTHORIZATION, format!("Bearer {rpc_token()}"))
.json(&json!({
"jsonrpc": "2.0",
"id": id,
diff --git a/tests/in_process/agent_prompt_comprehension_e2e.rs b/tests/in_process/agent_prompt_comprehension_e2e.rs
index 6b8543d7ec..9dc39d6dd6 100644
--- a/tests/in_process/agent_prompt_comprehension_e2e.rs
+++ b/tests/in_process/agent_prompt_comprehension_e2e.rs
@@ -16,6 +16,8 @@
//! `env_lock()` across `.await` on purpose, as there.
#![allow(clippy::await_holding_lock)]
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock_with_file_keyring as env_lock;
use std::net::SocketAddr;
use std::path::Path;
use std::sync::{Mutex, OnceLock};
@@ -29,59 +31,14 @@ use serde_json::{json, Value};
use tempfile::tempdir;
use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_rpc::server::build_core_http_router;
const TEST_RPC_TOKEN: &str = "json-rpc-e2e-local-token";
// ─── Env serialization ──────────────────────────────────────────────────────
-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
-static KEYRING_INIT: OnceLock<()> = OnceLock::new();
static AGENT_DEF_REGISTRY_INIT: OnceLock<()> = OnceLock::new();
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- KEYRING_INIT.get_or_init(|| unsafe {
- std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");
- });
- match ENV_LOCK.get_or_init(|| Mutex::new(())).lock() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
- }
-}
-
-struct EnvVarGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, path: &Path) -> Self {
- let old = std::env::var(key).ok();
- unsafe {
- std::env::set_var(key, path.as_os_str());
- }
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var(key).ok();
- unsafe {
- std::env::remove_var(key);
- }
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- match &self.old {
- Some(v) => unsafe { std::env::set_var(self.key, v) },
- None => unsafe { std::env::remove_var(self.key) },
- }
- }
-}
-
// ─── Scripted upstream ──────────────────────────────────────────────────────
static SCRIPTED: OnceLock<Mutex<std::collections::VecDeque<Value>>> = OnceLock::new();
diff --git a/tests/in_process/agent_turn_overrides_e2e.rs b/tests/in_process/agent_turn_overrides_e2e.rs
index 2c6991f4c4..09008fbda0 100644
--- a/tests/in_process/agent_turn_overrides_e2e.rs
+++ b/tests/in_process/agent_turn_overrides_e2e.rs
@@ -25,9 +25,9 @@
//! positive here.
#![allow(clippy::await_holding_lock)]
-#[path = "support/noop_memory.rs"]
-mod noop_memory;
-
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock;
+use crate::noop_memory;
use async_trait::async_trait;
use std::collections::VecDeque;
use std::path::PathBuf;
@@ -50,37 +50,6 @@ use tinytools_agent::dialect::{NativeDialect, XmlDialect};
// ─── Harness ────────────────────────────────────────────────────────────────
-struct EnvGuard {
- key: &'static str,
- previous: Option<std::ffi::OsString>,
-}
-
-impl EnvGuard {
- fn set_path(key: &'static str, value: &std::path::Path) -> Self {
- let previous = std::env::var_os(key);
- unsafe { std::env::set_var(key, value) };
- Self { key, previous }
- }
-}
-
-impl Drop for EnvGuard {
- fn drop(&mut self) {
- match self.previous.take() {
- Some(value) => unsafe { std::env::set_var(self.key, value) },
- None => unsafe { std::env::remove_var(self.key) },
- }
- }
-}
-
-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
-
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- ENV_LOCK
- .get_or_init(|| Mutex::new(()))
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
-}
-
/// The agent turn loop needs the wide worker stack the product gives it.
fn run_on_agent_stack<F, Fut>(name: &str, future_factory: F)
where
@@ -336,7 +305,7 @@ async fn suppress_active_goal_keeps_the_thread_goal_out_of_the_prompt_inner() {
{
// CONTROL — without the override the goal reaches the prompt.
- let control_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &control_workspace);
+ let control_guard = EnvVarGuard::set_path("OPENHUMAN_WORKSPACE", &control_workspace);
goal_store::set(&control_workspace, THREAD, OBJECTIVE, None)
.await
.expect("seed an active thread goal for the control");
@@ -361,7 +330,7 @@ async fn suppress_active_goal_keeps_the_thread_goal_out_of_the_prompt_inner() {
// SUPPRESSED — a goal seeded identically, in a workspace no other agent
// has ever written a transcript into, must not appear.
- let _workspace_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
+ let _workspace_guard = EnvVarGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
goal_store::set(&workspace_path, THREAD, OBJECTIVE, None)
.await
.expect("seed an active thread goal for the measured agent");
@@ -422,7 +391,7 @@ fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcript() {
async fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcript_inner() {
let _env = env_lock();
let (_temp, workspace_path) = workspace("suppress-transcript-autoload");
- let _workspace_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
+ let _workspace_guard = EnvVarGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
const PRIOR_MARKER: &str = "turn-overrides-prior-thread-secret-topic";
// Two ids, so the run enacts #1725's actual shape: a host that has re-bound
@@ -536,7 +505,7 @@ fn turn_overrides_apply_to_exactly_one_turn_and_then_reset() {
async fn turn_overrides_apply_to_exactly_one_turn_and_then_reset_inner() {
let _env = env_lock();
let (_temp, workspace_path) = workspace("overrides-reset");
- let _workspace_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
+ let _workspace_guard = EnvVarGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
let model = ScriptedModel::new(vec![text("suppressed reply"), text("restored reply")]);
let mut agent = agent_with(
@@ -607,7 +576,7 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_inner
{
// CONTROL — an Active goal reaches a turn.
- let control_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &control_workspace);
+ let control_guard = EnvVarGuard::set_path("OPENHUMAN_WORKSPACE", &control_workspace);
goal_store::set(&control_workspace, THREAD, OBJECTIVE, None)
.await
.expect("seed an active thread goal for the control");
@@ -629,7 +598,7 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_inner
// MEASURED — seed the same goal in a pristine workspace, settle it via
// the API under test, then run the only turn that workspace ever sees.
- let _workspace_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
+ let _workspace_guard = EnvVarGuard::set_path("OPENHUMAN_WORKSPACE", &workspace_path);
goal_store::set(&workspace_path, THREAD, OBJECTIVE, None)
.await
.expect("seed an active thread goal for the measured agent");
diff --git a/tests/in_process/channels_default_channel_e2e.rs b/tests/in_process/channels_default_channel_e2e.rs
index 82607c8f1b..7721609fa7 100644
--- a/tests/in_process/channels_default_channel_e2e.rs
+++ b/tests/in_process/channels_default_channel_e2e.rs
@@ -49,6 +49,9 @@
//!
//! Run with: `cargo test -p openhuman-cli --test channels_default_channel_e2e`
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock;
+use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock, RwLock};
use std::time::Duration;
@@ -58,73 +61,10 @@ use reqwest::StatusCode;
use serde_json::{json, Value};
use tempfile::{tempdir, TempDir};
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_rpc::server::build_core_http_router;
-const TEST_RPC_TOKEN: &str = "channels-default-channel-e2e-token";
-
-static AUTH_INIT: OnceLock<()> = OnceLock::new();
-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
-
// ── Env isolation ────────────────────────────────────────────────────
-struct EnvVarGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, path: &Path) -> Self {
- let old = std::env::var(key).ok();
- // SAFETY: every caller holds `env_lock()`, which serialises the
- // process-global env mutations this type performs.
- unsafe { std::env::set_var(key, path.as_os_str()) };
- Self { key, old }
- }
-
- fn set(key: &'static str, value: &str) -> Self {
- let old = std::env::var(key).ok();
- // SAFETY: see `set_to_path`.
- unsafe { std::env::set_var(key, value) };
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var(key).ok();
- // SAFETY: see `set_to_path`.
- unsafe { std::env::remove_var(key) };
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- match &self.old {
- // SAFETY: teardown runs inside the same `env_lock()` critical
- // section as setup.
- Some(value) => unsafe { std::env::set_var(self.key, value) },
- // SAFETY: see above.
- None => unsafe { std::env::remove_var(self.key) },
- }
- }
-}
-
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- match ENV_LOCK.get_or_init(|| Mutex::new(())).lock() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
- }
-}
-
-fn ensure_rpc_auth() {
- AUTH_INIT.get_or_init(|| {
- // SAFETY: runs once, behind a `OnceLock`, before any server starts.
- unsafe { std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN) };
- let token_dir = std::env::temp_dir().join("openhuman-channels-default-e2e-auth");
- init_rpc_token(&token_dir).expect("init rpc auth token");
- });
-}
-
fn write_config(openhuman_dir: &Path) {
std::fs::create_dir_all(openhuman_dir).expect("create .openhuman");
let cfg = r#"api_url = "http://127.0.0.1:9"
@@ -234,7 +174,7 @@ async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
let url = format!("{}/rpc", base.trim_end_matches('/'));
let response = client
.post(&url)
- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .header(AUTHORIZATION, format!("Bearer {rpc_token()}"))
.json(&json!({
"jsonrpc": "2.0",
"id": id,
diff --git a/tests/in_process/config_auth_app_state_connectivity_e2e.rs b/tests/in_process/config_auth_app_state_connectivity_e2e.rs
index 21314d0676..da19724624 100644
--- a/tests/in_process/config_auth_app_state_connectivity_e2e.rs
+++ b/tests/in_process/config_auth_app_state_connectivity_e2e.rs
@@ -1,6 +1,9 @@
//! Focused JSON-RPC E2E coverage for config, auth/credentials, app_state,
//! and connectivity controller surfaces.
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock;
+use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::{
@@ -28,7 +31,6 @@ use openhuman_core::config::{
user_openhuman_dir, write_active_user_id, Config, DaemonConfig, DictationActivationMode,
LlmBackend, ReflectionSource, UpdateRestartStrategy,
};
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_core::core::events::DomainEvent;
use openhuman_core::desktop::app_state::app_state_schemas;
use openhuman_core::security::credentials::bus::SessionExpiredSubscriber;
@@ -47,78 +49,6 @@ use openhuman_tinyhumans::backend::url::{
};
use tinybus::EventHandler;
-const TEST_RPC_TOKEN: &str = "worker-a-domain-e2e-token";
-
-static AUTH_INIT: OnceLock<()> = OnceLock::new();
-// This file is its own integration target, and other binaries may `#[path]`-include it.
-// `ENV_LOCK` aliases `crate::SHARED_ENV_LOCK`, which resolves to this file's
-// own static when built standalone (separate process, isolated env) and to the
-// aggregate's shared static when nested into `raw_coverage_all` (so its env
-// mutations serialize against every other aggregated suite). The nested copy of
-// this static is simply unused.
-#[allow(dead_code)]
-pub static SHARED_ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
-static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;
-
-struct EnvVarGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set(key: &'static str, value: &str) -> Self {
- let old = std::env::var(key).ok();
- std::env::set_var(key, value);
- Self { key, old }
- }
-
- fn set_to_path(key: &'static str, path: &Path) -> Self {
- let old = std::env::var(key).ok();
- std::env::set_var(key, path.as_os_str());
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var(key).ok();
- std::env::remove_var(key);
- 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),
- }
- }
-}
-
-// `pub` so binaries that `#[path]`-include this file as a module can route their
-// own env-mutating tests through the SAME lock, serializing all
-// OPENHUMAN_WORKSPACE/BACKEND_URL mutations in the combined binary.
-pub fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- let mutex = ENV_LOCK.get_or_init(|| Mutex::new(()));
- match mutex.lock() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
- }
-}
-
-fn ensure_rpc_auth() {
- AUTH_INIT.get_or_init(|| {
- // The core carries no backend client; the `auth_*` remote paths below
- // reach the mock backend through the `openhuman-tinyhumans` transport.
- // Inline (not via `tests/support/`) because this file is also
- // `#[path]`-included into `raw_coverage_all`.
- openhuman_tinyhumans::install(openhuman_tinyhumans::InstallOptions::default())
- .expect("install the TinyHumans backend transport");
- std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN);
- let token_dir = std::env::temp_dir().join("openhuman-worker-a-e2e-auth");
- init_rpc_token(&token_dir).expect("init rpc auth token");
- });
-}
-
async fn serve_rpc() -> (
SocketAddr,
tokio::task::JoinHandle<Result<(), std::io::Error>>,
@@ -386,7 +316,7 @@ async fn rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {
let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));
let response = client
.post(&url)
- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .header(AUTHORIZATION, format!("Bearer {rpc_token()}"))
.json(&json!({
"jsonrpc": "2.0",
"id": id,
diff --git a/tests/in_process/domain_modules_e2e.rs b/tests/in_process/domain_modules_e2e.rs
index 1210783b8f..1883dacb3a 100644
--- a/tests/in_process/domain_modules_e2e.rs
+++ b/tests/in_process/domain_modules_e2e.rs
@@ -5,9 +5,10 @@
//! exercises cheap read/status handlers through HTTP. Mutating or networked
//! domain behavior remains covered by the focused `*_e2e.rs` suites.
-#[path = "support/memory_module.rs"]
-mod memory_module;
-
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock;
+use crate::memory_module;
+use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use std::net::SocketAddr;
use std::path::Path;
use std::sync::{Mutex, OnceLock};
@@ -18,66 +19,8 @@ use reqwest::StatusCode;
use serde_json::{json, Value};
use tempfile::{tempdir, TempDir};
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_rpc::server::build_core_http_router;
-const TEST_RPC_TOKEN: &str = "domain-modules-e2e-token";
-
-static AUTH_INIT: OnceLock<()> = OnceLock::new();
-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
-
-struct EnvVarGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, path: &Path) -> Self {
- let old = std::env::var(key).ok();
- std::env::set_var(key, path.as_os_str());
- Self { key, old }
- }
-
- fn set(key: &'static str, value: &str) -> Self {
- let old = std::env::var(key).ok();
- std::env::set_var(key, value);
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var(key).ok();
- std::env::remove_var(key);
- 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),
- }
- }
-}
-
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- let mutex = ENV_LOCK.get_or_init(|| Mutex::new(()));
- match mutex.lock() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
- }
-}
-
-fn ensure_rpc_auth() {
- AUTH_INIT.get_or_init(|| {
- // SAFETY: guarded by OnceLock and set once before the router for this
- // test binary is used concurrently.
- unsafe { std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN) };
- let token_dir = std::env::temp_dir().join("openhuman-domain-modules-e2e-auth");
- init_rpc_token(&token_dir).expect("init rpc auth token");
- });
-}
-
async fn serve_rpc() -> (
SocketAddr,
tokio::task::JoinHandle<Result<(), std::io::Error>>,
@@ -186,7 +129,7 @@ async fn rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {
let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));
let response = client
.post(&url)
- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .header(AUTHORIZATION, format!("Bearer {rpc_token()}"))
.json(&json!({
"jsonrpc": "2.0",
"id": id,
diff --git a/tests/in_process/embeddings_rpc_e2e.rs b/tests/in_process/embeddings_rpc_e2e.rs
index 313eec1895..250c20b078 100644
--- a/tests/in_process/embeddings_rpc_e2e.rs
+++ b/tests/in_process/embeddings_rpc_e2e.rs
@@ -7,6 +7,9 @@
//!
//! Run with: `cargo test --test embeddings_rpc_e2e`
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock;
+use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use std::net::SocketAddr;
use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock};
@@ -19,75 +22,12 @@ use axum::{Json, Router};
use serde_json::{json, Value};
use tempfile::tempdir;
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_rpc::server::build_core_http_router;
// ── Auth / token setup ────────────────────────────────────────────────────────
-const TEST_RPC_TOKEN: &str = "embeddings-e2e-test-token";
-static E2E_AUTH_INIT: OnceLock<()> = OnceLock::new();
-
-/// Serialises tests: env-var mutations (`HOME`, `OPENHUMAN_WORKSPACE`,
-/// `OPENHUMAN_APP_ENV`) are process-global. The OnceLock+Mutex pattern mirrors
-/// `json_rpc_e2e.rs` so tests don't race each other.
-static EMBEDDINGS_E2E_ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
-
-fn embeddings_e2e_env_lock() -> std::sync::MutexGuard<'static, ()> {
- let mutex = EMBEDDINGS_E2E_ENV_LOCK.get_or_init(|| Mutex::new(()));
- match mutex.lock() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
- }
-}
-
-fn ensure_test_rpc_auth() {
- E2E_AUTH_INIT.get_or_init(|| {
- // SAFETY: runs exactly once inside OnceLock before any concurrent env
- // reads occur. Rust 1.81+ requires unsafe for set_var in multi-threaded
- // contexts; the OnceLock guard limits the mutation to a single call.
- unsafe { std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN) };
- let token_dir = std::env::temp_dir().join("openhuman-embeddings-e2e-auth");
- init_rpc_token(&token_dir).expect("init rpc auth token for embeddings_rpc_e2e");
- });
-}
-
// ── Env-var guard (RAII restore) ──────────────────────────────────────────────
-struct EnvVarGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, path: &Path) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::set_var(key, path.as_os_str()) };
- Self { key, old }
- }
-
- #[allow(dead_code)]
- fn set(key: &'static str, value: &str) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::set_var(key, value) };
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::remove_var(key) };
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- match &self.old {
- Some(v) => unsafe { std::env::set_var(self.key, v) },
- None => unsafe { std::env::remove_var(self.key) },
- }
- }
-}
-
// ── Minimal config writer ─────────────────────────────────────────────────────
fn write_min_config(config_dir: &Path) {
@@ -109,7 +49,7 @@ async fn serve_on_ephemeral() -> (
SocketAddr,
tokio::task::JoinHandle<Result<(), std::io::Error>>,
) {
- ensure_test_rpc_auth();
+ ensure_rpc_auth();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind ephemeral port");
@@ -207,7 +147,7 @@ async fn post_json_rpc(rpc_base: &str, id: i64, method: &str, params: Value) ->
let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));
let resp = client
.post(&url)
- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .header(AUTHORIZATION, format!("Bearer {rpc_token()}"))
.json(&body)
.send()
.await
@@ -311,7 +251,7 @@ async fn setup_embeddings_test() -> (
#[tokio::test(flavor = "multi_thread")]
async fn embeddings_get_settings_returns_catalog() {
- let _lock = embeddings_e2e_env_lock();
+ let _lock = env_lock();
let (rpc_base, _tmp, _guards, _join) = setup_embeddings_test().await;
let resp = post_json_rpc(&rpc_base, 1, "openhuman.embeddings_get_settings", json!({})).await;
@@ -402,7 +342,7 @@ async fn embeddings_get_settings_returns_catalog() {
#[tokio::test(flavor = "multi_thread")]
async fn embeddings_update_settings_switches_provider() {
- let _lock = embeddings_e2e_env_lock();
+ let _lock = env_lock();
let (rpc_base, _tmp, _guards, _join) = setup_embeddings_test().await;
// Switch to "none" (noop) which has 0 dimensions — dimension change from
@@ -437,7 +377,7 @@ async fn embeddings_update_settings_switches_provider() {
#[tokio::test(flavor = "multi_thread")]
async fn embeddings_update_settings_dimension_change_requires_wipe() {
- let _lock = embeddings_e2e_env_lock();
+ let _lock = env_lock();
let (rpc_base, _tmp, _guards, _join) = setup_embeddings_test().await;
// First set provider to voyage (a provider that supports multiple dims)
@@ -495,7 +435,7 @@ async fn embeddings_update_settings_dimension_change_requires_wipe() {
#[tokio::test(flavor = "multi_thread")]
async fn embeddings_set_and_clear_api_key() {
- let _lock = embeddings_e2e_env_lock();
+ let _lock = env_lock();
let (rpc_base, _tmp, _guards, _join) = setup_embeddings_test().await;
// Store a key for voyage
@@ -581,7 +521,7 @@ async fn embeddings_set_and_clear_api_key() {
#[tokio::test(flavor = "multi_thread")]
async fn embeddings_test_connection_with_none_provider() {
- let _lock = embeddings_e2e_env_lock();
+ let _lock = env_lock();
let (rpc_base, _tmp, _guards, _join) = setup_embeddings_test().await;
// Switch to "none" so test_connection uses the noop provider (no network).
@@ -619,7 +559,7 @@ async fn embeddings_test_connection_with_none_provider() {
#[tokio::test(flavor = "multi_thread")]
async fn embeddings_embed_with_none_returns_empty_vectors() {
- let _lock = embeddings_e2e_env_lock();
+ let _lock = env_lock();
let (rpc_base, _tmp, _guards, _join) = setup_embeddings_test().await;
// Switch to noop so embed() doesn't require network.
@@ -661,7 +601,7 @@ async fn embeddings_embed_with_none_returns_empty_vectors() {
#[tokio::test(flavor = "multi_thread")]
async fn embeddings_embed_with_custom_openai_endpoint_round_trips_vectors_and_api_key() {
- let _lock = embeddings_e2e_env_lock();
+ let _lock = env_lock();
let (rpc_base, _tmp, _guards, _join) = setup_embeddings_test().await;
let (mock_base, mock_state, mock_join) = serve_mock_embeddings().await;
@@ -781,7 +721,7 @@ async fn serve_mock_embeddings_no_api(
/// the 404-on-every-re-embed Sentry flood can never be configured.
#[tokio::test(flavor = "multi_thread")]
async fn embeddings_update_settings_rejects_endpoint_with_no_embeddings_api() {
- let _lock = embeddings_e2e_env_lock();
+ let _lock = env_lock();
let (rpc_base, _tmp, _guards, _join) = setup_embeddings_test().await;
let (mock_base, mock_join) = serve_mock_embeddings_no_api().await;
@@ -843,7 +783,7 @@ async fn embeddings_update_settings_rejects_endpoint_with_no_embeddings_api() {
#[tokio::test(flavor = "multi_thread")]
async fn legacy_alias_inference_embed_resolves() {
- let _lock = embeddings_e2e_env_lock();
+ let _lock = env_lock();
let (rpc_base, _tmp, _guards, _join) = setup_embeddings_test().await;
// Set provider to none so the embed call itself doesn't fail on missing keys.
@@ -903,7 +843,7 @@ async fn legacy_alias_inference_embed_resolves() {
/// what keeps the live embed path's length guard from rejecting later embeds.
#[tokio::test(flavor = "multi_thread")]
async fn embeddings_update_settings_adopts_custom_endpoint_native_dimension() {
- let _lock = embeddings_e2e_env_lock();
+ let _lock = env_lock();
let (rpc_base, _tmp, _guards, _join) = setup_embeddings_test().await;
let (mock_base, _mock_state, mock_join) = serve_mock_embeddings().await;
@@ -964,7 +904,7 @@ async fn embeddings_update_settings_adopts_custom_endpoint_native_dimension() {
/// field to reopen the populated form after a reload in Disabled mode.
#[tokio::test(flavor = "multi_thread")]
async fn embeddings_get_settings_returns_retained_custom_profile_while_disabled() {
- let _lock = embeddings_e2e_env_lock();
+ let _lock = env_lock();
let (rpc_base, tmp, _guards, _join) = setup_embeddings_test().await;
for config_path in [
tmp.path().join(".openhuman").join("config.toml"),
@@ -1028,7 +968,7 @@ embedding_dimensions = 2048
#[tokio::test(flavor = "multi_thread")]
async fn embeddings_controllers_reject_missing_required_params() {
- let _lock = embeddings_e2e_env_lock();
+ let _lock = env_lock();
let (rpc_base, _tmp, _guards, _join) = setup_embeddings_test().await;
for (id, method) in [
diff --git a/tests/in_process/memory_graph_roundtrip_e2e.rs b/tests/in_process/memory_graph_roundtrip_e2e.rs
index 16da684ec5..c0ce1fd8bd 100644
--- a/tests/in_process/memory_graph_roundtrip_e2e.rs
+++ b/tests/in_process/memory_graph_roundtrip_e2e.rs
@@ -73,6 +73,9 @@
//! A large stack is also needed — `RUST_MIN_STACK=67108864` — because
//! publishing the policy touches deeply nested config types.
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock;
+use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
@@ -82,13 +85,8 @@ use reqwest::StatusCode;
use serde_json::{json, Value};
use tempfile::{tempdir, TempDir};
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_rpc::server::build_core_http_router;
-const TEST_RPC_TOKEN: &str = "memory-graph-roundtrip-e2e-token";
-
-static AUTH_INIT: OnceLock<()> = OnceLock::new();
-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();
/// One tempdir shared by every test in this target.
///
@@ -101,54 +99,6 @@ static TEST_ROOT: OnceLock<TempDir> = OnceLock::new();
// ── Env isolation ────────────────────────────────────────────────────
-struct EnvVarGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, path: &Path) -> Self {
- let old = std::env::var(key).ok();
- // SAFETY: every caller holds `env_lock()`, which serialises the
- // process-global env mutations this type performs.
- unsafe { std::env::set_var(key, path.as_os_str()) };
- Self { key, old }
- }
-
- fn set(key: &'static str, value: &str) -> Self {
- let old = std::env::var(key).ok();
- // SAFETY: see `set_to_path`.
- unsafe { std::env::set_var(key, value) };
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var(key).ok();
- // SAFETY: see `set_to_path`.
- unsafe { std::env::remove_var(key) };
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- match &self.old {
- // SAFETY: teardown runs inside the same `env_lock()` critical
- // section as setup.
- Some(value) => unsafe { std::env::set_var(self.key, value) },
- // SAFETY: see above.
- None => unsafe { std::env::remove_var(self.key) },
- }
- }
-}
-
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- match ENV_LOCK.get_or_init(|| Mutex::new(())).lock() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
- }
-}
-
fn test_root() -> &'static TempDir {
TEST_ROOT.get_or_init(|| tempdir().expect("memory graph roundtrip tempdir"))
}
@@ -183,15 +133,6 @@ fn ensure_memory_seams(workspace: &Path) {
});
}
-fn ensure_rpc_auth() {
- AUTH_INIT.get_or_init(|| {
- // SAFETY: runs once, behind a `OnceLock`, before any server starts.
- unsafe { std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN) };
- let token_dir = std::env::temp_dir().join("openhuman-memory-graph-roundtrip-e2e-auth");
- init_rpc_token(&token_dir).expect("init rpc auth token");
- });
-}
-
/// Config for a memory-backed core with no network reachability.
///
/// Note what is deliberately ABSENT: `[memory] provider = "none"`. Several
@@ -276,7 +217,7 @@ async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
let url = format!("{}/rpc", base.trim_end_matches('/'));
let response = client
.post(&url)
- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .header(AUTHORIZATION, format!("Bearer {rpc_token()}"))
.json(&json!({
"jsonrpc": "2.0",
"id": id,
diff --git a/tests/in_process/memory_sources_e2e.rs b/tests/in_process/memory_sources_e2e.rs
index 068b316613..3725c30ec1 100644
--- a/tests/in_process/memory_sources_e2e.rs
+++ b/tests/in_process/memory_sources_e2e.rs
@@ -6,9 +6,10 @@
//!
//! Run with: `cargo test --test memory_sources_e2e`
-#[path = "support/memory_module.rs"]
-mod memory_module;
-
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock;
+use crate::memory_module;
+use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
@@ -17,31 +18,11 @@ use axum::http::header::AUTHORIZATION;
use serde_json::{json, Value};
use tempfile::tempdir;
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_rpc::server::build_core_http_router;
-const TEST_RPC_TOKEN: &str = "memory-sources-e2e-token";
-static AUTH_INIT: OnceLock<()> = OnceLock::new();
-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();
static TEST_HOME: OnceLock<tempfile::TempDir> = OnceLock::new();
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- let mutex = ENV_LOCK.get_or_init(|| Mutex::new(()));
- match mutex.lock() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
- }
-}
-
-fn ensure_rpc_auth() {
- AUTH_INIT.get_or_init(|| {
- unsafe { std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN) };
- let token_dir = std::env::temp_dir().join("openhuman-memory-sources-e2e-auth");
- init_rpc_token(&token_dir).expect("init rpc auth");
- });
-}
-
/// The transport-only JSON-RPC router does not create a core runtime context,
/// so memory-backed routes need their host seams installed explicitly.
fn ensure_memory_seams() {
@@ -66,34 +47,6 @@ fn test_home() -> &'static Path {
.path()
}
-struct EnvVarGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, path: &Path) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::set_var(key, path.as_os_str()) };
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::remove_var(key) };
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- match &self.old {
- Some(v) => unsafe { std::env::set_var(self.key, v) },
- None => unsafe { std::env::remove_var(self.key) },
- }
- }
-}
-
fn write_config(dir: &Path) {
std::fs::create_dir_all(dir).expect("mkdir");
let cfg = r#"
@@ -142,7 +95,7 @@ async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
let url = format!("{}/rpc", base.trim_end_matches('/'));
let resp = client
.post(&url)
- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .header(AUTHORIZATION, format!("Bearer {rpc_token()}"))
.json(&body)
.send()
.await
diff --git a/tests/in_process/memory_tree_health_e2e.rs b/tests/in_process/memory_tree_health_e2e.rs
index 93b53095b3..3705ec6aab 100644
--- a/tests/in_process/memory_tree_health_e2e.rs
+++ b/tests/in_process/memory_tree_health_e2e.rs
@@ -24,9 +24,10 @@
//! cross-method invariant that IS reachable and says so in a comment, rather
//! than asserting `0 == 0` and calling it coverage.
-#[path = "support/memory_module.rs"]
-mod memory_module;
-
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock;
+use crate::memory_module;
+use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
@@ -35,31 +36,11 @@ use axum::http::header::AUTHORIZATION;
use serde_json::{json, Value};
use tempfile::tempdir;
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_rpc::server::build_core_http_router;
-const TEST_RPC_TOKEN: &str = "memory-tree-health-e2e-token";
-static AUTH_INIT: OnceLock<()> = OnceLock::new();
-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();
static TEST_HOME: OnceLock<tempfile::TempDir> = OnceLock::new();
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- let mutex = ENV_LOCK.get_or_init(|| Mutex::new(()));
- match mutex.lock() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
- }
-}
-
-fn ensure_rpc_auth() {
- AUTH_INIT.get_or_init(|| {
- unsafe { std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN) };
- let token_dir = std::env::temp_dir().join("openhuman-memory-sources-e2e-auth");
- init_rpc_token(&token_dir).expect("init rpc auth");
- });
-}
-
/// The transport-only JSON-RPC router does not create a core runtime context,
/// so memory-backed routes need their host seams installed explicitly.
fn ensure_memory_seams() {
@@ -85,34 +66,6 @@ fn test_home() -> &'static Path {
.path()
}
-struct EnvVarGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, path: &Path) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::set_var(key, path.as_os_str()) };
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::remove_var(key) };
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- match &self.old {
- Some(v) => unsafe { std::env::set_var(self.key, v) },
- None => unsafe { std::env::remove_var(self.key) },
- }
- }
-}
-
fn write_config(dir: &Path) {
std::fs::create_dir_all(dir).expect("mkdir");
let cfg = r#"
@@ -161,7 +114,7 @@ async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
let url = format!("{}/rpc", base.trim_end_matches('/'));
let resp = client
.post(&url)
- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .header(AUTHORIZATION, format!("Bearer {rpc_token()}"))
.json(&body)
.send()
.await
diff --git a/tests/in_process/skill_registry_e2e.rs b/tests/in_process/skill_registry_e2e.rs
index 562fdaf63e..492bdf45f7 100644
--- a/tests/in_process/skill_registry_e2e.rs
+++ b/tests/in_process/skill_registry_e2e.rs
@@ -6,6 +6,9 @@
//! The test uses a local fixture catalog and local SKILL.md download URL so CI
//! does not depend on the live Hermes API.
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock_with_file_keyring as env_lock;
+use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use std::net::SocketAddr;
use std::path::Path;
use std::sync::{Mutex, OnceLock};
@@ -17,77 +20,17 @@ use axum::Router;
use serde_json::{json, Value};
use tempfile::tempdir;
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_rpc::server::build_core_http_router;
// ── Constants ──────────────────────────────────────────────────────────────
-const TEST_RPC_TOKEN: &str = "skill-registry-e2e-token";
-
// ── One-time auth init ─────────────────────────────────────────────────────
-static SKILL_REGISTRY_AUTH_INIT: OnceLock<()> = OnceLock::new();
-
-fn ensure_test_rpc_auth() {
- SKILL_REGISTRY_AUTH_INIT.get_or_init(|| {
- unsafe { std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN) };
- let token_dir = std::env::temp_dir().join("openhuman-skill-registry-e2e-auth");
- init_rpc_token(&token_dir).expect("init rpc auth token for skill_registry_e2e");
- });
-}
-
// ── Env lock (process-global env vars must not race) ──────────────────────
-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
-static KEYRING_INIT: OnceLock<()> = OnceLock::new();
-
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- KEYRING_INIT.get_or_init(|| unsafe {
- std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");
- });
- let mutex = ENV_LOCK.get_or_init(|| Mutex::new(()));
- match mutex.lock() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
- }
-}
// ── EnvVarGuard ───────────────────────────────────────────────────────────
-struct EnvVarGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, path: &Path) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::set_var(key, path.as_os_str()) };
- Self { key, old }
- }
-
- fn set(key: &'static str, value: &str) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::set_var(key, value) };
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::remove_var(key) };
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- match &self.old {
- Some(v) => unsafe { std::env::set_var(self.key, v) },
- None => unsafe { std::env::remove_var(self.key) },
- }
- }
-}
-
// ── Server helpers ─────────────────────────────────────────────────────────
async fn serve_on_ephemeral(
@@ -96,7 +39,7 @@ async fn serve_on_ephemeral(
SocketAddr,
tokio::task::JoinHandle<Result<(), std::io::Error>>,
) {
- ensure_test_rpc_auth();
+ ensure_rpc_auth();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind ephemeral port");
@@ -185,7 +128,7 @@ async fn post_json_rpc(rpc_base: &str, id: i64, method: &str, params: Value) ->
let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));
let resp = client
.post(&url)
- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .header(AUTHORIZATION, format!("Bearer {rpc_token()}"))
.json(&body)
.send()
.await
@@ -230,7 +173,7 @@ async fn skill_registry_e2e_sources_browse_search_install() {
let _home_guard = EnvVarGuard::set_to_path("HOME", home);
let _workspace_guard = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _token_guard = EnvVarGuard::set(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN);
+ let _token_guard = EnvVarGuard::set(CORE_TOKEN_ENV_VAR, rpc_token());
let _keyring_guard = EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file");
let cfg_dir = openhuman_home.clone();
diff --git a/tests/in_process/tree_summarizer_e2e.rs b/tests/in_process/tree_summarizer_e2e.rs
index 2af0585f64..17e9d76032 100644
--- a/tests/in_process/tree_summarizer_e2e.rs
+++ b/tests/in_process/tree_summarizer_e2e.rs
@@ -20,9 +20,10 @@
//!
//! Run with: `cargo test -p openhuman-cli --test tree_summarizer_e2e`
-#[path = "support/memory_module.rs"]
-mod memory_module;
-
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock;
+use crate::memory_module;
+use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
@@ -32,63 +33,19 @@ use chrono::{DateTime, SecondsFormat, TimeZone, Utc};
use serde_json::{json, Value};
use tempfile::TempDir;
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_rpc::server::build_core_http_router;
-const TEST_RPC_TOKEN: &str = "tree-summarizer-e2e-token";
const NAMESPACE: &str = "tree-summarizer-e2e";
-static AUTH_INIT: OnceLock<()> = OnceLock::new();
static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();
-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
static TEST_HOME: OnceLock<TempDir> = OnceLock::new();
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- match ENV_LOCK.get_or_init(|| Mutex::new(())).lock() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
- }
-}
-
fn test_home() -> &'static Path {
TEST_HOME
.get_or_init(|| tempfile::tempdir().expect("tree summarizer tempdir"))
.path()
}
-struct EnvVarGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, path: &Path) -> Self {
- let old = std::env::var(key).ok();
- // SAFETY: every caller holds env_lock() for the whole of setup and
- // teardown, so these process-global mutations are serialised.
- unsafe { std::env::set_var(key, path.as_os_str()) };
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var(key).ok();
- // SAFETY: see set_to_path.
- unsafe { std::env::remove_var(key) };
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- match &self.old {
- // SAFETY: see EnvVarGuard::set_to_path.
- Some(value) => unsafe { std::env::set_var(self.key, value) },
- // SAFETY: see EnvVarGuard::set_to_path.
- None => unsafe { std::env::remove_var(self.key) },
- }
- }
-}
-
/// Publish the module host policy for this process.
///
/// `tree_summarizer_ingest` reaches the loaded tinymemory module through
@@ -123,16 +80,6 @@ fn ensure_memory_seams() {
});
}
-fn ensure_rpc_auth() {
- AUTH_INIT.get_or_init(|| {
- // SAFETY: called once, under env_lock() via the test body.
- unsafe { std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN) };
- let token_dir = std::env::temp_dir().join("openhuman-tree-summarizer-e2e-auth");
- std::fs::create_dir_all(&token_dir).expect("mkdir token dir");
- init_rpc_token(&token_dir).expect("init rpc token");
- });
-}
-
fn write_config(dir: &Path) {
std::fs::create_dir_all(dir).expect("mkdir openhuman home");
let cfg = r#"
@@ -172,7 +119,7 @@ async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
let url = format!("{}/rpc", base.trim_end_matches('/'));
let resp = client
.post(&url)
- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .header(AUTHORIZATION, format!("Bearer {rpc_token()}"))
.json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))
.send()
.await
diff --git a/tests/in_process/worker_b_domain_e2e.rs b/tests/in_process/worker_b_domain_e2e.rs
index fa1ff5c85b..701ca95b15 100644
--- a/tests/in_process/worker_b_domain_e2e.rs
+++ b/tests/in_process/worker_b_domain_e2e.rs
@@ -5,6 +5,9 @@
//! deterministic controller paths. External-service paths are asserted at
//! validation/config boundaries so the suite stays hermetic.
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock;
+use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use std::net::SocketAddr;
use std::path::Path;
use std::sync::{Mutex, OnceLock};
@@ -15,64 +18,8 @@ use reqwest::StatusCode;
use serde_json::{json, Value};
use tempfile::{tempdir, TempDir};
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_rpc::server::build_core_http_router;
-const TEST_RPC_TOKEN: &str = "worker-b-domain-e2e-token";
-
-static AUTH_INIT: OnceLock<()> = OnceLock::new();
-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
-
-struct EnvVarGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, path: &Path) -> Self {
- let old = std::env::var(key).ok();
- std::env::set_var(key, path.as_os_str());
- Self { key, old }
- }
-
- fn set(key: &'static str, value: &str) -> Self {
- let old = std::env::var(key).ok();
- std::env::set_var(key, value);
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var(key).ok();
- std::env::remove_var(key);
- 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),
- }
- }
-}
-
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- let mutex = ENV_LOCK.get_or_init(|| Mutex::new(()));
- match mutex.lock() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
- }
-}
-
-fn ensure_rpc_auth() {
- AUTH_INIT.get_or_init(|| {
- std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN);
- let token_dir = std::env::temp_dir().join("openhuman-worker-b-domain-e2e-auth");
- init_rpc_token(&token_dir).expect("init rpc auth token");
- });
-}
-
async fn serve_rpc() -> (
SocketAddr,
tokio::task::JoinHandle<Result<(), std::io::Error>>,
@@ -169,7 +116,7 @@ async fn rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {
let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));
let response = client
.post(&url)
- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .header(AUTHORIZATION, format!("Bearer {rpc_token()}"))
.json(&json!({
"jsonrpc": "2.0",
"id": id,
diff --git a/tests/in_process/worker_c_modules_e2e.rs b/tests/in_process/worker_c_modules_e2e.rs
index 22acdc768a..42942d7b8e 100644
--- a/tests/in_process/worker_c_modules_e2e.rs
+++ b/tests/in_process/worker_c_modules_e2e.rs
@@ -4,6 +4,9 @@
//! composio / threads slice and drives the real HTTP JSON-RPC router against
//! an isolated workspace. It avoids live network calls.
+use crate::env_guard::EnvVarGuard;
+use crate::env_guard::env_lock;
+use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
@@ -16,49 +19,9 @@ use reqwest::StatusCode;
use serde_json::{json, Value};
use tempfile::{tempdir, TempDir};
-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_core::core::dispatch::UNKNOWN_METHOD_PREFIX;
use openhuman_rpc::server::build_core_http_router;
-const TEST_RPC_TOKEN: &str = "worker-c-modules-e2e-token";
-
-static AUTH_INIT: OnceLock<()> = OnceLock::new();
-static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
-
-struct EnvVarGuard {
- key: &'static str,
- old: Option<String>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, path: &Path) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::set_var(key, path.as_os_str()) };
- Self { key, old }
- }
-
- fn set(key: &'static str, value: &str) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::set_var(key, value) };
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var(key).ok();
- unsafe { std::env::remove_var(key) };
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- match &self.old {
- Some(value) => unsafe { std::env::set_var(self.key, value) },
- None => unsafe { std::env::remove_var(self.key) },
- }
- }
-}
-
struct Harness {
rpc_base: String,
_tmp: TempDir,
@@ -72,22 +35,6 @@ impl Drop for Harness {
}
}
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- let mutex = ENV_LOCK.get_or_init(|| Mutex::new(()));
- match mutex.lock() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
- }
-}
-
-fn ensure_rpc_auth() {
- AUTH_INIT.get_or_init(|| {
- unsafe { std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN) };
- let token_dir = std::env::temp_dir().join("openhuman-worker-c-e2e-auth");
- init_rpc_token(&token_dir).expect("init rpc auth token");
- });
-}
-
fn write_config(openhuman_dir: &Path) {
std::fs::create_dir_all(openhuman_dir).expect("create .openhuman");
let cfg = r#"api_url = "http://127.0.0.1:9"
@@ -158,7 +105,7 @@ async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
let url = format!("{}/rpc", base.trim_end_matches('/'));
let response = client
.post(&url)
- .header(AUTHORIZATION, format!("Bearer {TEST_RPC_TOKEN}"))
+ .header(AUTHORIZATION, format!("Bearer {rpc_token()}"))
.json(&json!({
"jsonrpc": "2.0",
"id": id,