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/// Convert a JSON value's object keys from camelCase to snake_case recursively.
80///
81/// Used when serializing fixture options for FFI-based languages (Rust, C, Java)
82/// where the receiving Rust type uses default serde (snake_case) without `rename_all`.
83pub(crate) fn normalize_json_keys_to_snake_case(value: &serde_json::Value) -> serde_json::Value {
84    use heck::ToSnakeCase;
85    match value {
86        serde_json::Value::Object(obj) => {
87            let new_obj: serde_json::Map<String, serde_json::Value> = obj
88                .iter()
89                .map(|(k, v)| (k.to_snake_case(), normalize_json_keys_to_snake_case(v)))
90                .collect();
91            serde_json::Value::Object(new_obj)
92        }
93        serde_json::Value::Array(arr) => {
94            serde_json::Value::Array(arr.iter().map(normalize_json_keys_to_snake_case).collect())
95        }
96        other => other.clone(),
97    }
98}
99
100/// Trait for per-language e2e test code generation.
101pub trait E2eCodegen: Send + Sync {
102    /// Generate all e2e test project files for this language.
103    ///
104    /// `type_defs` is the IR type registry extracted from the source crate.
105    /// It is used by backends that need to introspect struct field types at
106    /// codegen time (e.g. the TypeScript/WASM generator uses it to
107    /// auto-derive `nested_types` mappings for wasm-bindgen class wrapping).
108    fn generate(
109        &self,
110        groups: &[FixtureGroup],
111        e2e_config: &E2eConfig,
112        config: &ResolvedCrateConfig,
113        type_defs: &[TypeDef],
114    ) -> Result<Vec<GeneratedFile>>;
115
116    /// Language name for display and directory naming.
117    fn language_name(&self) -> &'static str;
118}
119
120/// Get all available e2e code generators.
121pub fn all_generators() -> Vec<Box<dyn E2eCodegen>> {
122    vec![
123        Box::new(rust::RustE2eCodegen),
124        Box::new(python::PythonE2eCodegen),
125        Box::new(typescript::TypeScriptCodegen),
126        Box::new(go::GoCodegen),
127        Box::new(java::JavaCodegen),
128        Box::new(kotlin::KotlinE2eCodegen),
129        Box::new(csharp::CSharpCodegen),
130        Box::new(php::PhpCodegen),
131        Box::new(ruby::RubyCodegen),
132        Box::new(elixir::ElixirCodegen),
133        Box::new(gleam::GleamE2eCodegen),
134        Box::new(r::RCodegen),
135        Box::new(wasm::WasmCodegen),
136        Box::new(c::CCodegen),
137        Box::new(zig::ZigE2eCodegen),
138        Box::new(dart::DartE2eCodegen),
139        Box::new(swift::SwiftE2eCodegen),
140        Box::new(brew::BrewCodegen),
141    ]
142}
143
144/// Get e2e code generators for specific language names.
145pub fn generators_for(languages: &[String]) -> Vec<Box<dyn E2eCodegen>> {
146    all_generators()
147        .into_iter()
148        .filter(|g| languages.iter().any(|l| l == g.language_name()))
149        .collect()
150}
151
152/// Resolve a JSON field from a fixture input by path.
153///
154/// Field paths in call config are "input.path", "input.config", etc.
155/// Since we already receive `fixture.input`, strip the leading "input." prefix.
156/// When `field_path` is exactly `"input"`, the whole input object is returned.
157pub(crate) fn resolve_field<'a>(input: &'a serde_json::Value, field_path: &str) -> &'a serde_json::Value {
158    // "input" with no subpath means "the entire input object".
159    if field_path == "input" {
160        return input;
161    }
162    let path = field_path.strip_prefix("input.").unwrap_or(field_path);
163    let mut current = input;
164    for part in path.split('.') {
165        current = current.get(part).unwrap_or(&serde_json::Value::Null);
166    }
167    current
168}