1use crate::{Request, Response, Router};
6use hyper::{Body, Method, Uri};
7use std::collections::HashMap;
8
9pub struct TestClient {
11 router: Router,
12 default_headers: HashMap<String, String>,
13}
14
15impl TestClient {
16 pub fn new(router: Router) -> Self {
18 Self {
19 router,
20 default_headers: HashMap::new(),
21 }
22 }
23
24 pub fn with_auth(mut self, token: &str) -> Self {
26 self.default_headers
27 .insert("authorization".to_string(), format!("Bearer {}", token));
28 self
29 }
30
31 pub fn with_session(mut self, session_id: &str) -> Self {
33 self.default_headers.insert(
34 "cookie".to_string(),
35 format!("yaiko_session={}", session_id),
36 );
37 self
38 }
39
40 pub fn with_header(mut self, key: &str, value: &str) -> Self {
42 self.default_headers
43 .insert(key.to_string(), value.to_string());
44 self
45 }
46
47 pub async fn get(&self, path: &str) -> TestResponse {
49 self.request(Method::GET, path, None, HashMap::new()).await
50 }
51
52 pub async fn post(&self, path: &str, body: impl Into<String>) -> TestResponse {
54 let mut headers = HashMap::new();
55 headers.insert("content-type".to_string(), "application/json".to_string());
56 self.request(Method::POST, path, Some(body.into()), headers)
57 .await
58 }
59
60 pub async fn put(&self, path: &str, body: impl Into<String>) -> TestResponse {
62 let mut headers = HashMap::new();
63 headers.insert("content-type".to_string(), "application/json".to_string());
64 self.request(Method::PUT, path, Some(body.into()), headers)
65 .await
66 }
67
68 pub async fn patch(&self, path: &str, body: impl Into<String>) -> TestResponse {
70 let mut headers = HashMap::new();
71 headers.insert("content-type".to_string(), "application/json".to_string());
72 self.request(Method::PATCH, path, Some(body.into()), headers)
73 .await
74 }
75
76 pub async fn delete(&self, path: &str) -> TestResponse {
78 self.request(Method::DELETE, path, None, HashMap::new())
79 .await
80 }
81
82 pub async fn post_form(&self, path: &str, data: &HashMap<String, String>) -> TestResponse {
84 let encoded: String = data
85 .iter()
86 .map(|(k, v)| {
87 format!(
88 "{}={}",
89 percent_encoding::utf8_percent_encode(k, percent_encoding::NON_ALPHANUMERIC),
90 percent_encoding::utf8_percent_encode(v, percent_encoding::NON_ALPHANUMERIC),
91 )
92 })
93 .collect::<Vec<_>>()
94 .join("&");
95 let mut headers = HashMap::new();
96 headers.insert(
97 "content-type".to_string(),
98 "application/x-www-form-urlencoded".to_string(),
99 );
100 self.request(Method::POST, path, Some(encoded), headers)
101 .await
102 }
103
104 pub async fn request(
106 &self,
107 method: Method,
108 path: &str,
109 body: Option<String>,
110 headers: HashMap<String, String>,
111 ) -> TestResponse {
112 let uri: Uri = path.parse().expect("Invalid URI");
113
114 let mut builder = hyper::Request::builder().method(method.clone()).uri(uri);
115
116 for (key, value) in &self.default_headers {
118 builder = builder.header(key.as_str(), value.as_str());
119 }
120 for (key, value) in &headers {
122 builder = builder.header(key.as_str(), value.as_str());
123 }
124
125 let hyper_body = match body {
126 Some(b) => Body::from(b),
127 None => Body::empty(),
128 };
129
130 let hyper_req = builder.body(hyper_body).expect("Failed to build request");
131 let req = match Request::from_hyper(hyper_req).await {
132 Ok(r) => r,
133 Err(e) => {
134 return TestResponse {
135 status: 500,
136 headers: HashMap::new(),
137 body: format!("Failed to create request: {}", e),
138 };
139 }
140 };
141
142 match self.router.handle_request(req).await {
143 Ok(response) => TestResponse::from_response(response).await,
144 Err(e) => TestResponse {
145 status: 500,
146 headers: HashMap::new(),
147 body: format!("Error: {}", e),
148 },
149 }
150 }
151}
152
153#[derive(Debug)]
155pub struct TestResponse {
156 pub status: u16,
157 pub headers: HashMap<String, String>,
158 pub body: String,
159}
160
161impl TestResponse {
162 async fn from_response(response: Response) -> Self {
163 let status = response.status.as_u16();
164 let headers: HashMap<String, String> = response
165 .headers
166 .iter()
167 .map(|(k, v)| (k.clone(), v.clone()))
168 .collect();
169
170 let body_bytes = hyper::body::to_bytes(response.body)
171 .await
172 .unwrap_or_default();
173 let body = String::from_utf8_lossy(&body_bytes).to_string();
174
175 Self {
176 status,
177 headers,
178 body,
179 }
180 }
181
182 pub fn is_success(&self) -> bool {
184 self.status >= 200 && self.status < 300
185 }
186
187 pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
189 serde_json::from_str(&self.body)
190 }
191
192 pub fn assert_status(&self, expected: u16) -> &Self {
194 assert_eq!(
195 self.status, expected,
196 "Expected status {}, got {}",
197 expected, self.status
198 );
199 self
200 }
201
202 pub fn assert_body_contains(&self, text: &str) -> &Self {
204 assert!(
205 self.body.contains(text),
206 "Body does not contain '{}': {}",
207 text,
208 self.body
209 );
210 self
211 }
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217
218 #[tokio::test]
219 async fn test_client_works() {
220 let router = Router::new();
222 let _client = TestClient::new(router);
223 }
224}