1use std::fmt::Write as FmtWrite;
4
5use crate::escape::rust_raw_string;
6use crate::fixture::{CorsConfig, Fixture, StaticFilesConfig};
7
8enum ServerCall<'a> {
10 Shorthand(&'a str),
12 AxumMethod(&'a str),
14}
15
16enum RouteRegistration<'a> {
18 Shorthand(&'a str),
20 Explicit(&'a str),
22}
23
24pub fn render_http_test_function(out: &mut String, fixture: &Fixture, dep_name: &str) {
30 let http = match &fixture.http {
31 Some(h) => h,
32 None => return,
33 };
34
35 let fn_name = crate::escape::sanitize_ident(&fixture.id);
36 let description = &fixture.description;
37
38 let route = &http.handler.route;
39
40 let route_reg = match http.handler.method.to_lowercase().as_str() {
43 "get" => RouteRegistration::Shorthand("get"),
44 "post" => RouteRegistration::Shorthand("post"),
45 "put" => RouteRegistration::Shorthand("put"),
46 "patch" => RouteRegistration::Shorthand("patch"),
47 "delete" => RouteRegistration::Shorthand("delete"),
48 "head" => RouteRegistration::Explicit("Head"),
49 "options" => RouteRegistration::Explicit("Options"),
50 "trace" => RouteRegistration::Explicit("Trace"),
51 _ => RouteRegistration::Shorthand("get"),
52 };
53
54 let server_call = match http.request.method.to_uppercase().as_str() {
57 "GET" => ServerCall::Shorthand("get"),
58 "POST" => ServerCall::Shorthand("post"),
59 "PUT" => ServerCall::Shorthand("put"),
60 "PATCH" => ServerCall::Shorthand("patch"),
61 "DELETE" => ServerCall::Shorthand("delete"),
62 "HEAD" => ServerCall::AxumMethod("HEAD"),
63 "OPTIONS" => ServerCall::AxumMethod("OPTIONS"),
64 "TRACE" => ServerCall::AxumMethod("TRACE"),
65 _ => ServerCall::Shorthand("get"),
66 };
67
68 let req_path = &http.request.path;
69 let status = http.expected_response.status_code;
70
71 let body_str = match &http.expected_response.body {
73 Some(b) => serde_json::to_string(b).unwrap_or_else(|_| "{}".to_string()),
74 None => String::new(),
75 };
76 let body_literal = rust_raw_string(&body_str);
77
78 let req_body_str = match &http.request.body {
80 Some(b) => serde_json::to_string(b).unwrap_or_else(|_| "{}".to_string()),
81 None => String::new(),
82 };
83 let has_req_body = !req_body_str.is_empty();
84
85 let middleware = http.handler.middleware.as_ref();
87 let cors_cfg: Option<&CorsConfig> = middleware.and_then(|m| m.cors.as_ref());
88 let static_files_cfgs: Option<&Vec<StaticFilesConfig>> = middleware.and_then(|m| m.static_files.as_ref());
89 let has_static_files = static_files_cfgs.is_some_and(|v| !v.is_empty());
90
91 let _ = writeln!(out, "#[tokio::test]");
92 let _ = writeln!(out, "async fn test_{fn_name}() {{");
93 let _ = writeln!(out, " // {description}");
94
95 if has_static_files {
97 render_static_files_test(out, fixture, static_files_cfgs.unwrap(), &server_call, req_path, status);
98 return;
99 }
100
101 let _ = writeln!(out, " let expected_body = {body_literal}.to_string();");
103 let _ = writeln!(out, " let mut app = {dep_name}::App::new();");
104
105 match &route_reg {
107 RouteRegistration::Shorthand(method) => {
108 let _ = writeln!(
109 out,
110 " app.route({dep_name}::{method}({route:?}), move |_ctx: {dep_name}::RequestContext| {{"
111 );
112 }
113 RouteRegistration::Explicit(variant) => {
114 let _ = writeln!(
115 out,
116 " app.route({dep_name}::RouteBuilder::new({dep_name}::Method::{variant}, {route:?}), move |_ctx: {dep_name}::RequestContext| {{"
117 );
118 }
119 }
120 let _ = writeln!(out, " let body = expected_body.clone();");
121 let _ = writeln!(out, " async move {{");
122 let _ = writeln!(out, " Ok(axum::http::Response::builder()");
123 let _ = writeln!(out, " .status({status}u16)");
124 let _ = writeln!(out, " .header(\"content-type\", \"application/json\")");
125 let _ = writeln!(out, " .body(axum::body::Body::from(body))");
126 let _ = writeln!(out, " .unwrap())");
127 let _ = writeln!(out, " }}");
128 let _ = writeln!(out, " }}).unwrap();");
129
130 let _ = writeln!(out, " let router = app.into_router().unwrap();");
132 if let Some(cors) = cors_cfg {
133 render_cors_layer(out, cors);
134 }
135 let _ = writeln!(out, " let server = axum_test::TestServer::new(router);");
136
137 match &server_call {
139 ServerCall::Shorthand(method) => {
140 let _ = writeln!(out, " let response = server.{method}({req_path:?})");
141 }
142 ServerCall::AxumMethod(method) => {
143 let _ = writeln!(
144 out,
145 " let response = server.method(axum::http::Method::{method}, {req_path:?})"
146 );
147 }
148 }
149
150 for (name, value) in &http.request.headers {
152 let n = rust_raw_string(name);
153 let v = rust_raw_string(value);
154 let _ = writeln!(out, " .add_header({n}, {v})");
155 }
156
157 if has_req_body {
159 let req_body_literal = rust_raw_string(&req_body_str);
160 let _ = writeln!(
161 out,
162 " .bytes(bytes::Bytes::copy_from_slice({req_body_literal}.as_bytes()))"
163 );
164 }
165
166 let _ = writeln!(out, " .await;");
167
168 if cors_cfg.is_some() && (200..300).contains(&status) {
172 let _ = writeln!(
173 out,
174 " assert!(response.status_code().is_success(), \"expected CORS success status, got {{}}\", response.status_code());"
175 );
176 } else {
177 let _ = writeln!(out, " assert_eq!(response.status_code().as_u16(), {status}u16);");
178 }
179
180 let _ = writeln!(out, "}}");
181}
182
183pub fn render_cors_layer(out: &mut String, cors: &CorsConfig) {
188 let _ = writeln!(
189 out,
190 " // Apply CorsLayer from tower-http based on fixture CORS config."
191 );
192 let _ = writeln!(out, " use tower_http::cors::CorsLayer;");
193 let _ = writeln!(out, " use axum::http::{{HeaderName, HeaderValue, Method}};");
194 let _ = writeln!(out, " let cors_layer = CorsLayer::new()");
195
196 if cors.allow_origins.is_empty() {
198 let _ = writeln!(out, " .allow_origin(tower_http::cors::Any)");
199 } else {
200 let _ = writeln!(out, " .allow_origin([");
201 for origin in &cors.allow_origins {
202 let _ = writeln!(out, " \"{origin}\".parse::<HeaderValue>().unwrap(),");
203 }
204 let _ = writeln!(out, " ])");
205 }
206
207 if cors.allow_methods.is_empty() {
209 let _ = writeln!(out, " .allow_methods(tower_http::cors::Any)");
210 } else {
211 let methods: Vec<String> = cors
212 .allow_methods
213 .iter()
214 .map(|m| format!("Method::{}", m.to_uppercase()))
215 .collect();
216 let _ = writeln!(out, " .allow_methods([{}])", methods.join(", "));
217 }
218
219 if cors.allow_headers.is_empty() {
221 let _ = writeln!(out, " .allow_headers(tower_http::cors::Any)");
222 } else {
223 let headers: Vec<String> = cors
224 .allow_headers
225 .iter()
226 .map(|h| {
227 let lower = h.to_lowercase();
228 match lower.as_str() {
229 "content-type" => "axum::http::header::CONTENT_TYPE".to_string(),
230 "authorization" => "axum::http::header::AUTHORIZATION".to_string(),
231 "accept" => "axum::http::header::ACCEPT".to_string(),
232 _ => format!("HeaderName::from_static(\"{lower}\")"),
233 }
234 })
235 .collect();
236 let _ = writeln!(out, " .allow_headers([{}])", headers.join(", "));
237 }
238
239 if let Some(secs) = cors.max_age {
241 let _ = writeln!(out, " .max_age(std::time::Duration::from_secs({secs}));");
242 } else {
243 let _ = writeln!(out, " ;");
244 }
245
246 let _ = writeln!(out, " let router = router.layer(cors_layer);");
247}
248
249fn render_static_files_test(
254 out: &mut String,
255 fixture: &Fixture,
256 cfgs: &[StaticFilesConfig],
257 server_call: &ServerCall<'_>,
258 req_path: &str,
259 status: u16,
260) {
261 let http = fixture.http.as_ref().unwrap();
262
263 let _ = writeln!(out, " use tower_http::services::ServeDir;");
264 let _ = writeln!(out, " use axum::Router;");
265 let _ = writeln!(out, " let tmp_dir = tempfile::tempdir().expect(\"tmp dir\");");
266
267 let _ = writeln!(out, " let mut router = Router::new();");
269 for cfg in cfgs {
270 for file in &cfg.files {
271 let file_path = file.path.replace('\\', "/");
272 let content = rust_raw_string(&file.content);
273 if file_path.contains('/') {
274 let parent: String = file_path.rsplitn(2, '/').last().unwrap_or("").to_string();
275 let _ = writeln!(
276 out,
277 " std::fs::create_dir_all(tmp_dir.path().join(\"{parent}\")).unwrap();"
278 );
279 }
280 let _ = writeln!(
281 out,
282 " std::fs::write(tmp_dir.path().join(\"{file_path}\"), {content}).unwrap();"
283 );
284 }
285 let prefix = &cfg.route_prefix;
286 let serve_dir_expr = if cfg.index_file {
287 "ServeDir::new(tmp_dir.path()).append_index_html_on_directories(true)".to_string()
288 } else {
289 "ServeDir::new(tmp_dir.path())".to_string()
290 };
291 let _ = writeln!(out, " router = router.nest_service({prefix:?}, {serve_dir_expr});");
292 }
293
294 let _ = writeln!(out, " let server = axum_test::TestServer::new(router);");
295
296 match server_call {
298 ServerCall::Shorthand(method) => {
299 let _ = writeln!(out, " let response = server.{method}({req_path:?})");
300 }
301 ServerCall::AxumMethod(method) => {
302 let _ = writeln!(
303 out,
304 " let response = server.method(axum::http::Method::{method}, {req_path:?})"
305 );
306 }
307 }
308
309 for (name, value) in &http.request.headers {
311 let n = rust_raw_string(name);
312 let v = rust_raw_string(value);
313 let _ = writeln!(out, " .add_header({n}, {v})");
314 }
315
316 let _ = writeln!(out, " .await;");
317 let _ = writeln!(out, " assert_eq!(response.status_code().as_u16(), {status}u16);");
318 let _ = writeln!(out, "}}");
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324
325 #[test]
326 fn render_cors_layer_empty_policy_uses_any() {
327 let cors = CorsConfig::default();
328 let mut out = String::new();
329 render_cors_layer(&mut out, &cors);
330 assert!(out.contains("allow_origin(tower_http::cors::Any)"));
331 assert!(out.contains("allow_methods(tower_http::cors::Any)"));
332 assert!(out.contains("allow_headers(tower_http::cors::Any)"));
333 }
334}