arqen 0.7.0

Backend infrastructure for agent-ready applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! Testing utilities module for Arqen.
//!
//! Provides TestApp, MockAuth, fixture helpers, and request builders for testing.

use std::sync::Arc;

use axum::Router;
use axum::body::Body;
use axum::http::{Method, Request};
use axum::response::Response;
use tower::ServiceExt;

use crate::agent::ToolRegistry;
use crate::auth::{AuthContext, AuthError, Authentication};
use crate::config::AppConfig;
use crate::state::AppState;
use crate::thingd::{MemoryThingdBackend, ThingdBackend};

/// Test application with memory adapters.
pub struct TestApp {
    state: AppState,
    router: Router,
}

impl TestApp {
    /// Create a new TestApp builder.
    pub fn builder() -> TestAppBuilder {
        TestAppBuilder::new()
    }

    /// Make an HTTP request to the test app.
    pub async fn request(&self, method: Method, path: &str) -> Response {
        self.router
            .clone()
            .oneshot(
                Request::builder()
                    .method(method)
                    .uri(path)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .expect("failed to make request")
    }

    /// Make a GET request.
    pub async fn get(&self, path: &str) -> Response {
        self.request(Method::GET, path).await
    }

    /// Make a POST request with JSON body.
    pub async fn post_json(&self, path: &str, body: serde_json::Value) -> Response {
        self.router
            .clone()
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri(path)
                    .header("content-type", "application/json")
                    .body(Body::from(serde_json::to_string(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .expect("failed to make request")
    }

    /// Make a PUT request with JSON body.
    pub async fn put_json(&self, path: &str, body: serde_json::Value) -> Response {
        self.router
            .clone()
            .oneshot(
                Request::builder()
                    .method(Method::PUT)
                    .uri(path)
                    .header("content-type", "application/json")
                    .body(Body::from(serde_json::to_string(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .expect("failed to make request")
    }

    /// Make a DELETE request.
    pub async fn delete(&self, path: &str) -> Response {
        self.request(Method::DELETE, path).await
    }

    /// Make a request with custom headers.
    pub async fn request_with_headers(
        &self,
        method: Method,
        path: &str,
        headers: Vec<(&str, &str)>,
    ) -> Response {
        let mut builder = Request::builder().method(method).uri(path);
        for (key, value) in headers {
            builder = builder.header(key, value);
        }
        self.router
            .clone()
            .oneshot(builder.body(Body::empty()).unwrap())
            .await
            .expect("failed to make request")
    }

    /// Get the app state.
    pub fn state(&self) -> &AppState {
        &self.state
    }

    /// Get the storage backend.
    pub fn storage(&self) -> &Arc<dyn ThingdBackend> {
        &self.state.storage
    }

    /// Get the tool registry.
    pub fn registry(&self) -> &Arc<ToolRegistry> {
        &self.state.tool_registry
    }
}

/// Builder for TestApp.
pub struct TestAppBuilder {
    config: AppConfig,
    auth: Option<Arc<dyn Authentication>>,
    storage: Option<Arc<dyn ThingdBackend>>,
    registry: Option<ToolRegistry>,
}

impl TestAppBuilder {
    /// Create a new builder.
    pub fn new() -> Self {
        Self {
            config: AppConfig::default(),
            auth: None,
            storage: None,
            registry: None,
        }
    }

    /// Set the config.
    pub fn with_config(mut self, config: AppConfig) -> Self {
        self.config = config;
        self
    }

    /// Set the auth adapter.
    pub fn with_auth(mut self, auth: Arc<dyn Authentication>) -> Self {
        self.auth = Some(auth);
        self
    }

    /// Set the storage backend.
    pub fn with_storage(mut self, storage: Arc<dyn ThingdBackend>) -> Self {
        self.storage = Some(storage);
        self
    }

    /// Set the tool registry.
    pub fn with_registry(mut self, registry: ToolRegistry) -> Self {
        self.registry = Some(registry);
        self
    }

    /// Build the TestApp.
    pub fn build(self) -> TestApp {
        let storage = self
            .storage
            .unwrap_or_else(|| Arc::new(MemoryThingdBackend::new()));

        let registry = self.registry.unwrap_or_else(|| {
            ToolRegistry::new(
                &format!("{}-test", env!("CARGO_PKG_NAME")),
                env!("CARGO_PKG_VERSION"),
                "Test agent",
                "memory",
            )
        });

        let state = AppState::builder()
            .with_config(self.config)
            .with_storage(storage)
            .with_tool_registry(registry)
            .build()
            .expect("failed to build AppState");

        let router = crate::http::create_router_with_state(state.clone());

        TestApp { state, router }
    }
}

impl Default for TestAppBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Mock authentication adapter for testing.
pub struct MockAuth {
    behavior: MockAuthBehavior,
}

/// Behavior for MockAuth.
pub enum MockAuthBehavior {
    /// Always succeed with the given context.
    AlwaysSuccess(AuthContext),
    /// Always fail with the given error.
    AlwaysFail(AuthError),
}

impl MockAuth {
    /// Create a MockAuth that always succeeds.
    pub fn always_success(subject: impl Into<String>) -> Self {
        Self {
            behavior: MockAuthBehavior::AlwaysSuccess(AuthContext::new(subject, "mock")),
        }
    }

    /// Create a MockAuth that always fails.
    pub fn always_fail(error: AuthError) -> Self {
        Self {
            behavior: MockAuthBehavior::AlwaysFail(error),
        }
    }

    /// Create a MockAuth that returns missing credentials error.
    pub fn always_missing() -> Self {
        Self::always_fail(AuthError::Missing)
    }

    /// Create a MockAuth that returns invalid credentials error.
    pub fn always_invalid() -> Self {
        Self::always_fail(AuthError::Invalid)
    }
}

#[axum::async_trait]
impl Authentication for MockAuth {
    async fn authenticate(
        &self,
        _headers: &axum::http::HeaderMap,
    ) -> Result<AuthContext, AuthError> {
        match &self.behavior {
            MockAuthBehavior::AlwaysSuccess(ctx) => Ok(ctx.clone()),
            MockAuthBehavior::AlwaysFail(err) => Err(err.clone()),
        }
    }
}

/// Fixture helper for creating test data.
pub struct Fixtures {
    storage: Arc<dyn ThingdBackend>,
}

impl Fixtures {
    /// Create a new Fixtures instance.
    pub fn new(storage: Arc<dyn ThingdBackend>) -> Self {
        Self { storage }
    }

    /// Create a test object.
    pub async fn create_object(
        &self,
        kind: &str,
        id: &str,
        data: serde_json::Value,
    ) -> Result<crate::thingd::ThingdObject, crate::core::AppError> {
        self.storage.put_object(kind, id, data).await
    }

    /// Get a test object.
    pub async fn get_object(
        &self,
        kind: &str,
        id: &str,
    ) -> Result<Option<serde_json::Value>, crate::core::AppError> {
        let obj = self.storage.get_object(kind, id).await?;
        Ok(obj.map(|o| o.data))
    }

    /// Delete a test object.
    pub async fn delete_object(&self, kind: &str, id: &str) -> Result<(), crate::core::AppError> {
        self.storage.delete_object(kind, id).await
    }

    /// Create multiple test objects.
    pub async fn create_objects(
        &self,
        kind: &str,
        count: usize,
    ) -> Result<Vec<crate::thingd::ThingdObject>, crate::core::AppError> {
        let mut objects = Vec::new();
        for i in 0..count {
            let id = format!("{}-{}", kind, i);
            let data = serde_json::json!({"index": i});
            let obj = self.storage.put_object(kind, &id, data).await?;
            objects.push(obj);
        }
        Ok(objects)
    }
}

/// Response body reader.
pub async fn read_body(response: Response) -> serde_json::Value {
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("failed to read body");
    serde_json::from_slice(&body).expect("failed to parse JSON")
}

/// Assert that a response has the expected status code.
#[macro_export]
macro_rules! assert_response {
    ($response:expr, $status:expr) => {
        assert_eq!($response.status(), $status, "expected status {}", $status);
    };
    ($response:expr, $status:expr, $body:expr) => {
        assert_eq!($response.status(), $status, "expected status {}", $status);
        let body = axum::body::to_bytes($response.into_body(), usize::MAX)
            .await
            .expect("failed to read body");
        let body: serde_json::Value = serde_json::from_slice(&body).expect("failed to parse JSON");
        assert_eq!(body, $body);
    };
}

/// Assert that an error response has the expected error code.
#[macro_export]
macro_rules! assert_error {
    ($response:expr, $code:expr) => {
        assert_eq!(
            $response.status(),
            $crate::core::error::ErrorCode::$code.status_code()
        );
        let body = axum::body::to_bytes($response.into_body(), usize::MAX)
            .await
            .expect("failed to read body");
        let body: serde_json::Value = serde_json::from_slice(&body).expect("failed to parse JSON");
        assert_eq!(body["error"]["code"], stringify!($code));
    };
}

/// Assert that JSON contains expected fields.
#[macro_export]
macro_rules! assert_json_contains {
    ($json:expr, { $($key:expr => $value:expr),* $(,)? }) => {
        $(
            assert_eq!($json[$key], $value, "expected {} to be {:?}", $key, $value);
        )*
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::StatusCode;
    use serde_json::json;

    #[tokio::test]
    async fn test_testapp_builder_default() {
        let app = TestApp::builder().build();
        let response = app.get("/health").await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_testapp_get() {
        let app = TestApp::builder().build();
        let response = app.get("/health").await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_testapp_post_json() {
        let app = TestApp::builder().build();
        let response = app.post_json("/agent", json!({})).await;
        assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
    }

    #[tokio::test]
    async fn test_testapp_put_json() {
        let app = TestApp::builder().build();
        let response = app.put_json("/agent", json!({})).await;
        assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
    }

    #[tokio::test]
    async fn test_testapp_delete() {
        let app = TestApp::builder().build();
        let response = app.delete("/agent").await;
        assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
    }

    #[tokio::test]
    async fn test_testapp_state() {
        let app = TestApp::builder().build();
        assert_eq!(app.state().config.server.port, 8888);
    }

    #[tokio::test]
    async fn test_testapp_storage() {
        let app = TestApp::builder().build();
        let result = app.storage().count_objects("test").await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_testapp_registry() {
        let app = TestApp::builder().build();
        let manifest = app.registry().generate_manifest();
        assert!(manifest.name.contains("test"));
    }

    #[tokio::test]
    async fn test_mock_auth_always_success() {
        let auth = MockAuth::always_success("user-123");
        let ctx = auth
            .authenticate(&axum::http::HeaderMap::new())
            .await
            .unwrap();
        assert_eq!(ctx.subject, "user-123");
        assert_eq!(ctx.adapter, "mock");
    }

    #[tokio::test]
    async fn test_mock_auth_always_fail() {
        let auth = MockAuth::always_fail(AuthError::Invalid);
        let err = auth
            .authenticate(&axum::http::HeaderMap::new())
            .await
            .unwrap_err();
        assert_eq!(err, AuthError::Invalid);
    }

    #[tokio::test]
    async fn test_mock_auth_always_missing() {
        let auth = MockAuth::always_missing();
        let err = auth
            .authenticate(&axum::http::HeaderMap::new())
            .await
            .unwrap_err();
        assert_eq!(err, AuthError::Missing);
    }

    #[tokio::test]
    async fn test_mock_auth_always_invalid() {
        let auth = MockAuth::always_invalid();
        let err = auth
            .authenticate(&axum::http::HeaderMap::new())
            .await
            .unwrap_err();
        assert_eq!(err, AuthError::Invalid);
    }

    #[tokio::test]
    async fn test_fixtures_create_object() {
        let storage = Arc::new(MemoryThingdBackend::new());
        let fixtures = Fixtures::new(storage);
        let obj = fixtures
            .create_object("user", "user-1", json!({"name": "Alice"}))
            .await
            .unwrap();
        assert_eq!(obj.id, "user-1");
    }

    #[tokio::test]
    async fn test_fixtures_get_object() {
        let storage = Arc::new(MemoryThingdBackend::new());
        let fixtures = Fixtures::new(storage);
        let obj = fixtures
            .create_object("user", "user-1", json!({"name": "Alice"}))
            .await
            .unwrap();
        let data = fixtures.get_object("user", &obj.id).await.unwrap();
        assert!(data.is_some());
        assert_eq!(data.unwrap()["name"], "Alice");
    }

    #[tokio::test]
    async fn test_fixtures_get_nonexistent() {
        let storage = Arc::new(MemoryThingdBackend::new());
        let fixtures = Fixtures::new(storage);
        let obj = fixtures.get_object("user", "nonexistent").await.unwrap();
        assert!(obj.is_none());
    }

    #[tokio::test]
    async fn test_fixtures_create_multiple() {
        let storage = Arc::new(MemoryThingdBackend::new());
        let fixtures = Fixtures::new(storage);
        let objects = fixtures.create_objects("item", 5).await.unwrap();
        assert_eq!(objects.len(), 5);
    }

    #[tokio::test]
    async fn test_read_body() {
        let app = TestApp::builder().build();
        let response = app.get("/health").await;
        let body = read_body(response).await;
        assert!(body.is_object() || body.is_string() || body.is_null());
    }
}