Skip to main content

larust_testing/
client.rs

1use crate::TestResponse;
2use axum::body::Body;
3use axum::http::{header, Request};
4use axum::Router;
5use larust_core::AppError;
6use larust_http::session::{resolve_backend, Session, SessionBackend};
7use sqlx::AnyPool;
8use std::sync::Arc;
9use tower::ServiceExt;
10
11/// Drives a real `axum::Router` in-process (via `tower::ServiceExt::oneshot` -
12/// no TCP binding) and automatically threads the session cookie between
13/// requests, eliminating the boilerplate every hand-rolled test in this
14/// codebase repeats: building a `Request` by hand, extracting `Set-Cookie`,
15/// and re-attaching it to every subsequent call.
16///
17/// Every request method takes `&mut self` - a `TestClient` is one
18/// sequential conversation, not something to drive concurrently (its
19/// cookie is "whatever the last response set"). A second concurrent actor
20/// in one test is just a second `TestClient::new(router.clone(), &pool)` -
21/// `axum::Router::clone()` is cheap (`Arc`-backed), so this isn't wasteful.
22pub struct TestClient {
23    router: Router,
24    session_store: SessionBackend,
25    cookie: Option<String>,
26}
27
28impl TestClient {
29    /// `router` must already have a session layer installed (e.g. via
30    /// `larust_http::Router::with_sessions(session_pool, ..)`, built from
31    /// the same pool passed here) if any route needs sessions/CSRF/auth.
32    /// `session_store` resolves to whichever backend `Config::
33    /// session_driver` selects (`larust_http::session::resolve_backend`,
34    /// the same function `with_sessions` itself uses) - so `acting_as`
35    /// below writes through the identical backend the router's own
36    /// session layer reads from, database- or file-backed alike.
37    pub fn new(router: Router, session_pool: &AnyPool) -> Self {
38        Self {
39            router,
40            session_store: resolve_backend(session_pool),
41            cookie: None,
42        }
43    }
44
45    pub async fn get(&mut self, path: &str) -> TestResponse {
46        self.send(Request::get(path).body(Body::empty()).unwrap())
47            .await
48    }
49
50    /// Sends a `application/x-www-form-urlencoded` POST - the shape every
51    /// Blade-rendered form in a Larust app submits.
52    pub async fn post_form(&mut self, path: &str, form: &[(&str, &str)]) -> TestResponse {
53        let body = form_urlencoded::Serializer::new(String::new())
54            .extend_pairs(form)
55            .finish();
56        let request = Request::post(path)
57            .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
58            .body(Body::from(body))
59            .unwrap();
60        self.send(request).await
61    }
62
63    /// Sends a single-file `multipart/form-data` POST - for routes using
64    /// axum's `Multipart` extractor (real file uploads, e.g.
65    /// `UploadController::store`). The field name is fixed and
66    /// unconditional since every handler in this codebase that reads
67    /// multipart data takes whatever the *first* field is
68    /// (`multipart.next_field()`), the same way `UploadController::store`
69    /// does - there's nothing to name it for yet.
70    ///
71    /// `csrf_token` goes in the `X-CSRF-TOKEN` header, not a form field -
72    /// `larust_http::csrf::verify` checks that header *before* touching
73    /// the body at all specifically so a multipart body never gets
74    /// misread as `application/x-www-form-urlencoded` (see that
75    /// function's own doc comment). Get a token via
76    /// `TestResponse::csrf_token()` on any rendered page first, same as
77    /// `post_form`-based tests already do.
78    pub async fn post_multipart(
79        &mut self,
80        path: &str,
81        csrf_token: &str,
82        filename: &str,
83        content_type: &str,
84        bytes: &[u8],
85    ) -> TestResponse {
86        const BOUNDARY: &str = "----larust-test-boundary";
87        let mut body = Vec::new();
88        body.extend_from_slice(
89            format!(
90                "--{BOUNDARY}\r\n\
91                 Content-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\n\
92                 Content-Type: {content_type}\r\n\r\n"
93            )
94            .as_bytes(),
95        );
96        body.extend_from_slice(bytes);
97        body.extend_from_slice(format!("\r\n--{BOUNDARY}--\r\n").as_bytes());
98
99        let request = Request::post(path)
100            .header(
101                header::CONTENT_TYPE,
102                format!("multipart/form-data; boundary={BOUNDARY}"),
103            )
104            .header("X-CSRF-TOKEN", csrf_token)
105            .body(Body::from(body))
106            .unwrap();
107        self.send(request).await
108    }
109
110    /// Sends a JSON POST with the CSRF token in the `X-CSRF-TOKEN` header -
111    /// same "CSRF via header, not a form field" pattern as
112    /// `post_multipart`, for routes consumed by `fetch()`/`XMLHttpRequest`
113    /// rather than a plain `<form>` submission (e.g.
114    /// `larust_support::wire::update`, and any other JS-driven endpoint).
115    /// Get a token via `TestResponse::csrf_token()` on any rendered page
116    /// first, same as `post_form`/`post_multipart`-based tests already do.
117    pub async fn post_json<T: serde::Serialize>(
118        &mut self,
119        path: &str,
120        csrf_token: &str,
121        body: &T,
122    ) -> TestResponse {
123        let request = Request::post(path)
124            .header(header::CONTENT_TYPE, "application/json")
125            .header("X-CSRF-TOKEN", csrf_token)
126            .body(Body::from(
127                serde_json::to_vec(body).expect("test request body must be JSON-serializable"),
128            ))
129            .unwrap();
130        self.send(request).await
131    }
132
133    /// Laravel's `actingAs($user)`: logs `user` in against this client's
134    /// own session store (`resolve_backend` - the same underlying
135    /// pool/table, or the same directory, the router's own session layer
136    /// uses, so this handle behaves identically to the router's) and
137    /// adopts the resulting cookie for
138    /// every request this client sends from here on - without needing a
139    /// working `/login` route to exist in `router` at all. Calling this
140    /// again with a different user switches identity mid-test, cleanly
141    /// replacing the previously adopted cookie.
142    pub async fn acting_as<U: larust_support::auth::Authenticatable>(
143        &mut self,
144        user: &U,
145    ) -> Result<(), AppError> {
146        let session = Session::new(None, Arc::new(self.session_store.clone()), None);
147        larust_support::auth::login(&session, user).await?;
148        session
149            .save()
150            .await
151            .map_err(|source| AppError::Internal(Box::new(source)))?;
152        let id = session
153            .id()
154            .expect("session id is set after a successful save()");
155        self.cookie = Some(format!("{}={id}", larust_http::session::cookie_name()));
156        Ok(())
157    }
158
159    async fn send(&mut self, mut request: Request<Body>) -> TestResponse {
160        if let Some(cookie) = &self.cookie {
161            request
162                .headers_mut()
163                .insert(header::COOKIE, cookie.parse().unwrap());
164        }
165
166        let response = self.router.clone().oneshot(request).await.unwrap();
167        let status = response.status();
168        let headers = response.headers().clone();
169
170        if let Some(set_cookie) = headers
171            .get(header::SET_COOKIE)
172            .and_then(|v| v.to_str().ok())
173        {
174            self.cookie = Some(set_cookie.split(';').next().unwrap().to_string());
175        }
176
177        let body_bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
178            .await
179            .unwrap();
180        let body = String::from_utf8_lossy(&body_bytes).into_owned();
181
182        TestResponse::new(status, headers, body)
183    }
184}