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 {
router: Router,
}
impl TestApp {
pub fn new(router: Router) -> Self {
Self { router }
}
pub fn request(&self, method: Method, uri: &str) -> TestRequest {
TestRequest {
router: self.router.clone(),
builder: Request::builder().method(method).uri(uri).extension(
axum::extract::ConnectInfo(std::net::SocketAddr::from(([127, 0, 0, 1], 12345))),
),
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 {
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 {
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 {
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 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")]
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 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;