use capy::{
axum::http::{header, HeaderValue, Method, StatusCode},
prelude::*,
};
use capy_framework as capy;
use capy_testing::TestApp;
use std::sync::Arc;
#[derive(Debug, Deserialize, Validate)]
#[serde(crate = "capy::serde")]
#[validate(crate = "capy::validator")]
struct Input {
#[validate(email)]
email: String,
#[validate(nested)]
children: Vec<Child>,
}
#[derive(Debug, Deserialize, Validate)]
#[serde(crate = "capy::serde")]
#[validate(crate = "capy::validator")]
struct Child {
#[validate(length(min = 2))]
name: String,
}
async fn app() -> Result<TestApp> {
let mut config = AppConfig::default();
config.app.name = "Typed context".into();
config.database.url = "sqlite::memory:".into();
let context = AppContext {
db: capy::db::connect(&config.database).await?,
config: Arc::new(config),
};
let routes = Routes::new()
.get("/state", |Context(ctx): Context| async move {
Json(json!({ "name": ctx.config.app.name }))
})
.get("/items/{id}", |Path(id): Path<i32>| async move {
Json(json!({ "id": id }))
})
.post("/input", |Validated(input): Validated<Input>| async move {
Created(json!({ "email": input.email }))
})
.put("/input", || async { NoContent })
.patch("/input", || async { NoContent })
.delete("/input", || async { NoContent })
.get("/unauthorized", || async { AppError::Unauthorized })
.get("/forbidden", || async { AppError::Forbidden })
.get("/conflict", || async {
AppError::Conflict("Already exists".into())
})
.get("/database", || async {
AppError::from(capy::sea_orm::DbErr::Custom(
"postgres://user:secret@host/db SQL SELECT".into(),
))
})
.get("/internal", || async {
AppError::Internal(anyhow::anyhow!("private internal details"))
})
.get("/configuration", || async {
AppError::Configuration("DATABASE_URL=secret".into())
});
assert_eq!(routes.inventory().len(), 12);
Ok(TestApp::new(App::new().routes(routes).into_router(context)))
}
#[capy::tokio::test(crate = "capy::tokio")]
async fn routes_state_and_response_helpers_work() -> Result<()> {
let app = app().await?;
app.get("/state")
.send()
.await
.assert_ok()
.assert_json(json!({"name":"Typed context"}));
app.get("/items/42")
.send()
.await
.assert_json(json!({"id":42}));
app.post("/input")
.json(json!({"email":"a@example.com","children":[]}))
.send()
.await
.assert_created()
.assert_json(json!({"email":"a@example.com"}));
app.put("/input").send().await.assert_no_content();
app.patch("/input").send().await.assert_no_content();
app.delete("/input").send().await.assert_no_content();
let head = app.request(Method::HEAD, "/state").send().await;
head.assert_ok();
assert!(head.body.is_empty());
app.post("/state")
.send()
.await
.assert_status(StatusCode::METHOD_NOT_ALLOWED)
.assert_json(json!({"message":"Method not allowed"}));
app.get("/missing")
.send()
.await
.assert_status(StatusCode::NOT_FOUND)
.assert_json(json!({"message":"Resource not found"}));
Ok(())
}
#[capy::tokio::test(crate = "capy::tokio")]
async fn validation_covers_nested_fields_and_json_rejections() -> Result<()> {
let app = app().await?;
app.post("/input")
.json(json!({"email":"secret-not-email","children":[{"name":"x"}]}))
.send()
.await
.assert_status(StatusCode::UNPROCESSABLE_ENTITY)
.assert_json(json!({"message":"Validation failed","errors":{
"email":["The email field must be a valid email address."],
"children.0.name":["The children.0.name field has an invalid length."]
}}));
app.post("/input")
.json(json!({"email":42}))
.send()
.await
.assert_status(StatusCode::UNPROCESSABLE_ENTITY);
app.post("/input")
.header(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
)
.body("{bad-json")
.send()
.await
.assert_status(StatusCode::BAD_REQUEST)
.assert_json(json!({"message":"Malformed JSON body"}));
app.post("/input")
.body("{}")
.send()
.await
.assert_status(StatusCode::UNSUPPORTED_MEDIA_TYPE);
app.post("/input")
.header(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
)
.body("x".repeat(2 * 1024 * 1024 + 1))
.send()
.await
.assert_status(StatusCode::PAYLOAD_TOO_LARGE);
Ok(())
}
#[capy::tokio::test(crate = "capy::tokio")]
async fn errors_are_consistent_and_never_expose_internal_details() -> Result<()> {
let app = app().await?;
for (path, status, message) in [
("/unauthorized", StatusCode::UNAUTHORIZED, "Unauthenticated"),
("/forbidden", StatusCode::FORBIDDEN, "Forbidden"),
("/conflict", StatusCode::CONFLICT, "Already exists"),
(
"/database",
StatusCode::INTERNAL_SERVER_ERROR,
"Internal server error",
),
(
"/internal",
StatusCode::INTERNAL_SERVER_ERROR,
"Internal server error",
),
(
"/configuration",
StatusCode::INTERNAL_SERVER_ERROR,
"Internal server error",
),
] {
app.get(path)
.send()
.await
.assert_status(status)
.assert_json(json!({"message":message}));
}
Ok(())
}
#[capy::tokio::test(crate = "capy::tokio")]
async fn route_inventory_and_unknown_commands_do_not_connect() -> Result<()> {
App::new()
.routes(Routes::new().get("/health", capy::health))
.run_command("routes")
.await?;
assert!(App::new().run_command("unknown").await.is_err());
Ok(())
}