Skip to main content

alef_e2e/codegen/rust/
http.rs

1//! HTTP integration test generation for Rust e2e tests.
2
3use std::fmt::Write as FmtWrite;
4
5use crate::escape::rust_raw_string;
6use crate::fixture::{CorsConfig, Fixture, StaticFilesConfig};
7
8/// How to call a method on axum_test::TestServer in generated code.
9enum ServerCall<'a> {
10    /// Emit `server.get(path)` / `server.post(path)` etc.
11    Shorthand(&'a str),
12    /// Emit `server.method(axum::http::Method::OPTIONS, path)` etc.
13    AxumMethod(&'a str),
14}
15
16/// How to register a route on a spikard App in generated code.
17enum RouteRegistration<'a> {
18    /// Emit `spikard::get(path)` / `spikard::post(path)` etc.
19    Shorthand(&'a str),
20    /// Emit `spikard::RouteBuilder::new(spikard::Method::Options, path)` etc.
21    Explicit(&'a str),
22}
23
24/// Generate a complete integration test function for an http fixture.
25///
26/// Builds a real spikard `App` with a handler that returns the expected
27/// response, then uses `axum_test::TestServer` to send the request and
28/// assert the status code.
29pub 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    // spikard provides convenience functions for GET/POST/PUT/PATCH/DELETE.
41    // All other methods (HEAD, OPTIONS, TRACE, etc.) must use RouteBuilder::new directly.
42    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    // axum_test::TestServer has shorthand methods for GET/POST/PUT/PATCH/DELETE.
55    // For HEAD and other methods, use server.method(axum::http::Method::HEAD, path).
56    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    // Serialize expected response body (if any).
72    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    // Serialize request body (if any).
79    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    // Extract middleware from handler (if any).
86    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    // When static-files middleware is configured, serve from a temp dir via ServeDir.
96    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    // Build handler that returns the expected response.
102    let _ = writeln!(out, "    let expected_body = {body_literal}.to_string();");
103    let _ = writeln!(out, "    let mut app = {dep_name}::App::new();");
104
105    // Emit route registration.
106    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    // Build axum-test TestServer from the app router, optionally wrapping with CorsLayer.
131    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    // Build and send the request.
138    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    // Add request headers (axum_test::TestRequest::add_header accepts &str via TryInto).
151    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    // Add request body if present (pass as a JSON string so axum-test's bytes() API gets a Bytes value).
158    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    // Assert status code.
169    // When a CorsLayer is applied and the fixture expects a 2xx status, tower-http may
170    // return 200 instead of 204 for preflight. Accept any 2xx status in that case.
171    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
183/// Emit lines that wrap the axum router with a `tower_http::cors::CorsLayer`.
184///
185/// The CORS policy is derived from the fixture's `cors` middleware config.
186/// After this function, `router` is reassigned to the layer-wrapped version.
187pub 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    // allow_origins
197    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    // allow_methods
208    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    // allow_headers
220    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    // max_age
240    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
249/// Emit lines for a static-files integration test.
250///
251/// Writes fixture files to a temporary directory and serves them via
252/// `tower_http::services::ServeDir`, bypassing the spikard App entirely.
253fn 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    // Build the router by nesting a ServeDir for each config entry.
268    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    // Build and send the request.
297    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    // Add request headers.
310    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}