mod boot;
mod contracts;
mod factory;
mod session;
pub use boot::{TestAppBuilder, TestApplication, TestDatabase};
pub use factory::{Factory, FactoryBuilder};
pub use session::{SessionRequest, TestSession};
use axum::{
body::{to_bytes, Body, Bytes},
http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode},
Router,
};
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value;
use tower::ServiceExt;
#[derive(Clone)]
pub struct TestApp {
contracts: Option<std::sync::Arc<std::result::Result<contracts::ContractRegistry, String>>>,
services: capy_core::Services,
seeds: Option<capy_db::Seeds>,
router: Router,
context: Option<capy_core::AppContext>,
database: Option<std::sync::Arc<boot::DatabaseGuard>>,
peer: std::net::SocketAddr,
csrf: bool,
#[cfg(feature = "jobs")]
jobs: Option<TestQueue>,
#[cfg(feature = "mail")]
mail: Option<TestMailer>,
}
impl TestApp {
pub fn new(router: Router) -> Self {
Self {
contracts: None,
services: capy_core::Services::new(),
seeds: None,
router,
context: None,
database: None,
peer: ([127, 0, 0, 1], 12345).into(),
csrf: false,
#[cfg(feature = "jobs")]
jobs: None,
#[cfg(feature = "mail")]
mail: None,
}
}
pub async fn boot(application: impl TestApplication) -> capy_core::Result<Self> {
Self::builder(application).boot().await
}
pub fn builder<A: TestApplication>(application: A) -> TestAppBuilder<A> {
TestAppBuilder::new(application)
}
pub fn with_context(mut self, context: capy_core::AppContext) -> Self {
self.context = Some(context);
self
}
pub fn with_services(mut self, services: capy_core::Services) -> Self {
self.services = services;
self
}
pub fn with_contracts(mut self, document: Value) -> Self {
self.contracts = Some(std::sync::Arc::new(contracts::ContractRegistry::new(
document,
)));
self
}
pub fn service<T: Send + Sync + 'static>(&self) -> capy_core::Result<std::sync::Arc<T>> {
self.services.get::<T>()
}
pub fn with_seeds(mut self, seeds: Option<capy_db::Seeds>) -> Self {
self.seeds = seeds;
self
}
pub async fn seed(&self) -> capy_core::Result<()> {
let seeds = self.seeds.as_ref().ok_or_else(|| {
capy_core::AppError::Configuration(
"Register application-owned seeds with App::seeds.".into(),
)
})?;
seeds.run(self.context()).await
}
pub fn with_csrf(mut self, enabled: bool) -> Self {
self.csrf = enabled;
self
}
pub fn context(&self) -> &capy_core::AppContext {
self.context
.as_ref()
.expect("Use TestApp::boot or attach the real application context")
}
pub fn db(&self) -> &sea_orm::DatabaseConnection {
&self.context().db
}
#[cfg(feature = "storage")]
pub fn storage(&self) -> capy_core::Result<std::sync::Arc<capy_storage::Storage>> {
self.service::<capy_storage::Storage>()
}
pub fn session(&self) -> TestSession {
TestSession::new(self.clone())
}
pub async fn login(&self, email: &str, password: &str) -> capy_core::Result<TestSession> {
let mut session = self.session();
if !session.login(email, password).await?.status.is_success() {
return Err(capy_core::AppError::Configuration(
"Test login failed; inspect it with TestSession::login (credentials redacted)."
.into(),
));
}
Ok(session)
}
pub fn factory<F: Factory + Default>(
&self,
) -> FactoryBuilder<'_, F, sea_orm::DatabaseConnection> {
FactoryBuilder::new(F::default(), self.db())
}
pub async fn cleanup(self) -> capy_core::Result<()> {
if let Some(database) = &self.database {
database.cleanup().await?;
}
Ok(())
}
#[cfg(feature = "jobs")]
pub fn with_jobs(mut self, jobs: TestQueue) -> Self {
self.jobs = Some(jobs);
self
}
#[cfg(feature = "jobs")]
pub fn jobs(&self) -> &TestQueue {
self.jobs
.as_ref()
.expect("Register jobs in the application factory")
}
#[cfg(feature = "mail")]
pub fn with_mail(mut self, mail: TestMailer) -> Self {
self.mail = Some(mail);
self
}
#[cfg(feature = "mail")]
pub fn mail(&self) -> &TestMailer {
self.mail
.as_ref()
.expect("Enable TestAppBuilder::capture_mail or attach a capture")
}
pub fn request(&self, method: Method, uri: &str) -> TestRequest {
TestRequest {
method: method.clone(),
path: uri.into(),
contracts: self.contracts.clone(),
router: self.router.clone(),
builder: Request::builder()
.method(method)
.uri(uri)
.extension(axum::extract::ConnectInfo(self.peer)),
body: Body::empty(),
}
}
pub fn get(&self, uri: &str) -> TestRequest {
self.request(Method::GET, uri)
}
pub fn post(&self, uri: &str) -> TestRequest {
self.request(Method::POST, uri)
}
pub fn put(&self, uri: &str) -> TestRequest {
self.request(Method::PUT, uri)
}
pub fn patch(&self, uri: &str) -> TestRequest {
self.request(Method::PATCH, uri)
}
pub fn delete(&self, uri: &str) -> TestRequest {
self.request(Method::DELETE, uri)
}
}
pub struct TestRequest {
method: Method,
path: String,
contracts: Option<std::sync::Arc<std::result::Result<contracts::ContractRegistry, String>>>,
router: Router,
builder: axum::http::request::Builder,
body: Body,
}
impl TestRequest {
pub fn peer_addr(mut self, peer: std::net::SocketAddr) -> Self {
self.builder = self.builder.extension(axum::extract::ConnectInfo(peer));
self
}
pub fn without_peer(mut self) -> Self {
if let Some(extensions) = self.builder.extensions_mut() {
extensions.remove::<axum::extract::ConnectInfo<std::net::SocketAddr>>();
}
self
}
pub fn json(mut self, value: impl Serialize) -> Self {
self.builder = self.builder.header("content-type", "application/json");
self.body = Body::from(serde_json::to_vec(&value).expect("test JSON must serialize"));
self
}
pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
self.builder = self.builder.header(name, value);
self
}
pub fn cookie(mut self, mut cookie: HeaderValue) -> Self {
cookie.set_sensitive(true);
self.builder = self.builder.header(axum::http::header::COOKIE, cookie);
self
}
pub fn body(mut self, body: impl Into<Body>) -> Self {
self.body = body.into();
self
}
pub async fn send(self) -> TestResponse {
let response = self
.router
.oneshot(self.builder.body(self.body).expect("invalid test request"))
.await
.expect("Axum service is infallible");
let (parts, body) = response.into_parts();
TestResponse {
method: self.method,
path: self.path,
contracts: self.contracts,
status: parts.status,
headers: parts.headers,
body: to_bytes(body, 16 * 1024 * 1024)
.await
.expect("test response exceeds 16 MiB or cannot be read"),
}
}
}
pub struct TestResponse {
method: Method,
path: String,
contracts: Option<std::sync::Arc<std::result::Result<contracts::ContractRegistry, String>>>,
pub status: StatusCode,
pub headers: HeaderMap,
pub body: Bytes,
}
impl std::fmt::Debug for TestResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TestResponse")
.field("status", &self.status)
.field("body_bytes", &self.body.len())
.finish_non_exhaustive()
}
}
impl TestResponse {
pub fn validate_contract(&self) -> std::result::Result<(), String> {
let contracts = self.contracts.as_ref().ok_or("No application contracts attached. Use TestApp::boot(application()) or with_contracts.")?.as_ref().as_ref().map_err(Clone::clone)?;
contracts.validate(
&self.method,
&self.path,
self.status,
&self.headers,
&self.body,
)
}
pub fn assert_contract(&self) -> &Self {
if let Err(error) = self.validate_contract() {
panic!("{error}");
}
self
}
pub fn cookie(&self, name: &str) -> Option<HeaderValue> {
self.headers
.get_all(axum::http::header::SET_COOKIE)
.iter()
.find_map(|value| {
let pair = value.to_str().ok()?.split(';').next()?;
let (key, _) = pair.split_once('=')?;
if key != name {
return None;
}
let mut value = HeaderValue::from_str(pair).ok()?;
value.set_sensitive(true);
Some(value)
})
}
pub fn assert_status(&self, status: impl Into<StatusCode>) -> &Self {
assert_eq!(
self.status,
status.into(),
"response: {}",
String::from_utf8_lossy(&self.body)
);
self
}
pub fn assert_ok(&self) -> &Self {
self.assert_status(StatusCode::OK)
}
pub fn assert_created(&self) -> &Self {
self.assert_status(StatusCode::CREATED)
}
pub fn assert_no_content(&self) -> &Self {
self.assert_status(StatusCode::NO_CONTENT);
assert!(self.body.is_empty(), "204 responses must be empty");
self
}
pub fn json<T: DeserializeOwned>(&self) -> T {
serde_json::from_slice(&self.body)
.expect("response must be valid JSON of the requested type")
}
pub fn assert_json(&self, expected: Value) -> &Self {
assert_eq!(self.json::<Value>(), expected);
self
}
}
#[cfg(feature = "jobs")]
#[derive(Clone)]
pub struct TestQueue {
queue: capy_jobs::Queue,
worker: capy_jobs::Worker,
}
#[cfg(feature = "jobs")]
impl TestQueue {
pub fn new(context: capy_core::AppContext, jobs: capy_jobs::Jobs) -> capy_core::Result<Self> {
Ok(Self {
queue: capy_jobs::Queue::new(context.db.clone()),
worker: capy_jobs::Worker::new(context, jobs)?,
})
}
pub fn with_services(mut self, services: capy_core::Services) -> Self {
self.worker = self.worker.with_services(services);
self
}
pub fn on_queue(mut self, name: impl Into<String>) -> capy_core::Result<Self> {
let name = capy_jobs::QueueName::new(name)?;
self.queue = self.queue.named(name.clone());
self.worker = self.worker.queues(vec![name])?;
Ok(self)
}
pub fn queue(&self) -> &capy_jobs::Queue {
&self.queue
}
pub async fn assert_dispatched<J: capy_jobs::Job>(&self) -> capy_core::Result<()> {
assert!(
self.queue.count::<J>().await? > 0,
"Expected a persisted job of type {}",
J::NAME
);
Ok(())
}
pub async fn run_next_job(&self) -> capy_core::Result<bool> {
self.worker.run_next().await
}
pub async fn drain(&self, limit: usize) -> capy_core::Result<usize> {
let mut processed = 0;
while processed < limit && self.worker.run_next().await? {
processed += 1;
}
Ok(processed)
}
}
#[cfg(feature = "mail")]
pub use capy_mail::CaptureTransport as TestMailer;