The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore(composio): add client tests
Steven Enamakel725ea5542732
diff --git a/crates/openhuman-core/src/integrations/composio/client_tests.rs b/crates/openhuman-core/src/integrations/composio/client_tests.rsindex 48466dd6ff..87bd3bec4e 100644--- a/crates/openhuman-core/src/integrations/composio/client_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/client_tests.rs@@ -1,22 +1,13 @@use super::*;use crate::config::Config;-// ── Mock-backend integration tests ─────────────────────────────-//-// These stand up a real axum HTTP server on a random localhost port,-// point a `ComposioClient` at it, and drive each method end-to-end.-// That exercises the envelope parsing, HTTP plumbing, and URL-// construction in `ComposioClient` — which is otherwise only covered-// by live backend tests.-use axum::{- extract::{Path, Query, State},+ extract::State,http::StatusCode,- routing::{get, post},+ routing::get,Json, Router,};-use serde_json::{json, Value};-use std::collections::HashMap;+use serde_json::json;use std::sync::atomic::{AtomicUsize, Ordering};async fn start_mock_backend(app: Router) -> String {@@ -28,29 +19,16 @@ async fn start_mock_backend(app: Router) -> String {format!("http://127.0.0.1:{}", addr.port())}-fn build_client_for(base_url: String) -> ComposioClient {- let inner = Arc::new(crate::integrations::IntegrationClient::new(- base_url,- "test-token".into(),- ));- ComposioClient::new(inner)-}-// Calendar bare-date → RFC 3339 normalization is now covered by-// `execute_prepare::prepare_execute_arguments` (PR #1827); see-// `execute_prepare_tests.rs` for the equivalent test surface that-// supersedes the per-slug `normalize_calendar_query_args` helper-// removed alongside the upstream-main merge.--// ── Factory tests (`create_composio_client`) ────────────────────────+// ── Route resolution tests (`resolve_composio_route`) ─────────────────//-// Mirror the four branches the spec demands:+// Mirror the branches the spec demands:// 1. backend mode with a session JWT — Backend variant// 2. direct mode + stored api key — Direct variant// 3. direct mode without api key — explicit error// 4. unknown mode string — explicit error-fn config_with_session_token(tmp: &tempfile::TempDir) -> crate::config::Config {- let mut config = crate::config::Config::default();+fn config_with_session_token(tmp: &tempfile::TempDir) -> Config {+ let mut config = Config::default();config.config_path = tmp.path().join("config.toml");crate::security::credentials::AuthService::from_config(&config).store_provider_token(@@ -64,53 +42,20 @@ fn config_with_session_token(tmp: &tempfile::TempDir) -> crate::config::Config {config}-// ── Pricing short-circuit ───────────────────────────────────────────--// ── Direct-mode reshapers (`direct_authorize` / `direct_execute` / ─-// `direct_list_connections` / `direct_list_tools`)-//-// These helpers wrap a `ComposioTool` and reshape v3 responses into-// the backend-proxied envelope types. Most still assert the-// empty/invalid-input paths that don't require HTTP:-//-// * `direct_authorize` rejects an empty toolkit before any network-// hit, with an explicit error so the caller can surface it as a-// 400-class user error.-// * `direct_execute` accepts a None-arguments call and falls-// through to the underlying tool surface (which then errors on the-// network call — covered by the integration test in `ops_tests.rs`).-// * `direct_list_connections` is a thin mapper; the real coverage-// for its row → ComposioConnection translation lives in the-// `connected_account_*` tests in `composio_tests.rs`.-//-// `direct_list_tools` IS exercised over HTTP: `ComposioTool::new_with_v3_base`-// points its `/tools` GET at a local axum mock, so we can assert both the-// outbound `tags` filter (repeated query params) and the v3 → backend-envelope-// reshape without touching `backend.composio.dev`.--fn direct_tool_for_test() -> std::sync::Arc<crate::tools::ComposioTool> {- std::sync::Arc::new(crate::tools::ComposioTool::new(- "ck_test_direct",- Some("default"),- std::sync::Arc::new(crate::security::SecurityPolicy::default()),- ))-}--/// Like [`direct_tool_for_test`] but with the v3 base pointed at a local-/// mock server so HTTP paths (e.g. `direct_list_tools`) can be asserted.-fn direct_tool_for_mock(base_v3: String) -> std::sync::Arc<crate::tools::ComposioTool> {+/// Direct-mode reads are exercised over HTTP: `DirectComposioClient::new_with_v3_base`+/// points its `/tools` and `/connected_accounts` GETs at a local axum mock, so we can+/// assert the outbound `tags` filter (repeated query params) and the v3 ->+/// canonical-envelope reshape without touching `backend.composio.dev`.+fn direct_tool_for_mock(base_v3: String) -> std::sync::Arc<crate::tools::DirectComposioClient> {direct_tool_for_mock_with_key(base_v3, "ck_test_direct")}fn direct_tool_for_mock_with_key(base_v3: String,api_key: &str,-) -> std::sync::Arc<crate::tools::ComposioTool> {- std::sync::Arc::new(crate::tools::ComposioTool::new_with_v3_base(- api_key,- Some("default"),- std::sync::Arc::new(crate::security::SecurityPolicy::default()),- base_v3,+) -> std::sync::Arc<crate::tools::DirectComposioClient> {+ std::sync::Arc::new(crate::tools::DirectComposioClient::new_with_v3_base(+ api_key, base_v3,))}@@ -119,7 +64,7 @@ struct DirectAuthFailureGuard {}impl DirectAuthFailureGuard {- fn for_tool(tool: &std::sync::Arc<crate::tools::ComposioTool>) -> Self {+ fn for_tool(tool: &std::sync::Arc<crate::tools::DirectComposioClient>) -> Self {let key_id = tool.auth_key_fingerprint();crate::integrations::composio::direct_auth::reset_direct_auth_failure(key_id);Self { key_id }@@ -132,7 +77,271 @@ impl Drop for DirectAuthFailureGuard {}}-#[path = "client_authorize_and_execute_tests.rs"]-mod authorize_and_execute_tests;-#[path = "client_triggers_and_factory_tests.rs"]-mod triggers_and_factory_tests;+#[test]+fn resolve_composio_route_backend_variant_when_mode_default() {+ let tmp = tempfile::tempdir().expect("tempdir");+ let config = config_with_session_token(&tmp);+ let route = resolve_composio_route(&config).expect("backend mode should build");+ assert_eq!(route.mode(), "backend");+ assert!(matches!(route, ComposioRoute::Backend));+}++#[test]+fn resolve_composio_route_backend_empty_mode_falls_back_to_backend() {+ // A literal empty string in TOML should be treated as the default+ // (`"backend"`) rather than an unknown mode error.+ let tmp = tempfile::tempdir().expect("tempdir");+ let mut config = config_with_session_token(&tmp);+ config.composio.mode = String::new();+ let route = resolve_composio_route(&config).expect("empty mode should fall back to backend");+ assert_eq!(route.mode(), "backend");+}++#[test]+fn resolve_composio_route_backend_errors_without_session() {+ // Backend mode requires the app-session JWT — without it the+ // factory must return an explicit error (not silently downgrade).+ let tmp = tempfile::tempdir().expect("tempdir");+ let mut config = crate::config::Config::default();+ config.config_path = tmp.path().join("config.toml");+ let err = resolve_composio_route(&config)+ .err()+ .expect("must error without auth token");+ assert!(+ err.to_string().contains("no backend session token"),+ "unexpected error: {err}"+ );+}++#[test]+fn resolve_composio_route_direct_variant_with_stored_key() {+ let tmp = tempfile::tempdir().expect("tempdir");+ let mut config = crate::config::Config::default();+ config.config_path = tmp.path().join("config.toml");+ config.composio.mode = "direct".into();+ // Persist the key the way the RPC layer would.+ crate::security::credentials::AuthService::from_config(&config)+ .store_provider_token(+ crate::security::credentials::COMPOSIO_DIRECT_PROVIDER,+ crate::security::credentials::DEFAULT_AUTH_PROFILE_NAME,+ "ck_test_key_redacted",+ std::collections::HashMap::new(),+ true,+ )+ .expect("store direct api key");+ let route = resolve_composio_route(&config).expect("direct mode with stored key should build");+ assert_eq!(route.mode(), "direct");+ assert!(matches!(route, ComposioRoute::Direct(_)));+}++#[test]+fn resolve_composio_route_direct_falls_back_to_config_api_key() {+ let tmp = tempfile::tempdir().expect("tempdir");+ let mut config = crate::config::Config::default();+ config.config_path = tmp.path().join("config.toml");+ config.composio.mode = "direct".into();+ // No keychain entry — fall back to the inline config field.+ config.composio.api_key = Some("ck_inline_redacted".into());+ let route = resolve_composio_route(&config)+ .expect("direct mode should accept inline config.api_key when keychain is empty");+ assert_eq!(route.mode(), "direct");+}++#[test]+fn resolve_composio_route_direct_errors_without_key() {+ let tmp = tempfile::tempdir().expect("tempdir");+ let mut config = crate::config::Config::default();+ config.config_path = tmp.path().join("config.toml");+ config.composio.mode = "direct".into();+ let err = resolve_composio_route(&config)+ .err()+ .expect("direct without key must error");+ let msg = err.to_string();+ assert!(+ msg.contains("no api key is configured"),+ "unexpected error: {msg}"+ );+}++#[test]+fn resolve_composio_route_unknown_mode_errors() {+ let tmp = tempfile::tempdir().expect("tempdir");+ let mut config = crate::config::Config::default();+ config.config_path = tmp.path().join("config.toml");+ config.composio.mode = "voyage".into();+ let err = resolve_composio_route(&config)+ .err()+ .expect("unknown mode must error");+ let msg = err.to_string();+ assert!(msg.contains("unknown composio mode"), "got: {msg}");+ assert!(+ msg.contains("voyage"),+ "should echo the invalid value, got: {msg}"+ );+}++// ── Direct-mode credentials helpers ─────────────────────────────────++#[test]+fn store_get_clear_composio_api_key_roundtrip() {+ use crate::security::credentials::{get_composio_api_key, COMPOSIO_DIRECT_PROVIDER};++ let tmp = tempfile::tempdir().expect("tempdir");+ let mut config = crate::config::Config::default();+ config.config_path = tmp.path().join("config.toml");++ // Initially: nothing stored.+ assert_eq!(+ get_composio_api_key(&config).expect("read empty store"),+ None+ );++ // Store under the direct-mode provider slot.+ crate::security::credentials::AuthService::from_config(&config)+ .store_provider_token(+ COMPOSIO_DIRECT_PROVIDER,+ crate::security::credentials::DEFAULT_AUTH_PROFILE_NAME,+ "ck_secret_value_redacted",+ std::collections::HashMap::new(),+ true,+ )+ .expect("store");++ assert_eq!(+ get_composio_api_key(&config).expect("read stored"),+ Some("ck_secret_value_redacted".into())+ );++ // Clearing the profile must remove it again.+ crate::security::credentials::AuthService::from_config(&config)+ .remove_profile(+ COMPOSIO_DIRECT_PROVIDER,+ crate::security::credentials::DEFAULT_AUTH_PROFILE_NAME,+ )+ .expect("remove");+ assert_eq!(+ get_composio_api_key(&config).expect("read post-clear"),+ None+ );+}++#[tokio::test]+async fn direct_list_connections_stops_hitting_composio_after_repeated_invalid_api_key() {+ let hits = Arc::new(AtomicUsize::new(0));+ let app = Router::new()+ .route(+ "/connected_accounts",+ get(|State(hits): State<Arc<AtomicUsize>>| async move {+ hits.fetch_add(1, Ordering::SeqCst);+ (+ StatusCode::UNAUTHORIZED,+ Json(json!({ "error": { "message": "Invalid API key" } })),+ )+ }),+ )+ .with_state(hits.clone());+ let base = start_mock_backend(app).await;+ let tool = direct_tool_for_mock_with_key(base, "ck_test_direct_invalid_backoff");+ let _auth_guard = DirectAuthFailureGuard::for_tool(&tool);++ for _ in 0..2 {+ let err = direct_list_connections(&tool)+ .await+ .expect_err("invalid key should reject");+ assert!(+ err.to_string().contains("Invalid API key"),+ "unexpected error: {err:#}"+ );+ }++ let opened = direct_list_connections(&tool)+ .await+ .expect_err("third invalid-key failure should open the backoff gate");+ assert!(+ opened.to_string().contains("re-enter"),+ "backoff error should be actionable, got: {opened:#}"+ );++ let short_circuit = direct_list_connections(&tool)+ .await+ .expect_err("open backoff gate should short-circuit before HTTP");+ assert!(+ short_circuit.to_string().contains("re-enter"),+ "short-circuit error should stay actionable, got: {short_circuit:#}"+ );+ assert_eq!(+ hits.load(Ordering::SeqCst),+ 3,+ "after three invalid-key failures, later polls must not hit Composio"+ );+}++#[tokio::test]+async fn direct_list_tools_forwards_tags_and_reshapes_v3_envelope() {+ use axum::extract::RawQuery;+ use std::sync::Mutex;++ let captured: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));+ let sink = captured.clone();+ let app = Router::new().route(+ "/tools",+ get(move |RawQuery(q): RawQuery| {+ let sink = sink.clone();+ async move {+ *sink.lock().unwrap() = q;+ Json(json!({+ "items": [+ {+ "slug": "GITHUB_STAR_A_REPOSITORY",+ "description": "Star a repository",+ "input_parameters": { "type": "object" },+ "toolkit": { "slug": "github" }+ },+ // Empty-slug rows must be dropped by the reshaper.+ { "slug": "", "description": "junk" }+ ]+ }))+ }+ }),+ );+ let base = start_mock_backend(app).await;+ let tool = direct_tool_for_mock(base);++ let resp = super::super::direct_list_tools(+ &tool,+ &["github".to_string()],+ Some(&["stars".to_string(), "repos".to_string()]),+ )+ .await+ .expect("direct_list_tools should succeed against the mock");++ // Outbound: tags forwarded as repeated params, toolkits CSV.+ let query = captured.lock().unwrap().clone().expect("server saw query");+ assert!(query.contains("tags=stars"), "query was: {query}");+ assert!(query.contains("tags=repos"), "query was: {query}");+ assert!(query.contains("toolkits=github"), "query was: {query}");++ // Inbound: reshaped into the backend envelope, empty-slug row dropped.+ assert_eq!(resp.tools.len(), 1);+ assert_eq!(resp.tools[0].function.name, "GITHUB_STAR_A_REPOSITORY");+ assert_eq!(resp.tools[0].kind, "function");+}++#[tokio::test]+async fn pricing_for_config_short_circuits_in_direct_mode() {+ // Build a client pointed at an unreachable backend — if the+ // short-circuit fires, we never actually attempt the network call+ // and the empty default struct comes back immediately.+ let client =+ crate::integrations::IntegrationClient::new("http://127.0.0.1:0".into(), "test".into());+ let mut config = crate::config::Config::default();+ config.composio.mode = "direct".into();++ let pricing = crate::integrations::pricing_for_config(&client, &config).await;+ // The default struct has every per-integration entry as `None`.+ assert!(pricing.integrations.apify.is_none());+ assert!(pricing.integrations.twilio.is_none());+ assert!(pricing.integrations.google_places.is_none());+ assert!(pricing.integrations.parallel.is_none());+ assert!(pricing.integrations.tinyfish.is_none());+}