Skip to main content

alef_e2e/codegen/
mod.rs

1//! E2e test code generation trait and language dispatch.
2//!
3//! ## DRY layer ([`client`])
4//!
5//! Per-language e2e codegen historically duplicated the structural shape of every
6//! test (function header, request build, response assert) and only differed in
7//! syntax. The [`client`] submodule pulls that shape into trait + driver pairs
8//! ([`client::TestClientRenderer`] + [`client::http_call::render_http_test`])
9//! so each language can be migrated to TestClient-driven tests by:
10//!
11//! 1. Implementing `TestClientRenderer` once per language (small, mechanical).
12//! 2. Replacing the language's monolithic `render_http_test_function` with a
13//!    call to `client::http_call::render_http_test(out, &MyRenderer, fixture)`.
14//! 3. Optionally splitting the per-language file into a directory
15//!    `<lang>/{mod.rs,client.rs,ws.rs,helpers.rs}` when the file gets unwieldy.
16//!
17//! Until a language migrates, it continues using the legacy monolithic renderer —
18//! both can coexist behind the per-language [`E2eCodegen::generate`] entry.
19
20pub mod brew;
21pub mod c;
22pub mod client;
23pub mod csharp;
24pub mod dart;
25pub mod elixir;
26pub mod gleam;
27pub mod go;
28pub mod java;
29pub mod kotlin;
30pub mod php;
31pub mod python;
32pub mod r;
33pub mod ruby;
34pub mod rust;
35pub mod streaming_assertions;
36pub mod swift;
37pub mod typescript;
38pub mod wasm;
39pub mod zig;
40
41use crate::config::E2eConfig;
42use crate::fixture::{Fixture, FixtureGroup};
43use alef_core::backend::GeneratedFile;
44use alef_core::config::ResolvedCrateConfig;
45use alef_core::ir::TypeDef;
46use anyhow::Result;
47
48/// Check if a fixture should be included for the given language.
49///
50/// Returns false if:
51/// - The fixture's resolved category is in `e2e_config.exclude_categories`
52///   (fixture is excluded from every language's cross-language e2e codegen)
53/// - The fixture has a skip condition that applies to this language
54/// - The fixture's call has no resolvable function for this language (no base
55///   `function` set and no override for the language). Calls that share a base
56///   function but only carry per-language type/arg overrides are still emitted
57///   for languages without an explicit override.
58pub(crate) fn should_include_fixture(fixture: &Fixture, language: &str, e2e_config: &E2eConfig) -> bool {
59    if !e2e_config.exclude_categories.is_empty() && e2e_config.exclude_categories.contains(&fixture.resolved_category())
60    {
61        return false;
62    }
63    if let Some(skip) = &fixture.skip {
64        if skip.should_skip(language) {
65            return false;
66        }
67    }
68    let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
69    // Also respect skip_languages on the resolved call (e.g. batch_scrape skips elixir).
70    if call_config.skip_languages.iter().any(|l| l == language) {
71        return false;
72    }
73    if call_config.function.is_empty() && !call_config.overrides.contains_key(language) {
74        return false;
75    }
76    true
77}
78
79/// Recursively rewrite a JSON value's object keys to the target wire case.
80///
81/// `wire_case` accepts the same vocabulary as serde's `rename_all` attribute:
82/// `"snake_case"` (default), `"camelCase"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`,
83/// `"kebab-case"`, `"SCREAMING-KEBAB-CASE"`. Unknown values fall back to `snake_case`.
84///
85/// Used by per-language e2e codegen to translate canonical (snake_case) fixture keys
86/// to the wire case that each binding's `from_json` / typed deserializer expects, as
87/// driven by `ResolvedCrateConfig::serde_rename_all_for_language`.
88pub(crate) fn transform_json_keys_for_language(value: &serde_json::Value, wire_case: &str) -> serde_json::Value {
89    use heck::{ToKebabCase, ToLowerCamelCase, ToPascalCase, ToShoutyKebabCase, ToShoutySnakeCase, ToSnakeCase};
90    let rewrite_key: fn(&str) -> String = match wire_case {
91        "camelCase" => |k| k.to_lower_camel_case(),
92        "PascalCase" => |k| k.to_pascal_case(),
93        "SCREAMING_SNAKE_CASE" => |k| k.to_shouty_snake_case(),
94        "kebab-case" => |k| k.to_kebab_case(),
95        "SCREAMING-KEBAB-CASE" => |k| k.to_shouty_kebab_case(),
96        _ => |k| k.to_snake_case(),
97    };
98    fn walk(value: &serde_json::Value, rewrite_key: fn(&str) -> String) -> serde_json::Value {
99        match value {
100            serde_json::Value::Object(obj) => {
101                let new_obj: serde_json::Map<String, serde_json::Value> = obj
102                    .iter()
103                    .map(|(k, v)| (rewrite_key(k), walk(v, rewrite_key)))
104                    .collect();
105                serde_json::Value::Object(new_obj)
106            }
107            serde_json::Value::Array(arr) => {
108                serde_json::Value::Array(arr.iter().map(|v| walk(v, rewrite_key)).collect())
109            }
110            other => other.clone(),
111        }
112    }
113    walk(value, rewrite_key)
114}
115
116/// Trait for per-language e2e test code generation.
117pub trait E2eCodegen: Send + Sync {
118    /// Generate all e2e test project files for this language.
119    ///
120    /// `type_defs` is the IR type registry extracted from the source crate.
121    /// It is used by backends that need to introspect struct field types at
122    /// codegen time (e.g. the TypeScript/WASM generator uses it to
123    /// auto-derive `nested_types` mappings for wasm-bindgen class wrapping).
124    fn generate(
125        &self,
126        groups: &[FixtureGroup],
127        e2e_config: &E2eConfig,
128        config: &ResolvedCrateConfig,
129        type_defs: &[TypeDef],
130    ) -> Result<Vec<GeneratedFile>>;
131
132    /// Language name for display and directory naming.
133    fn language_name(&self) -> &'static str;
134}
135
136/// Get all available e2e code generators.
137pub fn all_generators() -> Vec<Box<dyn E2eCodegen>> {
138    vec![
139        Box::new(rust::RustE2eCodegen),
140        Box::new(python::PythonE2eCodegen),
141        Box::new(typescript::TypeScriptCodegen),
142        Box::new(go::GoCodegen),
143        Box::new(java::JavaCodegen),
144        Box::new(kotlin::KotlinE2eCodegen),
145        Box::new(csharp::CSharpCodegen),
146        Box::new(php::PhpCodegen),
147        Box::new(ruby::RubyCodegen),
148        Box::new(elixir::ElixirCodegen),
149        Box::new(gleam::GleamE2eCodegen),
150        Box::new(r::RCodegen),
151        Box::new(wasm::WasmCodegen),
152        Box::new(c::CCodegen),
153        Box::new(zig::ZigE2eCodegen),
154        Box::new(dart::DartE2eCodegen),
155        Box::new(swift::SwiftE2eCodegen),
156        Box::new(brew::BrewCodegen),
157    ]
158}
159
160/// Get e2e code generators for specific language names.
161pub fn generators_for(languages: &[String]) -> Vec<Box<dyn E2eCodegen>> {
162    all_generators()
163        .into_iter()
164        .filter(|g| languages.iter().any(|l| l == g.language_name()))
165        .collect()
166}
167
168/// Resolve a JSON field from a fixture input by path.
169///
170/// Field paths in call config are "input.path", "input.config", etc.
171/// Since we already receive `fixture.input`, strip the leading "input." prefix.
172/// When `field_path` is exactly `"input"`, the whole input object is returned.
173pub(crate) fn resolve_field<'a>(input: &'a serde_json::Value, field_path: &str) -> &'a serde_json::Value {
174    // "input" with no subpath means "the entire input object".
175    if field_path == "input" {
176        return input;
177    }
178    let path = field_path.strip_prefix("input.").unwrap_or(field_path);
179    let mut current = input;
180    for part in path.split('.') {
181        current = current.get(part).unwrap_or(&serde_json::Value::Null);
182    }
183    current
184}