Skip to content

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

refactor(embed): extract shared test helpers into a common module

Steven Enamakel5b31923d7307
diff --git a/crates/openhuman-embed/tests/common/mod.rs b/crates/openhuman-embed/tests/common/mod.rs
new file mode 100644
index 0000000000..b8c41b9938
--- /dev/null
+++ b/crates/openhuman-embed/tests/common/mod.rs
@@ -0,0 +1,108 @@
+//! Helpers shared by the embed crate's end-to-end tests.
+//!
+//! Each test file owns its process: a runtime claims a process-wide slot, so
+//! the files split by scenario rather than by assertion.
+
+#![allow(dead_code)]
+
+use openhuman_core::config::Config;
+use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};
+use serde_json::json;
+
+/// An OpenAI-compatible chat completion carrying `content`.
+pub fn chat_completion(content: &str) -> serde_json::Value {
+ json!({
+ "id": "chatcmpl-embed-test",
+ "object": "chat.completion",
+ "created": 1_700_000_000_u64,
+ "model": "embed-test-model",
+ "choices": [{
+ "index": 0,
+ "message": { "role": "assistant", "content": content },
+ "finish_reason": "stop"
+ }],
+ "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2 }
+ })
+}
+
+/// A config that keeps the turn offline: no local runtimes, no spaCy, no
+/// embeddings endpoint. Mirrors `crates/openhuman-core/src/bin/library_profile/harness.rs::fixture()`,
+/// which is the recipe already proven against real turns.
+pub fn offline_config() -> Config {
+ let mut config = Config::default();
+ config.local_ai.runtime_enabled = false;
+ config.runtime_python.enabled = false;
+ config.memory_tree.spacy_enabled = false;
+ config.memory_tree.embedding_endpoint = None;
+ config.memory_tree.embedding_model = None;
+ config.memory_tree.embedding_strict = false;
+ // User-message memory autosave is intentionally fire-and-forget. It can
+ // still be writing after a turn returns, which is useful in the product but
+ // unrelated to these tests' contracts and would race the final
+ // ephemeral-workspace cleanup assertion.
+ config.memory.auto_save = false;
+ // Session-store dual writes and shadow reads are also deliberately
+ // fire-and-forget; leaving them on makes their detached filesystem work
+ // race the synchronous ephemeral cleanup.
+ config.agent.session_dual_write = false;
+ config.agent.session_shadow_reads = false;
+ config.default_temperature = 0.0;
+ config
+}
+
+/// The tuned runtime the harness documents as the caller's responsibility.
+///
+/// A default 2 MiB worker stack overflows on a turn that delegates to a
+/// sub-agent and aborts the whole process, so building it the documented way is
+/// both what the test needs and a check that the documented way works.
+pub fn runtime() -> tokio::runtime::Runtime {
+ tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .thread_stack_size(AGENT_WORKER_STACK_BYTES)
+ .max_blocking_threads(MAX_BLOCKING_THREADS)
+ .build()
+ .expect("tokio runtime")
+}
+
+/// A stub backend that answers every incidental non-inference call.
+pub async fn stub_backend() -> wiremock::MockServer {
+ let backend = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::any())
+ .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(json!({
+ "success": true,
+ "data": { "id": "embed-test", "email": "[email protected]" }
+ })))
+ .mount(&backend)
+ .await;
+ backend
+}
+
+/// An OpenAI-compatible provider answering `/v1/chat/completions` with `reply`.
+pub async fn provider(reply: &str) -> wiremock::MockServer {
+ let server = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .and(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(chat_completion(reply)))
+ .mount(&server)
+ .await;
+ server
+}
+
+/// The tool names a recorded chat-completion request advertised.
+pub fn tool_names(request: &wiremock::Request) -> Vec<String> {
+ let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default();
+ body.get("tools")
+ .and_then(|t| t.as_array())
+ .map(|tools| {
+ tools
+ .iter()
+ .filter_map(|t| {
+ t.pointer("/function/name")
+ .or_else(|| t.get("name"))
+ .and_then(|n| n.as_str())
+ .map(str::to_string)
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
diff --git a/crates/openhuman-embed/tests/harness_embed.rs b/crates/openhuman-embed/tests/harness_embed.rs
index 9a5289f91b..aabcec966a 100644
--- a/crates/openhuman-embed/tests/harness_embed.rs
+++ b/crates/openhuman-embed/tests/harness_embed.rs
@@ -17,8 +17,9 @@
//! also what makes the routing assertion possible — if the turn had gone
//! anywhere else, the mock would have recorded no request.
-use openhuman_core::config::Config;
-use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};
+mod common;
+
+use common::{chat_completion, offline_config, runtime};
use openhuman_embed::{Access, Harness, Provider, Workspace};
use serde_json::json;
use wiremock::matchers::{any, method, path};
@@ -26,63 +27,6 @@ use wiremock::{Mock, MockServer, ResponseTemplate};
const REPLY: &str = "harness-embed-ok";
-/// An OpenAI-compatible chat completion carrying `content`.
-fn chat_completion(content: &str) -> serde_json::Value {
- json!({
- "id": "chatcmpl-harness-embed",
- "object": "chat.completion",
- "created": 1_700_000_000_u64,
- "model": "harness-embed-model",
- "choices": [{
- "index": 0,
- "message": { "role": "assistant", "content": content },
- "finish_reason": "stop"
- }],
- "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2 }
- })
-}
-
-/// A config that keeps the turn offline: no local runtimes, no spaCy, no
-/// embeddings endpoint. Mirrors `crates/openhuman-core/src/bin/library_profile/harness.rs::fixture()`,
-/// which is the recipe already proven against real turns.
-fn offline_config() -> Config {
- let mut config = Config::default();
- config.local_ai.runtime_enabled = false;
- config.runtime_python.enabled = false;
- config.memory_tree.spacy_enabled = false;
- config.memory_tree.embedding_endpoint = None;
- config.memory_tree.embedding_model = None;
- config.memory_tree.embedding_strict = false;
- // User-message memory autosave is intentionally fire-and-forget. It can
- // still be writing after a turn returns, which is useful in the product but
- // unrelated to this test's provider/session/concurrency contract and would
- // race the final ephemeral-workspace cleanup assertion.
- config.memory.auto_save = false;
- // Session-store dual writes and shadow reads are also deliberately
- // fire-and-forget. This test already verifies the authoritative session
- // database; leaving the migration mirrors enabled makes their detached
- // filesystem work race the harness's synchronous ephemeral cleanup after
- // the 100-turn stress case.
- config.agent.session_dual_write = false;
- config.agent.session_shadow_reads = false;
- config.default_temperature = 0.0;
- config
-}
-
-/// The tuned runtime the harness documents as the caller's responsibility.
-///
-/// A default 2 MiB worker stack overflows on a turn that delegates to a
-/// sub-agent and aborts the whole process, so building it the documented way is
-/// both what the test needs and a check that the documented way works.
-fn runtime() -> tokio::runtime::Runtime {
- tokio::runtime::Builder::new_multi_thread()
- .enable_all()
- .thread_stack_size(AGENT_WORKER_STACK_BYTES)
- .max_blocking_threads(MAX_BLOCKING_THREADS)
- .build()
- .expect("tokio runtime")
-}
-
#[test]
fn a_harness_runs_a_turn_against_the_provider_it_was_given() {
let _ = env_logger::builder().is_test(true).try_init();
@@ -236,8 +180,17 @@ fn a_harness_runs_a_turn_against_the_provider_it_was_given() {
"sessions were not persisted under the harness workspace"
);
- // A second harness in this process must be refused rather than silently
- // sharing process-global core state with the first.
+ // The harness is one runtime plus one agent, and says so.
+ assert_eq!(harness.agent().id(), "harness");
+ assert_eq!(harness.runtime().workspace_dir(), harness.workspace_dir());
+ assert_eq!(harness.runtime().agent_ids(), vec!["harness".to_string()]);
+ assert!(
+ harness.agent().transcripts_dir().is_dir(),
+ "the harness agent's transcripts land in its own subtree"
+ );
+
+ // A second harness — a second runtime — in this process must be
+ // refused rather than silently sharing process-global core state.
let err = Harness::builder()
.workspace(Workspace::Ephemeral)
.build()
@@ -247,6 +200,15 @@ fn a_harness_runs_a_turn_against_the_provider_it_was_given() {
matches!(err, openhuman_embed::HarnessError::AlreadyRunning),
"got {err:?}"
);
+ let err = openhuman_embed::Runtime::builder()
+ .workspace(Workspace::Ephemeral)
+ .build()
+ .await
+ .expect_err("a second runtime must be refused");
+ assert!(
+ matches!(err, openhuman_embed::RuntimeError::AlreadyRunning),
+ "got {err:?}"
+ );
drop(harness);
assert!(
diff --git a/crates/openhuman-embed/tests/public_api.rs b/crates/openhuman-embed/tests/public_api.rs
index fd0d8d1c18..ac099f589f 100644
--- a/crates/openhuman-embed/tests/public_api.rs
+++ b/crates/openhuman-embed/tests/public_api.rs
@@ -1,9 +1,10 @@
use std::sync::Arc;
use openhuman_embed::{
- set_product_identity, Access, AgentTurnOrigin, Core, CoreBuilder, CoreRuntime, DomainSet,
- GroupMode, Harness, HostKind, ProductIdentity, Provider, RuntimeConfig, ServiceSet, ToolGroups,
- TrustedAccess, TrustedAutomationSource, Workspace,
+ set_product_identity, Access, Agent, AgentDefinitionSpec, AgentSpec, AgentTurnOrigin, ApiKey,
+ Core, CoreBuilder, CoreRuntime, DomainSet, GroupMode, Harness, HostKind, ProductIdentity,
+ Provider, Runtime, RuntimeBuilder, RuntimeConfig, SandboxModeSpec, ServiceSet, ToolGroups,
+ ToolScopeSpec, TrustedAccess, TrustedAutomationSource, Workspace,
};
#[test]
@@ -15,12 +16,17 @@ fn exposes_the_host_facing_embedding_contract() {
fn accepts_access(_: Access) {}
fn accepts_provider(_: Provider) {}
fn accepts_workspace(_: Workspace) {}
- fn applies_turn_origin<'a>(
- turn: openhuman_embed::Turn<'a>,
+ fn applies_turn_origin(
+ turn: openhuman_embed::Turn,
origin: AgentTurnOrigin,
- ) -> openhuman_embed::Turn<'a> {
+ ) -> openhuman_embed::Turn {
turn.origin(origin)
}
+ fn accepts_runtime_handle(_: Runtime) {}
+ fn accepts_runtime_builder(_: RuntimeBuilder) {}
+ fn accepts_agent(_: Agent) {}
+ fn accepts_agent_spec(_: AgentSpec) {}
+ fn accepts_api_key(_: ApiKey) {}
let _ = accepts_core;
let _ = accepts_builder;
@@ -30,6 +36,26 @@ fn exposes_the_host_facing_embedding_contract() {
let _ = accepts_provider;
let _ = accepts_workspace;
let _ = applies_turn_origin;
+ let _ = accepts_runtime_handle;
+ let _ = accepts_runtime_builder;
+ let _ = accepts_agent;
+ let _ = accepts_agent_spec;
+ let _ = accepts_api_key;
+ let _ = Runtime::builder()
+ .api_key("th_public_api")
+ .backend_url("https://backend.example");
+ let _ = AgentSpec::new("public-api")
+ .system_prompt("You are a test.")
+ .definition(
+ AgentDefinitionSpec::new()
+ .tools(ToolScopeSpec::Named(vec!["read_file".into()]))
+ .sandbox(SandboxModeSpec::ReadOnly),
+ )
+ .access(Access::readonly())
+ .action_dir("/tmp/embed-public-api")
+ .include_user_skills(false)
+ .shared_memory(false)
+ .config(|_config| {});
let _ = DomainSet::embedded;
let _ = ServiceSet::none;
let _ = HostKind::Library;