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