use axum::body::Body;
use axum::http::{header, HeaderMap, Method, Request, StatusCode};
use axum::Router;
use http_body_util::BodyExt;
use sea_orm::DatabaseConnection;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use std::future::Future;
use tower::ServiceExt;
use crate::db;
pub struct TestApp {
router: Router,
db: DatabaseConnection,
}
impl TestApp {
pub fn from_router(router: Router, db: DatabaseConnection) -> Self {
Self { router, db }
}
#[cfg(feature = "db-sqlite")]
pub async fn spawn_with<F, Fut>(builder: F) -> Self
where
F: FnOnce(DatabaseConnection) -> Fut,
Fut: Future<Output = Router>,
{
let db = db::connect_in_memory()
.await
.expect("Failed to connect to in-memory SQLite database for TestApp");
let router = builder(db.clone()).await;
Self { router, db }
}
pub fn db(&self) -> &DatabaseConnection {
&self.db
}
pub async fn get_html(&self, path: &str) -> TestResponse {
self.send(
Method::GET,
path,
&[(header::ACCEPT.as_str(), "text/html")],
Body::empty(),
)
.await
}
pub async fn post_form(&self, path: &str, fields: &[(&str, &str)]) -> TestResponse {
let encoded = encode_form(fields);
self.send(
Method::POST,
path,
&[
(header::CONTENT_TYPE.as_str(), "application/x-www-form-urlencoded"),
(header::ACCEPT.as_str(), "text/html"),
],
Body::from(encoded),
)
.await
}
pub async fn get_json(&self, path: &str) -> TestResponse {
self.send(
Method::GET,
path,
&[(header::ACCEPT.as_str(), "application/json")],
Body::empty(),
)
.await
}
pub async fn post_json<T: Serialize>(&self, path: &str, body: &T) -> TestResponse {
let payload = serde_json::to_vec(body).expect("Failed to serialize JSON request body");
self.send(
Method::POST,
path,
&[
(header::CONTENT_TYPE.as_str(), "application/json"),
(header::ACCEPT.as_str(), "application/json"),
],
Body::from(payload),
)
.await
}
pub async fn put_json<T: Serialize>(&self, path: &str, body: &T) -> TestResponse {
let payload = serde_json::to_vec(body).expect("Failed to serialize JSON request body");
self.send(
Method::PUT,
path,
&[
(header::CONTENT_TYPE.as_str(), "application/json"),
(header::ACCEPT.as_str(), "application/json"),
],
Body::from(payload),
)
.await
}
pub async fn delete(&self, path: &str) -> TestResponse {
self.send(
Method::DELETE,
path,
&[(header::ACCEPT.as_str(), "application/json")],
Body::empty(),
)
.await
}
pub async fn get_ai(&self, path: &str) -> TestResponse {
self.send(
Method::GET,
path,
&[
(header::ACCEPT.as_str(), "text/markdown"),
("x-agent-mode", "true"),
],
Body::empty(),
)
.await
}
pub fn as_agent<'a>(&'a self, scopes: &[&str]) -> AgentTestClient<'a> {
AgentTestClient {
app: self,
scopes: scopes.iter().map(|s| s.to_string()).collect(),
api_key: None,
}
}
async fn send(
&self,
method: Method,
path: &str,
headers: &[(&str, &str)],
body: Body,
) -> TestResponse {
let mut builder = Request::builder().method(method).uri(path);
for (name, value) in headers {
builder = builder.header(*name, *value);
}
let request = builder.body(body).expect("Failed to build test HTTP request");
let response = self
.router
.clone()
.oneshot(request)
.await
.expect("Router service error during test");
let status = response.status();
let resp_headers = response.headers().clone();
let bytes = response
.into_body()
.collect()
.await
.expect("Failed to read test response body")
.to_bytes();
let body_text = String::from_utf8_lossy(&bytes).to_string();
TestResponse {
status,
headers: resp_headers,
body: body_text,
}
}
}
pub struct AgentTestClient<'a> {
app: &'a TestApp,
scopes: Vec<String>,
api_key: Option<String>,
}
impl<'a> AgentTestClient<'a> {
pub fn with_api_key(mut self, key: impl Into<String>) -> Self {
self.api_key = Some(key.into());
self
}
pub async fn get_ai(&self, path: &str) -> TestResponse {
let scopes_header = self.scopes.join(",");
let mut headers = vec![
(header::ACCEPT.as_str(), "text/markdown"),
("x-agent-mode", "true"),
("x-agent-scopes", scopes_header.as_str()),
];
let auth_val;
if let Some(key) = &self.api_key {
auth_val = format!("Bearer {}", key);
headers.push((header::AUTHORIZATION.as_str(), auth_val.as_str()));
}
self.app
.send(Method::GET, path, &headers, Body::empty())
.await
}
pub async fn call_mcp_tool(&self, tool_name: &str, arguments: Value) -> TestResponse {
let rpc = serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": tool_name,
"arguments": arguments
}
});
let payload = serde_json::to_vec(&rpc).expect("Failed to serialize MCP payload");
let scopes_header = self.scopes.join(",");
let mut headers = vec![
(header::CONTENT_TYPE.as_str(), "application/json"),
(header::ACCEPT.as_str(), "application/json"),
("x-agent-scopes", scopes_header.as_str()),
];
let auth_val;
if let Some(key) = &self.api_key {
auth_val = format!("Bearer {}", key);
headers.push((header::AUTHORIZATION.as_str(), auth_val.as_str()));
}
self.app
.send(Method::POST, "/mcp", &headers, Body::from(payload))
.await
}
}
#[derive(Debug, Clone)]
pub struct TestResponse {
status: StatusCode,
headers: HeaderMap,
body: String,
}
impl TestResponse {
pub fn status(&self) -> StatusCode {
self.status
}
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
pub fn text(&self) -> &str {
&self.body
}
pub fn json<T: DeserializeOwned>(&self) -> T {
serde_json::from_str(&self.body).unwrap_or_else(|e| {
panic!(
"Failed to parse JSON response ({}): {}\nBody: {}",
self.status, e, self.body
)
})
}
pub fn assert_status(&self, expected: StatusCode) -> &Self {
assert_eq!(
self.status, expected,
"Expected HTTP {}, got {}.\nBody:\n{}",
expected, self.status, self.body
);
self
}
pub fn assert_ok(&self) -> &Self {
self.assert_status(StatusCode::OK)
}
pub fn assert_contains(&self, needle: &str) -> &Self {
assert!(
self.body.contains(needle),
"Expected response body to contain {:?}, but it did not.\nBody:\n{}",
needle,
self.body
);
self
}
pub fn assert_header_contains(&self, name: &str, needle: &str) -> &Self {
let actual = self
.headers
.get(name)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
assert!(
actual.contains(needle),
"Expected header '{}' to contain {:?}, got {:?}",
name,
needle,
actual
);
self
}
pub fn assert_has_action(&self, action_name: &str) -> &Self {
let marker = format!("**{}**", action_name);
assert!(
self.body.contains("## Available Actions") && self.body.contains(&marker),
"Expected AI response to include action {:?} under '## Available Actions'.\nBody:\n{}",
action_name,
self.body
);
self
}
}
fn encode_form(fields: &[(&str, &str)]) -> String {
fields
.iter()
.map(|(k, v)| format!("{}={}", percent_encode(k), percent_encode(v)))
.collect::<Vec<_>>()
.join("&")
}
fn percent_encode(input: &str) -> String {
let mut out = String::with_capacity(input.len());
for byte in input.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(byte as char);
}
b' ' => out.push('+'),
other => out.push_str(&format!("%{:02X}", other)),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::response::{ActionAffordance, ActionResponse, Format};
use axum::routing::{delete, get, post};
use axum::Json;
use serde::Deserialize;
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Item {
name: String,
}
async fn demo_handler(Format(fmt): Format) -> ActionResponse<Item> {
ActionResponse::new(
fmt,
Item {
name: "widget".into(),
},
)
.with_title("Demo")
.with_canonical_url("/items")
.with_html("<main><h1>Demo</h1></main>")
.with_action(ActionAffordance::new(
"create_item",
"POST",
"/items",
"Create item",
))
}
async fn echo_json(Json(item): Json<Item>) -> Json<Item> {
Json(item)
}
async fn delete_item() -> StatusCode {
StatusCode::NO_CONTENT
}
async fn form_handler(body: String) -> String {
body
}
#[tokio::test]
async fn test_app_supports_html_json_ai_and_agent_clients() {
let app = TestApp::spawn_with(|_db| async {
Router::new()
.route("/items", get(demo_handler).post(echo_json).put(echo_json))
.route("/items/1", delete(delete_item))
.route("/form", post(form_handler))
.route("/mcp", post(|Json(v): Json<Value>| async move { Json(v) }))
})
.await;
app.db().ping().await.unwrap();
app.get_html("/items")
.await
.assert_ok()
.assert_contains("<h1>Demo</h1>")
.assert_header_contains("link", "/.well-known/ferrik-agent.json");
let item: Item = app.get_json("/items").await.assert_ok().json();
assert_eq!(item.name, "widget");
app.get_ai("/items")
.await
.assert_ok()
.assert_contains("canonical_url: /items")
.assert_has_action("create_item");
let created: Item = app
.post_json("/items", &Item { name: "new".into() })
.await
.assert_ok()
.json();
assert_eq!(created.name, "new");
let updated: Item = app
.put_json("/items", &Item { name: "upd".into() })
.await
.assert_ok()
.json();
assert_eq!(updated.name, "upd");
app.delete("/items/1")
.await
.assert_status(StatusCode::NO_CONTENT);
app.post_form("/form", &[("title", "hello world!")])
.await
.assert_ok()
.assert_contains("title=hello+world%21");
let agent = app.as_agent(&["items:read", "items:write"]).with_api_key("ferrik_ak_test");
agent.get_ai("/items").await.assert_ok().assert_has_action("create_item");
let mcp: Value = agent
.call_mcp_tool("items_create", serde_json::json!({ "name": "bot" }))
.await
.assert_ok()
.json();
assert_eq!(mcp["params"]["name"], "items_create");
}
}