larust_testing/response.rs
1use axum::http::{HeaderMap, StatusCode};
2
3/// A `TestClient` response with the body already buffered into an owned
4/// `String` - every existing hand-rolled test in this codebase repeats
5/// the same `axum::body::to_bytes(...).await.unwrap().to_vec()` +
6/// `String::from_utf8(...).unwrap()` dance at nearly every assertion
7/// site; this does it once, at construction, instead.
8pub struct TestResponse {
9 status: StatusCode,
10 headers: HeaderMap,
11 body: String,
12}
13
14impl TestResponse {
15 pub(crate) fn new(status: StatusCode, headers: HeaderMap, body: String) -> Self {
16 Self {
17 status,
18 headers,
19 body,
20 }
21 }
22
23 pub fn status(&self) -> StatusCode {
24 self.status
25 }
26
27 pub fn body(&self) -> &str {
28 &self.body
29 }
30
31 pub fn header(&self, name: &str) -> Option<&str> {
32 self.headers.get(name)?.to_str().ok()
33 }
34
35 /// Scrapes the hidden `_csrf_token` field's value out of the response
36 /// body (reuses [`larust_http::csrf::FIELD_NAME`] rather than a
37 /// hardcoded string), for a test that fetched a form page and now
38 /// needs the token to submit it via [`crate::TestClient::post_form`] -
39 /// the exact manual step every CSRF-protected test in this codebase
40 /// performed by hand before this crate existed.
41 pub fn csrf_token(&self) -> Option<String> {
42 extract_hidden_field_value(&self.body, larust_http::csrf::FIELD_NAME)
43 }
44
45 /// Scrapes the CSRF token out of the shared layout's
46 /// `<meta name="csrf-token" content="...">` tag instead of a hidden
47 /// form field - for a page with no `@csrf`-rendered `<form>` at all
48 /// (e.g. one whose only interaction is a JS-driven `fetch()`, like a
49 /// `@wire(...)`-mounted component's `wire:model`/`wire:submit` sync),
50 /// the same way the real client runtime
51 /// (`crates/larust-live/assets/wire-runtime.js`) itself reads it.
52 pub fn meta_csrf_token(&self) -> Option<String> {
53 extract_attr_value(&self.body, "name=\"csrf-token\" content=\"")
54 }
55
56 /// Panics (with the actual vs. expected status in the message) unless
57 /// the response has `expected`'s status - matching this codebase's
58 /// plain `assert!`/`assert_eq!` style, just packaged for chaining.
59 pub fn assert_status(&self, expected: StatusCode) -> &Self {
60 assert_eq!(
61 self.status, expected,
62 "expected status {expected}, got {} - body: {}",
63 self.status, self.body
64 );
65 self
66 }
67
68 /// Asserts a 3xx status whose `Location` header equals `path` exactly
69 /// (Laravel's `assertRedirect($path)`).
70 pub fn assert_redirect_to(&self, path: &str) -> &Self {
71 assert!(
72 self.status.is_redirection(),
73 "expected a redirect, got status {} - body: {}",
74 self.status,
75 self.body
76 );
77 assert_eq!(
78 self.header("location"),
79 Some(path),
80 "expected a redirect to `{path}`"
81 );
82 self
83 }
84
85 /// Asserts the response body contains `needle` (Laravel's
86 /// `assertSee($text)`).
87 pub fn assert_body_contains(&self, needle: &str) -> &Self {
88 assert!(
89 self.body.contains(needle),
90 "expected body to contain `{needle}` - body: {}",
91 self.body
92 );
93 self
94 }
95}
96
97/// The actual scraping logic, factored out from [`TestResponse::csrf_token`]
98/// so it's testable against a plain string without a real response.
99/// Looks for `name="{field}" value="..."` and returns the `value`.
100fn extract_hidden_field_value(html: &str, field: &str) -> Option<String> {
101 extract_attr_value(html, &format!("name=\"{field}\" value=\""))
102}
103
104/// Finds `needle` (an attribute-name-and-opening-quote prefix, e.g.
105/// `name="csrf-token" content="`) and returns the quoted value that
106/// follows it, up to the next `"`. Shared by [`extract_hidden_field_value`]
107/// and [`TestResponse::meta_csrf_token`] - the only difference between
108/// scraping a hidden input's `value=` and a meta tag's `content=` is which
109/// attribute name comes right before the value.
110fn extract_attr_value(html: &str, needle: &str) -> Option<String> {
111 let start = html.find(needle)? + needle.len();
112 let end = html[start..].find('"')? + start;
113 Some(html[start..end].to_string())
114}
115
116#[cfg(test)]
117mod tests {
118 use super::*;
119
120 #[test]
121 fn extract_hidden_field_value_finds_the_value() {
122 let html = r#"<input type="hidden" name="_csrf_token" value="abc123">"#;
123 assert_eq!(
124 extract_hidden_field_value(html, "_csrf_token"),
125 Some("abc123".to_string())
126 );
127 }
128
129 #[test]
130 fn extract_hidden_field_value_returns_none_when_absent() {
131 let html = "<p>no token here</p>";
132 assert_eq!(extract_hidden_field_value(html, "_csrf_token"), None);
133 }
134
135 #[test]
136 fn extract_hidden_field_value_only_matches_the_named_field() {
137 let html = r#"<input name="other_field" value="not-this-one">"#;
138 assert_eq!(extract_hidden_field_value(html, "_csrf_token"), None);
139 }
140
141 #[test]
142 fn extract_attr_value_finds_a_meta_tags_content() {
143 let html = r#"<meta name="csrf-token" content="xyz789">"#;
144 assert_eq!(
145 extract_attr_value(html, "name=\"csrf-token\" content=\""),
146 Some("xyz789".to_string())
147 );
148 }
149}