Skip to main content

alef_e2e/codegen/rust/
mod.rs

1//! Rust e2e test code generator.
2//!
3//! Generates `e2e/rust/Cargo.toml` and `tests/{category}_test.rs` files from
4//! JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.
5
6pub mod assertions;
7pub mod cargo_toml;
8pub mod http;
9pub mod mock_server;
10pub mod test_file;
11
12mod args;
13mod assertion_helpers;
14mod assertion_synthetic;
15
16pub use cargo_toml::render_cargo_toml;
17pub use mock_server::{render_mock_server_binary, render_mock_server_module};
18
19use alef_core::backend::GeneratedFile;
20use alef_core::config::ResolvedCrateConfig;
21use anyhow::Result;
22use std::path::PathBuf;
23
24use crate::config::E2eConfig;
25use crate::escape::sanitize_filename;
26use crate::fixture::{Fixture, FixtureGroup};
27
28use super::E2eCodegen;
29use test_file::{is_skipped, render_test_file};
30
31/// Rust e2e test code generator.
32pub struct RustE2eCodegen;
33
34impl E2eCodegen for RustE2eCodegen {
35    fn generate(
36        &self,
37        groups: &[FixtureGroup],
38        e2e_config: &E2eConfig,
39        config: &ResolvedCrateConfig,
40    ) -> Result<Vec<GeneratedFile>> {
41        let mut files = Vec::new();
42        let output_base = PathBuf::from(e2e_config.effective_output()).join("rust");
43
44        // Resolve crate name and path from config.
45        let crate_name = resolve_crate_name(e2e_config, config);
46        let crate_path = resolve_crate_path(e2e_config, &crate_name);
47        let dep_name = crate_name.replace('-', "_");
48
49        // Cargo.toml
50        // Check if any call config (default or named) uses json_object/handle args (needs serde_json dep).
51        let all_call_configs = std::iter::once(&e2e_config.call).chain(e2e_config.calls.values());
52        let needs_serde_json = all_call_configs
53            .flat_map(|c| c.args.iter())
54            .any(|a| a.arg_type == "json_object" || a.arg_type == "handle");
55
56        // Check if any fixture in any group requires a mock HTTP server.
57        // This includes both liter-llm mock_response fixtures and spikard http fixtures.
58        let needs_mock_server = groups
59            .iter()
60            .flat_map(|g| g.fixtures.iter())
61            .any(|f| !is_skipped(f, "rust") && f.mock_response.is_some());
62
63        // Check if any fixture uses the http integration test pattern (spikard http fixtures).
64        let needs_http_tests = groups
65            .iter()
66            .flat_map(|g| g.fixtures.iter())
67            .any(|f| !is_skipped(f, "rust") && f.http.is_some());
68
69        // Check if any http fixture uses CORS or static-files middleware (needs tower-http).
70        let needs_tower_http = groups
71            .iter()
72            .flat_map(|g| g.fixtures.iter())
73            .filter(|f| !is_skipped(f, "rust"))
74            .filter_map(|f| f.http.as_ref())
75            .filter_map(|h| h.handler.middleware.as_ref())
76            .any(|m| m.cors.is_some() || m.static_files.is_some());
77
78        // Tokio is needed when any test is async (mock server, http tests, or async call config).
79        let any_async_call = std::iter::once(&e2e_config.call)
80            .chain(e2e_config.calls.values())
81            .any(|c| c.r#async);
82        let needs_tokio = needs_mock_server || needs_http_tests || any_async_call;
83
84        let crate_version = resolve_crate_version(e2e_config).or_else(|| config.resolved_version());
85        files.push(GeneratedFile {
86            path: output_base.join("Cargo.toml"),
87            content: render_cargo_toml(
88                &crate_name,
89                &dep_name,
90                &crate_path,
91                needs_serde_json,
92                needs_mock_server,
93                needs_http_tests,
94                needs_tokio,
95                needs_tower_http,
96                e2e_config.dep_mode,
97                crate_version.as_deref(),
98                &config.features,
99            ),
100            generated_header: true,
101        });
102
103        // Generate mock_server.rs when at least one fixture uses mock_response.
104        if needs_mock_server {
105            files.push(GeneratedFile {
106                path: output_base.join("tests").join("mock_server.rs"),
107                content: render_mock_server_module(),
108                generated_header: true,
109            });
110        }
111        // Always generate standalone mock-server binary for cross-language e2e suites
112        // when any fixture has http data (serves fixture responses for non-Rust tests).
113        if needs_mock_server || needs_http_tests {
114            files.push(GeneratedFile {
115                path: output_base.join("src").join("main.rs"),
116                content: render_mock_server_binary(),
117                generated_header: true,
118            });
119        }
120
121        // Per-category test files.
122        for group in groups {
123            let fixtures: Vec<&Fixture> = group.fixtures.iter().filter(|f| !is_skipped(f, "rust")).collect();
124
125            if fixtures.is_empty() {
126                continue;
127            }
128
129            let filename = format!("{}_test.rs", sanitize_filename(&group.category));
130            let content = render_test_file(&group.category, &fixtures, e2e_config, &dep_name, needs_mock_server);
131
132            files.push(GeneratedFile {
133                path: output_base.join("tests").join(filename),
134                content,
135                generated_header: true,
136            });
137        }
138
139        Ok(files)
140    }
141
142    fn language_name(&self) -> &'static str {
143        "rust"
144    }
145}
146
147// ---------------------------------------------------------------------------
148// Config resolution helpers
149// ---------------------------------------------------------------------------
150
151fn resolve_crate_name(_e2e_config: &E2eConfig, config: &ResolvedCrateConfig) -> String {
152    // Always use the Cargo package name (with hyphens) from alef.toml [crate].
153    // The `crate_name` override in [e2e.call.overrides.rust] is for the Rust
154    // import identifier, not the Cargo package name.
155    config.name.clone()
156}
157
158fn resolve_crate_path(e2e_config: &E2eConfig, crate_name: &str) -> String {
159    e2e_config
160        .resolve_package("rust")
161        .and_then(|p| p.path.clone())
162        .unwrap_or_else(|| format!("../../crates/{crate_name}"))
163}
164
165fn resolve_crate_version(e2e_config: &E2eConfig) -> Option<String> {
166    e2e_config.resolve_package("rust").and_then(|p| p.version.clone())
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn resolve_crate_name_uses_config_name() {
175        use alef_core::config::NewAlefConfig;
176        let cfg: NewAlefConfig = toml::from_str(
177            r#"
178[workspace]
179languages = ["rust"]
180
181[[crates]]
182name = "my-lib"
183sources = ["src/lib.rs"]
184
185[crates.e2e]
186fixtures = "fixtures"
187output = "e2e"
188[crates.e2e.call]
189function = "process"
190module = "my_lib"
191result_var = "result"
192"#,
193        )
194        .unwrap();
195        let e2e = cfg.crates[0].e2e.clone().unwrap();
196        let resolved = cfg.resolve().unwrap().remove(0);
197        let name = resolve_crate_name(&e2e, &resolved);
198        assert_eq!(name, "my-lib");
199    }
200}