next_rust_server/
testing.rs1use bytes::Bytes;
14use futures_util::StreamExt;
15use http::HeaderMap;
16use next_rust_core::{Config, Environment};
17
18use crate::app::{App, AppBuilder, Routes};
19use crate::request::Request;
20use crate::response::Body;
21
22#[derive(Debug, Clone)]
24pub struct TestResponse {
25 pub status: u16,
26 pub headers: HeaderMap,
27 pub text: String,
28 pub chunks: Vec<String>,
30}
31
32impl TestResponse {
33 pub fn header(&self, name: &str) -> Option<&str> {
34 self.headers.get(name).and_then(|v| v.to_str().ok())
35 }
36
37 pub fn json<T: serde::de::DeserializeOwned>(&self) -> T {
38 serde_json::from_str(&self.text).unwrap_or_else(|e| panic!("response is not valid JSON ({e}): {}", self.text))
39 }
40
41 pub fn cookies(&self) -> Vec<&str> {
43 self.headers.get_all("set-cookie").iter().filter_map(|v| v.to_str().ok()).collect()
44 }
45}
46
47#[derive(Clone)]
49pub struct TestClient {
50 app: App,
51 cookies: std::sync::Arc<std::sync::Mutex<Vec<(String, String)>>>,
52}
53
54impl TestClient {
55 pub fn new(routes: Routes) -> Self {
58 Self::with(App::new(routes), Environment::Test)
59 }
60
61 pub fn production(routes: Routes) -> Self {
64 Self::with(App::new(routes), Environment::Production)
65 }
66
67 pub fn with(builder: AppBuilder, env: Environment) -> Self {
68 let root = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".into());
69 let config = Config::discover(&root).expect("valid next-rust configuration");
70 let app = builder
71 .config(config)
72 .environment(env)
73 .page_store(next_rust_cache::MemoryStore::new(1000))
74 .build()
75 .expect("app builds");
76 TestClient { app, cookies: Default::default() }
77 }
78
79 pub fn from_app(app: App) -> Self {
80 TestClient { app, cookies: Default::default() }
81 }
82
83 pub fn app(&self) -> &App {
84 &self.app
85 }
86
87 pub async fn send(&self, mut req: http::Request<Bytes>) -> TestResponse {
91 if !req.headers().contains_key("cookie") {
92 let jar = self.cookies.lock().unwrap_or_else(|e| e.into_inner()).clone();
93 if !jar.is_empty() {
94 let v = jar.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join("; ");
95 if let Ok(v) = http::HeaderValue::from_str(&v) {
96 req.headers_mut().insert("cookie", v);
97 }
98 }
99 }
100 if !req.headers().contains_key("host") {
101 req.headers_mut().insert("host", http::HeaderValue::from_static("localhost"));
102 }
103 let res = self.app.handle(Request::from_http(req)).await;
104 let status = res.status.as_u16();
105 let headers = res.headers.clone();
106 {
107 let mut jar = self.cookies.lock().unwrap_or_else(|e| e.into_inner());
108 for v in headers.get_all("set-cookie").iter().filter_map(|v| v.to_str().ok()) {
109 let Some((pair, _)) = v.split_once(';').or(Some((v, ""))) else { continue };
110 let Some((k, val)) = pair.split_once('=') else { continue };
111 jar.retain(|(name, _)| name != k);
112 if !v.contains("Max-Age=0") {
113 jar.push((k.to_owned(), val.to_owned()));
114 }
115 }
116 }
117 let mut chunks = Vec::new();
118 match res.body {
119 Body::Empty => {}
120 Body::Bytes(b) => chunks.push(String::from_utf8_lossy(&b).into_owned()),
121 Body::Stream(mut s) => {
122 while let Some(chunk) = s.next().await {
123 match chunk {
124 Ok(b) => chunks.push(String::from_utf8_lossy(&b).into_owned()),
125 Err(e) => chunks.push(format!("<stream error: {e}>")),
126 }
127 }
128 }
129 }
130 TestResponse { status, headers, text: chunks.concat(), chunks }
131 }
132
133 pub fn action_url(&self, id: &str) -> String {
137 let name = crate::action_token::BIND_COOKIE;
139 let binding = {
140 let mut jar = self.cookies.lock().unwrap_or_else(|e| e.into_inner());
141 match jar.iter().find(|(k, _)| k == name) {
142 Some((_, v)) => v.clone(),
143 None => {
144 let v = crate::random_hex(32);
145 jar.push((name.to_owned(), v.clone()));
146 v
147 }
148 }
149 };
150 crate::actions::signed_url(id, &binding, self.app.config().security.action_token_ttl)
151 }
152
153 pub async fn get(&self, uri: &str) -> TestResponse {
154 self.send(http::Request::get(uri).body(Bytes::new()).expect("valid request")).await
155 }
156
157 pub async fn get_with_headers(&self, uri: &str, headers: &[(&str, &str)]) -> TestResponse {
159 let mut req = http::Request::get(uri);
160 for (name, value) in headers {
161 req = req.header(*name, *value);
162 }
163 self.send(req.body(Bytes::new()).expect("valid request")).await
164 }
165
166 pub async fn navigate(&self, uri: &str, from_html: &str) -> TestResponse {
169 let keys = layout_keys(from_html).join(",");
170 self.get_with_headers(uri, &[("x-nr-nav", "1"), ("x-nr-layouts", &keys)]).await
171 }
172
173 pub async fn post_json<T: serde::Serialize>(&self, uri: &str, body: &T) -> TestResponse {
174 let bytes = serde_json::to_vec(body).expect("serializable body");
175 self.send(
176 http::Request::post(uri)
177 .header("content-type", "application/json")
178 .body(Bytes::from(bytes))
179 .expect("valid request"),
180 )
181 .await
182 }
183
184 pub async fn post_form(&self, uri: &str, body: &str) -> TestResponse {
186 self.send(
187 http::Request::post(uri)
188 .header("content-type", "application/x-www-form-urlencoded")
189 .body(Bytes::from(body.to_owned()))
190 .expect("valid request"),
191 )
192 .await
193 }
194}
195
196pub fn layout_keys(html: &str) -> Vec<String> {
198 html.split("<!--nr-l:").skip(1).filter_map(|rest| rest.split("-->").next()).map(str::to_owned).collect()
199}
200
201pub fn strip_layout_markers(html: &str) -> String {
204 let mut out = String::with_capacity(html.len());
205 let mut rest = html;
206 while let Some(at) = rest.find("<!--nr-l:").into_iter().chain(rest.find("<!--/nr-l:")).min() {
207 out.push_str(&rest[..at]);
208 match rest[at..].find("-->") {
209 Some(end) => rest = &rest[at + end + 3..],
210 None => {
211 rest = &rest[at..];
212 break;
213 }
214 }
215 }
216 out.push_str(rest);
217 out
218}