use crate::TestResponse;
use axum::body::Body;
use axum::http::{header, Request};
use axum::Router;
use larust_core::AppError;
use larust_http::session::{resolve_backend, Session, SessionBackend};
use sqlx::AnyPool;
use std::sync::Arc;
use tower::ServiceExt;
pub struct TestClient {
router: Router,
session_store: SessionBackend,
cookie: Option<String>,
}
impl TestClient {
pub fn new(router: Router, session_pool: &AnyPool) -> Self {
Self {
router,
session_store: resolve_backend(session_pool),
cookie: None,
}
}
pub async fn get(&mut self, path: &str) -> TestResponse {
self.send(Request::get(path).body(Body::empty()).unwrap())
.await
}
pub async fn post_form(&mut self, path: &str, form: &[(&str, &str)]) -> TestResponse {
let body = form_urlencoded::Serializer::new(String::new())
.extend_pairs(form)
.finish();
let request = Request::post(path)
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(Body::from(body))
.unwrap();
self.send(request).await
}
pub async fn post_multipart(
&mut self,
path: &str,
csrf_token: &str,
filename: &str,
content_type: &str,
bytes: &[u8],
) -> TestResponse {
const BOUNDARY: &str = "----larust-test-boundary";
let mut body = Vec::new();
body.extend_from_slice(
format!(
"--{BOUNDARY}\r\n\
Content-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\n\
Content-Type: {content_type}\r\n\r\n"
)
.as_bytes(),
);
body.extend_from_slice(bytes);
body.extend_from_slice(format!("\r\n--{BOUNDARY}--\r\n").as_bytes());
let request = Request::post(path)
.header(
header::CONTENT_TYPE,
format!("multipart/form-data; boundary={BOUNDARY}"),
)
.header("X-CSRF-TOKEN", csrf_token)
.body(Body::from(body))
.unwrap();
self.send(request).await
}
pub async fn post_json<T: serde::Serialize>(
&mut self,
path: &str,
csrf_token: &str,
body: &T,
) -> TestResponse {
let request = Request::post(path)
.header(header::CONTENT_TYPE, "application/json")
.header("X-CSRF-TOKEN", csrf_token)
.body(Body::from(
serde_json::to_vec(body).expect("test request body must be JSON-serializable"),
))
.unwrap();
self.send(request).await
}
pub async fn acting_as<U: larust_support::auth::Authenticatable>(
&mut self,
user: &U,
) -> Result<(), AppError> {
let session = Session::new(None, Arc::new(self.session_store.clone()), None);
larust_support::auth::login(&session, user).await?;
session
.save()
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
let id = session
.id()
.expect("session id is set after a successful save()");
self.cookie = Some(format!("{}={id}", larust_http::session::cookie_name()));
Ok(())
}
async fn send(&mut self, mut request: Request<Body>) -> TestResponse {
if let Some(cookie) = &self.cookie {
request
.headers_mut()
.insert(header::COOKIE, cookie.parse().unwrap());
}
let response = self.router.clone().oneshot(request).await.unwrap();
let status = response.status();
let headers = response.headers().clone();
if let Some(set_cookie) = headers
.get(header::SET_COOKIE)
.and_then(|v| v.to_str().ok())
{
self.cookie = Some(set_cookie.split(';').next().unwrap().to_string());
}
let body_bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let body = String::from_utf8_lossy(&body_bytes).into_owned();
TestResponse::new(status, headers, body)
}
}