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 async fn get(&self, uri: &str) -> TestResponse {
134 self.send(http::Request::get(uri).body(Bytes::new()).expect("valid request")).await
135 }
136
137 pub async fn post_json<T: serde::Serialize>(&self, uri: &str, body: &T) -> TestResponse {
138 let bytes = serde_json::to_vec(body).expect("serializable body");
139 self.send(
140 http::Request::post(uri)
141 .header("content-type", "application/json")
142 .body(Bytes::from(bytes))
143 .expect("valid request"),
144 )
145 .await
146 }
147
148 pub async fn post_form(&self, uri: &str, body: &str) -> TestResponse {
150 self.send(
151 http::Request::post(uri)
152 .header("content-type", "application/x-www-form-urlencoded")
153 .body(Bytes::from(body.to_owned()))
154 .expect("valid request"),
155 )
156 .await
157 }
158}