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),
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 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
}
}